From cdfec56460b0a1cb673d8970a3aec34b67a60091 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:03:51 +0100 Subject: [PATCH] STRA-338 size: the engine crates are rustfmt-clean at 120 columns (per-crate rustfmt.toml: max_width 120, Max heuristics); width violations 6869 -> 2862 prod, 1273 -> 717 test; files that grew are re-split. Reasons for the raised census numbers: fn_lines +119 and complexity +14 are functions that cross 30 lines / 10 branches only because rustfmt put their one-line bodies on several lines (nothing was added); test lists identical (1793), 800 tests pass, the same 5 known failures; bring-up print gate lookback 20 -> 30 lines for the same reason --- architecture-baseline.json | 56 +- crates/context/rustfmt.toml | 3 + crates/context/src/context_policy.rs | 71 +- crates/context/src/context_policy/tests.rs | 46 +- crates/context/src/geometry.rs | 39 +- crates/context/src/geometry/tests.rs | 60 +- .../memory_plan/impl_default_for_geometry.rs | 56 +- .../src/memory_plan/plan_with_per_token.rs | 34 +- crates/context/src/memory_plan/tests.rs | 40 +- crates/context/src/ptx_abi.rs | 7 +- .../src/rope_scaling/fill_rope_table.rs | 44 +- .../src/rope_scaling/impl_fmt_display_for.rs | 10 +- .../src/rope_scaling/impl_ropescalingtype.rs | 31 +- crates/context/src/rope_scaling/tests.rs | 141 +- crates/context/src/setup_policy.rs | 42 +- crates/context/tests/context_lift.rs | 54 +- crates/context/tests/rope_plan_golden.rs | 72 +- .../every_fixture_case_has.rs | 35 +- crates/context/tests/setup_policy_oracle.rs | 71 +- crates/cuda-driver/rustfmt.toml | 3 + crates/cuda-driver/src/api.rs | 18 +- crates/cuda-driver/src/api/enabled.rs | 115 +- crates/cuda-driver/src/arch_ptx.rs | 112 +- .../src/arch_ptx/stream_k_off_fn.rs | 19 +- .../src/asset_validation_cache_tests.rs | 36 +- crates/cuda-driver/src/async_owned_copy.rs | 25 +- .../cuda-driver/src/async_owned_copy_gpu.rs | 102 +- crates/cuda-driver/src/batch_gr_preview.rs | 79 +- .../src/bringup_trace_enabled_fn.rs | 92 +- crates/cuda-driver/src/closed_kernels.rs | 119 +- .../src/closed_kernels/impl_program.rs | 55 +- .../src/closed_kernels/s_gemv_slots_fn.rs | 42 +- .../cuda-driver/src/closed_kernels/tests.rs | 15 +- .../flash_and_poison_signatures_match.rs | 139 +- .../tests/sealed_assets_match_their_pins.rs | 32 +- crates/cuda-driver/src/closed_kernels_gpu.rs | 4 +- .../src/closed_kernels_gpu/failure_fn.rs | 5 +- .../impl_closedkernels_2.rs | 46 +- .../impl_closedkernels_2_2.rs | 133 +- .../src/closed_kernels_gpu_smoke.rs | 183 +- .../src/closed_kernels_gpu_smoke/impl_rng.rs | 35 +- crates/cuda-driver/src/command_profile.rs | 4 +- crates/cuda-driver/src/compute_drain.rs | 1 - crates/cuda-driver/src/deferred_status.rs | 55 +- crates/cuda-driver/src/deferred_status_ffi.rs | 12 +- crates/cuda-driver/src/device_arena.rs | 29 +- crates/cuda-driver/src/device_slab.rs | 13 +- crates/cuda-driver/src/device_slab/tests.rs | 13 +- crates/cuda-driver/src/experimental.rs | 197 +- .../src/experimental/impl_kvshape.rs | 40 +- .../cuda-driver/src/experimental/impl_mode.rs | 34 +- crates/cuda-driver/src/experimental/tests.rs | 167 +- crates/cuda-driver/src/experimental_gpu.rs | 19 +- .../src/experimental_gpu/impl_context.rs | 10 +- .../impl_experimental/impl_experimental_2.rs | 55 +- .../impl_experimental_2_2.rs | 35 +- .../impl_experimental/impl_experimental_3.rs | 17 +- .../src/experimental_gpu/impl_streammap.rs | 57 +- .../cuda-driver/src/experimental_gpu_smoke.rs | 103 +- crates/cuda-driver/src/family_tests.rs | 170 +- crates/cuda-driver/src/ffi.rs | 58 +- crates/cuda-driver/src/ffi/enabled.rs | 10 +- .../cuda-driver/src/ffi/enabled/impl_api.rs | 81 +- .../cuda-driver/src/ffi/enabled/impl_api_2.rs | 451 +- .../cuda-driver/src/ffi/enabled/impl_api_3.rs | 40 +- .../cuda-driver/src/ffi/enabled/impl_api_4.rs | 62 +- .../cuda-driver/src/ffi/enabled/impl_api_5.rs | 11 +- .../cuda-driver/src/ffi/enabled/impl_api_6.rs | 85 +- .../src/ffi/enabled/impl_drop_for_library.rs | 6 +- crates/cuda-driver/src/ffi/impl_api.rs | 63 +- .../cuda-driver/src/ffi/impl_contexthandle.rs | 86 +- .../src/ffi/impl_functionhandle.rs | 47 +- .../cuda-driver/src/ffi/projection_tests.rs | 83 +- crates/cuda-driver/src/ffi/tests.rs | 40 +- crates/cuda-driver/src/gdn_batch_gemm.rs | 33 +- crates/cuda-driver/src/gdn_closed_queue.rs | 51 +- .../gdn_closed_queue/impl_gdnqueuestage.rs | 34 +- .../impl_gdnrowprefix/impl_gdnrowprefix_2.rs | 22 +- .../impl_gdnrowprefix_2_2.rs | 34 +- .../impl_gdnrowprefix/impl_gdnrowprefix_3.rs | 37 +- .../src/gdn_closed_queue/impl_gdnrowqueue.rs | 5 +- .../cuda-driver/src/gdn_closed_queue_gpu.rs | 185 +- .../src/gdn_closed_queue_gpu/bytes_fn.rs | 71 +- .../gdn_closed_queue_gpu/columns_pair_fn.rs | 20 +- crates/cuda-driver/src/gdn_fused_t1.rs | 58 +- .../impl_gdnfusedprefix_2.rs | 28 +- .../impl_gdnfusedprefix_2_2.rs | 31 +- .../src/gdn_fused_t1/impl_gdnfusedt1.rs | 29 +- .../cuda-driver/src/gdn_fused_t1/pinned_fn.rs | 33 +- .../cuda-driver/src/gdn_fused_t1/words_fn.rs | 8 +- crates/cuda-driver/src/gdn_fused_t1_gpu.rs | 68 +- crates/cuda-driver/src/gdn_native_batch.rs | 39 +- .../src/gdn_native_batch/impl_context.rs | 66 +- .../impl_gdnbatchprefix_2.rs | 50 +- .../impl_gdnbatchprefix_2_2.rs | 43 +- .../impl_gdnbatchprefix_3.rs | 46 +- .../src/gdn_native_batch/pinned_fn.rs | 32 +- .../src/gdn_native_batch/staging_fn.rs | 4 +- .../cuda-driver/src/gdn_native_batch/tests.rs | 60 +- .../cuda-driver/src/gdn_native_batch_abi.rs | 6 +- .../cuda-driver/src/gdn_native_batch_gpu.rs | 74 +- .../src/gdn_native_batch_gpu/bytes_of_fn.rs | 33 +- .../src/gdn_native_batch_gpu/impl_hostgemm.rs | 53 +- .../src/gdn_native_batch_gpu/run_case_fn.rs | 98 +- crates/cuda-driver/src/gdn_prompt_device.rs | 4 +- .../impl_originalgdnpromptdevice_2.rs | 25 +- .../impl_originalgdnpromptdevice_2_2.rs | 181 +- .../impl_originalgdnpromptdevice_3.rs | 8 +- .../cuda-driver/src/gdn_state_finite_guard.rs | 45 +- .../src/gr_batch_inject_workspace.rs | 92 +- .../src/gr_batch_inject_workspace_gpu.rs | 117 +- crates/cuda-driver/src/gr_batch_read.rs | 119 +- .../src/gr_batch_read/impl_context.rs | 6 +- .../impl_drop_for_grmicrobatchread.rs | 12 +- .../impl_grmicrobatchread_2.rs | 42 +- .../impl_grmicrobatchread_2_2.rs | 39 +- .../impl_grmicrobatchread_3.rs | 30 +- crates/cuda-driver/src/gr_native_batch.rs | 12 +- .../src/gr_native_batch/impl_context.rs | 12 +- .../impl_grnativebatch_2.rs | 58 +- .../impl_grnativebatch_2_2.rs | 18 +- .../impl_grnativebatch_3.rs | 12 +- crates/cuda-driver/src/gr_read_guard.rs | 61 +- .../src/grouped_down_columns_gpu.rs | 119 +- .../cuda-driver/src/grouped_gu21_gu23_gpu.rs | 132 +- .../src/grouped_gu21_gu23_nc4_gpu.rs | 17 +- .../grouped_gu21_gu23_nc4_gpu/guards_fn.rs | 93 +- .../grouped_gu21_gu23_nc4_gpu/upload_fn.rs | 76 +- crates/cuda-driver/src/head_greedy.rs | 63 +- crates/cuda-driver/src/head_greedy_gpu.rs | 31 +- crates/cuda-driver/src/impl_context.rs | 35 +- crates/cuda-driver/src/impl_context_2.rs | 58 +- crates/cuda-driver/src/impl_context_3.rs | 47 +- crates/cuda-driver/src/impl_context_4.rs | 71 +- crates/cuda-driver/src/impl_context_5.rs | 51 +- crates/cuda-driver/src/impl_context_6.rs | 11 +- crates/cuda-driver/src/impl_devicebuffer.rs | 44 +- crates/cuda-driver/src/impl_projectionkind.rs | 53 +- .../cuda-driver/src/iq3_native_integer_mma.rs | 57 +- crates/cuda-driver/src/kar_decode_levels.rs | 37 +- .../src/kar_decode_levels/tests.rs | 152 +- .../cuda-driver/src/kar_decode_levels_gpu.rs | 16 +- .../src/kar_decode_levels_gpu/f32_bytes_fn.rs | 16 +- .../src/kar_decode_levels_gpu/impl_context.rs | 19 +- .../impl_kardecodelevels.rs | 79 +- .../src/kar_decode_levels_gpu_smoke.rs | 103 +- crates/cuda-driver/src/kv_stream_gpu.rs | 47 +- crates/cuda-driver/src/launch_ex.rs | 3 +- crates/cuda-driver/src/lib.rs | 425 +- crates/cuda-driver/src/mapped_expert_bank.rs | 5 +- .../src/mapped_expert_bank/impl_context.rs | 46 +- .../impl_drop_for_mappedexpertbank.rs | 27 +- .../impl_mappedexpertbank_2.rs | 20 +- .../impl_mappedexpertbank_2_2.rs | 51 +- .../impl_mappedexpertbank_3.rs | 1 - .../src/mapped_file_dma_stress_gpu.rs | 18 +- crates/cuda-driver/src/mmq.rs | 100 +- crates/cuda-driver/src/mmq/asset_fn.rs | 43 +- crates/cuda-driver/src/mmq/impl_context.rs | 163 +- .../src/mmq/impl_drop_for_mmqexperiment.rs | 36 +- .../cuda-driver/src/mmq/impl_mmqexperiment.rs | 133 +- crates/cuda-driver/src/mmq/impl_tile.rs | 363 +- crates/cuda-driver/src/mmq_ffi.rs | 4 +- .../impl_mmqoriginalgatherarguments.rs | 6 +- .../src/mmq_ffi/impl_mmqresidentarguments.rs | 15 +- crates/cuda-driver/src/mmq_ffi/impl_owned.rs | 32 +- .../cuda-driver/src/mmq_native_activation.rs | 41 +- crates/cuda-driver/src/mmq_native_down.rs | 18 +- .../src/mmq_native_resident_gpu.rs | 176 +- .../src/mmq_native_resident_gpu/digest_fn.rs | 93 +- .../native_hidden_q8_fn.rs | 16 +- crates/cuda-driver/src/mmq_numeric_gpu.rs | 54 +- .../src/mmq_numeric_gpu/cases_fn.rs | 31 +- .../src/mmq_numeric_gpu/digest_fn.rs | 82 +- .../impl_chunkstream.rs | 12 +- .../mmq_original_chunk_stream/impl_core.rs | 14 +- .../src/mmq_original_enqueue_ffi.rs | 77 +- crates/cuda-driver/src/mmq_original_group.rs | 40 +- .../src/mmq_original_group/asset_fn.rs | 56 +- .../mmq_original_group/impl_mmqworkspace.rs | 116 +- .../impl_originalmmqlayer_2.rs | 80 +- .../impl_originalmmqlayer_2_2.rs | 49 +- .../impl_originalmmqlayer_3.rs | 76 +- .../impl_originalmmqlayer_2.rs | 92 +- .../impl_originalmmqoutput.rs | 47 +- .../src/mmq_original_group/kind_fn.rs | 18 +- .../src/mmq_original_group_stress_gpu.rs | 18 +- .../src/mmq_original_host_stage.rs | 8 +- .../mmq_original_host_stage/impl_hoststage.rs | 15 +- .../verify_enabled_fn.rs | 5 +- .../src/mmq_original_prefill_misc.rs | 26 +- crates/cuda-driver/src/mmq_original_ring.rs | 35 +- .../impl_originalmmqcopyschedule.rs | 64 +- .../impl_ring/impl_ring_2.rs | 73 +- .../impl_ring/impl_ring_2_2.rs | 136 +- .../impl_ring/impl_ring_3.rs | 54 +- .../mmq_original_ring/skip_expert_dma_fn.rs | 27 +- .../src/mmq_original_stream_all.rs | 4 +- .../impl_originalmmqlayer.rs | 108 +- ...inalstreamallgroupproducer_for_producer.rs | 11 +- .../mmq_original_stream_all/impl_transport.rs | 49 +- .../cuda-driver/src/mmq_original_weights.rs | 62 +- crates/cuda-driver/src/mmq_resident.rs | 4 +- .../cuda-driver/src/mmq_resident/asset_fn.rs | 66 +- .../impl_drop_for_mmqworkspace.rs | 99 +- .../impl_mmqworkspace/impl_mmqworkspace_2.rs | 53 +- .../impl_mmqworkspace_2_2.rs | 74 +- .../impl_mmqworkspace/impl_mmqworkspace_3.rs | 17 +- crates/cuda-driver/src/mmq_resident_gpu.rs | 259 +- .../src/mmq_resident_gpu/chain_fn.rs | 119 +- .../src/mmq_resident_gpu/digest_fn.rs | 88 +- .../src/mmq_resident_gpu/native_owner_fn.rs | 101 +- crates/cuda-driver/src/moe_down_pack_gpu.rs | 55 +- .../cuda-driver/src/moe_group_down_columns.rs | 95 +- .../cuda-driver/src/moe_group_projection.rs | 84 +- crates/cuda-driver/src/moe_prefill_batch.rs | 31 +- .../impl_moebatchprefix_2.rs | 44 +- .../impl_moebatchprefix_2_2.rs | 54 +- .../impl_moebatchprefix_3.rs | 33 +- .../moe_prefill_batch/impl_moeprefillbatch.rs | 69 +- .../src/moe_prefill_batch/pinned_fn.rs | 26 +- .../src/moe_prefill_batch/tests.rs | 76 +- .../src/moe_prefill_batch/words_fn.rs | 8 +- .../cuda-driver/src/moe_prefill_batch_gpu.rs | 56 +- .../src/moe_prefill_batch_gpu/bytes_of_fn.rs | 58 +- .../moe_prefill_batch_gpu/check_clean_fn.rs | 67 +- .../src/moe_prefill_batch_gpu/impl_fixture.rs | 49 +- .../cuda-driver/src/moe_prompt_packet_copy.rs | 23 +- crates/cuda-driver/src/mtp_dense_kv.rs | 60 +- .../cuda-driver/src/mtp_dense_kv_ring_gpu.rs | 69 +- crates/cuda-driver/src/mtp_input_workspace.rs | 13 +- .../impl_mtpinputcompletion.rs | 33 +- .../impl_mtpinputprefix.rs | 91 +- .../impl_mtpinputworkspace.rs | 5 +- .../src/mtp_input_workspace_gpu.rs | 28 +- .../src/mtp_input_workspace_gpu/bytes_fn.rs | 69 +- .../numeric_case_fn.rs | 70 +- .../src/mtp_original_full_drafter.rs | 4 +- .../impl_completedoriginalmtpdraft.rs | 5 +- .../impl_drop_for_originalmtpdrafter.rs | 42 +- .../impl_originalmtpdrafter_2.rs | 45 +- .../impl_originalmtpdrafter_2_2.rs | 62 +- .../impl_originalmtpdrafter_3.rs | 58 +- .../cuda-driver/src/mtp_original_full_ffi.rs | 402 +- .../src/mtp_original_full_ffi/enabled.rs | 303 + .../src/mtp_original_full_forward.rs | 42 +- .../impl_context_2.rs | 48 +- ...l_crate_original_gpu_schedule_resources.rs | 13 +- .../impl_fullowned.rs | 50 +- .../impl_originalmtpforwardprogram.rs | 72 +- .../impl_originalmtpfullforward.rs | 63 +- .../impl_originalmtpfullforward.rs | 173 +- .../impl_originalmtpfullforward_2_2.rs | 52 +- .../impl_originalmtpfullforward_3.rs | 53 +- .../impl_originalmtpfullforward.rs | 128 +- .../impl_originalmtpfullforward_2.rs | 40 +- .../impl_originalmtpretainedprefix.rs | 52 +- .../validate_scalar_prefix_fn.rs | 17 +- .../src/mtp_original_full_graph.rs | 84 +- .../src/mtp_original_full_mapped.rs | 58 +- .../src/mtp_original_full_round.rs | 320 +- .../impl_originalmtpdraftprogram.rs | 250 + .../impl_stagedsource.rs | 240 + .../mtp_original_full_round/post_select_fn.rs | 25 + .../src/mtp_original_full_round/put_fn.rs | 240 + .../src/mtp_original_full_symbols.rs | 65 +- crates/cuda-driver/src/mtp_original_int8.rs | 39 +- .../impl_drop_for_mtporiginalint8.rs | 50 +- .../mtp_original_int8/impl_mtpint8ownerid.rs | 37 +- .../impl_mtporiginalint8_2.rs | 83 +- .../impl_mtporiginalint8_2_2.rs | 57 +- .../impl_mtporiginalint8_3.rs | 38 +- .../impl_mtporiginalint8_4.rs | 78 +- .../impl_mtporiginalint8_5.rs | 27 +- .../mtp_original_int8/impl_physicalring.rs | 13 +- .../cuda-driver/src/mtp_original_int8_ffi.rs | 24 +- .../src/mtp_original_int8_ffi/enabled.rs | 44 +- .../src/mtp_original_int8_ffi/host_enabled.rs | 44 +- .../mtp_original_int8_ffi/impl_arguments.rs | 19 +- .../src/mtp_original_logical_prefix.rs | 37 +- .../src/mtp_original_native_embedding.rs | 23 +- .../src/mtp_original_physical_layout.rs | 60 +- .../cuda-driver/src/mtp_original_prefill.rs | 66 +- .../impl_completeddraftkv.rs | 75 +- .../impl_originalmtpprefill_2.rs | 61 +- .../impl_originalmtpprefill_2_2.rs | 24 +- .../impl_originalmtpprefill_3.rs | 40 +- .../impl_originalmtpprefill_4.rs | 259 +- .../impl_originalmtpprefill_5.rs | 1 - .../src/mtp_original_prefill/impl_region.rs | 7 +- .../src/mtp_original_prefill_ffi.rs | 137 +- .../src/mtp_original_prefill_symbols.rs | 48 +- .../src/mtp_original_ring_state/a16_fn.rs | 20 +- .../mtp_original_ring_state/impl_selected.rs | 20 +- .../mtp_original_ring_state/pin_failure_fn.rs | 32 +- .../src/mtp_original_scalar_ffi.rs | 168 +- .../src/mtp_original_scalar_graph.rs | 277 +- .../src/mtp_original_scalar_mapped.rs | 49 +- .../src/mtp_original_scalar_prefill.rs | 34 +- ...l_crate_original_gpu_schedule_resources.rs | 13 +- .../impl_originalmtpscalarprefill_2.rs | 72 +- .../impl_originalmtpscalarprefill_2_2.rs | 59 +- .../impl_originalmtpscalarprefill_3.rs | 33 +- .../impl_originalmtpscalarprefill_4.rs | 213 +- .../impl_originalmtpscalarprefill_5.rs | 5 +- .../src/mtp_original_scalar_short_gpu.rs | 98 +- .../src/mtp_original_scalar_weights.rs | 80 +- .../cuda-driver/src/mtp_original_session.rs | 20 +- .../impl_drop_for_sessionowned.rs | 25 +- .../impl_originalmtpsessionplan.rs | 34 +- .../impl_originalmtpsessionresources.rs | 92 +- .../cuda-driver/src/native_batch_workspace.rs | 37 +- crates/cuda-driver/src/native_flash_attn.rs | 27 +- crates/cuda-driver/src/native_head.rs | 72 +- .../src/native_head/alias_tests.rs | 16 +- .../impl_drop_for_originalnativeheadrows.rs | 25 +- .../src/native_head/impl_headowned.rs | 48 +- .../native_head/impl_originalnativeembed.rs | 65 +- .../impl_originalnativeheadrows_2.rs | 61 +- .../impl_originalnativeheadrows_2_2.rs | 51 +- .../src/native_head/native_asset_fn.rs | 64 +- .../src/native_head/projection_commands_fn.rs | 14 +- crates/cuda-driver/src/native_head_ffi.rs | 67 +- crates/cuda-driver/src/native_head_mapped.rs | 47 +- crates/cuda-driver/src/native_parity.rs | 42 +- .../impl_nativeparity/impl_nativeparity_2.rs | 54 +- .../impl_nativeparity_2_2.rs | 62 +- .../native_parity/impl_nativeparityexpert.rs | 24 +- .../src/native_parity/impl_state.rs | 41 +- .../src/native_parity/sealed_ptx_fn.rs | 30 +- crates/cuda-driver/src/native_parity_ffi.rs | 81 +- .../cuda-driver/src/native_prompt_device.rs | 39 +- .../impl_originaldeviceblock.rs | 55 +- .../impl_originalplehistory.rs | 52 +- .../impl_originalpromptdevice_2.rs | 28 +- .../impl_originalpromptdevice_2_2.rs | 30 +- .../impl_originalpromptdevice_3.rs | 122 +- .../impl_originalpromptdevice_4.rs | 5 +- .../impl_originalpromptdevice_5.rs | 64 +- .../impl_originalpromptdevice_6.rs | 87 +- .../impl_originalpromptdevice_7.rs | 17 +- .../src/native_prompt_device_stage.rs | 22 +- crates/cuda-driver/src/nvml.rs | 36 +- .../src/original_conversation_state.rs | 29 +- .../src/original_conversation_state/tests.rs | 10 +- .../cuda-driver/src/original_expert_cache.rs | 7 +- .../impl_originalcacheprefix.rs | 16 +- .../impl_originalexpertcache_2.rs | 36 +- .../impl_originalexpertcache_2_2.rs | 26 +- .../impl_originalexpertcache_3.rs | 88 +- .../impl_originalexpertcache_4.rs | 27 +- .../cuda-driver/src/original_expert_slots.rs | 54 +- .../cuda-driver/src/original_expert_stager.rs | 15 +- .../original_expert_stager/impl_context.rs | 55 +- .../impl_originalexpertstager.rs | 45 +- .../impl_originalstagerbatch.rs | 86 +- .../impl_originalstageroptions.rs | 111 +- .../src/original_expert_stager/impl_shared.rs | 28 +- .../original_expert_stager_ffi/check_fn.rs | 9 +- .../original_expert_stager_ffi/impl_api.rs | 85 +- .../impl_hostbuffer.rs | 33 +- .../src/original_file_expert_source.rs | 2 +- .../available_memory_fn.rs | 37 +- ...mpl_default_for_originalresidentoptions.rs | 64 +- .../impl_drop_for_originalfileexpertsource.rs | 55 +- .../impl_originalfileexpertsource_2.rs | 45 +- .../impl_originalfileexpertsource_2_2.rs | 37 +- .../impl_originalfileexpertsource_3.rs | 75 +- .../impl_originalfileexpertsource_4.rs | 34 +- .../src/original_file_expert_source_ffi.rs | 8 +- .../check_fn.rs | 67 +- .../impl_arena.rs | 53 +- .../src/original_gpu_head_bridge.rs | 25 +- .../cuda-driver/src/original_gpu_schedule.rs | 36 +- .../impl_originalgpugraph.rs | 57 +- .../impl_originalgpustream.rs | 56 +- .../impl_originalgraphkey.rs | 54 +- .../set_side_streams_wanted_fn.rs | 25 +- .../src/original_gpu_schedule/transport_fn.rs | 35 +- .../src/original_gpu_schedule_ffi.rs | 12 +- .../src/original_gpu_schedule_ffi/platform.rs | 17 +- .../platform/impl_api.rs | 92 +- .../platform/impl_api_2.rs | 28 +- .../platform/impl_drop_for_library.rs | 9 +- .../src/original_gpu_verify_bridge.rs | 42 +- .../src/original_moe_prompt_device.rs | 19 +- .../original_moe_prompt_device/blank_fn.rs | 17 +- .../impl_drop_for_originalmoepromptdevice.rs | 53 +- .../impl_originalmoepromptdevice_2.rs | 71 +- .../impl_originalmoepromptdevice_2_2.rs | 64 +- .../impl_originalmoepromptdevice_3.rs | 7 +- crates/cuda-driver/src/original_mtp_actor.rs | 24 +- .../src/original_mtp_actor_loaded.rs | 10 +- .../impl_originalmtpactor_2.rs | 85 +- .../impl_originalmtpactor_2_2.rs | 119 +- .../inconsistent_fn.rs | 10 +- crates/cuda-driver/src/original_mtp_bank.rs | 73 +- .../cuda-driver/src/original_mtp_bank_gpu.rs | 112 +- .../cuda-driver/src/original_mtp_coupled.rs | 109 +- .../src/original_mtp_draft_head.rs | 45 +- .../src/original_mtp_draft_vocab.rs | 59 +- .../src/original_mtp_draft_vocab/tests.rs | 166 +- crates/cuda-driver/src/original_mtp_loader.rs | 117 +- .../original_mtp_loader/impl_loadererror.rs | 138 +- .../src/original_mtp_loader/tests.rs | 23 +- .../src/original_mtp_round_lifecycle.rs | 304 +- .../impl_originalmtpdrafter.rs | 247 + .../impl_originalmtpdrafter_2.rs | 32 + .../impl_originalmtpprefillplan.rs | 117 + crates/cuda-driver/src/original_mtp_rt.rs | 32 +- .../src/original_mtp_rt/impl_rterror.rs | 63 +- .../src/original_mtp_rt/read_index_fn.rs | 39 +- .../cuda-driver/src/original_mtp_rt/tests.rs | 4 +- .../tests/expert_stream_error_paths_use.rs | 41 +- .../tests/parses_getline_loop_and_skips.rs | 149 +- .../src/original_pcie_copy_gpu_smoke.rs | 10 +- .../cuda-driver/src/original_prefill_arena.rs | 284 +- .../src/original_prefill_layout.rs | 144 +- .../src/original_prefill_schedule.rs | 21 +- .../original_prefill_schedule/impl_planner.rs | 7 +- .../src/original_prefill_schedule/tests.rs | 52 +- .../original_prefill_schedule_crosscheck.rs | 9 +- crates/cuda-driver/src/original_sampler.rs | 10 +- .../src/original_sampler/asset_fn.rs | 15 +- .../impl_originalsampler_2.rs | 67 +- .../impl_originalsampler_2_2.rs | 61 +- .../impl_originalsampler_3.rs | 42 +- .../impl_originalsampler_4.rs | 1 - .../cuda-driver/src/original_sampler_ffi.rs | 143 +- .../src/original_sampler_mapped.rs | 50 +- .../src/original_sampler_params.rs | 24 +- .../cuda-driver/src/original_serve_assets.rs | 10 +- .../src/original_session_qsa_init.rs | 66 +- .../cuda-driver/src/original_session_rope.rs | 114 +- .../cuda-driver/src/original_session_state.rs | 342 +- .../src/original_session_state/add_fn.rs | 213 + .../impl_originalsessionlayout.rs | 241 + .../original_session_state/qsa_price_fn.rs | 209 + crates/cuda-driver/src/original_stream_all.rs | 108 +- .../impl_originalexpertstager.rs | 456 +- .../impl_originalstreamalloptions.rs | 200 +- .../impl_originalexpertstager.rs | 247 + .../impl_originalstreamall.rs | 157 + .../impl_originalstreamalloptions_2.rs | 136 + crates/cuda-driver/src/original_verify.rs | 308 +- .../impl_originalverifygdnjournal.rs | 193 +- .../impl_originalverifygdnjournal_2.rs | 224 + .../impl_originalverifygdnjournal_2_2.rs | 239 + .../impl_originalverifygdnjournal_3.rs | 231 + .../impl_originalverifywindow.rs | 51 + .../share_window_modules_fn.rs | 215 +- .../impl_originalverifybank.rs | 248 + .../impl_originalverifybank_2.rs | 206 + .../share_window_modules_fn/impl_physical.rs | 249 + .../share_window_modules_fn_2.rs | 214 + .../src/original_verify_expert_probe.rs | 20 +- crates/cuda-driver/src/original_verify_ffi.rs | 278 +- .../src/original_verify_gpu_plan.rs | 350 +- .../dma_options_for_fn.rs | 19 + .../impl_originalverifygpuplan.rs | 97 + .../impl_schedule_originalverifycpusink.rs | 249 + .../src/original_verify_gpu_plan/tests.rs | 19 +- .../cuda-driver/src/original_verify_layout.rs | 242 +- .../cuda-driver/src/original_verify_logits.rs | 5 +- .../cuda-driver/src/original_verify_mapped.rs | 213 +- .../src/original_verify_schedule.rs | 317 +- .../commit_sync_forced_fn.rs | 201 + .../impl_originalverifier_2.rs | 255 + .../impl_originalverifier_3.rs | 231 + .../impl_originalverifier_4.rs | 197 + .../src/original_verify_window_chain.rs | 76 +- .../src/original_verify_window_draft.rs | 10 +- .../src/original_verify_window_gpu.rs | 10 +- .../src/original_verify_window_gr.rs | 44 +- .../original_verify_window_gr/assets_fn.rs | 17 +- .../plan_hc_read_fn.rs | 19 +- .../plan_ple_row_fn.rs | 10 +- .../src/original_verify_window_gr/tests.rs | 6 +- .../tests/head_mix_is_the_native.rs | 16 +- .../tests/tiled_down_projection_covers.rs | 23 +- .../src/original_verify_window_kernels.rs | 23 +- .../src/original_verify_window_moe.rs | 109 +- .../pcie_fast_kernel_fn.rs | 1 - .../plan_expert_groups_fn.rs | 53 +- .../plan_f32_to_bf16_fn.rs | 10 +- .../src/original_verify_window_moe/tests.rs | 4 +- .../tests/alternative_pcie_staging_copy.rs | 11 +- .../tests/hit_add_scans_the_cpu.rs | 1 - .../tests/shared_gate_without_native_bf16.rs | 26 +- .../src/original_verify_window_ops.rs | 28 +- .../all_window_assets_fn.rs | 15 +- .../impl_originalverifier.rs | 14 +- .../impl_originalverifywindowops.rs | 8 +- ...l_windowops_for_originalverifywindowops.rs | 34 +- .../src/original_verify_window_ops/tests.rs | 3 +- .../src/original_verify_window_plan.rs | 12 +- .../src/original_verify_window_planner.rs | 18 +- .../original_verify_window_planner/tests.rs | 93 +- .../tests/every_window_size_and_group.rs | 47 +- .../src/original_verify_window_proj.rs | 388 +- .../admit_matrix_fn.rs | 14 +- .../q8_1_row_bytes_fn.rs | 37 +- .../src/original_verify_window_proj/tests.rs | 18 +- .../src/original_verify_window_qsa.rs | 25 +- .../original_verify_window_qsa/assets_fn.rs | 30 +- .../impl_qsawindow.rs | 387 +- .../impl_qsawindow/impl_qsawindow_2.rs | 241 + .../impl_qsawindow/impl_qsawindow_2_2.rs | 207 + .../src/original_verify_window_qsa/tests.rs | 4 +- .../tests/q_path_per_token_splits.rs | 32 +- .../tests/sealed_assets_are_pinned.rs | 13 +- .../tests/weight_sizes_are_the_original.rs | 1 - .../src/original_verify_window_record.rs | 5 +- .../original_verify_window_record/tests.rs | 135 +- .../src/original_verify_window_sm120.rs | 10 +- .../src/owned_gate_up_upload_gpu.rs | 104 +- crates/cuda-driver/src/ple_batch_ffi.rs | 12 +- .../cuda-driver/src/ple_batch_ffi/enabled.rs | 7 +- .../src/ple_batch_ffi/enabled/impl_blas.rs | 87 +- .../src/ple_batch_ffi/enabled/impl_blas_2.rs | 47 +- .../src/ple_batch_ffi/enabled/impl_library.rs | 15 +- .../src/ple_batch_ffi/impl_kernelarguments.rs | 44 +- crates/cuda-driver/src/ple_batch_queue.rs | 63 +- .../src/ple_batch_queue/assets_fn.rs | 17 +- .../impl_drop_for_plebatchqueue.rs | 40 +- .../impl_plebatchqueue_2.rs | 45 +- .../impl_plebatchqueue_2_2.rs | 125 +- .../impl_plebatchqueue_3.rs | 6 +- crates/cuda-driver/src/ple_closed_queue.rs | 281 +- .../src/ple_closed_queue/float_owner_fn.rs | 23 + .../impl_pleclosedcompletion.rs | 180 + .../ple_closed_queue/impl_pleclosedqueue_2.rs | 246 + .../cuda-driver/src/ple_closed_queue_gpu.rs | 262 +- crates/cuda-driver/src/ple_value_full_gpu.rs | 51 +- crates/cuda-driver/src/prefill_stage.rs | 8 +- .../cuda-driver/src/prefill_stage_gdn_gpu.rs | 294 +- .../src/prefill_stage_gdn_gpu/impl_rng.rs | 7 +- crates/cuda-driver/src/prefill_stage_gpu.rs | 4 +- .../cuda-driver/src/prefill_stage_gr_gpu.rs | 360 +- .../src/prefill_stage_gr_gpu/impl_rng.rs | 47 + crates/cuda-driver/src/q6_k_shape_fn.rs | 26 +- crates/cuda-driver/src/q6_layer_preview.rs | 57 +- crates/cuda-driver/src/qsa_cluster.rs | 18 +- crates/cuda-driver/src/qsa_index_ffi.rs | 286 +- .../cuda-driver/src/qsa_index_ffi/enabled.rs | 208 + crates/cuda-driver/src/qsa_late.rs | 33 +- crates/cuda-driver/src/qsa_late_gpu.rs | 116 +- crates/cuda-driver/src/qsa_mapped_journal.rs | 53 +- .../impl_originalqsamappedjournal.rs | 207 +- .../impl_originalqsamappedprefix.rs | 208 +- .../impl_originalqsamappedjournal_2.rs | 205 + .../impl_originalqsamappedprefix_2.rs | 226 + crates/cuda-driver/src/qsa_native_batch.rs | 262 +- .../impl_qsanativebatchworkspace_2.rs | 238 + .../qsa_native_batch/impl_qsanativekind.rs | 235 + crates/cuda-driver/src/qsa_native_decode.rs | 126 +- crates/cuda-driver/src/qsa_native_gate.rs | 16 +- .../cuda-driver/src/qsa_prompt_attention.rs | 6 +- .../impl_drop_for_qsapromptattention.rs | 27 +- .../impl_qsaattentioninputs.rs | 4 +- .../impl_qsapromptattention.rs | 110 +- .../src/qsa_prompt_attention_ffi.rs | 78 +- .../src/qsa_prompt_attention_select.rs | 39 +- .../impl_poolpresence.rs | 57 +- .../q_prescale_fn.rs | 1 - .../src/qsa_prompt_attention_select/tests.rs | 5 +- crates/cuda-driver/src/qsa_prompt_device.rs | 191 +- .../src/qsa_prompt_device/impl_context.rs | 42 + .../impl_originalqsapromptdevice.rs | 229 + .../impl_originalqsapromptdevice_2.rs | 242 + .../impl_originalqsapromptdevice_3.rs | 186 + .../src/qsa_prompt_device_attention.rs | 59 +- .../src/qsa_prompt_device_index.rs | 473 +- .../cuda-driver/src/qsa_prompt_device_kv.rs | 93 +- crates/cuda-driver/src/qsa_prompt_host_ffi.rs | 48 +- crates/cuda-driver/src/qsa_prompt_index.rs | 312 +- .../impl_qsapromptindexworkspace.rs | 223 + .../impl_qsapromptindexworkspace_2.rs | 149 + .../impl_qsapromptindexworkspace_3.rs | 371 + .../impl_qsapromptindexworkspace_4.rs | 227 + .../src/qsa_prompt_index/max_blocks_fn.rs | 40 + crates/cuda-driver/src/qsa_prompt_kv.rs | 33 +- .../impl_drop_for_qsapromptkv.rs | 41 +- .../impl_qsapromptkv/impl_qsapromptkv_2.rs | 71 +- .../impl_qsapromptkv/impl_qsapromptkv_2_2.rs | 60 +- .../src/qsa_prompt_kv/offsets_fn.rs | 68 +- crates/cuda-driver/src/qsa_prompt_resolver.rs | 64 +- .../cuda-driver/src/qsa_resident_attention.rs | 257 +- crates/cuda-driver/src/qsa_resident_decode.rs | 91 +- crates/cuda-driver/src/qsa_resident_device.rs | 147 +- .../impl_originalqsapromptdevice.rs | 202 + .../impl_originalqsapromptdevice_2.rs | 113 + .../impl_originalqsaresidentselection.rs | 208 + crates/cuda-driver/src/qsa_resident_index.rs | 243 +- .../src/qsa_resident_index/image_bytes_fn.rs | 57 + .../impl_originalqsaindexbatch.rs | 70 + .../impl_originalqsaresidentindex.rs | 252 + .../impl_originalqsaresidentindex_2.rs | 251 + .../src/qsa_resident_index_program.rs | 153 +- .../impl_qsapromptindexworkspace.rs | 415 + .../impl_qsapromptindexworkspace_2.rs | 140 + .../src/qsa_resident_scalar_index.rs | 76 +- .../cuda-driver/src/qsa_resident_transfer.rs | 177 +- .../src/qsa_resident_transfer/enabled.rs | 340 + .../cuda-driver/src/qsa_resident_transport.rs | 381 +- crates/cuda-driver/src/qsa_selected_kv.rs | 89 +- .../src/qsa_selected_kv/asset_fn.rs | 1 - .../impl_drop_for_qsaselectedkvworkspace.rs | 12 +- .../impl_qsaselectedkvworkspace.rs | 74 +- .../src/qsa_verification_commit.rs | 242 +- .../impl_originalverifyqsajournal.rs | 252 + .../impl_originalverifyqsajournal_2.rs | 231 + .../impl_originalverifyqsajournal_3.rs | 151 + .../impl_originalverifyrope.rs | 46 + crates/cuda-driver/src/qwen_dispatch.rs | 41 +- .../src/qwen_dispatch/admission_fn.rs | 8 +- .../qwen_dispatch/gdn_products_installed.rs | 60 +- .../src/qwen_dispatch/impl_cache.rs | 36 +- .../impl_context/impl_context_2.rs | 78 +- .../impl_context/impl_context_2_2.rs | 70 +- .../impl_context/impl_context_3.rs | 75 +- .../impl_context/impl_context_4.rs | 92 +- .../impl_context/impl_context_5.rs | 60 +- .../impl_context/impl_context_6.rs | 60 +- .../impl_context/impl_context_7.rs | 30 +- .../qwen_dispatch/prepare_gr_read_set_fn.rs | 47 +- .../src/qwen_dispatch/queued_gr_installed.rs | 40 +- crates/cuda-driver/src/qwen_dispatch/tests.rs | 65 +- .../tests/full_s2_bank_extent.rs | 133 +- .../tests/moe_new_preflight_requires_exact.rs | 144 +- .../tests/qsa_new_slots_keep_atomic.rs | 114 +- .../tests/qwen_actual_owner_poison_missing.rs | 92 +- .../qwen_attempted_launch_always_syncs.rs | 122 +- crates/cuda-driver/src/qwen_ffi.rs | 276 +- crates/cuda-driver/src/qwen_ffi/asset_fn.rs | 30 +- .../src/qwen_ffi/impl_operation.rs | 51 +- .../src/qwen_ffi/impl_operation_2.rs | 92 +- .../cuda-driver/src/qwen_ffi/mock_asset_fn.rs | 23 +- .../src/qwen_ffi/mtp_s2_full_layout_fn.rs | 116 +- .../cuda-driver/src/qwen_ffi/qsa_layout_fn.rs | 115 +- crates/cuda-driver/src/qwen_ffi/tests.rs | 4 +- .../qwen_ffi/tests/full_s2_expert_scalar.rs | 141 +- .../tests/moe_fixed_pointer_abi_extents.rs | 168 +- .../tests/mtp_new_qualified_assets.rs | 41 +- .../tests/qsa_new_literal_abi_scalar.rs | 168 +- crates/cuda-driver/src/qwen_shared_tail.rs | 28 +- .../impl_drop_for_sharedexpertworkspace.rs | 40 +- .../impl_sharedexpertworkspace_2.rs | 47 +- .../impl_sharedexpertworkspace_2_2.rs | 112 +- .../impl_sharedexpertworkspace_3.rs | 1 - .../cuda-driver/src/qwen_shared_tail_gpu.rs | 33 +- .../qwen_shared_tail_gpu/guard_probe_fn.rs | 69 +- .../src/qwen_shared_tail_gpu/original_fn.rs | 64 +- .../src/qwen_shared_tail_gpu/read_fn.rs | 31 +- .../src/routed_columns_loan_gpu.rs | 213 +- .../cuda-driver/src/routed_group_workspace.rs | 7 +- .../routed_group_workspace/impl_context.rs | 96 +- .../impl_routedgroupworkspace.rs | 94 +- .../src/routed_group_workspace_gpu.rs | 182 +- .../cuda-driver/src/routed_resident_queue.rs | 2 +- .../impl_drop_for_routedresidentqueue.rs | 13 +- .../impl_routedresidentcompletion.rs | 6 +- .../impl_routedresidentqueue.rs | 87 +- .../src/routed_resident_queue_gpu.rs | 22 +- .../src/routed_resident_queue_gpu/case_fn.rs | 77 +- .../src/routed_resident_queue_gpu/run_fn.rs | 21 +- .../routed_resident_queue_gpu/upload_fn.rs | 37 +- .../src/routed_stage_finite_guard.rs | 53 +- .../src/routed_stage_finite_guard_gpu.rs | 36 +- crates/cuda-driver/src/s_gemv_legacy.rs | 48 +- .../s_gemv_legacy/impl_default_for_sform.rs | 77 +- .../s_gemv_legacy/plan_s2_gemv_quads_fn.rs | 16 +- crates/cuda-driver/src/s_gemv_legacy/tests.rs | 62 +- crates/cuda-driver/src/sealed_ptx.rs | 11 +- crates/cuda-driver/src/serving_context.rs | 54 +- crates/cuda-driver/src/sm86_table.rs | 1310 ++- crates/cuda-driver/src/tests.rs | 90 +- crates/cuda-driver/src/vram_ledger.rs | 23 +- .../tests/full_matrix_transport_gpu.rs | 117 +- crates/cuda-driver/tests/gpu_driver.rs | 81 +- crates/cuda-driver/tests/mock_driver.rs | 184 +- .../tests/mock_driver/bootstrap_copies_fn.rs | 91 +- .../mock_driver/check_matvec_lengths_fn.rs | 105 +- .../mock_driver/isolated_cpu_elf_matrix.rs | 1 - .../mock_driver/matvec_launch_count_fn.rs | 47 +- .../cuda-driver/tests/mock_driver/trace_fn.rs | 31 +- .../tests/mock_driver/vector_bounds_fn.rs | 150 +- .../vector_module_context_trace_fn.rs | 89 +- .../cuda-driver/tests/original_arena_probe.rs | 14 +- .../tests/original_executor_probe.rs | 33 +- .../tests/original_serve_preflight_probe.rs | 12 +- .../env_usize_fn.rs | 73 +- .../preflight_00_sealed_asset_report.rs | 42 +- .../synthetic_verifier_fn.rs | 168 +- crates/cuda-driver/tests/ple_key_bulk_gpu.rs | 62 +- .../tests/prepared_routed_gate_up_gpu.rs | 131 +- .../tests/projection_family_gpu.rs | 71 +- .../tests/projection_family_mock.rs | 10 +- .../common_protocol_matrix.rs | 156 +- .../family_public_q8_child.rs | 117 +- .../tests/projection_family_oracle.rs | 23 +- crates/cuda-driver/tests/q5_gpu.rs | 104 +- crates/cuda-driver/tests/q5_mock.rs | 94 +- crates/cuda-driver/tests/q5_oracle.rs | 11 +- crates/cuda-driver/tests/q6_gpu.rs | 125 +- crates/cuda-driver/tests/q6_mock.rs | 6 +- .../q6_mock/isolated_q6_protocol_matrix.rs | 5 +- .../tests/q6_mock/q6_fixture_child.rs | 142 +- crates/cuda-driver/tests/q6_oracle.rs | 15 +- crates/engine-core/rustfmt.toml | 3 + .../engine-core/src/conversation/binding.rs | 26 +- crates/engine-core/src/conversation/buffer.rs | 91 +- crates/engine-core/src/conversation/cache.rs | 4 +- .../cache/impl_conversationcache.rs | 34 +- .../cache/impl_conversationcheckpoint.rs | 41 +- .../src/conversation/cache/tests.rs | 5 +- .../retained_buffers_count_against_bytes.rs | 177 +- .../cache/tests/what_is_not_superseded.rs | 39 +- .../src/conversation/golden_cache.rs | 120 +- .../src/conversation/golden_manager.rs | 155 +- crates/engine-core/src/conversation/kv.rs | 20 +- .../src/conversation/kv/impl_layout.rs | 54 +- .../src/conversation/kv/kv_save_fn.rs | 72 +- .../src/conversation/kv/kv_verify_fn.rs | 12 +- .../engine-core/src/conversation/manager.rs | 15 +- .../impl_conversationmanager_2.rs | 28 +- .../impl_conversationmanager_2_2.rs | 57 +- .../impl_default_for_conversationoptions.rs | 6 +- .../src/conversation/manager_tests.rs | 24 +- .../manager_tests/byte_budget_and_slot.rs | 132 +- .../manager_tests/continuing_chat_reuses.rs | 166 +- .../src/conversation/manager_tests/hash_fn.rs | 109 +- .../impl_sessiondevice_for_simdevice.rs | 76 +- ...andom_conversation_traffic_always_resum.rs | 59 +- crates/engine-core/src/conversation/model.rs | 20 +- .../engine-core/src/conversation/snapshot.rs | 126 +- .../src/conversation/snapshot_tests.rs | 33 +- .../conversation/snapshot_tests/fixture_fn.rs | 300 +- .../snapshot_tests/full_session_fn.rs | 159 +- .../snapshot_tests/golden_state_fn.rs | 64 +- .../conversation/snapshot_tests/impl_pools.rs | 41 +- .../snapshot_tests/kv_level_fn.rs | 92 +- .../snapshot_tests/kv_region_fn.rs | 52 +- .../layer_snapshots_are_byte_exact.rs | 104 +- crates/engine-core/src/conversation/state.rs | 116 +- .../engine-core/src/conversation/testing.rs | 65 +- crates/engine-core/src/memory.rs | 4 +- crates/engine-core/src/prefix_cache/budget.rs | 43 +- crates/engine-core/src/prefix_cache/hash.rs | 5 +- .../src/prefix_cache/store/decayed_fn.rs | 6 +- .../impl_prefixstore/impl_prefixstore_2.rs | 31 +- .../impl_prefixstore/impl_prefixstore_2_2.rs | 121 +- .../impl_prefixstore/impl_prefixstore_3.rs | 16 +- .../src/prefix_cache/store/tests.rs | 11 +- .../store/tests/hit_by_another_session.rs | 21 +- .../store/tests/request_resumes_from.rs | 14 +- .../engine-core/src/prefix_cache/summary.rs | 64 +- crates/engine-core/src/prompt.rs | 222 +- crates/engine-core/src/prompt/grid_tests.rs | 69 + .../src/prompt/impl_promptoptions.rs | 62 +- crates/engine-core/src/prompt/tests.rs | 228 + crates/engine-core/src/request.rs | 13 +- crates/engine-core/src/spec/adaptive.rs | 4 +- .../src/spec/adaptive/impl_adaptiveconfig.rs | 12 +- .../src/spec/adaptive/impl_adaptivepolicy.rs | 42 +- .../src/spec/adaptive/impl_specstats.rs | 20 +- crates/engine-core/src/spec/adaptive/tests.rs | 349 +- .../spec/adaptive/tests/default_ceiling.rs | 98 + .../stationary_regimes_reach_the_best.rs | 247 + crates/engine-core/src/spec/policy.rs | 287 +- crates/engine-fake/rustfmt.toml | 3 + crates/engine-qwen35-cuda/build.rs | 10 +- crates/engine-qwen35-cuda/rustfmt.toml | 3 + crates/engine-qwen35-cuda/src/backend.rs | 138 +- .../src/backend/clock_tests.rs | 39 +- .../engine-qwen35-cuda/src/backend/config.rs | 38 +- .../engine-qwen35-cuda/src/backend/digests.rs | 48 +- .../engine-qwen35-cuda/src/backend/errors.rs | 18 +- .../src/backend/generate.rs | 95 +- .../src/backend/generate_mtp.rs | 64 +- .../src/backend/lifecycle_tests.rs | 120 +- .../src/backend/lifecycle_tests/ends.rs | 92 +- .../src/backend/lifecycle_tests/prefix.rs | 61 +- crates/engine-qwen35-cuda/src/backend/load.rs | 10 +- .../src/backend/load_admit.rs | 85 +- .../src/backend/load_bind.rs | 44 +- .../src/backend/load_cuda.rs | 48 +- .../src/backend/load_identity.rs | 46 +- .../src/backend/load_moe.rs | 38 +- .../src/backend/load_moe_gates.rs | 47 +- .../src/backend/load_sources.rs | 148 +- .../src/backend/load_tests.rs | 95 +- .../src/backend/load_weights.rs | 91 +- .../engine-qwen35-cuda/src/backend/owner.rs | 43 +- .../engine-qwen35-cuda/src/backend/probes.rs | 42 +- .../src/backend/profile_tests.rs | 19 +- .../engine-qwen35-cuda/src/backend/proxy.rs | 58 +- .../engine-qwen35-cuda/src/backend/request.rs | 44 +- .../src/backend/serve_close.rs | 28 +- .../src/backend/serve_generate.rs | 46 +- .../src/backend/serve_loop.rs | 40 +- .../src/backend/serve_report.rs | 55 +- .../src/backend/serve_run.rs | 48 +- .../engine-qwen35-cuda/src/backend/sources.rs | 78 +- .../engine-qwen35-cuda/src/backend/spawn.rs | 135 +- .../src/backend/spawn_optimized.rs | 94 +- .../src/backend/spawn_original.rs | 28 +- .../engine-qwen35-cuda/src/backend/tests.rs | 114 +- crates/engine-qwen35-cuda/src/backend/utf8.rs | 30 +- .../src/backend/validate.rs | 57 +- .../src/backend_measurement.rs | 28 +- .../src/backend_original_serve.rs | 10 +- .../impl_originalservemode.rs | 15 +- .../src/backend_original_serve/runner.rs | 30 +- .../runner/generate_fn.rs | 33 +- .../runner/gpu_probe_fn.rs | 25 +- .../backend_original_serve/runner/run_fn.rs | 121 +- .../src/backend_original_serve/tests.rs | 29 +- .../src/backend_original_serve_replay.rs | 568 +- .../required_path_fn.rs | 8 + .../src/conversation/memory.rs | 40 +- .../src/conversation/mod.rs | 4 +- .../src/conversation/original.rs | 71 +- .../src/conversation/resident.rs | 87 +- .../src/conversation/resident/tests.rs | 88 +- crates/engine-qwen35-cuda/src/experimental.rs | 34 +- .../src/experimental/tests.rs | 111 +- .../gpu_proofs/backend_measurement_sdet.rs | 39 +- .../gpu_proofs/backend_original_serve_arms.rs | 49 +- .../backend_original_serve_laptop.rs | 122 +- .../backend_original_serve_memory_smoke.rs | 248 +- .../backend_original_serve_prefix_smoke.rs | 71 +- .../backend_original_serve_smoke.rs | 644 +- .../gpu_proofs/backend_original_serve_ttft.rs | 44 +- .../combined_changed_boundary_proof.rs | 45 +- .../src/gpu_proofs/combined_prefix_numeric.rs | 168 +- .../combined_prefix_numeric_sdet.rs | 41 +- .../src/gpu_proofs/fivecase_frames.rs | 37 +- .../src/gpu_proofs/fivecase_runtime.rs | 93 +- .../src/gpu_proofs/layer0_native_mmq_proof.rs | 42 +- .../long_public_request.rs | 75 +- .../native_down_adaptive_candidate_only.rs | 135 +- .../gpu_proofs/native_down_candidate_only.rs | 564 +- .../src/gpu_proofs/native_down_public_pair.rs | 155 +- .../native_resident_mmq_model_proof.rs | 54 +- .../gpu_proofs/resident_mmq_model_proof.rs | 41 +- .../src/gpu_proofs/singleload_proof.rs | 91 +- crates/engine-qwen35-cuda/src/idle_sweep.rs | 5 +- crates/engine-qwen35-cuda/src/lib.rs | 11 +- .../engine-qwen35-cuda/src/memory_governor.rs | 76 +- .../src/model_binding/kar_expert_source.rs | 116 +- .../src/model_binding/kar_levels.rs | 23 +- .../src/model_binding/qwen4exp_gdn.rs | 98 +- .../src/model_binding/qwen4exp_gdn/tests.rs | 20 +- .../src/model_binding/qwen4exp_gr.rs | 159 +- .../src/model_binding/qwen4exp_gr/tests.rs | 35 +- .../qwen4exp_inherited_kar_gpu.rs | 73 +- .../src/model_binding/qwen4exp_input.rs | 17 +- .../qwen4exp_input/impl_fmt_display_for.rs | 22 +- .../qwen4exp_input/impl_modelbinding.rs | 55 +- .../validate_ple_descriptor_fn.rs | 45 +- .../model_binding/qwen4exp_input_decode.rs | 45 +- .../src/model_binding/qwen4exp_kar_ple.rs | 70 +- .../impl_inheritedkararchive.rs | 72 +- .../weight_source_tests.rs | 5 +- .../load_pinned_inherited_archive_fn.rs | 86 +- .../qwen4exp_kar_ple/pinned_profile_fn.rs | 36 +- .../qwen4exp_kar_ple/pinned_profile_tests.rs | 52 +- .../qwen4exp_kar_ple/private_copy.rs | 68 +- .../private_copy/checked_reader_fn.rs | 31 +- .../qwen4exp_kar_ple/private_copy/inode_fn.rs | 130 +- .../qwen4exp_kar_ple/win_archive.rs | 4 +- .../qwen4exp_moe_encoded_finite.rs | 18 +- .../src/model_binding/qwen4exp_moe_expert.rs | 46 +- .../impl_modelbinding/impl_modelbinding_2.rs | 82 +- .../impl_modelbinding_2_2.rs | 52 +- .../impl_moeexpertweights.rs | 23 +- .../impl_moeroutedsourcescope.rs | 102 +- .../routed_source_descriptor_fn.rs | 126 +- .../src/model_binding/qwen4exp_moe_route.rs | 48 +- .../src/model_binding/qwen4exp_mtp.rs | 270 +- .../src/model_binding/qwen4exp_mtp/backing.rs | 113 +- .../qwen4exp_mtp/impl_mtpweights.rs | 112 +- .../qwen4exp_mtp/pack_identity_fn.rs | 36 +- .../qwen4exp_mtp/read_expert_rows_fn.rs | 86 +- .../src/model_binding/qwen4exp_mtp/tests.rs | 44 +- .../src/model_binding/qwen4exp_native_head.rs | 102 +- .../qwen4exp_original_file_source.rs | 19 +- .../src/model_binding/qwen4exp_output.rs | 82 +- .../src/model_binding/qwen4exp_ple.rs | 110 +- .../src/model_binding/qwen4exp_ple_reader.rs | 112 +- .../src/model_binding/qwen4exp_qsa.rs | 91 +- .../qwen4exp_resident_expert_source.rs | 83 +- .../src/qwen_forward/cache_cpu_budget.rs | 55 +- .../qwen_forward/cache_ephemeral_routed.rs | 47 +- .../healthy_cancel_fn.rs | 13 +- .../impl_drop_for_ephemeralroutedowner.rs | 420 +- .../impl_ephemeralroutedowner.rs | 356 +- .../impl_ephemeralroutedowner_2.rs | 170 + .../impl_ephemeralroutedowner_2_2.rs | 223 + .../impl_ephemeralroutedowner_3.rs | 138 + .../qwen_forward/cache_learned_main_sdet.rs | 37 +- .../cache_lru_index/impl_lruindex.rs | 61 +- .../cache_lru_index/impl_lruindex_2.rs | 38 +- .../src/qwen_forward/cache_lru_index_sdet.rs | 67 +- .../cache_original_mtp_weights.rs | 347 +- .../dense_copies_equal_fn.rs | 94 + .../impl_retainedoriginalmtpweights.rs | 219 + .../src/qwen_forward/cache_original_prompt.rs | 345 +- .../impl_moeweightcache.rs | 208 + .../impl_moeweightcache_2.rs | 218 + .../prompt_stream_settings_fn.rs | 49 + .../src/qwen_forward/cache_original_verify.rs | 5 +- .../src/qwen_forward/cache_profile.rs | 8 +- .../cache_profile/impl_rankedprofile.rs | 72 +- .../cache_profile/impl_sharedpermanentpool.rs | 74 +- .../src/qwen_forward/cache_profile_fill.rs | 10 +- .../impl_moeweightcache_2.rs | 79 +- .../impl_moeweightcache_2_2.rs | 82 +- .../impl_moeweightcache_2.rs | 251 +- .../impl_moeweightcache_3.rs | 192 +- .../impl_moeweightcache_4.rs | 143 +- .../profile_window_spill_fn.rs | 5 +- .../src/qwen_forward/cache_profile_sdet.rs | 75 +- .../src/qwen_forward/cache_routed_outputs.rs | 42 +- .../cache_shared_permanent_sdet.rs | 191 +- .../src/qwen_forward/cache_strata_adaptive.rs | 11 +- .../impl_adaptivecache.rs | 244 +- .../cache_strata_adaptive/reserve_fn.rs | 152 +- .../transfer_metadata_bound_fn.rs | 1 - .../cache_strata_adaptive_sdet.rs | 98 +- .../src/qwen_forward/chunk_modules.rs | 15 +- .../src/qwen_forward/contract.rs | 88 +- .../src/qwen_forward/cpu_expert_miss.rs | 268 +- .../src/qwen_forward/dense_weight_cache.rs | 12 +- .../dense_slab_policy_fn.rs | 5 +- .../impl_denseweightcache_2.rs | 94 +- .../impl_denseweightcache_2_2.rs | 108 +- .../impl_denseweightcache_3.rs | 81 +- .../impl_denseweightcache_4.rs | 65 +- .../impl_denseweightcache_5.rs | 53 +- .../impl_denseweightcache_6.rs | 20 +- .../impl_denseweightcache_7.rs | 11 +- .../src/qwen_forward/executor.rs | 181 +- .../executor/impl_prefillstepproduct.rs | 25 +- .../impl_qwenforward/impl_qwenforward_2.rs | 8 +- .../impl_qwenforward/impl_qwenforward_2_2.rs | 105 +- .../impl_qwenforward/impl_qwenforward_3.rs | 3 - .../executor/read_layer_attention_fn.rs | 31 +- .../src/qwen_forward/executor/tests.rs | 77 +- .../qwen_forward/executor_mmq_evaluation.rs | 166 +- .../src/qwen_forward/executor_mtp_window.rs | 92 +- .../executor_native_mmq_evaluation.rs | 174 +- .../qwen_forward/executor_original_prompt.rs | 145 +- .../impl_drop_for_originalpromptexecutor.rs | 130 +- .../impl_originalpromptexecutor_2.rs | 228 +- .../impl_originalpromptexecutor.rs | 242 + .../impl_originalpromptexecutor_2_2.rs | 194 + .../impl_originalpromptexecutor_2_2.rs | 245 +- .../impl_originalpromptexecutor.rs | 492 ++ .../impl_originalpromptexecutor_2.rs | 10 + .../impl_originalpromptexecutor_3.rs | 40 +- .../staged_input_enabled_fn.rs | 2 +- .../check_chunk_on_loaded_fn.rs | 143 +- .../impl_qwenforward/impl_qwenforward_2.rs | 2 - .../impl_qwenforward/impl_qwenforward_2_2.rs | 3 - .../impl_qwenforward/impl_qwenforward_3.rs | 551 +- .../impl_targetstepproduct.rs | 10 +- .../prepare_micro_ffn_rows_fn.rs | 173 +- .../prepare_q6_layer_columns_fn.rs | 28 +- .../read_chunk_attention_ffn_fn.rs | 22 +- .../qwen_forward/executor_window_numeric.rs | 52 +- .../src/qwen_forward/gdn.rs | 140 +- .../src/qwen_forward/gdn/driver_error_fn.rs | 4 +- .../src/qwen_forward/gdn/gates_fn.rs | 77 +- .../src/qwen_forward/gdn/impl_gdnstage.rs | 166 +- .../src/qwen_forward/gdn/project_fn.rs | 71 +- .../src/qwen_forward/gdn/step_cached_fn.rs | 33 +- .../src/qwen_forward/gdn_chain.rs | 84 +- .../gdn_chain/allocate_qk_slot_fn.rs | 59 +- .../gdn_chain/impl_chain/impl_chain_2.rs | 103 +- .../gdn_chain/impl_chain/impl_chain_2_2.rs | 65 +- .../gdn_chain/impl_chain/impl_chain_3.rs | 131 +- .../gdn_chain/impl_chain/impl_chain_4.rs | 9 +- .../src/qwen_forward/gdn_chain_fused.rs | 105 +- .../src/qwen_forward/gdn_chain_reuse_gpu.rs | 155 +- .../src/qwen_forward/gdn_chunk_device.rs | 13 +- .../impl_drop_for_gdnchunkdevice.rs | 18 +- .../impl_gdnchunkdevice_2.rs | 80 +- .../impl_gdnchunkdevice_2_2.rs | 94 +- .../impl_gdnchunkdevice_3.rs | 66 +- .../mirror_reuse_enabled_fn.rs | 33 +- .../src/qwen_forward/gdn_chunk_fused.rs | 68 +- .../src/qwen_forward/gdn_chunk_numeric_gpu.rs | 16 +- .../batch_adoption_fn.rs | 8 +- .../gdn_chunk_numeric_gpu/exercise_fn.rs | 119 +- .../gdn_chunk_numeric_gpu/operands_fn.rs | 52 +- .../src/qwen_forward/gdn_chunk_producer.rs | 94 +- .../src/qwen_forward/gdn_four_borrow_gpu.rs | 150 +- .../src/qwen_forward/gdn_fused_t1_step.rs | 51 +- .../src/qwen_forward/gdn_input_scratch.rs | 27 +- .../src/qwen_forward/gdn_input_scratch_gpu.rs | 138 +- .../src/qwen_forward/gdn_prefill_batch.rs | 24 +- .../gdn_prefill_batch/impl_buffers.rs | 32 +- .../impl_gdnbatchresources.rs | 107 +- .../gdn_prefill_batch/impl_gdnstage.rs | 75 +- .../src/qwen_forward/gdn_prefill_batch_gpu.rs | 14 +- .../src/qwen_forward/gdn_prompt_device.rs | 152 +- .../src/qwen_forward/gdn_row_queue_gpu.rs | 139 +- .../src/qwen_forward/gdn_state.rs | 129 +- .../src/qwen_forward/gdn_state_mirror.rs | 9 +- .../impl_gdnstatemirror_2.rs | 30 +- .../impl_gdnstatemirror_2_2.rs | 41 +- .../gdn_state_mirror/impl_mirrorreadout.rs | 15 +- .../gdn_state_mirror/upload_checked_fn.rs | 5 +- .../qwen_forward/gdn_state_mirror_fused.rs | 14 +- .../src/qwen_forward/gdn_state_mirror_gpu.rs | 177 +- .../src/qwen_forward/gdn_verification.rs | 371 +- .../gdn_verification/compute_row_fn.rs | 242 +- .../compute_row_fn/compute_row_fn_2.rs | 65 + .../compute_row_fn/impl_workspace.rs | 239 + .../compute_row_fn/impl_workspace_2.rs | 223 + .../gdn_verification/impl_workspace.rs | 15 +- .../engine-qwen35-cuda/src/qwen_forward/gr.rs | 28 +- .../src/qwen_forward/gr/diagnose_fn.rs | 88 +- .../src/qwen_forward/gr/download_f32_fn.rs | 24 +- .../src/qwen_forward/gr/impl_grstage.rs | 117 +- .../src/qwen_forward/gr/impl_residualready.rs | 11 +- .../qwen_forward/gr/output_workspace_gpu.rs | 304 +- .../output_workspace_gpu/check_handoff_fn.rs | 94 +- .../gr/output_workspace_gpu/fresh_read_fn.rs | 32 +- .../qwen_forward/gr/read_cached_cuda_fn.rs | 72 +- .../src/qwen_forward/gr/read_cuda_fn.rs | 111 +- .../src/qwen_forward/gr/tests.rs | 61 +- .../src/qwen_forward/gr_attention_chunk.rs | 93 +- .../src/qwen_forward/gr_batch_chunk.rs | 4 +- .../gr_batch_chunk/impl_grmicroinput.rs | 47 +- .../gr_batch_chunk/impl_grstage.rs | 93 +- .../gr_batch_chunk/impl_grstage_2.rs | 84 +- .../src/qwen_forward/gr_residual_reuse_gpu.rs | 155 +- .../src/qwen_forward/gr_retained_handoff.rs | 86 +- .../qwen_forward/gr_retained_handoff_gpu.rs | 89 +- .../src/qwen_forward/input.rs | 65 +- .../src/qwen_forward/input/gather_rows_fn.rs | 72 +- .../src/qwen_forward/input/impl_inputstage.rs | 46 +- .../qwen_forward/input/impl_inputstage_2.rs | 102 +- .../input/impl_residualstreams.rs | 8 +- .../src/qwen_forward/input/ple_cuda_fn.rs | 157 +- .../qwen_forward/input/ple_upload_f32_fn.rs | 121 +- .../src/qwen_forward/input_hash.rs | 43 +- .../src/qwen_forward/kar_ple_cache.rs | 10 +- .../kar_ple_cache/impl_karplecache.rs | 136 +- .../qwen_forward/kar_ple_cache/lru_tests.rs | 50 +- .../kar_ple_cache/publish_gather_fn.rs | 4 +- .../kar_ple_cache/row_parity_probe.rs | 14 +- .../kar_ple_cache/scratch_bytes_fn.rs | 68 +- .../qwen_forward/kar_ple_cache/slot_tests.rs | 17 +- .../qwen_forward/layer0_mmq_observation.rs | 74 +- .../src/qwen_forward/mod.rs | 68 +- .../qwen_forward/moe_activation_reuse_gpu.rs | 27 +- .../moe_activation_reuse_gpu/encoded_fn.rs | 58 +- .../former_fixture_domain_refusal_fn.rs | 90 +- .../src/qwen_forward/moe_down.rs | 6 +- .../qwen_forward/moe_down/impl_downscope.rs | 111 +- .../moe_down/impl_residentpackeddown.rs | 21 +- .../moe_down/impl_retainedscalar.rs | 54 +- .../src/qwen_forward/moe_down_reuse_gpu.rs | 195 +- .../moe_down_reuse_gpu/exact_fn.rs | 13 +- .../src/qwen_forward/moe_expert.rs | 40 +- .../moe_expert/cached_mlp_down_fn.rs | 38 +- .../qwen_forward/moe_expert/expert_mlp_fn.rs | 30 +- .../moe_expert/finish_with_parts_fn.rs | 112 +- .../moe_expert/impl_expertready.rs | 70 +- .../moe_expert/project_matrix_fn.rs | 58 +- .../src/qwen_forward/moe_expert/tests.rs | 22 +- .../moe_expert/validate_values_fn.rs | 24 +- .../src/qwen_forward/moe_group_adaptive.rs | 143 +- .../moe_group_adaptive_packets.rs | 325 +- .../project_adaptive_packets_fn.rs | 26 + .../project_inner_fn.rs | 361 + .../stage_gpu_wave_fn.rs | 78 + .../src/qwen_forward/moe_group_chunk.rs | 55 +- .../moe_group_chunk/execute_bound_fn.rs | 120 +- .../moe_group_chunk/finish_shared_with_fn.rs | 37 +- .../moe_group_chunk/impl_preparedmoerow.rs | 101 +- .../ordered_down_refusal_fn.rs | 198 +- .../project_group_direct_fn.rs | 81 +- .../moe_group_chunk/project_group_fn.rs | 98 +- .../project_group_source_consumers_fn.rs | 251 +- .../project_group_source_fenced_fn.rs | 7 +- .../qwen_forward/moe_group_down_direct_gpu.rs | 421 +- .../qwen_forward/moe_group_resident_queue.rs | 184 +- .../src/qwen_forward/moe_layer0_pair.rs | 11 +- .../src/qwen_forward/moe_mmq_adaptive.rs | 178 +- .../src/qwen_forward/moe_mmq_chunk.rs | 351 +- .../src/qwen_forward/moe_mmq_slotpack.rs | 94 +- .../src/qwen_forward/moe_prefill_batch.rs | 16 +- .../moe_prefill_batch/device_bytes_fn.rs | 33 +- .../impl_moeprefillresources.rs | 59 +- .../moe_prefill_batch/impl_moeprefillstage.rs | 73 +- .../qwen_forward/moe_prefill_batch/tests.rs | 40 +- .../src/qwen_forward/moe_prompt_finish.rs | 87 +- .../src/qwen_forward/moe_route.rs | 59 +- .../moe_route/impl_routerlogits.rs | 86 +- .../moe_route/project_logits_fn.rs | 52 +- .../src/qwen_forward/moe_route/run_cuda_fn.rs | 37 +- .../src/qwen_forward/moe_route/tests.rs | 191 +- .../src/qwen_forward/moe_weight_cache.rs | 119 +- .../moe_weight_cache/impl_moeweightcache.rs | 4 +- .../impl_moeweightcache_10.rs | 20 +- .../impl_moeweightcache_2.rs | 49 +- .../impl_moeweightcache_2_2.rs | 75 +- .../impl_moeweightcache_3.rs | 52 +- .../impl_moeweightcache_4.rs | 105 +- .../impl_moeweightcache_5.rs | 61 +- .../impl_moeweightcache_6.rs | 75 +- .../impl_moeweightcache_7.rs | 80 +- .../impl_moeweightcache_8.rs | 94 +- .../impl_moeweightcache_9.rs | 84 +- .../moe_weight_cache/impl_moeweightcache_2.rs | 157 +- .../impl_routedsourcehealth.rs | 6 +- .../impl_routedworkspaceowner.rs | 85 +- .../validate_ranked_profile_fn.rs | 78 +- .../src/qwen_forward/mtp.rs | 42 +- .../src/qwen_forward/mtp/impl_mtpframe.rs | 62 +- .../mtp/project_attention_out_numeric_fn.rs | 6 +- .../src/qwen_forward/mtp/step_fn.rs | 37 +- .../src/qwen_forward/mtp_attention.rs | 40 +- .../qwen_forward/mtp_attention/geometry_fn.rs | 47 +- .../mtp_attention/impl_mtpattentionready.rs | 66 +- .../mtp_attention/release_transport_fn.rs | 33 +- .../src/qwen_forward/mtp_attention/tests.rs | 10 +- .../qwen_forward/mtp_attention_reuse_gpu.rs | 121 +- .../src/qwen_forward/mtp_decode.rs | 35 +- .../mtp_decode/first_seed_reuse_enabled_fn.rs | 11 +- .../impl_mtpdecoder/impl_mtpdecoder_2.rs | 65 +- .../impl_mtpdecoder/impl_mtpdecoder_2_2.rs | 68 +- .../impl_mtpdecoder/impl_mtpdecoder_3.rs | 33 +- .../mtp_decode/impl_mtpwindowspec.rs | 6 +- .../src/qwen_forward/mtp_decode_chunk.rs | 28 +- .../src/qwen_forward/mtp_decoder_batch_gpu.rs | 29 +- .../mtp_decoder_batch_gpu/check_loaded_fn.rs | 105 +- .../mtp_decoder_batch_gpu/impl_collection.rs | 43 +- .../src/qwen_forward/mtp_expert_transport.rs | 11 +- .../mtp_expert_transport/impl_role.rs | 70 +- .../mtp_expert_transport/shared_project_fn.rs | 72 +- .../qwen_forward/mtp_expert_transport_gpu.rs | 89 +- .../mtp_expert_transport_gpu/exact_fn.rs | 76 +- .../private_owner_guards_fn.rs | 54 +- .../src/qwen_forward/mtp_expert_workspace.rs | 127 +- .../impl_drop_for_transport.rs | 58 +- .../mtp_expert_workspace/impl_fixedbuffers.rs | 23 +- .../mtp_expert_workspace/impl_role.rs | 63 +- .../src/qwen_forward/mtp_experts.rs | 77 +- .../src/qwen_forward/mtp_experts/tests.rs | 34 +- .../src/qwen_forward/mtp_final_transport.rs | 81 +- .../qwen_forward/mtp_final_transport_gpu.rs | 178 +- .../src/qwen_forward/mtp_gr.rs | 19 +- .../qwen_forward/mtp_gr/driver_error_fn.rs | 81 +- .../src/qwen_forward/mtp_gr/finalize_fn.rs | 33 +- .../src/qwen_forward/mtp_kv_only.rs | 12 +- .../src/qwen_forward/mtp_kv_resident.rs | 32 +- .../src/qwen_forward/mtp_state.rs | 6 +- .../qwen_forward/mtp_state/impl_densekv.rs | 67 +- .../qwen_forward/mtp_state/impl_mtpsession.rs | 32 +- .../mtp_state/impl_prefixdraftsnapshot.rs | 8 +- .../src/qwen_forward/mtp_state/tests.rs | 71 +- .../src/qwen_forward/mtp_state_chunk.rs | 35 +- .../mtp_state_chunk/checked_chunk_end_fn.rs | 35 +- .../mtp_state_chunk/impl_mtpsession.rs | 17 +- .../src/qwen_forward/mtp_state_warming.rs | 117 +- .../src/qwen_forward/oracle_capture.rs | 87 +- .../qwen_forward/original_cache_startup.rs | 393 +- .../original_file_cache_source.rs | 199 +- .../qwen_forward/original_mtp_full_owner.rs | 434 +- .../src/qwen_forward/original_mtp_prefill.rs | 218 +- .../original_mtp_scalar_prefill.rs | 183 +- .../original_mtp_verified_adapter.rs | 423 +- .../qwen_forward/original_prompt_embedding.rs | 167 +- .../qwen_forward/original_sampled_serve.rs | 4 +- .../src/qwen_forward/original_sampler.rs | 180 +- .../src/qwen_forward/original_serve_config.rs | 29 +- .../original_serve_config/tests.rs | 3 +- .../original_serve_conversation.rs | 10 +- .../original_serve_conversation/tests.rs | 37 +- .../src/qwen_forward/original_serve_engine.rs | 152 +- .../original_serve_engine/env_tests.rs | 96 +- .../impl_draftcompletion.rs | 229 +- .../impl_draftcompletion_2.rs | 233 + ...ginalspecengine_for_originalserveengine.rs | 191 + ...inalfirstdraftengine_for_originalservee.rs | 389 +- .../original_serve_engine/tests.rs | 389 +- .../tests/constructor_validates_dimensions.rs | 355 +- .../tests/restore_attempts_do_not_depend.rs | 338 +- .../src/qwen_forward/original_serve_host.rs | 14 +- ...l_nativeservehost_for_originalservehost.rs | 64 +- .../impl_requestsampling.rs | 20 +- .../src/qwen_forward/original_serve_ledger.rs | 37 +- .../qwen_forward/original_serve_lookahead.rs | 9 +- .../src/qwen_forward/original_serve_native.rs | 367 +- .../impl_nativewindow.rs | 120 + ...l_originalserveport_for_nativeserveport.rs | 297 + .../src/qwen_forward/original_serve_pool.rs | 43 +- .../original_serve_pool/impl_cpuexpertpool.rs | 55 +- .../original_serve_pool/impl_directtier.rs | 37 +- .../impl_drop_for_directtier.rs | 6 +- .../prefetch_off_file_exists_fn.rs | 7 +- .../src/qwen_forward/original_serve_prefix.rs | 10 +- .../original_serve_prefix/clock_tests.rs | 39 +- .../impl_prefixserve/impl_prefixserve_2.rs | 18 +- .../impl_prefixserve/impl_prefixserve_2_2.rs | 51 +- .../original_serve_prefix/tests.rs | 48 +- .../tests/one_token_prompt_reads.rs | 1 - .../tests/second_session.rs | 9 +- .../qwen_forward/original_serve_request.rs | 231 +- .../original_serve_request/tests.rs | 212 + .../qwen_forward/original_serve_residency.rs | 24 +- .../impl_std_fmt_debug.rs | 13 +- .../original_serve_residency/open_tier_fn.rs | 19 +- .../source_spans_fn.rs | 37 +- .../split_group_pcie_fn.rs | 29 +- .../tail_skip_rank_fn.rs | 30 +- .../original_serve_residency/tests.rs | 18 +- .../tier_env_tests.rs | 106 +- .../original_serve_residency_gpu.rs | 47 +- .../src/qwen_forward/original_serve_seed.rs | 2 +- .../src/qwen_forward/original_serve_stack.rs | 46 +- .../impl_originalservestack_2.rs | 217 +- .../impl_originalservestack_2_2.rs | 77 +- .../impl_originalservestack_3.rs | 22 +- .../impl_originalservestack_4.rs | 65 +- .../impl_originalservestack_5.rs | 61 +- .../impl_originalservestack_6.rs | 67 +- ...mpl_prefixdevice_for_originalservestack.rs | 45 +- .../original_serve_stack/impl_promptchunk.rs | 16 +- .../original_serve_stack/lifecycle_fake.rs | 28 +- .../lifecycle_fake/port.rs | 29 +- .../lifecycle_fake/prefix.rs | 12 +- .../lifecycle_fake/stack.rs | 45 +- .../original_serve_stack/tests.rs | 9 +- .../qwen_forward/original_serve_verifier.rs | 5 +- .../original_serve_verifier/tests.rs | 28 +- .../original_spec_adaptive_env.rs | 32 +- .../qwen_forward/original_spec_controller.rs | 130 +- .../impl_originalspeccontroller.rs | 216 +- .../impl_originalspeccontroller_2.rs | 165 + .../impl_originalspeccontroller_2_2.rs | 260 + .../impl_originalspeccontroller_2.rs | 206 +- .../original_spec_controller/tests.rs | 290 +- .../adaptation_join_failure_is_reported.rs | 236 +- .../tests/config_rejects_out_of_range.rs | 379 +- .../original_spec_controller/tests/golden.rs | 18 +- .../tests/non_finite_window.rs | 399 +- .../trace_enabled_fn.rs | 166 +- .../src/qwen_forward/original_spec_draft.rs | 346 +- .../src/qwen_forward/original_spec_suffix.rs | 226 +- .../src/qwen_forward/output.rs | 39 +- .../output/impl_originalpromptsample.rs | 80 +- .../impl_outputstage/impl_outputstage_2.rs | 93 +- .../impl_outputstage/impl_outputstage_2_2.rs | 60 +- .../qwen_forward/output/impl_outputstage_2.rs | 45 +- .../src/qwen_forward/output/tests.rs | 33 +- .../src/qwen_forward/output_native.rs | 214 +- .../src/qwen_forward/output_native_history.rs | 171 +- .../src/qwen_forward/owner_wall_profile.rs | 23 +- .../src/qwen_forward/ple_key_retained_gpu.rs | 110 +- .../ple_key_retained_gpu/bf16_fn.rs | 74 +- .../src/qwen_forward/ple_transport.rs | 8 +- .../ple_transport/compose_inner_fn.rs | 86 +- .../qwen_forward/ple_transport/impl_role.rs | 51 +- .../src/qwen_forward/prefill_profile.rs | 46 +- .../src/qwen_forward/prompt_device_rows.rs | 85 +- .../impl_promptdeviceread.rs | 240 +- .../impl_promptdeviceread_2.rs | 245 + .../produce_original_gdn_fn.rs | 235 + .../impl_promptplehistory.rs | 59 +- .../prompt_device_rows/impl_std_ops_deref.rs | 219 +- .../impl_promptdevicerows.rs | 237 + .../impl_promptdevicerows_2.rs | 87 + .../impl_std_ops_deref_2.rs | 185 + .../src/qwen_forward/q6_attention_columns.rs | 4 +- .../q6_attention_columns/numeric_fn.rs | 70 +- .../q6_attention_columns/project_impl_fn.rs | 57 +- .../src/qwen_forward/qsa_attention.rs | 31 +- .../decode_selected_cached_fn.rs | 62 +- .../qsa_attention/impl_nativeattended.rs | 85 +- .../qsa_attention/impl_qsaready.rs | 62 +- .../qwen_forward/qsa_attention_reuse_gpu.rs | 161 +- .../src/qwen_forward/qsa_attention_scratch.rs | 131 +- .../qwen_forward/qsa_attention_scratch_gpu.rs | 124 +- .../src/qwen_forward/qsa_decode_attention.rs | 28 +- .../src/qwen_forward/qsa_decode_index.rs | 90 +- .../src/qwen_forward/qsa_directory.rs | 30 +- .../src/qwen_forward/qsa_directory_sdet.rs | 20 +- .../src/qwen_forward/qsa_index.rs | 120 +- .../src/qwen_forward/qsa_index/context_fn.rs | 76 +- .../qsa_index/dispatch_projection_fn.rs | 81 +- .../qsa_index/impl_qsaindexstage.rs | 101 +- .../qwen_forward/qsa_index/impl_qsapending.rs | 89 +- .../src/qwen_forward/qsa_index/norm_fn.rs | 44 +- .../qwen_forward/qsa_index/validate_ids_fn.rs | 40 +- .../src/qwen_forward/qsa_index_resident.rs | 83 +- .../qsa_index_resident/max_rows_fn.rs | 38 +- .../synthetic_late_prior_fn.rs | 6 +- .../src/qwen_forward/qsa_input_reuse_gpu.rs | 144 +- .../src/qwen_forward/qsa_input_scratch.rs | 31 +- .../src/qwen_forward/qsa_native_resources.rs | 71 +- .../src/qwen_forward/qsa_native_state.rs | 106 +- .../src/qwen_forward/qsa_prefill_batch.rs | 376 +- .../src/qwen_forward/qsa_prompt_device.rs | 265 +- .../src/qwen_forward/qsa_prompt_index.rs | 346 +- .../src/qwen_forward/qsa_resident_device.rs | 301 +- .../impl_residentqsacompleted.rs | 113 + .../impl_residentqsalayer.rs | 240 + .../impl_residentqsalayer_2.rs | 234 + .../impl_residentqsaprior.rs | 123 + .../src/qwen_forward/qsa_resident_scalar.rs | 339 +- .../src/qwen_forward/qsa_selected_cache.rs | 97 +- .../src/qwen_forward/router_scratch.rs | 100 +- .../src/qwen_forward/router_scratch_gpu.rs | 43 +- .../router_scratch_gpu/impl_report.rs | 76 +- .../router_scratch_gpu/valid_reset_fn.rs | 42 +- .../src/qwen_forward/session.rs | 7 +- .../qwen_forward/session/impl_qwensession.rs | 32 +- .../impl_qwensteptxn/impl_qwensteptxn_2.rs | 81 +- .../impl_qwensteptxn/impl_qwensteptxn_2_2.rs | 49 +- .../session/impl_resetreplaysnapshot.rs | 84 +- .../src/qwen_forward/session/tests.rs | 4 +- .../tests/gdn_session_commit_advances_all.rs | 121 +- .../tests/retained_gr_handoff_identity.rs | 110 +- .../src/qwen_forward/session_checkpoint.rs | 78 +- .../src/qwen_forward/session_chunk.rs | 41 +- .../session_chunk/host_charge_bounded_fn.rs | 9 +- .../session_chunk/impl_gdnchunkstart.rs | 164 +- .../impl_qwenchunktxn/impl_qwenchunktxn_2.rs | 57 +- .../impl_qwenchunktxn_2_2.rs | 141 +- .../impl_qwenchunktxn/impl_qwenchunktxn_3.rs | 82 +- .../impl_qwenchunktxn/impl_qwenchunktxn_4.rs | 57 +- .../impl_qwenchunktxn/impl_qwenchunktxn_5.rs | 77 +- .../impl_qwenchunktxn/impl_qwenchunktxn_6.rs | 99 +- .../impl_qwenchunktxn/impl_qwenchunktxn_7.rs | 72 +- .../impl_qwenchunktxn/impl_qwenchunktxn_8.rs | 38 +- .../impl_qwenchunktxn/impl_qwenchunktxn_9.rs | 82 +- .../impl_testgdncomponentrows.rs | 16 +- .../src/qwen_forward/session_chunk_verify.rs | 4 +- .../impl_qwenchunktxn/impl_qwenchunktxn_2.rs | 245 +- .../impl_qwenchunktxn_2_2.rs | 99 +- .../impl_qwenchunktxn/impl_qwenchunktxn_3.rs | 71 +- .../impl_verifiedtargetprefix.rs | 4 +- .../session_chunk_verify/tests.rs | 140 +- .../qwen_forward/session_original_draft.rs | 365 +- .../impl_originaldraftcheckpoint.rs | 251 + .../impl_originaldraftsession_2.rs | 242 + .../published_first_materialized_fn.rs | 35 + .../qwen_forward/session_original_prompt.rs | 73 +- .../impl_originalpromptinput.rs | 221 +- .../impl_originalpromptinput_2.rs | 162 + .../impl_qwensession.rs | 248 + .../impl_originalpromptphase.rs | 134 +- .../impl_originalprompttxn.rs | 247 +- .../impl_originalprompttxn_2.rs | 242 + .../impl_originalprompttxn_2_2.rs | 181 + .../impl_originalprompttxn_3.rs | 101 + .../qwen_forward/session_original_verified.rs | 23 +- .../session_original_verified/tests.rs | 7 +- .../qwen_forward/shared_expert_workspace.rs | 35 +- .../src/qwen_forward/step_sampler.rs | 33 +- crates/engine-qwen35-cuda/src/serve_meta.rs | 27 +- .../src/serve_meta/tests.rs | 33 +- crates/engine-qwen35-cuda/src/serve_tuning.rs | 92 +- crates/engine-qwen35-cuda/src/serving.rs | 12 +- crates/engine-qwen35-cuda/src/settings.rs | 4 +- .../src/settings/capture_tests.rs | 41 +- .../src/settings/decode_tests.rs | 88 +- .../src/settings/diagnostics_tests.rs | 17 +- crates/engine-qwen35-cuda/src/settings/kv.rs | 12 +- .../src/settings/kv_tests.rs | 66 +- .../engine-qwen35-cuda/src/settings/memory.rs | 12 +- .../src/settings/memory_tests.rs | 131 +- .../engine-qwen35-cuda/src/settings/serve.rs | 3 +- .../src/settings/serve_tests.rs | 31 +- .../engine-qwen35-cuda/src/settings/source.rs | 11 +- .../tests/bringup_prints_gated.rs | 46 +- .../tests/stra161_reference.rs | 219 +- .../tests/stra166_reference.rs | 39 +- .../tests/stra168_full_vocabulary.rs | 86 +- crates/gateway-text/src/prompt/impl_json.rs | 38 +- .../gateway-text/src/prompt/impl_renderer.rs | 80 +- crates/gateway-text/src/prompt/json_string.rs | 12 +- crates/gateway-text/src/prompt/tests.rs | 218 +- .../src/prompt/without_empty_turns.rs | 26 +- crates/leleka-memory/examples/swap_ab.rs | 11 +- crates/leleka-memory/rustfmt.toml | 3 + crates/leleka-memory/src/census.rs | 43 +- .../governor/impl_drop_for_samplerguard.rs | 1 - .../governor/impl_governor/impl_governor_2.rs | 25 +- .../impl_governor/impl_governor_2_2.rs | 38 +- .../governor/impl_governor/impl_governor_3.rs | 88 +- .../governor/impl_governor/impl_governor_4.rs | 7 +- .../src/governor/impl_governorconfig.rs | 22 +- .../src/governor/pressure_tests.rs | 66 +- crates/leleka-memory/src/governor/tests.rs | 44 +- crates/leleka-memory/src/heap.rs | 8 +- crates/leleka-memory/src/host.rs | 7 +- crates/leleka-memory/src/inventory.rs | 17 +- crates/leleka-memory/src/ledger.rs | 19 +- crates/leleka-memory/src/lib.rs | 9 +- crates/leleka-memory/src/lock.rs | 14 +- .../leleka-memory/src/lock/impl_lockmode.rs | 15 +- crates/leleka-memory/src/lock/sys.rs | 33 +- crates/leleka-memory/src/lock/tests.rs | 21 +- .../src/plan/auto_prefix_budget.rs | 11 +- crates/leleka-memory/src/plan/impl_policy.rs | 56 +- crates/leleka-memory/src/plan/tests.rs | 7 +- crates/leleka-memory/src/pressure.rs | 189 +- crates/leleka-memory/src/pressure/tests.rs | 147 + crates/leleka-memory/src/pressure_port.rs | 38 +- crates/leleka-memory/src/procfs.rs | 3 +- crates/leleka-memory/src/procfs/tests.rs | 5 +- crates/leleka-memory/src/smi.rs | 21 +- crates/leleka-memory/src/telemetry/lock.rs | 15 +- crates/leleka-memory/src/telemetry/render.rs | 18 +- crates/leleka-memory/src/telemetry/tests.rs | 61 +- crates/leleka-memory/src/winproc.rs | 35 +- crates/leleka-memory/tests/sparse_archive.rs | 5 +- crates/leleka-runtime/rustfmt.toml | 3 + .../model-format/examples/bulk_read_bench.rs | 20 +- crates/model-format/examples/kar_cases.rs | 170 +- crates/model-format/examples/kar_census.rs | 6 +- crates/model-format/rustfmt.toml | 3 + .../src/bulk_read/for_each_chunk.rs | 30 +- .../src/bulk_read/impl_strategy.rs | 32 +- crates/model-format/src/bulk_read/tests.rs | 71 +- crates/model-format/src/gguf/impl_cursor.rs | 43 +- .../src/gguf/impl_verifiedgguffile.rs | 81 +- .../src/gguf/impl_verifiedgguffile/port.rs | 10 +- .../src/gguf/parse_artifact_digest.rs | 19 +- .../model-format/src/gguf/read_index_file.rs | 47 +- ...ead_metadata_snapshot_with_architecture.rs | 80 +- .../src/gguf/stream_buffer_bytes.rs | 1 - crates/model-format/src/gguf/tests.rs | 23 +- .../admits_flash_metadata_and_rejects.rs | 77 +- ...uffered_cursor_preserves_offsets_parsin.rs | 84 +- ...empty_owned_tensor_validation_preserves.rs | 63 +- .../original_first_source_fence_retains.rs | 27 +- crates/model-format/src/gguf/value_width.rs | 22 +- .../model-format/src/gguf_digest_capture.rs | 61 +- .../src/gguf_digest_capture_sdet.rs | 70 +- crates/model-format/src/gguf_native_head.rs | 79 +- .../model-format/src/gguf_owned_read_test.rs | 49 +- crates/model-format/src/gguf_resident.rs | 70 +- .../gguf_resident/impl_verifiedgguffile.rs | 106 +- .../gguf_resident/impl_verifiedgguffile_2.rs | 14 +- .../src/gguf_resident/next_source_id.rs | 4 +- crates/model-format/src/gguf_resident_sdet.rs | 102 +- crates/model-format/src/huge_pages.rs | 32 +- crates/model-format/src/kar.rs | 23 +- .../src/kar/decode_record_range.rs | 94 +- .../src/kar/impl_karpleprofile.rs | 4 +- .../src/kar/impl_std_fmt_display.rs | 95 +- .../src/kar/impl_verifiedkarpleartifact.rs | 83 +- .../src/kar/independent_handles.rs | 54 +- crates/model-format/src/kar/inspect_file.rs | 95 +- crates/model-format/src/kar/read_region.rs | 20 +- crates/model-format/src/kar_extents.rs | 14 +- .../src/kar_extents/impl_extent.rs | 36 +- .../src/kar_extents/impl_karinspection.rs | 49 +- .../kar_kernel_model/decode_params_valid.rs | 32 +- .../kar_kernel_model/impl_fmt_display_for.rs | 42 +- crates/model-format/src/kar_levels.rs | 4 +- .../src/kar_levels/expert_scratch.rs | 18 +- .../src/kar_levels/impl_fmt_display_for.rs | 103 +- .../src/kar_levels/impl_selection.rs | 76 +- crates/model-format/src/kar_nested.rs | 66 +- crates/model-format/src/lib.rs | 4 +- crates/model-format/src/native_dense_plan.rs | 22 +- .../src/native_dense_plan/tests.rs | 137 +- crates/model-format/src/pinned_arena_plan.rs | 352 +- .../src/pinned_arena_plan/fnv1a64_fn.rs | 236 + .../src/pinned_arena_plan/load_experts_fn.rs | 141 + .../src/pinned_arena_plan/tests.rs | 50 +- .../src/ple_reader/impl_fmt_debug_for.rs | 1 - .../ple_reader/impl_pagesource_for_file.rs | 28 +- .../src/ple_reader/impl_plereader.rs | 56 +- .../model-format/src/ple_reader/impl_state.rs | 30 +- crates/model-format/src/ple_reader/tests.rs | 10 +- .../max_inflight_bounds_concurrent_reads.rs | 63 +- .../tests/prefetched_keys_are_matched.rs | 36 +- .../tests/rows_match_the_oracle_including.rs | 67 +- crates/model-format/src/qwen4exp.rs | 18 +- .../src/qwen4exp/expected_inventory.rs | 307 +- .../src/qwen4exp/impl_fmt_display_for.rs | 1 - .../src/qwen4exp/impl_qwen4expartifact.rs | 95 +- .../src/qwen4exp/impl_qwen4expartifact_2.rs | 9 +- .../src/qwen4exp/plan_stream_rows.rs | 167 +- .../src/qwen4exp/validate_logical_views.rs | 31 +- .../qwen4exp/validate_owner_index_split.rs | 35 +- .../src/qwen4exp/validate_role_inventory.rs | 65 +- .../whole_dense_matrix_transport_tests.rs | 171 +- .../src/qwen4exp/whole_moe_matrix_sdet.rs | 37 +- .../qwen4exp_digest_capture/capture_admit.rs | 33 +- .../impl_provisionalexpertsource.rs | 49 +- .../impl_provisionalexpertsource_2.rs | 102 +- .../impl_provisionalexpertsource_3.rs | 27 +- .../impl_qwen4expartifact.rs | 78 +- ...wen4exp_digest_capture_incremental_sdet.rs | 259 +- .../impl_qwen4expartifact.rs | 107 +- .../impl_qwen4expartifact_2.rs | 68 +- .../retention_metadata_bytes.rs | 62 +- .../src/qwen4exp_file_expert_source.rs | 69 +- crates/model-format/src/readahead.rs | 60 +- crates/model-format/src/verify_stamp.rs | 6 +- crates/model-format/src/weight_source.rs | 12 +- .../model-format/src/weight_source/digest.rs | 9 +- crates/model-format/src/weight_source/file.rs | 18 +- .../src/weight_source/kar_inspection_tests.rs | 9 +- .../src/weight_source/kar_levels_tests.rs | 15 +- crates/model-format/src/weight_source/mem.rs | 4 +- .../model-format/src/weight_source/range.rs | 4 +- .../src/weight_source/resident.rs | 23 +- .../model-format/src/weight_source/tests.rs | 83 +- crates/model-format/tests/kar_crc_slicing.rs | 44 +- crates/model-format/tests/kar_extents.rs | 20 +- .../kar_extents/builder_makes_archives.rs | 57 +- .../corrupt_launch_parameters_fail_closed.rs | 119 +- .../f16_widening_matches_exact_reference.rs | 39 +- .../tests/kar_kernel_model/mod.rs | 78 +- .../swiglu_model_matches_silu_times.rs | 20 +- crates/model-format/tests/kar_levels/mod.rs | 12 +- .../scratch_budget_reserves_releases.rs | 88 +- .../tensor_classes_follow_gguf_name.rs | 147 +- .../fused_integrity_scan_preserves_crc.rs | 116 +- .../literal_rows_and_partition_books.rs | 87 +- crates/model-format/tests/kar_ple/mod.rs | 59 +- .../tests/qwen_artifact_binding/fixtures.rs | 6 +- .../fixtures/geometry_fn.rs | 26 +- .../fixtures/impl_tinyowner.rs | 47 +- .../fixtures/metadata_fn.rs | 40 +- .../large_rows_chunk_by_stream.rs | 50 +- .../tests/qwen_artifact_binding/mod.rs | 72 +- .../production_identity_bytes_match.rs | 138 +- .../sec_uc143_inventory_missing_extra.rs | 112 +- .../file_size_mutation_is_refused.rs | 36 +- .../matrix_and_secondary_spans_equal.rs | 46 +- .../model-format/tests/qwen_rows_sdet/mod.rs | 22 +- crates/native-cpu-expert/build.rs | 6 +- .../native-cpu-expert/examples/kernel_ab.rs | 7339 +++++++++-------- crates/native-cpu-expert/rustfmt.toml | 3 + crates/native-cpu-expert/src/cpu_report.rs | 21 +- crates/native-cpu-expert/src/ffi.rs | 84 +- crates/native-cpu-expert/src/impl_cpupool.rs | 139 + .../src/impl_gateupformat.rs | 179 + crates/native-cpu-expert/src/lib.rs | 313 +- crates/native-cpu-expert/src/pool_plan.rs | 6 +- crates/native-cpu-expert/src/rust_bench.rs | 204 +- .../src/rust_bench_frontend.rs | 362 +- .../src/rust_bench_frontend/cpu_blob_fn.rs | 234 + .../rust_bench_frontend/float_reference_fn.rs | 230 + .../src/rust_bench_frontend/numerical_fn.rs | 107 + .../src/rust_bench_frontend/run_fn.rs | 123 + .../native-cpu-expert/src/rust_bench_gpu.rs | 18 +- .../native-cpu-expert/src/rust_bench_model.rs | 400 +- .../native-cpu-expert/src/rust_codebooks.rs | 2223 ++++- crates/native-cpu-expert/src/rust_dequant.rs | 367 +- .../src/rust_expert_layout.rs | 293 +- .../src/rust_general_pool.rs | 185 +- .../rust_general_pool/impl_default_for_job.rs | 51 + .../src/rust_general_pool/impl_expertpool.rs | 254 + .../rust_general_pool/impl_expertpool_2.rs | 176 + .../src/rust_general_pool/impl_shared.rs | 242 + .../src/rust_general_pool/impl_shared_2.rs | 30 + crates/native-cpu-expert/src/rust_ggml.rs | 246 +- .../src/rust_ggml/impl_kind.rs | 219 + .../src/rust_ggml/impl_nativeformat.rs | 214 + .../src/rust_ggml/quantize_raw_fn.rs | 123 + .../native-cpu-expert/src/rust_ggml_extra.rs | 275 +- .../native-cpu-expert/src/rust_ggml_native.rs | 356 +- crates/native-cpu-expert/src/rust_iq.rs | 326 +- .../src/rust_iq/dot_multi512_impl_fn.rs | 228 + .../src/rust_iq/iq4nl_n_fn.rs | 37 + crates/native-cpu-expert/src/rust_iq/tests.rs | 280 + .../native-cpu-expert/src/rust_iq/u16_fn.rs | 226 + crates/native-cpu-expert/src/rust_iq1_grid.rs | 2306 +++++- crates/native-cpu-expert/src/rust_k_blocks.rs | 180 +- crates/native-cpu-expert/src/rust_kq.rs | 372 +- crates/native-cpu-expert/src/rust_legacy.rs | 231 +- .../src/rust_legacy/admit_fn.rs | 217 + .../src/rust_legacy/gate_each_fn.rs | 105 + .../src/rust_legacy/set_oracle_q8_zero_fn.rs | 241 + .../src/rust_legacy/tests.rs | 78 + .../native-cpu-expert/src/rust_model_quant.rs | 81 +- .../src/rust_native_general.rs | 182 +- .../group_dot_bytes_policy_fn.rs | 255 + .../impl_default_for_nativeactivation.rs | 196 + .../src/rust_native_general/iq4nl_rows_fn.rs | 187 + .../src/rust_native_general/tests.rs | 119 + crates/native-cpu-expert/src/rust_platform.rs | 189 +- .../src/rust_platform_win.rs | 9 +- crates/native-cpu-expert/src/rust_pool.rs | 269 +- .../rust_pool/impl_default_for_nativeact.rs | 64 + .../src/rust_pool/impl_nativepool.rs | 245 + .../src/rust_pool/impl_nativepool_2.rs | 128 + .../src/rust_pool/impl_shared.rs | 243 + crates/native-cpu-expert/src/rust_q2.rs | 321 +- crates/native-cpu-expert/src/rust_quant.rs | 465 +- .../native-cpu-expert/src/rust_quant_grids.rs | 563 +- crates/native-cpu-expert/src/rust_simd.rs | 184 +- crates/native-cpu-expert/src/rust_topology.rs | 198 +- crates/native-cpu-expert/src/rust_types.rs | 132 +- .../native-cpu-expert/src/rust_weight_iq.rs | 126 +- .../src/rust_weight_iq/alloc_fn.rs | 224 + .../src/rust_weight_iq/impl_grid.rs | 170 + .../src/rust_weight_iq/iq1_m_fn.rs | 172 + .../src/rust_weight_iq/iq2_xxs_fn.rs | 178 + .../src/rust_weight_iq/iq3_fn.rs | 223 + .../src/rust_weight_quant.rs | 134 +- .../src/rust_weight_quant/best_fp4_fn.rs | 239 + .../src/rust_weight_quant/iq4_fn.rs | 140 + .../src/rust_weight_quant/nearest_fn.rs | 204 + .../src/rust_weight_quant/q45k_fn.rs | 174 + .../src/rust_weight_quant/qp_fn.rs | 238 + .../tests/borrowed_group_parity.rs | 112 +- .../native-cpu-expert/tests/cpu_pool_probe.rs | 5 +- .../tests/cpu_service_bench.rs | 32 +- .../native-cpu-expert/tests/pool_lifecycle.rs | 12 +- .../tests/token_count_invariance.rs | 40 +- crates/obs/rustfmt.toml | 3 + crates/obs/src/hist.rs | 6 +- crates/obs/src/impl_level.rs | 20 +- crates/obs/src/lib.rs | 89 +- crates/obs/src/rate.rs | 10 +- crates/obs/src/redact.rs | 139 +- crates/obs/src/redact/tests.rs | 80 + crates/obs/src/time.rs | 4 +- crates/obs/src/time/clock.rs | 32 +- crates/obs/src/write_stderr_fn.rs | 1 - limits-baseline.json | 92 +- 1637 files changed, 80340 insertions(+), 74407 deletions(-) create mode 100644 crates/context/rustfmt.toml create mode 100644 crates/cuda-driver/rustfmt.toml create mode 100644 crates/cuda-driver/src/mtp_original_full_ffi/enabled.rs create mode 100644 crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs create mode 100644 crates/cuda-driver/src/mtp_original_full_round/impl_stagedsource.rs create mode 100644 crates/cuda-driver/src/mtp_original_full_round/post_select_fn.rs create mode 100644 crates/cuda-driver/src/mtp_original_full_round/put_fn.rs create mode 100644 crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs create mode 100644 crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter_2.rs create mode 100644 crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpprefillplan.rs create mode 100644 crates/cuda-driver/src/original_session_state/add_fn.rs create mode 100644 crates/cuda-driver/src/original_session_state/impl_originalsessionlayout.rs create mode 100644 crates/cuda-driver/src/original_session_state/qsa_price_fn.rs create mode 100644 crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs create mode 100644 crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamall.rs create mode 100644 crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamalloptions_2.rs create mode 100644 crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs create mode 100644 crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs create mode 100644 crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs create mode 100644 crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs create mode 100644 crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank.rs create mode 100644 crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs create mode 100644 crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs create mode 100644 crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs create mode 100644 crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs create mode 100644 crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs create mode 100644 crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs create mode 100644 crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs create mode 100644 crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs create mode 100644 crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs create mode 100644 crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs create mode 100644 crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs create mode 100644 crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs create mode 100644 crates/cuda-driver/src/ple_closed_queue/float_owner_fn.rs create mode 100644 crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs create mode 100644 crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs create mode 100644 crates/cuda-driver/src/prefill_stage_gr_gpu/impl_rng.rs create mode 100644 crates/cuda-driver/src/qsa_index_ffi/enabled.rs create mode 100644 crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs create mode 100644 crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedprefix_2.rs create mode 100644 crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs create mode 100644 crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_device/impl_context.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs create mode 100644 crates/cuda-driver/src/qsa_prompt_index/max_blocks_fn.rs create mode 100644 crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs create mode 100644 crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs create mode 100644 crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index/impl_originalqsaindexbatch.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs create mode 100644 crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs create mode 100644 crates/cuda-driver/src/qsa_resident_transfer/enabled.rs create mode 100644 crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal.rs create mode 100644 crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs create mode 100644 crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs create mode 100644 crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyrope.rs create mode 100644 crates/engine-core/rustfmt.toml create mode 100644 crates/engine-core/src/prompt/grid_tests.rs create mode 100644 crates/engine-core/src/prompt/tests.rs create mode 100644 crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs create mode 100644 crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs create mode 100644 crates/engine-fake/rustfmt.toml create mode 100644 crates/engine-qwen35-cuda/rustfmt.toml create mode 100644 crates/engine-qwen35-cuda/src/backend_original_serve_replay/required_path_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/dense_copies_equal_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_stream_settings_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/compute_row_fn_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_adaptive_packets_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_originalspecengine_for_originalserveengine.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request/tests.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsaprior.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftsession_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/published_first_materialized_fn.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_originalpromptinput_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs create mode 100644 crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs create mode 100644 crates/leleka-memory/rustfmt.toml create mode 100644 crates/leleka-memory/src/pressure/tests.rs create mode 100644 crates/leleka-runtime/rustfmt.toml create mode 100644 crates/model-format/rustfmt.toml create mode 100644 crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs create mode 100644 crates/model-format/src/pinned_arena_plan/load_experts_fn.rs create mode 100644 crates/native-cpu-expert/rustfmt.toml create mode 100644 crates/native-cpu-expert/src/impl_cpupool.rs create mode 100644 crates/native-cpu-expert/src/impl_gateupformat.rs create mode 100644 crates/native-cpu-expert/src/rust_bench_frontend/cpu_blob_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_bench_frontend/float_reference_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_bench_frontend/numerical_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_bench_frontend/run_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_general_pool/impl_default_for_job.rs create mode 100644 crates/native-cpu-expert/src/rust_general_pool/impl_expertpool.rs create mode 100644 crates/native-cpu-expert/src/rust_general_pool/impl_expertpool_2.rs create mode 100644 crates/native-cpu-expert/src/rust_general_pool/impl_shared.rs create mode 100644 crates/native-cpu-expert/src/rust_general_pool/impl_shared_2.rs create mode 100644 crates/native-cpu-expert/src/rust_ggml/impl_kind.rs create mode 100644 crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs create mode 100644 crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_iq/dot_multi512_impl_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_iq/iq4nl_n_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_iq/tests.rs create mode 100644 crates/native-cpu-expert/src/rust_iq/u16_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_legacy/admit_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_legacy/gate_each_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_legacy/tests.rs create mode 100644 crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_native_general/impl_default_for_nativeactivation.rs create mode 100644 crates/native-cpu-expert/src/rust_native_general/iq4nl_rows_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_native_general/tests.rs create mode 100644 crates/native-cpu-expert/src/rust_pool/impl_default_for_nativeact.rs create mode 100644 crates/native-cpu-expert/src/rust_pool/impl_nativepool.rs create mode 100644 crates/native-cpu-expert/src/rust_pool/impl_nativepool_2.rs create mode 100644 crates/native-cpu-expert/src/rust_pool/impl_shared.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs create mode 100644 crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs create mode 100644 crates/obs/rustfmt.toml create mode 100644 crates/obs/src/redact/tests.rs diff --git a/architecture-baseline.json b/architecture-baseline.json index d4f0ce06..5f14f753 100644 --- a/architecture-baseline.json +++ b/architecture-baseline.json @@ -20,20 +20,21 @@ "crates/cpu-sys/src/lib.rs": 1007, "crates/cpu-sys/src/simd.rs": 1503, "crates/cpu-worker/tests/serve_loop.rs": 477, - "crates/cuda-driver/src/experimental.rs": 407, - "crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 618, - "crates/cuda-driver/src/lib.rs": 938, - "crates/cuda-driver/src/mmq_resident_gpu.rs": 517, - "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 621, - "crates/cuda-driver/src/mtp_original_full_symbols.rs": 445, - "crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 676, - "crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 622, - "crates/cuda-driver/src/native_head.rs": 467, - "crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 420, - "crates/cuda-driver/src/qwen_ffi.rs": 876, - "crates/cuda-driver/src/sm86_table.rs": 933, - "crates/cuda-driver/tests/mock_driver.rs": 453, - "crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs": 411, + "crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs": 541, + "crates/cuda-driver/src/lib.rs": 801, + "crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs": 520, + "crates/cuda-driver/src/mtp_original_full_symbols.rs": 404, + "crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs": 557, + "crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs": 487, + "crates/cuda-driver/src/native_head.rs": 483, + "crates/cuda-driver/src/original_verify_window_proj.rs": 439, + "crates/cuda-driver/src/prefill_stage_gdn_gpu.rs": 616, + "crates/cuda-driver/src/prefill_stage_gr_gpu.rs": 445, + "crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs": 415, + "crates/cuda-driver/src/qwen_ffi.rs": 826, + "crates/cuda-driver/src/sm86_table.rs": 1719, + "crates/cuda-driver/tests/mock_driver.rs": 435, + "crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs": 455, "crates/deploy/src/app.rs": 1490, "crates/deploy/src/bin/fake_runtime.rs": 426, "crates/deploy/src/cli/tests.rs": 407, @@ -49,20 +50,17 @@ "crates/deploy/src/sealed.rs": 592, "crates/deploy/src/supervisor.rs": 1863, "crates/deploy/tests/e2e.rs": 2118, - "crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs": 474, - "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 851, - "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 447, - "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs": 979, - "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs": 1648, - "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs": 540, - "crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 651, - "crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 980, - "crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs": 466, - "crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs": 493, - "crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs": 454, + "crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs": 472, + "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs": 993, + "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs": 484, + "crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs": 1247, + "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs": 1528, + "crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs": 465, + "crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs": 465, + "crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs": 492, + "crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs": 857, "crates/experimental-ref/tests/emulated_kernels.rs": 467, "crates/gateway-domain/src/responses/render.rs": 405, - "crates/gateway-text/src/prompt/tests.rs": 492, "crates/gateway-text/src/tool_output/tests.rs": 654, "crates/gguf/src/lib.rs": 560, "crates/gguf/tests/synthetic.rs": 460, @@ -72,7 +70,9 @@ "crates/gptoss/tests/synthetic_model.rs": 922, "crates/igpu/src/lib.rs": 1386, "crates/igpu/src/shaders.rs": 440, - "crates/native-cpu-expert/examples/kernel_ab.rs": 3347, + "crates/native-cpu-expert/examples/kernel_ab.rs": 3992, + "crates/native-cpu-expert/src/rust_codebooks.rs": 1905, + "crates/native-cpu-expert/src/rust_iq1_grid.rs": 2051, "crates/openvino/src/lib.rs": 676, "crates/quant-core/src/iq2s_grid.rs": 1032, "crates/runtime-client/tests/grpc_backend.rs": 689, @@ -109,7 +109,7 @@ "dyn-trait:strata-desktop-core": 2, "env-read:leleka-cpu-kernels": 1, "env-read:leleka-cpu-worker": 2, - "env-read:leleka-cuda-driver": 76, + "env-read:leleka-cuda-driver": 73, "env-read:leleka-deploy": 41, "env-read:leleka-engine-qwen35-cuda": 1, "env-read:leleka-gateway-text": 2, diff --git a/crates/context/rustfmt.toml b/crates/context/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/context/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/context/src/context_policy.rs b/crates/context/src/context_policy.rs index fe706acc..18933d30 100644 --- a/crates/context/src/context_policy.rs +++ b/crates/context/src/context_policy.rs @@ -23,12 +23,12 @@ //! the fp32 indexer store and the rope table. Nothing here is a performance or quality claim. use crate::memory_plan::{ - Costs, EngineResidentEstimate, Geometry, KvFormat, Plan, PlanError, cli_pool, - engine_resident_estimate, kv_bytes_per_token, make_plan_with_format, state_bytes, + Costs, EngineResidentEstimate, Geometry, KvFormat, Plan, PlanError, cli_pool, engine_resident_estimate, + kv_bytes_per_token, make_plan_with_format, state_bytes, }; use crate::rope_scaling::{ - MAX_CHARTER_CONTEXT, ModelRopeKeys, RopeKnobError, RopeKnobs, RopeScaling, RopeScalingType, - SetupRopeError, TRAINED_CONTEXT, resolve_rope_scaling, rope_table_bytes, setup_resolve_rope, + MAX_CHARTER_CONTEXT, ModelRopeKeys, RopeKnobError, RopeKnobs, RopeScaling, RopeScalingType, SetupRopeError, + TRAINED_CONTEXT, resolve_rope_scaling, rope_table_bytes, setup_resolve_rope, }; use std::fmt; @@ -79,11 +79,7 @@ impl ContextRequest { rope_knobs: RopeKnobs::default(), model_rope: ModelRopeKeys::default(), geometry: Geometry::default(), - vram: VramBudget { - free_vram_bytes, - costs: Costs::default(), - state_bytes_per_slot: None, - }, + vram: VramBudget { free_vram_bytes, costs: Costs::default(), state_bytes_per_slot: None }, } } } @@ -112,16 +108,11 @@ impl fmt::Display for PolicyError { Self::ZeroSlots => f.write_str("at least one slot is required"), Self::ZeroContext => f.write_str("the per-slot context must be positive"), Self::ContextTooLarge { requested, max } => { - write!( - f, - "per-slot context {requested} exceeds the supported {max}" - ) + write!(f, "per-slot context {requested} exceeds the supported {max}") + } + Self::ExperimentalKvFormat(k) => { + write!(f, "KV format {} is experimental and was not explicitly enabled", k.name()) } - Self::ExperimentalKvFormat(k) => write!( - f, - "KV format {} is experimental and was not explicitly enabled", - k.name() - ), Self::Setup(e) => write!(f, "{e}"), Self::Rope(e) => write!(f, "{e}"), Self::Plan(e) => write!(f, "{e}"), @@ -173,10 +164,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result MAX_CHARTER_CONTEXT { - return Err(PolicyError::ContextTooLarge { - requested: req.ctx_per_slot, - max: MAX_CHARTER_CONTEXT, - }); + return Err(PolicyError::ContextTooLarge { requested: req.ctx_per_slot, max: MAX_CHARTER_CONTEXT }); } if req.kv_format.is_experimental() && !req.allow_experimental { return Err(PolicyError::ExperimentalKvFormat(req.kv_format)); @@ -184,13 +172,9 @@ pub fn resolve_context(req: &ContextRequest) -> Result= 1.0 { - req.model_rope.orig_ctx as u64 - } else { - TRAINED_CONTEXT - }; - let setup = setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained) - .map_err(PolicyError::Setup)?; + let trained = if req.model_rope.orig_ctx >= 1.0 { req.model_rope.orig_ctx as u64 } else { TRAINED_CONTEXT }; + let setup = + setup_resolve_rope(req.ctx_per_slot, req.rope_scaling, req.rope_scale, trained).map_err(PolicyError::Setup)?; let mut knobs = req.rope_knobs; match setup { Some((kind, scale)) => { @@ -219,8 +203,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result Result s, None => state_bytes(g).map_err(PolicyError::Plan)?, }; - let total_cells = req - .slots - .checked_mul(req.ctx_per_slot) - .ok_or(PolicyError::Plan(PlanError::Overflow))?; - let state_total = req - .slots - .checked_mul(state_per_slot) - .ok_or(PolicyError::Plan(PlanError::Overflow))?; - let costs = Costs { - state_bytes: state_total, - ..req.vram.costs - }; + let total_cells = req.slots.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; + let state_total = req.slots.checked_mul(state_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; + let costs = Costs { state_bytes: state_total, ..req.vram.costs }; let pool = cli_pool(req.vram.free_vram_bytes, &costs).map_err(PolicyError::Plan)?; - let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool) - .map_err(PolicyError::Plan)?; + let plan = make_plan_with_format(total_cells, g, req.kv_format, &costs, pool).map_err(PolicyError::Plan)?; let per_token = kv_bytes_per_token(g, req.kv_format).map_err(PolicyError::Plan)?; - let per_slot = per_token - .checked_mul(req.ctx_per_slot) - .ok_or(PolicyError::Plan(PlanError::Overflow))?; + let per_slot = per_token.checked_mul(req.ctx_per_slot).ok_or(PolicyError::Plan(PlanError::Overflow))?; let engine_estimate = engine_resident_estimate( g, req.kv_format, @@ -265,9 +236,7 @@ pub fn resolve_context(req: &ContextRequest) -> Result e.plan.vram_budget - ); + assert_eq!(e.engine_estimate_exceeds_pool, e.engine_estimate.total > e.plan.vram_budget); } } diff --git a/crates/context/src/geometry.rs b/crates/context/src/geometry.rs index 192ce4a5..08fea84e 100644 --- a/crates/context/src/geometry.rs +++ b/crates/context/src/geometry.rs @@ -39,10 +39,9 @@ pub enum GeometryError { impl fmt::Display for GeometryError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Cells(n) => write!( - f, - "context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}" - ), + Self::Cells(n) => { + write!(f, "context of {n} cells must be a positive multiple of {PAGE_CELLS} and at most {MAX_CELLS}") + } Self::Resident(n) => write!( f, "a resident KV window of {n} cells is not servable: it must give at least {RESOLVE_BLOCK} pages and at most {MAX_CELLS} cells (0 keeps the whole context resident)" @@ -71,9 +70,7 @@ pub struct QsaGeometry { impl QsaGeometry { /// The frozen default (`262144` cells). - pub const TRAINED: Self = Self { - cells: TRAINED_CELLS, - }; + pub const TRAINED: Self = Self { cells: TRAINED_CELLS }; pub fn new(cells: usize) -> R { if cells == 0 || !cells.is_multiple_of(PAGE_CELLS) || cells > MAX_CELLS { @@ -126,21 +123,12 @@ impl QsaGeometry { /// Device staging pool: four runs, identity table and a 4 byte status word (`277_086_212`). pub fn stage_bytes(self) -> R { let r = self.stage_runs()?; - add( - add( - add(add(r[0], r[1])?, add(r[2], r[3])?)?, - self.page_table_bytes(), - )?, - 4, - ) + add(add(add(add(r[0], r[1])?, add(r[2], r[3])?)?, self.page_table_bytes())?, 4) } /// Device bytes of one layer's resident pool: the fixed 8192-page resident runs, the page table and /// `map_bytes` of resolver state. `34_865_152 + map_bytes` at the trained size. pub fn resident_bytes(self, map_bytes: usize) -> R { - add( - add(RESIDENT_RUNS_BYTES, self.page_table_bytes())?, - map_bytes, - ) + add(add(RESIDENT_RUNS_BYTES, self.page_table_bytes())?, map_bytes) } /// Resident pages (VRAM slots) of one streamed QSA layer for `--kv-resident resident_cells` /// (`layer.cpp::kv_plan`, `mode == 1`): `ceil(max(resident_cells, 20480) / 4)`. `0` keeps every page of @@ -154,9 +142,7 @@ impl QsaGeometry { let pages = if resident_cells == 0 { self.pages() } else { - resident_cells - .max(KV_RESIDENT_MIN_CELLS) - .div_ceil(PAGE_CELLS) + resident_cells.max(KV_RESIDENT_MIN_CELLS).div_ceil(PAGE_CELLS) }; if pages < RESOLVE_BLOCK { return Err(GeometryError::Resident(resident_cells)); @@ -167,13 +153,7 @@ impl QsaGeometry { /// context page table and `map_bytes` of resolver state. pub fn resident_bytes_with(self, slots: usize, map_bytes: usize) -> R { let runs = resident_runs(slots)?; - add( - add( - add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?, - self.page_table_bytes(), - )?, - map_bytes, - ) + add(add(add(add(runs[0], runs[1])?, add(runs[2], runs[3])?)?, self.page_table_bytes())?, map_bytes) } /// Canonical host metadata bound of one layer (`NativeQsaResources::CANONICAL_METADATA`). pub fn canonical_metadata_bytes(self) -> R { @@ -220,8 +200,7 @@ impl QsaGeometry { /// [`KvStreamFootprint`] of this context with `--kv-resident resident_cells`. pub fn kv_stream_footprint(self, resident_cells: usize) -> R { let resident_pages = self.resident_pages_for(resident_cells)?; - let layer_vram_bytes = - self.resident_bytes_with(resident_pages, stream_map_bytes(resident_pages)?)?; + let layer_vram_bytes = self.resident_bytes_with(resident_pages, stream_map_bytes(resident_pages)?)?; Ok(KvStreamFootprint { cells: self.cells, resident_cells, diff --git a/crates/context/src/geometry/tests.rs b/crates/context/src/geometry/tests.rs index fb172af3..570d966a 100644 --- a/crates/context/src/geometry/tests.rs +++ b/crates/context/src/geometry/tests.rs @@ -12,14 +12,8 @@ fn trained_geometry_reproduces_every_frozen_literal() { assert_eq!(g.max_blocks(), 65_538); // qsa_prompt_index MAX_BLOCKS assert_eq!(g.host_payload_bytes(), Ok(276_824_064)); // QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES assert_eq!(g.mapped_host_bytes(), Ok(276_825_088)); // QSA_PROMPT_MAPPED_HOST_BYTES, host BYTES - assert_eq!( - g.stage_runs(), - Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304]) - ); - assert_eq!( - g.stage_offsets(), - Ok([0, 134_217_728, 268_435_456, 272_629_760]) - ); + assert_eq!(g.stage_runs(), Ok([134_217_728, 134_217_728, 4_194_304, 4_194_304])); + assert_eq!(g.stage_offsets(), Ok([0, 134_217_728, 268_435_456, 272_629_760])); assert_eq!(g.stage_bytes(), Ok(277_086_212)); // QSA_PROMPT_STAGE_BYTES assert_eq!(g.resident_bytes(0), Ok(34_865_152)); // QSA_PROMPT_RESIDENT_BYTES - MAP_BYTES assert_eq!(g.canonical_metadata_bytes(), Ok(65_536 * 160 + 4096)); @@ -33,40 +27,22 @@ fn trained_geometry_reproduces_every_frozen_literal() { #[test] fn resident_window_follows_kv_plan_and_reproduces_the_frozen_pool_at_the_default() { let g = QsaGeometry::TRAINED; - assert_eq!( - g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), - Ok(RESIDENT_PAGES) - ); + assert_eq!(g.resident_pages_for(KV_RESIDENT_DEFAULT_CELLS), Ok(RESIDENT_PAGES)); assert_eq!(resident_runs(RESIDENT_PAGES), Ok(RESIDENT_RUNS)); assert_eq!(stream_map_bytes(RESIDENT_PAGES), Ok(163_904)); - assert_eq!( - g.resident_bytes_with(RESIDENT_PAGES, 163_904), - g.resident_bytes(163_904) - ); + assert_eq!(g.resident_bytes_with(RESIDENT_PAGES, 163_904), g.resident_bytes(163_904)); // max(resident, qsa_kv_resident_min()) rounded up to whole pages assert_eq!(g.resident_pages_for(1), Ok(5120)); assert_eq!(g.resident_pages_for(20_480), Ok(5120)); assert_eq!(g.resident_pages_for(20_481), Ok(5121)); // 0: the whole context resident assert_eq!(g.resident_pages_for(0), Ok(65_536)); - assert_eq!( - QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0), - Ok(131_072) - ); + assert_eq!(QsaGeometry::new(MAX_CELLS).unwrap().resident_pages_for(0), Ok(131_072)); // a tiny context cannot be fully resident with fewer slots than the resolve block - assert_eq!( - QsaGeometry::new(1024).unwrap().resident_pages_for(0), - Err(GeometryError::Resident(0)) - ); - assert_eq!( - g.resident_pages_for(MAX_CELLS + 4), - Err(GeometryError::Resident(MAX_CELLS + 4)) - ); + assert_eq!(QsaGeometry::new(1024).unwrap().resident_pages_for(0), Err(GeometryError::Resident(0))); + assert_eq!(g.resident_pages_for(MAX_CELLS + 4), Err(GeometryError::Resident(MAX_CELLS + 4))); // production profile: 12 layers x (32768 cells x 1056 B) of VRAM KV - assert_eq!( - resident_runs(RESIDENT_PAGES).unwrap().iter().sum::(), - 32_768 * KV_CELL_BYTES - ); + assert_eq!(resident_runs(RESIDENT_PAGES).unwrap().iter().sum::(), 32_768 * KV_CELL_BYTES); } #[test] @@ -81,10 +57,7 @@ fn production_profile_footprint() { // the smallest window frees 12 x 3072 pages x 4224 B of VRAM for expert slots let small = QsaGeometry::TRAINED.kv_stream_footprint(20_480).unwrap(); assert_eq!(f.vram_bytes - small.vram_bytes, 12 * 3072 * (4224 + 20)); - assert!( - f.to_string() - .starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)") - ); + assert!(f.to_string().starts_with("kv int8 context=262144 resident=32768 cells (8192 pages/layer)")); } #[test] @@ -100,19 +73,10 @@ fn charter_512k_scales_every_cell_linear_size_by_exactly_two() { let b = QsaGeometry::new(MAX_CELLS).unwrap(); assert_eq!(b.pages(), 131_072); assert_eq!(b.page_table_bytes(), 524_288); - assert_eq!( - b.host_payload_bytes().unwrap(), - 2 * a.host_payload_bytes().unwrap() - ); + assert_eq!(b.host_payload_bytes().unwrap(), 2 * a.host_payload_bytes().unwrap()); assert_eq!(b.mapped_host_bytes(), Ok(553_649_152)); - assert_eq!( - b.stage_runs(), - Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608]) - ); - assert_eq!( - b.stage_offsets(), - Ok([0, 268_435_456, 536_870_912, 545_259_520]) - ); + assert_eq!(b.stage_runs(), Ok([268_435_456, 268_435_456, 8_388_608, 8_388_608])); + assert_eq!(b.stage_offsets(), Ok([0, 268_435_456, 536_870_912, 545_259_520])); // staging pool: runs + table + status assert_eq!(b.stage_bytes(), Ok(2 * 276_824_064 + 524_288 + 4)); // the resident runs do not grow, only the table does diff --git a/crates/context/src/memory_plan/impl_default_for_geometry.rs b/crates/context/src/memory_plan/impl_default_for_geometry.rs index 4b11738c..5f58c92c 100644 --- a/crates/context/src/memory_plan/impl_default_for_geometry.rs +++ b/crates/context/src/memory_plan/impl_default_for_geometry.rs @@ -25,18 +25,14 @@ impl Default for Geometry { impl Geometry { pub fn n_gdn_layers(&self) -> Result { - self.n_layers - .checked_sub(self.n_qsa_layers) - .ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers")) + self.n_layers.checked_sub(self.n_qsa_layers).ok_or(PlanError::Geometry("n_qsa_layers exceeds n_layers")) } /// Rejects values that would divide by zero or underflow in the Original's integer arithmetic. pub fn validate(&self) -> Result<(), PlanError> { self.n_gdn_layers()?; if self.kv_group == 0 || self.qsa_block == 0 || self.ssm_d_conv == 0 { - return Err(PlanError::Geometry( - "kv_group, qsa_block and ssm_d_conv must be non-zero", - )); + return Err(PlanError::Geometry("kv_group, qsa_block and ssm_d_conv must be non-zero")); } Ok(()) } @@ -44,14 +40,7 @@ impl Geometry { impl Default for Costs { fn default() -> Self { - Self { - expert_blob: 1_382_400, - dense_bytes: 0, - embd_bytes: 0, - mtp_bytes: 0, - workspace_bytes: 0, - state_bytes: 0, - } + Self { expert_blob: 1_382_400, dense_bytes: 0, embd_bytes: 0, mtp_bytes: 0, workspace_bytes: 0, state_bytes: 0 } } } @@ -77,10 +66,7 @@ pub(super) fn add(a: u64, b: u64) -> R { /// GDN recurrence + conv history, bytes per sequence (plan.hpp `state_bytes`). pub fn state_bytes(g: &Geometry) -> R { g.validate()?; - let recurrence = mul( - mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?, - 4, - )?; + let recurrence = mul(mul(mul(g.ssm_state_size, g.ssm_v_heads)?, g.ssm_state_size)?, 4)?; let conv = mul(mul(g.ssm_d_conv - 1, g.ssm_conv_channels)?, 4)?; mul(g.n_gdn_layers()?, add(recurrence, conv)?) } @@ -127,37 +113,24 @@ impl KvFormat { impl KvShapes { pub fn real() -> Self { - Self { - n_head_kv: 2, - head_dim: 256, - page_size: 4, - } + Self { n_head_kv: 2, head_dim: 256, page_size: 4 } } pub fn from_geometry(g: &Geometry) -> Self { - Self { - n_head_kv: g.n_kv_heads, - head_dim: g.head_dim, - page_size: 4, - } + Self { n_head_kv: g.n_kv_heads, head_dim: g.head_dim, page_size: 4 } } pub(super) fn validate(&self, fmt: KvFormat) -> R<()> { if self.page_size == 0 { return Err(PlanError::Geometry("page_size must be non-zero")); } if fmt != KvFormat::Fp16 && !self.head_dim.is_multiple_of(KV_Q8_GROUP) { - return Err(PlanError::Geometry( - "quantised KV needs head_dim to be a multiple of 64", - )); + return Err(PlanError::Geometry("quantised KV needs head_dim to be a multiple of 64")); } Ok(()) } } pub(super) fn q8_bytes_per_cell(s: &KvShapes) -> R { - add( - mul(mul(s.n_head_kv, s.head_dim)?, 2)?, - mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?, - ) + add(mul(mul(s.n_head_kv, s.head_dim)?, 2)?, mul(mul(s.n_head_kv, s.head_dim / KV_Q8_GROUP)?, 4)?) } pub(super) fn q4_bytes_per_head(head_dim: u64) -> R { mul(head_dim / QK4_0, BLOCK_Q4_0_BYTES) @@ -175,10 +148,7 @@ pub fn kv_cell_bytes(s: &KvShapes, fmt: KvFormat) -> R { KvFormat::K8V4 => { let rows = s.n_head_kv; add( - add( - mul(rows, s.head_dim)?, - mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?, - )?, + add(mul(rows, s.head_dim)?, mul(mul(rows, s.head_dim / KV_Q8_GROUP)?, 2)?)?, mul(rows, q4_bytes_per_head(s.head_dim)?)?, ) } @@ -216,12 +186,6 @@ pub fn make_plan(max_context: u64, g: &Geometry, c: &Costs, pool: u64) -> R R { +pub fn make_plan_with_format(max_context: u64, g: &Geometry, fmt: KvFormat, c: &Costs, pool: u64) -> R { plan_with_per_token(max_context, kv_bytes_per_token(g, fmt)?, c, pool) } diff --git a/crates/context/src/memory_plan/plan_with_per_token.rs b/crates/context/src/memory_plan/plan_with_per_token.rs index ae3eab16..e085a4c6 100644 --- a/crates/context/src/memory_plan/plan_with_per_token.rs +++ b/crates/context/src/memory_plan/plan_with_per_token.rs @@ -3,21 +3,13 @@ #[allow(unused_imports)] use super::*; -pub(super) fn plan_with_per_token( - max_context: u64, - per_token: u64, - c: &Costs, - pool: u64, -) -> R { +pub(super) fn plan_with_per_token(max_context: u64, per_token: u64, c: &Costs, pool: u64) -> R { if c.expert_blob == 0 { return Err(PlanError::Geometry("expert_blob must be non-zero")); } let kv_bytes = mul(per_token, max_context)?; let dram_experts = add(c.dense_bytes, c.embd_bytes)?; - let fixed = add( - add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, - c.state_bytes, - )?; + let fixed = add(add(add(dram_experts, c.mtp_bytes)?, c.workspace_bytes)?, c.state_bytes)?; let need = add(kv_bytes, fixed)?; if need > pool { return does_not_close(format!( @@ -28,9 +20,7 @@ pub(super) fn plan_with_per_token( let cache_slots = cache_bytes / c.expert_blob; let vram_used = pool - cache_bytes % c.expert_blob; if cache_slots == 0 { - return does_not_close(format!( - "no room for even one expert cache slot at max-context {max_context}" - )); + return does_not_close(format!("no room for even one expert cache slot at max-context {max_context}")); } Ok(Plan { max_context, @@ -95,10 +85,7 @@ pub fn engine_resident_estimate( let kv_layer = kv_pool_bytes(&s, pages, fmt)?; let pooled_rows = ctx_per_slot / g.qsa_block + 2; let idx_layer = add( - add( - mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, - mul(g.indexer_key_dim, 4)?, - )?, + add(mul(mul(g.qsa_block - 1, g.indexer_key_dim)?, 4)?, mul(g.indexer_key_dim, 4)?)?, mul(mul(pooled_rows, g.indexer_key_dim)?, 4)?, )?; let per_slot_kv = mul(layers, kv_layer)?; @@ -112,15 +99,6 @@ pub fn engine_resident_estimate( let page_tables = mul(slots, per_slot_pt)?; let indexer_stores = mul(slots, per_slot_idx)?; let rope_tables = mul(slots, per_slot_rope)?; - let total = add( - add(add(kv_pools, page_tables)?, indexer_stores)?, - rope_tables, - )?; - Ok(EngineResidentEstimate { - kv_pools, - page_tables, - indexer_stores, - rope_tables, - total, - }) + let total = add(add(add(kv_pools, page_tables)?, indexer_stores)?, rope_tables)?; + Ok(EngineResidentEstimate { kv_pools, page_tables, indexer_stores, rope_tables, total }) } diff --git a/crates/context/src/memory_plan/tests.rs b/crates/context/src/memory_plan/tests.rs index fc7e098d..99b2456f 100644 --- a/crates/context/src/memory_plan/tests.rs +++ b/crates/context/src/memory_plan/tests.rs @@ -5,10 +5,7 @@ use super::*; #[test] fn real_geometry_constants() { let g = Geometry::default(); - assert_eq!( - state_bytes(&g).unwrap(), - 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4) - ); + assert_eq!(state_bytes(&g).unwrap(), 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)); assert_eq!(state_bytes(&g).unwrap(), 117_669_888); // 12 layers x (1056 + 32) assert_eq!(kv_bytes_per_token_int8(&g).unwrap(), 13_056); @@ -26,19 +23,8 @@ fn per_cell_bytes_on_real_shapes() { #[test] fn int8_generic_equals_literal() { - for g in [ - Geometry::default(), - Geometry { - n_kv_heads: 4, - head_dim: 128, - n_qsa_layers: 9, - ..Geometry::default() - }, - ] { - assert_eq!( - kv_bytes_per_token(&g, KvFormat::Int8).unwrap(), - kv_bytes_per_token_int8(&g).unwrap() - ); + for g in [Geometry::default(), Geometry { n_kv_heads: 4, head_dim: 128, n_qsa_layers: 9, ..Geometry::default() }] { + assert_eq!(kv_bytes_per_token(&g, KvFormat::Int8).unwrap(), kv_bytes_per_token_int8(&g).unwrap()); } } @@ -47,10 +33,7 @@ fn pool_derivation_quirks() { let c = Costs::default(); assert_eq!(cli_pool(12_000_000_000, &c).unwrap(), 12_000_000_000); // derived 0 becomes the default pool - let heavy = Costs { - dense_bytes: 13_000_000_000, - ..c - }; + let heavy = Costs { dense_bytes: 13_000_000_000, ..c }; assert_eq!(cli_pool(12_000_000_000, &heavy).unwrap(), vram_pool_bytes()); assert_eq!(cli_pool(0, &c).unwrap(), vram_pool_bytes()); } @@ -67,28 +50,19 @@ fn does_not_close_messages() { // exactly full pool: zero cache slots let exact = 13_056 * 1000; let e = make_plan(1000, &g, &c, exact).unwrap_err(); - assert_eq!( - e.to_string(), - "no room for even one expert cache slot at max-context 1000" - ); + assert_eq!(e.to_string(), "no room for even one expert cache slot at max-context 1000"); } #[test] fn overflow_is_reported_not_wrapped() { let g = Geometry::default(); - assert_eq!( - make_plan(u64::MAX, &g, &Costs::default(), 1), - Err(PlanError::Overflow) - ); + assert_eq!(make_plan(u64::MAX, &g, &Costs::default(), 1), Err(PlanError::Overflow)); } #[test] fn q4_makes_both_charter_profiles_close_where_int8_does_not() { let g = Geometry::default(); - let c = Costs { - state_bytes: state_bytes(&g).unwrap(), - ..Costs::default() - }; + let c = Costs { state_bytes: state_bytes(&g).unwrap(), ..Costs::default() }; let pool = 5_943_000_000; assert!(make_plan_with_format(524_288, &g, KvFormat::Int8, &c, pool).is_err()); assert!(make_plan_with_format(524_288, &g, KvFormat::Q4_0, &c, pool).is_ok()); diff --git a/crates/context/src/ptx_abi.rs b/crates/context/src/ptx_abi.rs index 9f6f0a12..a2cae35f 100644 --- a/crates/context/src/ptx_abi.rs +++ b/crates/context/src/ptx_abi.rs @@ -64,7 +64,8 @@ pub fn classify_set(entries: &[(&str, &str, usize)], extra: usize) -> Option String { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../cuda-driver/src") - .join(name); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../cuda-driver/src").join(name); std::fs::read_to_string(path).unwrap() } diff --git a/crates/context/src/rope_scaling/fill_rope_table.rs b/crates/context/src/rope_scaling/fill_rope_table.rs index 348a0ceb..157c9673 100644 --- a/crates/context/src/rope_scaling/fill_rope_table.rs +++ b/crates/context/src/rope_scaling/fill_rope_table.rs @@ -22,17 +22,13 @@ pub fn fill_rope_table( return Err(RopeTableError::BufferLength); } let rows = cos_out.len() / half; - let end = first_pos - .checked_add(rows) - .ok_or(RopeTableError::TooManyPositions(rows))?; + let end = first_pos.checked_add(rows).ok_or(RopeTableError::TooManyPositions(rows))?; if i32::try_from(end).is_err() { return Err(RopeTableError::TooManyPositions(end)); } // inv[i] depends only on i: hoisting the pow out of the position loop yields the same value per entry. let n_rot_f = n_rot as f64; - let inv: Vec = (0..half) - .map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)) - .collect(); + let inv: Vec = (0..half).map(|i| sc.freq_base.powf(-2.0 * (i as f64) / n_rot_f)).collect(); if sc.kind == RopeScalingType::None { for r in 0..rows { let p = (first_pos + r) as f64; @@ -50,9 +46,7 @@ pub fn fill_rope_table( let correct = sc.ext_factor != 0.0; let (low, high) = (cd[0] as f32, cd[1] as f32); // the ramp depends on the pair only - let ramp: Vec = (0..half) - .map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor) - .collect(); + let ramp: Vec = (0..half).map(|i| f64::from(rope_yarn_ramp(low, high, i as i32)) * sc.ext_factor).collect(); for r in 0..rows { let p = (first_pos + r) as f64; for i in 0..half { @@ -82,24 +76,13 @@ impl RopeTable { } /// `build_rope_table(n_rot, scaling, n_pos, ...)`; `n_pos` up to 524288 (128 MiB for `n_rot` 64) and beyond. -pub fn build_rope_table( - n_rot: usize, - sc: &RopeScaling, - n_pos: usize, -) -> Result { +pub fn build_rope_table(n_rot: usize, sc: &RopeScaling, n_pos: usize) -> Result { check_n_rot(n_rot)?; - let len = n_pos - .checked_mul(n_rot / 2) - .ok_or(RopeTableError::TooManyPositions(n_pos))?; + let len = n_pos.checked_mul(n_rot / 2).ok_or(RopeTableError::TooManyPositions(n_pos))?; let mut cos = vec![0.0f32; len]; let mut sin = vec![0.0f32; len]; fill_rope_table(n_rot, sc, 0, &mut cos, &mut sin)?; - Ok(RopeTable { - n_rot, - n_pos, - cos, - sin, - }) + Ok(RopeTable { n_rot, n_pos, cos, sin }) } impl Default for RopeKnobs { @@ -144,10 +127,7 @@ impl std::error::Error for RopeKnobError {} /// Port of the `generate.cpp` rope resolution: range checks, then precedence flag > model file > defaults, /// the `none` reset, and the whole-config validity rule. -pub fn resolve_rope_scaling( - knobs: &RopeKnobs, - model: &ModelRopeKeys, -) -> Result { +pub fn resolve_rope_scaling(knobs: &RopeKnobs, model: &ModelRopeKeys) -> Result { let all = [ knobs.rope_scale, knobs.rope_freq_base, @@ -220,16 +200,10 @@ pub fn resolve_rope_scaling( || knobs.yarn_ext_factor > 0.0 || knobs.yarn_attn_factor != 1.0; let base = cfg.freq_base; - cfg = RopeScaling { - freq_base: base, - ..RopeScaling::default() - }; + cfg = RopeScaling { freq_base: base, ..RopeScaling::default() }; } cfg.validate().map_err(RopeKnobError::Invalid)?; - Ok(ResolvedRope { - scaling: cfg, - inert_knobs_ignored: inert, - }) + Ok(ResolvedRope { scaling: cfg, inert_knobs_ignored: inert }) } /// `setup.py::derived_factor`: final context over the trained one, at least 1. diff --git a/crates/context/src/rope_scaling/impl_fmt_display_for.rs b/crates/context/src/rope_scaling/impl_fmt_display_for.rs index 09ef6326..2622fe36 100644 --- a/crates/context/src/rope_scaling/impl_fmt_display_for.rs +++ b/crates/context/src/rope_scaling/impl_fmt_display_for.rs @@ -35,16 +35,10 @@ pub fn setup_resolve_rope( return Ok(None); } let kind = scaling.unwrap_or(RopeScalingType::YaRN); - return Ok(Some(( - kind, - scale.unwrap_or_else(|| derived_factor(ctx, trained)), - ))); + return Ok(Some((kind, scale.unwrap_or_else(|| derived_factor(ctx, trained))))); } if scaling == Some(RopeScalingType::None) { return Err(SetupRopeError::NoneBeyondTrained); } - Ok(Some(( - scaling.unwrap_or(RopeScalingType::YaRN), - scale.unwrap_or_else(|| derived_factor(ctx, trained)), - ))) + Ok(Some((scaling.unwrap_or(RopeScalingType::YaRN), scale.unwrap_or_else(|| derived_factor(ctx, trained))))) } diff --git a/crates/context/src/rope_scaling/impl_ropescalingtype.rs b/crates/context/src/rope_scaling/impl_ropescalingtype.rs index 1e4ab068..a172aada 100644 --- a/crates/context/src/rope_scaling/impl_ropescalingtype.rs +++ b/crates/context/src/rope_scaling/impl_ropescalingtype.rs @@ -23,13 +23,7 @@ impl RopeScalingType { impl Default for RopeKernelArgs { fn default() -> Self { - Self { - freq_scale: 1.0, - corr_low: 0.0, - corr_high: 0.0, - ext_factor: 0.0, - attn_factor: 1.0, - } + Self { freq_scale: 1.0, corr_low: 0.0, corr_high: 0.0, ext_factor: 0.0, attn_factor: 1.0 } } } @@ -39,9 +33,7 @@ impl RopeScalingError { Self::FreqBase => "the frequency base must be a finite value above 1", Self::Factor => "the scaling factor must be a finite value >= 1", Self::FreqScaleIn => "the frequency scale must be finite and positive (0 = 1/factor)", - Self::ResolvedFreqScale => { - "the resolved frequency scale must be a finite positive value" - } + Self::ResolvedFreqScale => "the resolved frequency scale must be a finite positive value", Self::OrigCtx => "the original (trained) context must be finite and > 0", Self::ExtFactor => "the YaRN ext factor must be finite and >= 0", Self::AttnFactor => "the attention factor must be finite and > 0", @@ -86,11 +78,7 @@ impl RopeScaling { if self.kind == RopeScalingType::None { return 1.0; } - if self.freq_scale_in > 0.0 { - self.freq_scale_in - } else { - 1.0 / self.factor - } + if self.freq_scale_in > 0.0 { self.freq_scale_in } else { 1.0 / self.factor } } /// The magnitude correction; the log term rides on `ext_factor != 0`, not on the type. @@ -103,14 +91,10 @@ impl RopeScaling { /// The correction window in PAIR indices, clamped to `[0, n_rot - 1]`. pub fn corr_dims(&self, n_rot: i32) -> [f64; 2] { - let start = - rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor(); + let start = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_fast, self.freq_base).floor(); let end = rope_yarn_corr_dim(n_rot, self.orig_ctx, self.beta_slow, self.freq_base).ceil(); let hi = f64::from(n_rot - 1); - [ - if start < 0.0 { 0.0 } else { start }, - if end > hi { hi } else { end }, - ] + [if start < 0.0 { 0.0 } else { start }, if end > hi { hi } else { end }] } /// The analytic kernels' constants; `none` returns the identity whatever the other knobs hold. @@ -156,10 +140,7 @@ impl RopeScaling { if !self.attn_factor.is_finite() || self.attn_factor <= 0.0 { return Err(RopeScalingError::AttnFactor); } - if !self.beta_fast.is_finite() - || self.beta_fast <= 0.0 - || !self.beta_slow.is_finite() - || self.beta_slow <= 0.0 + if !self.beta_fast.is_finite() || self.beta_fast <= 0.0 || !self.beta_slow.is_finite() || self.beta_slow <= 0.0 { return Err(RopeScalingError::Betas); } diff --git a/crates/context/src/rope_scaling/tests.rs b/crates/context/src/rope_scaling/tests.rs index 4bdf06cd..6c56d9ff 100644 --- a/crates/context/src/rope_scaling/tests.rs +++ b/crates/context/src/rope_scaling/tests.rs @@ -3,12 +3,7 @@ use super::*; fn yarn(factor: f64) -> RopeScaling { - RopeScaling { - kind: RopeScalingType::YaRN, - factor, - ext_factor: 1.0, - ..RopeScaling::default() - } + RopeScaling { kind: RopeScalingType::YaRN, factor, ext_factor: 1.0, ..RopeScaling::default() } } #[test] @@ -49,11 +44,7 @@ fn non_finite_values_are_rejected_before_range_checks() { s.attn_factor = f64::NAN; assert_eq!(s.validate(), Err(RopeScalingError::AttnFactor)); // none ignores every knob except the base - let n = RopeScaling { - factor: f64::NAN, - beta_fast: -1.0, - ..RopeScaling::default() - }; + let n = RopeScaling { factor: f64::NAN, beta_fast: -1.0, ..RopeScaling::default() }; assert_eq!(n.validate(), Ok(())); } @@ -81,25 +72,13 @@ fn position_zero_exposes_mscale() { #[test] fn bad_shapes_and_configs_are_refused() { - assert_eq!( - build_rope_table(63, &RopeScaling::default(), 1), - Err(RopeTableError::NRot(63)) - ); - assert_eq!( - build_rope_table(0, &RopeScaling::default(), 1), - Err(RopeTableError::NRot(0)) - ); + assert_eq!(build_rope_table(63, &RopeScaling::default(), 1), Err(RopeTableError::NRot(63))); + assert_eq!(build_rope_table(0, &RopeScaling::default(), 1), Err(RopeTableError::NRot(0))); let bad = yarn(0.5); - assert!(matches!( - build_rope_table(64, &bad, 1), - Err(RopeTableError::Config(RopeScalingError::Factor)) - )); + assert!(matches!(build_rope_table(64, &bad, 1), Err(RopeTableError::Config(RopeScalingError::Factor)))); let mut c = vec![0.0; 33]; let mut s = vec![0.0; 33]; - assert_eq!( - fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s), - Err(RopeTableError::BufferLength) - ); + assert_eq!(fill_rope_table(64, &RopeScaling::default(), 0, &mut c, &mut s), Err(RopeTableError::BufferLength)); } #[test] @@ -115,30 +94,12 @@ fn setup_resolution_matches_setup_py() { let t = TRAINED_CONTEXT; assert_eq!(setup_resolve_rope(t, None, None, t), Ok(None)); assert_eq!(setup_resolve_rope(t, nn, None, t), Ok(None)); - assert_eq!( - setup_resolve_rope(t, None, Some(2.0), t), - Err(SetupRopeError::ScaleWithoutMethod) - ); - assert_eq!( - setup_resolve_rope(t, Some(Linear), None, t), - Ok(Some((Linear, 1.0))) - ); - assert_eq!( - setup_resolve_rope(524_288, None, None, t), - Ok(Some((YaRN, 2.0))) - ); - assert_eq!( - setup_resolve_rope(393_216, None, None, t), - Ok(Some((YaRN, 1.5))) - ); - assert_eq!( - setup_resolve_rope(524_288, Some(Linear), Some(3.0), t), - Ok(Some((Linear, 3.0))) - ); - assert_eq!( - setup_resolve_rope(524_288, nn, None, t), - Err(SetupRopeError::NoneBeyondTrained) - ); + assert_eq!(setup_resolve_rope(t, None, Some(2.0), t), Err(SetupRopeError::ScaleWithoutMethod)); + assert_eq!(setup_resolve_rope(t, Some(Linear), None, t), Ok(Some((Linear, 1.0)))); + assert_eq!(setup_resolve_rope(524_288, None, None, t), Ok(Some((YaRN, 2.0)))); + assert_eq!(setup_resolve_rope(393_216, None, None, t), Ok(Some((YaRN, 1.5)))); + assert_eq!(setup_resolve_rope(524_288, Some(Linear), Some(3.0), t), Ok(Some((Linear, 3.0)))); + assert_eq!(setup_resolve_rope(524_288, nn, None, t), Err(SetupRopeError::NoneBeyondTrained)); } #[test] @@ -149,47 +110,24 @@ fn knob_resolution_follows_generate_cpp() { assert!(!r.inert_knobs_ignored); // yarn factor 2: ext auto = 1 - let k = RopeKnobs { - scaling: Some(RopeScalingType::YaRN), - rope_scale: 2.0, - ..RopeKnobs::default() - }; + let k = RopeKnobs { scaling: Some(RopeScalingType::YaRN), rope_scale: 2.0, ..RopeKnobs::default() }; let r = resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap(); assert_eq!(r.scaling.kind, RopeScalingType::YaRN); assert_eq!(r.scaling.factor, 2.0); assert_eq!(r.scaling.ext_factor, 1.0); // linear: ext auto = 0 - let k = RopeKnobs { - scaling: Some(RopeScalingType::Linear), - rope_scale: 2.0, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&k, &ModelRopeKeys::default()) - .unwrap() - .scaling - .ext_factor, - 0.0 - ); + let k = RopeKnobs { scaling: Some(RopeScalingType::Linear), rope_scale: 2.0, ..RopeKnobs::default() }; + assert_eq!(resolve_rope_scaling(&k, &ModelRopeKeys::default()).unwrap().scaling.ext_factor, 0.0); // model file supplies defaults; an explicit none opts out and notes the dropped knobs - let model = ModelRopeKeys { - scaling_type: Some("yarn".into()), - factor: 2.0, - freq_base: 5e6, - orig_ctx: 131_072.0, - }; + let model = ModelRopeKeys { scaling_type: Some("yarn".into()), factor: 2.0, freq_base: 5e6, orig_ctx: 131_072.0 }; let r = resolve_rope_scaling(&RopeKnobs::default(), &model).unwrap(); assert_eq!(r.scaling.kind, RopeScalingType::YaRN); assert_eq!(r.scaling.factor, 2.0); assert_eq!(r.scaling.freq_base, 5e6); assert_eq!(r.scaling.orig_ctx, 131_072.0); - let k = RopeKnobs { - scaling: Some(RopeScalingType::None), - rope_scale: 2.0, - ..RopeKnobs::default() - }; + let k = RopeKnobs { scaling: Some(RopeScalingType::None), rope_scale: 2.0, ..RopeKnobs::default() }; let r = resolve_rope_scaling(&k, &model).unwrap(); assert_eq!(r.scaling.kind, RopeScalingType::None); assert_eq!(r.scaling.freq_base, 5e6); @@ -197,43 +135,16 @@ fn knob_resolution_follows_generate_cpp() { assert!(r.inert_knobs_ignored); // refusals - let bad_scale = RopeKnobs { - rope_scale: 0.5, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&bad_scale, &model), - Err(RopeKnobError::ScaleBelowOne) - ); - let nan = RopeKnobs { - yarn_beta_fast: f64::NAN, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&nan, &model), - Err(RopeKnobError::NotFinite) - ); - let base1 = RopeKnobs { - rope_freq_base: 1.0, - ..RopeKnobs::default() - }; - assert_eq!( - resolve_rope_scaling(&base1, &model), - Err(RopeKnobError::FreqBase) - ); - let neg = RopeKnobs { - yarn_attn_factor: 0.0, - ..RopeKnobs::default() - }; + let bad_scale = RopeKnobs { rope_scale: 0.5, ..RopeKnobs::default() }; + assert_eq!(resolve_rope_scaling(&bad_scale, &model), Err(RopeKnobError::ScaleBelowOne)); + let nan = RopeKnobs { yarn_beta_fast: f64::NAN, ..RopeKnobs::default() }; + assert_eq!(resolve_rope_scaling(&nan, &model), Err(RopeKnobError::NotFinite)); + let base1 = RopeKnobs { rope_freq_base: 1.0, ..RopeKnobs::default() }; + assert_eq!(resolve_rope_scaling(&base1, &model), Err(RopeKnobError::FreqBase)); + let neg = RopeKnobs { yarn_attn_factor: 0.0, ..RopeKnobs::default() }; assert_eq!(resolve_rope_scaling(&neg, &model), Err(RopeKnobError::Knob)); - let weird = ModelRopeKeys { - scaling_type: Some("longrope".into()), - ..ModelRopeKeys::default() - }; - assert_eq!( - resolve_rope_scaling(&RopeKnobs::default(), &weird), - Err(RopeKnobError::ModelType("longrope".into())) - ); + let weird = ModelRopeKeys { scaling_type: Some("longrope".into()), ..ModelRopeKeys::default() }; + assert_eq!(resolve_rope_scaling(&RopeKnobs::default(), &weird), Err(RopeKnobError::ModelType("longrope".into()))); // a resolved factor that is fine per-flag but invalid as a whole let k = RopeKnobs { scaling: Some(RopeScalingType::YaRN), diff --git a/crates/context/src/setup_policy.rs b/crates/context/src/setup_policy.rs index bfbbf859..0b20819d 100644 --- a/crates/context/src/setup_policy.rs +++ b/crates/context/src/setup_policy.rs @@ -28,36 +28,12 @@ pub struct Model { /// `setup.py` `MODELS`, in file order. pub const MODELS: [Model; 6] = [ - Model { - name: "Q2_0", - ram_gb: 48, - arena_gb: 34.0, - }, - Model { - name: "IQ2_XS", - ram_gb: 48, - arena_gb: 35.5, - }, - Model { - name: "IQ3_XXS", - ram_gb: 60, - arena_gb: 42.9, - }, - Model { - name: "IQ3_S", - ram_gb: 62, - arena_gb: 50.3, - }, - Model { - name: "IQ1_M", - ram_gb: 32, - arena_gb: 23.4, - }, - Model { - name: "UD-Q4_K_XL", - ram_gb: 48, - arena_gb: 77.0, - }, + Model { name: "Q2_0", ram_gb: 48, arena_gb: 34.0 }, + Model { name: "IQ2_XS", ram_gb: 48, arena_gb: 35.5 }, + Model { name: "IQ3_XXS", ram_gb: 60, arena_gb: 42.9 }, + Model { name: "IQ3_S", ram_gb: 62, arena_gb: 50.3 }, + Model { name: "IQ1_M", ram_gb: 32, arena_gb: 23.4 }, + Model { name: "UD-Q4_K_XL", ram_gb: 48, arena_gb: 77.0 }, ]; pub fn model(name: &str) -> Option<&'static Model> { @@ -73,11 +49,7 @@ pub enum Kv { impl Kv { pub fn parse(name: &str) -> Self { - if name == "q4_0" { - Self::Q4_0 - } else { - Self::Int8 - } + if name == "q4_0" { Self::Q4_0 } else { Self::Int8 } } } diff --git a/crates/context/tests/context_lift.rs b/crates/context/tests/context_lift.rs index 16a2993a..adda97fd 100644 --- a/crates/context/tests/context_lift.rs +++ b/crates/context/tests/context_lift.rs @@ -2,23 +2,14 @@ //! geometry the driver and runtime allocate from. The driver and runtime consume `QsaGeometry` through their //! serving context (linux-only crates); everything they size is a function of the values asserted here. -use leleka_context::context_policy::{ - CHARTER_PROFILES, ContextRequest, PolicyError, ROPE_N_ROT, resolve_context, -}; +use leleka_context::context_policy::{CHARTER_PROFILES, ContextRequest, PolicyError, ROPE_N_ROT, resolve_context}; use leleka_context::geometry::{MAX_CELLS, QsaGeometry, TRAINED_CELLS}; use leleka_context::memory_plan::KvFormat; use leleka_context::rope_scaling::{RopeScalingType, build_rope_table}; const GIB: u64 = 1 << 30; -fn geometry_of( - slots: u64, - ctx: u64, - vram: u64, -) -> ( - leleka_context::context_policy::EffectiveContext, - QsaGeometry, -) { +fn geometry_of(slots: u64, ctx: u64, vram: u64) -> (leleka_context::context_policy::EffectiveContext, QsaGeometry) { let e = resolve_context(&ContextRequest::new(slots, ctx, KvFormat::Int8, vram)).unwrap(); let g = QsaGeometry::new(e.ctx_per_slot as usize).unwrap(); (e, g) @@ -45,10 +36,7 @@ fn two_slots_of_256k_size_each_slot_like_the_default_without_scaling() { assert_eq!(e.total_cells, 524_288); assert_eq!(g, QsaGeometry::TRAINED, "per-slot buffers do not grow"); assert_eq!(e.rope_table_rows, TRAINED_CELLS as u64); - assert_eq!( - e.rope_table_bytes, - g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64 - ); + assert_eq!(e.rope_table_bytes, g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64); } #[test] @@ -63,22 +51,13 @@ fn one_slot_of_512k_with_yarn_2_scales_every_buffer_formula() { assert_eq!(g.page_table_bytes(), 2 * t.page_table_bytes()); assert_eq!(g.pooled_rows(), 2 * t.pages() + 1); assert_eq!(g.max_blocks(), 2 * t.pages() + 2); - assert_eq!( - g.host_payload_bytes().unwrap(), - 2 * t.host_payload_bytes().unwrap() - ); - assert_eq!( - g.mapped_host_bytes().unwrap(), - 2 * t.host_payload_bytes().unwrap() + 1024 - ); + assert_eq!(g.host_payload_bytes().unwrap(), 2 * t.host_payload_bytes().unwrap()); + assert_eq!(g.mapped_host_bytes().unwrap(), 2 * t.host_payload_bytes().unwrap() + 1024); for (a, b) in g.stage_runs().unwrap().iter().zip(t.stage_runs().unwrap()) { assert_eq!(*a, 2 * b); } assert_eq!(g.canonical_metadata_bytes().unwrap(), 131_072 * 160 + 4096); - assert_eq!( - e.rope_table_bytes, - g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64 - ); + assert_eq!(e.rope_table_bytes, g.rope_table_bytes(ROPE_N_ROT).unwrap() as u64); assert_eq!(e.rope_table_rows as usize, g.cells()); // the planner and the geometry agree on the total cell count assert_eq!(e.total_cells as usize, g.cells()); @@ -97,13 +76,7 @@ fn charter_profiles_all_resolve_and_total_at_most_512k_cells() { #[test] fn planner_refusals() { // KV does not close on the default 5.943 GB pool - let small = resolve_context(&ContextRequest::new( - 1, - 524_288, - KvFormat::Int8, - 5_943_000_000, - )) - .unwrap_err(); + let small = resolve_context(&ContextRequest::new(1, 524_288, KvFormat::Int8, 5_943_000_000)).unwrap_err(); assert!(small.is_planner_rejection()); // two slots of 512K are past the charter and past the supported bound assert!(matches!( @@ -126,10 +99,7 @@ fn boundary_positions_262143_262144_524287_524288() { // `admits_end(n)` is "n tokens fit": the last valid position is n - 1 assert!(t.admits_end(262_143 + 1)); assert!(!t.admits_end(262_144 + 1)); - assert!( - m.admits_end(262_144 + 1), - "262144 is a valid position at 512K" - ); + assert!(m.admits_end(262_144 + 1), "262144 is a valid position at 512K"); assert!(m.admits_end(524_287 + 1)); assert!(!m.admits_end(524_288 + 1)); @@ -138,13 +108,7 @@ fn boundary_positions_262143_262144_524287_524288() { let scaled = build_rope_table(ROPE_N_ROT, &e.rope, MAX_CELLS).unwrap(); assert_eq!(scaled.n_pos, MAX_CELLS); for pos in [262_143usize, 262_144, 524_287] { - assert!( - scaled - .row_cos(pos) - .iter() - .chain(scaled.row_sin(pos)) - .all(|v| v.is_finite()) - ); + assert!(scaled.row_cos(pos).iter().chain(scaled.row_sin(pos)).all(|v| v.is_finite())); } let (d, _) = geometry_of(1, 262_144, 32 * GIB); let plain = build_rope_table(ROPE_N_ROT, &d.rope, TRAINED_CELLS).unwrap(); diff --git a/crates/context/tests/rope_plan_golden.rs b/crates/context/tests/rope_plan_golden.rs index f52ee8bd..344f9731 100644 --- a/crates/context/tests/rope_plan_golden.rs +++ b/crates/context/tests/rope_plan_golden.rs @@ -12,12 +12,10 @@ #![allow(clippy::too_many_lines)] use leleka_context::memory_plan::{ - Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan, - make_plan_with_format, state_bytes, -}; -use leleka_context::rope_scaling::{ - RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle, + Costs, Geometry, KvFormat, KvShapes, PlanError, cli_pool, kv_pool_bytes, make_plan, make_plan_with_format, + state_bytes, }; +use leleka_context::rope_scaling::{RopeScaling, RopeScalingType, fill_rope_table, rope_scaled_angle}; use serde_json::Value; const ROPE_JSON: &str = include_str!("rope_plan_golden/rope_golden.json"); @@ -41,11 +39,7 @@ fn ulp_diff(a: f32, b: f32) -> u32 { } let map = |x: f32| { let u = x.to_bits() as i64; - if u >= 0x8000_0000 { - 0x8000_0000 - (u & 0x7fff_ffff) - } else { - u + 0x8000_0000 - } + if u >= 0x8000_0000 { 0x8000_0000 - (u & 0x7fff_ffff) } else { u + 0x8000_0000 } }; (map(a) - map(b)).unsigned_abs() as u32 } @@ -107,18 +101,11 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { let name = c["name"].as_str().unwrap(); // validity message, exactly let want = c["invalid"].as_str(); - assert_eq!( - sc.validate().err().map(|e| e.reason()), - want, - "{name}: validity" - ); + assert_eq!(sc.validate().err().map(|e| e.reason()), want, "{name}: validity"); // scalar resolutions: libm log is the only dependency let tol = if EXACT { 0.0 } else { 4.0 * f64::EPSILON }; let near = |a: f64, b: f64| (a - b).abs() <= tol * b.abs().max(1.0); - assert!( - near(sc.freq_scale(), bits64(&c["freq_scale"])), - "{name}: freq_scale" - ); + assert!(near(sc.freq_scale(), bits64(&c["freq_scale"])), "{name}: freq_scale"); if want.is_none() || sc.freq_scale().is_finite() { assert!(near(sc.mscale(), bits64(&c["mscale"])), "{name}: mscale"); } @@ -126,18 +113,11 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { for k in 0..2 { let want = bits64(&c["corr_dims"][k]); // a NaN from log(<0) of an invalid config: any NaN matches (payload/sign are libm detail) - assert!( - cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()), - "{name}: corr_dims[{k}]" - ); + assert!(cd[k].to_bits() == want.to_bits() || (cd[k].is_nan() && want.is_nan()), "{name}: corr_dims[{k}]"); } let a = sc.kernel_args(n_rot); let w = &c["kernel_args"]; - assert_eq!( - a.freq_scale.to_bits(), - bits32(&w["freq_scale"]).to_bits(), - "{name}: args.freq_scale" - ); + assert_eq!(a.freq_scale.to_bits(), bits32(&w["freq_scale"]).to_bits(), "{name}: args.freq_scale"); assert!( same_f32(a.corr_low, bits32(&w["corr_low"])), "{name}: args.corr_low: {:#010x} vs {:#010x}", @@ -150,16 +130,8 @@ fn check_scalars(c: &Value, sc: &RopeScaling, n_rot: i32) { a.corr_high.to_bits(), bits32(&w["corr_high"]).to_bits() ); - assert_eq!( - a.ext_factor.to_bits(), - bits32(&w["ext_factor"]).to_bits(), - "{name}: args.ext_factor" - ); - assert_eq!( - a.attn_factor.to_bits(), - bits32(&w["attn_factor"]).to_bits(), - "{name}: args.attn_factor" - ); + assert_eq!(a.ext_factor.to_bits(), bits32(&w["ext_factor"]).to_bits(), "{name}: args.ext_factor"); + assert_eq!(a.attn_factor.to_bits(), bits32(&w["attn_factor"]).to_bits(), "{name}: args.attn_factor"); // analytic float32 path for s in c["analytic"].as_array().unwrap() { let (co, si) = rope_scaled_angle( @@ -198,18 +170,8 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { if p >= first && p < first + CHUNK { let r = p - first; for i in 0..half { - assert_close( - &format!("{name}: row {p} cos[{i}]"), - cbuf[r * half + i], - bits32(&s["cos"][i]), - 1, - ); - assert_close( - &format!("{name}: row {p} sin[{i}]"), - sbuf[r * half + i], - bits32(&s["sin"][i]), - 1, - ); + assert_close(&format!("{name}: row {p} cos[{i}]"), cbuf[r * half + i], bits32(&s["cos"][i]), 1); + assert_close(&format!("{name}: row {p} sin[{i}]"), sbuf[r * half + i], bits32(&s["sin"][i]), 1); } } } @@ -234,10 +196,7 @@ fn check_tables(c: &Value, sc: &RopeScaling, n_rot: usize) { } fn run_case(name: &str) { - let c = cases() - .into_iter() - .find(|c| c["name"] == name) - .expect("case in fixture"); + let c = cases().into_iter().find(|c| c["name"] == name).expect("case in fixture"); let sc = config_of(&c); let n_rot = c["n_rot"].as_u64().unwrap() as usize; check_scalars(&c, &sc, n_rot as i32); @@ -314,10 +273,7 @@ fn interpret_cli(args: &[String]) -> Option<(i32, String, String)> { Some(match make_plan(ctx, &g, &costs, pool) { Ok(p) => { // the format-generic path with INT8 must be the same plan - assert_eq!( - make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(), - p - ); + assert_eq!(make_plan_with_format(ctx, &g, KvFormat::Int8, &costs, pool).unwrap(), p); (0, p.to_text(), String::new()) } Err(e @ PlanError::DoesNotClose(_)) => (1, String::new(), format!("strata-plan: {e}\n")), diff --git a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs index becfa873..13ec748f 100644 --- a/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs +++ b/crates/context/tests/rope_plan_golden/every_fixture_case_has.rs @@ -3,13 +3,9 @@ #[allow(unused_imports)] use super::*; - #[test] fn every_fixture_case_has_a_test() { - let names: Vec = cases() - .iter() - .map(|c| c["name"].as_str().unwrap().to_owned()) - .collect(); + let names: Vec = cases().iter().map(|c| c["name"].as_str().unwrap().to_owned()).collect(); assert_eq!(names.len(), 25); } @@ -20,10 +16,7 @@ fn yarn_is_observably_different_from_none() { let find = |n: &str| cs.iter().find(|c| c["name"] == n).unwrap().clone(); let (a, b) = (find("none_default"), find("yarn_2")); assert_ne!(a["tables"][1]["cos_fnv1a64"], b["tables"][1]["cos_fnv1a64"]); - assert_ne!( - find("linear_2")["tables"][1]["cos_fnv1a64"], - b["tables"][1]["cos_fnv1a64"] - ); + assert_ne!(find("linear_2")["tables"][1]["cos_fnv1a64"], b["tables"][1]["cos_fnv1a64"]); // yarn with ext_factor 0 and a non-unit mscale path differs from linear only by the log term being off assert_eq!(find("yarn_ext0")["mscale"], find("linear_2")["mscale"]); } @@ -31,39 +24,25 @@ fn yarn_is_observably_different_from_none() { #[test] fn strata_plan_cli_output_is_reproduced_exactly() { let root: Value = serde_json::from_str(PLAN_JSON).unwrap(); - assert_eq!( - root["state_bytes_default"].as_u64().unwrap(), - state_bytes(&Geometry::default()).unwrap() - ); + assert_eq!(root["state_bytes_default"].as_u64().unwrap(), state_bytes(&Geometry::default()).unwrap()); let mut compared = 0; let mut closed = 0; let mut refused = 0; for run in root["cli"].as_array().unwrap() { - let args: Vec = run["args"] - .as_array() - .unwrap() - .iter() - .map(|a| a.as_str().unwrap().to_owned()) - .collect(); + let args: Vec = + run["args"].as_array().unwrap().iter().map(|a| a.as_str().unwrap().to_owned()).collect(); let Some((exit, out, err)) = interpret_cli(&args) else { assert!(matches!(run["exit"].as_i64().unwrap(), 0 | 2), "{args:?}"); continue; }; - assert_eq!( - exit as i64, - run["exit"].as_i64().unwrap(), - "{args:?}: exit code" - ); + assert_eq!(exit as i64, run["exit"].as_i64().unwrap(), "{args:?}: exit code"); assert_eq!(out, run["stdout"].as_str().unwrap(), "{args:?}: stdout"); assert_eq!(err, run["stderr"].as_str().unwrap(), "{args:?}: stderr"); compared += 1; if exit == 0 { closed += 1 } else { refused += 1 } } // the table must exercise both outcomes, or the comparison is vacuous - assert!( - compared >= 60 && closed >= 30 && refused >= 8, - "{compared} {closed} {refused}" - ); + assert!(compared >= 60 && closed >= 30 && refused >= 8, "{compared} {closed} {refused}"); } #[test] diff --git a/crates/context/tests/setup_policy_oracle.rs b/crates/context/tests/setup_policy_oracle.rs index a8206838..e2bfe80d 100644 --- a/crates/context/tests/setup_policy_oracle.rs +++ b/crates/context/tests/setup_policy_oracle.rs @@ -16,11 +16,7 @@ fn model(name: &Value) -> &'static policy::Model { } fn same(got: f64, want: &Value, what: &str) { - assert_eq!( - got.to_bits(), - want.as_f64().unwrap().to_bits(), - "{what}: {got} vs {want}" - ); + assert_eq!(got.to_bits(), want.as_f64().unwrap().to_bits(), "{what}: {got} vs {want}"); } #[test] @@ -28,20 +24,11 @@ fn model_table_and_contexts_are_setup_pys() { let g = golden(); for (name, row) in g["models"].as_object().unwrap() { let m = policy::model(name).unwrap_or_else(|| panic!("{name} missing")); - assert_eq!( - u64::from(m.ram_gb), - row["ram_gb"].as_u64().unwrap(), - "{name}" - ); + assert_eq!(u64::from(m.ram_gb), row["ram_gb"].as_u64().unwrap(), "{name}"); same(m.arena_gb, &row["arena_gb"], name); } assert_eq!(g["models"].as_object().unwrap().len(), policy::MODELS.len()); - let contexts: Vec = g["contexts"] - .as_array() - .unwrap() - .iter() - .map(|c| c.as_u64().unwrap()) - .collect(); + let contexts: Vec = g["contexts"].as_array().unwrap().iter().map(|c| c.as_u64().unwrap()).collect(); assert_eq!(contexts, policy::CONTEXTS); } @@ -50,10 +37,7 @@ fn derived_factor_and_resolve_rope_match() { let g = golden(); for row in g["derived_factor"].as_array().unwrap() { same( - derived_factor( - row["ctx"].as_u64().unwrap(), - row["trained"].as_u64().unwrap(), - ), + derived_factor(row["ctx"].as_u64().unwrap(), row["trained"].as_u64().unwrap()), &row["result"], "derived_factor", ); @@ -68,12 +52,8 @@ fn derived_factor_and_resolve_rope_match() { let rows = g["resolve_rope"].as_array().unwrap(); assert!(rows.len() > 300); for row in rows { - let got = setup_resolve_rope( - row["ctx"].as_u64().unwrap(), - kind(&row["scaling"]), - row["scale"].as_f64(), - 262144, - ); + let got = + setup_resolve_rope(row["ctx"].as_u64().unwrap(), kind(&row["scaling"]), row["scale"].as_f64(), 262144); if row.get("error").is_some() { assert!(got.is_err(), "{row}"); continue; @@ -94,21 +74,14 @@ fn ram_rules_match() { let g = golden(); for row in g["ram_ctx"].as_array().unwrap() { assert_eq!( - policy::ram_ctx( - model(&row["model"]), - row["ram"].as_f64().unwrap(), - row["low_ram"].as_bool().unwrap() - ), + policy::ram_ctx(model(&row["model"]), row["ram"].as_f64().unwrap(), row["low_ram"].as_bool().unwrap()), row["result"].as_u64().unwrap(), "{row}" ); } for row in g["ctx_ram_need"].as_array().unwrap() { - let got = policy::ctx_ram_need( - model(&row["model"]), - row["ctx"].as_u64().unwrap(), - row["low_ram"].as_bool().unwrap(), - ); + let got = + policy::ctx_ram_need(model(&row["model"]), row["ctx"].as_u64().unwrap(), row["low_ram"].as_bool().unwrap()); match (got, &row["result"]) { (None, Value::Null) => {} (Some(got), want) => same(got, want, &row.to_string()), @@ -139,27 +112,13 @@ fn low_ram_rules_match() { let kv = || Kv::parse(row["kv"].as_str().unwrap()); let ctx = || row["ctx"].as_u64().unwrap(); match row["fn"].as_str().unwrap() { - "needed" => assert_eq!( - policy::low_ram_needed(m, f("ram")), - row["result"].as_bool().unwrap(), - "{row}" - ), - "fits" => assert_eq!( - policy::low_ram_fits(m, f("ram"), f("vram")), - row["result"].as_bool().unwrap(), - "{row}" - ), + "needed" => assert_eq!(policy::low_ram_needed(m, f("ram")), row["result"].as_bool().unwrap(), "{row}"), + "fits" => { + assert_eq!(policy::low_ram_fits(m, f("ram"), f("vram")), row["result"].as_bool().unwrap(), "{row}") + } "gpu_gb" => { - same( - policy::low_ram_gpu_gb(m, f("vram"), ctx(), kv()), - &row["result"], - &row.to_string(), - ); - same( - policy::low_ram_gpu_share(m, f("vram"), ctx(), kv()), - &row["share"], - &row.to_string(), - ); + same(policy::low_ram_gpu_gb(m, f("vram"), ctx(), kv()), &row["result"], &row.to_string()); + same(policy::low_ram_gpu_share(m, f("vram"), ctx(), kv()), &row["share"], &row.to_string()); } "resident" => assert_eq!( policy::low_ram_resident(m, f("ram"), f("vram"), ctx(), kv()), diff --git a/crates/cuda-driver/rustfmt.toml b/crates/cuda-driver/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/cuda-driver/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/cuda-driver/src/api.rs b/crates/cuda-driver/src/api.rs index 466cc243..05ea1922 100644 --- a/crates/cuda-driver/src/api.rs +++ b/crates/cuda-driver/src/api.rs @@ -16,17 +16,9 @@ pub(crate) struct MappedCopyArguments { pub(crate) words: i64, } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::AsyncApi; #[cfg(not(all( @@ -36,11 +28,7 @@ pub(crate) use enabled::AsyncApi; )))] pub(crate) struct AsyncApi; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::{MappedApi, page_size}; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/api/enabled.rs b/crates/cuda-driver/src/api/enabled.rs index e2e45a48..0edbeba4 100644 --- a/crates/cuda-driver/src/api/enabled.rs +++ b/crates/cuda-driver/src/api/enabled.rs @@ -35,20 +35,14 @@ pub(crate) struct AsyncApi { zero: Zero, } fn check(operation: &'static str, code: c_int) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { operation, code }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation, code }) } } macro_rules! symbol { ($library:ident, $name:literal, $ty:ty) => {{ // SAFETY: fixed C name and live dlopen owner, never caller-selected. let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) }; if address.is_null() { - return Err(Error::MissingSymbol( - $name.to_str().expect("ASCII ABI name"), - )); + return Err(Error::MissingSymbol($name.to_str().expect("ASCII ABI name"))); } // SAFETY: exact Linux64 fixed function signature for this symbol. unsafe { std::mem::transmute::<*mut c_void, $ty>(address) } @@ -58,9 +52,7 @@ impl AsyncApi { pub(crate) fn load() -> Result { // SAFETY: fixed library name/flags; a second owned reference leaves // the original synchronous loader and its symbol set untouched. - let handle = unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }; + let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if handle.is_null() { return Err(Error::LibraryUnavailable); } @@ -84,9 +76,7 @@ impl AsyncApi { pub(crate) fn create_stream(&self) -> Result { let mut handle = std::ptr::null_mut(); // SAFETY: valid out pointer, NON_BLOCKING=1, current owning Context. - check("cuStreamCreate", unsafe { - (self.stream_create)(&mut handle, 1) - })?; + check("cuStreamCreate", unsafe { (self.stream_create)(&mut handle, 1) })?; if handle.is_null() { return Err(Error::InvalidDriverValue("cuStreamCreate")); } @@ -96,9 +86,7 @@ impl AsyncApi { pub(crate) fn create_event(&self) -> Result { let mut handle = std::ptr::null_mut(); // SAFETY: valid out pointer, DISABLE_TIMING=2, current Context. - check("cuEventCreate", unsafe { - (self.event_create)(&mut handle, 2) - })?; + check("cuEventCreate", unsafe { (self.event_create)(&mut handle, 2) })?; if handle.is_null() { return Err(Error::InvalidDriverValue("cuEventCreate")); } @@ -107,82 +95,57 @@ impl AsyncApi { pub(crate) fn register(&self, bytes: &mut [u8]) -> Result<()> { // SAFETY: nonempty whole uniquely owned initialized allocation, // no resize/mutation/free until unregister after completion. - check("cuMemHostRegister_v2", unsafe { - (self.register)(bytes.as_mut_ptr().cast(), bytes.len(), 0) - }) + check("cuMemHostRegister_v2", unsafe { (self.register)(bytes.as_mut_ptr().cast(), bytes.len(), 0) }) } pub(crate) fn unregister(&self, bytes: &mut [u8]) -> Result<()> { // SAFETY: identical registered base retained by private owner. - check("cuMemHostUnregister", unsafe { - (self.unregister)(bytes.as_mut_ptr().cast()) - }) + check("cuMemHostUnregister", unsafe { (self.unregister)(bytes.as_mut_ptr().cast()) }) } pub(crate) fn copy(&self, destination: u64, bytes: &[u8], stream: Stream) -> Result<()> { // SAFETY: whole actual admitted allocation, registered source and // stream retained until genuine recorded event completion. check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy)( - destination, - bytes.as_ptr().cast(), - bytes.len(), - stream.0 as *mut c_void, - ) + (self.copy)(destination, bytes.as_ptr().cast(), bytes.len(), stream.0 as *mut c_void) }) } pub(crate) fn synchronize_stream(&self, stream: Stream) -> Result<()> { // SAFETY: the cache owns every source/destination until this fence; // Stream(0) is CUDA's actual legacy default stream, not a fake owner. - check("cuStreamSynchronize", unsafe { - (self.stream_wait)(stream.0 as *mut c_void) - }) + check("cuStreamSynchronize", unsafe { (self.stream_wait)(stream.0 as *mut c_void) }) } pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> { // SAFETY: the caller validates the genuine whole cache allocation. - check("cuMemsetD8_v2", unsafe { - (self.zero)(destination, 0, bytes) - }) + check("cuMemsetD8_v2", unsafe { (self.zero)(destination, 0, bytes) }) } pub(crate) fn record(&self, event: Event, stream: Stream) -> Result<()> { // SAFETY: live owned handles in their actual current Context. - check("cuEventRecord", unsafe { - (self.event_record)(event.0 as *mut c_void, stream.0 as *mut c_void) - }) + check("cuEventRecord", unsafe { (self.event_record)(event.0 as *mut c_void, stream.0 as *mut c_void) }) } pub(crate) fn query(&self, event: Event) -> Result { // SAFETY: event was genuinely recorded after the complete batch. match unsafe { (self.event_query)(event.0 as *mut c_void) } { 0 => Ok(true), 600 => Ok(false), // CUDA_ERROR_NOT_READY, never publication. - code => Err(Error::Driver { - operation: "cuEventQuery", - code, - }), + code => Err(Error::Driver { operation: "cuEventQuery", code }), } } pub(crate) fn wait(&self, event: Event) -> Result<()> { // SAFETY: event and registered sources remain live for this wait. - check("cuEventSynchronize", unsafe { - (self.event_wait)(event.0 as *mut c_void) - }) + check("cuEventSynchronize", unsafe { (self.event_wait)(event.0 as *mut c_void) }) } pub(crate) fn destroy_event(&self, event: Event) -> Result<()> { // SAFETY: only called before enqueue or after proven completion. - check("cuEventDestroy_v2", unsafe { - (self.event_destroy)(event.0 as *mut c_void) - }) + check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event.0 as *mut c_void) }) } pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> { crate::compute_drain::unregister(stream.0); // SAFETY: only called before enqueue or after proven completion. - check("cuStreamDestroy_v2", unsafe { - (self.stream_destroy)(stream.0 as *mut c_void) - }) + check("cuStreamDestroy_v2", unsafe { (self.stream_destroy)(stream.0 as *mut c_void) }) } } type Alias = unsafe extern "C" fn(*mut u64, *mut c_void, c_uint) -> c_int; type LoadModule = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; -type GetFunction = - unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; +type GetFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; type Launch = unsafe extern "C" fn( *mut c_void, c_uint, @@ -208,9 +171,7 @@ impl MappedApi { pub(crate) fn load() -> Result { let image = include_bytes!("../../kernels/mapped_expert_copy.ptx"); if image.starts_with(b"UNSEALED") || image.last() != Some(&0) { - return Err(Error::InvalidDriverValue( - "mapped expert copy asset unsealed", - )); + return Err(Error::InvalidDriverValue("mapped expert copy asset unsealed")); } let inner = AsyncApi::load()?; let library = &inner._library; @@ -221,33 +182,20 @@ impl MappedApi { let launch = symbol!(library, c"cuLaunchKernel", Launch); let mut module = std::ptr::null_mut(); // SAFETY: fixed sealed terminated image; current actual Context. - check("cuModuleLoadData", unsafe { - load(&mut module, crate::arch_ptx::image(image).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut module, crate::arch_ptx::image(image).as_ptr().cast()) })?; if module.is_null() { return Err(Error::InvalidDriverValue("mapped module")); } let mut function = std::ptr::null_mut(); // SAFETY: real owned module and fixed original byte-only symbol. - let result = check("cuModuleGetFunction", unsafe { - get(&mut function, module, c"fetch_blobs_kernel".as_ptr()) - }); + let result = + check("cuModuleGetFunction", unsafe { get(&mut function, module, c"fetch_blobs_kernel".as_ptr()) }); if result.is_err() || function.is_null() { // SAFETY: no launch occurred; release actual partial module. let cleanup = check("cuModuleUnload", unsafe { unload(module) }); - return crate::combine( - result.and_then(|()| Err(Error::InvalidDriverValue("mapped function"))), - cleanup, - ); + return crate::combine(result.and_then(|()| Err(Error::InvalidDriverValue("mapped function"))), cleanup); } - Ok(Self { - inner, - alias, - module, - function, - unload, - launch, - }) + Ok(Self { inner, alias, module, function, unload, launch }) } pub(crate) fn register_bank(&self, bytes: &[u8]) -> Result<()> { // SAFETY: immutable retained actual initialized Box; DEVICEMAP=2. @@ -261,28 +209,21 @@ impl MappedApi { check("cuMemHostGetDevicePointer_v2", unsafe { (self.alias)(&mut address, bytes.as_ptr().cast_mut().cast(), 0) })?; - if address == 0 - || !address.is_multiple_of(16) - || address.checked_add(bytes.len() as u64).is_none() - { + if address == 0 || !address.is_multiple_of(16) || address.checked_add(bytes.len() as u64).is_none() { return Err(Error::InvalidDriverValue("mapped alias")); } Ok(address) } pub(crate) fn unregister_bank(&self, bytes: &[u8]) -> Result<()> { // SAFETY: identical live registered base; all consumers drained. - check("cuMemHostUnregister", unsafe { - (self.inner.unregister)(bytes.as_ptr().cast_mut().cast()) - }) + check("cuMemHostUnregister", unsafe { (self.inner.unregister)(bytes.as_ptr().cast_mut().cast()) }) } /// Page-lock `len` bytes at page-aligned `start`, inside a read-only file mapping a bank retains /// (CU_MEMHOSTREGISTER_READ_ONLY = 8; no device mapping): the pages are read in and stay resident, and /// copies from them are DMA instead of staged. pub(crate) fn register_read_only(&self, start: usize, len: usize) -> Result<()> { // SAFETY: the caller passes a page range inside a live mapping it retains until `unregister_at`. - check("cuMemHostRegister_v2", unsafe { - (self.inner.register)(start as *mut c_void, len, 8) - }) + check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 8) }) } pub(crate) fn unregister_at(&self, start: usize) -> Result<()> { // SAFETY: identical live registered base from `register_read_only`; all consumers drained. @@ -294,11 +235,7 @@ impl MappedApi { // SAFETY: the caller passes a live page-aligned allocation it retains until `unregister_at`. check("cuMemHostRegister_v2", unsafe { (self.inner.register)(start as *mut c_void, len, 0) }) } - pub(crate) fn copy_kernel( - &self, - actual: &mut MappedCopyArguments, - stream: Stream, - ) -> Result<()> { + pub(crate) fn copy_kernel(&self, actual: &mut MappedCopyArguments, stream: Stream) -> Result<()> { let mut args = [ (&mut actual.source as *mut u64).cast(), (&mut actual.count as *mut u64).cast(), diff --git a/crates/cuda-driver/src/arch_ptx.rs b/crates/cuda-driver/src/arch_ptx.rs index 90b65677..722924b5 100644 --- a/crates/cuda-driver/src/arch_ptx.rs +++ b/crates/cuda-driver/src/arch_ptx.rs @@ -24,8 +24,7 @@ mod imp { pub(super) fn current_cc() -> Option<(i32, i32)> { // SAFETY: fixed library name; RTLD_NOLOAD only returns a handle if the caller's own Api already loaded it, and // the extra reference is dropped below. - let handle = - unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) }; + let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_NOLOAD) }; if handle.is_null() { return None; } @@ -37,10 +36,7 @@ mod imp { let (mut major, mut minor) = (0, 0); // SAFETY: valid writable outputs; a current context is the caller's precondition for a module load. unsafe { - if get(&mut device) != 0 - || attr(&mut major, 75, device) != 0 - || attr(&mut minor, 76, device) != 0 - { + if get(&mut device) != 0 || attr(&mut major, 75, device) != 0 || attr(&mut minor, 76, device) != 0 { return None; } } @@ -68,10 +64,7 @@ mod imp { } } -#[cfg(all( - feature = "sm86", - not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")) -))] +#[cfg(all(feature = "sm86", not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))))] mod imp { pub(super) fn current_cc() -> Option<(i32, i32)> { None @@ -96,10 +89,7 @@ mod tests { let path = entry.unwrap().path(); if path.extension().and_then(|e| e.to_str()) == Some("ptx") { let bytes = std::fs::read(&path).unwrap(); - out.push(( - path.file_name().unwrap().to_string_lossy().into_owned(), - bytes, - )); + out.push((path.file_name().unwrap().to_string_lossy().into_owned(), bytes)); } } } @@ -121,10 +111,7 @@ mod tests { let tail = &text[at + ".entry ".len()..]; let open = tail.find('(').unwrap(); let close = tail.find(')').unwrap(); - out.insert( - tail[..open].to_string(), - tail[open..close].matches(".param").count(), - ); + out.insert(tail[..open].to_string(), tail[open..close].matches(".param").count()); } out } @@ -132,12 +119,7 @@ mod tests { #[test] fn table_is_sorted_unique_and_every_companion_passes_its_pin() { for pair in COMPANIONS.windows(2) { - assert!( - pair[0].key < pair[1].key, - "{} / {}", - pair[0].name, - pair[1].name - ); + assert!(pair[0].key < pair[1].key, "{} / {}", pair[0].name, pair[1].name); } for c in COMPANIONS { let pinned = crate::sealed_ptx::pinned(c.ptx, Some((c.len, c.sha))); @@ -153,23 +135,14 @@ mod tests { .collect(); for c in COMPANIONS { let originals: Vec<_> = sealed.iter().filter(|(_, key, _)| *key == c.key).collect(); - assert!( - !originals.is_empty(), - "{}: no sealed sm_120 file has the table key", - c.name - ); + assert!(!originals.is_empty(), "{}: no sealed sm_120 file has the table key", c.name); let text = std::str::from_utf8(body(c.ptx)).unwrap(); let targets: Vec<_> = text.lines().filter(|l| l.starts_with(".target")).collect(); assert_eq!(targets, [".target sm_86"], "{}", c.name); assert!(text.lines().any(|l| l == ".address_size 64"), "{}", c.name); assert!(!text.contains("UNSEALED"), "{}", c.name); for (name, _, original) in originals { - assert_eq!( - entries(body(original)), - entries(body(c.ptx)), - "{} vs {name}", - c.name - ); + assert_eq!(entries(body(original)), entries(body(c.ptx)), "{} vs {name}", c.name); } } } @@ -177,14 +150,9 @@ mod tests { #[test] fn every_sealed_sm120_file_has_a_companion_or_a_documented_reason() { let manifest: serde_json::Value = - serde_json::from_slice(&std::fs::read(src().join("ptx-sm86/MANIFEST.json")).unwrap()) - .unwrap(); - let not_built: Vec<&str> = manifest["not_built"] - .as_array() - .unwrap() - .iter() - .map(|v| v["name"].as_str().unwrap()) - .collect(); + serde_json::from_slice(&std::fs::read(src().join("ptx-sm86/MANIFEST.json")).unwrap()).unwrap(); + let not_built: Vec<&str> = + manifest["not_built"].as_array().unwrap().iter().map(|v| v["name"].as_str().unwrap()).collect(); let portable: Vec<&str> = manifest["portable_no_companion_needed"] .as_array() .unwrap() @@ -211,19 +179,13 @@ mod tests { ); } // the placeholders have no companion by design: they cannot be loaded on any device until sealed - assert!( - placeholders - .iter() - .all(|p| !COMPANIONS.iter().any(|c| c.name == *p)) - ); + assert!(placeholders.iter().all(|p| !COMPANIONS.iter().any(|c| c.name == *p))); } #[test] fn lookup_swaps_only_sealed_images_and_only_to_a_pinned_companion() { - let (name, bytes) = sealed_files() - .into_iter() - .find(|(n, _)| n == "device_poison.ptx") - .expect("device_poison.ptx"); + let (name, bytes) = + sealed_files().into_iter().find(|(n, _)| n == "device_poison.ptx").expect("device_poison.ptx"); let mut stored = body(&bytes).to_vec(); stored.push(0); let swapped = companion_for(&stored).unwrap_or_else(|| panic!("{name}: no companion")); @@ -243,53 +205,39 @@ mod tests { #[test] fn capability_gates() { - assert!( - cc_major_ok(12) - && cc_major_ok(8) - && cc_major_ok(9) - && !cc_major_ok(7) - && !cc_major_ok(13) - ); - assert!( - mmq_cc_ok(12, 0) - && mmq_cc_ok(8, 6) - && mmq_cc_ok(8, 9) - && !mmq_cc_ok(8, 0) - && !mmq_cc_ok(12, 1) - ); - assert!( - companion_cc(8, 6) && companion_cc(9, 0) && !companion_cc(8, 0) && !companion_cc(12, 0) - ); + assert!(cc_major_ok(12) && cc_major_ok(8) && cc_major_ok(9) && !cc_major_ok(7) && !cc_major_ok(13)); + assert!(mmq_cc_ok(12, 0) && mmq_cc_ok(8, 6) && mmq_cc_ok(8, 9) && !mmq_cc_ok(8, 0) && !mmq_cc_ok(12, 1)); + assert!(companion_cc(8, 6) && companion_cc(9, 0) && !companion_cc(8, 0) && !companion_cc(12, 0)); } } mod stream_k_off_fn; #[allow(unused_imports)] -pub(crate) use stream_k_off_fn::stream_k_off; -#[allow(unused_imports)] -pub(crate) use stream_k_off_fn::forced_sms; -#[allow(unused_imports)] -pub(crate) use stream_k_off_fn::chunk_drain; -#[allow(unused_imports)] -pub(crate) use stream_k_off_fn::latch_stream_k_policy; -#[allow(unused_imports)] pub(crate) use stream_k_off_fn::cc_major_ok; #[allow(unused_imports)] -pub(crate) use stream_k_off_fn::mmq_cc_ok; +pub(crate) use stream_k_off_fn::chunk_drain; #[allow(unused_imports)] pub(crate) use stream_k_off_fn::companion_cc; #[cfg(feature = "sm86")] #[allow(unused_imports)] -pub(crate) use stream_k_off_fn::loadable; -#[cfg(feature = "sm86")] +pub(crate) use stream_k_off_fn::companion_for; #[allow(unused_imports)] -pub(crate) use stream_k_off_fn::native_sm120; +pub(crate) use stream_k_off_fn::forced_sms; #[cfg(not(feature = "sm86"))] #[allow(unused_imports)] pub(crate) use stream_k_off_fn::image; #[cfg(feature = "sm86")] #[allow(unused_imports)] pub(crate) use stream_k_off_fn::image; +#[allow(unused_imports)] +pub(crate) use stream_k_off_fn::latch_stream_k_policy; #[cfg(feature = "sm86")] #[allow(unused_imports)] -pub(crate) use stream_k_off_fn::companion_for; +pub(crate) use stream_k_off_fn::loadable; +#[allow(unused_imports)] +pub(crate) use stream_k_off_fn::mmq_cc_ok; +#[cfg(feature = "sm86")] +#[allow(unused_imports)] +pub(crate) use stream_k_off_fn::native_sm120; +#[allow(unused_imports)] +pub(crate) use stream_k_off_fn::stream_k_off; diff --git a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs index f8a5d6b1..bdfbe3a4 100644 --- a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs +++ b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs @@ -18,7 +18,8 @@ pub(crate) fn stream_k_off() -> bool { static PRESENT: [AtomicBool; 2] = [const { AtomicBool::new(false) }; 2]; let fixed = *FIXED.get_or_init(|| std::env::var_os("LELEKA_MMQ_NO_STREAMK").is_some_and(|v| v != "0")); let paths = PATHS.get_or_init(|| { - ["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"].map(|name| std::env::var_os(name).map(std::path::PathBuf::from)) + ["LELEKA_MMQ_NO_STREAMK_FILE", "LELEKA_MMQ_STREAMK_FILE"] + .map(|name| std::env::var_os(name).map(std::path::PathBuf::from)) }); if paths.iter().any(Option::is_some) { let now = CHECKED.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; @@ -43,7 +44,11 @@ pub(crate) fn stream_k_off() -> bool { /// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K grids (and size /// their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the laptop's decomposition there. pub(crate) fn forced_sms(real: u32) -> u32 { - std::env::var("LELEKA_FORCE_SMS").ok().and_then(|v| v.parse::().ok()).filter(|n| (1..=4096).contains(n)).unwrap_or(real) + std::env::var("LELEKA_FORCE_SMS") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|n| (1..=4096).contains(n)) + .unwrap_or(real) } /// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_CHUNK_DRAIN=1`, or the existence of the file named by `LELEKA_CHUNK_DRAIN_FILE` @@ -59,7 +64,9 @@ pub(crate) fn chunk_drain() -> bool { if *FIXED.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN").is_some_and(|v| v != "0")) { return true; } - let Some(path) = PATH.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN_FILE").map(std::path::PathBuf::from)).as_ref() else { + let Some(path) = + PATH.get_or_init(|| std::env::var_os("LELEKA_CHUNK_DRAIN_FILE").map(std::path::PathBuf::from)).as_ref() + else { return false; }; let now = START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64; @@ -152,11 +159,7 @@ pub(crate) fn companion_for(ptx: &[u8]) -> Option<&'static [u8]> { let c = &table[at]; let pinned = crate::sealed_ptx::pinned(c.ptx, Some((c.len, c.sha))); if pinned.is_some() && std::env::var_os("LELEKA_SM86_TRACE").is_some() { - eprintln!( - "sm86: companion {} ({} bytes) replaces the sealed sm_120 image", - c.name, - c.len - 1 - ); + eprintln!("sm86: companion {} ({} bytes) replaces the sealed sm_120 image", c.name, c.len - 1); } pinned } diff --git a/crates/cuda-driver/src/asset_validation_cache_tests.rs b/crates/cuda-driver/src/asset_validation_cache_tests.rs index 325912a3..287b4e0f 100644 --- a/crates/cuda-driver/src/asset_validation_cache_tests.rs +++ b/crates/cuda-driver/src/asset_validation_cache_tests.rs @@ -2,12 +2,7 @@ use super::*; use std::cell::Cell; -fn checked( - asset: &Asset, - operation: Operation, - memo: &OnceLock, - calls: &Cell, -) -> Result<()> { +fn checked(asset: &Asset, operation: Operation, memo: &OnceLock, calls: &Cell) -> Result<()> { asset.validate_with_memo(operation, memo, |ptx| { calls.set(calls.get() + 1); inspect_ptx(ptx) // The real ASCII/NUL/length/SHA validator, not a stub. @@ -34,12 +29,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { let other: &'static [u8] = Box::leak(base.ptx.to_vec().into_boxed_slice()); assert!(!std::ptr::eq(other, base.ptx)); assert_eq!(other, base.ptx); - let distinct = Asset { - operation, - ptx: other, - receipt: base.receipt, - pin: base.pin, - }; + let distinct = Asset { operation, ptx: other, receipt: base.receipt, pin: base.pin }; assert_eq!(checked(&distinct, operation, &memo, &calls), Ok(())); assert_eq!(calls.get(), 2); // A one-slot memo still holds the original allocation. The distinct one @@ -97,16 +87,8 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { } _ => unreachable!(), } - assert_eq!( - checked(&asset, request, &memo, &calls), - Err(Error::UnsupportedQwenOperation), - "warm case {case}" - ); - assert_eq!( - calls.get(), - 3, - "metadata and memo hash refusal must not rescan" - ); + assert_eq!(checked(&asset, request, &memo, &calls), Err(Error::UnsupportedQwenOperation), "warm case {case}"); + assert_eq!(calls.get(), 3, "metadata and memo hash refusal must not rescan"); assert!(std::ptr::eq(memo.get().unwrap().ptx, base.ptx)); assert_eq!(memo.get().unwrap().digest, base.receipt.ptx_sha256); } @@ -118,10 +100,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { asset.pin = asset.receipt; let fresh = OnceLock::new(); let count = Cell::new(0); - assert_eq!( - checked(&asset, operation, &fresh, &count), - Err(Error::UnsupportedQwenOperation) - ); + assert_eq!(checked(&asset, operation, &fresh, &count), Err(Error::UnsupportedQwenOperation)); assert_eq!(count.get(), 1); assert!(fresh.get().is_none()); } @@ -130,10 +109,7 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { wrong_hash.pin = wrong_hash.receipt; let fresh = OnceLock::new(); let count = Cell::new(0); - assert_eq!( - checked(&wrong_hash, operation, &fresh, &count), - Err(Error::UnsupportedQwenOperation) - ); + assert_eq!(checked(&wrong_hash, operation, &fresh, &count), Err(Error::UnsupportedQwenOperation)); assert_eq!(count.get(), 1); assert!(fresh.get().is_none()); // Failure did not reserve/poison the content proof: the first valid asset diff --git a/crates/cuda-driver/src/async_owned_copy.rs b/crates/cuda-driver/src/async_owned_copy.rs index 7947adbe..927cd55f 100644 --- a/crates/cuda-driver/src/async_owned_copy.rs +++ b/crates/cuda-driver/src/async_owned_copy.rs @@ -87,10 +87,7 @@ impl Context<'_> { return Err(Error::ContextMismatch); } if destination.bytes != source.len() { - return Err(Error::ShapeMismatch { - expected: destination.bytes, - actual: source.len(), - }); + return Err(Error::ShapeMismatch { expected: destination.bytes, actual: source.len() }); } let handle = destination.handle.ok_or(Error::ContextPoisoned)?; handle.validate_extent(destination.bytes)?; @@ -171,14 +168,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> { for i in 0..self.count { let (destination, source) = self.pairs[i].as_ref().expect("admitted whole pair"); self.attempted = true; - api.copy( - destination - .handle - .expect("admitted live allocation") - .qwen_address(), - source, - stream, - )?; + api.copy(destination.handle.expect("admitted live allocation").qwen_address(), source, stream)?; } api.record(self.event.expect("actual created event"), stream)?; self.recorded = true; @@ -209,11 +199,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> { }; let api = self.api.as_ref().expect("private live ABI"); let event = self.event.expect("actual recorded event"); - let observed = if wait { - api.wait(event).map(|()| true) - } else { - api.query(event) - }; + let observed = if wait { api.wait(event).map(|()| true) } else { api.query(event) }; let observed = combine(observed, guard.finish()); match observed { Ok(true) => { @@ -247,10 +233,7 @@ impl<'ctx> PendingOwnedCopy<'ctx> { } self.cleanup_transport()?; let pairs = std::mem::replace(&mut self.pairs, std::array::from_fn(|_| None)); - Ok(CompletedOwnedCopy { - pairs, - count: self.count, - }) + Ok(CompletedOwnedCopy { pairs, count: self.count }) } /// Cancellation/draining discards the unpublished destinations only after /// genuine completion; first failure is preserved with all cleanup attempts. diff --git a/crates/cuda-driver/src/async_owned_copy_gpu.rs b/crates/cuda-driver/src/async_owned_copy_gpu.rs index df026a3a..02190cf2 100644 --- a/crates/cuda-driver/src/async_owned_copy_gpu.rs +++ b/crates/cuda-driver/src/async_owned_copy_gpu.rs @@ -3,45 +3,20 @@ use super::*; #[test] fn bounded_host_capacity_admission_has_no_completion_shortcut() { - assert!(matches!( - admit_count_and_capacities(&[], 100), - Err(Error::InvalidSize) - )); - assert!(matches!( - admit_count_and_capacities(&[(1, 1); 7], 100), - Err(Error::InvalidSize) - )); - assert!(matches!( - admit_count_and_capacities(&[(1, 0)], 100), - Err(Error::InvalidSize) - )); - assert!(matches!( - admit_count_and_capacities(&[(0, 0)], 100), - Err(Error::InvalidSize) - )); - assert!(matches!( - admit_count_and_capacities(&[(1, usize::MAX), (1, 1)], usize::MAX), - Err(Error::BudgetExceeded) - )); - assert!(matches!( - admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 47), - Err(Error::BudgetExceeded) - )); + assert!(matches!(admit_count_and_capacities(&[], 100), Err(Error::InvalidSize))); + assert!(matches!(admit_count_and_capacities(&[(1, 1); 7], 100), Err(Error::InvalidSize))); + assert!(matches!(admit_count_and_capacities(&[(1, 0)], 100), Err(Error::InvalidSize))); + assert!(matches!(admit_count_and_capacities(&[(0, 0)], 100), Err(Error::InvalidSize))); + assert!(matches!(admit_count_and_capacities(&[(1, usize::MAX), (1, 1)], usize::MAX), Err(Error::BudgetExceeded))); + assert!(matches!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 47), Err(Error::BudgetExceeded))); assert!(admit_count_and_capacities(&[(10, 16), (10, 16), (10, 16)], 48).is_ok()); } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] #[ignore = "Root-only genuine registered triplet event transport proof"] fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), Ok("yes")); let driver = crate::Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(16 * 1024 * 1024).unwrap(); @@ -53,26 +28,18 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { let sizes = [262_144usize, 524_288, 786_432]; for round in 0..3u32 { let mut pairs = Vec::new(); - pairs - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + pairs.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; let mut expected = Vec::new(); - expected - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + expected.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; let mut pointers = [0usize; 3]; for (role, bytes) in sizes.into_iter().enumerate() { let mut source = Vec::new(); - source - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + source.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; for i in 0..bytes / 4 { let word = if round == 2 { [0, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0042][i % 6] } else { - (i as u32) - .wrapping_mul(0x9e37_79b9) - .wrapping_add(round + role as u32) + (i as u32).wrapping_mul(0x9e37_79b9).wrapping_add(round + role as u32) }; source.extend_from_slice(&word.to_le_bytes()); } @@ -107,20 +74,14 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { if let Some((destination, source)) = pair { let observed = destination.copy_to_owned(sizes[i]); if source.as_ptr() as usize != pointers[i] { - completion_error = combine( - completion_error, - Err(Error::InvalidDriverValue("staging ownership")), - ); + completion_error = + combine(completion_error, Err(Error::InvalidDriverValue("staging ownership"))); } match observed { - Ok(bytes) if bytes == expected[i] && source == expected[i] => { - compared += bytes.len() - } + Ok(bytes) if bytes == expected[i] && source == expected[i] => compared += bytes.len(), Ok(_) => { - completion_error = combine( - completion_error, - Err(Error::InvalidDriverValue("async byte equality")), - ) + completion_error = + combine(completion_error, Err(Error::InvalidDriverValue("async byte equality"))) } Err(error) => completion_error = combine(completion_error, Err(error)), } @@ -130,30 +91,20 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { completion_error?; } // Genuine foreign allocation and exact whole-byte shape admission. - let invalid = - context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]); + let invalid = context.copy_owned_batch_async(vec![(foreign.allocate(4096)?, vec![0; 4096])]); if !matches!(invalid, Err(Error::ContextMismatch)) { return Err(Error::InvalidDriverValue("foreign refusal")); } drop(invalid); refusals += 1; - let invalid = - context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]); - if !matches!( - invalid, - Err(Error::ShapeMismatch { - expected: 4096, - actual: 4095 - }) - ) { + let invalid = context.copy_owned_batch_async(vec![(context.allocate(4096)?, vec![0; 4095])]); + if !matches!(invalid, Err(Error::ShapeMismatch { expected: 4096, actual: 4095 })) { return Err(Error::InvalidDriverValue("extent refusal")); } drop(invalid); refusals += 1; // Real abandoned pending owner explicitly drains without publication. - context - .copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])? - .close()?; + context.copy_owned_batch_async(vec![(context.allocate(262_144)?, vec![7; 262_144])])?.close()?; Ok(()) })(); let sync = context.synchronize(); @@ -172,18 +123,11 @@ fn original_three_copies_first_owned_event_triplet_bytes_guards_and_cleanup() { ); } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] #[ignore = "Root-only: poison while a registered copy is pending must retain, not free"] fn poison_while_pending_retains_registered_owners_and_preserves_the_primary_error() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_OWNED_ASYNC_COPY").as_deref(), Ok("yes")); let driver = crate::Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(16 * 1024 * 1024).unwrap(); diff --git a/crates/cuda-driver/src/batch_gr_preview.rs b/crates/cuda-driver/src/batch_gr_preview.rs index c9d19905..8463d010 100644 --- a/crates/cuda-driver/src/batch_gr_preview.rs +++ b/crates/cuda-driver/src/batch_gr_preview.rs @@ -5,10 +5,7 @@ fn batch_layout(operation: Operation, tokens: usize) -> Result if !(1..=64).contains(&tokens) || !matches!( operation, - Operation::Norm - | Operation::LayerGate - | Operation::FinalGate - | Operation::InjectResidual + Operation::Norm | Operation::LayerGate | Operation::FinalGate | Operation::InjectResidual ) { return Err(Error::InvalidQwenShape); @@ -18,15 +15,10 @@ fn batch_layout(operation: Operation, tokens: usize) -> Result if operation == Operation::Norm && i == 1 { continue; } - layout.bytes[i] = layout.bytes[i] - .checked_mul(tokens) - .ok_or(Error::InvalidQwenShape)?; + layout.bytes[i] = layout.bytes[i].checked_mul(tokens).ok_or(Error::InvalidQwenShape)?; } if operation != Operation::Norm { - layout.columns = layout - .columns - .checked_mul(tokens as u32) - .ok_or(Error::InvalidQwenShape)?; + layout.columns = layout.columns.checked_mul(tokens as u32).ok_or(Error::InvalidQwenShape)?; } layout.grid_y = tokens as u32; Ok(layout) @@ -61,18 +53,9 @@ mod installed { }; let result = (|| { Ok([ - context - .driver - .api - .qwen_function(module, Operation::LayerGate)?, - context - .driver - .api - .qwen_function(module, Operation::FinalGate)?, - context - .driver - .api - .qwen_function(module, Operation::InjectResidual)?, + context.driver.api.qwen_function(module, Operation::LayerGate)?, + context.driver.api.qwen_function(module, Operation::FinalGate)?, + context.driver.api.qwen_function(module, Operation::InjectResidual)?, context.driver.api.qwen_function(module, Operation::Norm)?, ]) })(); @@ -92,12 +75,7 @@ mod installed { context.retain_driver(); return Err(e); } - Ok(Self { - context, - module: Some(module), - functions, - launch_attempts: std::cell::Cell::new(0), - }) + Ok(Self { context, module: Some(module), functions, launch_attempts: std::cell::Cell::new(0) }) } pub fn inject( &self, @@ -107,18 +85,9 @@ mod installed { inject: &DeviceBuffer<'_>, candidate: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.run( - Operation::InjectResidual, - tokens, - &[residual, output, inject, candidate], - ) + self.run(Operation::InjectResidual, tokens, &[residual, output, inject, candidate]) } - pub(super) fn run( - &self, - operation: Operation, - tokens: usize, - buffers: &[&DeviceBuffer<'_>], - ) -> Result<()> { + pub(super) fn run(&self, operation: Operation, tokens: usize, buffers: &[&DeviceBuffer<'_>]) -> Result<()> { self.run_with_epsilon(operation, tokens, buffers, 0.) } pub(super) fn run_with_epsilon( @@ -156,10 +125,7 @@ mod installed { let kernel = self.functions[slot(operation)?]; let mut arguments = Arguments::with_layout(operation, layout, handles, epsilon); let guard = context.enter()?; - let launch = context - .driver - .api - .launch_qwen(kernel, operation, &mut arguments); + let launch = context.driver.api.launch_qwen(kernel, operation, &mut arguments); self.launch_attempts.set(self.launch_attempts.get() + 1); let sync = context.driver.api.synchronize(); if sync.is_err() { @@ -218,15 +184,15 @@ impl Context<'_> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] { let dispatcher = installed::GrBatchPreview::new(self)?; - let result = dispatcher.run( - Operation::InjectResidual, - tokens, - &[residual, output, inject, candidate], - ); + let result = dispatcher.run(Operation::InjectResidual, tokens, &[residual, output, inject, candidate]); let cleanup = dispatcher.close(); combine(result, cleanup) } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + )))] { let _ = (tokens, residual, output, inject, candidate); Err(Error::UnsupportedPlatform) @@ -247,15 +213,14 @@ impl Context<'_> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] { let dispatcher = installed::GrBatchPreview::new(self)?; - let result = dispatcher.run_with_epsilon( - Operation::Norm, - tokens, - &[residual, gamma, output], - epsilon, - ); + let result = dispatcher.run_with_epsilon(Operation::Norm, tokens, &[residual, gamma, output], epsilon); combine(result, dispatcher.close()) } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + )))] { let _ = (tokens, residual, gamma, epsilon, output); Err(Error::UnsupportedPlatform) diff --git a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs index dca8f5f6..cbbc5be2 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - /// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr. /// Off by default so production serving prints nothing extra. pub(crate) fn bringup_trace_enabled() -> bool { @@ -33,9 +31,7 @@ impl Error { Self::LibraryUnavailable => "cannot load libcuda.so.1", Self::InvalidOrdinal => "device ordinal must be nonnegative", Self::HostAllocation => "cannot allocate owned host staging memory", - Self::ContextPoisoned => { - "context is poisoned after uncertain completion or restoration" - } + Self::ContextPoisoned => "context is poisoned after uncertain completion or restoration", Self::UnexpectedContext => "CUDA pop returned a different context", _ => return None, }) @@ -43,29 +39,15 @@ impl Error { pub(super) fn validation_message(&self) -> Option<&'static str> { Some(match self { Self::ContextMismatch => "buffers must belong to this exact context", - Self::InvalidVectorShape => { - "vector shape must be nonempty f32 bytes with a bounded u32 count/grid" - } - Self::InvalidMatvecShape => { - "matvec requires exact nonempty bounded row-major f32 shapes" - } - Self::InvalidQ5KProjectionShape => { - "Q5_K projection requires exact bounded row-major single-column shapes" - } - Self::InvalidQ6KProjectionShape => { - "Q6_K projection requires exact bounded row-major single-column shapes" - } + Self::InvalidVectorShape => "vector shape must be nonempty f32 bytes with a bounded u32 count/grid", + Self::InvalidMatvecShape => "matvec requires exact nonempty bounded row-major f32 shapes", + Self::InvalidQ5KProjectionShape => "Q5_K projection requires exact bounded row-major single-column shapes", + Self::InvalidQ6KProjectionShape => "Q6_K projection requires exact bounded row-major single-column shapes", Self::UnsupportedProjection => "projection format is not integrated", Self::UnsupportedQwenOperation => "Qwen operation has no qualified fixed asset", - Self::InvalidQwenShape => { - "Qwen operation requires its exact pinned topology and byte layout" - } - Self::InvalidBf16ProjectionShape => { - "BF16 projection requires exact bounded rows and positive even columns" - } - Self::InvalidProjectionShape => { - "projection requires exact bounded packed single-column shapes" - } + Self::InvalidQwenShape => "Qwen operation requires its exact pinned topology and byte layout", + Self::InvalidBf16ProjectionShape => "BF16 projection requires exact bounded rows and positive even columns", + Self::InvalidProjectionShape => "projection requires exact bounded packed single-column shapes", Self::InvalidQ8Activation => "activation cannot be represented by native Q8_1", Self::NonFiniteMmqOutput(_) => "MMQ produced a nonfinite stage output", Self::OutputAliasesInput => "output must not alias an input", @@ -77,10 +59,7 @@ impl Error { } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(message) = self - .environment_message() - .or_else(|| self.validation_message()) - { + if let Some(message) = self.environment_message().or_else(|| self.validation_message()) { return f.write_str(message); } match self { @@ -95,10 +74,16 @@ impl fmt::Display for Error { write!(f, "byte shape mismatch: expected {expected}, got {actual}") } Self::GraphOutOfMemory { window: 0 } => { - write!(f, "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") + write!( + f, + "the verifier commit graph did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)" + ) } Self::GraphOutOfMemory { window } => { - write!(f, "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)") + write!( + f, + "the verifier window graph T={window} did not fit in device memory (cuGraphInstantiateWithFlags: out of memory)" + ) } Self::Multiple { primary, secondary } => { write!(f, "{primary}; subsequent error: {secondary}") @@ -113,18 +98,13 @@ pub(super) fn combine(primary: Result, secondary: Result<()>) -> Result match (primary, secondary) { (Ok(value), Ok(())) => Ok(value), (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error), - (Err(primary), Err(secondary)) => Err(Error::Multiple { - primary: Box::new(primary), - secondary: Box::new(secondary), - }), + (Err(primary), Err(secondary)) => { + Err(Error::Multiple { primary: Box::new(primary), secondary: Box::new(secondary) }) + } } } pub(super) fn valid_size(bytes: usize) -> Result<()> { - if bytes == 0 || bytes > isize::MAX as usize { - Err(Error::InvalidSize) - } else { - Ok(()) - } + if bytes == 0 || bytes > isize::MAX as usize { Err(Error::InvalidSize) } else { Ok(()) } } impl Driver { /// Resolve the entire fixed ABI before initializing CUDA. @@ -141,11 +121,7 @@ impl Driver { if ordinal < 0 { return Err(Error::InvalidOrdinal); } - Ok(Device { - driver: self, - handle: self.api.device(ordinal)?, - ordinal, - }) + Ok(Device { driver: self, handle: self.api.device(ordinal)?, ordinal }) } } impl<'driver> Device<'driver> { @@ -153,13 +129,8 @@ impl<'driver> Device<'driver> { valid_size(byte_budget)?; let api = &self.driver.api; let handle = api.create(self.handle)?; - let restore = api.pop().and_then(|popped| { - if popped == handle { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } - }); + let restore = + api.pop().and_then(|popped| if popped == handle { Ok(()) } else { Err(Error::UnexpectedContext) }); if let Err(error) = restore { let cleanup = api.destroy(handle); if cleanup.is_err() { @@ -200,12 +171,19 @@ impl<'driver> Device<'driver> { } } impl PoisonCell { - pub(crate) fn new(v: bool) -> Self { Self(Cell::new(v)) } - pub(crate) fn get(&self) -> bool { self.0.get() } + pub(crate) fn new(v: bool) -> Self { + Self(Cell::new(v)) + } + pub(crate) fn get(&self) -> bool { + self.0.get() + } pub(crate) fn set(&self, v: bool) { if v && !self.0.get() && std::env::var_os("LELEKA_TRACE_POISON").is_some() { - crate::bringup_trace!("DBG context poisoned here: -{}", std::backtrace::Backtrace::force_capture()); + crate::bringup_trace!( + "DBG context poisoned here: +{}", + std::backtrace::Backtrace::force_capture() + ); } self.0.set(v); } diff --git a/crates/cuda-driver/src/closed_kernels.rs b/crates/cuda-driver/src/closed_kernels.rs index 3107c602..a6663bbd 100644 --- a/crates/cuda-driver/src/closed_kernels.rs +++ b/crates/cuda-driver/src/closed_kernels.rs @@ -43,32 +43,32 @@ ptx_asset!(DEVICE_POISON_PTX, "device_poison.ptx"); pub const PINS: [PtxPin; 3] = [ PtxPin { source_sha256: [ - 92, 183, 59, 88, 146, 201, 66, 56, 174, 58, 68, 112, 170, 113, 88, 85, 80, 193, 82, 105, - 131, 234, 11, 86, 85, 40, 31, 41, 79, 53, 71, 52, + 92, 183, 59, 88, 146, 201, 66, 56, 174, 58, 68, 112, 170, 113, 88, 85, 80, 193, 82, 105, 131, 234, 11, 86, + 85, 40, 31, 41, 79, 53, 71, 52, ], ptx_sha256: [ - 190, 53, 62, 97, 154, 21, 165, 102, 229, 123, 174, 18, 160, 191, 48, 204, 23, 18, 162, - 129, 188, 230, 146, 143, 59, 183, 108, 20, 229, 17, 75, 186, + 190, 53, 62, 97, 154, 21, 165, 102, 229, 123, 174, 18, 160, 191, 48, 204, 23, 18, 162, 129, 188, 230, 146, + 143, 59, 183, 108, 20, 229, 17, 75, 186, ], }, PtxPin { source_sha256: [ - 9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12, - 222, 133, 157, 30, 78, 65, 80, 198, 7, 181, 25, 82, + 9, 34, 187, 150, 202, 59, 47, 17, 16, 80, 154, 218, 178, 66, 207, 118, 250, 31, 145, 12, 222, 133, 157, 30, + 78, 65, 80, 198, 7, 181, 25, 82, ], ptx_sha256: [ - 58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93, - 140, 241, 162, 2, 96, 175, 110, 15, 82, 5, 172, 118, 213, + 58, 180, 209, 42, 94, 151, 196, 226, 244, 96, 44, 108, 135, 35, 114, 197, 192, 104, 93, 140, 241, 162, 2, + 96, 175, 110, 15, 82, 5, 172, 118, 213, ], }, PtxPin { source_sha256: [ - 107, 44, 169, 146, 172, 57, 213, 182, 177, 130, 10, 116, 74, 216, 188, 160, 63, 100, 38, - 48, 43, 193, 120, 192, 211, 8, 158, 79, 118, 123, 97, 14, + 107, 44, 169, 146, 172, 57, 213, 182, 177, 130, 10, 116, 74, 216, 188, 160, 63, 100, 38, 48, 43, 193, 120, + 192, 211, 8, 158, 79, 118, 123, 97, 14, ], ptx_sha256: [ - 88, 123, 9, 122, 32, 26, 103, 48, 232, 254, 85, 67, 41, 25, 135, 187, 248, 7, 218, 114, - 218, 18, 184, 224, 161, 105, 249, 229, 232, 246, 166, 88, + 88, 123, 9, 122, 32, 26, 103, 48, 232, 254, 85, 67, 41, 25, 135, 187, 248, 7, 218, 114, 218, 18, 184, 224, + 161, 105, 249, 229, 232, 246, 166, 88, ], }, ]; @@ -103,74 +103,23 @@ const S2_TPR: &[Arg] = &[P, P, P, P, L, L, I]; /// Order is `Kernel::ALL_ENTRIES`. pub static S_GEMV_ENTRIES: [Entry; 17] = [ - Entry { - name: c"leleka_s_gemv_2", - args: S_FP16, - }, - Entry { - name: c"leleka_s_gemv_4", - args: S_FP16, - }, - Entry { - name: c"leleka_s_gemv_8", - args: S_FP16, - }, - Entry { - name: c"leleka_s_gemv_split_2", - args: S_SPLIT, - }, - Entry { - name: c"leleka_s_gemv_split_4", - args: S_SPLIT, - }, - Entry { - name: c"leleka_s_gemv_split_8", - args: S_SPLIT, - }, - Entry { - name: c"leleka_s_gemv_q8k_4", - args: S_FP16, - }, - Entry { - name: c"leleka_s_gemv_q8k_8", - args: S_FP16, - }, - Entry { - name: c"leleka_s_gemv_q8k_split_4", - args: S_Q8, - }, - Entry { - name: c"leleka_s_gemv_q8k_split_8", - args: S_Q8, - }, - Entry { - name: c"leleka_s_gemv_q8_0_split_4", - args: S_Q8, - }, - Entry { - name: c"leleka_s_gemv_q8_0_split_8", - args: S_Q8, - }, - Entry { - name: c"leleka_s2_gemv", - args: S2_PLAIN, - }, - Entry { - name: c"leleka_s2_gemv_quads", - args: S2_TPR, - }, - Entry { - name: c"leleka_s2_gemv_q8", - args: S2_TPR, - }, - Entry { - name: c"leleka_s2_gemv_fast_staged", - args: S2_TPR, - }, - Entry { - name: c"leleka_s2_gemv_fast_unstaged", - args: S2_TPR, - }, + Entry { name: c"leleka_s_gemv_2", args: S_FP16 }, + Entry { name: c"leleka_s_gemv_4", args: S_FP16 }, + Entry { name: c"leleka_s_gemv_8", args: S_FP16 }, + Entry { name: c"leleka_s_gemv_split_2", args: S_SPLIT }, + Entry { name: c"leleka_s_gemv_split_4", args: S_SPLIT }, + Entry { name: c"leleka_s_gemv_split_8", args: S_SPLIT }, + Entry { name: c"leleka_s_gemv_q8k_4", args: S_FP16 }, + Entry { name: c"leleka_s_gemv_q8k_8", args: S_FP16 }, + Entry { name: c"leleka_s_gemv_q8k_split_4", args: S_Q8 }, + Entry { name: c"leleka_s_gemv_q8k_split_8", args: S_Q8 }, + Entry { name: c"leleka_s_gemv_q8_0_split_4", args: S_Q8 }, + Entry { name: c"leleka_s_gemv_q8_0_split_8", args: S_Q8 }, + Entry { name: c"leleka_s2_gemv", args: S2_PLAIN }, + Entry { name: c"leleka_s2_gemv_quads", args: S2_TPR }, + Entry { name: c"leleka_s2_gemv_q8", args: S2_TPR }, + Entry { name: c"leleka_s2_gemv_fast_staged", args: S2_TPR }, + Entry { name: c"leleka_s2_gemv_fast_unstaged", args: S2_TPR }, ]; pub const POISON_F32: usize = 0; @@ -235,22 +184,22 @@ mod tests; mod impl_program; #[allow(unused_imports)] -pub use impl_program::admit_ptx; -#[allow(unused_imports)] pub use impl_program::admit; #[allow(unused_imports)] -pub use impl_program::s_gemv_entry_index; +pub use impl_program::admit_ptx; #[allow(unused_imports)] pub use impl_program::conforms; #[allow(unused_imports)] -pub use impl_program::flash_slots; -#[allow(unused_imports)] pub use impl_program::flash_bytes; #[allow(unused_imports)] +pub use impl_program::flash_slots; +#[allow(unused_imports)] pub use impl_program::poison_slots; #[allow(unused_imports)] use impl_program::s_activation_bytes; #[allow(unused_imports)] +pub use impl_program::s_gemv_entry_index; +#[allow(unused_imports)] pub use impl_program::s_operand_bytes; mod s_gemv_slots_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/closed_kernels/impl_program.rs b/crates/cuda-driver/src/closed_kernels/impl_program.rs index 3bfd6301..7e52ece0 100644 --- a/crates/cuda-driver/src/closed_kernels/impl_program.rs +++ b/crates/cuda-driver/src/closed_kernels/impl_program.rs @@ -3,13 +3,8 @@ #[allow(unused_imports)] use super::*; - impl Program { - pub const ALL: [Program; 3] = [ - Program::NativeFlashAttn, - Program::SGemvLegacy, - Program::DevicePoison, - ]; + pub const ALL: [Program; 3] = [Program::NativeFlashAttn, Program::SGemvLegacy, Program::DevicePoison]; pub const fn name(self) -> &'static str { match self { Self::NativeFlashAttn => "native_flash_attn", @@ -50,11 +45,7 @@ pub fn admit_ptx(program: Program, ptx: &'static [u8], pin: &PtxPin) -> Result<( if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] { return Err(refuse); } - if ptx.len() < 2 - || ptx.last() != Some(&0) - || ptx[..ptx.len() - 1].contains(&0) - || !ptx.is_ascii() - { + if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() { return Err(refuse); } if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 { @@ -92,14 +83,10 @@ impl Slot { pub fn conforms(entry: &Entry, slots: &[Slot]) -> bool { slots.len() <= MAX_ENTRY_ARGUMENTS && entry.args.len() == slots.len() - && entry - .args - .iter() - .zip(slots) - .all(|(want, slot)| match (want, slot.kind()) { - (Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true, - (a, b) => *a == b, - }) + && entry.args.iter().zip(slots).all(|(want, slot)| match (want, slot.kind()) { + (Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true, + (a, b) => *a == b, + }) } /// `leleka_native_flash_attn_short(q, k, v, step, max_context, padded_length, scale, out, status, mask)`. @@ -114,11 +101,7 @@ pub fn flash_slots(max_context: i32, with_mask: bool) -> Vec { Slot::F32(flash::SCALE), Slot::Ptr(Role::Out), Slot::Ptr(Role::Status), - if with_mask { - Slot::Ptr(Role::Mask) - } else { - Slot::Null - }, + if with_mask { Slot::Ptr(Role::Mask) } else { Slot::Null }, ] } pub fn flash_bytes(capacity: i64) -> Result { @@ -144,16 +127,10 @@ pub fn poison_slots(n_floats: u64) -> Result> { } pub(super) fn s_activation_bytes(kernel: Kernel, n_in: u64) -> u64 { - use crate::s_gemv_legacy::{ - Q8_0_BLOCK_BYTES, Q8_0_BLOCK_ELEMS, Q8K_BLOCK_BYTES, Q8K_BLOCK_ELEMS, - }; + use crate::s_gemv_legacy::{Q8_0_BLOCK_BYTES, Q8_0_BLOCK_ELEMS, Q8K_BLOCK_BYTES, Q8K_BLOCK_ELEMS}; match kernel { - Kernel::SGemvQ8k(_) | Kernel::SGemvQ8kSplit(_) => { - n_in / Q8K_BLOCK_ELEMS as u64 * Q8K_BLOCK_BYTES as u64 - } - Kernel::SGemvQ80Split(_) | Kernel::S2GemvQ8 => { - n_in / Q8_0_BLOCK_ELEMS as u64 * Q8_0_BLOCK_BYTES as u64 - } + Kernel::SGemvQ8k(_) | Kernel::SGemvQ8kSplit(_) => n_in / Q8K_BLOCK_ELEMS as u64 * Q8K_BLOCK_BYTES as u64, + Kernel::SGemvQ80Split(_) | Kernel::S2GemvQ8 => n_in / Q8_0_BLOCK_ELEMS as u64 * Q8_0_BLOCK_BYTES as u64, _ => n_in * 2, } } @@ -168,20 +145,12 @@ pub fn s_operand_bytes(kernel: Kernel, form: &SForm, n_in: i64, n_out: i64) -> R let (n_in, n_out) = (n_in as u64, n_out as u64); let s2 = matches!( kernel, - Kernel::S2Gemv - | Kernel::S2GemvQuads - | Kernel::S2GemvQ8 - | Kernel::S2GemvFastStaged - | Kernel::S2GemvFastUnstaged + Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8 | Kernel::S2GemvFastStaged | Kernel::S2GemvFastUnstaged ); let (bits, group, offset) = if s2 { (2u64, crate::s_gemv_legacy::S2_QK as u64, false) } else { - ( - form.code_bits as u64, - form.group_elems as u64, - form.has_offset, - ) + (form.code_bits as u64, form.group_elems as u64, form.has_offset) }; if bits == 0 || group == 0 || n_in % group != 0 || n_in * bits % 8 != 0 { return invalid("S-form GEMV rows must hold whole groups and whole code bytes"); diff --git a/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs b/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs index fff9d6f0..a4e60063 100644 --- a/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs +++ b/crates/cuda-driver/src/closed_kernels/s_gemv_slots_fn.rs @@ -3,27 +3,12 @@ #[allow(unused_imports)] use super::*; - /// The kernel arguments of a planned S-form GEMV, in the entry's order. `offset_present` is `offset != nullptr`. -pub fn s_gemv_slots( - plan: &Plan, - form: &SForm, - n_in: i64, - n_out: i64, - offset_present: bool, -) -> Vec { - let offset = if offset_present { - Slot::Ptr(Role::Offset) - } else { - Slot::Null - }; +pub fn s_gemv_slots(plan: &Plan, form: &SForm, n_in: i64, n_out: i64, offset_present: bool) -> Vec { + let offset = if offset_present { Slot::Ptr(Role::Offset) } else { Slot::Null }; let tpr = Slot::I32(plan.launch.block[0] as i32); let head = |with_offset: bool| -> Vec { - let mut v = vec![ - Slot::Ptr(Role::X), - Slot::Ptr(Role::Codes), - Slot::Ptr(Role::Scales), - ]; + let mut v = vec![Slot::Ptr(Role::X), Slot::Ptr(Role::Codes), Slot::Ptr(Role::Scales)]; if with_offset { v.push(offset); } @@ -31,11 +16,8 @@ pub fn s_gemv_slots( v.extend([Slot::I64(n_in), Slot::I64(n_out)]); v }; - let (bias, codebook, has_offset) = ( - Slot::I32(form.code_bias), - Slot::I32(form.codebook as i32), - Slot::I32(i32::from(form.has_offset)), - ); + let (bias, codebook, has_offset) = + (Slot::I32(form.code_bias), Slot::I32(form.codebook as i32), Slot::I32(i32::from(form.has_offset))); match plan.kernel { Kernel::SGemv(_) | Kernel::SGemvQ8k(_) => { let mut v = head(true); @@ -44,14 +26,7 @@ pub fn s_gemv_slots( } Kernel::SGemvSplit(_) => { let mut v = head(true); - v.extend([ - bias, - codebook, - Slot::I32(form.group_elems), - Slot::I32(plan.group_shift), - has_offset, - tpr, - ]); + v.extend([bias, codebook, Slot::I32(form.group_elems), Slot::I32(plan.group_shift), has_offset, tpr]); v } Kernel::SGemvQ8kSplit(_) | Kernel::SGemvQ80Split(_) => { @@ -60,10 +35,7 @@ pub fn s_gemv_slots( v } Kernel::S2Gemv => head(false), - Kernel::S2GemvQuads - | Kernel::S2GemvQ8 - | Kernel::S2GemvFastStaged - | Kernel::S2GemvFastUnstaged => { + Kernel::S2GemvQuads | Kernel::S2GemvQ8 | Kernel::S2GemvFastStaged | Kernel::S2GemvFastUnstaged => { let mut v = head(false); v.push(tpr); v diff --git a/crates/cuda-driver/src/closed_kernels/tests.rs b/crates/cuda-driver/src/closed_kernels/tests.rs index 94f44ee3..31d21dd2 100644 --- a/crates/cuda-driver/src/closed_kernels/tests.rs +++ b/crates/cuda-driver/src/closed_kernels/tests.rs @@ -5,9 +5,7 @@ use crate::s_gemv_legacy as sg; /// `count_params`: parameter kinds of `extern "C" __global__ ... name(...)` in a `.cu` text. fn kinds_in(source: &str, name: &str) -> Vec<&'static str> { - let at = source - .find(&format!(" {name}(")) - .unwrap_or_else(|| panic!("{name} not in source")); + let at = source.find(&format!(" {name}(")).unwrap_or_else(|| panic!("{name} not in source")); let rest = &source[at + name.len() + 2..]; let close = rest.find(") {").expect("parameter list end"); rest[..close] @@ -31,15 +29,8 @@ fn kinds_in(source: &str, name: &str) -> Vec<&'static str> { /// The S-form entries are generated by macros: expand the two argument macros to find their parameter kinds. fn macro_kinds(source: &str, macro_name: &str) -> Vec<&'static str> { - let at = source - .find(&format!("#define {macro_name} ")) - .expect("macro"); - let body = source[at..] - .lines() - .take(3) - .collect::>() - .join(" ") - .replace('\\', " "); + let at = source.find(&format!("#define {macro_name} ")).expect("macro"); + let body = source[at..].lines().take(3).collect::>().join(" ").replace('\\', " "); let params = body.split_once(macro_name).unwrap().1.trim_start(); // the macro text ends at its last parameter ("int has_offset"); stop before the next `#define` let params = params.split("#define").next().unwrap(); diff --git a/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs b/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs index 3993f09d..ab5d1bb1 100644 --- a/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs +++ b/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn flash_and_poison_signatures_match_their_cuda_source() { for program in [Program::NativeFlashAttn, Program::DevicePoison] { @@ -13,11 +12,7 @@ fn flash_and_poison_signatures_match_their_cuda_source() { assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS); } } - assert!( - Program::NativeFlashAttn - .source() - .contains("__launch_bounds__(128, 1)") - ); + assert!(Program::NativeFlashAttn.source().contains("__launch_bounds__(128, 1)")); assert_eq!(flash::LAUNCH.block[0] * flash::LAUNCH.block[1], 128); } @@ -26,12 +21,7 @@ fn s_gemv_signatures_match_their_cuda_source() { let source = Program::SGemvLegacy.source(); let fp16 = macro_kinds(source, "LELEKA_S_FP16_ARGS"); let q8 = macro_kinds(source, "LELEKA_S_Q8_ARGS"); - assert_eq!( - fp16, - [ - "ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32" - ] - ); + assert_eq!(fp16, ["ptr", "ptr", "ptr", "ptr", "ptr", "i64", "i64", "i32", "i32", "i32", "i32"]); assert_eq!(q8, fp16); for (index, entry) in S_GEMV_ENTRIES.iter().enumerate() { let name = entry.name.to_str().unwrap(); @@ -58,23 +48,10 @@ fn s_gemv_signatures_match_their_cuda_source() { fn index_constants_and_planners_point_at_the_named_entries() { let name = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); assert_eq!(name(Program::NativeFlashAttn, FLASH_SHORT), flash::ENTRY); - assert_eq!( - name(Program::DevicePoison, POISON_F32), - crate::device_arena::ENTRY_POISON - ); - let form = SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - ..SForm::default() - }; - let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false) - .unwrap() - .unwrap(); - assert_eq!( - name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)), - "leleka_s_gemv_split_4" - ); + assert_eq!(name(Program::DevicePoison, POISON_F32), crate::device_arena::ENTRY_POISON); + let form = SForm { code_bits: 4, code_bias: -8, group_elems: 32, ..SForm::default() }; + let plan = sg::plan_s_gemv_split(512, 8, &form, 64, false).unwrap().unwrap(); + assert_eq!(name(Program::SGemvLegacy, s_gemv_entry_index(plan.kernel)), "leleka_s_gemv_split_4"); for (i, e) in Kernel::ALL_ENTRIES.iter().enumerate() { assert_eq!(S_GEMV_ENTRIES[i].name.to_str().unwrap(), *e); } @@ -83,26 +60,9 @@ fn index_constants_and_planners_point_at_the_named_entries() { #[test] fn every_planned_launch_conforms_to_its_entry() { let forms = [ - SForm { - code_bits: 2, - code_bias: -1, - group_elems: 64, - ..SForm::default() - }, - SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - has_offset: true, - ..SForm::default() - }, - SForm { - code_bits: 8, - code_bias: -128, - group_elems: 64, - codebook: sg::Codebook::Iq4Nl, - ..SForm::default() - }, + SForm { code_bits: 2, code_bias: -1, group_elems: 64, ..SForm::default() }, + SForm { code_bits: 4, code_bias: -8, group_elems: 32, has_offset: true, ..SForm::default() }, + SForm { code_bits: 8, code_bias: -128, group_elems: 64, codebook: sg::Codebook::Iq4Nl, ..SForm::default() }, ]; let mut planned = 0; for form in forms { @@ -113,18 +73,10 @@ fn every_planned_launch_conforms_to_its_entry() { let (n_in, n_out) = (1024, 6); let mut plans: Vec = Vec::new(); plans.extend(sg::plan_s_gemv(n_in, n_out, &form, offset).ok().flatten()); - plans.extend( - sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset) - .ok() - .flatten(), - ); + plans.extend(sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset).ok().flatten()); plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, &form).ok().flatten()); plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, &form).ok().flatten()); - plans.extend( - sg::plan_s_gemv_q8_0_split(n_in, n_out, &form) - .ok() - .flatten(), - ); + plans.extend(sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).ok().flatten()); for plan in plans { let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; let slots = s_gemv_slots(&plan, &form, n_in, n_out, offset); @@ -162,9 +114,7 @@ fn slot_values_follow_the_oracle_driver() { has_offset: true, ..SForm::default() }; - let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true) - .unwrap() - .unwrap(); + let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true).unwrap().unwrap(); let slots = s_gemv_slots(&plan, &form, 512, 8, true); assert_eq!( slots, @@ -184,92 +134,47 @@ fn slot_values_follow_the_oracle_driver() { Slot::I32(64), ] ); - assert_eq!( - ( - plan.launch.grid, - plan.launch.block, - plan.launch.dynamic_shared - ), - ([8, 1, 1], [64, 1, 1], 256) - ); + assert_eq!((plan.launch.grid, plan.launch.block, plan.launch.dynamic_shared), ([8, 1, 1], [64, 1, 1], 256)); // the Q8 split kernels take the shift in place of the group let plan = sg::plan_s_gemv_q8k_split(512, 8, &form).unwrap().unwrap(); let slots = s_gemv_slots(&plan, &form, 512, 8, true); - assert_eq!( - &slots[7..], - &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)] - ); + assert_eq!(&slots[7..], &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)]); // a form without an offset passes a null offset pointer - let none = SForm { - has_offset: false, - ..form - }; + let none = SForm { has_offset: false, ..form }; let plan = sg::plan_s_gemv(512, 8, &none, false).unwrap().unwrap(); assert_eq!(s_gemv_slots(&plan, &none, 512, 8, false)[3], Slot::Null); } #[test] fn operand_sizes_follow_the_pack_format() { - let form = SForm { - code_bits: 4, - code_bias: -8, - group_elems: 32, - has_offset: true, - ..SForm::default() - }; + let form = SForm { code_bits: 4, code_bias: -8, group_elems: 32, has_offset: true, ..SForm::default() }; let b = s_operand_bytes(Kernel::SGemvSplit(4), &form, 512, 8).unwrap(); - assert_eq!( - (b.x, b.codes, b.scales, b.offset, b.y), - (1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32) - ); + assert_eq!((b.x, b.codes, b.scales, b.offset, b.y), (1024, 8 * 256, 8 * 16 * 4, Some(8 * 16 * 4), 32)); let b = s_operand_bytes(Kernel::SGemvQ8k(4), &form, 512, 8).unwrap(); assert_eq!(b.x, 2 * 292); let b = s_operand_bytes(Kernel::SGemvQ80Split(4), &form, 512, 8).unwrap(); assert_eq!(b.x, 16 * 34); let b = s_operand_bytes(Kernel::S2GemvQ8, &SForm::default(), 512, 8).unwrap(); - assert_eq!( - (b.x, b.codes, b.scales, b.offset), - (16 * 34, 8 * 128, 8 * 8 * 4, None) - ); + assert_eq!((b.x, b.codes, b.scales, b.offset), (16 * 34, 8 * 128, 8 * 8 * 4, None)); assert!(s_operand_bytes(Kernel::SGemv(2), &SForm::default(), 0, 8).is_err()); - assert!( - s_operand_bytes( - Kernel::SGemv(2), - &SForm { - group_elems: 64, - ..SForm::default() - }, - 100, - 8 - ) - .is_err() - ); + assert!(s_operand_bytes(Kernel::SGemv(2), &SForm { group_elems: 64, ..SForm::default() }, 100, 8).is_err()); } #[test] fn flash_and_poison_slots_and_sizes() { let slots = flash_slots(256, true); assert!(conforms(&FLASH_ENTRIES[0], &slots)); - assert_eq!( - slots[4..7], - [Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)] - ); + assert_eq!(slots[4..7], [Slot::I32(256), Slot::I32(256), Slot::F32(0.0625)]); assert_eq!(flash_slots(256, false)[9], Slot::Null); assert!(conforms(&FLASH_ENTRIES[0], &flash_slots(7, false))); let b = flash_bytes(4096).unwrap(); - assert_eq!( - (b.q, b.kv, b.step, b.out, b.status, b.mask), - (24576, 4096 * 1024, 16, 24576, 4, 512) - ); + assert_eq!((b.q, b.kv, b.step, b.out, b.status, b.mask), (24576, 4096 * 1024, 16, 24576, 4, 512)); assert!(flash_bytes(255).is_err()); let slots = poison_slots(1000).unwrap(); assert_eq!(slots, vec![Slot::Ptr(Role::Poison), Slot::I64(1000)]); assert!(conforms(&POISON_ENTRIES[0], &slots)); assert!(poison_slots(u64::MAX).is_err()); // a mismatching scalar kind never conforms - assert!(!conforms( - &POISON_ENTRIES[0], - &[Slot::Ptr(Role::Poison), Slot::I32(1)] - )); + assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison), Slot::I32(1)])); assert!(!conforms(&POISON_ENTRIES[0], &[Slot::Ptr(Role::Poison)])); } diff --git a/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs b/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs index 3a476816..214f6a57 100644 --- a/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs +++ b/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs @@ -3,12 +3,11 @@ #[allow(unused_imports)] use super::*; - #[test] fn sealed_assets_match_their_pins_and_export_every_entry() { use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, + with_embedded_nul, without_terminator, }; for program in Program::ALL { // Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim, @@ -33,34 +32,15 @@ fn sealed_assets_match_their_pins_and_export_every_entry() { let mut wrong_digest = *pin; wrong_digest.ptx_sha256[0] ^= 1; assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [ - PtxPin { source_sha256: [0; 32], ..*pin }, - PtxPin { ptx_sha256: [0; 32], ..*pin }, - ] { + for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); } } // a matching pin admits; any difference refuses static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), - }; + let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]) }; assert_eq!(admit_ptx(Program::DevicePoison, GOOD, &pin), Ok(())); - let wrong = PtxPin { - ptx_sha256: [2; 32], - ..pin - }; + let wrong = PtxPin { ptx_sha256: [2; 32], ..pin }; assert!(admit_ptx(Program::DevicePoison, GOOD, &wrong).is_err()); - assert!( - admit_ptx( - Program::DevicePoison, - GOOD, - &PtxPin { - source_sha256: [0; 32], - ..pin - } - ) - .is_err() - ); + assert!(admit_ptx(Program::DevicePoison, GOOD, &PtxPin { source_sha256: [0; 32], ..pin }).is_err()); } diff --git a/crates/cuda-driver/src/closed_kernels_gpu.rs b/crates/cuda-driver/src/closed_kernels_gpu.rs index 9cc8d073..512dc5f6 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu.rs @@ -22,8 +22,8 @@ use crate::{ Context, DeviceBuffer, Error, closed_kernels::{ - FLASH_SHORT, POISON_F32, Program, Role, Slot, admit, conforms, flash_bytes, flash_slots, - poison_slots, s_gemv_entry_index, s_gemv_slots, s_operand_bytes, + FLASH_SHORT, POISON_F32, Program, Role, Slot, admit, conforms, flash_bytes, flash_slots, poison_slots, + s_gemv_entry_index, s_gemv_slots, s_operand_bytes, }, combine, device_arena, experimental::{ExperimentalError, Result, invalid}, diff --git a/crates/cuda-driver/src/closed_kernels_gpu/failure_fn.rs b/crates/cuda-driver/src/closed_kernels_gpu/failure_fn.rs index e64dd90e..db292551 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/failure_fn.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/failure_fn.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - /// A primary driver failure plus the outcome of the mandatory context restore. pub(super) fn failure(primary: Error, restore: DriverResult<()>) -> ExperimentalError { - combine::<()>(Err(primary), restore) - .expect_err("a primary failure always stays an error") - .into() + combine::<()>(Err(primary), restore).expect_err("a primary failure always stays an error").into() } diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs index dfcd6688..e19fa0ac 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'c> ClosedKernels<'c> { /// Pin gate, then load the module and resolve every entry; nothing is kept unless all of them resolve. pub fn open(context: &'c Context<'c>, program: Program) -> Result { @@ -32,12 +30,7 @@ impl<'c> ClosedKernels<'c> { match resolved { Ok(()) => { guard.finish()?; - Ok(Self { - context, - program, - module, - functions, - }) + Ok(Self { context, program, module, functions }) } Err(error) => { let cleanup = api.unload(module); @@ -45,8 +38,7 @@ impl<'c> ClosedKernels<'c> { context.poisoned.set(true); std::mem::forget(Rc::clone(api)); } - let primary = - combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); + let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); Err(failure(primary, guard.finish())) } } @@ -88,10 +80,7 @@ impl<'c> ClosedKernels<'c> { if !conforms(spec, slots) { return invalid("closed launch arguments differ from the entry's fixed signature"); } - if block.contains(&0) - || grid.contains(&0) - || block.iter().map(|b| u64::from(*b)).product::() > 1024 - { + if block.contains(&0) || grid.contains(&0) || block.iter().map(|b| u64::from(*b)).product::() > 1024 { return invalid("closed launch geometry is empty or exceeds 1024 threads per block"); } let context = self.context; @@ -111,17 +100,12 @@ impl<'c> ClosedKernels<'c> { return Err(Error::ContextMismatch.into()); } let handle = operand.buffer.handle.ok_or(Error::ContextPoisoned)?; - let min = usize::try_from(operand.min) - .or_else(|_| invalid("closed buffer size exceeds usize"))?; + let min = usize::try_from(operand.min).or_else(|_| invalid("closed buffer size exceeds usize"))?; if min == 0 || operand.buffer.bytes < min { return invalid("closed buffer is smaller than the geometry requires"); } handle.validate_projection_extent(operand.buffer.bytes, 16)?; - admitted.push(Admitted { - handle, - bytes: operand.buffer.bytes, - writes: operand.writes, - }); + admitted.push(Admitted { handle, bytes: operand.buffer.bytes, writes: operand.writes }); let at = handle.experimental_offset(operand.offset)?; args.push(ffi::KarArgument::Scalar64(at.qwen_address())); } @@ -138,13 +122,7 @@ impl<'c> ClosedKernels<'c> { } } } - Ok(Launch { - function: self.functions[entry], - grid, - block, - shared, - args: ffi::KarLevelsArgs::new(&args)?, - }) + Ok(Launch { function: self.functions[entry], grid, block, shared, args: ffi::KarLevelsArgs::new(&args)? }) } /// Launch in order and drain with exactly one synchronize. @@ -156,19 +134,11 @@ impl<'c> ClosedKernels<'c> { let guard = context.enter()?; let mut launch = Ok(()); for l in &mut launches { - launch = context.driver.api.launch_closed( - l.function, - l.grid, - l.block, - l.shared, - &mut l.args, - ); + launch = context.driver.api.launch_closed(l.function, l.grid, l.block, l.shared, &mut l.args); if launch.is_err() { break; } } - context - .complete_launch(launch, launches, guard) - .map_err(Into::into) + context.complete_launch(launch, launches, guard).map_err(Into::into) } } diff --git a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs index 9a87045b..a720fc34 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu/impl_closedkernels/impl_closedkernels_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'c> ClosedKernels<'c> { - // --------------------------------------------------------------------------- short FlashAttention /// `native_flash_attn_short_step`: one query, Q 24x256 f32, K/V 2x256 f16 cells (`capacity` of them each), device @@ -32,8 +29,7 @@ impl<'c> ClosedKernels<'c> { let bytes = flash_bytes(capacity)?; let address = |b: &DeviceBuffer<'_>| -> Result { let handle = b.handle.ok_or(Error::ContextPoisoned)?; - usize::try_from(handle.qwen_address()) - .or_else(|_| invalid("device address exceeds usize")) + usize::try_from(handle.qwen_address()).or_else(|_| invalid("device address exceeds usize")) }; let launch = flash::admit(&flash::Arguments { n_head: flash::HEADS as i64, @@ -54,67 +50,18 @@ impl<'c> ClosedKernels<'c> { }) .map_err(|e| ExperimentalError::Invalid(e.message()))?; let mut operands = vec![ - Operand { - role: Role::Q, - buffer: q, - min: bytes.q, - offset: 0, - writes: false, - }, - Operand { - role: Role::K, - buffer: k, - min: bytes.kv, - offset: 0, - writes: false, - }, - Operand { - role: Role::V, - buffer: v, - min: bytes.kv, - offset: 0, - writes: false, - }, - Operand { - role: Role::Step, - buffer: step, - min: bytes.step, - offset: 0, - writes: false, - }, - Operand { - role: Role::Out, - buffer: out, - min: bytes.out, - offset: 0, - writes: true, - }, - Operand { - role: Role::Status, - buffer: status, - min: bytes.status, - offset: 0, - writes: true, - }, + Operand { role: Role::Q, buffer: q, min: bytes.q, offset: 0, writes: false }, + Operand { role: Role::K, buffer: k, min: bytes.kv, offset: 0, writes: false }, + Operand { role: Role::V, buffer: v, min: bytes.kv, offset: 0, writes: false }, + Operand { role: Role::Step, buffer: step, min: bytes.step, offset: 0, writes: false }, + Operand { role: Role::Out, buffer: out, min: bytes.out, offset: 0, writes: true }, + Operand { role: Role::Status, buffer: status, min: bytes.status, offset: 0, writes: true }, ]; if let Some(mask) = mask { - operands.push(Operand { - role: Role::Mask, - buffer: mask, - min: bytes.mask, - offset: 0, - writes: false, - }); + operands.push(Operand { role: Role::Mask, buffer: mask, min: bytes.mask, offset: 0, writes: false }); } let slots = flash_slots(max_context, mask.is_some()); - let launch = self.build( - FLASH_SHORT, - launch.grid, - launch.block, - launch.dynamic_shared, - &slots, - &operands, - )?; + let launch = self.build(FLASH_SHORT, launch.grid, launch.block, launch.dynamic_shared, &slots, &operands)?; self.run(vec![launch]) } @@ -124,8 +71,7 @@ impl<'c> ClosedKernels<'c> { /// `0x7fc00000`, in slices of at most `0x7FFFFFFF` blocks of 256 threads, under one drain. pub fn poison_f32(&self, buffer: &mut DeviceBuffer<'_>) -> Result<()> { self.expect(Program::DevicePoison)?; - let plan = - device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS); + let plan = device_arena::poison_launches(buffer.bytes as u64, device_arena::POISON_MAX_BLOCKS); if plan.is_empty() { return invalid("poison needs at least one float"); } @@ -138,12 +84,7 @@ impl<'c> ClosedKernels<'c> { offset: slice.float_offset * 4, writes: true, }]; - let grid = [ - u32::try_from(slice.blocks) - .or_else(|_| invalid("poison slice exceeds the grid"))?, - 1, - 1, - ]; + let grid = [u32::try_from(slice.blocks).or_else(|_| invalid("poison slice exceeds the grid"))?, 1, 1]; launches.push(self.build( POISON_F32, grid, @@ -180,43 +121,13 @@ impl<'c> ClosedKernels<'c> { return invalid("the S-form has an offset exactly when an offset buffer is passed"); } let mut operands = vec![ - Operand { - role: Role::X, - buffer: x, - min: bytes.x, - offset: 0, - writes: false, - }, - Operand { - role: Role::Codes, - buffer: codes, - min: bytes.codes, - offset: 0, - writes: false, - }, - Operand { - role: Role::Scales, - buffer: scales, - min: bytes.scales, - offset: 0, - writes: false, - }, - Operand { - role: Role::Y, - buffer: y, - min: bytes.y, - offset: 0, - writes: true, - }, + Operand { role: Role::X, buffer: x, min: bytes.x, offset: 0, writes: false }, + Operand { role: Role::Codes, buffer: codes, min: bytes.codes, offset: 0, writes: false }, + Operand { role: Role::Scales, buffer: scales, min: bytes.scales, offset: 0, writes: false }, + Operand { role: Role::Y, buffer: y, min: bytes.y, offset: 0, writes: true }, ]; if let (Some(buffer), Some(min)) = (offset, bytes.offset) { - operands.push(Operand { - role: Role::Offset, - buffer, - min, - offset: 0, - writes: false, - }); + operands.push(Operand { role: Role::Offset, buffer, min, offset: 0, writes: false }); } let slots = s_gemv_slots(plan, form, n_in, n_out, offset.is_some()); let launch = self.build( @@ -242,16 +153,6 @@ impl<'c> ClosedKernels<'c> { scales: &DeviceBuffer<'_>, y: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.s_gemv( - plan, - &SForm::default(), - n_in, - n_out, - x, - codes, - scales, - None, - y, - ) + self.s_gemv(plan, &SForm::default(), n_in, n_out, x, codes, scales, None, y) } } diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs index 38962b52..2b472d5c 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs @@ -31,17 +31,10 @@ fn closed_gpu_poison_fills_the_nan_pattern_and_nothing_else() { let mut want = vec![0u32; floats]; device_arena::poison_model( &mut want, - &device_arena::poison_launches( - (floats * 4) as u64, - device_arena::POISON_MAX_BLOCKS, - )[0], + &device_arena::poison_launches((floats * 4) as u64, device_arena::POISON_MAX_BLOCKS)[0], ); for (i, word) in got.chunks_exact(4).enumerate() { - assert_eq!( - u32::from_le_bytes(word.try_into().unwrap()), - want[i], - "float {i} of {floats}" - ); + assert_eq!(u32::from_le_bytes(word.try_into().unwrap()), want[i], "float {i} of {floats}"); } } gpu.close().unwrap(); @@ -62,43 +55,18 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() { for with_mask in [false, true] { let mut rng = Rng(0xf1a5_0000 + width as u64 * 2 + u64::from(with_mask)); let q: Vec = (0..24 * 256).map(|_| 0.8 * rng.normal()).collect(); - let k: Vec = (0..capacity * 512) - .map(|_| f16_bits(rng.normal())) - .collect(); - let v: Vec = (0..capacity * 512) - .map(|_| f16_bits(rng.normal())) - .collect(); - let mask: Vec = (0..256) - .map(|c| { - f16_bits(if with_mask { - ((c * 7) % 5) as f32 * -0.5 - } else { - 0.0 - }) - }) - .collect(); - let step = [ - width as i32 - 1, - width as i32, - width as i32 / 4, - width as i32, - ]; + let k: Vec = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect(); + let v: Vec = (0..capacity * 512).map(|_| f16_bits(rng.normal())).collect(); + let mask: Vec = + (0..256).map(|c| f16_bits(if with_mask { ((c * 7) % 5) as f32 * -0.5 } else { 0.0 })).collect(); + let step = [width as i32 - 1, width as i32, width as i32 / 4, width as i32]; let bytes = |h: &[u16]| h.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let (q_b, k_b, v_b) = ( - upload( - &ctx, - &q.iter().flat_map(|x| x.to_le_bytes()).collect::>(), - ), + upload(&ctx, &q.iter().flat_map(|x| x.to_le_bytes()).collect::>()), upload(&ctx, &bytes(&k)), upload(&ctx, &bytes(&v)), ); - let step_b = upload( - &ctx, - &step - .iter() - .flat_map(|x| x.to_le_bytes()) - .collect::>(), - ); + let step_b = upload(&ctx, &step.iter().flat_map(|x| x.to_le_bytes()).collect::>()); let mask_b = upload(&ctx, &bytes(&mask)); let mut out_b = upload(&ctx, &vec![0xffu8; 24 * 256 * 4]); let mut status_b = upload(&ctx, &(-1i32).to_le_bytes()); @@ -124,23 +92,16 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() { let h2f = |b: u16| sg::f16_to_f32(b); for head in 0..24 { let kv = head / 12; - let kk: Vec> = (0..width) - .map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect()) - .collect(); - let vv: Vec> = (0..width) - .map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect()) - .collect(); + let kk: Vec> = + (0..width).map(|c| (0..256).map(|d| h2f(k[(c * 2 + kv) * 256 + d])).collect()).collect(); + let vv: Vec> = + (0..width).map(|c| (0..256).map(|d| h2f(v[(c * 2 + kv) * 256 + d])).collect()).collect(); let m: Vec = (0..width).map(|c| h2f(mask[c])).collect(); - let want = flash::reference_head( - &q[head * 256..(head + 1) * 256], - &kk, - &vv, - with_mask.then_some(&m[..]), - ); + let want = + flash::reference_head(&q[head * 256..(head + 1) * 256], &kk, &vv, with_mask.then_some(&m[..])); let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); for d in 0..256 { - worst = - worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude); + worst = worst.max(f64::from((out[head * 256 + d] - want[d]).abs()) / magnitude); } } } @@ -165,15 +126,8 @@ fn closed_gpu_native_flash_attn_matches_the_fp64_specification() { &mut status_b, ) .unwrap(); - assert_eq!( - i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), - flash::STATUS_UNSUPPORTED_STEP - ); - assert!( - f32s(&download(&out_b, 24 * 256 * 4)) - .iter() - .all(|x| x.is_nan()) - ); + assert_eq!(i32::from_le_bytes(download(&status_b, 4)[..4].try_into().unwrap()), flash::STATUS_UNSUPPORTED_STEP); + assert!(f32s(&download(&out_b, 24 * 256 * 4)).iter().all(|x| x.is_nan())); gpu.close().unwrap(); } ctx.close().unwrap(); @@ -199,70 +153,28 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { code_bits: case["bits"].as_i64().unwrap() as i32, code_bias: case["bias"].as_i64().unwrap() as i32, group_elems: case["group"].as_i64().unwrap() as i32, - codebook: if case["codebook"].as_i64().unwrap() == 1 { - Codebook::Iq4Nl - } else { - Codebook::Affine - }, + codebook: if case["codebook"].as_i64().unwrap() == 1 { Codebook::Iq4Nl } else { Codebook::Affine }, has_offset: case["has_offset"].as_i64().unwrap() == 1, act_kind: 0, }; - let (n_in, n_out) = ( - case["n_in"].as_i64().unwrap(), - case["n_out"].as_i64().unwrap(), - ); + let (n_in, n_out) = (case["n_in"].as_i64().unwrap(), case["n_out"].as_i64().unwrap()); let exact = case["exact"].as_i64().unwrap() == 1; let codes = upload(&ctx, &json_bytes(&case["codes"])); - let scales = upload( - &ctx, - &json_f32(&case["scales"]) - .iter() - .flat_map(|x| x.to_le_bytes()) - .collect::>(), - ); + let scales = + upload(&ctx, &json_f32(&case["scales"]).iter().flat_map(|x| x.to_le_bytes()).collect::>()); let offset = form.has_offset.then(|| { - upload( - &ctx, - &json_f32(&case["offset"]) - .iter() - .flat_map(|x| x.to_le_bytes()) - .collect::>(), - ) + upload(&ctx, &json_f32(&case["offset"]).iter().flat_map(|x| x.to_le_bytes()).collect::>()) }); - let x16: Vec = case["x"] - .as_array() - .unwrap() - .iter() - .flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()) - .collect(); - let (x16_b, q8k, q80) = ( - upload(&ctx, &x16), - json_bytes(&case["q8k"]), - json_bytes(&case["q80"]), - ); + let x16: Vec = + case["x"].as_array().unwrap().iter().flat_map(|v| (v.as_u64().unwrap() as u16).to_le_bytes()).collect(); + let (x16_b, q8k, q80) = (upload(&ctx, &x16), json_bytes(&case["q8k"]), json_bytes(&case["q80"])); let mut check = |what: &str, plan: sg::Plan, x: &DeviceBuffer<'_>, want: &[f32]| { let mut y = upload(&ctx, &vec![0xffu8; n_out as usize * 4]); - if form.code_bits == 2 - && matches!( - plan.kernel, - Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8 - ) + if form.code_bits == 2 && matches!(plan.kernel, Kernel::S2Gemv | Kernel::S2GemvQuads | Kernel::S2GemvQ8) { - gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y) - .unwrap(); + gpu.s2_gemv(&plan, n_in, n_out, x, &codes, &scales, &mut y).unwrap(); } else { - gpu.s_gemv( - &plan, - &form, - n_in, - n_out, - x, - &codes, - &scales, - offset.as_ref(), - &mut y, - ) - .unwrap(); + gpu.s_gemv(&plan, &form, n_in, n_out, x, &codes, &scales, offset.as_ref(), &mut y).unwrap(); } let got = f32s(&download(&y, n_out as usize * 4)); let magnitude = want.iter().fold(1e-6f64, |a, w| a.max(f64::from(w.abs()))); @@ -277,20 +189,11 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { let y_fp16 = json_f32(&case["y_fp16"]); let offset_present = form.has_offset; if exact { - check( - "s_gemv", - sg::plan_s_gemv(n_in, n_out, &form, offset_present) - .unwrap() - .unwrap(), - &x16_b, - &y_fp16, - ); + check("s_gemv", sg::plan_s_gemv(n_in, n_out, &form, offset_present).unwrap().unwrap(), &x16_b, &y_fp16); } check( "s_gemv_split64", - sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present) - .unwrap() - .unwrap(), + sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset_present).unwrap().unwrap(), &x16_b, &y_fp16, ); @@ -298,9 +201,7 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { let b = upload(&ctx, &q8k); check( "q8k_split", - sg::plan_s_gemv_q8k_split(n_in, n_out, &form) - .unwrap() - .unwrap(), + sg::plan_s_gemv_q8k_split(n_in, n_out, &form).unwrap().unwrap(), &b, &json_f32(&case["y_q8k"]), ); @@ -309,9 +210,7 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { let b = upload(&ctx, &q80); check( "q8_0_split", - sg::plan_s_gemv_q8_0_split(n_in, n_out, &form) - .unwrap() - .unwrap(), + sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).unwrap().unwrap(), &b, &json_f32(&case["y_q80"]), ); @@ -327,18 +226,18 @@ fn closed_gpu_s_gemv_matches_the_shim_executed_golden() { #[path = "closed_kernels_gpu_smoke/impl_rng.rs"] mod impl_rng; #[allow(unused_imports)] -use impl_rng::f16_bits; -#[allow(unused_imports)] -use impl_rng::upload; -#[allow(unused_imports)] use impl_rng::download; #[allow(unused_imports)] +use impl_rng::f16_bits; +#[allow(unused_imports)] use impl_rng::f32s; #[allow(unused_imports)] -use impl_rng::open; -#[allow(unused_imports)] -use impl_rng::zero_kv; -#[allow(unused_imports)] use impl_rng::json_bytes; #[allow(unused_imports)] use impl_rng::json_f32; +#[allow(unused_imports)] +use impl_rng::open; +#[allow(unused_imports)] +use impl_rng::upload; +#[allow(unused_imports)] +use impl_rng::zero_kv; diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke/impl_rng.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke/impl_rng.rs index 042c23de..183da920 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke/impl_rng.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke/impl_rng.rs @@ -5,18 +5,12 @@ use super::*; impl Rng { pub(super) fn next(&mut self) -> u32 { - self.0 = self - .0 - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (self.0 >> 32) as u32 } /// A standard-normal-ish value (sum of twelve uniforms). pub(super) fn normal(&mut self) -> f32 { - (0..12) - .map(|_| (self.next() >> 8) as f32 / 16_777_216.0) - .sum::() - - 6.0 + (0..12).map(|_| (self.next() >> 8) as f32 / 16_777_216.0).sum::() - 6.0 } } @@ -54,18 +48,11 @@ pub(super) fn download(b: &DeviceBuffer<'_>, len: usize) -> Vec { all } pub(super) fn f32s(bytes: &[u8]) -> Vec { - bytes - .chunks_exact(4) - .map(|c| f32::from_le_bytes(c.try_into().unwrap())) - .collect() + bytes.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect() } pub(super) fn open<'c>(ctx: &'c Context<'c>, program: Program) -> ClosedKernels<'c> { - ClosedKernels::open(ctx, program).unwrap_or_else(|e| { - panic!( - "{} open failed ({e}); TODO-ROOT: build PTX and freeze the pin", - program.name() - ) - }) + ClosedKernels::open(ctx, program) + .unwrap_or_else(|e| panic!("{} open failed ({e}); TODO-ROOT: build PTX and freeze the pin", program.name())) } pub(super) fn zero_kv<'c>(ctx: &'c Context<'c>) -> DeviceBuffer<'c> { @@ -73,16 +60,8 @@ pub(super) fn zero_kv<'c>(ctx: &'c Context<'c>) -> DeviceBuffer<'c> { } pub(super) fn json_bytes(v: &serde_json::Value) -> Vec { - v.as_array() - .unwrap() - .iter() - .map(|x| x.as_u64().unwrap() as u8) - .collect() + v.as_array().unwrap().iter().map(|x| x.as_u64().unwrap() as u8).collect() } pub(super) fn json_f32(v: &serde_json::Value) -> Vec { - v.as_array() - .unwrap() - .iter() - .map(|x| x.as_f64().unwrap() as f32) - .collect() + v.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32).collect() } diff --git a/crates/cuda-driver/src/command_profile.rs b/crates/cuda-driver/src/command_profile.rs index 3c50220f..a60b15a7 100644 --- a/crates/cuda-driver/src/command_profile.rs +++ b/crates/cuda-driver/src/command_profile.rs @@ -9,9 +9,7 @@ static TOTALS: Mutex> = /// Whether per-command timing is on (both switches set). pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some() - }) + *ON.get_or_init(|| crate::bringup_trace_enabled() && std::env::var_os("LELEKA_PREFILL_PROFILE_SYNC").is_some()) } pub(crate) fn add(producer: &'static str, index: usize, label: &'static str, elapsed: Duration) { if let Ok(mut totals) = TOTALS.lock() { diff --git a/crates/cuda-driver/src/compute_drain.rs b/crates/cuda-driver/src/compute_drain.rs index 73ae33e6..8d532cd6 100644 --- a/crates/cuda-driver/src/compute_drain.rs +++ b/crates/cuda-driver/src/compute_drain.rs @@ -13,7 +13,6 @@ use std::sync::atomic::{AtomicUsize, Ordering}; static STREAMS: Mutex> = Mutex::new(Vec::new()); static BACKGROUND: AtomicUsize = AtomicUsize::new(0); - pub(crate) fn register(stream: usize) { if stream == 0 { return; diff --git a/crates/cuda-driver/src/deferred_status.rs b/crates/cuda-driver/src/deferred_status.rs index df5b135c..9852e1dd 100644 --- a/crates/cuda-driver/src/deferred_status.rs +++ b/crates/cuda-driver/src/deferred_status.rs @@ -56,7 +56,10 @@ pub(crate) fn enabled() -> bool { #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod device { use super::evaluate; - use crate::ffi::{BufferHandle, deferred_status::{Api, HostBuffer}}; + use crate::ffi::{ + BufferHandle, + deferred_status::{Api, HostBuffer}, + }; use crate::{Context, Error, Result}; use std::cell::RefCell; use std::collections::VecDeque; @@ -111,10 +114,19 @@ mod device { } /// Step 1 of a deferred run: zero the status words, stream ordered. - pub(crate) fn begin(context: &Context<'_>, status: BufferHandle, bytes: usize, stream: usize, slot_bytes: usize) -> Result<()> { + pub(crate) fn begin( + context: &Context<'_>, + status: BufferHandle, + bytes: usize, + stream: usize, + slot_bytes: usize, + ) -> Result<()> { STATE.with(|cell| { let mut guard = cell.borrow_mut(); - if guard.as_ref().is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) { + if guard + .as_ref() + .is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) + { if guard.as_ref().is_some_and(|s| !s.live.is_empty()) { return Err(Error::ContextMismatch); } @@ -152,7 +164,13 @@ mod device { for other in crate::compute_drain::streams_except(stream) { st.api.wait_stream(other, slot.event)?; } - st.live.push_back(Check { slot: slot_index, bytes, stride, order: order.to_vec(), labels: labels.to_vec() }); + st.live.push_back(Check { + slot: slot_index, + bytes, + stride, + order: order.to_vec(), + labels: labels.to_vec(), + }); Ok(()) }) } @@ -189,14 +207,26 @@ mod device { #[allow(unused_imports)] pub(crate) use device::{begin, finish, pending, resolve}; -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] mod unsupported { use crate::ffi::BufferHandle; use crate::{Context, Error, Result}; pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn finish(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize, _: &[usize], _: &[&'static str]) -> Result<()> { + pub(crate) fn finish( + _: &Context<'_>, + _: BufferHandle, + _: usize, + _: usize, + _: usize, + _: &[usize], + _: &[&'static str], + ) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn resolve(_: &Context<'_>) -> Result<()> { @@ -206,10 +236,19 @@ mod unsupported { 0 } } -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] pub(crate) use unsupported::{begin, finish, pending, resolve}; -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] #[path = "deferred_status_gpu.rs"] mod gpu_tests; diff --git a/crates/cuda-driver/src/deferred_status_ffi.rs b/crates/cuda-driver/src/deferred_status_ffi.rs index 7ba079a8..e4ea8ea5 100644 --- a/crates/cuda-driver/src/deferred_status_ffi.rs +++ b/crates/cuda-driver/src/deferred_status_ffi.rs @@ -148,13 +148,21 @@ impl Api { // SAFETY: validated extent of a live allocation of the current context; stream handle of the same context. check("cuMemsetD8Async", unsafe { (self.memset)(buffer.0, 0, bytes, stream as Handle) }) } - pub(crate) fn read_async(&self, host: &HostBuffer, source: BufferHandle, bytes: usize, stream: usize) -> Result<()> { + pub(crate) fn read_async( + &self, + host: &HostBuffer, + source: BufferHandle, + bytes: usize, + stream: usize, + ) -> Result<()> { if bytes == 0 || bytes > host.bytes { return Err(Error::InvalidSize); } source.validate_extent(bytes)?; // SAFETY: pinned destination of at least `bytes`, validated device extent, same-context stream; the caller keeps both // alive and does not read or reuse the host buffer before the event recorded after this copy has completed. - check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) }) + check("cuMemcpyDtoHAsync_v2", unsafe { + (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) + }) } } diff --git a/crates/cuda-driver/src/device_arena.rs b/crates/cuda-driver/src/device_arena.rs index 39b4c74f..51cca18b 100644 --- a/crates/cuda-driver/src/device_arena.rs +++ b/crates/cuda-driver/src/device_arena.rs @@ -96,7 +96,9 @@ pub fn min_compute_capability(experimental_sm60: bool) -> (u32, &'static str) { pub fn check_compute_capability(name: &str, major: u32, minor: u32, experimental_sm60: bool) -> Result<(), String> { let (min, need) = min_compute_capability(experimental_sm60); if major * 10 + minor < min { - return Err(format!("device {name} reports compute capability {major}.{minor}; Strata needs compute capability {need}")); + return Err(format!( + "device {name} reports compute capability {major}.{minor}; Strata needs compute capability {need}" + )); } Ok(()) } @@ -117,10 +119,13 @@ mod tests { assert_eq!(big[0], PoisonLaunch { float_offset: 0, blocks: (3u64 << 30).div_ceil(256), n_floats: 3u64 << 30 }); // the slicing with a small max: 1000 floats -> 4 blocks, max 3 -> two launches let l = poison_launches(4000, 3); - assert_eq!(l, vec![ - PoisonLaunch { float_offset: 0, blocks: 3, n_floats: 1000 }, - PoisonLaunch { float_offset: 768, blocks: 1, n_floats: 232 }, - ]); + assert_eq!( + l, + vec![ + PoisonLaunch { float_offset: 0, blocks: 3, n_floats: 1000 }, + PoisonLaunch { float_offset: 768, blocks: 1, n_floats: 232 }, + ] + ); assert!(poison_launches(0, 3).is_empty()); assert!(poison_launches(3, 3).is_empty(), "less than one float is nothing to poison"); } @@ -138,15 +143,18 @@ mod tests { #[test] fn golden_poison_executed_on_the_host_shim_matches_the_model() { - let g: serde_json::Value = serde_json::from_str(include_str!("../oracle/fixtures/misc_kernels_golden.json")).unwrap(); + let g: serde_json::Value = + serde_json::from_str(include_str!("../oracle/fixtures/misc_kernels_golden.json")).unwrap(); let p = &g["poison"]; - let (bytes, words, max_blocks) = (p["bytes"].as_u64().unwrap(), p["words"].as_u64().unwrap() as usize, p["max_blocks"].as_u64().unwrap()); + let (bytes, words, max_blocks) = + (p["bytes"].as_u64().unwrap(), p["words"].as_u64().unwrap() as usize, p["max_blocks"].as_u64().unwrap()); let mut mem = vec![0xdead_beefu32; words]; for launch in poison_launches(bytes, max_blocks) { poison_model(&mut mem, &launch); } let raw: Vec = mem.iter().flat_map(|w| w.to_le_bytes()).collect(); - let fnv = raw.iter().fold(1_469_598_103_934_665_603u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211)); + let fnv = + raw.iter().fold(1_469_598_103_934_665_603u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211)); assert_eq!(format!("{fnv:x}"), p["hash"].as_str().unwrap()); } @@ -161,7 +169,10 @@ mod tests { assert!(a.alloc(8, 3).unwrap_err().contains("power of two")); assert!(a.alloc(8, 0).unwrap_err().contains("power of two")); let err = a.alloc(700, 8).unwrap_err(); - assert_eq!(err, "DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - the plan from P1.S9 did not close"); + assert_eq!( + err, + "DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - the plan from P1.S9 did not close" + ); assert_eq!(a.used(), 369, "a refused allocation leaves the arena untouched"); assert!(a.alloc(u64::MAX, 8).is_err()); assert_eq!(DeviceArenaPlan::new(0).unwrap_err(), "DeviceArena of 0 bytes"); diff --git a/crates/cuda-driver/src/device_slab.rs b/crates/cuda-driver/src/device_slab.rs index ea82950a..12091459 100644 --- a/crates/cuda-driver/src/device_slab.rs +++ b/crates/cuda-driver/src/device_slab.rs @@ -121,7 +121,10 @@ pub struct DeviceSlice<'ctx> { enum SliceBacking<'ctx> { Own(DeviceBuffer<'ctx>), /// `view` is a borrowed alias of a range of `slab` (dropping it frees nothing); `slab` keeps the memory alive. - Carved { slab: Rc>, view: DeviceBuffer<'ctx> }, + Carved { + slab: Rc>, + view: DeviceBuffer<'ctx>, + }, } impl<'ctx> DeviceSlice<'ctx> { @@ -237,7 +240,13 @@ impl<'ctx> DeviceBuffer<'ctx> { /// alive for as long as the alias is used: [`DeviceSlice`] holds the slab for it. pub(crate) fn view(&self, offset: usize, len: usize) -> Result> { let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, len)?; - Ok(DeviceBuffer { context: self.context, handle: Some(handle), bytes: len, _thread: std::marker::PhantomData, borrowed: true }) + Ok(DeviceBuffer { + context: self.context, + handle: Some(handle), + bytes: len, + _thread: std::marker::PhantomData, + borrowed: true, + }) } } diff --git a/crates/cuda-driver/src/device_slab/tests.rs b/crates/cuda-driver/src/device_slab/tests.rs index bb7a7ed8..129e2abe 100644 --- a/crates/cuda-driver/src/device_slab/tests.rs +++ b/crates/cuda-driver/src/device_slab/tests.rs @@ -110,7 +110,18 @@ fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_e sizes.extend([6_600_000, 3_300_000, 3_300_000, 10_240, 10_240, 4096, 4096, 4096, 4096]); } for _ in 0..12 { - sizes.extend([4_900_000, 1_400_000, 1_400_000, 2_600_000, 650_000, 4_900_000, 2560 * 4, 2560 * 4, 2560 * 4, 2560 * 4]); + sizes.extend([ + 4_900_000, + 1_400_000, + 1_400_000, + 2_600_000, + 650_000, + 4_900_000, + 2560 * 4, + 2560 * 4, + 2560 * 4, + 2560 * 4, + ]); } sizes.extend(std::iter::repeat_n(5 * MIB / 2, 48)); sizes.extend(std::iter::repeat_n(330_000, 97 * 3)); diff --git a/crates/cuda-driver/src/experimental.rs b/crates/cuda-driver/src/experimental.rs index 5190cea9..eedc9922 100644 --- a/crates/cuda-driver/src/experimental.rs +++ b/crates/cuda-driver/src/experimental.rs @@ -106,62 +106,62 @@ pub struct PtxPin { pub const PINS: [PtxPin; 6] = [ PtxPin { source_sha256: [ - 75, 46, 214, 128, 8, 243, 170, 135, 173, 241, 68, 92, 96, 139, 174, 228, 67, 154, 12, - 164, 18, 19, 172, 46, 40, 10, 112, 232, 132, 72, 180, 32, + 75, 46, 214, 128, 8, 243, 170, 135, 173, 241, 68, 92, 96, 139, 174, 228, 67, 154, 12, 164, 18, 19, 172, 46, + 40, 10, 112, 232, 132, 72, 180, 32, ], ptx_sha256: [ - 116, 102, 91, 1, 111, 222, 157, 196, 245, 10, 54, 230, 44, 191, 46, 87, 140, 115, 94, - 72, 227, 190, 81, 183, 7, 52, 233, 229, 57, 66, 205, 231, + 116, 102, 91, 1, 111, 222, 157, 196, 245, 10, 54, 230, 44, 191, 46, 87, 140, 115, 94, 72, 227, 190, 81, + 183, 7, 52, 233, 229, 57, 66, 205, 231, ], }, PtxPin { source_sha256: [ - 147, 164, 86, 148, 37, 12, 28, 154, 190, 203, 55, 41, 64, 186, 82, 225, 88, 136, 123, - 203, 234, 88, 19, 50, 21, 145, 14, 38, 169, 106, 113, 116, + 147, 164, 86, 148, 37, 12, 28, 154, 190, 203, 55, 41, 64, 186, 82, 225, 88, 136, 123, 203, 234, 88, 19, 50, + 21, 145, 14, 38, 169, 106, 113, 116, ], ptx_sha256: [ - 67, 195, 8, 150, 8, 48, 131, 62, 41, 50, 153, 7, 226, 123, 229, 32, 62, 243, 188, 137, - 204, 125, 10, 145, 118, 39, 13, 193, 135, 50, 214, 0, + 67, 195, 8, 150, 8, 48, 131, 62, 41, 50, 153, 7, 226, 123, 229, 32, 62, 243, 188, 137, 204, 125, 10, 145, + 118, 39, 13, 193, 135, 50, 214, 0, ], }, PtxPin { source_sha256: [ - 171, 135, 59, 249, 57, 245, 35, 80, 35, 221, 146, 215, 6, 200, 129, 74, 183, 143, 149, - 90, 177, 94, 18, 147, 184, 224, 185, 108, 170, 92, 193, 83, + 171, 135, 59, 249, 57, 245, 35, 80, 35, 221, 146, 215, 6, 200, 129, 74, 183, 143, 149, 90, 177, 94, 18, + 147, 184, 224, 185, 108, 170, 92, 193, 83, ], ptx_sha256: [ - 79, 113, 231, 32, 224, 202, 149, 13, 50, 27, 163, 203, 178, 0, 130, 202, 71, 62, 152, - 57, 183, 109, 8, 137, 142, 149, 182, 98, 59, 255, 254, 80, + 79, 113, 231, 32, 224, 202, 149, 13, 50, 27, 163, 203, 178, 0, 130, 202, 71, 62, 152, 57, 183, 109, 8, 137, + 142, 149, 182, 98, 59, 255, 254, 80, ], }, PtxPin { source_sha256: [ - 119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86, - 205, 252, 94, 66, 17, 8, 109, 46, 240, 134, 113, 197, + 119, 197, 14, 91, 175, 248, 66, 227, 31, 13, 113, 98, 74, 87, 6, 244, 110, 215, 74, 86, 205, 252, 94, 66, + 17, 8, 109, 46, 240, 134, 113, 197, ], ptx_sha256: [ - 26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178, - 134, 160, 43, 126, 90, 253, 250, 57, 172, 173, 170, 51, 230, + 26, 184, 184, 21, 110, 140, 130, 65, 49, 192, 12, 236, 218, 23, 127, 229, 125, 116, 178, 134, 160, 43, 126, + 90, 253, 250, 57, 172, 173, 170, 51, 230, ], }, PtxPin { source_sha256: [ - 198, 93, 153, 26, 217, 254, 112, 1, 1, 206, 1, 42, 128, 201, 79, 199, 222, 88, 33, 23, - 250, 227, 87, 197, 238, 168, 149, 67, 112, 25, 93, 143, + 198, 93, 153, 26, 217, 254, 112, 1, 1, 206, 1, 42, 128, 201, 79, 199, 222, 88, 33, 23, 250, 227, 87, 197, + 238, 168, 149, 67, 112, 25, 93, 143, ], ptx_sha256: [ - 86, 35, 165, 174, 155, 46, 189, 47, 160, 16, 195, 52, 54, 127, 252, 84, 135, 154, 198, - 223, 118, 174, 240, 131, 129, 219, 211, 43, 15, 126, 243, 17, + 86, 35, 165, 174, 155, 46, 189, 47, 160, 16, 195, 52, 54, 127, 252, 84, 135, 154, 198, 223, 118, 174, 240, + 131, 129, 219, 211, 43, 15, 126, 243, 17, ], }, PtxPin { source_sha256: [ - 212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73, - 193, 72, 151, 224, 186, 193, 88, 220, 212, 202, 53, 110, + 212, 254, 34, 27, 17, 86, 157, 183, 50, 71, 100, 75, 183, 145, 24, 179, 77, 4, 11, 73, 193, 72, 151, 224, + 186, 193, 88, 220, 212, 202, 53, 110, ], ptx_sha256: [ - 25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98, - 180, 114, 102, 60, 0, 209, 137, 65, 49, 59, 250, 62, 188, + 25, 58, 221, 92, 180, 72, 245, 225, 147, 242, 15, 242, 72, 202, 68, 89, 171, 185, 98, 180, 114, 102, 60, 0, + 209, 137, 65, 49, 59, 250, 62, 188, ], }, ]; @@ -171,12 +171,7 @@ pub const PINS: [PtxPin; 6] = [ /// previous source, so [`admit`] refuses them. The server-side reseal (nvcc 13.2.86, group `experimental`, /// `scripts/gpu-bringup/reseal_own.py --plan docs/cuda-seal-plan-additions-experimental.json`) refreshes both pin /// fields and empties this list; the unit test `pending_reseal_lists_exactly_the_unsealed_sources` forces that. -pub const PENDING_RESEAL: &[Program] = &[ - Program::KvQ4, - Program::KvQ8, - Program::KvStream, - Program::QsaAttn, -]; +pub const PENDING_RESEAL: &[Program] = &[Program::KvQ4, Program::KvQ8, Program::KvStream, Program::QsaAttn]; // ------------------------------------------------------------------------------------- entry signatures @@ -208,26 +203,10 @@ pub const Q4_APPEND_STEP: usize = 1; pub const Q4_APPEND_BATCH: usize = 2; pub const Q4_GATHER_STEP: usize = 3; pub static KV_Q4_ENTRIES: [Entry; 4] = [ - Entry { - name: c"leleka_fwht256_f32", - block: [32, 4, 1], - args: &[P, P, L], - }, - Entry { - name: c"leleka_kv_append_q4_step", - block: [32, 1, 1], - args: &[P, P, P, P, P, P, I, I, I, N, N], - }, - Entry { - name: c"leleka_kv_append_q4_batch", - block: [32, 1, 1], - args: &[P, P, P, L, P, P, I, I, I, I, N, N, N, N], - }, - Entry { - name: c"leleka_kv_gather_q4_step", - block: [32, 4, 1], - args: &[P, P, P, P, P, I, I, I, P, P], - }, + Entry { name: c"leleka_fwht256_f32", block: [32, 4, 1], args: &[P, P, L] }, + Entry { name: c"leleka_kv_append_q4_step", block: [32, 1, 1], args: &[P, P, P, P, P, P, I, I, I, N, N] }, + Entry { name: c"leleka_kv_append_q4_batch", block: [32, 1, 1], args: &[P, P, P, L, P, P, I, I, I, I, N, N, N, N] }, + Entry { name: c"leleka_kv_gather_q4_step", block: [32, 4, 1], args: &[P, P, P, P, P, I, I, I, P, P] }, ]; pub const Q8_APPEND_STEP: usize = 0; @@ -238,11 +217,7 @@ pub static KV_Q8_ENTRIES: [Entry; 2] = [ block: [64, 1, 1], args: &[N, P, N, P, P, P, N, P, I, I, I, N, N, N, N], }, - Entry { - name: c"leleka_kv_gather_q8_step", - block: [256, 1, 1], - args: &[P, P, P, P, P, P, P, I, I, I, P, P], - }, + Entry { name: c"leleka_kv_gather_q8_step", block: [256, 1, 1], args: &[P, P, P, P, P, P, P, I, I, I, P, P] }, ]; pub const STREAM_RESET: usize = 0; @@ -251,50 +226,27 @@ pub const STREAM_COPY: usize = 2; pub const RING_TABLE: usize = 3; pub const COPY_U4: usize = 4; pub static KV_STREAM_ENTRIES: [Entry; 5] = [ - Entry { - name: c"leleka_kv_stream_reset", - block: [256, 1, 1], - args: &[P, P, P, P, P, L, L], - }, - Entry { - name: c"leleka_kv_stream_resolve", - block: [1024, 1, 1], - args: &[P, P, P, P, P, P, P, L, P, P, I, I, I], - }, + Entry { name: c"leleka_kv_stream_reset", block: [256, 1, 1], args: &[P, P, P, P, P, L, L] }, + Entry { name: c"leleka_kv_stream_resolve", block: [1024, 1, 1], args: &[P, P, P, P, P, P, P, L, P, P, I, I, I] }, Entry { name: c"leleka_kv_stream_copy", block: [128, 1, 1], args: &[P, P, P, P, N, N, N, P, N, N, N, I, I, I, I, I], }, - Entry { - name: c"leleka_kv_ring_table", - block: [256, 1, 1], - args: &[P, L, L], - }, - Entry { - name: c"leleka_kv_copy_u4", - block: [128, 1, 1], - args: &[P, P, L], - }, + Entry { name: c"leleka_kv_ring_table", block: [256, 1, 1], args: &[P, L, L] }, + Entry { name: c"leleka_kv_copy_u4", block: [128, 1, 1], args: &[P, P, L] }, ]; pub const KEYLESS_ROUTE: usize = 0; -pub static KEYLESS_ENTRIES: [Entry; 1] = [Entry { - name: c"leleka_keyless_route_query", - block: [256, 1, 1], - args: &[P, P, I], -}]; +pub static KEYLESS_ENTRIES: [Entry; 1] = + [Entry { name: c"leleka_keyless_route_query", block: [256, 1, 1], args: &[P, P, I] }]; pub const ATTN_CHUNK_M2: usize = 0; pub const ATTN_CHUNK_M3: usize = 1; pub const ATTN_CHUNK_M4: usize = 2; pub const ATTN_MERGE: usize = 3; pub static QSA_ATTN_ENTRIES: [Entry; 4] = [ - Entry { - name: c"leleka_qsa_attn_chunk_m2", - block: [256, 1, 1], - args: &[P, P, P, P, P, P, I, I, P, P, P, I, I, L], - }, + Entry { name: c"leleka_qsa_attn_chunk_m2", block: [256, 1, 1], args: &[P, P, P, P, P, P, I, I, P, P, P, I, I, L] }, Entry { name: c"leleka_qsa_attn_chunk_m3", block: [256, 1, 1], @@ -305,19 +257,12 @@ pub static QSA_ATTN_ENTRIES: [Entry; 4] = [ block: [256, 1, 1], args: &[P, P, P, P, P, P, N, I, P, P, I, I, P, P, P, I, I, L], }, - Entry { - name: c"leleka_qsa_attn_merge", - block: [256, 1, 1], - args: &[P, P, P, I, P, L], - }, + Entry { name: c"leleka_qsa_attn_merge", block: [256, 1, 1], args: &[P, P, P, I, P, L] }, ]; pub const CVEC_APPLY: usize = 0; -pub static CVEC_ENTRIES: [Entry; 1] = [Entry { - name: c"leleka_cvec_apply", - block: [256, 1, 1], - args: &[P, P, P, P, I, L, I, I, L, N, L, N, L, I], -}]; +pub static CVEC_ENTRIES: [Entry; 1] = + [Entry { name: c"leleka_cvec_apply", block: [256, 1, 1], args: &[P, P, P, P, I, L, I, I, L, N, L, N, L, I] }]; #[allow(dead_code)] const _: Arg = F; // `F32` arguments exist in the ABI (the attention scale is a compile-time constant here) @@ -361,47 +306,47 @@ mod tests; mod impl_mode; #[allow(unused_imports)] -pub(crate) use impl_mode::invalid; +pub use impl_mode::admit; #[allow(unused_imports)] pub use impl_mode::admit_ptx; #[allow(unused_imports)] -pub use impl_mode::source_is_sealed; -#[allow(unused_imports)] -pub use impl_mode::admit; -#[allow(unused_imports)] use impl_mode::grid_x; #[allow(unused_imports)] use impl_mode::grid_yz; +#[allow(unused_imports)] +pub(crate) use impl_mode::invalid; +#[allow(unused_imports)] +pub use impl_mode::source_is_sealed; mod impl_kvshape; #[allow(unused_imports)] -pub use impl_kvshape::fwht_grid; -#[allow(unused_imports)] -pub use impl_kvshape::fwht_bytes; -#[allow(unused_imports)] -pub use impl_kvshape::q4_step_grid; -#[allow(unused_imports)] -pub use impl_kvshape::q4_batch_grid; -#[allow(unused_imports)] -pub use impl_kvshape::q4_gather_grid; -#[allow(unused_imports)] -pub use impl_kvshape::q8_step_grid; -#[allow(unused_imports)] -pub use impl_kvshape::q8_gather_grid; -#[allow(unused_imports)] -pub use impl_kvshape::copy_u4_grid; -#[allow(unused_imports)] -pub use impl_kvshape::check_stream_resolve; -#[allow(unused_imports)] -use impl_kvshape::stream_error_text; -#[allow(unused_imports)] -pub use impl_kvshape::keyless_grid; -#[allow(unused_imports)] -pub use impl_kvshape::keyless_matrices_bytes; -#[allow(unused_imports)] -pub use impl_kvshape::cvec_grid; -#[allow(unused_imports)] pub use impl_kvshape::attn_chunk_grid; #[allow(unused_imports)] pub use impl_kvshape::attn_merge_grid; #[allow(unused_imports)] pub use impl_kvshape::attn_scratch_floats; +#[allow(unused_imports)] +pub use impl_kvshape::check_stream_resolve; +#[allow(unused_imports)] +pub use impl_kvshape::copy_u4_grid; +#[allow(unused_imports)] +pub use impl_kvshape::cvec_grid; +#[allow(unused_imports)] +pub use impl_kvshape::fwht_bytes; +#[allow(unused_imports)] +pub use impl_kvshape::fwht_grid; +#[allow(unused_imports)] +pub use impl_kvshape::keyless_grid; +#[allow(unused_imports)] +pub use impl_kvshape::keyless_matrices_bytes; +#[allow(unused_imports)] +pub use impl_kvshape::q4_batch_grid; +#[allow(unused_imports)] +pub use impl_kvshape::q4_gather_grid; +#[allow(unused_imports)] +pub use impl_kvshape::q4_step_grid; +#[allow(unused_imports)] +pub use impl_kvshape::q8_gather_grid; +#[allow(unused_imports)] +pub use impl_kvshape::q8_step_grid; +#[allow(unused_imports)] +use impl_kvshape::stream_error_text; diff --git a/crates/cuda-driver/src/experimental/impl_kvshape.rs b/crates/cuda-driver/src/experimental/impl_kvshape.rs index 5367b205..760f0dd3 100644 --- a/crates/cuda-driver/src/experimental/impl_kvshape.rs +++ b/crates/cuda-driver/src/experimental/impl_kvshape.rs @@ -3,14 +3,9 @@ #[allow(unused_imports)] use super::*; - impl KvShape { pub const fn real() -> Self { - Self { - kv_heads: 2, - head_dim: 256, - page_size: 4, - } + Self { kv_heads: 2, head_dim: 256, page_size: 4 } } pub fn as_qsa(&self) -> QsaShapes { let mut s = QsaShapes::real(); @@ -24,8 +19,7 @@ impl KvShape { if self.kv_heads == 0 || self.page_size == 0 || self.head_dim == 0 { return invalid("KV shape needs positive heads, head_dim and page_size"); } - if u64::from(self.kv_heads) > MAX_GRID_YZ || self.page_size > 1 << 20 || self.kv_heads > 64 - { + if u64::from(self.kv_heads) > MAX_GRID_YZ || self.page_size > 1 << 20 || self.kv_heads > 64 { return invalid("KV shape is beyond the closed programs' limits"); } Ok(()) @@ -85,25 +79,16 @@ pub fn q4_step_grid(shape: &KvShape) -> Result { } pub fn q4_batch_grid(tokens: u64, shape: &KvShape) -> Result { shape.check_q4()?; - Ok([ - grid_x(tokens)?, - shape.kv_heads, - shape.head_dim / q4_0::QK4_0 as u32, - ]) + Ok([grid_x(tokens)?, shape.kv_heads, shape.head_dim / q4_0::QK4_0 as u32]) } pub fn q4_gather_grid(max_ids: u64, shape: &KvShape) -> Result { shape.check_q4()?; - let blocks = - max_ids * u64::from(shape.kv_heads) * u64::from(shape.head_dim / q4_0::QK4_0 as u32); + let blocks = max_ids * u64::from(shape.kv_heads) * u64::from(shape.head_dim / q4_0::QK4_0 as u32); Ok([grid_x(blocks.div_ceil(4))?, 1, 1]) } pub fn q8_step_grid(shape: &KvShape, with_keys: bool) -> Result { shape.check_q8()?; - Ok([ - shape.kv_heads, - shape.head_dim / kv_q8::KV_Q8_GROUP as u32, - if with_keys { 2 } else { 1 }, - ]) + Ok([shape.kv_heads, shape.head_dim / kv_q8::KV_Q8_GROUP as u32, if with_keys { 2 } else { 1 }]) } pub fn q8_gather_grid(max_ids: u64, shape: &KvShape) -> Result { shape.check_q8()?; @@ -125,13 +110,8 @@ pub fn check_stream_resolve(shape: &KvShape, n_slots: u64, n_q: u64, cap: u64) - if n_slots > i32::MAX as u64 { return invalid("streaming resolve has too many slots"); } - leleka_experimental_ref::kv_stream::check_resolve( - &shape.as_qsa(), - n_slots as i64, - n_q as i64, - cap as i64, - ) - .map_err(|e| ExperimentalError::Invalid(stream_error_text(e))) + leleka_experimental_ref::kv_stream::check_resolve(&shape.as_qsa(), n_slots as i64, n_q as i64, cap as i64) + .map_err(|e| ExperimentalError::Invalid(stream_error_text(e))) } pub(super) fn stream_error_text(e: leleka_experimental_ref::kv_stream::StreamError) -> &'static str { use leleka_experimental_ref::kv_stream::StreamError as E; @@ -171,11 +151,7 @@ pub fn attn_chunk_grid(cap: u64, shape: &KvShape, n_q: u64) -> Result { if cap == 0 || cap > i32::MAX as u64 || n_q == 0 || n_q > MAX_GRID_YZ { return invalid("attention needs a positive cap and 1..=65535 queries"); } - Ok([ - grid_x(cap.div_ceil(leleka_experimental_ref::attn::CHUNK as u64))?, - shape.kv_heads, - n_q as u32, - ]) + Ok([grid_x(cap.div_ceil(leleka_experimental_ref::attn::CHUNK as u64))?, shape.kv_heads, n_q as u32]) } pub fn attn_merge_grid(shape: &KvShape, n_q: u64) -> Result { shape.check_attn()?; diff --git a/crates/cuda-driver/src/experimental/impl_mode.rs b/crates/cuda-driver/src/experimental/impl_mode.rs index 8693da29..ea391894 100644 --- a/crates/cuda-driver/src/experimental/impl_mode.rs +++ b/crates/cuda-driver/src/experimental/impl_mode.rs @@ -3,16 +3,9 @@ #[allow(unused_imports)] use super::*; - impl Mode { - pub const ALL: [Mode; 6] = [ - Mode::KvQ40, - Mode::KvK8V4, - Mode::KvRotatedInt8, - Mode::KeylessVOnly, - Mode::KvStreamed, - Mode::ControlVectors, - ]; + pub const ALL: [Mode; 6] = + [Mode::KvQ40, Mode::KvK8V4, Mode::KvRotatedInt8, Mode::KeylessVOnly, Mode::KvStreamed, Mode::ControlVectors]; pub const fn name(self) -> &'static str { match self { Self::KvQ40 => "kv-q4_0", @@ -54,14 +47,8 @@ impl OptIn { } impl Program { - pub const ALL: [Program; 6] = [ - Program::KvQ4, - Program::KvQ8, - Program::KvStream, - Program::Keyless, - Program::QsaAttn, - Program::Cvec, - ]; + pub const ALL: [Program; 6] = + [Program::KvQ4, Program::KvQ8, Program::KvStream, Program::Keyless, Program::QsaAttn, Program::Cvec]; pub const fn name(self) -> &'static str { match self { Self::KvQ4 => "kv_q4", @@ -122,10 +109,9 @@ impl fmt::Display for ExperimentalError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Invalid(message) => f.write_str(message), - Self::NotEnabled(program) => write!( - f, - "experimental program {program} is off: enable one of its modes explicitly" - ), + Self::NotEnabled(program) => { + write!(f, "experimental program {program} is off: enable one of its modes explicitly") + } Self::Unpinned(program) => write!( f, "experimental program {program} PTX is not pinned for its checked-in source (TODO-ROOT: pin zero, PTX bytes or source digest differ)" @@ -150,11 +136,7 @@ pub fn admit_ptx(program: Program, ptx: &'static [u8], pin: &PtxPin) -> Result<( if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] { return Err(refuse); } - if ptx.len() < 2 - || ptx.last() != Some(&0) - || ptx[..ptx.len() - 1].contains(&0) - || !ptx.is_ascii() - { + if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() { return Err(refuse); } if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 { diff --git a/crates/cuda-driver/src/experimental/tests.rs b/crates/cuda-driver/src/experimental/tests.rs index 1c4baa75..b03e0a4f 100644 --- a/crates/cuda-driver/src/experimental/tests.rs +++ b/crates/cuda-driver/src/experimental/tests.rs @@ -3,17 +3,10 @@ use super::*; fn count_params(source: &str, name: &str) -> (Vec<&'static str>, u32) { - let at = source - .find(&format!(" {name}(")) - .unwrap_or_else(|| panic!("{name} not in source")); + let at = source.find(&format!(" {name}(")).unwrap_or_else(|| panic!("{name} not in source")); let head = &source[..at]; - let decl = head - .rfind("extern \"C\" __global__") - .expect("extern C entry"); - let bounds = head[decl..] - .split("__launch_bounds__(") - .nth(1) - .expect("launch bounds"); + let decl = head.rfind("extern \"C\" __global__").expect("extern C entry"); + let bounds = head[decl..].split("__launch_bounds__(").nth(1).expect("launch bounds"); let threads: u32 = bounds.split(')').next().unwrap().trim().parse().unwrap(); let rest = &source[at + name.len() + 2..]; let close = rest.find(") {").expect("parameter list end"); @@ -55,11 +48,7 @@ fn every_entry_signature_matches_its_cuda_source() { }) .collect(); assert_eq!(kinds, want, "{name}"); - assert_eq!( - threads, - entry.block.iter().product::(), - "{name} launch bounds" - ); + assert_eq!(threads, entry.block.iter().product::(), "{name} launch bounds"); assert!(entry.args.len() <= MAX_ENTRY_ARGUMENTS, "{name}"); checked += 1; } @@ -72,37 +61,19 @@ fn index_constants_point_at_the_named_entries() { let n = |p: Program, i: usize| p.entries()[i].name.to_str().unwrap(); assert_eq!(n(Program::KvQ4, FWHT256), "leleka_fwht256_f32"); assert_eq!(n(Program::KvQ4, Q4_APPEND_STEP), "leleka_kv_append_q4_step"); - assert_eq!( - n(Program::KvQ4, Q4_APPEND_BATCH), - "leleka_kv_append_q4_batch" - ); + assert_eq!(n(Program::KvQ4, Q4_APPEND_BATCH), "leleka_kv_append_q4_batch"); assert_eq!(n(Program::KvQ4, Q4_GATHER_STEP), "leleka_kv_gather_q4_step"); assert_eq!(n(Program::KvQ8, Q8_APPEND_STEP), "leleka_kv_append_q8_step"); assert_eq!(n(Program::KvQ8, Q8_GATHER_STEP), "leleka_kv_gather_q8_step"); assert_eq!(n(Program::KvStream, STREAM_RESET), "leleka_kv_stream_reset"); - assert_eq!( - n(Program::KvStream, STREAM_RESOLVE), - "leleka_kv_stream_resolve" - ); + assert_eq!(n(Program::KvStream, STREAM_RESOLVE), "leleka_kv_stream_resolve"); assert_eq!(n(Program::KvStream, STREAM_COPY), "leleka_kv_stream_copy"); assert_eq!(n(Program::KvStream, RING_TABLE), "leleka_kv_ring_table"); assert_eq!(n(Program::KvStream, COPY_U4), "leleka_kv_copy_u4"); - assert_eq!( - n(Program::Keyless, KEYLESS_ROUTE), - "leleka_keyless_route_query" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M2), - "leleka_qsa_attn_chunk_m2" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M3), - "leleka_qsa_attn_chunk_m3" - ); - assert_eq!( - n(Program::QsaAttn, ATTN_CHUNK_M4), - "leleka_qsa_attn_chunk_m4" - ); + assert_eq!(n(Program::Keyless, KEYLESS_ROUTE), "leleka_keyless_route_query"); + assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M2), "leleka_qsa_attn_chunk_m2"); + assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M3), "leleka_qsa_attn_chunk_m3"); + assert_eq!(n(Program::QsaAttn, ATTN_CHUNK_M4), "leleka_qsa_attn_chunk_m4"); assert_eq!(n(Program::QsaAttn, ATTN_MERGE), "leleka_qsa_attn_merge"); assert_eq!(n(Program::Cvec, CVEC_APPLY), "leleka_cvec_apply"); } @@ -114,36 +85,18 @@ fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() { assert_eq!(none.digest_text(), ""); for program in Program::ALL { assert!(!none.enables(program)); - assert_eq!( - admit(program, &none), - Err(ExperimentalError::NotEnabled(program.name())) - ); + assert_eq!(admit(program, &none), Err(ExperimentalError::NotEnabled(program.name()))); assert!(!program.needed_by().is_empty()); } let q4 = OptIn::default().with(Mode::KvQ40); assert!(q4.enables(Program::KvQ4) && q4.enables(Program::QsaAttn)); - assert!( - !q4.enables(Program::KvStream) - && !q4.enables(Program::Cvec) - && !q4.enables(Program::KvQ8) - ); + assert!(!q4.enables(Program::KvStream) && !q4.enables(Program::Cvec) && !q4.enables(Program::KvQ8)); let k = OptIn::default().with(Mode::KeylessVOnly); - assert!( - k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4) - ); - assert_eq!( - OptIn::default() - .with(Mode::KvStreamed) - .with(Mode::KvQ40) - .digest_text(), - "kv-q4_0,kv-streamed" - ); + assert!(k.enables(Program::Keyless) && k.enables(Program::KvQ8) && !k.enables(Program::KvQ4)); + assert_eq!(OptIn::default().with(Mode::KvStreamed).with(Mode::KvQ40).digest_text(), "kv-q4_0,kv-streamed"); // every mode reaches at least one program, and the names are unique for mode in Mode::ALL { - assert!( - Program::ALL.iter().any(|p| p.needed_by().contains(&mode)), - "{mode:?}" - ); + assert!(Program::ALL.iter().any(|p| p.needed_by().contains(&mode)), "{mode:?}"); } let names: std::collections::BTreeSet<_> = Mode::ALL.iter().map(|m| m.name()).collect(); assert_eq!(names.len(), Mode::ALL.len()); @@ -152,8 +105,8 @@ fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() { #[test] fn sealed_assets_match_their_pins_and_export_every_entry() { use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, + with_embedded_nul, without_terminator, }; let all = OptIn::NONE .with(Mode::KvQ40) @@ -173,17 +126,11 @@ fn sealed_assets_match_their_pins_and_export_every_entry() { assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open - let expected = if PENDING_RESEAL.contains(&program) { - Err(ExperimentalError::Unpinned(program.name())) - } else { - Ok(()) - }; + let expected = + if PENDING_RESEAL.contains(&program) { Err(ExperimentalError::Unpinned(program.name())) } else { Ok(()) }; assert_eq!(admit(program, &all), expected, "{}", program.name()); // the opt-in gate still comes first - assert_eq!( - admit(program, &OptIn::NONE), - Err(ExperimentalError::NotEnabled(program.name())) - ); + assert_eq!(admit(program, &OptIn::NONE), Err(ExperimentalError::NotEnabled(program.name()))); // the pin guard still refuses every deviation, on synthetic copies of the real PTX let refuse = Err(ExperimentalError::Unpinned(program.name())); assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); @@ -194,10 +141,7 @@ fn sealed_assets_match_their_pins_and_export_every_entry() { let mut wrong_digest = *pin; wrong_digest.ptx_sha256[0] ^= 1; assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [ - PtxPin { source_sha256: [0; 32], ..*pin }, - PtxPin { ptx_sha256: [0; 32], ..*pin }, - ] { + for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); } } @@ -214,11 +158,7 @@ fn pending_reseal_lists_exactly_the_unsealed_sources() { ); } for (i, program) in PENDING_RESEAL.iter().enumerate() { - assert!( - !PENDING_RESEAL[i + 1..].contains(program), - "{} listed twice", - program.name() - ); + assert!(!PENDING_RESEAL[i + 1..].contains(program), "{} listed twice", program.name()); } } @@ -235,48 +175,24 @@ fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(())); // ... but they were not built from the checked-in source: admit fails closed assert!(!source_is_sealed(program)); - assert_eq!( - admit(program, &all), - Err(ExperimentalError::Unpinned(program.name())) - ); + assert_eq!(admit(program, &all), Err(ExperimentalError::Unpinned(program.name()))); } } #[test] fn a_matching_pin_admits_and_any_difference_refuses() { static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]), - }; + let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]) }; assert_eq!(admit_ptx(Program::Cvec, GOOD, &pin), Ok(())); - let wrong = PtxPin { - ptx_sha256: [2; 32], - ..pin - }; - assert_eq!( - admit_ptx(Program::Cvec, GOOD, &wrong), - Err(ExperimentalError::Unpinned("cvec")) - ); - let half = PtxPin { - source_sha256: [0; 32], - ..pin - }; - assert_eq!( - admit_ptx(Program::Cvec, GOOD, &half), - Err(ExperimentalError::Unpinned("cvec")) - ); + let wrong = PtxPin { ptx_sha256: [2; 32], ..pin }; + assert_eq!(admit_ptx(Program::Cvec, GOOD, &wrong), Err(ExperimentalError::Unpinned("cvec"))); + let half = PtxPin { source_sha256: [0; 32], ..pin }; + assert_eq!(admit_ptx(Program::Cvec, GOOD, &half), Err(ExperimentalError::Unpinned("cvec"))); static NO_NUL: &[u8] = b".version 8.7\n"; - let p2 = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(NO_NUL), - }; + let p2 = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(NO_NUL) }; assert!(admit_ptx(Program::Cvec, NO_NUL, &p2).is_err()); static EMBEDDED: &[u8] = b"a\0b\0"; - let p3 = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(b"a\0b"), - }; + let p3 = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(b"a\0b") }; assert!(admit_ptx(Program::Cvec, EMBEDDED, &p3).is_err()); } @@ -313,11 +229,7 @@ fn kv_geometry_matches_the_originals_host_wrappers() { assert!(keyless_grid(0, 24).is_err()); assert_eq!(keyless_matrices_bytes(24), 24 * 65_536 * 4); assert_eq!(cvec_grid(4, 3, 2560), Ok([4, 3, 1])); - assert!( - cvec_grid(4, 3, 4097).is_err() - && cvec_grid(4, 3, 0).is_err() - && cvec_grid(0, 3, 2560).is_err() - ); + assert!(cvec_grid(4, 3, 4097).is_err() && cvec_grid(4, 3, 0).is_err() && cvec_grid(0, 3, 2560).is_err()); } #[test] @@ -335,17 +247,10 @@ fn byte_sizes_agree_with_the_reference_layouts() { let k8v4 = pool_arrays(KvFormat::K8V4, &q, pages); assert_eq!( (k8v4[0].bytes, k8v4[1].bytes, k8v4[2].bytes), - ( - s.q8_code_bytes(pages), - s.q8_scale_bytes(pages), - s.q4_bytes(pages) - ) + (s.q8_code_bytes(pages), s.q8_scale_bytes(pages), s.q4_bytes(pages)) ); // 576 B per cell and layer for Q4_0, one page = 4 cells - assert_eq!( - kv_pool_bytes(KvFormat::Q4_0, &q, pages), - pages * 4 * 576 + 64 - ); + assert_eq!(kv_pool_bytes(KvFormat::Q4_0, &q, pages), pages * 4 * 576 + 64); assert_eq!(s.q4_bytes(pages) * 2, pages * 4 * 576); assert_eq!(s.gather_scratch_bytes(2048), 2048 * 2 * 256 * 2); assert_eq!(attn_scratch_floats(2048, &s), 32 * 24 * 258 + 64); @@ -364,11 +269,7 @@ fn stream_resolve_guards_are_the_originals() { matches!(check_stream_resolve(&s, 1024, 8, 4096), Err(ExperimentalError::Invalid(m)) if m.contains("distinct blocks")) ); assert!(check_stream_resolve(&s, 5120, 0, 8).is_err()); - let misaligned = KvShape { - kv_heads: 1, - page_size: 1, - ..s - }; + let misaligned = KvShape { kv_heads: 1, page_size: 1, ..s }; assert!( matches!(check_stream_resolve(&misaligned, 5120, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("16 bytes")) ); diff --git a/crates/cuda-driver/src/experimental_gpu.rs b/crates/cuda-driver/src/experimental_gpu.rs index e337337d..2a6043d7 100644 --- a/crates/cuda-driver/src/experimental_gpu.rs +++ b/crates/cuda-driver/src/experimental_gpu.rs @@ -21,10 +21,10 @@ use crate::{ Context, DeviceBuffer, Error, combine, experimental::{ - self, ATTN_CHUNK_M2, ATTN_CHUNK_M3, ATTN_CHUNK_M4, ATTN_MERGE, Arg, COPY_U4, CVEC_APPLY, - Entry, ExperimentalError, FWHT256, KEYLESS_ROUTE, KvShape, LoadedProgram, OptIn, Program, - Q4_APPEND_BATCH, Q4_APPEND_STEP, Q4_GATHER_STEP, Q8_APPEND_STEP, Q8_GATHER_STEP, - RING_TABLE, Result, STEP_BYTES, STREAM_COPY, STREAM_RESET, STREAM_RESOLVE, admit, invalid, + self, ATTN_CHUNK_M2, ATTN_CHUNK_M3, ATTN_CHUNK_M4, ATTN_MERGE, Arg, COPY_U4, CVEC_APPLY, Entry, + ExperimentalError, FWHT256, KEYLESS_ROUTE, KvShape, LoadedProgram, OptIn, Program, Q4_APPEND_BATCH, + Q4_APPEND_STEP, Q4_GATHER_STEP, Q8_APPEND_STEP, Q8_GATHER_STEP, RING_TABLE, Result, STEP_BYTES, STREAM_COPY, + STREAM_RESET, STREAM_RESOLVE, admit, invalid, }, ffi, }; @@ -82,16 +82,9 @@ pub struct StreamMap<'b, 'c> { /// The pool arrays an experimental attention mode reads. pub enum AttnPools<'b, 'c> { /// Mode 2: Q4_0 keys and values. - Q4 { - k_q4: &'b DeviceBuffer<'c>, - v_q4: &'b DeviceBuffer<'c>, - }, + Q4 { k_q4: &'b DeviceBuffer<'c>, v_q4: &'b DeviceBuffer<'c> }, /// Mode 3: INT8 keys, Q4_0 values. - K8V4 { - k_q: &'b DeviceBuffer<'c>, - k_scale: &'b DeviceBuffer<'c>, - v_q4: &'b DeviceBuffer<'c>, - }, + K8V4 { k_q: &'b DeviceBuffer<'c>, k_scale: &'b DeviceBuffer<'c>, v_q4: &'b DeviceBuffer<'c> }, /// Mode 4: V-only INT8; keys rebuilt by RoPE from the value rows (cos/sin `[cell][32]`, optional M-RoPE /// positions `[cell][3]`). Keyless { diff --git a/crates/cuda-driver/src/experimental_gpu/impl_context.rs b/crates/cuda-driver/src/experimental_gpu/impl_context.rs index b5eae198..0dccb336 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_context.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_context.rs @@ -3,15 +3,10 @@ #[allow(unused_imports)] use super::*; - impl Context<'_> { /// Opt-in and pin gates, then load and cache the module once. Refuses without touching the driver while the /// pin is zero or the mode is off. - pub(crate) fn experimental_program( - &self, - program: Program, - opt_in: &OptIn, - ) -> Result { + pub(crate) fn experimental_program(&self, program: Program, opt_in: &OptIn) -> Result { admit(program, opt_in)?; if let Some(loaded) = self.experimental[program as usize].get() { return Ok(loaded); @@ -50,8 +45,7 @@ impl Context<'_> { self.poisoned.set(true); std::mem::forget(Rc::clone(api)); } - let primary = - combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); + let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); Err(failure(primary, guard.finish())) } } diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs index 58ecebed..3a8fdb32 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2.rs @@ -3,17 +3,11 @@ #[allow(unused_imports)] use super::*; - - impl<'c> Experimental<'c> { /// Load (once) and return the cached program. Fails closed with `NotEnabled` / `Unpinned`. pub fn open(context: &'c Context<'c>, program: Program, opt_in: &OptIn) -> Result { let loaded = context.experimental_program(program, opt_in)?; - Ok(Self { - context, - program, - loaded, - }) + Ok(Self { context, program, loaded }) } /// The module is owned by the context and unloaded by `Context::close`. @@ -29,13 +23,7 @@ impl<'c> Experimental<'c> { } pub(in super::super) fn call(&self, entry: usize) -> Call<'_, 'c> { - Call { - gpu: self, - entry, - args: Vec::new(), - kinds: Vec::new(), - admitted: Vec::new(), - } + Call { gpu: self, entry, args: Vec::new(), kinds: Vec::new(), admitted: Vec::new() } } /// Launch every entry in order and drain with exactly one synchronize. @@ -47,38 +35,23 @@ impl<'c> Experimental<'c> { let guard = context.enter()?; let mut launch = Ok(()); for l in &mut launches { - launch = context - .driver - .api - .launch_kar_levels(l.function, l.grid, l.block, &mut l.args); + launch = context.driver.api.launch_kar_levels(l.function, l.grid, l.block, &mut l.args); if launch.is_err() { break; } } - context - .complete_launch(launch, launches, guard) - .map_err(Into::into) + context.complete_launch(launch, launches, guard).map_err(Into::into) } // ------------------------------------------------------------------------------------- FWHT-256 /// `fwht256_cuda`: orthonormal Walsh-Hadamard transform of `rows` rows of 256 floats (scale 1/16; the /// transform is its own inverse). `src` and `dst` must not overlap. - pub fn fwht256( - &self, - src: &DeviceBuffer<'_>, - dst: &mut DeviceBuffer<'_>, - rows: u64, - ) -> Result<()> { + pub fn fwht256(&self, src: &DeviceBuffer<'_>, dst: &mut DeviceBuffer<'_>, rows: u64) -> Result<()> { self.expect(Program::KvQ4)?; let grid = experimental::fwht_grid(rows)?; let bytes = experimental::fwht_bytes(rows); - let launch = self - .call(FWHT256) - .ro(src, bytes)? - .rw(dst, bytes)? - .i64(i64_of(rows)?) - .finish(grid)?; + let launch = self.call(FWHT256).ro(src, bytes)?.rw(dst, bytes)?.i64(i64_of(rows)?).finish(grid)?; self.run(vec![launch]) } @@ -201,11 +174,7 @@ impl<'c> Experimental<'c> { pub fn q8_append_step( &self, p: &Paged, - keys: Option<( - &mut DeviceBuffer<'_>, - &mut DeviceBuffer<'_>, - &DeviceBuffer<'_>, - )>, + keys: Option<(&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>, &DeviceBuffer<'_>)>, v_q: &mut DeviceBuffer<'_>, v_scale: &mut DeviceBuffer<'_>, table: &DeviceBuffer<'_>, @@ -221,18 +190,12 @@ impl<'c> Experimental<'c> { match keys { Some((k_q, k_scale, kcur)) => { c = c.rw(k_q, codes)?.rw(v_q, codes)?.rw(k_scale, scales)?; - c = c - .rw(v_scale, scales)? - .ro(table, p.table_entries * 4)? - .ro(step, STEP_BYTES)?; + c = c.rw(v_scale, scales)?.ro(table, p.table_entries * 4)?.ro(step, STEP_BYTES)?; c = c.ro(kcur, cell)?; } None => { c = c.null().rw(v_q, codes)?.null().rw(v_scale, scales)?; - c = c - .ro(table, p.table_entries * 4)? - .ro(step, STEP_BYTES)? - .null(); + c = c.ro(table, p.table_entries * 4)?.ro(step, STEP_BYTES)?.null(); } } let launch = c diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs index aa28868a..53c7c0a0 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'c> Experimental<'c> { - /// `kv_gather_q8_step`: dequantize the selected cells into fp16 scratch (K and V of the same pool). #[allow(clippy::too_many_arguments)] // closed ABI operands pub fn q8_gather_step( @@ -49,12 +46,7 @@ impl<'c> Experimental<'c> { // --------------------------------------------------------------------------------- KV streaming /// `kv_stream_reset`: every block non-resident, every slot free, clock state zero. - pub fn stream_reset( - &self, - map: &mut StreamMap<'_, '_>, - n_blocks: u64, - n_slots: u64, - ) -> Result<()> { + pub fn stream_reset(&self, map: &mut StreamMap<'_, '_>, n_blocks: u64, n_slots: u64) -> Result<()> { self.expect(Program::KvStream)?; let launch = map .bind(self.call(STREAM_RESET), n_blocks, n_slots, false)? @@ -117,19 +109,12 @@ impl<'c> Experimental<'c> { for i in 0..4 { copy = copy.i32(runs.get(i).map_or(0, |r| r.1 as i32)); } - let copy = copy - .i32(runs.len() as i32) - .finish(experimental::STREAM_COPY_GRID)?; + let copy = copy.i32(runs.len() as i32).finish(experimental::STREAM_COPY_GRID)?; self.run(vec![resolve, copy]) } /// `kv_ring_table`: the ring layout's fixed block -> slot table (`block % n_slots`). - pub fn ring_table( - &self, - table: &mut DeviceBuffer<'_>, - n_blocks: u64, - n_slots: u64, - ) -> Result<()> { + pub fn ring_table(&self, table: &mut DeviceBuffer<'_>, n_blocks: u64, n_slots: u64) -> Result<()> { self.expect(Program::KvStream)?; if n_blocks == 0 || n_slots == 0 { return invalid("kv ring: empty table"); @@ -145,20 +130,10 @@ impl<'c> Experimental<'c> { /// `leleka_kv_copy_u4`: grid-stride copy of `n_u4` 16-byte units (stands in for `cudaMemcpyAsync` in /// `kv_ring_restore` / `kv_stage_from_host`; `src` and `dst` must not overlap). - pub fn copy_u4( - &self, - src: &DeviceBuffer<'_>, - dst: &mut DeviceBuffer<'_>, - n_u4: u64, - ) -> Result<()> { + pub fn copy_u4(&self, src: &DeviceBuffer<'_>, dst: &mut DeviceBuffer<'_>, n_u4: u64) -> Result<()> { self.expect(Program::KvStream)?; let grid = experimental::copy_u4_grid(n_u4)?; - let launch = self - .call(COPY_U4) - .ro(src, n_u4 * 16)? - .rw(dst, n_u4 * 16)? - .i64(i64_of(n_u4)?) - .finish(grid)?; + let launch = self.call(COPY_U4).ro(src, n_u4 * 16)?.rw(dst, n_u4 * 16)?.i64(i64_of(n_u4)?).finish(grid)?; self.run(vec![launch]) } diff --git a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs index d1d259dd..9305c3fe 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_experimental/impl_experimental_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'c> Experimental<'c> { - // ------------------------------------------------------------------------------------ attention /// `qsa_decode_attn_batch` for the experimental KV modes: the chunk kernel of `pools`' mode, then the merge, @@ -59,13 +56,7 @@ impl<'c> Experimental<'c> { .ro(steps, n_q * STEP_BYTES)? .i32(kv) .i32(ps), - AttnPools::Keyless { - v_q, - v_scale, - cos, - sin, - mrope, - } => { + AttnPools::Keyless { v_q, v_scale, cos, sin, mrope } => { let n_rot = leleka_experimental_ref::keyless::N_ROT as u64; let c = self .call(ATTN_CHUNK_M4) @@ -79,11 +70,7 @@ impl<'c> Experimental<'c> { Some(m) => c.ro(m, 4)?, None => c.null(), }; - c.i32(n_rot as i32) - .ro(ids, n_q * cap * 4)? - .ro(steps, n_q * STEP_BYTES)? - .i32(kv) - .i32(ps) + c.i32(n_rot as i32).ro(ids, n_q * cap * 4)?.ro(steps, n_q * STEP_BYTES)?.i32(kv).i32(ps) } }; let scratch_bytes = n_q * stride * 4; diff --git a/crates/cuda-driver/src/experimental_gpu/impl_streammap.rs b/crates/cuda-driver/src/experimental_gpu/impl_streammap.rs index fc51b93d..66d0e13b 100644 --- a/crates/cuda-driver/src/experimental_gpu/impl_streammap.rs +++ b/crates/cuda-driver/src/experimental_gpu/impl_streammap.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl StreamMap<'_, '_> { /// The first five (or seven, for resolve) pointer arguments of `reset` / `resolve`. pub(super) fn bind<'g, 'c>( @@ -20,22 +19,14 @@ impl StreamMap<'_, '_> { .rw(&*self.slot_ref, n_slots * 4)? .rw(&*self.ctl, CTL_INTS as u64 * 4)?; if with_miss { - c = c - .rw(&*self.miss_block, n_slots * 4)? - .rw(&*self.miss_slot, n_slots * 4)?; + c = c.rw(&*self.miss_block, n_slots * 4)?.rw(&*self.miss_slot, n_slots * 4)?; } Ok(c) } } impl Call<'_, '_> { - pub(super) fn pointer( - mut self, - buffer: &DeviceBuffer<'_>, - min: u64, - offset: u64, - writes: bool, - ) -> Result { + pub(super) fn pointer(mut self, buffer: &DeviceBuffer<'_>, min: u64, offset: u64, writes: bool) -> Result { let context = self.gpu.context; if context.poisoned.get() { return Err(Error::ContextPoisoned.into()); @@ -44,20 +35,14 @@ impl Call<'_, '_> { return Err(Error::ContextMismatch.into()); } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - let min = - usize::try_from(min).or_else(|_| invalid("experimental buffer size exceeds usize"))?; + let min = usize::try_from(min).or_else(|_| invalid("experimental buffer size exceeds usize"))?; if min == 0 || buffer.bytes < min { return invalid("experimental buffer is smaller than the geometry requires"); } handle.validate_projection_extent(buffer.bytes, 16)?; - self.admitted.push(Admitted { - handle, - bytes: buffer.bytes, - writes, - }); + self.admitted.push(Admitted { handle, bytes: buffer.bytes, writes }); let at = handle.experimental_offset(offset)?; - self.args - .push(ffi::KarArgument::Scalar64(at.qwen_address())); + self.args.push(ffi::KarArgument::Scalar64(at.qwen_address())); self.kinds.push(Arg::Ptr); Ok(self) } @@ -93,18 +78,12 @@ impl Call<'_, '_> { pub(super) fn finish(self, grid: [u32; 3]) -> Result { let entry: &Entry = &self.gpu.program.entries()[self.entry]; let matches = entry.args.len() == self.kinds.len() - && entry - .args - .iter() - .zip(&self.kinds) - .all(|(want, got)| match (want, got) { - (Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true, - (a, b) => a == b, - }); + && entry.args.iter().zip(&self.kinds).all(|(want, got)| match (want, got) { + (Arg::PtrOpt, Arg::Ptr | Arg::PtrOpt) => true, + (a, b) => a == b, + }); if !matches { - return invalid( - "experimental launch arguments differ from the entry's fixed signature", - ); + return invalid("experimental launch arguments differ from the entry's fixed signature"); } for (i, a) in self.admitted.iter().enumerate() { for b in &self.admitted[i + 1..] { @@ -117,21 +96,13 @@ impl Call<'_, '_> { } } } - let function = self.gpu.loaded.functions[self.entry].ok_or(ExperimentalError::Invalid( - "experimental entry is not loaded", - ))?; - Ok(Launch { - function, - grid, - block: entry.block, - args: ffi::KarLevelsArgs::new(&self.args)?, - }) + let function = self.gpu.loaded.functions[self.entry] + .ok_or(ExperimentalError::Invalid("experimental entry is not loaded"))?; + Ok(Launch { function, grid, block: entry.block, args: ffi::KarLevelsArgs::new(&self.args)? }) } } /// A primary driver failure plus the outcome of the mandatory context restore. pub(super) fn failure(primary: Error, restore: DriverResult<()>) -> ExperimentalError { - combine::<()>(Err(primary), restore) - .expect_err("a primary failure always stays an error") - .into() + combine::<()>(Err(primary), restore).expect_err("a primary failure always stays an error").into() } diff --git a/crates/cuda-driver/src/experimental_gpu_smoke.rs b/crates/cuda-driver/src/experimental_gpu_smoke.rs index e95ab380..a00c19fb 100644 --- a/crates/cuda-driver/src/experimental_gpu_smoke.rs +++ b/crates/cuda-driver/src/experimental_gpu_smoke.rs @@ -20,10 +20,7 @@ use leleka_experimental_ref::{ struct Rng(u64); impl Rng { fn next(&mut self) -> u32 { - self.0 = self - .0 - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); + self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (self.0 >> 32) as u32 } fn unit(&mut self) -> f32 { @@ -60,10 +57,7 @@ fn download(b: &DeviceBuffer<'_>, len: usize) -> Vec { fn open<'c>(ctx: &'c Context<'c>, program: Program, mode: Mode) -> Experimental<'c> { Experimental::open(ctx, program, &OptIn::default().with(mode)).unwrap_or_else(|error| { - panic!( - "{} open failed ({error}); TODO-ROOT: build PTX and freeze the pin", - program.name() - ) + panic!("{} open failed ({error}); TODO-ROOT: build PTX and freeze the pin", program.name()) }) } @@ -104,55 +98,31 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() { { let gpu = open(&ctx, Program::KvQ4, Mode::KvQ40); let q = QsaShapes::real(); - let p = Paged { - shape: KvShape::real(), - pages: 4, - table_entries: 4, - }; + let p = Paged { shape: KvShape::real(), pages: 4, table_entries: 4 }; let table: Vec = vec![0, 1, 2, 3]; let mut rng = Rng(0x57a7_0002); let n = 2 * 256; let mut cpu = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap(); let mut cells = Vec::new(); - let (mut k_b, mut v_b) = ( - zeroed(&ctx, p.shape.q4_bytes(4) as usize), - zeroed(&ctx, p.shape.q4_bytes(4) as usize), - ); - let (table_b, ids_b) = ( - upload(&ctx, &i32_bytes(&table)), - upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12])), - ); + let (mut k_b, mut v_b) = + (zeroed(&ctx, p.shape.q4_bytes(4) as usize), zeroed(&ctx, p.shape.q4_bytes(4) as usize)); + let (table_b, ids_b) = (upload(&ctx, &i32_bytes(&table)), upload(&ctx, &i32_bytes(&[0, 3, 5, 7, 9, 12]))); for pos in 0..13i32 { let kc: Vec = (0..n).map(|_| rng.unit()).collect(); let vc: Vec = (0..n).map(|_| rng.unit()).collect(); let step = upload(&ctx, &i32_bytes(&[pos, 0, 0, 0])); let (kb, vb) = (upload(&ctx, &f32_bytes(&kc)), upload(&ctx, &f32_bytes(&vc))); - gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb) - .unwrap(); + gpu.q4_append_step(&p, &mut k_b, &mut v_b, &table_b, &step, &kb, &vb).unwrap(); cells.push((pos, kc, vc)); } let got_k = download(&k_b, p.shape.q4_bytes(4) as usize); let got_v = download(&v_b, p.shape.q4_bytes(4) as usize); // nvcc contracts a*b+c; the Fused model is the expectation, Separate the fallback we report. let mut which = "none"; - for (name, c) in [ - ("fused", Contraction::Fused), - ("separate", Contraction::Separate), - ] { + for (name, c) in [("fused", Contraction::Fused), ("separate", Contraction::Separate)] { let mut m = PoolSet::new(KvFormat::Q4_0, &q, p.shape.rows(p.pages)).unwrap(); for (pos, kc, vc) in &cells { - append_cell( - KvFormat::Q4_0, - &mut m, - None, - &table, - i64::from(*pos), - kc, - vc, - &q, - c, - ) - .unwrap(); + append_cell(KvFormat::Q4_0, &mut m, None, &table, i64::from(*pos), kc, vc, &q, c).unwrap(); } if m.k_q4 == got_k && m.v_q4 == got_v { which = name; @@ -160,23 +130,16 @@ fn experimental_gpu_q4_append_and_gather_match_cpu() { break; } } - assert_ne!( - which, "none", - "device Q4_0 pools differ from both contraction models" - ); + assert_ne!(which, "none", "device Q4_0 pools differ from both contraction models"); println!("EXPERIMENTAL q4_append cells=13 matches={which}"); // gather let ids = [0, 3, 5, 7, 9, 12]; let step = upload(&ctx, &i32_bytes(&[0, 13, 0, 6])); let scratch = p.shape.gather_scratch_bytes(6) as usize; let (mut ks, mut vs) = (zeroed(&ctx, scratch), zeroed(&ctx, scratch)); - gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs) - .unwrap(); + gpu.q4_gather_step(&p, &k_b, &v_b, &table_b, &ids_b, &step, 6, &mut ks, &mut vs).unwrap(); let want_k = gather_q4(&cpu.k_q4, &table, &ids, &q).unwrap(); - let got: Vec = download(&ks, scratch) - .chunks(2) - .map(|b| u16::from_le_bytes([b[0], b[1]])) - .collect(); + let got: Vec = download(&ks, scratch).chunks(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); assert_eq!(got, want_k, "gathered fp16 K bits"); gpu.close().unwrap(); } @@ -195,16 +158,11 @@ fn experimental_gpu_keyless_route_matches_cpu() { let q0: Vec = (0..tokens * heads * 256).map(|_| rng.unit()).collect(); let m: Vec = (0..heads * 256 * 256).map(|_| rng.unit() * 0.1).collect(); let (mut q_b, m_b) = (upload(&ctx, &f32_bytes(&q0)), upload(&ctx, &f32_bytes(&m))); - gpu.keyless_route_query(&mut q_b, &m_b, tokens as u64, heads as u64) - .unwrap(); + gpu.keyless_route_query(&mut q_b, &m_b, tokens as u64, heads as u64).unwrap(); let mut want = q0.clone(); keyless::route_query(&mut want, &m, tokens, heads).unwrap(); let got = download(&q_b, want.len() * 4); - let mismatches = want - .iter() - .enumerate() - .filter(|(i, w)| got[i * 4..i * 4 + 4] != w.to_le_bytes()) - .count(); + let mismatches = want.iter().enumerate().filter(|(i, w)| got[i * 4..i * 4 + 4] != w.to_le_bytes()).count(); assert_eq!(mismatches, 0, "fmaf-ordered routing is bit-exact"); println!("EXPERIMENTAL keyless_route tokens={tokens} heads={heads} mismatches=0"); gpu.close().unwrap(); @@ -224,15 +182,11 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { let (n_blocks, n_slots, n_q, cap) = (4096u64, 1024u64, 2u64, 64u64); let runs = stream_runs(&q, StreamFormat::F16); let mut rng = Rng(0x57a7_0004); - let host_bytes: Vec> = runs - .iter() - .map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect()) - .collect(); + let host_bytes: Vec> = + runs.iter().map(|(_, len)| (0..n_blocks * len).map(|_| rng.next() as u8).collect()).collect(); let host: Vec> = host_bytes.iter().map(|b| upload(&ctx, b)).collect(); - let mut slots: Vec> = runs - .iter() - .map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize)) - .collect(); + let mut slots: Vec> = + runs.iter().map(|(_, len)| zeroed(&ctx, (n_slots * len) as usize)).collect(); let mut page_table = upload(&ctx, &i32_bytes(&vec![-1; n_blocks as usize])); let mut slot_block = zeroed(&ctx, n_slots as usize * 4); let mut slot_stamp = zeroed(&ctx, n_slots as usize * 4); @@ -258,10 +212,7 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { ids.extend((0..cap as i32).map(|i| i * 4 + qi * 8)); steps.extend([cap as i32 * 4, 0, 0, width]); } - let (ids_b, steps_b) = ( - upload(&ctx, &i32_bytes(&ids)), - upload(&ctx, &i32_bytes(&steps)), - ); + let (ids_b, steps_b) = (upload(&ctx, &i32_bytes(&ids)), upload(&ctx, &i32_bytes(&steps))); let host_refs: Vec<&DeviceBuffer<'_>> = host.iter().collect(); let mut slot_refs: Vec<&mut DeviceBuffer<'_>> = slots.iter_mut().collect(); gpu.stream_resolve( @@ -292,16 +243,9 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { .expect("cpu resolve"); let _ = report; let table = download(&*map.page_table, n_blocks as usize * 4); - let table: Vec = table - .chunks(4) - .map(|b| i32::from_le_bytes(b.try_into().unwrap())) - .collect(); + let table: Vec = table.chunks(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect(); let resident: Vec = (0..n_blocks as usize).filter(|b| table[*b] >= 0).collect(); - assert_eq!( - resident.len(), - cpu.resident_blocks(), - "same set of distinct blocks resident" - ); + assert_eq!(resident.len(), cpu.resident_blocks(), "same set of distinct blocks resident"); for b in resident { let slot = table[b] as usize; for (i, (_, len)) in runs.iter().enumerate() { @@ -314,10 +258,7 @@ fn experimental_gpu_stream_resolve_copies_missed_blocks() { ); } } - println!( - "EXPERIMENTAL kv_stream resolve+copy resident={}", - cpu.resident_blocks() - ); + println!("EXPERIMENTAL kv_stream resolve+copy resident={}", cpu.resident_blocks()); gpu.close().unwrap(); } ctx.close().unwrap(); diff --git a/crates/cuda-driver/src/family_tests.rs b/crates/cuda-driver/src/family_tests.rs index 3340ff9b..d4c6abc7 100644 --- a/crates/cuda-driver/src/family_tests.rs +++ b/crates/cuda-driver/src/family_tests.rs @@ -16,99 +16,43 @@ const KINDS: [ProjectionKind; 10] = [ #[test] fn common_checked_geometry_matches_frozen_native_layouts() { for (kind, index) in KINDS.into_iter().zip([0, 1, 2, 3, 4, 5, 5, 6, 6, 7]) { - let shape = projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: 256, - }) - .unwrap(); + let shape = projection_shape(ProjectionSpec { kind, rows: 5, columns: 256 }).unwrap(); assert_eq!( shape.weight_bytes, - 5 * (256 / family_expectations::LAYOUTS[index].0) - * family_expectations::LAYOUTS[index].1 + 5 * (256 / family_expectations::LAYOUTS[index].0) * family_expectations::LAYOUTS[index].1 ); assert_eq!( - ( - shape.activation_bytes, - shape.output_bytes, - shape.scratch_bytes, - shape.temporary_bytes - ), + (shape.activation_bytes, shape.output_bytes, shape.scratch_bytes, shape.temporary_bytes), (1024, 20, 288, 292) ); } for (n, bytes, grid) in family_expectations::TAILS { - let shape = projection_shape(ProjectionSpec { - kind: KINDS[0], - rows: 5, - columns: n, - }) - .unwrap(); - assert_eq!( - (shape.scratch_bytes, shape.quant_grid, shape.projection_grid), - (bytes, grid as u32, 2) - ); + let shape = projection_shape(ProjectionSpec { kind: KINDS[0], rows: 5, columns: n }).unwrap(); + assert_eq!((shape.scratch_bytes, shape.quant_grid, shape.projection_grid), (bytes, grid as u32, 2)); } - for (kind, limit) in [ - (KINDS[0], 1024), - (KINDS[1], 2048), - (KINDS[5], 2048), - (KINDS[7], 4096), - ] { + for (kind, limit) in [(KINDS[0], 1024), (KINDS[1], 2048), (KINDS[5], 2048), (KINDS[7], 4096)] { for (n, grid) in [(limit - 256, 2), (limit, 5), (limit + 256, 5)] { - assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: n - }) - .unwrap() - .projection_grid, - grid - ); + assert_eq!(projection_shape(ProjectionSpec { kind, rows: 5, columns: n }).unwrap().projection_grid, grid); } } for kind in [KINDS[2], KINDS[3], KINDS[4], KINDS[6], KINDS[8], KINDS[9]] { - assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: 5, - columns: 6144 - }) - .unwrap() - .projection_grid, - 2 - ); + assert_eq!(projection_shape(ProjectionSpec { kind, rows: 5, columns: 6144 }).unwrap().projection_grid, 2); } } #[test] fn common_invalid_shapes_have_fixed_errors() { for kind in KINDS { - for (m, n) in [ - (0, 256), - (1, 0), - (1, 31), - (1, 33), - (usize::MAX, 256), - (1, usize::MAX), - (i32::MAX as usize + 1, 256), - ] { + for (m, n) in + [(0, 256), (1, 0), (1, 31), (1, 33), (usize::MAX, 256), (1, usize::MAX), (i32::MAX as usize + 1, 256)] + { assert_eq!( - projection_shape(ProjectionSpec { - kind, - rows: m, - columns: n - }), + projection_shape(ProjectionSpec { kind, rows: m, columns: n }), Err(Error::InvalidProjectionShape) ); } } assert_eq!( - projection_shape(ProjectionSpec { - kind: KINDS[1], - rows: 1, - columns: 32 - }), + projection_shape(ProjectionSpec { kind: KINDS[1], rows: 1, columns: 32 }), Err(Error::InvalidProjectionShape) ); } @@ -124,8 +68,7 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() { let max_block_index = i32::MAX as usize / BLOCK_BYTES; // Include the common final +8-block PTX increment after the last // iteration, then round the small-N four-row CTA down to its boundary. - let max_padded_rows = - ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); + let max_padded_rows = ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES; assert!(at_limit_offset <= i32::MAX as usize); assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256)); @@ -187,11 +130,7 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() { for rows in [14_913_081, 14_913_082] { assert!(!q4_k_native_indices_fit(rows, 256)); assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows, - columns: 256, - }), + projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows, columns: 256 }), Err(Error::InvalidProjectionShape) ); } @@ -202,12 +141,8 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() { let large_n = 256 * 3_000_000; assert!(q4_k_native_indices_fit(1, large_n)); assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: 1, - columns: large_n, - }) - .is_ok() + projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows: 1, columns: large_n }) + .is_ok() ); // Positive individually-valid M and N still refuse when their Q4_K @@ -224,52 +159,28 @@ fn q4_k_admission_bounds_every_padded_cta_byte_offset() { ); } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] #[ignore = "private quantizer transport only; isolated CPU mock, not GPU math"] fn family_quantizer_transport_child() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let n: usize = std::env::var("LELEKA_FAMILY_N").unwrap().parse().unwrap(); let driver = Driver::load().unwrap(); let context = driver.device(0).unwrap().create_context(8192).unwrap(); let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap(); let before = std::fs::read(&trace_path).unwrap(); for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) { - let shape = projection_shape(ProjectionSpec { - kind, - rows: 1, - columns: 256, - }) - .unwrap(); - let addresses = [ - ffi::BufferHandle::synthetic(2), - ffi::BufferHandle::synthetic(4096), - ffi::BufferHandle::synthetic(8192), - ]; + let shape = projection_shape(ProjectionSpec { kind, rows: 1, columns: 256 }).unwrap(); + let addresses = + [ffi::BufferHandle::synthetic(2), ffi::BufferHandle::synthetic(4096), ffi::BufferHandle::synthetic(8192)]; assert_eq!( projection_ranges(kind, &shape, addresses), - if alignment == 4 { - Err(Error::InvalidProjectionShape) - } else { - Ok(()) - } + if alignment == 4 { Err(Error::InvalidProjectionShape) } else { Ok(()) } ); assert_eq!(std::fs::read(&trace_path).unwrap(), before); assert_eq!(context.allocated_bytes(), 0); assert!(context.common_quantizer.get().is_none()); - assert!( - context - .projection_kernels - .iter() - .all(|slot| slot.get().is_none()) - ); + assert!(context.projection_kernels.iter().all(|slot| slot.get().is_none())); } let mut input = context.allocate(4 * n).unwrap(); input.copy_from(&vec![0; 4 * n]).unwrap(); @@ -290,18 +201,11 @@ fn family_quantizer_transport_child() { n as u32, ); let guard = context.enter()?; - let launch = context.driver.api.launch_q8_quantize( - kernel.function, - n.div_ceil(256) as u32, - &mut args, - ); + let launch = context.driver.api.launch_q8_quantize(kernel.function, n.div_ceil(256) as u32, &mut args); context.complete_launch(launch, args, guard)?; let mut bytes = [0; 4]; status.copy_to(&mut bytes)?; - let expected = std::env::var("MOCK_FAMILY_STATUS") - .unwrap_or_else(|_| "0".into()) - .parse::() - .unwrap(); + let expected = std::env::var("MOCK_FAMILY_STATUS").unwrap_or_else(|_| "0".into()).parse::().unwrap(); assert_eq!(u32::from_le_bytes(bytes), expected); Ok(()) })(); @@ -310,18 +214,16 @@ fn family_quantizer_transport_child() { assert_eq!(result.is_err(), failure, "result={result:?}"); let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default(); let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default(); - let expected_charge = if family.contains("quant_sync") - || family.contains("quant_restore") - || base == "lookup:1,unload:1" - { - 4 * n + n / 32 * 36 + 4 - } else if base == "free:1" { - 4 * n + 4 - } else if base == "free:2" { - 4 * n + n / 32 * 36 - } else { - 4 * n - }; + let expected_charge = + if family.contains("quant_sync") || family.contains("quant_restore") || base == "lookup:1,unload:1" { + 4 * n + n / 32 * 36 + 4 + } else if base == "free:1" { + 4 * n + 4 + } else if base == "free:2" { + 4 * n + n / 32 * 36 + } else { + 4 * n + }; assert_eq!(context.allocated_bytes(), expected_charge); if family == "quant_launch,quant_sync,quant_restore" { let error = format!("{result:?}"); diff --git a/crates/cuda-driver/src/ffi.rs b/crates/cuda-driver/src/ffi.rs index 61545583..993980da 100644 --- a/crates/cuda-driver/src/ffi.rs +++ b/crates/cuda-driver/src/ffi.rs @@ -97,8 +97,8 @@ pub(crate) struct Q5ProjectionArguments { #[path = "mmq_ffi.rs"] mod mmq_abi; pub(crate) use mmq_abi::{ - Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments, - MmqOriginalSwigluArguments, MmqQuantArguments, MmqResidentArguments, + Iq3NativeIntegerArguments, MmqArguments, MmqFixupArguments, MmqOriginalGatherArguments, MmqOriginalSwigluArguments, + MmqQuantArguments, MmqResidentArguments, }; // Closed kernel-parameter storage of the Strata-prefill GDN / native dequant modules. @@ -108,17 +108,9 @@ mod gdn_native_abi; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub(crate) use gdn_native_abi::{GdnPrefillArguments, KernelArg}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::{Api, KarArgument, KarLevelsArgs}; #[cfg(not(all( @@ -150,48 +142,32 @@ struct HeadGreedyStorage { } pub(crate) struct HeadGreedyArguments(std::ptr::NonNull); -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_expert_stager_ffi.rs"] pub(crate) mod original_stager; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_file_expert_source_ffi.rs"] pub(crate) mod original_file_source; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "deferred_status_ffi.rs"] pub(crate) mod deferred_status; mod impl_contexthandle; #[allow(unused_imports)] -use impl_contexthandle::projection_ptx; -#[cfg(any( - test, - all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ) -))] -#[allow(unused_imports)] -use impl_contexthandle::validate_projection_ptx; -#[allow(unused_imports)] pub(crate) use impl_contexthandle::projection_available; #[allow(unused_imports)] use impl_contexthandle::projection_entry; -mod impl_functionhandle; -mod impl_drop_for_q5projectionarguments; +#[allow(unused_imports)] +use impl_contexthandle::projection_ptx; +#[cfg(any( + test, + all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64") +))] +#[allow(unused_imports)] +use impl_contexthandle::validate_projection_ptx; mod impl_api; +mod impl_drop_for_q5projectionarguments; +mod impl_functionhandle; mod impl_qsaselectedarguments; diff --git a/crates/cuda-driver/src/ffi/enabled.rs b/crates/cuda-driver/src/ffi/enabled.rs index 80f8e690..b2be5559 100644 --- a/crates/cuda-driver/src/ffi/enabled.rs +++ b/crates/cuda-driver/src/ffi/enabled.rs @@ -21,8 +21,7 @@ type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult; type MemGetInfoV2 = unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult; type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult; type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult; -type ModuleGetFunction = - unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult; +type ModuleGetFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult; type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult; type LaunchKernel = unsafe extern "C" fn( *mut c_void, @@ -40,8 +39,7 @@ type LaunchKernel = unsafe extern "C" fn( static FIXED_PTX: &[u8] = concat!(include_str!("../vector_add.ptx"), "\0").as_bytes(); static MATVEC_PTX: &[u8] = concat!(include_str!("../matvec.ptx"), "\0").as_bytes(); static Q5_K_PTX: &[u8] = concat!(include_str!("../q5_k_q8_1.ptx"), "\0").as_bytes(); -static COMMON_QUANTIZER_PTX: &[u8] = - concat!(include_str!("../q8_1_quantize.ptx"), "\0").as_bytes(); +static COMMON_QUANTIZER_PTX: &[u8] = concat!(include_str!("../q8_1_quantize.ptx"), "\0").as_bytes(); static Q6_K_PTX: &[u8] = concat!(include_str!("../q6_k_q8_1.ptx"), "\0").as_bytes(); type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult; type MemcpyDtoDV2 = unsafe extern "C" fn(CuDevicePtr, CuDevicePtr, usize) -> CuResult; @@ -87,9 +85,7 @@ macro_rules! symbol { // SAFETY: valid owned library handle and static C name. let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) }; if address.is_null() { - return Err(Error::MissingSymbol( - $name.to_str().expect("static ASCII symbol"), - )); + return Err(Error::MissingSymbol($name.to_str().expect("static ASCII symbol"))); } // SAFETY: the fixed ABI name is paired with its exact // documented signature. Linux64 supports dlsym function diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api.rs b/crates/cuda-driver/src/ffi/enabled/impl_api.rs index d6e868fb..0e7891a8 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api.rs @@ -21,16 +21,9 @@ impl Api { } pub(crate) fn mmq_capabilities(&self) -> Result { let library = &self._library; - let get = symbol!( - library, - c"cuCtxGetDevice", - unsafe extern "C" fn(*mut c_int) -> CuResult - ); - let attr = symbol!( - library, - c"cuDeviceGetAttribute", - unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult - ); + let get = symbol!(library, c"cuCtxGetDevice", unsafe extern "C" fn(*mut c_int) -> CuResult); + let attr = + symbol!(library, c"cuDeviceGetAttribute", unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult); let mut device = 0; // SAFETY: fixed optional Driver ABI, owner context current, valid output. check("cuCtxGetDevice", unsafe { get(&mut device) })?; @@ -39,10 +32,7 @@ impl Api { // SAFETY: fixed capability selectors and live device returned above. check("cuDeviceGetAttribute", unsafe { attr(slot, key, device) })?; } - if !crate::arch_ptx::mmq_cc_ok(values[0], values[1]) - || values[2] < 52480 - || !(1..=4096).contains(&values[3]) - { + if !crate::arch_ptx::mmq_cc_ok(values[0], values[1]) || values[2] < 52480 || !(1..=4096).contains(&values[3]) { return Err(Error::InvalidDriverValue("MMQ SM120 capabilities")); } Ok(crate::arch_ptx::forced_sms(values[3] as u32)) @@ -103,40 +93,22 @@ impl Api { return Err(Error::InvalidProjectionShape); } let library = &self._library; - let set = symbol!( - library, - c"cuFuncSetAttribute", - unsafe extern "C" fn(*mut c_void, c_int, c_int) -> CuResult - ); + let set = symbol!(library, c"cuFuncSetAttribute", unsafe extern "C" fn(*mut c_void, c_int, c_int) -> CuResult); // SAFETY: fixed attribute8, admitted shared bytes and live owned function. - check("cuFuncSetAttribute", unsafe { - set(function.0 as *mut c_void, 8, bytes as c_int) - }) + check("cuFuncSetAttribute", unsafe { set(function.0 as *mut c_void, 8, bytes as c_int) }) } pub(crate) fn load_iq3_native_integer(&self) -> Result { let ptx = crate::mmq::resident::native_integer::asset()?; let mut m = std::ptr::null_mut(); // SAFETY: ROOT-sealed fixed NUL PTX, actual owning current Context. - check("cuModuleLoadData", unsafe { - (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; ModuleHandle::qwen_success(m as usize) } - pub(crate) fn iq3_native_integer_function( - &self, - m: ModuleHandle, - reduce: bool, - ) -> Result { - let name = if reduce { - c"leleka_iq3_native_order_reduce" - } else { - c"leleka_iq3_native_integer_dot" - }; + pub(crate) fn iq3_native_integer_function(&self, m: ModuleHandle, reduce: bool) -> Result { + let name = if reduce { c"leleka_iq3_native_order_reduce" } else { c"leleka_iq3_native_integer_dot" }; let mut f = std::ptr::null_mut(); // SAFETY: closed fixed two-entry map in actual owned module. - check("cuModuleGetFunction", unsafe { - (self.get_function)(&mut f, m.0 as *mut c_void, name.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, m.0 as *mut c_void, name.as_ptr()) })?; FunctionHandle::qwen_success(f as usize) } pub(crate) fn launch_iq3_native_integer( @@ -149,11 +121,7 @@ impl Api { if !(1..=64).contains(&tokens) { return Err(Error::InvalidProjectionShape); } - let (x, y, z, by) = if reduce { - (160, tokens, 1, 4) - } else { - (40, tokens.div_ceil(8), 80, 1) - }; + let (x, y, z, by) = if reduce { (160, tokens, 1, 4) } else { (40, tokens.div_ceil(8), 80, 1) }; // SAFETY: fixed complete M640/K2560/T1..64 grid, exact privately boxed ABI; // queue retains every owner through one same-default-stream synchronize/pop. check("cuLaunchKernel", unsafe { @@ -176,23 +144,14 @@ impl Api { let ptx = crate::mmq::resident::native_activation::asset()?; let mut m = std::ptr::null_mut(); // SAFETY: pinned immutable NUL PTX in current owned Context. - check("cuModuleLoadData", unsafe { - (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { (self.load_module)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; ModuleHandle::qwen_success(m as usize) } - pub(crate) fn native_resident_d4_function( - &self, - m: ModuleHandle, - ) -> Result { + pub(crate) fn native_resident_d4_function(&self, m: ModuleHandle) -> Result { let mut f = std::ptr::null_mut(); // SAFETY: fixed entry in actual owned module. check("cuModuleGetFunction", unsafe { - (self.get_function)( - &mut f, - m.0 as *mut c_void, - c"leleka_native_resident_d4".as_ptr(), - ) + (self.get_function)(&mut f, m.0 as *mut c_void, c"leleka_native_resident_d4".as_ptr()) })?; FunctionHandle::qwen_success(f as usize) } @@ -205,16 +164,8 @@ impl Api { })?; ModuleHandle::qwen_success(module as usize) } - pub(crate) fn head_greedy_function( - &self, - module: ModuleHandle, - last: bool, - ) -> Result { - let name = if last { - c"leleka_head_final" - } else { - c"leleka_head_groups" - }; + pub(crate) fn head_greedy_function(&self, module: ModuleHandle, last: bool) -> Result { + let name = if last { c"leleka_head_final" } else { c"leleka_head_groups" }; let mut function = std::ptr::null_mut(); // SAFETY: closed two-entry map, actual retained module. check("cuModuleGetFunction", unsafe { diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_2.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_2.rs index b6a87c99..2294048e 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_2.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_2.rs @@ -6,23 +6,14 @@ use super::*; impl Api { pub(crate) fn mmq_original_group_shared_limit(&self) -> Result { let library = &self._library; - let get = symbol!( - library, - c"cuCtxGetDevice", - unsafe extern "C" fn(*mut c_int) -> CuResult - ); - let attr = symbol!( - library, - c"cuDeviceGetAttribute", - unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult - ); + let get = symbol!(library, c"cuCtxGetDevice", unsafe extern "C" fn(*mut c_int) -> CuResult); + let attr = + symbol!(library, c"cuDeviceGetAttribute", unsafe extern "C" fn(*mut c_int, c_int, CuDevice) -> CuResult); let mut device = 0; let mut limit = 0; // SAFETY: current real Context, fixed attribute97 and live output slots. check("cuCtxGetDevice", unsafe { get(&mut device) })?; - check("cuDeviceGetAttribute", unsafe { - attr(&mut limit, 97, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut limit, 97, device) })?; u32::try_from(limit).map_err(|_| Error::InvalidDriverValue("MMQ shared capacity")) } pub(crate) fn load_mmq_original_group(&self, kind: u32) -> Result { @@ -41,149 +32,303 @@ impl Api { width: u32, fixup: bool, ) -> Result { - let name=match(kind,width,fixup){ - (0,0,false)=>c"leleka_original_mmq_swiglu", - (1,0,false)=>c"leleka_original_mmq_gather", - (2,0,false)=>c"leleka_original_mmq_gu_finite", - (18,8,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,16,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,24,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,32,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,40,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,48,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,64,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,80,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,96,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,112,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (18,128,false)=>c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (18,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,8,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,16,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,24,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,32,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,40,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,48,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,64,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,80,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,96,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,112,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (22,128,false)=>c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (22,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,8,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,16,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,24,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,32,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,40,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,48,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,64,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,80,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,96,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,112,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (21,128,false)=>c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (21,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,8,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,16,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,24,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,32,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,40,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,48,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,64,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,80,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,96,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,112,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (23,128,false)=>c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (23,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,8,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,16,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,24,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,32,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,40,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,48,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,64,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,80,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,96,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,112,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (20,128,false)=>c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (20,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,8,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,8,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,16,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,16,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,24,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,24,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,32,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,32,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,40,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,40,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,48,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,48,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,64,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,64,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,80,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,80,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,96,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,96,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,112,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,112,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (42,128,false)=>c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (42,128,true)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - _=>return Err(Error::InvalidProjectionShape), + let name = match (kind, width, fixup) { + (0, 0, false) => c"leleka_original_mmq_swiglu", + (1, 0, false) => c"leleka_original_mmq_gather", + (2, 0, false) => c"leleka_original_mmq_gu_finite", + (18, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (18, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (18, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type18ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (18, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (22, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (22, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (22, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type22ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (22, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (21, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (21, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (21, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type21ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (21, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (23, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (23, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (23, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type23ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (23, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (20, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (20, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (20, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type20ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (20, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (42, 8, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 8, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 16, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 16, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 24, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 24, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 32, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 32, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 40, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 40, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 48, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 48, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 64, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 64, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 80, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 80, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 96, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 96, true) => c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + (42, 112, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 112, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (42, 128, false) => { + c"_Z9mul_mat_qIL9ggml_type42ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (42, 128, true) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + _ => return Err(Error::InvalidProjectionShape), }; let mut f = std::ptr::null_mut(); // SAFETY: closed literal Original template symbols only. - check("cuModuleGetFunction", unsafe { - (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) })?; FunctionHandle::qwen_success(f as usize) } pub(crate) fn launch_mmq_original_gather( diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_3.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_3.rs index c64aacff..32b65729 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_3.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_3.rs @@ -39,11 +39,7 @@ impl Api { })?; ModuleHandle::qwen_success(module as usize) } - pub(crate) fn mmq_resident_function( - &self, - module: ModuleHandle, - kind: u8, - ) -> Result { + pub(crate) fn mmq_resident_function(&self, module: ModuleHandle, kind: u8) -> Result { let name = match kind { 0 => c"leleka_mmq_zero", 1 => c"leleka_mmq_finite", @@ -52,9 +48,7 @@ impl Api { }; let mut f = std::ptr::null_mut(); // SAFETY: closed three-entry name map, actual retained helper module. - check("cuModuleGetFunction", unsafe { - (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { (self.get_function)(&mut f, module.0 as *mut c_void, name.as_ptr()) })?; FunctionHandle::qwen_success(f as usize) } pub(crate) fn launch_mmq_resident( @@ -130,12 +124,7 @@ impl Api { ) }) } - pub(crate) fn fixup_mmq( - &self, - function: FunctionHandle, - grid: u32, - args: &mut MmqFixupArguments, - ) -> Result<()> { + pub(crate) fn fixup_mmq(&self, function: FunctionHandle, grid: u32, args: &mut MmqFixupArguments) -> Result<()> { // SAFETY: closed fixed 13-param ABI, actual same scratch/result after completed mul; args retained through sync. check("cuLaunchKernel", unsafe { (self.launch_kernel)( @@ -175,16 +164,8 @@ impl Api { })?; ModuleHandle::qwen_success(module as usize) } - pub(crate) fn qsa_selected_function( - &self, - module: ModuleHandle, - gather: bool, - ) -> Result { - let name = if gather { - c"leleka_qsa_selected_gather" - } else { - c"leleka_qsa_selected_scatter" - }; + pub(crate) fn qsa_selected_function(&self, module: ModuleHandle, gather: bool) -> Result { + let name = if gather { c"leleka_qsa_selected_gather" } else { c"leleka_qsa_selected_scatter" }; let mut function = std::ptr::null_mut(); // SAFETY: two fixed entry names, live retained module and writable out pointer. check("cuModuleGetFunction", unsafe { @@ -219,10 +200,7 @@ impl Api { ) }) } - pub(crate) fn load_qwen_module( - &self, - asset: &crate::qwen_ffi::Asset, - ) -> Result { + pub(crate) fn load_qwen_module(&self, asset: &crate::qwen_ffi::Asset) -> Result { asset.validate(asset.operation)?; let mut module = std::ptr::null_mut(); // SAFETY: validated immutable closed-map NUL-terminated PTX and @@ -241,11 +219,7 @@ impl Api { // SAFETY: live private module, fixed operation-to-entry map and // writable output. No external symbol resolver is exposed. check("cuModuleGetFunction", unsafe { - (self.get_function)( - &mut function, - module.0 as *mut c_void, - operation.entry().as_ptr(), - ) + (self.get_function)(&mut function, module.0 as *mut c_void, operation.entry().as_ptr()) })?; FunctionHandle::qwen_success(function as usize) } diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs index be9d4ff3..ded5b151 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_4.rs @@ -33,9 +33,7 @@ impl Api { } pub(crate) fn load() -> Result { // SAFETY: fixed NUL-terminated soname and immediate local lookup. - let handle = unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }; + let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; if handle.is_null() { return Err(Error::LibraryUnavailable); } @@ -133,47 +131,21 @@ impl Api { pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result { let bytes = match operation { FixedOperation::CommonQuantize => COMMON_QUANTIZER_PTX, - FixedOperation::GroupedSwiglu => { - concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedDownIq4 => { - concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedDownQ2 => { - concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq3 => { - concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq2 => { - concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq3S => { - concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq4Xs => { - concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq3SNc4 => { - concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes() - } - FixedOperation::GroupedIq4XsNc4 => { - concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes() - } - FixedOperation::Projection(kind) => { - projection_ptx(kind).ok_or(Error::UnsupportedProjection)? - } + FixedOperation::GroupedSwiglu => concat!(include_str!("../../moe_group_swiglu.ptx"), "\0").as_bytes(), + FixedOperation::GroupedDownIq4 => concat!(include_str!("../../moe_group_down_iq4_nl.ptx"), "\0").as_bytes(), + FixedOperation::GroupedDownQ2 => concat!(include_str!("../../moe_group_down_q2_0.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3 => concat!(include_str!("../../moe_group_iq3_xxs.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq2 => concat!(include_str!("../../moe_group_iq2_s.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3S => concat!(include_str!("../../moe_group_iq3_s.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq4Xs => concat!(include_str!("../../moe_group_iq4_xs.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq3SNc4 => concat!(include_str!("../../moe_group_iq3_s_nc4.ptx"), "\0").as_bytes(), + FixedOperation::GroupedIq4XsNc4 => concat!(include_str!("../../moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes(), + FixedOperation::Projection(kind) => projection_ptx(kind).ok_or(Error::UnsupportedProjection)?, FixedOperation::VectorAdd => FIXED_PTX, - FixedOperation::GrReadFinite => { - concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes() - } + FixedOperation::GrReadFinite => concat!(include_str!("../../gr_read_guard.ptx"), "\0").as_bytes(), FixedOperation::Matvec => MATVEC_PTX, - FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => { - Q5_K_PTX - } - FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => { - Q6_K_PTX - } + FixedOperation::Q5K | FixedOperation::Q5KQuantize | FixedOperation::Q5KProject => Q5_K_PTX, + FixedOperation::Q6K | FixedOperation::Q6KQuantize | FixedOperation::Q6KProject => Q6_K_PTX, }; if matches!( operation, @@ -205,11 +177,7 @@ impl Api { } Ok(ModuleHandle(module as usize)) } - pub(crate) fn fixed_function( - &self, - module: ModuleHandle, - operation: FixedOperation, - ) -> Result { + pub(crate) fn fixed_function(&self, module: ModuleHandle, operation: FixedOperation) -> Result { let mut function = std::ptr::null_mut(); // SAFETY: live private module in current owner context; fixed C // entry name; valid writable opaque function output. diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_5.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_5.rs index a521d738..49dc57a1 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_5.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_5.rs @@ -8,16 +8,9 @@ impl Api { // SAFETY: usable handle was consumed before this single attempt, // current context owns it, and all prior work completed. It is // never retried or reused even when unload reports failure. - check("cuModuleUnload", unsafe { - (self.unload_module)(module.0 as *mut c_void) - }) + check("cuModuleUnload", unsafe { (self.unload_module)(module.0 as *mut c_void) }) } - pub(crate) fn launch( - &self, - function: FunctionHandle, - grid: u32, - arguments: &mut LaunchArguments, - ) -> Result<()> { + pub(crate) fn launch(&self, function: FunctionHandle, grid: u32, arguments: &mut LaunchArguments) -> Result<()> { // SAFETY: fixed live function/owner context; checked exact shapes, // nonaliasing output and grid; six fixed dimensions + sharedBytes; // null stream/extra. Four pointer entries address initialized typed diff --git a/crates/cuda-driver/src/ffi/enabled/impl_api_6.rs b/crates/cuda-driver/src/ffi/enabled/impl_api_6.rs index ec223699..d578b3f1 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_api_6.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_api_6.rs @@ -14,9 +14,7 @@ impl Api { let mut context = std::ptr::null_mut(); // SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device // returned by cuDeviceGet, and a valid writable context pointer. - check("cuCtxCreate_v2", unsafe { - (self.create)(&mut context, 0, device) - })?; + check("cuCtxCreate_v2", unsafe { (self.create)(&mut context, 0, device) })?; if context.is_null() { return Err(Error::InvalidDriverValue("cuCtxCreate_v2")); } @@ -26,15 +24,11 @@ impl Api { // SAFETY: this handle was created by this Api and remains owned by // the caller context. No buffer can outlive the borrow owner. This // API explicitly supports destroying a non-current owned context. - check("cuCtxDestroy_v2", unsafe { - (self.destroy)(context.0 as CuContext) - }) + check("cuCtxDestroy_v2", unsafe { (self.destroy)(context.0 as CuContext) }) } pub(crate) fn push(&self, context: ContextHandle) -> Result<()> { // SAFETY: live private context, same creating thread (Rc owners). - check("cuCtxPushCurrent_v2", unsafe { - (self.push)(context.0 as CuContext) - }) + check("cuCtxPushCurrent_v2", unsafe { (self.push)(context.0 as CuContext) }) } pub(crate) fn pop(&self) -> Result { let mut context = std::ptr::null_mut(); @@ -49,9 +43,11 @@ impl Api { // drained, then wait for the compute streams only (never for the copy stream) crate::prefetch_point(); // SAFETY: caller guard makes its live owned context current; registered live streams. - return crate::compute_drain::timed(5, || crate::compute_drain::drain(|s| { - check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) }) - })); + return crate::compute_drain::timed(5, || { + crate::compute_drain::drain(|s| { + check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) }) + }) + }); } // SAFETY: caller guard makes its live owned context current. check("cuCtxSynchronize", unsafe { (self.synchronize)() }) @@ -81,21 +77,21 @@ impl Api { if crate::compute_drain::zero_memset() && owned.len() <= 1 << 20 && owned.iter().all(|b| *b == 0) { // EXPERIMENT (chunk stream in flight): an all-zero upload is a device memset, which does not queue // behind the expert copies on the host-to-device copy engine - return crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe { - (self.zero)(buffer.0, 0, owned.len()) - })); + return crate::compute_drain::timed(4, || { + check("cuMemsetD8_v2", unsafe { (self.zero)(buffer.0, 0, owned.len()) }) + }); } - crate::compute_drain::timed(2, || check("cuMemcpyHtoD_v2", unsafe { - (self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len()) - })) + crate::compute_drain::timed(2, || { + check("cuMemcpyHtoD_v2", unsafe { (self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len()) }) + }) } pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> { // SAFETY: valid owned writable staging of exactly the allocation // size; current owner context; caller synchronizes or leaks as // above. No borrowed output is passed directly to the driver. - crate::compute_drain::timed(3, || check("cuMemcpyDtoH_v2", unsafe { - (self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len()) - })) + crate::compute_drain::timed(3, || { + check("cuMemcpyDtoH_v2", unsafe { (self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len()) }) + }) } pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> { if destination == 0 || bytes == 0 { @@ -103,38 +99,27 @@ impl Api { } // SAFETY: caller owns the current-context allocation and has // validated this exact nonzero extent before dispatch. - crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe { - (self.zero)(destination, 0, bytes) - })) + crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe { (self.zero)(destination, 0, bytes) })) } - pub(crate) fn copy_mmq_weight( - &self, - destination: BufferHandle, - source: BufferHandle, - bytes: usize, - ) -> Result<()> { + pub(crate) fn copy_mmq_weight(&self, destination: BufferHandle, source: BufferHandle, bytes: usize) -> Result<()> { if !matches!(bytes, 627200 | 524800 | 704000 | 870400 | 921600 | 460800) { return Err(Error::InvalidProjectionShape); } // SAFETY: the closed MMQ facade validates actual same-context, // disjoint whole raw source and padded destination allocations. // Owners stay borrowed until synchronize/pop, with poison on uncertainty. - crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { - (self.copy_moe_down)(destination.0, source.0, bytes) - })) + crate::compute_drain::timed(6, || { + check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) }) + }) } - pub(crate) fn copy_moe_down( - &self, - destination: BufferHandle, - source: BufferHandle, - ) -> Result<()> { + pub(crate) fn copy_moe_down(&self, destination: BufferHandle, source: BufferHandle) -> Result<()> { // SAFETY: facade admits exact same-context disjoint owned extents, // a checked ten-slot destination address and exactly10240 bytes. // Both allocations remain borrowed until sync and context restore; // ambiguous completion poisons their context before any later free. - crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { - (self.copy_moe_down)(destination.0, source.0, 10_240) - })) + crate::compute_drain::timed(6, || { + check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 10_240) }) + }) } pub(crate) fn copy_original_down_group( &self, @@ -147,21 +132,17 @@ impl Api { } // SAFETY: actual affine grouped Down producer and prompt arena // supply disjoint checked extents; both survive sync and pop. - crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { - (self.copy_moe_down)(destination.0, source.0, bytes) - })) + crate::compute_drain::timed(6, || { + check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, bytes) }) + }) } - pub(crate) fn copy_moe_group_column( - &self, - destination: BufferHandle, - source: BufferHandle, - ) -> Result<()> { + pub(crate) fn copy_moe_group_column(&self, destination: BufferHandle, source: BufferHandle) -> Result<()> { // SAFETY: facade admits exact same-context disjoint owned extents, // a checked 64-column destination address and exactly2560 bytes. // Both allocations remain borrowed until sync and context restore; // ambiguous completion poisons their context before any later free. - crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe { - (self.copy_moe_down)(destination.0, source.0, 2560) - })) + crate::compute_drain::timed(6, || { + check("cuMemcpyDtoD_v2", unsafe { (self.copy_moe_down)(destination.0, source.0, 2560) }) + }) } } diff --git a/crates/cuda-driver/src/ffi/enabled/impl_drop_for_library.rs b/crates/cuda-driver/src/ffi/enabled/impl_drop_for_library.rs index 816b32de..4991857d 100644 --- a/crates/cuda-driver/src/ffi/enabled/impl_drop_for_library.rs +++ b/crates/cuda-driver/src/ffi/enabled/impl_drop_for_library.rs @@ -14,9 +14,5 @@ impl Drop for Library { } } pub(super) fn check(operation: &'static str, code: CuResult) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { operation, code }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation, code }) } } diff --git a/crates/cuda-driver/src/ffi/impl_api.rs b/crates/cuda-driver/src/ffi/impl_api.rs index 47abb916..32c0cf96 100644 --- a/crates/cuda-driver/src/ffi/impl_api.rs +++ b/crates/cuda-driver/src/ffi/impl_api.rs @@ -25,10 +25,7 @@ impl Api { format: Option<(crate::mmq::MmqFormat, crate::mmq::Tile)>, fixup: bool, ) -> Result { - let _ = ( - module.0, - format.map(|(f, j)| if fixup { f.fixup_entry(j) } else { f.entry(j) }), - ); + let _ = (module.0, format.map(|(f, j)| if fixup { f.fixup_entry(j) } else { f.entry(j) })); Err(Error::UnsupportedPlatform) } pub(crate) fn mmq_shared(&self, function: FunctionHandle, bytes: u32) -> Result<()> { @@ -38,11 +35,7 @@ impl Api { pub(crate) fn load_iq3_native_integer(&self) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn iq3_native_integer_function( - &self, - m: ModuleHandle, - reduce: bool, - ) -> Result { + pub(crate) fn iq3_native_integer_function(&self, m: ModuleHandle, reduce: bool) -> Result { let _ = (m.0, reduce); Err(Error::UnsupportedPlatform) } @@ -68,11 +61,7 @@ impl Api { let _ = crate::head_greedy::asset(); Err(Error::UnsupportedPlatform) } - pub(crate) fn head_greedy_function( - &self, - module: ModuleHandle, - last: bool, - ) -> Result { + pub(crate) fn head_greedy_function(&self, module: ModuleHandle, last: bool) -> Result { let _ = (module.0, last); Err(Error::UnsupportedPlatform) } @@ -139,12 +128,7 @@ impl Api { let _ = (m.0, k); Err(Error::UnsupportedPlatform) } - pub(crate) fn launch_mmq_resident( - &self, - f: FunctionHandle, - w: u32, - a: &mut MmqResidentArguments, - ) -> Result<()> { + pub(crate) fn launch_mmq_resident(&self, f: FunctionHandle, w: u32, a: &mut MmqResidentArguments) -> Result<()> { let _ = (f.0, w, a.parameters()); Err(Error::UnsupportedPlatform) } @@ -167,12 +151,7 @@ impl Api { let _ = (function.0, l, grid, args.parameters()); Err(Error::UnsupportedPlatform) } - pub(crate) fn fixup_mmq( - &self, - function: FunctionHandle, - grid: u32, - args: &mut MmqFixupArguments, - ) -> Result<()> { + pub(crate) fn fixup_mmq(&self, function: FunctionHandle, grid: u32, args: &mut MmqFixupArguments) -> Result<()> { let _ = (function.0, grid, args.parameters()); Err(Error::UnsupportedPlatform) } @@ -180,11 +159,7 @@ impl Api { pub(crate) fn load_qsa_selected(&self) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn qsa_selected_function( - &self, - module: ModuleHandle, - gather: bool, - ) -> Result { + pub(crate) fn qsa_selected_function(&self, module: ModuleHandle, gather: bool) -> Result { let _ = (module.0, gather); Err(Error::UnsupportedPlatform) } @@ -218,20 +193,12 @@ impl Api { Err(Error::UnsupportedPlatform) } pub(crate) fn load() -> Result { - if cfg!(feature = "cuda-driver") { - Err(Error::UnsupportedPlatform) - } else { - Err(Error::Disabled) - } + if cfg!(feature = "cuda-driver") { Err(Error::UnsupportedPlatform) } else { Err(Error::Disabled) } } pub(crate) fn load_fixed_module(&self, _: FixedOperation) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn fixed_function( - &self, - module: ModuleHandle, - operation: FixedOperation, - ) -> Result { + pub(crate) fn fixed_function(&self, module: ModuleHandle, operation: FixedOperation) -> Result { if let FixedOperation::Projection(kind) = operation { let _ = projection_entry(kind); } @@ -242,12 +209,7 @@ impl Api { let _ = module.0; Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - function: FunctionHandle, - _: u32, - arguments: &mut LaunchArguments, - ) -> Result<()> { + pub(crate) fn launch(&self, function: FunctionHandle, _: u32, arguments: &mut LaunchArguments) -> Result<()> { let _ = (function.0, arguments.storage); Err(Error::UnsupportedPlatform) } @@ -367,12 +329,7 @@ impl Api { pub(crate) fn copy_moe_down(&self, _: BufferHandle, _: BufferHandle) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy_original_down_group( - &self, - _: BufferHandle, - _: BufferHandle, - _: usize, - ) -> Result<()> { + pub(crate) fn copy_original_down_group(&self, _: BufferHandle, _: BufferHandle, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } } diff --git a/crates/cuda-driver/src/ffi/impl_contexthandle.rs b/crates/cuda-driver/src/ffi/impl_contexthandle.rs index 1ecb2956..f4797a91 100644 --- a/crates/cuda-driver/src/ffi/impl_contexthandle.rs +++ b/crates/cuda-driver/src/ffi/impl_contexthandle.rs @@ -5,11 +5,7 @@ use super::*; #[cfg(all( test, - not(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - )) + not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")) ))] impl ContextHandle { pub(in super::super) fn synthetic(address: usize) -> Self { @@ -25,20 +21,13 @@ impl BufferHandle { handle.validate_projection_extent(bytes, 16)?; Ok(handle) } - pub(crate) fn checked_subspan( - self, - allocation: usize, - offset: usize, - bytes: usize, - ) -> Result { + pub(crate) fn checked_subspan(self, allocation: usize, offset: usize, bytes: usize) -> Result { self.validate_extent(allocation)?; if bytes == 0 || offset.checked_add(bytes).is_none_or(|end| end > allocation) { return Err(Error::InvalidSize); } - let address = self - .0 - .checked_add(u64::try_from(offset).map_err(|_| Error::InvalidSize)?) - .ok_or(Error::InvalidSize)?; + let address = + self.0.checked_add(u64::try_from(offset).map_err(|_| Error::InvalidSize)?).ok_or(Error::InvalidSize)?; let result = Self(address); result.validate_extent(bytes)?; Ok(result) @@ -55,28 +44,19 @@ impl BufferHandle { } pub(crate) fn validate_projection_extent(self, bytes: usize, alignment: u64) -> Result<()> { let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidProjectionShape)?; - if self.0 == 0 - || bytes == 0 - || !self.0.is_multiple_of(alignment) - || self.0.checked_add(bytes).is_none() - { + if self.0 == 0 || bytes == 0 || !self.0.is_multiple_of(alignment) || self.0.checked_add(bytes).is_none() { return Err(Error::InvalidProjectionShape); } Ok(()) } // Admission validates both extents before this half-open range comparison. pub(crate) fn overlaps(self, bytes: usize, other: Self, other_bytes: usize) -> bool { - self.0 < other.0.saturating_add(other_bytes as u64) - && other.0 < self.0.saturating_add(bytes as u64) + self.0 < other.0.saturating_add(other_bytes as u64) && other.0 < self.0.saturating_add(bytes as u64) } // A pointer `offset` bytes into an allocation the facade already admitted whole (experimental attention // scratch: three partial buffers share one allocation). Overflow refuses. pub(in super::super) fn experimental_offset(self, offset: u64) -> Result { - Ok(Self( - self.0 - .checked_add(offset) - .ok_or(Error::InvalidProjectionShape)?, - )) + Ok(Self(self.0.checked_add(offset).ok_or(Error::InvalidProjectionShape)?)) } pub(in super::super) fn moe_group_column(self, total: usize, index: usize) -> Result { if !(1..=64).contains(&total) || index >= total { @@ -84,22 +64,14 @@ impl BufferHandle { } self.validate_projection_extent(total * 2560, 4)?; let offset = u64::try_from(index * 2560).map_err(|_| Error::InvalidProjectionShape)?; - Ok(Self( - self.0 - .checked_add(offset) - .ok_or(Error::InvalidProjectionShape)?, - )) + Ok(Self(self.0.checked_add(offset).ok_or(Error::InvalidProjectionShape)?)) } pub(in super::super) fn moe_group_down_column(self, total: usize, index: usize) -> Result { if !(1..=64).contains(&total) || index >= total { return Err(Error::InvalidProjectionShape); } self.validate_projection_extent(total * 10240, 4)?; - Ok(Self( - self.0 - .checked_add((index * 10240) as u64) - .ok_or(Error::InvalidProjectionShape)?, - )) + Ok(Self(self.0.checked_add((index * 10240) as u64).ok_or(Error::InvalidProjectionShape)?)) } // The only admitted interior address is one of ten fixed MoE Down slots. pub(crate) fn moe_down_slot(self, slot: u32) -> Result { @@ -107,9 +79,7 @@ impl BufferHandle { return Err(Error::InvalidQwenShape); } self.validate_projection_extent(102_400, 4)?; - let offset = u64::from(slot) - .checked_mul(10_240) - .ok_or(Error::InvalidQwenShape)?; + let offset = u64::from(slot).checked_mul(10_240).ok_or(Error::InvalidQwenShape)?; let address = self.0.checked_add(offset).ok_or(Error::InvalidQwenShape)?; let end = address.checked_add(10_240).ok_or(Error::InvalidQwenShape)?; if end > self.0.checked_add(102_400).ok_or(Error::InvalidQwenShape)? { @@ -129,14 +99,10 @@ pub(super) fn projection_ptx(kind: ProjectionKind) -> Option<&'static [u8]> { match kind { // Root-delivered STRA-146 frozen artifact341abbd0; independent // installed-Driver proof precedes this bounded public composition. - ProjectionKind::Dense(DenseFormat::Q8_0) => { - Some(concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes()) - } + ProjectionKind::Dense(DenseFormat::Q8_0) => Some(concat!(include_str!("../q8_0_q8_1.ptx"), "\0").as_bytes()), // Source-qualified STRA-154 Q4_K dense artifact; its independent // qualification receipt is 017f1d90. Keep the original dense entry. - ProjectionKind::Dense(DenseFormat::Q4_K) => { - Some(concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()) - } + ProjectionKind::Dense(DenseFormat::Q4_K) => Some(concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()), // Root-delivered STRA-148 frozen routed artifact f9c10814; its // standalone installed-Driver proof is distinct from composition. ProjectionKind::Routed(RoutedFormat::IQ3_XXS) => { @@ -153,32 +119,24 @@ pub(super) fn projection_ptx(kind: ProjectionKind) -> Option<&'static [u8]> { } // Root-delivered STRA-151 frozen paired IQ4_NL artifact 189b02ce. // One module contains the separately named dense and routed entries. - ProjectionKind::Dense(DenseFormat::IQ4_NL) - | ProjectionKind::Routed(RoutedFormat::IQ4_NL) => { + ProjectionKind::Dense(DenseFormat::IQ4_NL) | ProjectionKind::Routed(RoutedFormat::IQ4_NL) => { Some(concat!(include_str!("../iq4_nl_q8_1.ptx"), "\0").as_bytes()) } // Root-delivered STRA-152 frozen paired IQ4_XS artifact 2c853bad. // Its dense and routed entries share one isolated cache module. - ProjectionKind::Dense(DenseFormat::IQ4_XS) - | ProjectionKind::Routed(RoutedFormat::IQ4_XS) => { + ProjectionKind::Dense(DenseFormat::IQ4_XS) | ProjectionKind::Routed(RoutedFormat::IQ4_XS) => { Some(concat!(include_str!("../iq4_xs_q8_1.ptx"), "\0").as_bytes()) } // STRA-153 qualified the routed Q2_0 artifact independently (exact // producer source SHA-256: 8e81dbbaa76d8516476339c168f1d9c172341a78ccecda08714a13a5687e3b6e). // This fixed arm only composes that frozen asset; public GPU parity is // still a separate STRA-154 acceptance gate. - ProjectionKind::Routed(RoutedFormat::Q2_0) => { - Some(concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()) - } + ProjectionKind::Routed(RoutedFormat::Q2_0) => Some(concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()), } } #[cfg(any( test, - all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ) + all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64") ))] pub(super) fn validate_projection_ptx(bytes: &[u8]) -> Result<()> { // Installed Driver JIT rejects non-ASCII comment bytes even when ptxas @@ -207,19 +165,11 @@ pub(super) fn projection_entry(kind: ProjectionKind) -> &'static std::ffi::CStr } #[cfg(any( test, - all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ) + all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64") ))] impl ModuleHandle { pub(in super::super) fn qwen_success(address: usize) -> Result { - if address == 0 { - Err(Error::InvalidDriverValue("cuModuleLoadData")) - } else { - Ok(Self(address)) - } + if address == 0 { Err(Error::InvalidDriverValue("cuModuleLoadData")) } else { Ok(Self(address)) } } } #[cfg(test)] diff --git a/crates/cuda-driver/src/ffi/impl_functionhandle.rs b/crates/cuda-driver/src/ffi/impl_functionhandle.rs index 9a0a0610..b393a0ab 100644 --- a/crates/cuda-driver/src/ffi/impl_functionhandle.rs +++ b/crates/cuda-driver/src/ffi/impl_functionhandle.rs @@ -5,19 +5,11 @@ use super::*; #[cfg(any( test, - all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" - ) + all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64") ))] impl FunctionHandle { pub(in super::super) fn qwen_success(address: usize) -> Result { - if address == 0 { - Err(Error::InvalidDriverValue("cuModuleGetFunction")) - } else { - Ok(Self(address)) - } + if address == 0 { Err(Error::InvalidDriverValue("cuModuleGetFunction")) } else { Ok(Self(address)) } } } #[cfg(test)] @@ -42,9 +34,7 @@ impl LaunchArguments { } (*storage).parameters[3] = (&raw mut (*storage).count).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } impl Drop for LaunchArguments { @@ -71,9 +61,7 @@ impl GrReadGuardArguments { (*raw).parameters[i] = (&raw mut (*raw).addresses[i]).cast(); } } - Self { - storage: std::ptr::NonNull::new(raw).expect("Box non-null"), - } + Self { storage: std::ptr::NonNull::new(raw).expect("Box non-null") } } } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] @@ -108,18 +96,11 @@ impl MatvecArguments { (*storage).parameters[3] = (&raw mut (*storage).rows).cast(); (*storage).parameters[4] = (&raw mut (*storage).columns).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } impl Q8QuantizeArguments { - pub(crate) fn new( - input: BufferHandle, - scratch: BufferHandle, - status: BufferHandle, - elements: u32, - ) -> Self { + pub(crate) fn new(input: BufferHandle, scratch: BufferHandle, status: BufferHandle, elements: u32) -> Self { let storage = Box::into_raw(Box::new(Q8QuantizeStorage { addresses: [input.0, scratch.0, status.0], elements, @@ -132,9 +113,7 @@ impl Q8QuantizeArguments { } (*storage).parameters[3] = (&raw mut (*storage).elements).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } impl Drop for Q8QuantizeArguments { @@ -165,9 +144,7 @@ impl Q6ProjectionArguments { (*storage).parameters[3] = (&raw mut (*storage).rows).cast(); (*storage).parameters[4] = (&raw mut (*storage).columns).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } impl Drop for Q6ProjectionArguments { @@ -198,9 +175,7 @@ impl ProjectionArguments { (*storage).parameters[3] = (&raw mut (*storage).rows).cast(); (*storage).parameters[4] = (&raw mut (*storage).columns).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } impl Drop for ProjectionArguments { @@ -231,8 +206,6 @@ impl Q5ProjectionArguments { (*storage).parameters[3] = (&raw mut (*storage).rows).cast(); (*storage).parameters[4] = (&raw mut (*storage).columns).cast(); } - Self { - storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"), - } + Self { storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null") } } } diff --git a/crates/cuda-driver/src/ffi/projection_tests.rs b/crates/cuda-driver/src/ffi/projection_tests.rs index 43a27d3b..bd5a4f48 100644 --- a/crates/cuda-driver/src/ffi/projection_tests.rs +++ b/crates/cuda-driver/src/ffi/projection_tests.rs @@ -3,14 +3,8 @@ use super::*; #[test] fn new_fixed_asset_encoding_refuses_unicode_before_driver_call() { - assert_eq!( - validate_projection_ptx(include_bytes!("../q6_k_q8_1.ptx")), - Ok(()) - ); - assert_eq!( - validate_projection_ptx(include_bytes!("../q8_1_quantize.ptx")), - Ok(()) - ); + assert_eq!(validate_projection_ptx(include_bytes!("../q6_k_q8_1.ptx")), Ok(())); + assert_eq!(validate_projection_ptx(include_bytes!("../q8_1_quantize.ptx")), Ok(())); assert_eq!(validate_projection_ptx(b"// plain ASCII\n\0"), Ok(())); assert_eq!( validate_projection_ptx("// \u{d7}\n\0".as_bytes()), @@ -21,10 +15,7 @@ fn new_fixed_asset_encoding_refuses_unicode_before_driver_call() { fn q4_k_dense_selector_resolves_only_its_qualified_asset() { let kind = ProjectionKind::Dense(DenseFormat::Q4_K); let bytes = projection_ptx(kind).expect("fixed Q4_K asset is integrated"); - assert_eq!( - bytes, - concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes() - ); + assert_eq!(bytes, concat!(include_str!("../q4_k_q8_1.ptx"), "\0").as_bytes()); assert_eq!(validate_projection_ptx(bytes), Ok(())); assert_eq!(projection_entry(kind).to_bytes(), b"leleka_q4_k_q8_1_dense"); } @@ -32,43 +23,25 @@ fn q4_k_dense_selector_resolves_only_its_qualified_asset() { fn iq3_s_routed_selector_resolves_only_its_qualified_asset() { let kind = ProjectionKind::Routed(RoutedFormat::IQ3_S); let bytes = projection_ptx(kind).expect("fixed IQ3_S asset is integrated"); - assert_eq!( - bytes, - concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes() - ); + assert_eq!(bytes, concat!(include_str!("../iq3_s_q8_1.ptx"), "\0").as_bytes()); assert_eq!(validate_projection_ptx(bytes), Ok(())); - assert_eq!( - projection_entry(kind).to_bytes(), - b"leleka_iq3_s_q8_1_routed" - ); + assert_eq!(projection_entry(kind).to_bytes(), b"leleka_iq3_s_q8_1_routed"); } #[test] fn iq2_s_routed_selector_resolves_only_its_qualified_asset() { let kind = ProjectionKind::Routed(RoutedFormat::IQ2_S); let bytes = projection_ptx(kind).expect("fixed IQ2_S asset is integrated"); - assert_eq!( - bytes, - concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes() - ); + assert_eq!(bytes, concat!(include_str!("../iq2_s_q8_1.ptx"), "\0").as_bytes()); assert_eq!(validate_projection_ptx(bytes), Ok(())); - assert_eq!( - projection_entry(kind).to_bytes(), - b"leleka_iq2_s_q8_1_routed" - ); + assert_eq!(projection_entry(kind).to_bytes(), b"leleka_iq2_s_q8_1_routed"); } #[test] fn q2_0_routed_selector_resolves_only_its_qualified_asset() { let kind = ProjectionKind::Routed(RoutedFormat::Q2_0); let bytes = projection_ptx(kind).expect("fixed Q2_0 asset is integrated"); - assert_eq!( - bytes, - concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes() - ); + assert_eq!(bytes, concat!(include_str!("../q2_0_q8_1.ptx"), "\0").as_bytes()); assert_eq!(validate_projection_ptx(bytes), Ok(())); - assert_eq!( - projection_entry(kind).to_bytes(), - b"leleka_q2_0_q8_1_routed" - ); + assert_eq!(projection_entry(kind).to_bytes(), b"leleka_q2_0_q8_1_routed"); } #[test] fn iq4_nl_dense_and_routed_select_distinct_entries_from_one_asset() { @@ -78,14 +51,8 @@ fn iq4_nl_dense_and_routed_select_distinct_entries_from_one_asset() { assert_eq!(projection_ptx(dense), Some(bytes)); assert_eq!(projection_ptx(routed), Some(bytes)); assert_eq!(validate_projection_ptx(bytes), Ok(())); - assert_eq!( - projection_entry(dense).to_bytes(), - b"leleka_iq4_nl_q8_1_dense" - ); - assert_eq!( - projection_entry(routed).to_bytes(), - b"leleka_iq4_nl_q8_1_routed" - ); + assert_eq!(projection_entry(dense).to_bytes(), b"leleka_iq4_nl_q8_1_dense"); + assert_eq!(projection_entry(routed).to_bytes(), b"leleka_iq4_nl_q8_1_routed"); } #[test] fn iq4_xs_dense_and_routed_select_distinct_entries_from_one_asset() { @@ -95,38 +62,20 @@ fn iq4_xs_dense_and_routed_select_distinct_entries_from_one_asset() { assert_eq!(projection_ptx(dense), Some(bytes)); assert_eq!(projection_ptx(routed), Some(bytes)); assert_eq!(validate_projection_ptx(bytes), Ok(())); - assert_eq!( - projection_entry(dense).to_bytes(), - b"leleka_iq4_xs_q8_1_dense" - ); - assert_eq!( - projection_entry(routed).to_bytes(), - b"leleka_iq4_xs_q8_1_routed" - ); + assert_eq!(projection_entry(dense).to_bytes(), b"leleka_iq4_xs_q8_1_dense"); + assert_eq!(projection_entry(routed).to_bytes(), b"leleka_iq4_xs_q8_1_routed"); } #[test] fn packed_alignment_extents_and_overlap() { assert_eq!(BufferHandle(2).validate_projection_extent(34, 2), Ok(())); - assert_eq!( - BufferHandle(2).validate_projection_extent(4, 4), - Err(Error::InvalidProjectionShape) - ); - assert_eq!( - BufferHandle(u64::MAX - 1).validate_projection_extent(4, 2), - Err(Error::InvalidProjectionShape) - ); + assert_eq!(BufferHandle(2).validate_projection_extent(4, 4), Err(Error::InvalidProjectionShape)); + assert_eq!(BufferHandle(u64::MAX - 1).validate_projection_extent(4, 2), Err(Error::InvalidProjectionShape)); assert!(BufferHandle(16).overlaps(8, BufferHandle(12), 8)); assert!(!BufferHandle(16).overlaps(8, BufferHandle(8), 8)); } #[test] fn common_projection_raw_owner_keeps_exact_parameter_widths() { - let args = ProjectionArguments::new( - BufferHandle(11), - BufferHandle(22), - BufferHandle(33), - 129, - u32::MAX, - ); + let args = ProjectionArguments::new(BufferHandle(11), BufferHandle(22), BufferHandle(33), 129, u32::MAX); let pointer = args.storage.as_ptr(); let moved = vec![args].pop().unwrap(); let churn: Vec<_> = (0..1024).map(|_| Box::new([7u64; 8])).collect(); diff --git a/crates/cuda-driver/src/ffi/tests.rs b/crates/cuda-driver/src/ffi/tests.rs index 264d4286..ee1511d6 100644 --- a/crates/cuda-driver/src/ffi/tests.rs +++ b/crates/cuda-driver/src/ffi/tests.rs @@ -7,49 +7,23 @@ fn checked_subspan_refuses_empty_wrap_and_outside_allocation() { assert!(h.checked_subspan(1024, 0, 1024).is_ok()); assert!(h.checked_subspan(1024, 1023, 1).is_ok()); for (offset, bytes) in [(0, 0), (1024, 1), (1023, 2), (usize::MAX, 1)] { - assert!(matches!( - h.checked_subspan(1024, offset, bytes), - Err(Error::InvalidSize) - )); + assert!(matches!(h.checked_subspan(1024, offset, bytes), Err(Error::InvalidSize))); } - assert!( - super::BufferHandle::synthetic(u64::MAX - 2) - .checked_subspan(4, 0, 1) - .is_err() - ); - assert!( - super::BufferHandle::synthetic(0) - .checked_subspan(4, 0, 1) - .is_err() - ); + assert!(super::BufferHandle::synthetic(u64::MAX - 2).checked_subspan(4, 0, 1).is_err()); + assert!(super::BufferHandle::synthetic(0).checked_subspan(4, 0, 1).is_err()); } use super::*; #[test] fn matvec_address_extents() { - assert_eq!( - BufferHandle(0).validate_extent(4), - Err(Error::InvalidMatvecShape) - ); - assert_eq!( - BufferHandle(1).validate_extent(0), - Err(Error::InvalidMatvecShape) - ); - assert_eq!( - BufferHandle(u64::MAX - 3).validate_extent(4), - Err(Error::InvalidMatvecShape) - ); + assert_eq!(BufferHandle(0).validate_extent(4), Err(Error::InvalidMatvecShape)); + assert_eq!(BufferHandle(1).validate_extent(0), Err(Error::InvalidMatvecShape)); + assert_eq!(BufferHandle(u64::MAX - 3).validate_extent(4), Err(Error::InvalidMatvecShape)); assert_eq!(BufferHandle(u64::MAX - 4).validate_extent(4), Ok(())); } #[test] fn matvec_raw_storage_survives_owner_moves() { - let arguments = MatvecArguments::new( - BufferHandle(11), - BufferHandle(22), - BufferHandle(33), - 129, - u32::MAX, - ); + let arguments = MatvecArguments::new(BufferHandle(11), BufferHandle(22), BufferHandle(33), 129, u32::MAX); let pointer = arguments.storage.as_ptr(); let moved = vec![arguments].pop().unwrap(); let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect(); diff --git a/crates/cuda-driver/src/gdn_batch_gemm.rs b/crates/cuda-driver/src/gdn_batch_gemm.rs index acbd5681..29da540e 100644 --- a/crates/cuda-driver/src/gdn_batch_gemm.rs +++ b/crates/cuda-driver/src/gdn_batch_gemm.rs @@ -17,10 +17,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { if stream == 0 { return Err(Error::InvalidDriverValue("native GDN shared stream")); } - Ok(Self { - workspace, - stream: GdnStream::from_raw(stream), - }) + Ok(Self { workspace, stream: GdnStream::from_raw(stream) }) } fn enqueue( @@ -41,8 +38,8 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640) ); if bf16 { - let interleaved = (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96) - && matches!(shape.y_offset, 0 | 48); + let interleaved = + (shape.rows, shape.depth, shape.ldy) == (48, 2560, 96) && matches!(shape.y_offset, 0 | 48); let moe = matches!((shape.rows, shape.depth), (512, 2560) | (1, 2560)) && shape.ldy == shape.rows && shape.y_offset == 0; @@ -61,8 +58,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { || (!bf16 && w.bytes != matrix_bytes && w.bytes != DEQUANT_BYTES - && !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640)) - && w.bytes == 3_276_800)) + && !(matches!((shape.rows, shape.depth), (640, 2560) | (2560, 640)) && w.bytes == 3_276_800)) { return Err(Error::InvalidQwenShape); } @@ -79,10 +75,7 @@ impl<'loan, 'ctx> NativeGdnGemm<'loan, 'ctx> { let xh = x.handle.ok_or(Error::ContextPoisoned)?; let wh = w.handle.ok_or(Error::ContextPoisoned)?; let yh = y.handle.ok_or(Error::ContextPoisoned)?; - if xh.overlaps(x.bytes, wh, w.bytes) - || xh.overlaps(x.bytes, yh, y.bytes) - || wh.overlaps(w.bytes, yh, y.bytes) - { + if xh.overlaps(x.bytes, wh, w.bytes) || xh.overlaps(x.bytes, yh, y.bytes) || wh.overlaps(w.bytes, yh, y.bytes) { return Err(Error::OutputAliasesInput); } self.workspace.blas()?.gemm_gdn( @@ -104,22 +97,10 @@ impl GdnGemm for NativeGdnGemm<'_, '_> { fn stream(&self) -> GdnStream { self.stream } - fn f16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.enqueue(false, x, w, y, shape) } - fn bf16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.enqueue(true, x, w, y, shape) } } diff --git a/crates/cuda-driver/src/gdn_closed_queue.rs b/crates/cuda-driver/src/gdn_closed_queue.rs index 33c32eb5..15aac277 100644 --- a/crates/cuda-driver/src/gdn_closed_queue.rs +++ b/crates/cuda-driver/src/gdn_closed_queue.rs @@ -154,10 +154,7 @@ mod tests { fn column_rows_are_only_whole_batch_multiples_of_one_qkv_row() { assert_eq!(column_row_offset(QKV_BYTES, 0).unwrap(), 0); assert_eq!(column_row_offset(3 * QKV_BYTES, 2).unwrap(), 2 * QKV_BYTES); - assert_eq!( - column_row_offset(64 * QKV_BYTES, 63).unwrap(), - 63 * QKV_BYTES - ); + assert_eq!(column_row_offset(64 * QKV_BYTES, 63).unwrap(), 63 * QKV_BYTES); for (total, row) in [ (0, 0), (QKV_BYTES - 4, 0), @@ -166,10 +163,7 @@ mod tests { (65 * QKV_BYTES, 0), (QKV_BYTES, usize::MAX), ] { - assert!(matches!( - column_row_offset(total, row), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(column_row_offset(total, row), Err(Error::InvalidQwenShape))); } } @@ -204,15 +198,9 @@ mod tests { assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, None); words[GdnQueueStage::Gate.slot()] = 1; words[GdnQueueStage::NextState.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap().1, - Some(GdnQueueStage::Gate) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, Some(GdnQueueStage::Gate)); words[GdnQueueStage::Alpha.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap().1, - Some(GdnQueueStage::Alpha) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap().1, Some(GdnQueueStage::Alpha)); } #[test] @@ -220,41 +208,24 @@ mod tests { let mut words = [0u32; SLOTS]; words[GdnQueueStage::Z.slot()] = 1; // Only the first Z-1 stages were admitted: a set unused slot is invalid. - assert!(matches!( - decode_statuses(&bytes(&words), GdnQueueStage::Z.slot()), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(decode_statuses(&bytes(&words), GdnQueueStage::Z.slot()), Err(Error::InvalidDriverValue(_)))); words[GdnQueueStage::Z.slot()] = 2; - assert!(matches!( - decode_statuses(&bytes(&words), SLOTS), - Err(Error::InvalidDriverValue(_)) - )); - assert!(matches!( - decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(decode_statuses(&bytes(&words), SLOTS), Err(Error::InvalidDriverValue(_)))); + assert!(matches!(decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), Err(Error::InvalidQwenShape))); + assert!(matches!(decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), Err(Error::InvalidQwenShape))); } } -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_closed_queue_gpu.rs"] mod gpu; #[path = "gdn_closed_queue/impl_gdnqueuestage.rs"] mod impl_gdnqueuestage; #[allow(unused_imports)] -use impl_gdnqueuestage::decode_statuses; -#[allow(unused_imports)] use impl_gdnqueuestage::column_row_offset; +#[allow(unused_imports)] +use impl_gdnqueuestage::decode_statuses; #[path = "gdn_closed_queue/impl_gdnrowprefix.rs"] mod impl_gdnrowprefix; #[path = "gdn_closed_queue/impl_gdnrowqueue.rs"] diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs index 15a505f8..ece0f612 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs @@ -48,11 +48,7 @@ pub(super) fn decode_statuses(bytes: &[u8], checks: usize) -> Result<([u32; SLOT return Err(Error::InvalidDriverValue("GDN row numeric witness")); } } - let refusal = decoded - .iter() - .take(checks) - .position(|status| *status != 0) - .map(|slot| STAGES[slot]); + let refusal = decoded.iter().take(checks).position(|status| *status != 0).map(|slot| STAGES[slot]); Ok((decoded, refusal)) } @@ -95,32 +91,19 @@ impl<'ctx> GdnRowQueue<'ctx> { return Err(Error::ContextPoisoned); } for operation in OPS { - qwen_ffi::asset(operation) - .ok_or(Error::UnsupportedQwenOperation)? - .validate(operation)?; + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; } - if context - .allocated_bytes() - .checked_add(STATUS_BYTES) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - status: None, - module: None, - kernels: None, - failed: false, - }; + let mut owner = Self { context, status: None, module: None, kernels: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); let guard = context.enter()?; let load = (|| { let mut qwen = [None; 6]; for (i, operation) in OPS.into_iter().enumerate() { - let asset = - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); } let module = context.driver.api.load_mmq_resident()?; @@ -172,12 +155,9 @@ impl<'ctx> GdnRowQueue<'ctx> { pub fn begin<'lease>(&'lease mut self) -> Result> { self.status_handle()?; let mut held = Vec::new(); - held.try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; + held.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; Ok(GdnRowPrefix { queue: self, held, diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs index e656466d..4864a16f 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { pub(in super::super) fn ready(&self, step: Step) -> Result<()> { if let Some(error) = &self.refusal { @@ -93,9 +91,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { } let words = stage.words(); let queue = &*self.queue; - let status = queue - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + let status = queue.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.finite; self.commands.push(Command::Guard( function, @@ -112,11 +108,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { /// `tokens x 10,240` F32 owner of one batched projection; the fixed /// 40,960 B row range is derived here (never caller supplied) exactly as the /// recurrence derives its Q/K/V ranges from completed whole producers. - pub fn scan_qkv_columns( - &mut self, - columns: &'lease DeviceBuffer<'lease>, - row: usize, - ) -> Result<()> { + pub fn scan_qkv_columns(&mut self, columns: &'lease DeviceBuffer<'lease>, row: usize) -> Result<()> { let result = (|| { self.ready(Step::Alpha)?; if self.checks != 0 || self.columns.is_some() { @@ -228,15 +220,9 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { self.commands.push(Command::Qwen( function, Operation::GdnConv, - Box::new(Arguments::with_layout( - Operation::GdnConv, - original, - handles, - 0.0, - )), + Box::new(Arguments::with_layout(Operation::GdnConv, original, handles, 0.0)), )); - self.held - .extend_from_slice(&[history, columns, weights, next_history, raw, h]); + self.held.extend_from_slice(&[history, columns, weights, next_history, raw, h]); self.push_scan(GdnQueueStage::ConvRaw, raw)?; self.push_scan(GdnQueueStage::NextHistory, next_history)?; self.push_scan(GdnQueueStage::ConvH, h)?; diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs index 9d422009..d9187df5 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { /// Original Q/K L2 kernel into the whole 10,240-word slot; the scan covers /// the initialized tail too, as the scalar chain's full readback did. @@ -84,17 +82,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { // Admit the WHOLE real allocations, including aliases outside the // consumed ranges, before deriving any private pointer operands. let mut whole = original; - whole.bytes = [ - STATE_BYTES, - QK_BYTES, - QK_BYTES, - 192, - 192, - STATE_BYTES, - 24_576, - 0, - 0, - ]; + whole.bytes = [STATE_BYTES, QK_BYTES, QK_BYTES, 192, 192, STATE_BYTES, 24_576, 0, 0]; whole.align = [4; 9]; whole.count = 7; whole.outputs = 0b110_0000; @@ -119,23 +107,15 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { let q = owners[1].checked_subspan(QK_BYTES, 0, 8192)?; let k = owners[1].checked_subspan(QK_BYTES, 8192, 8192)?; let v = owners[2].checked_subspan(QK_BYTES, 16_384, 24_576)?; - let handles = [ - owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], - ]; + let handles = [owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0]]; ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; let function = queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[STEP]; self.commands.push(Command::Qwen( function, Operation::GdnStep, - Box::new(Arguments::with_layout( - Operation::GdnStep, - original, - handles, - 0.0, - )), + Box::new(Arguments::with_layout(Operation::GdnStep, original, handles, 0.0)), )); - self.held - .extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]); + self.held.extend_from_slice(&[state, qk, h, gate, beta, next_state, readout]); // Earliest full-state refusal precedes the readout, as before. self.push_scan(GdnQueueStage::NextState, next_state)?; self.push_scan(GdnQueueStage::Readout, readout)?; @@ -207,11 +187,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { } Ok(GdnRowCompletion { refusal: drained.refusal, - next_history: if drained.refusal.is_none() { - drained.next_history - } else { - None - }, + next_history: if drained.refusal.is_none() { drained.next_history } else { None }, }) } } diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs index 5d2ee4e8..967ef24d 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowprefix/impl_gdnrowprefix_3.rs @@ -3,33 +3,21 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { - pub(in super::super) fn drain(mut self, fetch: bool) -> Result { let status = self.queue.status_handle()?; let mut statuses = staging(STATUS_BYTES)?; let write_fetch = fetch && self.refusal.is_none(); let mut fetched = staging(if write_fetch { HISTORY_BYTES } else { 0 })?; if !self.commands.is_empty() { - let zero = self - .queue - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .zero; + let zero = self.queue.kernels.as_ref().ok_or(Error::ContextPoisoned)?.zero; let mut reset = ffi::MmqResidentArguments::zero(status, SLOTS as u32); let context = self.queue.context; let guard = context.enter().inspect_err(|_| { self.queue.failed = true; context.poisoned.set(true); })?; - let mut operation = - context - .driver - .api - .launch_mmq_resident(zero, SLOTS as u32, &mut reset); + let mut operation = context.driver.api.launch_mmq_resident(zero, SLOTS as u32, &mut reset); for command in &mut self.commands { if operation.is_err() { break; @@ -53,8 +41,7 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { // Completion is uncertain: retain every actual argument/staging // owner and every borrowed buffer; Context poison forbids reuse. std::mem::forget((reset, self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain GDN row drain")); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN row drain")); } combine(combine(operation, sync), pop)?; } @@ -68,24 +55,12 @@ impl<'lease, 'ctx> GdnRowPrefix<'lease, 'ctx> { }; let next_history = if write_fetch && refusal.is_none() { let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_BYTES / 4) - .map_err(|_| Error::HostAllocation)?; - values.extend( - fetched - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(HISTORY_BYTES / 4).map_err(|_| Error::HostAllocation)?; + values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); Some(values.into_boxed_slice()) } else { None }; - Ok(Drained { - refusal, - deferred: self.refusal, - next_history, - }) + Ok(Drained { refusal, deferred: self.refusal, next_history }) } } diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs index af125a7d..aae1d781 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnrowqueue.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl GdnRowQueue<'_> { pub(super) fn close_inner(&mut self) -> Result<()> { self.failed = true; @@ -51,9 +50,7 @@ impl Drop for GdnRowQueue<'_> { } pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs index f5cc959d..748ae42f 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu.rs @@ -70,42 +70,11 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { } // Earliest refusal in program order, then the queue stays usable. let cases = [ - ( - Poison { - alpha: true, - ..Poison::default() - }, - GdnQueueStage::Alpha, - ), - ( - Poison { - conv_weights: true, - ..Poison::default() - }, - GdnQueueStage::ConvRaw, - ), - ( - Poison { - state: true, - ..Poison::default() - }, - GdnQueueStage::NextState, - ), - ( - Poison { - z: true, - ..Poison::default() - }, - GdnQueueStage::Z, - ), - ( - Poison { - alpha: true, - z: true, - ..Poison::default() - }, - GdnQueueStage::Alpha, - ), + (Poison { alpha: true, ..Poison::default() }, GdnQueueStage::Alpha), + (Poison { conv_weights: true, ..Poison::default() }, GdnQueueStage::ConvRaw), + (Poison { state: true, ..Poison::default() }, GdnQueueStage::NextState), + (Poison { z: true, ..Poison::default() }, GdnQueueStage::Z), + (Poison { alpha: true, z: true, ..Poison::default() }, GdnQueueStage::Alpha), ]; for (poison, stage) in cases { refusal_case(&context, &mut queue, poison, stage, &mut report)?; @@ -114,36 +83,9 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { // Retained batched QKV rows: first, middle and last of a 3-row and a // 64-row batch; a poisoned OTHER row is irrelevant, the USED row refuses. for (tokens, used) in [(3usize, 0usize), (3, 1), (3, 2), (64, 63)] { - columns_pair( - &context, - &mut queue, - 8, - tokens, - used, - false, - false, - &mut report, - )?; - columns_pair( - &context, - &mut queue, - 8, - tokens, - used, - false, - true, - &mut report, - )?; - columns_pair( - &context, - &mut queue, - 8, - tokens, - used, - true, - false, - &mut report, - )?; + columns_pair(&context, &mut queue, 8, tokens, used, false, false, &mut report)?; + columns_pair(&context, &mut queue, 8, tokens, used, false, true, &mut report)?; + columns_pair(&context, &mut queue, 8, tokens, used, true, false, &mut report)?; clean_pair(&context, &mut queue, 3, &mut report)?; } // Program order, data flow, aliasing, context and shape admission. @@ -153,14 +95,7 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { // Convolution before the two input scans. let mut prefix = queue.begin()?; refuse( - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - ), + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), Error::InvalidQwenShape, &mut report, )?; @@ -169,57 +104,27 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - )?; - refuse( - prefix.qk_l2(&row.raw, &row.qk, EPSILON), - Error::InvalidQwenShape, - &mut report, - )?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + refuse(prefix.qk_l2(&row.raw, &row.qk, EPSILON), Error::InvalidQwenShape, &mut report)?; // A latched admission error still drains the admitted prefix first. refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; // Recurrence whose current state and next state are one owner. let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - )?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; prefix.qk_l2(&row.h, &row.qk, EPSILON)?; prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; refuse( - prefix.recurrence( - &row.state, - &row.qk, - &row.h, - &row.gate, - &row.sigmoid, - &row.state, - &row.readout, - ), + prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.state, &row.readout), Error::OutputAliasesInput, &mut report, )?; refuse(prefix.finish(), Error::OutputAliasesInput, &mut report)?; // A buffer from another Context. let mut prefix = queue.begin()?; - refuse( - prefix.scan_alpha(&other.alpha), - Error::ContextMismatch, - &mut report, - )?; + refuse(prefix.scan_alpha(&other.alpha), Error::ContextMismatch, &mut report)?; refuse(prefix.finish(), Error::ContextMismatch, &mut report)?; // A whole buffer of the wrong size. let short = blank(&context, 47)?; @@ -233,19 +138,8 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - )?; - refuse( - prefix.fetch_next_history(&row.history), - Error::InvalidQwenShape, - &mut report, - )?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; + refuse(prefix.fetch_next_history(&row.history), Error::InvalidQwenShape, &mut report)?; refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; @@ -258,32 +152,17 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { let image = upload(&context, &column_image(1, 3, 1))?; let admission = (|| -> Result<()> { let mut prefix = queue.begin()?; - refuse( - prefix.scan_qkv_columns(&ragged, 0), - Error::InvalidQwenShape, - &mut report, - )?; + refuse(prefix.scan_qkv_columns(&ragged, 0), Error::InvalidQwenShape, &mut report)?; refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; let mut prefix = queue.begin()?; - refuse( - prefix.scan_qkv_columns(&image, 3), - Error::InvalidQwenShape, - &mut report, - )?; + refuse(prefix.scan_qkv_columns(&image, 3), Error::InvalidQwenShape, &mut report)?; refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; let mut prefix = queue.begin()?; prefix.scan_qkv_columns(&image, 1)?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; refuse( - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - ), + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h), Error::InvalidQwenShape, &mut report, )?; @@ -308,11 +187,7 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; - refuse( - prefix.scan_qkv_columns(&image, 1), - Error::InvalidQwenShape, - &mut report, - )?; + refuse(prefix.scan_qkv_columns(&image, 1), Error::InvalidQwenShape, &mut report)?; refuse(prefix.finish(), Error::InvalidQwenShape, &mut report)?; // The retained-row conv over another owner than the scanned one. let mut prefix = queue.begin()?; @@ -359,32 +234,32 @@ fn queued_gdn_row_matches_scalar_calls_orders_refusals_and_cleans_up() { #[path = "gdn_closed_queue_gpu/bytes_fn.rs"] mod bytes_fn; #[allow(unused_imports)] -use bytes_fn::bytes; -#[allow(unused_imports)] -use bytes_fn::upload; -#[allow(unused_imports)] use bytes_fn::blank; #[allow(unused_imports)] -use bytes_fn::read; +use bytes_fn::bytes; +#[allow(unused_imports)] +use bytes_fn::column_image; #[allow(unused_imports)] use bytes_fn::pattern; #[allow(unused_imports)] -use bytes_fn::scalar; -#[allow(unused_imports)] use bytes_fn::queued; #[allow(unused_imports)] use bytes_fn::queued_columns; #[allow(unused_imports)] -use bytes_fn::column_image; +use bytes_fn::read; +#[allow(unused_imports)] +use bytes_fn::scalar; +#[allow(unused_imports)] +use bytes_fn::upload; #[path = "gdn_closed_queue_gpu/columns_pair_fn.rs"] mod columns_pair_fn; #[allow(unused_imports)] +use columns_pair_fn::clean_pair; +#[allow(unused_imports)] use columns_pair_fn::columns_pair; #[allow(unused_imports)] use columns_pair_fn::compare; #[allow(unused_imports)] -use columns_pair_fn::clean_pair; -#[allow(unused_imports)] use columns_pair_fn::refusal_case; #[allow(unused_imports)] use columns_pair_fn::refuse; diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs index a41909d0..e7f493e2 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/bytes_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn bytes(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } @@ -23,9 +22,7 @@ pub(super) fn read(buffer: &DeviceBuffer<'_>) -> Result> { Ok(out) } pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec { - (0..count) - .map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset) - .collect() + (0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect() } impl<'a> Row<'a> { pub(super) fn new(context: &'a Context<'_>, salt: usize, poison: Poison) -> Result { @@ -34,9 +31,7 @@ impl<'a> Row<'a> { if poison.alpha { alpha[47] = nan; } - let mut weights = (0..4 * CHANNELS) - .map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4]) - .collect::>(); + let mut weights = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][(i + salt) % 4]).collect::>(); if poison.conv_weights { weights[4 * CHANNELS - 1] = nan; } @@ -119,14 +114,7 @@ impl<'a> Row<'a> { /// Independent original sequence: every launch separately completed. pub(super) fn scalar(context: &Context<'_>, row: &mut Row<'_>) -> Result<()> { - context.gdn_conv_silu_f32( - &row.history, - &row.qkv, - &row.weights, - &mut row.next_history, - &mut row.raw, - &mut row.h, - )?; + context.gdn_conv_silu_f32(&row.history, &row.qkv, &row.weights, &mut row.next_history, &mut row.raw, &mut row.h)?; context.gdn_qk_l2_f32(&row.h, &mut row.qk, EPSILON)?; context.gdn_beta_sigmoid_f32(&row.beta_raw, &mut row.sigmoid)?; context.gdn_gate_softplus_f32(&row.alpha, &row.dt, &row.a, &mut row.gate)?; @@ -139,39 +127,18 @@ pub(super) fn scalar(context: &Context<'_>, row: &mut Row<'_>) -> Result<()> { &mut row.next_state, &mut row.readout, )?; - context.gdn_out_norm_f32( - &row.readout, - &row.z, - &row.gamma, - &mut row.normalized, - EPSILON, - ) + context.gdn_out_norm_f32(&row.readout, &row.z, &row.gamma, &mut row.normalized, EPSILON) } pub(super) fn queued<'q>(queue: &'q mut GdnRowQueue<'_>, row: &'q Row<'_>) -> Result { let mut prefix = queue.begin()?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu( - &row.history, - &row.qkv, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - )?; + prefix.conv_silu(&row.history, &row.qkv, &row.weights, &row.next_history, &row.raw, &row.h)?; prefix.qk_l2(&row.h, &row.qk, EPSILON)?; prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; - prefix.recurrence( - &row.state, - &row.qk, - &row.h, - &row.gate, - &row.sigmoid, - &row.next_state, - &row.readout, - )?; + prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.next_state, &row.readout)?; prefix.scan_z(&row.z)?; prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?; prefix.fetch_next_history(&row.next_history)?; @@ -190,27 +157,11 @@ pub(super) fn queued_columns<'q>( prefix.scan_qkv_columns(columns, index)?; prefix.scan_alpha(&row.alpha)?; prefix.scan_beta_raw(&row.beta_raw)?; - prefix.conv_silu_columns( - &row.history, - columns, - index, - &row.weights, - &row.next_history, - &row.raw, - &row.h, - )?; + prefix.conv_silu_columns(&row.history, columns, index, &row.weights, &row.next_history, &row.raw, &row.h)?; prefix.qk_l2(&row.h, &row.qk, EPSILON)?; prefix.beta_sigmoid(&row.beta_raw, &row.sigmoid)?; prefix.gate_softplus(&row.alpha, &row.dt, &row.a, &row.gate)?; - prefix.recurrence( - &row.state, - &row.qk, - &row.h, - &row.gate, - &row.sigmoid, - &row.next_state, - &row.readout, - )?; + prefix.recurrence(&row.state, &row.qk, &row.h, &row.gate, &row.sigmoid, &row.next_state, &row.readout)?; prefix.scan_z(&row.z)?; prefix.out_norm(&row.readout, &row.z, &row.gamma, &row.normalized, EPSILON)?; prefix.fetch_next_history(&row.next_history)?; @@ -221,11 +172,7 @@ pub(super) fn queued_columns<'q>( pub(super) fn column_image(salt: usize, tokens: usize, used: usize) -> Vec { let mut image = Vec::with_capacity(tokens * CHANNELS); for row in 0..tokens { - let source = if row == used { - salt + 1 - } else { - salt + 40 + row - }; + let source = if row == used { salt + 1 } else { salt + 40 + row }; image.extend(pattern(CHANNELS, source, 29, 1.0 / 64.0, 0.21)); } image diff --git a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs index 3754b82e..a0a47d11 100644 --- a/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs +++ b/crates/cuda-driver/src/gdn_closed_queue_gpu/columns_pair_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Retained-row QKV must match the original sequence over the same row bit for /// bit; non-finite words in OTHER rows must not matter, in the used row they /// must refuse at the first stage. @@ -43,9 +42,8 @@ pub(super) fn columns_pair( } return Ok(()); } - let history = completion - .into_next_history() - .map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?; + let history = + completion.into_next_history().map_err(|_| Error::InvalidDriverValue("unexpected GDN column refusal"))?; let found = actual.products()?; compare(&expected, &found, report); if bytes(&history) != found[0] { @@ -54,10 +52,7 @@ pub(super) fn columns_pair( report.rows += 1; Ok(()) })(); - combine( - combine(combine(operation, old.release()), actual.release()), - columns.release(), - ) + combine(combine(combine(operation, old.release()), actual.release()), columns.release()) } pub(super) fn compare(old: &[Vec], actual: &[Vec], report: &mut Report) { @@ -87,9 +82,8 @@ pub(super) fn clean_pair( if completion.numerical_refusal().is_some() { return Err(Error::InvalidDriverValue("unexpected GDN row refusal")); } - let history = completion - .into_next_history() - .map_err(|_| Error::InvalidDriverValue("missing GDN next history"))?; + let history = + completion.into_next_history().map_err(|_| Error::InvalidDriverValue("missing GDN next history"))?; let found = actual.products()?; compare(&expected, &found, report); // The fetched canonical history is exactly the next-history owner. @@ -113,9 +107,7 @@ pub(super) fn refusal_case( let operation = (|| { let completion = queued(queue, &row)?; report.guards += 1; - if completion.numerical_refusal() != Some(expected) - || completion.into_next_history().err() != Some(expected) - { + if completion.numerical_refusal() != Some(expected) || completion.into_next_history().err() != Some(expected) { report.differences += 1; } else { report.refusals += 1; diff --git a/crates/cuda-driver/src/gdn_fused_t1.rs b/crates/cuda-driver/src/gdn_fused_t1.rs index c8462bc9..41197b74 100644 --- a/crates/cuda-driver/src/gdn_fused_t1.rs +++ b/crates/cuda-driver/src/gdn_fused_t1.rs @@ -50,8 +50,8 @@ pub const GDN_FUSED_T1_PERSISTENT_BYTES: usize = STATUS_BYTES; const FUSED_PTX_LEN: usize = 51663; // TODO-ROOT: sha256 of offline_gdn_fused_t1.ptx (without the trailing NUL). const FUSED_PTX_SHA256: [u8; 32] = [ - 123, 208, 9, 9, 39, 60, 65, 6, 85, 195, 225, 120, 30, 88, 210, 26, 225, 84, 24, 31, 189, 116, - 198, 178, 17, 85, 116, 140, 151, 3, 93, 211, + 123, 208, 9, 9, 39, 60, 65, 6, 85, 195, 225, 120, 30, 88, 210, 26, 225, 84, 24, 31, 189, 116, 198, 178, 17, 85, + 116, 140, 151, 3, 93, 211, ]; // ------------------------------------------------------------------ kernel table @@ -228,17 +228,7 @@ mod tests { seen.push(step); step = step.next(); } - assert_eq!( - seen, - [ - Step::Inputs, - Step::Seed, - Step::Conv, - Step::Ab, - Step::Norm, - Step::Fetch - ] - ); + assert_eq!(seen, [Step::Inputs, Step::Seed, Step::Conv, Step::Ab, Step::Norm, Step::Fetch]); assert_eq!(Step::Done.next(), Step::Done); } @@ -248,15 +238,9 @@ mod tests { assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), None); statuses[GdnFusedStage::Gate.slot()] = 1; statuses[GdnFusedStage::State.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&statuses), SLOTS).unwrap(), - Some(GdnFusedStage::Gate) - ); + assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), Some(GdnFusedStage::Gate)); statuses[GdnFusedStage::Qkv.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&statuses), SLOTS).unwrap(), - Some(GdnFusedStage::Qkv) - ); + assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), Some(GdnFusedStage::Qkv)); } #[test] @@ -275,13 +259,7 @@ mod tests { fn kernel_table_is_closed_and_geometry_matches_the_original_launches() { for (index, kernel) in FUSED_KERNELS.into_iter().enumerate() { assert_eq!(kernel.index(), index); - assert!( - kernel - .entry() - .to_str() - .unwrap() - .starts_with("leleka_gdn_fused_") - ); + assert!(kernel.entry().to_str().unwrap().starts_with("leleka_gdn_fused_")); } // fused_gdn_conv_l2: channels / S blocks of S; fused_gdn_ab: (2 h_v + 7) / 8 blocks of 256; // fused_gdn_step_norm: h_v blocks of (S, RG). @@ -295,10 +273,7 @@ mod tests { #[test] fn unpinned_artifact_fails_closed_and_pins_check_length_and_digest() { static GOOD: &[u8] = b".version 8.0\n\0"; - assert!(matches!( - pinned(GOOD, 0, [0; 32]), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(pinned(GOOD, 0, [0; 32]), Err(Error::InvalidDriverValue(_)))); let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); assert!(pinned(GOOD, GOOD.len() - 1, digest).is_ok()); assert!(pinned(GOOD, GOOD.len() - 2, digest).is_err()); @@ -309,32 +284,27 @@ mod tests { } } -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_fused_t1_gpu.rs"] mod gpu; #[path = "gdn_fused_t1/pinned_fn.rs"] mod pinned_fn; #[allow(unused_imports)] -use pinned_fn::pinned; +use pinned_fn::decode_statuses; #[allow(unused_imports)] pub(crate) use pinned_fn::fused_asset; #[allow(unused_imports)] use pinned_fn::linear; #[allow(unused_imports)] -use pinned_fn::decode_statuses; -#[path = "gdn_fused_t1/impl_gdnfusedt1.rs"] -mod impl_gdnfusedt1; +use pinned_fn::pinned; #[path = "gdn_fused_t1/impl_gdnfusedprefix.rs"] mod impl_gdnfusedprefix; +#[path = "gdn_fused_t1/impl_gdnfusedt1.rs"] +mod impl_gdnfusedt1; #[path = "gdn_fused_t1/words_fn.rs"] mod words_fn; #[allow(unused_imports)] -use words_fn::words; -#[allow(unused_imports)] use words_fn::staging; +#[allow(unused_imports)] +use words_fn::words; diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs index 61bb21c5..f0cf168c 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { pub(in super::super) fn ready(&self, step: Step) -> Result<()> { if let Some(error) = &self.refusal { @@ -53,11 +51,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg], ) -> Result<()> { - let function = self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)?[kernel.index()]; + let function = self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?[kernel.index()]; self.commands.push(Command { function, grid: geometry.0, @@ -67,9 +61,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { Ok(()) } pub(in super::super) fn status_word(&self, stage: GdnFusedStage) -> Result { - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) + self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) } /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are /// scanned strictly in program order. @@ -101,11 +93,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { /// Admit the program inputs and scan them first: the projected QKV `[10240]` and Z `[6144]` (device-resident, /// not yet finite-checked by their producer). - pub fn scan_inputs( - &mut self, - qkv: &'lease DeviceBuffer<'lease>, - z: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + pub fn scan_inputs(&mut self, qkv: &'lease DeviceBuffer<'lease>, z: &'lease DeviceBuffer<'lease>) -> Result<()> { let result = (|| { self.ready(Step::Inputs)?; self.bind(Role::Qkv, qkv, GdnFusedStage::Qkv.bytes())?; @@ -135,9 +123,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { &[ ffi::KernelArg::Pointer(source), ffi::KernelArg::Pointer(next), - ffi::KernelArg::U32( - u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?, - ), + ffi::KernelArg::U32(u32::try_from(STATE_WORDS).map_err(|_| Error::InvalidQwenShape)?), ], )?; } @@ -158,11 +144,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Conv)?; let qkv = self.handle(Role::Qkv)?; - let hist = self.bind( - Role::NextHistory, - next_history, - GdnFusedStage::NextHistory.bytes(), - )?; + let hist = self.bind(Role::NextHistory, next_history, GdnFusedStage::NextHistory.bytes())?; let w = self.bind(Role::ConvW, conv_weights, 4 * C * F32)?; let h_handle = self.bind(Role::H, h, GdnFusedStage::H.bytes())?; self.push( diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs index 1f55628d..3e1a4c19 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { /// `fused_gdn_step_norm`: the in-place state update, readout and per-head norm / ssm_norm / sigmoid(z) gate. /// `gamma` is the f32 `[128]` ssm_norm weight; `y` receives the f32 `[6144]` normalized readout. Scans `y` then @@ -73,11 +71,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { } Ok(GdnFusedCompletion { refusal: drained.refusal, - fetched: if drained.refusal.is_none() { - drained.fetched - } else { - None - }, + fetched: if drained.refusal.is_none() { drained.fetched } else { None }, }) } @@ -85,11 +79,7 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { let status = self.batch.status_handle()?; let mut statuses = staging(STATUS_BYTES)?; let write_fetch = fetch && self.refusal.is_none(); - let mut fetched_state = staging(if write_fetch { - GDN_FUSED_T1_STATE_BYTES - } else { - 0 - })?; + let mut fetched_state = staging(if write_fetch { GDN_FUSED_T1_STATE_BYTES } else { 0 })?; let mut fetched_history = staging(if write_fetch { HISTORY_WORDS * F32 } else { 0 })?; if self.commands.len() > 1 { let context = self.batch.context; @@ -135,15 +125,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { if sync.is_err() || pop.is_err() { // Completion is uncertain: retain every actual argument/staging owner. The borrowed buffers are kept alive // by the poisoned context (it refuses to enter, so their frees leak instead of racing the device). - std::mem::forget(( - self.commands, - self.held, - statuses, - fetched_state, - fetched_history, - )); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain fused GDN T1 drain")); + std::mem::forget((self.commands, self.held, statuses, fetched_state, fetched_history)); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain fused GDN T1 drain")); } combine(combine(operation, sync), pop)?; } @@ -163,10 +146,6 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { } else { None }; - Ok(Drained { - refusal, - deferred: self.refusal, - fetched, - }) + Ok(Drained { refusal, deferred: self.refusal, fetched }) } } diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs index 4c675098..7200aceb 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedt1.rs @@ -3,28 +3,18 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GdnFusedT1<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } let required = STATUS_BYTES + RESERVE; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - status: None, - module: None, - functions: None, - failed: false, - }; + let mut owner = Self { context, status: None, module: None, functions: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); let guard = context.enter().inspect_err(|_| { @@ -92,22 +82,15 @@ impl<'ctx> GdnFusedT1<'ctx> { pub fn begin<'lease>(&'lease mut self) -> Result> { let status = self.status_handle()?; let mut held = Vec::new(); - held.try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; + held.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; let (grid, block) = linear(SLOTS)?; commands.push(Command { - function: self.functions.as_ref().ok_or(Error::ContextPoisoned)? - [FusedKernel::Zero.index()], + function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?[FusedKernel::Zero.index()], grid, block, - args: ffi::GdnPrefillArguments::new(&[ - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(SLOTS as u32), - ])?, + args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?, }); Ok(GdnFusedPrefix { batch: self, diff --git a/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs index a56bd9f3..cd25993a 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs @@ -3,19 +3,13 @@ #[allow(unused_imports)] use super::*; - pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result<&'static [u8]> { - if ptx.last() != Some(&0) - || !ptx[..ptx.len() - 1].is_ascii() - || ptx[..ptx.len() - 1].contains(&0) - { + if ptx.last() != Some(&0) || !ptx[..ptx.len() - 1].is_ascii() || ptx[..ptx.len() - 1].contains(&0) { return Err(Error::InvalidDriverValue("GDN fused T1 artifact encoding")); } let body = &ptx[..ptx.len() - 1]; if len == 0 || digest == [0; 32] { - return Err(Error::InvalidDriverValue( - "GDN fused T1 artifact pin is unset (TODO-ROOT)", - )); + return Err(Error::InvalidDriverValue("GDN fused T1 artifact pin is unset (TODO-ROOT)")); } if body.len() != len || crate::qwen_ffi::sha256(body) != digest { return Err(Error::InvalidDriverValue("GDN fused T1 artifact digest")); @@ -23,11 +17,7 @@ pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result Ok(ptx) } pub(crate) fn fused_asset() -> Result<&'static [u8]> { - pinned( - concat!(include_str!("../offline_gdn_fused_t1.ptx"), "\0").as_bytes(), - FUSED_PTX_LEN, - FUSED_PTX_SHA256, - ) + pinned(concat!(include_str!("../offline_gdn_fused_t1.ptx"), "\0").as_bytes(), FUSED_PTX_LEN, FUSED_PTX_SHA256) } impl FusedKernel { pub(crate) fn entry(self) -> &'static std::ffi::CStr { @@ -94,11 +84,8 @@ pub(super) fn decode_statuses(bytes: &[u8], checks: usize) -> Result Self { - Self { - slots: [None; ROLES], - } + Self { slots: [None; ROLES] } } pub(super) fn bind(&mut self, role: Role, handle: ffi::BufferHandle, bytes: usize) -> Result<()> { if let Some((bound, size)) = self.slots[role as usize] { - return if bound == handle && size == bytes { - Ok(()) - } else { - Err(Error::InvalidQwenShape) - }; + return if bound == handle && size == bytes { Ok(()) } else { Err(Error::InvalidQwenShape) }; } for (other, size) in self.slots.iter().flatten() { if handle.overlaps(bytes, *other, *size) { diff --git a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs index fac0951e..d60517a6 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs @@ -5,17 +5,13 @@ use super::*; pub(super) fn words(bytes: &[u8], decode: fn([u8; 4]) -> T) -> Result> { let mut values = Vec::new(); - values - .try_reserve_exact(bytes.len() / 4) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::HostAllocation)?; values.extend(bytes.as_chunks::<4>().0.iter().map(|word| decode(*word))); Ok(values.into_boxed_slice()) } pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } diff --git a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs index eae61f3a..c362ee3a 100644 --- a/crates/cuda-driver/src/gdn_fused_t1_gpu.rs +++ b/crates/cuda-driver/src/gdn_fused_t1_gpu.rs @@ -27,9 +27,7 @@ fn mismatch(what: &'static str) -> Result { fn synth(count: usize, salt: u32) -> Vec { (0..count) .map(|i| { - let x = (i as u32) - .wrapping_mul(2_654_435_761) - .wrapping_add(salt.wrapping_mul(40_503)); + let x = (i as u32).wrapping_mul(2_654_435_761).wrapping_add(salt.wrapping_mul(40_503)); ((x >> 8) % 1000) as f32 / 1000.0 - 0.5 }) .collect() @@ -48,14 +46,8 @@ struct Case { gamma: Vec, } fn case() -> Case { - let wa: Vec = synth(HV * N_EMBD, 7) - .iter() - .map(|v| bf_bits(v * 0.05)) - .collect(); - let wb: Vec = synth(HV * N_EMBD, 8) - .iter() - .map(|v| bf_bits(v * 0.05)) - .collect(); + let wa: Vec = synth(HV * N_EMBD, 7).iter().map(|v| bf_bits(v * 0.05)).collect(); + let wb: Vec = synth(HV * N_EMBD, 8).iter().map(|v| bf_bits(v * 0.05)).collect(); Case { qkv: synth(C, 1), z: synth(VALUES, 2), @@ -82,16 +74,8 @@ fn reference(c: &Case) -> Reference { let mut history = c.history.clone(); let mut h = vec![0f32; C]; for ch in 0..C { - let (v0, v1, v2, x) = ( - history[ch * 3], - history[ch * 3 + 1], - history[ch * 3 + 2], - c.qkv[ch], - ); - let sum = v0 * c.conv[ch * 4] - + v1 * c.conv[ch * 4 + 1] - + v2 * c.conv[ch * 4 + 2] - + x * c.conv[ch * 4 + 3]; + let (v0, v1, v2, x) = (history[ch * 3], history[ch * 3 + 1], history[ch * 3 + 2], c.qkv[ch]); + let sum = v0 * c.conv[ch * 4] + v1 * c.conv[ch * 4 + 1] + v2 * c.conv[ch * 4 + 2] + x * c.conv[ch * 4 + 3]; history[ch * 3] = v1; history[ch * 3 + 1] = v2; history[ch * 3 + 2] = x; @@ -145,14 +129,7 @@ fn reference(c: &Case) -> Reference { y[head * S + col] = oc[col] * scale * c.gamma[col] / (1.0 + (-zz).exp()); } } - Reference { - history, - h, - gate, - beta, - y, - state, - } + Reference { history, h, gate, beta, y, state } } const QK: usize = 2048; const HK: usize = 16; @@ -175,22 +152,12 @@ fn upload<'c>(context: &'c Context<'c>, values: &[f32]) -> Result(context: &'c Context<'c>, bits: &[u16]) -> Result> { let mut buffer = context.allocate(bits.len() * 2)?; - buffer.copy_from( - &bits - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>(), - )?; + buffer.copy_from(&bits.iter().flat_map(|v| v.to_le_bytes()).collect::>())?; Ok(buffer) } fn download<'c>(buffer: &DeviceBuffer<'c>, count: usize) -> Result> { let bytes = buffer.copy_to_owned(count * 4)?; - Ok(bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| f32::from_le_bytes(*w)) - .collect()) + Ok(bytes.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect()) } /// One program run. `from_resident`: seed the candidate state by the device copy of a resident mirror instead of a @@ -221,18 +188,11 @@ fn run( let gamma_b = upload(context, &c.gamma)?; let y_b = context.allocate(VALUES * 4)?; let resident = upload(context, &c.state)?; - let next_state = if from_resident { - context.allocate(STATE_WORDS * 4)? - } else { - upload(context, &c.state)? - }; + let next_state = if from_resident { context.allocate(STATE_WORDS * 4)? } else { upload(context, &c.state)? }; let refusal = (|| -> Result> { let mut prefix = owner.begin()?; prefix.scan_inputs(&qkv_b, &z_b)?; - prefix.seed_state( - if from_resident { Some(&resident) } else { None }, - &next_state, - )?; + prefix.seed_state(if from_resident { Some(&resident) } else { None }, &next_state)?; prefix.conv_l2(&hist_b, &conv_b, &h_b, EPS)?; prefix.ab(&mixed_b, &wa_b, &wb_b, &dt_b, &a_b, &gate_b, &beta_b)?; prefix.step_norm(&gamma_b, &y_b, EPS)?; @@ -241,9 +201,7 @@ fn run( if let Some(stage) = completion.numerical_refusal() { return Ok(Some(stage)); } - let (state, history) = completion - .into_fetched() - .map_err(|_| Error::InvalidQwenShape)?; + let (state, history) = completion.into_fetched().map_err(|_| Error::InvalidQwenShape)?; let want = reference(c); close("history", &history, &want.history)?; close("state", &state, &want.state)?; @@ -259,8 +217,8 @@ fn run( })(); let mut cleanup = Ok(()); for buffer in [ - qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b, - y_b, resident, next_state, + qkv_b, z_b, hist_b, conv_b, h_b, mixed_b, wa_b, wb_b, dt_b, a_b, gate_b, beta_b, gamma_b, y_b, resident, + next_state, ] { cleanup = combine(cleanup, buffer.release()); } diff --git a/crates/cuda-driver/src/gdn_native_batch.rs b/crates/cuda-driver/src/gdn_native_batch.rs index 6f76a120..0fa74a4a 100644 --- a/crates/cuda-driver/src/gdn_native_batch.rs +++ b/crates/cuda-driver/src/gdn_native_batch.rs @@ -51,15 +51,15 @@ const F16: usize = 2; const PREFILL_PTX_LEN: usize = 52304; // TODO-ROOT: sha256 of offline_gdn_prefill.ptx (without the trailing NUL). const PREFILL_PTX_SHA256: [u8; 32] = [ - 92, 195, 160, 40, 93, 185, 131, 206, 190, 158, 53, 250, 194, 213, 62, 87, 50, 104, 175, 129, - 127, 19, 27, 35, 64, 189, 0, 58, 227, 225, 100, 206, + 92, 195, 160, 40, 93, 185, 131, 206, 190, 158, 53, 250, 194, 213, 62, 87, 50, 104, 175, 129, 127, 19, 27, 35, 64, + 189, 0, 58, 227, 225, 100, 206, ]; // TODO-ROOT: exact byte length (without the trailing NUL) of offline_native_dequant_f16.ptx. const DEQUANT_PTX_LEN: usize = 58080; // TODO-ROOT: sha256 of offline_native_dequant_f16.ptx (without the trailing NUL). const DEQUANT_PTX_SHA256: [u8; 32] = [ - 2, 11, 199, 151, 252, 90, 143, 54, 35, 7, 84, 54, 180, 78, 2, 26, 46, 151, 255, 186, 170, 191, - 84, 210, 115, 234, 206, 193, 49, 50, 235, 42, + 2, 11, 199, 151, 252, 90, 143, 54, 35, 7, 84, 54, 180, 78, 2, 26, 46, 151, 255, 186, 170, 191, 84, 210, 115, 234, + 206, 193, 49, 50, 235, 42, ]; // ------------------------------------------------------------------ kernel table @@ -152,21 +152,9 @@ pub trait GdnGemm { fn stream(&self) -> GdnStream; /// cublasGemmEx(OP_T, OP_N, rows, tokens, depth, 1, W:CUDA_R_16F, X:CUDA_R_16F, /// beta, Y:CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT). - fn f16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()>; + fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()>; /// The same with `CUDA_R_16BF` for `x` and `w`. - fn bf16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()>; + fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()>; } // ------------------------------------------------------------------ stages @@ -340,12 +328,7 @@ struct Drained { #[path = "gdn_native_batch/tests.rs"] mod tests; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_native_batch_gpu.rs"] mod gpu; @@ -357,15 +340,15 @@ pub use prompt_device::{OriginalGdnPromptDevice, OriginalGdnPromptWeights}; #[path = "gdn_native_batch/pinned_fn.rs"] mod pinned_fn; #[allow(unused_imports)] -use pinned_fn::pinned; -#[allow(unused_imports)] -pub(crate) use pinned_fn::prefill_asset; +use pinned_fn::decode_statuses; #[allow(unused_imports)] pub(crate) use pinned_fn::dequant_asset; #[allow(unused_imports)] use pinned_fn::linear; #[allow(unused_imports)] -use pinned_fn::decode_statuses; +use pinned_fn::pinned; +#[allow(unused_imports)] +pub(crate) use pinned_fn::prefill_asset; #[path = "gdn_native_batch/impl_context.rs"] mod impl_context; #[path = "gdn_native_batch/impl_gdnbatchprefix.rs"] diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs index 4292e7b2..93681fa1 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Context<'_> { pub fn gdn_prefill_batch(&self) -> Result> { GdnPrefillBatch::new(self) @@ -24,21 +23,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(STATUS_BYTES) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - capacity, - context, - status: None, - modules: [None, None], - functions: None, - failed: false, - }; + let mut owner = Self { capacity, context, status: None, modules: [None, None], functions: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); let guard = context.enter()?; @@ -50,16 +38,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> { owner.modules[1] = Some(dequant); let mut all = [None; KERNELS.len()]; for kernel in KERNELS { - let module = if kernel.is_dequant() { - dequant - } else { - prefill - }; + let module = if kernel.is_dequant() { dequant } else { prefill }; all[kernel.index()] = Some(api.gdn_native_function(module, kernel)?); } - Ok(Functions { - all: all.map(|function| function.expect("every GDN batch kernel resolved")), - }) + Ok(Functions { all: all.map(|function| function.expect("every GDN batch kernel resolved")) }) })(); let pop = guard.finish(); if pop.is_err() { @@ -111,27 +93,17 @@ impl<'ctx> GdnPrefillBatch<'ctx> { } let status = self.status_handle()?; let mut held = Vec::new(); - held.try_reserve_exact(48) - .map_err(|_| Error::HostAllocation)?; + held.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(64) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?; // The zeroing of the status words is the first command of every drain. let (grid, block) = linear(SLOTS)?; commands.push(Command::Kernel { - function: self - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .get(Kernel::Zero), + function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(Kernel::Zero), stream: gemm.stream(), grid, block, - args: ffi::GdnPrefillArguments::new(&[ - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(SLOTS as u32), - ])?, + args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?, }); Ok(GdnBatchPrefix { batch: self, @@ -154,24 +126,10 @@ impl<'ctx> GdnPrefillBatch<'ctx> { impl Command<'_> { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { match self { - Self::Kernel { - function, - stream, - grid, - block, - args, - } => context - .driver - .api - .launch_gdn_native(*function, *stream, *grid, *block, args), - Self::Gemm { - gemm, - bf16, - x, - w, - y, - shape, - } => { + Self::Kernel { function, stream, grid, block, args } => { + context.driver.api.launch_gdn_native(*function, *stream, *grid, *block, args) + } + Self::Gemm { gemm, bf16, x, w, y, shape } => { if *bf16 { gemm.bf16(x, w, y, *shape) } else { diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs index 9473fb6d..19c31350 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { pub fn tokens(&self) -> usize { self.tokens @@ -26,12 +24,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { result } pub(in super::super) fn function(&self, kernel: Kernel) -> Result { - Ok(self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .get(kernel)) + Ok(self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?.get(kernel)) } /// Admit one caller buffer under `role`. `bytes` is the exact size unless /// `at_least`, in which case the whole allocation is bound. @@ -45,8 +38,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { if !std::ptr::eq(self.batch.context, buffer.context) { return Err(Error::ContextMismatch); } - if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) - { + if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) { return Err(Error::InvalidQwenShape); } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; @@ -88,15 +80,8 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { if bytes != stage.bytes(self.tokens) { return Err(Error::InvalidQwenShape); } - let status = - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; - let kernel = if stage.is_half() { - Kernel::FiniteF16 - } else { - Kernel::FiniteF32 - }; + let status = self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + let kernel = if stage.is_half() { Kernel::FiniteF16 } else { Kernel::FiniteF32 }; self.push_kernel( kernel, linear(elements)?, @@ -114,10 +99,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { if self.checks != stage.slot() || stage != GdnBatchStage::StateSteps { return Err(Error::InvalidQwenShape); } - let word = - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; + let word = self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; self.checks = stage.slot() + 1; Ok(word) } @@ -126,11 +108,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { } pub(in super::super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { let handle = self.handle(role)?; - self.held - .iter() - .copied() - .find(|buffer| buffer.handle == Some(handle)) - .ok_or(Error::InvalidQwenShape) + self.held.iter().copied().find(|buffer| buffer.handle == Some(handle)).ok_or(Error::InvalidQwenShape) } // ---------------------------------------------------------------- images @@ -152,12 +130,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; let lo = match mixed_bf_lo { - Some(buffer) => ffi::KernelArg::Pointer(self.bind( - Role::MixedBfLo, - buffer, - t * N * F16, - false, - )?), + Some(buffer) => ffi::KernelArg::Pointer(self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?), None => ffi::KernelArg::NullPointer, }; self.push_kernel( @@ -240,14 +213,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { x, w: scratch, y: output.1, - shape: GemmShape { - tokens: t, - rows, - depth, - ldy: rows, - y_offset: 0, - beta: 0.0, - }, + shape: GemmShape { tokens: t, rows, depth, ldy: rows, y_offset: 0, beta: 0.0 }, }); Ok(()) } diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs index 08c97fbd..2885c084 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { /// Native `attn_qkv` projection: dequantize to FP16, `Y[T,10240] = X . W^T` /// with `X` = the FP16 image of `mixed`; then the QKV scan. @@ -18,16 +16,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Qkv)?; let bytes = self.tokens * C * F32; - self.project_native( - format, - (Role::QkvW, weights), - scratch, - Role::MixedH, - (Role::Qkv, qkv), - C, - N, - bytes, - )?; + self.project_native(format, (Role::QkvW, weights), scratch, Role::MixedH, (Role::Qkv, qkv), C, N, bytes)?; self.scan(GdnBatchStage::Qkv, Role::Qkv)?; self.step = self.step.next(); Ok(()) @@ -45,16 +34,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Z)?; let bytes = self.tokens * ZV * F32; - self.project_native( - format, - (Role::ZW, weights), - scratch, - Role::MixedH, - (Role::Z, z), - ZV, - N, - bytes, - )?; + self.project_native(format, (Role::ZW, weights), scratch, Role::MixedH, (Role::Z, z), ZV, N, bytes)?; self.scan(GdnBatchStage::Z, Role::Z)?; self.step = self.step.next(); Ok(()) @@ -80,14 +60,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let x = self.buffer_ref(Role::MixedBf)?; let lo = self.buffer_ref(Role::MixedBfLo).ok(); for (weights, y_offset) in [(alpha_weights, 0), (beta_weights, HV)] { - let shape = |beta| GemmShape { - tokens: t, - rows: HV, - depth: N, - ldy: 2 * HV, - y_offset, - beta, - }; + let shape = |beta| GemmShape { tokens: t, rows: HV, depth: N, ldy: 2 * HV, y_offset, beta }; self.commands.push(Command::Gemm { gemm: self.gemm, bf16: true, @@ -187,10 +160,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { } else { self.push_kernel( Kernel::ConvTiled, - ( - [(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], - [128, 1, 1], - ), + ([(C / 128) as u32, t.div_ceil(CONV_TILE) as u32, 1], [128, 1, 1]), &[ ffi::KernelArg::Pointer(hist), ffi::KernelArg::Pointer(qkv), @@ -227,10 +197,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { self.push_kernel( Kernel::L2, ([32, self.tokens as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(h), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ], + &[ffi::KernelArg::Pointer(h), ffi::KernelArg::F32(GDN_BATCH_EPSILON)], )?; self.scan(GdnBatchStage::Qk, Role::H)?; self.step = self.step.next(); diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs index e5d5ee22..28d38633 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_gdnbatchprefix/impl_gdnbatchprefix_3.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { /// `gdn_rec_cols_pipe`: the whole-chunk recurrence. `state_in` is the /// immutable prior state `[128][48][128]`, `state_out` the separate final @@ -50,11 +48,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { } /// `gdn_out_norm`: in place on `y` (f32) plus the half image `y16` /// (`hf(v)`), gated by `z`; then the Y and Y16 scans. - pub fn out_norm( - &mut self, - gamma: &'lease DeviceBuffer<'lease>, - y16: &'lease DeviceBuffer<'lease>, - ) -> Result<()> { + pub fn out_norm(&mut self, gamma: &'lease DeviceBuffer<'lease>, y16: &'lease DeviceBuffer<'lease>) -> Result<()> { let result = (|| { self.ready(Step::OutNorm)?; let t = self.tokens; @@ -92,16 +86,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Out)?; let bytes = self.tokens * N * F32; - self.project_native( - format, - (Role::OutW, weights), - scratch, - Role::Y16, - (Role::Bo, bo), - N, - ZV, - bytes, - )?; + self.project_native(format, (Role::OutW, weights), scratch, Role::Y16, (Role::Bo, bo), N, ZV, bytes)?; self.scan(GdnBatchStage::Bo, Role::Bo)?; self.step = self.step.next(); Ok(()) @@ -125,11 +110,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { } Ok(GdnBatchCompletion { refusal: drained.refusal, - next_history: if drained.refusal.is_none() { - drained.next_history - } else { - None - }, + next_history: if drained.refusal.is_none() { drained.next_history } else { None }, }) } @@ -176,8 +157,7 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { // Completion is uncertain: retain every actual argument/staging // owner and every borrowed buffer; Context poison forbids reuse. std::mem::forget((self.commands, self.held, statuses, fetched)); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain GDN batch drain")); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain GDN batch drain")); } combine(combine(operation, sync), pop)?; } @@ -191,24 +171,12 @@ impl<'lease, 'ctx> GdnBatchPrefix<'lease, 'ctx> { }; let next_history = if write_fetch && refusal.is_none() { let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_WORDS) - .map_err(|_| Error::HostAllocation)?; - values.extend( - fetched - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; + values.extend(fetched.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); Some(values.into_boxed_slice()) } else { None }; - Ok(Drained { - refusal, - deferred: self.refusal, - next_history, - }) + Ok(Drained { refusal, deferred: self.refusal, next_history }) } } diff --git a/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs b/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs index f8236c14..262d1814 100644 --- a/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs @@ -3,24 +3,13 @@ #[allow(unused_imports)] use super::*; - -pub(super) fn pinned( - ptx: &'static [u8], - len: usize, - digest: [u8; 32], - what: &'static str, -) -> Result<&'static [u8]> { - if ptx.last() != Some(&0) - || !ptx[..ptx.len() - 1].is_ascii() - || ptx[..ptx.len() - 1].contains(&0) - { +pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32], what: &'static str) -> Result<&'static [u8]> { + if ptx.last() != Some(&0) || !ptx[..ptx.len() - 1].is_ascii() || ptx[..ptx.len() - 1].contains(&0) { return Err(Error::InvalidDriverValue(what)); } let body = &ptx[..ptx.len() - 1]; if len == 0 || digest == [0; 32] { - return Err(Error::InvalidDriverValue( - "GDN prefill artifact pin is unset (TODO-ROOT)", - )); + return Err(Error::InvalidDriverValue("GDN prefill artifact pin is unset (TODO-ROOT)")); } if body.len() != len || crate::qwen_ffi::sha256(body) != digest { return Err(Error::InvalidDriverValue(what)); @@ -125,10 +114,7 @@ impl GdnNativeFormat { if rows == 0 || cols == 0 || !cols.is_multiple_of(elements) { return Err(Error::InvalidQwenShape); } - (cols / elements) - .checked_mul(bytes) - .and_then(|row| row.checked_mul(rows)) - .ok_or(Error::InvalidQwenShape) + (cols / elements).checked_mul(bytes).and_then(|row| row.checked_mul(rows)).ok_or(Error::InvalidQwenShape) } } impl GdnStream { @@ -209,17 +195,11 @@ impl Step { } impl Bindings { pub(super) fn new() -> Self { - Self { - slots: [None; ROLES], - } + Self { slots: [None; ROLES] } } pub(super) fn bind(&mut self, role: Role, handle: ffi::BufferHandle, bytes: usize) -> Result<()> { if let Some((bound, size)) = self.slots[role as usize] { - return if bound == handle && size == bytes { - Ok(()) - } else { - Err(Error::InvalidQwenShape) - }; + return if bound == handle && size == bytes { Ok(()) } else { Err(Error::InvalidQwenShape) }; } for (other, size) in self.slots.iter().flatten() { if handle.overlaps(bytes, *other, *size) { diff --git a/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs b/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs index 9c713707..aa79687d 100644 --- a/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch/staging_fn.rs @@ -5,9 +5,7 @@ use super::*; pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } diff --git a/crates/cuda-driver/src/gdn_native_batch/tests.rs b/crates/cuda-driver/src/gdn_native_batch/tests.rs index 317d72fc..00985060 100644 --- a/crates/cuda-driver/src/gdn_native_batch/tests.rs +++ b/crates/cuda-driver/src/gdn_native_batch/tests.rs @@ -54,50 +54,26 @@ fn earliest_status_in_program_order_is_the_refusal() { assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); words[GdnBatchStage::Beta.slot()] = 1; words[GdnBatchStage::NextState.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(GdnBatchStage::Beta) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(GdnBatchStage::Beta)); words[GdnBatchStage::Qkv.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(GdnBatchStage::Qkv) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(GdnBatchStage::Qkv)); } #[test] fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { let mut words = [0u32; SLOTS]; words[GdnBatchStage::Y.slot()] = 1; - assert!(matches!( - decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(decode_statuses(&bytes(&words), GdnBatchStage::Y.slot()), Err(Error::InvalidDriverValue(_)))); words[GdnBatchStage::Y.slot()] = 2; - assert!(matches!( - decode_statuses(&bytes(&words), SLOTS), - Err(Error::InvalidDriverValue(_)) - )); - assert!(matches!( - decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(decode_statuses(&bytes(&words), SLOTS), Err(Error::InvalidDriverValue(_)))); + assert!(matches!(decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), Err(Error::InvalidQwenShape))); + assert!(matches!(decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), Err(Error::InvalidQwenShape))); } #[test] fn native_formats_have_the_original_block_geometry() { - assert_eq!( - GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(), - 21_504_000 - ); - assert_eq!( - GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(), - 2 * 2 * 34 - ); + assert_eq!(GdnNativeFormat::Q6K.matrix_bytes(10_240, 2_560).unwrap(), 21_504_000); + assert_eq!(GdnNativeFormat::Q8_0.matrix_bytes(2, 64).unwrap(), 2 * 2 * 34); assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(1, 32).unwrap(), 18); assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(1, 256).unwrap(), 136); assert_eq!(GdnNativeFormat::Q4K.matrix_bytes(1, 256).unwrap(), 144); @@ -149,18 +125,9 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { bindings.bind(Role::Qkv, a, 0x1000).unwrap(); bindings.bind(Role::Z, b, 0x1000).unwrap(); bindings.bind(Role::Qkv, a, 0x1000).unwrap(); - assert!(matches!( - bindings.bind(Role::Qkv, b, 0x1000), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Qkv, a, 0x800), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Gate, overlapping, 0x100), - Err(Error::OutputAliasesInput) - )); + assert!(matches!(bindings.bind(Role::Qkv, b, 0x1000), Err(Error::InvalidQwenShape))); + assert!(matches!(bindings.bind(Role::Qkv, a, 0x800), Err(Error::InvalidQwenShape))); + assert!(matches!(bindings.bind(Role::Gate, overlapping, 0x100), Err(Error::OutputAliasesInput))); assert!(bindings.get(Role::Gate).is_err()); assert!(bindings.get(Role::Z).unwrap() == (b, 0x1000)); } @@ -168,10 +135,7 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { #[test] fn unpinned_artifacts_fail_closed_and_pins_check_length_and_digest() { static GOOD: &[u8] = b".version 8.0\n\0"; - assert!(matches!( - pinned(GOOD, 0, [0; 32], "x"), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(pinned(GOOD, 0, [0; 32], "x"), Err(Error::InvalidDriverValue(_)))); let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); assert!(pinned(GOOD, GOOD.len() - 1, digest, "x").is_ok()); assert!(pinned(GOOD, GOOD.len() - 2, digest, "x").is_err()); diff --git a/crates/cuda-driver/src/gdn_native_batch_abi.rs b/crates/cuda-driver/src/gdn_native_batch_abi.rs index f63ff71b..f6b869c8 100644 --- a/crates/cuda-driver/src/gdn_native_batch_abi.rs +++ b/crates/cuda-driver/src/gdn_native_batch_abi.rs @@ -34,10 +34,8 @@ impl GdnPrefillArguments { if args.is_empty() || args.len() > MAX_ARGS { return Err(Error::InvalidQwenShape); } - let owner = Box::into_raw(Box::new(Storage { - slots: [0; MAX_ARGS], - parameters: [std::ptr::null_mut(); MAX_ARGS], - })); + let owner = + Box::into_raw(Box::new(Storage { slots: [0; MAX_ARGS], parameters: [std::ptr::null_mut(); MAX_ARGS] })); let owner = std::ptr::NonNull::new(owner).expect("Box is non-null"); // SAFETY: freshly allocated, uniquely owned, stable storage; the // parameter pointers target this same Box and live until `Drop`. diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu.rs b/crates/cuda-driver/src/gdn_native_batch_gpu.rs index 7e7d42ab..4d5be8ce 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu.rs @@ -96,56 +96,22 @@ fn strata_prefill_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() { run_case(&context, &mut batch, tokens, Poison::default(), None)?; } // Earliest stage in program order wins and the owner stays usable. - run_case( - &context, - &mut batch, - 4, - Poison { - z: true, - ab: true, - ..Poison::default() - }, - Some(GdnBatchStage::Z), - )?; - run_case( - &context, - &mut batch, - 4, - Poison { - ab: true, - ..Poison::default() - }, - Some(GdnBatchStage::Ab), - )?; - run_case( - &context, - &mut batch, - 4, - Poison { - dt: true, - ..Poison::default() - }, - Some(GdnBatchStage::Gate), - )?; + run_case(&context, &mut batch, 4, Poison { z: true, ab: true, ..Poison::default() }, Some(GdnBatchStage::Z))?; + run_case(&context, &mut batch, 4, Poison { ab: true, ..Poison::default() }, Some(GdnBatchStage::Ab))?; + run_case(&context, &mut batch, 4, Poison { dt: true, ..Poison::default() }, Some(GdnBatchStage::Gate))?; // A non-finite prior state is caught by the recurrence kernel's own witness // before the final-state scan could see it. run_case( &context, &mut batch, 4, - Poison { - state: true, - ..Poison::default() - }, + Poison { state: true, ..Poison::default() }, Some(GdnBatchStage::StateSteps), )?; run_case(&context, &mut batch, 3, Poison::default(), None)?; // Admission refusals leave nothing behind. - let idle = HostGemm { - poison: Poison::default(), - captured: RefCell::new(Captured::default()), - calls: Cell::new(0), - }; + let idle = + HostGemm { poison: Poison::default(), captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; if batch.begin(0, &idle).is_ok() || batch.begin(GDN_BATCH_MAX_TOKENS + 1, &idle).is_ok() { return mismatch("token bounds not enforced"); } @@ -159,40 +125,40 @@ fn strata_prefill_gdn_program_runs_in_order_refuses_earliest_and_cleans_up() { #[path = "gdn_native_batch_gpu/bytes_of_fn.rs"] mod bytes_of_fn; #[allow(unused_imports)] +use bytes_of_fn::bf_bits; +#[allow(unused_imports)] +use bytes_of_fn::bf_value; +#[allow(unused_imports)] use bytes_of_fn::bytes_of; #[allow(unused_imports)] -use bytes_of_fn::words_of; -#[allow(unused_imports)] -use bytes_of_fn::halves_of; +use bytes_of_fn::close; #[allow(unused_imports)] use bytes_of_fn::f16_bits; #[allow(unused_imports)] use bytes_of_fn::f16_value; #[allow(unused_imports)] -use bytes_of_fn::bf_bits; -#[allow(unused_imports)] -use bytes_of_fn::bf_value; -#[allow(unused_imports)] -use bytes_of_fn::sigm; +use bytes_of_fn::halves_of; #[allow(unused_imports)] use bytes_of_fn::pattern; #[allow(unused_imports)] -use bytes_of_fn::close; -#[allow(unused_imports)] use bytes_of_fn::q8_0; #[allow(unused_imports)] use bytes_of_fn::reference; +#[allow(unused_imports)] +use bytes_of_fn::sigm; +#[allow(unused_imports)] +use bytes_of_fn::words_of; #[path = "gdn_native_batch_gpu/impl_hostgemm.rs"] mod impl_hostgemm; #[allow(unused_imports)] -use impl_hostgemm::upload; +use impl_hostgemm::mismatch; #[allow(unused_imports)] use impl_hostgemm::read; #[allow(unused_imports)] -use impl_hostgemm::mismatch; +use impl_hostgemm::upload; #[path = "gdn_native_batch_gpu/run_case_fn.rs"] mod run_case_fn; #[allow(unused_imports)] -use run_case_fn::run_case; -#[allow(unused_imports)] use run_case_fn::check_clean; +#[allow(unused_imports)] +use run_case_fn::run_case; diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs index 2bd42728..0a852eb5 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs @@ -3,26 +3,15 @@ #[allow(unused_imports)] use super::*; - // ---------------------------------------------------------------- host numerics helpers pub(super) fn bytes_of(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } pub(super) fn words_of(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| f32::from_le_bytes(*w)) - .collect() + bytes.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect() } pub(super) fn halves_of(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<2>() - .0 - .iter() - .map(|w| u16::from_le_bytes(*w)) - .collect() + bytes.as_chunks::<2>().0.iter().map(|w| u16::from_le_bytes(*w)).collect() } pub(super) fn f16_bits(f: f32) -> u16 { let x = f.to_bits(); @@ -82,9 +71,7 @@ pub(super) fn sigm(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) } pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec { - (0..count) - .map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset) - .collect() + (0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect() } pub(super) fn close(a: f32, b: f32, tolerance: f32) -> bool { (a - b).abs() <= tolerance * (1.0 + b.abs()) @@ -144,11 +131,7 @@ pub(super) fn reference( for c in 0..C { for k in 0..3 { let t = tokens as isize - 3 + k as isize; - next_history[c * 3 + k] = if t >= 0 { - qkv[t as usize * C + c] - } else { - history[c * 3 + (t + 3) as usize] - }; + next_history[c * 3 + k] = if t >= 0 { qkv[t as usize * C + c] } else { history[c * 3 + (t + 3) as usize] }; } } for t in 0..tokens { @@ -195,11 +178,5 @@ pub(super) fn reference( } } } - Reference { - h, - next_history, - next_state, - y, - y16, - } + Reference { h, next_history, next_state, y, y16 } } diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs index a86fccd0..1e14f770 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs @@ -20,23 +20,12 @@ impl HostGemm { let mut yb = vec![0u8; y.len()]; y.copy_to(&mut yb)?; let value = |bits: u16| { - if bf16 { - bf_value(bits) - } else { - f16_value(bits) - } + if bf16 { bf_value(bits) } else { f16_value(bits) } }; let xh = halves_of(&xb); let wh = halves_of(&wb); let mut out = words_of(&yb); - let GemmShape { - tokens, - rows, - depth, - ldy, - y_offset, - beta, - } = shape; + let GemmShape { tokens, rows, depth, ldy, y_offset, beta } = shape; if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy { return Err(Error::InvalidQwenShape); } @@ -44,8 +33,7 @@ impl HostGemm { for n in 0..rows { let mut acc = 0f32; for k in 0..4 { - acc += value(xh[t * depth + (7 * n + k) % depth]) - * value(wh[n * depth + (3 * k + n) % depth]); + acc += value(xh[t * depth + (7 * n + k) % depth]) * value(wh[n * depth + (3 * k + n) % depth]); } let at = t * ldy + y_offset + n; out[at] = acc + beta * out[at]; @@ -57,10 +45,7 @@ impl HostGemm { if self.poison.ab && rows == HV { out[tokens * ldy - 1] = f32::from_bits(0x7fc0_0001); } - y.context - .driver - .api - .copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; + y.context.driver.api.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; let mut captured = self.captured.borrow_mut(); if !bf16 { captured.scratch.push((rows, wh[..rows * depth].to_vec())); @@ -75,22 +60,10 @@ impl GdnGemm for HostGemm { // The host stand-in copies synchronously on the default stream. GdnStream::default_stream() } - fn f16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.run(false, x, w, y, shape) } - fn bf16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.run(true, x, w, y, shape) } } @@ -117,23 +90,15 @@ impl<'a> Fixture<'a> { } let host_mixed = pattern(tokens * N, 1, 37, 1.0 / 32.0, 0.5); let host_history = pattern(HISTORY_WORDS, 2, 13, 1.0 / 128.0, 0.04); - let host_conv_w: Vec = (0..4 * C) - .map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]) - .collect(); + let host_conv_w: Vec = (0..4 * C).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); let host_a = vec![-1.0f32; HV]; - let host_gamma = pattern(S, 3, 7, 1.0 / 16.0, 0.0) - .iter() - .map(|v| v + 0.5) - .collect::>(); + let host_gamma = pattern(S, 3, 7, 1.0 / 16.0, 0.0).iter().map(|v| v + 0.5).collect::>(); let mut host_state = pattern(STATE_WORDS, 4, 19, 1.0 / 2048.0, 0.004); if poison.state { host_state[STATE_WORDS - 1] = f32::from_bits(0x7fc0_0001); } let bf16_weights = |salt: usize| -> Vec { - pattern(HV * N, salt, 11, 1.0 / 64.0, 0.08) - .into_iter() - .flat_map(|v| bf_bits(v).to_le_bytes()) - .collect() + pattern(HV * N, salt, 11, 1.0 / 64.0, 0.08).into_iter().flat_map(|v| bf_bits(v).to_le_bytes()).collect() }; Ok(Self { mixed: upload(context, &bytes_of(&host_mixed))?, diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs index af743258..0244dcd3 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/run_case_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// One complete program for `tokens` rows; returns the completion and, when the /// program finished clean, the checks against the host reference. pub(super) fn run_case( @@ -14,49 +13,20 @@ pub(super) fn run_case( expect: Option, ) -> Result<()> { let fixture = Fixture::new(context, tokens, poison)?; - let gemm = HostGemm { - poison, - captured: RefCell::new(Captured::default()), - calls: Cell::new(0), - }; + let gemm = HostGemm { poison, captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; let result = (|| -> Result<()> { let mut prefix = batch.begin(tokens, &gemm)?; let program = (|| -> Result<()> { - prefix.pack_mixed( - &fixture.mixed, - &fixture.mixed_h, - &fixture.mixed_bf, - Some(&fixture.mixed_bf_lo), - )?; - prefix.project_qkv( - GdnNativeFormat::Q8_0, - &fixture.qkv_w, - &fixture.scratch, - &fixture.qkv, - )?; - prefix.project_z( - GdnNativeFormat::Q8_0, - &fixture.z_w, - &fixture.scratch, - &fixture.z, - )?; + prefix.pack_mixed(&fixture.mixed, &fixture.mixed_h, &fixture.mixed_bf, Some(&fixture.mixed_bf_lo))?; + prefix.project_qkv(GdnNativeFormat::Q8_0, &fixture.qkv_w, &fixture.scratch, &fixture.qkv)?; + prefix.project_z(GdnNativeFormat::Q8_0, &fixture.z_w, &fixture.scratch, &fixture.z)?; prefix.project_alpha_beta(&fixture.alpha_w, &fixture.beta_w, &fixture.ab)?; prefix.gates(&fixture.dt, &fixture.a, &fixture.gate, &fixture.beta)?; - prefix.conv( - &fixture.history, - &fixture.conv_w, - &fixture.next_history, - &fixture.h, - )?; + prefix.conv(&fixture.history, &fixture.conv_w, &fixture.next_history, &fixture.h)?; prefix.l2()?; prefix.recurrence(&fixture.state, &fixture.next_state, &fixture.y)?; prefix.out_norm(&fixture.gamma, &fixture.y16)?; - prefix.project_out( - GdnNativeFormat::Q8_0, - &fixture.out_w, - &fixture.scratch, - &fixture.bo, - ) + prefix.project_out(GdnNativeFormat::Q8_0, &fixture.out_w, &fixture.scratch, &fixture.bo) })(); let completion = prefix.finish(); program?; @@ -77,41 +47,27 @@ pub(super) fn run_case( _ => mismatch("refused batch must withhold its history"), }; } - let history = - history.map_err(|_| Error::InvalidDriverValue("clean batch lost its history"))?; + let history = history.map_err(|_| Error::InvalidDriverValue("clean batch lost its history"))?; check_clean(&fixture, &gemm, tokens, &history) })(); combine(result, fixture.release()) } -pub(super) fn check_clean( - f: &Fixture<'_>, - gemm: &HostGemm, - tokens: usize, - next_history: &[f32], -) -> Result<()> { +pub(super) fn check_clean(f: &Fixture<'_>, gemm: &HostGemm, tokens: usize, next_history: &[f32]) -> Result<()> { // Five projections' FP16 matrices, the images and four GEMM calls with the lo pass. let captured = gemm.captured.borrow(); if gemm.calls.get() != 3 + 4 || captured.x.len() != 7 { return mismatch("unexpected GEMM call sequence"); } // Dequantization is exact against the host transcription of group32<8>. - for ((rows, half), (r, c, salt)) in - captured - .scratch - .iter() - .zip([(C, N, 1usize), (ZV, N, 2), (N, ZV, 3)]) - { + for ((rows, half), (r, c, salt)) in captured.scratch.iter().zip([(C, N, 1usize), (ZV, N, 2), (N, ZV, 3)]) { if *rows != r || half != &q8_0(r, c, salt).1 { return mismatch("dequantized FP16 weights differ from the original group32"); } } // The images of `mixed`. - let (h_img, bf_img, lo_img) = ( - halves_of(&read(&f.mixed_h)?), - halves_of(&read(&f.mixed_bf)?), - halves_of(&read(&f.mixed_bf_lo)?), - ); + let (h_img, bf_img, lo_img) = + (halves_of(&read(&f.mixed_h)?), halves_of(&read(&f.mixed_bf)?), halves_of(&read(&f.mixed_bf_lo)?)); for (i, &s) in f.host_mixed.iter().enumerate() { let hi = bf_bits(s); if h_img[i] != f16_bits(s) || bf_img[i] != hi || lo_img[i] != bf_bits(s - bf_value(hi)) { @@ -120,12 +76,7 @@ pub(super) fn check_clean( } // Downstream kernels against the host reference built from the adapter's own outputs. let by_rows = |rows: usize, nth: usize| -> Option<&Vec> { - captured - .y - .iter() - .filter(|(r, _)| *r == rows) - .nth(nth) - .map(|(_, y)| y) + captured.y.iter().filter(|(r, _)| *r == rows).nth(nth).map(|(_, y)| y) }; let qkv = by_rows(C, 0).ok_or(Error::InvalidDriverValue("qkv call missing"))?; let z = by_rows(ZV, 0).ok_or(Error::InvalidDriverValue("z call missing"))?; @@ -156,16 +107,10 @@ pub(super) fn check_clean( let state = words_of(&read(&f.next_state)?); let y = words_of(&read(&f.y)?); let y16 = halves_of(&read(&f.y16)?); - for (name, got, expected) in [ - ("conv+l2", &h, &want.h), - ("next state", &state, &want.next_state), - ("normalized output", &y, &want.y), - ] { - if got.len() != expected.len() - || got - .iter() - .zip(expected) - .any(|(g, e)| !g.is_finite() || !close(*g, *e, 2e-4)) + for (name, got, expected) in + [("conv+l2", &h, &want.h), ("next state", &state, &want.next_state), ("normalized output", &y, &want.y)] + { + if got.len() != expected.len() || got.iter().zip(expected).any(|(g, e)| !g.is_finite() || !close(*g, *e, 2e-4)) { return Err(Error::InvalidDriverValue(match name { "conv+l2" => "conv+l2 differs from the host reference", @@ -174,18 +119,11 @@ pub(super) fn check_clean( })); } } - if y16 - .iter() - .zip(&want.y16) - .any(|(g, e)| !close(f16_value(*g), f16_value(*e), 4e-3)) - { + if y16.iter().zip(&want.y16).any(|(g, e)| !close(f16_value(*g), f16_value(*e), 4e-3)) { return mismatch("y16 differs from the host reference"); } // The Out GEMM consumed exactly the device y16. - let last = captured - .x - .last() - .ok_or(Error::InvalidDriverValue("out call missing"))?; + let last = captured.x.last().ok_or(Error::InvalidDriverValue("out call missing"))?; if last.0 != ZV || halves_of(&last.1) != y16 { return mismatch("Out GEMM did not read the y16 image"); } diff --git a/crates/cuda-driver/src/gdn_prompt_device.rs b/crates/cuda-driver/src/gdn_prompt_device.rs index e9f5f8c3..8bb93dd3 100644 --- a/crates/cuda-driver/src/gdn_prompt_device.rs +++ b/crates/cuda-driver/src/gdn_prompt_device.rs @@ -59,7 +59,7 @@ mod stage_gpu_tests; #[path = "gdn_prompt_device/impl_context.rs"] mod impl_context; -#[path = "gdn_prompt_device/impl_originalgdnpromptdevice.rs"] -mod impl_originalgdnpromptdevice; #[path = "gdn_prompt_device/impl_drop_for_originalgdnpromptdevice.rs"] mod impl_drop_for_originalgdnpromptdevice; +#[path = "gdn_prompt_device/impl_originalgdnpromptdevice.rs"] +mod impl_originalgdnpromptdevice; diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs index 89ffc428..800ffcde 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalGdnPromptDevice<'ctx> { pub fn device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -16,16 +15,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { capacity: usize, profile: crate::GrNativeProfile, ) -> Result { - let required = Self::device_bytes(capacity)? - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; + let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|x| x > context.budget_bytes()) + if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -58,20 +52,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { Ok(owner) } pub fn is_failed(&self) -> bool { - self.failed - || self.context.is_poisoned() - || self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed) + self.failed || self.context.is_poisoned() || self.batch.as_ref().is_none_or(GdnPrefillBatch::is_failed) } pub fn allocated_bytes(&self) -> usize { - self.batch - .as_ref() - .map_or(0, GdnPrefillBatch::allocated_bytes) + self.batch.as_ref().map_or(0, GdnPrefillBatch::allocated_bytes) + self.scratch.as_ref().map_or(0, DeviceBuffer::len) - + self - .history - .iter() - .flatten() - .map(DeviceBuffer::len) - .sum::() + + self.history.iter().flatten().map(DeviceBuffer::len).sum::() } } diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs index 61bad2b9..630a1a7c 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalGdnPromptDevice<'ctx> { /// Consumes the actual affine GR read. `state` is untouched prior; only /// `next_state` is written. Runtime alone may adopt it after this clean drain. @@ -35,38 +34,25 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { let batch = self.batch.as_ref().ok_or(Error::ContextPoisoned)?; let status = batch.status_handle()?; let mut bindings = Bindings::new(); - let mut buffer = - |role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result { - if !std::ptr::eq(b.context, self.context) { - return Err(Error::ContextMismatch); - } - if b.len() != bytes { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 4)?; - workspace.reject_alias(h, bytes)?; - if h.overlaps(bytes, status, STATUS_BYTES) { - return Err(Error::OutputAliasesInput); - } - bindings.bind(role, h, bytes)?; - Ok(h) - }; - let scratch = buffer( - Role::Scratch, - self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - SCRATCH, - )?; - let hin = buffer( - Role::History, - self.history[0].as_ref().ok_or(Error::ContextPoisoned)?, - HISTORY, - )?; - let hout = buffer( - Role::NextHistory, - self.history[1].as_ref().ok_or(Error::ContextPoisoned)?, - HISTORY, - )?; + let mut buffer = |role: Role, b: &DeviceBuffer<'_>, bytes: usize| -> Result { + if !std::ptr::eq(b.context, self.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + workspace.reject_alias(h, bytes)?; + if h.overlaps(bytes, status, STATUS_BYTES) { + return Err(Error::OutputAliasesInput); + } + bindings.bind(role, h, bytes)?; + Ok(h) + }; + let scratch = buffer(Role::Scratch, self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, SCRATCH)?; + let hin = buffer(Role::History, self.history[0].as_ref().ok_or(Error::ContextPoisoned)?, HISTORY)?; + let hout = buffer(Role::NextHistory, self.history[1].as_ref().ok_or(Error::ContextPoisoned)?, HISTORY)?; let sin = buffer(Role::StateIn, state, STATE_WORDS * 4)?; let sout = buffer(Role::StateOut, next_state, STATE_WORDS * 4)?; let mut w = [sin; 5]; @@ -77,20 +63,13 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { (3, Role::AlphaW, HV, N), (4, Role::BetaW, HV, N), ] { - let bytes = if i < 3 { - weights.formats[i].matrix_bytes(n, k)? - } else { - n * k * 2 - }; + let bytes = if i < 3 { weights.formats[i].matrix_bytes(n, k)? } else { n * k * 2 }; w[i] = buffer(role, weights.matrices[i], bytes)?; } let mut a = [sin; 4]; - for (i, role, n) in [ - (0, Role::ConvW, C * 4 * 4), - (1, Role::Dt, HV * 4), - (2, Role::SsmA, HV * 4), - (3, Role::Gamma, S * 4), - ] { + for (i, role, n) in + [(0, Role::ConvW, C * 4 * 4), (1, Role::Dt, HV * 4), (2, Role::SsmA, HV * 4), (3, Role::Gamma, S * 4)] + { a[i] = buffer(role, weights.aux[i], n)?; } drop(buffer); @@ -115,22 +94,10 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { bindings.bind(role, h, bytes)?; Ok(h) }; - let mixed = carved( - Role::MixedH, - None, - Some((OriginalPromptSpan::MixedHalf, 5120)), - )?; - let high = carved( - Role::MixedBf, - None, - Some((OriginalPromptSpan::MixedHigh, 5120)), - )?; + let mixed = carved(Role::MixedH, None, Some((OriginalPromptSpan::MixedHalf, 5120)))?; + let high = carved(Role::MixedBf, None, Some((OriginalPromptSpan::MixedHigh, 5120)))?; let lower = if self.profile == crate::GrNativeProfile::HighAndLow { - Some(carved( - Role::MixedBfLo, - None, - Some((OriginalPromptSpan::MixedLow, 5120)), - )?) + Some(carved(Role::MixedBfLo, None, Some((OriginalPromptSpan::MixedLow, 5120)))?) } else { None }; @@ -146,14 +113,9 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { drop(carved); // Every owner/alias/shape admission above precedes the first write. let mut commands = Vec::new(); - commands - .try_reserve_exact(48) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; let funcs = batch.functions.as_ref().ok_or(Error::ContextPoisoned)?; - let mut push = |kernel: Kernel, - geometry: ([u32; 3], [u32; 3]), - args: &[ffi::KernelArg]| - -> Result<()> { + let mut push = |kernel: Kernel, geometry: ([u32; 3], [u32; 3]), args: &[ffi::KernelArg]| -> Result<()> { commands.push(DeviceCommand::Kernel { function: funcs.get(kernel), grid: geometry.0, @@ -162,14 +124,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { }); Ok(()) }; - push( - Kernel::Zero, - linear(SLOTS)?, - &[ - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(SLOTS as u32), - ], - )?; + push(Kernel::Zero, linear(SLOTS)?, &[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?; drop(push); let add_kernel = |commands: &mut Vec, kernel: Kernel, @@ -184,18 +139,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { }); Ok(()) }; - let scan = |commands: &mut Vec, - stage: GdnBatchStage, - data: ffi::BufferHandle| - -> Result<()> { + let scan = |commands: &mut Vec, stage: GdnBatchStage, data: ffi::BufferHandle| -> Result<()> { let word = status.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4)?; add_kernel( commands, - if stage.is_half() { - Kernel::FiniteF16 - } else { - Kernel::FiniteF32 - }, + if stage.is_half() { Kernel::FiniteF16 } else { Kernel::FiniteF32 }, linear(stage.elements(t))?, &[ ffi::KernelArg::Pointer(data), @@ -395,15 +343,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { &mut commands, Kernel::L2, ([32, t as u32, 1], [128, 1, 1]), - &[ - ffi::KernelArg::Pointer(h), - ffi::KernelArg::F32(GDN_BATCH_EPSILON), - ], + &[ffi::KernelArg::Pointer(h), ffi::KernelArg::F32(GDN_BATCH_EPSILON)], )?; scan(&mut commands, GdnBatchStage::Qk, h)?; } - let witness = - status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?; + let witness = status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?; if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) { let kh = !crate::prefill_stage::fast_rec(); commands.push(DeviceCommand::Stage { @@ -441,7 +385,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { scan(&mut commands, GdnBatchStage::NextState, sout)?; if fused { commands.push(DeviceCommand::Stage { - index: if crate::prefill_stage::gdn_nostore() { crate::prefill_stage::GDN_OUT_NORM_Y16 } else { crate::prefill_stage::GDN_OUT_NORM }, + index: if crate::prefill_stage::gdn_nostore() { + crate::prefill_stage::GDN_OUT_NORM_Y16 + } else { + crate::prefill_stage::GDN_OUT_NORM + }, grid: (48 * t).div_ceil(2) as u32, block: 256, args: KernelArguments::new(vec![ @@ -483,9 +431,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { let mut flags = staging(STATUS_BYTES)?; let mut final_history = staging(HISTORY)?; let mut values = Vec::new(); - values - .try_reserve_exact(HISTORY_WORDS) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; let context = self.context; let blas = workspace.blas()?; let guard = match context.enter() { @@ -509,11 +455,8 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { } let timed = crate::command_profile::enabled(); let started = std::time::Instant::now(); - let mut operation = context - .driver - .api - .copy_from(hin, &history_bytes) - .and_then(|()| context.driver.api.synchronize()); + let mut operation = + context.driver.api.copy_from(hin, &history_bytes).and_then(|()| context.driver.api.synchronize()); if timed { crate::command_profile::add("gdn", 0, "history upload", started.elapsed()); } @@ -522,37 +465,23 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { break; } let started = std::time::Instant::now(); - let label = match cmd { DeviceCommand::Kernel { .. } => "kernel", DeviceCommand::Gemm { .. } => "gemm", DeviceCommand::Stage { .. } => "stage" }; + let label = match cmd { + DeviceCommand::Kernel { .. } => "kernel", + DeviceCommand::Gemm { .. } => "gemm", + DeviceCommand::Stage { .. } => "stage", + }; operation = match cmd { - DeviceCommand::Kernel { - function, - grid, - block, - args, - } => context.driver.api.launch_gdn_native( + DeviceCommand::Kernel { function, grid, block, args } => context.driver.api.launch_gdn_native( *function, GdnStream::from_raw(blas.stream()), *grid, *block, args, ), - DeviceCommand::Gemm { - bf16, - x, - w, - y, - n, - k, - ldy, - offset, - beta, - } => blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta), - DeviceCommand::Stage { - index, - grid, - block, - args, - } => match self.stage.as_ref() { + DeviceCommand::Gemm { bf16, x, w, y, n, k, ldy, offset, beta } => { + blas.gemm_gdn(*bf16, *x, *w, *y, t as i32, *n, *k, *ldy, *offset, beta) + } + DeviceCommand::Stage { index, grid, block, args } => match self.stage.as_ref() { Some(module) => module.launch(*index, *grid, *block, blas.stream(), args), None => Err(Error::ContextPoisoned), }, @@ -603,13 +532,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { _ => "GDN prompt stage", })); } - values.extend( - final_history - .as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x)), - ); + values.extend(final_history.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); if values.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("GDN final history")); } diff --git a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs index 83624a70..9d2ff333 100644 --- a/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs +++ b/crates/cuda-driver/src/gdn_prompt_device/impl_originalgdnpromptdevice/impl_originalgdnpromptdevice_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalGdnPromptDevice<'ctx> { pub fn close(mut self) -> Result<()> { self.close_inner() @@ -11,12 +10,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> { pub(in super::super) fn close_inner(&mut self) -> Result<()> { self.failed = true; let mut result = Ok(()); - for b in self - .history - .iter_mut() - .filter_map(Option::take) - .chain(self.scratch.take()) - { + for b in self.history.iter_mut().filter_map(Option::take).chain(self.scratch.take()) { let r = if self.context.is_poisoned() { std::mem::forget(b); Err(Error::ContextPoisoned) diff --git a/crates/cuda-driver/src/gdn_state_finite_guard.rs b/crates/cuda-driver/src/gdn_state_finite_guard.rs index 1b1d15f2..6d23ca97 100644 --- a/crates/cuda-driver/src/gdn_state_finite_guard.rs +++ b/crates/cuda-driver/src/gdn_state_finite_guard.rs @@ -29,20 +29,10 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(STATUS_BYTES) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - status: None, - module: None, - functions: None, - failed: false, - }; + let mut owner = Self { context, status: None, module: None, functions: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); let guard = context.enter()?; @@ -90,9 +80,7 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { return Err(Error::ContextPoisoned); } let status_buffer = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(self.context, next.context) - || !std::ptr::eq(self.context, status_buffer.context) - { + if !std::ptr::eq(self.context, next.context) || !std::ptr::eq(self.context, status_buffer.context) { return Err(Error::ContextMismatch); } if next.bytes != STATE_BYTES || status_buffer.bytes != STATUS_BYTES { @@ -109,22 +97,12 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { let mut reset = ffi::MmqResidentArguments::zero(status, 1); let mut scan = ffi::MmqResidentArguments::finite(source, status, 0, STATE_WORDS, 0); let mut staging = Vec::new(); - staging - .try_reserve_exact(STATUS_BYTES) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(STATUS_BYTES).map_err(|_| Error::HostAllocation)?; staging.resize(STATUS_BYTES, 0); let guard = self.context.enter()?; - let mut operation = - self.context - .driver - .api - .launch_mmq_resident(functions[0], 1, &mut reset); + let mut operation = self.context.driver.api.launch_mmq_resident(functions[0], 1, &mut reset); if operation.is_ok() { - operation = - self.context - .driver - .api - .launch_mmq_resident(functions[1], STATE_WORDS, &mut scan); + operation = self.context.driver.api.launch_mmq_resident(functions[1], STATE_WORDS, &mut scan); } if operation.is_ok() { operation = self.context.driver.api.copy_to(status, &mut staging); @@ -170,13 +148,10 @@ impl<'ctx> GdnStateFiniteGuard<'ctx> { if status_result.is_err() { self.context.poisoned.set(true); } - let module_result = - self.module - .take() - .map_or(Ok(()), |module| match self.context.enter() { - Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), - Err(error) => Err(error), - }); + let module_result = self.module.take().map_or(Ok(()), |module| match self.context.enter() { + Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), + Err(error) => Err(error), + }); if module_result.is_err() { self.context.poisoned.set(true); // Keep the driver ABI loaded while an uncertain module can exist. diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace.rs b/crates/cuda-driver/src/gr_batch_inject_workspace.rs index f6ec3caf..e66f352d 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace.rs @@ -48,10 +48,7 @@ fn layout(shape: GrBatchInjectShape) -> Result { for bytes in result.bytes.iter_mut().take(result.count) { *bytes = bytes.checked_mul(tokens).ok_or(Error::InvalidQwenShape)?; } - result.columns = result - .columns - .checked_mul(tokens as u32) - .ok_or(Error::InvalidQwenShape)?; + result.columns = result.columns.checked_mul(tokens as u32).ok_or(Error::InvalidQwenShape)?; result.grid_y = tokens as u32; Ok(result) } @@ -62,13 +59,8 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } // Validate the SAME original module receipt before any allocation. qwen_ffi::gr_batch_preview_ptx()?; - let required = GR_BATCH_INJECT_WORKSPACE_BYTES - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) + let required = GR_BATCH_INJECT_WORKSPACE_BYTES.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -90,12 +82,7 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { let load = (|| { let module = context.driver.api.load_gr_batch_preview_module()?; owner.module = Some(module); - owner.kernel = Some( - context - .driver - .api - .qwen_function(module, Operation::InjectResidual)?, - ); + owner.kernel = Some(context.driver.api.qwen_function(module, Operation::InjectResidual)?); Ok(()) })(); let pop = guard.finish(); @@ -120,22 +107,14 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { self.failed || self.context.is_poisoned() || self.context.handle.is_none() } pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .flatten() - .map(|buffer| buffer.bytes) - .sum() + self.buffers.iter().flatten().flatten().map(|buffer| buffer.bytes).sum() } fn handles(&self, shape: GrBatchInjectShape) -> Result<[ffi::BufferHandle; 9]> { if self.is_failed() || self.module.is_none() || self.kernel.is_none() { return Err(Error::ContextPoisoned); } // Fixed stack ledger; no heap allocation in whole-owner validation. - let first = self.buffers[0][0] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?; + let first = self.buffers[0][0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?; let mut owned = [(first, 0usize); 12]; let mut count = 0; for (bank, buffers) in self.buffers.iter().enumerate() { @@ -150,11 +129,7 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; handle.validate_projection_extent(bytes, 4)?; - if owned - .iter() - .take(count) - .any(|(prior, prior_bytes)| handle.overlaps(bytes, *prior, *prior_bytes)) - { + if owned.iter().take(count).any(|(prior, prior_bytes)| handle.overlaps(bytes, *prior, *prior_bytes)) { return Err(Error::OutputAliasesInput); } owned[count] = (handle, bytes); @@ -167,13 +142,7 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { for i in 0..4 { (handles[i], bytes[i]) = owned[start + i]; } - ranges_layout( - Operation::InjectResidual, - layout(shape)?, - handles, - bytes, - false, - )?; + ranges_layout(Operation::InjectResidual, layout(shape)?, handles, bytes, false)?; if self.context.allocated_bytes() > self.context.budget_bytes() { return Err(Error::BudgetExceeded); } @@ -195,28 +164,15 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } let handles = self.handles(shape)?; let tokens = shape.tokens(); - if streams.len() != 10240 * tokens - || blocks.len() != 2560 * tokens - || injects.len() != 4 * tokens - { + if streams.len() != 10240 * tokens || blocks.len() != 2560 * tokens || injects.len() != 4 * tokens { return Err(Error::InvalidQwenShape); } - if streams - .iter() - .chain(blocks) - .chain(injects) - .any(|value| !value.is_finite()) - { + if streams.iter().chain(blocks).chain(injects).any(|value| !value.is_finite()) { return Err(Error::InvalidDriverValue("GR batch injection finite input")); } // Fallible initialized staging is retained through every attempted command. let staging = [encode(streams)?, encode(blocks)?, encode(injects)?]; - let mut arguments = Box::new(Arguments::with_layout( - Operation::InjectResidual, - layout(shape)?, - handles, - 0., - )); + let mut arguments = Box::new(Arguments::with_layout(Operation::InjectResidual, layout(shape)?, handles, 0.)); let kernel = self.kernel.ok_or(Error::ContextPoisoned)?; let guard = self.context.enter()?; let mut commands = Ok(()); @@ -227,11 +183,7 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } } if commands.is_ok() { - commands = self.context.driver.api.launch_qwen( - kernel, - Operation::InjectResidual, - &mut arguments, - ); + commands = self.context.driver.api.launch_qwen(kernel, Operation::InjectResidual, &mut arguments); } // Fence all attempted uploads/launches, including the first failed call. let sync = self.context.driver.api.synchronize(); @@ -246,9 +198,7 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { std::mem::forget((staging, arguments)); } combine(combine(commands, sync), pop)?; - let output = self.buffers[shape.bank()][3] - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let output = self.buffers[shape.bank()][3].as_ref().ok_or(Error::ContextPoisoned)?; let readback = match output.copy_to_owned(40960 * tokens) { Ok(bytes) => bytes, Err(error) => { @@ -259,16 +209,8 @@ impl<'ctx> GrBatchInjectWorkspace<'ctx> { } }; let mut values = Vec::new(); - values - .try_reserve_exact(10240 * tokens) - .map_err(|_| Error::HostAllocation)?; - values.extend( - readback - .as_chunks::<4>() - .0 - .iter() - .map(|bytes| f32::from_le_bytes(*bytes)), - ); + values.try_reserve_exact(10240 * tokens).map_err(|_| Error::HostAllocation)?; + values.extend(readback.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); Ok(values.into_boxed_slice()) } pub fn close(mut self) -> Result<()> { @@ -320,9 +262,7 @@ impl Drop for GrBatchInjectWorkspace<'_> { } fn encode(values: &[f32]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len() * 4) - .map_err(|_| Error::HostAllocation)?; + bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::HostAllocation)?; bytes.extend(values.iter().flat_map(|value| value.to_le_bytes())); Ok(bytes) } diff --git a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs index f5ff7ddf..3371113f 100644 --- a/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs +++ b/crates/cuda-driver/src/gr_batch_inject_workspace_gpu.rs @@ -4,11 +4,7 @@ use crate::Driver; type Products = [Vec; 4]; fn check(ok: bool) -> Result<()> { - if ok { - Ok(()) - } else { - Err(Error::InvalidDriverValue("GR batch workspace proof")) - } + if ok { Ok(()) } else { Err(Error::InvalidDriverValue("GR batch workspace proof")) } } fn bytes(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() @@ -57,21 +53,14 @@ fn inputs(tokens: usize, pattern: usize) -> [Vec; 3] { } // All actual old owners are explicitly closed even on a comparison refusal. -fn original( - context: &Context<'_>, - shape: GrBatchInjectShape, - source: &[Vec; 3], -) -> Result { +fn original(context: &Context<'_>, shape: GrBatchInjectShape, source: &[Vec; 3]) -> Result { let mut buffers: [Option>; 4] = std::array::from_fn(|_| None); let result = (|| { for (i, size) in ROW_BYTES.into_iter().enumerate() { buffers[i] = Some(context.allocate(size * shape.tokens())?); } for (buffer, source) in buffers.iter_mut().zip(source).take(3) { - buffer - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&bytes(source))?; + buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&bytes(source))?; } let (sources, output) = buffers.split_at_mut(3); context.gr_batch_inject_residual_f32( @@ -83,10 +72,8 @@ fn original( )?; let mut products: Products = std::array::from_fn(|_| Vec::new()); for (i, buffer) in buffers.iter().enumerate() { - products[i] = buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .copy_to_owned(ROW_BYTES[i] * shape.tokens())?; + products[i] = + buffer.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(ROW_BYTES[i] * shape.tokens())?; } Ok(products) })(); @@ -99,10 +86,7 @@ fn original( fn products(workspace: &GrBatchInjectWorkspace<'_>, shape: GrBatchInjectShape) -> Result { let mut result = std::array::from_fn(|_| Vec::new()); for (i, buffer) in workspace.buffers[shape.bank()].iter().enumerate() { - result[i] = buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .copy_to_owned(ROW_BYTES[i] * shape.tokens())?; + result[i] = buffer.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(ROW_BYTES[i] * shape.tokens())?; } Ok(result) } @@ -137,38 +121,22 @@ fn refuses_without_change( let charged = context.allocated_bytes(); let refusal = workspace.inject(context, shape, &source[0], &source[1], &source[2]); check(refusal.err() == Some(expected))?; - check( - products(workspace, shape)? == previous - && context.allocated_bytes() == charged - && !workspace.is_failed(), - ) + check(products(workspace, shape)? == previous && context.allocated_bytes() == charged && !workspace.is_failed()) } #[test] #[ignore] fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA172_RUN_GR_BATCH_INJECT_WORKSPACE").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA172_RUN_GR_BATCH_INJECT_WORKSPACE").as_deref(), Ok("yes")); let driver = Driver::load().expect("real CUDA driver required"); let device = driver.device(0).expect("real GPU required"); - let context = device - .create_context(512 * 1024 * 1024) - .expect("owned Context"); - let foreign = device - .create_context(512 * 1024 * 1024) - .expect("foreign Context"); - let budget = device - .create_context(GR_BATCH_INJECT_WORKSPACE_BYTES + RESERVE - 1) - .expect("budget Context"); + let context = device.create_context(512 * 1024 * 1024).expect("owned Context"); + let foreign = device.create_context(512 * 1024 * 1024).expect("foreign Context"); + let budget = device.create_context(GR_BATCH_INJECT_WORKSPACE_BYTES + RESERVE - 1).expect("budget Context"); let result = (|| -> Result<(usize, usize)> { // Scope the borrowed Result/owner before the budget Context is moved. let refused = match budget.gr_batch_inject_workspace() { - Ok(owner) => combine( - Err(Error::InvalidDriverValue("missing eager budget refusal")), - owner.close(), - ), + Ok(owner) => combine(Err(Error::InvalidDriverValue("missing eager budget refusal")), owner.close()), Err(error) => check(error == Error::BudgetExceeded), }; refused?; @@ -178,40 +146,19 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { check(workspace.allocated_bytes() == GR_BATCH_INJECT_WORKSPACE_BYTES)?; let mut words = 0; let mut guards = 1; - for shape in [ - GrBatchInjectShape::T1, - GrBatchInjectShape::T2, - GrBatchInjectShape::T3, - ] { + for shape in [GrBatchInjectShape::T1, GrBatchInjectShape::T2, GrBatchInjectShape::T3] { for pattern in [0, 1, 2, 0] { - words += original_first( - &context, - &mut workspace, - shape, - &inputs(shape.tokens(), pattern), - )?; + words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), pattern))?; } // All three roles and both short/long lengths refuse before writes. for role in 0..3 { let mut wrong = inputs(shape.tokens(), 1); wrong[role].pop(); - refuses_without_change( - &context, - &mut workspace, - shape, - &wrong, - Error::InvalidQwenShape, - )?; + refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?; guards += 1; wrong[role].push(0.); wrong[role].push(0.); - refuses_without_change( - &context, - &mut workspace, - shape, - &wrong, - Error::InvalidQwenShape, - )?; + refuses_without_change(&context, &mut workspace, shape, &wrong, Error::InvalidQwenShape)?; guards += 1; for invalid in [f32::NAN, f32::INFINITY] { let mut late = inputs(shape.tokens(), 1); @@ -224,20 +171,13 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { Error::InvalidDriverValue("GR batch injection finite input"), )?; guards += 1; - words += original_first( - &context, - &mut workspace, - shape, - &inputs(shape.tokens(), 0), - )?; + words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 0))?; } } let previous = products(&workspace, shape)?; let source = inputs(shape.tokens(), 0); check( - workspace - .inject(&foreign, shape, &source[0], &source[1], &source[2]) - .err() + workspace.inject(&foreign, shape, &source[0], &source[1], &source[2]).err() == Some(Error::ContextMismatch), )?; check(products(&workspace, shape)? == previous && !workspace.is_failed())?; @@ -256,18 +196,12 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { .iter() .any(|b| !f32::from_le_bytes(*b).is_finite()), )?; - words += - original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 1))?; + words += original_first(&context, &mut workspace, shape, &inputs(shape.tokens(), 1))?; } // Switching one bank cannot overwrite a completed other whole bank. let t1 = products(&workspace, GrBatchInjectShape::T1)?; let t2 = products(&workspace, GrBatchInjectShape::T2)?; - words += original_first( - &context, - &mut workspace, - GrBatchInjectShape::T3, - &inputs(3, 2), - )?; + words += original_first(&context, &mut workspace, GrBatchInjectShape::T3, &inputs(3, 2))?; check( products(&workspace, GrBatchInjectShape::T1)? == t1 && products(&workspace, GrBatchInjectShape::T2)? == t2, @@ -277,16 +211,9 @@ fn original_first_t1_t2_t3_gr_batch_injection_overwrite_refusal_and_cleanup() { })(); combine(operation, workspace.close()) })(); - let allocated = [ - context.allocated_bytes(), - foreign.allocated_bytes(), - budget.allocated_bytes(), - ]; + let allocated = [context.allocated_bytes(), foreign.allocated_bytes(), budget.allocated_bytes()]; // Every actual Context is closed before result/numerical assertions. - let result = combine( - combine(combine(result, context.close()), foreign.close()), - budget.close(), - ); + let result = combine(combine(combine(result, context.close()), foreign.close()), budget.close()); let (words, guards) = result.expect("original-first workspace proof and exhaustive teardown"); assert_eq!(allocated, [0; 3]); println!( diff --git a/crates/cuda-driver/src/gr_batch_read.rs b/crates/cuda-driver/src/gr_batch_read.rs index 572ac60d..70dd916d 100644 --- a/crates/cuda-driver/src/gr_batch_read.rs +++ b/crates/cuda-driver/src/gr_batch_read.rs @@ -4,9 +4,7 @@ //! rounding equivalence or expose a model/row/finite capability. use super::*; -const SIZES: [usize; 11] = [ - 40960, 40960, 1280, 1280, 40960, 40960, 10240, 16, 10240, 40960, 32, -]; +const SIZES: [usize; 11] = [40960, 40960, 1280, 1280, 40960, 40960, 10240, 16, 10240, 40960, 32]; const OPS: [Operation; 6] = [ Operation::Norm, Operation::Down, @@ -35,15 +33,7 @@ pub struct GrMicrobatchRead<'ctx> { phase: u8, failed: bool, } -const STAGES: [&str; 7] = [ - "GR norm", - "GR down", - "GR silu", - "GR up", - "GR products", - "GR mixed", - "GR inject", -]; +const STAGES: [&str; 7] = ["GR norm", "GR down", "GR silu", "GR up", "GR products", "GR mixed", "GR inject"]; #[cfg(test)] mod tests { @@ -60,10 +50,7 @@ mod tests { assert!(end <= whole); } assert_eq!(end, tokens * bytes); - assert_eq!( - checked_row(tokens, tokens, bytes), - Err(Error::InvalidQwenShape) - ); + assert_eq!(checked_row(tokens, tokens, bytes), Err(Error::InvalidQwenShape)); } } for invalid in [0, 65, usize::MAX] { @@ -72,12 +59,7 @@ mod tests { } } -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64", - feature = "cuda-driver" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] mod installed { use super::*; use crate::Driver; @@ -95,26 +77,14 @@ mod installed { block: &[f32], ) -> Result { let mut buffers = Vec::new(); - buffers - .try_reserve_exact(10) - .map_err(|_| Error::HostAllocation)?; + buffers.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; for bytes in SIZES.iter().take(10) { buffers.push(context.allocate(*bytes)?); } let result = (|| { buffers[0].copy_from_owned(encode(streams)?)?; - let [ - residual, - xn, - down, - activated, - gates, - products, - mixed, - inject, - output, - candidate, - ] = buffers.as_mut_slice() + let [residual, xn, down, activated, gates, products, mixed, inject, output, candidate] = + buffers.as_mut_slice() else { return Err(Error::InvalidQwenShape); }; @@ -137,36 +107,21 @@ mod installed { context.gr_inject_residual_f32(residual, output, inject, candidate)?; Ok((mixed_values, injection_values, decode(candidate)?)) })(); - let cleanup = buffers - .into_iter() - .rev() - .fold(Ok(()), |old, buffer| combine(old, buffer.release())); + let cleanup = buffers.into_iter().rev().fold(Ok(()), |old, buffer| combine(old, buffer.release())); combine(result, cleanup) } #[test] #[ignore = "Root-only changed genuine T-bank transport arithmetic gate"] fn original_first_microbank_read_inject_ffn_all_rows_bits_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GR_MICROBATCH").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GR_MICROBATCH").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(192 * 1024 * 1024).unwrap(); let mut weights = Vec::new(); - for (count, bf16) in [ - (10240, false), - (320 * 10240, true), - (10240 * 320, true), - (4 * 10240, true), - ] { + for (count, bf16) in [(10240, false), (320 * 10240, true), (10240 * 320, true), (4 * 10240, true)] { let mut bytes = Vec::new(); for i in 0..count { - let value = if bf16 { - if i % 13 == 0 { 0.015625f32 } else { 0.0 } - } else { - 1.0f32 - }; + let value = if bf16 { if i % 13 == 0 { 0.015625f32 } else { 0.0 } } else { 1.0f32 }; if bf16 { bytes.extend_from_slice(&((value.to_bits() >> 16) as u16).to_le_bytes()); } else { @@ -176,25 +131,14 @@ mod installed { weights.push(upload(&context, &bytes).unwrap()); } let result = (|| -> Result { - let refs: [&DeviceBuffer<'_>; 4] = weights - .iter() - .collect::>() - .try_into() - .map_err(|_| Error::InvalidQwenShape)?; + let refs: [&DeviceBuffer<'_>; 4] = + weights.iter().collect::>().try_into().map_err(|_| Error::InvalidQwenShape)?; let mut words = 0usize; for tokens in [1usize, 3, 64] { let streams: Vec = (0..tokens * 10240) - .map(|i| { - if i % 29 == 0 { - -0.0 - } else { - ((i % 97) as f32 - 48.) * 0.00390625 - } - }) - .collect(); - let blocks: Vec = (0..tokens * 2560) - .map(|i| ((i % 19) as f32 - 9.) * 0.015625) + .map(|i| if i % 29 == 0 { -0.0 } else { ((i % 97) as f32 - 48.) * 0.00390625 }) .collect(); + let blocks: Vec = (0..tokens * 2560).map(|i| ((i % 19) as f32 - 9.) * 0.015625).collect(); let mut expected_mixed = Vec::new(); let mut expected_inject = Vec::new(); let mut expected_streams = Vec::new(); @@ -256,9 +200,7 @@ mod installed { // Same ONE changed-bank entry: a late gamma NaN/Inf is // observed by the old full read FIRST, then ordered bank status; // valid weights reuse the completed numerical-refusal owner. - let streams: Vec = (0..3 * 10240) - .map(|i| ((i % 31) as f32 + 1.) / 32.) - .collect(); + let streams: Vec = (0..3 * 10240).map(|i| ((i % 31) as f32 + 1.) / 32.).collect(); let blocks = vec![0.125f32; 3 * 2560]; let expected = original(&context, refs, &streams[..10240], &blocks[..2560])?.0; let mut bank = context.gr_microbatch_read(3, &streams)?; @@ -276,26 +218,18 @@ mod installed { && !bank.is_failed(); bad.release()?; if !refused { - return Err(Error::InvalidDriverValue( - "GR micro full finite arbitration", - )); + return Err(Error::InvalidDriverValue("GR micro full finite arbitration")); } let valid = bank.read(refs, 1e-6)?; - if !valid.mixed[..2560] - .iter() - .zip(expected.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) - { + if !valid.mixed[..2560].iter().zip(expected.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) { return Err(Error::InvalidDriverValue("GR micro status reset")); } let mut invalid_block = blocks.clone(); let last = invalid_block.len() - 1; invalid_block[last] = invalid; let before = bank.phase; - if !matches!( - bank.inject(&invalid_block), - Err(Error::InvalidDriverValue("GR micro block finite")) - ) || bank.phase != before + if !matches!(bank.inject(&invalid_block), Err(Error::InvalidDriverValue("GR micro block finite"))) + || bank.phase != before || bank.is_failed() { return Err(Error::InvalidDriverValue("GR micro prewrite refusal")); @@ -316,17 +250,12 @@ mod installed { } Ok(words) })(); - let cleanup = weights - .into_iter() - .rev() - .fold(Ok(()), |old, buffer| combine(old, buffer.release())); + let cleanup = weights.into_iter().rev().fold(Ok(()), |old, buffer| combine(old, buffer.release())); let allocated = context.allocated_bytes(); let closed = context.close(); let words = combine(combine(result, cleanup), closed).unwrap(); assert_eq!(allocated, 0); - eprintln!( - "GR microbank original-FIRST words={words} bit_exact=true allocated0=true context_closed=true" - ); + eprintln!("GR microbank original-FIRST words={words} bit_exact=true allocated0=true context_closed=true"); } } @@ -336,9 +265,9 @@ mod impl_context; use impl_context::checked_row; #[allow(unused_imports)] use impl_context::encode; -#[path = "gr_batch_read/impl_grmicrobatchread.rs"] -mod impl_grmicrobatchread; #[path = "gr_batch_read/impl_drop_for_grmicrobatchread.rs"] mod impl_drop_for_grmicrobatchread; +#[path = "gr_batch_read/impl_grmicrobatchread.rs"] +mod impl_grmicrobatchread; #[allow(unused_imports)] use impl_drop_for_grmicrobatchread::decode; diff --git a/crates/cuda-driver/src/gr_batch_read/impl_context.rs b/crates/cuda-driver/src/gr_batch_read/impl_context.rs index 7fb56b09..8025bef3 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_context.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_context.rs @@ -4,11 +4,7 @@ use super::*; impl Context<'_> { - pub fn gr_microbatch_read( - &self, - tokens: usize, - streams: &[f32], - ) -> Result> { + pub fn gr_microbatch_read(&self, tokens: usize, streams: &[f32]) -> Result> { GrMicrobatchRead::new(self, tokens, streams) } } diff --git a/crates/cuda-driver/src/gr_batch_read/impl_drop_for_grmicrobatchread.rs b/crates/cuda-driver/src/gr_batch_read/impl_drop_for_grmicrobatchread.rs index 2538d19b..c12ec9de 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_drop_for_grmicrobatchread.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_drop_for_grmicrobatchread.rs @@ -11,16 +11,8 @@ impl Drop for GrMicrobatchRead<'_> { pub(super) fn decode(buffer: &DeviceBuffer<'_>) -> Result> { let bytes = buffer.copy_to_owned(buffer.len())?; let mut values = Vec::new(); - values - .try_reserve_exact(bytes.len() / 4) - .map_err(|_| Error::HostAllocation)?; - values.extend( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); if values.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("GR canonical readback")); } diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs index b4d073b4..330520ff 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrMicrobatchRead<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>, tokens: usize, streams: &[f32]) -> Result { checked_row(tokens, 0, 40960)?; @@ -16,13 +15,9 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if context.is_poisoned() { return Err(Error::ContextPoisoned); } - let required = SIZES.iter().try_fold(RESERVE, |sum, n| { - sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) - })?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) + let required = + SIZES.iter().try_fold(RESERVE, |sum, n| sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded))?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -57,10 +52,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if context.memory_info()?.0 < RESERVE { return Err(Error::BudgetExceeded); } - owner.buffers[0] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(staging)?; + owner.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_owned(staging)?; Ok(()) })(); if let Err(primary) = result { @@ -81,10 +73,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if self.is_failed() { return Err(Error::ContextPoisoned); } - self.buffers - .get(slot) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn handle(&self, slot: usize, row: usize) -> Result { let buffer = self.buffer(slot)?; @@ -95,10 +84,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if buffer.len() != whole { return Err(Error::InvalidQwenShape); } - buffer - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(whole, offset, SIZES[slot]) + buffer.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(whole, offset, SIZES[slot]) } pub(in super::super) fn validate(&self, weights: &[&DeviceBuffer<'_>]) -> Result<()> { if self.is_failed() || self.finite_module.is_none() || self.finite.is_none() { @@ -109,11 +95,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { self.handle(i, self.tokens - 1)?; let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; for prior in self.buffers[..i].iter().flatten() { - if handle.overlaps( - buffer.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { + if handle.overlaps(buffer.bytes, prior.handle.ok_or(Error::ContextPoisoned)?, prior.bytes) { return Err(Error::OutputAliasesInput); } } @@ -121,11 +103,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if !std::ptr::eq(self.context, weight.context) { return Err(Error::ContextMismatch); } - if handle.overlaps( - buffer.bytes, - weight.handle.ok_or(Error::ContextPoisoned)?, - weight.bytes, - ) { + if handle.overlaps(buffer.bytes, weight.handle.ok_or(Error::ContextPoisoned)?, weight.bytes) { return Err(Error::OutputAliasesInput); } } @@ -162,9 +140,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { &[w[3], h[1], h[7]], ]; let mut prepared = Vec::new(); - prepared - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; + prepared.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; for (operation, set) in OPS.into_iter().zip(sets) { let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; asset.validate(operation)?; diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs index c5ee2948..7e0aec80 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrMicrobatchRead<'ctx> { // Seven separate actual status words per row preserve complete ordered // Norm/Down/Silu/Up/products/mixed/inject refusal arbitration. The reused @@ -14,13 +13,9 @@ impl<'ctx> GrMicrobatchRead<'ctx> { } self.validate(&weights)?; let mut arguments = Vec::new(); - arguments - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; + arguments.try_reserve_exact(self.tokens).map_err(|_| Error::HostAllocation)?; let mut scans = Vec::new(); - scans - .try_reserve_exact(self.tokens * 7) - .map_err(|_| Error::HostAllocation)?; + scans.try_reserve_exact(self.tokens * 7).map_err(|_| Error::HostAllocation)?; for row in 0..self.tokens { arguments.push(self.row_arguments(row, weights, epsilon)?); for (stage, slot) in [1, 2, 3, 4, 5, 6, 7].into_iter().enumerate() { @@ -39,9 +34,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { let guard = self.context.enter()?; let kernels = (|| { let mut result = Vec::new(); - result - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; for operation in OPS { result.push(registered( self.context, @@ -73,11 +66,8 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if commands.is_err() { break; } - commands = self.context.driver.api.launch_qwen( - kernels[stage].function, - OPS[stage], - &mut row_args[stage], - ); + commands = + self.context.driver.api.launch_qwen(kernels[stage].function, OPS[stage], &mut row_args[stage]); if commands.is_ok() { let scan_stage = if stage == 5 { 6 } else { stage }; let words = SIZES[[1, 2, 3, 4, 5, 7][stage]] / 4; @@ -91,11 +81,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { } } if stage == 4 && commands.is_ok() { - commands = self.context.driver.api.launch_mmq_resident( - finite, - 2560, - &mut scans[row * 7 + 5], - ); + commands = self.context.driver.api.launch_mmq_resident(finite, 2560, &mut scans[row * 7 + 5]); if commands.is_ok() { completed_scans += 1; } @@ -105,11 +91,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { break; } } - let read_status = if initialized { - self.context.driver.api.copy_to(status, &mut readback) - } else { - Ok(()) - }; + let read_status = if initialized { self.context.driver.api.copy_to(status, &mut readback) } else { Ok(()) }; let status_read = initialized && read_status.is_ok(); let commands = combine(commands, read_status); let sync = self.context.driver.api.synchronize(); @@ -133,9 +115,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { break; } scan_index += 1; - let flag = u32::from_le_bytes( - bytes.try_into().map_err(|_| Error::InvalidQwenShape)?, - ); + let flag = u32::from_le_bytes(bytes.try_into().map_err(|_| Error::InvalidQwenShape)?); if flag & !1 != 0 { self.failed = true; return Err(Error::InvalidDriverValue("GR micro finite status")); @@ -152,7 +132,6 @@ impl<'ctx> GrMicrobatchRead<'ctx> { self.phase = 1; return Ok(GrMicroValues { mixed, inject }); } - combine(combine(commands, sync), pop) - .map(|()| unreachable!("uncertain completion is an error")) + combine(combine(commands, sync), pop).map(|()| unreachable!("uncertain completion is an error")) } } diff --git a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs index d00c0e86..aae23254 100644 --- a/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs +++ b/crates/cuda-driver/src/gr_batch_read/impl_grmicrobatchread/impl_grmicrobatchread_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrMicrobatchRead<'ctx> { /// Original residual write consumes retained real input and injection banks. /// Blocks are the only new upload. Completed candidate is retained as the @@ -22,12 +21,8 @@ impl<'ctx> GrMicrobatchRead<'ctx> { let staging = encode(blocks)?; let mut arguments = Vec::new(); let mut scans = Vec::new(); - arguments - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; - scans - .try_reserve_exact(self.tokens) - .map_err(|_| Error::HostAllocation)?; + arguments.try_reserve_exact(self.tokens).map_err(|_| Error::HostAllocation)?; + scans.try_reserve_exact(self.tokens).map_err(|_| Error::HostAllocation)?; let operation = Operation::InjectResidual; let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; asset.validate(operation)?; @@ -74,11 +69,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { if commands.is_err() { break; } - commands = self - .context - .driver - .api - .launch_qwen(kernel.function, operation, args); + commands = self.context.driver.api.launch_qwen(kernel.function, operation, args); if commands.is_ok() { commands = self.context.driver.api.launch_mmq_resident( self.finite.ok_or(Error::ContextPoisoned)?, @@ -90,11 +81,7 @@ impl<'ctx> GrMicrobatchRead<'ctx> { completed_scans += 1; } } - let read_status = if initialized { - self.context.driver.api.copy_to(status, &mut readback) - } else { - Ok(()) - }; + let read_status = if initialized { self.context.driver.api.copy_to(status, &mut readback) } else { Ok(()) }; let status_read = initialized && read_status.is_ok(); let commands = combine(commands, read_status); let sync = self.context.driver.api.synchronize(); @@ -106,16 +93,11 @@ impl<'ctx> GrMicrobatchRead<'ctx> { self.context.poison(); self.context.retain_driver(); std::mem::forget((arguments, scans, staging, zero, readback)); - return combine(combine(commands, sync), pop) - .map(|()| unreachable!("uncertain completion")); + return combine(combine(commands, sync), pop).map(|()| unreachable!("uncertain completion")); } if status_read { for row in readback.chunks_exact(32).take(completed_scans) { - let flag = u32::from_le_bytes( - row[28..32] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ); + let flag = u32::from_le_bytes(row[28..32].try_into().map_err(|_| Error::InvalidQwenShape)?); if flag & !1 != 0 { self.failed = true; return Err(Error::InvalidDriverValue("GR micro candidate status")); diff --git a/crates/cuda-driver/src/gr_native_batch.rs b/crates/cuda-driver/src/gr_native_batch.rs index f30d7e0a..caf54da9 100644 --- a/crates/cuda-driver/src/gr_native_batch.rs +++ b/crates/cuda-driver/src/gr_native_batch.rs @@ -18,9 +18,7 @@ const ENTRIES: &[&CStr] = &[ ]; // Every active span is a whole owner; optional low operands have genuine // storage but are passed as NULL in HighOnly to preserve Original arithmetic. -const BYTES: [usize; 15] = [ - 40960, 16, 20480, 20480, 1280, 640, 640, 40960, 10240, 5120, 5120, 5120, 16, 10240, 32, -]; +const BYTES: [usize; 15] = [40960, 16, 20480, 20480, 1280, 640, 640, 40960, 10240, 5120, 5120, 5120, 16, 10240, 32]; const RESERVE: usize = 128 * 1024 * 1024; const STAGES: [&str; 7] = [ "GR native norm", @@ -51,10 +49,10 @@ pub struct GrNativeBatch<'ctx> { #[path = "gr_native_batch/impl_context.rs"] mod impl_context; #[allow(unused_imports)] -use impl_context::encode; -#[allow(unused_imports)] use impl_context::decode; -#[path = "gr_native_batch/impl_grnativebatch.rs"] -mod impl_grnativebatch; +#[allow(unused_imports)] +use impl_context::encode; #[path = "gr_native_batch/impl_drop_for_grnativebatch.rs"] mod impl_drop_for_grnativebatch; +#[path = "gr_native_batch/impl_grnativebatch.rs"] +mod impl_grnativebatch; diff --git a/crates/cuda-driver/src/gr_native_batch/impl_context.rs b/crates/cuda-driver/src/gr_native_batch/impl_context.rs index 40904ae9..77a435c7 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_context.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_context.rs @@ -32,16 +32,8 @@ pub(super) fn encode(values: &[f32]) -> Result> { pub(super) fn decode(buffer: &DeviceBuffer<'_>) -> Result> { let bytes = buffer.copy_to_owned(buffer.len())?; let mut values = Vec::new(); - values - .try_reserve_exact(bytes.len() / 4) - .map_err(|_| Error::HostAllocation)?; - values.extend( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x)), - ); + values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); if values.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("GR native canonical")); } diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs index 85748a79..c2c00060 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2.rs @@ -3,15 +3,12 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrNativeBatch<'ctx> { pub fn prompt_device_bytes(tokens: usize) -> Result { if !(1..=8192).contains(&tokens) { return Err(Error::InvalidQwenShape); } - BYTES.iter().try_fold(0usize, |sum, n| { - sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded) - }) + BYTES.iter().try_fold(0usize, |sum, n| sum.checked_add(n * tokens).ok_or(Error::BudgetExceeded)) } pub(in super::super) fn new( context: &'ctx Context<'ctx>, @@ -41,14 +38,9 @@ impl<'ctx> GrNativeBatch<'ctx> { if context.is_poisoned() { return Err(Error::ContextPoisoned); } - let bank = BYTES.iter().try_fold(0usize, |n, x| { - n.checked_add(x * tokens).ok_or(Error::BudgetExceeded) - })?; + let bank = BYTES.iter().try_fold(0usize, |n, x| n.checked_add(x * tokens).ok_or(Error::BudgetExceeded))?; let required = bank.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -81,10 +73,7 @@ impl<'ctx> GrNativeBatch<'ctx> { if context.memory_info()?.0 < RESERVE { return Err(Error::BudgetExceeded); } - owner.buffers[0] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(encode(streams)?)?; + owner.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_owned(encode(streams)?)?; Ok(()) })(); if let Err(primary) = attempted { @@ -103,10 +92,7 @@ impl<'ctx> GrNativeBatch<'ctx> { if self.is_failed() { return Err(Error::ContextPoisoned); } - self.buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.buffers.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn handle(&self, i: usize) -> Result { let b = self.buffer(i)?; @@ -129,11 +115,7 @@ impl<'ctx> GrNativeBatch<'ctx> { let b = b.as_ref().ok_or(Error::ContextPoisoned)?; let h = self.handle(i)?; for prior in self.buffers[..i].iter().flatten() { - if h.overlaps( - b.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { + if h.overlaps(b.bytes, prior.handle.ok_or(Error::ContextPoisoned)?, prior.bytes) { return Err(Error::OutputAliasesInput); } } @@ -149,11 +131,7 @@ impl<'ctx> GrNativeBatch<'ctx> { Ok(()) } pub(in super::super) fn low(&self, slot: usize) -> Result { - if self.profile == GrNativeProfile::HighOnly { - Ok(A::NullAddress) - } else { - Ok(A::Address(self.handle(slot)?)) - } + if self.profile == GrNativeProfile::HighOnly { Ok(A::NullAddress) } else { Ok(A::Address(self.handle(slot)?)) } } pub(in super::super) fn args(values: Vec) -> KernelArguments { KernelArguments::new(values) @@ -192,27 +170,9 @@ impl<'ctx> GrNativeBatch<'ctx> { beta0: &f32, beta1: &f32, ) -> Result<()> { - blas.gemm_bf16( - self.handle(input)?, - weight, - self.handle(output)?, - self.tokens as i32, - n, - k, - alpha, - beta0, - )?; + blas.gemm_bf16(self.handle(input)?, weight, self.handle(output)?, self.tokens as i32, n, k, alpha, beta0)?; if self.profile == GrNativeProfile::HighAndLow { - blas.gemm_bf16( - self.handle(low)?, - weight, - self.handle(output)?, - self.tokens as i32, - n, - k, - alpha, - beta1, - )?; + blas.gemm_bf16(self.handle(low)?, weight, self.handle(output)?, self.tokens as i32, n, k, alpha, beta1)?; } Ok(()) } diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs index d21f6537..60ee0aca 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrNativeBatch<'ctx> { #[allow(clippy::too_many_arguments)] // One complete retained command/drain ownership set. pub(in super::super) fn finish( @@ -51,9 +50,7 @@ impl<'ctx> GrNativeBatch<'ctx> { } for row in readback.chunks_exact(32) { let flag = u32::from_le_bytes( - row[stage * 4..stage * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, + row[stage * 4..stage * 4 + 4].try_into().map_err(|_| Error::InvalidQwenShape)?, ); if flag & !1 != 0 { self.failed = true; @@ -117,17 +114,8 @@ impl<'ctx> GrNativeBatch<'ctx> { A::I64(t), ]), self.scan(4, 320, 1)?, - Self::args(vec![ - A::Address(self.handle(4)?), - A::Address(self.handle(5)?), - self.low(6)?, - A::I64(t * 320), - ]), - Self::args(vec![ - A::Address(self.handle(4)?), - A::Address(flags), - A::I64(t), - ]), + Self::args(vec![A::Address(self.handle(4)?), A::Address(self.handle(5)?), self.low(6)?, A::I64(t * 320)]), + Self::args(vec![A::Address(self.handle(4)?), A::Address(flags), A::I64(t)]), self.scan(7, 10240, 3)?, self.scan(12, 4, 6)?, Self::args(vec![ diff --git a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs index b53af944..7c3eb6a7 100644 --- a/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs +++ b/crates/cuda-driver/src/gr_native_batch/impl_grnativebatch/impl_grnativebatch_3.rs @@ -3,13 +3,8 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GrNativeBatch<'ctx> { - pub fn inject( - &mut self, - blocks: &[f32], - workspace: &mut NativeBatchWorkspace<'ctx>, - ) -> Result> { + pub fn inject(&mut self, blocks: &[f32], workspace: &mut NativeBatchWorkspace<'ctx>) -> Result> { if self.phase != 1 { return Err(Error::InvalidQwenShape); } @@ -25,10 +20,7 @@ impl<'ctx> GrNativeBatch<'ctx> { if blocks.iter().any(|x| !x.is_finite()) { return Err(Error::InvalidDriverValue("GR micro block finite")); } - self.buffers[13] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_owned(encode(blocks)?)?; + self.buffers[13].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_owned(encode(blocks)?)?; let flags = self.handle(14)?; let mut args = vec![ Self::args(vec![ diff --git a/crates/cuda-driver/src/gr_read_guard.rs b/crates/cuda-driver/src/gr_read_guard.rs index 10fb0f4a..68c257ce 100644 --- a/crates/cuda-driver/src/gr_read_guard.rs +++ b/crates/cuda-driver/src/gr_read_guard.rs @@ -34,7 +34,11 @@ impl Context<'_> { let result = (|| { status.copy_from(&[0; 4])?; handles[5] = status.handle.ok_or(Error::ContextPoisoned)?; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + ))] { let guard = self.enter()?; let kernel = match self.fixed_kernel(FixedOperation::GrReadFinite) { @@ -42,10 +46,7 @@ impl Context<'_> { Err(error) => return combine(Err(error), guard.finish()), }; let mut arguments = ffi::GrReadGuardArguments::new(handles); - let launch = self - .driver - .api - .launch_gr_read_guard(kernel.function, &mut arguments); + let launch = self.driver.api.launch_gr_read_guard(kernel.function, &mut arguments); let sync = self.driver.api.synchronize(); if sync.is_err() { self.poisoned.set(true); @@ -57,11 +58,19 @@ impl Context<'_> { } combine(combine(launch, sync), pop)?; } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + )))] { return Err(Error::UnsupportedPlatform); } - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + ))] { let mut bytes = [0; 4]; status.copy_to(&mut bytes)?; @@ -93,36 +102,23 @@ mod tests { } } -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64", - feature = "cuda-driver" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] mod installed_tests { use super::*; #[test] #[ignore = "root-only new installed-driver finite witness gate"] fn installed_gr_read_guard_matches_all_stage_bits_and_first_nonfinite() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GR_DEVICE_GUARD").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GR_DEVICE_GUARD").as_deref(), Ok("yes")); let driver = Driver::load().expect("installed driver"); let device = driver.device(0).unwrap(); let context = device.create_context(2 * 1024 * 1024).unwrap(); - let mut buffers: Vec<_> = BYTES - .into_iter() - .map(|b| context.allocate(b).unwrap()) - .collect(); + let mut buffers: Vec<_> = BYTES.into_iter().map(|b| context.allocate(b).unwrap()).collect(); let mut cases = 0; for expected in 0u32..32 { for (stage, buffer) in buffers.iter_mut().enumerate() { let mut values = vec![0u8; BYTES[stage]]; for (index, word) in values.chunks_exact_mut(4).enumerate() { - word.copy_from_slice( - &(if index % 2 == 0 { 0.0f32 } else { -0.0f32 }).to_le_bytes(), - ); + word.copy_from_slice(&(if index % 2 == 0 { 0.0f32 } else { -0.0f32 }).to_le_bytes()); } if expected & (1 << stage) != 0 { let offset = values.len() - 4; @@ -131,13 +127,8 @@ mod installed_tests { buffer.copy_from(&values).unwrap(); } let refs: Vec<_> = buffers.iter().collect(); - let actual = context - .gr_read_finite_mask( - refs.try_into() - .ok() - .expect("exactly five actual stage buffers"), - ) - .unwrap(); + let actual = + context.gr_read_finite_mask(refs.try_into().ok().expect("exactly five actual stage buffers")).unwrap(); assert_eq!(actual, expected); if actual != 0 { assert_eq!(actual.trailing_zeros(), expected.trailing_zeros()); @@ -153,13 +144,7 @@ mod installed_tests { } let refs: Vec<_> = buffers.iter().collect(); assert_eq!( - context - .gr_read_finite_mask( - refs.try_into() - .ok() - .expect("exactly five actual stage buffers") - ) - .unwrap(), + context.gr_read_finite_mask(refs.try_into().ok().expect("exactly five actual stage buffers")).unwrap(), 31 ); cases += 1; diff --git a/crates/cuda-driver/src/grouped_down_columns_gpu.rs b/crates/cuda-driver/src/grouped_down_columns_gpu.rs index e2b54ab9..a73f5983 100644 --- a/crates/cuda-driver/src/grouped_down_columns_gpu.rs +++ b/crates/cuda-driver/src/grouped_down_columns_gpu.rs @@ -2,10 +2,7 @@ use super::*; fn bytes(values: &[f32]) -> Vec { - values - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect() + values.iter().flat_map(|value| value.to_le_bytes()).collect() } fn weights(format: RoutedFormat) -> Vec { @@ -35,24 +32,13 @@ fn corpus(total: usize, zero: bool) -> (Vec, Vec) { for row in 0..640 { let (g, u) = if zero { ( - f32::from_bits(if (column + row).is_multiple_of(2) { - 0 - } else { - 0x80000000 - }), - f32::from_bits(if (column + 2 * row).is_multiple_of(2) { - 0x80000000 - } else { - 0 - }), + f32::from_bits(if (column + row).is_multiple_of(2) { 0 } else { 0x80000000 }), + f32::from_bits(if (column + 2 * row).is_multiple_of(2) { 0x80000000 } else { 0 }), ) } else if row == 0 { (-100.0, 1.0) // Valid finite sigmoid saturation, not malformed input. } else { - ( - ((row * 7 + column * 11) % 31) as f32 / 8.0 - 2.0, - ((row * 13 + column * 3) % 29) as f32 / 16.0 - 0.75, - ) + (((row * 7 + column * 11) % 31) as f32 / 8.0 - 2.0, ((row * 13 + column * 3) % 29) as f32 / 16.0 - 0.75) }; gate.push(g); up.push(u); @@ -81,9 +67,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { for (g, u) in gate_bytes.chunks(2560).zip(up_bytes.chunks(2560)) { scalar_gate.copy_from(g).unwrap(); scalar_up.copy_from(u).unwrap(); - context - .moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden) - .unwrap(); + context.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden).unwrap(); let mut observed = vec![0; 2560]; scalar_hidden.copy_to(&mut observed).unwrap(); expected_hidden.extend_from_slice(&observed); @@ -94,11 +78,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let mut references = Vec::new(); for format in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] { let literal = weights(format); - let spec = ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - }; + let spec = ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 }; let shape = projection_shape(spec).unwrap(); assert_eq!(shape.weight_bytes, literal.len()); assert_eq!(shape.scratch_bytes, 720); @@ -107,9 +87,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let mut expected = Vec::with_capacity(total * 10240); for h in expected_hidden.chunks(2560) { scalar_hidden.copy_from(h).unwrap(); - context - .project_q8_1(&matrix, &scalar_hidden, &mut scalar_output, spec) - .unwrap(); + context.project_q8_1(&matrix, &scalar_hidden, &mut scalar_output, spec).unwrap(); let mut observed = vec![0; 10240]; scalar_output.copy_to(&mut observed).unwrap(); expected.extend_from_slice(&observed); @@ -124,9 +102,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let mut hidden = context.allocate(gate_bytes.len()).unwrap(); gate.copy_from(&gate_bytes).unwrap(); up.copy_from(&up_bytes).unwrap(); - context - .moe_swiglu_columns(&gate, &up, &mut hidden, total) - .unwrap(); + context.moe_swiglu_columns(&gate, &up, &mut hidden, total).unwrap(); let mut observed_hidden = vec![0; gate_bytes.len()]; hidden.copy_to(&mut observed_hidden).unwrap(); let mut gate_after = vec![0; gate_bytes.len()]; @@ -143,16 +119,12 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let mut column = context.allocate(10240).unwrap(); matrix.copy_from(&literal).unwrap(); let charge = context.allocated_bytes(); - context - .project_routed_down_columns(&matrix, &hidden, &mut output, total, format) - .unwrap(); + context.project_routed_down_columns(&matrix, &hidden, &mut output, total, format).unwrap(); assert_eq!(context.allocated_bytes(), charge); let mut observed = vec![0; total * 10240]; output.copy_to(&mut observed).unwrap(); for index in [0, total / 2, total - 1] { - context - .copy_routed_down_column(&output, total, index, &mut column) - .unwrap(); + context.copy_routed_down_column(&output, total, index, &mut column).unwrap(); let mut copied = vec![0; 10240]; column.copy_to(&mut copied).unwrap(); assert_eq!(copied, observed[index * 10240..(index + 1) * 10240]); @@ -190,18 +162,9 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { output.copy_from(&sentinel).unwrap(); let charge = context.allocated_bytes(); for total in [0, 65] { + assert_eq!(context.moe_swiglu_columns(&input, &up, &mut hidden, total), Err(Error::InvalidProjectionShape)); assert_eq!( - context.moe_swiglu_columns(&input, &up, &mut hidden, total), - Err(Error::InvalidProjectionShape) - ); - assert_eq!( - context.project_routed_down_columns( - &matrix, - &input, - &mut output, - total, - RoutedFormat::IQ4_NL - ), + context.project_routed_down_columns(&matrix, &input, &mut output, total, RoutedFormat::IQ4_NL), Err(Error::InvalidProjectionShape) ); } @@ -209,10 +172,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { context.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ3_S), Err(Error::UnsupportedProjection) ); - assert_eq!( - context.copy_routed_down_column(&output, 1, 1, &mut column), - Err(Error::InvalidProjectionShape) - ); + assert_eq!(context.copy_routed_down_column(&output, 1, 1, &mut column), Err(Error::InvalidProjectionShape)); let short = context.allocate(2556).unwrap(); assert_eq!( context.project_routed_down_columns(&matrix, &short, &mut output, 1, RoutedFormat::IQ4_NL), @@ -222,13 +182,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let foreign = device.create_context(4096).unwrap(); let foreign_input = foreign.allocate(2560).unwrap(); assert_eq!( - context.project_routed_down_columns( - &matrix, - &foreign_input, - &mut output, - 1, - RoutedFormat::IQ4_NL - ), + context.project_routed_down_columns(&matrix, &foreign_input, &mut output, 1, RoutedFormat::IQ4_NL), Err(Error::ContextMismatch) ); foreign_input.release().unwrap(); @@ -239,13 +193,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { malformed[2556..].copy_from_slice(&bad.to_le_bytes()); input.copy_from(&malformed).unwrap(); assert_eq!( - context.project_routed_down_columns( - &matrix, - &input, - &mut output, - 1, - RoutedFormat::IQ4_NL - ), + context.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL), Err(Error::InvalidQ8Activation) ); assert_eq!(context.allocated_bytes(), charge); @@ -257,15 +205,11 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { output.copy_to(&mut after).unwrap(); assert_eq!(after, sentinel); input.copy_from(&valid).unwrap(); - context - .project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL) - .unwrap(); + context.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL).unwrap(); let mut malformed_gate = valid.clone(); malformed_gate[2556..].copy_from_slice(&0x7fc00001_u32.to_le_bytes()); input.copy_from(&malformed_gate).unwrap(); - context - .moe_swiglu_columns(&input, &up, &mut hidden, 1) - .unwrap(); + context.moe_swiglu_columns(&input, &up, &mut hidden, 1).unwrap(); let mut malformed_hidden = vec![0; 2560]; hidden.copy_to(&mut malformed_hidden).unwrap(); assert!(!f32::from_le_bytes(malformed_hidden[2556..].try_into().unwrap()).is_finite()); @@ -274,9 +218,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { malformed_weights[2559 * 360..2559 * 360 + 2].copy_from_slice(&0x7e00_u16.to_le_bytes()); matrix.copy_from(&malformed_weights).unwrap(); input.copy_from(&valid).unwrap(); - context - .project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL) - .unwrap(); + context.project_routed_down_columns(&matrix, &input, &mut output, 1, RoutedFormat::IQ4_NL).unwrap(); let mut malformed_down = vec![0; 10240]; output.copy_to(&mut malformed_down).unwrap(); assert!(!f32::from_le_bytes(malformed_down[10236..].try_into().unwrap()).is_finite()); @@ -297,10 +239,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { h.copy_from(&valid).unwrap(); o.copy_from(&sentinel).unwrap(); let charge = small.allocated_bytes(); - assert_eq!( - small.project_routed_down_columns(&w, &h, &mut o, 1, RoutedFormat::IQ4_NL), - Err(Error::BudgetExceeded) - ); + assert_eq!(small.project_routed_down_columns(&w, &h, &mut o, 1, RoutedFormat::IQ4_NL), Err(Error::BudgetExceeded)); assert_eq!(small.allocated_bytes(), charge); o.copy_to(&mut after).unwrap(); assert_eq!(after, sentinel); @@ -315,13 +254,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { let mut hidden_words = 0; for (total, zero, wanted, got) in hidden_pairs { - for (index, (a, b)) in wanted - .as_chunks::<4>() - .0 - .iter() - .zip(got.as_chunks::<4>().0) - .enumerate() - { + for (index, (a, b)) in wanted.as_chunks::<4>().0.iter().zip(got.as_chunks::<4>().0).enumerate() { assert_eq!(a, b, "hidden T={total} zero={zero} word={index}"); assert!(f32::from_le_bytes(*b).is_finite()); hidden_words += 1; @@ -329,13 +262,7 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { } let mut down_words = 0; for (total, zero, format, wanted, got) in down_pairs { - for (index, (a, b)) in wanted - .as_chunks::<4>() - .0 - .iter() - .zip(got.as_chunks::<4>().0) - .enumerate() - { + for (index, (a, b)) in wanted.as_chunks::<4>().0.iter().zip(got.as_chunks::<4>().0).enumerate() { assert_eq!(a, b, "Down {format:?} T={total} zero={zero} word={index}"); assert!(f32::from_le_bytes(*b).is_finite()); down_words += 1; @@ -343,7 +270,5 @@ fn scalar_first_grouped_swiglu_down_columns_exact_and_closed_guards() { } assert_eq!(hidden_words, 107520); assert_eq!(down_words, 860160); - println!( - "STRA169_GROUPED_DOWN_PROOF hidden_words={hidden_words} down_words={down_words} exact=true allocated=0" - ); + println!("STRA169_GROUPED_DOWN_PROOF hidden_words={hidden_words} down_words={down_words} exact=true allocated=0"); } diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs b/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs index 5eaad1f9..ed602588 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_gpu.rs @@ -30,11 +30,7 @@ fn gu_weights(format: RoutedFormat, salt: usize) -> Vec { raw } fn down_weights(format: RoutedFormat) -> Vec { - let blocks = if format == RoutedFormat::IQ4_NL { - 20 - } else { - 10 - }; + let blocks = if format == RoutedFormat::IQ4_NL { 20 } else { 10 }; let mut bytes = Vec::with_capacity(2560 * blocks * 18); for row in 0..2560 { for block in 0..blocks { @@ -50,11 +46,7 @@ fn input(column: usize, zero: bool) -> Vec { (0usize..2560) .flat_map(|index| { let value = if zero { - f32::from_bits(if (index + column).is_multiple_of(2) { - 0x80000000 - } else { - 0 - }) + f32::from_bits(if (index + column).is_multiple_of(2) { 0x80000000 } else { 0 }) } else { ((index * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 + column as f32 / 256.0 }; @@ -73,23 +65,14 @@ fn numeric(context: &Context<'_>, checks: &mut Vec) -> Result<()> { let up_bytes = gu_weights(format, 79); let gate_weights = upload(context, &gate_bytes)?; let up_weights = upload(context, &up_bytes)?; - let down_raw = [ - down_weights(RoutedFormat::IQ4_NL), - down_weights(RoutedFormat::Q2_0), - ]; - let down_weights = [ - upload(context, &down_raw[0])?, - upload(context, &down_raw[1])?, - ]; + let down_raw = [down_weights(RoutedFormat::IQ4_NL), down_weights(RoutedFormat::Q2_0)]; + let down_weights = [upload(context, &down_raw[0])?, upload(context, &down_raw[1])?]; for total in [1usize, 2, 3, 4, 63, 64] { for zero in [false, true] { - let inputs: Vec<_> = (0..total) - .map(|column| upload(context, &input(column, zero))) - .collect::>()?; - let prepared: Vec<_> = inputs - .iter() - .map(|input| context.prepare_routed_gate_up_q8(input)) - .collect::>()?; + let inputs: Vec<_> = + (0..total).map(|column| upload(context, &input(column, zero))).collect::>()?; + let prepared: Vec<_> = + inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>()?; let refs: Vec<_> = prepared.iter().collect(); let mut scalar_gate = context.allocate(2560)?; let mut scalar_up = context.allocate(2560)?; @@ -98,35 +81,18 @@ fn numeric(context: &Context<'_>, checks: &mut Vec) -> Result<()> { let mut expected: [Vec; 5] = std::array::from_fn(|_| Vec::new()); // ALL original scalar operations for this complete corpus FIRST. for owner in &prepared { - context.project_routed_gate_up_prepared( - &gate_weights, - owner, - &mut scalar_gate, - format, - )?; - context.project_routed_gate_up_prepared( - &up_weights, - owner, - &mut scalar_up, - format, - )?; + context.project_routed_gate_up_prepared(&gate_weights, owner, &mut scalar_gate, format)?; + context.project_routed_gate_up_prepared(&up_weights, owner, &mut scalar_up, format)?; expected[0].extend_from_slice(&read(&scalar_gate)?); expected[1].extend_from_slice(&read(&scalar_up)?); context.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden)?; expected[2].extend_from_slice(&read(&scalar_hidden)?); - for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] - .into_iter() - .enumerate() - { + for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0].into_iter().enumerate() { context.project_q8_1( &down_weights[index], &scalar_hidden, &mut scalar_down, - ProjectionSpec { - kind: ProjectionKind::Routed(down_format), - rows: 2560, - columns: 640, - }, + ProjectionSpec { kind: ProjectionKind::Routed(down_format), rows: 2560, columns: 640 }, )?; expected[index + 3].extend_from_slice(&read(&scalar_down)?); } @@ -147,10 +113,7 @@ fn numeric(context: &Context<'_>, checks: &mut Vec) -> Result<()> { actual[1] = read(&up)?; context.moe_swiglu_columns(&gate, &up, &mut hidden, total)?; actual[2] = read(&hidden)?; - for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] - .into_iter() - .enumerate() - { + for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0].into_iter().enumerate() { context.project_routed_down_columns( &down_weights[index], &hidden, @@ -206,17 +169,9 @@ fn numeric(context: &Context<'_>, checks: &mut Vec) -> Result<()> { expected: gate_bytes, actual: read(&gate_weights)?, }); - checks.push(Comparison { - name: "Up weights unchanged".into(), - expected: up_bytes, - actual: read(&up_weights)?, - }); + checks.push(Comparison { name: "Up weights unchanged".into(), expected: up_bytes, actual: read(&up_weights)? }); for (matrix, raw) in down_weights.into_iter().zip(down_raw) { - checks.push(Comparison { - name: "Down weights unchanged".into(), - expected: raw, - actual: read(&matrix)?, - }); + checks.push(Comparison { name: "Down weights unchanged".into(), expected: raw, actual: read(&matrix)? }); matrix.release()?; } up_weights.release()?; @@ -246,12 +201,8 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> == Err(Error::InvalidProjectionShape), ); checks.push( - context.project_routed_gate_up_columns( - &weights, - &[&owner], - &mut output, - RoutedFormat::IQ4_NL, - ) == Err(Error::UnsupportedProjection), + context.project_routed_gate_up_columns(&weights, &[&owner], &mut output, RoutedFormat::IQ4_NL) + == Err(Error::UnsupportedProjection), ); let mut short = context.allocate(2556)?; checks.push( @@ -261,23 +212,15 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> short.release()?; let short_weight = context.allocate(raw.len() - 2)?; checks.push( - context.project_routed_gate_up_columns( - &short_weight, - &[&owner], - &mut output, - format, - ) == Err(Error::InvalidProjectionShape), + context.project_routed_gate_up_columns(&short_weight, &[&owner], &mut output, format) + == Err(Error::InvalidProjectionShape), ); short_weight.release()?; let foreign = device.create_context(raw.len() + 4096)?; let foreign_weight = upload(&foreign, &raw)?; checks.push( - context.project_routed_gate_up_columns( - &foreign_weight, - &[&owner], - &mut output, - format, - ) == Err(Error::ContextMismatch), + context.project_routed_gate_up_columns(&foreign_weight, &[&owner], &mut output, format) + == Err(Error::ContextMismatch), ); foreign_weight.release()?; checks.push(foreign.allocated_bytes() == 0); @@ -287,11 +230,7 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> // A real whole weight allocation with a late NaN/Inf header: the // unchanged arithmetic returns data; the original finite consumer // refuses it. No typed finite product is manufactured here. - let block_bytes = if format == RoutedFormat::IQ3_S { - 110 - } else { - 136 - }; + let block_bytes = if format == RoutedFormat::IQ3_S { 110 } else { 136 }; for bits in [0x7e01u16, 0x7c00, 0xfc00] { let mut malformed = raw.clone(); let last = (640 * 10 - 1) * block_bytes; @@ -302,16 +241,11 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> context.project_routed_gate_up_columns(&weights, &[&owner], &mut output, format)?; let actual = read(&output)?; checks.push( - expected + expected.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x).is_finite()).eq(actual .as_chunks::<4>() .0 .iter() - .map(|x| f32::from_le_bytes(*x).is_finite()) - .eq(actual - .as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x).is_finite())), + .map(|x| f32::from_le_bytes(*x).is_finite())), ); checks.push(!f32::from_le_bytes(actual[2556..].try_into().unwrap()).is_finite()); } @@ -325,10 +259,7 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> let mut bad = valid.clone(); bad[10236..].copy_from_slice(&bits.to_le_bytes()); activation.copy_from(&bad)?; - checks.push(matches!( - context.prepare_routed_gate_up_q8(&activation), - Err(Error::InvalidQ8Activation) - )); + checks.push(matches!(context.prepare_routed_gate_up_q8(&activation), Err(Error::InvalidQ8Activation))); activation.copy_from(&valid)?; context.prepare_routed_gate_up_q8(&activation)?.close()?; } @@ -344,10 +275,8 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> let mut out = upload(&small, &[0xa5; 2560])?; let owner = small.prepare_routed_gate_up_q8(&input)?; let charge = small.allocated_bytes(); - checks.push( - small.project_routed_gate_up_columns(&w, &[&owner], &mut out, format) - == Err(Error::BudgetExceeded), - ); + checks + .push(small.project_routed_gate_up_columns(&w, &[&owner], &mut out, format) == Err(Error::BudgetExceeded)); checks.push(read(&out)? == vec![0xa5; 2560] && small.allocated_bytes() == charge); owner.close()?; out.release()?; @@ -362,16 +291,13 @@ fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> #[test] #[ignore = "root-only new native GU21/23 column adapters, no model or speed proof"] fn original_first_gu21_gu23_full_products_refusals_reset_and_cleanup() { - assert!( - std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23").is_ok_and(|value| value == "yes") - ); + assert!(std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23").is_ok_and(|value| value == "yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(32 * 1024 * 1024).unwrap(); let mut products = Vec::new(); let mut refusals = Vec::new(); - let work = - numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals)); + let work = numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals)); let allocated = context.allocated_bytes(); let closed = context.close(); assert_eq!(work, Ok(())); diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs index 50197a8b..0be107b9 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu.rs @@ -11,16 +11,13 @@ struct Comparison { #[test] #[ignore = "root-only NC4 GU21/23 source successor, no model or speed proof"] fn original_first_gu21_gu23_nc4_full_products_tails_refusals_reset_and_cleanup() { - assert!( - std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23_NC4").is_ok_and(|value| value == "yes") - ); + assert!(std::env::var("LELEKA_STRA172_RUN_GROUPED_GU21_GU23_NC4").is_ok_and(|value| value == "yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(32 * 1024 * 1024).unwrap(); let mut products = Vec::new(); let mut refusals = Vec::new(); - let work = - numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals)); + let work = numeric(&context, &mut products).and_then(|()| guards(&context, &device, &mut refusals)); let allocated = context.allocated_bytes(); let closed = context.close(); assert_eq!(work, Ok(())); @@ -50,17 +47,17 @@ fn original_first_gu21_gu23_nc4_full_products_tails_refusals_reset_and_cleanup() #[path = "grouped_gu21_gu23_nc4_gpu/upload_fn.rs"] mod upload_fn; #[allow(unused_imports)] -use upload_fn::upload; -#[allow(unused_imports)] -use upload_fn::read; +use upload_fn::down_weights; #[allow(unused_imports)] use upload_fn::gu_weights; #[allow(unused_imports)] -use upload_fn::down_weights; -#[allow(unused_imports)] use upload_fn::input; #[allow(unused_imports)] use upload_fn::numeric; +#[allow(unused_imports)] +use upload_fn::read; +#[allow(unused_imports)] +use upload_fn::upload; #[path = "grouped_gu21_gu23_nc4_gpu/guards_fn.rs"] mod guards_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/guards_fn.rs b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/guards_fn.rs index 96266ec6..68c0c551 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/guards_fn.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/guards_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Vec) -> Result<()> { for format in [RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] { let raw = gu_weights(format, 11); @@ -25,12 +24,8 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve == Err(Error::InvalidProjectionShape), ); checks.push( - context.project_routed_gate_up_columns( - &weights, - &[&owner], - &mut output, - RoutedFormat::IQ4_NL, - ) == Err(Error::UnsupportedProjection), + context.project_routed_gate_up_columns(&weights, &[&owner], &mut output, RoutedFormat::IQ4_NL) + == Err(Error::UnsupportedProjection), ); let mut short = context.allocate(2556)?; checks.push( @@ -40,23 +35,15 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve short.release()?; let short_weight = context.allocate(raw.len() - 2)?; checks.push( - context.project_routed_gate_up_columns( - &short_weight, - &[&owner], - &mut output, - format, - ) == Err(Error::InvalidProjectionShape), + context.project_routed_gate_up_columns(&short_weight, &[&owner], &mut output, format) + == Err(Error::InvalidProjectionShape), ); short_weight.release()?; let foreign = device.create_context(raw.len() + 4096)?; let foreign_weight = upload(&foreign, &raw)?; checks.push( - context.project_routed_gate_up_columns( - &foreign_weight, - &[&owner], - &mut output, - format, - ) == Err(Error::ContextMismatch), + context.project_routed_gate_up_columns(&foreign_weight, &[&owner], &mut output, format) + == Err(Error::ContextMismatch), ); foreign_weight.release()?; checks.push(foreign.allocated_bytes() == 0); @@ -65,23 +52,16 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve checks.push(context.allocated_bytes() == charge); // Genuine T5 exercises the four-column tile plus its live tail. // Every original scalar column completes FIRST for each fault/reset. - let extra_inputs: Vec<_> = (2..6) - .map(|column| upload(context, &input(column, false))) - .collect::>()?; - let extra_prepared: Vec<_> = extra_inputs - .iter() - .map(|input| context.prepare_routed_gate_up_q8(input)) - .collect::>()?; + let extra_inputs: Vec<_> = + (2..6).map(|column| upload(context, &input(column, false))).collect::>()?; + let extra_prepared: Vec<_> = + extra_inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>()?; let mut refs = vec![&owner]; refs.extend(extra_prepared.iter()); let mut multi_output = upload(context, &[0xa5; 5 * 2560])?; // Raw numerical outputs are inspected by the same full finite // consumer; no usable finite product is manufactured after failure. - let block_bytes = if format == RoutedFormat::IQ3_S { - 110 - } else { - 136 - }; + let block_bytes = if format == RoutedFormat::IQ3_S { 110 } else { 136 }; for bits in [0x7e01u16, 0x7c00, 0xfc00] { let mut malformed = raw.clone(); let last = (640 * 10 - 1) * block_bytes; @@ -89,36 +69,23 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve weights.copy_from(&malformed)?; let mut expected = Vec::new(); for column in &refs { - context.project_routed_gate_up_prepared( - &weights, - column, - &mut scalar, - format, - )?; + context.project_routed_gate_up_prepared(&weights, column, &mut scalar, format)?; expected.extend_from_slice(&read(&scalar)?); } - context.project_routed_gate_up_columns( - &weights, - &refs, - &mut multi_output, - format, - )?; + context.project_routed_gate_up_columns(&weights, &refs, &mut multi_output, format)?; let actual = read(&multi_output)?; checks.push( - expected + expected.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x).is_finite()).eq(actual .as_chunks::<4>() .0 .iter() - .map(|x| f32::from_le_bytes(*x).is_finite()) - .eq(actual - .as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x).is_finite())), + .map(|x| f32::from_le_bytes(*x).is_finite())), + ); + checks.push( + actual + .chunks_exact(2560) + .all(|column| !f32::from_le_bytes(column[2556..].try_into().unwrap()).is_finite()), ); - checks.push(actual.chunks_exact(2560).all(|column| { - !f32::from_le_bytes(column[2556..].try_into().unwrap()).is_finite() - })); } weights.copy_from(&raw)?; let mut expected = Vec::new(); @@ -143,10 +110,7 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve let mut bad = valid.clone(); bad[10236..].copy_from_slice(&bits.to_le_bytes()); activation.copy_from(&bad)?; - checks.push(matches!( - context.prepare_routed_gate_up_q8(&activation), - Err(Error::InvalidQ8Activation) - )); + checks.push(matches!(context.prepare_routed_gate_up_q8(&activation), Err(Error::InvalidQ8Activation))); activation.copy_from(&valid)?; context.prepare_routed_gate_up_q8(&activation)?.close()?; } @@ -158,20 +122,13 @@ pub(super) fn guards(context: &Context<'_>, device: &Device<'_>, checks: &mut Ve // Five genuine distinct Context/Q8 input owners, not repeated pointers. let small = device.create_context(raw.len() + 5 * (10240 + 2880) + 5 * 2560 + 39)?; let w = upload(&small, &raw)?; - let inputs: Vec<_> = (0..5) - .map(|column| upload(&small, &input(column, false))) - .collect::>()?; + let inputs: Vec<_> = (0..5).map(|column| upload(&small, &input(column, false))).collect::>()?; let mut out = upload(&small, &[0xa5; 5 * 2560])?; - let owners: Vec<_> = inputs - .iter() - .map(|input| small.prepare_routed_gate_up_q8(input)) - .collect::>()?; + let owners: Vec<_> = + inputs.iter().map(|input| small.prepare_routed_gate_up_q8(input)).collect::>()?; let refs: Vec<_> = owners.iter().collect(); let charge = small.allocated_bytes(); - checks.push( - small.project_routed_gate_up_columns(&w, &refs, &mut out, format) - == Err(Error::BudgetExceeded), - ); + checks.push(small.project_routed_gate_up_columns(&w, &refs, &mut out, format) == Err(Error::BudgetExceeded)); checks.push(read(&out)? == vec![0xa5; 5 * 2560] && small.allocated_bytes() == charge); drop(refs); for owner in owners { diff --git a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs index a0e3846f..fde8e00d 100644 --- a/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs +++ b/crates/cuda-driver/src/grouped_gu21_gu23_nc4_gpu/upload_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result> { let mut buffer = context.allocate(bytes.len())?; buffer.copy_from(bytes)?; @@ -32,11 +31,7 @@ pub(super) fn gu_weights(format: RoutedFormat, salt: usize) -> Vec { raw } pub(super) fn down_weights(format: RoutedFormat) -> Vec { - let blocks = if format == RoutedFormat::IQ4_NL { - 20 - } else { - 10 - }; + let blocks = if format == RoutedFormat::IQ4_NL { 20 } else { 10 }; let mut bytes = Vec::with_capacity(2560 * blocks * 18); for row in 0..2560 { for block in 0..blocks { @@ -52,11 +47,7 @@ pub(super) fn input(column: usize, zero: bool) -> Vec { (0usize..2560) .flat_map(|index| { let value = if zero { - f32::from_bits(if (index + column).is_multiple_of(2) { - 0x80000000 - } else { - 0 - }) + f32::from_bits(if (index + column).is_multiple_of(2) { 0x80000000 } else { 0 }) } else { ((index * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 + column as f32 / 256.0 }; @@ -70,23 +61,14 @@ pub(super) fn numeric(context: &Context<'_>, checks: &mut Vec) -> Re let up_bytes = gu_weights(format, 79); let gate_weights = upload(context, &gate_bytes)?; let up_weights = upload(context, &up_bytes)?; - let down_raw = [ - down_weights(RoutedFormat::IQ4_NL), - down_weights(RoutedFormat::Q2_0), - ]; - let down_weights = [ - upload(context, &down_raw[0])?, - upload(context, &down_raw[1])?, - ]; + let down_raw = [down_weights(RoutedFormat::IQ4_NL), down_weights(RoutedFormat::Q2_0)]; + let down_weights = [upload(context, &down_raw[0])?, upload(context, &down_raw[1])?]; for total in [1usize, 2, 3, 4, 5, 63, 64] { for zero in [false, true] { - let inputs: Vec<_> = (0..total) - .map(|column| upload(context, &input(column, zero))) - .collect::>()?; - let prepared: Vec<_> = inputs - .iter() - .map(|input| context.prepare_routed_gate_up_q8(input)) - .collect::>()?; + let inputs: Vec<_> = + (0..total).map(|column| upload(context, &input(column, zero))).collect::>()?; + let prepared: Vec<_> = + inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>()?; let refs: Vec<_> = prepared.iter().collect(); let mut scalar_gate = context.allocate(2560)?; let mut scalar_up = context.allocate(2560)?; @@ -95,35 +77,18 @@ pub(super) fn numeric(context: &Context<'_>, checks: &mut Vec) -> Re let mut expected: [Vec; 5] = std::array::from_fn(|_| Vec::new()); // ALL original scalar operations for this complete corpus FIRST. for owner in &prepared { - context.project_routed_gate_up_prepared( - &gate_weights, - owner, - &mut scalar_gate, - format, - )?; - context.project_routed_gate_up_prepared( - &up_weights, - owner, - &mut scalar_up, - format, - )?; + context.project_routed_gate_up_prepared(&gate_weights, owner, &mut scalar_gate, format)?; + context.project_routed_gate_up_prepared(&up_weights, owner, &mut scalar_up, format)?; expected[0].extend_from_slice(&read(&scalar_gate)?); expected[1].extend_from_slice(&read(&scalar_up)?); context.moe_swiglu_f32(&scalar_gate, &scalar_up, &mut scalar_hidden)?; expected[2].extend_from_slice(&read(&scalar_hidden)?); - for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] - .into_iter() - .enumerate() - { + for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0].into_iter().enumerate() { context.project_q8_1( &down_weights[index], &scalar_hidden, &mut scalar_down, - ProjectionSpec { - kind: ProjectionKind::Routed(down_format), - rows: 2560, - columns: 640, - }, + ProjectionSpec { kind: ProjectionKind::Routed(down_format), rows: 2560, columns: 640 }, )?; expected[index + 3].extend_from_slice(&read(&scalar_down)?); } @@ -144,10 +109,7 @@ pub(super) fn numeric(context: &Context<'_>, checks: &mut Vec) -> Re actual[1] = read(&up)?; context.moe_swiglu_columns(&gate, &up, &mut hidden, total)?; actual[2] = read(&hidden)?; - for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] - .into_iter() - .enumerate() - { + for (index, down_format) in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0].into_iter().enumerate() { context.project_routed_down_columns( &down_weights[index], &hidden, @@ -203,17 +165,9 @@ pub(super) fn numeric(context: &Context<'_>, checks: &mut Vec) -> Re expected: gate_bytes, actual: read(&gate_weights)?, }); - checks.push(Comparison { - name: "Up weights unchanged".into(), - expected: up_bytes, - actual: read(&up_weights)?, - }); + checks.push(Comparison { name: "Up weights unchanged".into(), expected: up_bytes, actual: read(&up_weights)? }); for (matrix, raw) in down_weights.into_iter().zip(down_raw) { - checks.push(Comparison { - name: "Down weights unchanged".into(), - expected: raw, - actual: read(&matrix)?, - }); + checks.push(Comparison { name: "Down weights unchanged".into(), expected: raw, actual: read(&matrix)? }); matrix.release()?; } up_weights.release()?; diff --git a/crates/cuda-driver/src/head_greedy.rs b/crates/cuda-driver/src/head_greedy.rs index 81e49727..0f5d5232 100644 --- a/crates/cuda-driver/src/head_greedy.rs +++ b/crates/cuda-driver/src/head_greedy.rs @@ -53,20 +53,11 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(HEAD_GREEDY_WORKSPACE_BYTES) - .is_none_or(|bytes| bytes > context.budget) + if context.allocated_bytes().checked_add(HEAD_GREEDY_WORKSPACE_BYTES).is_none_or(|bytes| bytes > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - buffers: [None, None], - module: None, - functions: None, - failed: false, - }; + let mut owner = Self { context, buffers: [None, None], module: None, functions: None, failed: false }; let operation = (|| { owner.buffers[0] = Some(context.allocate(GROUP_BYTES)?); owner.buffers[1] = Some(context.allocate(RESULT_BYTES)?); @@ -92,11 +83,7 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { Ok(owner) } pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .map(|buffer| buffer.bytes) - .sum() + self.buffers.iter().flatten().map(|buffer| buffer.bytes).sum() } /// `None` means a completed whole-vocabulary NaN/Inf refusal. No partial /// winner escapes. Every group and result is overwritten, including flags. @@ -118,9 +105,7 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { source_handle.validate_projection_extent(SOURCE_BYTES, 4)?; let groups = self.buffers[0].as_ref().ok_or(Error::ContextPoisoned)?; let result = self.buffers[1].as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(self.context, groups.context) - || !std::ptr::eq(self.context, result.context) - { + if !std::ptr::eq(self.context, groups.context) || !std::ptr::eq(self.context, result.context) { return Err(Error::ContextMismatch); } if groups.bytes != GROUP_BYTES || result.bytes != RESULT_BYTES { @@ -140,22 +125,12 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { let mut first = ffi::HeadGreedyArguments::new(source_handle, group_handle); let mut second = ffi::HeadGreedyArguments::new(group_handle, result_handle); let mut staging = Vec::new(); - staging - .try_reserve_exact(RESULT_BYTES) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(RESULT_BYTES).map_err(|_| Error::HostAllocation)?; staging.resize(RESULT_BYTES, 0); let guard = self.context.enter()?; - let mut operation = - self.context - .driver - .api - .launch_head_greedy(functions[0], false, &mut first); + let mut operation = self.context.driver.api.launch_head_greedy(functions[0], false, &mut first); if operation.is_ok() { - operation = self - .context - .driver - .api - .launch_head_greedy(functions[1], true, &mut second); + operation = self.context.driver.api.launch_head_greedy(functions[1], true, &mut second); } if operation.is_ok() { operation = self.context.driver.api.copy_to(result_handle, &mut staging); @@ -180,13 +155,8 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { let packed = u64::from_le_bytes(staging[..8].try_into().expect("fixed result")); let index = !(packed as u32); let key = (packed >> 32) as u32; - let bits = if key & 0x8000_0000 != 0 { - key ^ 0x8000_0000 - } else { - !key - }; - if index >= WORDS as u32 || bits & 0x7f80_0000 == 0x7f80_0000 || bits == 0x8000_0000 - { + let bits = if key & 0x8000_0000 != 0 { key ^ 0x8000_0000 } else { !key }; + if index >= WORDS as u32 || bits & 0x7f80_0000 == 0x7f80_0000 || bits == 0x8000_0000 { self.failed = true; return Err(Error::InvalidDriverValue("fixed head greedy witness")); } @@ -219,13 +189,10 @@ impl<'ctx> HeadGreedyWorkspace<'ctx> { } result = combine(result, release); } - let module = self - .module - .take() - .map_or(Ok(()), |module| match self.context.enter() { - Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), - Err(error) => Err(error), - }); + let module = self.module.take().map_or(Ok(()), |module| match self.context.enter() { + Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), + Err(error) => Err(error), + }); if module.is_err() { self.context.poisoned.set(true); std::mem::forget(Rc::clone(&self.context.driver.api)); @@ -244,6 +211,6 @@ impl Drop for HeadGreedyWorkspace<'_> { mod gpu; const ASSET_SHA: [u8; 32] = [ - 0x78, 0x9f, 0xb7, 0xfc, 0xd5, 0x56, 0x4d, 0xea, 0xac, 0x9e, 0xbd, 0x24, 0x79, 0x7d, 0x3a, 0x15, - 0xcd, 0xbb, 0x7c, 0x45, 0xf3, 0x97, 0xa7, 0x72, 0x05, 0x7a, 0x6c, 0x5e, 0xd3, 0xf5, 0x2e, 0xb1, + 0x78, 0x9f, 0xb7, 0xfc, 0xd5, 0x56, 0x4d, 0xea, 0xac, 0x9e, 0xbd, 0x24, 0x79, 0x7d, 0x3a, 0x15, 0xcd, 0xbb, 0x7c, + 0x45, 0xf3, 0x97, 0xa7, 0x72, 0x05, 0x7a, 0x6c, 0x5e, 0xd3, 0xf5, 0x2e, 0xb1, ]; diff --git a/crates/cuda-driver/src/head_greedy_gpu.rs b/crates/cuda-driver/src/head_greedy_gpu.rs index 67eaec51..157573ab 100644 --- a/crates/cuda-driver/src/head_greedy_gpu.rs +++ b/crates/cuda-driver/src/head_greedy_gpu.rs @@ -16,11 +16,7 @@ fn old_greedy(bytes: &[u8]) -> Option<(u32, f32)> { } best } -fn original_first( - source: &mut DeviceBuffer<'_>, - workspace: &mut HeadGreedyWorkspace<'_>, - values: &[u32], -) -> usize { +fn original_first(source: &mut DeviceBuffer<'_>, workspace: &mut HeadGreedyWorkspace<'_>, values: &[u32]) -> usize { let bytes: Vec = values.iter().flat_map(|word| word.to_le_bytes()).collect(); source.copy_from(&bytes).unwrap(); let mut original = vec![0; SOURCE_BYTES]; @@ -34,11 +30,7 @@ fn original_first( (Some((index, value)), Some(actual)) => { assert_eq!(actual.vocabulary_index(), index); let key = actual.ordered_key(); - let bits = if key & 0x8000_0000 != 0 { - key ^ 0x8000_0000 - } else { - !key - }; + let bits = if key & 0x8000_0000 != 0 { key ^ 0x8000_0000 } else { !key }; assert_eq!(f32::from_bits(bits), value); if value == 0.0 { assert_eq!(bits, 0); @@ -61,27 +53,16 @@ fn original_first_complete_greedy_ties_finite_reset_guards_and_cleanup() { let device = driver.device(0).unwrap(); let context = device.create_context(4 * 1024 * 1024).unwrap(); let foreign = device.create_context(2 * 1024 * 1024).unwrap(); - let small = device - .create_context(HEAD_GREEDY_WORKSPACE_BYTES - 1) - .unwrap(); - assert!(matches!( - small.head_greedy_workspace(), - Err(Error::BudgetExceeded) - )); + let small = device.create_context(HEAD_GREEDY_WORKSPACE_BYTES - 1).unwrap(); + assert!(matches!(small.head_greedy_workspace(), Err(Error::BudgetExceeded))); assert_eq!(small.allocated_bytes(), 0); let mut workspace = context.head_greedy_workspace().unwrap(); assert_eq!(workspace.allocated_bytes(), 11_652); let mut source = context.allocate(SOURCE_BYTES).unwrap(); let other = foreign.allocate(SOURCE_BYTES).unwrap(); let short = context.allocate(SOURCE_BYTES - 4).unwrap(); - assert!(matches!( - workspace.select(&other), - Err(Error::ContextMismatch) - )); - assert!(matches!( - workspace.select(&short), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(workspace.select(&other), Err(Error::ContextMismatch))); + assert!(matches!(workspace.select(&short), Err(Error::InvalidQwenShape))); let mut products = 0usize; let mut words = 0usize; for case in 0..6 { diff --git a/crates/cuda-driver/src/impl_context.rs b/crates/cuda-driver/src/impl_context.rs index 8ba5d227..01591583 100644 --- a/crates/cuda-driver/src/impl_context.rs +++ b/crates/cuda-driver/src/impl_context.rs @@ -49,18 +49,11 @@ impl Context<'_> { self.retain_driver(); return Err(error); } - Ok(CurrentGuard { - context: self, - active: true, - }) + Ok(CurrentGuard { context: self, active: true }) } pub fn allocate(&self, bytes: usize) -> Result> { valid_size(bytes)?; - let total = self - .allocated - .get() - .checked_add(bytes) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(bytes).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -73,13 +66,7 @@ impl Context<'_> { // context owns that allocation until destruction, so no unguarded free. let handle = combine(allocation, guard.finish())?; vram_ledger::note_alloc(handle.qwen_address(), bytes); - Ok(DeviceBuffer { - context: self, - handle: Some(handle), - bytes, - _thread: PhantomData, - borrowed: false, - }) + Ok(DeviceBuffer { context: self, handle: Some(handle), bytes, _thread: PhantomData, borrowed: false }) } /// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the /// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once. @@ -91,7 +78,11 @@ impl Context<'_> { }; static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); let limit = *LIMIT.get_or_init(|| { - std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(512) << 20 + std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(512) + << 20 }); if pending > limit { self.flush_deferred_frees() } else { Ok(()) } } @@ -185,10 +176,7 @@ impl Context<'_> { Ok(kernel) => kernel, Err(error) => return combine(Err(error), guard.finish()), }; - let launch = self - .driver - .api - .launch(kernel.function, grid, &mut arguments); + let launch = self.driver.api.launch(kernel.function, grid, &mut arguments); self.complete_launch(launch, arguments, guard) } pub(super) fn vector_admission( @@ -200,10 +188,7 @@ impl Context<'_> { if self.poisoned.get() { return Err(Error::ContextPoisoned); } - if !std::ptr::eq(self, a.context) - || !std::ptr::eq(self, b.context) - || !std::ptr::eq(self, output.context) - { + if !std::ptr::eq(self, a.context) || !std::ptr::eq(self, b.context) || !std::ptr::eq(self, output.context) { return Err(Error::ContextMismatch); } let (count, grid) = vector_shape(a.bytes)?; diff --git a/crates/cuda-driver/src/impl_context_2.rs b/crates/cuda-driver/src/impl_context_2.rs index 5cf086de..c54b4960 100644 --- a/crates/cuda-driver/src/impl_context_2.rs +++ b/crates/cuda-driver/src/impl_context_2.rs @@ -17,22 +17,14 @@ impl Context<'_> { ) -> Result<()> { let (shape, handles) = self.matvec_admission([matrix, vector, output], rows, columns)?; let [matrix_handle, vector_handle, output_handle] = handles; - let mut arguments = ffi::MatvecArguments::new( - matrix_handle, - vector_handle, - output_handle, - shape.rows, - shape.columns, - ); + let mut arguments = + ffi::MatvecArguments::new(matrix_handle, vector_handle, output_handle, shape.rows, shape.columns); let guard = self.enter()?; let kernel = match self.fixed_kernel(FixedOperation::Matvec) { Ok(kernel) => kernel, Err(error) => return combine(Err(error), guard.finish()), }; - let launch = self - .driver - .api - .launch_matvec(kernel.function, shape.grid, &mut arguments); + let launch = self.driver.api.launch_matvec(kernel.function, shape.grid, &mut arguments); self.complete_launch(launch, arguments, guard) } @@ -45,16 +37,11 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, shape: Q5KProjectionShape, ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.q5_k_admission(weights, activation, output, shape)?; + let (shape, handles, temporary_bytes) = self.q5_k_admission(weights, activation, output, shape)?; // Account the complete worst-case scratch/status requirement before // the first context push, module load, or allocation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(temporary_bytes).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -89,11 +76,7 @@ impl Context<'_> { shape.columns, ); let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.quantize, - shape.quant_grid, - &mut quant_arguments, - ); + let quantize = self.driver.api.launch_q8_quantize(kernels.quantize, shape.quant_grid, &mut quant_arguments); self.complete_launch(quantize, quant_arguments, quant_guard)?; let mut native_status = [0u8; 4]; @@ -110,11 +93,8 @@ impl Context<'_> { shape.columns, ); let project_guard = self.enter()?; - let project = self.driver.api.launch_q5_projection( - kernels.project, - shape.projection_grid, - &mut project_arguments, - ); + let project = + self.driver.api.launch_q5_projection(kernels.project, shape.projection_grid, &mut project_arguments); self.complete_launch(project, project_arguments, project_guard) })(); @@ -130,15 +110,10 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, dimensions: Q6KProjectionShape, ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.q6_k_admission(weights, activation, output, dimensions)?; + let (shape, handles, temporary_bytes) = self.q6_k_admission(weights, activation, output, dimensions)?; // Charge the complete scratch/status requirement before native mutation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(temporary_bytes).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -173,11 +148,7 @@ impl Context<'_> { shape.columns, ); let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.quantize, - shape.quant_grid, - &mut quant_arguments, - ); + let quantize = self.driver.api.launch_q8_quantize(kernels.quantize, shape.quant_grid, &mut quant_arguments); self.complete_launch(quantize, quant_arguments, quant_guard)?; let mut native_status = [0u8; 4]; @@ -194,11 +165,8 @@ impl Context<'_> { shape.columns, ); let project_guard = self.enter()?; - let project = self.driver.api.launch_q6_projection( - kernels.project, - shape.projection_grid, - &mut project_arguments, - ); + let project = + self.driver.api.launch_q6_projection(kernels.project, shape.projection_grid, &mut project_arguments); self.complete_launch(project, project_arguments, project_guard) })(); diff --git a/crates/cuda-driver/src/impl_context_3.rs b/crates/cuda-driver/src/impl_context_3.rs index 18192153..02bd4dd7 100644 --- a/crates/cuda-driver/src/impl_context_3.rs +++ b/crates/cuda-driver/src/impl_context_3.rs @@ -11,15 +11,10 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, spec: ProjectionSpec, ) -> Result<()> { - let (shape, handles, temporary_bytes) = - self.projection_admission_weight(weights, activation, output, spec)?; + let (shape, handles, temporary_bytes) = self.projection_admission_weight(weights, activation, output, spec)?; // Charge the complete scratch/status requirement before native mutation. - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(temporary_bytes).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -54,11 +49,7 @@ impl Context<'_> { shape.columns, ); let quant_guard = self.enter()?; - let quantize = self.driver.api.launch_q8_quantize( - kernels.0, - shape.quant_grid, - &mut quant_arguments, - ); + let quantize = self.driver.api.launch_q8_quantize(kernels.0, shape.quant_grid, &mut quant_arguments); self.complete_launch(quantize, quant_arguments, quant_guard)?; let mut native_status = [0u8; 4]; @@ -75,11 +66,7 @@ impl Context<'_> { shape.columns, ); let project_guard = self.enter()?; - let project = self.driver.api.launch_projection( - kernels.1, - shape.projection_grid, - &mut project_arguments, - ); + let project = self.driver.api.launch_projection(kernels.1, shape.projection_grid, &mut project_arguments); self.complete_launch(project, project_arguments, project_guard) })(); @@ -103,11 +90,7 @@ impl Context<'_> { return Err(Error::InvalidProjectionShape); } source.validate_projection_extent(10240, 4)?; - let total = self - .allocated - .get() - .checked_add(2884) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(2884).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -142,13 +125,9 @@ impl Context<'_> { }; combine(Ok(kernel), guard.finish())? }; - let mut arguments = - ffi::Q8QuantizeArguments::new(source, quantized, status_handle, 2560); + let mut arguments = ffi::Q8QuantizeArguments::new(source, quantized, status_handle, 2560); let guard = self.enter()?; - let launch = self - .driver - .api - .launch_q8_quantize(kernel.function, 10, &mut arguments); + let launch = self.driver.api.launch_q8_quantize(kernel.function, 10, &mut arguments); self.complete_launch(launch, arguments, guard)?; let mut native_status = [0u8; 4]; status.copy_to(&mut native_status)?; @@ -169,10 +148,7 @@ impl Context<'_> { } return combine(Err(error), scratch.release()); } - Ok(RoutedGateUpQ8 { - activation, - scratch: Some(scratch), - }) + Ok(RoutedGateUpQ8 { activation, scratch: Some(scratch) }) } /// Project a fixed routed 640x2560 Gate/Up matrix using prepared Q8_1. @@ -184,11 +160,6 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, format: RoutedFormat, ) -> Result<()> { - self.project_routed_gate_up_prepared_weight( - NativeWeights::Raw(weights), - prepared, - output, - format, - ) + self.project_routed_gate_up_prepared_weight(NativeWeights::Raw(weights), prepared, output, format) } } diff --git a/crates/cuda-driver/src/impl_context_4.rs b/crates/cuda-driver/src/impl_context_4.rs index 9930502f..1ec6b4c3 100644 --- a/crates/cuda-driver/src/impl_context_4.rs +++ b/crates/cuda-driver/src/impl_context_4.rs @@ -24,32 +24,15 @@ impl Context<'_> { return Err(Error::ContextPoisoned); } } - if !matches!( - format, - RoutedFormat::IQ3_XXS - | RoutedFormat::IQ3_S - | RoutedFormat::IQ2_S - | RoutedFormat::IQ4_XS - ) { + if !matches!(format, RoutedFormat::IQ3_XXS | RoutedFormat::IQ3_S | RoutedFormat::IQ2_S | RoutedFormat::IQ4_XS) { return Err(Error::UnsupportedProjection); } let kind = ProjectionKind::Routed(format); if !ffi::projection_available(kind) { return Err(Error::UnsupportedProjection); } - let shape = projection_shape(ProjectionSpec { - kind, - rows: 640, - columns: 2560, - })?; - weight_owner.validate( - ProjectionSpec { - kind, - rows: 640, - columns: 2560, - }, - shape.weight_bytes, - )?; + let shape = projection_shape(ProjectionSpec { kind, rows: 640, columns: 2560 })?; + weight_owner.validate(ProjectionSpec { kind, rows: 640, columns: 2560 }, shape.weight_bytes)?; if prepared.activation.bytes != shape.activation_bytes || scratch.bytes != shape.scratch_bytes || output.bytes != shape.output_bytes @@ -86,13 +69,9 @@ impl Context<'_> { }; combine(Ok(kernels.1), guard.finish())? }; - let mut arguments = - ffi::ProjectionArguments::new(weight, quantized, out, shape.rows, shape.columns); + let mut arguments = ffi::ProjectionArguments::new(weight, quantized, out, shape.rows, shape.columns); let guard = self.enter()?; - let launch = - self.driver - .api - .launch_projection(kernel, shape.projection_grid, &mut arguments); + let launch = self.driver.api.launch_projection(kernel, shape.projection_grid, &mut arguments); self.complete_launch(launch, arguments, guard) } @@ -133,11 +112,7 @@ impl Context<'_> { return Err(Error::OutputAliasesInput); } let temporary_bytes = shape.temporary_bytes; - let total = self - .allocated - .get() - .checked_add(temporary_bytes) - .ok_or(Error::BudgetExceeded)?; + let total = self.allocated.get().checked_add(temporary_bytes).ok_or(Error::BudgetExceeded)?; if total > self.budget { return Err(Error::BudgetExceeded); } @@ -172,19 +147,10 @@ impl Context<'_> { if output == weight || output == activation { return Err(Error::OutputAliasesInput); } - weight - .validate_extent(shape.weight_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - activation - .validate_extent(shape.activation_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - output - .validate_extent(shape.output_bytes) - .map_err(|_| Error::InvalidQ5KProjectionShape)?; - let temporary_bytes = shape - .scratch_bytes - .checked_add(4) - .ok_or(Error::BudgetExceeded)?; + weight.validate_extent(shape.weight_bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; + activation.validate_extent(shape.activation_bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; + output.validate_extent(shape.output_bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; + let temporary_bytes = shape.scratch_bytes.checked_add(4).ok_or(Error::BudgetExceeded)?; Ok((shape, [weight, activation, output], temporary_bytes)) } @@ -217,19 +183,10 @@ impl Context<'_> { if output == weight || output == activation { return Err(Error::OutputAliasesInput); } - weight - .validate_extent(shape.weight_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - activation - .validate_extent(shape.activation_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - output - .validate_extent(shape.output_bytes) - .map_err(|_| Error::InvalidQ6KProjectionShape)?; - let temporary_bytes = shape - .scratch_bytes - .checked_add(4) - .ok_or(Error::BudgetExceeded)?; + weight.validate_extent(shape.weight_bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; + activation.validate_extent(shape.activation_bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; + output.validate_extent(shape.output_bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; + let temporary_bytes = shape.scratch_bytes.checked_add(4).ok_or(Error::BudgetExceeded)?; Ok((shape, [weight, activation, output], temporary_bytes)) } diff --git a/crates/cuda-driver/src/impl_context_5.rs b/crates/cuda-driver/src/impl_context_5.rs index 0cd79b43..036dd063 100644 --- a/crates/cuda-driver/src/impl_context_5.rs +++ b/crates/cuda-driver/src/impl_context_5.rs @@ -136,30 +136,16 @@ impl Context<'_> { return combine(Err(error), cleanup); } }; - let kernels = FixedPairKernels { - module, - quantize, - project, - }; + let kernels = FixedPairKernels { module, quantize, project }; // Publish only after both closed fixed entries resolve successfully. cache.set(Some(kernels)); Ok(kernels) } pub(super) fn q5_kernels(&self) -> Result { - self.fixed_pair( - &self.q5_k_kernel, - FixedOperation::Q5K, - FixedOperation::Q5KQuantize, - FixedOperation::Q5KProject, - ) + self.fixed_pair(&self.q5_k_kernel, FixedOperation::Q5K, FixedOperation::Q5KQuantize, FixedOperation::Q5KProject) } pub(super) fn q6_kernels(&self) -> Result { - self.fixed_pair( - &self.q6_k_kernel, - FixedOperation::Q6K, - FixedOperation::Q6KQuantize, - FixedOperation::Q6KProject, - ) + self.fixed_pair(&self.q6_k_kernel, FixedOperation::Q6K, FixedOperation::Q6KQuantize, FixedOperation::Q6KProject) } pub(super) fn unload_pair(&self, cache: &Cell>) -> Result<()> { let Some(kernels) = cache.take() else { @@ -185,40 +171,21 @@ impl Context<'_> { } combine(unload, guard.finish()) } - pub(super) fn common_kernels( - &self, - kind: ProjectionKind, - ) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> { + pub(super) fn common_kernels(&self, kind: ProjectionKind) -> Result<(ffi::FunctionHandle, ffi::FunctionHandle)> { let quantizer = self.fixed_kernel(FixedOperation::CommonQuantize)?; let slot = &self.projection_kernels[kind.layout().0]; let kernels = if let Some(kernels) = slot.get() { kernels } else { - let module = self - .driver - .api - .load_fixed_module(FixedOperation::Projection(kind))?; + let module = self.driver.api.load_fixed_module(FixedOperation::Projection(kind))?; let load = (|| { let (dense, routed) = kind.required_modes(); - let dense = dense - .map(|k| { - self.driver - .api - .fixed_function(module, FixedOperation::Projection(k)) - }) - .transpose()?; + let dense = + dense.map(|k| self.driver.api.fixed_function(module, FixedOperation::Projection(k))).transpose()?; let routed = routed - .map(|k| { - self.driver - .api - .fixed_function(module, FixedOperation::Projection(k)) - }) + .map(|k| self.driver.api.fixed_function(module, FixedOperation::Projection(k))) .transpose()?; - Ok(ProjectionKernels { - module, - dense, - routed, - }) + Ok(ProjectionKernels { module, dense, routed }) })(); match load { Ok(kernels) => { diff --git a/crates/cuda-driver/src/impl_context_6.rs b/crates/cuda-driver/src/impl_context_6.rs index 66d9618c..a61d9c43 100644 --- a/crates/cuda-driver/src/impl_context_6.rs +++ b/crates/cuda-driver/src/impl_context_6.rs @@ -101,10 +101,7 @@ impl Context<'_> { ), ), combine( - combine( - self.unload_kernel(FixedOperation::VectorAdd), - self.unload_kernel(FixedOperation::Matvec), - ), + combine(self.unload_kernel(FixedOperation::VectorAdd), self.unload_kernel(FixedOperation::Matvec)), combine(self.unload_q5_kernels(), self.unload_q6_kernels()), ), ), @@ -143,11 +140,7 @@ impl CurrentGuard<'_, '_> { } self.active = false; let result = self.context.driver.api.pop().and_then(|popped| { - if Some(popped) == self.context.handle { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } + if Some(popped) == self.context.handle { Ok(()) } else { Err(Error::UnexpectedContext) } }); if result.is_err() { self.context.poisoned.set(true); diff --git a/crates/cuda-driver/src/impl_devicebuffer.rs b/crates/cuda-driver/src/impl_devicebuffer.rs index 53226eb0..77102b5e 100644 --- a/crates/cuda-driver/src/impl_devicebuffer.rs +++ b/crates/cuda-driver/src/impl_devicebuffer.rs @@ -12,18 +12,13 @@ impl DeviceBuffer<'_> { } pub(super) fn staging(&self, actual: usize) -> Result> { if actual != self.bytes { - return Err(Error::ShapeMismatch { - expected: self.bytes, - actual, - }); + return Err(Error::ShapeMismatch { expected: self.bytes, actual }); } if self.context.poisoned.get() { return Err(Error::ContextPoisoned); } let mut staging = Vec::new(); - staging - .try_reserve_exact(self.bytes) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(self.bytes).map_err(|_| Error::HostAllocation)?; staging.resize(self.bytes, 0); Ok(staging) } @@ -37,10 +32,7 @@ impl DeviceBuffer<'_> { pub fn copy_from_owned(&mut self, input: Vec) -> Result<()> { // Preserve the original staging() shape-before-poison admission order. if input.len() != self.bytes { - return Err(Error::ShapeMismatch { - expected: self.bytes, - actual: input.len(), - }); + return Err(Error::ShapeMismatch { expected: self.bytes, actual: input.len() }); } if self.context.poisoned.get() { return Err(Error::ContextPoisoned); @@ -62,15 +54,9 @@ impl DeviceBuffer<'_> { if self.context.poisoned.get() { return Err(Error::ContextPoisoned); } - let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - self.bytes, - offset, - input.len(), - )?; + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, input.len())?; let mut staging = Vec::new(); - staging - .try_reserve_exact(input.len()) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(input.len()).map_err(|_| Error::HostAllocation)?; staging.extend_from_slice(input); let guard = self.context.enter()?; let copy = self.context.driver.api.copy_from(handle, &staging); @@ -89,15 +75,9 @@ impl DeviceBuffer<'_> { if self.context.poisoned.get() { return Err(Error::ContextPoisoned); } - let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - self.bytes, - offset, - output.len(), - )?; + let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, output.len())?; let mut staging = Vec::new(); - staging - .try_reserve_exact(output.len()) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(output.len()).map_err(|_| Error::HostAllocation)?; staging.resize(output.len(), 0); let guard = self.context.enter()?; let copy = self.context.driver.api.copy_to(handle, &mut staging); @@ -164,9 +144,7 @@ impl DeviceBuffer<'_> { let guard = self.context.enter()?; let free = self.context.driver.api.free(handle); if free.is_ok() { - self.context - .allocated - .set(self.context.allocated.get() - self.bytes); + self.context.allocated.set(self.context.allocated.get() - self.bytes); } combine(free, guard.finish()) } @@ -183,7 +161,11 @@ impl Drop for DeviceBuffer<'_> { pub fn chain_selects_mtp() -> bool { original_verify::chain::flags().mtp } -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] pub fn chain_selects_mtp() -> bool { false } diff --git a/crates/cuda-driver/src/impl_projectionkind.rs b/crates/cuda-driver/src/impl_projectionkind.rs index 815c4e01..36c83c8a 100644 --- a/crates/cuda-driver/src/impl_projectionkind.rs +++ b/crates/cuda-driver/src/impl_projectionkind.rs @@ -24,21 +24,18 @@ impl ProjectionKind { // Native Q4_K half2/u32 fields and IQ4_XS qs at offset8 require // aligned 32-bit loads. The remaining packed blocks use halfwords. match self { - Self::Dense(DenseFormat::Q4_K | DenseFormat::IQ4_XS) - | Self::Routed(RoutedFormat::IQ4_XS) => 4, + Self::Dense(DenseFormat::Q4_K | DenseFormat::IQ4_XS) | Self::Routed(RoutedFormat::IQ4_XS) => 4, _ => 2, } } pub(super) fn required_modes(self) -> (Option, Option) { match self { - Self::Dense(DenseFormat::IQ4_NL) | Self::Routed(RoutedFormat::IQ4_NL) => ( - Some(Self::Dense(DenseFormat::IQ4_NL)), - Some(Self::Routed(RoutedFormat::IQ4_NL)), - ), - Self::Dense(DenseFormat::IQ4_XS) | Self::Routed(RoutedFormat::IQ4_XS) => ( - Some(Self::Dense(DenseFormat::IQ4_XS)), - Some(Self::Routed(RoutedFormat::IQ4_XS)), - ), + Self::Dense(DenseFormat::IQ4_NL) | Self::Routed(RoutedFormat::IQ4_NL) => { + (Some(Self::Dense(DenseFormat::IQ4_NL)), Some(Self::Routed(RoutedFormat::IQ4_NL))) + } + Self::Dense(DenseFormat::IQ4_XS) | Self::Routed(RoutedFormat::IQ4_XS) => { + (Some(Self::Dense(DenseFormat::IQ4_XS)), Some(Self::Routed(RoutedFormat::IQ4_XS))) + } Self::Dense(_) => (Some(self), None), Self::Routed(_) => (None, Some(self)), } @@ -58,19 +55,12 @@ pub(super) fn q4_k_native_indices_fit(rows: usize, columns: usize) -> bool { return false; } - let rows_per_cta = if columns < 2048 { - Q4_K_ROWS_PER_CTA_SMALL - } else { - 1 - }; - let last_cta_base_row = match rows - .div_ceil(rows_per_cta) - .checked_sub(1) - .and_then(|index| index.checked_mul(rows_per_cta)) - { - Some(value) => value, - None => return false, - }; + let rows_per_cta = if columns < 2048 { Q4_K_ROWS_PER_CTA_SMALL } else { 1 }; + let last_cta_base_row = + match rows.div_ceil(rows_per_cta).checked_sub(1).and_then(|index| index.checked_mul(rows_per_cta)) { + Some(value) => value, + None => return false, + }; // PTX materializes row, row+1, row+2, and row+3 offsets even for the // one-row large-N launch; the invalid output arms are only guarded later. let last_computed_row = match last_cta_base_row.checked_add(3) { @@ -126,11 +116,7 @@ pub(super) fn projection_shape(spec: ProjectionSpec) -> Result let scratch_bytes = bounded((n / 32).checked_mul(36))?; let temporary_bytes = bounded(scratch_bytes.checked_add(4))?; let quant_grid = u32::try_from(n.div_ceil(256)).map_err(|_| Error::InvalidProjectionShape)?; - let grid = if small.is_none_or(|limit| n < limit) { - m.div_ceil(4) - } else { - m - }; + let grid = if small.is_none_or(|limit| n < limit) { m.div_ceil(4) } else { m }; let projection_grid = u32::try_from(grid).map_err(|_| Error::InvalidProjectionShape)?; Ok(ProjectionShape { weight_bytes, @@ -177,15 +163,11 @@ pub(super) fn q5_k_shape(rows: usize, columns: usize) -> Result { return Err(Error::InvalidQ5KProjectionShape); } let checked_bytes = |elements: usize, width: usize| -> Result { - let bytes = elements - .checked_mul(width) - .ok_or(Error::InvalidQ5KProjectionShape)?; + let bytes = elements.checked_mul(width).ok_or(Error::InvalidQ5KProjectionShape)?; valid_size(bytes).map_err(|_| Error::InvalidQ5KProjectionShape)?; Ok(bytes) }; - let weight_blocks = rows - .checked_mul(columns / 256) - .ok_or(Error::InvalidQ5KProjectionShape)?; + let weight_blocks = rows.checked_mul(columns / 256).ok_or(Error::InvalidQ5KProjectionShape)?; let weight_bytes = checked_bytes(weight_blocks, 176)?; let activation_bytes = checked_bytes(columns, 4)?; let output_bytes = checked_bytes(rows, 4)?; @@ -207,7 +189,6 @@ pub(super) fn q5_k_shape(rows: usize, columns: usize) -> Result { rows: rows_abi, columns: columns_abi, quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ5KProjectionShape)?, - projection_grid: u32::try_from(projection_ctas) - .map_err(|_| Error::InvalidQ5KProjectionShape)?, + projection_grid: u32::try_from(projection_ctas).map_err(|_| Error::InvalidQ5KProjectionShape)?, }) } diff --git a/crates/cuda-driver/src/iq3_native_integer_mma.rs b/crates/cuda-driver/src/iq3_native_integer_mma.rs index d5275e86..a23330ba 100644 --- a/crates/cuda-driver/src/iq3_native_integer_mma.rs +++ b/crates/cuda-driver/src/iq3_native_integer_mma.rs @@ -5,24 +5,16 @@ pub(super) const CHARGE: usize = 13_107_200; /// Actual root GPU-hidden NVCC 12.8.93 sm_120 asset; explicit experimental policy. pub(crate) fn asset() -> Result<&'static [u8]> { let b = include_bytes!("iq3_native_integer_mma.ptx"); - if b.len() != 17928 - || b.last() != Some(&0) - || !b[..b.len() - 1].is_ascii() - || b[..b.len() - 1].contains(&0) - { - return Err(Error::InvalidDriverValue( - "IQ3 native integer MMA PTX encoding", - )); + if b.len() != 17928 || b.last() != Some(&0) || !b[..b.len() - 1].is_ascii() || b[..b.len() - 1].contains(&0) { + return Err(Error::InvalidDriverValue("IQ3 native integer MMA PTX encoding")); } if crate::qwen_ffi::sha256(&b[..b.len() - 1]) != [ - 59, 251, 32, 197, 49, 208, 213, 116, 205, 208, 18, 218, 159, 208, 202, 224, 99, 246, - 22, 209, 160, 112, 224, 32, 23, 153, 171, 17, 215, 54, 142, 99, + 59, 251, 32, 197, 49, 208, 213, 116, 205, 208, 18, 218, 159, 208, 202, 224, 99, 246, 22, 209, 160, 112, + 224, 32, 23, 153, 171, 17, 215, 54, 142, 99, ] { - return Err(Error::InvalidDriverValue( - "IQ3 native integer MMA PTX digest", - )); + return Err(Error::InvalidDriverValue("IQ3 native integer MMA PTX digest")); } Ok(b) } @@ -38,19 +30,10 @@ impl<'ctx> NativeInteger<'ctx> { return Err(Error::ContextPoisoned); } asset()?; - if context - .allocated_bytes() - .checked_add(CHARGE) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(CHARGE).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - dots: None, - module: None, - functions: None, - }; + let mut owner = Self { context, dots: None, module: None, functions: None }; let result = (|| { owner.dots = Some(context.allocate(CHARGE)?); let guard = context.enter()?; @@ -82,16 +65,12 @@ impl<'ctx> NativeInteger<'ctx> { if !std::ptr::eq(self.context, b.context) || b.bytes != CHARGE { return Err(Error::ContextMismatch); } - b.handle - .ok_or(Error::ContextPoisoned)? - .validate_projection_extent(CHARGE, 4) + b.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(CHARGE, 4) } pub(super) fn overlaps(&self, h: ffi::BufferHandle, bytes: usize) -> Result { self.check()?; let d = self.dots.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(d.handle - .ok_or(Error::ContextPoisoned)? - .overlaps(CHARGE, h, bytes)) + Ok(d.handle.ok_or(Error::ContextPoisoned)?.overlaps(CHARGE, h, bytes)) } pub(super) fn append( &self, @@ -118,12 +97,7 @@ impl<'ctx> NativeInteger<'ctx> { weights.validate_projection_extent(l.weight, 2)?; packed.validate_projection_extent(l.packed, 16)?; output.validate_projection_extent(l.output, 4)?; - let dh = self - .dots - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; + let dh = self.dots.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; dh.validate_projection_extent(CHARGE, 4)?; for (h, n) in [(weights, l.weight), (packed, l.packed), (output, l.output)] { if dh.overlaps(CHARGE, h, n) { @@ -156,13 +130,10 @@ impl<'ctx> NativeInteger<'ctx> { b.release() } }); - let b = self - .module - .take() - .map_or(Ok(()), |m| match self.context.enter() { - Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), - Err(e) => Err(e), - }); + let b = self.module.take().map_or(Ok(()), |m| match self.context.enter() { + Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), + Err(e) => Err(e), + }); if a.is_err() || b.is_err() { self.context.poisoned.set(true); } diff --git a/crates/cuda-driver/src/kar_decode_levels.rs b/crates/cuda-driver/src/kar_decode_levels.rs index efec40fb..a262f9fe 100644 --- a/crates/cuda-driver/src/kar_decode_levels.rs +++ b/crates/cuda-driver/src/kar_decode_levels.rs @@ -37,8 +37,7 @@ pub const ENTRY_SWIGLU: &CStr = c"leleka_kar_swiglu_f32"; pub const MAX_SWIGLU_VALUES: u64 = 1 << 20; /// Frozen-asset bytes plus the single ABI NUL, like every other fixed asset. -pub static KAR_DECODE_LEVELS_PTX: &[u8] = - concat!(include_str!("kar_decode_levels.ptx"), "\0").as_bytes(); +pub static KAR_DECODE_LEVELS_PTX: &[u8] = concat!(include_str!("kar_decode_levels.ptx"), "\0").as_bytes(); #[derive(Debug, Clone, PartialEq, Eq)] pub enum KarDecodeError { @@ -90,12 +89,12 @@ pub struct PtxPin { /// TODO-ROOT: freeze after `nvcc` build and the `#[ignore]d` GPU smoke. pub const KAR_DECODE_LEVELS_PIN: PtxPin = PtxPin { source_sha256: [ - 19, 150, 144, 13, 105, 87, 184, 78, 93, 160, 43, 71, 157, 11, 101, 150, 134, 16, 117, 250, - 161, 60, 121, 117, 131, 93, 199, 90, 90, 111, 127, 126, + 19, 150, 144, 13, 105, 87, 184, 78, 93, 160, 43, 71, 157, 11, 101, 150, 134, 16, 117, 250, 161, 60, 121, 117, + 131, 93, 199, 90, 90, 111, 127, 126, ], ptx_sha256: [ - 236, 105, 119, 135, 224, 0, 83, 16, 0, 94, 177, 105, 167, 88, 49, 94, 181, 80, 58, 199, 103, - 26, 56, 73, 94, 234, 234, 244, 251, 42, 142, 201, + 236, 105, 119, 135, 224, 0, 83, 16, 0, 94, 177, 105, 167, 88, 49, 94, 181, 80, 58, 199, 103, 26, 56, 73, 94, + 234, 234, 244, 251, 42, 142, 201, ], }; @@ -104,11 +103,7 @@ pub fn admit_ptx(ptx: &'static [u8], pin: &PtxPin) -> Result<()> { if pin.source_sha256 == [0; 32] || pin.ptx_sha256 == [0; 32] { return Err(KarDecodeError::Unpinned); } - if ptx.len() < 2 - || ptx.last() != Some(&0) - || ptx[..ptx.len() - 1].contains(&0) - || !ptx.is_ascii() - { + if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() { return Err(KarDecodeError::Unpinned); } if qwen_ffi::sha256(&ptx[..ptx.len() - 1]) != pin.ptx_sha256 { @@ -208,8 +203,7 @@ impl DecodeGeometry { let groups_needed = (u64::from(self.head_group) + count - 1) / group + 1; if words_needed > u64::from(self.window_words) || groups_needed > u64::from(self.window_groups) - || u64::from(self.scales_offset) + 2 * u64::from(self.window_groups) - > u64::from(self.packet_bytes) + || u64::from(self.scales_offset) + 2 * u64::from(self.window_groups) > u64::from(self.packet_bytes) || u64::from(self.planes_offset) + level * u64::from(self.plane_stride_words) * 4 > u64::from(self.packet_bytes) { @@ -326,11 +320,7 @@ pub struct ExpertShape { } impl ExpertShape { /// Check three decode windows against one expert's shape and return it. - pub fn from_matrices( - gate: &MultiplyGeometry, - up: &MultiplyGeometry, - down: &MultiplyGeometry, - ) -> Result { + pub fn from_matrices(gate: &MultiplyGeometry, up: &MultiplyGeometry, down: &MultiplyGeometry) -> Result { for g in [gate, up, down] { g.validate()?; if g.tokens != 1 { @@ -344,20 +334,13 @@ impl ExpertShape { { return invalid("KAR expert gate/up/down shapes are inconsistent"); } - Ok(Self { - hidden: gate.columns, - ff: gate.rows, - }) + Ok(Self { hidden: gate.columns, ff: gate.rows }) } } /// Interpret a status word read back from the device. pub fn check_status(bits: u32) -> Result<()> { - if bits == 0 { - Ok(()) - } else { - Err(KarDecodeError::DeviceStatus(bits)) - } + if bits == 0 { Ok(()) } else { Err(KarDecodeError::DeviceStatus(bits)) } } #[cfg(test)] diff --git a/crates/cuda-driver/src/kar_decode_levels/tests.rs b/crates/cuda-driver/src/kar_decode_levels/tests.rs index 0157e500..d14307b4 100644 --- a/crates/cuda-driver/src/kar_decode_levels/tests.rs +++ b/crates/cuda-driver/src/kar_decode_levels/tests.rs @@ -37,10 +37,7 @@ fn level_group_and_count_bounds() { assert!(DecodeGeometry::for_window(level, 32, 0, 1).is_ok()); } for group in [0, 1, 16, 31, 33, 48, 1056, u32::MAX] { - assert!( - DecodeGeometry::for_window(2, group, 0, 1).is_err(), - "{group}" - ); + assert!(DecodeGeometry::for_window(2, group, 0, 1).is_err(), "{group}"); } for group in [32, 64, 96, 128, 1024] { assert!(DecodeGeometry::for_window(2, group, 0, 1).is_ok()); @@ -87,65 +84,17 @@ fn validate_rejects_each_corruption() { ("level 1", DecodeGeometry { level: 1, ..good }), ("level 6", DecodeGeometry { level: 6, ..good }), ("count 0", DecodeGeometry { count: 0, ..good }), - ( - "count max+1", - DecodeGeometry { - count: MAX_RANGE_ELEMENTS as u32 + 1, - ..good - }, - ), + ("count max+1", DecodeGeometry { count: MAX_RANGE_ELEMENTS as u32 + 1, ..good }), ("group 0", DecodeGeometry { group: 0, ..good }), ("group 33", DecodeGeometry { group: 33, ..good }), ("head32", DecodeGeometry { head32: 32, ..good }), - ( - "head_group", - DecodeGeometry { - head_group: good.group, - ..good - }, - ), - ( - "words short", - DecodeGeometry { - window_words: good.window_words - 1, - ..good - }, - ), - ( - "groups short", - DecodeGeometry { - window_groups: good.window_groups - 1, - ..good - }, - ), - ( - "stride", - DecodeGeometry { - plane_stride_words: good.plane_stride_words - 1, - ..good - }, - ), - ( - "planes misaligned", - DecodeGeometry { - planes_offset: good.planes_offset + 2, - ..good - }, - ), - ( - "packet short", - DecodeGeometry { - packet_bytes: good.packet_bytes - 4, - ..good - }, - ), - ( - "scales odd", - DecodeGeometry { - scales_offset: 65, - ..good - }, - ), + ("head_group", DecodeGeometry { head_group: good.group, ..good }), + ("words short", DecodeGeometry { window_words: good.window_words - 1, ..good }), + ("groups short", DecodeGeometry { window_groups: good.window_groups - 1, ..good }), + ("stride", DecodeGeometry { plane_stride_words: good.plane_stride_words - 1, ..good }), + ("planes misaligned", DecodeGeometry { planes_offset: good.planes_offset + 2, ..good }), + ("packet short", DecodeGeometry { packet_bytes: good.packet_bytes - 4, ..good }), + ("scales odd", DecodeGeometry { scales_offset: 65, ..good }), ]; for (name, bad) in cases { assert!(bad.validate().is_err(), "{name}"); @@ -154,11 +103,7 @@ fn validate_rejects_each_corruption() { #[test] fn multiply_geometry_bounds() { - let ok = MultiplyGeometry { - columns: 2048, - rows: 512, - tokens: 8, - }; + let ok = MultiplyGeometry { columns: 2048, rows: 512, tokens: 8 }; ok.validate().unwrap(); assert_eq!(ok.weights_len(), 2048 * 512 * 4); assert_eq!(ok.input_len(), 2048 * 8 * 4); @@ -168,16 +113,8 @@ fn multiply_geometry_bounds() { MultiplyGeometry { rows: 0, ..ok }, MultiplyGeometry { tokens: 0, ..ok }, MultiplyGeometry { tokens: 9, ..ok }, - MultiplyGeometry { - columns: (MAX_COLUMNS + 1) as u32, - rows: 1, - tokens: 1, - }, - MultiplyGeometry { - columns: 4096, - rows: 4097, - tokens: 1, - }, + MultiplyGeometry { columns: (MAX_COLUMNS + 1) as u32, rows: 1, tokens: 1 }, + MultiplyGeometry { columns: 4096, rows: 4097, tokens: 1 }, ] { assert!(bad.validate().is_err(), "{bad:?}"); } @@ -185,32 +122,14 @@ fn multiply_geometry_bounds() { #[test] fn expert_shape_requires_consistent_single_token_matrices() { - let m = |columns, rows| MultiplyGeometry { - columns, - rows, - tokens: 1, - }; - let shape = - ExpertShape::from_matrices(&m(2560, 640), &m(2560, 640), &m(640, 2560)).unwrap(); - assert_eq!( - shape, - ExpertShape { - hidden: 2560, - ff: 640 - } - ); + let m = |columns, rows| MultiplyGeometry { columns, rows, tokens: 1 }; + let shape = ExpertShape::from_matrices(&m(2560, 640), &m(2560, 640), &m(640, 2560)).unwrap(); + assert_eq!(shape, ExpertShape { hidden: 2560, ff: 640 }); let bad: [(MultiplyGeometry, MultiplyGeometry, MultiplyGeometry); 5] = [ (m(2560, 640), m(2560, 641), m(640, 2560)), (m(2560, 640), m(2560, 640), m(641, 2560)), (m(2560, 640), m(2560, 640), m(640, 2561)), - ( - m(2560, 640), - m(2560, 640), - MultiplyGeometry { - tokens: 2, - ..m(640, 2560) - }, - ), + (m(2560, 640), m(2560, 640), MultiplyGeometry { tokens: 2, ..m(640, 2560) }), (m(0, 640), m(0, 640), m(640, 0)), ]; for (g, u, d) in bad { @@ -229,8 +148,8 @@ fn status_word_is_fail_closed() { #[test] fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() { use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, - without_terminator, + assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, + with_embedded_nul, without_terminator, }; let ptx = KAR_DECODE_LEVELS_PTX; // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is @@ -243,10 +162,7 @@ fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() { assert_nvcc_13_2_86("kar_decode_levels", ptx); assert_ne!(KAR_DECODE_LEVELS_PIN.source_sha256, [0; 32]); assert_ne!(KAR_DECODE_LEVELS_PIN.ptx_sha256, [0; 32]); - assert_eq!( - KAR_DECODE_LEVELS_PIN.ptx_sha256, - qwen_ffi::sha256(&ptx[..ptx.len() - 1]) - ); + assert_eq!(KAR_DECODE_LEVELS_PIN.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1])); assert_eq!( KAR_DECODE_LEVELS_PIN.source_sha256, qwen_ffi::sha256(include_str!("../kar_decode_levels.cu").as_bytes()) @@ -270,36 +186,21 @@ fn sealed_ptx_matches_its_pin_and_every_admission_deviation_fails() { // zero PTX pin still refuses, and a wrong digest refuses. let digest = qwen_ffi::sha256(&ptx[..ptx.len() - 1]); for pin in [ - PtxPin { - source_sha256: [0; 32], - ptx_sha256: digest, - }, - PtxPin { - source_sha256: [1; 32], - ptx_sha256: [0; 32], - }, - PtxPin { - source_sha256: [1; 32], - ptx_sha256: [2; 32], - }, + PtxPin { source_sha256: [0; 32], ptx_sha256: digest }, + PtxPin { source_sha256: [1; 32], ptx_sha256: [0; 32] }, + PtxPin { source_sha256: [1; 32], ptx_sha256: [2; 32] }, ] { assert_eq!(admit_ptx(ptx, &pin), Err(KarDecodeError::Unpinned)); } // Only a complete matching pin (a test-local one) admits these bytes. - let matching = PtxPin { - source_sha256: [1; 32], - ptx_sha256: digest, - }; + let matching = PtxPin { source_sha256: [1; 32], ptx_sha256: digest }; assert_eq!(admit_ptx(ptx, &matching), Ok(())); // Malformed bytes (embedded NUL, no terminator, non-ASCII) never admit. static EMBEDDED_NUL: [u8; 4] = [b'a', 0, b'b', 0]; static NO_TERMINATOR: [u8; 3] = *b"abc"; static NON_ASCII: [u8; 3] = [b'a', 0xc3, 0]; for bytes in [&EMBEDDED_NUL[..], &NO_TERMINATOR[..], &NON_ASCII[..]] { - let pin = PtxPin { - source_sha256: [1; 32], - ptx_sha256: qwen_ffi::sha256(&bytes[..bytes.len() - 1]), - }; + let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&bytes[..bytes.len() - 1]) }; assert!(admit_ptx(bytes, &pin).is_err()); } } @@ -318,10 +219,7 @@ fn rust_constants_match_the_cuda_source() { ("kBookRegionBytes", BOOK_REGION_BYTES.to_string()), ("kStatusBadArgument", STATUS_BAD_ARGUMENT.to_string()), ("kStatusNonfiniteInput", STATUS_NONFINITE_INPUT.to_string()), - ( - "kStatusNonfiniteOutput", - STATUS_NONFINITE_OUTPUT.to_string(), - ), + ("kStatusNonfiniteOutput", STATUS_NONFINITE_OUTPUT.to_string()), ] { let needle = format!("{name} = {value};"); assert!(source.contains(&needle), "missing `{needle}`"); diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu.rs b/crates/cuda-driver/src/kar_decode_levels_gpu.rs index 8f30ef84..d623a4ff 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu.rs @@ -22,9 +22,9 @@ use crate::{ Context, DeviceBuffer, Error, combine, ffi, kar_decode_levels::{ - BLOCK_THREADS, DecodeGeometry, ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU, ExpertShape, - KAR_DECODE_LEVELS_PIN, KAR_DECODE_LEVELS_PTX, KarDecodeError, KarLevelsKernels, - MultiplyGeometry, Result, STATUS_BYTES, admit_ptx, check_status, + BLOCK_THREADS, DecodeGeometry, ENTRY_DECODE, ENTRY_MULTIPLY, ENTRY_SWIGLU, ExpertShape, KAR_DECODE_LEVELS_PIN, + KAR_DECODE_LEVELS_PTX, KarDecodeError, KarLevelsKernels, MultiplyGeometry, Result, STATUS_BYTES, admit_ptx, + check_status, }, }; use std::rc::Rc; @@ -52,16 +52,16 @@ pub struct KarMatrix<'a> { pub packet: &'a [u8], } +mod f32_bytes_fn; mod impl_context; mod impl_kardecodelevels; -mod f32_bytes_fn; -#[allow(unused_imports)] -use f32_bytes_fn::f32_bytes; #[allow(unused_imports)] use f32_bytes_fn::download; #[allow(unused_imports)] +use f32_bytes_fn::f32_bytes; +#[allow(unused_imports)] use f32_bytes_fn::failure; #[allow(unused_imports)] -use f32_bytes_fn::release_all; -#[allow(unused_imports)] use f32_bytes_fn::finite_f32; +#[allow(unused_imports)] +use f32_bytes_fn::release_all; diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu/f32_bytes_fn.rs b/crates/cuda-driver/src/kar_decode_levels_gpu/f32_bytes_fn.rs index 18d5f51e..70375c22 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu/f32_bytes_fn.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu/f32_bytes_fn.rs @@ -3,16 +3,13 @@ #[allow(unused_imports)] use super::*; - pub(super) fn f32_bytes(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } pub(super) fn download(buffer: &DeviceBuffer<'_>, len: usize) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(len) - .map_err(|_| Error::HostAllocation)?; + bytes.try_reserve_exact(len).map_err(|_| Error::HostAllocation)?; bytes.resize(len, 0); buffer.copy_to(&mut bytes)?; Ok(bytes) @@ -20,9 +17,7 @@ pub(super) fn download(buffer: &DeviceBuffer<'_>, len: usize) -> Result> /// A primary driver failure plus the outcome of the mandatory context restore. pub(super) fn failure(primary: Error, restore: DriverResult<()>) -> KarDecodeError { - combine::<()>(Err(primary), restore) - .expect_err("a primary failure always stays an error") - .into() + combine::<()>(Err(primary), restore).expect_err("a primary failure always stays an error").into() } pub(super) fn release_all(buffers: [DeviceBuffer<'_>; N]) -> Result<()> { @@ -34,12 +29,7 @@ pub(super) fn release_all(buffers: [DeviceBuffer<'_>; N]) -> Res } pub(super) fn finite_f32(bytes: &[u8]) -> Result> { - let values: Vec = bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect(); + let values: Vec = bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)).collect(); if values.iter().any(|v| !v.is_finite()) { return Err(KarDecodeError::NonFinite); } diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_context.rs b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_context.rs index c85efe6f..b8683d3a 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_context.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_context.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Context<'_> { /// Admit the PTX against the pin, then load and cache the module once. /// Refuses (`Unpinned`) without touching the driver while the pin is zero. @@ -23,25 +22,16 @@ impl Context<'_> { }; let resolved = api .kar_levels_function(module, ENTRY_DECODE) - .and_then(|decode| { - api.kar_levels_function(module, ENTRY_MULTIPLY) - .map(|multiply| (decode, multiply)) - }) + .and_then(|decode| api.kar_levels_function(module, ENTRY_MULTIPLY).map(|multiply| (decode, multiply))) .and_then(|(decode, multiply)| { - api.kar_levels_function(module, ENTRY_SWIGLU) - .map(|swiglu| (decode, multiply, swiglu)) + api.kar_levels_function(module, ENTRY_SWIGLU).map(|swiglu| (decode, multiply, swiglu)) }); match resolved { Ok((decode, multiply, swiglu)) => { // Nothing is published until every entry resolves and the // context restore succeeds (a failed pop poisons the context). guard.finish()?; - let kernels = KarLevelsKernels { - module, - decode, - multiply, - swiglu, - }; + let kernels = KarLevelsKernels { module, decode, multiply, swiglu }; self.kar_levels.set(Some(kernels)); Ok(kernels) } @@ -51,8 +41,7 @@ impl Context<'_> { self.poisoned.set(true); std::mem::forget(Rc::clone(api)); } - let primary = - combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); + let primary = combine::<()>(Err(error), cleanup).expect_err("resolution failure is primary"); Err(failure(primary, guard.finish())) } } diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs index 1871edda..5efba328 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu/impl_kardecodelevels.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'c> KarDecodeLevels<'c> { /// Load (once) and return the cached program. Fails closed with /// `Unpinned` while the PTX pin is zero. @@ -27,22 +26,11 @@ impl<'c> KarDecodeLevels<'c> { return Err(Error::ContextMismatch.into()); } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - if bytes == 0 - || if exact { - buffer.bytes != bytes - } else { - buffer.bytes < bytes - } - { - return Err(KarDecodeError::Invalid( - "KAR buffer is smaller than (or differs from) the geometry requires", - )); + if bytes == 0 || if exact { buffer.bytes != bytes } else { buffer.bytes < bytes } { + return Err(KarDecodeError::Invalid("KAR buffer is smaller than (or differs from) the geometry requires")); } handle.validate_projection_extent(buffer.bytes, 16)?; - Ok(Admitted { - handle, - bytes: buffer.bytes, - }) + Ok(Admitted { handle, bytes: buffer.bytes }) } pub(super) fn disjoint(buffers: &[&Admitted]) -> Result<()> { @@ -68,26 +56,18 @@ impl<'c> KarDecodeLevels<'c> { let guard = context.enter()?; let mut launch = Ok(()); for (function, grid, block, arguments) in &mut launches { - launch = context - .driver - .api - .launch_kar_levels(*function, *grid, *block, arguments); + launch = context.driver.api.launch_kar_levels(*function, *grid, *block, arguments); if launch.is_err() { break; } } // Single drain; on sync/restore uncertainty the context is poisoned and // the argument tables are forgotten (leaked), not freed. - context - .complete_launch(launch, launches, guard) - .map_err(Into::into) + context.complete_launch(launch, launches, guard).map_err(Into::into) } pub(super) fn arguments(pointers: &[&Admitted], scalars: &[u32]) -> Result { - let mut all: Vec = pointers - .iter() - .map(|p| ffi::KarArgument::Pointer(p.handle)) - .collect(); + let mut all: Vec = pointers.iter().map(|p| ffi::KarArgument::Pointer(p.handle)).collect(); all.extend(scalars.iter().copied().map(ffi::KarArgument::Scalar)); Ok(ffi::KarLevelsArgs::new(&all)?) } @@ -160,9 +140,7 @@ impl<'c> KarDecodeLevels<'c> { decode.validate()?; multiply.validate()?; if u64::from(decode.count) != u64::from(multiply.columns) * u64::from(multiply.rows) { - return Err(KarDecodeError::Invalid( - "KAR decode window is not exactly columns * rows weights", - )); + return Err(KarDecodeError::Invalid("KAR decode window is not exactly columns * rows weights")); } let packet = self.admit(packet, decode.packet_len(), false)?; let weights = self.admit(weights, multiply.weights_len(), false)?; @@ -198,9 +176,7 @@ impl<'c> KarDecodeLevels<'c> { pub fn decode_to_host(&self, geometry: &DecodeGeometry, packet: &[u8]) -> Result> { geometry.validate()?; if packet.len() != geometry.packet_len() { - return Err(KarDecodeError::Invalid( - "KAR packet byte length differs from the geometry", - )); + return Err(KarDecodeError::Invalid("KAR packet byte length differs from the geometry")); } let context = self.context; let mut packet_buffer = context.allocate(geometry.packet_len())?; @@ -208,12 +184,7 @@ impl<'c> KarDecodeLevels<'c> { let mut status_buffer = context.allocate(STATUS_BYTES)?; packet_buffer.copy_from(packet)?; status_buffer.copy_from(&[0; STATUS_BYTES])?; - self.decode( - &packet_buffer, - &mut output_buffer, - &mut status_buffer, - geometry, - )?; + self.decode(&packet_buffer, &mut output_buffer, &mut status_buffer, geometry)?; let flags = self.read_status(&status_buffer)?; let bytes = download(&output_buffer, geometry.output_len())?; release_all([packet_buffer, output_buffer, status_buffer])?; @@ -236,9 +207,7 @@ impl<'c> KarDecodeLevels<'c> { || input.len() * 4 != multiply.input_len() || input.iter().any(|v| !v.is_finite()) { - return Err(KarDecodeError::Invalid( - "KAR packet or finite input length differs from the geometry", - )); + return Err(KarDecodeError::Invalid("KAR packet or finite input length differs from the geometry")); } let context = self.context; let mut packet_buffer = context.allocate(decode.packet_len())?; @@ -260,13 +229,7 @@ impl<'c> KarDecodeLevels<'c> { )?; let flags = self.read_status(&status_buffer)?; let bytes = download(&output_buffer, multiply.output_len())?; - release_all([ - packet_buffer, - weights, - input_buffer, - output_buffer, - status_buffer, - ])?; + release_all([packet_buffer, weights, input_buffer, output_buffer, status_buffer])?; check_status(flags)?; finite_f32(&bytes) } @@ -283,31 +246,21 @@ impl<'c> KarDecodeLevels<'c> { down: &KarMatrix<'_>, input: &[f32], ) -> Result> { - let ExpertShape { hidden, ff } = - ExpertShape::from_matrices(&gate.shape, &up.shape, &down.shape)?; + let ExpertShape { hidden, ff } = ExpertShape::from_matrices(&gate.shape, &up.shape, &down.shape)?; for matrix in [gate, up, down] { matrix.geometry.validate()?; matrix.shape.validate()?; if matrix.packet.len() != matrix.geometry.packet_len() - || u64::from(matrix.geometry.count) - != u64::from(matrix.shape.columns) * u64::from(matrix.shape.rows) + || u64::from(matrix.geometry.count) != u64::from(matrix.shape.columns) * u64::from(matrix.shape.rows) { - return Err(KarDecodeError::Invalid( - "KAR expert packet or window differs from its matrix shape", - )); + return Err(KarDecodeError::Invalid("KAR expert packet or window differs from its matrix shape")); } } if input.len() != hidden as usize || input.iter().any(|v| !v.is_finite()) { - return Err(KarDecodeError::Invalid( - "KAR expert input must be exactly `hidden` finite values", - )); + return Err(KarDecodeError::Invalid("KAR expert input must be exactly `hidden` finite values")); } let context = self.context; - let weights_bytes = [gate, up, down] - .iter() - .map(|m| m.shape.weights_len()) - .max() - .unwrap_or(0); + let weights_bytes = [gate, up, down].iter().map(|m| m.shape.weights_len()).max().unwrap_or(0); let (hidden_bytes, ff_bytes) = (hidden as usize * 4, ff as usize * 4); let mut packets = [ context.allocate(gate.geometry.packet_len())?, diff --git a/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs b/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs index 4f344eaf..a7c5e9a2 100644 --- a/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs +++ b/crates/cuda-driver/src/kar_decode_levels_gpu_smoke.rs @@ -54,9 +54,7 @@ struct Truth { fn truth(rng: &mut Rng, level: u32, group: u32, elements: usize) -> Truth { let groups = elements.div_ceil(group as usize); Truth { - codes: (0..elements) - .map(|_| (rng.next() % (1 << level)) as u32) - .collect(), + codes: (0..elements).map(|_| (rng.next() % (1 << level)) as u32).collect(), scales: (0..groups).map(|_| rng.finite_f16()).collect(), book: (0..1 << level).map(|_| rng.finite_f16()).collect(), group, @@ -65,10 +63,7 @@ fn truth(rng: &mut Rng, level: u32, group: u32, elements: usize) -> Truth { impl Truth { fn expected(&self, start: usize, count: usize) -> Vec { (start..start + count) - .map(|p| { - f16_to_f32(self.book[self.codes[p] as usize]) - * f16_to_f32(self.scales[p / self.group as usize]) - }) + .map(|p| f16_to_f32(self.book[self.codes[p] as usize]) * f16_to_f32(self.scales[p / self.group as usize])) .collect() } /// Pack exactly the window the geometry describes, MSB plane first. @@ -92,8 +87,7 @@ impl Truth { let code = self.codes.get(p).copied().unwrap_or(0); value |= ((code >> (level - 1 - plane)) & 1) << bit; } - let at = g.planes_offset as usize - + (plane as usize * g.plane_stride_words as usize + word) * 4; + let at = g.planes_offset as usize + (plane as usize * g.plane_stride_words as usize + word) * 4; packet[at..at + 4].copy_from_slice(&value.to_le_bytes()); } } @@ -129,11 +123,7 @@ fn kar_levels_device_decode_matches_cpu_for_levels_2_to_5() { let g = DecodeGeometry::for_window(level, group, start as u64, count as u64).unwrap(); let packet = t.packet(level, &g, start); let got = program.decode_to_host(&g, &packet).unwrap(); - assert_eq!( - bits(&got), - bits(&t.expected(start, count)), - "L{level} g{group} {start}+{count}" - ); + assert_eq!(bits(&got), bits(&t.expected(start, count)), "L{level} g{group} {start}+{count}"); windows += 1; } } @@ -146,17 +136,9 @@ fn kar_levels_device_decode_matches_cpu_for_levels_2_to_5() { let t = truth(&mut rng, level, 32, (columns * rows) as usize); let g = DecodeGeometry::for_window(level, 32, 0, u64::from(columns * rows)).unwrap(); let packet = t.packet(level, &g, 0); - let m = MultiplyGeometry { - columns, - rows, - tokens, - }; - let input: Vec = (0..columns * tokens) - .map(|i| ((i % 23) as f32 - 11.0) / 8.0) - .collect(); - let got = program - .decode_multiply_to_host(&g, &m, &packet, &input) - .unwrap(); + let m = MultiplyGeometry { columns, rows, tokens }; + let input: Vec = (0..columns * tokens).map(|i| ((i % 23) as f32 - 11.0) / 8.0).collect(); + let got = program.decode_multiply_to_host(&g, &m, &packet, &input).unwrap(); let weights = t.expected(0, (columns * rows) as usize); let mut want = vec![0f32; (rows * tokens) as usize]; for token in 0..tokens as usize { @@ -166,8 +148,7 @@ fn kar_levels_device_decode_matches_cpu_for_levels_2_to_5() { let mut sum = 0f32; let mut c = lane; while c < columns as usize { - sum += - weights[row * columns as usize + c] * input[token * columns as usize + c]; + sum += weights[row * columns as usize + c] * input[token * columns as usize + c]; c += 256; } *slot = sum; @@ -191,24 +172,15 @@ fn kar_levels_device_decode_matches_cpu_for_levels_2_to_5() { t.scales[1] = 0x7c00; // Inf scale used by elements 32..64 let g = DecodeGeometry::for_window(level, 32, 0, 64).unwrap(); let packet = t.packet(level, &g, 0); - assert_eq!( - program.decode_to_host(&g, &packet), - Err(KarDecodeError::DeviceStatus(STATUS_NONFINITE_INPUT)) - ); + assert_eq!(program.decode_to_host(&g, &packet), Err(KarDecodeError::DeviceStatus(STATUS_NONFINITE_INPUT))); // A corrupt window (words too few) is refused on the host before launch. let mut bad = g; bad.window_words -= 1; - assert!(matches!( - program.decode_to_host(&bad, &packet), - Err(KarDecodeError::Invalid(_)) - )); + assert!(matches!(program.decode_to_host(&bad, &packet), Err(KarDecodeError::Invalid(_)))); // The context is still healthy after the fail-closed paths. let ok = truth(&mut rng, level, 32, 64); let packet = ok.packet(level, &g, 0); - assert_eq!( - bits(&program.decode_to_host(&g, &packet).unwrap()), - bits(&ok.expected(0, 64)) - ); + assert_eq!(bits(&program.decode_to_host(&g, &packet).unwrap()), bits(&ok.expected(0, 64))); assert_eq!(ctx.allocated_bytes(), 0, "scratch is released"); program.close().unwrap(); ctx.close().unwrap(); @@ -232,61 +204,31 @@ fn kar_levels_expert_mlp_matches_cpu_within_tolerance() { let mut cpu_weights = Vec::new(); let mut packets = Vec::new(); let mut geometries = Vec::new(); - for (level, count) in [ - (l_gate, hidden * ff), - (l_up, hidden * ff), - (l_down, hidden * ff), - ] { + for (level, count) in [(l_gate, hidden * ff), (l_up, hidden * ff), (l_down, hidden * ff)] { let t = truth(&mut rng, level, 32, count as usize); let g = DecodeGeometry::for_window(level, 32, 0, u64::from(count)).unwrap(); packets.push(t.packet(level, &g, 0)); cpu_weights.push(t.expected(0, count as usize)); geometries.push(g); } - let input: Vec = (0..hidden) - .map(|i| ((i % 13) as f32 - 6.0) / 16.0) - .collect(); + let input: Vec = (0..hidden).map(|i| ((i % 13) as f32 - 6.0) / 16.0).collect(); let shapes = [ - MultiplyGeometry { - columns: hidden, - rows: ff, - tokens: 1, - }, - MultiplyGeometry { - columns: hidden, - rows: ff, - tokens: 1, - }, - MultiplyGeometry { - columns: ff, - rows: hidden, - tokens: 1, - }, + MultiplyGeometry { columns: hidden, rows: ff, tokens: 1 }, + MultiplyGeometry { columns: hidden, rows: ff, tokens: 1 }, + MultiplyGeometry { columns: ff, rows: hidden, tokens: 1 }, ]; - let matrix = |i: usize| KarMatrix { - geometry: geometries[i], - shape: shapes[i], - packet: &packets[i], - }; - let got = program - .expert_mlp_to_host(&matrix(0), &matrix(1), &matrix(2), &input) - .unwrap(); + let matrix = |i: usize| KarMatrix { geometry: geometries[i], shape: shapes[i], packet: &packets[i] }; + let got = program.expert_mlp_to_host(&matrix(0), &matrix(1), &matrix(2), &input).unwrap(); // f64 reference of silu(gate x) * (up x), then down; tolerance is relative // to the L1 mass of each output (binary32 sums plus device expf), a sanity // bound and not a bit claim. let matvec = |w: &[f32], x: &[f64], cols: usize| -> Vec { - w.chunks(cols) - .map(|row| row.iter().zip(x).map(|(a, b)| f64::from(*a) * b).sum()) - .collect() + w.chunks(cols).map(|row| row.iter().zip(x).map(|(a, b)| f64::from(*a) * b).sum()).collect() }; let x: Vec = input.iter().map(|v| f64::from(*v)).collect(); let g = matvec(&cpu_weights[0], &x, hidden as usize); let u = matvec(&cpu_weights[1], &x, hidden as usize); - let act: Vec = g - .iter() - .zip(&u) - .map(|(g, u)| g / (1.0 + (-g).exp()) * u) - .collect(); + let act: Vec = g.iter().zip(&u).map(|(g, u)| g / (1.0 + (-g).exp()) * u).collect(); let want = matvec(&cpu_weights[2], &act, ff as usize); for (row, (a, b)) in got.iter().zip(&want).enumerate() { let mass: f64 = cpu_weights[2][row * ff as usize..(row + 1) * ff as usize] @@ -294,10 +236,7 @@ fn kar_levels_expert_mlp_matches_cpu_within_tolerance() { .zip(&act) .map(|(w, v)| (f64::from(*w) * v).abs()) .sum(); - assert!( - (f64::from(*a) - b).abs() <= mass * 1e-4 + 1e-6, - "row {row}: {a} vs {b}" - ); + assert!((f64::from(*a) - b).abs() <= mass * 1e-4 + 1e-6, "row {row}: {a} vs {b}"); } assert_eq!(ctx.allocated_bytes(), 0, "scratch is released"); println!("KAR_LEVELS expert_mlp rows={hidden} ff={ff} levels=3/4/2 tolerance=1e-4_L1"); diff --git a/crates/cuda-driver/src/kv_stream_gpu.rs b/crates/cuda-driver/src/kv_stream_gpu.rs index 071384ef..082dc7f6 100644 --- a/crates/cuda-driver/src/kv_stream_gpu.rs +++ b/crates/cuda-driver/src/kv_stream_gpu.rs @@ -59,15 +59,20 @@ fn int8_kv_append_kernels_match_the_original_host_reference_bit_exactly() { // 1. prompt path (`leleka_qsa_kv_append`): resident slots, identity stage and identity host copy { - let m = load(c, include_bytes!("qsa_prompt_kv.ptx"), &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"]) - .expect("prompt KV asset"); + let m = load( + c, + include_bytes!("qsa_prompt_kv.ptx"), + &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"], + ) + .expect("prompt KV asset"); let kb = upload(c, &f32s(&k)).unwrap(); let vb = upload(c, &f32s(&v)).unwrap(); let tb = upload(c, &i32s(&table)).unwrap(); let res: Vec<_> = fill(resident_pages).iter().map(|b| upload(c, b).unwrap()).collect(); let stage: Vec<_> = fill(identity_pages).iter().map(|b| upload(c, b).unwrap()).collect(); let host: Vec<_> = fill(identity_pages).iter().map(|b| upload(c, b).unwrap()).collect(); - let mut args = vec![Arg::U64(addr(&kb)), Arg::U64(addr(&vb)), Arg::I64(pos0 as i64), Arg::U64(addr(&tb)), Arg::I64(4)]; + let mut args = + vec![Arg::U64(addr(&kb)), Arg::U64(addr(&vb)), Arg::I64(pos0 as i64), Arg::U64(addr(&tb)), Arg::I64(4)]; args.extend(res.iter().chain(&stage).chain(&host).map(|b| Arg::U64(addr(b)))); launch(c, &m, &mut w, 1, [t as u32, 2, 8], 64, args).expect("prompt append"); for i in 0..4 { @@ -123,7 +128,9 @@ fn int8_kv_append_kernels_match_the_original_host_reference_bit_exactly() { w.close().unwrap(); assert_eq!(context.allocated_bytes(), 0); context.close().unwrap(); - eprintln!("kv-int8 append: prompt and window kernels bit-exact vs the Original reference over {compared} bytes ({t} rows, 7 group kinds)"); + eprintln!( + "kv-int8 append: prompt and window kernels bit-exact vs the Original reference over {compared} bytes ({t} rows, 7 group kinds)" + ); } #[test] @@ -182,8 +189,12 @@ fn streamed_attention_equals_fully_resident_attention_with_a_20480_cell_window() resolver.reset(&mut w, addr(&table)).expect("reset"); let res_addr: [u64; 4] = std::array::from_fn(|i| addr(&resident[i])); - let attention = load(c, include_bytes!("mtp_original_full_attention.ptx"), &[c"leleka_qsa_decode_chunk", c"leleka_qsa_decode_merge"]) - .expect("attention asset"); + let attention = load( + c, + include_bytes!("mtp_original_full_attention.ptx"), + &[c"leleka_qsa_decode_chunk", c"leleka_qsa_decode_merge"], + ) + .expect("attention asset"); let chunks = CAP.div_ceil(CHUNK); let stride = chunks * HEADS * HD + 2 * chunks * HEADS; let mut ids = c.allocate(3 * CAP * 4).unwrap(); @@ -241,20 +252,22 @@ fn streamed_attention_equals_fully_resident_attention_with_a_20480_cell_window() let qv: Vec = (0..3 * HEADS * HD).map(|_| (rng.unit() - 0.5) * 4.0).collect(); q.copy_from(&f32s(&qv)).unwrap(); - resolver - .resolve(&mut w, addr(&table), ids_at, steps_at, n, host, res_addr) - .expect("resolve"); + resolver.resolve(&mut w, addr(&table), ids_at, steps_at, n, host, res_addr).expect("resolve"); calls += 1; // every block the call named is resident and holds the host bytes; nothing overflowed let map = table.copy_to_owned(geometry.page_table_bytes()).unwrap(); let map: Vec = map.chunks_exact(4).map(|b| i32::from_le_bytes(b.try_into().unwrap())).collect(); - let pools: Vec> = resident.iter().zip(PAGE).map(|(b, len)| b.copy_to_owned(len * slots).unwrap()).collect(); + let pools: Vec> = + resident.iter().zip(PAGE).map(|(b, len)| b.copy_to_owned(len * slots).unwrap()).collect(); for &b in &named { let s = map[b]; assert!(s >= 0 && (s as usize) < slots, "call {call}: block {b} not resident ({s})"); for i in 0..4 { let (len, s) = (PAGE[i], s as usize); - assert!(pools[i][s * len..(s + 1) * len] == image[i][b * len..(b + 1) * len], "call {call}: block {b} run {i}"); + assert!( + pools[i][s * len..(s + 1) * len] == image[i][b * len..(b + 1) * len], + "call {call}: block {b} run {i}" + ); } checked_blocks += 1; } @@ -301,20 +314,20 @@ fn streamed_attention_equals_fully_resident_attention_with_a_20480_cell_window() mod impl_rng; #[allow(unused_imports)] -use impl_rng::upload; -#[allow(unused_imports)] use impl_rng::addr; #[allow(unused_imports)] +use impl_rng::expected; +#[allow(unused_imports)] use impl_rng::f32s; #[allow(unused_imports)] +use impl_rng::group; +#[allow(unused_imports)] use impl_rng::i32s; #[allow(unused_imports)] use impl_rng::launch; #[allow(unused_imports)] use impl_rng::load; #[allow(unused_imports)] -use impl_rng::group; -#[allow(unused_imports)] -use impl_rng::expected; -#[allow(unused_imports)] use impl_rng::selection; +#[allow(unused_imports)] +use impl_rng::upload; diff --git a/crates/cuda-driver/src/launch_ex.rs b/crates/cuda-driver/src/launch_ex.rs index 0f844e80..8aa4a5c0 100644 --- a/crates/cuda-driver/src/launch_ex.rs +++ b/crates/cuda-driver/src/launch_ex.rs @@ -31,7 +31,8 @@ pub(crate) struct LaunchConfig { pub(crate) attrs: *mut LaunchAttribute, pub(crate) num_attrs: u32, } -pub(crate) type LaunchEx = unsafe extern "C" fn(*const LaunchConfig, *mut c_void, *mut *mut c_void, *mut *mut c_void) -> c_int; +pub(crate) type LaunchEx = + unsafe extern "C" fn(*const LaunchConfig, *mut c_void, *mut *mut c_void, *mut *mut c_void) -> c_int; pub(crate) type FuncSetAttribute = unsafe extern "C" fn(*mut c_void, c_int, c_int) -> c_int; #[cfg(test)] diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index 52fb2812..962bbfcf 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -27,22 +27,27 @@ pub(crate) use bringup_trace; /// deadlock). Elsewhere the guard does nothing. pub struct PromptSyncTrace(()); -use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc}; +use std::{ + cell::{Cell, RefCell}, + fmt, + marker::PhantomData, + rc::Rc, +}; +pub mod compute_drain; +mod device_slab; #[allow(unsafe_code)] mod ffi; -pub mod compute_drain; pub mod vram_ledger; -mod device_slab; pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats}; -pub mod nvml; mod deferred_status; +pub mod nvml; #[allow(unsafe_code)] mod original_gpu_schedule; pub use original_gpu_schedule::{ - OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph, - OriginalGpuStream, OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, - OriginalGraphResources, OriginalStreamKind, OriginalWait, + OriginalCapture, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, OriginalGpuGraph, OriginalGpuStream, + OriginalGraphFlight, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind, + OriginalWait, }; mod original_expert_cache; mod original_expert_slots; @@ -50,9 +55,7 @@ pub use original_expert_cache::OriginalExpertCache; mod original_moe_prompt_device; pub use original_moe_prompt_device::{OriginalMoePromptDevice, OriginalMoePromptLayer}; mod original_prefill_arena; -pub use original_prefill_arena::{ - OriginalPrefillArena, OriginalPromptLeaseIdentity, OriginalPromptRows, -}; +pub use original_prefill_arena::{OriginalPrefillArena, OriginalPromptLeaseIdentity, OriginalPromptRows}; mod original_prefill_layout; pub use original_prefill_layout::{ OriginalPrefillLayout, PrefillKvStage, PrefillLayoutOptions, PrefillPhase, PrefillSpan, @@ -69,53 +72,37 @@ pub use routed_stage_finite_guard::{RoutedFiniteStage, RoutedStageFiniteGuard}; mod gr_read_guard; mod mmq; mod mmq_native; +pub(crate) use mmq::resident::original_group::prefetch_point; pub use mmq::resident::original_group::{ OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes, }; -pub(crate) use mmq::resident::original_group::prefetch_point; -pub use mmq::resident::{ - FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace, -}; +pub use mmq::resident::{FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace}; pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqWeights}; use mmq_native::NativeWeights; mod moe_group_down_columns; mod moe_group_projection; mod mtp_dense_kv; mod original_mtp_actor; +mod original_mtp_bank; mod original_mtp_coupled; mod original_mtp_loader; mod original_mtp_rt; -mod original_mtp_bank; +pub use original_mtp_actor::{ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; pub use original_mtp_bank::{ - OriginalMtpLoadFailure, original_mtp_draft_vocab_bytes, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind, -}; -pub use original_mtp_actor::{ - ActorRefusal as OriginalMtpActorRefusal, DraftSettings as OriginalMtpDraftSettings, + OriginalMtpLoadFailure, OriginalMtpRtBank, OriginalMtpRtTensor, OriginalMtpTensorKind, + original_mtp_draft_vocab_bytes, }; pub use original_mtp_loader::{ - CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat, - KvMode as OriginalMtpKvMode, KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError, - OriginalMtpCapture, OriginalMtpKvStartup, OriginalMtpLoadPlan, original_mtp_bind_reserve, - WeightBankPlan as OriginalMtpWeightBankPlan, + CoupledPlan as OriginalMtpCoupledPlan, KvFormat as OriginalMtpKvFormat, KvMode as OriginalMtpKvMode, + KvPlan as OriginalMtpKvPlan, LoaderError as OriginalMtpPlanError, OriginalMtpCapture, OriginalMtpKvStartup, + OriginalMtpLoadPlan, WeightBankPlan as OriginalMtpWeightBankPlan, original_mtp_bind_reserve, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_mtp_actor::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_mtp_draft_head; mod original_mtp_draft_vocab; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_mtp_draft_head::OriginalMtpDraftHead; mod original_session_state; pub use original_session_state::{ @@ -126,82 +113,59 @@ mod qwen_dispatch; pub use qwen_dispatch::gr_batch_read::{GrMicroValues, GrMicrobatchRead}; mod qsa_selected_kv; mod serving_context; -pub use serving_context::{ - KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, - configure_kv_resident, configure_serving_context, kv_resident_cells, - serving_context, -}; -pub use mtp_dense_kv::MtpDenseKvRing; pub use mtp_dense_kv::MTP_ORIGINAL_WINDOW; +pub use mtp_dense_kv::MtpDenseKvRing; pub use mtp_dense_kv::{ - CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, - MtpOriginalMixed, MtpOriginalQuery, + CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, MtpOriginalMixed, + MtpOriginalQuery, }; pub use qsa_selected_kv::{QsaSelectedKvProducts, QsaSelectedKvWorkspace}; +pub use serving_context::{ + KV_RESIDENT_DEFAULT_CELLS, KV_RESIDENT_MIN_CELLS, MAX_CONTEXT_CELLS, ServingContext, TRAINED_CONTEXT_CELLS, + configure_kv_resident, configure_serving_context, kv_resident_cells, serving_context, +}; #[allow(unsafe_code)] mod qwen_ffi; -pub mod host_profile; -pub mod experimental; /// Per-command timing of the batched prompt producers (bring-up profiling only). pub mod command_profile; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +pub mod experimental; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub mod experimental_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "experimental_gpu_smoke.rs"] mod experimental_gpu_smoke; +pub mod host_profile; pub mod kar_decode_levels; // Pure selection/geometry half of the Original QSA prompt-attention variants (any host). pub mod qsa_prompt_attention_select; // Pure scheduling model of the Original Prefill::run (expert stream plan, PLE read-ahead, fusion, hand-off). pub mod original_prefill_schedule; // Pure halves of small Original kernels/host files: prefill/moe_mmq.cu copy1/strata_q2/iota, core/device.cu. -pub mod mmq_original_prefill_misc; pub mod device_arena; +pub mod mmq_original_prefill_misc; // Pure half of the Original native_flash_attn.cu (admission, geometry, step rule, FP64 specification). pub mod native_flash_attn; pub mod s_gemv_legacy; // Closed driver programs for native_flash_attn / s_gemv_legacy / device_poison: pins, entry signatures, argument slots (pure half). pub mod closed_kernels; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub mod closed_kernels_gpu; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "closed_kernels_gpu_smoke.rs"] mod closed_kernels_gpu_smoke; -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -mod original_prefill_schedule_crosscheck; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub mod kar_decode_levels_gpu; +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "kar_decode_levels_gpu_smoke.rs"] +mod kar_decode_levels_gpu_smoke; #[cfg(all( test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" + target_pointer_width = "64" ))] -#[path = "kar_decode_levels_gpu_smoke.rs"] -mod kar_decode_levels_gpu_smoke; +mod original_prefill_schedule_crosscheck; // Model-free stress of DMA out of a read-only file mapping that is page-locked in place, under working-set trimming (Windows only). #[cfg(all(test, windows, feature = "cuda-driver", target_pointer_width = "64"))] #[path = "mapped_file_dma_stress_gpu.rs"] @@ -510,33 +474,27 @@ pub use qwen_dispatch::batch_gr_preview::GrBatchModule; mod grouped_down_columns_gpu; pub use qwen_dispatch::qwen_shared_tail::{ - SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion, - SharedTailRefusal, + SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailCompletion, SharedTailRefusal, }; // Additive closed MTP input transport owners. -pub use qwen_dispatch::gdn_closed_queue::{ - GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue, -}; +pub use qwen_dispatch::gdn_closed_queue::{GdnQueueStage, GdnRowCompletion, GdnRowPrefix, GdnRowQueue}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gdn_fused_t1::{ - GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix, - GdnFusedStage, GdnFusedT1, + GDN_FUSED_T1_PERSISTENT_BYTES, GDN_FUSED_T1_STATE_BYTES, GdnFusedCompletion, GdnFusedPrefix, GdnFusedStage, + GdnFusedT1, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gdn_native_batch::{ - GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, - GdnGemm, GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, - OriginalGdnPromptWeights, + GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnBatchCompletion, GdnBatchPrefix, GdnBatchStage, GdnGemm, + GdnNativeFormat, GdnPrefillBatch, GdnStream, GemmShape, OriginalGdnPromptDevice, OriginalGdnPromptWeights, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::moe_prefill_batch::{ - MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, - MoeBatchStage, MoePrefillBatch, MoeRouteBatch, -}; -pub use qwen_dispatch::mtp_input_workspace::{ - MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace, + MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoeBatchCompletion, MoeBatchPrefix, MoeBatchStage, MoePrefillBatch, + MoeRouteBatch, }; +pub use qwen_dispatch::mtp_input_workspace::{MtpInputCompletion, MtpInputPrefix, MtpInputRefusal, MtpInputWorkspace}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub use qwen_dispatch::gr_batch_inject_workspace::{ @@ -547,9 +505,7 @@ pub use qwen_dispatch::gr_batch_inject_workspace::{ #[allow(unsafe_code)] mod api; mod async_owned_copy; -pub use async_owned_copy::{ - CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy, -}; +pub use async_owned_copy::{CompletedOwnedCopy, MAX_ASYNC_COPY_PAIRS, OwnedCopyPairs, OwnedCopyPoll, PendingOwnedCopy}; // Explicit experimental resident pipeline; original entry bodies remain unchanged. mod routed_resident_queue; @@ -572,9 +528,7 @@ pub use qwen_dispatch::gr_native_batch::{GrNativeBatch, GrNativeProfile}; #[allow(unsafe_code)] pub(crate) mod ple_batch_ffi; mod ple_batch_queue; -pub use ple_batch_queue::{ - PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode, -}; +pub use ple_batch_queue::{PLE_BATCH_QUEUE_BYTES, PleBatchCompletion, PleBatchQueue, PleBatchRow, PleBf16Mode}; mod native_batch_workspace; pub use native_batch_workspace::{NATIVE_BATCH_WORKSPACE_BYTES, NativeBatchWorkspace}; @@ -587,8 +541,7 @@ pub use gdn_batch_gemm::NativeGdnGemm; mod qsa_native_batch; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_native_batch::{ - QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, - QsaNativeProjections, + QSA_NATIVE_BATCH_BYTES, QsaNativeBatchWorkspace, QsaNativeKind, QsaNativePacking, QsaNativeProjections, }; // Literal Original QSA prompt index assets share the admitted native stream. @@ -599,9 +552,8 @@ mod qsa_index_ffi; mod qsa_prompt_index; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_prompt_index::{ - OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, - QSA_PROMPT_INDEX_BYTES, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, - QsaPromptSelection, + OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights, QSA_PROMPT_INDEX_BYTES, + QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, QsaPromptSelection, }; // Genuine page4 INT8 owners and literal Original prompt/decode programs. @@ -626,14 +578,13 @@ mod kv_stream_gpu; pub use qsa_native_decode::{QSA_NATIVE_DECODE_BYTES, QsaNativeDecode, QsaNativeDecodeCompletion}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_prompt_attention::{ - QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, - QsaPromptAttentionCompletion, + QSA_PROMPT_ATTENTION_BYTES, QsaAttentionInputs, QsaPromptAttention, QsaPromptAttentionCompletion, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_prompt_kv::{ CompletedQsaKvAppend, QSA_PROMPT_MAPPED_HOST_BYTES, QSA_PROMPT_MAX_SNAPSHOT_METADATA_BYTES, - QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES, QSA_PROMPT_RESIDENT_BYTES, QSA_PROMPT_STAGE_BYTES, - QsaKvInputs, QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, + QSA_PROMPT_MAX_SNAPSHOT_PAYLOAD_BYTES, QSA_PROMPT_RESIDENT_BYTES, QSA_PROMPT_STAGE_BYTES, QsaKvInputs, + QsaKvOwnerId, QsaKvSnapshot, QsaPromptKv, QsaPromptStage, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -642,223 +593,141 @@ pub use qsa_native_decode::OriginalQsaResidentDecodeCompletion; pub use qsa_prompt_attention::OriginalQsaResidentAttention; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_prompt_index::{ - OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, - OriginalQsaResidentPromptDevice, OriginalQsaResidentScalarIndex, - OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, + OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex, OriginalQsaResidentPromptDevice, + OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, OriginalQsaResidentSelection, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub use qsa_prompt_kv::{ - OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, - OriginalQsaResidentTransport, + OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod moe_prompt_packet_copy; mod qsa_native_gate; pub use qsa_native_gate::QsaNativeGate; -mod original_sampler; -mod original_sampler_params; -mod sealed_ptx; #[allow(unsafe_code)] mod arch_ptx; mod gpu_report; +mod original_sampler; +mod original_sampler_params; +mod sealed_ptx; pub use gpu_report::gpu_kernel_report; -#[cfg(feature = "sm86")] -mod sm86_table; #[allow(unsafe_code)] mod original_sampler_ffi; #[allow(unsafe_code)] mod original_sampler_mapped; +#[cfg(feature = "sm86")] +mod sm86_table; pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath}; +mod launch_ex; mod native_prompt_device; mod prefill_stage; -mod launch_ex; mod qsa_cluster; mod qsa_late; +pub use native_prompt_device::{ + OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, OriginalDeviceResidual, + OriginalPleHistory, OriginalPromptDevice, PromptInputStage, +}; +pub use prefill_stage::{ + set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override, +}; +pub use qsa_cluster::{requested as qsa_cluster_requested, set_override as set_qsa_cluster_override}; pub use qsa_late::set_override as set_qsa_late_override; pub use qsa_late::set_topk_override as set_qsa_topk_override; pub use qsa_prompt_kv::set_qsa_prefetch_override; -pub use qsa_cluster::{requested as qsa_cluster_requested, set_override as set_qsa_cluster_override}; -pub use prefill_stage::{set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override}; -pub use native_prompt_device::{ - OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, - OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use mtp_dense_kv::OriginalMtpSkippedPrefix; pub use mtp_dense_kv::{ - CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, - OriginalMtpPrefill, OriginalMtpPrefillWeights, + CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, OriginalMtpPrefill, + OriginalMtpPrefillWeights, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use mtp_dense_kv::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, + OriginalMtpStepOutput, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_expert_stager; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_expert_stager::{ - OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, - OriginalStagerJob, OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, - OriginalStreamAllForward, OriginalStreamAllOptions, + OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerBatch, OriginalStagerCompleted, OriginalStagerJob, + OriginalStagerOptions, OriginalStreamAll, OriginalStreamAllCompleted, OriginalStreamAllForward, + OriginalStreamAllOptions, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod native_parity; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[allow(unsafe_code)] mod native_parity_ffi; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use native_parity::{ NativeParity, NativeParityExpert, native_parity_embed_supported, native_parity_iq_supported, native_parity_row_bytes, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use mtp_dense_kv::{ - OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, - OriginalMtpScalarPrefill, + OriginalMtpGrVariant, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_gpu_schedule::OriginalStreamDrained; pub use original_gpu_schedule::capture_timing as original_capture_timing; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod native_head; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use native_head::{ - NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight, - NativeHeadSampling, NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, - OriginalNativeHead, OriginalNativeHeadGraphResources, OriginalNativeHeadRows, - native_embed_supported, native_head_row_bytes, native_head_supported, + NativeEmbedFlight, NativeHeadDispatch, NativeHeadFlight, NativeHeadProjectionFlight, NativeHeadSampling, + NativeHeadSelection, OriginalNativeEmbed, OriginalNativeEmbedRows, OriginalNativeHead, + OriginalNativeHeadGraphResources, OriginalNativeHeadRows, native_embed_supported, native_head_row_bytes, + native_head_supported, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_file_expert_source; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_file_expert_source::{ - OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, - OriginalResidentOptions, OriginalSourceSwap, + OriginalFileExpertSource, OriginalFileSourceBlob, OriginalFileSourceCounters, OriginalResidentOptions, + OriginalSourceSwap, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) mod original_verify; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_verify::chain::set_down_override as set_chain_down_override; pub use original_verify::sm120::set_overrides as set_sm120_overrides; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_verify::{ - MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, - OriginalVerifier, OriginalVerifyBank, OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows, - OriginalVerifyCpuSink, OriginalVerifyGdnJournal, OriginalVerifyGdnStage, - OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGraphResources, - OriginalVerifyLayout, OriginalVerifyResources, OriginalVerifyRow, OriginalVerifySpan, - OriginalVerifyWindow, OriginalVerifyWindowResult, + MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifier, OriginalVerifyBank, + OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGdnJournal, + OriginalVerifyGdnStage, OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGpuPlan, + OriginalVerifyGraphResources, OriginalVerifyLayout, OriginalVerifyPcieSource, OriginalVerifyResources, + OriginalVerifyRow, OriginalVerifySpan, OriginalVerifyWindow, OriginalVerifyWindowResult, }; // Live verifier release/diagnostic owner, profile report and completed-logit readout. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_verify::{ - HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyExpertFormats, - OriginalVerifyGdnProjections, OriginalVerifyGrBinding, OriginalVerifyMoeBinding, - OriginalVerifyMoeLayerWeights, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, - OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, + ExpertTier, HcHalf, OriginalVerifyDiag, OriginalVerifyExpertLayout, OriginalVerifyProfile, + OriginalVerifyWindowResources, PROFILE_STAMPS_PER_LAYER, PlanLayout, Projection, QuantSource, RowLogprob, + Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, WindowOps as OriginalVerifyWindowOps, + WindowPolicy as OriginalVerifyWindowPolicy, analyse_row, logpos_topk_from_environment, original_verify_diagnostics, + original_verify_live_count, original_verify_release_live, profile_stamp_slot, profile_stamp_words, + record_window as record_original_verify_window, top_k, write_original_verify_diagnostics, write_row_line, + write_window_logprobs, +}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use original_verify::{ + HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyExpertFormats, OriginalVerifyGdnProjections, + OriginalVerifyGrBinding, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights, OriginalVerifyNativeMatrix, + OriginalVerifyProjBinding, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, OriginalVerifyQsaPolicy, OriginalVerifyQsaProjections, PLE_SCRATCH_BYTES, PleBuffers, PleKeyBuffer, QsaRope, unsealed_window_assets, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use original_verify::{ - ExpertTier, HcHalf, OriginalVerifyExpertLayout, OriginalVerifyWindowResources, PlanLayout, - Projection, QuantSource, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, - WindowOps as OriginalVerifyWindowOps, WindowPolicy as OriginalVerifyWindowPolicy, - record_window as record_original_verify_window, - OriginalVerifyDiag, OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, RowLogprob, analyse_row, - logpos_topk_from_environment, original_verify_diagnostics, original_verify_live_count, - original_verify_release_live, profile_stamp_slot, profile_stamp_words, top_k, write_row_line, - write_window_logprobs, write_original_verify_diagnostics, -}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; #[cfg(all( feature = "cuda-driver", feature = "expert-tier-probe", @@ -866,29 +735,19 @@ pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; target_pointer_width = "64" ))] pub use original_verify::{OriginalExpertTierProbe, expert_probe_geometry}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use qsa_prompt_index::{OriginalVerifyQsaJournal, OriginalVerifyRope}; // Which compiled assets the Original serve stack needs, and which of them are sealed in this build. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_serve_assets; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_serve_assets::{ OriginalAssetKind, OriginalAssetStatus, original_serve_asset_status, original_serve_assets_sealed, unsealed_original_serve_assets, }; // Session-lineage reads over the verifier QSA journal (see the file header). -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod original_serve_access; mod bringup_trace_enabled_fn; @@ -900,20 +759,20 @@ use bringup_trace_enabled_fn::combine; use bringup_trace_enabled_fn::valid_size; mod impl_projectionkind; #[allow(unused_imports)] -use impl_projectionkind::q4_k_native_indices_fit; +use impl_projectionkind::projection_ranges; #[allow(unused_imports)] use impl_projectionkind::projection_shape; #[allow(unused_imports)] -use impl_projectionkind::projection_ranges; +use impl_projectionkind::q4_k_native_indices_fit; #[allow(unused_imports)] use impl_projectionkind::q5_k_shape; mod q6_k_shape_fn; #[allow(unused_imports)] -use q6_k_shape_fn::q6_k_shape; +use q6_k_shape_fn::matvec_allocations; #[allow(unused_imports)] use q6_k_shape_fn::matvec_shape; #[allow(unused_imports)] -use q6_k_shape_fn::matvec_allocations; +use q6_k_shape_fn::q6_k_shape; #[allow(unused_imports)] use q6_k_shape_fn::vector_shape; mod impl_context; @@ -926,7 +785,11 @@ mod impl_devicebuffer; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[allow(unused_imports)] pub use impl_devicebuffer::chain_selects_mtp; -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] #[allow(unused_imports)] pub use impl_devicebuffer::chain_selects_mtp; #[cfg(not(all( diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index c739f223..c5780770 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -3,8 +3,7 @@ //! current row and coverage independently. No caller bytes or raw alias API. use crate::{Context, DeviceBuffer, Error, Result, api, combine}; use leleka_model_format::qwen4exp::{ - LayerRole, ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan, - TensorRole, + LayerRole, ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan, TensorRole, }; use std::{mem::size_of, rc::Rc}; const BANKS: usize = 144; @@ -84,7 +83,7 @@ mod locked_tests { mod impl_context; #[allow(unused_imports)] pub(crate) use impl_context::aligned_copy_enabled; -mod impl_mappedexpertbank; mod impl_drop_for_mappedexpertbank; +mod impl_mappedexpertbank; #[allow(unused_imports)] use impl_drop_for_mappedexpertbank::range_covered; diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_context.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_context.rs index cd1b58ec..4de49353 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_context.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_context.rs @@ -18,9 +18,7 @@ impl Context<'_> { return Err(Error::InvalidSize); } let mut ranges = Vec::new(); - ranges - .try_reserve_exact(BANKS) - .map_err(|_| Error::HostAllocation)?; + ranges.try_reserve_exact(BANKS).map_err(|_| Error::HostAllocation)?; let mut extra = 0usize; for (n, member) in members.iter().enumerate() { let role = match n % 3 { @@ -29,11 +27,7 @@ impl Context<'_> { _ => LayerRole::FfnDownExperts, }; if !member.belongs_to_lease(&lease) - || member.role() - != (TensorRole::Layer { - layer: (n / 3) as u8, - role, - }) + || member.role() != (TensorRole::Layer { layer: (n / 3) as u8, role }) || member.bytes().is_empty() || !member.bytes().len().is_multiple_of(512 * 16) { @@ -43,29 +37,21 @@ impl Context<'_> { if !start.is_multiple_of(16) { return Err(Error::InvalidSize); } - let end = start - .checked_add(member.bytes().len()) - .ok_or(Error::InvalidSize)?; + let end = start.checked_add(member.bytes().len()).ok_or(Error::InvalidSize)?; let rounded_start = start & !(page - 1); let rounded_end = end.checked_add(page - 1).ok_or(Error::InvalidSize)? & !(page - 1); - if ranges - .iter() - .any(|&(a, b)| rounded_start < b && a < rounded_end) - { + if ranges.iter().any(|&(a, b)| rounded_start < b && a < rounded_end) { return Err(Error::OutputAliasesInput); } - extra = extra - .checked_add(rounded_end - rounded_start - member.bytes().len()) - .ok_or(Error::BudgetExceeded)?; + extra = + extra.checked_add(rounded_end - rounded_start - member.bytes().len()).ok_or(Error::BudgetExceeded)?; ranges.push((rounded_start, rounded_end)); } // Registered exact ptr/len only; rounded pages are accounted and checked // for overlap, never exposed as owned bytes or a broader device range. let member_capacity = members.capacity(); let mut banks = Vec::new(); - banks - .try_reserve_exact(BANKS) - .map_err(|_| Error::HostAllocation)?; + banks.try_reserve_exact(BANKS).map_err(|_| Error::HostAllocation)?; let metadata = member_capacity .checked_mul(size_of::()) .and_then(|n| n.checked_add(banks.capacity() * size_of::())) @@ -82,11 +68,7 @@ impl Context<'_> { return Err(Error::BudgetExceeded); } for member in members { - banks.push(RegisteredBank { - member, - alias: 0, - registered: false, - }); + banks.push(RegisteredBank { member, alias: 0, registered: false }); } let mut owner = MappedExpertBank { context: self, @@ -105,17 +87,9 @@ impl Context<'_> { return Ok(()); } for bank in &mut owner.banks { - owner - .api - .as_ref() - .expect("actual loaded ABI") - .register_bank(bank.member.bytes())?; + owner.api.as_ref().expect("actual loaded ABI").register_bank(bank.member.bytes())?; bank.registered = true; - bank.alias = owner - .api - .as_ref() - .expect("actual loaded ABI") - .bank_alias(bank.member.bytes())?; + bank.alias = owner.api.as_ref().expect("actual loaded ABI").bank_alias(bank.member.bytes())?; } Ok(()) })(); diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_drop_for_mappedexpertbank.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_drop_for_mappedexpertbank.rs index cde5b6cb..411b5881 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_drop_for_mappedexpertbank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_drop_for_mappedexpertbank.rs @@ -10,9 +10,7 @@ impl Drop for MappedExpertBank<'_> { } impl<'ctx> PendingMappedExpertCopy<'ctx> { pub fn destination_bytes(&self) -> usize { - self.destinations - .as_ref() - .map_or(0, |b| b.iter().map(DeviceBuffer::len).sum()) + self.destinations.as_ref().map_or(0, |b| b.iter().map(DeviceBuffer::len).sum()) } pub(super) fn observe(&mut self, wait: bool) -> Result { if self.complete { @@ -32,8 +30,7 @@ impl<'ctx> PendingMappedExpertCopy<'ctx> { }; let api = bank.api.as_ref().ok_or(Error::ContextPoisoned)?; let result = if wait { - api.wait(self.event.ok_or(Error::ContextPoisoned)?) - .map(|()| true) + api.wait(self.event.ok_or(Error::ContextPoisoned)?).map(|()| true) } else { api.query(self.event.ok_or(Error::ContextPoisoned)?) }; @@ -115,11 +112,7 @@ impl<'ctx> PendingMappedExpertCopy<'ctx> { return Err(primary); } let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; - let scratch = MappedExpertCopyScratch { - context: bank.context, - tables, - arguments, - }; + let scratch = MappedExpertCopyScratch { context: bank.context, tables, arguments }; drop(self.spans.take()); Ok(MappedExpertCopyCompletion { destinations: self.destinations.take().ok_or(Error::ContextPoisoned)?, @@ -146,23 +139,15 @@ impl Drop for PendingMappedExpertCopy<'_> { impl Context<'_> { pub fn mapped_expert_copy_scratch<'ctx>(&'ctx self) -> Result> { let mut tables = Vec::new(); - tables - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; + tables.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; let mut arguments = Vec::new(); - arguments - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + arguments.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; arguments.resize(3, api::MappedCopyArguments::default()); for _ in 0..3 { tables.push(self.allocate(8)?); tables.push(self.allocate(4)?); } - Ok(MappedExpertCopyScratch { - context: self, - tables, - arguments, - }) + Ok(MappedExpertCopyScratch { context: self, tables, arguments }) } } impl MappedExpertCopyScratch<'_> { diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs index 4ba7ac01..2b48ff37 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MappedExpertBank<'ctx> { pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool { !self.closed && std::ptr::eq(self.context, context) @@ -28,14 +27,8 @@ impl<'ctx> MappedExpertBank<'ctx> { _ => return Err(Error::InvalidSize), }; let bank = self.banks.get(n).ok_or(Error::InvalidSize)?; - let end = span - .offset() - .checked_add(span.bytes().len()) - .ok_or(Error::InvalidSize)?; - bank.member - .bytes() - .get(span.offset()..end) - .ok_or(Error::InvalidSize) + let end = span.offset().checked_add(span.bytes().len()).ok_or(Error::InvalidSize)?; + bank.member.bytes().get(span.offset()..end).ok_or(Error::InvalidSize) } /// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it /// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at @@ -68,10 +61,7 @@ impl<'ctx> MappedExpertBank<'ctx> { } Ok((&member[a - base..b - base], start - a)) } - pub(crate) fn retained_span_handle( - &self, - span: &ResidentExpertBankSpan, - ) -> Result { + pub(crate) fn retained_span_handle(&self, span: &ResidentExpertBankSpan) -> Result { crate::ffi::BufferHandle::registered_bank_alias(self.alias(span)?, span.bytes().len()) } pub fn page_overhead_bytes(&self) -> usize { @@ -81,9 +71,7 @@ impl<'ctx> MappedExpertBank<'ctx> { self.lease.source_bytes() } pub fn metadata_bytes(&self) -> usize { - size_of::() - + 2 * size_of::() - + self.banks.capacity() * size_of::() + size_of::() + 2 * size_of::() + self.banks.capacity() * size_of::() } /// The gate/up/down host ranges (address, length) of `expert` of `layer`: the members hold 512 equal /// per-expert extents in id order (the same extents `cache_source` returns for that expert's spans). diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs index 7d66a977..746ab4bc 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MappedExpertBank<'ctx> { pub(in super::super) fn page_locked(&self, bytes: &[u8]) -> bool { let start = bytes.as_ptr() as usize; @@ -44,10 +43,7 @@ impl<'ctx> MappedExpertBank<'ctx> { if self.pageable { return Err(Error::UnsupportedQwenOperation); } - self.banks[n] - .alias - .checked_add(span.offset() as u64) - .ok_or(Error::InvalidSize) + self.banks[n].alias.checked_add(span.offset() as u64).ok_or(Error::InvalidSize) } /// Every check of a span against its retained bank except the device alias; returns the bank index. pub(in super::super) fn check(&self, span: &ResidentExpertBankSpan) -> Result { @@ -70,10 +66,7 @@ impl<'ctx> MappedExpertBank<'ctx> { if (!bank.registered && !self.pageable) || !span.belongs_to(&bank.member) || span.bytes().is_empty() - || span - .offset() - .checked_add(span.bytes().len()) - .is_none_or(|n| n > bank.member.bytes().len()) + || span.offset().checked_add(span.bytes().len()).is_none_or(|n| n > bank.member.bytes().len()) || !span.offset().is_multiple_of(16) || !span.bytes().len().is_multiple_of(16) { @@ -110,9 +103,7 @@ impl<'ctx> MappedExpertBank<'ctx> { if !self.eligible(&spans) { return Err(Error::InvalidSize); } - if !std::ptr::eq(scratch.context, self.context) - || scratch.tables.len() != 6 - || scratch.arguments.len() != 3 + if !std::ptr::eq(scratch.context, self.context) || scratch.tables.len() != 6 || scratch.arguments.len() != 3 { return Err(Error::ContextMismatch); } @@ -122,19 +113,12 @@ impl<'ctx> MappedExpertBank<'ctx> { return Err(Error::ContextMismatch); } if destination.bytes != span.bytes().len() { - return Err(Error::ShapeMismatch { - expected: span.bytes().len(), - actual: destination.bytes, - }); + return Err(Error::ShapeMismatch { expected: span.bytes().len(), actual: destination.bytes }); } let handle = destination.handle.ok_or(Error::ContextPoisoned)?; handle.validate_extent(destination.bytes)?; for prior in &destinations[..n] { - if handle.overlaps( - destination.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { + if handle.overlaps(destination.bytes, prior.handle.ok_or(Error::ContextPoisoned)?, prior.bytes) { return Err(Error::OutputAliasesInput); } } @@ -173,29 +157,14 @@ impl<'ctx> MappedExpertBank<'ctx> { let actual = pending.destinations.as_ref().expect("owned triplet"); pending.attempted = true; pending.arguments[n] = api::MappedCopyArguments { - source: pending.tables[n * 2] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), - count: pending.tables[n * 2 + 1] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), - destination: actual[n] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(), + source: pending.tables[n * 2].handle.ok_or(Error::ContextPoisoned)?.qwen_address(), + count: pending.tables[n * 2 + 1].handle.ok_or(Error::ContextPoisoned)?.qwen_address(), + destination: actual[n].handle.ok_or(Error::ContextPoisoned)?.qwen_address(), words: (actual[n].bytes / 16) as i64, }; - api.copy_kernel( - &mut pending.arguments[n], - pending.stream.expect("actual stream"), - )?; + api.copy_kernel(&mut pending.arguments[n], pending.stream.expect("actual stream"))?; } - api.record( - pending.event.expect("actual event"), - pending.stream.expect("actual stream"), - )?; + api.record(pending.event.expect("actual event"), pending.stream.expect("actual stream"))?; pending.recorded = true; Ok(()) })(); diff --git a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs index 01c6693e..a59700f8 100644 --- a/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs +++ b/crates/cuda-driver/src/mapped_expert_bank/impl_mappedexpertbank/impl_mappedexpertbank_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MappedExpertBank<'ctx> { pub(in super::super) fn retain_uncertain(&mut self) { self.context.poisoned.set(true); diff --git a/crates/cuda-driver/src/mapped_file_dma_stress_gpu.rs b/crates/cuda-driver/src/mapped_file_dma_stress_gpu.rs index d93250e0..bf519035 100644 --- a/crates/cuda-driver/src/mapped_file_dma_stress_gpu.rs +++ b/crates/cuda-driver/src/mapped_file_dma_stress_gpu.rs @@ -84,7 +84,8 @@ fn mapped_file_dma_under_working_set_trimming_is_exact() { let api = { let guard = ctx.enter().unwrap(); let api = MappedApi::load().unwrap(); - api.register_read_only(base_address, registered).unwrap_or_else(|e| panic!("READ_ONLY registration of {registered} bytes failed: {e:?}")); + api.register_read_only(base_address, registered) + .unwrap_or_else(|e| panic!("READ_ONLY registration of {registered} bytes failed: {e:?}")); guard.finish().unwrap(); api }; @@ -128,14 +129,23 @@ fn mapped_file_dma_under_working_set_trimming_is_exact() { let at = lo + 16 * (rng.next() as usize % ((hi - lo - len) / 16)); // SAFETY: inside the live mapping, which stays mapped (and the first `registered` bytes registered) until after the loop. let source = unsafe { std::slice::from_raw_parts((base_address + at) as *const u8, len) }; - stream.enqueue_copy_h2d(device, source).unwrap_or_else(|e| panic!("copy failed at file offset {at} ({len} bytes, locked={locked}): {e:?}")); - stream.synchronize().unwrap_or_else(|e| panic!("stream failed after a copy of file offset {at} ({len} bytes, locked={locked}): {e:?}")); + stream + .enqueue_copy_h2d(device, source) + .unwrap_or_else(|e| panic!("copy failed at file offset {at} ({len} bytes, locked={locked}): {e:?}")); + stream.synchronize().unwrap_or_else(|e| { + panic!("stream failed after a copy of file offset {at} ({len} bytes, locked={locked}): {e:?}") + }); let mut back = vec![0u8; PIECE_MAX]; destination.copy_to(&mut back).unwrap(); let want = expected(at, len); if let Some(i) = (0..len).find(|&i| back[i] != want[i]) { seen_bad += 1; - println!("MISMATCH locked={locked} file offset {at} + {i} (page {}): got {:#04x}, want {:#04x}, piece {len} bytes", (at + i) / 4096, back[i], want[i]); + println!( + "MISMATCH locked={locked} file offset {at} + {i} (page {}): got {:#04x}, want {:#04x}, piece {len} bytes", + (at + i) / 4096, + back[i], + want[i] + ); } copies[usize::from(!locked)] += 1; } diff --git a/crates/cuda-driver/src/mmq.rs b/crates/cuda-driver/src/mmq.rs index 80bf9743..b88ddcd3 100644 --- a/crates/cuda-driver/src/mmq.rs +++ b/crates/cuda-driver/src/mmq.rs @@ -49,22 +49,21 @@ pub(crate) enum Tile { J64, } type TileFunctions = [[ffi::FunctionHandle; 7]; 4]; -pub(crate) const QUANT_ENTRY: &CStr = - c"_Z17quantize_mmq_q8_1IL18mmq_q8_1_ds_layout0ELb0EEvPKfPKiPvllllliii"; +pub(crate) const QUANT_ENTRY: &CStr = c"_Z17quantize_mmq_q8_1IL18mmq_q8_1_ds_layout0ELb0EEvPKfPKiPvllllliii"; // ROOT replaces these None pins only with actual compiled, read-back PTX. // The marker files have no entry and cannot be admitted as executable artifacts. const ORIGINAL_FORMATS_MUL_PIN: Option<(usize, [u8; 32])> = Some(( 2072449, [ - 41, 217, 45, 234, 20, 9, 149, 134, 197, 124, 151, 10, 54, 70, 167, 142, 99, 26, 73, 154, - 113, 87, 213, 106, 160, 226, 10, 193, 224, 180, 1, 54, + 41, 217, 45, 234, 20, 9, 149, 134, 197, 124, 151, 10, 54, 70, 167, 142, 99, 26, 73, 154, 113, 87, 213, 106, + 160, 226, 10, 193, 224, 180, 1, 54, ], )); const ORIGINAL_FORMATS_FIXUP_PIN: Option<(usize, [u8; 32])> = Some(( 309893, [ - 166, 106, 133, 108, 228, 151, 130, 32, 187, 176, 18, 87, 243, 52, 228, 72, 70, 206, 179, - 77, 93, 195, 6, 223, 190, 186, 149, 101, 126, 5, 11, 243, + 166, 106, 133, 108, 228, 151, 130, 32, 187, 176, 18, 87, 243, 52, 228, 72, 70, 206, 179, 77, 93, 195, 6, 223, + 190, 186, 149, 101, 126, 5, 11, 243, ], )); type MmqObservation = (Box<[f32]>, Box<[u8]>); @@ -95,12 +94,7 @@ mod mmq_numeric_gpu_tests; #[path = "mmq_resident.rs"] pub(crate) mod resident; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod triplet_upload_installed { use super::*; @@ -109,17 +103,9 @@ mod triplet_upload_installed { let mut raw = bytes(layout.raw_weight)?; for (index, block) in raw.chunks_exact_mut(layout.block_bytes).enumerate() { for (offset, value) in block.iter_mut().enumerate().skip(2) { - *value = (index - .wrapping_mul(17) - .wrapping_add(offset * 29) - .wrapping_add(salt) - & 255) as u8; + *value = (index.wrapping_mul(17).wrapping_add(offset * 29).wrapping_add(salt) & 255) as u8; } - let scale = if negative_zero && index % 3 == 0 { - 0x8000u16 - } else { - 0x1c00 - }; + let scale = if negative_zero && index % 3 == 0 { 0x8000u16 } else { 0x1c00 }; block[..2].copy_from_slice(&scale.to_le_bytes()); } Ok(raw) @@ -143,60 +129,31 @@ mod triplet_upload_installed { #[test] #[ignore = "Root-only closed triplet upload transport proof"] fn original_three_uploads_first_triplet_exact_padding_refusals_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA172_RUN_MMQ_TRIPLET").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA172_RUN_MMQ_TRIPLET").as_deref(), Ok("yes")); let driver = Driver::load().expect("installed driver"); let device = driver.device(0).expect("device0"); - let context = device - .create_context(16 * 1024 * 1024) - .expect("bounded context"); + let context = device.create_context(16 * 1024 * 1024).expect("bounded context"); let mut mismatch = false; let operation: Result<(usize, usize)> = (|| { let mut compared = 0; let mut guards = 0; for (formats, signed_zero) in [ - ( - [ - MmqFormat::Iq3XxsGateUp, - MmqFormat::Iq3XxsGateUp, - MmqFormat::Iq4NlDown, - ], - false, - ), - ( - [ - MmqFormat::Iq2SGateUp, - MmqFormat::Iq2SGateUp, - MmqFormat::Q2Down, - ], - true, - ), + ([MmqFormat::Iq3XxsGateUp, MmqFormat::Iq3XxsGateUp, MmqFormat::Iq4NlDown], false), + ([MmqFormat::Iq2SGateUp, MmqFormat::Iq2SGateUp, MmqFormat::Q2Down], true), ] { let sources = [ packed(formats[0], signed_zero, 0)?, packed(formats[1], signed_zero, 83)?, packed(formats[2], signed_zero, 167)?, ]; - let raw = [ - sources[0].as_slice(), - sources[1].as_slice(), - sources[2].as_slice(), - ]; + let raw = [sources[0].as_slice(), sources[1].as_slice(), sources[2].as_slice()]; // The original independently completed producer runs FIRST. let mut original = Vec::new(); - original - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + original.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; for (format, source) in formats.into_iter().zip(raw) { original.push(context.mmq_weights(format, source)?); } - let references = [ - read(&original[0])?, - read(&original[1])?, - read(&original[2])?, - ]; + let references = [read(&original[0])?, read(&original[1])?, read(&original[2])?]; let mut original_cleanup = Ok(()); for owner in original.into_iter().rev() { let closed = owner.close(); @@ -231,8 +188,7 @@ mod triplet_upload_installed { mismatch |= context.allocated_bytes() != baseline; guards += 1; mismatch |= !matches!( - context - .mmq_weight_triplet(formats, [raw[0], raw[1], &raw[2][..raw[2].len() - 1]]), + context.mmq_weight_triplet(formats, [raw[0], raw[1], &raw[2][..raw[2].len() - 1]]), Err(Error::InvalidProjectionShape) ); mismatch |= context.allocated_bytes() != baseline; @@ -250,10 +206,7 @@ mod triplet_upload_installed { .into_iter() .sum(); let small = device.create_context(charged - 1)?; - mismatch |= !matches!( - small.mmq_weight_triplet(formats, raw), - Err(Error::BudgetExceeded) - ); + mismatch |= !matches!(small.mmq_weight_triplet(formats, raw), Err(Error::BudgetExceeded)); let small_allocated = small.allocated_bytes(); small.close()?; mismatch |= small_allocated != 0; @@ -270,34 +223,27 @@ mod triplet_upload_installed { assert!(!mismatch, "padded bytes/refusal admission differ"); assert_eq!(guards, 8); assert_eq!(compared, 3_686_724); - println!( - "MMQ_TRIPLET compared_bytes={compared} guards={guards} allocated={allocated} exact=true" - ); + println!("MMQ_TRIPLET compared_bytes={compared} guards={guards} allocated={allocated} exact=true"); } } -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "owned_gate_up_upload_gpu.rs"] mod owned_gate_up_upload_gpu; -mod impl_tile; mod asset_fn; +mod impl_tile; #[allow(unused_imports)] pub(crate) use asset_fn::asset; #[allow(unused_imports)] -use asset_fn::original_formats_asset; -#[allow(unused_imports)] use asset_fn::bytes; #[allow(unused_imports)] use asset_fn::finite_f32; +#[allow(unused_imports)] +use asset_fn::original_formats_asset; mod impl_context; mod release_triplet_fn; #[allow(unused_imports)] use release_triplet_fn::release_triplet; -mod impl_mmqexperiment; mod impl_drop_for_mmqexperiment; +mod impl_mmqexperiment; diff --git a/crates/cuda-driver/src/mmq/asset_fn.rs b/crates/cuda-driver/src/mmq/asset_fn.rs index 4a6433c6..cc51be21 100644 --- a/crates/cuda-driver/src/mmq/asset_fn.rs +++ b/crates/cuda-driver/src/mmq/asset_fn.rs @@ -15,29 +15,24 @@ pub(crate) fn asset(kind: u32) -> Result<&'static [u8]> { static ADAPTIVE_FIXUP: &[u8] = include_bytes!("../mmq-adaptive-fixup.ptx"); let valid = *VERIFIED.get_or_init(|| { let expected_mul = [ - 0x5a, 0x56, 0xd8, 0xeb, 0x66, 0xf1, 0xf9, 0x8e, 0x3c, 0xb3, 0xab, 0x75, 0x18, 0x1e, - 0x0f, 0x26, 0x3e, 0x4d, 0x51, 0xc4, 0xe7, 0x1e, 0x27, 0xab, 0x2b, 0xc9, 0x9a, 0x1a, - 0x3b, 0x7c, 0x01, 0xcb, + 0x5a, 0x56, 0xd8, 0xeb, 0x66, 0xf1, 0xf9, 0x8e, 0x3c, 0xb3, 0xab, 0x75, 0x18, 0x1e, 0x0f, 0x26, 0x3e, 0x4d, + 0x51, 0xc4, 0xe7, 0x1e, 0x27, 0xab, 0x2b, 0xc9, 0x9a, 0x1a, 0x3b, 0x7c, 0x01, 0xcb, ]; let expected_quant = [ - 0xbe, 0x3b, 0x9f, 0x55, 0xff, 0x60, 0x69, 0xde, 0x50, 0x52, 0xc8, 0x3e, 0xf2, 0x2d, - 0xa8, 0xfe, 0x88, 0xcd, 0x65, 0xe3, 0xe4, 0xfb, 0x1b, 0x13, 0xa7, 0xf9, 0x3d, 0xd1, - 0x4f, 0x69, 0x9c, 0x1b, + 0xbe, 0x3b, 0x9f, 0x55, 0xff, 0x60, 0x69, 0xde, 0x50, 0x52, 0xc8, 0x3e, 0xf2, 0x2d, 0xa8, 0xfe, 0x88, 0xcd, + 0x65, 0xe3, 0xe4, 0xfb, 0x1b, 0x13, 0xa7, 0xf9, 0x3d, 0xd1, 0x4f, 0x69, 0x9c, 0x1b, ]; let expected_fixup = [ - 0x32, 0xa0, 0xc8, 0xc5, 0x45, 0x8b, 0xce, 0x5f, 0x2e, 0x07, 0xc7, 0x95, 0x7e, 0x39, - 0xaa, 0x97, 0xbe, 0xac, 0x8d, 0x79, 0xbf, 0xad, 0x4a, 0x95, 0x4c, 0x91, 0xdc, 0xe3, - 0x97, 0xa4, 0x79, 0x71, + 0x32, 0xa0, 0xc8, 0xc5, 0x45, 0x8b, 0xce, 0x5f, 0x2e, 0x07, 0xc7, 0x95, 0x7e, 0x39, 0xaa, 0x97, 0xbe, 0xac, + 0x8d, 0x79, 0xbf, 0xad, 0x4a, 0x95, 0x4c, 0x91, 0xdc, 0xe3, 0x97, 0xa4, 0x79, 0x71, ]; let expected_adaptive = [ - 0x0c, 0x7f, 0xa1, 0x08, 0x28, 0x02, 0x0b, 0x9e, 0xc8, 0x9b, 0x8b, 0x2f, 0xe5, 0x85, - 0x50, 0x2c, 0x84, 0x89, 0xbe, 0x92, 0xf1, 0xf8, 0x25, 0x18, 0x7d, 0x4c, 0x6b, 0x90, - 0xf1, 0x06, 0x49, 0x48, + 0x0c, 0x7f, 0xa1, 0x08, 0x28, 0x02, 0x0b, 0x9e, 0xc8, 0x9b, 0x8b, 0x2f, 0xe5, 0x85, 0x50, 0x2c, 0x84, 0x89, + 0xbe, 0x92, 0xf1, 0xf8, 0x25, 0x18, 0x7d, 0x4c, 0x6b, 0x90, 0xf1, 0x06, 0x49, 0x48, ]; let expected_adaptive_fixup = [ - 0xe8, 0x14, 0xd7, 0x50, 0x21, 0xa7, 0x3c, 0x38, 0x31, 0x02, 0x3d, 0x29, 0x81, 0x84, - 0x72, 0x23, 0x2d, 0xb4, 0x47, 0x29, 0x21, 0x3d, 0xf1, 0x0d, 0x60, 0xc4, 0x78, 0x63, - 0xaa, 0x47, 0x72, 0x78, + 0xe8, 0x14, 0xd7, 0x50, 0x21, 0xa7, 0x3c, 0x38, 0x31, 0x02, 0x3d, 0x29, 0x81, 0x84, 0x72, 0x23, 0x2d, 0xb4, + 0x47, 0x29, 0x21, 0x3d, 0xf1, 0x0d, 0x60, 0xc4, 0x78, 0x63, 0xaa, 0x47, 0x72, 0x78, ]; [ (MUL, 955353, expected_mul), @@ -69,14 +64,8 @@ pub(crate) fn asset(kind: u32) -> Result<&'static [u8]> { } pub(super) fn original_formats_asset(kind: u32) -> Result<&'static [u8]> { let (b, pin): (&[u8], _) = match kind { - 5 => ( - include_bytes!("../mmq-original-formats.ptx"), - ORIGINAL_FORMATS_MUL_PIN, - ), - 6 => ( - include_bytes!("../mmq-original-formats-fixup.ptx"), - ORIGINAL_FORMATS_FIXUP_PIN, - ), + 5 => (include_bytes!("../mmq-original-formats.ptx"), ORIGINAL_FORMATS_MUL_PIN), + 6 => (include_bytes!("../mmq-original-formats-fixup.ptx"), ORIGINAL_FORMATS_FIXUP_PIN), _ => return Err(Error::InvalidProjectionShape), }; let (len, sha) = pin.ok_or(Error::InvalidDriverValue("MMQ Original formats unsealed"))?; @@ -92,16 +81,12 @@ pub(super) fn original_formats_asset(kind: u32) -> Result<&'static [u8]> { } pub(super) fn bytes(size: usize) -> Result> { let mut b = Vec::new(); - b.try_reserve_exact(size) - .map_err(|_| Error::HostAllocation)?; + b.try_reserve_exact(size).map_err(|_| Error::HostAllocation)?; b.resize(size, 0); Ok(b) } pub(super) fn finite_f32(b: &[u8]) -> bool { - b.as_chunks::<4>() - .0 - .iter() - .all(|v| f32::from_le_bytes(*v).is_finite()) + b.as_chunks::<4>().0.iter().all(|v| f32::from_le_bytes(*v).is_finite()) } impl Context<'_> { pub fn mmq_experiment(&self) -> Result> { diff --git a/crates/cuda-driver/src/mmq/impl_context.rs b/crates/cuda-driver/src/mmq/impl_context.rs index 82573afd..352da153 100644 --- a/crates/cuda-driver/src/mmq/impl_context.rs +++ b/crates/cuda-driver/src/mmq/impl_context.rs @@ -6,26 +6,16 @@ use super::*; impl Context<'_> { /// Closed Gate/Up/Down upload. All three immutable owners become usable /// only after the attempted copies share one confirmed completion fence. - pub fn mmq_weight_triplet( - &self, - formats: [MmqFormat; 3], - raw: [&[u8]; 3], - ) -> Result<[MmqWeights<'_>; 3]> { + pub fn mmq_weight_triplet(&self, formats: [MmqFormat; 3], raw: [&[u8]; 3]) -> Result<[MmqWeights<'_>; 3]> { if self.is_poisoned() || self.handle.is_none() { return Err(Error::ContextPoisoned); } - if !formats[..2] - .iter() - .all(|format| matches!(format, MmqFormat::Iq3XxsGateUp | MmqFormat::Iq2SGateUp)) + if !formats[..2].iter().all(|format| matches!(format, MmqFormat::Iq3XxsGateUp | MmqFormat::Iq2SGateUp)) || !matches!(formats[2], MmqFormat::Iq4NlDown | MmqFormat::Q2Down) { return Err(Error::InvalidProjectionShape); } - let layouts = [ - formats[0].layout(1)?, - formats[1].layout(1)?, - formats[2].layout(1)?, - ]; + let layouts = [formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?]; let mut charge = 0usize; // Validate every source before allocating staging or entering CUDA. for (source, layout) in raw.iter().zip(layouts) { @@ -38,23 +28,12 @@ impl Context<'_> { { return Err(Error::InvalidQ8Activation); } - charge = charge - .checked_add(layout.weight) - .ok_or(Error::BudgetExceeded)?; + charge = charge.checked_add(layout.weight).ok_or(Error::BudgetExceeded)?; } - if self - .allocated - .get() - .checked_add(charge) - .is_none_or(|n| n > self.budget) - { + if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } - let mut staging = [ - bytes(layouts[0].weight)?, - bytes(layouts[1].weight)?, - bytes(layouts[2].weight)?, - ]; + let mut staging = [bytes(layouts[0].weight)?, bytes(layouts[1].weight)?, bytes(layouts[2].weight)?]; for (padded, source) in staging.iter_mut().zip(raw) { padded[..source.len()].copy_from_slice(source); } @@ -67,18 +46,9 @@ impl Context<'_> { } let operation = (|| { let handles = [ - buffers[0] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[1] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[2] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, + buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, ]; let guard = self.enter()?; let mut copy = Ok(()); @@ -108,21 +78,9 @@ impl Context<'_> { unreachable!("all triplet allocations completed before upload") }; Ok([ - MmqWeights { - context: self, - format: formats[0], - buffer: Some(gate), - }, - MmqWeights { - context: self, - format: formats[1], - buffer: Some(up), - }, - MmqWeights { - context: self, - format: formats[2], - buffer: Some(down), - }, + MmqWeights { context: self, format: formats[0], buffer: Some(gate) }, + MmqWeights { context: self, format: formats[1], buffer: Some(up) }, + MmqWeights { context: self, format: formats[2], buffer: Some(down) }, ]) } @@ -150,11 +108,7 @@ impl Context<'_> { { return Err(Error::InvalidProjectionShape); } - let layouts = [ - formats[0].layout(1)?, - formats[1].layout(1)?, - formats[2].layout(1)?, - ]; + let layouts = [formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?]; let sources = [ raw[0].handle.ok_or(Error::ContextPoisoned)?, raw[1].handle.ok_or(Error::ContextPoisoned)?, @@ -168,27 +122,16 @@ impl Context<'_> { if raw[i].bytes != layouts[i].raw_weight { return Err(Error::InvalidProjectionShape); } - let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { - 4 - } else { - 2 - }; + let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { 4 } else { 2 }; sources[i].validate_projection_extent(raw[i].bytes, alignment)?; for j in 0..i { if sources[i].overlaps(raw[i].bytes, sources[j], raw[j].bytes) { return Err(Error::OutputAliasesInput); } } - charge = charge - .checked_add(layouts[i].weight) - .ok_or(Error::BudgetExceeded)?; + charge = charge.checked_add(layouts[i].weight).ok_or(Error::BudgetExceeded)?; } - if self - .allocated - .get() - .checked_add(charge) - .is_none_or(|n| n > self.budget) - { + if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } // Only the literal over-read tails have host staging; no raw GPU weight @@ -207,18 +150,9 @@ impl Context<'_> { } let operation = (|| { let targets = [ - buffers[0] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[1] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[2] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, + buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, ]; let all = [ (sources[0], raw[0].bytes), @@ -239,11 +173,8 @@ impl Context<'_> { let mut tail_handles = [None; 3]; for i in 0..3 { if !tails[i].is_empty() { - tail_handles[i] = Some(targets[i].checked_subspan( - layouts[i].weight, - layouts[i].raw_weight, - tails[i].len(), - )?); + tail_handles[i] = + Some(targets[i].checked_subspan(layouts[i].weight, layouts[i].raw_weight, tails[i].len())?); } } let guard = self.enter()?; @@ -255,10 +186,7 @@ impl Context<'_> { break; } } - copy = self - .driver - .api - .copy_mmq_weight(targets[i], sources[i], raw[i].bytes); + copy = self.driver.api.copy_mmq_weight(targets[i], sources[i], raw[i].bytes); if copy.is_err() { break; } @@ -280,21 +208,9 @@ impl Context<'_> { unreachable!("all padded triplet allocations complete before any copy") }; Ok([ - MmqWeights { - context: self, - format: formats[0], - buffer: Some(gate), - }, - MmqWeights { - context: self, - format: formats[1], - buffer: Some(up), - }, - MmqWeights { - context: self, - format: formats[2], - buffer: Some(down), - }, + MmqWeights { context: self, format: formats[0], buffer: Some(gate) }, + MmqWeights { context: self, format: formats[1], buffer: Some(up) }, + MmqWeights { context: self, format: formats[2], buffer: Some(down) }, ]) } @@ -315,21 +231,13 @@ impl Context<'_> { _ => return Err(Error::UnsupportedProjection), }; let l = kind.layout(1)?; - if shape - != (ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - }) + if shape != (ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 }) || l.weight != l.raw_weight || raw.len() != l.raw_weight { return Err(Error::InvalidProjectionShape); } - if raw - .chunks_exact(l.block_bytes) - .any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) - { + if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) { return Err(Error::InvalidQ8Activation); } let mut b = self.allocate(l.weight)?; @@ -341,11 +249,7 @@ impl Context<'_> { } return combine(Err(error), cleanup); } - Ok(MmqWeights { - context: self, - format: kind, - buffer: Some(b), - }) + Ok(MmqWeights { context: self, format: kind, buffer: Some(b) }) } /// One producer-owned padded native/MMQ matrix. No experimental modules are loaded. @@ -357,10 +261,7 @@ impl Context<'_> { if raw.len() != l.raw_weight { return Err(Error::InvalidProjectionShape); } - if raw - .chunks_exact(l.block_bytes) - .any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) - { + if raw.chunks_exact(l.block_bytes).any(|block| u16::from_le_bytes([block[0], block[1]]) & 0x7c00 == 0x7c00) { return Err(Error::InvalidQ8Activation); } let mut padded = bytes(l.weight)?; @@ -374,10 +275,6 @@ impl Context<'_> { } return combine(Err(error), cleanup); } - Ok(MmqWeights { - context: self, - format, - buffer: Some(b), - }) + Ok(MmqWeights { context: self, format, buffer: Some(b) }) } } diff --git a/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs b/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs index a062311c..47b984b8 100644 --- a/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs +++ b/crates/cuda-driver/src/mmq/impl_drop_for_mmqexperiment.rs @@ -38,11 +38,7 @@ impl<'ctx> MmqWeights<'ctx> { MmqFormat::Iq4XsGateUp => (RoutedFormat::IQ4_XS, 640, 2560), MmqFormat::Iq4NlGateUp => (RoutedFormat::IQ4_NL, 640, 2560), }; - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows, - columns, - } + ProjectionSpec { kind: ProjectionKind::Routed(format), rows, columns } } pub(super) fn native_format(&self) -> RoutedFormat { match self.native_spec().kind { @@ -51,14 +47,9 @@ impl<'ctx> MmqWeights<'ctx> { } } pub fn native_q8_1(&self, input: &DeviceBuffer<'_>, out: &mut DeviceBuffer<'_>) -> Result<()> { - self.context - .project_q8_1_weight(NativeWeights::Dual(self), input, out, self.native_spec()) + self.context.project_q8_1_weight(NativeWeights::Dual(self), input, out, self.native_spec()) } - pub fn native_gate_up_prepared( - &self, - prepared: &RoutedGateUpQ8<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn native_gate_up_prepared(&self, prepared: &RoutedGateUpQ8<'_>, out: &mut DeviceBuffer<'_>) -> Result<()> { self.context.project_routed_gate_up_prepared_weight( NativeWeights::Dual(self), prepared, @@ -66,11 +57,7 @@ impl<'ctx> MmqWeights<'ctx> { self.native_format(), ) } - pub fn native_gate_up_columns( - &self, - prepared: &[&RoutedGateUpQ8<'_>], - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn native_gate_up_columns(&self, prepared: &[&RoutedGateUpQ8<'_>], out: &mut DeviceBuffer<'_>) -> Result<()> { self.context.project_routed_gate_up_columns_weight( NativeWeights::Dual(self), prepared, @@ -109,12 +96,7 @@ impl<'ctx> MmqWeights<'ctx> { prepared: &[&RoutedGateUpQ8<'_>], out: &mut DeviceBuffer<'_>, ) -> Result<()> { - workspace.gate_up_weight( - NativeWeights::Dual(self), - prepared, - out, - self.native_format(), - ) + workspace.gate_up_weight(NativeWeights::Dual(self), prepared, out, self.native_format()) } pub fn native_down_columns_in( &self, @@ -123,13 +105,7 @@ impl<'ctx> MmqWeights<'ctx> { tokens: u32, out: &mut DeviceBuffer<'_>, ) -> Result<()> { - workspace.down_weight( - NativeWeights::Dual(self), - hidden, - out, - tokens as usize, - self.native_format(), - ) + workspace.down_weight(NativeWeights::Dual(self), hidden, out, tokens as usize, self.native_format()) } pub fn close(mut self) -> Result<()> { diff --git a/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs b/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs index e8edde5c..682f52fb 100644 --- a/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs +++ b/crates/cuda-driver/src/mmq/impl_mmqexperiment.rs @@ -29,19 +29,10 @@ impl<'ctx> MmqExperiment<'ctx> { owner.modules[3] = Some(context.driver.api.load_mmq(3)?); owner.modules[4] = Some(context.driver.api.load_mmq(4)?); let mut fixups = Vec::new(); - fixups - .try_reserve_exact(28) - .map_err(|_| Error::HostAllocation)?; + fixups.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; let mut functions = Vec::new(); - functions - .try_reserve_exact(28) - .map_err(|_| Error::HostAllocation)?; - for format in [ - MmqFormat::Iq3XxsGateUp, - MmqFormat::Iq2SGateUp, - MmqFormat::Iq4NlDown, - MmqFormat::Q2Down, - ] { + functions.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; + for format in [MmqFormat::Iq3XxsGateUp, MmqFormat::Iq2SGateUp, MmqFormat::Iq4NlDown, MmqFormat::Q2Down] { for tile in Tile::ALL { let module = if tile == Tile::J64 { 0 } else { 3 }; let fixup_module = if tile == Tile::J64 { 2 } else { 4 }; @@ -53,11 +44,7 @@ impl<'ctx> MmqExperiment<'ctx> { let mut l = format.layout(1)?; l.tile = tile; let j = tile.width(); - let stride = if format == MmqFormat::Iq2SGateUp { - 84 - } else { - 76 - }; + let stride = if format == MmqFormat::Iq2SGateUp { 84 } else { 76 }; l.shared = 128 * stride * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; context.driver.api.mmq_shared(f, l.shared)?; functions.push(f); @@ -68,24 +55,14 @@ impl<'ctx> MmqExperiment<'ctx> { )?); } } - let functions: [ffi::FunctionHandle; 28] = functions - .try_into() - .map_err(|_| Error::InvalidProjectionShape)?; - let fixups: [ffi::FunctionHandle; 28] = fixups - .try_into() - .map_err(|_| Error::InvalidProjectionShape)?; - owner.functions = Some(std::array::from_fn(|f| { - std::array::from_fn(|j| functions[f * 7 + j]) - })); - owner.fixups = Some(std::array::from_fn(|f| { - std::array::from_fn(|j| fixups[f * 7 + j]) - })); + let functions: [ffi::FunctionHandle; 28] = + functions.try_into().map_err(|_| Error::InvalidProjectionShape)?; + let fixups: [ffi::FunctionHandle; 28] = fixups.try_into().map_err(|_| Error::InvalidProjectionShape)?; + owner.functions = Some(std::array::from_fn(|f| std::array::from_fn(|j| functions[f * 7 + j]))); + owner.fixups = Some(std::array::from_fn(|f| std::array::from_fn(|j| fixups[f * 7 + j]))); - owner.quantizer = Some(context.driver.api.mmq_function( - owner.modules[1].ok_or(Error::ContextPoisoned)?, - None, - false, - )?); + owner.quantizer = + Some(context.driver.api.mmq_function(owner.modules[1].ok_or(Error::ContextPoisoned)?, None, false)?); Ok(()) })(); let result = combine(result, guard.finish()); @@ -107,12 +84,8 @@ impl<'ctx> MmqExperiment<'ctx> { self.original_modules[1] = Some(self.context.driver.api.load_mmq(6)?); let mut functions = Vec::new(); let mut fixups = Vec::new(); - functions - .try_reserve_exact(14) - .map_err(|_| Error::HostAllocation)?; - fixups - .try_reserve_exact(14) - .map_err(|_| Error::HostAllocation)?; + functions.try_reserve_exact(14).map_err(|_| Error::HostAllocation)?; + fixups.try_reserve_exact(14).map_err(|_| Error::HostAllocation)?; for format in [MmqFormat::Iq3SGateUp, MmqFormat::Iq4XsGateUp] { for tile in Tile::ALL { let f = self.context.driver.api.mmq_function( @@ -130,18 +103,11 @@ impl<'ctx> MmqExperiment<'ctx> { )?); } } - let functions: [ffi::FunctionHandle; 14] = functions - .try_into() - .map_err(|_| Error::InvalidProjectionShape)?; - let fixups: [ffi::FunctionHandle; 14] = fixups - .try_into() - .map_err(|_| Error::InvalidProjectionShape)?; - self.original_functions = Some(std::array::from_fn(|i| { - std::array::from_fn(|j| functions[i * 7 + j]) - })); - self.original_fixups = Some(std::array::from_fn(|i| { - std::array::from_fn(|j| fixups[i * 7 + j]) - })); + let functions: [ffi::FunctionHandle; 14] = + functions.try_into().map_err(|_| Error::InvalidProjectionShape)?; + let fixups: [ffi::FunctionHandle; 14] = fixups.try_into().map_err(|_| Error::InvalidProjectionShape)?; + self.original_functions = Some(std::array::from_fn(|i| std::array::from_fn(|j| functions[i * 7 + j]))); + self.original_fixups = Some(std::array::from_fn(|i| std::array::from_fn(|j| fixups[i * 7 + j]))); Ok(()) })(); combine(result, guard.finish()) @@ -152,11 +118,7 @@ impl<'ctx> MmqExperiment<'ctx> { let table = if fixup { self.fixups } else { self.functions }; Ok(table.ok_or(Error::ContextPoisoned)?[format.index()][tile.index()]) } else { - let table = if fixup { - self.original_fixups - } else { - self.original_functions - }; + let table = if fixup { self.original_fixups } else { self.original_functions }; Ok(table.ok_or(Error::UnsupportedProjection)?[format.index() - 4][tile.index()]) } } @@ -241,7 +203,11 @@ impl<'ctx> MmqExperiment<'ctx> { let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); let grid = match profile { MmqProfile::CompleteTiles => tiles, - MmqProfile::OriginalStreamK | MmqProfile::OriginalAdaptive if efficiency >= 90 || crate::arch_ptx::stream_k_off() => tiles, + MmqProfile::OriginalStreamK | MmqProfile::OriginalAdaptive + if efficiency >= 90 || crate::arch_ptx::stream_k_off() => + { + tiles + } MmqProfile::OriginalStreamK | MmqProfile::OriginalAdaptive => self.sms, }; let fixup = tiles % grid != 0; @@ -252,19 +218,13 @@ impl<'ctx> MmqExperiment<'ctx> { packed.copy_from(&zeros)?; let ph = packed.handle.ok_or(Error::ContextPoisoned)?; ph.validate_projection_extent(l.packed, 16)?; - if [(wh, l.weight), (ih, l.input), (oh, l.output)] - .into_iter() - .any(|(h, n)| ph.overlaps(l.packed, h, n)) - { + if [(wh, l.weight), (ih, l.input), (oh, l.output)].into_iter().any(|(h, n)| ph.overlaps(l.packed, h, n)) { return Err(Error::OutputAliasesInput); } let mut quant = ffi::MmqQuantArguments::new(ih, ph, l); let guard = self.context.enter()?; - let launch = self.context.driver.api.quantize_mmq( - self.quantizer.ok_or(Error::ContextPoisoned)?, - l, - &mut quant, - ); + let launch = + self.context.driver.api.quantize_mmq(self.quantizer.ok_or(Error::ContextPoisoned)?, l, &mut quant); if launch.is_err() { self.context.poisoned.set(true) } @@ -272,11 +232,7 @@ impl<'ctx> MmqExperiment<'ctx> { let mut q = bytes(l.packed)?; packed.copy_to(&mut q)?; if q[l.payload..].iter().any(|b| *b != 0) - || q[..l.payload] - .as_chunks::<144>() - .0 - .iter() - .any(|block| !finite_f32(&block[..16])) + || q[..l.payload].as_chunks::<144>().0.iter().any(|block| !finite_f32(&block[..16])) { return Err(Error::InvalidQ8Activation); } @@ -290,14 +246,9 @@ impl<'ctx> MmqExperiment<'ctx> { b.copy_from(&bytes(extent)?)?; let th = b.handle.ok_or(Error::ContextPoisoned)?; th.validate_projection_extent(extent, 4)?; - if [ - (wh, l.weight), - (ih, l.input), - (oh, l.output), - (ph, l.packed), - ] - .into_iter() - .any(|(h, n)| th.overlaps(extent, h, n)) + if [(wh, l.weight), (ih, l.input), (oh, l.output), (ph, l.packed)] + .into_iter() + .any(|(h, n)| th.overlaps(extent, h, n)) { return Err(Error::OutputAliasesInput); } @@ -327,21 +278,11 @@ impl<'ctx> MmqExperiment<'ctx> { return Err(Error::InvalidQ8Activation); } let mut values = Vec::new(); - values - .try_reserve_exact(out.len() / 4) - .map_err(|_| Error::HostAllocation)?; - values.extend( - out.as_chunks::<4>() - .0 - .iter() - .map(|v| f32::from_le_bytes(*v)), - ); + values.try_reserve_exact(out.len() / 4).map_err(|_| Error::HostAllocation)?; + values.extend(out.as_chunks::<4>().0.iter().map(|v| f32::from_le_bytes(*v))); Ok((values.into_boxed_slice(), q.into_boxed_slice())) })(); - if matches!( - &result, - Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext) - ) { + if matches!(&result, Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext)) { self.context.poisoned.set(true) } let cleanup = temporary.map_or(Ok(()), |b| self.release_buffer(b)); @@ -357,11 +298,7 @@ impl<'ctx> MmqExperiment<'ctx> { self.original_functions = None; self.original_fixups = None; let mut result = Ok(()); - for module in self - .modules - .iter_mut() - .chain(self.original_modules.iter_mut()) - { + for module in self.modules.iter_mut().chain(self.original_modules.iter_mut()) { if let Some(m) = module.take() { let step = match self.context.enter() { Ok(guard) => combine(self.context.driver.api.unload(m), guard.finish()), diff --git a/crates/cuda-driver/src/mmq/impl_tile.rs b/crates/cuda-driver/src/mmq/impl_tile.rs index 08f110fb..ef4e6043 100644 --- a/crates/cuda-driver/src/mmq/impl_tile.rs +++ b/crates/cuda-driver/src/mmq/impl_tile.rs @@ -4,15 +4,7 @@ use super::*; impl Tile { - pub(super) const ALL: [Self; 7] = [ - Self::J8, - Self::J16, - Self::J24, - Self::J32, - Self::J40, - Self::J48, - Self::J64, - ]; + pub(super) const ALL: [Self; 7] = [Self::J8, Self::J16, Self::J24, Self::J32, Self::J40, Self::J48, Self::J64]; pub(crate) fn width(self) -> u32 { match self { Self::J8 => 8, @@ -41,10 +33,7 @@ impl Tile { } // All seven actual accepted configurations fit admitted shared capacity. // Original host stops at the first strictly improving one-column tile. - Self::ALL - .into_iter() - .find(|j| tokens <= j.width()) - .ok_or(Error::InvalidProjectionShape) + Self::ALL.into_iter().find(|j| tokens <= j.width()).ok_or(Error::InvalidProjectionShape) } } @@ -61,98 +50,266 @@ impl MmqFormat { } } pub(crate) fn entry(self, tile: Tile) -> &'static CStr { - match (self,tile) { - (Self::Iq3XxsGateUp,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3XxsGateUp,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq2SGateUp,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlDown,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Q2Down,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq3SGateUp,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J8)=>c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J16)=>c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J24)=>c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J32)=>c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J40)=>c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J48)=>c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4XsGateUp,Tile::J64)=>c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - (Self::Iq4NlGateUp,tile)=>Self::Iq4NlDown.entry(tile), - } + match (self, tile) { + (Self::Iq3XxsGateUp, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type18ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type18ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type18ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type18ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type18ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type18ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3XxsGateUp, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type18ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type22ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type22ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type22ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type22ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type22ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type22ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq2SGateUp, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type22ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type20ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type20ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type20ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type20ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type20ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type20ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlDown, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type20ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type42ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type42ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type42ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type42ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type42ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type42ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Q2Down, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type42ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type21ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type21ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type21ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type21ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type21ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type21ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq3SGateUp, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type21ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J8) => { + c"_Z9mul_mat_qIL9ggml_type23ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J16) => { + c"_Z9mul_mat_qIL9ggml_type23ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J24) => { + c"_Z9mul_mat_qIL9ggml_type23ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J32) => { + c"_Z9mul_mat_qIL9ggml_type23ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J40) => { + c"_Z9mul_mat_qIL9ggml_type23ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J48) => { + c"_Z9mul_mat_qIL9ggml_type23ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4XsGateUp, Tile::J64) => { + c"_Z9mul_mat_qIL9ggml_type23ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_" + } + (Self::Iq4NlGateUp, tile) => Self::Iq4NlDown.entry(tile), + } } pub(crate) fn fixup_entry(self, tile: Tile) -> &'static CStr { - match (self,tile) { - (Self::Iq3XxsGateUp,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3XxsGateUp,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq2SGateUp,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlDown,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Q2Down,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq3SGateUp,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J8)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J16)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J24)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J32)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J40)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J48)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4XsGateUp,Tile::J64)=>c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - (Self::Iq4NlGateUp,tile)=>Self::Iq4NlDown.fixup_entry(tile), - } + match (self, tile) { + (Self::Iq3XxsGateUp, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3XxsGateUp, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type18ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq2SGateUp, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type22ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlDown, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type20ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Q2Down, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type42ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq3SGateUp, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type21ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J8) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J16) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J24) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J32) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J40) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J48) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4XsGateUp, Tile::J64) => { + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type23ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_" + } + (Self::Iq4NlGateUp, tile) => Self::Iq4NlDown.fixup_entry(tile), + } } pub(crate) fn layout(self, tokens: u32) -> Result { if !(1..=64).contains(&tokens) { diff --git a/crates/cuda-driver/src/mmq_ffi.rs b/crates/cuda-driver/src/mmq_ffi.rs index cab5f075..4506680d 100644 --- a/crates/cuda-driver/src/mmq_ffi.rs +++ b/crates/cuda-driver/src/mmq_ffi.rs @@ -28,7 +28,7 @@ pub(crate) struct MmqOriginalGatherArguments(Owned); mod impl_owned; #[allow(unused_imports)] use impl_owned::fastdiv; -#[path = "mmq_ffi/impl_mmqresidentarguments.rs"] -mod impl_mmqresidentarguments; #[path = "mmq_ffi/impl_mmqoriginalgatherarguments.rs"] mod impl_mmqoriginalgatherarguments; +#[path = "mmq_ffi/impl_mmqresidentarguments.rs"] +mod impl_mmqresidentarguments; diff --git a/crates/cuda-driver/src/mmq_ffi/impl_mmqoriginalgatherarguments.rs b/crates/cuda-driver/src/mmq_ffi/impl_mmqoriginalgatherarguments.rs index 891cc9d7..8ab78711 100644 --- a/crates/cuda-driver/src/mmq_ffi/impl_mmqoriginalgatherarguments.rs +++ b/crates/cuda-driver/src/mmq_ffi/impl_mmqoriginalgatherarguments.rs @@ -17,11 +17,7 @@ impl MmqOriginalGatherArguments { unsafe { let s = &mut *owner.0.as_ptr(); s.addresses[..5].copy_from_slice(&[raw[0].0, raw[1].0, gu.0, raw[2].0, down.0]); - s.wide[..3].copy_from_slice(&[ - (gu_bytes / 16) as i64, - (gu_bytes / 16) as i64, - (down_bytes / 16) as i64, - ]); + s.wide[..3].copy_from_slice(&[(gu_bytes / 16) as i64, (gu_bytes / 16) as i64, (down_bytes / 16) as i64]); s.parameters[0] = (&raw mut s.addresses[0]).cast(); s.parameters[1] = (&raw mut s.wide[0]).cast(); s.parameters[2] = (&raw mut s.addresses[1]).cast(); diff --git a/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs b/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs index 765f82c1..3974eb54 100644 --- a/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs +++ b/crates/cuda-driver/src/mmq_ffi/impl_mmqresidentarguments.rs @@ -39,13 +39,7 @@ impl MmqResidentArguments { } Self(owner) } - pub(crate) fn finite( - source: BufferHandle, - status: BufferHandle, - mode: u32, - amount: u32, - tail: u32, - ) -> Self { + pub(crate) fn finite(source: BufferHandle, status: BufferHandle, mode: u32, amount: u32, tail: u32) -> Self { let owner = Owned::new(); // SAFETY: fixed five-param pointer/pointer/u32/u32/u32 ABI in stable Box. unsafe { @@ -87,12 +81,7 @@ impl MmqResidentArguments { } } impl Iq3NativeIntegerArguments { - pub(crate) fn dot( - weights: BufferHandle, - packed: BufferHandle, - dots: BufferHandle, - tokens: u32, - ) -> Self { + pub(crate) fn dot(weights: BufferHandle, packed: BufferHandle, dots: BufferHandle, tokens: u32) -> Self { Self::new([weights.0, packed.0, dots.0, 0], 3, tokens) } pub(crate) fn reduce( diff --git a/crates/cuda-driver/src/mmq_ffi/impl_owned.rs b/crates/cuda-driver/src/mmq_ffi/impl_owned.rs index 45ccf91a..42f205de 100644 --- a/crates/cuda-driver/src/mmq_ffi/impl_owned.rs +++ b/crates/cuda-driver/src/mmq_ffi/impl_owned.rs @@ -27,11 +27,7 @@ impl Drop for Owned { } pub(super) fn fastdiv(d: u32) -> [u32; 3] { let l = 32 - (d - 1).leading_zeros(); - [ - (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, - l, - d, - ] + [(((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, l, d] } impl MmqQuantArguments { pub(crate) fn new(input: BufferHandle, packed: BufferHandle, l: Layout) -> Self { @@ -76,23 +72,8 @@ impl MmqArguments { // SAFETY: private exact upstream 24-param ABI, null unused one-expert inputs. unsafe { let s = &mut *owner.0.as_ptr(); - s.addresses = [ - weights.0, - packed.0, - 0, - 0, - output.0, - tmp.map_or(0, |p| p.0), - 0, - ]; - s.divisors = [ - fastdiv(l.columns / l.qk), - fastdiv(1), - fastdiv(1), - fastdiv(1), - fastdiv(1), - fastdiv(1), - ]; + s.addresses = [weights.0, packed.0, 0, 0, output.0, tmp.map_or(0, |p| p.0), 0]; + s.divisors = [fastdiv(l.columns / l.qk), fastdiv(1), fastdiv(1), fastdiv(1), fastdiv(1), fastdiv(1)]; s.integers = [ l.rows as i32, l.tokens as i32, @@ -138,12 +119,7 @@ impl MmqFixupArguments { unsafe { let s = &mut *owner.0.as_ptr(); s.addresses[..4].copy_from_slice(&[0, 0, output.0, tmp.0]); - s.divisors[..4].copy_from_slice(&[ - fastdiv(l.columns / l.qk), - fastdiv(1), - fastdiv(1), - fastdiv(1), - ]); + s.divisors[..4].copy_from_slice(&[fastdiv(l.columns / l.qk), fastdiv(1), fastdiv(1), fastdiv(1)]); s.integers[..5].copy_from_slice(&[ l.rows as i32, l.tokens as i32, diff --git a/crates/cuda-driver/src/mmq_native_activation.rs b/crates/cuda-driver/src/mmq_native_activation.rs index de2baea3..199fc9fc 100644 --- a/crates/cuda-driver/src/mmq_native_activation.rs +++ b/crates/cuda-driver/src/mmq_native_activation.rs @@ -14,8 +14,8 @@ pub(crate) fn asset() -> Result<&'static [u8]> { Ok(b) } const EXPECTED_RAW_SHA: [u8; 32] = [ - 0xea, 0x33, 0xd3, 0xd1, 0xdb, 0xc3, 0xc6, 0x39, 0x81, 0x55, 0xef, 0xa1, 0x92, 0xb5, 0xbb, 0x4d, - 0x5a, 0x25, 0xf7, 0x3f, 0x6e, 0x8a, 0xf6, 0x5f, 0x2d, 0xdc, 0x1b, 0x91, 0x95, 0xbb, 0x3e, 0xeb, + 0xea, 0x33, 0xd3, 0xd1, 0xdb, 0xc3, 0xc6, 0x39, 0x81, 0x55, 0xef, 0xa1, 0x92, 0xb5, 0xbb, 0x4d, 0x5a, 0x25, 0xf7, + 0x3f, 0x6e, 0x8a, 0xf6, 0x5f, 0x2d, 0xdc, 0x1b, 0x91, 0x95, 0xbb, 0x3e, 0xeb, ]; pub(super) struct NativeActivation<'ctx> { context: &'ctx Context<'ctx>, @@ -28,19 +28,10 @@ impl<'ctx> NativeActivation<'ctx> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(CHARGE) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(CHARGE).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - buffer: None, - module: None, - function: None, - }; + let mut owner = Self { context, buffer: None, module: None, function: None }; let result = (|| { owner.buffer = Some(context.allocate(CHARGE)?); let guard = context.enter()?; @@ -69,9 +60,7 @@ impl<'ctx> NativeActivation<'ctx> { if !std::ptr::eq(self.context, b.context) || b.bytes != CHARGE { return Err(Error::ContextMismatch); } - b.handle - .ok_or(Error::ContextPoisoned)? - .validate_projection_extent(CHARGE, 4) + b.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(CHARGE, 4) } pub(super) fn buffer(&self) -> Result<&DeviceBuffer<'ctx>> { self.check()?; @@ -99,10 +88,7 @@ impl<'ctx> NativeActivation<'ctx> { return Err(Error::OutputAliasesInput); } let guard = self.context.enter()?; - let k = combine( - self.context.fixed_kernel(FixedOperation::CommonQuantize), - guard.finish(), - )?; + let k = combine(self.context.fixed_kernel(FixedOperation::CommonQuantize), guard.finish())?; commands.push(QueuedCommand::NativeQuantize( k.function, (l.columns * l.tokens).div_ceil(256), @@ -111,9 +97,7 @@ impl<'ctx> NativeActivation<'ctx> { commands.push(QueuedCommand::Helper( self.function.ok_or(Error::ContextPoisoned)?, (l.packed / 4) as u32, - ffi::MmqResidentArguments::native_resident_d4( - native, packed, status, l.columns, l.tokens, - ), + ffi::MmqResidentArguments::native_resident_d4(native, packed, status, l.columns, l.tokens), )); Ok(()) } @@ -130,13 +114,10 @@ impl<'ctx> NativeActivation<'ctx> { b.release() } }); - let b = self - .module - .take() - .map_or(Ok(()), |m| match self.context.enter() { - Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), - Err(e) => Err(e), - }); + let b = self.module.take().map_or(Ok(()), |m| match self.context.enter() { + Ok(g) => combine(self.context.driver.api.unload(m), g.finish()), + Err(e) => Err(e), + }); if a.is_err() || b.is_err() { self.context.poisoned.set(true); } diff --git a/crates/cuda-driver/src/mmq_native_down.rs b/crates/cuda-driver/src/mmq_native_down.rs index 7201c9f7..7cd87ebf 100644 --- a/crates/cuda-driver/src/mmq_native_down.rs +++ b/crates/cuda-driver/src/mmq_native_down.rs @@ -13,20 +13,12 @@ impl MmqWorkspace<'_> { MmqFormat::Q2Down => (RoutedFormat::Q2_0, FixedOperation::GroupedDownQ2), _ => return Err(Error::UnsupportedProjection), }; - let spec = ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - }; + let spec = ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 }; let shape = projection_shape(spec)?; let owner = NativeWeights::Dual(weights); owner.validate(spec, shape.weight_bytes)?; let weight = owner.buffer()?; - let native = self - .native_activation - .as_ref() - .ok_or(Error::UnsupportedProjection)? - .buffer()?; + let native = self.native_activation.as_ref().ok_or(Error::UnsupportedProjection)?.buffer()?; if !std::ptr::eq(self.context, weights.context) || !std::ptr::eq(self.context, weight.context) || !std::ptr::eq(self.context, native.context) @@ -41,11 +33,7 @@ impl MmqWorkspace<'_> { return Err(Error::InvalidProjectionShape); } qh.validate_projection_extent(native.bytes, 4)?; - let spans = [ - (wh, weight.bytes), - (qh, native.bytes), - (oh, self.buffer(DOWN)?.bytes), - ]; + let spans = [(wh, weight.bytes), (qh, native.bytes), (oh, self.buffer(DOWN)?.bytes)]; for i in 0..spans.len() { for j in i + 1..spans.len() { if spans[i].0.overlaps(spans[i].1, spans[j].0, spans[j].1) { diff --git a/crates/cuda-driver/src/mmq_native_resident_gpu.rs b/crates/cuda-driver/src/mmq_native_resident_gpu.rs index a6962589..4eb72180 100644 --- a/crates/cuda-driver/src/mmq_native_resident_gpu.rs +++ b/crates/cuda-driver/src/mmq_native_resident_gpu.rs @@ -13,34 +13,19 @@ struct Alias<'a, 'c> { #[test] #[ignore = "root-only actual expert215 T2 native transport diagnostic; no quality gate"] fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { - assert_eq!( - std::env::var("LELEKA_RUN_REAL_NATIVE_D4").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_RUN_REAL_NATIVE_D4").as_deref(), Ok("yes")); let [data, gate, up, down] = fixture(); // Exact independent raw expert slices, not a whole-model provenance claim. for (b, sha) in [ - ( - &gate, - "fd6f70d60c177b98b30e194c68323a30a4b6c2cb2599ba85f3ab1a73ae6338aa", - ), - ( - &up, - "228f1c166face5f392c4f52f33dc5c68194c6c2bc12a451d29f58a690d09ffd4", - ), - ( - &down, - "c02a439a67cca4fe52c303595e8d5aa38ad4734c11d9e95ffe159ad563ff5b75", - ), + (&gate, "fd6f70d60c177b98b30e194c68323a30a4b6c2cb2599ba85f3ab1a73ae6338aa"), + (&up, "228f1c166face5f392c4f52f33dc5c68194c6c2bc12a451d29f58a690d09ffd4"), + (&down, "c02a439a67cca4fe52c303595e8d5aa38ad4734c11d9e95ffe159ad563ff5b75"), ] { assert_eq!(digest(b), sha); } let root = PathBuf::from(std::env::var("LELEKA_REAL_GU_OUTPUT_DIR").unwrap()); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); DirBuilder::new().mode(0o700).create(&root).unwrap(); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); @@ -53,10 +38,7 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { context.mmq_weights(MmqFormat::Iq3XxsGateUp, &up).unwrap(), context.mmq_weights(MmqFormat::Iq4NlDown, &down).unwrap(), ]; - let immutable_weights: Vec<_> = weights - .iter() - .map(|w| download(w.native_buffer().unwrap())) - .collect(); + let immutable_weights: Vec<_> = weights.iter().map(|w| download(w.native_buffer().unwrap())).collect(); for (actual, raw) in immutable_weights.iter().zip([&gate, &up, &down]) { assert_eq!(&actual[..raw.len()], raw); assert!(actual[raw.len()..].iter().all(|v| *v == 0)); @@ -69,22 +51,15 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { let input = upload(&context, &data[row * 10240..(row + 1) * 10240]); let prepared = context.prepare_routed_gate_up_q8(&input).unwrap(); native_gu_q8.extend(download(prepared.scratch.as_ref().unwrap())); - let mut outputs = [ - context.allocate(2560).unwrap(), - context.allocate(2560).unwrap(), - ]; + let mut outputs = [context.allocate(2560).unwrap(), context.allocate(2560).unwrap()]; for i in 0..2 { - weights[i] - .native_gate_up_prepared(&prepared, &mut outputs[i]) - .unwrap(); + weights[i].native_gate_up_prepared(&prepared, &mut outputs[i]).unwrap(); let b = download(&outputs[i]); assert!(finite_f32(&b)); native[i].extend(b); } let mut hidden = context.allocate(2560).unwrap(); - context - .moe_swiglu_f32(&outputs[0], &outputs[1], &mut hidden) - .unwrap(); + context.moe_swiglu_f32(&outputs[0], &outputs[1], &mut hidden).unwrap(); let b = download(&hidden); assert!(finite_f32(&b)); native[2].extend(b); @@ -112,25 +87,13 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { { let mut chunk = w.prepare_gate_up_chunk(&source, 2).unwrap(); let packed = prefix(chunk.workspace.buffer(CHUNK).unwrap(), 14976); - let q = prefix( - chunk - .workspace - .native_activation - .as_ref() - .unwrap() - .buffer() - .unwrap(), - 5760, - ); + let q = prefix(chunk.workspace.native_activation.as_ref().unwrap().buffer().unwrap(), 5760); assert_eq!(q, native_gu_q8); associate(&q, &packed, 2560); write_file(&root, "gu.native_q8.bin", &q); write_file(&root, "gu.native_d4.bin", &packed); let group = chunk.gather_gate_up(&[0, 1]).unwrap(); - assert_eq!( - prefix(group.workspace.buffer(GROUP).unwrap(), 14976), - packed - ); + assert_eq!(prefix(group.workspace.buffer(GROUP).unwrap(), 14976), packed); let hidden = group.gate_up(&weights[0], &weights[1]).unwrap(); for (slot, name) in [(GATE, "gate"), (UP, "up"), (HIDDEN, "hidden")] { let b = prefix(hidden.workspace.buffer(slot).unwrap(), 5120); @@ -147,11 +110,7 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { let oldq = prefix(chunk.workspace.buffer(CHUNK).unwrap(), 14976); assert!(oldq[5760..].iter().all(|v| *v == 0)); write_file(&root, "gu.original_d4.bin", &oldq); - let hidden = chunk - .gather_gate_up(&[0, 1]) - .unwrap() - .gate_up(&weights[0], &weights[1]) - .unwrap(); + let hidden = chunk.gather_gate_up(&[0, 1]).unwrap().gate_up(&weights[0], &weights[1]).unwrap(); for (slot, name) in [(GATE, "gate"), (UP, "up"), (HIDDEN, "hidden")] { let b = prefix(hidden.workspace.buffer(slot).unwrap(), 5120); assert!(finite_f32(&b)); @@ -164,28 +123,13 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { } // Same native-hidden isolation uses only an actual raw scratch upload + private numeric helpers. // No MmqHidden product is forged from host data. - for (workspace, arm) in [ - (&mut w, "native_compatible"), - (&mut original, "original_d4"), - ] { - workspace.buffers[HIDDEN] - .as_mut() - .unwrap() - .copy_from_range(0, &native[2]) - .unwrap(); + for (workspace, arm) in [(&mut w, "native_compatible"), (&mut original, "original_d4")] { + workspace.buffers[HIDDEN].as_mut().unwrap().copy_from_range(0, &native[2]).unwrap(); workspace.quantize(HIDDEN, DOWN_Q8, down_layout).unwrap(); let packed = prefix(workspace.buffer(DOWN_Q8).unwrap(), 11520); assert!(packed[2304..].iter().all(|v| *v == 0)); if arm == "native_compatible" { - let q = prefix( - workspace - .native_activation - .as_ref() - .unwrap() - .buffer() - .unwrap(), - 1440, - ); + let q = prefix(workspace.native_activation.as_ref().unwrap().buffer().unwrap(), 1440); assert_eq!(q, native_down_q8); associate(&q, &packed, 640); write_file(&root, "down.native_q8.bin", &q); @@ -197,10 +141,7 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { write_file(&root, &format!("down_same_source.{arm}.f32"), &b); } let mut metrics = String::new(); - for (i, role) in ["gate", "up", "hidden", "down_chain"] - .into_iter() - .enumerate() - { + for (i, role) in ["gate", "up", "hidden", "down_chain"].into_iter().enumerate() { write_file(&root, &format!("{role}.native.f32"), &native[i]); for arm in ["native_compatible", "original_d4"] { let b = read(&root.join(format!("{role}.{arm}.f32")), native[i].len()); @@ -212,66 +153,33 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { metrics.push_str(&measure(2, "down_same_source", arm, &native[3], &b)); } // Closed new-policy guards, all before any output publication. - assert!(matches!( - w.prepare_gate_up_chunk(&source, 0), - Err(Error::InvalidProjectionShape) - )); - assert!(matches!( - w.prepare_gate_up_chunk(&source, 65), - Err(Error::InvalidProjectionShape) - )); - assert!(matches!( - w.prepare_gate_up_chunk(&source[..source.len() - 1], 2), - Err(Error::InvalidQ8Activation) - )); + assert!(matches!(w.prepare_gate_up_chunk(&source, 0), Err(Error::InvalidProjectionShape))); + assert!(matches!(w.prepare_gate_up_chunk(&source, 65), Err(Error::InvalidProjectionShape))); + assert!(matches!(w.prepare_gate_up_chunk(&source[..source.len() - 1], 2), Err(Error::InvalidQ8Activation))); let foreign_weights = foreign.mmq_weights(MmqFormat::Iq3XxsGateUp, &gate).unwrap(); - assert_eq!( - w.project(&foreign_weights, CHUNK, GATE, 2), - Err(Error::ContextMismatch) - ); + assert_eq!(w.project(&foreign_weights, CHUNK, GATE, 2), Err(Error::ContextMismatch)); foreign_weights.close().unwrap(); let saved = w.buffers[CHUNK].as_ref().unwrap().handle; w.buffers[CHUNK].as_mut().unwrap().handle = w.buffers[INPUT].as_ref().unwrap().handle; { - let alias = Alias { - workspace: &mut w, - saved, - }; - assert_eq!( - alias.workspace.quantize(INPUT, CHUNK, gu_layout), - Err(Error::OutputAliasesInput) - ); + let alias = Alias { workspace: &mut w, saved }; + assert_eq!(alias.workspace.quantize(INPUT, CHUNK, gu_layout), Err(Error::OutputAliasesInput)); } // Actual late device NaN: native status admission refuses, context stays unpoisoned. - for (slot, packed, layout, valid) in [ - (INPUT, CHUNK, gu_layout, &data), - (HIDDEN, DOWN_Q8, down_layout, &native[2]), - ] { + for (slot, packed, layout, valid) in + [(INPUT, CHUNK, gu_layout, &data), (HIDDEN, DOWN_Q8, down_layout, &native[2])] + { let mut bad = valid.to_vec(); let n = bad.len(); bad[n - 4..].copy_from_slice(&f32::NAN.to_le_bytes()); - w.buffers[slot] - .as_mut() - .unwrap() - .copy_from_range(0, &bad) - .unwrap(); - assert_eq!( - w.quantize(slot, packed, layout), - Err(Error::InvalidQ8Activation) - ); + w.buffers[slot].as_mut().unwrap().copy_from_range(0, &bad).unwrap(); + assert_eq!(w.quantize(slot, packed, layout), Err(Error::InvalidQ8Activation)); assert!(!context.is_poisoned()); - w.buffers[slot] - .as_mut() - .unwrap() - .copy_from_range(0, valid) - .unwrap(); + w.buffers[slot].as_mut().unwrap().copy_from_range(0, valid).unwrap(); w.quantize(slot, packed, layout).unwrap(); } let small = device.create_context(184319).unwrap(); - assert!(matches!( - small.native_mmq_workspace(), - Err(Error::BudgetExceeded) - )); + assert!(matches!(small.native_mmq_workspace(), Err(Error::BudgetExceeded))); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); assert_eq!(prefix(w.buffer(INPUT).unwrap(), 20480), data); @@ -302,29 +210,29 @@ fn actual_expert215_native_resident_gu_and_same_source_down_diagnostic() { #[path = "mmq_native_resident_gpu/digest_fn.rs"] mod digest_fn; #[allow(unused_imports)] +use digest_fn::associate; +#[allow(unused_imports)] use digest_fn::digest; #[allow(unused_imports)] -use digest_fn::read; -#[allow(unused_imports)] -use digest_fn::fixture; -#[allow(unused_imports)] -use digest_fn::upload; -#[allow(unused_imports)] use digest_fn::download; #[allow(unused_imports)] +use digest_fn::fixture; +#[allow(unused_imports)] +use digest_fn::floats; +#[allow(unused_imports)] use digest_fn::half_bits; #[allow(unused_imports)] -use digest_fn::associate; -#[allow(unused_imports)] -use digest_fn::write_file; -#[allow(unused_imports)] -use digest_fn::ordered; -#[allow(unused_imports)] use digest_fn::measure; #[allow(unused_imports)] +use digest_fn::ordered; +#[allow(unused_imports)] use digest_fn::prefix; #[allow(unused_imports)] -use digest_fn::floats; +use digest_fn::read; +#[allow(unused_imports)] +use digest_fn::upload; +#[allow(unused_imports)] +use digest_fn::write_file; #[path = "mmq_native_resident_gpu/native_hidden_q8_fn.rs"] mod native_hidden_q8_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mmq_native_resident_gpu/digest_fn.rs b/crates/cuda-driver/src/mmq_native_resident_gpu/digest_fn.rs index a5a5fcc1..36e0b97d 100644 --- a/crates/cuda-driver/src/mmq_native_resident_gpu/digest_fn.rs +++ b/crates/cuda-driver/src/mmq_native_resident_gpu/digest_fn.rs @@ -12,18 +12,11 @@ pub(super) fn digest(b: &[u8]) -> String { s } pub(super) fn read(path: &Path, max: usize) -> Vec { - let mut f = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(path) - .unwrap(); + let mut f = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path).unwrap(); let before = f.metadata().unwrap(); assert!(before.is_file() && before.len() <= max as u64); let mut b = Vec::new(); - std::io::Read::by_ref(&mut f) - .take(max as u64 + 1) - .read_to_end(&mut b) - .unwrap(); + std::io::Read::by_ref(&mut f).take(max as u64 + 1).read_to_end(&mut b).unwrap(); let after = f.metadata().unwrap(); assert_eq!( ( @@ -35,15 +28,7 @@ pub(super) fn read(path: &Path, max: usize) -> Vec { before.ctime(), before.ctime_nsec() ), - ( - after.dev(), - after.ino(), - after.len(), - after.mtime(), - after.mtime_nsec(), - after.ctime(), - after.ctime_nsec() - ) + (after.dev(), after.ino(), after.len(), after.mtime(), after.mtime_nsec(), after.ctime(), after.ctime_nsec()) ); assert_eq!(b.len() as u64, before.len()); b @@ -53,14 +38,8 @@ pub(super) fn fixture() -> [Vec; 4] { assert!(root.is_absolute()); assert_eq!(root.canonicalize().unwrap(), root); let manifest = read(&root.join("ROOT-GU-DOWN.tsv"), 8192); - assert_eq!( - digest(&manifest), - std::env::var("LELEKA_REAL_GU_MANIFEST_SHA").unwrap() - ); - assert_eq!( - digest(&manifest), - "6f3b0df514a1228340377fb3566d135ce3e7a8a4055d602db13d7250e98b89b5" - ); + assert_eq!(digest(&manifest), std::env::var("LELEKA_REAL_GU_MANIFEST_SHA").unwrap()); + assert_eq!(digest(&manifest), "6f3b0df514a1228340377fb3566d135ce3e7a8a4055d602db13d7250e98b89b5"); let text = std::str::from_utf8(&manifest).unwrap(); let mut lines = text.lines(); assert_eq!(lines.next(), Some("schema\tstra169-real-gu-v1")); @@ -69,14 +48,8 @@ pub(super) fn fixture() -> [Vec; 4] { let p: Vec<_> = line.split('\t').collect(); assert_eq!(p.len(), 4); assert_eq!(p[0], "file"); - assert!(matches!( - p[1], - "EXTRACTION.json" | "input.f32" | "gate.raw" | "up.raw" | "down.raw" - )); - assert!( - pins.insert(p[1], (p[2].parse::().unwrap(), p[3])) - .is_none() - ); + assert!(matches!(p[1], "EXTRACTION.json" | "input.f32" | "gate.raw" | "up.raw" | "down.raw")); + assert!(pins.insert(p[1], (p[2].parse::().unwrap(), p[3])).is_none()); } assert_eq!(pins.len(), 5); let mut values = BTreeMap::new(); @@ -99,26 +72,12 @@ pub(super) fn fixture() -> [Vec; 4] { values.insert(name, b); } let input = values.remove("input.f32").unwrap(); - assert_eq!( - digest(&input), - "db757265bb72da9435ef26bf0158b77ec661ad95e635fcb94d0025d378c0d267" - ); - assert_eq!( - digest(&input[..10240]), - "76a3b4c4db8e86b89c4966a4db6068fc46cac2648c6356811ac167e13e8fc8ea" - ); - assert_eq!( - digest(&input[10240..]), - "bdca56ede51d8ff62b3af41ad9bf04ffed09707b4c7e4037f39e7363c18a708c" - ); + assert_eq!(digest(&input), "db757265bb72da9435ef26bf0158b77ec661ad95e635fcb94d0025d378c0d267"); + assert_eq!(digest(&input[..10240]), "76a3b4c4db8e86b89c4966a4db6068fc46cac2648c6356811ac167e13e8fc8ea"); + assert_eq!(digest(&input[10240..]), "bdca56ede51d8ff62b3af41ad9bf04ffed09707b4c7e4037f39e7363c18a708c"); assert!(finite_f32(&input)); // ROOT pins EXTRACTION.json only after actual GGUF topology/offset and matrix-byte checks. - [ - input, - values.remove("gate.raw").unwrap(), - values.remove("up.raw").unwrap(), - values.remove("down.raw").unwrap(), - ] + [input, values.remove("gate.raw").unwrap(), values.remove("up.raw").unwrap(), values.remove("down.raw").unwrap()] } pub(super) fn upload<'c>(c: &'c Context<'c>, b: &[u8]) -> DeviceBuffer<'c> { let mut d = c.allocate(b.len()).unwrap(); @@ -161,19 +120,14 @@ pub(super) fn associate(native: &[u8], d4: &[u8], columns: usize) { for sub in 0..4 { let nb = block * 4 + sub; if nb < native_blocks { - let n = &native - [(row * native_blocks + nb) * 36..(row * native_blocks + nb + 1) * 36]; + let n = &native[(row * native_blocks + nb) * 36..(row * native_blocks + nb + 1) * 36]; let scale = half_bits(u16::from_le_bytes([n[0], n[1]])); assert_ne!(u16::from_le_bytes([n[2], n[3]]) & 0x7c00, 0x7c00); assert_eq!(&out[sub * 4..sub * 4 + 4], &scale.to_le_bytes()); assert_eq!(&out[16 + sub * 32..16 + (sub + 1) * 32], &n[4..]); } else { assert!(out[sub * 4..sub * 4 + 4].iter().all(|v| *v == 0)); - assert!( - out[16 + sub * 32..16 + (sub + 1) * 32] - .iter() - .all(|v| *v == 0) - ); + assert!(out[16 + sub * 32..16 + (sub + 1) * 32].iter().all(|v| *v == 0)); } } } @@ -181,12 +135,7 @@ pub(super) fn associate(native: &[u8], d4: &[u8], columns: usize) { assert!(d4[payload..].iter().all(|v| *v == 0)); } pub(super) fn write_file(root: &Path, name: &str, b: &[u8]) { - let mut f = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(root.join(name)) - .unwrap(); + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o600).open(root.join(name)).unwrap(); f.write_all(b).unwrap(); } pub(super) fn ordered(v: f32) -> u32 { @@ -200,13 +149,7 @@ pub(super) fn measure(row: usize, role: &str, arm: &str, a: &[u8], b: &[u8]) -> let mut first = None; let mut abs = 0.0f64; let mut ulp = 0u32; - for (i, (x, y)) in a - .as_chunks::<4>() - .0 - .iter() - .zip(b.as_chunks::<4>().0) - .enumerate() - { + for (i, (x, y)) in a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).enumerate() { let x = f32::from_le_bytes(*x); let y = f32::from_le_bytes(*y); if x.to_bits() != y.to_bits() { @@ -227,9 +170,5 @@ pub(super) fn prefix(b: &DeviceBuffer<'_>, amount: usize) -> Vec { } pub(super) fn floats(b: &[u8]) -> Vec { assert!(finite_f32(b)); - b.as_chunks::<4>() - .0 - .iter() - .map(|v| f32::from_le_bytes(*v)) - .collect() + b.as_chunks::<4>().0.iter().map(|v| f32::from_le_bytes(*v)).collect() } diff --git a/crates/cuda-driver/src/mmq_native_resident_gpu/native_hidden_q8_fn.rs b/crates/cuda-driver/src/mmq_native_resident_gpu/native_hidden_q8_fn.rs index e89877aa..cd1ee150 100644 --- a/crates/cuda-driver/src/mmq_native_resident_gpu/native_hidden_q8_fn.rs +++ b/crates/cuda-driver/src/mmq_native_resident_gpu/native_hidden_q8_fn.rs @@ -9,21 +9,11 @@ pub(super) fn native_hidden_q8(context: &Context<'_>, input: &DeviceBuffer<'_>) let mut status = context.allocate(4).unwrap(); status.copy_from(&[0; 4]).unwrap(); let guard = context.enter().unwrap(); - let k = context - .fixed_kernel(FixedOperation::CommonQuantize) - .unwrap(); + let k = context.fixed_kernel(FixedOperation::CommonQuantize).unwrap(); guard.finish().unwrap(); - let mut args = ffi::Q8QuantizeArguments::new( - input.handle.unwrap(), - q.handle.unwrap(), - status.handle.unwrap(), - 640, - ); + let mut args = ffi::Q8QuantizeArguments::new(input.handle.unwrap(), q.handle.unwrap(), status.handle.unwrap(), 640); let guard = context.enter().unwrap(); - let launch = context - .driver - .api - .launch_q8_quantize(k.function, 3, &mut args); + let launch = context.driver.api.launch_q8_quantize(k.function, 3, &mut args); context.complete_launch(launch, args, guard).unwrap(); assert_eq!(download(&status), [0; 4]); let result = download(&q); diff --git a/crates/cuda-driver/src/mmq_numeric_gpu.rs b/crates/cuda-driver/src/mmq_numeric_gpu.rs index 774db6a4..159b4350 100644 --- a/crates/cuda-driver/src/mmq_numeric_gpu.rs +++ b/crates/cuda-driver/src/mmq_numeric_gpu.rs @@ -38,16 +38,9 @@ struct Case { #[test] #[ignore = "ROOT-only original-first pinned reference; actual CUDA, never automatic suite"] fn original_first_mmq_adaptive_and_distinct_fixed_profiles_exact() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), - Ok("yes"), - "explicit GPU opt-in" - ); - let root = PathBuf::from( - std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").expect("ROOT reference directory"), - ); - let pin = - std::env::var("LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA").expect("ROOT reference pin"); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), Ok("yes"), "explicit GPU opt-in"); + let root = PathBuf::from(std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").expect("ROOT reference directory")); + let pin = std::env::var("LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA").expect("ROOT reference pin"); let receipt = Receipt::load(root, &pin); let inputs: Vec<_> = [ (18, MmqFormat::Iq3XxsGateUp, 640, 2560, 627200, 0), @@ -55,17 +48,12 @@ fn original_first_mmq_adaptive_and_distinct_fixed_profiles_exact() { (20, MmqFormat::Iq4NlDown, 2560, 640, 921600, 216), (42, MmqFormat::Q2Down, 2560, 640, 460800, 108), ] - .map(|(kind, format, rows, columns, raw, tail)| { - (format, cases(&receipt, kind, rows, columns, raw, tail)) - }) + .map(|(kind, format, rows, columns, raw, tail)| (format, cases(&receipt, kind, rows, columns, raw, tail))) .into(); let driver = Driver::load().unwrap(); let context = driver.device(0).unwrap().create_context(BUDGET).unwrap(); let experiment = context.mmq_experiment().unwrap(); - assert!( - (1..=256).contains(&experiment.sms), - "closed fixture SM budget" - ); + assert!((1..=256).contains(&experiment.sms), "closed fixture SM budget"); let mut words = 0_usize; let mut packed_bytes = 0_usize; let mut launches = 0_usize; @@ -81,28 +69,22 @@ fn original_first_mmq_adaptive_and_distinct_fixed_profiles_exact() { let mut input = context.allocate(case.input.len()).unwrap(); input.copy_from(&case.input).unwrap(); let mut output = context.allocate(case.adaptive.len()).unwrap(); - for (profile, reference) in [ - (MmqProfile::OriginalAdaptive, &case.adaptive), - (MmqProfile::OriginalStreamK, &case.fixed), - ] { + for (profile, reference) in + [(MmqProfile::OriginalAdaptive, &case.adaptive), (MmqProfile::OriginalStreamK, &case.fixed)] + { if profile == MmqProfile::OriginalStreamK && case.tokens == 64 { continue; } output.copy_from(&vec![0xff; reference.len()]).unwrap(); let charge = context.allocated_bytes(); - let (values, q8) = experiment - .project_observed(profile, &weights, &input, case.tokens, &mut output) - .unwrap(); + let (values, q8) = + experiment.project_observed(profile, &weights, &input, case.tokens, &mut output).unwrap(); assert_eq!(&*q8, case.q8.as_slice(), "complete original D4Q8 bytes"); compare(&values, reference, "MMQ exact original profile"); let mut actual = vec![0; reference.len()]; output.copy_to(&mut actual).unwrap(); assert_eq!(&actual, reference); - assert_eq!( - context.allocated_bytes(), - charge, - "all projection scratch freed" - ); + assert_eq!(context.allocated_bytes(), charge, "all projection scratch freed"); let mut source_after = vec![0; case.input.len()]; input.copy_to(&mut source_after).unwrap(); assert_eq!(source_after, case.input); @@ -138,19 +120,19 @@ fn original_first_mmq_adaptive_and_distinct_fixed_profiles_exact() { #[path = "mmq_numeric_gpu/digest_fn.rs"] mod digest_fn; #[allow(unused_imports)] +use digest_fn::compare; +#[allow(unused_imports)] use digest_fn::digest; #[allow(unused_imports)] -use digest_fn::hex; -#[allow(unused_imports)] -use digest_fn::read_regular; -#[allow(unused_imports)] use digest_fn::field; #[allow(unused_imports)] -use digest_fn::integer; -#[allow(unused_imports)] use digest_fn::finite; #[allow(unused_imports)] -use digest_fn::compare; +use digest_fn::hex; +#[allow(unused_imports)] +use digest_fn::integer; +#[allow(unused_imports)] +use digest_fn::read_regular; #[path = "mmq_numeric_gpu/cases_fn.rs"] mod cases_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs b/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs index a485bce9..7d471878 100644 --- a/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs +++ b/crates/cuda-driver/src/mmq_numeric_gpu/cases_fn.rs @@ -47,31 +47,15 @@ pub(super) fn cases( let sms = integer(&metadata, "nsm"); assert!((1..=256).contains(&sms)); let tiles = rows / 128; - let grid = if 100 * tiles / (sms * tiles.div_ceil(sms)) >= 90 { - tiles - } else { - sms - }; + let grid = if 100 * tiles / (sms * tiles.div_ceil(sms)) >= 90 { tiles } else { sms }; for key in ["original_streamk_grid", "fixed_j64_streamk_grid"] { assert_eq!(integer(&metadata, key), grid); } for key in ["original_streamk_fixup", "fixed_j64_streamk_fixup"] { - assert_eq!( - field(&metadata, key), - if tiles.is_multiple_of(grid) { - "false" - } else { - "true" - } - ); + assert_eq!(field(&metadata, key), if tiles.is_multiple_of(grid) { "false" } else { "true" }); } assert_eq!(integer(&metadata, "auxiliary_tiling_grid"), tiles); - for key in [ - "original_first", - "input_column_major", - "inputs_weights_unchanged", - "model_free", - ] { + for key in ["original_first", "input_column_major", "inputs_weights_unchanged", "model_free"] { assert_eq!(field(&metadata, key), "true"); } assert_eq!(input.len(), columns * tokens as usize * 4); @@ -86,14 +70,7 @@ pub(super) fn cases( for block in q8[..q8.len() - 9216].as_chunks::<144>().0 { finite(&block[..16]); } - cases.push(Case { - tokens, - input, - q8, - adaptive, - fixed, - metadata, - }); + cases.push(Case { tokens, input, q8, adaptive, fixed, metadata }); } (weights, cases) } diff --git a/crates/cuda-driver/src/mmq_numeric_gpu/digest_fn.rs b/crates/cuda-driver/src/mmq_numeric_gpu/digest_fn.rs index 601eab8b..3cca8ff8 100644 --- a/crates/cuda-driver/src/mmq_numeric_gpu/digest_fn.rs +++ b/crates/cuda-driver/src/mmq_numeric_gpu/digest_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn digest(bytes: &[u8]) -> String { use std::fmt::Write; let mut out = String::with_capacity(64); @@ -14,12 +13,7 @@ pub(super) fn digest(bytes: &[u8]) -> String { } pub(super) fn hex(value: &str) { assert_eq!(value.len(), 64, "SHA256 length"); - assert!( - value - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)), - "SHA256 encoding" - ); + assert!(value.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)), "SHA256 encoding"); } pub(super) fn read_regular(path: &Path, limit: usize) -> Vec { let mut file = OpenOptions::new() @@ -28,20 +22,11 @@ pub(super) fn read_regular(path: &Path, limit: usize) -> Vec { .open(path) .expect("open pinned regular file"); let before = file.metadata().unwrap(); - assert!( - before.is_file() && before.len() <= limit as u64, - "bounded regular fixture" - ); + assert!(before.is_file() && before.len() <= limit as u64, "bounded regular fixture"); let mut bytes = Vec::new(); - file.by_ref() - .take(limit as u64 + 1) - .read_to_end(&mut bytes) - .unwrap(); + file.by_ref().take(limit as u64 + 1).read_to_end(&mut bytes).unwrap(); let after = file.metadata().unwrap(); - assert_eq!( - (before.dev(), before.ino(), before.len()), - (after.dev(), after.ino(), after.len()) - ); + assert_eq!((before.dev(), before.ino(), before.len()), (after.dev(), after.ino(), after.len())); assert_eq!(bytes.len() as u64, before.len(), "fixture changed length"); bytes } @@ -49,11 +34,7 @@ impl Receipt { pub(super) fn load(root: PathBuf, expected: &str) -> Self { hex(expected); assert!(root.is_absolute()); - assert_eq!( - root.canonicalize().unwrap(), - root, - "canonical fixture directory" - ); + assert_eq!(root.canonicalize().unwrap(), root, "canonical fixture directory"); let bytes = read_regular(&root.join("ROOT-REFERENCE.tsv"), 64 * 1024); assert_eq!(digest(&bytes), expected, "ROOT manifest pin"); let text = std::str::from_utf8(&bytes).unwrap(); @@ -63,24 +44,12 @@ impl Receipt { let fields: Vec<_> = line.split('\t').collect(); match fields.as_slice() { ["file", name, length, sha] => { - assert!( - Path::new(name) - .components() - .all(|c| matches!(c, Component::Normal(_))) - ); + assert!(Path::new(name).components().all(|c| matches!(c, Component::Normal(_)))); hex(sha); let bytes: usize = length.parse().unwrap(); assert!(bytes > 0 && bytes <= 64 * 1024 * 1024); assert!( - files - .insert( - (*name).to_owned(), - Pin { - bytes, - sha: (*sha).to_owned() - } - ) - .is_none(), + files.insert((*name).to_owned(), Pin { bytes, sha: (*sha).to_owned() }).is_none(), "duplicate file" ); } @@ -99,11 +68,7 @@ impl Receipt { ("profile", "sm120-fastmath-adaptive-original-first"), ("cases", "12"), ] { - assert_eq!( - headers.get(key).copied(), - Some(value), - "ROOT provenance {key}" - ); + assert_eq!(headers.get(key).copied(), Some(value), "ROOT provenance {key}"); } let mut allowed = vec![ "COMPLETE.json".to_owned(), @@ -118,19 +83,12 @@ impl Receipt { } } allowed.sort(); - assert_eq!( - files.keys().cloned().collect::>(), - allowed, - "exact 87 pinned files" - ); + assert_eq!(files.keys().cloned().collect::>(), allowed, "exact 87 pinned files"); let receipt = Self { root, files }; for name in receipt.files.keys() { let _ = receipt.read(name); } - assert_eq!( - digest(&receipt.read("ORACLE-SOURCE-MANIFEST.json")), - SOURCE_SHA - ); + assert_eq!(digest(&receipt.read("ORACLE-SOURCE-MANIFEST.json")), SOURCE_SHA); assert!(receipt.read("original_mmq_oracle").starts_with(b"\x7fELF")); let complete = String::from_utf8(receipt.read("COMPLETE.json")).unwrap(); for (key, value) in [ @@ -158,14 +116,7 @@ impl Receipt { pub(super) fn field<'a>(json: &'a str, key: &str) -> &'a str { let needle = format!("\"{key}\":"); assert_eq!(json.matches(&needle).count(), 1, "unique metadata key"); - json.split_once(&needle) - .unwrap() - .1 - .trim_start() - .split([',', '}']) - .next() - .unwrap() - .trim() + json.split_once(&needle).unwrap().1.trim_start().split([',', '}']).next().unwrap().trim() } pub(super) fn integer(json: &str, key: &str) -> usize { field(json, key).parse().unwrap() @@ -173,10 +124,7 @@ pub(super) fn integer(json: &str, key: &str) -> usize { pub(super) fn finite(bytes: &[u8]) { let (words, tail) = bytes.as_chunks::<4>(); assert!(tail.is_empty()); - assert!( - words.iter().all(|v| f32::from_le_bytes(*v).is_finite()), - "full finite reference" - ); + assert!(words.iter().all(|v| f32::from_le_bytes(*v).is_finite()), "full finite reference"); } pub(super) fn compare(values: &[f32], reference: &[u8], label: &str) { let (words, tail) = reference.as_chunks::<4>(); @@ -184,10 +132,6 @@ pub(super) fn compare(values: &[f32], reference: &[u8], label: &str) { assert_eq!(values.len(), words.len()); for (index, (actual, expected)) in values.iter().zip(words).enumerate() { assert!(actual.is_finite()); - assert_eq!( - actual.to_bits(), - u32::from_le_bytes(*expected), - "{label} word {index}" - ); + assert_eq!(actual.to_bits(), u32::from_le_bytes(*expected), "{label} word {index}"); } } diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs index d9754cd2..727ff8ca 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_chunkstream.rs @@ -21,7 +21,10 @@ impl ChunkStream { topup: usize, context: usize, ) -> Result { - if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 + if targets.is_empty() + || copied.len() != targets.len() + || used.len() != targets.len() + || first >= 48 || !(starts.is_empty() || starts.len() == targets.len()) { return Err(Error::InvalidProjectionShape); @@ -97,9 +100,10 @@ impl ChunkStream { } /// Whether entry `k` copies exactly these gate/up/down byte ranges. pub(in super::super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool { - self.core.entries.get(k).is_some_and(|e| { - e.exact.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len()) - }) + self.core + .entries + .get(k) + .is_some_and(|e| e.exact.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len())) } /// Slot offsets of entry `k`'s exact gate/up/down pieces. pub(in super::super) fn entry_at(&self, k: usize) -> Result<[usize; 3]> { diff --git a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_core.rs b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_core.rs index 9809fa3d..f5fd7a08 100644 --- a/crates/cuda-driver/src/mmq_original_chunk_stream/impl_core.rs +++ b/crates/cuda-driver/src/mmq_original_chunk_stream/impl_core.rs @@ -11,9 +11,7 @@ impl Core { self.layer_start[usize::from(layer) + 1] } pub(super) fn limit(&self, wanted: usize) -> usize { - wanted - .min(self.entries.len()) - .min(self.consumed.load(Ordering::Acquire) + self.ring().min(self.ahead)) + wanted.min(self.entries.len()).min(self.consumed.load(Ordering::Acquire) + self.ring().min(self.ahead)) } /// Inline mode: enqueue entries until `wanted` (never past the ring: entry k - ring must be consumed first). pub(super) fn issue_until(&self, wanted: usize) -> Result<()> { @@ -99,7 +97,12 @@ impl Core { if end > capacity { return Err(Error::InvalidSize); } - self.api.copy_raw(target.checked_subspan(capacity, entry.dest[piece], length)?, address, length, self.copy)?; + self.api.copy_raw( + target.checked_subspan(capacity, entry.dest[piece], length)?, + address, + length, + self.copy, + )?; self.calls.fetch_add(1, Ordering::Relaxed); copied_bytes += length; } @@ -121,7 +124,8 @@ impl Core { break; } let ready = k < self.limit(k + 1) - && (k < self.depth || self.api.event_query(self.copied[(k - self.depth) % self.ring()]).unwrap_or(false)); + && (k < self.depth + || self.api.event_query(self.copied[(k - self.depth) % self.ring()]).unwrap_or(false)); if !ready { idle += 1; if idle < 200 { diff --git a/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs b/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs index 552c10a3..e38f677f 100644 --- a/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs +++ b/crates/cuda-driver/src/mmq_original_enqueue_ffi.rs @@ -16,11 +16,7 @@ pub(crate) enum Command { Project(FunctionHandle, Layout, u32, MmqArguments), Fixup(FunctionHandle, u32, MmqFixupArguments), } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod platform { use super::*; use std::ffi::{CStr, c_void}; @@ -56,21 +52,12 @@ mod platform { copy: H2D, } fn check(name: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: name, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code: n }) } } impl Api { pub(crate) fn load() -> Result { // SAFETY: fixed NUL-terminated library name and flags. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -78,35 +65,20 @@ mod platform { // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; if p.is_null() { - Err(Error::MissingSymbol( - n.to_str().unwrap_or("Original ring symbol"), - )) + Err(Error::MissingSymbol(n.to_str().unwrap_or("Original ring symbol"))) } else { Ok(p) } } // SAFETY: non-null `cuLaunchKernel` address; `Launch` is its exact Linux64 C signature. - let launch = unsafe { - std::mem::transmute::(symbol(&library, c"cuLaunchKernel")?) - }; + let launch = unsafe { std::mem::transmute::(symbol(&library, c"cuLaunchKernel")?) }; // SAFETY: non-null `cuMemcpyHtoDAsync_v2` address; `H2D` is its exact Linux64 C signature. - let copy = unsafe { - std::mem::transmute::(symbol(&library, c"cuMemcpyHtoDAsync_v2")?) - }; - Ok(Self { - _library: library, - launch, - copy, - }) + let copy = unsafe { std::mem::transmute::(symbol(&library, c"cuMemcpyHtoDAsync_v2")?) }; + Ok(Self { _library: library, launch, copy }) } /// Sources are the actual registered immutable bank slices, retained by /// the ring owner until used/drain. Destination is a real arena slot. - pub(crate) fn copy_registered( - &self, - destination: BufferHandle, - source: &[u8], - stream: usize, - ) -> Result<()> { + pub(crate) fn copy_registered(&self, destination: BufferHandle, source: &[u8], stream: usize) -> Result<()> { if stream == 0 || source.is_empty() { return Err(Error::InvalidProjectionShape); } @@ -114,12 +86,7 @@ mod platform { // SAFETY: destination extent validated (16-byte aligned) and `source` is a registered immutable bank slice the ring keeps retained // (`Ring.bank` Rc) until `Ring::drain`/close synchronized this non-default `stream`. check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy)( - destination.0, - source.as_ptr().cast(), - source.len(), - stream as Handle, - ) + (self.copy)(destination.0, source.as_ptr().cast(), source.len(), stream as Handle) }) } pub(crate) fn enqueue(&self, command: &mut Command, stream: usize) -> Result<()> { @@ -143,29 +110,13 @@ mod platform { if !(1..=81920).contains(rows) { return Err(Error::InvalidProjectionShape); } - ( - *f, - (*rows * 640).div_ceil(256), - 1, - 256, - 1, - 0, - a.parameters(), - ) + (*f, (*rows * 640).div_ceil(256), 1, 256, 1, 0, a.parameters()) } Command::Quantize(f, l, a) => { if l.tokens == 0 || l.tokens > 81920 || !l.padded_columns.is_multiple_of(512) { return Err(Error::InvalidProjectionShape); } - ( - *f, - l.tokens, - l.padded_columns / 512, - 128, - 1, - 0, - a.parameters(), - ) + (*f, l.tokens, l.padded_columns / 512, 128, 1, 0, a.parameters()) } Command::Project(f, l, grid, a) => { if *grid == 0 { @@ -202,11 +153,7 @@ mod platform { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use platform::Api; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mmq_original_group.rs b/crates/cuda-driver/src/mmq_original_group.rs index 73445818..0491238b 100644 --- a/crates/cuda-driver/src/mmq_original_group.rs +++ b/crates/cuda-driver/src/mmq_original_group.rs @@ -25,9 +25,27 @@ const FORMATS: [MmqFormat; 7] = [ ]; // ROOT seals actual compiled bytes; None is an intentional fail-closed source donor. const SEALED: [Option<(usize, [u8; 32])>; 3] = [ - Some((6091, [169, 19, 153, 54, 0, 135, 140, 237, 209, 40, 190, 224, 247, 118, 137, 81, 25, 229, 86, 227, 63, 42, 215, 13, 173, 240, 142, 158, 26, 126, 185, 189])), - Some((13083404, [234, 13, 183, 133, 5, 40, 158, 142, 116, 58, 85, 46, 242, 61, 237, 152, 214, 104, 164, 137, 198, 121, 160, 228, 72, 147, 176, 0, 68, 91, 72, 199])), - Some((1455509, [168, 199, 81, 145, 186, 142, 247, 164, 87, 32, 130, 72, 80, 214, 76, 244, 67, 69, 155, 48, 188, 83, 121, 171, 128, 126, 184, 62, 38, 20, 136, 63])), + Some(( + 6091, + [ + 169, 19, 153, 54, 0, 135, 140, 237, 209, 40, 190, 224, 247, 118, 137, 81, 25, 229, 86, 227, 63, 42, 215, + 13, 173, 240, 142, 158, 26, 126, 185, 189, + ], + )), + Some(( + 13083404, + [ + 234, 13, 183, 133, 5, 40, 158, 142, 116, 58, 85, 46, 242, 61, 237, 152, 214, 104, 164, 137, 198, 121, 160, + 228, 72, 147, 176, 0, 68, 91, 72, 199, + ], + )), + Some(( + 1455509, + [ + 168, 199, 81, 145, 186, 142, 247, 164, 87, 32, 130, 72, 80, 214, 76, 244, 67, 69, 155, 48, 188, 83, 121, + 171, 128, 126, 184, 62, 38, 20, 136, 63, + ], + )), ]; pub(crate) struct OriginalGroupBank<'ctx> { context: &'ctx Context<'ctx>, @@ -85,24 +103,24 @@ mod asset_fn; #[allow(unused_imports)] pub(crate) use asset_fn::asset; #[allow(unused_imports)] -use asset_fn::sizes; -#[allow(unused_imports)] pub use asset_fn::original_mmq_group_bank_bytes; +#[allow(unused_imports)] +use asset_fn::sizes; #[path = "mmq_original_group/kind_fn.rs"] mod kind_fn; #[allow(unused_imports)] -use kind_fn::kind; -#[allow(unused_imports)] -use kind_fn::shared; -#[allow(unused_imports)] use kind_fn::format_index; #[allow(unused_imports)] +use kind_fn::kind; +#[allow(unused_imports)] use kind_fn::layout; +#[allow(unused_imports)] +use kind_fn::shared; #[path = "mmq_original_group/impl_mmqworkspace.rs"] mod impl_mmqworkspace; #[path = "mmq_original_group/impl_originalmmqlayer.rs"] mod impl_originalmmqlayer; -#[path = "mmq_original_group/impl_originalmmqoutput.rs"] -mod impl_originalmmqoutput; #[path = "mmq_original_group/impl_originalmmqlayer_2.rs"] mod impl_originalmmqlayer_2; +#[path = "mmq_original_group/impl_originalmmqoutput.rs"] +mod impl_originalmmqoutput; diff --git a/crates/cuda-driver/src/mmq_original_group/asset_fn.rs b/crates/cuda-driver/src/mmq_original_group/asset_fn.rs index 4c704624..79f2f835 100644 --- a/crates/cuda-driver/src/mmq_original_group/asset_fn.rs +++ b/crates/cuda-driver/src/mmq_original_group/asset_fn.rs @@ -10,8 +10,7 @@ pub(crate) fn asset(kind: u32) -> Result<&'static [u8]> { 2 => include_bytes!("../mmq_original_group_fixup.ptx"), _ => return Err(Error::InvalidProjectionShape), }; - let (size, sha) = - SEALED[kind as usize].ok_or(Error::InvalidDriverValue("unsealed Original MMQ group"))?; + let (size, sha) = SEALED[kind as usize].ok_or(Error::InvalidDriverValue("unsealed Original MMQ group"))?; if bytes.len() != size || bytes.last() != Some(&0) || !bytes[..bytes.len() - 1].is_ascii() @@ -46,27 +45,16 @@ pub(super) fn sizes(capacity: u32, sms: u32) -> Result<[usize; 12]> { /// Actual eager group-bank charge; scratch depends on the real SM count, not a /// guessed device. This excludes unchanged existing workspace/native owners. pub fn original_mmq_group_bank_bytes(capacity: u32, sms: u32) -> Result { - sizes(capacity, sms)? - .into_iter() - .try_fold(0usize, |a, b| a.checked_add(b).ok_or(Error::BudgetExceeded)) + sizes(capacity, sms)?.into_iter().try_fold(0usize, |a, b| a.checked_add(b).ok_or(Error::BudgetExceeded)) } impl<'ctx> OriginalGroupBank<'ctx> { - pub(super) fn new( - context: &'ctx Context<'ctx>, - sms: u32, - capacity: u32, - arena_only: bool, - ) -> Result { + pub(super) fn new(context: &'ctx Context<'ctx>, sms: u32, capacity: u32, arena_only: bool) -> Result { for k in 0..3 { asset(k)?; } crate::bringup_trace!("PROBE group bank new: sms={sms} capacity={capacity}"); let sizes = sizes(capacity, sms)?; - let charge = if arena_only { - sizes[TMP] - } else { - original_mmq_group_bank_bytes(capacity, sms)? - }; + let charge = if arena_only { sizes[TMP] } else { original_mmq_group_bank_bytes(capacity, sms)? }; if context .allocated_bytes() .checked_add(charge) @@ -75,11 +63,7 @@ impl<'ctx> OriginalGroupBank<'ctx> { { return Err(Error::BudgetExceeded); } - if context.memory_info()?.0 - < charge - .checked_add(128 * 1024 * 1024) - .ok_or(Error::BudgetExceeded)? - { + if context.memory_info()?.0 < charge.checked_add(128 * 1024 * 1024).ok_or(Error::BudgetExceeded)? { return Err(Error::BudgetExceeded); } let mut bank = Self { @@ -128,7 +112,9 @@ impl<'ctx> OriginalGroupBank<'ctx> { continue; } let kind = kind(format); - crate::bringup_trace!("PROBE group i={i} j={j} kind={kind} width={width} shared={shared} limit={limit}"); + crate::bringup_trace!( + "PROBE group i={i} j={j} kind={kind} width={width} shared={shared} limit={limit}" + ); let f = context.driver.api.mmq_original_group_function( bank.modules[1].ok_or(Error::ContextPoisoned)?, kind, @@ -150,7 +136,9 @@ impl<'ctx> OriginalGroupBank<'ctx> { } Ok(()) })(); - if let Err(e) = &operation { crate::bringup_trace!("PROBE group operation err: {e:?}"); } + if let Err(e) = &operation { + crate::bringup_trace!("PROBE group operation err: {e:?}"); + } let pop = guard.finish(); if operation.is_err() || pop.is_err() { context.poisoned.set(true); @@ -158,14 +146,9 @@ impl<'ctx> OriginalGroupBank<'ctx> { combine(operation, pop)?; // Module residency is not an invented typed charge. Requery actual physical // room after the real loads before allocating this complete charged bank. - let required = charge - .checked_add(128 * 1024 * 1024) - .ok_or(Error::BudgetExceeded)?; + let required = charge.checked_add(128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; if context.memory_info()?.0 < required - || context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } @@ -185,18 +168,9 @@ impl<'ctx> OriginalGroupBank<'ctx> { if self.failed || self.context.is_poisoned() { return Err(Error::ContextPoisoned); } - self.buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.buffers.get(index).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } - pub(super) fn handle( - &self, - index: usize, - offset: usize, - bytes: usize, - align: u64, - ) -> Result { + pub(super) fn handle(&self, index: usize, offset: usize, bytes: usize, align: u64) -> Result { let b = self.buffer(index)?; if !std::ptr::eq(self.context, b.context) { return Err(Error::ContextMismatch); diff --git a/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs b/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs index 7f522e21..85159ce9 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_mmqworkspace.rs @@ -41,11 +41,7 @@ impl<'ctx> MmqWorkspace<'ctx> { } pub fn original_expert_capacity(&self) -> Result { self.check()?; - Ok(self - .original_group - .as_ref() - .ok_or(Error::UnsupportedProjection)? - .capacity) + Ok(self.original_group.as_ref().ok_or(Error::UnsupportedProjection)?.capacity) } pub fn prepare_original_expert_layer<'lease>( &'lease mut self, @@ -55,10 +51,7 @@ impl<'ctx> MmqWorkspace<'ctx> { sorted_source_rows: &[u32], ) -> Result> { self.check()?; - let bank = self - .original_group - .as_ref() - .ok_or(Error::UnsupportedProjection)?; + let bank = self.original_group.as_ref().ok_or(Error::UnsupportedProjection)?; if bank.arena_only || tokens == 0 || tokens > bank.capacity @@ -72,13 +65,8 @@ impl<'ctx> MmqWorkspace<'ctx> { if values.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidQ8Activation); } - let total = counts.iter().try_fold(0u32, |a, b| { - a.checked_add(*b).ok_or(Error::InvalidProjectionShape) - })?; - if total - != tokens - .checked_mul(10) - .ok_or(Error::InvalidProjectionShape)? + let total = counts.iter().try_fold(0u32, |a, b| a.checked_add(*b).ok_or(Error::InvalidProjectionShape))?; + if total != tokens.checked_mul(10).ok_or(Error::InvalidProjectionShape)? || sorted_source_rows.len() != total as usize || sorted_source_rows.iter().any(|r| *r >= tokens) { @@ -87,8 +75,7 @@ impl<'ctx> MmqWorkspace<'ctx> { // Every actual source row appears exactly10 times; each expert's columns are // strictly increasing. This is transport geometry, not a route certificate. let mut uses = Vec::new(); - uses.try_reserve_exact(tokens as usize) - .map_err(|_| Error::HostAllocation)?; + uses.try_reserve_exact(tokens as usize).map_err(|_| Error::HostAllocation)?; uses.resize(tokens as usize, 0u8); let mut at = 0; for count in counts { @@ -97,9 +84,7 @@ impl<'ctx> MmqWorkspace<'ctx> { return Err(Error::InvalidProjectionShape); } for r in rows { - uses[*r as usize] = uses[*r as usize] - .checked_add(1) - .ok_or(Error::InvalidProjectionShape)?; + uses[*r as usize] = uses[*r as usize].checked_add(1).ok_or(Error::InvalidProjectionShape)?; } at += *count as usize; } @@ -107,23 +92,13 @@ impl<'ctx> MmqWorkspace<'ctx> { return Err(Error::InvalidProjectionShape); } let mut owned_counts = Vec::new(); - owned_counts - .try_reserve_exact(counts.len()) - .map_err(|_| Error::HostAllocation)?; + owned_counts.try_reserve_exact(counts.len()).map_err(|_| Error::HostAllocation)?; owned_counts.extend_from_slice(counts); let mut bounds = Vec::new(); - bounds - .try_reserve_exact(counts.len() + 1) - .map_err(|_| Error::HostAllocation)?; + bounds.try_reserve_exact(counts.len() + 1).map_err(|_| Error::HostAllocation)?; bounds.push(0u32); for n in counts { - bounds.push( - bounds - .last() - .copied() - .ok_or(Error::InvalidProjectionShape)? - + n, - ); + bounds.push(bounds.last().copied().ok_or(Error::InvalidProjectionShape)? + n); } let mut bound_bytes = bytes((counts.len() + 1 + counts.len().div_ceil(16) * 17) * 4)?; for (i, n) in bounds.iter().enumerate() { @@ -146,20 +121,9 @@ impl<'ctx> MmqWorkspace<'ctx> { row_ids[i * 4..i * 4 + 4].copy_from_slice(&r.to_le_bytes()); identity[i * 4..i * 4 + 4].copy_from_slice(&(i as u32).to_le_bytes()); } - let bank = self - .original_group - .as_mut() - .ok_or(Error::UnsupportedProjection)?; - for (index, src) in [ - (X, &input), - (ROW_IDS, &row_ids), - (IDENTITY, &identity), - (BOUNDS, &bound_bytes), - ] { - bank.buffers[index] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from_range(0, src)?; + let bank = self.original_group.as_mut().ok_or(Error::UnsupportedProjection)?; + for (index, src) in [(X, &input), (ROW_IDS, &row_ids), (IDENTITY, &identity), (BOUNDS, &bound_bytes)] { + bank.buffers[index].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, src)?; } // Actual indexed non-scatter quantization once for T*10 expert-order columns. let mut layer = OriginalMmqLayer { @@ -189,10 +153,7 @@ impl<'ctx> MmqWorkspace<'ctx> { } let tokens = u32::try_from(read.rows()).map_err(|_| Error::InvalidProjectionShape)?; self.check()?; - let bank = self - .original_group - .as_ref() - .ok_or(Error::UnsupportedProjection)?; + let bank = self.original_group.as_ref().ok_or(Error::UnsupportedProjection)?; if !bank.arena_only || tokens == 0 || tokens > bank.capacity @@ -202,13 +163,8 @@ impl<'ctx> MmqWorkspace<'ctx> { { return Err(Error::InvalidProjectionShape); } - let total = counts.iter().try_fold(0u32, |a, b| { - a.checked_add(*b).ok_or(Error::InvalidProjectionShape) - })?; - if total - != tokens - .checked_mul(10) - .ok_or(Error::InvalidProjectionShape)? + let total = counts.iter().try_fold(0u32, |a, b| a.checked_add(*b).ok_or(Error::InvalidProjectionShape))?; + if total != tokens.checked_mul(10).ok_or(Error::InvalidProjectionShape)? || sorted_source_rows.len() != total as usize || sorted_source_rows.iter().any(|r| *r >= tokens) { @@ -217,8 +173,7 @@ impl<'ctx> MmqWorkspace<'ctx> { // Every actual source row appears exactly10 times; each expert's columns are // strictly increasing. This is transport geometry, not a route certificate. let mut uses = Vec::new(); - uses.try_reserve_exact(tokens as usize) - .map_err(|_| Error::HostAllocation)?; + uses.try_reserve_exact(tokens as usize).map_err(|_| Error::HostAllocation)?; uses.resize(tokens as usize, 0u8); let mut at = 0; for count in counts { @@ -227,9 +182,7 @@ impl<'ctx> MmqWorkspace<'ctx> { return Err(Error::InvalidProjectionShape); } for r in rows { - uses[*r as usize] = uses[*r as usize] - .checked_add(1) - .ok_or(Error::InvalidProjectionShape)?; + uses[*r as usize] = uses[*r as usize].checked_add(1).ok_or(Error::InvalidProjectionShape)?; } at += *count as usize; } @@ -237,23 +190,13 @@ impl<'ctx> MmqWorkspace<'ctx> { return Err(Error::InvalidProjectionShape); } let mut owned_counts = Vec::new(); - owned_counts - .try_reserve_exact(counts.len()) - .map_err(|_| Error::HostAllocation)?; + owned_counts.try_reserve_exact(counts.len()).map_err(|_| Error::HostAllocation)?; owned_counts.extend_from_slice(counts); let mut bounds = Vec::new(); - bounds - .try_reserve_exact(counts.len() + 1) - .map_err(|_| Error::HostAllocation)?; + bounds.try_reserve_exact(counts.len() + 1).map_err(|_| Error::HostAllocation)?; bounds.push(0u32); for n in counts { - bounds.push( - bounds - .last() - .copied() - .ok_or(Error::InvalidProjectionShape)? - + n, - ); + bounds.push(bounds.last().copied().ok_or(Error::InvalidProjectionShape)? + n); } let mut bound_bytes = bytes((counts.len() + 1 + counts.len().div_ceil(16) * 17) * 4)?; for (i, n) in bounds.iter().enumerate() { @@ -275,14 +218,8 @@ impl<'ctx> MmqWorkspace<'ctx> { // Every genuine destination span is admitted before the first metadata // upload. Source vectors remain alive through the one successful drain. let mut destinations = Vec::new(); - destinations - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; - for (index, src) in [ - (ROW_IDS, &row_ids), - (IDENTITY, &identity), - (BOUNDS, &bound_bytes), - ] { + destinations.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + for (index, src) in [(ROW_IDS, &row_ids), (IDENTITY, &identity), (BOUNDS, &bound_bytes)] { let (h, n) = GroupArena::span(read, index)?; let h = h.checked_subspan(n, 0, src.len())?; h.validate_projection_extent(src.len(), 4)?; @@ -318,13 +255,8 @@ impl<'ctx> MmqWorkspace<'ctx> { formats: None, completed: false, }; - let (input, extent) = read - .lease() - .common_span(crate::original_prefill_arena::OriginalPromptSpan::Mixed)?; - let amount = read - .rows() - .checked_mul(10240) - .ok_or(Error::InvalidProjectionShape)?; + let (input, extent) = read.lease().common_span(crate::original_prefill_arena::OriginalPromptSpan::Mixed)?; + let amount = read.rows().checked_mul(10240).ok_or(Error::InvalidProjectionShape)?; let input = input.checked_subspan(extent, 0, amount)?; layer.quantize_device_mixed(input)?; Ok(layer) diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs index e51d746e..26e6fba2 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2.rs @@ -3,14 +3,10 @@ #[allow(unused_imports)] use super::*; - impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { pub(in super::super) fn bank(&self) -> Result<&OriginalGroupBank<'ctx>> { self.workspace.check()?; - self.workspace - .original_group - .as_ref() - .ok_or(Error::UnsupportedProjection) + self.workspace.original_group.as_ref().ok_or(Error::UnsupportedProjection) } pub(in super::super) fn span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> { let b = self.bank()?; @@ -37,13 +33,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { } else { 0 }; - let h = h.checked_subspan( - n, - group - .checked_add(offset) - .ok_or(Error::InvalidProjectionShape)?, - bytes, - )?; + let h = h.checked_subspan(n, group.checked_add(offset).ok_or(Error::InvalidProjectionShape)?, bytes)?; h.validate_projection_extent(bytes, align)?; Ok(h) } @@ -77,13 +67,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { cmds.push(QueuedCommand::OriginalHelper( w.kernel(1)?, ((if q8 { amount * 144 + tail } else { amount * 4 }) / 4) as u32, - ffi::MmqResidentArguments::finite( - source, - status, - u32::from(q8), - amount as u32, - tail as u32, - ), + ffi::MmqResidentArguments::finite(source, status, u32::from(q8), amount as u32, tail as u32), )); match w.run_queued(cmds, Some(status))? { 0 => Ok(()), @@ -102,22 +86,9 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { ids: Option, ) -> Result<()> { let b = self.bank()?; - let f = if columns == 2560 { - MmqFormat::Iq3XxsGateUp - } else { - MmqFormat::Iq4NlDown - }; + let f = if columns == 2560 { MmqFormat::Iq3XxsGateUp } else { MmqFormat::Iq4NlDown }; let l = layout(f, if columns == 2560 { 1280 } else { 2560 }, tokens, 64)?; - let ih = self.handle( - input, - 0, - if ids.is_some() { - b.capacity as usize * 10240 - } else { - l.input - }, - 16, - )?; + let ih = self.handle(input, 0, if ids.is_some() { b.capacity as usize * 10240 } else { l.input }, 16)?; let qh = self.handle(packed, 0, l.packed, 16)?; let mut cmds = commands()?; cmds.push(QueuedCommand::OriginalHelper( @@ -125,9 +96,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { (l.packed / 4) as u32, ffi::MmqResidentArguments::zero(qh, (l.packed / 4) as u32), )); - let id_handle = ids - .map(|i| self.handle(i, 0, tokens as usize * 4, 4)) - .transpose()?; + let id_handle = ids.map(|i| self.handle(i, 0, tokens as usize * 4, 4)).transpose()?; let args = ffi::MmqQuantArguments::original_indexed(ih, id_handle, qh, l); cmds.push(QueuedCommand::Quantize( self.workspace @@ -164,11 +133,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { )); self.finite(cmds, qh, l.payload / 144, true, "Q8") } - pub fn stage_expert( - &mut self, - formats: [MmqFormat; 3], - raw: [&DeviceBuffer<'_>; 3], - ) -> Result<()> { + pub fn stage_expert(&mut self, formats: [MmqFormat; 3], raw: [&DeviceBuffer<'_>; 3]) -> Result<()> { let n = (self.counts.len() - self.next).min(16); if self.completed || self.staged >= n { return Err(Error::InvalidProjectionShape); @@ -187,16 +152,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; let mut handles = [None; 3]; for (i, source) in raw.into_iter().enumerate() { - let expected = if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }; - let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { - 4 - } else { - 2 - }; + let expected = if i < 2 { gu.raw_weight } else { down.raw_weight }; + let alignment = if formats[i] == MmqFormat::Iq4XsGateUp { 4 } else { 2 }; if source.bytes != expected { return Err(Error::InvalidProjectionShape); } @@ -206,25 +163,12 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let h = source.handle.ok_or(Error::ContextPoisoned)?; h.validate_projection_extent(expected, alignment)?; for prior in raw.iter().take(i) { - if h.overlaps( - expected, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { + if h.overlaps(expected, prior.handle.ok_or(Error::ContextPoisoned)?, prior.bytes) { return Err(Error::OutputAliasesInput); } } - for owner in b - .buffers - .iter() - .chain(self.workspace.buffers.iter()) - .flatten() - { - if h.overlaps( - expected, - owner.handle.ok_or(Error::ContextPoisoned)?, - owner.bytes, - ) { + for owner in b.buffers.iter().chain(self.workspace.buffers.iter()).flatten() { + if h.overlaps(expected, owner.handle.ok_or(Error::ContextPoisoned)?, owner.bytes) { return Err(Error::OutputAliasesInput); } } diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs index 58d4e2d5..c31d38ce 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_2_2.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { - pub(in super::super) fn stage_raw(&mut self, formats: [MmqFormat; 3], raw: [ffi::BufferHandle; 3]) -> Result<()> { let n = (self.counts.len() - self.next).min(16); if self.completed || self.staged >= n { @@ -24,56 +22,28 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let wh = self.handle(WG, self.staged * gu.raw_weight * 2, gu.raw_weight * 2, 4)?; let dh = self.handle(WD, self.staged * down.raw_weight, down.raw_weight, 4)?; for (i, h) in raw.iter().enumerate() { - let amount = if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }; + let amount = if i < 2 { gu.raw_weight } else { down.raw_weight }; h.validate_projection_extent(amount, 16)?; for (j, prior) in raw.iter().take(i).enumerate() { - let prior_amount = if j < 2 { - gu.raw_weight - } else { - down.raw_weight - }; + let prior_amount = if j < 2 { gu.raw_weight } else { down.raw_weight }; if h.overlaps(amount, *prior, prior_amount) { return Err(Error::OutputAliasesInput); } } - for owner in b - .buffers - .iter() - .chain(self.workspace.buffers.iter()) - .flatten() - { - if h.overlaps( - amount, - owner.handle.ok_or(Error::ContextPoisoned)?, - owner.bytes, - ) { + for owner in b.buffers.iter().chain(self.workspace.buffers.iter()).flatten() { + if h.overlaps(amount, owner.handle.ok_or(Error::ContextPoisoned)?, owner.bytes) { return Err(Error::OutputAliasesInput); } } } for (i, h) in raw.iter().enumerate() { - self.reject_arena_alias( - *h, - if i < 2 { - gu.raw_weight - } else { - down.raw_weight - }, - )?; + self.reject_arena_alias(*h, if i < 2 { gu.raw_weight } else { down.raw_weight })?; } // All admitted formats have real 16-byte-aligned lengths/owners. This is // exactly Original gather_native's copy16 branch, not three host-staged copies. wh.validate_projection_extent(gu.raw_weight * 2, 16)?; dh.validate_projection_extent(down.raw_weight, 16)?; - for (h, bytes) in [ - (raw[0], gu.raw_weight), - (raw[1], gu.raw_weight), - (raw[2], down.raw_weight), - ] { + for (h, bytes) in [(raw[0], gu.raw_weight), (raw[1], gu.raw_weight), (raw[2], down.raw_weight)] { h.validate_projection_extent(bytes, 16)?; } let mut commands = commands()?; @@ -102,12 +72,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let down = formats[2].layout(1)?; for (i, span) in spans.iter().enumerate() { if span.raw_kind() != kind(formats[i]) - || span.bytes().len() - != if i < 2 { - gu.raw_weight - } else { - down.raw_weight - } + || span.bytes().len() != if i < 2 { gu.raw_weight } else { down.raw_weight } { return Err(Error::InvalidProjectionShape); } diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs index c4fe98fd..df2e3deb 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer/impl_originalmmqlayer_3.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { - pub(in super::super) fn project( &self, format: MmqFormat, @@ -22,10 +20,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let tokens = if down { nr } else { self.total }; let l = layout(format, rows, tokens, width)?; let fi = format_index(format)?; - let ti = WIDTHS - .iter() - .position(|j| *j == width) - .ok_or(Error::UnsupportedProjection)?; + let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?; let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?; let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?; let maxr = self.counts[self.next..self.next + self.staged] @@ -34,22 +29,12 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { .max() .ok_or(Error::InvalidProjectionShape)?; let ntx = maxr.div_ceil(width); - let tiles = (rows / 128) - .checked_mul(ntx) - .and_then(|n| n.checked_mul(experts)) - .ok_or(Error::InvalidProjectionShape)?; - if tiles - .checked_mul(l.columns / l.qk) - .is_none_or(|n| n >= 1 << 30) - { + let tiles = + (rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?; + if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) { return Err(Error::InvalidProjectionShape); } - let sms = self - .workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .sms; + let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms; let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms)); let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms }; let needs_fix = !tiles.is_multiple_of(grid); @@ -57,44 +42,28 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let ph = self.handle(packed, 0, l.packed, 16)?; let oh = self.handle(out, 0, l.output, 4)?; let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?; - let offset = if down { - self.counts.len() + 1 + (self.next / 16) * 17 - } else { - self.next - }; + let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next }; let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?; - let tmp = if needs_fix { - Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) - } else { - None - }; + let tmp = + if needs_fix { Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) } else { None }; let mut cmds = commands()?; cmds.push(QueuedCommand::Project( f, l, grid, - ffi::MmqArguments::original_group( - wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqArguments::original_group(wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width), )); if let Some(tmp) = tmp { cmds.push(QueuedCommand::Fixup( fix, grid, - ffi::MmqFixupArguments::original_group( - ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqFixupArguments::original_group(ids, bounds, oh, tmp, l, experts, maxr, width), )); } let source = if down { oh } else { - self.handle( - out, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )? + self.handle(out, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)? }; if down { self.finite(cmds, source, nr as usize * 2560, false, "Down") @@ -143,10 +112,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { best.ok_or(Error::UnsupportedProjection) } pub fn run_group<'a>(&'a mut self) -> Result> { - if self.completed - || self.staged == 0 - || self.staged != (self.counts.len() - self.next).min(16) - { + if self.completed || self.staged == 0 || self.staged != (self.counts.len() - self.next).min(16) { return Err(Error::InvalidProjectionShape); } let formats = self.formats.ok_or(Error::InvalidProjectionShape)?; @@ -167,12 +133,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { self.workspace.run_queued(zeros, None)?; self.project(formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; let b = self.bank()?; - let gu = self.handle( - GU, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )?; + let gu = self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?; let h = self.handle(H, 0, nr as usize * 640 * 4, 4)?; let mut cmds = commands()?; cmds.push(QueuedCommand::OriginalSwiglu( @@ -187,10 +148,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { Ok(OriginalMmqOutput { layer: self }) } pub fn finish_group(&mut self) -> Result<()> { - if !self.completed - || self.staged != (self.counts.len() - self.next).min(16) - || self.staged == 0 - { + if !self.completed || self.staged != (self.counts.len() - self.next).min(16) || self.staged == 0 { return Err(Error::InvalidProjectionShape); } // Called only after the affine output loan drops. Numerical outputs cannot @@ -202,10 +160,6 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { Ok(()) } pub fn finish(self) -> Result<()> { - if self.next != self.counts.len() || self.staged != 0 { - Err(Error::InvalidProjectionShape) - } else { - Ok(()) - } + if self.next != self.counts.len() || self.staged != 0 { Err(Error::InvalidProjectionShape) } else { Ok(()) } } } diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs index 0cdb1dcf..93e43525 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqlayer_2.rs @@ -38,16 +38,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { } } let groups = self.counts.len().div_ceil(16); - let mut ring = copy_ring::Ring::new( - self.workspace.context, - read, - layer, - schedule, - bank, - formats, - sources, - groups, - )?; + let mut ring = + copy_ring::Ring::new(self.workspace.context, read, layer, schedule, bank, formats, sources, groups)?; let operation = (|| { // The actual carved ring size determines the literal STAGE-1 lookahead. let stages = read.lease().copy_ring_slots()?; @@ -87,22 +79,10 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { ffi::MmqResidentArguments::zero(h, 1024), ))?; } - self.enqueue_ring_project( - &mut ring, - formats[0], - WG, - XQ, - GU, - false, - self.width(formats[0])?, - )?; + self.enqueue_ring_project(&mut ring, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; let b = self.bank()?; - let gu_source = self.handle( - GU, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )?; + let gu_source = + self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?; let gu_flag = ring.flag(group, 0)?; ring.enqueue(Command::Helper( b.gu_finite.ok_or(Error::ContextPoisoned)?, @@ -142,23 +122,9 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { ring.enqueue(Command::Helper( self.workspace.kernel(1)?, (ql.packed / 4) as u32, - ffi::MmqResidentArguments::finite( - q, - q_flag, - 1, - (ql.payload / 144) as u32, - (128 * 144) as u32, - ), + ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32), ))?; - self.enqueue_ring_project( - &mut ring, - formats[2], - WD, - HQ, - D, - true, - self.width(formats[2])?, - )?; + self.enqueue_ring_project(&mut ring, formats[2], WD, HQ, D, true, self.width(formats[2])?)?; let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?; let d_flag = ring.flag(group, 3)?; ring.enqueue(Command::Helper( @@ -231,10 +197,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let tokens = if down { nr } else { self.total }; let l = layout(format, rows, tokens, width)?; let fi = format_index(format)?; - let ti = WIDTHS - .iter() - .position(|j| *j == width) - .ok_or(Error::UnsupportedProjection)?; + let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?; let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?; let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?; let maxr = self.counts[self.next..self.next + self.staged] @@ -243,22 +206,12 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { .max() .ok_or(Error::InvalidProjectionShape)?; let ntx = maxr.div_ceil(width); - let tiles = (rows / 128) - .checked_mul(ntx) - .and_then(|n| n.checked_mul(experts)) - .ok_or(Error::InvalidProjectionShape)?; - if tiles - .checked_mul(l.columns / l.qk) - .is_none_or(|n| n >= 1 << 30) - { + let tiles = + (rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?; + if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) { return Err(Error::InvalidProjectionShape); } - let sms = self - .workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .sms; + let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms; let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms)); let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms }; let needs_fix = !tiles.is_multiple_of(grid); @@ -266,32 +219,21 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let ph = self.handle(packed, 0, l.packed, 16)?; let oh = self.handle(out, 0, l.output, 4)?; let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?; - let offset = if down { - self.counts.len() + 1 + (self.next / 16) * 17 - } else { - self.next - }; + let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next }; let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?; - let tmp = if needs_fix { - Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) - } else { - None - }; + let tmp = + if needs_fix { Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) } else { None }; ring.enqueue(Command::Project( f, l, grid, - ffi::MmqArguments::original_group( - wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqArguments::original_group(wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width), ))?; if let Some(tmp) = tmp { ring.enqueue(Command::Fixup( fix, grid, - ffi::MmqFixupArguments::original_group( - ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqFixupArguments::original_group(ids, bounds, oh, tmp, l, experts, maxr, width), ))?; } Ok(()) diff --git a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqoutput.rs b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqoutput.rs index e791fd0e..768065b7 100644 --- a/crates/cuda-driver/src/mmq_original_group/impl_originalmmqoutput.rs +++ b/crates/cuda-driver/src/mmq_original_group/impl_originalmmqoutput.rs @@ -6,10 +6,7 @@ use super::*; impl OriginalMmqOutput<'_, '_, '_> { /// Copy the complete finite group contiguously into Original's expert-order /// Dm arena. The later literal slot_dev combine follows the authentic route. - pub fn copy_group_down_to_prompt( - &self, - read: &crate::OriginalDeviceGrRead<'_, '_, '_>, - ) -> Result<()> { + pub fn copy_group_down_to_prompt(&self, read: &crate::OriginalDeviceGrRead<'_, '_, '_>) -> Result<()> { let layer = &*self.layer; let bank = layer.bank()?; if !read.context_matches(bank.context) || read.rows() as u32 != layer.total / 10 { @@ -18,17 +15,10 @@ impl OriginalMmqOutput<'_, '_, '_> { let (dm, extent) = read.lease().span(crate::PrefillPhase::Moe, "Dm")?; let start = layer.bounds[layer.next] as usize; let count = (layer.bounds[layer.next + layer.staged] - layer.bounds[layer.next]) as usize; - let bytes = count - .checked_mul(10240) - .ok_or(Error::InvalidProjectionShape)?; + let bytes = count.checked_mul(10240).ok_or(Error::InvalidProjectionShape)?; let source = layer.handle(D, 0, bytes, 4)?; - let destination = dm.checked_subspan( - extent, - start - .checked_mul(10240) - .ok_or(Error::InvalidProjectionShape)?, - bytes, - )?; + let destination = + dm.checked_subspan(extent, start.checked_mul(10240).ok_or(Error::InvalidProjectionShape)?, bytes)?; if layer.arena.is_some() { // The grouped Down kernel already wrote the genuine expert-order Dm span. // Exact address equality is checked; no redundant DtoD copy is introduced. @@ -41,11 +31,7 @@ impl OriginalMmqOutput<'_, '_, '_> { return Err(Error::OutputAliasesInput); } let guard = bank.context.enter()?; - let copy = bank - .context - .driver - .api - .copy_original_down_group(destination, source, bytes); + let copy = bank.context.driver.api.copy_original_down_group(destination, source, bytes); let sync = bank.context.driver.api.synchronize(); let pop = guard.finish(); if copy.is_err() || sync.is_err() || pop.is_err() { @@ -73,9 +59,7 @@ impl OriginalMmqOutput<'_, '_, '_> { 4, )?; let mut handles = Vec::new(); - handles - .try_reserve_exact(copies.len()) - .map_err(|_| Error::HostAllocation)?; + handles.try_reserve_exact(copies.len()).map_err(|_| Error::HostAllocation)?; for (column, dest, slot) in copies.iter() { if *column >= count || *slot >= 10 || dest.bytes != 102400 { return Err(Error::InvalidProjectionShape); @@ -86,23 +70,13 @@ impl OriginalMmqOutput<'_, '_, '_> { let dh = dest.handle.ok_or(Error::ContextPoisoned)?; dh.validate_projection_extent(dest.bytes, 4)?; for prior in &handles { - let (whole, _, _): &(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle) = - prior; + let (whole, _, _): &(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle) = prior; if whole.overlaps(102400, dh, 102400) { return Err(Error::OutputAliasesInput); } } - for owner in b - .buffers - .iter() - .chain(layer.workspace.buffers.iter()) - .flatten() - { - if dh.overlaps( - dest.bytes, - owner.handle.ok_or(Error::ContextPoisoned)?, - owner.bytes, - ) { + for owner in b.buffers.iter().chain(layer.workspace.buffers.iter()).flatten() { + if dh.overlaps(dest.bytes, owner.handle.ok_or(Error::ContextPoisoned)?, owner.bytes) { return Err(Error::OutputAliasesInput); } } @@ -110,8 +84,7 @@ impl OriginalMmqOutput<'_, '_, '_> { dh, dh.moe_down_slot(*slot)?, source.checked_subspan( - (layer.bounds[layer.next + layer.staged] - layer.bounds[layer.next]) as usize - * 10240, + (layer.bounds[layer.next + layer.staged] - layer.bounds[layer.next]) as usize * 10240, (start + column) as usize * 10240, 10240, )?, diff --git a/crates/cuda-driver/src/mmq_original_group/kind_fn.rs b/crates/cuda-driver/src/mmq_original_group/kind_fn.rs index 589123d7..b7dbcc1b 100644 --- a/crates/cuda-driver/src/mmq_original_group/kind_fn.rs +++ b/crates/cuda-driver/src/mmq_original_group/kind_fn.rs @@ -14,15 +14,10 @@ pub(super) fn kind(f: MmqFormat) -> u32 { } } pub(super) fn shared(f: MmqFormat, j: u32) -> u32 { - 128 * if f == MmqFormat::Iq2SGateUp { 84 } else { 76 } * 4 - + j * 4 - + (j * 144).div_ceil(1024) * 1024 + 128 * if f == MmqFormat::Iq2SGateUp { 84 } else { 76 } * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 } pub(super) fn format_index(f: MmqFormat) -> Result { - FORMATS - .iter() - .position(|x| *x == f) - .ok_or(Error::UnsupportedProjection) + FORMATS.iter().position(|x| *x == f).ok_or(Error::UnsupportedProjection) } pub(super) fn layout(f: MmqFormat, rows: u32, tokens: u32, width: u32) -> Result { let mut l = f.layout(1)?; @@ -39,10 +34,7 @@ pub(super) fn layout(f: MmqFormat, rows: u32, tokens: u32, width: u32) -> Result } impl Context<'_> { /// Selected Original prompt grouping; old native/verification constructors are unchanged. - pub fn native_integer_iq3_mmq_original_grouped_workspace( - &self, - capacity: u32, - ) -> Result> { + pub fn native_integer_iq3_mmq_original_grouped_workspace(&self, capacity: u32) -> Result> { for k in 0..3 { asset(k)?; } @@ -62,9 +54,7 @@ impl GroupArena for crate::OriginalDeviceGrRead<'_, '_, '_> { fn span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> { use crate::PrefillPhase as P; match index { - X => self - .lease() - .common_span(crate::original_prefill_arena::OriginalPromptSpan::Mixed), + X => self.lease().common_span(crate::original_prefill_arena::OriginalPromptSpan::Mixed), ROW_IDS => self.lease().span(P::Moe, "src_dev"), IDENTITY => self.lease().span(P::Common, "ids_identity"), BOUNDS => self.lease().span(P::Common, "bounds_dev"), diff --git a/crates/cuda-driver/src/mmq_original_group_stress_gpu.rs b/crates/cuda-driver/src/mmq_original_group_stress_gpu.rs index 4c36af6d..f13fb6ed 100644 --- a/crates/cuda-driver/src/mmq_original_group_stress_gpu.rs +++ b/crates/cuda-driver/src/mmq_original_group_stress_gpu.rs @@ -163,8 +163,12 @@ fn original_group_stream_k_stress() { for (which, (index, floats)) in [(GU, nr * 1280), (D, nr * 2560)].into_iter().enumerate() { let mut bytes = vec![0u8; floats * 4]; let start = if index == GU { layer.bounds[layer.next] as usize * 1280 * 4 } else { 0 }; - layer.bank()?.buffers[index].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(start, &mut bytes)?; - collected[which].extend(bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))); + layer.bank()?.buffers[index] + .as_ref() + .ok_or(Error::ContextPoisoned)? + .copy_to_range(start, &mut bytes)?; + collected[which] + .extend(bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))); } layer.finish_group()?; } @@ -201,11 +205,17 @@ fn original_group_stream_k_stress() { ); } if trial % 20 == 0 { - eprintln!("STRESS trial {trial}: tokens {tokens} experts {} max count {} worst relative difference so far gate/up {worst_gu:e}, down {worst:e}", counts.len(), counts.iter().max().copied().unwrap_or(0)); + eprintln!( + "STRESS trial {trial}: tokens {tokens} experts {} max count {} worst relative difference so far gate/up {worst_gu:e}, down {worst:e}", + counts.len(), + counts.iter().max().copied().unwrap_or(0) + ); } } let _ = std::fs::remove_file(&flag); - eprintln!("STRESS OK: {layers} random layers x 2 grids at sms {sms}, worst relative difference gate/up {worst_gu:e}, down {worst:e}"); + eprintln!( + "STRESS OK: {layers} random layers x 2 grids at sms {sms}, worst relative difference gate/up {worst_gu:e}, down {worst:e}" + ); drop(pool); let _ = workspace.close(); } diff --git a/crates/cuda-driver/src/mmq_original_host_stage.rs b/crates/cuda-driver/src/mmq_original_host_stage.rs index 29803f40..aba9446e 100644 --- a/crates/cuda-driver/src/mmq_original_host_stage.rs +++ b/crates/cuda-driver/src/mmq_original_host_stage.rs @@ -81,14 +81,14 @@ mod tests; #[path = "mmq_original_host_stage/verify_enabled_fn.rs"] mod verify_enabled_fn; #[allow(unused_imports)] -use verify_enabled_fn::verify_enabled; -#[allow(unused_imports)] -pub(super) use verify_enabled_fn::layer_priority; -#[allow(unused_imports)] use verify_enabled_fn::apply_priority; #[allow(unused_imports)] use verify_enabled_fn::block_bytes; #[allow(unused_imports)] +pub(super) use verify_enabled_fn::layer_priority; +#[allow(unused_imports)] pub(super) use verify_enabled_fn::scales_finite; +#[allow(unused_imports)] +use verify_enabled_fn::verify_enabled; #[path = "mmq_original_host_stage/impl_hoststage.rs"] mod impl_hoststage; diff --git a/crates/cuda-driver/src/mmq_original_host_stage/impl_hoststage.rs b/crates/cuda-driver/src/mmq_original_host_stage/impl_hoststage.rs index 8580be8a..ad643bfc 100644 --- a/crates/cuda-driver/src/mmq_original_host_stage/impl_hoststage.rs +++ b/crates/cuda-driver/src/mmq_original_host_stage/impl_hoststage.rs @@ -93,7 +93,8 @@ impl HostStage { let mut sizes = Vec::new(); sizes.try_reserve_exact(jobs.len()).map_err(|_| Error::HostAllocation)?; for job in &jobs { - sizes.push(job.pieces.iter().try_fold(0usize, |n, piece| n.checked_add(piece.1)).ok_or(Error::InvalidSize)?); + sizes + .push(job.pieces.iter().try_fold(0usize, |n, piece| n.checked_add(piece.1)).ok_or(Error::InvalidSize)?); } self.sizes = sizes; self.generation = self.generation.wrapping_add(1) & !NON_FINITE; @@ -111,10 +112,7 @@ impl HostStage { } wake.jobs = list; wake.generation = self.generation; - self.shared.head.store( - (u64::from(self.generation) << 32) | ((self.jobs as u64) << 16), - Ordering::Release, - ); + self.shared.head.store((u64::from(self.generation) << 32) | ((self.jobs as u64) << 16), Ordering::Release); drop(wake); self.shared.cv.notify_all(); Ok(()) @@ -122,7 +120,12 @@ impl HostStage { /// Job `j`'s staged bytes (`length` of them), once its copy is ready. `release` is polled while waiting: it /// returns how many issued jobs' DMAs have completed, in order (the helpers wait for those buffers). `length` /// may not exceed what the job's helper copied: the buffers are uninitialised page-locked memory. - pub(in super::super) fn wait(&mut self, j: usize, length: usize, mut release: impl FnMut() -> Result) -> Result<&[u8]> { + pub(in super::super) fn wait( + &mut self, + j: usize, + length: usize, + mut release: impl FnMut() -> Result, + ) -> Result<&[u8]> { if j >= self.jobs || j != self.issued || length > self.shared.buffer_bytes || length > self.sizes[j] { return Err(Error::InvalidProjectionShape); } diff --git a/crates/cuda-driver/src/mmq_original_host_stage/verify_enabled_fn.rs b/crates/cuda-driver/src/mmq_original_host_stage/verify_enabled_fn.rs index d0d6df3f..927ef5eb 100644 --- a/crates/cuda-driver/src/mmq_original_host_stage/verify_enabled_fn.rs +++ b/crates/cuda-driver/src/mmq_original_host_stage/verify_enabled_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Bring-up: `LELEKA_BRINGUP_TRACE` and `LELEKA_STAGE_VERIFY` compare every staged buffer with its source when its DMA is released. pub(super) fn verify_enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -26,7 +25,9 @@ pub(in super::super) fn layer_priority(layer: usize, per_layer_bytes: usize) -> static MODE: OnceLock>> = OnceLock::new(); let mode = *MODE.get_or_init(|| match std::env::var("LELEKA_STAGE_PRIORITY").ok().as_deref() { Some("on") | Some("auto") | Some("1") => Some(None), - Some(other) => other.parse::().ok().filter(|g| *g > 0.0).map(|g| Some((g * (1u64 << 30) as f64) as u64)), + Some(other) => { + other.parse::().ok().filter(|g| *g > 0.0).map(|g| Some((g * (1u64 << 30) as f64) as u64)) + } None => None, }); let Some(fixed) = mode else { return 0 }; diff --git a/crates/cuda-driver/src/mmq_original_prefill_misc.rs b/crates/cuda-driver/src/mmq_original_prefill_misc.rs index dfd1a6ae..39344d67 100644 --- a/crates/cuda-driver/src/mmq_original_prefill_misc.rs +++ b/crates/cuda-driver/src/mmq_original_prefill_misc.rs @@ -41,7 +41,15 @@ pub enum GatherNative { } /// `gather_native(gate, up, gu_half_bytes, down, d_bytes, gu_dst, d_dst)`: every address and both byte counts /// 16-aligned selects the `uint4` copy, otherwise the byte copy; grid `blocks(2 * na + nc)`. -pub fn gather_native_plan(gate: u64, up: u64, gu_half_bytes: u64, down: u64, d_bytes: u64, gu_dst: u64, d_dst: u64) -> GatherNative { +pub fn gather_native_plan( + gate: u64, + up: u64, + gu_half_bytes: u64, + down: u64, + d_bytes: u64, + gu_dst: u64, + d_dst: u64, +) -> GatherNative { let a16 = (gate | up | down | gu_dst | d_dst | gu_half_bytes | d_bytes) % 16 == 0; if a16 { let (na, nc) = ((gu_half_bytes / 16) as i64, (d_bytes / 16) as i64); @@ -72,7 +80,11 @@ pub fn strata_q2_convert(blob: &[u8]) -> Result<(Vec, Vec), &'static s } else { let j = i - GU_BLOCKS as i64; let (row, b) = ((j / 10) as usize, (j % 10) as usize); - (O_D_CODES + row * 160 + b * 16, O_D_SC + (row * 10 + b) * 2, &mut dn[(j as usize) * 9..(j as usize) * 9 + 9]) + ( + O_D_CODES + row * 160 + b * 16, + O_D_SC + (row * 10 + b) * 2, + &mut dn[(j as usize) * 9..(j as usize) * 9 + 9], + ) }; out[0] = word(scale); for k in 0..8 { @@ -142,7 +154,10 @@ mod tests { fn gather_native_picks_the_copy_width_like_the_original() { let g = |gate, up, half, down, d, gu_dst, d_dst| gather_native_plan(gate, up, half, down, d, gu_dst, d_dst); // Q2_0 expert of the IQ packs: gate/up half 1280/2 rows... aligned everywhere: uint4 copy - assert_eq!(g(0x1000, 0x2000, 640 * 1280, 0x3000, 2560 * 160, 0x4000, 0x5000), GatherNative::Copy16 { na: 51_200, nc: 25_600, blocks: blocks(2 * 51_200 + 25_600) }); + assert_eq!( + g(0x1000, 0x2000, 640 * 1280, 0x3000, 2560 * 160, 0x4000, 0x5000), + GatherNative::Copy16 { na: 51_200, nc: 25_600, blocks: blocks(2 * 51_200 + 25_600) } + ); // one misaligned address or byte count falls to the byte copy for bad in 0..7 { let mut a = [0x1000u64, 0x2000, 640 * 1280, 0x3000, 2560 * 160, 0x4000, 0x5000]; @@ -168,7 +183,10 @@ mod tests { assert_eq!(&words_to_bytes(&gu[1..9])[..], &blob[0..16]); let last = D_BLOCKS - 1; assert_eq!(dn[last * 9], u16::from_le_bytes([blob[O_D_SC + last * 2], blob[O_D_SC + last * 2 + 1]])); - assert_eq!(&words_to_bytes(&dn[last * 9 + 1..last * 9 + 9])[..], &blob[O_D_CODES + 2559 * 160 + 9 * 16..O_D_CODES + 2559 * 160 + 10 * 16]); + assert_eq!( + &words_to_bytes(&dn[last * 9 + 1..last * 9 + 9])[..], + &blob[O_D_CODES + 2559 * 160 + 9 * 16..O_D_CODES + 2559 * 160 + 10 * 16] + ); // gather (both widths) and iota for (key, width) in [("copy16", 16usize), ("copy1", 1usize)] { let c = &g[key]; diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 66ba2e14..f1cd4bd0 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -2,9 +2,7 @@ //! arena row loan, registered source bank and all stable ABI owners outlive work. use super::*; use crate::ffi::original_enqueue::{Api, Command}; -use crate::original_gpu_schedule::{ - OriginalEventKind, OriginalGpuEvent, OriginalGpuStream, OriginalStreamKind, -}; +use crate::original_gpu_schedule::{OriginalEventKind, OriginalGpuEvent, OriginalGpuStream, OriginalStreamKind}; use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole}; use std::rc::Rc; #[path = "mmq_original_host_stage.rs"] @@ -14,17 +12,20 @@ use host_stage::{HostStage, Job}; #[path = "mmq_original_chunk_stream.rs"] mod chunk_stream; #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -use chunk_stream::{ChunkStream, Entry as StreamEntry}; -#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use chunk_stream::prefetch_point; -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +use chunk_stream::{ChunkStream, Entry as StreamEntry}; +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] struct ChunkStream; const COMMAND_CAP: usize = 2048; trait RingArena: GroupArena { fn stage_slots(&self) -> Result; fn stage_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)>; - fn cache_span(&self, layer: usize, expert: usize) - -> Result>; + fn cache_span(&self, layer: usize, expert: usize) -> Result>; fn matches_context(&self, c: &Context<'_>) -> bool; } struct Slot { @@ -111,18 +112,22 @@ pub(super) struct Ring<'read, 'ctx> { #[path = "mmq_original_ring/skip_expert_dma_fn.rs"] mod skip_expert_dma_fn; -#[allow(unused_imports)] -use skip_expert_dma_fn::skip_expert_dma; -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] #[allow(unused_imports)] pub(crate) use skip_expert_dma_fn::prefetch_point; #[allow(unused_imports)] use skip_expert_dma_fn::serialize_ring; -#[path = "mmq_original_ring/impl_originalmmqcopyschedule.rs"] -mod impl_originalmmqcopyschedule; +#[allow(unused_imports)] +use skip_expert_dma_fn::skip_expert_dma; #[path = "mmq_original_ring/impl_drop_for_originalmmqcopyschedule.rs"] mod impl_drop_for_originalmmqcopyschedule; -#[path = "mmq_original_ring/impl_ring.rs"] -mod impl_ring; #[path = "mmq_original_ring/impl_drop_for_ring.rs"] mod impl_drop_for_ring; +#[path = "mmq_original_ring/impl_originalmmqcopyschedule.rs"] +mod impl_originalmmqcopyschedule; +#[path = "mmq_original_ring/impl_ring.rs"] +mod impl_ring; diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs b/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs index 381e52ed..bc17a0cc 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_originalmmqcopyschedule.rs @@ -10,11 +10,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { if self.is_failed() { return Err(Error::ContextPoisoned); } - if self - .metadata_bytes()? - .checked_add(bytes) - .is_none_or(|n| n > 16 << 20) - { + if self.metadata_bytes()?.checked_add(bytes).is_none_or(|n| n > 16 << 20) { return Err(Error::BudgetExceeded); } self.host_metadata_outside = bytes; @@ -41,7 +37,11 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { ) -> Result<()> { self.begin_stream_inner(read, bank, first, bytes_per_second) } - #[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] + #[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" + )))] pub(super) fn begin_stream_inner( &mut self, _: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>, @@ -61,7 +61,10 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { ) -> Result<()> { use crate::ffi::original_stager::Api as StagerApi; self.validate_context(self.context)?; - if self.stream.is_some() || bank.pageable() || !bank.cache_context_matches(self.context) || first >= 48 + if self.stream.is_some() + || bank.pageable() + || !bank.cache_context_matches(self.context) + || first >= 48 || !read.context_matches(self.context) { return Err(Error::InvalidProjectionShape); @@ -75,9 +78,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { } let aligned_copy = crate::mapped_expert_bank::aligned_copy_enabled(); let mut entries = Vec::new(); - entries - .try_reserve_exact((48 - usize::from(first)) * 512) - .map_err(|_| Error::HostAllocation)?; + entries.try_reserve_exact((48 - usize::from(first)) * 512).map_err(|_| Error::HostAllocation)?; for layer in first..48 { for expert in 0..512u32 { if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() { @@ -100,8 +101,12 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { } if off <= slot_bytes { entry = Some(StreamEntry { - layer, expert, pieces: [(sup[0].0, sup[0].1), (sup[1].0, sup[1].1), (sup[2].0, sup[2].1)], - exact, dest, at, + layer, + expert, + pieces: [(sup[0].0, sup[0].1), (sup[1].0, sup[1].1), (sup[2].0, sup[2].1)], + exact, + dest, + at, }); } } @@ -128,7 +133,11 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { events.try_reserve_exact(per_slot * ring).map_err(|_| Error::HostAllocation)?; for i in 0..per_slot * ring { // with the statistics on, `copied` (first block) and `start` (third block) carry timestamps - events.push(if stats && (i < ring || i >= 2 * ring) { api.event_create_timing()? } else { api.event_create()? }); + events.push(if stats && (i < ring || i >= 2 * ring) { + api.event_create_timing()? + } else { + api.event_create()? + }); } Ok(()) })(); @@ -143,7 +152,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { } let (copied, used) = (events[..ring].to_vec(), events[ring..2 * ring].to_vec()); let starts = events[2 * ring..].to_vec(); - let topup = std::env::var("LELEKA_PREFILL_TOPUP").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(48); + let topup = + std::env::var("LELEKA_PREFILL_TOPUP").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(48); let _ = bytes_per_second; let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?; // the copies must follow everything the compute path queued so far on its own streams @@ -200,7 +210,11 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { self.stream_bank.take(); result } - #[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] + #[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" + )))] pub(super) fn destroy_stream_events(&self, _: &[usize]) -> Result<()> { Ok(()) } @@ -230,14 +244,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { if self.failed || self.closed || c.is_poisoned() { return Err(Error::ContextPoisoned); } - self.copy - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c)?; - self.compute - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c) + self.copy.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(c)?; + self.compute.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(c) } pub fn is_failed(&self) -> bool { self.failed || self.closed || self.context.is_poisoned() @@ -251,14 +259,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> { } let ended = self.end_prompt_stream(); self.closed = true; - let copy = self - .copy - .as_ref() - .map_or(Ok(()), OriginalGpuStream::synchronize); - let compute = self - .compute - .as_ref() - .map_or(Ok(()), OriginalGpuStream::synchronize); + let copy = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize); + let compute = self.compute.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize); let mut result = combine(ended, combine(copy, compute)); if let Some(mut host) = self.host.take() { if result.is_ok() { diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs index c2aca818..c40b1dff 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'read, 'ctx> Ring<'read, 'ctx> { pub(in super::super::super) fn new( context: &'ctx Context<'ctx>, @@ -29,10 +28,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; - let blob = gu - .checked_mul(2) - .and_then(|n| n.checked_add(down)) - .ok_or(Error::InvalidSize)?; + let blob = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?; let admitted: &dyn RingArena = read; let count = admitted.stage_slots()?; schedule.validate_context(context)?; @@ -59,22 +55,10 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { closed: false, }; let result = (|| { - owner - .slots - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; - owner - .sources - .try_reserve_exact(spans.len()) - .map_err(|_| Error::HostAllocation)?; - owner - .commands - .try_reserve_exact(COMMAND_CAP) - .map_err(|_| Error::HostAllocation)?; - owner - .flags - .try_reserve_exact(groups * 16) - .map_err(|_| Error::HostAllocation)?; + owner.slots.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; + owner.sources.try_reserve_exact(spans.len()).map_err(|_| Error::HostAllocation)?; + owner.commands.try_reserve_exact(COMMAND_CAP).map_err(|_| Error::HostAllocation)?; + owner.flags.try_reserve_exact(groups * 16).map_err(|_| Error::HostAllocation)?; owner.flags.resize(groups * 16, 0); // Includes actual fixed ABI storage conservatively (<=512B each), // plus actual vector capacities; no second unbounded launch list. @@ -103,12 +87,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { return Err(Error::OutputAliasesInput); } } - owner.slots.push(Slot { - span: h, - bytes: n, - live: false, - gathered: false, - }); + owner.slots.push(Slot { span: h, bytes: n, live: false, gathered: false }); } let bank = owner.bank.as_ref().ok_or(Error::ContextPoisoned)?; for (i, spans) in spans.iter().enumerate() { @@ -120,9 +99,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } for (role, span) in spans.iter().enumerate() { let actual = bank.cache_source(span)?; - if span.raw_kind() != kind(formats[role]) - || actual.len() != if role < 2 { gu } else { down } - { + if span.raw_kind() != kind(formats[role]) || actual.len() != if role < 2 { gu } else { down } { return Err(Error::InvalidProjectionShape); } } @@ -139,14 +116,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { ]) }) .transpose()?; - owner.sources.push(Source { - spans, - resident, - slot: None, - job: None, - entry: None, - dest: None, - }); + owner.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None }); } // With an active chunk stream for this layer, every non-resident expert is the stream's entry. if let Some(stream) = owner.schedule.stream.as_ref() { @@ -155,15 +125,17 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { if source.resident.is_some() { continue; } - let entry = stream - .entry(layer as u8, source.spans[0].expert()) - .ok_or(Error::InvalidProjectionShape)?; + let entry = + stream.entry(layer as u8, source.spans[0].expert()).ok_or(Error::InvalidProjectionShape)?; // the stream copies exactly the bytes this span names - if !stream.entry_matches(entry, [ - bank.cache_source(&source.spans[0])?, - bank.cache_source(&source.spans[1])?, - bank.cache_source(&source.spans[2])?, - ]) { + if !stream.entry_matches( + entry, + [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ], + ) { return Err(Error::InvalidProjectionShape); } source.entry = Some(entry); @@ -194,13 +166,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } } let charge = groups * 16; - let required = charge - .checked_add(128 * 1024 * 1024) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + let required = charge.checked_add(128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs index 34b23f31..bd8c4368 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_2_2.rs @@ -3,24 +3,18 @@ #[allow(unused_imports)] use super::*; - impl<'read, 'ctx> Ring<'read, 'ctx> { pub(in super::super::super) fn metadata_bytes(&self) -> Result { self.slots .capacity() .checked_mul(std::mem::size_of::()) .and_then(|n| n.checked_add(self.sources.capacity() * std::mem::size_of::())) - .and_then(|n| { - n.checked_add(self.commands.capacity() * (std::mem::size_of::() + 512)) - }) + .and_then(|n| n.checked_add(self.commands.capacity() * (std::mem::size_of::() + 512))) .and_then(|n| n.checked_add(self.flags.capacity() + std::mem::size_of::())) .ok_or(Error::BudgetExceeded) } pub(in super::super::super) fn enqueue(&mut self, command: Command) -> Result<()> { - if self.closed - || self.commands.len() == COMMAND_CAP - || !self.read.matches_context(self.context) - { + if self.closed || self.commands.len() == COMMAND_CAP || !self.read.matches_context(self.context) { return Err(Error::InvalidProjectionShape); } self.commands.push(command); @@ -46,18 +40,12 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( b.bytes, - group - .checked_mul(16) - .and_then(|n| n.checked_add(stage * 4)) - .ok_or(Error::InvalidSize)?, + group.checked_mul(16).and_then(|n| n.checked_add(stage * 4)).ok_or(Error::InvalidSize)?, 4, ) } pub(in super::super::super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> { - let source = self - .sources - .get(index) - .ok_or(Error::InvalidProjectionShape)?; + let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?; if source.resident.is_some() || source.entry.is_some() { return Ok(()); } @@ -75,11 +63,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } // Re-recorded copied and used events have the same real source // streams; the copy stream waits the previous gather before reuse. - events - .used - .as_mut() - .ok_or(Error::ContextPoisoned)? - .wait_on(copy)?; + events.used.as_mut().ok_or(Error::ContextPoisoned)?.wait_on(copy)?; } let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?; @@ -110,64 +94,64 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { host_events[j % ring].record(copy)?; host.issued(j); } else { - // page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit) - let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() { - let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3]; - let mut off = 0usize; - for (i, part) in parts.iter_mut().enumerate() { - let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?; - *part = (superset, lead, off); - off += superset.len().div_ceil(4096) * 4096; - } - (off <= slot.bytes).then_some(parts) - } else { - None - }; - if let Some(parts) = aligned { - self.submitted = true; - self.drained = false; - copy.with_enqueue(|stream| { - for (superset, _, off) in parts { - api.copy_registered(slot.span.checked_subspan(slot.bytes, off, superset.len())?, superset, stream)?; - } - Ok(()) - })?; - new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]); - } else { - let sources = [ - bank.cache_source(&source.spans[0])?, - bank.cache_source(&source.spans[1])?, - bank.cache_source(&source.spans[2])?, - ]; - let destinations = [ - slot.span.checked_subspan(slot.bytes, 0, gu)?, - slot.span.checked_subspan(slot.bytes, gu, gu)?, - slot.span.checked_subspan(slot.bytes, gu * 2, down)?, - ]; - self.submitted = true; - self.drained = false; - copy.with_enqueue(|stream| { - // Physical role-major bank layout requires three H2Ds. Same source - // bytes and literal blob G/U/D layout; no decode/conversion/copy tmp. - for (destination, source) in destinations.into_iter().zip(sources) { - // one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`) - for (offset, bytes) in bank.copy_pieces(source) { - api.copy_registered( - destination.checked_subspan(source.len(), offset, bytes)?, - &source[offset..offset + bytes], - stream, - )?; + // page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit) + let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() { + let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3]; + let mut off = 0usize; + for (i, part) in parts.iter_mut().enumerate() { + let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?; + *part = (superset, lead, off); + off += superset.len().div_ceil(4096) * 4096; } + (off <= slot.bytes).then_some(parts) + } else { + None + }; + if let Some(parts) = aligned { + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| { + for (superset, _, off) in parts { + api.copy_registered( + slot.span.checked_subspan(slot.bytes, off, superset.len())?, + superset, + stream, + )?; + } + Ok(()) + })?; + new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]); + } else { + let sources = [ + bank.cache_source(&source.spans[0])?, + bank.cache_source(&source.spans[1])?, + bank.cache_source(&source.spans[2])?, + ]; + let destinations = [ + slot.span.checked_subspan(slot.bytes, 0, gu)?, + slot.span.checked_subspan(slot.bytes, gu, gu)?, + slot.span.checked_subspan(slot.bytes, gu * 2, down)?, + ]; + self.submitted = true; + self.drained = false; + copy.with_enqueue(|stream| { + // Physical role-major bank layout requires three H2Ds. Same source + // bytes and literal blob G/U/D layout; no decode/conversion/copy tmp. + for (destination, source) in destinations.into_iter().zip(sources) { + // one copy per registered/unregistered piece (`MappedExpertBank::copy_pieces`) + for (offset, bytes) in bank.copy_pieces(source) { + api.copy_registered( + destination.checked_subspan(source.len(), offset, bytes)?, + &source[offset..offset + bytes], + stream, + )?; + } + } + Ok(()) + })?; } - Ok(()) - })?; } - } - events - .copied - .as_mut() - .ok_or(Error::ContextPoisoned)? - .record(copy)?; + events.copied.as_mut().ok_or(Error::ContextPoisoned)?.record(copy)?; if serialize_ring(Drain::Copies) { copy.synchronize()?; } diff --git a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs index abc01a75..ef2bdb3b 100644 --- a/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs +++ b/crates/cuda-driver/src/mmq_original_ring/impl_ring/impl_ring_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'read, 'ctx> Ring<'read, 'ctx> { pub(in super::super::super) fn gather( &mut self, @@ -13,10 +12,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { gate_up: ffi::BufferHandle, down_out: ffi::BufferHandle, ) -> Result<()> { - let source = self - .sources - .get(index) - .ok_or(Error::InvalidProjectionShape)?; + let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?; let gu = formats[0].layout(1)?.raw_weight; let down = formats[2].layout(1)?.raw_weight; let sl = source.slot; @@ -29,11 +25,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let schedule = &mut *self.schedule; let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; let at = stream.entry_at(k)?; - let (span, bytes) = schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.acquire(k, s))?; + let (span, bytes) = + schedule.compute.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|s| stream.acquire(k, s))?; [ span.checked_subspan(bytes, at[0], gu)?, span.checked_subspan(bytes, at[1], gu)?, @@ -50,12 +43,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { .copied .as_mut() .ok_or(Error::ContextPoisoned)? - .wait_on( - self.schedule - .compute - .as_ref() - .ok_or(Error::ContextPoisoned)?, - )?; + .wait_on(self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; let at = dest.unwrap_or([0, gu, gu * 2]); [ slot.span.checked_subspan(slot.bytes, at[0], gu)?, @@ -84,21 +72,16 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { if let Some(k) = entry { let schedule = &mut *self.schedule; let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; - schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.consumed(k, s))?; + schedule.compute.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|s| stream.consumed(k, s))?; } if let Some(sl) = sl { let slot = &mut self.slots[sl]; let events = &mut self.schedule.events[sl]; - events.used.as_mut().ok_or(Error::ContextPoisoned)?.record( - self.schedule - .compute - .as_ref() - .ok_or(Error::ContextPoisoned)?, - )?; + events + .used + .as_mut() + .ok_or(Error::ContextPoisoned)? + .record(self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; slot.gathered = true; } Ok(()) @@ -111,20 +94,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { let layer = self.layer; let schedule = &mut *self.schedule; let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?; - schedule - .compute - .as_mut() - .ok_or(Error::ContextPoisoned)? - .with_enqueue(|s| stream.finish_layer(layer, s))?; + schedule.compute.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|s| stream.finish_layer(layer, s))?; self.streamed = false; } self.drain()?; let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; let guard = self.context.enter()?; - let copy = self.context.driver.api.copy_to( - status.handle.ok_or(Error::ContextPoisoned)?, - &mut self.flags, - ); + let copy = self.context.driver.api.copy_to(status.handle.ok_or(Error::ContextPoisoned)?, &mut self.flags); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); if copy.is_err() || sync.is_err() || pop.is_err() { @@ -146,11 +122,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> { } else { self.schedule.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize) }; - let compute = self - .schedule - .compute - .as_ref() - .map_or(Ok(()), OriginalGpuStream::synchronize); + let compute = self.schedule.compute.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize); let result = combine(copy, compute); self.drained = result.is_ok(); if result.is_err() { diff --git a/crates/cuda-driver/src/mmq_original_ring/skip_expert_dma_fn.rs b/crates/cuda-driver/src/mmq_original_ring/skip_expert_dma_fn.rs index 573340ca..5e5a593f 100644 --- a/crates/cuda-driver/src/mmq_original_ring/skip_expert_dma_fn.rs +++ b/crates/cuda-driver/src/mmq_original_ring/skip_expert_dma_fn.rs @@ -9,9 +9,17 @@ pub(super) fn skip_expert_dma() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA").is_some_and(|v| v == "1")) } -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] pub(crate) fn prefetch_point() {} -#[cfg(not(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] impl ChunkStream { pub(super) fn entry(&self, _: u8, _: u32) -> Option { None @@ -107,10 +115,7 @@ impl Context<'_> { status_pool: None, }; let result = (|| { - owner - .events - .try_reserve_exact(slots) - .map_err(|_| Error::HostAllocation)?; + owner.events.try_reserve_exact(slots).map_err(|_| Error::HostAllocation)?; if owner.metadata_bytes()? > 16 * 1024 * 1024 { return Err(Error::BudgetExceeded); } @@ -118,20 +123,14 @@ impl Context<'_> { owner.copy = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?); owner.compute = Some(self.original_gpu_stream(OriginalStreamKind::NonBlocking)?); for _ in 0..slots { - owner.events.push(Events { - copied: None, - used: None, - }); + owner.events.push(Events { copied: None, used: None }); let e = owner.events.last_mut().ok_or(Error::ContextPoisoned)?; e.copied = Some(self.original_gpu_event(OriginalEventKind::Completion)?); e.used = Some(self.original_gpu_event(OriginalEventKind::Completion)?); } // Opaque driver stream/event residency is not called zero bytes; // physical headroom is queried after creation before profile fills. - if self - .allocated_bytes() - .checked_add(128 * 1024 * 1024) - .is_none_or(|n| n > self.budget) + if self.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|n| n > self.budget) || self.memory_info()?.0 < 128 * 1024 * 1024 { return Err(Error::BudgetExceeded); diff --git a/crates/cuda-driver/src/mmq_original_stream_all.rs b/crates/cuda-driver/src/mmq_original_stream_all.rs index 8d42ada3..68c95e14 100644 --- a/crates/cuda-driver/src/mmq_original_stream_all.rs +++ b/crates/cuda-driver/src/mmq_original_stream_all.rs @@ -25,10 +25,10 @@ struct Producer<'producer, 'layer, 'ctx> { layer_id: u8, } -#[path = "mmq_original_stream_all/impl_transport.rs"] -mod impl_transport; #[path = "mmq_original_stream_all/impl_originalstreamallgroupproducer_for_producer.rs"] mod impl_originalstreamallgroupproducer_for_producer; +#[path = "mmq_original_stream_all/impl_transport.rs"] +mod impl_transport; #[allow(unused_imports)] use impl_originalstreamallgroupproducer_for_producer::rows_group_span; #[path = "mmq_original_stream_all/impl_originalmmqlayer.rs"] diff --git a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs index c83551f3..c436d736 100644 --- a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs +++ b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalmmqlayer.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { pub(super) fn enqueue_global_group( &self, @@ -19,42 +18,20 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { for stage in 0..4 { let flag = transport.flag(group, stage)?; transport.enqueue( - Command::Helper( - self.workspace.kernel(0)?, - 1, - ffi::MmqResidentArguments::zero(flag, 1), - ), + Command::Helper(self.workspace.kernel(0)?, 1, ffi::MmqResidentArguments::zero(flag, 1)), stream, )?; } for (index, bytes) in [(WG, gu * 2 * self.staged), (WD, down * self.staged)] { let h = self.handle(index, bytes, 4096, 4)?; transport.enqueue( - Command::Helper( - self.workspace.kernel(0)?, - 1024, - ffi::MmqResidentArguments::zero(h, 1024), - ), + Command::Helper(self.workspace.kernel(0)?, 1024, ffi::MmqResidentArguments::zero(h, 1024)), stream, )?; } - self.enqueue_global_project( - transport, - stream, - formats[0], - WG, - XQ, - GU, - false, - self.width(formats[0])?, - )?; + self.enqueue_global_project(transport, stream, formats[0], WG, XQ, GU, false, self.width(formats[0])?)?; let b = self.bank()?; - let gu_source = self.handle( - GU, - self.bounds[self.next] as usize * 1280 * 4, - nr as usize * 1280 * 4, - 4, - )?; + let gu_source = self.handle(GU, self.bounds[self.next] as usize * 1280 * 4, nr as usize * 1280 * 4, 4)?; let gu_flag = transport.flag(group, 0)?; transport.enqueue( Command::Helper( @@ -110,26 +87,11 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { Command::Helper( self.workspace.kernel(1)?, (ql.packed / 4) as u32, - ffi::MmqResidentArguments::finite( - q, - q_flag, - 1, - (ql.payload / 144) as u32, - (128 * 144) as u32, - ), + ffi::MmqResidentArguments::finite(q, q_flag, 1, (ql.payload / 144) as u32, (128 * 144) as u32), ), stream, )?; - self.enqueue_global_project( - transport, - stream, - formats[2], - WD, - HQ, - D, - true, - self.width(formats[2])?, - )?; + self.enqueue_global_project(transport, stream, formats[2], WD, HQ, D, true, self.width(formats[2])?)?; let d = self.handle(D, 0, nr as usize * 2560 * 4, 4)?; let d_flag = transport.flag(group, 3)?; transport.enqueue( @@ -161,10 +123,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let tokens = if down { nr } else { self.total }; let l = layout(format, rows, tokens, width)?; let fi = format_index(format)?; - let ti = WIDTHS - .iter() - .position(|j| *j == width) - .ok_or(Error::UnsupportedProjection)?; + let ti = WIDTHS.iter().position(|j| *j == width).ok_or(Error::UnsupportedProjection)?; let f = b.functions[fi][ti].ok_or(Error::UnsupportedProjection)?; let fix = b.fixups[fi][ti].ok_or(Error::UnsupportedProjection)?; let maxr = self.counts[self.next..self.next + self.staged] @@ -173,22 +132,12 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { .max() .ok_or(Error::InvalidProjectionShape)?; let ntx = maxr.div_ceil(width); - let tiles = (rows / 128) - .checked_mul(ntx) - .and_then(|n| n.checked_mul(experts)) - .ok_or(Error::InvalidProjectionShape)?; - if tiles - .checked_mul(l.columns / l.qk) - .is_none_or(|n| n >= 1 << 30) - { + let tiles = + (rows / 128).checked_mul(ntx).and_then(|n| n.checked_mul(experts)).ok_or(Error::InvalidProjectionShape)?; + if tiles.checked_mul(l.columns / l.qk).is_none_or(|n| n >= 1 << 30) { return Err(Error::InvalidProjectionShape); } - let sms = self - .workspace - .experiment - .as_ref() - .ok_or(Error::ContextPoisoned)? - .sms; + let sms = self.workspace.experiment.as_ref().ok_or(Error::ContextPoisoned)?.sms; let efficiency = 100 * tiles / (sms * tiles.div_ceil(sms)); let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { sms }; let needs_fix = !tiles.is_multiple_of(grid); @@ -196,25 +145,16 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { let ph = self.handle(packed, 0, l.packed, 16)?; let oh = self.handle(out, 0, l.output, 4)?; let ids = self.handle(IDENTITY, 0, tokens as usize * 4, 4)?; - let offset = if down { - self.counts.len() + 1 + (self.next / 16) * 17 - } else { - self.next - }; + let offset = if down { self.counts.len() + 1 + (self.next / 16) * 17 } else { self.next }; let bounds = self.handle(BOUNDS, offset * 4, (experts as usize + 1) * 4, 4)?; - let tmp = if needs_fix { - Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) - } else { - None - }; + let tmp = + if needs_fix { Some(self.handle(TMP, 0, grid as usize * width as usize * 128 * 4, 4)?) } else { None }; transport.enqueue( Command::Project( f, l, grid, - ffi::MmqArguments::original_group( - wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqArguments::original_group(wh, ph, ids, bounds, oh, tmp, l, experts, maxr, width), ), stream, )?; @@ -223,9 +163,7 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { Command::Fixup( fix, grid, - ffi::MmqFixupArguments::original_group( - ids, bounds, oh, tmp, l, experts, maxr, width, - ), + ffi::MmqFixupArguments::original_group(ids, bounds, oh, tmp, l, experts, maxr, width), ), stream, )?; @@ -250,18 +188,8 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> { { return Err(Error::InvalidProjectionShape); } - let transport = Transport::new( - self.workspace.context, - experts.len().div_ceil(16), - host_allowance, - )?; - let mut producer = Producer { - layer: self, - transport, - formats, - experts, - layer_id: layer, - }; + let transport = Transport::new(self.workspace.context, experts.len().div_ceil(16), host_allowance)?; + let mut producer = Producer { layer: self, transport, formats, experts, layer_id: layer }; let operation = forward.consume_layer_grouped(read.lease(), layer, experts, &mut producer); let succeeded = operation.is_ok(); let drained = forward.with_compute(|stream| { diff --git a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalstreamallgroupproducer_for_producer.rs b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalstreamallgroupproducer_for_producer.rs index eee69296..c6034bc8 100644 --- a/crates/cuda-driver/src/mmq_original_stream_all/impl_originalstreamallgroupproducer_for_producer.rs +++ b/crates/cuda-driver/src/mmq_original_stream_all/impl_originalstreamallgroupproducer_for_producer.rs @@ -59,10 +59,7 @@ impl<'ctx> OriginalStreamAllGroupProducer<'ctx> for Producer<'_, '_, 'ctx> { } let gu = self.formats[0].layout(1)?.raw_weight; let down = self.formats[2].layout(1)?.raw_weight; - let amount = gu - .checked_mul(2) - .and_then(|n| n.checked_add(down)) - .ok_or(Error::InvalidSize)?; + let amount = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?; let (blob, extent) = member.checked_blob()?; if extent < amount { return Err(Error::InvalidSize); @@ -87,11 +84,7 @@ impl<'ctx> OriginalStreamAllGroupProducer<'ctx> for Producer<'_, '_, 'ctx> { } let f = p.bank()?.gather.ok_or(Error::ContextPoisoned)?; self.transport.enqueue( - Command::Gather( - f, - (amount / 16) as u32, - ffi::MmqOriginalGatherArguments::new(raw, wh, dh, gu, down), - ), + Command::Gather(f, (amount / 16) as u32, ffi::MmqOriginalGatherArguments::new(raw, wh, dh, gu, down)), stream, )?; p.formats = Some(self.formats); diff --git a/crates/cuda-driver/src/mmq_original_stream_all/impl_transport.rs b/crates/cuda-driver/src/mmq_original_stream_all/impl_transport.rs index eb52023f..5d2679d2 100644 --- a/crates/cuda-driver/src/mmq_original_stream_all/impl_transport.rs +++ b/crates/cuda-driver/src/mmq_original_stream_all/impl_transport.rs @@ -17,36 +17,20 @@ impl<'ctx> Transport<'ctx> { submitted: false, drained: false, }; - owner - .commands - .try_reserve_exact(COMMAND_CAP) - .map_err(|_| Error::HostAllocation)?; - owner - .flags - .try_reserve_exact(groups * 16) - .map_err(|_| Error::HostAllocation)?; + owner.commands.try_reserve_exact(COMMAND_CAP).map_err(|_| Error::HostAllocation)?; + owner.flags.try_reserve_exact(groups * 16).map_err(|_| Error::HostAllocation)?; owner.flags.resize(groups * 16, 0); let metadata = owner .commands .capacity() .checked_mul(std::mem::size_of::() + 512) - .and_then(|n| { - n.checked_add(owner.flags.capacity() + std::mem::size_of::() + 1024) - }) + .and_then(|n| n.checked_add(owner.flags.capacity() + std::mem::size_of::() + 1024)) .ok_or(Error::BudgetExceeded)?; - if owner.commands.capacity() > COMMAND_CAP - || metadata > host_allowance - || metadata > 16 << 20 - { + if owner.commands.capacity() > COMMAND_CAP || metadata > host_allowance || metadata > 16 << 20 { return Err(Error::BudgetExceeded); } - let required = (groups * 16) - .checked_add(128 << 20) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + let required = (groups * 16).checked_add(128 << 20).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -62,10 +46,7 @@ impl<'ctx> Transport<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( b.bytes, - group - .checked_mul(16) - .and_then(|n| n.checked_add(stage * 4)) - .ok_or(Error::InvalidSize)?, + group.checked_mul(16).and_then(|n| n.checked_add(stage * 4)).ok_or(Error::InvalidSize)?, 4, ) } @@ -91,11 +72,7 @@ impl<'ctx> Transport<'ctx> { self.context.poison(); self.context.retain_driver(); })?; - let copy = self - .context - .driver - .api - .copy_to(b.handle.ok_or(Error::ContextPoisoned)?, &mut self.flags); + let copy = self.context.driver.api.copy_to(b.handle.ok_or(Error::ContextPoisoned)?, &mut self.flags); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); if copy.is_err() || sync.is_err() || pop.is_err() { @@ -134,19 +111,13 @@ impl Drop for Transport<'_> { } impl Drop for Producer<'_, '_, '_> { fn drop(&mut self) { - if self.transport.submitted && !self.transport.drained - || self.transport.context.is_poisoned() - { + if self.transport.submitted && !self.transport.drained || self.transport.context.is_poisoned() { let workspace = &mut *self.layer.workspace; workspace.failed = true; workspace.functions = None; workspace.context.poison(); workspace.context.retain_driver(); - std::mem::forget(( - workspace.original_group.take(), - workspace.helper.take(), - workspace.experiment.take(), - )); + std::mem::forget((workspace.original_group.take(), workspace.helper.take(), workspace.experiment.take())); } } } diff --git a/crates/cuda-driver/src/mmq_original_weights.rs b/crates/cuda-driver/src/mmq_original_weights.rs index 979d3999..c6d1a22b 100644 --- a/crates/cuda-driver/src/mmq_original_weights.rs +++ b/crates/cuda-driver/src/mmq_original_weights.rs @@ -3,11 +3,7 @@ //! admits the actual additional Original GU formats without changing old APIs. use super::*; impl Context<'_> { - pub fn mmq_original_weight_triplet( - &self, - formats: [MmqFormat; 3], - raw: [&[u8]; 3], - ) -> Result<[MmqWeights<'_>; 3]> { + pub fn mmq_original_weight_triplet(&self, formats: [MmqFormat; 3], raw: [&[u8]; 3]) -> Result<[MmqWeights<'_>; 3]> { if self.is_poisoned() || self.handle.is_none() { return Err(Error::ContextPoisoned); } @@ -24,11 +20,7 @@ impl Context<'_> { { return Err(Error::InvalidProjectionShape); } - let layouts = [ - formats[0].layout(1)?, - formats[1].layout(1)?, - formats[2].layout(1)?, - ]; + let layouts = [formats[0].layout(1)?, formats[1].layout(1)?, formats[2].layout(1)?]; let mut charge = 0usize; // Validate every source before allocating staging or entering CUDA. for (source, layout) in raw.iter().zip(layouts) { @@ -41,23 +33,12 @@ impl Context<'_> { { return Err(Error::InvalidQ8Activation); } - charge = charge - .checked_add(layout.weight) - .ok_or(Error::BudgetExceeded)?; + charge = charge.checked_add(layout.weight).ok_or(Error::BudgetExceeded)?; } - if self - .allocated - .get() - .checked_add(charge) - .is_none_or(|n| n > self.budget) - { + if self.allocated.get().checked_add(charge).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } - let mut staging = [ - bytes(layouts[0].weight)?, - bytes(layouts[1].weight)?, - bytes(layouts[2].weight)?, - ]; + let mut staging = [bytes(layouts[0].weight)?, bytes(layouts[1].weight)?, bytes(layouts[2].weight)?]; for (padded, source) in staging.iter_mut().zip(raw) { padded[..source.len()].copy_from_slice(source); } @@ -70,18 +51,9 @@ impl Context<'_> { } let operation = (|| { let handles = [ - buffers[0] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[1] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, - buffers[2] - .as_ref() - .and_then(|b| b.handle) - .ok_or(Error::ContextPoisoned)?, + buffers[0].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[1].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, + buffers[2].as_ref().and_then(|b| b.handle).ok_or(Error::ContextPoisoned)?, ]; let guard = self.enter()?; let mut copy = Ok(()); @@ -111,21 +83,9 @@ impl Context<'_> { unreachable!("all triplet allocations completed before upload") }; Ok([ - MmqWeights { - context: self, - format: formats[0], - buffer: Some(gate), - }, - MmqWeights { - context: self, - format: formats[1], - buffer: Some(up), - }, - MmqWeights { - context: self, - format: formats[2], - buffer: Some(down), - }, + MmqWeights { context: self, format: formats[0], buffer: Some(gate) }, + MmqWeights { context: self, format: formats[1], buffer: Some(up) }, + MmqWeights { context: self, format: formats[2], buffer: Some(down) }, ]) } } diff --git a/crates/cuda-driver/src/mmq_resident.rs b/crates/cuda-driver/src/mmq_resident.rs index bdde5217..0bb0d517 100644 --- a/crates/cuda-driver/src/mmq_resident.rs +++ b/crates/cuda-driver/src/mmq_resident.rs @@ -83,7 +83,7 @@ mod asset_fn; pub(crate) use asset_fn::asset; #[allow(unused_imports)] use asset_fn::commands; -#[path = "mmq_resident/impl_mmqworkspace.rs"] -mod impl_mmqworkspace; #[path = "mmq_resident/impl_drop_for_mmqworkspace.rs"] mod impl_drop_for_mmqworkspace; +#[path = "mmq_resident/impl_mmqworkspace.rs"] +mod impl_mmqworkspace; diff --git a/crates/cuda-driver/src/mmq_resident/asset_fn.rs b/crates/cuda-driver/src/mmq_resident/asset_fn.rs index 85301e3e..12fb0204 100644 --- a/crates/cuda-driver/src/mmq_resident/asset_fn.rs +++ b/crates/cuda-driver/src/mmq_resident/asset_fn.rs @@ -12,9 +12,8 @@ pub(crate) fn asset() -> Result<&'static [u8]> { if b.len() != 4046 || crate::qwen_ffi::sha256(&b[..b.len() - 1]) != [ - 0x87, 0x0c, 0x6b, 0xc8, 0xa6, 0xec, 0x32, 0x0a, 0x05, 0x9c, 0x50, 0xbe, 0x9d, 0x5c, - 0x96, 0x2f, 0xed, 0xec, 0x86, 0x63, 0x4d, 0x98, 0x8f, 0xc0, 0xe6, 0xb9, 0xd7, 0xed, - 0xea, 0x11, 0x8d, 0x89, + 0x87, 0x0c, 0x6b, 0xc8, 0xa6, 0xec, 0x32, 0x0a, 0x05, 0x9c, 0x50, 0xbe, 0x9d, 0x5c, 0x96, 0x2f, 0xed, + 0xec, 0x86, 0x63, 0x4d, 0x98, 0x8f, 0xc0, 0xe6, 0xb9, 0xd7, 0xed, 0xea, 0x11, 0x8d, 0x89, ] { return Err(Error::InvalidDriverValue("MMQ resident artifact digest")); @@ -24,54 +23,31 @@ pub(crate) fn asset() -> Result<&'static [u8]> { impl QueuedCommand { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { match self { - Self::OriginalGather(f, words, args) => context - .driver - .api - .launch_mmq_original_gather(*f, *words, args), - Self::OriginalHelper(f, words, args) => context - .driver - .api - .launch_mmq_original_group_helper(*f, *words, args), - Self::OriginalSwiglu(f, rows, args) => context - .driver - .api - .launch_mmq_original_swiglu(*f, *rows, args), - Self::NativeIntegerDot(f, tokens, args) => context - .driver - .api - .launch_iq3_native_integer(*f, *tokens, false, args), - Self::NativeIntegerReduce(f, tokens, args) => context - .driver - .api - .launch_iq3_native_integer(*f, *tokens, true, args), - Self::Helper(f, words, args) => { - context.driver.api.launch_mmq_resident(*f, *words, args) + Self::OriginalGather(f, words, args) => context.driver.api.launch_mmq_original_gather(*f, *words, args), + Self::OriginalHelper(f, words, args) => { + context.driver.api.launch_mmq_original_group_helper(*f, *words, args) } + Self::OriginalSwiglu(f, rows, args) => context.driver.api.launch_mmq_original_swiglu(*f, *rows, args), + Self::NativeIntegerDot(f, tokens, args) => { + context.driver.api.launch_iq3_native_integer(*f, *tokens, false, args) + } + Self::NativeIntegerReduce(f, tokens, args) => { + context.driver.api.launch_iq3_native_integer(*f, *tokens, true, args) + } + Self::Helper(f, words, args) => context.driver.api.launch_mmq_resident(*f, *words, args), Self::Quantize(f, layout, args) => context.driver.api.quantize_mmq(*f, *layout, args), - Self::NativeQuantize(f, grid, args) => { - context.driver.api.launch_q8_quantize(*f, *grid, args) - } - Self::Project(f, layout, grid, args) => { - context.driver.api.project_mmq(*f, *layout, *grid, args) - } + Self::NativeQuantize(f, grid, args) => context.driver.api.launch_q8_quantize(*f, *grid, args), + Self::Project(f, layout, grid, args) => context.driver.api.project_mmq(*f, *layout, *grid, args), Self::Fixup(f, grid, args) => context.driver.api.fixup_mmq(*f, *grid, args), - Self::NativeDown(f, tokens, args) => context - .driver - .api - .launch_grouped_projection(*f, 640, *tokens, args), - Self::Swiglu(f, tokens, args) => context - .driver - .api - .launch_grouped_swiglu(*f, 5, *tokens, args), + Self::NativeDown(f, tokens, args) => context.driver.api.launch_grouped_projection(*f, 640, *tokens, args), + Self::Swiglu(f, tokens, args) => context.driver.api.launch_grouped_swiglu(*f, 5, *tokens, args), } } } pub(super) fn commands() -> Result> { let mut result = Vec::new(); // Closed stages need at most five commands, never an unbounded launch list. - result - .try_reserve_exact(5) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; Ok(result) } impl Context<'_> { @@ -100,11 +76,7 @@ impl Context<'_> { original_formats_asset(5)?; original_formats_asset(6)?; let mut owner = MmqWorkspace::new(self, true, true)?; - let result = owner - .experiment - .as_mut() - .ok_or(Error::ContextPoisoned)? - .enable_original_formats(); + let result = owner.experiment.as_mut().ok_or(Error::ContextPoisoned)?.enable_original_formats(); if let Err(error) = result { return combine(Err(error), owner.close()); } diff --git a/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs b/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs index 34456854..5e1d384b 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_drop_for_mmqworkspace.rs @@ -9,10 +9,7 @@ impl Drop for MmqWorkspace<'_> { } } impl<'ctx> MmqChunkActivation<'_, 'ctx> { - pub fn gather_gate_up<'lease>( - &'lease mut self, - indices: &[u32], - ) -> Result> { + pub fn gather_gate_up<'lease>(&'lease mut self, indices: &[u32]) -> Result> { self.workspace.check()?; if indices.is_empty() || indices.len() > 64 @@ -29,21 +26,13 @@ impl<'ctx> MmqChunkActivation<'_, 'ctx> { for (i, x) in indices.iter().enumerate() { ids[i * 4..i * 4 + 4].copy_from_slice(&x.to_le_bytes()); } - w.buffers[IDS] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&ids)?; - let source = w.handle( - CHUNK, - MmqFormat::Iq3XxsGateUp.layout(self.tokens)?.packed, - 16, - )?; + w.buffers[IDS].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&ids)?; + let source = w.handle(CHUNK, MmqFormat::Iq3XxsGateUp.layout(self.tokens)?.packed, 16)?; let out = w.handle(GROUP, l.packed, 16)?; let ids = w.handle(IDS, 256, 4)?; - for (a, an, b, bn) in [ - (source, w.buffer(CHUNK)?.bytes, out, w.buffer(GROUP)?.bytes), - (ids, 256, out, w.buffer(GROUP)?.bytes), - ] { + for (a, an, b, bn) in + [(source, w.buffer(CHUNK)?.bytes, out, w.buffer(GROUP)?.bytes), (ids, 256, out, w.buffer(GROUP)?.bytes)] + { if a.overlaps(an, b, bn) { return Err(Error::OutputAliasesInput); } @@ -53,38 +42,20 @@ impl<'ctx> MmqChunkActivation<'_, 'ctx> { commands.push(QueuedCommand::Helper( w.kernel(2)?, (l.payload / 4) as u32, - ffi::MmqResidentArguments::gather( - source, - ids, - out, - self.tokens, - t, - l.padded_columns / 128, - ), + ffi::MmqResidentArguments::gather(source, ids, out, self.tokens, t, l.padded_columns / 128), )); w.finish_finite(commands, GROUP, l.payload / 144, true) })(); w.fail(r)?; - Ok(MmqGroupActivation { - workspace: w, - tokens: t, - original: self.original, - }) + Ok(MmqGroupActivation { workspace: w, tokens: t, original: self.original }) } } impl<'lease, 'ctx> MmqGroupActivation<'lease, 'ctx> { - pub fn gate_up( - self, - gate: &MmqWeights<'_>, - up: &MmqWeights<'_>, - ) -> Result> { + pub fn gate_up(self, gate: &MmqWeights<'_>, up: &MmqWeights<'_>) -> Result> { let admitted = |format| { matches!(format, MmqFormat::Iq3XxsGateUp | MmqFormat::Iq2SGateUp) || (self.original - && matches!( - format, - MmqFormat::Iq3SGateUp | MmqFormat::Iq4XsGateUp | MmqFormat::Iq4NlGateUp - )) + && matches!(format, MmqFormat::Iq3SGateUp | MmqFormat::Iq4XsGateUp | MmqFormat::Iq4NlGateUp)) }; if !admitted(gate.format) || !admitted(up.format) { return Err(Error::InvalidProjectionShape); @@ -114,24 +85,13 @@ impl<'lease, 'ctx> MmqGroupActivation<'lease, 'ctx> { return Err(Error::OutputAliasesInput); } let guard = w.context.enter()?; - let k = combine( - w.context.fixed_kernel(FixedOperation::GroupedSwiglu), - guard.finish(), - )?; + let k = combine(w.context.fixed_kernel(FixedOperation::GroupedSwiglu), guard.finish())?; let mut commands = commands()?; - commands.push(QueuedCommand::Swiglu( - k.function, - t, - ffi::ProjectionArguments::new(a, b, c, 640, 640), - )); + commands.push(QueuedCommand::Swiglu(k.function, t, ffi::ProjectionArguments::new(a, b, c, 640, 640))); w.finish_finite(commands, HIDDEN, t as usize * 640, false) })(); w.fail(r)?; - Ok(MmqHidden { - workspace: w, - tokens: t, - original: self.original, - }) + Ok(MmqHidden { workspace: w, tokens: t, original: self.original }) } } impl<'lease, 'ctx> MmqHidden<'lease, 'ctx> { @@ -156,44 +116,28 @@ impl<'lease, 'ctx> MmqHidden<'lease, 'ctx> { } })(); w.fail(r)?; - Ok(FiniteMmqOutput { - workspace: w, - tokens: t, - }) + Ok(FiniteMmqOutput { workspace: w, tokens: t }) } } impl FiniteMmqOutput<'_, '_> { pub fn tokens(&self) -> u32 { self.tokens } - pub fn copy_down_column_to_slot( - &self, - column: u32, - destination: &mut DeviceBuffer<'_>, - slot: u32, - ) -> Result<()> { + pub fn copy_down_column_to_slot(&self, column: u32, destination: &mut DeviceBuffer<'_>, slot: u32) -> Result<()> { self.copy_down_columns_to_slots(&mut [(column, destination, slot)]) } /// Copy a bounded group of actual finite Down columns into disjoint whole /// ten-slot packets. All copies finish before return; the caller publishes /// its route/coverage proofs only after this method succeeds. - pub fn copy_down_columns_to_slots( - &self, - copies: &mut [(u32, &mut DeviceBuffer<'_>, u32)], - ) -> Result<()> { + pub fn copy_down_columns_to_slots(&self, copies: &mut [(u32, &mut DeviceBuffer<'_>, u32)]) -> Result<()> { let w = &*self.workspace; w.check()?; - if copies.is_empty() - || copies.len() > 64 - || copies.windows(2).any(|pair| pair[0].0 >= pair[1].0) - { + if copies.is_empty() || copies.len() > 64 || copies.windows(2).any(|pair| pair[0].0 >= pair[1].0) { return Err(Error::InvalidProjectionShape); } let source = w.handle(DOWN, self.tokens as usize * 10240, 4)?; let mut handles = Vec::new(); - handles - .try_reserve_exact(copies.len()) - .map_err(|_| Error::HostAllocation)?; + handles.try_reserve_exact(copies.len()).map_err(|_| Error::HostAllocation)?; // No device operation occurs until every owner/span is admitted. for (column, destination, slot) in copies.iter() { if *column >= self.tokens || *slot >= 10 || destination.bytes != 102400 { @@ -205,14 +149,11 @@ impl FiniteMmqOutput<'_, '_> { let target = destination.handle.ok_or(Error::ContextPoisoned)?; target.validate_projection_extent(102400, 4)?; if source.overlaps(w.buffer(DOWN)?.bytes, target, 102400) - || handles - .iter() - .any(|(whole, _, _): &DownCopyHandles| whole.overlaps(102400, target, 102400)) + || handles.iter().any(|(whole, _, _): &DownCopyHandles| whole.overlaps(102400, target, 102400)) { return Err(Error::OutputAliasesInput); } - let part = - source.checked_subspan(w.buffer(DOWN)?.bytes, *column as usize * 10240, 10240)?; + let part = source.checked_subspan(w.buffer(DOWN)?.bytes, *column as usize * 10240, 10240)?; handles.push((target, target.moe_down_slot(*slot)?, part)); } let guard = w.context.enter()?; diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs index 2269bd4e..48a73a71 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MmqWorkspace<'ctx> { pub(in super::super) fn new( context: &'ctx Context<'ctx>, @@ -21,30 +20,17 @@ impl<'ctx> MmqWorkspace<'ctx> { } } let experiment = context.mmq_experiment()?; - let scratch = (experiment.sms as usize) - .checked_mul(64 * 128 * 4) - .ok_or(Error::BudgetExceeded)?; - let sizes = [ - 655360, 193536, 193536, 163840, 163840, 163840, 82944, 655360, scratch, 256, 4, - ]; + let scratch = (experiment.sms as usize).checked_mul(64 * 128 * 4).ok_or(Error::BudgetExceeded)?; + let sizes = [655360, 193536, 193536, 163840, 163840, 163840, 82944, 655360, scratch, 256, 4]; let charge = sizes.iter().try_fold( if native_policy { - native_activation::CHARGE - + if integer_policy { - native_integer::CHARGE - } else { - 0 - } + native_activation::CHARGE + if integer_policy { native_integer::CHARGE } else { 0 } } else { 0 }, |a, b| a.checked_add(*b).ok_or(Error::BudgetExceeded), )?; - if context - .allocated_bytes() - .checked_add(charge) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(charge).is_none_or(|n| n > context.budget) { return combine(Err(Error::BudgetExceeded), experiment.close()); } let mut owner = Self { @@ -89,23 +75,10 @@ impl<'ctx> MmqWorkspace<'ctx> { Ok(owner) } pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() - + self - .original_group - .as_ref() - .map_or(0, |b| b.allocated_bytes()) - + self - .native_activation - .as_ref() - .map_or(0, |_| native_activation::CHARGE) - + self - .native_integer - .as_ref() - .map_or(0, |_| native_integer::CHARGE) + self.buffers.iter().flatten().map(|b| b.bytes).sum::() + + self.original_group.as_ref().map_or(0, |b| b.allocated_bytes()) + + self.native_activation.as_ref().map_or(0, |_| native_activation::CHARGE) + + self.native_integer.as_ref().map_or(0, |_| native_integer::CHARGE) } pub(in super::super) fn check(&self) -> Result<()> { if self.failed @@ -119,11 +92,7 @@ impl<'ctx> MmqWorkspace<'ctx> { } if let Some(integer) = &self.native_integer { integer.check()?; - let native = self - .native_activation - .as_ref() - .ok_or(Error::UnsupportedProjection)? - .buffer()?; + let native = self.native_activation.as_ref().ok_or(Error::UnsupportedProjection)?.buffer()?; if integer.overlaps(native.handle.ok_or(Error::ContextPoisoned)?, native.bytes)? { return Err(Error::OutputAliasesInput); } @@ -151,9 +120,7 @@ impl<'ctx> MmqWorkspace<'ctx> { } pub(in super::super) fn kernel(&self, kind: usize) -> Result { self.check()?; - self.functions - .ok_or(Error::ContextPoisoned) - .map(|f| f[kind]) + self.functions.ok_or(Error::ContextPoisoned).map(|f| f[kind]) } pub(in super::super) fn fail(&mut self, r: Result) -> Result { if r.is_err() { diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs index 1ad6455a..06e55cb0 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MmqWorkspace<'ctx> { pub(in super::super) fn finish_finite( &self, @@ -13,12 +12,8 @@ impl<'ctx> MmqWorkspace<'ctx> { q8: bool, ) -> Result<()> { let tail = if q8 { 9216 } else { 0 }; - let bytes = if q8 { - amount.checked_mul(144).and_then(|n| n.checked_add(tail)) - } else { - amount.checked_mul(4) - } - .ok_or(Error::InvalidProjectionShape)?; + let bytes = if q8 { amount.checked_mul(144).and_then(|n| n.checked_add(tail)) } else { amount.checked_mul(4) } + .ok_or(Error::InvalidProjectionShape)?; let source = self.handle(index, bytes, 4)?; let status = self.handle(STATUS, 4, 4)?; if source.overlaps(self.buffer(index)?.bytes, status, 4) { @@ -32,13 +27,7 @@ impl<'ctx> MmqWorkspace<'ctx> { commands.push(QueuedCommand::Helper( self.kernel(1)?, (bytes / 4) as u32, - ffi::MmqResidentArguments::finite( - source, - status, - u32::from(q8), - amount as u32, - tail as u32, - ), + ffi::MmqResidentArguments::finite(source, status, u32::from(q8), amount as u32, tail as u32), )); match self.run_queued(commands, Some(status))? { 0 => Ok(()), @@ -93,32 +82,18 @@ impl<'ctx> MmqWorkspace<'ctx> { let ih = self.handle(input, l.input, 16)?; let qh = self.handle(packed, l.packed, 16)?; let sh = self.handle(STATUS, 4, 4)?; - let sources = [ - (ih, self.buffer(input)?.bytes), - (qh, self.buffer(packed)?.bytes), - (sh, 4), - ]; + let sources = [(ih, self.buffer(input)?.bytes), (qh, self.buffer(packed)?.bytes), (sh, 4)]; for i in 0..sources.len() { for j in i + 1..sources.len() { - if sources[i] - .0 - .overlaps(sources[i].1, sources[j].0, sources[j].1) - { + if sources[i].0.overlaps(sources[i].1, sources[j].0, sources[j].1) { return Err(Error::OutputAliasesInput); } } } - let n = self - .native_activation - .as_ref() - .ok_or(Error::InvalidProjectionShape)?; + let n = self.native_activation.as_ref().ok_or(Error::InvalidProjectionShape)?; let nh = n.buffer()?.handle.ok_or(Error::ContextPoisoned)?; for b in self.buffers.iter().flatten() { - if nh.overlaps( - native_activation::CHARGE, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { + if nh.overlaps(native_activation::CHARGE, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { return Err(Error::OutputAliasesInput); } } @@ -155,9 +130,7 @@ impl<'ctx> MmqWorkspace<'ctx> { original: bool, ) -> Result<()> { self.check()?; - let l = weights - .format - .adaptive_layout(tokens, MmqProfile::OriginalAdaptive)?; + let l = weights.format.adaptive_layout(tokens, MmqProfile::OriginalAdaptive)?; let w = weights.native_buffer()?; if !std::ptr::eq(self.context, weights.context) { return Err(Error::ContextMismatch); @@ -166,10 +139,7 @@ impl<'ctx> MmqWorkspace<'ctx> { wh.validate_projection_extent(w.bytes, 2)?; let ph = self.handle(packed, l.packed, 16)?; let oh = self.handle(out, l.output, 4)?; - for (h, n) in [ - (ph, self.buffer(packed)?.bytes), - (oh, self.buffer(out)?.bytes), - ] { + for (h, n) in [(ph, self.buffer(packed)?.bytes), (oh, self.buffer(out)?.bytes)] { if wh.overlaps(w.bytes, h, n) { return Err(Error::OutputAliasesInput); } @@ -184,8 +154,7 @@ impl<'ctx> MmqWorkspace<'ctx> { return Err(Error::UnsupportedProjection); } if matches!(weights.format, MmqFormat::Iq3XxsGateUp) { - if self.native_activation.is_none() || packed != GROUP || !matches!(out, GATE | UP) - { + if self.native_activation.is_none() || packed != GROUP || !matches!(out, GATE | UP) { return Err(Error::UnsupportedProjection); } for b in self.buffers.iter().flatten() { @@ -207,11 +176,7 @@ impl<'ctx> MmqWorkspace<'ctx> { let temp = if fixup { let n = grid as usize * l.tile.width() as usize * 128 * 4; let th = self.handle(SCRATCH, n, 4)?; - for (h, b) in [ - (wh, w.bytes), - (ph, self.buffer(packed)?.bytes), - (oh, self.buffer(out)?.bytes), - ] { + for (h, b) in [(wh, w.bytes), (ph, self.buffer(packed)?.bytes), (oh, self.buffer(out)?.bytes)] { if th.overlaps(self.buffer(SCRATCH)?.bytes, h, b) { return Err(Error::OutputAliasesInput); } @@ -222,24 +187,13 @@ impl<'ctx> MmqWorkspace<'ctx> { }; let mut commands = commands()?; if fixup { - commands.push( - self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?, - ); + commands.push(self.zero_command(SCRATCH, grid as usize * l.tile.width() as usize * 128 * 4)?); } let f = e.function(weights.format, l.tile, false)?; - commands.push(QueuedCommand::Project( - f, - l, - grid, - ffi::MmqArguments::new(wh, ph, oh, temp, l), - )); + commands.push(QueuedCommand::Project(f, l, grid, ffi::MmqArguments::new(wh, ph, oh, temp, l))); if let Some(th) = temp { let f = e.function(weights.format, l.tile, true)?; - commands.push(QueuedCommand::Fixup( - f, - grid, - ffi::MmqFixupArguments::new(oh, th, l), - )); + commands.push(QueuedCommand::Fixup(f, grid, ffi::MmqFixupArguments::new(oh, th, l))); } self.finish_finite(commands, out, l.output / 4, false) } diff --git a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs index 4a3124d7..3f48399b 100644 --- a/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs +++ b/crates/cuda-driver/src/mmq_resident/impl_mmqworkspace/impl_mmqworkspace_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MmqWorkspace<'ctx> { /// Mint an affine Original-prompt activation using the actual D4 quantizer, /// independently of this workspace's optional native integer operators. @@ -40,18 +39,11 @@ impl<'ctx> MmqWorkspace<'ctx> { dst.copy_from_range(0, &b)?; self.quantize_with_operator(INPUT, CHUNK, l, original) })(); - if matches!( - &r, - Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext) - ) { + if matches!(&r, Err(Error::Driver { .. }) | Err(Error::Multiple { .. }) | Err(Error::UnexpectedContext)) { self.context.poisoned.set(true); } self.fail(r)?; - Ok(MmqChunkActivation { - workspace: self, - tokens, - original, - }) + Ok(MmqChunkActivation { workspace: self, tokens, original }) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -61,10 +53,7 @@ impl<'ctx> MmqWorkspace<'ctx> { self.functions = None; let mut r = self.original_group.take().map_or(Ok(()), |n| n.close()); r = combine(r, self.native_integer.take().map_or(Ok(()), |n| n.close())); - r = combine( - r, - self.native_activation.take().map_or(Ok(()), |n| n.close()), - ); + r = combine(r, self.native_activation.take().map_or(Ok(()), |n| n.close())); for b in &mut self.buffers { if let Some(b) = b.take() { let step = b.release(); diff --git a/crates/cuda-driver/src/mmq_resident_gpu.rs b/crates/cuda-driver/src/mmq_resident_gpu.rs index 5e85d7a6..ada80fb3 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu.rs @@ -31,16 +31,11 @@ const ROOT_REFERENCE_SHA: &str = "752d9c2c2c77df57455384dedbfb191b524c6c1c5155d7 #[test] #[ignore = "ROOT-only new resident memory transport; actual CUDA"] fn original_references_resident_chain_gather_dual_native_and_guards_exact() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), Ok("yes")); let expected = std::env::var("LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA").unwrap(); assert_eq!(expected, ROOT_REFERENCE_SHA); - let receipt = Receipt::load( - PathBuf::from(std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").unwrap()), - &expected, - ); + let receipt = + Receipt::load(PathBuf::from(std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").unwrap()), &expected); let driver = Driver::load().unwrap(); let c = driver.device(0).unwrap().create_context(BUDGET).unwrap(); let mut w = c.mmq_workspace().unwrap(); @@ -97,47 +92,26 @@ fn original_references_resident_chain_gather_dual_native_and_guards_exact() { let _private = chunk.gather_gate_up(&[0, 3]).unwrap(); } assert_eq!(direct(&receipt, &mut w, 18, 4, &owners[0]), (2560, 20736)); - assert_eq!( - witness(&mut w, &file(&receipt, 18, 4, "reference_q8.bin")), - 21 - ); + assert_eq!(witness(&mut w, &file(&receipt, 18, 4, "reference_q8.bin")), 21); let charge = c.allocated_bytes(); for t in [0, 65, u32::MAX] { - assert!(matches!( - w.prepare_gate_up_chunk(&[0.0; 2560], t), - Err(Error::InvalidProjectionShape) - )); + assert!(matches!(w.prepare_gate_up_chunk(&[0.0; 2560], t), Err(Error::InvalidProjectionShape))); } let mut invalid = floats(&file(&receipt, 18, 4, "input.f32")); *invalid.last_mut().unwrap() = f32::NAN; - assert!(matches!( - w.prepare_gate_up_chunk(&invalid, 4), - Err(Error::InvalidQ8Activation) - )); + assert!(matches!(w.prepare_gate_up_chunk(&invalid, 4), Err(Error::InvalidQ8Activation))); assert_eq!(c.allocated_bytes(), charge); assert!(!c.is_poisoned()); let foreign = driver.device(0).unwrap().create_context(BUDGET).unwrap(); - let foreign_weight = foreign - .mmq_weights( - MmqFormat::Iq3XxsGateUp, - &file(&receipt, 18, 4, "weights.bin"), - ) - .unwrap(); - assert!(matches!( - w.project(&foreign_weight, CHUNK, GATE, 4), - Err(Error::ContextMismatch) - )); + let foreign_weight = foreign.mmq_weights(MmqFormat::Iq3XxsGateUp, &file(&receipt, 18, 4, "weights.bin")).unwrap(); + assert!(matches!(w.project(&foreign_weight, CHUNK, GATE, 4), Err(Error::ContextMismatch))); foreign_weight.close().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); for ((kind, _, _), owner) in formats.into_iter().zip(owners) { let raw = file(&receipt, kind, 4, "weights.bin"); let all = download(owner.native_buffer().unwrap(), owner.allocated_bytes()); - same( - &all[..raw.len()], - &raw, - "all operations weight immutability", - ); + same(&all[..raw.len()], &raw, "all operations weight immutability"); assert!(all[raw.len()..].iter().all(|v| *v == 0)); owner.close().unwrap(); } @@ -146,11 +120,7 @@ fn original_references_resident_chain_gather_dual_native_and_guards_exact() { assert_eq!(c.allocated_bytes(), 0); assert!(!c.is_poisoned()); c.close().unwrap(); - let small = driver - .device(0) - .unwrap() - .create_context(2272515 + sms as usize * 32768) - .unwrap(); + let small = driver.device(0).unwrap().create_context(2272515 + sms as usize * 32768).unwrap(); assert!(matches!(small.mmq_workspace(), Err(Error::BudgetExceeded))); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); @@ -169,16 +139,11 @@ struct LivePacketAlias<'borrow, 'ctx> { #[test] #[ignore = "ROOT-only changed queued finite boundary and bulk Down copy; actual CUDA"] fn queued_finite_chain_and_bulk_down_packets_exact() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_MMQ_NUMERIC").as_deref(), Ok("yes")); let expected = std::env::var("LELEKA_STRA169_MMQ_REFERENCE_MANIFEST_SHA").unwrap(); assert_eq!(expected, ROOT_REFERENCE_SHA); - let receipt = Receipt::load( - PathBuf::from(std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").unwrap()), - &expected, - ); + let receipt = + Receipt::load(PathBuf::from(std::env::var_os("LELEKA_STRA169_MMQ_REFERENCE_DIR").unwrap()), &expected); const T: u32 = 4; const GU_BYTES: usize = 4 * 2560; const DOWN_BYTES: usize = 4 * 10240; @@ -189,11 +154,7 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { finite(&data); let driver = Driver::load().unwrap(); let c = driver.device(0).unwrap().create_context(BUDGET).unwrap(); - let foreign = driver - .device(0) - .unwrap() - .create_context(PACKET_BYTES) - .unwrap(); + let foreign = driver.device(0).unwrap().create_context(PACKET_BYTES).unwrap(); let gu = c.mmq_weights(MmqFormat::Iq3XxsGateUp, &gu_raw).unwrap(); let down = c.mmq_weights(MmqFormat::Iq4NlDown, &down_raw).unwrap(); let weight_before = download(gu.native_buffer().unwrap(), gu.allocated_bytes()); @@ -210,44 +171,20 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { let input = upload(&c, &data); let mut gate = c.allocate(GU_BYTES).unwrap(); let mut up = c.allocate(GU_BYTES).unwrap(); - let (gate_values, q8) = old - .project_observed(MmqProfile::OriginalAdaptive, &gu, &input, T, &mut gate) - .unwrap(); - let (up_values, _) = old - .project_observed(MmqProfile::OriginalAdaptive, &gu, &input, T, &mut up) - .unwrap(); - compare( - &gate_values, - &file(&receipt, 18, T, "reference_streamk.f32"), - "original GU", - ); - same( - &q8, - &file(&receipt, 18, T, "reference_q8.bin"), - "original D4", - ); + let (gate_values, q8) = old.project_observed(MmqProfile::OriginalAdaptive, &gu, &input, T, &mut gate).unwrap(); + let (up_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, &gu, &input, T, &mut up).unwrap(); + compare(&gate_values, &file(&receipt, 18, T, "reference_streamk.f32"), "original GU"); + same(&q8, &file(&receipt, 18, T, "reference_q8.bin"), "original D4"); let mut hidden = c.allocate(GU_BYTES).unwrap(); - c.moe_swiglu_columns(&gate, &up, &mut hidden, T as usize) - .unwrap(); + c.moe_swiglu_columns(&gate, &up, &mut hidden, T as usize).unwrap(); let hidden_bytes = download(&hidden, GU_BYTES); finite(&hidden_bytes); let mut old_output = c.allocate(DOWN_BYTES).unwrap(); - let (down_values, down_q8) = old - .project_observed( - MmqProfile::OriginalAdaptive, - &down, - &hidden, - T, - &mut old_output, - ) - .unwrap(); + let (down_values, down_q8) = + old.project_observed(MmqProfile::OriginalAdaptive, &down, &hidden, T, &mut old_output).unwrap(); let down_bytes = download(&old_output, DOWN_BYTES); compare(&down_values, &down_bytes, "qualified actual Down"); - same( - &download(&input, data.len()), - &data, - "baseline source immutable", - ); + same(&download(&input, data.len()), &data, "baseline source immutable"); old_output.release().unwrap(); hidden.release().unwrap(); up.release().unwrap(); @@ -261,30 +198,14 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { let mut d = upload(&c, &vec![0x3c; PACKET_BYTES]); let mut short = upload(&c, &[0x7e; 4]); let charge = c.allocated_bytes(); - let before = [ - download(&a, PACKET_BYTES), - download(&b, PACKET_BYTES), - download(&d, PACKET_BYTES), - ]; + let before = [download(&a, PACKET_BYTES), download(&b, PACKET_BYTES), download(&d, PACKET_BYTES)]; let mut expected_packets = before.clone(); { let mut prepared = w.prepare_gate_up_chunk(&floats(&data), T).unwrap(); - same( - &download(prepared.workspace.buffer(INPUT).unwrap(), data.len()), - &data, - "queued source immutable", - ); - same( - &download(prepared.workspace.buffer(CHUNK).unwrap(), q8.len()), - &q8, - "queued chunk Q8", - ); + same(&download(prepared.workspace.buffer(INPUT).unwrap(), data.len()), &data, "queued source immutable"); + same(&download(prepared.workspace.buffer(CHUNK).unwrap(), q8.len()), &q8, "queued chunk Q8"); let group = prepared.gather_gate_up(&[0, 1, 2, 3]).unwrap(); - same( - &download(group.workspace.buffer(GROUP).unwrap(), q8.len()), - &q8, - "queued identity group Q8+tail", - ); + same(&download(group.workspace.buffer(GROUP).unwrap(), q8.len()), &q8, "queued identity group Q8+tail"); let actual_hidden = group.gate_up(&gu, &gu).unwrap(); same( &download(actual_hidden.workspace.buffer(GATE).unwrap(), GU_BYTES), @@ -302,46 +223,26 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { "queued finite hidden", ); let actual = actual_hidden.down(&down).unwrap(); - same( - &download(actual.workspace.buffer(DOWN_Q8).unwrap(), down_q8.len()), - &down_q8, - "queued Down Q8", - ); - same( - &download(actual.workspace.buffer(DOWN).unwrap(), DOWN_BYTES), - &down_bytes, - "queued finite Down", - ); + same(&download(actual.workspace.buffer(DOWN_Q8).unwrap(), down_q8.len()), &down_q8, "queued Down Q8"); + same(&download(actual.workspace.buffer(DOWN).unwrap(), DOWN_BYTES), &down_bytes, "queued finite Down"); assert_eq!(c.allocated_bytes(), charge); // All full packets, including untouched slots, compared after each bulk copy. - actual - .copy_down_columns_to_slots(&mut [(0, &mut a, 1), (3, &mut b, 8)]) - .unwrap(); + actual.copy_down_columns_to_slots(&mut [(0, &mut a, 1), (3, &mut b, 8)]).unwrap(); for (column, packet, slot) in [(0usize, 0usize, 1usize), (3, 1, 8)] { expected_packets[packet][slot * 10240..(slot + 1) * 10240] .copy_from_slice(&down_bytes[column * 10240..(column + 1) * 10240]); } for (packet, expected) in [&a, &b, &d].iter().zip(&expected_packets) { - same( - &download(packet, PACKET_BYTES), - expected, - "two-packet copy+sentinels", - ); + same(&download(packet, PACKET_BYTES), expected, "two-packet copy+sentinels"); } - actual - .copy_down_columns_to_slots(&mut [(0, &mut a, 9), (1, &mut b, 0), (2, &mut d, 4)]) - .unwrap(); + actual.copy_down_columns_to_slots(&mut [(0, &mut a, 9), (1, &mut b, 0), (2, &mut d, 4)]).unwrap(); for (column, packet, slot) in [(0usize, 0usize, 9usize), (1, 1, 0), (2, 2, 4)] { expected_packets[packet][slot * 10240..(slot + 1) * 10240] .copy_from_slice(&down_bytes[column * 10240..(column + 1) * 10240]); } for (packet, expected) in [&a, &b, &d].iter().zip(&expected_packets) { - same( - &download(packet, PACKET_BYTES), - expected, - "three-packet copy+sentinels", - ); + same(&download(packet, PACKET_BYTES), expected, "three-packet copy+sentinels"); } assert_eq!(c.allocated_bytes(), charge); @@ -355,25 +256,16 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { ([0, 1], [2, u32::MAX]), ] { assert!(matches!( - actual.copy_down_columns_to_slots(&mut [ - (columns[0], &mut a, slots[0]), - (columns[1], &mut b, slots[1]) - ]), + actual + .copy_down_columns_to_slots(&mut [(columns[0], &mut a, slots[0]), (columns[1], &mut b, slots[1])]), Err(Error::InvalidProjectionShape) )); for (packet, expected) in [&a, &b, &d].iter().zip(&expected_packets) { - same( - &download(packet, PACKET_BYTES), - expected, - "all-before-copy refusal", - ); + same(&download(packet, PACKET_BYTES), expected, "all-before-copy refusal"); } assert_eq!(c.allocated_bytes(), charge); } - assert!(matches!( - actual.copy_down_columns_to_slots(&mut []), - Err(Error::InvalidProjectionShape) - )); + assert!(matches!(actual.copy_down_columns_to_slots(&mut []), Err(Error::InvalidProjectionShape))); assert!(matches!( actual.copy_down_columns_to_slots(&mut [(0, &mut a, 2), (1, &mut short, 1)]), Err(Error::InvalidProjectionShape) @@ -382,41 +274,24 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { // RAII restoration runs on both the ordinary refusal and unwind path. let handle = a.handle; let mut alias = LivePacketAlias::new(&mut b, handle); - let alias_result = - actual.copy_down_columns_to_slots(&mut [(0, &mut a, 2), (1, alias.buffer(), 2)]); + let alias_result = actual.copy_down_columns_to_slots(&mut [(0, &mut a, 2), (1, alias.buffer(), 2)]); drop(alias); assert!(matches!(alias_result, Err(Error::OutputAliasesInput))); for (packet, expected) in [&a, &b, &d].iter().zip(&expected_packets) { - same( - &download(packet, PACKET_BYTES), - expected, - "alias refusal and restored real owner", - ); + same(&download(packet, PACKET_BYTES), expected, "alias refusal and restored real owner"); } let mut foreign_packet = upload(&foreign, &before[0]); assert!(matches!( actual.copy_down_columns_to_slots(&mut [(0, &mut a, 2), (1, &mut foreign_packet, 2)]), Err(Error::ContextMismatch) )); - same( - &download(&foreign_packet, PACKET_BYTES), - &before[0], - "foreign destination unchanged", - ); + same(&download(&foreign_packet, PACKET_BYTES), &before[0], "foreign destination unchanged"); foreign_packet.release().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); for (packet, expected) in [&a, &b, &d].iter().zip(&expected_packets) { - same( - &download(packet, PACKET_BYTES), - expected, - "foreign/short refusal no partial write", - ); + same(&download(packet, PACKET_BYTES), expected, "foreign/short refusal no partial write"); } - same( - &download(actual.workspace.buffer(DOWN).unwrap(), DOWN_BYTES), - &down_bytes, - "copy source immutable", - ); + same(&download(actual.workspace.buffer(DOWN).unwrap(), DOWN_BYTES), &down_bytes, "copy source immutable"); assert!(!c.is_poisoned()); assert_eq!(c.allocated_bytes(), charge); // Test-only actual status observation, not a forged finite producer: last @@ -426,19 +301,9 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { .unwrap() .copy_from_range(DOWN_BYTES - 4, &f32::NAN.to_le_bytes()) .unwrap(); - assert!(matches!( - actual.workspace.finite(DOWN, DOWN_BYTES / 4, false), - Err(Error::NonFiniteMmqOutput("Down")) - )); - actual.workspace.buffers[DOWN] - .as_mut() - .unwrap() - .copy_from_range(0, &down_bytes) - .unwrap(); - actual - .workspace - .finite(DOWN, DOWN_BYTES / 4, false) - .unwrap(); + assert!(matches!(actual.workspace.finite(DOWN, DOWN_BYTES / 4, false), Err(Error::NonFiniteMmqOutput("Down")))); + actual.workspace.buffers[DOWN].as_mut().unwrap().copy_from_range(0, &down_bytes).unwrap(); + actual.workspace.finite(DOWN, DOWN_BYTES / 4, false).unwrap(); assert!(!c.is_poisoned()); assert_eq!(c.allocated_bytes(), charge); short.release().unwrap(); @@ -472,41 +337,41 @@ fn queued_finite_chain_and_bulk_down_packets_exact() { #[path = "mmq_resident_gpu/digest_fn.rs"] mod digest_fn; #[allow(unused_imports)] -use digest_fn::digest; -#[allow(unused_imports)] -use digest_fn::hex; -#[allow(unused_imports)] -use digest_fn::read_regular; -#[allow(unused_imports)] -use digest_fn::field; -#[allow(unused_imports)] -use digest_fn::integer; -#[allow(unused_imports)] -use digest_fn::finite; -#[allow(unused_imports)] use digest_fn::compare; #[allow(unused_imports)] -use digest_fn::upload; +use digest_fn::digest; #[allow(unused_imports)] use digest_fn::download; #[allow(unused_imports)] -use digest_fn::floats; -#[allow(unused_imports)] use digest_fn::encoded; #[allow(unused_imports)] +use digest_fn::field; +#[allow(unused_imports)] use digest_fn::file; #[allow(unused_imports)] -use digest_fn::same; +use digest_fn::finite; +#[allow(unused_imports)] +use digest_fn::floats; +#[allow(unused_imports)] +use digest_fn::hex; +#[allow(unused_imports)] +use digest_fn::integer; #[allow(unused_imports)] use digest_fn::raw_format; +#[allow(unused_imports)] +use digest_fn::read_regular; +#[allow(unused_imports)] +use digest_fn::same; +#[allow(unused_imports)] +use digest_fn::upload; #[path = "mmq_resident_gpu/native_owner_fn.rs"] mod native_owner_fn; #[allow(unused_imports)] -use native_owner_fn::native_owner; -#[allow(unused_imports)] use native_owner_fn::direct; #[allow(unused_imports)] use native_owner_fn::gather; +#[allow(unused_imports)] +use native_owner_fn::native_owner; #[path = "mmq_resident_gpu/chain_fn.rs"] mod chain_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs index 9c6a77d4..cf261d90 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/chain_fn.rs @@ -18,31 +18,16 @@ pub(super) fn chain( let mut gate = c.allocate(t as usize * 2560).unwrap(); let mut up = c.allocate(t as usize * 2560).unwrap(); // Immutable qualified modules + original native SwiGLU baseline FIRST. - let (gate_values, q8) = old - .project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut gate) - .unwrap(); - let (up_values, _) = old - .project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut up) - .unwrap(); - compare( - &gate_values, - &file(r, kind, t, "reference_streamk.f32"), - "baseline GU original", - ); - same( - &q8, - &file(r, kind, t, "reference_q8.bin"), - "baseline original Q8", - ); + let (gate_values, q8) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut gate).unwrap(); + let (up_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, gu, &input, t, &mut up).unwrap(); + compare(&gate_values, &file(r, kind, t, "reference_streamk.f32"), "baseline GU original"); + same(&q8, &file(r, kind, t, "reference_q8.bin"), "baseline original Q8"); let mut hidden = c.allocate(t as usize * 2560).unwrap(); - c.moe_swiglu_columns(&gate, &up, &mut hidden, t as usize) - .unwrap(); + c.moe_swiglu_columns(&gate, &up, &mut hidden, t as usize).unwrap(); let hidden_values = download(&hidden, t as usize * 2560); finite(&hidden_values); let mut output = c.allocate(t as usize * 10240).unwrap(); - let (down_values, _) = old - .project_observed(MmqProfile::OriginalAdaptive, down, &hidden, t, &mut output) - .unwrap(); + let (down_values, _) = old.project_observed(MmqProfile::OriginalAdaptive, down, &hidden, t, &mut output).unwrap(); let down_bytes = download(&output, t as usize * 10240); finite(&down_bytes); compare(&down_values, &down_bytes, "baseline Down actual"); @@ -58,41 +43,26 @@ pub(super) fn chain( let group = prepared.gather_gate_up(&ids).unwrap(); let actual_hidden = group.gate_up(gu, gu).unwrap(); same( - &download( - actual_hidden.workspace.buffer(GATE).unwrap(), - t as usize * 2560, - ), + &download(actual_hidden.workspace.buffer(GATE).unwrap(), t as usize * 2560), &encoded(&gate_values), "resident Gate", ); same( - &download( - actual_hidden.workspace.buffer(UP).unwrap(), - t as usize * 2560, - ), + &download(actual_hidden.workspace.buffer(UP).unwrap(), t as usize * 2560), &encoded(&up_values), "resident Up", ); same( - &download( - actual_hidden.workspace.buffer(HIDDEN).unwrap(), - t as usize * 2560, - ), + &download(actual_hidden.workspace.buffer(HIDDEN).unwrap(), t as usize * 2560), &hidden_values, "resident original SwiGLU", ); let actual = actual_hidden.down(down).unwrap(); - same( - &download(actual.workspace.buffer(DOWN).unwrap(), down_bytes.len()), - &down_bytes, - "resident actual Down", - ); + same(&download(actual.workspace.buffer(DOWN).unwrap(), down_bytes.len()), &down_bytes, "resident actual Down"); let mut packet = upload(c, &vec![0xa5; 102400]); let before = download(&packet, 102400); for (column, slot) in [(0, 0), (t / 2, 4), (t - 1, 9)] { - actual - .copy_down_column_to_slot(column, &mut packet, slot) - .unwrap(); + actual.copy_down_column_to_slot(column, &mut packet, slot).unwrap(); } let mut expected = before.clone(); for (column, slot) in [(0, 0), (t / 2, 4), (t - 1, 9)] { @@ -100,41 +70,23 @@ pub(super) fn chain( let d = slot as usize * 10240; expected[d..d + 10240].copy_from_slice(&down_bytes[s..s + 10240]); } - same( - &download(&packet, 102400), - &expected, - "full slotpacket + untouched slots", - ); + same(&download(&packet, 102400), &expected, "full slotpacket + untouched slots"); for (column, slot) in [(t, 0), (u32::MAX, 0), (0, 10), (0, u32::MAX)] { assert!(matches!( actual.copy_down_column_to_slot(column, &mut packet, slot), Err(Error::InvalidProjectionShape) )); - same( - &download(&packet, 102400), - &expected, - "refused slot immutable", - ); + same(&download(&packet, 102400), &expected, "refused slot immutable"); } let mut short = upload(c, &[0xa5; 4]); - assert!(matches!( - actual.copy_down_column_to_slot(0, &mut short, 0), - Err(Error::InvalidProjectionShape) - )); + assert!(matches!(actual.copy_down_column_to_slot(0, &mut short, 0), Err(Error::InvalidProjectionShape))); same(&download(&short, 4), &[0xa5; 4], "short packet immutable"); short.release().unwrap(); if t == 4 { let foreign = c.driver.device(0).unwrap().create_context(102400).unwrap(); let mut destination = upload(&foreign, &before); - assert!(matches!( - actual.copy_down_column_to_slot(0, &mut destination, 0), - Err(Error::ContextMismatch) - )); - same( - &download(&destination, 102400), - &before, - "foreign slot destination immutable", - ); + assert!(matches!(actual.copy_down_column_to_slot(0, &mut destination, 0), Err(Error::ContextMismatch))); + same(&download(&destination, 102400), &before, "foreign slot destination immutable"); destination.release().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); @@ -150,12 +102,7 @@ pub(super) fn witness(w: &mut MmqWorkspace<'_>, reference: &[u8]) -> usize { for (i, b) in base.as_chunks_mut::<4>().0.iter_mut().enumerate() { *b = [0.0_f32, -0.0, f32::from_bits(1), -1.0][i % 4].to_le_bytes(); } - for bad in [ - None, - Some(f32::NAN), - Some(f32::INFINITY), - Some(f32::NEG_INFINITY), - ] { + for bad in [None, Some(f32::NAN), Some(f32::INFINITY), Some(f32::NEG_INFINITY)] { let mut data = base.clone(); if let Some(v) = bad { let n = data.len(); @@ -168,34 +115,21 @@ pub(super) fn witness(w: &mut MmqWorkspace<'_>, reference: &[u8]) -> usize { } else { assert!(matches!(result, Err(Error::NonFiniteMmqOutput("Gate")))); } - assert_eq!( - download(w.buffer(STATUS).unwrap(), 4), - u32::from(bad.is_some()).to_le_bytes() - ); + assert_eq!(download(w.buffer(STATUS).unwrap(), 4), u32::from(bad.is_some()).to_le_bytes()); assert!(!w.context.is_poisoned()); checked += 1; } let amount = (reference.len() - 9216) / 144; let check = |w: &mut MmqWorkspace<'_>, data: &[u8], expected: u32| { - w.buffers[GROUP] - .as_mut() - .unwrap() - .copy_from_range(0, data) - .unwrap(); + w.buffers[GROUP].as_mut().unwrap().copy_from_range(0, data).unwrap(); let r = w.finite(GROUP, amount, true); match expected { 0 => r.unwrap(), 1 | 3 => assert!(matches!(r, Err(Error::InvalidQ8Activation))), - 2 => assert!(matches!( - r, - Err(Error::InvalidDriverValue("MMQ dirty Q8 tail")) - )), + 2 => assert!(matches!(r, Err(Error::InvalidDriverValue("MMQ dirty Q8 tail")))), _ => unreachable!(), } - assert_eq!( - download(w.buffer(STATUS).unwrap(), 4), - expected.to_le_bytes() - ); + assert_eq!(download(w.buffer(STATUS).unwrap(), 4), expected.to_le_bytes()); assert!(!w.context.is_poisoned()); }; check(w, reference, 0); @@ -223,11 +157,7 @@ pub(super) fn witness(w: &mut MmqWorkspace<'_>, reference: &[u8]) -> usize { *data.last_mut().unwrap() = 1; check(w, &data, 3); checked += 1; - w.buffers[GATE] - .as_mut() - .unwrap() - .copy_from(&vec![0xa5; 163840]) - .unwrap(); + w.buffers[GATE].as_mut().unwrap().copy_from(&vec![0xa5; 163840]).unwrap(); w.zero(GATE, 16).unwrap(); let zeros = download(w.buffer(GATE).unwrap(), 163840); assert_eq!(&zeros[..16], &[0; 16]); @@ -235,10 +165,7 @@ pub(super) fn witness(w: &mut MmqWorkspace<'_>, reference: &[u8]) -> usize { checked } impl<'borrow, 'ctx> LivePacketAlias<'borrow, 'ctx> { - pub(super) fn new( - buffer: &'borrow mut DeviceBuffer<'ctx>, - handle: Option, - ) -> Self { + pub(super) fn new(buffer: &'borrow mut DeviceBuffer<'ctx>, handle: Option) -> Self { let original = std::mem::replace(&mut buffer.handle, handle); Self { buffer, original } } diff --git a/crates/cuda-driver/src/mmq_resident_gpu/digest_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/digest_fn.rs index ffac9f34..8ad0e28c 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/digest_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/digest_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn digest(bytes: &[u8]) -> String { use std::fmt::Write; let mut out = String::with_capacity(64); @@ -14,12 +13,7 @@ pub(super) fn digest(bytes: &[u8]) -> String { } pub(super) fn hex(value: &str) { assert_eq!(value.len(), 64, "SHA256 length"); - assert!( - value - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)), - "SHA256 encoding" - ); + assert!(value.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)), "SHA256 encoding"); } pub(super) fn read_regular(path: &Path, limit: usize) -> Vec { let mut file = OpenOptions::new() @@ -28,20 +22,11 @@ pub(super) fn read_regular(path: &Path, limit: usize) -> Vec { .open(path) .expect("open pinned regular file"); let before = file.metadata().unwrap(); - assert!( - before.is_file() && before.len() <= limit as u64, - "bounded regular fixture" - ); + assert!(before.is_file() && before.len() <= limit as u64, "bounded regular fixture"); let mut bytes = Vec::new(); - file.by_ref() - .take(limit as u64 + 1) - .read_to_end(&mut bytes) - .unwrap(); + file.by_ref().take(limit as u64 + 1).read_to_end(&mut bytes).unwrap(); let after = file.metadata().unwrap(); - assert_eq!( - (before.dev(), before.ino(), before.len()), - (after.dev(), after.ino(), after.len()) - ); + assert_eq!((before.dev(), before.ino(), before.len()), (after.dev(), after.ino(), after.len())); assert_eq!(bytes.len() as u64, before.len(), "fixture changed length"); bytes } @@ -49,11 +34,7 @@ impl Receipt { pub(super) fn load(root: PathBuf, expected: &str) -> Self { hex(expected); assert!(root.is_absolute()); - assert_eq!( - root.canonicalize().unwrap(), - root, - "canonical fixture directory" - ); + assert_eq!(root.canonicalize().unwrap(), root, "canonical fixture directory"); let bytes = read_regular(&root.join("ROOT-REFERENCE.tsv"), 64 * 1024); assert_eq!(digest(&bytes), expected, "ROOT manifest pin"); let text = std::str::from_utf8(&bytes).unwrap(); @@ -63,24 +44,12 @@ impl Receipt { let fields: Vec<_> = line.split('\t').collect(); match fields.as_slice() { ["file", name, length, sha] => { - assert!( - Path::new(name) - .components() - .all(|c| matches!(c, Component::Normal(_))) - ); + assert!(Path::new(name).components().all(|c| matches!(c, Component::Normal(_)))); hex(sha); let bytes: usize = length.parse().unwrap(); assert!(bytes > 0 && bytes <= 64 * 1024 * 1024); assert!( - files - .insert( - (*name).to_owned(), - Pin { - bytes, - sha: (*sha).to_owned() - } - ) - .is_none(), + files.insert((*name).to_owned(), Pin { bytes, sha: (*sha).to_owned() }).is_none(), "duplicate file" ); } @@ -99,11 +68,7 @@ impl Receipt { ("profile", "sm120-fastmath-adaptive-original-first"), ("cases", "12"), ] { - assert_eq!( - headers.get(key).copied(), - Some(value), - "ROOT provenance {key}" - ); + assert_eq!(headers.get(key).copied(), Some(value), "ROOT provenance {key}"); } let mut allowed = vec![ "COMPLETE.json".to_owned(), @@ -118,19 +83,12 @@ impl Receipt { } } allowed.sort(); - assert_eq!( - files.keys().cloned().collect::>(), - allowed, - "exact 87 pinned files" - ); + assert_eq!(files.keys().cloned().collect::>(), allowed, "exact 87 pinned files"); let receipt = Self { root, files }; for name in receipt.files.keys() { let _ = receipt.read(name); } - assert_eq!( - digest(&receipt.read("ORACLE-SOURCE-MANIFEST.json")), - SOURCE_SHA - ); + assert_eq!(digest(&receipt.read("ORACLE-SOURCE-MANIFEST.json")), SOURCE_SHA); assert!(receipt.read("original_mmq_oracle").starts_with(b"\x7fELF")); let complete = String::from_utf8(receipt.read("COMPLETE.json")).unwrap(); for (key, value) in [ @@ -158,14 +116,7 @@ impl Receipt { pub(super) fn field<'a>(json: &'a str, key: &str) -> &'a str { let needle = format!("\"{key}\":"); assert_eq!(json.matches(&needle).count(), 1, "unique metadata key"); - json.split_once(&needle) - .unwrap() - .1 - .trim_start() - .split([',', '}']) - .next() - .unwrap() - .trim() + json.split_once(&needle).unwrap().1.trim_start().split([',', '}']).next().unwrap().trim() } pub(super) fn integer(json: &str, key: &str) -> usize { field(json, key).parse().unwrap() @@ -173,10 +124,7 @@ pub(super) fn integer(json: &str, key: &str) -> usize { pub(super) fn finite(bytes: &[u8]) { let (words, tail) = bytes.as_chunks::<4>(); assert!(tail.is_empty()); - assert!( - words.iter().all(|v| f32::from_le_bytes(*v).is_finite()), - "full finite reference" - ); + assert!(words.iter().all(|v| f32::from_le_bytes(*v).is_finite()), "full finite reference"); } pub(super) fn compare(values: &[f32], reference: &[u8], label: &str) { let (words, tail) = reference.as_chunks::<4>(); @@ -184,11 +132,7 @@ pub(super) fn compare(values: &[f32], reference: &[u8], label: &str) { assert_eq!(values.len(), words.len()); for (index, (actual, expected)) in values.iter().zip(words).enumerate() { assert!(actual.is_finite()); - assert_eq!( - actual.to_bits(), - u32::from_le_bytes(*expected), - "{label} word {index}" - ); + assert_eq!(actual.to_bits(), u32::from_le_bytes(*expected), "{label} word {index}"); } } pub(super) fn upload<'a>(c: &'a Context<'a>, data: &[u8]) -> DeviceBuffer<'a> { @@ -205,11 +149,7 @@ pub(super) fn download(b: &DeviceBuffer<'_>, size: usize) -> Vec { } pub(super) fn floats(data: &[u8]) -> Vec { assert!(data.len().is_multiple_of(4)); - data.as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes(*b)) - .collect() + data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() } pub(super) fn encoded(data: &[f32]) -> Vec { data.iter().flat_map(|v| v.to_le_bytes()).collect() diff --git a/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs b/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs index 3230c6fc..8ae2a280 100644 --- a/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs +++ b/crates/cuda-driver/src/mmq_resident_gpu/native_owner_fn.rs @@ -15,55 +15,22 @@ pub(super) fn native_owner(c: &Context<'_>, dual: &MmqWeights<'_>, raw: &[u8], d finite(&reference); let charge = c.allocated_bytes(); dual.native_q8_1(&input, &mut new).unwrap(); - same( - &download(&new, spec.rows * 4), - &reference, - "raw vs dual native", - ); + same(&download(&new, spec.rows * 4), &reference, "raw vs dual native"); assert_eq!(c.allocated_bytes(), charge); - same( - &download(&input, spec.columns * 4), - &data[..spec.columns * 4], - "native input immutable", - ); + same(&download(&input, spec.columns * 4), &data[..spec.columns * 4], "native input immutable"); if spec.rows == 640 { let prepared = c.prepare_routed_gate_up_q8(&input).unwrap(); - c.project_routed_gate_up_prepared( - &raw_weight, - &prepared, - &mut old, - raw_format(dual.format), - ) - .unwrap(); + c.project_routed_gate_up_prepared(&raw_weight, &prepared, &mut old, raw_format(dual.format)).unwrap(); dual.native_gate_up_prepared(&prepared, &mut new).unwrap(); - same( - &download(&new, 2560), - &download(&old, 2560), - "dual prepared", - ); - c.project_routed_gate_up_columns( - &raw_weight, - &[&prepared], - &mut old, - raw_format(dual.format), - ) - .unwrap(); + same(&download(&new, 2560), &download(&old, 2560), "dual prepared"); + c.project_routed_gate_up_columns(&raw_weight, &[&prepared], &mut old, raw_format(dual.format)).unwrap(); dual.native_gate_up_columns(&[&prepared], &mut new).unwrap(); - same( - &download(&new, 2560), - &download(&old, 2560), - "dual grouped GU", - ); + same(&download(&new, 2560), &download(&old, 2560), "dual grouped GU"); prepared.close().unwrap(); } else { - c.project_routed_down_columns(&raw_weight, &input, &mut old, 1, raw_format(dual.format)) - .unwrap(); + c.project_routed_down_columns(&raw_weight, &input, &mut old, 1, raw_format(dual.format)).unwrap(); dual.native_down_columns(&input, 1, &mut new).unwrap(); - same( - &download(&new, 10240), - &download(&old, 10240), - "dual grouped Down", - ); + same(&download(&new, 10240), &download(&old, 10240), "dual grouped Down"); } new.release().unwrap(); old.release().unwrap(); @@ -81,10 +48,7 @@ pub(super) fn direct( let expected_q8 = file(r, kind, t, "reference_q8.bin"); let expected_output = file(r, kind, t, "reference_streamk.f32"); let metadata = String::from_utf8(file(r, kind, t, "metadata.json")).unwrap(); - assert_eq!( - integer(&metadata, "nsm"), - w.experiment.as_ref().unwrap().sms as usize - ); + assert_eq!(integer(&metadata, "nsm"), w.experiment.as_ref().unwrap().sms as usize); let l = weights.format.layout(t).unwrap(); assert_eq!(data.len(), l.input); assert_eq!(expected_q8.len(), l.packed); @@ -93,29 +57,13 @@ pub(super) fn direct( finite(&expected_output); let charge = w.context.allocated_bytes(); // Numeric child calls SAME actual resident producers. No finite-owner constructor. - w.buffers[INPUT] - .as_mut() - .unwrap() - .copy_from_range(0, &data) - .unwrap(); + w.buffers[INPUT].as_mut().unwrap().copy_from_range(0, &data).unwrap(); w.quantize(INPUT, CHUNK, l).unwrap(); let out = if kind == 18 || kind == 22 { GATE } else { DOWN }; w.project(weights, CHUNK, out, t).unwrap(); - same( - &download(w.buffer(CHUNK).unwrap(), l.packed), - &expected_q8, - "resident original D4", - ); - same( - &download(w.buffer(out).unwrap(), l.output), - &expected_output, - "resident sameT original adaptive", - ); - same( - &download(w.buffer(INPUT).unwrap(), l.input), - &data, - "resident original source immutable", - ); + same(&download(w.buffer(CHUNK).unwrap(), l.packed), &expected_q8, "resident original D4"); + same(&download(w.buffer(out).unwrap(), l.output), &expected_output, "resident sameT original adaptive"); + same(&download(w.buffer(INPUT).unwrap(), l.input), &data, "resident original source immutable"); assert_eq!(w.context.allocated_bytes(), charge); (l.output / 4, l.packed) } @@ -123,16 +71,9 @@ pub(super) fn gather(r: &Receipt, w: &mut MmqWorkspace<'_>) -> usize { let input = floats(&file(r, 18, 64, "input.f32")); let original = file(r, 18, 64, "reference_q8.bin"); let mut source = w.prepare_gate_up_chunk(&input, 64).unwrap(); - same( - &download(source.workspace.buffer(CHUNK).unwrap(), original.len()), - &original, - "gather source original", - ); + same(&download(source.workspace.buffer(CHUNK).unwrap(), original.len()), &original, "gather source original"); for bad in [vec![], vec![0; 65], vec![64], vec![0, 0], vec![2, 1]] { - assert!(matches!( - source.gather_gate_up(&bad), - Err(Error::InvalidProjectionShape) - )); + assert!(matches!(source.gather_gate_up(&bad), Err(Error::InvalidProjectionShape))); same( &download(source.workspace.buffer(CHUNK).unwrap(), original.len()), &original, @@ -140,11 +81,7 @@ pub(super) fn gather(r: &Receipt, w: &mut MmqWorkspace<'_>) -> usize { ); } let mut checked = 0; - for ids in [ - (0..64).collect::>(), - vec![0, 7, 32, 63], - (0..16).map(|i| i * 4).collect(), - ] { + for ids in [(0..64).collect::>(), vec![0, 7, 32, 63], (0..16).map(|i| i * 4).collect()] { let group = source.gather_gate_up(&ids).unwrap(); let mut expected = vec![0; 20 * ids.len() * 144 + 9216]; for block in 0..20 { @@ -154,11 +91,7 @@ pub(super) fn gather(r: &Receipt, w: &mut MmqWorkspace<'_>) -> usize { expected[dst..dst + 144].copy_from_slice(&original[src..src + 144]); } } - same( - &download(group.workspace.buffer(GROUP).unwrap(), expected.len()), - &expected, - "entire gathered D4/tail", - ); + same(&download(group.workspace.buffer(GROUP).unwrap(), expected.len()), &expected, "entire gathered D4/tail"); same( &download(group.workspace.buffer(CHUNK).unwrap(), original.len()), &original, diff --git a/crates/cuda-driver/src/moe_down_pack_gpu.rs b/crates/cuda-driver/src/moe_down_pack_gpu.rs index 2a54cc70..8af161ee 100644 --- a/crates/cuda-driver/src/moe_down_pack_gpu.rs +++ b/crates/cuda-driver/src/moe_down_pack_gpu.rs @@ -16,11 +16,7 @@ fn words(slot: usize, zero: bool) -> Vec { (0..2560) .flat_map(|i| { let value = if zero { - if (slot + i).is_multiple_of(2) { - -0.0f32 - } else { - 0. - } + if (slot + i).is_multiple_of(2) { -0.0f32 } else { 0. } } else { (((slot * 17 + i * 3) % 97) as f32 - 48.) / 64. }; @@ -45,14 +41,9 @@ fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() { for slot in (0..10).rev() { let bytes = words(slot, zero); source.copy_from(&bytes).unwrap(); - ctx.pack_moe_down_f32(&source, &mut actual, slot as u32) - .unwrap(); + ctx.pack_moe_down_f32(&source, &mut actual, slot as u32).unwrap(); staged[slot * SOURCE..(slot + 1) * SOURCE].copy_from_slice(&bytes); - assert_eq!( - read(&actual), - staged, - "fixed slot{slot} must not touch other slots" - ); + assert_eq!(read(&actual), staged, "fixed slot{slot} must not touch other slots"); assert_eq!(read(&source), bytes); assert_eq!(ctx.allocated_bytes(), charge); } @@ -68,20 +59,14 @@ fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() { let mut destination = upload(&ctx, &sentinel); let baseline = ctx.allocated_bytes(); for slot in [10, u32::MAX] { - assert_eq!( - ctx.pack_moe_down_f32(&source, &mut destination, slot), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ctx.pack_moe_down_f32(&source, &mut destination, slot), Err(Error::InvalidQwenShape)); assert_eq!(read(&destination), sentinel); assert_eq!(ctx.allocated_bytes(), baseline); } for len in [SOURCE - 4, SOURCE + 4] { let malformed = upload(&ctx, &vec![0x27; len]); let charge = ctx.allocated_bytes(); - assert_eq!( - ctx.pack_moe_down_f32(&malformed, &mut destination, 0), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ctx.pack_moe_down_f32(&malformed, &mut destination, 0), Err(Error::InvalidQwenShape)); assert_eq!(read(&destination), sentinel); assert_eq!(ctx.allocated_bytes(), charge); malformed.release().unwrap(); @@ -90,10 +75,7 @@ fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() { let bytes = vec![0x39; len]; let mut malformed = upload(&ctx, &bytes); let charge = ctx.allocated_bytes(); - assert_eq!( - ctx.pack_moe_down_f32(&source, &mut malformed, 0), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ctx.pack_moe_down_f32(&source, &mut malformed, 0), Err(Error::InvalidQwenShape)); assert_eq!(read(&malformed), bytes); assert_eq!(ctx.allocated_bytes(), charge); malformed.release().unwrap(); @@ -101,18 +83,9 @@ fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() { let foreign = device.create_context(1024 * 1024).unwrap(); let foreign_source = upload(&foreign, &words(0, false)); let mut foreign_destination = upload(&foreign, &sentinel); - assert_eq!( - ctx.pack_moe_down_f32(&foreign_source, &mut destination, 0), - Err(Error::ContextMismatch) - ); - assert_eq!( - ctx.pack_moe_down_f32(&source, &mut foreign_destination, 0), - Err(Error::ContextMismatch) - ); - assert_eq!( - foreign.pack_moe_down_f32(&source, &mut destination, 0), - Err(Error::ContextMismatch) - ); + assert_eq!(ctx.pack_moe_down_f32(&foreign_source, &mut destination, 0), Err(Error::ContextMismatch)); + assert_eq!(ctx.pack_moe_down_f32(&source, &mut foreign_destination, 0), Err(Error::ContextMismatch)); + assert_eq!(foreign.pack_moe_down_f32(&source, &mut destination, 0), Err(Error::ContextMismatch)); assert_eq!(read(&destination), sentinel); assert_eq!(read(&foreign_destination), sentinel); assert_eq!(read(&source), words(0, false)); @@ -133,14 +106,8 @@ fn fixed_down_pack_matches_original_upload_and_refuses_before_copy() { let source = upload(&poisoned, &words(0, false)); let mut destination = upload(&poisoned, &sentinel); poisoned.poisoned.set(true); - assert_eq!( - poisoned.pack_moe_down_f32(&source, &mut destination, 0), - Err(Error::ContextPoisoned) - ); - assert_eq!( - poisoned.pack_moe_down_f32(&source, &mut destination, 10), - Err(Error::ContextPoisoned) - ); + assert_eq!(poisoned.pack_moe_down_f32(&source, &mut destination, 0), Err(Error::ContextPoisoned)); + assert_eq!(poisoned.pack_moe_down_f32(&source, &mut destination, 10), Err(Error::ContextPoisoned)); assert_eq!(poisoned.allocated_bytes(), SOURCE + DEST); assert_eq!(source.release(), Err(Error::ContextPoisoned)); assert_eq!(destination.release(), Err(Error::ContextPoisoned)); diff --git a/crates/cuda-driver/src/moe_group_down_columns.rs b/crates/cuda-driver/src/moe_group_down_columns.rs index 61d95429..bddf291a 100644 --- a/crates/cuda-driver/src/moe_group_down_columns.rs +++ b/crates/cuda-driver/src/moe_group_down_columns.rs @@ -16,9 +16,7 @@ impl Context<'_> { } let source_handle = source.handle.ok_or(Error::ContextPoisoned)?; let mut handles: Vec = Vec::new(); - handles - .try_reserve_exact(total) - .map_err(|_| Error::HostAllocation)?; + handles.try_reserve_exact(total).map_err(|_| Error::HostAllocation)?; for (index, (column, destination, slot)) in copies.iter().enumerate() { if *column as usize != index || *slot >= 10 || destination.bytes != 102400 { return Err(Error::InvalidProjectionShape); @@ -26,17 +24,11 @@ impl Context<'_> { self.grouped_buffers(&[destination])?; let target = destination.handle.ok_or(Error::ContextPoisoned)?; if source_handle.overlaps(source.bytes, target, 102400) - || handles - .iter() - .any(|(whole, _, _)| whole.overlaps(102400, target, 102400)) + || handles.iter().any(|(whole, _, _)| whole.overlaps(102400, target, 102400)) { return Err(Error::OutputAliasesInput); } - handles.push(( - target, - target.moe_down_slot(*slot)?, - source_handle.moe_group_down_column(total, index)?, - )); + handles.push((target, target.moe_down_slot(*slot)?, source_handle.moe_group_down_column(total, index)?)); } // Every real owner and mapping is admitted before the first copy. let guard = match self.enter() { @@ -70,10 +62,7 @@ impl Context<'_> { if !std::ptr::eq(self, buffer.context) { return Err(Error::ContextMismatch); } - buffer - .handle - .ok_or(Error::ContextPoisoned)? - .validate_projection_extent(buffer.bytes, 4)?; + buffer.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(buffer.bytes, 4)?; } Ok(()) } @@ -89,11 +78,7 @@ impl Context<'_> { if !(1..=64).contains(&total) || [gate.bytes, up.bytes, output.bytes] != [total * 2560; 3] { return Err(Error::InvalidProjectionShape); } - let handles = [ - gate.handle.unwrap(), - up.handle.unwrap(), - output.handle.unwrap(), - ]; + let handles = [gate.handle.unwrap(), up.handle.unwrap(), output.handle.unwrap()]; if handles[2].overlaps(output.bytes, handles[0], gate.bytes) || handles[2].overlaps(output.bytes, handles[1], up.bytes) { @@ -104,13 +89,9 @@ impl Context<'_> { let result = self.fixed_kernel(FixedOperation::GroupedSwiglu); combine(result, guard.finish())? }; - let mut arguments = - ffi::ProjectionArguments::new(handles[0], handles[1], handles[2], 640, 640); + let mut arguments = ffi::ProjectionArguments::new(handles[0], handles[1], handles[2], 640, 640); let guard = self.enter()?; - let result = - self.driver - .api - .launch_grouped_swiglu(kernel.function, 5, total as u32, &mut arguments); + let result = self.driver.api.launch_grouped_swiglu(kernel.function, 5, total as u32, &mut arguments); self.complete_launch(result, arguments, guard) } /// Fresh original Q8_1 for every contiguous 640-value hidden column; one @@ -123,13 +104,7 @@ impl Context<'_> { total: usize, format: RoutedFormat, ) -> Result<()> { - self.project_routed_down_columns_weight( - NativeWeights::Raw(weights), - hidden, - output, - total, - format, - ) + self.project_routed_down_columns_weight(NativeWeights::Raw(weights), hidden, output, total, format) } pub(super) fn project_routed_down_columns_weight( &self, @@ -146,30 +121,16 @@ impl Context<'_> { RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2, _ => return Err(Error::UnsupportedProjection), }; - let shape = projection_shape(ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - })?; + let shape = + projection_shape(ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 })?; weight_owner.validate( - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - }, + ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 }, shape.weight_bytes, )?; - if !(1..=64).contains(&total) - || hidden.bytes != total * 2560 - || output.bytes != total * 10240 - { + if !(1..=64).contains(&total) || hidden.bytes != total * 2560 || output.bytes != total * 10240 { return Err(Error::InvalidProjectionShape); } - let handles = [ - weights.handle.unwrap(), - hidden.handle.unwrap(), - output.handle.unwrap(), - ]; + let handles = [weights.handle.unwrap(), hidden.handle.unwrap(), output.handle.unwrap()]; projection_ranges(ProjectionKind::Routed(format), &shape, handles)?; // projection_ranges checks one-column overlap; require full grouped extents. if handles[2].overlaps(output.bytes, handles[0], weights.bytes) @@ -178,12 +139,7 @@ impl Context<'_> { return Err(Error::OutputAliasesInput); } let scratch_bytes = total * 720; - if self - .allocated - .get() - .checked_add(scratch_bytes + 4) - .is_none_or(|v| v > self.budget) - { + if self.allocated.get().checked_add(scratch_bytes + 4).is_none_or(|v| v > self.budget) { return Err(Error::BudgetExceeded); } let scratch = self.allocate(scratch_bytes)?; @@ -202,11 +158,7 @@ impl Context<'_> { let flag = status.handle.ok_or(Error::ContextPoisoned)?; q8.validate_projection_extent(scratch_bytes, 4)?; flag.validate_projection_extent(4, 4)?; - for (h, n) in [ - (handles[0], weights.bytes), - (handles[1], hidden.bytes), - (handles[2], output.bytes), - ] { + for (h, n) in [(handles[0], weights.bytes), (handles[1], hidden.bytes), (handles[2], output.bytes)] { if q8.overlaps(scratch_bytes, h, n) || flag.overlaps(4, h, n) { return Err(Error::OutputAliasesInput); } @@ -224,14 +176,10 @@ impl Context<'_> { }; // 640 is a multiple of32: flattening columns preserves every Q8 // block, lane schedule, scale/sum and per-column original order. - let mut args = - ffi::Q8QuantizeArguments::new(handles[1], q8, flag, (640 * total) as u32); + let mut args = ffi::Q8QuantizeArguments::new(handles[1], q8, flag, (640 * total) as u32); let guard = self.enter()?; - let launch = self.driver.api.launch_q8_quantize( - quantizer.function, - (640 * total).div_ceil(256) as u32, - &mut args, - ); + let launch = + self.driver.api.launch_q8_quantize(quantizer.function, (640 * total).div_ceil(256) as u32, &mut args); self.complete_launch(launch, args, guard)?; let mut bytes = [0; 4]; status.copy_to(&mut bytes)?; @@ -240,12 +188,7 @@ impl Context<'_> { } let mut args = ffi::ProjectionArguments::new(handles[0], q8, handles[2], 2560, 640); let guard = self.enter()?; - let launch = self.driver.api.launch_grouped_projection( - projector.function, - 640, - total as u32, - &mut args, - ); + let launch = self.driver.api.launch_grouped_projection(projector.function, 640, total as u32, &mut args); self.complete_launch(launch, args, guard) })(); self.release_quantized_temporaries(result, scratch, status) diff --git a/crates/cuda-driver/src/moe_group_projection.rs b/crates/cuda-driver/src/moe_group_projection.rs index cfe7532f..44ec6a1e 100644 --- a/crates/cuda-driver/src/moe_group_projection.rs +++ b/crates/cuda-driver/src/moe_group_projection.rs @@ -8,12 +8,7 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, format: RoutedFormat, ) -> Result<()> { - self.project_routed_gate_up_columns_weight( - NativeWeights::Raw(weights), - columns, - output, - format, - ) + self.project_routed_gate_up_columns_weight(NativeWeights::Raw(weights), columns, output, format) } pub(super) fn project_routed_gate_up_columns_weight( &self, @@ -38,17 +33,10 @@ impl Context<'_> { if !(1..=64).contains(&columns.len()) { return Err(Error::InvalidProjectionShape); } - let shape = projection_shape(ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - })?; + let shape = + projection_shape(ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })?; weight_owner.validate( - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - }, + ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 }, shape.weight_bytes, )?; if output.bytes != columns.len() * 2560 { @@ -59,18 +47,13 @@ impl Context<'_> { } let weight = weights.handle.ok_or(Error::ContextPoisoned)?; let out = output.handle.ok_or(Error::ContextPoisoned)?; - weight.validate_projection_extent( - shape.weight_bytes, - ProjectionKind::Routed(format).weight_alignment(), - )?; + weight.validate_projection_extent(shape.weight_bytes, ProjectionKind::Routed(format).weight_alignment())?; out.validate_projection_extent(output.bytes, 4)?; if out.overlaps(output.bytes, weight, weights.bytes) { return Err(Error::OutputAliasesInput); } let mut pointers = Vec::new(); - pointers - .try_reserve_exact(columns.len() * 8) - .map_err(|_| Error::BudgetExceeded)?; + pointers.try_reserve_exact(columns.len() * 8).map_err(|_| Error::BudgetExceeded)?; for column in columns { let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; for buffer in [column.activation, scratch] { @@ -83,19 +66,10 @@ impl Context<'_> { return Err(Error::OutputAliasesInput); } } - if column.activation.bytes != 10240 - || scratch.bytes != 2880 - || self.common_quantizer.get().is_none() - { + if column.activation.bytes != 10240 || scratch.bytes != 2880 || self.common_quantizer.get().is_none() { return Err(Error::InvalidProjectionShape); } - pointers.extend_from_slice( - &scratch - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() - .to_le_bytes(), - ); + pointers.extend_from_slice(&scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address().to_le_bytes()); } let mut table = self.allocate(pointers.len())?; let result = (|| { @@ -117,12 +91,8 @@ impl Context<'_> { }; let mut arguments = ffi::ProjectionArguments::new(weight, table_handle, out, 640, 2560); let guard = self.enter()?; - let launch = self.driver.api.launch_grouped_projection( - kernel.function, - 160, - columns.len() as u32, - &mut arguments, - ); + let launch = + self.driver.api.launch_grouped_projection(kernel.function, 160, columns.len() as u32, &mut arguments); self.complete_launch(launch, arguments, guard) })(); combine(result, table.release()) @@ -182,16 +152,9 @@ mod installed_tests { #[test] #[ignore = "root-only installed CUDA grouped projection gate"] fn installed_grouped_native_gu18_gu22_matches_actual_scalar_columns() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_MOE_GROUP").unwrap(), - "yes" - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_MOE_GROUP").unwrap(), "yes"); let driver = Driver::load().unwrap(); - let context = driver - .device(0) - .unwrap() - .create_context(8 * 1024 * 1024) - .unwrap(); + let context = driver.device(0).unwrap().create_context(8 * 1024 * 1024).unwrap(); let mut words = 0; for (format, block_bytes) in [(RoutedFormat::IQ3_XXS, 98), (RoutedFormat::IQ2_S, 82)] { let stride = 10 * block_bytes; @@ -221,29 +184,18 @@ mod installed_tests { upload(&context, &bytes) }) .collect(); - let prepared: Vec<_> = inputs - .iter() - .map(|input| context.prepare_routed_gate_up_q8(input).unwrap()) - .collect(); + let prepared: Vec<_> = + inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input).unwrap()).collect(); let refs: Vec<_> = prepared.iter().collect(); let mut grouped = upload(&context, &vec![0xa5; total * 2560]); let allocated = context.allocated_bytes(); - context - .project_routed_gate_up_columns(&weights, &refs, &mut grouped, format) - .unwrap(); + context.project_routed_gate_up_columns(&weights, &refs, &mut grouped, format).unwrap(); assert_eq!(context.allocated_bytes(), allocated); let actual = read(&grouped, total * 2560); let mut scalar = context.allocate(2560).unwrap(); let mut copied = context.allocate(2560).unwrap(); for column in 0..total { - context - .project_routed_gate_up_prepared( - &weights, - refs[column], - &mut scalar, - format, - ) - .unwrap(); + context.project_routed_gate_up_prepared(&weights, refs[column], &mut scalar, format).unwrap(); let expected = read(&scalar, 2560); for word in expected.as_chunks::<4>().0 { assert!(f32::from_le_bytes(*word).is_finite()); @@ -253,9 +205,7 @@ mod installed_tests { expected, "{format:?} T{total} col{column}" ); - context - .copy_routed_gate_up_column(&grouped, total, column, &mut copied) - .unwrap(); + context.copy_routed_gate_up_column(&grouped, total, column, &mut copied).unwrap(); assert_eq!(read(&copied, 2560), expected); words += 640; } diff --git a/crates/cuda-driver/src/moe_prefill_batch.rs b/crates/cuda-driver/src/moe_prefill_batch.rs index 46073b98..52cd85ef 100644 --- a/crates/cuda-driver/src/moe_prefill_batch.rs +++ b/crates/cuda-driver/src/moe_prefill_batch.rs @@ -16,9 +16,7 @@ //! finite scan per stage into one status word, ONE drain on the adapter's stream with context fences before the first //! launch and before any D2H, earliest-stage refusal, completion uncertainty poisons the context and leaks the owners. //! The route ids/weights reach the host only after a clean complete drain. -use super::gdn_native_batch::{ - GdnGemm, GdnNativeFormat, GdnStream, GemmShape, Kernel as DequantKernel, -}; +use super::gdn_native_batch::{GdnGemm, GdnNativeFormat, GdnStream, GemmShape, Kernel as DequantKernel}; use super::*; /// Most rows of one window (the closed adapters' micro-window bound). @@ -47,8 +45,8 @@ pub const MOE_BATCH_SCRATCH_BYTES: usize = FF * N * F16; const MOE_PTX_LEN: usize = 71011; // TODO-ROOT: sha256 of offline_moe_prefill.ptx (without the trailing NUL). const MOE_PTX_SHA256: [u8; 32] = [ - 7, 94, 244, 56, 205, 182, 33, 21, 5, 70, 219, 239, 248, 245, 230, 253, 196, 170, 235, 194, 231, - 250, 16, 153, 230, 204, 110, 255, 63, 91, 111, 52, + 7, 94, 244, 56, 205, 182, 33, 21, 5, 70, 219, 239, 248, 245, 230, 253, 196, 170, 235, 194, 231, 250, 16, 153, 230, + 204, 110, 255, 63, 91, 111, 52, ]; // ------------------------------------------------------------------ kernel table @@ -235,36 +233,31 @@ struct Drained { #[path = "moe_prefill_batch/tests.rs"] mod tests; -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_prefill_batch_gpu.rs"] mod gpu; #[path = "moe_prefill_batch/pinned_fn.rs"] mod pinned_fn; #[allow(unused_imports)] -use pinned_fn::pinned; -#[allow(unused_imports)] -pub(crate) use pinned_fn::prefill_asset; +use pinned_fn::decode_statuses; #[allow(unused_imports)] use pinned_fn::format_index; #[allow(unused_imports)] use pinned_fn::linear; #[allow(unused_imports)] -use pinned_fn::decode_statuses; -#[path = "moe_prefill_batch/impl_moeprefillbatch.rs"] -mod impl_moeprefillbatch; +use pinned_fn::pinned; +#[allow(unused_imports)] +pub(crate) use pinned_fn::prefill_asset; #[path = "moe_prefill_batch/impl_moebatchprefix.rs"] mod impl_moebatchprefix; +#[path = "moe_prefill_batch/impl_moeprefillbatch.rs"] +mod impl_moeprefillbatch; #[path = "moe_prefill_batch/words_fn.rs"] mod words_fn; #[allow(unused_imports)] -use words_fn::words; -#[allow(unused_imports)] use words_fn::check_slot_map; #[allow(unused_imports)] use words_fn::staging; +#[allow(unused_imports)] +use words_fn::words; diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs index bb51ea59..0e3cf7e2 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { pub fn tokens(&self) -> usize { self.tokens @@ -26,12 +24,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { result } pub(in super::super) fn moe_function(&self, kernel: MoeKernel) -> Result { - Ok(self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .moe[kernel.index()]) + Ok(self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?.moe[kernel.index()]) } /// Admit one caller buffer under `role`. `bytes` is the exact size unless `at_least`, in which case the whole /// allocation is bound. @@ -45,8 +38,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { if !std::ptr::eq(self.batch.context, buffer.context) { return Err(Error::ContextMismatch); } - if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) - { + if bytes == 0 || (at_least && buffer.bytes < bytes) || (!at_least && buffer.bytes != bytes) { return Err(Error::InvalidQwenShape); } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; @@ -86,9 +78,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { Ok(()) } pub(in super::super) fn status_word(&self, stage: MoeBatchStage) -> Result { - self.batch - .status_handle()? - .checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) + self.batch.status_handle()?.checked_subspan(STATUS_BYTES, stage.slot() * 4, 4) } /// Complete finite scan of the whole buffer bound to `role`, into the stage's own status word. Stages are /// scanned strictly in program order. @@ -102,11 +92,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { return Err(Error::InvalidQwenShape); } let status = self.status_word(stage)?; - let kernel = if stage.is_half() { - MoeKernel::FiniteF16 - } else { - MoeKernel::FiniteF32 - }; + let kernel = if stage.is_half() { MoeKernel::FiniteF16 } else { MoeKernel::FiniteF32 }; self.push_kernel( kernel, linear(elements)?, @@ -124,11 +110,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { } pub(in super::super) fn buffer_ref(&self, role: Role) -> Result<&'lease DeviceBuffer<'lease>> { let handle = self.handle(role)?; - self.held - .iter() - .copied() - .find(|buffer| buffer.handle == Some(handle)) - .ok_or(Error::InvalidQwenShape) + self.held.iter().copied().find(|buffer| buffer.handle == Some(handle)).ok_or(Error::InvalidQwenShape) } // ---------------------------------------------------------------- images @@ -148,12 +130,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let h = self.bind(Role::MixedH, mixed_h, t * N * F16, false)?; let bf = self.bind(Role::MixedBf, mixed_bf, t * N * F16, false)?; let lo = match mixed_bf_lo { - Some(buffer) => ffi::KernelArg::Pointer(self.bind( - Role::MixedBfLo, - buffer, - t * N * F16, - false, - )?), + Some(buffer) => ffi::KernelArg::Pointer(self.bind(Role::MixedBfLo, buffer, t * N * F16, false)?), None => ffi::KernelArg::NullPointer, }; self.push_kernel( @@ -194,14 +171,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let weights_h = self.bind(Role::Weights, weights, t * SELECTED * F32, false)?; let x = self.buffer_ref(Role::MixedBf)?; let lo = self.buffer_ref(Role::MixedBfLo).ok(); - let shape = |beta| GemmShape { - tokens: t, - rows: EXPERTS, - depth: N, - ldy: EXPERTS, - y_offset: 0, - beta, - }; + let shape = |beta| GemmShape { tokens: t, rows: EXPERTS, depth: N, ldy: EXPERTS, y_offset: 0, beta }; self.commands.push(Command::Gemm { gemm: self.gemm, bf16: true, diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs index 420c123c..3b89451c 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { - // ---------------------------------------------------------------- shared expert /// Dequantize the exact GGUF matrix to FP16 scratch (one thread per 32-value group) and enqueue /// `Y[t][rows] = X . W^T` through the adapter. @@ -29,12 +26,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let scratch_handle = self.bind(Role::Scratch, scratch, half_bytes, true)?; self.bind(output.0, output.1, output_bytes, false)?; let groups_per_row = depth / 32; - let function = self - .batch - .functions - .as_ref() - .ok_or(Error::ContextPoisoned)? - .dequant[format_index(format)]; + let function = self.batch.functions.as_ref().ok_or(Error::ContextPoisoned)?.dequant[format_index(format)]; self.push_function( function, linear(rows * groups_per_row)?, @@ -54,14 +46,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { x, w: scratch, y: output.1, - shape: GemmShape { - tokens: t, - rows, - depth, - ldy: rows, - y_offset: 0, - beta: 0.0, - }, + shape: GemmShape { tokens: t, rows, depth, ldy: rows, y_offset: 0, beta: 0.0 }, }); Ok(()) } @@ -103,16 +88,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let result = (|| { self.ready(Step::Up)?; let bytes = self.tokens * FF * F32; - self.project_native( - format, - (Role::UpW, weights), - scratch, - Role::MixedH, - (Role::SUp, sup), - FF, - N, - bytes, - )?; + self.project_native(format, (Role::UpW, weights), scratch, Role::MixedH, (Role::SUp, sup), FF, N, bytes)?; self.scan(MoeBatchStage::SUp, Role::SUp)?; self.step = self.step.next(); Ok(()) @@ -184,22 +160,8 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { self.bind(Role::Sg, sg, t * F32, false)?; let x = self.buffer_ref(Role::MixedBf)?; let lo = self.buffer_ref(Role::MixedBfLo).ok(); - let shape = |beta| GemmShape { - tokens: t, - rows: 1, - depth: N, - ldy: 1, - y_offset: 0, - beta, - }; - self.commands.push(Command::Gemm { - gemm: self.gemm, - bf16: true, - x, - w: scalar_w, - y: sg, - shape: shape(0.0), - }); + let shape = |beta| GemmShape { tokens: t, rows: 1, depth: N, ldy: 1, y_offset: 0, beta }; + self.commands.push(Command::Gemm { gemm: self.gemm, bf16: true, x, w: scalar_w, y: sg, shape: shape(0.0) }); if let Some(lo) = lo { self.commands.push(Command::Gemm { gemm: self.gemm, @@ -229,11 +191,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { slot: &[i32], bo: &'lease DeviceBuffer<'lease>, ) -> Result<()> { - let result = if self.combine_only { - Err(Error::InvalidQwenShape) - } else { - self.combine_body(dm, slot, bo) - }; + let result = if self.combine_only { Err(Error::InvalidQwenShape) } else { self.combine_body(dm, slot, bo) }; self.latch(result) } } diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs index a25da431..ae287ec8 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moebatchprefix/impl_moebatchprefix_3.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { /// The combine-only program's single step (`begin_combine`): the same `moe_combine` over the caller-lent /// products of a drained window. `route_weights` is the exact `[t][10]` f32 route-weight buffer, `shared` the @@ -48,9 +46,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { let private = self.batch.slots.as_mut().ok_or(Error::ContextPoisoned)?; let slot_h = private.handle.ok_or(Error::ContextPoisoned)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(slot.len() * F32) - .map_err(|_| Error::HostAllocation)?; + bytes.try_reserve_exact(slot.len() * F32).map_err(|_| Error::HostAllocation)?; bytes.extend(slot.iter().flat_map(|v| v.to_le_bytes())); private.copy_from_range(0, &bytes)?; self.bindings.bind(Role::Slot, slot_h, SLOT_BYTES)?; @@ -94,11 +90,7 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { } Ok(MoeBatchCompletion { refusal: drained.refusal, - route: if drained.refusal.is_none() { - drained.route - } else { - None - }, + route: if drained.refusal.is_none() { drained.route } else { None }, }) } @@ -147,15 +139,8 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { } if sync.is_err() || pop.is_err() { // Completion is uncertain: retain every actual argument/staging owner and every borrowed buffer. - std::mem::forget(( - self.commands, - self.held, - statuses, - fetched_ids, - fetched_weights, - )); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain MoE batch drain")); + std::mem::forget((self.commands, self.held, statuses, fetched_ids, fetched_weights)); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain MoE batch drain")); } combine(combine(operation, sync), pop)?; } @@ -174,18 +159,12 @@ impl<'lease, 'ctx> MoeBatchPrefix<'lease, 'ctx> { if ids.iter().any(|id| !(0..EXPERTS as i32).contains(id)) { self.batch.failed = true; self.batch.context.poisoned.set(true); - return Err(Error::InvalidDriverValue( - "MoE route id outside the expert range", - )); + return Err(Error::InvalidDriverValue("MoE route id outside the expert range")); } Some(MoeRouteBatch { ids, weights }) } else { None }; - Ok(Drained { - refusal, - deferred: self.refusal, - route, - }) + Ok(Drained { refusal, deferred: self.refusal, route }) } } diff --git a/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs b/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs index f2b4a9d2..9ff39c23 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/impl_moeprefillbatch.rs @@ -3,27 +3,16 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoePrefillBatch<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(STATUS_BYTES + SLOT_BYTES) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(STATUS_BYTES + SLOT_BYTES).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - status: None, - slots: None, - modules: [None, None], - functions: None, - failed: false, - }; + let mut owner = + Self { context, status: None, slots: None, modules: [None, None], functions: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); owner.slots = Some(context.allocate(SLOT_BYTES)?); @@ -82,8 +71,7 @@ impl<'ctx> MoePrefillBatch<'ctx> { } /// Actual private status and combine-row-map allocations only; every window buffer is caller owned. pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, |status| status.bytes) - + self.slots.as_ref().map_or(0, |slots| slots.bytes) + self.status.as_ref().map_or(0, |status| status.bytes) + self.slots.as_ref().map_or(0, |slots| slots.bytes) } /// Owned staging only. `gemm` is the closed adapter whose stream carries the whole program; the borrow lasts /// through the final drain. @@ -118,24 +106,17 @@ impl<'ctx> MoePrefillBatch<'ctx> { } let status = self.status_handle()?; let mut held = Vec::new(); - held.try_reserve_exact(32) - .map_err(|_| Error::HostAllocation)?; + held.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(48) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(48).map_err(|_| Error::HostAllocation)?; let (grid, block) = linear(SLOTS)?; let stream = gemm.stream(); commands.push(Command::Kernel { - function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.moe - [MoeKernel::Zero.index()], + function: self.functions.as_ref().ok_or(Error::ContextPoisoned)?.moe[MoeKernel::Zero.index()], stream, grid, block, - args: ffi::GdnPrefillArguments::new(&[ - ffi::KernelArg::Pointer(status), - ffi::KernelArg::U32(SLOTS as u32), - ])?, + args: ffi::GdnPrefillArguments::new(&[ffi::KernelArg::Pointer(status), ffi::KernelArg::U32(SLOTS as u32)])?, }); Ok(MoeBatchPrefix { batch: self, @@ -144,16 +125,8 @@ impl<'ctx> MoePrefillBatch<'ctx> { stream, held, commands, - step: if combine_only { - Step::Combine - } else { - Step::Images - }, - checks: if combine_only { - MoeBatchStage::Bo.slot() - } else { - 0 - }, + step: if combine_only { Step::Combine } else { Step::Images }, + checks: if combine_only { MoeBatchStage::Bo.slot() } else { 0 }, refusal: None, bindings: Bindings::new(), fetch: None, @@ -167,24 +140,10 @@ impl<'ctx> MoePrefillBatch<'ctx> { impl Command<'_> { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { match self { - Self::Kernel { - function, - stream, - grid, - block, - args, - } => context - .driver - .api - .launch_gdn_native(*function, *stream, *grid, *block, args), - Self::Gemm { - gemm, - bf16, - x, - w, - y, - shape, - } => { + Self::Kernel { function, stream, grid, block, args } => { + context.driver.api.launch_gdn_native(*function, *stream, *grid, *block, args) + } + Self::Gemm { gemm, bf16, x, w, y, shape } => { if *bf16 { gemm.bf16(x, w, y, *shape) } else { diff --git a/crates/cuda-driver/src/moe_prefill_batch/pinned_fn.rs b/crates/cuda-driver/src/moe_prefill_batch/pinned_fn.rs index 2eaf7f77..2dadd6ef 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/pinned_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/pinned_fn.rs @@ -3,19 +3,13 @@ #[allow(unused_imports)] use super::*; - pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result<&'static [u8]> { - if ptx.last() != Some(&0) - || !ptx[..ptx.len() - 1].is_ascii() - || ptx[..ptx.len() - 1].contains(&0) - { + if ptx.last() != Some(&0) || !ptx[..ptx.len() - 1].is_ascii() || ptx[..ptx.len() - 1].contains(&0) { return Err(Error::InvalidDriverValue("MoE prefill artifact encoding")); } let body = &ptx[..ptx.len() - 1]; if len == 0 || digest == [0; 32] { - return Err(Error::InvalidDriverValue( - "MoE prefill artifact pin is unset (TODO-ROOT)", - )); + return Err(Error::InvalidDriverValue("MoE prefill artifact pin is unset (TODO-ROOT)")); } if body.len() != len || crate::qwen_ffi::sha256(body) != digest { return Err(Error::InvalidDriverValue("MoE prefill artifact digest")); @@ -23,11 +17,7 @@ pub(super) fn pinned(ptx: &'static [u8], len: usize, digest: [u8; 32]) -> Result Ok(ptx) } pub(crate) fn prefill_asset() -> Result<&'static [u8]> { - pinned( - concat!(include_str!("../offline_moe_prefill.ptx"), "\0").as_bytes(), - MOE_PTX_LEN, - MOE_PTX_SHA256, - ) + pinned(concat!(include_str!("../offline_moe_prefill.ptx"), "\0").as_bytes(), MOE_PTX_LEN, MOE_PTX_SHA256) } impl MoeKernel { pub(crate) fn entry(self) -> &'static std::ffi::CStr { @@ -117,17 +107,11 @@ impl Step { } impl Bindings { pub(super) fn new() -> Self { - Self { - slots: [None; ROLES], - } + Self { slots: [None; ROLES] } } pub(super) fn bind(&mut self, role: Role, handle: ffi::BufferHandle, bytes: usize) -> Result<()> { if let Some((bound, size)) = self.slots[role as usize] { - return if bound == handle && size == bytes { - Ok(()) - } else { - Err(Error::InvalidQwenShape) - }; + return if bound == handle && size == bytes { Ok(()) } else { Err(Error::InvalidQwenShape) }; } for (other, size) in self.slots.iter().flatten() { if handle.overlaps(bytes, *other, *size) { diff --git a/crates/cuda-driver/src/moe_prefill_batch/tests.rs b/crates/cuda-driver/src/moe_prefill_batch/tests.rs index 0fb3e726..7dc157d9 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/tests.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/tests.rs @@ -30,10 +30,7 @@ fn the_combine_only_program_starts_at_the_last_status_slot() { let mut statuses = [0u32; SLOTS]; assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), None); statuses[MoeBatchStage::Bo.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&statuses), SLOTS).unwrap(), - Some(MoeBatchStage::Bo) - ); + assert_eq!(decode_statuses(&bytes(&statuses), SLOTS).unwrap(), Some(MoeBatchStage::Bo)); // A stray bit in a slot the combine-only program never scans would also be 1 and so reported as that // stage; the zero kernel clears every slot first, so this cannot happen without a driver fault. statuses[MoeBatchStage::Bo.slot()] = 0; @@ -51,16 +48,7 @@ fn program_has_one_fixed_order_and_combine_is_the_only_tail() { } assert_eq!( seen, - [ - Step::Images, - Step::Router, - Step::Gate, - Step::Up, - Step::Swiglu, - Step::Down, - Step::Scalar, - Step::Combine - ] + [Step::Images, Step::Router, Step::Gate, Step::Up, Step::Swiglu, Step::Down, Step::Scalar, Step::Combine] ); assert_eq!(Step::Done.next(), Step::Done); } @@ -71,38 +59,20 @@ fn earliest_status_in_program_order_is_the_refusal() { assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), None); words[MoeBatchStage::Shared.slot()] = 1; words[MoeBatchStage::Bo.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(MoeBatchStage::Shared) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(MoeBatchStage::Shared)); words[MoeBatchStage::Logits.slot()] = 1; - assert_eq!( - decode_statuses(&bytes(&words), SLOTS).unwrap(), - Some(MoeBatchStage::Logits) - ); + assert_eq!(decode_statuses(&bytes(&words), SLOTS).unwrap(), Some(MoeBatchStage::Logits)); } #[test] fn unused_slots_and_non_boolean_words_are_driver_witness_errors() { let mut words = [0u32; SLOTS]; words[MoeBatchStage::Sg.slot()] = 1; - assert!(matches!( - decode_statuses(&bytes(&words), MoeBatchStage::Sg.slot()), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(decode_statuses(&bytes(&words), MoeBatchStage::Sg.slot()), Err(Error::InvalidDriverValue(_)))); words[MoeBatchStage::Sg.slot()] = 2; - assert!(matches!( - decode_statuses(&bytes(&words), SLOTS), - Err(Error::InvalidDriverValue(_)) - )); - assert!(matches!( - decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(decode_statuses(&bytes(&words), SLOTS), Err(Error::InvalidDriverValue(_)))); + assert!(matches!(decode_statuses(&bytes(&words)[..STATUS_BYTES - 4], SLOTS), Err(Error::InvalidQwenShape))); + assert!(matches!(decode_statuses(&bytes(&[0; SLOTS]), SLOTS + 1), Err(Error::InvalidQwenShape))); } #[test] @@ -110,10 +80,7 @@ fn kernel_table_is_closed_and_dequantizers_are_indexed_by_format() { for (index, kernel) in MOE_KERNELS.into_iter().enumerate() { assert_eq!(kernel.index(), index); } - let mut entries: Vec<_> = MOE_KERNELS - .into_iter() - .map(|k| k.entry().to_owned()) - .collect(); + let mut entries: Vec<_> = MOE_KERNELS.into_iter().map(|k| k.entry().to_owned()).collect(); entries.sort(); entries.dedup(); assert_eq!(entries.len(), MOE_KERNELS.len()); @@ -133,10 +100,7 @@ fn kernel_table_is_closed_and_dequantizers_are_indexed_by_format() { assert_eq!(GdnNativeFormat::Q5K.matrix_bytes(FF, N).unwrap(), 1_126_400); assert_eq!(GdnNativeFormat::Q6K.matrix_bytes(FF, N).unwrap(), 1_344_000); assert_eq!(GdnNativeFormat::Iq4Xs.matrix_bytes(FF, N).unwrap(), 870_400); - assert_eq!( - GdnNativeFormat::Q8_0.matrix_bytes(N, FF).unwrap(), - 1_740_800 - ); + assert_eq!(GdnNativeFormat::Q8_0.matrix_bytes(N, FF).unwrap(), 1_740_800); assert_eq!(GdnNativeFormat::Iq4Nl.matrix_bytes(N, FF).unwrap(), 921_600); } @@ -154,10 +118,7 @@ fn combine_row_map_must_be_a_permutation_of_the_routed_rows() { let mut negative = identity.clone(); negative[0] = -1; for bad in [duplicate, high, negative, identity[..29].to_vec()] { - assert!(matches!( - check_slot_map(&bad, 3), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(check_slot_map(&bad, 3), Err(Error::InvalidQwenShape))); } assert_eq!(SLOT_BYTES, 2560); } @@ -180,14 +141,8 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { bindings.bind(Role::Logits, a, 0x1000).unwrap(); bindings.bind(Role::Ids, b, 0x1000).unwrap(); bindings.bind(Role::Logits, a, 0x1000).unwrap(); - assert!(matches!( - bindings.bind(Role::Logits, b, 0x1000), - Err(Error::InvalidQwenShape) - )); - assert!(matches!( - bindings.bind(Role::Weights, overlapping, 0x100), - Err(Error::OutputAliasesInput) - )); + assert!(matches!(bindings.bind(Role::Logits, b, 0x1000), Err(Error::InvalidQwenShape))); + assert!(matches!(bindings.bind(Role::Weights, overlapping, 0x100), Err(Error::OutputAliasesInput))); assert!(bindings.get(Role::Weights).is_err()); assert!(bindings.get(Role::Ids).unwrap() == (b, 0x1000)); } @@ -195,10 +150,7 @@ fn bindings_refuse_overlap_and_rebinding_to_a_different_range() { #[test] fn unpinned_artifact_fails_closed_and_pins_check_length_and_digest() { static GOOD: &[u8] = b".version 8.0\n\0"; - assert!(matches!( - pinned(GOOD, 0, [0; 32]), - Err(Error::InvalidDriverValue(_)) - )); + assert!(matches!(pinned(GOOD, 0, [0; 32]), Err(Error::InvalidDriverValue(_)))); let digest = crate::qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]); assert!(pinned(GOOD, GOOD.len() - 1, digest).is_ok()); assert!(pinned(GOOD, GOOD.len() - 2, digest).is_err()); diff --git a/crates/cuda-driver/src/moe_prefill_batch/words_fn.rs b/crates/cuda-driver/src/moe_prefill_batch/words_fn.rs index a4f0e38c..8454055c 100644 --- a/crates/cuda-driver/src/moe_prefill_batch/words_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch/words_fn.rs @@ -5,9 +5,7 @@ use super::*; pub(super) fn words(bytes: &[u8], decode: fn([u8; 4]) -> T) -> Result> { let mut values = Vec::new(); - values - .try_reserve_exact(bytes.len() / 4) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(bytes.len() / 4).map_err(|_| Error::HostAllocation)?; values.extend(bytes.as_chunks::<4>().0.iter().map(|word| decode(*word))); Ok(values.into_boxed_slice()) } @@ -28,9 +26,7 @@ pub(super) fn check_slot_map(slot: &[i32], tokens: usize) -> Result<()> { } pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu.rs index ac4223a3..7fdb97d4 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu.rs @@ -76,40 +76,16 @@ fn strata_prefill_moe_program_runs_in_order_refuses_earliest_and_cleans_up() { &context, &mut batch, 4, - Poison { - logits: true, - sg: true, - ..clean - }, + Poison { logits: true, sg: true, ..clean }, false, false, Some(MoeBatchStage::Logits), )?; - run_case( - &context, - &mut batch, - 4, - Poison { sg: true, ..clean }, - false, - false, - Some(MoeBatchStage::Sg), - )?; - run_case( - &context, - &mut batch, - 4, - Poison { dm: true, ..clean }, - true, - false, - Some(MoeBatchStage::Bo), - )?; + run_case(&context, &mut batch, 4, Poison { sg: true, ..clean }, false, false, Some(MoeBatchStage::Sg))?; + run_case(&context, &mut batch, 4, Poison { dm: true, ..clean }, true, false, Some(MoeBatchStage::Bo))?; run_case(&context, &mut batch, 3, clean, true, false, None)?; // Admission refusals leave nothing behind. - let idle = HostGemm { - poison: clean, - captured: RefCell::new(Captured::default()), - calls: Cell::new(0), - }; + let idle = HostGemm { poison: clean, captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; if batch.begin(0, &idle).is_ok() || batch.begin(MOE_BATCH_MAX_TOKENS + 1, &idle).is_ok() { return mismatch("token bounds not enforced"); } @@ -123,33 +99,33 @@ fn strata_prefill_moe_program_runs_in_order_refuses_earliest_and_cleans_up() { #[path = "moe_prefill_batch_gpu/bytes_of_fn.rs"] mod bytes_of_fn; #[allow(unused_imports)] +use bytes_of_fn::bf_bits; +#[allow(unused_imports)] +use bytes_of_fn::bf_value; +#[allow(unused_imports)] use bytes_of_fn::bytes_of; #[allow(unused_imports)] -use bytes_of_fn::words_of; -#[allow(unused_imports)] -use bytes_of_fn::halves_of; +use bytes_of_fn::close; #[allow(unused_imports)] use bytes_of_fn::f16_bits; #[allow(unused_imports)] use bytes_of_fn::f16_value; #[allow(unused_imports)] -use bytes_of_fn::bf_bits; +use bytes_of_fn::halves_of; #[allow(unused_imports)] -use bytes_of_fn::bf_value; -#[allow(unused_imports)] -use bytes_of_fn::sigm; +use bytes_of_fn::mismatch; #[allow(unused_imports)] use bytes_of_fn::pattern; #[allow(unused_imports)] -use bytes_of_fn::close; -#[allow(unused_imports)] use bytes_of_fn::q8_0; #[allow(unused_imports)] -use bytes_of_fn::upload; -#[allow(unused_imports)] use bytes_of_fn::read; #[allow(unused_imports)] -use bytes_of_fn::mismatch; +use bytes_of_fn::sigm; +#[allow(unused_imports)] +use bytes_of_fn::upload; +#[allow(unused_imports)] +use bytes_of_fn::words_of; #[path = "moe_prefill_batch_gpu/impl_fixture.rs"] mod impl_fixture; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs index 65a8f5ad..1ce96aca 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/bytes_of_fn.rs @@ -3,26 +3,15 @@ #[allow(unused_imports)] use super::*; - // ---------------------------------------------------------------- host numerics helpers pub(super) fn bytes_of(values: &[f32]) -> Vec { values.iter().flat_map(|v| v.to_le_bytes()).collect() } pub(super) fn words_of(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| f32::from_le_bytes(*w)) - .collect() + bytes.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w)).collect() } pub(super) fn halves_of(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<2>() - .0 - .iter() - .map(|w| u16::from_le_bytes(*w)) - .collect() + bytes.as_chunks::<2>().0.iter().map(|w| u16::from_le_bytes(*w)).collect() } pub(super) fn f16_bits(f: f32) -> u16 { let x = f.to_bits(); @@ -82,9 +71,7 @@ pub(super) fn sigm(x: f32) -> f32 { 1.0 / (1.0 + (-x).exp()) } pub(super) fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec { - (0..count) - .map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset) - .collect() + (0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect() } pub(super) fn close(a: f32, b: f32, tolerance: f32) -> bool { (a - b).abs() <= tolerance * (1.0 + b.abs()) @@ -124,23 +111,12 @@ impl HostGemm { let mut yb = vec![0u8; y.len()]; y.copy_to(&mut yb)?; let value = |bits: u16| { - if bf16 { - bf_value(bits) - } else { - f16_value(bits) - } + if bf16 { bf_value(bits) } else { f16_value(bits) } }; let xh = halves_of(&xb); let wh = halves_of(&wb); let mut out = words_of(&yb); - let GemmShape { - tokens, - rows, - depth, - ldy, - y_offset, - beta, - } = shape; + let GemmShape { tokens, rows, depth, ldy, y_offset, beta } = shape; if xh.len() < tokens * depth || wh.len() < rows * depth || out.len() < tokens * ldy { return Err(Error::InvalidQwenShape); } @@ -148,8 +124,7 @@ impl HostGemm { for n in 0..rows { let mut acc = 0f32; for k in 0..4 { - acc += value(xh[t * depth + (7 * n + k) % depth]) - * value(wh[n * depth + (3 * k + n) % depth]); + acc += value(xh[t * depth + (7 * n + k) % depth]) * value(wh[n * depth + (3 * k + n) % depth]); } // A tiny per-column ramp keeps every router logit distinct (no ties in the top-10 reference). let at = t * ldy + y_offset + n; @@ -162,10 +137,7 @@ impl HostGemm { if self.poison.sg && rows == 1 { out[tokens - 1] = f32::from_bits(0x7fc0_0001); } - y.context - .driver - .api - .copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; + y.context.driver.api.copy_from(y.handle.ok_or(Error::ContextPoisoned)?, &bytes_of(&out))?; let mut captured = self.captured.borrow_mut(); if !bf16 { captured.scratch.push((rows, wh[..rows * depth].to_vec())); @@ -180,22 +152,10 @@ impl GdnGemm for HostGemm { // The host stand-in copies synchronously on the default stream. GdnStream::default_stream() } - fn f16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn f16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.run(false, x, w, y, shape) } - fn bf16( - &self, - x: &DeviceBuffer<'_>, - w: &DeviceBuffer<'_>, - y: &DeviceBuffer<'_>, - shape: GemmShape, - ) -> Result<()> { + fn bf16(&self, x: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>, y: &DeviceBuffer<'_>, shape: GemmShape) -> Result<()> { self.run(true, x, w, y, shape) } } diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs index 48023e8e..c5bac6ba 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/check_clean_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn check_clean( f: &Fixture<'_>, gemm: &HostGemm, @@ -20,34 +19,17 @@ pub(super) fn check_clean( return mismatch("unexpected GEMM call sequence"); } // Dequantization is exact against the host transcription of group32. - for ((rows, half), (r, c, salt)) in - captured - .scratch - .iter() - .zip([(FF, N, 1usize), (FF, N, 2), (N, FF, 3)]) - { + for ((rows, half), (r, c, salt)) in captured.scratch.iter().zip([(FF, N, 1usize), (FF, N, 2), (N, FF, 3)]) { if *rows != r || half != &q8_0(r, c, salt).1 { - return mismatch( - "dequantized FP16 shared weights differ from the original group32", - ); + return mismatch("dequantized FP16 shared weights differ from the original group32"); } } // The images of `mixed`. - let (h_img, bf_img) = ( - halves_of(&read(&f.mixed_h)?), - halves_of(&read(&f.mixed_bf)?), - ); - let lo_img = if with_lo { - halves_of(&read(&f.mixed_bf_lo)?) - } else { - Vec::new() - }; + let (h_img, bf_img) = (halves_of(&read(&f.mixed_h)?), halves_of(&read(&f.mixed_bf)?)); + let lo_img = if with_lo { halves_of(&read(&f.mixed_bf_lo)?) } else { Vec::new() }; for (i, &s) in f.host_mixed.iter().enumerate() { let hi = bf_bits(s); - if h_img[i] != f16_bits(s) - || bf_img[i] != hi - || (with_lo && lo_img[i] != bf_bits(s - bf_value(hi))) - { + if h_img[i] != f16_bits(s) || bf_img[i] != hi || (with_lo && lo_img[i] != bf_bits(s - bf_value(hi))) { return mismatch("mixed images differ from bf()/bf_lo()/hf()"); } } @@ -68,24 +50,12 @@ pub(super) fn check_clean( exps.iter().map(|v| v / total).collect() }; let mut order: Vec = (0..EXPERTS).collect(); - order.sort_by(|&a, &b| { - probabilities[b] - .total_cmp(&probabilities[a]) - .then(a.cmp(&b)) - }); + order.sort_by(|&a, &b| probabilities[b].total_cmp(&probabilities[a]).then(a.cmp(&b))); let picked = &order[..SELECTED]; - let sum: f32 = picked - .iter() - .map(|&e| probabilities[e]) - .sum::() - .max(6.103515625e-5); + let sum: f32 = picked.iter().map(|&e| probabilities[e]).sum::().max(6.103515625e-5); for (rank, &expert) in picked.iter().enumerate() { if route.ids[t * SELECTED + rank] != expert as i32 - || !close( - route.weights[t * SELECTED + rank], - probabilities[expert] / sum, - 2e-4, - ) + || !close(route.weights[t * SELECTED + rank], probabilities[expert] / sum, 2e-4) { return mismatch("route differs from the host softmax / top-10"); } @@ -93,12 +63,7 @@ pub(super) fn check_clean( } // Shared expert H = hf_sat(silu(gate) * up) as FP16. let by_rows = |rows: usize, nth: usize| -> Option<&Vec> { - captured - .y - .iter() - .filter(|(r, _)| *r == rows) - .nth(nth) - .map(|(_, y)| y) + captured.y.iter().filter(|(r, _)| *r == rows).nth(nth).map(|(_, y)| y) }; let gate = by_rows(FF, 0).ok_or(Error::InvalidDriverValue("gate call missing"))?; let up = by_rows(FF, 1).ok_or(Error::InvalidDriverValue("up call missing"))?; @@ -111,27 +76,19 @@ pub(super) fn check_clean( } } // The down GEMM consumed exactly the device H. - let down_x = captured - .x - .get(3 + usize::from(with_lo)) - .ok_or(Error::InvalidDriverValue("down call missing"))?; + let down_x = captured.x.get(3 + usize::from(with_lo)).ok_or(Error::InvalidDriverValue("down call missing"))?; if down_x.0 != FF || halves_of(&down_x.1) != h { return mismatch("down GEMM did not read the H image"); } if with_combine { let shared = by_rows(N, 0).ok_or(Error::InvalidDriverValue("down result missing"))?; - let sg = captured - .y - .last() - .map(|(_, y)| y) - .ok_or(Error::InvalidDriverValue("scalar call missing"))?; + let sg = captured.y.last().map(|(_, y)| y).ok_or(Error::InvalidDriverValue("scalar call missing"))?; let bo = words_of(&read(&f.bo)?); for t in 0..tokens { for d in 0..N { let mut s = 0f32; for k in 0..SELECTED { - s = route.weights[t * SELECTED + k] - .mul_add(f.host_dm[slot[t * SELECTED + k] as usize * N + d], s); + s = route.weights[t * SELECTED + k].mul_add(f.host_dm[slot[t * SELECTED + k] as usize * N + d], s); } let want = s + shared[t * N + d] * sigm(sg[t]); if !close(bo[t * N + d], want, 2e-4) { diff --git a/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs b/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs index 32f79212..015e9908 100644 --- a/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs +++ b/crates/cuda-driver/src/moe_prefill_batch_gpu/impl_fixture.rs @@ -12,10 +12,7 @@ impl<'a> Fixture<'a> { host_dm[0] = f32::from_bits(0x7fc0_0001); } let bf16_matrix = |count: usize, salt: usize| -> Vec { - pattern(count, salt, 11, 1.0 / 64.0, 0.08) - .into_iter() - .flat_map(|v| bf_bits(v).to_le_bytes()) - .collect() + pattern(count, salt, 11, 1.0 / 64.0, 0.08).into_iter().flat_map(|v| bf_bits(v).to_le_bytes()).collect() }; Ok(Self { mixed: upload(context, &bytes_of(&host_mixed))?, @@ -83,11 +80,7 @@ pub(super) fn run_case( expect: Option, ) -> Result<()> { let fixture = Fixture::new(context, tokens, poison)?; - let gemm = HostGemm { - poison, - captured: RefCell::new(Captured::default()), - calls: Cell::new(0), - }; + let gemm = HostGemm { poison, captured: RefCell::new(Captured::default()), calls: Cell::new(0) }; // A reversed permutation: the combine must follow the row map, not the identity. let slot: Vec = (0..(tokens * SELECTED) as i32).rev().collect(); let result = (|| -> Result<()> { @@ -95,31 +88,11 @@ pub(super) fn run_case( let lo = with_lo.then_some(&fixture.mixed_bf_lo); let program = (|| -> Result<()> { prefix.pack_mixed(&fixture.mixed, &fixture.mixed_h, &fixture.mixed_bf, lo)?; - prefix.route( - &fixture.router_w, - &fixture.logits, - &fixture.ids, - &fixture.weights, - )?; - prefix.shared_gate( - GdnNativeFormat::Q8_0, - &fixture.gate_w, - &fixture.scratch, - &fixture.sgate, - )?; - prefix.shared_up( - GdnNativeFormat::Q8_0, - &fixture.up_w, - &fixture.scratch, - &fixture.sup, - )?; + prefix.route(&fixture.router_w, &fixture.logits, &fixture.ids, &fixture.weights)?; + prefix.shared_gate(GdnNativeFormat::Q8_0, &fixture.gate_w, &fixture.scratch, &fixture.sgate)?; + prefix.shared_up(GdnNativeFormat::Q8_0, &fixture.up_w, &fixture.scratch, &fixture.sup)?; prefix.swiglu(&fixture.sh_h)?; - prefix.shared_down( - GdnNativeFormat::Q8_0, - &fixture.down_w, - &fixture.scratch, - &fixture.shared, - )?; + prefix.shared_down(GdnNativeFormat::Q8_0, &fixture.down_w, &fixture.scratch, &fixture.shared)?; prefix.shared_scalar(&fixture.scalar_w, &fixture.sg)?; if with_combine { prefix.combine(&fixture.dm, &slot, &fixture.bo)?; @@ -140,15 +113,7 @@ pub(super) fn run_case( }; } let route = route.map_err(|_| Error::InvalidDriverValue("clean window lost its route"))?; - check_clean( - &fixture, - &gemm, - tokens, - &route, - with_combine, - with_lo, - &slot, - ) + check_clean(&fixture, &gemm, tokens, &route, with_combine, with_lo, &slot) })(); combine(result, fixture.release()) } diff --git a/crates/cuda-driver/src/moe_prompt_packet_copy.rs b/crates/cuda-driver/src/moe_prompt_packet_copy.rs index 02454e5d..4703040a 100644 --- a/crates/cuda-driver/src/moe_prompt_packet_copy.rs +++ b/crates/cuda-driver/src/moe_prompt_packet_copy.rs @@ -18,10 +18,7 @@ impl Context<'_> { if !(1..=64).contains(&sources.len()) { return Err(Error::InvalidQwenShape); } - let bytes = sources - .len() - .checked_mul(PACKET_BYTES) - .ok_or(Error::InvalidQwenShape)?; + let bytes = sources.len().checked_mul(PACKET_BYTES).ok_or(Error::InvalidQwenShape)?; if !std::ptr::eq(self, destination.context) { return Err(Error::ContextMismatch); } @@ -51,10 +48,7 @@ impl Context<'_> { } let packet = target.checked_subspan(bytes, row * PACKET_BYTES, PACKET_BYTES)?; for slot in 0..10 { - copies[row * 10 + slot] = Some(( - packet.moe_down_slot(slot as u32)?, - from.moe_down_slot(slot as u32)?, - )); + copies[row * 10 + slot] = Some((packet.moe_down_slot(slot as u32)?, from.moe_down_slot(slot as u32)?)); } } let guard = match self.enter() { @@ -98,9 +92,7 @@ impl Context<'_> { if !(1..=64).contains(&total) || row >= total { return Err(Error::InvalidQwenShape); } - let bytes = total - .checked_mul(PACKET_BYTES) - .ok_or(Error::InvalidQwenShape)?; + let bytes = total.checked_mul(PACKET_BYTES).ok_or(Error::InvalidQwenShape)?; if source.bytes != PACKET_BYTES || destination.bytes != bytes { return Err(Error::InvalidQwenShape); } @@ -111,18 +103,13 @@ impl Context<'_> { if source_handle.overlaps(PACKET_BYTES, destination_handle, bytes) { return Err(Error::OutputAliasesInput); } - let offset = row - .checked_mul(PACKET_BYTES) - .ok_or(Error::InvalidQwenShape)?; + let offset = row.checked_mul(PACKET_BYTES).ok_or(Error::InvalidQwenShape)?; let packet = destination_handle.checked_subspan(bytes, offset, PACKET_BYTES)?; // The ten private interior handles are fully admitted before any command. // No public subview/DeviceBuffer is fabricated and no host allocation occurs. let mut copies = [None; 10]; for (slot, pair) in copies.iter_mut().enumerate() { - *pair = Some(( - packet.moe_down_slot(slot as u32)?, - source_handle.moe_down_slot(slot as u32)?, - )); + *pair = Some((packet.moe_down_slot(slot as u32)?, source_handle.moe_down_slot(slot as u32)?)); } let guard = match self.enter() { Ok(guard) => guard, diff --git a/crates/cuda-driver/src/mtp_dense_kv.rs b/crates/cuda-driver/src/mtp_dense_kv.rs index 21907b84..1c915d85 100644 --- a/crates/cuda-driver/src/mtp_dense_kv.rs +++ b/crates/cuda-driver/src/mtp_dense_kv.rs @@ -23,12 +23,7 @@ fn finite(bytes: &[u8], expected: usize) -> Result<()> { if bytes.len() != expected { return Err(Error::InvalidQwenShape); } - if bytes - .as_chunks::<2>() - .0 - .iter() - .any(|w| u16::from_le_bytes(*w) & 0x7c00 == 0x7c00) - { + if bytes.as_chunks::<2>().0.iter().any(|w| u16::from_le_bytes(*w) & 0x7c00 == 0x7c00) { return Err(Error::InvalidQwenShape); } Ok(()) @@ -39,11 +34,7 @@ impl<'ctx> Context<'ctx> { if self.is_poisoned() { return Err(Error::ContextPoisoned); } - if self - .allocated_bytes() - .checked_add(2 * HALF_RING_BYTES) - .is_none_or(|n| n > self.budget_bytes()) - { + if self.allocated_bytes().checked_add(2 * HALF_RING_BYTES).is_none_or(|n| n > self.budget_bytes()) { return Err(Error::BudgetExceeded); } let keys = self.allocate(HALF_RING_BYTES)?; @@ -54,13 +45,7 @@ impl<'ctx> Context<'ctx> { return Err(e); } }; - Ok(MtpDenseKvRing { - context: self, - keys: Some(keys), - values: Some(values), - next_position: None, - failed: false, - }) + Ok(MtpDenseKvRing { context: self, keys: Some(keys), values: Some(values), next_position: None, failed: false }) } } impl MtpDenseKvRing<'_> { @@ -74,11 +59,7 @@ impl MtpDenseKvRing<'_> { 2 * HALF_RING_BYTES } fn live(&self) -> Result<()> { - if self.failed || self.context.is_poisoned() { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } + if self.failed || self.context.is_poisoned() { Err(Error::ContextPoisoned) } else { Ok(()) } } fn transport(&mut self, result: Result<()>) -> Result<()> { if result.is_err() { @@ -136,12 +117,7 @@ impl MtpDenseKvRing<'_> { Ok(()) } /// Opaque ownership selects the active span; no DeviceBuffer is fabricated. - pub fn attend( - &mut self, - query: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { + pub fn attend(&mut self, query: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, position: u32) -> Result<()> { self.live()?; let (_, start) = shape(position)?; if self.next_position != Some(position + 1) { @@ -173,9 +149,7 @@ mod tests { use super::*; #[test] fn duplicated_window_chronological_span_boundaries() { - for p in [ - 0, 1, 63, 64, 32767, 32768, 32769, 65535, 170000, 190000, 262143, - ] { + for p in [0, 1, 63, 64, 32767, 32768, 32769, 65535, 170000, 190000, 262143] { let (width, start) = shape(p).unwrap(); assert!(start + width <= 2 * WINDOW); let oldest = p as usize + 1 - width; @@ -200,23 +174,19 @@ mod original_int8; pub use original_int8::MTP_ORIGINAL_WINDOW; pub(crate) use original_int8::session_assets_sealed; pub use original_int8::{ - CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, - MtpOriginalMixed, MtpOriginalQuery, OriginalMtpSkippedPrefix, + CompletedMtpAttention, CompletedMtpKvReplay, MtpInt8OwnerId, MtpInt8Snapshot, MtpOriginalInt8, MtpOriginalMixed, + MtpOriginalQuery, OriginalMtpSkippedPrefix, }; pub use original_int8::{ - CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, - OriginalMtpPrefill, OriginalMtpPrefillWeights, + CompletedDraftKv, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpEmbedding, OriginalMtpPrefill, + OriginalMtpPrefillWeights, }; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use original_int8::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, - OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights, + OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, + OriginalMtpStepOutput, }; diff --git a/crates/cuda-driver/src/mtp_dense_kv_ring_gpu.rs b/crates/cuda-driver/src/mtp_dense_kv_ring_gpu.rs index 9b77606e..0e593ab5 100644 --- a/crates/cuda-driver/src/mtp_dense_kv_ring_gpu.rs +++ b/crates/cuda-driver/src/mtp_dense_kv_ring_gpu.rs @@ -4,13 +4,8 @@ use crate::Driver; fn cell(position: usize, value: bool) -> Vec { (0..512) .flat_map(|i| { - let sign = if (position + i + usize::from(value)).is_multiple_of(3) { - 0x8000 - } else { - 0 - }; - let word: u16 = - sign | 0x3000 | ((position * 17 + i * 11 + usize::from(value) * 7) % 1024) as u16; + let sign = if (position + i + usize::from(value)).is_multiple_of(3) { 0x8000 } else { 0 }; + let word: u16 = sign | 0x3000 | ((position * 17 + i * 11 + usize::from(value) * 7) % 1024) as u16; word.to_le_bytes() }) .collect() @@ -18,16 +13,9 @@ fn cell(position: usize, value: bool) -> Vec { fn window(position: u32, value: bool) -> Vec { let width = (position as usize + 1).min(WINDOW); let first = position as usize + 1 - width; - (first..first + width) - .flat_map(|p| cell(p, value)) - .collect() + (first..first + width).flat_map(|p| cell(p, value)).collect() } -fn exact( - context: &Context<'_>, - ring: &mut MtpDenseKvRing<'_>, - query: &DeviceBuffer<'_>, - position: u32, -) { +fn exact(context: &Context<'_>, ring: &mut MtpDenseKvRing<'_>, query: &DeviceBuffer<'_>, position: u32) { let kb = window(position, false); let vb = window(position, true); let mut k = context.allocate(kb.len()).unwrap(); @@ -36,21 +24,14 @@ fn exact( v.copy_from(&vb).unwrap(); let mut old = context.allocate(6144 * 4).unwrap(); let mut new = context.allocate(6144 * 4).unwrap(); - context - .mtp_dense_attend_f16(query, &k, &v, &mut old, position) - .unwrap(); + context.mtp_dense_attend_f16(query, &k, &v, &mut old, position).unwrap(); ring.attend(query, &mut new, position).unwrap(); let mut a = vec![0; 6144 * 4]; let mut b = vec![0; 6144 * 4]; old.copy_to(&mut a).unwrap(); new.copy_to(&mut b).unwrap(); assert_eq!(a, b, "chronological ring differs at position {position}"); - assert!( - a.as_chunks::<4>() - .0 - .iter() - .all(|w| f32::from_le_bytes(*w).is_finite()) - ); + assert!(a.as_chunks::<4>().0.iter().all(|w| f32::from_le_bytes(*w).is_finite())); for buffer in [k, v, old, new] { buffer.release().unwrap(); } @@ -58,30 +39,21 @@ fn exact( #[test] #[ignore = "Root-only explicitly scheduled new MTP KV transport parity; no model load"] fn duplicated_ring_same_attention_reload_append_wrap() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_MTP_KV_RING_PROOF").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_MTP_KV_RING_PROOF").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let refused = device.create_context(128 * 1024 * 1024 - 1).unwrap(); - assert!(matches!( - refused.mtp_dense_kv_ring(), - Err(Error::BudgetExceeded) - )); + assert!(matches!(refused.mtp_dense_kv_ring(), Err(Error::BudgetExceeded))); assert_eq!(refused.allocated_bytes(), 0); refused.close().unwrap(); let context = device.create_context(256 * 1024 * 1024).unwrap(); let mut ring = context.mtp_dense_kv_ring().unwrap(); assert_eq!(ring.allocated_bytes(), 128 * 1024 * 1024); let mut query = context.allocate(6144 * 4).unwrap(); - let q: Vec = (0..6144) - .flat_map(|i| (((i % 23) as f32 - 11.0) / 32.0).to_le_bytes()) - .collect(); + let q: Vec = (0..6144).flat_map(|i| (((i % 23) as f32 - 11.0) / 32.0).to_le_bytes()).collect(); query.copy_from(&q).unwrap(); for start in [0, 62, 63, 32766, 32767, 65535, 170000, 190000, 262142] { - ring.reload(start, &window(start, false), &window(start, true)) - .unwrap(); + ring.reload(start, &window(start, false), &window(start, true)).unwrap(); exact(&context, &mut ring, &query, start); if start == 190000 { // A valid immediate successor and exact row extents reach the @@ -96,31 +68,16 @@ fn duplicated_ring_same_attention_reload_append_wrap() { assert_eq!(before, context.allocated_bytes()); exact(&context, &mut ring, &query, start); } - ring.append( - start + 1, - &cell(start as usize + 1, false), - &cell(start as usize + 1, true), - ) - .unwrap(); + ring.append(start + 1, &cell(start as usize + 1, false), &cell(start as usize + 1, true)).unwrap(); exact(&context, &mut ring, &query, start + 1); // Same numerical span may be read repeatedly without another publication. exact(&context, &mut ring, &query, start + 1); - assert!( - ring.append( - start + 1, - &cell(start as usize + 1, false), - &cell(start as usize + 1, true) - ) - .is_err() - ); + assert!(ring.append(start + 1, &cell(start as usize + 1, false), &cell(start as usize + 1, true)).is_err()); } let before = context.allocated_bytes(); assert!(ring.reload(crate::MAX_CONTEXT_CELLS as u32, &[], &[]).is_err()); // Mature-window reload must reject short extents independently. - assert!( - ring.reload(262143, &cell(262143, false), &cell(262143, true)) - .is_err() - ); + assert!(ring.reload(262143, &cell(262143, false), &cell(262143, true)).is_err()); assert_eq!(before, context.allocated_bytes()); query.release().unwrap(); ring.close().unwrap(); diff --git a/crates/cuda-driver/src/mtp_input_workspace.rs b/crates/cuda-driver/src/mtp_input_workspace.rs index 685a8fa6..ffe87d26 100644 --- a/crates/cuda-driver/src/mtp_input_workspace.rs +++ b/crates/cuda-driver/src/mtp_input_workspace.rs @@ -6,11 +6,7 @@ use crate::{DenseFormat, ProjectionKind, ProjectionSpec, projection_ranges, proj const SIZES: [usize; 9] = [10240, 40960, 10240, 10240, 40960, 40960, 40960, 2880, 52]; const TOTAL: usize = 197_492; const RESERVE: usize = 128 * 1024 * 1024; -const OPERATIONS: [Operation; 3] = [ - Operation::MtpEmbeddingNorm, - Operation::MtpHiddenNorm, - Operation::MtpBroadcast, -]; +const OPERATIONS: [Operation; 3] = [Operation::MtpEmbeddingNorm, Operation::MtpHiddenNorm, Operation::MtpBroadcast]; const STAGES: [&str; 13] = [ "embedding-norm", "embedding-quant", @@ -88,12 +84,7 @@ enum Command { Qwen(ffi::FunctionHandle, Operation, Box), } -#[cfg(all( - test, - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "mtp_input_workspace_gpu.rs"] mod gpu; diff --git a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputcompletion.rs b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputcompletion.rs index 6a5a277f..91379fa0 100644 --- a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputcompletion.rs +++ b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputcompletion.rs @@ -30,15 +30,10 @@ impl<'ctx> MtpInputWorkspace<'ctx> { return Err(Error::ContextPoisoned); } for operation in OPERATIONS { - qwen_ffi::asset(operation) - .ok_or(Error::UnsupportedQwenOperation)? - .validate(operation)?; + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; } let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -57,12 +52,10 @@ impl<'ctx> MtpInputWorkspace<'ctx> { } let guard = context.enter()?; let load = (|| { - let (quant, project) = - context.common_kernels(ProjectionKind::Dense(DenseFormat::Q8_0))?; + let (quant, project) = context.common_kernels(ProjectionKind::Dense(DenseFormat::Q8_0))?; let mut qwen = [None; 3]; for (i, operation) in OPERATIONS.into_iter().enumerate() { - let asset = - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); } let module = context.driver.api.load_mmq_resident()?; @@ -132,11 +125,7 @@ impl<'ctx> MtpInputWorkspace<'ctx> { self.buffers.iter().flatten().map(|b| b.bytes).sum() } /// Owned host staging only. Acquire the first genuine weight at its original seam. - pub fn begin<'lease>( - &'lease mut self, - embedding: &[f32], - streams: &[f32], - ) -> Result> { + pub fn begin<'lease>(&'lease mut self, embedding: &[f32], streams: &[f32]) -> Result> { self.handles()?; if embedding.len() != 2560 || streams.len() != 10240 { return Err(Error::InvalidQwenShape); @@ -144,9 +133,7 @@ impl<'ctx> MtpInputWorkspace<'ctx> { if embedding.iter().chain(streams).any(|x| !x.is_finite()) { return Err(Error::InvalidDriverValue("MTP input finite source")); } - self.generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let mut e = staging(10240)?; let mut r = staging(40960)?; for (v, out) in embedding.iter().zip(e.as_chunks_mut::<4>().0) { @@ -156,13 +143,9 @@ impl<'ctx> MtpInputWorkspace<'ctx> { out.copy_from_slice(&v.to_le_bytes()); } let mut commands = Vec::new(); - commands - .try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; let mut weights = Vec::new(); - weights - .try_reserve_exact(7) - .map_err(|_| Error::HostAllocation)?; + weights.try_reserve_exact(7).map_err(|_| Error::HostAllocation)?; Ok(MtpInputPrefix { workspace: self, weights, diff --git a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputprefix.rs b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputprefix.rs index e9aa40cc..c06096de 100644 --- a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputprefix.rs +++ b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputprefix.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { pub(super) fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize) -> Result { let owned = self.workspace.handles()?; @@ -42,12 +41,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { self.workspace.handles()?[8].checked_subspan(52, index * 4, 4) } pub(super) fn finite(&mut self, source: ffi::BufferHandle, words: u32, index: usize) -> Result<()> { - let function = self - .workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .guard[1]; + let function = self.workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.guard[1]; let status = self.status(index)?; self.commands.push(Command::Guard( function, @@ -75,11 +69,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { in_place: false, }, )?; - let f = workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .qwen[0]; + let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[0]; self.commands.push(Command::Qwen( f, operation, @@ -105,18 +95,10 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { rows: 2560, columns: 2560, })?; - projection_ranges( - ProjectionKind::Dense(DenseFormat::Q8_0), - &shape, - [w, source, output], - )?; + projection_ranges(ProjectionKind::Dense(DenseFormat::Q8_0), &shape, [w, source, output])?; let handles = self.workspace.handles()?; let status = self.status(quant_index)?; - let kernels = self - .workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let kernels = self.workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?; self.commands.push(Command::Quant( kernels.quant, shape.quant_grid, @@ -159,11 +141,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { in_place: false, }, )?; - let f = workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .qwen[1]; + let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[1]; self.commands.push(Command::Qwen( f, operation, @@ -209,11 +187,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { self.ready(7)?; let workspace = &*self.workspace; let operation = OPERATIONS[2]; - let buffers = [ - workspace.buffer(5)?, - workspace.buffer(3)?, - workspace.buffer(6)?, - ]; + let buffers = [workspace.buffer(5)?, workspace.buffer(3)?, workspace.buffer(6)?]; let (_, layout, handles) = admission( workspace.context, &buffers, @@ -225,11 +199,7 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { in_place: false, }, )?; - let f = workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .qwen[2]; + let f = workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.qwen[2]; self.commands.push(Command::Qwen( f, operation, @@ -258,28 +228,17 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { } pub(super) fn drain(mut self, final_output: bool) -> Result> { let handles = self.workspace.handles()?; - let generation = self - .workspace - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.workspace.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let mut statuses = staging(52)?; let write_final = final_output && self.checks == 13; let mut final_staging = staging(if write_final { 40960 } else { 0 })?; let mut values = Vec::new(); - values - .try_reserve_exact(if write_final { 10240 } else { 0 }) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(if write_final { 10240 } else { 0 }).map_err(|_| Error::HostAllocation)?; if write_final { values.resize(10240, 0.0); } if !self.commands.is_empty() { - let f = self - .workspace - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .guard[0]; + let f = self.workspace.kernels.as_ref().ok_or(Error::ContextPoisoned)?.guard[0]; let mut reset = ffi::MmqResidentArguments::zero(handles[8], 13); let context = self.workspace.context; let guard = context.enter().inspect_err(|_| { @@ -322,17 +281,12 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { values, self.weights, )); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain MTP input drain")); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain MTP input drain")); } combine(combine(operation, sync), pop)?; } let mut decoded = [0u32; 13]; - for (i, (out, bytes)) in decoded - .iter_mut() - .zip(statuses.as_chunks::<4>().0) - .enumerate() - { + for (i, (out, bytes)) in decoded.iter_mut().zip(statuses.as_chunks::<4>().0).enumerate() { *out = u32::from_le_bytes(*bytes); let allowed = if QUANT.contains(&i) { 3 } else { 1 }; if *out & !allowed != 0 || (i >= self.checks && *out != 0) { @@ -341,21 +295,12 @@ impl<'lease, 'ctx> MtpInputPrefix<'lease, 'ctx> { return Err(Error::InvalidDriverValue("MTP input numeric witness")); } } - let refusal = decoded - .iter() - .take(self.checks) - .enumerate() - .find(|(_, s)| **s != 0) - .map(|(i, _)| { - ( - if QUANT.contains(&i) { - MtpInputRefusal::InvalidQ8Activation - } else { - MtpInputRefusal::NonFinite - }, - STAGES[i], - ) - }); + let refusal = decoded.iter().take(self.checks).enumerate().find(|(_, s)| **s != 0).map(|(i, _)| { + ( + if QUANT.contains(&i) { MtpInputRefusal::InvalidQ8Activation } else { MtpInputRefusal::NonFinite }, + STAGES[i], + ) + }); for (out, bytes) in values.iter_mut().zip(final_staging.as_chunks::<4>().0) { *out = f32::from_le_bytes(*bytes); } diff --git a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputworkspace.rs b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputworkspace.rs index ecfd91a3..dea94539 100644 --- a/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputworkspace.rs +++ b/crates/cuda-driver/src/mtp_input_workspace/impl_mtpinputworkspace.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl MtpInputWorkspace<'_> { pub(super) fn close_inner(&mut self) -> Result<()> { self.failed = true; @@ -53,9 +52,7 @@ impl Drop for MtpInputWorkspace<'_> { } pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } diff --git a/crates/cuda-driver/src/mtp_input_workspace_gpu.rs b/crates/cuda-driver/src/mtp_input_workspace_gpu.rs index a82a2e4f..9de7848d 100644 --- a/crates/cuda-driver/src/mtp_input_workspace_gpu.rs +++ b/crates/cuda-driver/src/mtp_input_workspace_gpu.rs @@ -42,11 +42,7 @@ fn original_first_mtp_input_prefix_products_status_order_and_cleanup() { }; let operation = (|| { let mut report = run(&context, &foreign)?; - refuse( - budget.mtp_input_workspace(), - Error::BudgetExceeded, - &mut report, - )?; + refuse(budget.mtp_input_workspace(), Error::BudgetExceeded, &mut report)?; Ok(report) })(); let allocated = context.allocated_bytes(); @@ -65,9 +61,7 @@ fn original_first_mtp_input_prefix_products_status_order_and_cleanup() { assert_eq!(report.witness_errors, 0); assert_eq!(report.numeric, 6); assert_eq!(report.guards, report.refusals); - eprintln!( - "MTP-INPUT-PREFIX {report:?}; device_bytes={TOTAL}; statuses=13; cleanup=0; component_only=true" - ); + eprintln!("MTP-INPUT-PREFIX {report:?}; device_bytes={TOTAL}; statuses=13; cleanup=0; component_only=true"); } #[path = "mtp_input_workspace_gpu/bytes_fn.rs"] @@ -75,25 +69,25 @@ mod bytes_fn; #[allow(unused_imports)] use bytes_fn::bytes; #[allow(unused_imports)] -use bytes_fn::upload; +use bytes_fn::compare; #[allow(unused_imports)] -use bytes_fn::read; +use bytes_fn::finite_case; #[allow(unused_imports)] use bytes_fn::full_finite; #[allow(unused_imports)] -use bytes_fn::raw; -#[allow(unused_imports)] use bytes_fn::inputs; #[allow(unused_imports)] -use bytes_fn::compare; -#[allow(unused_imports)] -use bytes_fn::refuse; -#[allow(unused_imports)] use bytes_fn::original; #[allow(unused_imports)] use bytes_fn::queue; #[allow(unused_imports)] -use bytes_fn::finite_case; +use bytes_fn::raw; +#[allow(unused_imports)] +use bytes_fn::read; +#[allow(unused_imports)] +use bytes_fn::refuse; +#[allow(unused_imports)] +use bytes_fn::upload; #[path = "mtp_input_workspace_gpu/numeric_case_fn.rs"] mod numeric_case_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mtp_input_workspace_gpu/bytes_fn.rs b/crates/cuda-driver/src/mtp_input_workspace_gpu/bytes_fn.rs index 0c8d1240..28e33049 100644 --- a/crates/cuda-driver/src/mtp_input_workspace_gpu/bytes_fn.rs +++ b/crates/cuda-driver/src/mtp_input_workspace_gpu/bytes_fn.rs @@ -19,11 +19,7 @@ pub(super) fn read(buffer: &DeviceBuffer<'_>) -> Result> { Ok(bytes) } pub(super) fn full_finite(bytes: &[u8]) -> bool { - bytes - .as_chunks::<4>() - .0 - .iter() - .all(|b| f32::from_le_bytes(*b).is_finite()) + bytes.as_chunks::<4>().0.iter().all(|b| f32::from_le_bytes(*b).is_finite()) } pub(super) fn raw(salt: usize) -> Vec { let mut bytes = vec![0; 6_963_200]; @@ -43,15 +39,11 @@ pub(super) fn inputs(case: usize) -> (Vec, Vec) { ((i * 13 + case * 11) % 47) as f32 / 16.0 - 1.5 } }; - ( - (0usize..2560).map(make).collect(), - (0usize..10240).map(|i| make(i + 31)).collect(), - ) + ((0usize..2560).map(make).collect(), (0usize..10240).map(|i| make(i + 31)).collect()) } pub(super) fn compare(old: &[u8], actual: &[u8], report: &mut Report) { report.products += 1; - report.witness_errors += - usize::from(old.len() != actual.len() || !full_finite(old) || !full_finite(actual)); + report.witness_errors += usize::from(old.len() != actual.len() || !full_finite(old) || !full_finite(actual)); for (a, b) in old.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0) { report.words += 1; report.differences += usize::from(a != b); @@ -93,41 +85,25 @@ pub(super) fn original( context.mtp_embedding_norm_f32(e, weights[0], en)?; let value = read(en)?; if !full_finite(&value) { - return Ok(Err(Numeric { - error: MtpInputRefusal::NonFinite, - stage: STAGES[0], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[0] })); } products.push(value); - let spec = ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - rows: 2560, - columns: 2560, - }; + let spec = ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q8_0), rows: 2560, columns: 2560 }; match context.project_q8_1(weights[1], en, e2, spec) { Err(Error::InvalidQ8Activation) => { - return Ok(Err(Numeric { - error: MtpInputRefusal::InvalidQ8Activation, - stage: STAGES[1], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[1] })); } result => result?, } let value = read(e2)?; if !full_finite(&value) { - return Ok(Err(Numeric { - error: MtpInputRefusal::NonFinite, - stage: STAGES[2], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[2] })); } products.push(value); context.mtp_hidden_norm_f32(r, weights[2], hn)?; let hidden = read(hn)?; if !full_finite(&hidden) { - return Ok(Err(Numeric { - error: MtpInputRefusal::NonFinite, - stage: STAGES[3], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[3] })); } products.push(hidden.clone()); let mut joined = Vec::new(); @@ -135,19 +111,13 @@ pub(super) fn original( h_input.copy_from(&hidden[i * 10240..(i + 1) * 10240])?; match context.project_q8_1(weight, h_input, h_output, spec) { Err(Error::InvalidQ8Activation) => { - return Ok(Err(Numeric { - error: MtpInputRefusal::InvalidQ8Activation, - stage: STAGES[4 + 2 * i], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::InvalidQ8Activation, stage: STAGES[4 + 2 * i] })); } result => result?, } let value = read(h_output)?; if !full_finite(&value) { - return Ok(Err(Numeric { - error: MtpInputRefusal::NonFinite, - stage: STAGES[5 + 2 * i], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[5 + 2 * i] })); } joined.extend_from_slice(&value); products.push(value); @@ -156,10 +126,7 @@ pub(super) fn original( context.mtp_broadcast_f32(h2, e2, out)?; let value = read(out)?; if !full_finite(&value) { - return Ok(Err(Numeric { - error: MtpInputRefusal::NonFinite, - stage: STAGES[12], - })); + return Ok(Err(Numeric { error: MtpInputRefusal::NonFinite, stage: STAGES[12] })); } products.push(value); Ok(Ok(products)) @@ -197,8 +164,7 @@ pub(super) fn finite_case( .map_err(|_| Error::InvalidDriverValue("original finite MTP corpus"))?; let before = context.allocated_bytes(); let completed = queue(workspace, &embedding, &streams, weights)?; - report.witness_errors += - usize::from(completed.numerical_refusal().is_some() || completed.statuses != [0; 13]); + report.witness_errors += usize::from(completed.numerical_refusal().is_some() || completed.statuses != [0; 13]); let mut actual = Vec::new(); for index in [2usize, 3, 4] { actual.push(read(completed.workspace.buffer(index)?)?); @@ -211,13 +177,8 @@ pub(super) fn finite_case( for (old, actual) in old.iter().zip(&actual) { compare(old, actual, report); } - let final_values = completed - .into_streams() - .map_err(|_| Error::InvalidDriverValue("finite MTP completion"))?; - report.witness_errors += usize::from( - bytes(&final_values) != old[7] - || context.allocated_bytes() != before - || workspace.is_failed(), - ); + let final_values = completed.into_streams().map_err(|_| Error::InvalidDriverValue("finite MTP completion"))?; + report.witness_errors += + usize::from(bytes(&final_values) != old[7] || context.allocated_bytes() != before || workspace.is_failed()); Ok(()) } diff --git a/crates/cuda-driver/src/mtp_input_workspace_gpu/numeric_case_fn.rs b/crates/cuda-driver/src/mtp_input_workspace_gpu/numeric_case_fn.rs index fbb793ac..404f6498 100644 --- a/crates/cuda-driver/src/mtp_input_workspace_gpu/numeric_case_fn.rs +++ b/crates/cuda-driver/src/mtp_input_workspace_gpu/numeric_case_fn.rs @@ -17,17 +17,14 @@ pub(super) fn numeric_case( let completed = queue(workspace, &embedding, &streams, weights)?; let numeric = completed.numerical_refusal(); let stage = completed.refusal_stage(); - let actual = numeric - .zip(stage) - .map(|(error, stage)| Numeric { error, stage }); + let actual = numeric.zip(stage).map(|(error, stage)| Numeric { error, stage }); // The old observed refusal also supplies the expected stage independently. let expected = match old { Err(value) => value, Ok(_) => return Err(Error::InvalidDriverValue("original numerical corpus")), }; report.witness_errors += usize::from(actual.as_ref() != Some(&expected)); - report.witness_errors += - usize::from(completed.into_streams() != Err(expected.error) || workspace.is_failed()); + report.witness_errors += usize::from(completed.into_streams() != Err(expected.error) || workspace.is_failed()); report.numeric += 1; Ok(()) } @@ -62,9 +59,7 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result, foreign: &Context<'_>) -> Result, foreign: &Context<'_>) -> Result { #[path = "mtp_original_full_drafter/impl_completedoriginalmtpdraft.rs"] mod impl_completedoriginalmtpdraft; -#[path = "mtp_original_full_drafter/impl_originalmtpdrafter.rs"] -mod impl_originalmtpdrafter; #[path = "mtp_original_full_drafter/impl_drop_for_originalmtpdrafter.rs"] mod impl_drop_for_originalmtpdrafter; +#[path = "mtp_original_full_drafter/impl_originalmtpdrafter.rs"] +mod impl_originalmtpdrafter; diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_completedoriginalmtpdraft.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_completedoriginalmtpdraft.rs index d049c8f2..515aa8a4 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_completedoriginalmtpdraft.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_completedoriginalmtpdraft.rs @@ -26,10 +26,7 @@ impl CompletedOriginalMtpDraft<'_> { self.window.validate_context(ring.context)?; ring.validate_snapshot(&self.snapshot)?; if ring.generation != self.generation - || !ring - .current - .as_ref() - .is_some_and(|s| Rc::ptr_eq(&s.0, &self.snapshot.0)) + || !ring.current.as_ref().is_some_and(|s| Rc::ptr_eq(&s.0, &self.snapshot.0)) { return Err(Error::InvalidQwenShape); } diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_drop_for_originalmtpdrafter.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_drop_for_originalmtpdrafter.rs index 0b4cfe35..1bfa22f8 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_drop_for_originalmtpdrafter.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_drop_for_originalmtpdrafter.rs @@ -91,16 +91,7 @@ impl OriginalMtpFullPolicy { { return Err(Error::UnsupportedQwenOperation); } - if [ - k.theta_scale, - k.freq_scale, - k.corr_low, - k.corr_high, - k.ext_factor, - k.mscale, - ] - .iter() - .any(|v| !v.is_finite()) + if [k.theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.mscale].iter().any(|v| !v.is_finite()) || k.theta_scale <= 0.0 || k.freq_scale <= 0.0 || k.mscale <= 0.0 @@ -128,7 +119,18 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { direct_window: bool, ) -> Result> { self.launch_inner( - ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, first_rows, direct_window, None, + ring, + prior, + window, + selection, + a, + max_drafts, + min_p, + policy, + coupled, + first_rows, + direct_window, + None, )?; self.finish_inner(ring, prior, policy) } @@ -182,9 +184,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { policy: &OriginalMtpFullPolicy, coupled: Option<(SamplerParams, &[i32; 4096])>, ) -> Result> { - self.draft_inner( - ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, true, - ) + self.draft_inner(ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, true) } } @@ -202,18 +202,6 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { policy: &OriginalMtpFullPolicy, coupled: Option<(SamplerParams, &[i32; 4096])>, ) -> Result> { - self.draft_inner( - ring, - prior, - window, - selection, - 0, - max_drafts, - min_p, - policy, - coupled, - Some(rows), - true, - ) + self.draft_inner(ring, prior, window, selection, 0, max_drafts, min_p, policy, coupled, Some(rows), true) } } diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs index 757aaa9f..91219724 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2.rs @@ -3,12 +3,8 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpDrafter<'ctx> { - pub fn new( - full: OriginalMtpFullForward<'ctx>, - mut scalar: OriginalMtpScalarPrefill<'ctx>, - ) -> Result { + pub fn new(full: OriginalMtpFullForward<'ctx>, mut scalar: OriginalMtpScalarPrefill<'ctx>) -> Result { full.validate_context(scalar.context)?; scalar.validate()?; if full.inner.max_t != scalar.max_t || scalar.has_pending { @@ -32,10 +28,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { in_flight: None, }; let op = (|| { - result.graphs = Some(OriginalGraphRegistry::new( - c, - 2 * (max_t + max_t.saturating_sub(2)), - )?); + result.graphs = Some(OriginalGraphRegistry::new(c, 2 * (max_t + max_t.saturating_sub(2)))?); Ok(()) })(); if let Err(primary) = op { @@ -50,23 +43,13 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { if self.failed || c.is_poisoned() { return Err(Error::ContextPoisoned); } - self.full - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c)?; + self.full.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(c)?; validate_scalar_prefix(self.scalar.as_ref().ok_or(Error::ContextPoisoned)?)?; - self.stream - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c) + self.stream.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(c) } pub fn metadata_bytes(&self) -> Result { Ok(std::mem::size_of::() - + self - .graphs - .as_ref() - .ok_or(Error::ContextPoisoned)? - .metadata_bytes() + + self.graphs.as_ref().ok_or(Error::ContextPoisoned)?.metadata_bytes() + self.graph_metadata) } pub fn is_failed(&self) -> bool { @@ -87,9 +70,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { policy: &OriginalMtpFullPolicy, coupled: Option<(SamplerParams, &[i32; 4096])>, ) -> Result> { - self.draft_inner( - ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, false, - ) + self.draft_inner(ring, prior, window, selection, a, max_drafts, min_p, policy, coupled, None, false) } #[allow(clippy::too_many_arguments)] pub fn draft_first( @@ -104,18 +85,6 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { policy: &OriginalMtpFullPolicy, coupled: Option<(SamplerParams, &[i32; 4096])>, ) -> Result> { - self.draft_inner( - ring, - prior, - window, - selection, - 0, - max_drafts, - min_p, - policy, - coupled, - Some(rows), - false, - ) + self.draft_inner(ring, prior, window, selection, 0, max_drafts, min_p, policy, coupled, Some(rows), false) } } diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs index 1ee995d7..30e489ab 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpDrafter<'ctx> { #[allow(clippy::too_many_arguments)] pub(in super::super) fn launch_inner( @@ -38,25 +37,17 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { || rows > self.max_t || a >= rows || first > prior.0.end - || first - .checked_add(rows.max(a + 1)) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || first.checked_add(rows.max(a + 1)).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) { return Err(Error::InvalidQwenShape); } - if self - .direct_window_mode - .is_some_and(|old| old != direct_window) - { + if self.direct_window_mode.is_some_and(|old| old != direct_window) { return Err(Error::InvalidQwenShape); } self.direct_window_mode = Some(direct_window); let owner = prior.owner_id(); let policy_key = policy.capture_key(); - if self - .ring_owner - .as_ref() - .is_some_and(|old| !old.same_owner(&owner)) + if self.ring_owner.as_ref().is_some_and(|old| !old.same_owner(&owner)) || self.policy_key.is_some_and(|old| old != policy_key) { return Err(Error::InvalidQwenShape); @@ -64,14 +55,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { self.ring_owner = Some(owner); self.policy_key = Some(policy_key); let cp = coupled.is_some(); - if cp - && !self - .full - .as_ref() - .ok_or(Error::ContextPoisoned)? - .inner - .coupled - { + if cp && !self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.coupled { return Err(Error::InvalidQwenShape); } let window = Rc::new(window); @@ -85,18 +69,11 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { rows, )?; } else { - full.stage_first_residual( - Rc::clone(&window), - selection.take().ok_or(Error::InvalidQwenShape)?, - rows, - )?; + full.stage_first_residual(Rc::clone(&window), selection.take().ok_or(Error::InvalidQwenShape)?, rows)?; } } let pol = policy.for_capture(0, cp); - let key = OriginalGraphKey::MtpRound { - rows: rows as u8, - coupled: cp, - }; + let key = OriginalGraphKey::MtpRound { rows: rows as u8, coupled: cp }; let full = self.full.as_ref().ok_or(Error::ContextPoisoned)?; let scalar = self.scalar.as_ref().ok_or(Error::ContextPoisoned)?; let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; @@ -124,10 +101,8 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { )?; drop(span_record); if first_capture { - self.graph_metadata = self - .graph_metadata - .checked_add(graph.mtp_resource_metadata()?) - .ok_or(Error::BudgetExceeded)?; + self.graph_metadata = + self.graph_metadata.checked_add(graph.mtp_resource_metadata()?).ok_or(Error::BudgetExceeded)?; if crate::host_profile::enabled() { eprintln!("DBG mtp round graph rows {rows} (coupled {cp}): {:?} nodes", graph.nodes()); } @@ -143,12 +118,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { if first_rows.is_some() { graph.mtp_stage_first_after_capture()?; } else { - graph.mtp_stage_window( - stream, - Rc::clone(&window), - selection.take().ok_or(Error::InvalidQwenShape)?, - a, - )?; + graph.mtp_stage_window(stream, Rc::clone(&window), selection.take().ok_or(Error::InvalidQwenShape)?, a)?; } if let Some((params, history)) = coupled { graph.mtp_stage_sampling(params, history)?; @@ -160,18 +130,8 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { } return Err(error); } - self.in_flight = Some(InFlightDraft { - window, - key, - generation, - a, - rows, - first, - max_drafts, - min_p, - coupled: cp, - policy_key, - }); + self.in_flight = + Some(InFlightDraft { window, key, generation, a, rows, first, max_drafts, min_p, coupled: cp, policy_key }); Ok(()) } } diff --git a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs index 6684b137..9f0d6297 100644 --- a/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs +++ b/crates/cuda-driver/src/mtp_original_full_drafter/impl_originalmtpdrafter/impl_originalmtpdrafter_3.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpDrafter<'ctx> { - /// Read back the first graph of the draft `launch_inner` enqueued, run the chain and close the ring mutation: /// the second half of `draft_from_verifier`, over the same ring and prior. pub(in super::super) fn finish_inner( @@ -56,23 +54,13 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let mut j = 1usize; while (j as i32) < limit && probabilities[j - 1] >= min_p { let _span_chain = crate::host_profile::span("mtp.chain_step"); - let key = OriginalGraphKey::MtpStep { - step: j as u8, - coupled: cp, - }; + let key = OriginalGraphKey::MtpStep { step: j as u8, coupled: cp }; let pol = policy.for_capture(j, cp); let first_capture = graphs.find_mut(key)?.is_none(); - let graph = graphs.record( - key, - stream, - || full.prepare_step(scalar, ring, j, &pol), - |c, r| r.capture(c), - )?; + let graph = graphs.record(key, stream, || full.prepare_step(scalar, ring, j, &pol), |c, r| r.capture(c))?; if first_capture { - self.graph_metadata = self - .graph_metadata - .checked_add(graph.mtp_resource_metadata()?) - .ok_or(Error::BudgetExceeded)?; + self.graph_metadata = + self.graph_metadata.checked_add(graph.mtp_resource_metadata()?).ok_or(Error::BudgetExceeded)?; if crate::host_profile::enabled() { eprintln!("DBG mtp chain-step graph {j} (coupled {cp}): {:?} nodes", graph.nodes()); } @@ -93,14 +81,12 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { if let Some((a, _)) = timing.as_mut() { let _ = a.record(stream); } - let step_result = graph - .enqueue(stream) - .and_then(|_| { - if let Some((_, b)) = timing.as_mut() { - let _ = b.record(stream); - } - graph.mtp_finish_step(stream) - }); + let step_result = graph.enqueue(stream).and_then(|_| { + if let Some((_, b)) = timing.as_mut() { + let _ = b.record(stream); + } + graph.mtp_finish_step(stream) + }); if let Some((a, b)) = timing.as_ref() { if let Ok(ms) = a.elapsed_ms(b) { crate::host_profile::add("gpu.mtp_chain_step", f64::from(ms)); @@ -121,9 +107,7 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { j += 1; } window.validate_context(self.context)?; - let end = first - .checked_add(rows.max(a + count)) - .ok_or(Error::InvalidSize)?; + let end = first.checked_add(rows.max(a + count)).ok_or(Error::InvalidSize)?; let _span_ring = crate::host_profile::span("mtp.finish_ring"); let snapshot = ring.finish_original_graph_mutation(prior, first, end, generation)?; Ok(CompletedOriginalMtpDraft { @@ -179,9 +163,8 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { let stream = self.stream.take().ok_or(Error::ContextPoisoned)?; let scalar = self.scalar.as_mut().ok_or(Error::ContextPoisoned)?; scalar.stream = Some(stream); - let result = scalar.record( - residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, - ); + let result = + scalar.record(residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled); self.stream = scalar.stream.take(); if self.stream.is_none() || result.is_err() && self.context.is_poisoned() { self.failed = true; @@ -193,19 +176,10 @@ impl<'ctx> OriginalMtpDrafter<'ctx> { } pub(in super::super) fn close_inner(&mut self) -> Result<()> { self.failed = true; - let graphs = self - .graphs - .take() - .map_or(Ok(()), OriginalGraphRegistry::close); - let scalar = self - .scalar - .take() - .map_or(Ok(()), OriginalMtpScalarPrefill::close); + let graphs = self.graphs.take().map_or(Ok(()), OriginalGraphRegistry::close); + let scalar = self.scalar.take().map_or(Ok(()), OriginalMtpScalarPrefill::close); let stream = self.stream.take().map_or(Ok(()), OriginalGpuStream::close); - let full = self - .full - .take() - .map_or(Ok(()), OriginalMtpFullForward::close); + let full = self.full.take().map_or(Ok(()), OriginalMtpFullForward::close); combine(combine(combine(graphs, scalar), stream), full) } } diff --git a/crates/cuda-driver/src/mtp_original_full_ffi.rs b/crates/cuda-driver/src/mtp_original_full_ffi.rs index f687fd68..6a8b2443 100644 --- a/crates/cuda-driver/src/mtp_original_full_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_full_ffi.rs @@ -7,8 +7,8 @@ pub(crate) enum Arg { I32(i32), I64(i64), F32(f32), - Words3([u64;3]), - GrMulti(Box<[u64;114]>), + Words3([u64; 3]), + GrMulti(Box<[u64; 114]>), Params(crate::SamplerParams), } pub(crate) struct Arguments { @@ -16,24 +16,38 @@ pub(crate) struct Arguments { pointers: Vec<*mut c_void>, } impl Arguments { - pub(crate) fn metadata_bytes(&self)->usize{ - std::mem::size_of::()+self.values.len()*std::mem::size_of::()+self.pointers.capacity()*std::mem::size_of::<*mut c_void>() - +self.values.iter().map(|a|if matches!(a,Arg::GrMulti(_)){114*8}else{0}).sum::() + pub(crate) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + self.values.len() * std::mem::size_of::() + + self.pointers.capacity() * std::mem::size_of::<*mut c_void>() + + self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::() } pub(crate) fn new(values: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(values.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - values: values.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { values: values.into_boxed_slice(), pointers }) } } #[repr(C)] -pub(crate) struct Copy2D {src_x:usize,src_y:usize,src_type:u32,src_host:*const c_void,src_dev:u64,src_array:*mut c_void,src_pitch:usize,dst_x:usize,dst_y:usize,dst_type:u32,dst_host:*mut c_void,dst_dev:u64,dst_array:*mut c_void,dst_pitch:usize,width:usize,height:usize} +pub(crate) struct Copy2D { + src_x: usize, + src_y: usize, + src_type: u32, + src_host: *const c_void, + src_dev: u64, + src_array: *mut c_void, + src_pitch: usize, + dst_x: usize, + dst_y: usize, + dst_type: u32, + dst_host: *mut c_void, + dst_dev: u64, + dst_array: *mut c_void, + dst_pitch: usize, + width: usize, + height: usize, +} // Must stay bit-identical to CUDA_MEMCPY2D (LP64): the driver reads it through a raw pointer in `copy2d`. #[cfg(target_pointer_width = "64")] const _: () = { @@ -44,306 +58,32 @@ const _: () = { assert!(std::mem::offset_of!(Copy2D, dst_dev) == 88 && std::mem::offset_of!(Copy2D, dst_pitch) == 104); assert!(std::mem::offset_of!(Copy2D, width) == 112 && std::mem::offset_of!(Copy2D, height) == 120); }; -impl Copy2D{pub(crate) fn q_split(src:u64,dst:u64)->Self{Self{src_x:0,src_y:0,src_type:2,src_host:std::ptr::null(),src_dev:src,src_array:std::ptr::null_mut(),src_pitch:512*4,dst_x:0,dst_y:0,dst_type:2,dst_host:std::ptr::null_mut(),dst_dev:dst,dst_array:std::ptr::null_mut(),dst_pitch:256*4,width:256*4,height:24}}} -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -mod enabled { - use super::*; - type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; - type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; - type FunctionAttr = unsafe extern "C" fn(*mut c_void,i32,i32)->i32; - type Unload = unsafe extern "C" fn(*mut c_void) -> i32; - type CopySync = unsafe extern "C" fn(u64,u64,usize)->i32; - type StreamSync = unsafe extern "C" fn(*mut c_void)->i32; - type Copy = unsafe extern "C" fn(u64,u64,usize,*mut c_void)->i32; - type C2D = unsafe extern "C" fn(*const Copy2D,*mut c_void)->i32; - type Memset = unsafe extern "C" fn(u64,u8,usize)->i32; - type H2D = unsafe extern "C" fn(u64,*const c_void,usize,*mut c_void)->i32; - type Device = unsafe extern "C" fn(*mut i32) -> i32; - type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; - type Launch = unsafe extern "C" fn( - *mut c_void, - u32, - u32, - u32, - u32, - u32, - u32, - u32, - *mut c_void, - *mut *mut c_void, - *mut *mut c_void, - ) -> i32; - struct Library(*mut c_void); - impl Drop for Library { - fn drop(&mut self) { - if !self.0.is_null() { - // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. - unsafe { - libc::dlclose(self.0); - } - } - } - } - fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } - } - macro_rules! sym { - ($l:ident,$n:literal,$t:ty) => {{ - // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. - let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; - if p.is_null() { - return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); - } - // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature - // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). - unsafe { std::mem::transmute::<*mut c_void, $t>(p) } - }}; - } - pub(crate) struct Module { - library: Option, - module: Option, - functions: Vec, - launch: Launch, - unload: Unload, - copy: Copy, - copy_sync:CopySync, - stream_sync:StreamSync, - h2d: H2D, - memset:Memset, - c2d:C2D, - attr: FunctionAttr, - } - impl Module { - pub(crate) fn metadata_bytes(&self)->usize{std::mem::size_of::()+self.functions.capacity()*std::mem::size_of::()+std::mem::size_of::()} - pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { - if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { - return Err(Error::UnsupportedQwenOperation); - } - // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); - if l.0.is_null() { - return Err(Error::LibraryUnavailable); - } - let load = sym!(l, c"cuModuleLoadData", Load); - let get = sym!(l, c"cuModuleGetFunction", Function); - let dev = sym!(l, c"cuCtxGetDevice", Device); - let attr = sym!(l, c"cuDeviceGetAttribute", Attr); - let mut device = 0; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuCtxGetDevice", unsafe { dev(&mut device) })?; - let mut major = 0; - let mut shared = 0; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; - if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 { - return Err(Error::UnsupportedQwenOperation); - } - let mut owner = Self { - launch: sym!(l, c"cuLaunchKernel", Launch), - unload: sym!(l, c"cuModuleUnload", Unload), - copy: sym!(l,c"cuMemcpyAsync",Copy), - copy_sync:sym!(l,c"cuMemcpy",CopySync), - stream_sync:sym!(l,c"cuStreamSynchronize",StreamSync), - h2d: sym!(l,c"cuMemcpyHtoDAsync_v2",H2D), - memset:sym!(l,c"cuMemsetD8_v2",Memset), - c2d:sym!(l,c"cuMemcpy2DAsync_v2",C2D), - attr: sym!(l,c"cuFuncSetAttribute",FunctionAttr), - library: Some(l), - module: None, - functions: Vec::new(), - }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; - let result = (|| { - let mut m = std::ptr::null_mut(); - // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from - // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; - if m.is_null() { - return Err(Error::InvalidDriverValue("cuModuleLoadData")); - } - owner.module = Some(m as usize); - for n in entries { - let mut f = std::ptr::null_mut(); - // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static - // NUL-terminated literal; the function out-pointer is valid. - check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; - if f.is_null() { - return Err(Error::InvalidDriverValue("cuModuleGetFunction")); - } - owner.functions.push(f as usize); - } - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - // Literal down_chunk geometry: sm75 uses1280, others2560; preVolta - // uses actual per-block shared capacity rather than opt-in promise. - pub(crate) fn configure_gr(&self)->Result<(usize,usize)> { - let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; - let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; - let mut optin=0;let mut major=0;let mut minor=0;let mut per_block=0; - for (value,key) in [(&mut optin,97),(&mut major,75),(&mut minor,76),(&mut per_block,8)]{ - // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside - // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute(GR)",unsafe{attr(value,key,d)})?; - } - let tile=if major*10+minor==75{1280}else{2560}; - let usable=if major>=7&&optin>0{optin}else{per_block}; - if usable<=0{return Err(Error::InvalidDriverValue("Original GR shared geometry"));} - // Original sets both down-kernel attributes once, before launches. - for (index,want) in [(if tile==1280{4}else{5},8*tile*4),(2,2*8*1280*4)]{ - let want=if optin>0{want.min(optin as usize)}else{want}; - let function=*self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; - // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); - // attribute id and value are plain integers. - check("cuFuncSetAttribute",unsafe{(self.attr)(function as *mut c_void,8,want as i32)})?; - } - Ok((usable as usize,tile)) - } - pub(crate) fn launch( - &self, - index: usize, - grid: [u32; 3], - block: [u32;3], - shared: u32, - stream: usize, - args: &mut Arguments, - ) -> Result<()> { - if grid.contains(&0) - || !(matches!(block,[32,4,1]|[32,8,1]) || block[1..]==[1,1] && (block[0]==1 || block[0]<=1024 && block[0]%32==0)) - || shared>131072 - || stream == 0 - { - return Err(Error::InvalidQwenShape); - } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; - args.pointers.clear(); - for v in &mut args.values { - args.pointers.push(match v { - Arg::U64(x) => (x as *mut u64).cast(), - Arg::I32(x) => (x as *mut i32).cast(), - Arg::I64(x) => (x as *mut i64).cast(), - Arg::F32(x) => (x as *mut f32).cast(), - Arg::Words3(x) => x.as_mut_ptr().cast(), - Arg::GrMulti(x) => x.as_mut_ptr().cast(), - Arg::Params(x) => (x as *mut crate::SamplerParams).cast(), - }); - } - // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a - // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt - // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; - // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not - // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. - check("cuLaunchKernel", unsafe { - (self.launch)( - f as *mut c_void, - grid[0], - grid[1], - grid[2], - block[0], - block[1], - block[2], - shared, - stream as *mut c_void, - args.pointers.as_mut_ptr(), - std::ptr::null_mut(), - ) - }) - } - // Addresses are derived only by this producer from actual whole owners. - pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { - if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } - // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents - // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners - // must outlive the stream drain (graph resources / Context::synchronize on every close path). - check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) - } - // SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host destinations; - // a device->device copy is merely ordered on the legacy default stream (callers: mtp_original_full_round.rs). - pub(crate) fn copy_sync(&self,dst:u64,src:u64,n:usize)->Result<()>{if dst==0||src==0||n==0{return Err(Error::InvalidSize);}check("cuMemcpy",unsafe{(self.copy_sync)(dst,src,n)})} - // SAFETY: stream handle 0 is the legacy default stream, which `copy_sync` (cuMemcpy) uses; synchronizing it returns once every earlier - // legacy-stream operation (the D2D copies) has completed, and it does NOT wait for work queued on non-blocking streams (a pending - // verifier commit), unlike cuCtxSynchronize. After it returns, a launch on a non-blocking stream is ordered after the copies by the host. - pub(crate) fn fence_legacy_stream(&self)->Result<()>{check("cuStreamSynchronize",unsafe{(self.stream_sync)(std::ptr::null_mut())})} - // SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered on the legacy - // default stream but asynchronous with respect to the host; its only caller (FullOwned::new_internal) fences it. - pub(crate) fn zero(&self,dst:u64,n:usize)->Result<()>{if dst==0||n==0{return Err(Error::InvalidSize);}check("cuMemsetD8_v2",unsafe{(self.memset)(dst,0,n)})} - // SAFETY: `descriptor` is a #[repr(C)] CUDA_MEMCPY2D (layout asserted at compile time above) read by the driver during - // this call only; its src/dst are device addresses of live whole owners sized for pitch*height (see the q_split test). - pub(crate) fn copy2d(&self,descriptor:&Copy2D,stream:usize)->Result<()>{if stream==0{return Err(Error::InvalidQwenShape);}check("cuMemcpy2DAsync_v2",unsafe{(self.c2d)(descriptor,stream as *mut c_void)})} - pub(crate) fn copy_host(&self,dst:u64,source:&[u8],stream:usize)->Result<()> { - if dst==0||source.is_empty()||stream==0{return Err(Error::InvalidSize);} - // SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the - // driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is - // drained, so even a pinned-source (fully asynchronous) copy would read valid memory. - check("cuMemcpyHtoDAsync_v2",unsafe{(self.h2d)(dst,source.as_ptr().cast(),source.len(),stream as *mut c_void)}) - } - pub(crate) fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - if let Some(m) = self.module.take() { - // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the - // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. - let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); - if r.is_err() - && let Some(l) = self.library.take() - { - std::mem::forget(l); - } - r - } else { - Ok(()) - } - } - } - impl Drop for Module { - fn drop(&mut self) { - let _ = self.close_inner(); +impl Copy2D { + pub(crate) fn q_split(src: u64, dst: u64) -> Self { + Self { + src_x: 0, + src_y: 0, + src_type: 2, + src_host: std::ptr::null(), + src_dev: src, + src_array: std::ptr::null_mut(), + src_pitch: 512 * 4, + dst_x: 0, + dst_y: 0, + dst_type: 2, + dst_host: std::ptr::null_mut(), + dst_dev: dst, + dst_array: std::ptr::null_mut(), + dst_pitch: 256 * 4, + width: 256 * 4, + height: 24, } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[path = "mtp_original_full_ffi/enabled.rs"] +mod enabled; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::Module; #[cfg(not(all( feature = "cuda-driver", @@ -357,28 +97,36 @@ pub(crate) struct Module; target_pointer_width = "64" )))] impl Module { - pub(crate) fn metadata_bytes(&self)->usize{std::mem::size_of::()} - pub(crate) fn configure_gr(&self)->Result<(usize,usize)>{Err(Error::UnsupportedPlatform)} + pub(crate) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + } + pub(crate) fn configure_gr(&self) -> Result<(usize, usize)> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - _: usize, - _: [u32; 3], - _: [u32;3], - _: u32, - _: usize, - _: &mut Arguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy_sync(&self, _: u64, _: u64, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn fence_legacy_stream(&self) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn zero(&self, _: u64, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy2d(&self, _: &Copy2D, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy_host(&self, _dst: u64, _source: &[u8], _stream: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy(&self,_:u64,_:u64,_:usize,_:usize)->Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy_sync(&self,_:u64,_:u64,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn fence_legacy_stream(&self)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn zero(&self,_:u64,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn copy2d(&self,_:&Copy2D,_:usize)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn copy_host(&self,_dst:u64,_source:&[u8],_stream:usize)->Result<()> {Err(Error::UnsupportedPlatform)} pub(crate) fn close(self) -> Result<()> { Ok(()) } diff --git a/crates/cuda-driver/src/mtp_original_full_ffi/enabled.rs b/crates/cuda-driver/src/mtp_original_full_ffi/enabled.rs new file mode 100644 index 00000000..4bc311a2 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_ffi/enabled.rs @@ -0,0 +1,303 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; +type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; +type FunctionAttr = unsafe extern "C" fn(*mut c_void, i32, i32) -> i32; +type Unload = unsafe extern "C" fn(*mut c_void) -> i32; +type CopySync = unsafe extern "C" fn(u64, u64, usize) -> i32; +type StreamSync = unsafe extern "C" fn(*mut c_void) -> i32; +type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; +type C2D = unsafe extern "C" fn(*const Copy2D, *mut c_void) -> i32; +type Memset = unsafe extern "C" fn(u64, u8, usize) -> i32; +type H2D = unsafe extern "C" fn(u64, *const c_void, usize, *mut c_void) -> i32; +type Device = unsafe extern "C" fn(*mut i32) -> i32; +type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; +type Launch = unsafe extern "C" fn( + *mut c_void, + u32, + u32, + u32, + u32, + u32, + u32, + u32, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, +) -> i32; +struct Library(*mut c_void); +impl Drop for Library { + fn drop(&mut self) { + if !self.0.is_null() { + // SAFETY: self.0 is the non-null handle returned by this type's own dlopen; it is closed exactly once, here. + unsafe { + libc::dlclose(self.0); + } + } + } +} +fn check(op: &'static str, code: i32) -> Result<()> { + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } +} +macro_rules! sym { + ($l:ident,$n:literal,$t:ty) => {{ + // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. + let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol($n.to_str().expect("static ABI"))); + } + // SAFETY: p is the non-null address of the named libcuda export and the target type is that export's C signature + // (a plain pointer-sized fn pointer on 64-bit Linux, the only target this module is compiled for). + unsafe { std::mem::transmute::<*mut c_void, $t>(p) } + }}; +} +pub(crate) struct Module { + library: Option, + module: Option, + functions: Vec, + launch: Launch, + unload: Unload, + copy: Copy, + copy_sync: CopySync, + stream_sync: StreamSync, + h2d: H2D, + memset: Memset, + c2d: C2D, + attr: FunctionAttr, +} +impl Module { + pub(crate) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + self.functions.capacity() * std::mem::size_of::() + + std::mem::size_of::() + } + pub(crate) fn load(ptx: &'static [u8], entries: &'static [&'static CStr]) -> Result { + if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { + return Err(Error::UnsupportedQwenOperation); + } + // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); + if l.0.is_null() { + return Err(Error::LibraryUnavailable); + } + let load = sym!(l, c"cuModuleLoadData", Load); + let get = sym!(l, c"cuModuleGetFunction", Function); + let dev = sym!(l, c"cuCtxGetDevice", Device); + let attr = sym!(l, c"cuDeviceGetAttribute", Attr); + let mut device = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuCtxGetDevice", unsafe { dev(&mut device) })?; + let mut major = 0; + let mut shared = 0; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; + if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 { + return Err(Error::UnsupportedQwenOperation); + } + let mut owner = Self { + launch: sym!(l, c"cuLaunchKernel", Launch), + unload: sym!(l, c"cuModuleUnload", Unload), + copy: sym!(l, c"cuMemcpyAsync", Copy), + copy_sync: sym!(l, c"cuMemcpy", CopySync), + stream_sync: sym!(l, c"cuStreamSynchronize", StreamSync), + h2d: sym!(l, c"cuMemcpyHtoDAsync_v2", H2D), + memset: sym!(l, c"cuMemsetD8_v2", Memset), + c2d: sym!(l, c"cuMemcpy2DAsync_v2", C2D), + attr: sym!(l, c"cuFuncSetAttribute", FunctionAttr), + library: Some(l), + module: None, + functions: Vec::new(), + }; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; + let result = (|| { + let mut m = std::ptr::null_mut(); + // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from + // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + owner.module = Some(m as usize); + for n in entries { + let mut f = std::ptr::null_mut(); + // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static + // NUL-terminated literal; the function out-pointer is valid. + check("cuModuleGetFunction", unsafe { get(&mut f, m, n.as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + owner.functions.push(f as usize); + } + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + // Literal down_chunk geometry: sm75 uses1280, others2560; preVolta + // uses actual per-block shared capacity rather than opt-in promise. + pub(crate) fn configure_gr(&self) -> Result<(usize, usize)> { + let l = self.library.as_ref().ok_or(Error::ContextPoisoned)?; + let device = sym!(l, c"cuCtxGetDevice", Device); + let attr = sym!(l, c"cuDeviceGetAttribute", Attr); + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + let mut d = 0; + check("cuCtxGetDevice", unsafe { device(&mut d) })?; + let mut optin = 0; + let mut major = 0; + let mut minor = 0; + let mut per_block = 0; + for (value, key) in [(&mut optin, 97), (&mut major, 75), (&mut minor, 76), (&mut per_block, 8)] { + // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside + // `Context::enter` (module load / geometry probes are never called without it). + check("cuDeviceGetAttribute(GR)", unsafe { attr(value, key, d) })?; + } + let tile = if major * 10 + minor == 75 { 1280 } else { 2560 }; + let usable = if major >= 7 && optin > 0 { optin } else { per_block }; + if usable <= 0 { + return Err(Error::InvalidDriverValue("Original GR shared geometry")); + } + // Original sets both down-kernel attributes once, before launches. + for (index, want) in [(if tile == 1280 { 4 } else { 5 }, 8 * tile * 4), (2, 2 * 8 * 1280 * 4)] { + let want = if optin > 0 { want.min(optin as usize) } else { want }; + let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); + // attribute id and value are plain integers. + check("cuFuncSetAttribute", unsafe { (self.attr)(function as *mut c_void, 8, want as i32) })?; + } + Ok((usable as usize, tile)) + } + pub(crate) fn launch( + &self, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + stream: usize, + args: &mut Arguments, + ) -> Result<()> { + if grid.contains(&0) + || !(matches!(block, [32, 4, 1] | [32, 8, 1]) + || block[1..] == [1, 1] && (block[0] == 1 || block[0] <= 1024 && block[0] % 32 == 0)) + || shared > 131072 + || stream == 0 + { + return Err(Error::InvalidQwenShape); + } + let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + args.pointers.clear(); + for v in &mut args.values { + args.pointers.push(match v { + Arg::U64(x) => (x as *mut u64).cast(), + Arg::I32(x) => (x as *mut i32).cast(), + Arg::I64(x) => (x as *mut i64).cast(), + Arg::F32(x) => (x as *mut f32).cast(), + Arg::Words3(x) => x.as_mut_ptr().cast(), + Arg::GrMulti(x) => x.as_mut_ptr().cast(), + Arg::Params(x) => (x as *mut crate::SamplerParams).cast(), + }); + } + // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a + // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt + // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; + // the driver copies the parameter bytes during this call (also under stream capture), so the storage need not + // outlive it. Argument/PTX parameter agreement is a producer contract checked by the GPU parity tests, not here. + check("cuLaunchKernel", unsafe { + (self.launch)( + f as *mut c_void, + grid[0], + grid[1], + grid[2], + block[0], + block[1], + block[2], + shared, + stream as *mut c_void, + args.pointers.as_mut_ptr(), + std::ptr::null_mut(), + ) + }) + } + // Addresses are derived only by this producer from actual whole owners. + pub(crate) fn copy(&self, dst: u64, src: u64, n: usize, stream: usize) -> Result<()> { + if n == 0 || stream == 0 || dst == 0 || src == 0 { + return Err(Error::InvalidSize); + } + // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents + // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners + // must outlive the stream drain (graph resources / Context::synchronize on every close path). + check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) }) + } + // SAFETY: same address provenance as `copy`; n > 0. cuMemcpy returns after completion only for device->host destinations; + // a device->device copy is merely ordered on the legacy default stream (callers: mtp_original_full_round.rs). + pub(crate) fn copy_sync(&self, dst: u64, src: u64, n: usize) -> Result<()> { + if dst == 0 || src == 0 || n == 0 { + return Err(Error::InvalidSize); + } + check("cuMemcpy", unsafe { (self.copy_sync)(dst, src, n) }) + } + // SAFETY: stream handle 0 is the legacy default stream, which `copy_sync` (cuMemcpy) uses; synchronizing it returns once every earlier + // legacy-stream operation (the D2D copies) has completed, and it does NOT wait for work queued on non-blocking streams (a pending + // verifier commit), unlike cuCtxSynchronize. After it returns, a launch on a non-blocking stream is ordered after the copies by the host. + pub(crate) fn fence_legacy_stream(&self) -> Result<()> { + check("cuStreamSynchronize", unsafe { (self.stream_sync)(std::ptr::null_mut()) }) + } + // SAFETY: dst/n describe a device range the caller validated against a whole owner. cuMemsetD8_v2 is ordered on the legacy + // default stream but asynchronous with respect to the host; its only caller (FullOwned::new_internal) fences it. + pub(crate) fn zero(&self, dst: u64, n: usize) -> Result<()> { + if dst == 0 || n == 0 { + return Err(Error::InvalidSize); + } + check("cuMemsetD8_v2", unsafe { (self.memset)(dst, 0, n) }) + } + // SAFETY: `descriptor` is a #[repr(C)] CUDA_MEMCPY2D (layout asserted at compile time above) read by the driver during + // this call only; its src/dst are device addresses of live whole owners sized for pitch*height (see the q_split test). + pub(crate) fn copy2d(&self, descriptor: &Copy2D, stream: usize) -> Result<()> { + if stream == 0 { + return Err(Error::InvalidQwenShape); + } + check("cuMemcpy2DAsync_v2", unsafe { (self.c2d)(descriptor, stream as *mut c_void) }) + } + pub(crate) fn copy_host(&self, dst: u64, source: &[u8], stream: usize) -> Result<()> { + if dst == 0 || source.is_empty() || stream == 0 { + return Err(Error::InvalidSize); + } + // SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the + // driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is + // drained, so even a pinned-source (fully asynchronous) copy would read valid memory. + check("cuMemcpyHtoDAsync_v2", unsafe { + (self.h2d)(dst, source.as_ptr().cast(), source.len(), stream as *mut c_void) + }) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + if let Some(m) = self.module.take() { + // SAFETY: the handle was loaded by this owner and is taken (Option::take) so it is unloaded at most once; on failure the + // library is forgotten so the stored fn pointers stay valid. Callers drain the stream first; unload is not a fence. + let r = check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) }); + if r.is_err() + && let Some(l) = self.library.take() + { + std::mem::forget(l); + } + r + } else { + Ok(()) + } + } +} +impl Drop for Module { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_forward.rs b/crates/cuda-driver/src/mtp_original_full_forward.rs index c8fbe20e..f8d4a13a 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward.rs @@ -44,9 +44,7 @@ pub struct OriginalMtpRetainedPrefix<'ctx> { embedding: PrefixEmbedding<'ctx>, } enum PrefixEmbedding<'ctx> { - Device { - bank: Rc>, - }, + Device { bank: Rc> }, Native(OriginalMtpNativeEmbedding<'ctx>), } /// Fixed actual role order is documented in CONTRACT. This owner retains actual @@ -159,10 +157,8 @@ pub use full_round::OriginalMtpDraftProgram; #[path = "mtp_original_session.rs"] mod session_coupling; -pub use session_coupling::{ - OriginalMtpRopeForm, OriginalMtpSessionPlan, OriginalMtpSessionResources, -}; pub(crate) use session_coupling::session_assets_sealed; +pub use session_coupling::{OriginalMtpRopeForm, OriginalMtpSessionPlan, OriginalMtpSessionResources}; #[cfg(test)] mod role_map_tests { @@ -246,35 +242,35 @@ mod role_map_tests { } } -#[path = "mtp_original_full_forward/impl_originalmtpretainedprefix.rs"] -mod impl_originalmtpretainedprefix; -#[path = "mtp_original_full_forward/impl_fullowned.rs"] -mod impl_fullowned; #[path = "mtp_original_full_forward/impl_context.rs"] mod impl_context; +#[path = "mtp_original_full_forward/impl_fullowned.rs"] +mod impl_fullowned; #[path = "mtp_original_full_forward/impl_originalmtpfullforward.rs"] mod impl_originalmtpfullforward; +#[path = "mtp_original_full_forward/impl_originalmtpretainedprefix.rs"] +mod impl_originalmtpretainedprefix; #[path = "mtp_original_full_forward/validate_scalar_prefix_fn.rs"] mod validate_scalar_prefix_fn; #[allow(unused_imports)] -use validate_scalar_prefix_fn::validate_scalar_prefix; -#[allow(unused_imports)] -use validate_scalar_prefix_fn::push; +use validate_scalar_prefix_fn::chain_mtp_assets; #[allow(unused_imports)] use validate_scalar_prefix_fn::daily_mtp; #[allow(unused_imports)] -use validate_scalar_prefix_fn::chain_mtp_assets; -#[allow(unused_imports)] use validate_scalar_prefix_fn::fixed_entry; #[allow(unused_imports)] use validate_scalar_prefix_fn::mmvf_block; -#[path = "mtp_original_full_forward/impl_originalmtpfullforward_2.rs"] -mod impl_originalmtpfullforward_2; -#[path = "mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs"] -mod impl_crate_original_gpu_schedule_resources; -#[path = "mtp_original_full_forward/impl_originalmtpfullforward_3.rs"] -mod impl_originalmtpfullforward_3; -#[path = "mtp_original_full_forward/impl_originalmtpforwardprogram.rs"] -mod impl_originalmtpforwardprogram; +#[allow(unused_imports)] +use validate_scalar_prefix_fn::push; +#[allow(unused_imports)] +use validate_scalar_prefix_fn::validate_scalar_prefix; #[path = "mtp_original_full_forward/impl_context_2.rs"] mod impl_context_2; +#[path = "mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs"] +mod impl_crate_original_gpu_schedule_resources; +#[path = "mtp_original_full_forward/impl_originalmtpforwardprogram.rs"] +mod impl_originalmtpforwardprogram; +#[path = "mtp_original_full_forward/impl_originalmtpfullforward_2.rs"] +mod impl_originalmtpfullforward_2; +#[path = "mtp_original_full_forward/impl_originalmtpfullforward_3.rs"] +mod impl_originalmtpfullforward_3; diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_context_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_context_2.rs index 7045dcee..879a9f0b 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_context_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_context_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> Context<'ctx> { /// Exact supported Original arena/mapped layout shared by both producers. /// Existing constructors retain their old storage policy. Both returned owners @@ -24,22 +23,15 @@ impl<'ctx> Context<'ctx> { .ok_or(Error::InvalidSize)?; let charge = extras .iter() - .try_fold( - layout - .bytes - .checked_add(scalar) - .ok_or(Error::BudgetExceeded)?, - |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded), - )? + .try_fold(layout.bytes.checked_add(scalar).ok_or(Error::BudgetExceeded)?, |sum, n| { + sum.checked_add(*n).ok_or(Error::BudgetExceeded) + })? .checked_add(RESERVE_BYTES) .ok_or(Error::BudgetExceeded)?; if self.is_poisoned() { return Err(Error::ContextPoisoned); } - if self - .allocated_bytes() - .checked_add(charge) - .is_none_or(|n| n > self.budget_bytes()) + if self.allocated_bytes().checked_add(charge).is_none_or(|n| n > self.budget_bytes()) || self.memory_info()?.0 < charge { return Err(Error::BudgetExceeded); @@ -74,10 +66,9 @@ impl<'ctx> Context<'ctx> { let scalar = OriginalMtpScalarPrefill::planned_device_bytes(max_t, prompt_cap)? .checked_sub(Scratch::new(max_t)?.bytes) .ok_or(Error::InvalidSize)?; - extra.iter().try_fold( - l.bytes.checked_add(scalar).ok_or(Error::InvalidSize)?, - |a, n| a.checked_add(*n).ok_or(Error::InvalidSize), - ) + extra.iter().try_fold(l.bytes.checked_add(scalar).ok_or(Error::InvalidSize)?, |a, n| { + a.checked_add(*n).ok_or(Error::InvalidSize) + }) } pub fn original_mtp_shared_layout_pinned_bytes(max_t: usize, coupled: bool) -> Result { physical_layout::Records::planned_bytes(max_t, coupled) @@ -93,11 +84,7 @@ impl<'ctx> Context<'ctx> { max_t: usize, prompt_cap: usize, coupled: bool, - ) -> Result<( - MtpOriginalInt8<'ctx>, - OriginalMtpScalarPrefill<'ctx>, - OriginalMtpFullForward<'ctx>, - )> { + ) -> Result<(MtpOriginalInt8<'ctx>, OriginalMtpScalarPrefill<'ctx>, OriginalMtpFullForward<'ctx>)> { // State/pinned initialization precedes the main arena exactly as MtpDrafter::init. OriginalMtpScalarPrefill::assets_ready()?; for ptx in [ @@ -109,23 +96,16 @@ impl<'ctx> Context<'ctx> { return Err(Error::UnsupportedQwenOperation); } } - if symbols::ASSETS - .iter() - .any(|(p, _)| p.windows(8).any(|w| w == b"UNSEALED")) - { + if symbols::ASSETS.iter().any(|(p, _)| p.windows(8).any(|w| w == b"UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } weights.validate_context(self)?; let mut prepared = ring_state::PreparedState::new(self, max_t)?; - let (scalar, full) = - match self.original_mtp_shared_layout(weights, max_t, prompt_cap, coupled) { - Ok(pair) => pair, - Err(primary) => return combine(Err(primary), prepared.close()), - }; - let l = scalar - .original_layout - .as_ref() - .ok_or(Error::InvalidQwenShape)?; + let (scalar, full) = match self.original_mtp_shared_layout(weights, max_t, prompt_cap, coupled) { + Ok(pair) => pair, + Err(primary) => return combine(Err(primary), prepared.close()), + }; + let l = scalar.original_layout.as_ref().ok_or(Error::InvalidQwenShape)?; let bank = Rc::clone(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?); let spans = [ (l.offsets[19], l.sizes[19]), diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs index 3e1beb28..3f25e4d9 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_crate_original_gpu_schedule_resources.rs @@ -11,19 +11,10 @@ impl OriginalGraphResources for OriginalMtpForwardProgram<'_> { } self.tail.validate(c)?; self.ring.validate_context(c)?; - for b in [ - &self.prefix_scratch, - &self.prefix_status, - &self.prefix_records, - ] { + for b in [&self.prefix_scratch, &self.prefix_status, &self.prefix_records] { checked(c, b, b.bytes)?; } - if self - .prefix_mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none() - { + if self.prefix_mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none() { return Err(Error::ContextPoisoned); } Ok(()) diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_fullowned.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_fullowned.rs index 165cf8ef..c0c1c4ef 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_fullowned.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_fullowned.rs @@ -13,11 +13,7 @@ impl FullOwned<'_> { } self.weights.validate_context(c)?; if let Some(l) = &self.original_layout { - checked( - c, - self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - l.bytes, - )?; + checked(c, self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, l.bytes)?; for (b, n) in self.extras.iter().zip(physical_layout::Layout::extra_sizes( self.weights.vocab, self.max_t, @@ -28,12 +24,7 @@ impl FullOwned<'_> { } } } - if self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none() - { + if self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none() { return Err(Error::ContextPoisoned); } Ok(()) @@ -55,28 +46,16 @@ impl FullOwned<'_> { _ => return Err(Error::UnsupportedQwenOperation), }; let b = self.extras[slot].as_ref().ok_or(Error::ContextPoisoned)?; - return b - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, 0, n); + return b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, 0, n); } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, self.layout.offsets[i], n) + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, self.layout.offsets[i], n) } pub(super) fn address(&self, i: usize) -> Result { Ok(self.handle(i)?.qwen_address()) } pub(super) fn combined(&self) -> Result { match &self.original_layout { - Some(l) => Ok(l - .span( - self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - 32, - 0, - 10240, - )? - .qwen_address()), + Some(l) => Ok(l.span(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, 32, 0, 10240)?.qwen_address()), None => self.address(24), } } @@ -108,9 +87,7 @@ impl FullOwned<'_> { .scratch .as_ref() .zip(scalar.scratch.as_ref()) - .is_some_and(|(a, b)| { - std::ptr::eq(Rc::as_ptr(a).cast::<()>(), Rc::as_ptr(b).cast::<()>()) - }) + .is_some_and(|(a, b)| std::ptr::eq(Rc::as_ptr(a).cast::<()>(), Rc::as_ptr(b).cast::<()>())) } pub(super) fn logits(&self) -> Result { if self.original_layout.is_some() { @@ -138,11 +115,7 @@ impl FullOwned<'_> { } pub(super) fn close(&mut self) -> Result<()> { self.failed.set(true); - let mut op = if self.context.is_poisoned() { - Err(Error::ContextPoisoned) - } else { - self.context.synchronize() - }; + let mut op = if self.context.is_poisoned() { Err(Error::ContextPoisoned) } else { self.context.synchronize() }; if op.is_err() { self.context.poison(); self.context.retain_driver(); @@ -153,12 +126,9 @@ impl FullOwned<'_> { Err(Error::ContextPoisoned) } else { match self.context.enter() { - Ok(g) => combine( - Rc::try_unwrap(m) - .map_err(|_| Error::InvalidQwenShape) - .and_then(FM::close), - g.finish(), - ), + Ok(g) => { + combine(Rc::try_unwrap(m).map_err(|_| Error::InvalidQwenShape).and_then(FM::close), g.finish()) + } Err(e) => { self.context.poison(); std::mem::forget(m); diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs index 67f0eb37..780aa350 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpforwardprogram.rs @@ -13,14 +13,7 @@ impl OriginalMtpForwardProgram<'_> { if let Some(stage) = &mut self.coupled_stage { self.tail.modules[20].launch(1, [1, 1, 1], [256, 1, 1], 0, stream, stage)?; } - self.prefix_modules[0].launch( - 11, - [1, 1, 1], - [256, 1, 1], - 0, - stream, - &mut self.tail_reset, - )?; + self.prefix_modules[0].launch(11, [1, 1, 1], [256, 1, 1], 0, stream, &mut self.tail_reset)?; for (i, command) in self.prefix.iter_mut().enumerate() { if i == 1 && let Some(e) = &mut self.native_embedding @@ -28,15 +21,9 @@ impl OriginalMtpForwardProgram<'_> { e.capture(capture)?; } match command { - ScalarCommand::Kernel { - asset, - index, - grid, - block, - shared, - args, - } => self.prefix_modules[*asset] - .launch(*index, *grid, *block, *shared, stream, args)?, + ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { + self.prefix_modules[*asset].launch(*index, *grid, *block, *shared, stream, args)? + } ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape), } } @@ -47,10 +34,14 @@ impl OriginalMtpForwardProgram<'_> { self.tail.modules[13].copy2d(&self.split, stream)?; } if (command.asset == 19 || command.asset == symbols::DAILY_ASSET) && command.index == 0 { - self.ring.physical.modules[1] - .as_ref() - .ok_or(Error::ContextPoisoned)? - .launch(2, [8, 1, 1], [256, 1, 1], 0, stream, &mut self.window)?; + self.ring.physical.modules[1].as_ref().ok_or(Error::ContextPoisoned)?.launch( + 2, + [8, 1, 1], + [256, 1, 1], + 0, + stream, + &mut self.window, + )?; } self.tail.modules[command.asset].launch( command.index, @@ -66,10 +57,7 @@ impl OriginalMtpForwardProgram<'_> { pub fn metadata_bytes(&self) -> Result { let mut n = self.window.metadata_bytes() + self.tail_reset.metadata_bytes() - + self - .native_embedding - .as_ref() - .map_or(0, OriginalMtpNativeGather::metadata_bytes) + + self.native_embedding.as_ref().map_or(0, OriginalMtpNativeGather::metadata_bytes) + self.coupled_stage.as_ref().map_or(0, FA::metadata_bytes) + std::mem::size_of::() + self.prefix.capacity() * std::mem::size_of::() @@ -77,15 +65,11 @@ impl OriginalMtpForwardProgram<'_> { + std::mem::size_of::(); for command in &self.prefix { if let ScalarCommand::Kernel { args, .. } = command { - n = n - .checked_add(args.metadata_bytes()) - .ok_or(Error::BudgetExceeded)?; + n = n.checked_add(args.metadata_bytes()).ok_or(Error::BudgetExceeded)?; } } for command in &self.tail_commands { - n = n - .checked_add(command.args.metadata_bytes()) - .ok_or(Error::BudgetExceeded)?; + n = n.checked_add(command.args.metadata_bytes()).ok_or(Error::BudgetExceeded)?; } Ok(n) } @@ -103,10 +87,11 @@ impl OriginalMtpForwardProgram<'_> { })?; let copies = (|| { self.context.driver.api.copy_to( - self.prefix_status - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.prefix_status.bytes, 0, 64)?, + self.prefix_status.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + self.prefix_status.bytes, + 0, + 64, + )?, &mut prefix, )?; self.context.driver.api.copy_to(h, &mut flags) @@ -129,11 +114,7 @@ impl OriginalMtpForwardProgram<'_> { } pub(crate) fn output_after_actual_drain(&self) -> Result { self.validate_flags_after_actual_drain()?; - let mapped_borrow = self - .tail - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?; + let mapped_borrow = self.tail.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; let mapped = mapped_borrow.as_ref().ok_or(Error::ContextPoisoned)?; let mut id = [0u8; 4]; let mut probability = [0u8; 4]; @@ -163,21 +144,14 @@ impl OriginalMtpForwardProgram<'_> { if !self.tail.coupled { return Err(Error::InvalidQwenShape); } - if history - .iter() - .any(|id| *id < -1 || *id >= 0 && *id as usize >= self.tail.weights.id_vocab) - { + if history.iter().any(|id| *id < -1 || *id >= 0 && *id as usize >= self.tail.weights.id_vocab) { return Err(Error::InvalidQwenShape); } let mut bytes = [0u8; 4096 * 4]; for (i, id) in history.iter().enumerate() { bytes[i * 4..i * 4 + 4].copy_from_slice(&id.to_le_bytes()); } - let mut borrow = self - .tail - .mapped - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?; + let mut borrow = self.tail.mapped.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; let mapped = borrow.as_mut().ok_or(Error::ContextPoisoned)?; let base = self.tail.max_t * 236 + 384; mapped.write(base, ¶ms.bytes())?; diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward.rs index a262a7ab..1b02472e 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward.rs @@ -29,33 +29,18 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { if !(1..=8).contains(&max_t) { return Err(Error::InvalidQwenShape); } - if symbols::ASSETS - .iter() - .any(|(p, _)| p.windows(8).any(|w| w == b"UNSEALED")) - { + if symbols::ASSETS.iter().any(|(p, _)| p.windows(8).any(|w| w == b"UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } let layout = TailLayout::new(weights.vocab, max_t, coupled)?; - let original_layout = if original { - Some(physical_layout::Layout::new(max_t)?) - } else { - None - }; + let original_layout = if original { Some(physical_layout::Layout::new(max_t)?) } else { None }; let sizes = physical_layout::Layout::extra_sizes(weights.vocab, max_t, coupled)?; let own_bytes = match &original_layout { - Some(l) => sizes - .iter() - .try_fold(l.bytes, |a, n| a.checked_add(*n).ok_or(Error::InvalidSize))?, + Some(l) => sizes.iter().try_fold(l.bytes, |a, n| a.checked_add(*n).ok_or(Error::InvalidSize))?, None => layout.bytes, }; - let charge = own_bytes - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(charge) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < charge - { + let charge = own_bytes.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes().checked_add(charge).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < charge { return Err(Error::BudgetExceeded); } let mut o = FullOwned { @@ -72,9 +57,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { coupled, source: RefCell::new(None), }; - o.modules - .try_reserve_exact(symbols::ASSETS.len()) - .map_err(|_| Error::HostAllocation)?; + o.modules.try_reserve_exact(symbols::ASSETS.len()).map_err(|_| Error::HostAllocation)?; let op = (|| { let g = c.enter().inspect_err(|_| { c.poison(); @@ -142,13 +125,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { c.retain_driver(); } *o.mapped.get_mut() = Some(mapped?); - o.scratch = Some(Rc::new( - c.allocate( - o.original_layout - .as_ref() - .map_or(o.layout.bytes, |l| l.bytes), - )?, - )); + o.scratch = Some(Rc::new(c.allocate(o.original_layout.as_ref().map_or(o.layout.bytes, |l| l.bytes))?)); if original { for (i, n) in sizes.into_iter().enumerate() { if n != 0 { @@ -172,9 +149,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { .handle .ok_or(Error::ContextPoisoned)? .qwen_address(), - o.original_layout - .as_ref() - .map_or(o.layout.bytes, |l| l.bytes), + o.original_layout.as_ref().map_or(o.layout.bytes, |l| l.bytes), ) .and_then(|()| c.driver.api.synchronize()); let pop = g.finish(); @@ -185,8 +160,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { combine(zero, pop)?; if let Some(l) = &o.original_layout { let mut ids = Vec::new(); - ids.try_reserve_exact(l.t * l.cap * 4) - .map_err(|_| Error::HostAllocation)?; + ids.try_reserve_exact(l.t * l.cap * 4).map_err(|_| Error::HostAllocation)?; for _ in 0..l.t { for i in 0..l.cap { ids.extend_from_slice(&(i as i32).to_le_bytes()); @@ -205,23 +179,12 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { } pub fn allocated_bytes(&self) -> usize { self.inner.scratch.as_ref().map_or(0, |b| b.bytes) - + self - .inner - .extras - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() + + self.inner.extras.iter().flatten().map(|b| b.bytes).sum::() } pub fn metadata_bytes(&self) -> usize { std::mem::size_of::>() + self.inner.modules.capacity() * std::mem::size_of::>() - + self - .inner - .modules - .iter() - .map(|m| m.metadata_bytes()) - .sum::() + + self.inner.modules.iter().map(|m| m.metadata_bytes()).sum::() + self .inner .source @@ -237,8 +200,6 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { self.inner.failed.get() || self.inner.context.is_poisoned() } pub fn close(self) -> Result<()> { - Rc::try_unwrap(self.inner) - .map_err(|_| Error::InvalidQwenShape)? - .close() + Rc::try_unwrap(self.inner).map_err(|_| Error::InvalidQwenShape)?.close() } } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs index a4ec884e..3e71412d 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl OriginalMtpFullForward<'_> { pub(in super::super) fn plan( &self, @@ -18,16 +17,10 @@ impl OriginalMtpFullForward<'_> { } let o = &self.inner; let w = &o.weights; - let wa = |i: usize| -> Result { - Ok(w.roles[i] - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address()) - }; + let wa = |i: usize| -> Result { Ok(w.roles[i].handle.ok_or(Error::ContextPoisoned)?.qwen_address()) }; let a = |i| o.address(i); let mut v = Vec::new(); - v.try_reserve_exact(110) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(110).map_err(|_| Error::HostAllocation)?; // Prefix quantized mixed remains live: Q uses same Q8 image as K and V. // Original Q split is 24 distinct width256 rows, equivalent to its 2D D2D. let qfull = a(0)?; @@ -47,13 +40,7 @@ impl OriginalMtpFullForward<'_> { [12288, 1, 1], [32, 4, 1], 0, - vec![ - F::U64(qweight), - F::U64(p.q), - F::U64(qfull), - F::I32(2560), - F::I32(12288), - ], + vec![F::U64(qweight), F::U64(p.q), F::U64(qfull), F::I32(2560), F::I32(12288)], )?; self.finite_tail(&mut v, qfull, 12288, 0)?; // Copy commands remain distinct byte transports (24 literal rows); their @@ -66,13 +53,7 @@ impl OriginalMtpFullForward<'_> { [24, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(qcur), - F::U64(wa(1)?), - F::U64(qcur), - F::I32(256), - F::F32(1e-6), - ], + vec![F::U64(qcur), F::U64(wa(1)?), F::U64(qcur), F::I32(256), F::F32(1e-6)], )?; self.finite_tail(&mut v, qcur, 6144, 1)?; let kv = &policy.kv; @@ -170,8 +151,20 @@ impl OriginalMtpFullForward<'_> { } push( &mut v, - if daily { symbols::DAILY_ASSET } else if chain_mtp { symbols::CHAIN_ASSET } else { 19 }, - if daily { symbols::DAILY_MERGE_V2 } else if chain_mtp { symbols::CHAIN_QSA_MERGE_N } else { 1 }, + if daily { + symbols::DAILY_ASSET + } else if chain_mtp { + symbols::CHAIN_ASSET + } else { + 19 + }, + if daily { + symbols::DAILY_MERGE_V2 + } else if chain_mtp { + symbols::CHAIN_QSA_MERGE_N + } else { + 1 + }, [24, 1, 1], [256, 1, 1], 0, @@ -185,13 +178,7 @@ impl OriginalMtpFullForward<'_> { [24, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(attn), - F::U64(qfull), - F::U64(gated), - F::I32(24), - F::I32(256), - ], + vec![F::U64(attn), F::U64(qfull), F::U64(gated), F::I32(24), F::I32(256)], )?; self.finite_tail(&mut v, gated, 6144, 4)?; self.quant(&mut v, gated, p.q, 6144)?; @@ -200,12 +187,7 @@ impl OriginalMtpFullForward<'_> { self.finite_tail(&mut v, bo, 2560, 6)?; self.mlp_gr(&mut v, p, bo, policy)?; self.finite_tail(&mut v, p.r, 10240, 7)?; - self.finite_tail( - &mut v, - p.scalar.address(7, p.scalar.max_t * 40960)?, - 10240, - 8, - )?; + self.finite_tail(&mut v, p.scalar.address(7, p.scalar.max_t * 40960)?, 10240, 8)?; self.finite_tail(&mut v, p.scalar.address(8, p.scalar.max_t * 1280)?, 320, 9)?; self.finite_tail(&mut v, a(20)?, 4, 10)?; self.finite_tail(&mut v, p.mixed, 2560, 11)?; @@ -213,15 +195,7 @@ impl OriginalMtpFullForward<'_> { self.mmvf(&mut v, p.mixed, wa(7)?, router, 2560, 512)?; self.finite_tail(&mut v, router, 512, 12)?; if policy.native_router { - push( - &mut v, - 3, - 0, - [1, 1, 1], - [32, 8, 1], - 0, - vec![F::U64(router), F::U64(a(7)?), F::U64(a(6)?)], - )?; + push(&mut v, 3, 0, [1, 1, 1], [32, 8, 1], 0, vec![F::U64(router), F::U64(a(7)?), F::U64(a(6)?)])?; } else { push( &mut v, @@ -230,22 +204,11 @@ impl OriginalMtpFullForward<'_> { [1, 1, 1], [512, 1, 1], (512 + 512 * 8 + 512 * 4) as u32, - vec![ - F::U64(router), - F::I32(1), - F::I32(512), - F::I32(10), - F::U64(a(7)?), - F::U64(a(6)?), - ], + vec![F::U64(router), F::I32(1), F::I32(512), F::I32(10), F::U64(a(7)?), F::U64(a(6)?)], )?; } self.finite_tail(&mut v, a(6)?, 10, 13)?; - let expert = w - .experts - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); + let expert = w.experts.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); push( &mut v, 0, @@ -297,15 +260,7 @@ impl OriginalMtpFullForward<'_> { ], )?; self.finite_tail(&mut v, s2, 12800, 14)?; - push( - &mut v, - 0, - 3, - [6400usize.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(s2), F::I64(6400)], - )?; + push(&mut v, 0, 3, [6400usize.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, vec![F::U64(s2), F::I64(6400)])?; self.finite_tail(&mut v, s2, 6400, 15)?; push( &mut v, @@ -335,15 +290,7 @@ impl OriginalMtpFullForward<'_> { )?; self.finite_tail(&mut v, a(9)?, 25600, 16)?; // Shared projection consumes original mixed, not its unconditional BF16 image. - push( - &mut v, - 10, - 0, - [10, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(p.mixed), F::U64(a(23)?), F::I64(2560)], - )?; + push(&mut v, 10, 0, [10, 1, 1], [256, 1, 1], 0, vec![F::U64(p.mixed), F::U64(a(23)?), F::I64(2560)])?; self.quant(&mut v, p.mixed, p.q, 2560)?; self.q8_tail(&mut v, p.q, 2560, 17)?; self.mmvq(&mut v, wa(8)?, p.q, a(18)?, 2560, 640)?; @@ -375,31 +322,13 @@ impl OriginalMtpFullForward<'_> { [1, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(a(23)?), - F::U64(wa(11)?), - F::U64(a(22)?), - F::I32(2560), - ], + vec![F::U64(a(23)?), F::U64(wa(11)?), F::U64(a(22)?), F::I32(2560)], )?; } self.finite_tail(&mut v, a(22)?, 1, 23)?; - push( - &mut v, - 2, - 3, - [20, 1, 1], - [128, 1, 1], - 0, - vec![F::U64(a(11)?), F::U64(a(22)?), F::I32(2560)], - )?; + push(&mut v, 2, 3, [20, 1, 1], [128, 1, 1], 0, vec![F::U64(a(11)?), F::U64(a(22)?), F::I32(2560)])?; self.finite_tail(&mut v, a(11)?, 2560, 24)?; - let mut combine_args = vec![ - F::U64(a(9)?), - F::U64(a(6)?), - F::U64(a(11)?), - F::U64(o.combined()?), - ]; + let mut combine_args = vec![F::U64(a(9)?), F::U64(a(6)?), F::U64(a(11)?), F::U64(o.combined()?)]; if policy.native_combine { combine_args.extend([F::I64(2560), F::I32(10)]); } else { @@ -441,14 +370,7 @@ impl OriginalMtpFullForward<'_> { [40, 1, 1], [256, 1, 1], 16, - vec![ - F::U64(p.r), - F::U64(o.combined()?), - F::U64(a(20)?), - F::I32(2560), - F::I32(4), - F::U64(p.r), - ], + vec![F::U64(p.r), F::U64(o.combined()?), F::U64(a(20)?), F::I32(2560), F::I32(4), F::U64(p.r)], )?; } self.finite_tail(&mut v, p.r, 10240, 26)?; @@ -456,24 +378,14 @@ impl OriginalMtpFullForward<'_> { self.finite_tail(&mut v, a(24)?, 2560, 27)?; self.quant(&mut v, a(24)?, p.q, 2560)?; self.q8_tail(&mut v, p.q, 2560, 28)?; - let (name, grid, block, iq) = - head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?; + let (name, grid, block, iq) = head_dispatch::head_dispatch(w.head_kind, 2560, w.vocab, 1, w.dispatch)?; let asset = if iq { 14 } else { 13 }; let index = fixed_entry(asset, name)?; - let mut args = vec![F::U64( - w.head.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), - )]; + let mut args = vec![F::U64(w.head.handle.ok_or(Error::ContextPoisoned)?.qwen_address())]; if iq { - args.push(F::U64( - crate::native_head_row_bytes(w.head_kind, 2560)? as u64 - )); + args.push(F::U64(crate::native_head_row_bytes(w.head_kind, 2560)? as u64)); } - args.extend([ - F::U64(p.q), - F::U64(o.logits()?), - F::I32(2560), - F::I32(w.vocab as i32), - ]); + args.extend([F::U64(p.q), F::U64(o.logits()?), F::I32(2560), F::I32(w.vocab as i32)]); if iq { args.push(F::I32(1)); } @@ -488,21 +400,13 @@ impl OriginalMtpFullForward<'_> { let sub = w .subset .as_ref() - .map(|(f, _)| { - f.handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }) + .map(|(f, _)| f.handle.ok_or(Error::ContextPoisoned).map(|h| h.qwen_address())) .transpose()? .unwrap_or(0); let inv = w .subset .as_ref() - .map(|(_, i)| { - i.handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }) + .map(|(_, i)| i.handle.ok_or(Error::ContextPoisoned).map(|h| h.qwen_address())) .transpose()? .unwrap_or(0); push( @@ -593,12 +497,7 @@ impl OriginalMtpFullForward<'_> { [1, 1, 1], [1024, 1, 1], 0, - vec![ - F::U64(o.logits()?), - F::I32(w.vocab as i32), - F::U64(o.address(34)?), - F::U64(o.address(35)?), - ], + vec![F::U64(o.logits()?), F::I32(w.vocab as i32), F::U64(o.address(34)?), F::U64(o.address(35)?)], )?; if let Some((forward, _)) = &w.subset { push( diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs index c971b43d..417fcc98 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl OriginalMtpFullForward<'_> { pub(in super::super) fn finite_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { if slot >= TAIL_FLAGS || n == 0 || n > i32::MAX as usize { @@ -16,11 +15,7 @@ impl OriginalMtpFullForward<'_> { [n.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(x), - F::I32(n as i32), - F::U64(self.inner.address(27)? + (slot * 4) as u64), - ], + vec![F::U64(x), F::I32(n as i32), F::U64(self.inner.address(27)? + (slot * 4) as u64)], ) } pub(in super::super) fn q8_tail(&self, v: &mut Vec, x: u64, n: usize, slot: usize) -> Result<()> { @@ -34,11 +29,7 @@ impl OriginalMtpFullForward<'_> { [(n / 32).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(x), - F::I32((n / 32) as i32), - F::U64(self.inner.address(27)? + (slot * 4) as u64), - ], + vec![F::U64(x), F::I32((n / 32) as i32), F::U64(self.inner.address(27)? + (slot * 4) as u64)], ) } pub(in super::super) fn quant(&self, v: &mut Vec, x: u64, q: u64, n: usize) -> Result<()> { @@ -61,8 +52,7 @@ impl OriginalMtpFullForward<'_> { n: usize, out: usize, ) -> Result<()> { - let (name, grid, block, _) = - head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?; + let (name, grid, block, _) = head_dispatch::head_dispatch(8, n, out, 1, NativeHeadDispatch::default())?; push( v, 13, @@ -70,13 +60,7 @@ impl OriginalMtpFullForward<'_> { grid, block, 0, - vec![ - F::U64(w), - F::U64(q), - F::U64(y), - F::I32(n as i32), - F::I32(out as i32), - ], + vec![F::U64(w), F::U64(q), F::U64(y), F::I32(n as i32), F::I32(out as i32)], ) } pub(in super::super) fn mmvf( @@ -107,11 +91,7 @@ impl OriginalMtpFullForward<'_> { policy: &OriginalMtpFullPolicy, ) -> Result<()> { let w = &self.inner.weights.roles; - let wa = |i: usize| { - w[i].handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }; + let wa = |i: usize| w[i].handle.ok_or(Error::ContextPoisoned).map(|h| h.qwen_address()); let s = p.scalar; let xn = s.address(7, s.max_t * 40960)?; let mut words = Box::new([0u64; 114]); @@ -140,29 +120,13 @@ impl OriginalMtpFullForward<'_> { push( v, 17, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - 1, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], + if policy.gr == OriginalMtpGrVariant::Plain { 0 } else { 1 }, + [1, if policy.gr == OriginalMtpGrVariant::Plain { 1 } else { 4 }, 1], [256, 1, 1], 0, vec![make()], )?; - let bytes = if policy.gr == OriginalMtpGrVariant::Staged { - 10240 - } else { - s.plain_tile * 4 - }; + let bytes = if policy.gr == OriginalMtpGrVariant::Staged { 10240 } else { s.plain_tile * 4 }; if s.shared_limit < bytes { return Err(Error::InvalidProjectionShape); } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs index 05ac92da..5afea82f 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_2/impl_originalmtpfullforward_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl OriginalMtpFullForward<'_> { pub(in super::super) fn final_gr( &self, @@ -13,11 +12,7 @@ impl OriginalMtpFullForward<'_> { ) -> Result<()> { let a = |i| self.inner.address(i); let w = &self.inner.weights.roles; - let wa = |i: usize| { - w[i].handle - .ok_or(Error::ContextPoisoned) - .map(|h| h.qwen_address()) - }; + let wa = |i: usize| w[i].handle.ok_or(Error::ContextPoisoned).map(|h| h.qwen_address()); let xn = p.scalar.address(7, p.scalar.max_t * 40960)?; let lo = p.scalar.address(8, p.scalar.max_t * 1280)?; if policy.native_final_gr { @@ -28,24 +23,10 @@ impl OriginalMtpFullForward<'_> { [4, 1, 1], [1024, 1, 1], 0, - vec![ - F::U64(p.r), - F::U64(wa(12)?), - F::U64(xn), - F::I32(2560), - F::F32(1e-6), - ], + vec![F::U64(p.r), F::U64(wa(12)?), F::U64(xn), F::I32(2560), F::F32(1e-6)], )?; self.mmvf(v, xn, wa(13)?, lo, 10240, 320)?; - push( - v, - 8, - 0, - [2, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(lo), F::I32(320), F::F32(0.25)], - )?; + push(v, 8, 0, [2, 1, 1], [256, 1, 1], 0, vec![F::U64(lo), F::I32(320), F::F32(0.25)])?; self.mmvf(v, lo, wa(14)?, a(25)?, 320, 10240)?; push( v, @@ -54,14 +35,7 @@ impl OriginalMtpFullForward<'_> { [10, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(xn), - F::U64(a(25)?), - F::U64(a(24)?), - F::I32(2560), - F::I32(4), - F::F32(0.25), - ], + vec![F::U64(xn), F::U64(a(25)?), F::U64(a(24)?), F::I32(2560), F::I32(4), F::F32(0.25)], )?; } else { let fp = policy.fp32_final_gr; @@ -72,14 +46,7 @@ impl OriginalMtpFullForward<'_> { [4, 1, 1], [256, 1, 1], 0, - vec![ - F::U64(p.r), - F::U64(wa(12)?), - F::F32(1e-6), - F::I32(2560), - F::U64(xn), - F::U64(a(25)?), - ], + vec![F::U64(p.r), F::U64(wa(12)?), F::F32(1e-6), F::I32(2560), F::U64(xn), F::U64(a(25)?)], )?; push( v, @@ -113,15 +80,7 @@ impl OriginalMtpFullForward<'_> { F::U64(a(25)?), ], )?; - push( - v, - 9, - 7, - [10, 1, 1], - [256, 1, 1], - 0, - vec![F::U64(a(25)?), F::I32(2560), F::I32(4), F::U64(a(24)?)], - )?; + push(v, 9, 7, [10, 1, 1], [256, 1, 1], 0, vec![F::U64(a(25)?), F::I32(2560), F::I32(4), F::U64(a(24)?)])?; } Ok(()) } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs index 5c163b1e..7dfdce46 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpFullForward<'ctx> { /// Builds the literal full=true T1 prefix with genuine retained model roles. /// The resulting graph resource owns all scratch, records, weights and ring; @@ -48,12 +47,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { 4 * 10240 * 2, ]; ring.validate_original_main(scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - let eh = scalar - .scratch - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; + let eh = scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; let mut wh = [eh; 11]; for i in 0..11 { checked(scalar.context, wr[i], extents[i])?; @@ -62,24 +56,13 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { for b in wr.into_iter().chain(embedding.as_ref().map(|e| e.table)) { ring.reject_state_alias(b)?; let h = b.handle.ok_or(Error::ContextPoisoned)?; - for output in [&scalar.scratch, &scalar.status, &scalar.records] - .into_iter() - .flatten() - { - if h.overlaps( - b.bytes, - output.handle.ok_or(Error::ContextPoisoned)?, - output.bytes, - ) { + for output in [&scalar.scratch, &scalar.status, &scalar.records].into_iter().flatten() { + if h.overlaps(b.bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) { return Err(Error::OutputAliasesInput); } } for output in ring.buffers()?.iter().flatten() { - if h.overlaps( - b.bytes, - output.handle.ok_or(Error::ContextPoisoned)?, - output.bytes, - ) { + if h.overlaps(b.bytes, output.handle.ok_or(Error::ContextPoisoned)?, output.bytes) { return Err(Error::OutputAliasesInput); } } @@ -133,8 +116,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { let pos = self.inner.address(32)? + (step_row * 96) as u64; let policy = &prefix_policy; let mut cmds = Vec::new(); - cmds.try_reserve_exact(128) - .map_err(|_| Error::HostAllocation)?; + cmds.try_reserve_exact(128).map_err(|_| Error::HostAllocation)?; OriginalMtpScalarPrefill::kernel( &mut cmds, 0, @@ -158,9 +140,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { if let Some(embedding) = embedding { let eh = embedding.table.handle.ok_or(Error::ContextPoisoned)?; match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => OriginalMtpScalarPrefill::kernel( + EmbeddingKind::Native { kind, row_bytes, .. } => OriginalMtpScalarPrefill::kernel( &mut cmds, 1, 0, @@ -176,39 +156,29 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { Arg::U64(emb), ], )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => OriginalMtpScalarPrefill::kernel( - &mut cmds, - 0, - 5, - [10, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(eh.qwen_address()), - Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), - Arg::U64(tok), - Arg::I64(2560), - Arg::I32(bits), - Arg::I32(bias), - Arg::I32(group as i32), - Arg::U64((2560 / (8 / bits)) as u64), - Arg::U64((2560 / group) as u64), - Arg::U64(emb), - ], - )?, + EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => { + OriginalMtpScalarPrefill::kernel( + &mut cmds, + 0, + 5, + [10, t as u32, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(eh.qwen_address()), + Arg::U64(eh.qwen_address() + codes as u64), + Arg::U64(if offsets { eh.qwen_address() + (codes + scales) as u64 } else { 0 }), + Arg::U64(tok), + Arg::I64(2560), + Arg::I32(bits), + Arg::I32(bias), + Arg::I32(group as i32), + Arg::U64((2560 / (8 / bits)) as u64), + Arg::U64((2560 / group) as u64), + Arg::U64(emb), + ], + )? + } } } scalar.finite(&mut cmds, emb, t * 2560, group, 0)?; @@ -219,13 +189,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { [t as u32, 1, 1], [1024, 1, 1], 0, - vec![ - Arg::U64(emb), - Arg::U64(wh[0].qwen_address()), - Arg::U64(en), - Arg::I32(2560), - Arg::F32(1e-6), - ], + vec![Arg::U64(emb), Arg::U64(wh[0].qwen_address()), Arg::U64(en), Arg::I32(2560), Arg::F32(1e-6)], )?; scalar.finite(&mut cmds, en, t * 2560, group, 1)?; let q = scalar.address(15, 8 * 80 * 36)?; @@ -240,13 +204,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { [t as u32, 1, 1], [1024, 1, 1], 0, - vec![ - Arg::U64(rin), - Arg::U64(wh[2].qwen_address()), - Arg::U64(hn), - Arg::I32(10240), - Arg::F32(1e-6), - ], + vec![Arg::U64(rin), Arg::U64(wh[2].qwen_address()), Arg::U64(hn), Arg::I32(10240), Arg::F32(1e-6)], )?; scalar.finite(&mut cmds, hn, t * 10240, group, 3)?; for hc in (0..t * 4).step_by(8) { @@ -270,24 +228,12 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { [40, t as u32, 1], [256, 1, 1], 0, - vec![ - Arg::U64(h2), - Arg::U64(e2), - Arg::U64(r), - Arg::I64(2560), - Arg::I32(4), - ], + vec![Arg::U64(h2), Arg::U64(e2), Arg::U64(r), Arg::I64(2560), Arg::I32(4)], )?; scalar.finite(&mut cmds, r, t * 10240, group, 5)?; scalar.gr(&mut cmds, t, &wh, policy)?; scalar.finite(&mut cmds, scalar.address(9, t * 16)?, t * 4, group, 6)?; - scalar.finite( - &mut cmds, - scalar.address(7, t * 40960)?, - t * 10240, - group, - 6, - )?; + scalar.finite(&mut cmds, scalar.address(7, t * 40960)?, t * 10240, group, 6)?; scalar.finite(&mut cmds, scalar.address(8, t * 1280)?, t * 320, group, 7)?; scalar.finite(&mut cmds, scalar.address(10, t * 16)?, t * 4, group, 7)?; scalar.finite(&mut cmds, mixed, t * 2560, group, 8)?; @@ -307,13 +253,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { [2, 1, 1], [256, 1, 1], 0, - vec![ - Arg::U64(k), - Arg::U64(wh[9].qwen_address()), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1e-6), - ], + vec![Arg::U64(k), Arg::U64(wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)], )?; scalar.finite(&mut cmds, k, 512, group, 12)?; OriginalMtpScalarPrefill::kernel( diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs index 5243c6a9..ec9184bc 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpfullforward_3/impl_originalmtpfullforward_2.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpFullForward<'ctx> { - // Called ONLY at scalar capture preparation, immediately after the genuine // prefix plan builder has emitted its real current step append commands. pub(in super::super::super) fn program( @@ -37,11 +35,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { scalar.records.as_ref().ok_or(Error::ContextPoisoned)?, ]) { - if sh.overlaps( - scratch.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { + if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { let genuine_shared = self.inner.shares_original(scalar) && Rc::ptr_eq(b, scalar.scratch.as_ref().ok_or(Error::ContextPoisoned)?); if !genuine_shared { @@ -70,30 +64,18 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { ]) { ring.reject_state_alias(b)?; - if h.overlaps( - extra.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { + if h.overlaps(extra.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { return Err(Error::OutputAliasesInput); } } for b in ring.buffers()?.iter().flatten() { - if h.overlaps( - extra.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { + if h.overlaps(extra.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { return Err(Error::OutputAliasesInput); } } } for b in ring.buffers()?.iter().flatten() { - if sh.overlaps( - scratch.bytes, - b.handle.ok_or(Error::ContextPoisoned)?, - b.bytes, - ) { + if sh.overlaps(scratch.bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.bytes) { return Err(Error::OutputAliasesInput); } } @@ -109,9 +91,7 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { }; let commands = self.plan(&p, policy)?; let mut modules = Vec::new(); - modules - .try_reserve_exact(6) - .map_err(|_| Error::HostAllocation)?; + modules.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; for m in &scalar.modules { modules.push(Rc::clone(m.as_ref().ok_or(Error::ContextPoisoned)?)); } @@ -144,15 +124,9 @@ impl<'ctx> OriginalMtpFullForward<'ctx> { tail: Rc::clone(&self.inner), prefix, tail_commands: commands, - split: Box::new(full_abi::Copy2D::q_split( - self.inner.address(0)?, - self.inner.address(1)?, - )), + split: Box::new(full_abi::Copy2D::q_split(self.inner.address(0)?, self.inner.address(1)?)), window, - tail_reset: Arguments::new(vec![ - Arg::U64(self.inner.address(27)?), - Arg::I32(TAIL_FLAGS as i32), - ])?, + tail_reset: Arguments::new(vec![Arg::U64(self.inner.address(27)?), Arg::I32(TAIL_FLAGS as i32)])?, native_embedding, coupled_stage, residual_offset: scalar.layout.offsets[1], diff --git a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpretainedprefix.rs b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpretainedprefix.rs index 5d4911b0..ed1bb0eb 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpretainedprefix.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/impl_originalmtpretainedprefix.rs @@ -18,11 +18,7 @@ impl<'ctx> OriginalMtpRetainedPrefix<'ctx> { embedding: OriginalMtpNativeEmbedding<'ctx>, ) -> Result { embedding.validate_context(context)?; - let result = Self { - context, - roles, - embedding: PrefixEmbedding::Native(embedding), - }; + let result = Self { context, roles, embedding: PrefixEmbedding::Native(embedding) }; result.validate_context(context)?; Ok(result) } @@ -94,9 +90,7 @@ impl<'ctx> OriginalMtpRetainedFullWeights<'ctx> { checked( c, &head, - crate::native_head_row_bytes(head_kind, 2560)? - .checked_mul(vocab) - .ok_or(Error::InvalidSize)?, + crate::native_head_row_bytes(head_kind, 2560)?.checked_mul(vocab).ok_or(Error::InvalidSize)?, )?; if let Some((forward, inverse)) = &subset { checked(c, forward, vocab * 4)?; @@ -111,32 +105,18 @@ impl<'ctx> OriginalMtpRetainedFullWeights<'ctx> { .chain([&experts, &head]) .chain(subset.iter().flat_map(|(a, b)| [a, b])); let mut seen: Vec<&DeviceBuffer<'ctx>> = Vec::new(); - seen.try_reserve_exact(30) - .map_err(|_| Error::HostAllocation)?; + seen.try_reserve_exact(30).map_err(|_| Error::HostAllocation)?; for b in all { let h = b.handle.ok_or(Error::ContextPoisoned)?; for a in &seen { let ah = a.handle.ok_or(Error::ContextPoisoned)?; - if h.overlaps(b.bytes, ah, a.bytes) - && !(h.qwen_address() == ah.qwen_address() && b.bytes == a.bytes) - { + if h.overlaps(b.bytes, ah, a.bytes) && !(h.qwen_address() == ah.qwen_address() && b.bytes == a.bytes) { return Err(Error::OutputAliasesInput); } } seen.push(b); } - Ok(Self { - context: c, - prefix, - roles, - experts, - head, - head_kind, - vocab, - id_vocab, - subset, - dispatch, - }) + Ok(Self { context: c, prefix, roles, experts, head, head_kind, vocab, id_vocab, subset, dispatch }) } pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { if !std::ptr::eq(c, self.context) { @@ -147,11 +127,7 @@ impl<'ctx> OriginalMtpRetainedFullWeights<'ctx> { checked(c, b, FULL_EXTENTS[i])?; } checked(c, &self.experts, 512 * 1382400)?; - checked( - c, - &self.head, - crate::native_head_row_bytes(self.head_kind, 2560)? * self.vocab, - )?; + checked(c, &self.head, crate::native_head_row_bytes(self.head_kind, 2560)? * self.vocab)?; Ok(()) } pub fn metadata_bytes(&self) -> usize { @@ -209,11 +185,7 @@ impl TailLayout { TAIL_FLAGS * 4, if coupled { 64 } else { 0 }, if coupled { (4096 + max_t) * 4 } else { 0 }, - if coupled { - vocab.div_ceil(4096) * 64 * 8 - } else { - 0 - }, + if coupled { vocab.div_ceil(4096) * 64 * 8 } else { 0 }, 2 * max_t * 16, 2 * max_t * 96, 16, @@ -226,13 +198,7 @@ impl TailLayout { offsets[i] = bytes; bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; } - bytes = bytes - .checked_add(aligned(vocab * 4)?) - .ok_or(Error::InvalidSize)?; - Ok(Self { - sizes, - offsets, - bytes, - }) + bytes = bytes.checked_add(aligned(vocab * 4)?).ok_or(Error::InvalidSize)?; + Ok(Self { sizes, offsets, bytes }) } } diff --git a/crates/cuda-driver/src/mtp_original_full_forward/validate_scalar_prefix_fn.rs b/crates/cuda-driver/src/mtp_original_full_forward/validate_scalar_prefix_fn.rs index f7030c6e..88b0b06d 100644 --- a/crates/cuda-driver/src/mtp_original_full_forward/validate_scalar_prefix_fn.rs +++ b/crates/cuda-driver/src/mtp_original_full_forward/validate_scalar_prefix_fn.rs @@ -7,8 +7,7 @@ use super::*; // owner. Prefix planning uses the same physical resources without requiring a // second stream; standalone scalar producer validation remains byte-exact. pub(super) fn validate_scalar_prefix(s: &OriginalMtpScalarPrefill<'_>) -> Result<()> { - if s.failed || s.context.is_poisoned() || s.modules.iter().any(Option::is_none) || s.has_pending - { + if s.failed || s.context.is_poisoned() || s.modules.iter().any(Option::is_none) || s.has_pending { return Err(Error::ContextPoisoned); } if s.stream.as_ref().is_some_and(OriginalGpuStream::is_failed) { @@ -17,10 +16,7 @@ pub(super) fn validate_scalar_prefix(s: &OriginalMtpScalarPrefill<'_>) -> Result for (b, n) in [ (&s.scratch, s.layout.bytes), (&s.records, s.prompt_cap * 29 * 4), - ( - &s.status, - (s.prompt_cap.div_ceil(s.max_t) + 1) * SCALAR_FLAGS * 4, - ), + (&s.status, (s.prompt_cap.div_ceil(s.max_t) + 1) * SCALAR_FLAGS * 4), ] { checked(s.context, b.as_ref().ok_or(Error::ContextPoisoned)?, n)?; } @@ -36,14 +32,7 @@ pub(super) fn push( args: Vec, ) -> Result<()> { v.try_reserve(1).map_err(|_| Error::HostAllocation)?; - v.push(FullCommand { - asset, - index, - grid, - block, - shared, - args: FA::new(args)?, - }); + v.push(FullCommand { asset, index, grid, block, shared, args: FA::new(args)? }); Ok(()) } /// `LELEKA_SM120_ATTN_DAILY_MTP=1` (opt-in, default off, untested on the real model): the MTP draft step's attention chunk and merge are upstream's diff --git a/crates/cuda-driver/src/mtp_original_full_graph.rs b/crates/cuda-driver/src/mtp_original_full_graph.rs index 37862372..d616b163 100644 --- a/crates/cuda-driver/src/mtp_original_full_graph.rs +++ b/crates/cuda-driver/src/mtp_original_full_graph.rs @@ -2,40 +2,24 @@ use super::*; use crate::{OriginalMtpForwardProgram, OriginalMtpStepOutput}; impl<'ctx> OriginalGpuGraph<'ctx, OriginalMtpForwardProgram<'ctx>> { - pub fn mtp_stage_coupled( - &mut self, - params: crate::SamplerParams, - history: &[i32; 4096], - ) -> Result<()> { + pub fn mtp_stage_coupled(&mut self, params: crate::SamplerParams, history: &[i32; 4096]) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .stage_coupled_after_actual_retirement(params, history) + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_coupled_after_actual_retirement(params, history) } - pub fn mtp_output_after_launch( - &mut self, - stream: &mut OriginalGpuStream<'ctx>, - ) -> Result { + pub fn mtp_output_after_launch(&mut self, stream: &mut OriginalGpuStream<'ctx>) -> Result { self.validate()?; stream.validate_context(self.context)?; - if !self.launched - || !self - .last - .as_ref() - .is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) - { + if !self.launched || !self.last.as_ref().is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) { return Err(Error::InvalidQwenShape); } let done = stream.synchronize_with_receipt()?; if !Rc::ptr_eq(&done.stream, &stream.inner) || done.sequence < self.last_sequence { return Err(Error::ContextMismatch); } - self.resources_after_stream_drain(&done)? - .output_after_actual_drain() + self.resources_after_stream_drain(&done)?.output_after_actual_drain() } } @@ -56,88 +40,52 @@ impl<'ctx> OriginalGpuGraph<'ctx, OriginalMtpDraftProgram<'ctx>> { return Err(Error::InvalidQwenShape); } let h = stream.inner.validate()?; - self.resources - .as_mut() - .ok_or(Error::ContextPoisoned)? - .stage_round(window, selection, a, h)?; - if !self - .resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .uses_direct_verifier_window() - { + self.resources.as_mut().ok_or(Error::ContextPoisoned)?.stage_round(window, selection, a, h)?; + if !self.resources.as_ref().ok_or(Error::ContextPoisoned)?.uses_direct_verifier_window() { let done = stream.synchronize_with_receipt()?; if !Rc::ptr_eq(&done.stream, &stream.inner) { return Err(Error::ContextMismatch); } } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .stage_completed() + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_completed() } pub(crate) fn mtp_stage_first_after_capture(&mut self) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .stage_first_after_capture() + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_first_after_capture() } pub(crate) fn mtp_stage_chain(&mut self) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .stage_chain() + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_chain() } - pub(crate) fn mtp_stage_sampling( - &mut self, - params: crate::SamplerParams, - history: &[i32; 4096], - ) -> Result<()> { + pub(crate) fn mtp_stage_sampling(&mut self, params: crate::SamplerParams, history: &[i32; 4096]) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .stage_sampling(params, history) + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.stage_sampling(params, history) } - pub(crate) fn mtp_finish_step( - &mut self, - stream: &mut OriginalGpuStream<'ctx>, - ) -> Result { + pub(crate) fn mtp_finish_step(&mut self, stream: &mut OriginalGpuStream<'ctx>) -> Result { self.validate()?; stream.validate_context(self.context)?; - if !self.launched - || !self - .last - .as_ref() - .is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) - { + if !self.launched || !self.last.as_ref().is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) { return Err(Error::InvalidQwenShape); } let done = stream.synchronize_with_receipt()?; if !Rc::ptr_eq(&done.stream, &stream.inner) || done.sequence < self.last_sequence { return Err(Error::ContextMismatch); } - self.resources_after_stream_drain(&done)? - .finish_after_drain() + self.resources_after_stream_drain(&done)?.finish_after_drain() } } impl OriginalGpuGraph<'_, OriginalMtpDraftProgram<'_>> { pub(crate) fn mtp_resource_metadata(&self) -> Result { self.validate()?; - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .metadata_bytes() + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.metadata_bytes() } } diff --git a/crates/cuda-driver/src/mtp_original_full_mapped.rs b/crates/cuda-driver/src/mtp_original_full_mapped.rs index bf5f953a..c18f8126 100644 --- a/crates/cuda-driver/src/mtp_original_full_mapped.rs +++ b/crates/cuda-driver/src/mtp_original_full_mapped.rs @@ -1,9 +1,5 @@ use crate::{Error, Result}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod mapped_enabled { use super::super::physical_layout::Records; use super::*; @@ -23,14 +19,7 @@ mod mapped_enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -60,9 +49,7 @@ mod mapped_enabled { let records = max_t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 }; let bytes = ((records + 255) & !255) + max_t * 40960; // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -76,24 +63,15 @@ mod mapped_enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - free, - bytes, - shared: None, - }; + let mut owner = + Self { library: Some(library), host: Some(ptr as usize), alias: 0, free, bytes, shared: None }; // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -107,11 +85,7 @@ mod mapped_enabled { pub(crate) fn original(max_t: usize, coupled: bool) -> Result { let mut owner = Self::new(max_t, coupled)?; let host = owner.host.ok_or(Error::ContextPoisoned)?; - owner.shared = Some(Rc::new(RefCell::new(Records::borrowed( - host, - owner.alias, - owner.bytes, - )?))); + owner.shared = Some(Rc::new(RefCell::new(Records::borrowed(host, owner.alias, owner.bytes)?))); Ok(owner) } pub(crate) fn shared_original(&self) -> Result>> { @@ -119,9 +93,7 @@ mod mapped_enabled { } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { let p = self.host.ok_or(Error::ContextPoisoned)?; @@ -151,11 +123,7 @@ mod mapped_enabled { } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { - if self - .shared - .as_ref() - .is_some_and(|shared| Rc::strong_count(shared) > 1) - { + if self.shared.as_ref().is_some_and(|shared| Rc::strong_count(shared) > 1) { return Err(Error::InvalidQwenShape); } // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every @@ -271,11 +239,7 @@ mod mapped_enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use mapped_enabled::MappedOwner; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mtp_original_full_round.rs b/crates/cuda-driver/src/mtp_original_full_round.rs index 283e31a6..0fd689d4 100644 --- a/crates/cuda-driver/src/mtp_original_full_round.rs +++ b/crates/cuda-driver/src/mtp_original_full_round.rs @@ -2,250 +2,98 @@ //! The mapped R window is a real owned SessionState-style staging allocation. //! VerifyWindow's device alias is never relabelled as mapped memory. use super::*; -use crate::{OriginalVerifyWindow,NativeHeadSelection}; +use crate::{NativeHeadSelection, OriginalVerifyWindow}; -pub(super) struct StagedSource<'ctx>{ - pub(super) window:Rc>, - pub(super) selection:NativeHeadSelection, - pub(super) accepted_row:usize, - pub(super) next_j:usize, - pub(super) ready:bool, - pub(super) rows:usize,first_repeat:bool, -} -impl StagedSource<'_>{fn validate(&self,c:&Context<'_>)->Result<()>{self.window.validate_context(c)?;self.window.validate_selection(&self.selection)?;if self.rows==0||self.rows>8||self.accepted_row>=self.rows||if self.first_repeat{self.window.rows()!=1||self.accepted_row!=0}else{self.rows!=self.window.rows()}{return Err(Error::InvalidQwenShape);}Ok(())}} -impl FullOwned<'_>{ - fn mapped_window_offset(&self)->usize{let records=self.max_t*236+384+if self.coupled{64+4096*4}else{0};(records+255)&!255} - fn validate_staged(&self,j:usize)->Result<()>{ - self.validate(self.context)?; - let source=self.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - let source=source.as_ref().ok_or(Error::InvalidQwenShape)?;source.validate(self.context)?; - if !source.ready||source.next_j!=j{return Err(Error::InvalidQwenShape);}Ok(()) - } +pub(super) struct StagedSource<'ctx> { + pub(super) window: Rc>, + pub(super) selection: NativeHeadSelection, + pub(super) accepted_row: usize, + pub(super) next_j: usize, + pub(super) ready: bool, + pub(super) rows: usize, + first_repeat: bool, } /// Private stable capture resources retain the actual verifier arena, sampled /// output receipt, whole model buffers, physical ring and all ABI storage. -pub struct OriginalMtpDraftProgram<'ctx>{ - program:OriginalMtpForwardProgram<'ctx>, - rows:usize,j:usize, - before:Vec,after:Vec,post:Vec, - catchup:Vec,catchup_embed:Option>, - coupled_stage:Option, - direct_window:Option>>, -} -impl crate::original_gpu_schedule::resources::Sealed for OriginalMtpDraftProgram<'_>{} -impl OriginalGraphResources for OriginalMtpDraftProgram<'_>{ - fn validate_context(&self,c:&Context<'_>)->Result<()>{self.program.validate_context(c)} - fn validate_replay_context(&self,c:&Context<'_>)->Result<()>{self.program.validate_context(c)?;self.program.tail.validate_staged(self.j)?;if self.j==0&&self.program.tail.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().is_none_or(|s|s.rows!=self.rows){return Err(Error::InvalidQwenShape);}Ok(())} -} -impl<'ctx> OriginalMtpFullForward<'ctx>{ - pub fn planned_pinned_host_bytes(max_t:usize,coupled:bool)->Result{if !(1..=8).contains(&max_t){return Err(Error::InvalidQwenShape);}let records=max_t*236+384+if coupled{64+4096*4}else{0};Ok(((records+255)&!255)+max_t*40960)} - /// Capture is prepared before mapped input writes, as in Original. Only real - /// stage_verify_window completion can subsequently authorize replay. - pub fn prepare_round(&self,scalar:&OriginalMtpScalarPrefill<'ctx>,ring:&MtpOriginalInt8<'ctx>,rows:usize,policy:&OriginalMtpFullPolicy)->Result>{ - if rows==0||rows>self.inner.max_t||scalar.max_t!=self.inner.max_t||policy.coupled_j.is_some_and(|j|j!=0){return Err(Error::InvalidQwenShape);} - let (catchup,catchup_embed)=self.prefix_commands(scalar,ring,policy,rows,0)?; - let ra=2*self.inner.max_t-1; - let(mut prefix,embedding)=self.prefix_commands(scalar,ring,policy,1,ra)?; - // One reset before catch-up; later flags OR into the same full-stage safety - // owner until the final actual drain. Never erase an earlier numerical fault. - if !matches!(prefix.first(),Some(ScalarCommand::Kernel{asset:0,index:11,..})){return Err(Error::InvalidQwenShape);}prefix.remove(0); - let mut program=self.program(scalar,ring,prefix,policy,embedding,ra)?; - let coupled_stage=program.coupled_stage.take(); - let mut before=Vec::new();let mut after=Vec::new();let o=&self.inner; - mapped_i32(&mut before,scalar.address(12,rows*4)?,o.mapped_address(0,rows*4)?,rows)?; - mapped_i32(&mut before,o.address(31)?,o.mapped_address(self.inner.max_t*4+64,rows*32)?,rows*8)?; - mapped_i32(&mut before,o.address(32)?,o.mapped_address(self.inner.max_t*36+128,rows*192)?,rows*48)?; - mapped_i32(&mut before,o.address(33)?,o.mapped_address(self.inner.max_t*228+192,8)?,2)?; - let n4=rows*10240/4;push(&mut before,10,1,[n4.div_ceil(256).min(64)as u32,1,1],[256,1,1],0,vec![F::U64(scalar.address(0,rows*40960)?),F::U64(o.mapped_address(o.mapped_window_offset(),rows*40960)?),F::I64(n4 as i64)])?; - // Selection and late full-step records execute AFTER real catch-up kernels. - mtp_select(&mut after,scalar.address(0,rows*40960)?,scalar.address(12,rows*4)?,o.address(33)?,scalar.address(0,40960)?,scalar.address(12,4)?,0,0,0,0)?; - mapped_i32(&mut after,o.address(31)?+(ra*16)as u64,o.mapped_address(self.inner.max_t*4+64+ra*16,16)?,4)?; - mapped_i32(&mut after,o.address(32)?+(ra*96)as u64,o.mapped_address(self.inner.max_t*36+128+ra*96,96)?,24)?; - let post=post_select(&program,0)?;Ok(OriginalMtpDraftProgram{program,rows,j:0,before,after,post,catchup,catchup_embed,coupled_stage,direct_window:None}) - } - pub fn prepare_step(&self,scalar:&OriginalMtpScalarPrefill<'ctx>,ring:&MtpOriginalInt8<'ctx>,j:usize,policy:&OriginalMtpFullPolicy)->Result>{ - if j==0||j>=self.inner.max_t-1||scalar.max_t!=self.inner.max_t||policy.coupled_j.is_some_and(|v|v as usize!=j){return Err(Error::InvalidQwenShape);} - let row=self.inner.max_t+j-1;let(prefix,embedding)=self.prefix_commands(scalar,ring,policy,1,row)?; - let program=self.program(scalar,ring,prefix,policy,embedding,row)?;let o=&self.inner;let mut before=Vec::new(); - mapped_i32(&mut before,o.address(31)?+(row*16)as u64,o.mapped_address(self.inner.max_t*4+64+row*16,16)?,4)?; - mapped_i32(&mut before,o.address(32)?+(row*96)as u64,o.mapped_address(self.inner.max_t*36+128+row*96,96)?,24)?; - let post=post_select(&program,j)?;Ok(OriginalMtpDraftProgram{program,rows:1,j,before,after:Vec::new(),post,catchup:Vec::new(),catchup_embed:None,coupled_stage:None,direct_window:None}) - } -} -fn mapped_i32(v:&mut Vec,dst:u64,src:u64,n:usize)->Result<()>{push(v,10,2,[1,1,1],[128,1,1],0,vec![F::U64(dst),F::U64(src),F::I32(n as i32)])} -#[allow(clippy::too_many_arguments)] -fn mtp_select(v:&mut Vec,r:u64,ids:u64,row:u64,rin:u64,tok:u64,out:u64,j:usize,prob:u64,outp:u64)->Result<()>{push(v,12,2,[16,1,1],[256,1,1],0,vec![F::U64(r),F::I64(10240),F::U64(ids),F::U64(row),F::U64(rin),F::U64(tok),F::U64(out),F::I32(j as i32),F::U64(prob),F::U64(outp)])} -fn post_select(p:&OriginalMtpForwardProgram<'_>,j:usize)->Result>{ - let mut v=Vec::new();mtp_select(&mut v,p.prefix_scratch.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(p.prefix_scratch.bytes,p.residual_offset,40960)?.qwen_address(),p.tail.address(34)?,p.tail.address(33)?+4,p.input_address,p.token_address,p.tail.mapped_address(p.tail.max_t*228+256,p.tail.max_t*4)?,j,p.tail.address(35)?,p.tail.mapped_address(p.tail.max_t*232+320,p.tail.max_t*4)?)?;Ok(v) -} -impl<'ctx> OriginalMtpDraftProgram<'ctx>{ - fn enqueue_commands(&mut self,c:&mut OriginalCapture<'_, '_>,which:bool)->Result<()>{let stream=c.stream_handle(self.program.context)?;let commands=if which{&mut self.before}else{&mut self.after};for command in commands{self.program.tail.modules[command.asset].launch(command.index,command.grid,command.block,command.shared,stream,&mut command.args)?;}Ok(())} - pub fn capture(&mut self,c:&mut OriginalCapture<'_, '_>)->Result<()>{ - self.validate_context(self.program.context)?;c.validate_context(self.program.context)?; - if let Some(window)=&self.direct_window{window.validate_context(self.program.context)?;} - let stream=c.stream_handle(self.program.context)?; - let result=(||{ - if let Some(stage)=&mut self.coupled_stage{self.program.tail.modules[20].launch(1,[1,1,1],[256,1,1],0,stream,stage)?;} - self.enqueue_commands(c,true)?; - for(i,cmd)in self.catchup.iter_mut().enumerate(){if i==1&&let Some(e)=&mut self.catchup_embed{e.capture(c)?;}match cmd{ScalarCommand::Kernel{asset,index,grid,block,shared,args}=>self.program.prefix_modules[*asset].launch(*index,*grid,*block,*shared,stream,args)?,ScalarCommand::Copy{..}=>return Err(Error::InvalidQwenShape)}} - self.enqueue_commands(c,false)?;self.program.capture(c)?; - let p=&self.program; - for command in &mut self.post{p.tail.modules[command.asset].launch(command.index,command.grid,command.block,command.shared,stream,&mut command.args)?;} - Ok(()) - })(); - if result.is_err(){self.program.tail.failed.set(true);self.program.context.poison();self.program.context.retain_driver();}result - } - pub fn metadata_bytes(&self)->Result{let mut n=self.program.metadata_bytes()?+std::mem::size_of::()+self.catchup_embed.as_ref().map_or(0,OriginalMtpNativeGather::metadata_bytes)+self.coupled_stage.as_ref().map_or(0,FA::metadata_bytes);for v in [&self.before,&self.after,&self.post]{n=n.checked_add(v.capacity()*std::mem::size_of::()).ok_or(Error::BudgetExceeded)?;for c in v{n=n.checked_add(c.args.metadata_bytes()).ok_or(Error::BudgetExceeded)?;}}n=n.checked_add(self.catchup.capacity()*std::mem::size_of::()).ok_or(Error::BudgetExceeded)?;for c in &self.catchup{if let ScalarCommand::Kernel{args,..}=c{n=n.checked_add(args.metadata_bytes()).ok_or(Error::BudgetExceeded)?;}}Ok(n)} - pub(crate) fn stage_sampling(&self,params:SamplerParams,history:&[i32;4096])->Result<()>{self.program.stage_coupled_after_actual_retirement(params,history)} - pub(crate) fn stage_round(&mut self,window:Rc>,selection:NativeHeadSelection,a:usize,stream:usize)->Result<()> { - self.validate_context(self.program.context)?; - if self.j!=0||self.rows!=window.rows()||a>=self.rows{return Err(Error::InvalidQwenShape);} - window.validate_context(self.program.context)?;window.validate_selection(&selection)?;window.validate_mtp_geometry()?; - let o=&self.program.tail; - if selection.vocabulary()!=o.weights.id_vocab||window.first_position().checked_add(self.rows.max(a+1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS){return Err(Error::InvalidProjectionShape);} - let source=window.residuals()?; - if let Some(captured)=&self.direct_window{ - // Original bind uses Verifier::final_R_all(), a real DEVICE span. - if captured.retained_residual_address_for_mtp()?!=source.qwen_address(){return Err(Error::InvalidQwenShape);} - let new=StagedSource{window:Rc::clone(&window),selection,accepted_row:a,next_j:0,ready:false,rows:self.rows,first_repeat:false};new.validate(self.program.context)?; - *o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?=Some(new); - self.direct_window=Some(window);return self.write_mapped_round(); - } - let dest=o.mapped_address(o.mapped_window_offset(),self.rows*40960)?; - // Admission precedes every mutation. Prior source retained until actual drain. - if source.qwen_address()%16!=0||dest%16!=0||overlap(source.qwen_address(),self.rows*40960,dest,self.rows*40960)?{return Err(Error::InvalidSize);} - let new=StagedSource{window,selection,accepted_row:a,next_j:0,ready:false,rows:self.rows,first_repeat:false};new.validate(self.program.context)?; - *o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?=Some(new); - let g=self.program.context.enter().inspect_err(|_|{o.failed.set(true);self.program.context.poison();self.program.context.retain_driver();})?; - let op=o.modules[13].copy(dest,source.qwen_address(),self.rows*40960,stream);let pop=g.finish(); - if op.is_err()||pop.is_err(){o.failed.set(true);self.program.context.poison();self.program.context.retain_driver();}combine(op,pop)?; - self.write_mapped_round() - } - fn write_mapped_round(&self)->Result<()>{ - let o=&self.program.tail;let b=o.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let actual=b.as_ref().ok_or(Error::InvalidQwenShape)?;actual.validate(self.program.context)?; - if actual.rows!=self.rows{return Err(Error::InvalidQwenShape);} - let mut borrow=o.mapped.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let mapped=borrow.as_mut().ok_or(Error::ContextPoisoned)?; - for i in 0..actual.rows{let id=actual.selection.ids()[if actual.first_repeat{0}else{i}];mapped.write(i*4,&id.to_le_bytes())?;put(mapped,o.max_t,i,actual.window.first_position()+i)?;} - put(mapped,o.max_t,2*o.max_t-1,actual.window.first_position()+actual.accepted_row)?; - mapped.write(o.max_t*228+192,&(actual.accepted_row as i32).to_le_bytes())?;mapped.write(o.max_t*228+196,&0i32.to_le_bytes())?; - std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(()) - } - pub(crate) fn stage_first_after_capture(&self)->Result<()>{self.program.tail.validate_staged(0)?;let b=self.program.tail.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?;if b.as_ref().is_none_or(|s|!s.first_repeat||s.rows!=self.rows){return Err(Error::InvalidQwenShape);}drop(b);self.write_mapped_round()} - - pub(crate) fn stage_completed(&self)->Result<()>{let mut b=self.program.tail.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let s=b.as_mut().ok_or(Error::InvalidQwenShape)?;s.validate(self.program.context)?;s.ready=true;Ok(())} - pub(crate) fn stage_chain(&self)->Result<()>{self.program.tail.validate_staged(self.j)?;let source=self.program.tail.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let s=source.as_ref().ok_or(Error::InvalidQwenShape)?;let cell=s.window.first_position().checked_add(s.accepted_row).and_then(|n|n.checked_add(self.j)).ok_or(Error::InvalidQwenShape)?;let mut b=self.program.tail.mapped.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;put(b.as_mut().ok_or(Error::ContextPoisoned)?,self.program.tail.max_t,self.program.tail.max_t+self.j-1,cell)?;std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(())} - pub(crate) fn finish_after_drain(&self)->Result{ - self.program.tail.validate_staged(self.j)?;self.program.validate_flags_after_actual_drain()?; - let o=&self.program.tail;let b=o.mapped.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let m=b.as_ref().ok_or(Error::ContextPoisoned)?;let mut id=[0;4];let mut probability=[0;4];m.read(o.max_t*228+256+self.j*4,&mut id)?;m.read(o.max_t*232+320+self.j*4,&mut probability)?; - let token=i32::from_le_bytes(id);let probability=f32::from_le_bytes(probability);if token<0||token as usize>=o.weights.id_vocab||!probability.is_finite()||!(0.0..=1.0).contains(&probability){return Err(Error::InvalidQ8Activation);} - let mut b=o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let s=b.as_mut().ok_or(Error::InvalidQwenShape)?;s.validate(self.program.context)?;s.next_j=self.j+1;Ok(OriginalMtpStepOutput{token,probability}) - } -} -fn put(m:&mut full_mapped::MappedOwner,max_t:usize,row:usize,cell:usize)->Result<()>{if row>=2*max_t||cell>=262144{return Err(Error::InvalidQwenShape);}for(j,n)in [cell,cell+1,(cell+1)/4,cell+1].into_iter().enumerate(){m.write(max_t*4+64+row*16+j*4,&(n as i32).to_le_bytes())?;}for h in 0..24{m.write(max_t*36+128+row*96+h*4,&(cell as i32).to_le_bytes())?;}Ok(())} - -impl<'ctx> OriginalMtpFullForward<'ctx>{ - /// Literal draft_first: repeat the ONE genuine completed target residual/token - /// with synchronous device copies BEFORE the first round's capture. No fake - /// verifier window of repeated rows is constructed. - pub(crate) fn stage_first_residual(&self,window:Rc>,selection:NativeHeadSelection,rows:usize)->Result<()>{ - self.validate_context(self.inner.context)?;window.validate_context(self.inner.context)?;window.validate_mtp_geometry()?;window.validate_selection(&selection)?; - if window.rows()!=1||rows==0||rows>self.inner.max_t||window.first_position().checked_add(rows.max(1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=self.inner.weights.id_vocab{return Err(Error::InvalidQwenShape);} - let source=window.residuals()?;let o=&self.inner; - if source.qwen_address()%16!=0{return Err(Error::InvalidSize);} - let dest=o.mapped_address(o.mapped_window_offset(),rows*40960)?; - if overlap(source.qwen_address(),40960,dest,rows*40960)?{return Err(Error::OutputAliasesInput);} - let staged=StagedSource{window,selection,accepted_row:0,next_j:0,ready:false,rows,first_repeat:true};staged.validate(o.context)?; - *o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?=Some(staged); - let g=o.context.enter().inspect_err(|_|{o.failed.set(true);o.context.poison();o.context.retain_driver();})?; - let copies=(||{for t in 0..rows{o.modules[13].copy_sync(dest+(t*40960)as u64,source.qwen_address(),40960)?;}Ok(())})();let pop=g.finish(); - if copies.is_err()||pop.is_err(){o.failed.set(true);o.context.poison();o.context.retain_driver();}combine(copies,pop)?; - o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::InvalidQwenShape)?.ready=true;Ok(()) - } -} - -fn overlap(a:u64,an:usize,b:u64,bn:usize)->Result{let ae=a.checked_add(an as u64).ok_or(Error::InvalidSize)?;let be=b.checked_add(bn as u64).ok_or(Error::InvalidSize)?;Ok(a OriginalMtpFullForward<'ctx>{ - /// Literal Original bind/capture coupling. The completed verifier allocation - /// is retained BEFORE capture and its actual DEVICE R is the kernel source. - /// The copy_from_mapped kernel name does not imply the argument is mapped RAM. - pub fn prepare_round_from_verifier(&self,scalar:&OriginalMtpScalarPrefill<'ctx>,ring:&MtpOriginalInt8<'ctx>,window:Rc>,policy:&OriginalMtpFullPolicy)->Result>{ - window.validate_context(self.inner.context)?;window.validate_mtp_geometry()?; - self.prepare_round_from_verifier_rows(scalar,ring,window.clone(),window.rows(),false,policy) - } - pub(super) fn prepare_round_from_verifier_rows(&self,scalar:&OriginalMtpScalarPrefill<'ctx>,ring:&MtpOriginalInt8<'ctx>,window:Rc>,rows:usize,first_repeat:bool,policy:&OriginalMtpFullPolicy)->Result>{ - window.validate_context(self.inner.context)?;window.validate_mtp_geometry()?; - if rows==0||rows>self.inner.max_t||if first_repeat{window.rows()!=1}else{rows!=window.rows()}{return Err(Error::InvalidQwenShape);} - if first_repeat{let source=self.inner.source.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let source=source.as_ref().ok_or(Error::InvalidQwenShape)?;source.validate(self.inner.context)?;if !source.ready||!source.first_repeat||source.rows!=rows||!Rc::ptr_eq(&source.window,&window){return Err(Error::InvalidQwenShape);}} - let source=window.actual_mtp_residual_bank(rows)?;let dest=scalar.address(0,rows*40960)?; - if source.qwen_address()%16!=0||dest%16!=0||overlap(source.qwen_address(),rows*40960,dest,rows*40960)?{return Err(Error::OutputAliasesInput);} - let mut result=self.prepare_round(scalar,ring,rows,policy)?; - if result.before.len()!=5||result.before[4].asset!=10||result.before[4].index!=1{return Err(Error::InvalidQwenShape);} - let n4=rows*10240/4;let mut replacement=Vec::new(); - push(&mut replacement,10,1,[n4.div_ceil(256).min(64)as u32,1,1],[256,1,1],0,vec![F::U64(dest),F::U64(source.qwen_address()),F::I64(n4 as i64)])?; - result.before[4]=replacement.pop().ok_or(Error::InvalidQwenShape)?; - result.direct_window=Some(window);Ok(result) - } -} -impl OriginalMtpDraftProgram<'_>{ - pub(crate) fn uses_direct_verifier_window(&self)->bool{self.direct_window.is_some()} -} -impl<'ctx> OriginalMtpFullForward<'ctx>{ - /// Drop the verifier window the last round staged (the tail owner keeps it until the next stage). The caller drained the stream. - pub(crate) fn release_staged_source(&self)->Result<()>{ - self.inner.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.take();Ok(()) - } +pub struct OriginalMtpDraftProgram<'ctx> { + program: OriginalMtpForwardProgram<'ctx>, + rows: usize, + j: usize, + before: Vec, + after: Vec, + post: Vec, + catchup: Vec, + catchup_embed: Option>, + coupled_stage: Option, + direct_window: Option>>, } /// Bytes of one verifier residual row (10240 f32). -const RESIDUAL_ROW_BYTES:usize=40960; - -/// The copies of `stage_first_residual_direct`, then the fence. `cuMemcpy` between device addresses is ordered only on the legacy default -/// stream and does not block the host; the draft graph that reads the rows runs on a NON-blocking stream, which the legacy stream does not -/// order against, so without the fence the graph could read a row before its copy finished (cross-stream race, docs/memory-safety-unsafe.md -/// section 6.2). The fence is `cuStreamSynchronize(0)`: it waits for these copies only, not for a verifier commit queued on another stream. -/// A failed copy skips the fence (the caller poisons the context); a failed fence is an error. -fn copy_rows_then_fence(rows:usize,dst:u64,src:u64,copy:&mut dyn FnMut(u64,u64,usize)->Result<()>,fence:&mut dyn FnMut()->Result<()>)->Result<()>{ - for row in 0..rows{copy(dst+(row*RESIDUAL_ROW_BYTES)as u64,src,RESIDUAL_ROW_BYTES)?;} - fence() -} +const RESIDUAL_ROW_BYTES: usize = 40960; #[cfg(test)] -mod stage_fence_tests{ - use super::*; - #[test] - fn the_fence_comes_after_the_last_copy_and_only_once(){ - let log=std::cell::RefCell::new(Vec::::new()); - copy_rows_then_fence(3,0x1000,0x2000,&mut |d,s,n|{log.borrow_mut().push(format!("copy {d:#x}<-{s:#x} {n}"));Ok(())},&mut ||{log.borrow_mut().push("fence".into());Ok(())}).unwrap(); - assert_eq!(*log.borrow(),vec!["copy 0x1000<-0x2000 40960","copy 0xb000<-0x2000 40960","copy 0x15000<-0x2000 40960","fence"]); - } - #[test] - fn a_failed_copy_skips_the_fence_and_a_failed_fence_is_an_error(){ - let fenced=std::cell::Cell::new(0); - let r=copy_rows_then_fence(4,1,2,&mut |d,_,_|if d>1+40960{Err(Error::InvalidSize)}else{Ok(())},&mut ||{fenced.set(fenced.get()+1);Ok(())}); - assert!(r.is_err()&&fenced.get()==0,"no fence after a failed copy"); - let r=copy_rows_then_fence(1,1,2,&mut |_,_,_|Ok(()),&mut ||Err(Error::InvalidProjectionShape)); - assert!(matches!(r,Err(Error::InvalidProjectionShape)),"a failed fence must not read as success"); - let r=copy_rows_then_fence(0,1,2,&mut |_,_,_|panic!("no rows, no copies"),&mut ||Ok(())); - assert!(r.is_ok()); - } -} - -impl<'ctx> OriginalMtpFullForward<'ctx>{ - /// Literal mtp.cpp834: actual synchronous D2D into Verifier's OWN R bank, - /// before capture. Repeated scratch rows do not become verification results. - pub(super) fn stage_first_residual_direct(&self,window:Rc>,selection:NativeHeadSelection,rows:usize)->Result<()>{ - let o=&self.inner;o.validate(o.context)?;window.validate_context(o.context)?;window.validate_mtp_geometry()?;window.validate_selection(&selection)?; - if window.rows()!=1||rows==0||rows>o.max_t||window.first_position().checked_add(rows.max(1)).is_none_or(|n|n>MTP_ORIGINAL_MAX_CELLS)||selection.vocabulary()!=o.weights.id_vocab{return Err(Error::InvalidQwenShape);} - let src=window.residuals()?.qwen_address();let dst=window.actual_mtp_residual_bank(rows)?.qwen_address(); - // Exact row0 self-copy is Original; all later rows are disjoint, whole-owned. - if src!=dst||src%16!=0{return Err(Error::InvalidProjectionShape);} - let staged=StagedSource{window,selection,accepted_row:0,next_j:0,ready:false,rows,first_repeat:true};staged.validate(o.context)?; - *o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?=Some(staged); - let g=o.context.enter().inspect_err(|_|{o.failed.set(true);o.context.poison();o.context.retain_driver();})?; - let copies=copy_rows_then_fence(rows,dst,src,&mut |d,s,n|o.modules[13].copy_sync(d,s,n),&mut ||o.modules[13].fence_legacy_stream());let pop=g.finish(); - if copies.is_err()||pop.is_err(){o.failed.set(true);o.context.poison();o.context.retain_driver();}combine(copies,pop)?; - o.source.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::InvalidQwenShape)?.ready=true;Ok(()) - } +mod stage_fence_tests { + use super::*; + #[test] + fn the_fence_comes_after_the_last_copy_and_only_once() { + let log = std::cell::RefCell::new(Vec::::new()); + copy_rows_then_fence( + 3, + 0x1000, + 0x2000, + &mut |d, s, n| { + log.borrow_mut().push(format!("copy {d:#x}<-{s:#x} {n}")); + Ok(()) + }, + &mut || { + log.borrow_mut().push("fence".into()); + Ok(()) + }, + ) + .unwrap(); + assert_eq!( + *log.borrow(), + vec!["copy 0x1000<-0x2000 40960", "copy 0xb000<-0x2000 40960", "copy 0x15000<-0x2000 40960", "fence"] + ); + } + #[test] + fn a_failed_copy_skips_the_fence_and_a_failed_fence_is_an_error() { + let fenced = std::cell::Cell::new(0); + let r = copy_rows_then_fence( + 4, + 1, + 2, + &mut |d, _, _| if d > 1 + 40960 { Err(Error::InvalidSize) } else { Ok(()) }, + &mut || { + fenced.set(fenced.get() + 1); + Ok(()) + }, + ); + assert!(r.is_err() && fenced.get() == 0, "no fence after a failed copy"); + let r = copy_rows_then_fence(1, 1, 2, &mut |_, _, _| Ok(()), &mut || Err(Error::InvalidProjectionShape)); + assert!(matches!(r, Err(Error::InvalidProjectionShape)), "a failed fence must not read as success"); + let r = copy_rows_then_fence(0, 1, 2, &mut |_, _, _| panic!("no rows, no copies"), &mut || Ok(())); + assert!(r.is_ok()); + } } +#[path = "mtp_original_full_round/impl_stagedsource.rs"] +mod impl_stagedsource; +#[allow(unused_imports)] +use impl_stagedsource::mapped_i32; +#[allow(unused_imports)] +use impl_stagedsource::mtp_select; +#[path = "mtp_original_full_round/post_select_fn.rs"] +mod post_select_fn; +#[allow(unused_imports)] +use post_select_fn::post_select; +#[path = "mtp_original_full_round/impl_originalmtpdraftprogram.rs"] +mod impl_originalmtpdraftprogram; +#[path = "mtp_original_full_round/put_fn.rs"] +mod put_fn; +#[allow(unused_imports)] +use put_fn::copy_rows_then_fence; +#[allow(unused_imports)] +use put_fn::overlap; +#[allow(unused_imports)] +use put_fn::put; diff --git a/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs b/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs new file mode 100644 index 00000000..6dd28682 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_round/impl_originalmtpdraftprogram.rs @@ -0,0 +1,250 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDraftProgram. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalMtpDraftProgram<'ctx> { + pub(super) fn enqueue_commands(&mut self, c: &mut OriginalCapture<'_, '_>, which: bool) -> Result<()> { + let stream = c.stream_handle(self.program.context)?; + let commands = if which { &mut self.before } else { &mut self.after }; + for command in commands { + self.program.tail.modules[command.asset].launch( + command.index, + command.grid, + command.block, + command.shared, + stream, + &mut command.args, + )?; + } + Ok(()) + } + pub fn capture(&mut self, c: &mut OriginalCapture<'_, '_>) -> Result<()> { + self.validate_context(self.program.context)?; + c.validate_context(self.program.context)?; + if let Some(window) = &self.direct_window { + window.validate_context(self.program.context)?; + } + let stream = c.stream_handle(self.program.context)?; + let result = (|| { + if let Some(stage) = &mut self.coupled_stage { + self.program.tail.modules[20].launch(1, [1, 1, 1], [256, 1, 1], 0, stream, stage)?; + } + self.enqueue_commands(c, true)?; + for (i, cmd) in self.catchup.iter_mut().enumerate() { + if i == 1 + && let Some(e) = &mut self.catchup_embed + { + e.capture(c)?; + } + match cmd { + ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { + self.program.prefix_modules[*asset].launch(*index, *grid, *block, *shared, stream, args)? + } + ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape), + } + } + self.enqueue_commands(c, false)?; + self.program.capture(c)?; + let p = &self.program; + for command in &mut self.post { + p.tail.modules[command.asset].launch( + command.index, + command.grid, + command.block, + command.shared, + stream, + &mut command.args, + )?; + } + Ok(()) + })(); + if result.is_err() { + self.program.tail.failed.set(true); + self.program.context.poison(); + self.program.context.retain_driver(); + } + result + } + pub fn metadata_bytes(&self) -> Result { + let mut n = self.program.metadata_bytes()? + + std::mem::size_of::() + + self.catchup_embed.as_ref().map_or(0, OriginalMtpNativeGather::metadata_bytes) + + self.coupled_stage.as_ref().map_or(0, FA::metadata_bytes); + for v in [&self.before, &self.after, &self.post] { + n = n.checked_add(v.capacity() * std::mem::size_of::()).ok_or(Error::BudgetExceeded)?; + for c in v { + n = n.checked_add(c.args.metadata_bytes()).ok_or(Error::BudgetExceeded)?; + } + } + n = n + .checked_add(self.catchup.capacity() * std::mem::size_of::()) + .ok_or(Error::BudgetExceeded)?; + for c in &self.catchup { + if let ScalarCommand::Kernel { args, .. } = c { + n = n.checked_add(args.metadata_bytes()).ok_or(Error::BudgetExceeded)?; + } + } + Ok(n) + } + pub(crate) fn stage_sampling(&self, params: SamplerParams, history: &[i32; 4096]) -> Result<()> { + self.program.stage_coupled_after_actual_retirement(params, history) + } + pub(crate) fn stage_round( + &mut self, + window: Rc>, + selection: NativeHeadSelection, + a: usize, + stream: usize, + ) -> Result<()> { + self.validate_context(self.program.context)?; + if self.j != 0 || self.rows != window.rows() || a >= self.rows { + return Err(Error::InvalidQwenShape); + } + window.validate_context(self.program.context)?; + window.validate_selection(&selection)?; + window.validate_mtp_geometry()?; + let o = &self.program.tail; + if selection.vocabulary() != o.weights.id_vocab + || window.first_position().checked_add(self.rows.max(a + 1)).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidProjectionShape); + } + let source = window.residuals()?; + if let Some(captured) = &self.direct_window { + // Original bind uses Verifier::final_R_all(), a real DEVICE span. + if captured.retained_residual_address_for_mtp()? != source.qwen_address() { + return Err(Error::InvalidQwenShape); + } + let new = StagedSource { + window: Rc::clone(&window), + selection, + accepted_row: a, + next_j: 0, + ready: false, + rows: self.rows, + first_repeat: false, + }; + new.validate(self.program.context)?; + *o.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)? = Some(new); + self.direct_window = Some(window); + return self.write_mapped_round(); + } + let dest = o.mapped_address(o.mapped_window_offset(), self.rows * 40960)?; + // Admission precedes every mutation. Prior source retained until actual drain. + if source.qwen_address() % 16 != 0 + || dest % 16 != 0 + || overlap(source.qwen_address(), self.rows * 40960, dest, self.rows * 40960)? + { + return Err(Error::InvalidSize); + } + let new = StagedSource { + window, + selection, + accepted_row: a, + next_j: 0, + ready: false, + rows: self.rows, + first_repeat: false, + }; + new.validate(self.program.context)?; + *o.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)? = Some(new); + let g = self.program.context.enter().inspect_err(|_| { + o.failed.set(true); + self.program.context.poison(); + self.program.context.retain_driver(); + })?; + let op = o.modules[13].copy(dest, source.qwen_address(), self.rows * 40960, stream); + let pop = g.finish(); + if op.is_err() || pop.is_err() { + o.failed.set(true); + self.program.context.poison(); + self.program.context.retain_driver(); + } + combine(op, pop)?; + self.write_mapped_round() + } + pub(super) fn write_mapped_round(&self) -> Result<()> { + let o = &self.program.tail; + let b = o.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let actual = b.as_ref().ok_or(Error::InvalidQwenShape)?; + actual.validate(self.program.context)?; + if actual.rows != self.rows { + return Err(Error::InvalidQwenShape); + } + let mut borrow = o.mapped.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let mapped = borrow.as_mut().ok_or(Error::ContextPoisoned)?; + for i in 0..actual.rows { + let id = actual.selection.ids()[if actual.first_repeat { 0 } else { i }]; + mapped.write(i * 4, &id.to_le_bytes())?; + put(mapped, o.max_t, i, actual.window.first_position() + i)?; + } + put(mapped, o.max_t, 2 * o.max_t - 1, actual.window.first_position() + actual.accepted_row)?; + mapped.write(o.max_t * 228 + 192, &(actual.accepted_row as i32).to_le_bytes())?; + mapped.write(o.max_t * 228 + 196, &0i32.to_le_bytes())?; + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + pub(crate) fn stage_first_after_capture(&self) -> Result<()> { + self.program.tail.validate_staged(0)?; + let b = self.program.tail.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if b.as_ref().is_none_or(|s| !s.first_repeat || s.rows != self.rows) { + return Err(Error::InvalidQwenShape); + } + drop(b); + self.write_mapped_round() + } + + pub(crate) fn stage_completed(&self) -> Result<()> { + let mut b = self.program.tail.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let s = b.as_mut().ok_or(Error::InvalidQwenShape)?; + s.validate(self.program.context)?; + s.ready = true; + Ok(()) + } + pub(crate) fn stage_chain(&self) -> Result<()> { + self.program.tail.validate_staged(self.j)?; + let source = self.program.tail.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let s = source.as_ref().ok_or(Error::InvalidQwenShape)?; + let cell = s + .window + .first_position() + .checked_add(s.accepted_row) + .and_then(|n| n.checked_add(self.j)) + .ok_or(Error::InvalidQwenShape)?; + let mut b = self.program.tail.mapped.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + put( + b.as_mut().ok_or(Error::ContextPoisoned)?, + self.program.tail.max_t, + self.program.tail.max_t + self.j - 1, + cell, + )?; + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + pub(crate) fn finish_after_drain(&self) -> Result { + self.program.tail.validate_staged(self.j)?; + self.program.validate_flags_after_actual_drain()?; + let o = &self.program.tail; + let b = o.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let m = b.as_ref().ok_or(Error::ContextPoisoned)?; + let mut id = [0; 4]; + let mut probability = [0; 4]; + m.read(o.max_t * 228 + 256 + self.j * 4, &mut id)?; + m.read(o.max_t * 232 + 320 + self.j * 4, &mut probability)?; + let token = i32::from_le_bytes(id); + let probability = f32::from_le_bytes(probability); + if token < 0 + || token as usize >= o.weights.id_vocab + || !probability.is_finite() + || !(0.0..=1.0).contains(&probability) + { + return Err(Error::InvalidQ8Activation); + } + let mut b = o.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let s = b.as_mut().ok_or(Error::InvalidQwenShape)?; + s.validate(self.program.context)?; + s.next_j = self.j + 1; + Ok(OriginalMtpStepOutput { token, probability }) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_round/impl_stagedsource.rs b/crates/cuda-driver/src/mtp_original_full_round/impl_stagedsource.rs new file mode 100644 index 00000000..c7015dc5 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_round/impl_stagedsource.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: impl StagedSource, impl FullOwned, impl crate_original_gpu_schedule_resources, impl OriginalGraphResources_for_OriginalMtpDraftProgram, impl OriginalMtpFullForward, fn mapped_i32 .... + +#[allow(unused_imports)] +use super::*; + +impl StagedSource<'_> { + pub(super) fn validate(&self, c: &Context<'_>) -> Result<()> { + self.window.validate_context(c)?; + self.window.validate_selection(&self.selection)?; + if self.rows == 0 + || self.rows > 8 + || self.accepted_row >= self.rows + || if self.first_repeat { + self.window.rows() != 1 || self.accepted_row != 0 + } else { + self.rows != self.window.rows() + } + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } +} +impl FullOwned<'_> { + pub(super) fn mapped_window_offset(&self) -> usize { + let records = self.max_t * 236 + 384 + if self.coupled { 64 + 4096 * 4 } else { 0 }; + (records + 255) & !255 + } + pub(super) fn validate_staged(&self, j: usize) -> Result<()> { + self.validate(self.context)?; + let source = self.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let source = source.as_ref().ok_or(Error::InvalidQwenShape)?; + source.validate(self.context)?; + if !source.ready || source.next_j != j { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } +} +impl crate::original_gpu_schedule::resources::Sealed for OriginalMtpDraftProgram<'_> {} +impl OriginalGraphResources for OriginalMtpDraftProgram<'_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.program.validate_context(c) + } + fn validate_replay_context(&self, c: &Context<'_>) -> Result<()> { + self.program.validate_context(c)?; + self.program.tail.validate_staged(self.j)?; + if self.j == 0 + && self + .program + .tail + .source + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .is_none_or(|s| s.rows != self.rows) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } +} +impl<'ctx> OriginalMtpFullForward<'ctx> { + pub fn planned_pinned_host_bytes(max_t: usize, coupled: bool) -> Result { + if !(1..=8).contains(&max_t) { + return Err(Error::InvalidQwenShape); + } + let records = max_t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 }; + Ok(((records + 255) & !255) + max_t * 40960) + } + /// Capture is prepared before mapped input writes, as in Original. Only real + /// stage_verify_window completion can subsequently authorize replay. + pub fn prepare_round( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + rows: usize, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + if rows == 0 + || rows > self.inner.max_t + || scalar.max_t != self.inner.max_t + || policy.coupled_j.is_some_and(|j| j != 0) + { + return Err(Error::InvalidQwenShape); + } + let (catchup, catchup_embed) = self.prefix_commands(scalar, ring, policy, rows, 0)?; + let ra = 2 * self.inner.max_t - 1; + let (mut prefix, embedding) = self.prefix_commands(scalar, ring, policy, 1, ra)?; + // One reset before catch-up; later flags OR into the same full-stage safety + // owner until the final actual drain. Never erase an earlier numerical fault. + if !matches!(prefix.first(), Some(ScalarCommand::Kernel { asset: 0, index: 11, .. })) { + return Err(Error::InvalidQwenShape); + } + prefix.remove(0); + let mut program = self.program(scalar, ring, prefix, policy, embedding, ra)?; + let coupled_stage = program.coupled_stage.take(); + let mut before = Vec::new(); + let mut after = Vec::new(); + let o = &self.inner; + mapped_i32(&mut before, scalar.address(12, rows * 4)?, o.mapped_address(0, rows * 4)?, rows)?; + mapped_i32(&mut before, o.address(31)?, o.mapped_address(self.inner.max_t * 4 + 64, rows * 32)?, rows * 8)?; + mapped_i32(&mut before, o.address(32)?, o.mapped_address(self.inner.max_t * 36 + 128, rows * 192)?, rows * 48)?; + mapped_i32(&mut before, o.address(33)?, o.mapped_address(self.inner.max_t * 228 + 192, 8)?, 2)?; + let n4 = rows * 10240 / 4; + push( + &mut before, + 10, + 1, + [n4.div_ceil(256).min(64) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(scalar.address(0, rows * 40960)?), + F::U64(o.mapped_address(o.mapped_window_offset(), rows * 40960)?), + F::I64(n4 as i64), + ], + )?; + // Selection and late full-step records execute AFTER real catch-up kernels. + mtp_select( + &mut after, + scalar.address(0, rows * 40960)?, + scalar.address(12, rows * 4)?, + o.address(33)?, + scalar.address(0, 40960)?, + scalar.address(12, 4)?, + 0, + 0, + 0, + 0, + )?; + mapped_i32( + &mut after, + o.address(31)? + (ra * 16) as u64, + o.mapped_address(self.inner.max_t * 4 + 64 + ra * 16, 16)?, + 4, + )?; + mapped_i32( + &mut after, + o.address(32)? + (ra * 96) as u64, + o.mapped_address(self.inner.max_t * 36 + 128 + ra * 96, 96)?, + 24, + )?; + let post = post_select(&program, 0)?; + Ok(OriginalMtpDraftProgram { + program, + rows, + j: 0, + before, + after, + post, + catchup, + catchup_embed, + coupled_stage, + direct_window: None, + }) + } + pub fn prepare_step( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + j: usize, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + if j == 0 + || j >= self.inner.max_t - 1 + || scalar.max_t != self.inner.max_t + || policy.coupled_j.is_some_and(|v| v as usize != j) + { + return Err(Error::InvalidQwenShape); + } + let row = self.inner.max_t + j - 1; + let (prefix, embedding) = self.prefix_commands(scalar, ring, policy, 1, row)?; + let program = self.program(scalar, ring, prefix, policy, embedding, row)?; + let o = &self.inner; + let mut before = Vec::new(); + mapped_i32( + &mut before, + o.address(31)? + (row * 16) as u64, + o.mapped_address(self.inner.max_t * 4 + 64 + row * 16, 16)?, + 4, + )?; + mapped_i32( + &mut before, + o.address(32)? + (row * 96) as u64, + o.mapped_address(self.inner.max_t * 36 + 128 + row * 96, 96)?, + 24, + )?; + let post = post_select(&program, j)?; + Ok(OriginalMtpDraftProgram { + program, + rows: 1, + j, + before, + after: Vec::new(), + post, + catchup: Vec::new(), + catchup_embed: None, + coupled_stage: None, + direct_window: None, + }) + } +} +pub(super) fn mapped_i32(v: &mut Vec, dst: u64, src: u64, n: usize) -> Result<()> { + push(v, 10, 2, [1, 1, 1], [128, 1, 1], 0, vec![F::U64(dst), F::U64(src), F::I32(n as i32)]) +} +#[allow(clippy::too_many_arguments)] +pub(super) fn mtp_select( + v: &mut Vec, + r: u64, + ids: u64, + row: u64, + rin: u64, + tok: u64, + out: u64, + j: usize, + prob: u64, + outp: u64, +) -> Result<()> { + push( + v, + 12, + 2, + [16, 1, 1], + [256, 1, 1], + 0, + vec![ + F::U64(r), + F::I64(10240), + F::U64(ids), + F::U64(row), + F::U64(rin), + F::U64(tok), + F::U64(out), + F::I32(j as i32), + F::U64(prob), + F::U64(outp), + ], + ) +} diff --git a/crates/cuda-driver/src/mtp_original_full_round/post_select_fn.rs b/crates/cuda-driver/src/mtp_original_full_round/post_select_fn.rs new file mode 100644 index 00000000..7fb8c1f5 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_round/post_select_fn.rs @@ -0,0 +1,25 @@ +//! Moved out of the parent module by STRA-338: fn post_select. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn post_select(p: &OriginalMtpForwardProgram<'_>, j: usize) -> Result> { + let mut v = Vec::new(); + mtp_select( + &mut v, + p.prefix_scratch + .handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(p.prefix_scratch.bytes, p.residual_offset, 40960)? + .qwen_address(), + p.tail.address(34)?, + p.tail.address(33)? + 4, + p.input_address, + p.token_address, + p.tail.mapped_address(p.tail.max_t * 228 + 256, p.tail.max_t * 4)?, + j, + p.tail.address(35)?, + p.tail.mapped_address(p.tail.max_t * 232 + 320, p.tail.max_t * 4)?, + )?; + Ok(v) +} diff --git a/crates/cuda-driver/src/mtp_original_full_round/put_fn.rs b/crates/cuda-driver/src/mtp_original_full_round/put_fn.rs new file mode 100644 index 00000000..4e895db9 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_full_round/put_fn.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: fn put, impl OriginalMtpFullForward, fn overlap, impl OriginalMtpFullForward, impl OriginalMtpDraftProgram, impl OriginalMtpFullForward .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn put(m: &mut full_mapped::MappedOwner, max_t: usize, row: usize, cell: usize) -> Result<()> { + if row >= 2 * max_t || cell >= 262144 { + return Err(Error::InvalidQwenShape); + } + for (j, n) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() { + m.write(max_t * 4 + 64 + row * 16 + j * 4, &(n as i32).to_le_bytes())?; + } + for h in 0..24 { + m.write(max_t * 36 + 128 + row * 96 + h * 4, &(cell as i32).to_le_bytes())?; + } + Ok(()) +} + +impl<'ctx> OriginalMtpFullForward<'ctx> { + /// Literal draft_first: repeat the ONE genuine completed target residual/token + /// with synchronous device copies BEFORE the first round's capture. No fake + /// verifier window of repeated rows is constructed. + pub(crate) fn stage_first_residual( + &self, + window: Rc>, + selection: NativeHeadSelection, + rows: usize, + ) -> Result<()> { + self.validate_context(self.inner.context)?; + window.validate_context(self.inner.context)?; + window.validate_mtp_geometry()?; + window.validate_selection(&selection)?; + if window.rows() != 1 + || rows == 0 + || rows > self.inner.max_t + || window.first_position().checked_add(rows.max(1)).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || selection.vocabulary() != self.inner.weights.id_vocab + { + return Err(Error::InvalidQwenShape); + } + let source = window.residuals()?; + let o = &self.inner; + if source.qwen_address() % 16 != 0 { + return Err(Error::InvalidSize); + } + let dest = o.mapped_address(o.mapped_window_offset(), rows * 40960)?; + if overlap(source.qwen_address(), 40960, dest, rows * 40960)? { + return Err(Error::OutputAliasesInput); + } + let staged = + StagedSource { window, selection, accepted_row: 0, next_j: 0, ready: false, rows, first_repeat: true }; + staged.validate(o.context)?; + *o.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)? = Some(staged); + let g = o.context.enter().inspect_err(|_| { + o.failed.set(true); + o.context.poison(); + o.context.retain_driver(); + })?; + let copies = (|| { + for t in 0..rows { + o.modules[13].copy_sync(dest + (t * 40960) as u64, source.qwen_address(), 40960)?; + } + Ok(()) + })(); + let pop = g.finish(); + if copies.is_err() || pop.is_err() { + o.failed.set(true); + o.context.poison(); + o.context.retain_driver(); + } + combine(copies, pop)?; + o.source + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::InvalidQwenShape)? + .ready = true; + Ok(()) + } +} + +pub(super) fn overlap(a: u64, an: usize, b: u64, bn: usize) -> Result { + let ae = a.checked_add(an as u64).ok_or(Error::InvalidSize)?; + let be = b.checked_add(bn as u64).ok_or(Error::InvalidSize)?; + Ok(a < be && b < ae) +} + +impl<'ctx> OriginalMtpFullForward<'ctx> { + /// Literal Original bind/capture coupling. The completed verifier allocation + /// is retained BEFORE capture and its actual DEVICE R is the kernel source. + /// The copy_from_mapped kernel name does not imply the argument is mapped RAM. + pub fn prepare_round_from_verifier( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + window: Rc>, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + window.validate_context(self.inner.context)?; + window.validate_mtp_geometry()?; + self.prepare_round_from_verifier_rows(scalar, ring, window.clone(), window.rows(), false, policy) + } + pub(in super::super) fn prepare_round_from_verifier_rows( + &self, + scalar: &OriginalMtpScalarPrefill<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + window: Rc>, + rows: usize, + first_repeat: bool, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + window.validate_context(self.inner.context)?; + window.validate_mtp_geometry()?; + if rows == 0 || rows > self.inner.max_t || if first_repeat { window.rows() != 1 } else { rows != window.rows() } + { + return Err(Error::InvalidQwenShape); + } + if first_repeat { + let source = self.inner.source.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let source = source.as_ref().ok_or(Error::InvalidQwenShape)?; + source.validate(self.inner.context)?; + if !source.ready || !source.first_repeat || source.rows != rows || !Rc::ptr_eq(&source.window, &window) { + return Err(Error::InvalidQwenShape); + } + } + let source = window.actual_mtp_residual_bank(rows)?; + let dest = scalar.address(0, rows * 40960)?; + if source.qwen_address() % 16 != 0 + || dest % 16 != 0 + || overlap(source.qwen_address(), rows * 40960, dest, rows * 40960)? + { + return Err(Error::OutputAliasesInput); + } + let mut result = self.prepare_round(scalar, ring, rows, policy)?; + if result.before.len() != 5 || result.before[4].asset != 10 || result.before[4].index != 1 { + return Err(Error::InvalidQwenShape); + } + let n4 = rows * 10240 / 4; + let mut replacement = Vec::new(); + push( + &mut replacement, + 10, + 1, + [n4.div_ceil(256).min(64) as u32, 1, 1], + [256, 1, 1], + 0, + vec![F::U64(dest), F::U64(source.qwen_address()), F::I64(n4 as i64)], + )?; + result.before[4] = replacement.pop().ok_or(Error::InvalidQwenShape)?; + result.direct_window = Some(window); + Ok(result) + } +} +impl OriginalMtpDraftProgram<'_> { + pub(crate) fn uses_direct_verifier_window(&self) -> bool { + self.direct_window.is_some() + } +} +impl<'ctx> OriginalMtpFullForward<'ctx> { + /// Drop the verifier window the last round staged (the tail owner keeps it until the next stage). The caller drained the stream. + pub(crate) fn release_staged_source(&self) -> Result<()> { + self.inner.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.take(); + Ok(()) + } +} + +/// The copies of `stage_first_residual_direct`, then the fence. `cuMemcpy` between device addresses is ordered only on the legacy default +/// stream and does not block the host; the draft graph that reads the rows runs on a NON-blocking stream, which the legacy stream does not +/// order against, so without the fence the graph could read a row before its copy finished (cross-stream race, docs/memory-safety-unsafe.md +/// section 6.2). The fence is `cuStreamSynchronize(0)`: it waits for these copies only, not for a verifier commit queued on another stream. +/// A failed copy skips the fence (the caller poisons the context); a failed fence is an error. +pub(super) fn copy_rows_then_fence( + rows: usize, + dst: u64, + src: u64, + copy: &mut dyn FnMut(u64, u64, usize) -> Result<()>, + fence: &mut dyn FnMut() -> Result<()>, +) -> Result<()> { + for row in 0..rows { + copy(dst + (row * RESIDUAL_ROW_BYTES) as u64, src, RESIDUAL_ROW_BYTES)?; + } + fence() +} + +impl<'ctx> OriginalMtpFullForward<'ctx> { + /// Literal mtp.cpp834: actual synchronous D2D into Verifier's OWN R bank, + /// before capture. Repeated scratch rows do not become verification results. + pub(in super::super) fn stage_first_residual_direct( + &self, + window: Rc>, + selection: NativeHeadSelection, + rows: usize, + ) -> Result<()> { + let o = &self.inner; + o.validate(o.context)?; + window.validate_context(o.context)?; + window.validate_mtp_geometry()?; + window.validate_selection(&selection)?; + if window.rows() != 1 + || rows == 0 + || rows > o.max_t + || window.first_position().checked_add(rows.max(1)).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || selection.vocabulary() != o.weights.id_vocab + { + return Err(Error::InvalidQwenShape); + } + let src = window.residuals()?.qwen_address(); + let dst = window.actual_mtp_residual_bank(rows)?.qwen_address(); + // Exact row0 self-copy is Original; all later rows are disjoint, whole-owned. + if src != dst || src % 16 != 0 { + return Err(Error::InvalidProjectionShape); + } + let staged = + StagedSource { window, selection, accepted_row: 0, next_j: 0, ready: false, rows, first_repeat: true }; + staged.validate(o.context)?; + *o.source.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)? = Some(staged); + let g = o.context.enter().inspect_err(|_| { + o.failed.set(true); + o.context.poison(); + o.context.retain_driver(); + })?; + let copies = copy_rows_then_fence(rows, dst, src, &mut |d, s, n| o.modules[13].copy_sync(d, s, n), &mut || { + o.modules[13].fence_legacy_stream() + }); + let pop = g.finish(); + if copies.is_err() || pop.is_err() { + o.failed.set(true); + o.context.poison(); + o.context.retain_driver(); + } + combine(copies, pop)?; + o.source + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::InvalidQwenShape)? + .ready = true; + Ok(()) + } +} diff --git a/crates/cuda-driver/src/mtp_original_full_symbols.rs b/crates/cuda-driver/src/mtp_original_full_symbols.rs index b34091af..e3688cda 100644 --- a/crates/cuda-driver/src/mtp_original_full_symbols.rs +++ b/crates/cuda-driver/src/mtp_original_full_symbols.rs @@ -11,10 +11,7 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"mtp_full_down_grouped_t_kernel", ], ), - ( - include_bytes!("mtp_original_full_quant80.ptx"), - &[c"mtp_full_quantize_q8_0_scaled_kernel"], - ), + (include_bytes!("mtp_original_full_quant80.ptx"), &[c"mtp_full_quantize_q8_0_scaled_kernel"]), ( include_bytes!("mtp_original_full_shared.ptx"), &[ @@ -25,10 +22,7 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"mtp_full_moe_combine_kernel", ], ), - ( - include_bytes!("mtp_original_full_router.ptx"), - &[c"mtp_full_route"], - ), + (include_bytes!("mtp_original_full_router.ptx"), &[c"mtp_full_route"]), ( include_bytes!("mtp_original_full_router_legacy.ptx"), &[ @@ -37,10 +31,7 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"mtp_full_router_top10_serial_kernel", ], ), - ( - include_bytes!("mtp_original_full_combine.ptx"), - &[c"mtp_full_combine"], - ), + (include_bytes!("mtp_original_full_combine.ptx"), &[c"mtp_full_combine"]), ( include_bytes!("mtp_original_full_bf16.ptx"), &[ @@ -54,17 +45,10 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"mtp_full_mmvf256", ], ), - ( - include_bytes!("mtp_original_full_gr_norm.ptx"), - &[c"mtp_full_gr_norm"], - ), + (include_bytes!("mtp_original_full_gr_norm.ptx"), &[c"mtp_full_gr_norm"]), ( include_bytes!("mtp_original_full_gr_post.ptx"), - &[ - c"mtp_full_down_silu", - c"mtp_full_pre_final", - c"mtp_full_native_write", - ], + &[c"mtp_full_down_silu", c"mtp_full_pre_final", c"mtp_full_native_write"], ), ( include_bytes!("mtp_original_full_gr_write.ptx"), @@ -81,23 +65,12 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ ), ( include_bytes!("mtp_original_full_element.ptx"), - &[ - c"mtp_full_to_bf16", - c"mtp_full_copy_from_mapped", - c"mtp_full_copy_i32_from_mapped", - ], - ), - ( - include_bytes!("mtp_original_full_qsa_gate.ptx"), - &[c"mtp_full_gate"], + &[c"mtp_full_to_bf16", c"mtp_full_copy_from_mapped", c"mtp_full_copy_i32_from_mapped"], ), + (include_bytes!("mtp_original_full_qsa_gate.ptx"), &[c"mtp_full_gate"]), ( include_bytes!("mtp_original_full_verify.ptx"), - &[ - c"mtp_full_row_top_prob_kernel", - c"mtp_full_map_ids_kernel", - c"mtp_full_mtp_select_kernel", - ], + &[c"mtp_full_row_top_prob_kernel", c"mtp_full_map_ids_kernel", c"mtp_full_mtp_select_kernel"], ), ( include_bytes!("mtp_original_full_head_native.ptx"), @@ -383,10 +356,7 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"sampler_split_merge_kernel", ], ), - ( - include_bytes!("mtp_original_full_qnorm.ptx"), - &[c"mtp_full_qnorm", c"mtp_scalar_rope"], - ), + (include_bytes!("mtp_original_full_qnorm.ptx"), &[c"mtp_full_qnorm", c"mtp_scalar_rope"]), ( include_bytes!("mtp_original_full_fused_gr.ptx"), &[ @@ -398,22 +368,11 @@ pub(super) const ASSETS: &[(&[u8], &[&CStr])] = &[ c"mtp_scalar_gr_down2560", ], ), - ( - include_bytes!("mtp_original_full_checks.ptx"), - &[c"mtp_original_finite", c"mtp_original_q8_guard"], - ), - ( - include_bytes!("mtp_original_full_attention.ptx"), - &[c"leleka_qsa_decode_chunk", c"leleka_qsa_decode_merge"], - ), + (include_bytes!("mtp_original_full_checks.ptx"), &[c"mtp_original_finite", c"mtp_original_q8_guard"]), + (include_bytes!("mtp_original_full_attention.ptx"), &[c"leleka_qsa_decode_chunk", c"leleka_qsa_decode_merge"]), ( include_bytes!("mtp_original_full_coupled.ptx"), - &[ - c"sampler_split_part_kernel", - c"coupled_stage_kernel", - c"coupled_penalize_kernel", - c"coupled_merge_kernel", - ], + &[c"sampler_split_part_kernel", c"coupled_stage_kernel", c"coupled_penalize_kernel", c"coupled_merge_kernel"], ), // 21: chain_window.ptx (claude/chain-kernels), loaded only when LELEKA_CHAIN selects a group that launches from it // (`CHAIN_ASSET`); checked against its pin (`original_verify::chain::CHAIN`) before it is handed to the driver. diff --git a/crates/cuda-driver/src/mtp_original_int8.rs b/crates/cuda-driver/src/mtp_original_int8.rs index b4a2266c..c316497b 100644 --- a/crates/cuda-driver/src/mtp_original_int8.rs +++ b/crates/cuda-driver/src/mtp_original_int8.rs @@ -43,12 +43,8 @@ const TAIL_ENTRIES: &[&std::ffi::CStr] = &[ c"mtp_original_finite", c"mtp_original_q8_guard", ]; -const KV_ENTRIES: &[&std::ffi::CStr] = &[ - c"mtp_original_append", - c"mtp_original_ring_table", - c"mtp_original_window_ids", - c"mtp_original_encoded_guard", -]; +const KV_ENTRIES: &[&std::ffi::CStr] = + &[c"mtp_original_append", c"mtp_original_ring_table", c"mtp_original_window_ids", c"mtp_original_encoded_guard"]; const ATTN_ENTRIES: &[&std::ffi::CStr] = &[ c"leleka_qsa_prompt_guard", c"leleka_qsa_decode_chunk", @@ -71,10 +67,9 @@ pub(crate) use prefill::session_assets_sealed; pub use prefill::{ CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, - OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, - OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, - OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, - OriginalMtpStepOutput, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, OriginalMtpPrefillWeights, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, + OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, }; struct Page { runs: [Box<[u8]>; 4], @@ -124,18 +119,8 @@ pub struct CompletedMtpAttention<'loan, 'ctx, 'buffers> { _query: &'loan MtpOriginalQuery<'loan, 'buffers>, } enum Command { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, + Kernel { asset: usize, index: usize, grid: [u32; 3], block: [u32; 3], args: Arguments }, + Copy { dst: u64, src: u64, bytes: usize }, } /// Actual model-lifetime physical allocations. Causal current/generation lives /// only on MtpOriginalInt8. Graph resources retain this Rc without a RefCell loan. @@ -227,14 +212,14 @@ use impl_mtpint8ownerid::snapshot_memo; #[path = "mtp_original_int8/impl_physicalring.rs"] mod impl_physicalring; #[allow(unused_imports)] -use impl_physicalring::zero_bytes; -#[allow(unused_imports)] use impl_physicalring::checked; #[allow(unused_imports)] +use impl_physicalring::layout; +#[allow(unused_imports)] use impl_physicalring::rows_range; #[allow(unused_imports)] -use impl_physicalring::layout; -#[path = "mtp_original_int8/impl_mtporiginalint8.rs"] -mod impl_mtporiginalint8; +use impl_physicalring::zero_bytes; #[path = "mtp_original_int8/impl_drop_for_mtporiginalint8.rs"] mod impl_drop_for_mtporiginalint8; +#[path = "mtp_original_int8/impl_mtporiginalint8.rs"] +mod impl_mtporiginalint8; diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_drop_for_mtporiginalint8.rs b/crates/cuda-driver/src/mtp_original_int8/impl_drop_for_mtporiginalint8.rs index 4e7d42fa..6630f5fa 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_drop_for_mtporiginalint8.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_drop_for_mtporiginalint8.rs @@ -60,15 +60,9 @@ impl<'ctx> MtpOriginalInt8<'ctx> { })?; let load = (|| { for (i, (ptx, entries)) in [ - ( - include_bytes!("../mtp_original_tail.ptx").as_slice(), - TAIL_ENTRIES, - ), + (include_bytes!("../mtp_original_tail.ptx").as_slice(), TAIL_ENTRIES), (include_bytes!("../mtp_original_kv.ptx").as_slice(), KV_ENTRIES), - ( - include_bytes!("../qsa_native_decode.ptx").as_slice(), - ATTN_ENTRIES, - ), + (include_bytes!("../qsa_native_decode.ptx").as_slice(), ATTN_ENTRIES), ] .into_iter() .enumerate() @@ -85,10 +79,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { let (selected, mapped) = ring_state::Selected::from_prepared(prepared, main, spans)?; if selected.layout.resident { o.slots = 65536; - for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144] - .into_iter() - .enumerate() - { + for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144].into_iter().enumerate() { o.sizes[i] = n; o.physical_mut()?.sizes[i] = n; } @@ -100,15 +91,9 @@ impl<'ctx> MtpOriginalInt8<'ctx> { .into_iter() .enumerate() .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold(0usize, |a, (_, n)| { - a.checked_add(n).ok_or(Error::BudgetExceeded) - })?; + .try_fold(0usize, |a, (_, n)| a.checked_add(n).ok_or(Error::BudgetExceeded))?; let need = extras.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(need) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < need - { + if c.allocated_bytes().checked_add(need).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < need { return Err(Error::BudgetExceeded); } for (i, n) in o.sizes.into_iter().enumerate() { @@ -129,11 +114,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } pub fn fully_resident(&self) -> Result { self.validate()?; - Ok(self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.layout.resident)) + Ok(self.physical()?.selected.as_ref().is_some_and(|s| s.layout.resident)) } pub fn actual_pinned_host_bytes(&self) -> Result { let p = self.physical()?; @@ -153,12 +134,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } pub(super) fn read_encoded_page(&self, page: usize, runs: &mut [Vec; 4]) -> Result<()> { if self.fully_resident()? { - return self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_page(page, runs); + return self.physical()?.selected.as_ref().ok_or(Error::ContextPoisoned)?.read_page(page, runs); } let mapped = self.mapped()?; for (i, n) in PAGE_BYTES.into_iter().enumerate() { @@ -184,18 +160,14 @@ impl<'ctx> MtpOriginalInt8<'ctx> { Ok(()) } /// State+retained diagnostic owners only; main bank is counted by paired layout. - pub fn planned_original_state_device_bytes( - max_t: usize, - fully_resident: bool, - ) -> Result { + pub fn planned_original_state_device_bytes(max_t: usize, fully_resident: bool) -> Result { let (_, sizes) = layout(max_t)?; sizes .into_iter() .enumerate() .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold( - ring_state::StateLayout::new(max_t, fully_resident)?.bytes, - |a, (_, n)| a.checked_add(n).ok_or(Error::InvalidSize), - ) + .try_fold(ring_state::StateLayout::new(max_t, fully_resident)?.bytes, |a, (_, n)| { + a.checked_add(n).ok_or(Error::InvalidSize) + }) } } diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtpint8ownerid.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtpint8ownerid.rs index 9649f3a6..d4f0923e 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtpint8ownerid.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtpint8ownerid.rs @@ -72,9 +72,7 @@ impl MtpInt8Snapshot { + std::mem::size_of::() + 8 * std::mem::size_of::() + self.0.pages.len() - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) + * (std::mem::size_of::>() + std::mem::size_of::() + 2 * std::mem::size_of::()) } } impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { @@ -96,10 +94,7 @@ impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { } } impl<'loan, 'buffers> MtpOriginalQuery<'loan, 'buffers> { - pub(crate) fn from_completed_native( - c: &Context<'_>, - query: &'loan DeviceBuffer<'buffers>, - ) -> Result { + pub(crate) fn from_completed_native(c: &Context<'_>, query: &'loan DeviceBuffer<'buffers>) -> Result { checked(c, query, 6144 * 4)?; Ok(Self { query }) } @@ -137,21 +132,16 @@ impl CompletedMtpAttention<'_, '_, '_> { self.owner.validate()?; let bytes = self.owner.buffer(11)?.copy_to_owned(6144 * 4)?; let mut out = Vec::new(); - out.try_reserve_exact(6144) - .map_err(|_| Error::HostAllocation)?; + out.try_reserve_exact(6144).map_err(|_| Error::HostAllocation)?; for x in bytes.chunks_exact(4) { - out.push(f32::from_le_bytes( - x.try_into().map_err(|_| Error::InvalidSize)?, - )); + out.push(f32::from_le_bytes(x.try_into().map_err(|_| Error::InvalidSize)?)); } Ok(out.into_boxed_slice()) } } impl Clone for MtpOriginalRingResources<'_> { fn clone(&self) -> Self { - Self { - physical: Rc::clone(&self.physical), - } + Self { physical: Rc::clone(&self.physical) } } } impl MtpOriginalRingResources<'_> { @@ -162,21 +152,10 @@ impl MtpOriginalRingResources<'_> { MtpInt8OwnerId(self.physical.origin.clone()) } pub fn allocated_bytes(&self) -> usize { - self.physical - .buffers - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() - + self - .physical - .selected - .as_ref() - .map_or(0, |s| s.unique_bytes()) + self.physical.buffers.iter().flatten().map(|b| b.bytes).sum::() + + self.physical.selected.as_ref().map_or(0, |s| s.unique_bytes()) } pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::>() - + 2 * std::mem::size_of::() - + std::mem::size_of::() + std::mem::size_of::>() + 2 * std::mem::size_of::() + std::mem::size_of::() } } diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs index 7512e7e8..78fde6a0 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MtpOriginalInt8<'ctx> { pub fn planned_device_bytes(max_t: usize) -> Result { Ok(layout(max_t)?.1.into_iter().sum()) @@ -18,10 +17,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { std::mem::size_of::() + std::mem::size_of::() + 8 * std::mem::size_of::() - + 65536 - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) + + 65536 * (std::mem::size_of::>() + std::mem::size_of::() + 2 * std::mem::size_of::()) } pub(in super::super) fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { let (slots, sizes) = layout(max_t)?; @@ -37,16 +33,8 @@ impl<'ctx> MtpOriginalInt8<'ctx> { return Err(Error::UnsupportedQwenOperation); } } - let needed = sizes - .into_iter() - .sum::() - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < needed - { + let needed = sizes.into_iter().sum::().checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes().checked_add(needed).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < needed { return Err(Error::BudgetExceeded); } let origin = Rc::new(Origin); @@ -78,25 +66,14 @@ impl<'ctx> MtpOriginalInt8<'ctx> { c.retain_driver(); })?; let load = (|| { - o.physical_mut()?.modules[0] = Some(Module::load( - include_bytes!("../../mtp_original_tail.ptx"), - TAIL_ENTRIES, - )?); - o.physical_mut()?.modules[1] = Some(Module::load( - include_bytes!("../../mtp_original_kv.ptx"), - KV_ENTRIES, - )?); - o.physical_mut()?.modules[2] = Some(Module::load( - include_bytes!("../../qsa_native_decode.ptx"), - ATTN_ENTRIES, - )?); + o.physical_mut()?.modules[0] = + Some(Module::load(include_bytes!("../../mtp_original_tail.ptx"), TAIL_ENTRIES)?); + o.physical_mut()?.modules[1] = + Some(Module::load(include_bytes!("../../mtp_original_kv.ptx"), KV_ENTRIES)?); + o.physical_mut()?.modules[2] = + Some(Module::load(include_bytes!("../../qsa_native_decode.ptx"), ATTN_ENTRIES)?); *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); - if o.physical()? - .mapped - .borrow() - .as_ref() - .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) - { + if o.physical()?.mapped.borrow().as_ref().is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) { return Err(Error::InvalidSize); } Ok(()) @@ -132,35 +109,21 @@ impl<'ctx> MtpOriginalInt8<'ctx> { self.physical.as_deref().ok_or(Error::ContextPoisoned) } pub(in super::super) fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { - Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) - .ok_or(Error::InvalidQwenShape) + Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?).ok_or(Error::InvalidQwenShape) } pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.physical()? - .buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.physical()?.buffers.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn buffers(&self) -> Result<&[Option>; 15]> { Ok(&self.physical()?.buffers) } pub(in super::super) fn mapped(&self) -> Result> { - Ref::filter_map( - self.physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_ref, - ) - .map_err(|_| Error::ContextPoisoned) + Ref::filter_map(self.physical()?.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?, Option::as_ref) + .map_err(|_| Error::ContextPoisoned) } pub(in super::super) fn mapped_mut(&self) -> Result> { RefMut::filter_map( - self.physical()? - .mapped - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?, + self.physical()?.mapped.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?, Option::as_mut, ) .map_err(|_| Error::ContextPoisoned) @@ -178,9 +141,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } pub(crate) fn retain_physical_resources(&self) -> Result> { self.validate()?; - Ok(MtpOriginalRingResources { - physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), - }) + Ok(MtpOriginalRingResources { physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?) }) } pub fn physical_metadata_bytes() -> usize { std::mem::size_of::>() + 2 * std::mem::size_of::() @@ -200,12 +161,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { return Ok(s.span(i, o, n)?.qwen_address()); } } - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.sizes[i], o, n)? - .qwen_address()) + Ok(self.buffer(i)?.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.sizes[i], o, n)?.qwen_address()) } pub fn allocated_bytes(&self) -> usize { self.physical.as_ref().map_or(0, |p| { @@ -217,10 +173,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { self.failed || self.context.is_poisoned() || self.context.handle.is_none() - || self - .physical - .as_ref() - .is_none_or(|p| p.failed.get() || !p.active.get()) + || self.physical.as_ref().is_none_or(|p| p.failed.get() || !p.active.get()) } pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { if !std::ptr::eq(c, self.context) { diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs index 4bb0b4ac..2950556f 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MtpOriginalInt8<'ctx> { pub(in super::super) fn validate(&self) -> Result<()> { if self.is_failed() { @@ -11,12 +10,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } self.physical()?.validate_context(self.context)?; for i in 0..15 { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(i)) - { + if self.physical()?.selected.as_ref().is_some_and(|s| s.provides(i)) { continue; } let b = self.buffer(i)?; @@ -26,12 +20,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { s.reject_main_alias(b)?; } for j in 0..i { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(j)) - { + if self.physical()?.selected.as_ref().is_some_and(|s| s.provides(j)) { continue; } let other = self.buffer(j)?; @@ -57,13 +46,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { ) -> Result { let addr = checked(self.context, b, n)?; self.reject_state_alias(b)?; - if self - .physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_some() - { + if self.physical()?.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_some() { let mapped = self.mapped()?; let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { @@ -145,22 +128,12 @@ impl<'ctx> MtpOriginalInt8<'ctx> { if op.is_ok() { for command in &mut commands { let result = match command { - Command::Kernel { - asset, - index, - grid, - block, - args, - } => modules[*asset] + Command::Kernel { asset, index, grid, block, args } => modules[*asset] .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, 0, stream, args) - }), - Command::Copy { dst, src, bytes } => modules[1] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, stream) - }), + .map_or(Err(Error::ContextPoisoned), |m| m.launch(*index, *grid, *block, 0, stream, args)), + Command::Copy { dst, src, bytes } => { + modules[1].as_ref().map_or(Err(Error::ContextPoisoned), |m| m.copy(*dst, *src, *bytes, stream)) + } }; if let Err(e) = result { op = Err(e); @@ -189,13 +162,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { values: Vec, ) -> Result<()> { commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Kernel { - asset, - index, - grid, - block, - args: Arguments::new(values)?, - }); + commands.push(Command::Kernel { asset, index, grid, block, args: Arguments::new(values)? }); Ok(()) } pub(in super::super) fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { @@ -205,11 +172,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { 11, [64, 1, 1], [256, 1, 1], - vec![ - Arg::U64(a), - Arg::I32(n as i32), - Arg::U64(self.sub(10, status * 4, 4)?), - ], + vec![Arg::U64(a), Arg::I32(n as i32), Arg::U64(self.sub(10, status * 4, 4)?)], ) } pub(in super::super) fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs index df3abf9b..d097f502 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_3.rs @@ -3,27 +3,15 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MtpOriginalInt8<'ctx> { /// Restore real immutable host pages, then exact Original modulo ring blocks. /// The current witness is invalidated BEFORE any write; valid-end guards prevent /// O(1) future-backing pages from incorrectly skipping rematerialization. - pub fn restore( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - s: &MtpInt8Snapshot, - ) -> Result<()> { + pub fn restore(&mut self, w: &mut NativeBatchWorkspace<'ctx>, s: &MtpInt8Snapshot) -> Result<()> { self.validate_snapshot(s)?; w.validate_context(self.context)?; - self.generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - if self - .current - .as_ref() - .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) - { + self.generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; + if self.current.as_ref().is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) { return Ok(()); } let previous = self.current.take(); @@ -32,16 +20,11 @@ impl<'ctx> MtpOriginalInt8<'ctx> { // to the same identity cells before publishing the restored witness. for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) - && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) }) { continue; } - let state = self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let state = self.physical()?.selected.as_ref().ok_or(Error::ContextPoisoned)?; for (i, n) in PAGE_BYTES.into_iter().enumerate() { state.copy_from(i, p * n, &page.runs[i])?; } @@ -51,9 +34,10 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } let mut mapped = self.mapped_mut()?; for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { + if previous + .as_ref() + .is_some_and(|old| p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page))) + { continue; } for (i, n) in PAGE_BYTES.into_iter().enumerate() { @@ -64,9 +48,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { let b1 = s.0.end.div_ceil(4); let b0 = b1.saturating_sub(self.slots); let mut commands = Vec::new(); - commands - .try_reserve_exact(8) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(8).map_err(|_| Error::HostAllocation)?; let mut b = b0; while b < b1 { let slot = b % self.slots; diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs index 32cd067b..2e1b86a0 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MtpOriginalInt8<'ctx> { /// Exact attention tail of record_forward(false). Real input+GR has already /// produced this opaque mixed owner; no full MLP/head work is performed here. @@ -25,22 +24,10 @@ impl<'ctx> MtpOriginalInt8<'ctx> { let wv = self.external(w, weights[1], 512 * 80 * 34)?; let gamma = self.external(w, weights[2], 256 * 4)?; let spans = [ - ( - input.mixed.handle.ok_or(Error::ContextPoisoned)?, - input.mixed.bytes, - ), - ( - weights[0].handle.ok_or(Error::ContextPoisoned)?, - weights[0].bytes, - ), - ( - weights[1].handle.ok_or(Error::ContextPoisoned)?, - weights[1].bytes, - ), - ( - weights[2].handle.ok_or(Error::ContextPoisoned)?, - weights[2].bytes, - ), + (input.mixed.handle.ok_or(Error::ContextPoisoned)?, input.mixed.bytes), + (weights[0].handle.ok_or(Error::ContextPoisoned)?, weights[0].bytes), + (weights[1].handle.ok_or(Error::ContextPoisoned)?, weights[1].bytes), + (weights[2].handle.ok_or(Error::ContextPoisoned)?, weights[2].bytes), ]; for (i, (a, an)) in spans.iter().enumerate() { for (b, bn) in spans.iter().take(i) { @@ -50,25 +37,18 @@ impl<'ctx> MtpOriginalInt8<'ctx> { } } } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let end = input.first + input.rows; let n_pages = end.div_ceil(4); let first_page = input.first / 4; // All new host ownership is fallibly allocated before the first command. let mut pages = Vec::new(); - pages - .try_reserve_exact(n_pages) - .map_err(|_| Error::HostAllocation)?; + pages.try_reserve_exact(n_pages).map_err(|_| Error::HostAllocation)?; for page in prior.0.pages.iter().take(first_page) { pages.push(page.clone()); } let mut changed = Vec::new(); - changed - .try_reserve_exact(n_pages - first_page) - .map_err(|_| Error::HostAllocation)?; + changed.try_reserve_exact(n_pages - first_page).map_err(|_| Error::HostAllocation)?; for p in first_page..n_pages { let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); for (i, n) in PAGE_BYTES.into_iter().enumerate() { @@ -84,12 +64,10 @@ impl<'ctx> MtpOriginalInt8<'ctx> { for t in 0..input.rows { let p = input.first + t; for h in 0..24 { - pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] - .copy_from_slice(&(p as i32).to_le_bytes()); + pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4].copy_from_slice(&(p as i32).to_le_bytes()); } for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { - steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] - .copy_from_slice(&(v as i32).to_le_bytes()); + steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4].copy_from_slice(&(v as i32).to_le_bytes()); } } // The real mixed producer supplies the rewind position. Restoring the @@ -110,9 +88,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { self.copy_from_physical(9, &steps)?; self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; let mut commands = Vec::new(); - commands - .try_reserve_exact(32 + input.rows * 5) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(32 + input.rows * 5).map_err(|_| Error::HostAllocation)?; self.finite(&mut commands, mixed, input.rows * 2560, 0)?; Self::push( &mut commands, @@ -120,11 +96,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { 0, [(input.rows * 2560).div_ceil(256) as u32, 1, 1], [256, 1, 1], - vec![ - Arg::U64(mixed), - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 2560) as i32), - ], + vec![Arg::U64(mixed), Arg::U64(self.address(5)?), Arg::I32((input.rows * 2560) as i32)], )?; Self::push( &mut commands, @@ -132,11 +104,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { 12, [64, 1, 1], [256, 1, 1], - vec![ - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 80) as i32), - Arg::U64(self.sub(10, 4, 4)?), - ], + vec![Arg::U64(self.address(5)?), Arg::I32((input.rows * 80) as i32), Arg::U64(self.sub(10, 4, 4)?)], )?; for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { Self::push( @@ -163,13 +131,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { 9, [2, 1, 1], [256, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(gamma), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1.0e-6), - ], + vec![Arg::U64(k), Arg::U64(gamma), Arg::U64(k), Arg::I32(256), Arg::F32(1.0e-6)], )?; self.finite(&mut commands, k, 512, 4 + 2 * t)?; Self::push( @@ -195,17 +157,11 @@ impl<'ctx> MtpOriginalInt8<'ctx> { let flags = self.flags()?; for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { if *v != 0 { - return Err(if i == 1 { - Error::InvalidQ8Activation - } else { - Error::NonFiniteMmqOutput("mtp-kv-only") - }); + return Err(if i == 1 { Error::InvalidQ8Activation } else { Error::NonFiniteMmqOutput("mtp-kv-only") }); } } let mut append = Vec::new(); - append - .try_reserve_exact(input.rows * 2) - .map_err(|_| Error::HostAllocation)?; + append.try_reserve_exact(input.rows * 2).map_err(|_| Error::HostAllocation)?; let host = self.host_addresses()?; for t in 0..input.rows { Self::push( @@ -255,9 +211,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { self.read_encoded_page(p + first_page, runs)?; } for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { origin: self.origin.clone(), diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs index e135fee0..622ae2fc 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_mtporiginalint8/impl_mtporiginalint8_5.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MtpOriginalInt8<'ctx> { /// Literal Original dense-window INT8 split-K attention. No selected index, /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. @@ -30,10 +29,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { self.restore(w, snapshot)?; self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; let mut steps = [0u8; 16]; - for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] - .into_iter() - .enumerate() - { + for (i, v) in [position, position + 1, (position + 1) / 4, position + 1].into_iter().enumerate() { steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); } self.copy_from_physical(14, &steps)?; @@ -44,21 +40,14 @@ impl<'ctx> MtpOriginalInt8<'ctx> { return Err(Error::NonFiniteMmqOutput("mtp-query")); } let mut commands = Vec::new(); - commands - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; Self::push( &mut commands, 1, 2, [8, 1, 1], [256, 1, 1], - vec![ - Arg::U64(self.address(14)?), - Arg::I32(32768), - Arg::U64(self.address(13)?), - Arg::I64(32768), - ], + vec![Arg::U64(self.address(14)?), Arg::I32(32768), Arg::U64(self.address(13)?), Arg::I64(32768)], )?; let pa = self.address(12)?; let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; @@ -109,11 +98,7 @@ impl<'ctx> MtpOriginalInt8<'ctx> { if self.flags()?[1] != 0 { return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); } - Ok(CompletedMtpAttention { - owner: self, - _snapshot: snapshot, - _query: query, - }) + Ok(CompletedMtpAttention { owner: self, _snapshot: snapshot, _query: query }) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -130,8 +115,6 @@ impl<'ctx> MtpOriginalInt8<'ctx> { if Rc::strong_count(&physical) != 1 { return Err(Error::InvalidQwenShape); } - Rc::get_mut(&mut physical) - .ok_or(Error::InvalidQwenShape)? - .close_inner() + Rc::get_mut(&mut physical).ok_or(Error::InvalidQwenShape)?.close_inner() } } diff --git a/crates/cuda-driver/src/mtp_original_int8/impl_physicalring.rs b/crates/cuda-driver/src/mtp_original_int8/impl_physicalring.rs index 71122860..9c628916 100644 --- a/crates/cuda-driver/src/mtp_original_int8/impl_physicalring.rs +++ b/crates/cuda-driver/src/mtp_original_int8/impl_physicalring.rs @@ -13,12 +13,7 @@ impl PhysicalRing<'_> { || c.is_poisoned() || c.handle.is_none() || self.modules.iter().any(Option::is_none) - || (self.selected.is_none() - && self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none()) + || (self.selected.is_none() && self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none()) { return Err(Error::ContextPoisoned); } @@ -130,11 +125,7 @@ pub(super) fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result Ok(h.qwen_address()) } pub(super) fn rows_range(first: usize, rows: usize, max_t: usize) -> Result<()> { - if !(1..=max_t).contains(&rows) - || first - .checked_add(rows) - .is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) - { + if !(1..=max_t).contains(&rows) || first.checked_add(rows).is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) { return Err(Error::InvalidQwenShape); } Ok(()) diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi.rs b/crates/cuda-driver/src/mtp_original_int8_ffi.rs index dff571b3..2680a28d 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi.rs @@ -12,18 +12,10 @@ pub(crate) struct Arguments { values: Box<[Arg]>, pointers: Vec<*mut c_void>, } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "mtp_original_int8_ffi/enabled.rs"] mod enabled; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::Module; #[cfg(not(all( feature = "cuda-driver", @@ -33,18 +25,10 @@ pub(crate) use enabled::Module; pub(crate) struct Module; const HOST_BYTES: usize = 276_825_088; // Original payload + four256B cursor alignment allowances. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "mtp_original_int8_ffi/host_enabled.rs"] mod host_enabled; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use host_enabled::MappedOwner; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs index 67bb962e..71d98fdc 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/enabled.rs @@ -32,14 +32,7 @@ impl Drop for Library { } } fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ @@ -67,9 +60,7 @@ impl Module { return Err(Error::UnsupportedQwenOperation); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -85,14 +76,10 @@ impl Module { let mut shared = 0; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; if major < 8 || shared < 45584 { return Err(Error::UnsupportedQwenOperation); } @@ -104,17 +91,12 @@ impl Module { module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } @@ -146,19 +128,13 @@ impl Module { args: &mut Arguments, ) -> Result<()> { if grid.contains(&0) - || !matches!( - block, - [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1] - ) + || !matches!(block, [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1]) || !matches!(shared, 0 | 45584) || stream == 0 { return Err(Error::InvalidQwenShape); } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.pointers.clear(); for v in &mut args.values { args.pointers.push(match v { @@ -197,9 +173,7 @@ impl Module { // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners // must outlive the stream drain (graph resources / Context::synchronize on every close path). - check("cuMemcpyAsync", unsafe { - (self.copy)(dst, src, n, stream as *mut c_void) - }) + check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) }) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs index 119df2be..807ed723 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/host_enabled.rs @@ -17,14 +17,7 @@ impl Drop for Library { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -60,9 +53,7 @@ impl MappedOwner { return Err(Error::InvalidSize); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -76,17 +67,9 @@ impl MappedOwner { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - free, - bytes, - }; + let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, free, bytes }; // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { if owner.close().is_err() { if let Some(c) = context { @@ -96,8 +79,7 @@ impl MappedOwner { } return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { if owner.close().is_err() { if let Some(c) = context { c.poison(); @@ -124,18 +106,14 @@ impl MappedOwner { let zero = sym!(library, c"cuMemsetD8Async", Zero); // SAFETY: destination/bytes are a caller-validated whole device span; the memset is enqueued on the legacy default // stream and the caller drains (Context::synchronize) before the span is read or freed. - check("cuMemsetD8Async", unsafe { - zero(destination, 0, bytes, std::ptr::null_mut()) - }) + check("cuMemsetD8Async", unsafe { zero(destination, 0, bytes, std::ptr::null_mut()) }) } pub(crate) fn bytes(&self) -> usize { self.bytes } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { let p = self.host.ok_or(Error::ContextPoisoned)?; @@ -226,13 +204,7 @@ mod tests { } const BYTES: usize = 96; fn owner(b: &Block) -> MappedOwner { - MappedOwner { - library: None, - host: Some(b.addr()), - alias: b.addr() as u64, - free: fake_free, - bytes: BYTES, - } + MappedOwner { library: None, host: Some(b.addr()), alias: b.addr() as u64, free: fake_free, bytes: BYTES } } #[test] fn mapped_audit_int8_write_read_into_stay_inside_and_close_frees_once() { diff --git a/crates/cuda-driver/src/mtp_original_int8_ffi/impl_arguments.rs b/crates/cuda-driver/src/mtp_original_int8_ffi/impl_arguments.rs index e6b8fe32..dda9fc04 100644 --- a/crates/cuda-driver/src/mtp_original_int8_ffi/impl_arguments.rs +++ b/crates/cuda-driver/src/mtp_original_int8_ffi/impl_arguments.rs @@ -11,13 +11,8 @@ impl Arguments { } pub(crate) fn new(values: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(values.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - values: values.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { values: values.into_boxed_slice(), pointers }) } } #[cfg(not(all( @@ -29,15 +24,7 @@ impl Module { pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - _: usize, - _: [u32; 3], - _: [u32; 3], - _: u32, - _: usize, - _: &mut Arguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { diff --git a/crates/cuda-driver/src/mtp_original_logical_prefix.rs b/crates/cuda-driver/src/mtp_original_logical_prefix.rs index f628de05..0af573b5 100644 --- a/crates/cuda-driver/src/mtp_original_logical_prefix.rs +++ b/crates/cuda-driver/src/mtp_original_logical_prefix.rs @@ -29,10 +29,7 @@ impl OriginalMtpSkippedPrefix { pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { ring.validate_snapshot(&self.physical)?; if ring.generation != self.generation - || !ring - .current - .as_ref() - .is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) + || !ring.current.as_ref().is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) { return Err(Error::InvalidQwenShape); } @@ -77,9 +74,7 @@ impl MtpOriginalInt8<'_> { { return Err(Error::InvalidProjectionShape); } - let end = cell0 - .checked_add(residual.rows()) - .ok_or(Error::InvalidSize)?; + let end = cell0.checked_add(residual.rows()).ok_or(Error::InvalidSize)?; if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS { return Err(Error::InvalidProjectionShape); } @@ -94,11 +89,7 @@ impl MtpOriginalInt8<'_> { } old.logical_end } else { - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) - { + if self.current.as_ref().is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) { return Err(Error::InvalidQwenShape); } if self.current.is_none() && physical_prior.0.end != 0 { @@ -114,10 +105,7 @@ impl MtpOriginalInt8<'_> { if end > first_needed { return Ok(None); } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let result = OriginalMtpSkippedPrefix { physical: physical_prior.clone(), generation, @@ -138,18 +126,12 @@ impl MtpOriginalInt8<'_> { /// graph/window guards and successful drain, not these integers, authorize it. pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result { self.validate_snapshot(prior)?; - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) + if self.current.as_ref().is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) || self.current.is_none() && prior.0.end != 0 { return Err(Error::InvalidQwenShape); } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; self.current = None; self.generation = generation; Ok(generation) @@ -177,17 +159,14 @@ impl MtpOriginalInt8<'_> { } // The leading pages are shared with the prior (whole chunks, no per-page work); only the pages from `page0` on are read back. let mut tail = Vec::new(); - tail.try_reserve_exact(page1.saturating_sub(page0)) - .map_err(|_| Error::HostAllocation)?; + tail.try_reserve_exact(page1.saturating_sub(page0)).map_err(|_| Error::HostAllocation)?; for p in page0..page1 { let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); for (i, n) in PAGE_BYTES.into_iter().enumerate() { runs[i] = zero_bytes(n)?; } self.read_encoded_page(p, &mut runs)?; - tail.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + tail.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { origin: self.origin.clone(), diff --git a/crates/cuda-driver/src/mtp_original_native_embedding.rs b/crates/cuda-driver/src/mtp_original_native_embedding.rs index 65dd9e64..83119e6a 100644 --- a/crates/cuda-driver/src/mtp_original_native_embedding.rs +++ b/crates/cuda-driver/src/mtp_original_native_embedding.rs @@ -14,9 +14,7 @@ impl<'ctx> OriginalNativeEmbed<'ctx> { if self.inner.n != 2560 { return Err(Error::InvalidProjectionShape); } - Ok(OriginalMtpNativeEmbedding { - owner: Rc::clone(&self.inner), - }) + Ok(OriginalMtpNativeEmbedding { owner: Rc::clone(&self.inner) }) } } impl<'ctx> OriginalMtpNativeEmbedding<'ctx> { @@ -37,8 +35,7 @@ impl<'ctx> OriginalMtpNativeEmbedding<'ctx> { t: usize, ) -> Result> { self.owner.validate(c)?; - if !(1..=8).contains(&t) || tokens.qwen_address() % 4 != 0 || output.qwen_address() % 4 != 0 - { + if !(1..=8).contains(&t) || tokens.qwen_address() % 4 != 0 || output.qwen_address() % 4 != 0 { return Err(Error::InvalidProjectionShape); } if tokens.overlaps(t * 4, output, t * 10240) { @@ -63,15 +60,8 @@ impl<'ctx> OriginalMtpNativeEmbedding<'ctx> { Arg::Address(output.qwen_address()), ], )?; - self.owner - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .admit(&command)?; - Ok(OriginalMtpNativeGather { - owner: Rc::clone(&self.owner), - command, - }) + self.owner.kernels.as_ref().ok_or(Error::ContextPoisoned)?.admit(&command)?; + Ok(OriginalMtpNativeGather { owner: Rc::clone(&self.owner), command }) } } impl OriginalMtpNativeGather<'_> { @@ -83,10 +73,7 @@ impl OriginalMtpNativeGather<'_> { .kernels .as_ref() .ok_or(Error::ContextPoisoned)? - .launch( - capture.stream_handle(self.owner.context)?, - &mut self.command, - ); + .launch(capture.stream_handle(self.owner.context)?, &mut self.command); if result.as_ref().err().is_some_and(transport) { self.owner.failed.set(true); self.owner.context.poison(); diff --git a/crates/cuda-driver/src/mtp_original_physical_layout.rs b/crates/cuda-driver/src/mtp_original_physical_layout.rs index 6d9bbaed..94d6fde1 100644 --- a/crates/cuda-driver/src/mtp_original_physical_layout.rs +++ b/crates/cuda-driver/src/mtp_original_physical_layout.rs @@ -19,9 +19,7 @@ const WINDOW: usize = 32768; const CHUNKS: usize = 512; fn aligned(n: usize) -> Result { - n.checked_add(ALIGN - 1) - .map(|n| n & !(ALIGN - 1)) - .ok_or(Error::InvalidSize) + n.checked_add(ALIGN - 1).map(|n| n & !(ALIGN - 1)).ok_or(Error::InvalidSize) } fn product(a: usize, b: usize) -> Result { @@ -50,8 +48,7 @@ impl Layout { let attention_scratch = product(product(CHUNKS, HEADS)?, 258 * 4)?; // `moe_hit_grouped_scratch_bytes(10, 2560, ...)` in the upstream // full-row path. The full path is explicitly one row at a time. - let hit_scratch = - 10 * 1280 * 4 + aligned(10 * 20 * 34)? + 2 * aligned(10 * 20 * 4)? + 80 * 4; + let hit_scratch = 10 * 1280 * 4 + aligned(10 * 20 * 34)? + 2 * aligned(10 * 20 * 4)? + 80 * 4; let sizes = [ product(t, 4)?, // tok_ product(t, 32)?, // step_ (2*T rows, four i32s) @@ -106,17 +103,9 @@ impl Layout { let mut bytes: usize = 0; for (i, size) in sizes.iter().copied().enumerate() { offsets[i] = bytes; - bytes = bytes - .checked_add(aligned(size)?) - .ok_or(Error::InvalidSize)?; + bytes = bytes.checked_add(aligned(size)?).ok_or(Error::InvalidSize)?; } - Ok(Self { - t, - cap: WINDOW, - sizes, - offsets, - bytes, - }) + Ok(Self { t, cap: WINDOW, sizes, offsets, bytes }) } pub(super) fn span<'ctx>( @@ -130,12 +119,8 @@ impl Layout { if bytes == 0 || offset.checked_add(bytes).is_none_or(|end| end > size) { return Err(Error::InvalidSize); } - let start = self.offsets[role] - .checked_add(offset) - .ok_or(Error::InvalidSize)?; - bank.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(bank.bytes, start, bytes) + let start = self.offsets[role].checked_add(offset).ok_or(Error::InvalidSize)?; + bank.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(bank.bytes, start, bytes) } /// Maps TailLayout's legacy indices onto their literal MtpDrafter roles. @@ -194,11 +179,7 @@ impl Layout { sizes[out] = self.sizes[role]; offsets[out] = self.offsets[role]; } - Scratch { - sizes, - offsets, - bytes: self.bytes, - } + Scratch { sizes, offsets, bytes: self.bytes } } /// Separately-owned full-path buffers which the upstream carve keeps live @@ -213,11 +194,7 @@ impl Layout { 640, if coupled { 64 } else { 0 }, if coupled { product(4096 + t, 4)? } else { 0 }, - if coupled { - product(vocab.div_ceil(4096), 64 * 8)? - } else { - 0 - }, + if coupled { product(vocab.div_ceil(4096), 64 * 8)? } else { 0 }, product(vocab, 4)?, ]) } @@ -248,9 +225,7 @@ impl Records { pub(super) fn address(&self, offset: usize, bytes: usize) -> Result { self.range(offset, bytes)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } pub(super) fn planned_bytes(t: usize, coupled: bool) -> Result { @@ -260,17 +235,9 @@ impl Records { let records = t .checked_mul(236) .and_then(|n| n.checked_add(384)) - .and_then(|n| { - if coupled { - n.checked_add(64 + 4096 * 4) - } else { - Some(n) - } - }) + .and_then(|n| if coupled { n.checked_add(64 + 4096 * 4) } else { Some(n) }) .ok_or(Error::InvalidSize)?; - aligned(records)? - .checked_add(product(t, 40960)?) - .ok_or(Error::InvalidSize) + aligned(records)?.checked_add(product(t, 40960)?).ok_or(Error::InvalidSize) } } @@ -318,10 +285,7 @@ mod tests { for t in 1..=MAX_T { for coupled in [false, true] { let records = t * 236 + 384 + if coupled { 64 + 4096 * 4 } else { 0 }; - assert_eq!( - Records::planned_bytes(t, coupled), - Ok(((records + 255) & !255) + t * 40960) - ); + assert_eq!(Records::planned_bytes(t, coupled), Ok(((records + 255) & !255) + t * 40960)); } } assert!(Records::planned_bytes(0, false).is_err()); diff --git a/crates/cuda-driver/src/mtp_original_prefill.rs b/crates/cuda-driver/src/mtp_original_prefill.rs index 7c25d6b8..d2456f11 100644 --- a/crates/cuda-driver/src/mtp_original_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill.rs @@ -82,20 +82,8 @@ pub struct OriginalMtpEmbedding<'a, 'ctx> { kind: EmbeddingKind, } enum EmbeddingKind { - Native { - kind: i32, - row_bytes: usize, - vocab: usize, - }, - Compressed { - bits: i32, - bias: i32, - group: usize, - vocab: usize, - codes: usize, - scales: usize, - offsets: bool, - }, + Native { kind: i32, row_bytes: usize, vocab: usize }, + Compressed { bits: i32, bias: i32, group: usize, vocab: usize, codes: usize, scales: usize, offsets: bool }, } /// Explicit Original optional policy. It cannot assert finite tensors, source /// provenance, or readiness. Unsupported options produce fallback, never success. @@ -116,29 +104,9 @@ pub struct DraftKvPolicy { pub multimodal_positions: bool, } enum Cmd { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Args, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, - Gemm { - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - rows: i32, - n: i32, - k: i32, - alpha: f32, - beta: f32, - }, + Kernel { asset: usize, index: usize, grid: [u32; 3], block: [u32; 3], shared: u32, args: Args }, + Copy { dst: u64, src: u64, bytes: usize }, + Gemm { x: BufferHandle, w: BufferHandle, y: BufferHandle, rows: i32, n: i32, k: i32, alpha: f32, beta: f32 }, } struct Region { base: BufferHandle, @@ -158,25 +126,25 @@ pub struct OriginalMtpPrefill<'ctx> { #[path = "mtp_original_scalar_prefill.rs"] mod scalar; -pub use scalar::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, - OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, -}; pub(crate) use scalar::session_assets_sealed; +pub use scalar::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpRetainedFullWeights, + OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, + OriginalMtpStepOutput, +}; #[path = "mtp_original_prefill/impl_completeddraftkv.rs"] mod impl_completeddraftkv; #[allow(unused_imports)] -use impl_completeddraftkv::fastdiv; -#[allow(unused_imports)] use impl_completeddraftkv::aligned; #[allow(unused_imports)] +use impl_completeddraftkv::fastdiv; +#[allow(unused_imports)] use impl_completeddraftkv::q8_bytes; -#[path = "mtp_original_prefill/impl_region.rs"] -mod impl_region; -#[path = "mtp_original_prefill/impl_originalmtpprefill.rs"] -mod impl_originalmtpprefill; #[path = "mtp_original_prefill/impl_drop_for_originalmtpprefill.rs"] mod impl_drop_for_originalmtpprefill; +#[path = "mtp_original_prefill/impl_originalmtpprefill.rs"] +mod impl_originalmtpprefill; +#[path = "mtp_original_prefill/impl_region.rs"] +mod impl_region; diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs index 65969fe7..5139f911 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_completeddraftkv.rs @@ -10,10 +10,7 @@ impl CompletedDraftKv { || ring.generation != self.generation || self.snapshot.0.end != self.end || self.first_materialized >= self.end - || ring - .current - .as_ref() - .is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) + || ring.current.as_ref().is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) { return Err(Error::InvalidQwenShape); } @@ -49,11 +46,7 @@ impl CompletedDraftKv { pub fn snapshot_for_window(&self, position: usize, window: usize) -> Result { if window == 0 || position >= self.end - || position - .checked_add(1) - .ok_or(Error::InvalidSize)? - .saturating_sub(window) - < self.first_materialized + || position.checked_add(1).ok_or(Error::InvalidSize)?.saturating_sub(window) < self.first_materialized { return Err(Error::InvalidQwenShape); } @@ -61,12 +54,7 @@ impl CompletedDraftKv { } } impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { - pub fn native( - table: &'a DeviceBuffer<'ctx>, - kind: i32, - row_bytes: usize, - vocab: usize, - ) -> Result { + pub fn native(table: &'a DeviceBuffer<'ctx>, kind: i32, row_bytes: usize, vocab: usize) -> Result { let per = match kind { 16 => 66, 17 => 74, @@ -92,14 +80,7 @@ impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { { return Err(Error::InvalidProjectionShape); } - Ok(Self { - table, - kind: EmbeddingKind::Native { - kind, - row_bytes, - vocab, - }, - }) + Ok(Self { table, kind: EmbeddingKind::Native { kind, row_bytes, vocab } }) } pub fn compressed( table: &'a DeviceBuffer<'ctx>, @@ -109,43 +90,19 @@ impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { vocab: usize, offsets: bool, ) -> Result { - if !matches!(bits, 2 | 4 | 8) - || group == 0 - || !2560usize.is_multiple_of(group) - || vocab == 0 - || vocab > 262144 + if !matches!(bits, 2 | 4 | 8) || group == 0 || !2560usize.is_multiple_of(group) || vocab == 0 || vocab > 262144 { return Err(Error::InvalidProjectionShape); } - let codes = vocab - .checked_mul(2560 / (8 / bits as usize)) - .ok_or(Error::InvalidSize)?; - let scales = vocab - .checked_mul(2560 / group) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::InvalidSize)?; + let codes = vocab.checked_mul(2560 / (8 / bits as usize)).ok_or(Error::InvalidSize)?; + let scales = vocab.checked_mul(2560 / group).and_then(|n| n.checked_mul(4)).ok_or(Error::InvalidSize)?; let total = codes - .checked_add( - scales - .checked_mul(if offsets { 2 } else { 1 }) - .ok_or(Error::InvalidSize)?, - ) + .checked_add(scales.checked_mul(if offsets { 2 } else { 1 }).ok_or(Error::InvalidSize)?) .ok_or(Error::InvalidSize)?; if table.bytes != total { return Err(Error::InvalidProjectionShape); } - Ok(Self { - table, - kind: EmbeddingKind::Compressed { - bits, - bias, - group, - vocab, - codes, - scales, - offsets, - }, - }) + Ok(Self { table, kind: EmbeddingKind::Compressed { bits, bias, group, vocab, codes, scales, offsets } }) } pub(super) fn vocab(&self) -> usize { match self.kind { @@ -175,19 +132,11 @@ impl DraftKvPolicy { } pub(super) fn fastdiv(d: u32) -> [u32; 3] { let l = 32 - (d - 1).leading_zeros(); - [ - (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, - l, - d, - ] + [(((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, l, d] } pub(super) fn aligned(n: usize) -> Result { - n.checked_add(255) - .map(|n| n & !255) - .ok_or(Error::InvalidSize) + n.checked_add(255).map(|n| n & !255).ok_or(Error::InvalidSize) } pub(super) fn q8_bytes(rows: usize) -> Result { - rows.checked_mul(20 * 144) - .and_then(|n| n.checked_add(128 * 144)) - .ok_or(Error::InvalidSize) + rows.checked_mul(20 * 144).and_then(|n| n.checked_add(128 * 144)).ok_or(Error::InvalidSize) } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs index ee96b281..4506f00a 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpPrefill<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> Result { let assets = [ @@ -13,10 +12,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { include_bytes!("../../mtp_original_prefill_mmq.ptx").as_slice(), include_bytes!("../../mtp_original_prefill_fixup.ptx").as_slice(), ]; - if assets - .iter() - .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) - { + if assets.iter().any(|a| a.windows(8).any(|w| w == b"UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } let mut owner = Self { @@ -44,9 +40,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { })(); let pop = g.finish(); if pop.is_err() - || load.as_ref().is_err_and(|e| { - matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) - }) + || load.as_ref().is_err_and(|e| matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_))) { owner.poison(); } @@ -56,13 +50,8 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { .checked_mul(128 * 128 * 4) .and_then(|n| n.checked_add(FLAG_WORDS * 4)) .ok_or(Error::BudgetExceeded)?; - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) + let required = charge.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -77,8 +66,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { Ok(owner) } pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.tmp.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len) + self.tmp.as_ref().map_or(0, DeviceBuffer::len) } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() @@ -89,16 +77,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { self.context.retain_driver(); } pub(in super::super) fn module(&self, i: usize) -> Result<&Mod> { - self.modules - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.modules.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn status(&self, i: usize) -> Result { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, i * 4, 4) + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, i * 4, 4) } pub(in super::super) fn kernel( cmds: &mut Vec, @@ -110,14 +93,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { args: Vec, ) -> Result<()> { cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args: Args::new(args)?, - }); + cmds.push(Cmd::Kernel { asset, index, grid, block, shared, args: Args::new(args)? }); Ok(()) } pub(in super::super) fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { @@ -128,11 +104,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(words.div_ceil(256)) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(data), - A::I32(words as i32), - A::U64(self.status(stage)?.qwen_address()), - ], + vec![A::U64(data), A::I32(words as i32), A::U64(self.status(stage)?.qwen_address())], ) } pub(in super::super) fn weight( @@ -153,20 +125,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { for (a, len) in [ (region, n), (r, rn), + (self.status.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?, FLAG_WORDS * 4), ( - self.status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - FLAG_WORDS * 4, - ), - ( - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, + self.tmp.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?, self.sms * 128 * 128 * 4, ), ] { diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs index 5c17093a..336dfd17 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpPrefill<'ctx> { #[allow(clippy::too_many_arguments)] pub(in super::super) fn project( @@ -46,10 +45,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } let xq = r.address(17, q8_bytes(rows)?)?; let ids = r.address(18, rows * 4)?; - let bound = r - .handle(19, 16)? - .checked_subspan(16, bound_slot * 8, 8)? - .qwen_address(); + let bound = r.handle(19, 16)?.checked_subspan(16, bound_slot * 8, 8)?.qwen_address(); Self::kernel( cmds, 2, @@ -80,10 +76,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [72, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(xq + (rows * 20 * 144) as u64), - A::I32((128 * 144) as i32), - ], + vec![A::U64(xq + (rows * 20 * 144) as u64), A::I32((128 * 144) as i32)], )?; Self::kernel( cmds, @@ -92,19 +85,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(rows * 20).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(xq), - A::I32((rows * 20) as i32), - A::U64(self.status(stage)?.qwen_address()), - ], + vec![A::U64(xq), A::I32((rows * 20) as i32), A::U64(self.status(stage)?.qwen_address())], )?; let tmp = if fix { - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() + self.tmp.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address() } else { 0 }; diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs index 3c762cae..e8ae71ec 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpPrefill<'ctx> { pub(in super::super) fn run( &mut self, @@ -14,12 +13,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { ) -> Result<()> { let mut readback = zero_bytes(FLAG_WORDS * 4)?; let zero = zero_bytes(FLAG_WORDS * 4)?; - let status = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; + let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; status.validate_projection_extent(FLAG_WORDS * 4, 4)?; for i in 0..5 { self.module(i)?; @@ -49,33 +43,17 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { if operation.is_ok() { for c in &mut cmds { let r = match c { - Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args, - } => self.modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { + Cmd::Kernel { asset, index, grid, block, shared, args } => { + self.modules[*asset].as_ref().map_or(Err(Error::ContextPoisoned), |m| { m.launch(*index, *grid, *block, *shared, blas.stream(), args) - }), + }) + } Cmd::Copy { dst, src, bytes } => self.modules[0] .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, blas.stream()) - }), - Cmd::Gemm { - x, - w, - y, - rows, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), + .map_or(Err(Error::ContextPoisoned), |m| m.copy(*dst, *src, *bytes, blas.stream())), + Cmd::Gemm { x, w, y, rows, n, k, alpha, beta } => { + blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta) + } }; if let Err(e) = r { operation = Err(e); diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs index 7902b937..2021feab 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpPrefill<'ctx> { #[allow(clippy::too_many_arguments)] pub fn record<'arena, 'loan>( @@ -27,28 +26,17 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); } if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedStorage)); } if policy.alternate_f16 { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); } if policy.rope_table_enabled || policy.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedRopeTable)); } - if [ - policy.theta_scale, - policy.freq_scale, - policy.corr_low, - policy.corr_high, - policy.ext_factor, - policy.mscale, - ] - .iter() - .any(|x| !x.is_finite()) + if [policy.theta_scale, policy.freq_scale, policy.corr_low, policy.corr_high, policy.ext_factor, policy.mscale] + .iter() + .any(|x| !x.is_finite()) || policy.theta_scale <= 0.0 || policy.freq_scale <= 0.0 || policy.mscale <= 0.0 @@ -62,16 +50,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { || !residual.context_matches(self.context) || tokens.len() != residual.rows() || tokens.len() > 8192 - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || cell0.checked_add(tokens.len()).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) { return Err(Error::InvalidProjectionShape); } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { + if tokens.iter().any(|t| *t < 0 || *t as usize >= embedding.vocab()) { return Err(Error::InvalidProjectionShape); } let r0 = first_needed.saturating_sub(cell0); @@ -84,9 +67,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); }; crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); - if !WIDTHS.into_iter().any(|j| { - 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize - }) { + if !WIDTHS + .into_iter() + .any(|j| 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize) + { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); } let weight_refs = [ @@ -115,24 +99,38 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { ]; let mut wh = [region; 10]; for i in 0..10 { - wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; + wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { + crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); + e + })?; } crate::bringup_trace!("DBG prefill.record: 10 weights staged"); - let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); e })?; + let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { + crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); + e + })?; crate::bringup_trace!("DBG prefill.record: embedding table staged"); for (i, a) in weight_refs.iter().enumerate() { for b in weight_refs.iter().take(i) { - let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; - let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; - if ah.overlaps(a.bytes, bh, b.bytes) - && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) + let ah = a.handle.ok_or_else(|| { + crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); + Error::ContextPoisoned + })?; + let bh = b.handle.ok_or_else(|| { + crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); + Error::ContextPoisoned + })?; + if ah.overlaps(a.bytes, bh, b.bytes) && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) { return Err(Error::OutputAliasesInput); } } } for b in weight_refs { - let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; + let h = b.handle.ok_or_else(|| { + crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); + Error::ContextPoisoned + })?; if eh.overlaps(embedding.table.bytes, h, b.bytes) && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) { @@ -140,7 +138,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } } // Actual input residual lies outside the region being overwritten. - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { + crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); + e + })?; crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); if rh.overlaps(rbytes, region, region_bytes) { return Err(Error::OutputAliasesInput); @@ -160,22 +161,15 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } } crate::bringup_trace!("DBG prefill.record: overlap checks ok"); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let end = cell0 + tokens.len(); let first = cell0 + r0; let first_page = first / 4; let page_count = end.div_ceil(4); let mut pages = Vec::new(); - pages - .try_reserve_exact(page_count) - .map_err(|_| Error::HostAllocation)?; + pages.try_reserve_exact(page_count).map_err(|_| Error::HostAllocation)?; let mut changed = Vec::new(); - changed - .try_reserve_exact(page_count - first_page) - .map_err(|_| Error::HostAllocation)?; + changed.try_reserve_exact(page_count - first_page).map_err(|_| Error::HostAllocation)?; for p in 0..page_count { if p < first_page { if let Some(page) = prior.0.pages.get(p) { @@ -188,9 +182,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { runs[i] = zero_bytes(n)?; } if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } else { changed.push(runs); } @@ -200,8 +192,14 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } // Genuine idle dependency before this stream can mutate the real drafter KV. crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); - ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot - ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; + ring.execute(workspace, Vec::new()).map_err(|e| { + crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); + e + })?; // genuine global + shared drafter stream idle, even identical snapshot + ring.restore(workspace, prior).map_err(|e| { + crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); + e + })?; crate::bringup_trace!("DBG prefill.record: ring restored"); ring.current = None; for b0 in (r0..tokens.len()).step_by(r.b) { @@ -212,18 +210,13 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { return Ok(DraftKvOutcome::Cancelled); } let mut commands = Vec::new(); - commands - .try_reserve_exact(80) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(80).map_err(|_| Error::HostAllocation)?; let mut tk = zero_bytes(nb * 4)?; for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { dst.copy_from_slice(&t.to_le_bytes()); } let mut bounds = zero_bytes(16)?; - for (dst, v) in bounds - .chunks_exact_mut(4) - .zip([0, nb as i32, 0, (nb * 4) as i32]) - { + for (dst, v) in bounds.chunks_exact_mut(4).zip([0, nb as i32, 0, (nb * 4) as i32]) { dst.copy_from_slice(&v.to_le_bytes()); } Self::kernel( @@ -238,9 +231,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { let emb = r.address(0, nb * 10240)?; let tok = r.address(16, nb * 4)?; match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( + EmbeddingKind::Native { kind, row_bytes, .. } => Self::kernel( &mut commands, 1, 0, @@ -256,15 +247,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { A::U64(emb), ], )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( + EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => Self::kernel( &mut commands, 0, 5, @@ -274,11 +257,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { vec![ A::U64(eh.qwen_address()), A::U64(eh.qwen_address() + codes as u64), - A::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), + A::U64(if offsets { eh.qwen_address() + (codes + scales) as u64 } else { 0 }), A::U64(tok), A::I64(2560), A::I32(bits), @@ -298,35 +277,17 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [nb as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(emb), - A::U64(wh[0].qwen_address()), - A::I64(2560), - A::I64(2560), - A::F32(1e-6), - ], + vec![A::U64(emb), A::U64(wh[0].qwen_address()), A::I64(2560), A::I64(2560), A::F32(1e-6)], )?; self.finite(&mut commands, emb, nb * 2560, 1)?; let e2 = r.address(1, nb * 10240)?; - self.project( - &mut commands, - &r, - emb, - wh[1].qwen_address(), - e2, - nb, - 2560, - 0, - 2, - )?; + self.project(&mut commands, &r, emb, wh[1].qwen_address(), e2, nb, 2560, 0, 2)?; self.finite(&mut commands, e2, nb * 2560, 2)?; let hn = r.address(3, nb * 40960)?; let h2 = r.address(4, nb * 40960)?; commands.push(Cmd::Copy { dst: hn, - src: rh - .checked_subspan(rbytes, b0 * 40960, nb * 40960)? - .qwen_address(), + src: rh.checked_subspan(rbytes, b0 * 40960, nb * 40960)?.qwen_address(), bytes: nb * 40960, }); Self::kernel( @@ -336,26 +297,10 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [nb as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(hn), - A::U64(wh[2].qwen_address()), - A::I64(10240), - A::I64(10240), - A::F32(1e-6), - ], + vec![A::U64(hn), A::U64(wh[2].qwen_address()), A::I64(10240), A::I64(10240), A::F32(1e-6)], )?; self.finite(&mut commands, hn, nb * 10240, 3)?; - self.project( - &mut commands, - &r, - hn, - wh[3].qwen_address(), - h2, - nb * 4, - 2560, - 1, - 4, - )?; + self.project(&mut commands, &r, hn, wh[3].qwen_address(), h2, nb * 4, 2560, 1, 4)?; self.finite(&mut commands, h2, nb * 10240, 4)?; let rm = r.address(5, nb * 40960)?; let gated = r.address(6, nb * 40960)?; @@ -382,14 +327,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 4) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(rm), - A::U64(wh[4].qwen_address()), - A::F32(1e-6), - A::U64(grs), - A::U64(xn), - A::U64(0), - ], + vec![A::U64(rm), A::U64(wh[4].qwen_address()), A::F32(1e-6), A::U64(grs), A::U64(xn), A::U64(0)], )?; self.finite(&mut commands, grs, nb * 4, 6)?; Self::kernel( @@ -414,11 +352,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 10240).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(xn), - A::I32((nb * 10240) as i32), - A::U64(self.status(6)?.qwen_address()), - ], + vec![A::U64(xn), A::I32((nb * 10240) as i32), A::U64(self.status(6)?.qwen_address())], )?; commands.push(Cmd::Gemm { x: r.handle(8, nb * 20480)?, @@ -438,12 +372,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 320).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(lo), - A::U64(lo16), - A::U64(0), - A::I64((nb * 320) as i64), - ], + vec![A::U64(lo), A::U64(lo16), A::U64(0), A::I64((nb * 320) as i64)], )?; Self::kernel( &mut commands, @@ -452,11 +381,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 320).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(lo), - A::U64(self.status(8)?.qwen_address()), - A::I64(nb as i64), - ], + vec![A::U64(lo), A::U64(self.status(8)?.qwen_address()), A::I64(nb as i64)], )?; Self::kernel( &mut commands, @@ -465,11 +390,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 320).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(lo16), - A::I32((nb * 320) as i32), - A::U64(self.status(8)?.qwen_address()), - ], + vec![A::U64(lo16), A::I32((nb * 320) as i32), A::U64(self.status(8)?.qwen_address())], )?; commands.push(Cmd::Gemm { x: r.handle(10, nb * 640)?, @@ -520,29 +441,9 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { self.finite(&mut commands, mixed, nb * 2560, 10)?; let kc = r.address(14, nb * 2048)?; let vc = r.address(15, nb * 2048)?; - self.project( - &mut commands, - &r, - mixed, - wh[7].qwen_address(), - kc, - nb, - 512, - 0, - 11, - )?; + self.project(&mut commands, &r, mixed, wh[7].qwen_address(), kc, nb, 512, 0, 11)?; self.finite(&mut commands, kc, nb * 512, 11)?; - self.project( - &mut commands, - &r, - mixed, - wh[8].qwen_address(), - vc, - nb, - 512, - 0, - 12, - )?; + self.project(&mut commands, &r, mixed, wh[8].qwen_address(), vc, nb, 512, 0, 12)?; self.finite(&mut commands, vc, nb * 512, 12)?; Self::kernel( &mut commands, @@ -551,13 +452,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { [(nb * 2) as u32, 1, 1], [256, 1, 1], 0, - vec![ - A::U64(kc), - A::U64(wh[9].qwen_address()), - A::I64(256), - A::I64(256), - A::F32(1e-6), - ], + vec![A::U64(kc), A::U64(wh[9].qwen_address()), A::I64(256), A::I64(256), A::F32(1e-6)], )?; self.finite(&mut commands, kc, nb * 512, 13)?; Self::kernel( @@ -584,12 +479,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { ], )?; self.finite(&mut commands, kc, nb * 512, 14)?; - self.run( - rows, - workspace, - commands, - vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)], - )?; + self.run(rows, workspace, commands, vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)])?; if cancelled() { return Ok(DraftKvOutcome::Cancelled); } @@ -599,9 +489,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; } let mut append = Vec::new(); - append - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; + append.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; Self::kernel( &mut append, 0, @@ -654,9 +542,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } drop(mapped); for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { origin: ring.origin.clone(), @@ -666,11 +552,6 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { })); ring.current = Some(snapshot.clone()); ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) + Ok(DraftKvOutcome::Completed(CompletedDraftKv { snapshot, first_materialized: first, end, generation })) } } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs index 5cc48f6d..1e5e34b6 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_5.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpPrefill<'ctx> { pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_region.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_region.rs index 132f819e..2faabba0 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_region.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_region.rs @@ -47,12 +47,7 @@ impl Region { return Ok(None); } base.validate_projection_extent(bytes, 256)?; - Ok(Some(Self { - base, - bytes, - b, - roles, - })) + Ok(Some(Self { base, bytes, b, roles })) } pub(super) fn handle(&self, i: usize, len: usize) -> Result { let (offset, extent) = self.roles.get(i).copied().ok_or(Error::InvalidSize)?; diff --git a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs index df0e5a0b..bfb0a1a8 100644 --- a/crates/cuda-driver/src/mtp_original_prefill_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_prefill_ffi.rs @@ -7,9 +7,9 @@ pub(crate) enum Arg { I32(i32), I64(i64), F32(f32), - U3([u32;3]), - Words3([u64;3]), - Words8([u64;8]), + U3([u32; 3]), + Words3([u64; 3]), + Words8([u64; 8]), } pub(crate) struct Arguments { values: Box<[Arg]>, @@ -18,27 +18,18 @@ pub(crate) struct Arguments { impl Arguments { pub(crate) fn new(values: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(values.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - values: values.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { values: values.into_boxed_slice(), pointers }) } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; - type FunctionAttr = unsafe extern "C" fn(*mut c_void,i32,i32)->i32; + type FunctionAttr = unsafe extern "C" fn(*mut c_void, i32, i32) -> i32; type Unload = unsafe extern "C" fn(*mut c_void) -> i32; - type Copy = unsafe extern "C" fn(u64,u64,usize,*mut c_void)->i32; + type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; type Device = unsafe extern "C" fn(*mut i32) -> i32; type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; type Launch = unsafe extern "C" fn( @@ -66,14 +57,7 @@ mod enabled { } } fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ @@ -102,9 +86,7 @@ mod enabled { return Err(Error::UnsupportedQwenOperation); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -120,37 +102,28 @@ mod enabled { let mut shared = 0; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 { return Err(Error::UnsupportedQwenOperation); } let mut owner = Self { launch: sym!(l, c"cuLaunchKernel", Launch), unload: sym!(l, c"cuModuleUnload", Unload), - copy: sym!(l,c"cuMemcpyAsync",Copy), - attr: sym!(l,c"cuFuncSetAttribute",FunctionAttr), + copy: sym!(l, c"cuMemcpyAsync", Copy), + attr: sym!(l, c"cuFuncSetAttribute", FunctionAttr), library: Some(l), module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } @@ -172,42 +145,50 @@ mod enabled { } Ok(owner) } - pub(crate) fn info(&self)->Result<(usize,u32)>{ - let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; - let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); + pub(crate) fn info(&self) -> Result<(usize, u32)> { + let l = self.library.as_ref().ok_or(Error::ContextPoisoned)?; + let device = sym!(l, c"cuCtxGetDevice", Device); + let attr = sym!(l, c"cuDeviceGetAttribute", Attr); // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; - let mut sms=0;let mut shared=0; + let mut d = 0; + check("cuCtxGetDevice", unsafe { device(&mut d) })?; + let mut sms = 0; + let mut shared = 0; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute(SM)",unsafe{attr(&mut sms,16,d)})?; + check("cuDeviceGetAttribute(SM)", unsafe { attr(&mut sms, 16, d) })?; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute(shared optin)",unsafe{attr(&mut shared,97,d)})?; - if sms<=0||sms>4096||shared<=0{return Err(Error::InvalidDriverValue("MTP MMQ device geometry"));} - Ok((crate::arch_ptx::forced_sms(sms as u32) as usize,shared as u32)) + check("cuDeviceGetAttribute(shared optin)", unsafe { attr(&mut shared, 97, d) })?; + if sms <= 0 || sms > 4096 || shared <= 0 { + return Err(Error::InvalidDriverValue("MTP MMQ device geometry")); + } + Ok((crate::arch_ptx::forced_sms(sms as u32) as usize, shared as u32)) } pub(crate) fn launch( &self, index: usize, grid: [u32; 3], - block: [u32;3], + block: [u32; 3], shared: u32, stream: usize, args: &mut Arguments, ) -> Result<()> { if grid.contains(&0) - || !matches!(block, [64,1,1] | [128,1,1] | [256,1,1] | [1024,1,1] | [32,4,1] | [32,8,1] | [32,1,1]) - || !(shared==0 || [8usize,16,24,32,40,48,64,80,96,112,128].into_iter().any(|j|shared as usize==128*76*4+j*4+(j*144).div_ceil(1024)*1024)) + || !matches!( + block, + [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1] | [32, 8, 1] | [32, 1, 1] + ) + || !(shared == 0 + || [8usize, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128] + .into_iter() + .any(|j| shared as usize == 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024)) || stream == 0 { return Err(Error::InvalidQwenShape); } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.pointers.clear(); for v in &mut args.values { args.pointers.push(match v { @@ -222,7 +203,9 @@ mod enabled { } // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); // attribute id and value are plain integers. - if shared != 0 {check("cuFuncSetAttribute",unsafe{(self.attr)(f as *mut c_void,8,shared as i32)})?;} + if shared != 0 { + check("cuFuncSetAttribute", unsafe { (self.attr)(f as *mut c_void, 8, shared as i32) })?; + } // SAFETY: the function belongs to the module this owner still holds (unloaded only by close_inner/Drop); `stream` is a // handle of a live stream owner that is synchronized before it is destroyed; every pointer in `pointers` was rebuilt // just above to point into the boxed, never-resized argument storage with the size/type the kernel's .param declares; @@ -245,12 +228,14 @@ mod enabled { }) } // Addresses are derived only by this producer from actual whole owners. - pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { - if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } + pub(crate) fn copy(&self, dst: u64, src: u64, n: usize, stream: usize) -> Result<()> { + if n == 0 || stream == 0 || dst == 0 || src == 0 { + return Err(Error::InvalidSize); + } // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners // must outlive the stream drain (graph resources / Context::synchronize on every close path). - check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) + check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) }) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() @@ -277,11 +262,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::Module; #[cfg(not(all( feature = "cuda-driver", @@ -295,25 +276,19 @@ pub(crate) struct Module; target_pointer_width = "64" )))] impl Module { - pub(crate) fn info(&self)->Result<(usize,u32)>{Err(Error::UnsupportedPlatform)} + pub(crate) fn info(&self) -> Result<(usize, u32)> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - _: usize, - _: [u32; 3], - _: [u32;3], - _: u32, - _: usize, - _: &mut Arguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy(&self,_:u64,_:u64,_:usize,_:usize)->Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn close(self) -> Result<()> { Ok(()) } } - - diff --git a/crates/cuda-driver/src/mtp_original_prefill_symbols.rs b/crates/cuda-driver/src/mtp_original_prefill_symbols.rs index a9c67a21..1d59b8c7 100644 --- a/crates/cuda-driver/src/mtp_original_prefill_symbols.rs +++ b/crates/cuda-driver/src/mtp_original_prefill_symbols.rs @@ -1,27 +1,27 @@ use std::ffi::CStr; -pub(super) const PROJECT:&[&CStr]=&[ - c"_Z9mul_mat_qIL9ggml_type8ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", - c"_Z9mul_mat_qIL9ggml_type8ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", +pub(super) const PROJECT: &[&CStr] = &[ + c"_Z9mul_mat_qIL9ggml_type8ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", + c"_Z9mul_mat_qIL9ggml_type8ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_", ]; -pub(super) const FIXUP:&[&CStr]=&[ - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", - c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", +pub(super) const FIXUP: &[&CStr] = &[ + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", + c"_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_", ]; diff --git a/crates/cuda-driver/src/mtp_original_ring_state/a16_fn.rs b/crates/cuda-driver/src/mtp_original_ring_state/a16_fn.rs index c005374b..e869a8a4 100644 --- a/crates/cuda-driver/src/mtp_original_ring_state/a16_fn.rs +++ b/crates/cuda-driver/src/mtp_original_ring_state/a16_fn.rs @@ -11,16 +11,8 @@ impl StateLayout { if !(1..=8).contains(&t) { return Err(Error::InvalidQwenShape); } - let slots = if resident { - MTP_ORIGINAL_MAX_CELLS / 4 - } else { - (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4) - }; - let pooled = if resident { - MTP_ORIGINAL_MAX_CELLS / 4 + 2 - } else { - 2 - }; + let slots = if resident { MTP_ORIGINAL_MAX_CELLS / 4 } else { (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4) }; + let pooled = if resident { MTP_ORIGINAL_MAX_CELLS / 4 + 2 } else { 2 }; // Literal qsa_state_init, INT8, without_key=false, share_rope!=nullptr. let sizes = [ slots * 2048, @@ -50,12 +42,6 @@ impl StateLayout { if used > bytes { return Err(Error::InvalidSize); } - Ok(Self { - sizes, - offsets, - bytes, - slots, - resident, - }) + Ok(Self { sizes, offsets, bytes, slots, resident }) } } diff --git a/crates/cuda-driver/src/mtp_original_ring_state/impl_selected.rs b/crates/cuda-driver/src/mtp_original_ring_state/impl_selected.rs index ca162044..4d70821a 100644 --- a/crates/cuda-driver/src/mtp_original_ring_state/impl_selected.rs +++ b/crates/cuda-driver/src/mtp_original_ring_state/impl_selected.rs @@ -57,11 +57,7 @@ impl<'ctx> Selected<'ctx> { return Err(Error::InvalidSize); } let (b, base, size) = match i { - 0..=4 => ( - self.state.as_ref().ok_or(Error::ContextPoisoned)?, - self.layout.offsets[i], - self.layout.sizes[i], - ), + 0..=4 => (self.state.as_ref().ok_or(Error::ContextPoisoned)?, self.layout.offsets[i], self.layout.sizes[i]), 5..=9 | 12 | 13 => { let k = match i { 5 => 0, @@ -75,11 +71,7 @@ impl<'ctx> Selected<'ctx> { let (o, s) = self.main_spans[k]; (&*self.main, o, s) } - 14 => ( - self.state.as_ref().ok_or(Error::ContextPoisoned)?, - self.layout.offsets[9], - self.layout.sizes[9], - ), + 14 => (self.state.as_ref().ok_or(Error::ContextPoisoned)?, self.layout.offsets[9], self.layout.sizes[9]), _ => return Err(Error::InvalidSize), }; if offset.checked_add(n).is_none_or(|e| e > size) { @@ -109,10 +101,7 @@ impl<'ctx> Selected<'ctx> { return Err(Error::OutputAliasesInput); } for (i, (o, n)) in self.main_spans.into_iter().enumerate() { - self.main - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.main_bytes, o, n)?; + self.main.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.main_bytes, o, n)?; for (p, m) in self.main_spans.iter().take(i) { if o < *p + *m && *p < o + n { return Err(Error::OutputAliasesInput); @@ -179,8 +168,7 @@ impl<'ctx> Selected<'ctx> { pub(in super::super) fn copy_from(&self, i: usize, offset: usize, input: &[u8]) -> Result<()> { let h = self.span(i, offset, input.len())?; let mut v = Vec::new(); - v.try_reserve_exact(input.len()) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(input.len()).map_err(|_| Error::HostAllocation)?; v.extend_from_slice(input); self.transfer(h, v, false).map(|_| ()) } diff --git a/crates/cuda-driver/src/mtp_original_ring_state/pin_failure_fn.rs b/crates/cuda-driver/src/mtp_original_ring_state/pin_failure_fn.rs index a2904778..e37d1ca1 100644 --- a/crates/cuda-driver/src/mtp_original_ring_state/pin_failure_fn.rs +++ b/crates/cuda-driver/src/mtp_original_ring_state/pin_failure_fn.rs @@ -5,38 +5,19 @@ use super::*; /// Only actual CUDA pinned allocation/mapping failures choose Original fallback. pub(in super::super) fn pin_failure(e: &Error) -> bool { - matches!( - e, - Error::Driver { - operation: "cuMemHostAlloc" | "cuMemHostGetDevicePointer_v2", - .. - } - ) + matches!(e, Error::Driver { operation: "cuMemHostAlloc" | "cuMemHostGetDevicePointer_v2", .. }) } impl<'ctx> PreparedState<'ctx> { pub(super) fn attempt(c: &'ctx Context<'ctx>, t: usize, resident: bool) -> Result { let layout = StateLayout::new(t, resident)?; - let need = layout - .bytes - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; + let need = layout.bytes.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; if c.is_poisoned() { return Err(Error::ContextPoisoned); } - if c.allocated_bytes() - .checked_add(need) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < need - { + if c.allocated_bytes().checked_add(need).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < need { return Err(Error::BudgetExceeded); } - let mut o = Self { - context: c, - layout, - state: None, - pinned: std::array::from_fn(|_| None), - mapped: None, - }; + let mut o = Self { context: c, layout, state: None, pinned: std::array::from_fn(|_| None), mapped: None }; let op = (|| { o.state = Some(c.allocate(o.layout.bytes)?); let g = c.enter().inspect_err(|_| { @@ -47,10 +28,7 @@ impl<'ctx> PreparedState<'ctx> { o.pinned[0] = Some(MappedOwner::new_for_state(c, 20)?); o.pinned[1] = Some(MappedOwner::new_for_state(c, 96)?); if !resident { - o.mapped = Some(MappedOwner::new_for_state( - c, - MTP_ORIGINAL_PINNED_HOST_BYTES, - )?); + o.mapped = Some(MappedOwner::new_for_state(c, MTP_ORIGINAL_PINNED_HOST_BYTES)?); } Ok(()) })(); diff --git a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs index aa165697..7364bd55 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_ffi.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_ffi.rs @@ -7,43 +7,36 @@ pub(crate) enum Arg { I32(i32), I64(i64), F32(f32), - Words3([u64;3]), - GrMulti(Box<[u64;114]>), + Words3([u64; 3]), + GrMulti(Box<[u64; 114]>), } pub(crate) struct Arguments { values: Box<[Arg]>, pointers: Vec<*mut c_void>, } impl Arguments { - pub(crate) fn metadata_bytes(&self)->usize{ - std::mem::size_of::()+self.values.len()*std::mem::size_of::()+self.pointers.capacity()*std::mem::size_of::<*mut c_void>() - +self.values.iter().map(|a|if matches!(a,Arg::GrMulti(_)){114*8}else{0}).sum::() + pub(crate) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + self.values.len() * std::mem::size_of::() + + self.pointers.capacity() * std::mem::size_of::<*mut c_void>() + + self.values.iter().map(|a| if matches!(a, Arg::GrMulti(_)) { 114 * 8 } else { 0 }).sum::() } pub(crate) fn new(values: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(values.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - values: values.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { values: values.into_boxed_slice(), pointers }) } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> i32; - type FunctionAttr = unsafe extern "C" fn(*mut c_void,i32,i32)->i32; + type FunctionAttr = unsafe extern "C" fn(*mut c_void, i32, i32) -> i32; type Unload = unsafe extern "C" fn(*mut c_void) -> i32; - type Copy = unsafe extern "C" fn(u64,u64,usize,*mut c_void)->i32; - type H2D = unsafe extern "C" fn(u64,*const c_void,usize,*mut c_void)->i32; + type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; + type H2D = unsafe extern "C" fn(u64, *const c_void, usize, *mut c_void) -> i32; type Device = unsafe extern "C" fn(*mut i32) -> i32; type Attr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; type Launch = unsafe extern "C" fn( @@ -71,14 +64,7 @@ mod enabled { } } fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ @@ -108,9 +94,7 @@ mod enabled { return Err(Error::UnsupportedQwenOperation); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -126,38 +110,29 @@ mod enabled { let mut shared = 0; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; if !crate::arch_ptx::cc_major_ok(major) || shared < 45584 { return Err(Error::UnsupportedQwenOperation); } let mut owner = Self { launch: sym!(l, c"cuLaunchKernel", Launch), unload: sym!(l, c"cuModuleUnload", Unload), - copy: sym!(l,c"cuMemcpyAsync",Copy), - h2d: sym!(l,c"cuMemcpyHtoDAsync_v2",H2D), - attr: sym!(l,c"cuFuncSetAttribute",FunctionAttr), + copy: sym!(l, c"cuMemcpyAsync", Copy), + h2d: sym!(l, c"cuMemcpyHtoDAsync_v2", H2D), + attr: sym!(l, c"cuFuncSetAttribute", FunctionAttr), library: Some(l), module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } @@ -181,51 +156,58 @@ mod enabled { } // Literal down_chunk geometry: sm75 uses1280, others2560; preVolta // uses actual per-block shared capacity rather than opt-in promise. - pub(crate) fn configure_gr(&self)->Result<(usize,usize)> { - let l=self.library.as_ref().ok_or(Error::ContextPoisoned)?; - let device=sym!(l,c"cuCtxGetDevice",Device);let attr=sym!(l,c"cuDeviceGetAttribute",Attr); + pub(crate) fn configure_gr(&self) -> Result<(usize, usize)> { + let l = self.library.as_ref().ok_or(Error::ContextPoisoned)?; + let device = sym!(l, c"cuCtxGetDevice", Device); + let attr = sym!(l, c"cuDeviceGetAttribute", Attr); // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - let mut d=0;check("cuCtxGetDevice",unsafe{device(&mut d)})?; - let mut optin=0;let mut major=0;let mut minor=0;let mut per_block=0; - for (value,key) in [(&mut optin,97),(&mut major,75),(&mut minor,76),(&mut per_block,8)]{ + let mut d = 0; + check("cuCtxGetDevice", unsafe { device(&mut d) })?; + let mut optin = 0; + let mut major = 0; + let mut minor = 0; + let mut per_block = 0; + for (value, key) in [(&mut optin, 97), (&mut major, 75), (&mut minor, 76), (&mut per_block, 8)] { // SAFETY: valid out-pointers to live locals; the owning context is current because the caller runs inside // `Context::enter` (module load / geometry probes are never called without it). - check("cuDeviceGetAttribute(GR)",unsafe{attr(value,key,d)})?; + check("cuDeviceGetAttribute(GR)", unsafe { attr(value, key, d) })?; + } + let tile = if major * 10 + minor == 75 { 1280 } else { 2560 }; + let usable = if major >= 7 && optin > 0 { optin } else { per_block }; + if usable <= 0 { + return Err(Error::InvalidDriverValue("Original GR shared geometry")); } - let tile=if major*10+minor==75{1280}else{2560}; - let usable=if major>=7&&optin>0{optin}else{per_block}; - if usable<=0{return Err(Error::InvalidDriverValue("Original GR shared geometry"));} // Original sets both down-kernel attributes once, before launches. - for (index,want) in [(if tile==1280{4}else{5},8*tile*4),(2,2*8*1280*4)]{ - let want=if optin>0{want.min(optin as usize)}else{want}; - let function=*self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; + for (index, want) in [(if tile == 1280 { 4 } else { 5 }, 8 * tile * 4), (2, 2 * 8 * 1280 * 4)] { + let want = if optin > 0 { want.min(optin as usize) } else { want }; + let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; // SAFETY: the function handle belongs to this live module and the context is current (caller holds `Context::enter`); // attribute id and value are plain integers. - check("cuFuncSetAttribute",unsafe{(self.attr)(function as *mut c_void,8,want as i32)})?; + check("cuFuncSetAttribute", unsafe { (self.attr)(function as *mut c_void, 8, want as i32) })?; } - Ok((usable as usize,tile)) + Ok((usable as usize, tile)) } pub(crate) fn launch( &self, index: usize, grid: [u32; 3], - block: [u32;3], + block: [u32; 3], shared: u32, stream: usize, args: &mut Arguments, ) -> Result<()> { if grid.contains(&0) - || !matches!(block, [64,1,1] | [128,1,1] | [256,1,1] | [1024,1,1] | [32,4,1] | [32,8,1] | [32,1,1]) - || !(shared==0 || (1..=8).any(|t|shared as usize==t*10240 || shared as usize==t*5120)) + || !matches!( + block, + [64, 1, 1] | [128, 1, 1] | [256, 1, 1] | [1024, 1, 1] | [32, 4, 1] | [32, 8, 1] | [32, 1, 1] + ) + || !(shared == 0 || (1..=8).any(|t| shared as usize == t * 10240 || shared as usize == t * 5120)) || stream == 0 { return Err(Error::InvalidQwenShape); } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.pointers.clear(); for v in &mut args.values { args.pointers.push(match v { @@ -259,19 +241,25 @@ mod enabled { }) } // Addresses are derived only by this producer from actual whole owners. - pub(crate) fn copy(&self,dst:u64,src:u64,n:usize,stream:usize)->Result<()> { - if n==0 || stream==0 || dst==0 || src==0 { return Err(Error::InvalidSize); } + pub(crate) fn copy(&self, dst: u64, src: u64, n: usize, stream: usize) -> Result<()> { + if n == 0 || stream == 0 || dst == 0 || src == 0 { + return Err(Error::InvalidSize); + } // SAFETY: dst/src are device or mapped-host (UVA) addresses the producer derived from whole owners with checked extents // (checked_subspan / MappedOwner::address); n > 0 and the stream is non-zero. The copy is asynchronous: both owners // must outlive the stream drain (graph resources / Context::synchronize on every close path). - check("cuMemcpyAsync",unsafe{(self.copy)(dst,src,n,stream as *mut c_void)}) + check("cuMemcpyAsync", unsafe { (self.copy)(dst, src, n, stream as *mut c_void) }) } - pub(crate) fn copy_host(&self,dst:u64,source:&[u8],stream:usize)->Result<()> { - if dst==0||source.is_empty()||stream==0{return Err(Error::InvalidSize);} + pub(crate) fn copy_host(&self, dst: u64, source: &[u8], stream: usize) -> Result<()> { + if dst == 0 || source.is_empty() || stream == 0 { + return Err(Error::InvalidSize); + } // SAFETY: `source` is a live slice for the whole call and `dst` a checked device address. A pageable source is staged by the // driver before return; callers additionally retain the bytes (OriginalMtpScalarPrefill::pending_host) until the stream is // drained, so even a pinned-source (fully asynchronous) copy would read valid memory. - check("cuMemcpyHtoDAsync_v2",unsafe{(self.h2d)(dst,source.as_ptr().cast(),source.len(),stream as *mut c_void)}) + check("cuMemcpyHtoDAsync_v2", unsafe { + (self.h2d)(dst, source.as_ptr().cast(), source.len(), stream as *mut c_void) + }) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() @@ -298,11 +286,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::Module; #[cfg(not(all( feature = "cuda-driver", @@ -316,26 +300,22 @@ pub(crate) struct Module; target_pointer_width = "64" )))] impl Module { - pub(crate) fn configure_gr(&self)->Result<(usize,usize)>{Err(Error::UnsupportedPlatform)} + pub(crate) fn configure_gr(&self) -> Result<(usize, usize)> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - _: usize, - _: [u32; 3], - _: [u32;3], - _: u32, - _: usize, - _: &mut Arguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: [u32; 3], _: u32, _: usize, _: &mut Arguments) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy(&self, _: u64, _: u64, _: usize, _: usize) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn copy_host(&self, _dst: u64, _source: &[u8], _stream: usize) -> Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy(&self,_:u64,_:u64,_:usize,_:usize)->Result<()> { Err(Error::UnsupportedPlatform) } - pub(crate) fn copy_host(&self,_dst:u64,_source:&[u8],_stream:usize)->Result<()> {Err(Error::UnsupportedPlatform)} pub(crate) fn close(self) -> Result<()> { Ok(()) } } - - diff --git a/crates/cuda-driver/src/mtp_original_scalar_graph.rs b/crates/cuda-driver/src/mtp_original_scalar_graph.rs index c6f4db7c..0141245c 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_graph.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_graph.rs @@ -1,83 +1,202 @@ //! Literal cached MtpDrafter prefill graph scheduling. All kernel ABI arguments //! and real physical input/scratch/weight owners survive capture and replay. use super::*; -impl<'ctx> OriginalMtpScalarPrefill<'ctx>{ - pub(super) fn upload_records(&mut self,staging:&mut Vec<(BufferHandle,Vec)>)->Result<()>{ - self.pending_host.try_reserve(staging.len()+1).map_err(|_|Error::HostAllocation)?; - let zeros=zero_bytes(self.status.as_ref().ok_or(Error::ContextPoisoned)?.bytes)?; - let status=self.status.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; - let count=staging.len();let mut handles=Vec::new();handles.try_reserve_exact(count).map_err(|_|Error::HostAllocation)?; - self.pending_host.push(zeros); - for(h,bytes)in staging.drain(..){handles.push(h);self.pending_host.push(bytes);} - let module=Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?); - let base=self.pending_host.len()-count-1; - let host=&self.pending_host;let stream=self.stream.as_mut().ok_or(Error::ContextPoisoned)?; - self.has_pending=true; - stream.with_enqueue(|handle|{module.copy_host(status.qwen_address(),&host[base],handle)?; - for(i,h)in handles.iter().enumerate(){module.copy_host(h.qwen_address(),&host[base+1+i],handle)?;}Ok(())}) - } - pub(super) fn write_mapped(&self,tokens:&[i32],cell0:usize)->Result<()>{ - let mut mapped=self.mapped.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=mapped.as_mut().ok_or(Error::ContextPoisoned)?; - for(row,token)in tokens.iter().enumerate(){let cell=cell0+row;m.write(row*4,&token.to_le_bytes())?; - for(i,n)in [cell,cell+1,(cell+1)/4,cell+1].into_iter().enumerate(){m.write(self.max_t*4+(row*4+i)*4,&(n as i32).to_le_bytes())?;} - for head in 0..24{m.write(self.max_t*20+(row*24+head)*4,&(cell as i32).to_le_bytes())?;} - }Ok(()) - } - #[allow(clippy::too_many_arguments)] - pub(super) fn enqueue_group(&mut self,t:usize,group:usize,mapped:bool,weights:&Rc>,ring:&MtpOriginalInt8<'ctx>,commands:&mut Vec,copies:&mut [ScalarCommand],tokens:&[i32],cell0:usize)->Result<()>{ - let key=OriginalGraphKey::MtpPrefill{rows:t as u8,device_inputs:!mapped}; - let found=self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_some(); - if !found{ - let mut modules=Vec::new();modules.try_reserve_exact(6).map_err(|_|Error::HostAllocation)?; - for m in &self.modules{modules.push(Rc::clone(m.as_ref().ok_or(Error::ContextPoisoned)?));} - let modules:[Rc;6]=modules.try_into().map_err(|_|Error::InvalidSize)?; - let resources=GraphResources{context:self.context,modules,scratch:Rc::clone(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?),records:Rc::clone(self.records.as_ref().ok_or(Error::ContextPoisoned)?),status:Rc::clone(self.status.as_ref().ok_or(Error::ContextPoisoned)?),mapped:Rc::clone(&self.mapped),ring:ring.retain_physical_resources()?,weights:Rc::clone(weights),commands:std::mem::take(commands)}; - let mut charge=std::mem::size_of::>()+resources.commands.capacity()*std::mem::size_of::(); - for c in &resources.commands{if let ScalarCommand::Kernel{args,..}=c{charge=charge.checked_add(args.metadata_bytes()).ok_or(Error::BudgetExceeded)?;}} - if charge>512*1024{return Err(Error::BudgetExceeded);} - self.graph_metadata_bytes=self.graph_metadata_bytes.checked_add(charge).ok_or(Error::BudgetExceeded)?; - let graphs=self.graphs.as_mut().ok_or(Error::ContextPoisoned)?;let stream=self.stream.as_mut().ok_or(Error::ContextPoisoned)?; - graphs.record(key,stream,||Ok(resources),|capture,r|{ - let handle=capture.stream_handle(r.context)?; - for command in &mut r.commands{match command{ - ScalarCommand::Kernel{asset,index,grid,block,shared,args}=>r.modules[*asset].launch(*index,*grid,*block,*shared,handle,args)?, - ScalarCommand::Copy{..}=>return Err(Error::InvalidQwenShape),}} - Ok(()) - })?; - } - if mapped{self.write_mapped(tokens,cell0)?;} - self.has_pending=true; - // These are the four literal Original copies before each device-input graph; - // mapped mode keeps only the actual Rin copy outside the captured copy kernels. - let module=Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?); - self.stream.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|stream|{ - for copy in copies{match copy{ScalarCommand::Copy{dst,src,bytes}=>module.copy(*dst,*src,*bytes,stream)?,ScalarCommand::Kernel{..}=>return Err(Error::InvalidQwenShape)}}Ok(())})?; - let graph=self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.ok_or(Error::ContextPoisoned)?; - graph.enqueue(self.stream.as_ref().ok_or(Error::ContextPoisoned)?)?; - // Extra full-finite safety timeline: whole actual flags copied after this - // replay, before any following replay resets scratch. No host fence/readback. - let status=self.status.as_ref().ok_or(Error::ContextPoisoned)?;let h=status.handle.ok_or(Error::ContextPoisoned)?; - let dst=h.checked_subspan(status.bytes,(group+1)*SCALAR_FLAGS*4,SCALAR_FLAGS*4)?; - self.stream.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|stream|module.copy(dst.qwen_address(),h.qwen_address(),SCALAR_FLAGS*4,stream)) - } - pub(super) fn drain_graphs(&mut self,rows:&mut OriginalPromptRows<'_, '_, '_>,workspace:&mut NativeBatchWorkspace<'ctx>)->Result<()>{ - let drained=self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt(); - let receipt=match drained{Ok(r)=>r,Err(e)=>{self.poison();workspace.mark_failed();rows.mark_failed();let host=std::mem::take(&mut self.pending_host);std::mem::forget(host);return Err(e)}}; - for t in 1..=self.max_t{for inputs in [false,true]{let key=OriginalGraphKey::MtpPrefill{rows:t as u8,device_inputs:inputs}; - if let Some(g)=self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?{g.resources_after_stream_drain(&receipt)?;} - }} - self.has_pending=false;self.pending_host.clear(); - let status=self.status.as_ref().ok_or(Error::ContextPoisoned)?;let handle=status.handle.ok_or(Error::ContextPoisoned)?; - let mut readback=zero_bytes(status.bytes)?; - let guard=match self.context.enter(){Ok(g)=>g,Err(e)=>{self.poison();workspace.mark_failed();rows.mark_failed();return Err(e)}}; - let copy=self.context.driver.api.copy_to(handle,&mut readback);let pop=guard.finish(); - if copy.is_err()||pop.is_err(){self.poison();workspace.mark_failed();rows.mark_failed();} - if pop.is_err(){std::mem::forget(readback);return combine(copy,pop);}combine(copy,pop)?; - // Timeline is chronological groups, then exact stage order; scratch flags at - // index0 are deliberately excluded from arbitration. - for bytes in readback[SCALAR_FLAGS*4..].chunks_exact(4){let f=u32::from_le_bytes(bytes.try_into().map_err(|_|Error::InvalidSize)?); - if f>1{self.poison();return Err(Error::InvalidDriverValue("Original scalar MTP status"));} - if f!=0{return Err(Error::NonFiniteMmqOutput("Original scalar MTP"));} - }Ok(()) - } +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + pub(super) fn upload_records(&mut self, staging: &mut Vec<(BufferHandle, Vec)>) -> Result<()> { + self.pending_host.try_reserve(staging.len() + 1).map_err(|_| Error::HostAllocation)?; + let zeros = zero_bytes(self.status.as_ref().ok_or(Error::ContextPoisoned)?.bytes)?; + let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; + let count = staging.len(); + let mut handles = Vec::new(); + handles.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; + self.pending_host.push(zeros); + for (h, bytes) in staging.drain(..) { + handles.push(h); + self.pending_host.push(bytes); + } + let module = Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?); + let base = self.pending_host.len() - count - 1; + let host = &self.pending_host; + let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + self.has_pending = true; + stream.with_enqueue(|handle| { + module.copy_host(status.qwen_address(), &host[base], handle)?; + for (i, h) in handles.iter().enumerate() { + module.copy_host(h.qwen_address(), &host[base + 1 + i], handle)?; + } + Ok(()) + }) + } + pub(super) fn write_mapped(&self, tokens: &[i32], cell0: usize) -> Result<()> { + let mut mapped = self.mapped.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let m = mapped.as_mut().ok_or(Error::ContextPoisoned)?; + for (row, token) in tokens.iter().enumerate() { + let cell = cell0 + row; + m.write(row * 4, &token.to_le_bytes())?; + for (i, n) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() { + m.write(self.max_t * 4 + (row * 4 + i) * 4, &(n as i32).to_le_bytes())?; + } + for head in 0..24 { + m.write(self.max_t * 20 + (row * 24 + head) * 4, &(cell as i32).to_le_bytes())?; + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub(super) fn enqueue_group( + &mut self, + t: usize, + group: usize, + mapped: bool, + weights: &Rc>, + ring: &MtpOriginalInt8<'ctx>, + commands: &mut Vec, + copies: &mut [ScalarCommand], + tokens: &[i32], + cell0: usize, + ) -> Result<()> { + let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !mapped }; + let found = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_some(); + if !found { + let mut modules = Vec::new(); + modules.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; + for m in &self.modules { + modules.push(Rc::clone(m.as_ref().ok_or(Error::ContextPoisoned)?)); + } + let modules: [Rc; 6] = modules.try_into().map_err(|_| Error::InvalidSize)?; + let resources = GraphResources { + context: self.context, + modules, + scratch: Rc::clone(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?), + records: Rc::clone(self.records.as_ref().ok_or(Error::ContextPoisoned)?), + status: Rc::clone(self.status.as_ref().ok_or(Error::ContextPoisoned)?), + mapped: Rc::clone(&self.mapped), + ring: ring.retain_physical_resources()?, + weights: Rc::clone(weights), + commands: std::mem::take(commands), + }; + let mut charge = std::mem::size_of::>() + + resources.commands.capacity() * std::mem::size_of::(); + for c in &resources.commands { + if let ScalarCommand::Kernel { args, .. } = c { + charge = charge.checked_add(args.metadata_bytes()).ok_or(Error::BudgetExceeded)?; + } + } + if charge > 512 * 1024 { + return Err(Error::BudgetExceeded); + } + self.graph_metadata_bytes = self.graph_metadata_bytes.checked_add(charge).ok_or(Error::BudgetExceeded)?; + let graphs = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?; + let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + graphs.record( + key, + stream, + || Ok(resources), + |capture, r| { + let handle = capture.stream_handle(r.context)?; + for command in &mut r.commands { + match command { + ScalarCommand::Kernel { asset, index, grid, block, shared, args } => { + r.modules[*asset].launch(*index, *grid, *block, *shared, handle, args)? + } + ScalarCommand::Copy { .. } => return Err(Error::InvalidQwenShape), + } + } + Ok(()) + }, + )?; + } + if mapped { + self.write_mapped(tokens, cell0)?; + } + self.has_pending = true; + // These are the four literal Original copies before each device-input graph; + // mapped mode keeps only the actual Rin copy outside the captured copy kernels. + let module = Rc::clone(self.modules[0].as_ref().ok_or(Error::ContextPoisoned)?); + self.stream.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|stream| { + for copy in copies { + match copy { + ScalarCommand::Copy { dst, src, bytes } => module.copy(*dst, *src, *bytes, stream)?, + ScalarCommand::Kernel { .. } => return Err(Error::InvalidQwenShape), + } + } + Ok(()) + })?; + let graph = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.ok_or(Error::ContextPoisoned)?; + graph.enqueue(self.stream.as_ref().ok_or(Error::ContextPoisoned)?)?; + // Extra full-finite safety timeline: whole actual flags copied after this + // replay, before any following replay resets scratch. No host fence/readback. + let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + let h = status.handle.ok_or(Error::ContextPoisoned)?; + let dst = h.checked_subspan(status.bytes, (group + 1) * SCALAR_FLAGS * 4, SCALAR_FLAGS * 4)?; + self.stream + .as_mut() + .ok_or(Error::ContextPoisoned)? + .with_enqueue(|stream| module.copy(dst.qwen_address(), h.qwen_address(), SCALAR_FLAGS * 4, stream)) + } + pub(super) fn drain_graphs( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + let drained = self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt(); + let receipt = match drained { + Ok(r) => r, + Err(e) => { + self.poison(); + workspace.mark_failed(); + rows.mark_failed(); + let host = std::mem::take(&mut self.pending_host); + std::mem::forget(host); + return Err(e); + } + }; + for t in 1..=self.max_t { + for inputs in [false, true] { + let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: inputs }; + if let Some(g) = self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)? { + g.resources_after_stream_drain(&receipt)?; + } + } + } + self.has_pending = false; + self.pending_host.clear(); + let status = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + let handle = status.handle.ok_or(Error::ContextPoisoned)?; + let mut readback = zero_bytes(status.bytes)?; + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + workspace.mark_failed(); + rows.mark_failed(); + return Err(e); + } + }; + let copy = self.context.driver.api.copy_to(handle, &mut readback); + let pop = guard.finish(); + if copy.is_err() || pop.is_err() { + self.poison(); + workspace.mark_failed(); + rows.mark_failed(); + } + if pop.is_err() { + std::mem::forget(readback); + return combine(copy, pop); + } + combine(copy, pop)?; + // Timeline is chronological groups, then exact stage order; scratch flags at + // index0 are deliberately excluded from arbitration. + for bytes in readback[SCALAR_FLAGS * 4..].chunks_exact(4) { + let f = u32::from_le_bytes(bytes.try_into().map_err(|_| Error::InvalidSize)?); + if f > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("Original scalar MTP status")); + } + if f != 0 { + return Err(Error::NonFiniteMmqOutput("Original scalar MTP")); + } + } + Ok(()) + } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_mapped.rs b/crates/cuda-driver/src/mtp_original_scalar_mapped.rs index 932aec8f..e6453425 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_mapped.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_mapped.rs @@ -1,9 +1,5 @@ use crate::{Error, Result}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod mapped_enabled { use super::super::physical_layout::Records; use super::*; @@ -23,14 +19,7 @@ mod mapped_enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -59,9 +48,7 @@ mod mapped_enabled { } let bytes = max_t * 29 * 4; // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -84,15 +71,12 @@ mod mapped_enabled { shared: None, }; // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -105,23 +89,14 @@ mod mapped_enabled { } pub(crate) fn original(max_t: usize, shared: Rc>) -> Self { let bytes = max_t * 29 * 4; - Self { - library: None, - host: None, - alias: 0, - free: None, - bytes, - shared: Some(shared), - } + Self { library: None, host: None, alias: 0, free: None, bytes, shared: Some(shared) } } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { if let Some(shared) = &self.shared { return shared.borrow().address(offset, n); } self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { if let Some(shared) = &self.shared { @@ -147,9 +122,7 @@ mod mapped_enabled { if let Some(p) = self.host { // SAFETY: `p` is the block allocated by this owner, still marked owned (host is Some) and freed once; callers drained every // stream that references it before close(). On failure host stays Some so Drop leaks the block rather than re-freeing. - check("cuMemFreeHost", unsafe { - (self.free.ok_or(Error::ContextPoisoned)?)(p as *mut c_void) - })?; + check("cuMemFreeHost", unsafe { (self.free.ok_or(Error::ContextPoisoned)?)(p as *mut c_void) })?; self.host = None; self.alias = 0; } @@ -247,11 +220,7 @@ mod mapped_enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use mapped_enabled::MappedOwner; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs index 881ed16b..f10f8c27 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs @@ -5,10 +5,7 @@ use super::*; #[allow(unsafe_code)] #[path = "mtp_original_scalar_ffi.rs"] mod scalar_abi; -use crate::{ - OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, - OriginalStreamKind, -}; +use crate::{OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, OriginalStreamKind}; use scalar_abi::{Arg, Arguments, Module}; #[path = "mtp_original_scalar_weights.rs"] mod retained_weights; @@ -74,26 +71,15 @@ struct Scratch { #[path = "mtp_original_full_forward.rs"] mod full_forward; -pub use full_forward::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, -}; pub(crate) use full_forward::session_assets_sealed; +pub use full_forward::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, + OriginalMtpStepOutput, +}; enum ScalarCommand { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, + Kernel { asset: usize, index: usize, grid: [u32; 3], block: [u32; 3], shared: u32, args: Arguments }, + Copy { dst: u64, src: u64, bytes: usize }, } /// Real affine scalar producer. Cached Original capture must retain this owner /// AND genuine model-lifetime whole weights (see the explicit graph handoff). @@ -130,7 +116,7 @@ mod short_prompt_gpu; #[path = "mtp_original_scalar_prefill/impl_crate_original_gpu_schedule_resources.rs"] mod impl_crate_original_gpu_schedule_resources; -#[path = "mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs"] -mod impl_originalmtpscalarprefill; #[path = "mtp_original_scalar_prefill/impl_drop_for_originalmtpscalarprefill.rs"] mod impl_drop_for_originalmtpscalarprefill; +#[path = "mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs"] +mod impl_originalmtpscalarprefill; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_crate_original_gpu_schedule_resources.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_crate_original_gpu_schedule_resources.rs index 22d493b4..854cd587 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_crate_original_gpu_schedule_resources.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_crate_original_gpu_schedule_resources.rs @@ -14,12 +14,7 @@ impl OriginalGraphResources for GraphResources<'_> { for b in [&self.scratch, &self.records, &self.status] { checked(c, b, b.bytes)?; } - if self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none() - { + if self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?.is_none() { return Err(Error::ContextPoisoned); } Ok(()) @@ -54,11 +49,7 @@ impl Scratch { offsets[i] = bytes; bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; } - Ok(Self { - sizes, - offsets, - bytes, - }) + Ok(Self { sizes, offsets, bytes }) } } impl<'ctx> Context<'ctx> { diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs index e79e3357..22f58fa6 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpScalarPrefill<'ctx> { pub(in super::super) fn assets_ready() -> Result<()> { let assets = [ @@ -14,10 +13,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { include_bytes!("../../mtp_original_scalar_gr.ptx").as_slice(), include_bytes!("../../mtp_original_kv.ptx").as_slice(), ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { + if assets.iter().any(|p| p.windows(8).any(|w| w == b"UNSEALED")) { Err(Error::UnsupportedQwenOperation) } else { Ok(()) @@ -39,32 +35,21 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { // New per-call immutable host snapshot may include absent pruned-prefix pages; // charge its real worst-case payload+catalog separately from the existing // physical mapped ring. Cached graph metadata is bounded per actual T/key. - let snapshot = MTP_ORIGINAL_MAX_CELLS - .div_ceil(4) - .checked_mul(4224 + 128) - .ok_or(Error::BudgetExceeded)?; + let snapshot = MTP_ORIGINAL_MAX_CELLS.div_ceil(4).checked_mul(4224 + 128).ok_or(Error::BudgetExceeded)?; (2 * max_t) .checked_mul(512 * 1024) - .and_then(|n| { - n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) - }) + .and_then(|n| n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024)) .and_then(|n| n.checked_add(snapshot)) .ok_or(Error::BudgetExceeded) } pub fn host_metadata_bytes(&self) -> usize { - self.graphs - .as_ref() - .map_or(0, OriginalGraphRegistry::metadata_bytes) + self.graphs.as_ref().map_or(0, OriginalGraphRegistry::metadata_bytes) + self.graph_metadata_bytes + std::mem::size_of::() + self.pending_host.capacity() * std::mem::size_of::>() } pub fn pinned_host_bytes(&self) -> usize { - if self.original_layout.is_some() { - self.max_t * 236 + 384 - } else { - self.max_t * 29 * 4 - } + if self.original_layout.is_some() { self.max_t * 236 + 384 } else { self.max_t * 29 * 4 } } pub(in super::super) fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { Self::new_internal(c, max_t, prompt_cap, None) @@ -77,9 +62,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { ) -> Result { let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; let charge = if exact.is_some() { - legacy_charge - .checked_sub(Scratch::new(max_t)?.bytes) - .ok_or(Error::InvalidSize)? + legacy_charge.checked_sub(Scratch::new(max_t)?.bytes).ok_or(Error::InvalidSize)? } else { legacy_charge }; @@ -97,21 +80,14 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { include_bytes!("../../mtp_original_scalar_gr.ptx").as_slice(), include_bytes!("../../mtp_original_kv.ptx").as_slice(), ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { + if assets.iter().any(|p| p.windows(8).any(|w| w == b"UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; + let required = charge.checked_add(RESERVE_BYTES).ok_or(Error::BudgetExceeded)?; if c.is_poisoned() || c.handle.is_none() { return Err(Error::ContextPoisoned); } - if c.allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > c.budget_bytes()) + if c.allocated_bytes().checked_add(required).is_none_or(|n| n > c.budget_bytes()) || c.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -149,19 +125,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { })?; let load = (|| { o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); - o.modules[1] = Some(Rc::new(Module::load( - assets[1], - &[c"mtp_prefill_native_embedding"], - )?)); + o.modules[1] = Some(Rc::new(Module::load(assets[1], &[c"mtp_prefill_native_embedding"])?)); o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); o.modules[3] = Some(Rc::new(Module::load( assets[3], - &[ - c"mtp_scalar_norm1024", - c"mtp_scalar_rope", - c"mtp_scalar_copy_i32", - c"mtp_scalar_encoded", - ], + &[c"mtp_scalar_norm1024", c"mtp_scalar_rope", c"mtp_scalar_copy_i32", c"mtp_scalar_encoded"], )?)); o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); @@ -180,19 +148,14 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { None => Rc::new(c.allocate(o.layout.bytes)?), }); o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); - o.status = Some(Rc::new( - c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, - )); + o.status = Some(Rc::new(c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?)); o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); let g = c.enter().inspect_err(|_| { c.poison(); c.retain_driver(); })?; let allocation = match &exact { - Some(e) => Ok(mapped_records::MappedOwner::original( - max_t, - Rc::clone(&e.mapped), - )), + Some(e) => Ok(mapped_records::MappedOwner::original(max_t, Rc::clone(&e.mapped))), None => mapped_records::MappedOwner::new(max_t), }; let pop = g.finish(); @@ -212,9 +175,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { } *o.mapped.borrow_mut() = Some(allocation?); o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); - o.pending_host - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; + o.pending_host.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; if c.memory_info()?.0 < RESERVE_BYTES { return Err(Error::BudgetExceeded); } @@ -226,10 +187,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Ok(o) } pub fn allocated_bytes(&self) -> usize { - [&self.scratch, &self.records, &self.status] - .into_iter() - .map(|s| s.as_ref().map_or(0, |b| b.len())) - .sum() + [&self.scratch, &self.records, &self.status].into_iter().map(|s| s.as_ref().map_or(0, |b| b.len())).sum() } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs index f7c29b7a..1658c4f7 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_2_2.rs @@ -3,25 +3,18 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpScalarPrefill<'ctx> { pub(in super::super) fn validate(&self) -> Result<()> { if self.is_failed() || self.modules.iter().any(Option::is_none) - || self - .stream - .as_ref() - .is_none_or(OriginalGpuStream::is_failed) + || self.stream.as_ref().is_none_or(OriginalGpuStream::is_failed) { return Err(Error::ContextPoisoned); } for (b, n) in [ (&self.scratch, self.layout.bytes), (&self.records, self.prompt_cap * 29 * 4), - ( - &self.status, - (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, - ), + (&self.status, (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4), ] { let b = b.as_ref().ok_or(Error::ContextPoisoned)?; checked(self.context, b, n)?; @@ -34,20 +27,14 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { self.context.retain_driver(); } pub(in super::super) fn module(&self, i: usize) -> Result<&Module> { - self.modules - .get(i) - .and_then(Option::as_ref) - .map(Rc::as_ref) - .ok_or(Error::ContextPoisoned) + self.modules.get(i).and_then(Option::as_ref).map(Rc::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn scratch(&self, i: usize, n: usize) -> Result { let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; if n == 0 || n > self.layout.sizes[i] { return Err(Error::InvalidSize); } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, self.layout.offsets[i], n) + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, self.layout.offsets[i], n) } pub(in super::super) fn address(&self, i: usize, n: usize) -> Result { Ok(self.scratch(i, n)?.qwen_address()) @@ -85,14 +72,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { args: Vec, ) -> Result<()> { cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(ScalarCommand::Kernel { - asset, - index, - grid, - block, - shared, - args: Arguments::new(args)?, - }); + cmds.push(ScalarCommand::Kernel { asset, index, grid, block, shared, args: Arguments::new(args)? }); Ok(()) } pub(in super::super) fn finite( @@ -110,11 +90,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [n.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - Arg::U64(data), - Arg::I32(n as i32), - Arg::U64(self.flag(0, s)?), - ], + vec![Arg::U64(data), Arg::I32(n as i32), Arg::U64(self.flag(0, s)?)], ) } pub(in super::super) fn q8_guard( @@ -132,11 +108,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [(rows * 80).div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, - vec![ - Arg::U64(q), - Arg::I32((rows * 80) as i32), - Arg::U64(self.flag(0, s)?), - ], + vec![Arg::U64(q), Arg::I32((rows * 80) as i32), Arg::U64(self.flag(0, s)?)], ) } pub(in super::super) fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { @@ -168,13 +140,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [out as u32, 1, 1], [32, 4, 1], 0, - vec![ - Arg::U64(w), - Arg::U64(q), - Arg::U64(y), - Arg::I32(2560), - Arg::I32(out as i32), - ], + vec![Arg::U64(w), Arg::U64(q), Arg::U64(y), Arg::I32(2560), Arg::I32(out as i32)], ) } pub(in super::super) fn external( @@ -192,10 +158,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { if h.overlaps(n, r, rn) { return Err(Error::OutputAliasesInput); } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { + for own in [&self.scratch, &self.records, &self.status].into_iter().flatten() { if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { return Err(Error::OutputAliasesInput); } @@ -209,9 +172,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { if !ring.fully_resident()? { let mapped = ring.mapped()?; let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 - && host < h.qwen_address() + n as u64 - { + if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && host < h.qwen_address() + n as u64 { return Err(Error::OutputAliasesInput); } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs index 90a7705e..986a0545 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpScalarPrefill<'ctx> { pub(in super::super) fn gr( &self, @@ -16,29 +15,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Self::kernel( cmds, 4, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - t as u32, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], + if policy.gr == OriginalMtpGrVariant::Plain { 0 } else { 1 }, + [t as u32, if policy.gr == OriginalMtpGrVariant::Plain { 1 } else { 4 }, 1], [256, 1, 1], 0, vec![self.gr_args(0, t, wh, xn)?], )?; - let per_token = if policy.gr == OriginalMtpGrVariant::Staged { - 2 * 1280 * 4 - } else { - self.plain_tile * 4 - }; + let per_token = if policy.gr == OriginalMtpGrVariant::Staged { 2 * 1280 * 4 } else { self.plain_tile * 4 }; let capacity = (self.shared_limit / per_token).clamp(1, 8); for c in (0..t).step_by(capacity) { let ct = capacity.min(t - c); @@ -58,15 +41,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], )?; } - Self::kernel( - cmds, - 4, - 3, - [160, 1, 1], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - ) + Self::kernel(cmds, 4, 3, [160, 1, 1], [256, 1, 1], 0, vec![self.gr_args(0, t, wh, xn)?]) } #[allow(clippy::too_many_arguments)] pub fn record<'arena, 'loan>( diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs index 12b8eeb6..a56bb7f7 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpScalarPrefill<'ctx> { /// Literal cached device-input or mapped-input per-T graph scheduling. /// Unsupported storage/math branches return explicit fallback, never completion. @@ -29,28 +28,17 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); } if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedStorage)); } if kv.alternate_f16 { return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); } if kv.rope_table_enabled || kv.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedRopeTable, - )); + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedRopeTable)); } - if [ - kv.theta_scale, - kv.freq_scale, - kv.corr_low, - kv.corr_high, - kv.ext_factor, - kv.mscale, - ] - .iter() - .any(|x| !x.is_finite()) + if [kv.theta_scale, kv.freq_scale, kv.corr_low, kv.corr_high, kv.ext_factor, kv.mscale] + .iter() + .any(|x| !x.is_finite()) || kv.theta_scale <= 0.0 || kv.freq_scale <= 0.0 || kv.mscale <= 0.0 @@ -66,17 +54,12 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { if !residual.context_matches(self.context) || tokens.len() != residual.rows() || tokens.len() > self.prompt_cap - || cell0 - .checked_add(tokens.len()) - .is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || cell0.checked_add(tokens.len()).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) || ring.max_t < self.max_t { return Err(Error::InvalidProjectionShape); } - if tokens - .iter() - .any(|t| *t < 0 || *t as usize >= embedding.vocab()) - { + if tokens.iter().any(|t| *t < 0 || *t as usize >= embedding.vocab()) { return Err(Error::InvalidProjectionShape); } // Original skips WHOLE groups whose end<=first_needed, not individual rows. @@ -90,27 +73,17 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { let end = cell0 + tokens.len(); let rows = residual.lease_mut(); let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { + for own in [&self.scratch, &self.records, &self.status].into_iter().flatten() { if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { return Err(Error::OutputAliasesInput); } } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { + for own in [&self.scratch, &self.records, &self.status].into_iter().flatten() { ring.reject_state_alias(own)?; let h = own.handle.ok_or(Error::ContextPoisoned)?; workspace.reject_alias(h, own.bytes)?; for other in ring.buffers()?.iter().flatten() { - if h.overlaps( - own.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { + if h.overlaps(own.bytes, other.handle.ok_or(Error::ContextPoisoned)?, other.bytes) { return Err(Error::OutputAliasesInput); } } @@ -145,13 +118,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { for i in 0..11 { wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; } - let eh = self.external( - rows, - workspace, - ring, - embedding.table, - embedding.table.bytes, - )?; + let eh = self.external(rows, workspace, ring, embedding.table, embedding.table.bytes)?; for i in 0..wr.len() { for j in 0..i { if wh[i].overlaps(extents[i], wh[j], extents[j]) @@ -172,14 +139,8 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { kv.mscale.to_bits(), 0, ]; - if self - .retained - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &retained)) - || self - .ring_id - .as_ref() - .is_some_and(|id| !id.same_owner(&prior.owner_id())) + if self.retained.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &retained)) + || self.ring_id.as_ref().is_some_and(|id| !id.same_owner(&prior.owner_id())) || self.policy_key.is_some_and(|old| old != key) { return Err(Error::InvalidProjectionShape); @@ -187,20 +148,13 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { self.retained = Some(retained.clone()); self.ring_id = Some(prior.owner_id()); self.policy_key = Some(key); - let generation = ring - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let first_page = first / 4; let count = end.div_ceil(4); let mut pages = Vec::new(); - pages - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; + pages.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; let mut changed = Vec::new(); - changed - .try_reserve_exact(count - first_page) - .map_err(|_| Error::HostAllocation)?; + changed.try_reserve_exact(count - first_page).map_err(|_| Error::HostAllocation)?; for p in 0..count { if p < first_page { if let Some(old) = prior.0.pages.get(p) { @@ -213,9 +167,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { runs[i] = zero_bytes(n)?; } if p < first_page { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } else { changed.push(runs); } @@ -226,10 +178,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { for (i, token) in tokens.iter().enumerate() { let cell = cell0 + i; rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); - for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1] - .into_iter() - .enumerate() - { + for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() { let off = (n + i * 4 + j) * 4; rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); } @@ -239,10 +188,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { } } let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; - let rec_h = - rb.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(rb.bytes, 0, rec.len())?; + let rec_h = rb.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(rb.bytes, 0, rec.len())?; let mut staging = vec![(rec_h, rec)]; let mut cmds = Vec::new(); cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; @@ -276,32 +222,16 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { let pos = self.address(14, t * 96)?; let mut copies = [ (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), - ( - step, - rec_h.qwen_address() + ((n + c * 4) * 4) as u64, - t * 16, - ), - ( - pos, - rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, - t * 96, - ), - ( - rin, - rh.checked_subspan(rbytes, c * 40960, t * 40960)? - .qwen_address(), - t * 40960, - ), + (step, rec_h.qwen_address() + ((n + c * 4) * 4) as u64, t * 16), + (pos, rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, t * 96), + (rin, rh.checked_subspan(rbytes, c * 40960, t * 40960)?.qwen_address(), t * 40960), ] .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); let needs_capture = self .graphs .as_mut() .ok_or(Error::ContextPoisoned)? - .find_mut(OriginalGraphKey::MtpPrefill { - rows: t as u8, - device_inputs: !policy.per_group_sync, - })? + .find_mut(OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !policy.per_group_sync })? .is_none(); if needs_capture { // Captured per-T forward owns fixed whole scratch/status and stable arguments. @@ -315,16 +245,11 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], )?; if policy.per_group_sync { - let mapped = self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?; + let mapped = self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; - for (dst, offset, count) in [ - (tok, 0, t), - (step, self.max_t * 4, t * 4), - (pos, self.max_t * 20, t * 24), - ] { + for (dst, offset, count) in + [(tok, 0, t), (step, self.max_t * 4, t * 4), (pos, self.max_t * 20, t * 24)] + { Self::kernel( &mut cmds, 3, @@ -332,18 +257,12 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [1, 1, 1], [128, 1, 1], 0, - vec![ - Arg::U64(dst), - Arg::U64(m.address(offset, count * 4)?), - Arg::I32(count as i32), - ], + vec![Arg::U64(dst), Arg::U64(m.address(offset, count * 4)?), Arg::I32(count as i32)], )?; } } match embedding.kind { - EmbeddingKind::Native { - kind, row_bytes, .. - } => Self::kernel( + EmbeddingKind::Native { kind, row_bytes, .. } => Self::kernel( &mut cmds, 1, 0, @@ -359,15 +278,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { Arg::U64(emb), ], )?, - EmbeddingKind::Compressed { - bits, - bias, - group, - codes, - scales, - offsets, - .. - } => Self::kernel( + EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => Self::kernel( &mut cmds, 0, 5, @@ -377,11 +288,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { vec![ Arg::U64(eh.qwen_address()), Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { - eh.qwen_address() + (codes + scales) as u64 - } else { - 0 - }), + Arg::U64(if offsets { eh.qwen_address() + (codes + scales) as u64 } else { 0 }), Arg::U64(tok), Arg::I64(2560), Arg::I32(bits), @@ -401,13 +308,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [t as u32, 1, 1], [1024, 1, 1], 0, - vec![ - Arg::U64(emb), - Arg::U64(wh[0].qwen_address()), - Arg::U64(en), - Arg::I32(2560), - Arg::F32(1e-6), - ], + vec![Arg::U64(emb), Arg::U64(wh[0].qwen_address()), Arg::U64(en), Arg::I32(2560), Arg::F32(1e-6)], )?; self.finite(&mut cmds, en, t * 2560, group, 1)?; let q = self.address(15, 8 * 80 * 36)?; @@ -422,27 +323,14 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [t as u32, 1, 1], [1024, 1, 1], 0, - vec![ - Arg::U64(rin), - Arg::U64(wh[2].qwen_address()), - Arg::U64(hn), - Arg::I32(10240), - Arg::F32(1e-6), - ], + vec![Arg::U64(rin), Arg::U64(wh[2].qwen_address()), Arg::U64(hn), Arg::I32(10240), Arg::F32(1e-6)], )?; self.finite(&mut cmds, hn, t * 10240, group, 3)?; for hc in (0..t * 4).step_by(8) { let cols = 8.min(t * 4 - hc); Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; self.q8_guard(&mut cmds, q, cols, group, 4)?; - Self::project( - &mut cmds, - wh[3].qwen_address(), - q, - h2 + (hc * 10240) as u64, - cols, - 2560, - )?; + Self::project(&mut cmds, wh[3].qwen_address(), q, h2 + (hc * 10240) as u64, cols, 2560)?; } self.finite(&mut cmds, h2, t * 10240, group, 4)?; Self::kernel( @@ -452,13 +340,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [40, t as u32, 1], [256, 1, 1], 0, - vec![ - Arg::U64(h2), - Arg::U64(e2), - Arg::U64(r), - Arg::I64(2560), - Arg::I32(4), - ], + vec![Arg::U64(h2), Arg::U64(e2), Arg::U64(r), Arg::I64(2560), Arg::I32(4)], )?; self.finite(&mut cmds, r, t * 10240, group, 5)?; self.gr(&mut cmds, t, &wh, policy)?; @@ -483,13 +365,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { [2, 1, 1], [256, 1, 1], 0, - vec![ - Arg::U64(k), - Arg::U64(wh[9].qwen_address()), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1e-6), - ], + vec![Arg::U64(k), Arg::U64(wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)], )?; self.finite(&mut cmds, k, 512, group, 12)?; Self::kernel( @@ -574,11 +450,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { &retained, ring, &mut cmds, - if policy.per_group_sync { - &mut copies[3..] - } else { - &mut copies[..] - }, + if policy.per_group_sync { &mut copies[3..] } else { &mut copies[..] }, &tokens[c..c + t], cell0 + c, ) { @@ -600,9 +472,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { ring.read_encoded_page(first_page + p, runs)?; } for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); + pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { origin: ring.origin.clone(), @@ -612,11 +482,6 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { })); ring.current = Some(snapshot.clone()); ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) + Ok(DraftKvOutcome::Completed(CompletedDraftKv { snapshot, first_materialized: first, end, generation })) } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs index cb9b5466..3f4f847b 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMtpScalarPrefill<'ctx> { pub fn close(mut self) -> Result<()> { self.close_inner() @@ -30,9 +29,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { } else { match self.context.enter() { Ok(g) => combine( - Rc::try_unwrap(m) - .map_err(|_| Error::InvalidQwenShape) - .and_then(Module::close), + Rc::try_unwrap(m).map_err(|_| Error::InvalidQwenShape).and_then(Module::close), g.finish(), ), Err(e) => { diff --git a/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs index 107ce0a6..1deabae3 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_short_gpu.rs @@ -42,30 +42,71 @@ fn short_prompts_record_on_the_drafters_own_scalar_owner_not_on_a_standalone_one let alloc = |n: usize| context.allocate(n).map(Rc::new).expect("alloc"); // scalar prefix bank - 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 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 roles: [Rc; 11] = extents.map(alloc); let table = alloc(1100 * vocab); let descriptor = OriginalMtpEmbedding::native(&table, 21, 1100, vocab).expect("embedding"); - let scalar_bank = Rc::new(OriginalMtpRetainedScalarWeights::retain(&context, roles, Rc::clone(&table), &descriptor).expect("scalar bank")); + let scalar_bank = Rc::new( + OriginalMtpRetainedScalarWeights::retain(&context, roles, Rc::clone(&table), &descriptor).expect("scalar bank"), + ); let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(Rc::clone(&scalar_bank)).expect("prefix")); // full 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, + 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 full_roles: [Rc; 15] = full_extents.map(alloc); let weights = Rc::new( OriginalMtpRetainedFullWeights::retain( - &context, prefix, full_roles, alloc(512 * 1_382_400), alloc(1100 * vocab), 21, vocab, vocab, None, NativeHeadDispatch::default(), + &context, + prefix, + full_roles, + alloc(512 * 1_382_400), + alloc(1100 * vocab), + 21, + vocab, + vocab, + None, + NativeHeadDispatch::default(), ) .expect("full bank"), ); - let (mut ring, scalar_shared, full) = - context.original_mtp_shared_layout_with_ring(Rc::clone(&weights), max_t, capacity, false).expect("shared layout"); + let (mut ring, scalar_shared, full) = context + .original_mtp_shared_layout_with_ring(Rc::clone(&weights), max_t, capacity, false) + .expect("shared layout"); let mut drafter = OriginalMtpDrafter::new(full, scalar_shared).expect("drafter"); let mut standalone = context.original_mtp_scalar_prefill(max_t, capacity).expect("standalone scalar owner"); - let policy = OriginalMtpScalarPolicy { gr: OriginalMtpGrVariant::Plain, per_group_sync: false, kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)) }; + let policy = OriginalMtpScalarPolicy { + gr: OriginalMtpGrVariant::Plain, + per_group_sync: false, + kv: DraftKvPolicy::original_int8(1e7f32.powf(-2.0 / 64.0)), + }; let mut workspace = context.native_batch_workspace().expect("workspace"); let mut arena = context.original_prefill_arena(options(capacity)).expect("arena"); @@ -78,7 +119,18 @@ fn short_prompts_record_on_the_drafters_own_scalar_owner_not_on_a_standalone_one let rows = arena.begin_rows(n).expect("rows"); let mut residual = OriginalDeviceResidual::for_probe(rows); // the pre-fix wiring: a standalone owner against the paired ring - let old = standalone.record(&mut residual, &mut workspace, &mut ring, &prior, &tokens, 0, 0, Rc::clone(&scalar_bank), &policy, || false); + let old = standalone.record( + &mut residual, + &mut workspace, + &mut ring, + &prior, + &tokens, + 0, + 0, + Rc::clone(&scalar_bank), + &policy, + || false, + ); eprintln!("PREFLIGHT short n={n} standalone scalar owner: {:?}", old.as_ref().map(|_| "ok")); if matches!(old, Err(Error::InvalidQwenShape)) { standalone_refused += 1; @@ -89,14 +141,28 @@ fn short_prompts_record_on_the_drafters_own_scalar_owner_not_on_a_standalone_one let prior = ring.empty_snapshot().expect("empty snapshot"); ring.restore(&mut workspace, &prior).expect("ring reset"); let outcome = drafter - .record_scalar_prefill(&mut residual, &mut workspace, &mut ring, &prior, &tokens, 0, 0, Rc::clone(&scalar_bank), &policy, || false) + .record_scalar_prefill( + &mut residual, + &mut workspace, + &mut ring, + &prior, + &tokens, + 0, + 0, + Rc::clone(&scalar_bank), + &policy, + || false, + ) .unwrap_or_else(|e| panic!("n={n}: the drafter's own scalar owner refused: {e:?}")); - eprintln!("PREFLIGHT short n={n} drafter scalar owner: {}", match outcome { - DraftKvOutcome::Completed(_) => "completed", - DraftKvOutcome::Skipped => "skipped", - DraftKvOutcome::Cancelled => "cancelled", - DraftKvOutcome::Fallback(_) => "fallback", - }); + eprintln!( + "PREFLIGHT short n={n} drafter scalar owner: {}", + match outcome { + DraftKvOutcome::Completed(_) => "completed", + DraftKvOutcome::Skipped => "skipped", + DraftKvOutcome::Cancelled => "cancelled", + DraftKvOutcome::Fallback(_) => "fallback", + } + ); assert!(matches!(outcome, DraftKvOutcome::Completed(_)), "n={n}"); } eprintln!("PREFLIGHT standalone owner refused {standalone_refused} of 5 prompts"); diff --git a/crates/cuda-driver/src/mtp_original_scalar_weights.rs b/crates/cuda-driver/src/mtp_original_scalar_weights.rs index 565e9bd5..1e47ebad 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_weights.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_weights.rs @@ -12,18 +12,8 @@ pub struct OriginalMtpRetainedScalarWeights<'ctx> { } #[derive(Clone, Copy)] enum RetainedEmbedding { - Native { - i: i32, - row_bytes: usize, - vocab: usize, - }, - Compressed { - bits: i32, - bias: i32, - group: usize, - vocab: usize, - offsets: bool, - }, + Native { i: i32, row_bytes: usize, vocab: usize }, + Compressed { bits: i32, bias: i32, group: usize, vocab: usize, offsets: bool }, } impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { pub(super) fn prefix_context(&self) -> &'ctx Context<'ctx> { @@ -71,23 +61,10 @@ impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { } let kind = match &descriptor.kind { - EmbeddingKind::Native { - kind, - row_bytes, - vocab, - } => RetainedEmbedding::Native { - i: *kind, - row_bytes: *row_bytes, - vocab: *vocab, - }, - EmbeddingKind::Compressed { - bits, - bias, - group, - vocab, - offsets, - .. - } => RetainedEmbedding::Compressed { + EmbeddingKind::Native { kind, row_bytes, vocab } => { + RetainedEmbedding::Native { i: *kind, row_bytes: *row_bytes, vocab: *vocab } + } + EmbeddingKind::Compressed { bits, bias, group, vocab, offsets, .. } => RetainedEmbedding::Compressed { bits: *bits, bias: *bias, group: *group, @@ -95,12 +72,7 @@ impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { offsets: *offsets, }, }; - Ok(Self { - context, - roles, - embedding, - kind, - }) + Ok(Self { context, roles, embedding, kind }) } pub fn metadata_bytes(&self) -> usize { std::mem::size_of::() + 12 * 2 * std::mem::size_of::() @@ -134,10 +106,7 @@ impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { pub(super) fn loans( &self, context: &Context<'_>, - ) -> Result<( - OriginalMtpScalarWeights<'_, 'ctx>, - OriginalMtpEmbedding<'_, 'ctx>, - )> { + ) -> Result<(OriginalMtpScalarWeights<'_, 'ctx>, OriginalMtpEmbedding<'_, 'ctx>)> { self.validate_context(context)?; let r = &self.roles; let input = OriginalMtpPrefillWeights { @@ -153,33 +122,14 @@ impl<'ctx> OriginalMtpRetainedScalarWeights<'ctx> { key_norm: &r[9], }; let embedding = match self.kind { - RetainedEmbedding::Native { - i, - row_bytes, - vocab, - } => OriginalMtpEmbedding::native(&self.embedding, i, row_bytes, vocab)?, - RetainedEmbedding::Compressed { - bits, - bias, - group, - vocab, - offsets, - } => OriginalMtpEmbedding::compressed( - &self.embedding, - bits, - bias, - group, - vocab, - offsets, - )?, + RetainedEmbedding::Native { i, row_bytes, vocab } => { + OriginalMtpEmbedding::native(&self.embedding, i, row_bytes, vocab)? + } + RetainedEmbedding::Compressed { bits, bias, group, vocab, offsets } => { + OriginalMtpEmbedding::compressed(&self.embedding, bits, bias, group, vocab, offsets)? + } }; - Ok(( - OriginalMtpScalarWeights { - input, - gr_inject: &r[10], - }, - embedding, - )) + Ok((OriginalMtpScalarWeights { input, gr_inject: &r[10] }, embedding)) } pub fn with_whole_loans( &self, diff --git a/crates/cuda-driver/src/mtp_original_session.rs b/crates/cuda-driver/src/mtp_original_session.rs index 46f3e805..4fc63e07 100644 --- a/crates/cuda-driver/src/mtp_original_session.rs +++ b/crates/cuda-driver/src/mtp_original_session.rs @@ -39,8 +39,20 @@ struct SessionOwned<'ctx> { pub struct OriginalMtpSessionResources<'ctx> { inner: Rc>, } -const SESSION_NATIVE_ASSET_PIN: Option<(usize, [u8; 32])> = Some((10519, [133, 183, 239, 124, 165, 148, 61, 189, 113, 7, 16, 107, 48, 41, 213, 2, 123, 70, 68, 20, 141, 112, 5, 164, 125, 239, 127, 169, 1, 163, 215, 10])); -const SESSION_LEGACY_ASSET_PIN: Option<(usize, [u8; 32])> = Some((12203, [155, 186, 59, 53, 133, 12, 227, 134, 158, 50, 197, 108, 157, 230, 106, 6, 82, 105, 17, 136, 244, 199, 255, 29, 196, 177, 238, 155, 47, 157, 13, 159])); +const SESSION_NATIVE_ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 10519, + [ + 133, 183, 239, 124, 165, 148, 61, 189, 113, 7, 16, 107, 48, 41, 213, 2, 123, 70, 68, 20, 141, 112, 5, 164, 125, + 239, 127, 169, 1, 163, 215, 10, + ], +)); +const SESSION_LEGACY_ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 12203, + [ + 155, 186, 59, 53, 133, 12, 227, 134, 158, 50, 197, 108, 157, 230, 106, 6, 82, 105, 17, 136, 244, 199, 255, 29, + 196, 177, 238, 155, 47, 157, 13, 159, + ], +)); const SESSION_NATIVE_ENTRIES: &[&std::ffi::CStr] = &[c"mtp_session_analytic", c"mtp_session_table"]; const SESSION_LEGACY_ENTRIES: &[&std::ffi::CStr] = &[c"mtp_session_legacy"]; /// Only an actual retained owning plan may enqueue; returns no completion bit. @@ -57,9 +69,9 @@ mod impl_originalmtpsessionplan; #[path = "mtp_original_session/impl_originalmtpsessionresources.rs"] mod impl_originalmtpsessionresources; #[allow(unused_imports)] -use impl_originalmtpsessionresources::session_native_asset; -#[allow(unused_imports)] use impl_originalmtpsessionresources::session_legacy_asset; +#[allow(unused_imports)] +use impl_originalmtpsessionresources::session_native_asset; #[path = "mtp_original_session/impl_drop_for_sessionowned.rs"] mod impl_drop_for_sessionowned; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/mtp_original_session/impl_drop_for_sessionowned.rs b/crates/cuda-driver/src/mtp_original_session/impl_drop_for_sessionowned.rs index 66b43738..2b732dfd 100644 --- a/crates/cuda-driver/src/mtp_original_session/impl_drop_for_sessionowned.rs +++ b/crates/cuda-driver/src/mtp_original_session/impl_drop_for_sessionowned.rs @@ -49,18 +49,16 @@ impl OriginalMtpSessionRopePlan<'_> { OriginalMtpRopeForm::NativeTable => 1, OriginalMtpRopeForm::LegacyTable => 2, }; - let grid = if index == 2 { - [self.heads.div_ceil(128) as u32, 1, 1] - } else { - [1, self.heads as u32, 1] - }; + let grid = if index == 2 { [self.heads.div_ceil(128) as u32, 1, 1] } else { [1, self.heads as u32, 1] }; let entry = if index == 2 { 0 } else { index }; - let op = self - .session - .module - .as_ref() - .ok_or(Error::ContextPoisoned)? - .launch(entry, grid, [128, 1, 1], 0, stream, &mut self.args); + let op = self.session.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( + entry, + grid, + [128, 1, 1], + 0, + stream, + &mut self.args, + ); if op.is_err() { self.session.failed.set(true); self.session.context.poison(); @@ -72,8 +70,5 @@ impl OriginalMtpSessionRopePlan<'_> { /// Sealed-state of the two compiled MTP session assets (probe only). pub(crate) fn session_assets_sealed() -> [(&'static str, bool); 2] { - [ - ("mtp_session.native", session_native_asset().is_some()), - ("mtp_session.legacy", session_legacy_asset().is_some()), - ] + [("mtp_session.native", session_native_asset().is_some()), ("mtp_session.legacy", session_legacy_asset().is_some())] } diff --git a/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionplan.rs b/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionplan.rs index f8794c45..67e6145f 100644 --- a/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionplan.rs +++ b/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionplan.rs @@ -9,27 +9,12 @@ impl OriginalMtpSessionPlan { if max_cells == 0 || max_cells > i32::MAX as usize || k != 10 || !(1..=8).contains(&max_t) { return Err(Error::InvalidQwenShape); } - let w = if window > 0 && (window as u64) < max_cells as u64 { - window as usize - } else { - 0 - }; - let ring_cells = if w == 0 { - 0 - } else { - w.checked_add(4 * max_t + 64).ok_or(Error::InvalidSize)? - }; - let cap = if w > 0 { w } else { max_cells } - .checked_add(63) - .ok_or(Error::InvalidSize)? - / 64 - * 64; + let w = if window > 0 && (window as u64) < max_cells as u64 { window as usize } else { 0 }; + let ring_cells = if w == 0 { 0 } else { w.checked_add(4 * max_t + 64).ok_or(Error::InvalidSize)? }; + let cap = if w > 0 { w } else { max_cells }.checked_add(63).ok_or(Error::InvalidSize)? / 64 * 64; let pages = max_cells.div_ceil(4); let rope = max_cells.checked_mul(32 * 4).ok_or(Error::InvalidSize)?; - let host = pages - .checked_mul(4224) - .and_then(|n| n.checked_add(4 * 256)) - .ok_or(Error::InvalidSize)?; + let host = pages.checked_mul(4224).and_then(|n| n.checked_add(4 * 256)).ok_or(Error::InvalidSize)?; Ok(Self { max_cells, experts_per_token: k, @@ -38,11 +23,7 @@ impl OriginalMtpSessionPlan { ring_cells, attention_capacity: cap, page_count: pages, - ring_slots: if ring_cells > 0 { - ring_cells.div_ceil(4) - } else { - pages - }, + ring_slots: if ring_cells > 0 { ring_cells.div_ceil(4) } else { pages }, resident_slots: pages, shared_rope_bytes: rope, canonical_host_bytes: host, @@ -90,10 +71,7 @@ impl OriginalMtpSessionPlan { Ok(()) } pub fn validate_window(&self, first: usize, rows: usize) -> Result<()> { - if rows == 0 - || rows > self.max_t - || first.checked_add(rows).is_none_or(|n| n > self.max_cells) - { + if rows == 0 || rows > self.max_t || first.checked_add(rows).is_none_or(|n| n > self.max_cells) { return Err(Error::InvalidQwenShape); } Ok(()) diff --git a/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionresources.rs b/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionresources.rs index 971c4eba..ebed333f 100644 --- a/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionresources.rs +++ b/crates/cuda-driver/src/mtp_original_session/impl_originalmtpsessionresources.rs @@ -50,24 +50,15 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { return Err(Error::OutputAliasesInput); } if let Some(m) = &mrope { - checked( - context, - m, - plan.max_cells.checked_mul(12).ok_or(Error::InvalidSize)?, - )?; + checked(context, m, plan.max_cells.checked_mul(12).ok_or(Error::InvalidSize)?)?; let h = m.handle.ok_or(Error::ContextPoisoned)?; - if h.overlaps(m.bytes, ch, plan.shared_rope_bytes) - || h.overlaps(m.bytes, sh, plan.shared_rope_bytes) - { + if h.overlaps(m.bytes, ch, plan.shared_rope_bytes) || h.overlaps(m.bytes, sh, plan.shared_rope_bytes) { return Err(Error::OutputAliasesInput); } } - let asset = if form == OriginalMtpRopeForm::LegacyTable { - session_legacy_asset() - } else { - session_native_asset() - } - .ok_or(Error::UnsupportedQwenOperation)?; + let asset = + if form == OriginalMtpRopeForm::LegacyTable { session_legacy_asset() } else { session_native_asset() } + .ok_or(Error::UnsupportedQwenOperation)?; if asset.windows(8).any(|w| w == b"UNSEALED") { return Err(Error::UnsupportedQwenOperation); } @@ -89,11 +80,7 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { })?; let loaded = FM::load( asset, - if form == OriginalMtpRopeForm::LegacyTable { - SESSION_LEGACY_ENTRIES - } else { - SESSION_NATIVE_ENTRIES - }, + if form == OriginalMtpRopeForm::LegacyTable { SESSION_LEGACY_ENTRIES } else { SESSION_NATIVE_ENTRIES }, ); let pop = g.finish(); if pop.is_err() { @@ -106,9 +93,7 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { return combine(loaded.map(|_| ()), pop).map(|()| unreachable!()); } owned.module = Some(loaded?); - Ok(Self { - inner: Rc::new(owned), - }) + Ok(Self { inner: Rc::new(owned) }) } pub fn plan(&self) -> OriginalMtpSessionPlan { self.inner.plan @@ -120,8 +105,7 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { self.inner.validate(c) } pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::>() - + self.inner.module.as_ref().map_or(0, FM::metadata_bytes) + std::mem::size_of::>() + self.inner.module.as_ref().map_or(0, FM::metadata_bytes) } /// Actual table owners are shared with SessionState, not a new MTP allocation. pub fn additional_device_bytes(&self) -> usize { @@ -141,27 +125,17 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { } checked(self.inner.context, &data, data.bytes)?; checked(self.inner.context, &positions, positions.bytes)?; - let dh = data.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( - data.bytes, - offset, - heads * 256 * 4, + let dh = data.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(data.bytes, offset, heads * 256 * 4)?; + let ph = positions.handle.ok_or(Error::ContextPoisoned)?.checked_subspan( + positions.bytes, + position_offset, + heads * 4, )?; - let ph = positions - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(positions.bytes, position_offset, heads * 4)?; - if dh.qwen_address() % 16 != 0 - || ph.qwen_address() % 4 != 0 - || dh.overlaps(heads * 256 * 4, ph, heads * 4) - { + if dh.qwen_address() % 16 != 0 || ph.qwen_address() % 4 != 0 || dh.overlaps(heads * 256 * 4, ph, heads * 4) { return Err(Error::OutputAliasesInput); } for source in std::iter::once(&self.inner.tables).chain(self.inner.mrope.iter()) { - if dh.overlaps( - heads * 256 * 4, - source.handle.ok_or(Error::ContextPoisoned)?, - source.bytes, - ) { + if dh.overlaps(heads * 256 * 4, source.handle.ok_or(Error::ContextPoisoned)?, source.bytes) { return Err(Error::OutputAliasesInput); } } @@ -170,27 +144,15 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { .inner .mrope .as_ref() - .map(|b| { - b.handle - .map(|h| h.qwen_address()) - .ok_or(Error::ContextPoisoned) - }) + .map(|b| b.handle.map(|h| h.qwen_address()).ok_or(Error::ContextPoisoned)) .transpose()? .unwrap_or(0); let whole = self.inner.tables.handle.ok_or(Error::ContextPoisoned)?; let cos = whole - .checked_subspan( - self.inner.tables.bytes, - self.inner.table_offsets[0], - self.inner.plan.shared_rope_bytes, - )? + .checked_subspan(self.inner.tables.bytes, self.inner.table_offsets[0], self.inner.plan.shared_rope_bytes)? .qwen_address(); let sin = whole - .checked_subspan( - self.inner.tables.bytes, - self.inner.table_offsets[1], - self.inner.plan.shared_rope_bytes, - )? + .checked_subspan(self.inner.tables.bytes, self.inner.table_offsets[1], self.inner.plan.shared_rope_bytes)? .qwen_address(); let args = FA::new(vec![ F::U64(dh.qwen_address()), @@ -208,20 +170,20 @@ impl<'ctx> OriginalMtpSessionResources<'ctx> { F::U64(mt), F::Words3([cos, sin, self.inner.plan.max_cells as u64]), ])?; - Ok(OriginalMtpSessionRopePlan { - session: Rc::clone(&self.inner), - data, - positions, - args, - heads, - }) + Ok(OriginalMtpSessionRopePlan { session: Rc::clone(&self.inner), data, positions, args, heads }) } } pub(super) fn session_native_asset() -> Option<&'static [u8]> { - crate::sealed_ptx::pinned(concat!(include_str!("../mtp_original_session_native_rope.ptx"), "\0").as_bytes(), SESSION_NATIVE_ASSET_PIN) + crate::sealed_ptx::pinned( + concat!(include_str!("../mtp_original_session_native_rope.ptx"), "\0").as_bytes(), + SESSION_NATIVE_ASSET_PIN, + ) } pub(super) fn session_legacy_asset() -> Option<&'static [u8]> { - crate::sealed_ptx::pinned(concat!(include_str!("../mtp_original_session_legacy_rope.ptx"), "\0").as_bytes(), SESSION_LEGACY_ASSET_PIN) + crate::sealed_ptx::pinned( + concat!(include_str!("../mtp_original_session_legacy_rope.ptx"), "\0").as_bytes(), + SESSION_LEGACY_ASSET_PIN, + ) } impl SessionOwned<'_> { pub(super) fn validate(&self, c: &Context<'_>) -> Result<()> { diff --git a/crates/cuda-driver/src/native_batch_workspace.rs b/crates/cuda-driver/src/native_batch_workspace.rs index 5b0f2aff..c14a7922 100644 --- a/crates/cuda-driver/src/native_batch_workspace.rs +++ b/crates/cuda-driver/src/native_batch_workspace.rs @@ -21,30 +21,17 @@ impl<'ctx> NativeBatchWorkspace<'ctx> { return Err(Error::ContextPoisoned); } let required = NATIVE_BATCH_WORKSPACE_BYTES + RESERVE; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - buffer: None, - blas: None, - failed: false, - }; + let mut owner = Self { context, buffer: None, blas: None, failed: false }; let operation = (|| { owner.buffer = Some(context.allocate(NATIVE_BATCH_WORKSPACE_BYTES)?); let guard = context.enter()?; let load = Blas::load( - owner - .buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, + owner.buffer.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?, NATIVE_BATCH_WORKSPACE_BYTES, ); let pop = guard.finish(); @@ -92,10 +79,7 @@ impl<'ctx> NativeBatchWorkspace<'ctx> { if buffer.bytes != NATIVE_BATCH_WORKSPACE_BYTES { return Err(Error::InvalidSize); } - buffer - .handle - .ok_or(Error::ContextPoisoned)? - .validate_projection_extent(NATIVE_BATCH_WORKSPACE_BYTES, 256)?; + buffer.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(NATIVE_BATCH_WORKSPACE_BYTES, 256)?; if context.allocated_bytes() > context.budget { return Err(Error::BudgetExceeded); } @@ -109,17 +93,8 @@ impl<'ctx> NativeBatchWorkspace<'ctx> { self.failed = true; self.context.poisoned.set(true); } - pub(crate) fn reject_alias( - &self, - handle: crate::ffi::BufferHandle, - bytes: usize, - ) -> Result<()> { - let h = self - .buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; + pub(crate) fn reject_alias(&self, handle: crate::ffi::BufferHandle, bytes: usize) -> Result<()> { + let h = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; if handle.overlaps(bytes, h, NATIVE_BATCH_WORKSPACE_BYTES) { return Err(Error::OutputAliasesInput); } diff --git a/crates/cuda-driver/src/native_flash_attn.rs b/crates/cuda-driver/src/native_flash_attn.rs index 9da6e108..c860579b 100644 --- a/crates/cuda-driver/src/native_flash_attn.rs +++ b/crates/cuda-driver/src/native_flash_attn.rs @@ -38,7 +38,11 @@ pub const LAUNCH: Launch = Launch { grid: [24, 1, 1], block: [32, 4, 1], dynamic /// The device-side validity test at the top of the kernel. pub fn step_is_valid(step: &[i32; STEP_COUNT], max_context: i32) -> bool { let width = step[STEP_WIDTH]; - width >= 1 && width <= max_context && step[STEP_NKV] == width && step[STEP_POS] == width - 1 && step[STEP_NBID] == width / 4 + width >= 1 + && width <= max_context + && step[STEP_NKV] == width + && step[STEP_POS] == width - 1 + && step[STEP_NBID] == width / 4 } /// Status word the kernel writes (`valid ? Success : UnsupportedStep`). pub fn step_status(step: &[i32; STEP_COUNT], max_context: i32) -> i32 { @@ -63,7 +67,9 @@ pub enum AdmissionError { impl AdmissionError { pub fn message(self) -> &'static str { match self { - Self::Unsupported => "native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream", + Self::Unsupported => { + "native FlashAttention supports only Q24x256/KV2x256, capacity>=256 and context1..256 on an explicit stream" + } Self::SpanNotAdmitted => "native FlashAttention requires nonnull aligned bounded spans", Self::SpansOverlap => "native FlashAttention requires disjoint buffers", } @@ -157,8 +163,21 @@ mod tests { fn good() -> Arguments { Arguments { - n_head: 24, n_head_kv: 2, head_dim: 256, idx_block: 4, idx_top_k: 2051, capacity: 4096, max_context: 256, stream_present: true, - q: 0x1000_0000, k: 0x2000_0000, v: 0x3000_0000, step: 0x4000_0000, output: 0x5000_0000, status: 0x6000_0000, mask: Some(0x7000_0000), + n_head: 24, + n_head_kv: 2, + head_dim: 256, + idx_block: 4, + idx_top_k: 2051, + capacity: 4096, + max_context: 256, + stream_present: true, + q: 0x1000_0000, + k: 0x2000_0000, + v: 0x3000_0000, + step: 0x4000_0000, + output: 0x5000_0000, + status: 0x6000_0000, + mask: Some(0x7000_0000), } } diff --git a/crates/cuda-driver/src/native_head.rs b/crates/cuda-driver/src/native_head.rs index fa673a7e..003fd939 100644 --- a/crates/cuda-driver/src/native_head.rs +++ b/crates/cuda-driver/src/native_head.rs @@ -6,9 +6,7 @@ mod abi; #[path = "native_head_mapped.rs"] #[allow(unsafe_code)] mod mapped; -use crate::original_gpu_schedule::{ - OriginalCapture, OriginalGpuStream, OriginalGraphResources, resources, -}; +use crate::original_gpu_schedule::{OriginalCapture, OriginalGpuStream, OriginalGraphResources, resources}; use crate::{Context, DeviceBuffer, Error, Result, SamplerParams, SamplerPath, combine}; use abi::{Arg, Command, Module}; use mapped::MappedAllocation; @@ -17,9 +15,27 @@ use std::{ rc::Rc, }; // Only integration's pinned compiled Original assets can replace these None values. -const NATIVE_ASSET_PIN: Option<(usize, [u8; 32])> = Some((7398534, [129, 163, 153, 12, 20, 62, 69, 29, 172, 121, 72, 98, 207, 115, 63, 95, 65, 33, 245, 42, 160, 112, 80, 197, 110, 6, 28, 23, 99, 209, 71, 154])); -const IQ_ASSET_PIN: Option<(usize, [u8; 32])> = Some((753629, [102, 211, 230, 34, 238, 79, 184, 182, 113, 146, 138, 115, 218, 231, 3, 133, 228, 65, 93, 180, 122, 213, 52, 45, 94, 176, 210, 80, 123, 234, 181, 228])); -const SAMPLER_ASSET_PIN: Option<(usize, [u8; 32])> = Some((497892, [134, 61, 177, 61, 198, 80, 35, 32, 110, 177, 164, 95, 41, 212, 185, 144, 166, 89, 87, 186, 21, 215, 131, 194, 50, 155, 189, 136, 236, 97, 51, 63])); +const NATIVE_ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 7398534, + [ + 129, 163, 153, 12, 20, 62, 69, 29, 172, 121, 72, 98, 207, 115, 63, 95, 65, 33, 245, 42, 160, 112, 80, 197, 110, + 6, 28, 23, 99, 209, 71, 154, + ], +)); +const IQ_ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 753629, + [ + 102, 211, 230, 34, 238, 79, 184, 182, 113, 146, 138, 115, 218, 231, 3, 133, 228, 65, 93, 180, 122, 213, 52, 45, + 94, 176, 210, 80, 123, 234, 181, 228, + ], +)); +const SAMPLER_ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 497892, + [ + 134, 61, 177, 61, 198, 80, 35, 32, 110, 177, 164, 95, 41, 212, 185, 144, 166, 89, 87, 186, 21, 215, 131, 194, + 50, 155, 189, 136, 236, 97, 51, 63, + ], +)); const RESERVE: usize = 128 * 1024 * 1024; /// Actual sampling inputs, not a row, graph, or accepted-prefix certificate. #[derive(Clone, Copy)] @@ -422,44 +438,44 @@ mod alias_tests; mod native_asset_fn; #[allow(unused_imports)] -use native_asset_fn::native_asset; -#[allow(unused_imports)] -use native_asset_fn::iq_asset; -#[allow(unused_imports)] -use native_asset_fn::sampler_asset; -#[allow(unused_imports)] -pub use native_asset_fn::native_head_supported; -#[allow(unused_imports)] -pub use native_asset_fn::native_embed_supported; -#[allow(unused_imports)] -pub use native_asset_fn::native_head_row_bytes; -#[allow(unused_imports)] -use native_asset_fn::geometry; +use native_asset_fn::address; #[allow(unused_imports)] use native_asset_fn::admission; #[allow(unused_imports)] -use native_asset_fn::transport; -#[allow(unused_imports)] -use native_asset_fn::address; -#[allow(unused_imports)] use native_asset_fn::admit; #[allow(unused_imports)] use native_asset_fn::admit_history_prefix; #[allow(unused_imports)] +use native_asset_fn::cmd; +#[allow(unused_imports)] use native_asset_fn::disjoint; #[allow(unused_imports)] +use native_asset_fn::geometry; +#[allow(unused_imports)] use native_asset_fn::greedy_entry; #[allow(unused_imports)] -use native_asset_fn::cmd; +use native_asset_fn::iq_asset; +#[allow(unused_imports)] +use native_asset_fn::native_asset; +#[allow(unused_imports)] +pub use native_asset_fn::native_embed_supported; +#[allow(unused_imports)] +pub use native_asset_fn::native_head_row_bytes; +#[allow(unused_imports)] +pub use native_asset_fn::native_head_supported; +#[allow(unused_imports)] +use native_asset_fn::sampler_asset; +#[allow(unused_imports)] +use native_asset_fn::transport; mod impl_headowned; mod projection_commands_fn; #[allow(unused_imports)] use projection_commands_fn::projection_commands; -mod impl_originalnativeheadrows; -mod impl_drop_for_originalnativeheadrows; -mod impl_originalnativeembed; -mod impl_originalgraphresources_for_originalnativeem; mod dispatch_fn; +mod impl_drop_for_originalnativeheadrows; +mod impl_originalgraphresources_for_originalnativeem; +mod impl_originalnativeembed; +mod impl_originalnativeheadrows; #[allow(unused_imports)] use dispatch_fn::dispatch; mod impl_originalnativeheadgraphresources_for_origin; diff --git a/crates/cuda-driver/src/native_head/alias_tests.rs b/crates/cuda-driver/src/native_head/alias_tests.rs index b75c1d28..4b6b2097 100644 --- a/crates/cuda-driver/src/native_head/alias_tests.rs +++ b/crates/cuda-driver/src/native_head/alias_tests.rs @@ -21,14 +21,26 @@ fn mapped_table_alias_reads_the_host_bytes_and_costs_no_device_memory() { let mut mapped = mapped.unwrap(); mapped.write(0, &expected).unwrap(); let handle = crate::ffi::BufferHandle::registered_bank_alias(mapped.address(0, bytes).unwrap(), bytes).unwrap(); - let alias = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; + let alias = DeviceBuffer { + context: &context, + handle: Some(handle), + bytes, + _thread: std::marker::PhantomData, + borrowed: true, + }; assert_eq!(context.allocated_bytes(), 0, "an alias is not charged"); let mut back = vec![0u8; bytes]; alias.copy_to(&mut back).unwrap(); assert!(back == expected, "the device reads the host copy through the alias"); // dropping or releasing an alias frees nothing: a second alias of the same block still reads it drop(alias); - let again = DeviceBuffer { context: &context, handle: Some(handle), bytes, _thread: std::marker::PhantomData, borrowed: true }; + let again = DeviceBuffer { + context: &context, + handle: Some(handle), + bytes, + _thread: std::marker::PhantomData, + borrowed: true, + }; let mut back = vec![0u8; bytes]; again.copy_to(&mut back).unwrap(); assert!(back == expected); diff --git a/crates/cuda-driver/src/native_head/impl_drop_for_originalnativeheadrows.rs b/crates/cuda-driver/src/native_head/impl_drop_for_originalnativeheadrows.rs index dc556840..45df218e 100644 --- a/crates/cuda-driver/src/native_head/impl_drop_for_originalnativeheadrows.rs +++ b/crates/cuda-driver/src/native_head/impl_drop_for_originalnativeheadrows.rs @@ -115,10 +115,7 @@ impl<'ctx> Context<'ctx> { let row = native_head_row_bytes(kind, n)?; let bytes = row.checked_mul(vocab).ok_or(Error::InvalidSize)?; if payload.len() != bytes { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: payload.len(), - }); + return Err(Error::ShapeMismatch { expected: bytes, actual: payload.len() }); } let ptx = iq_asset().ok_or(Error::UnsupportedQwenOperation)?; let mut owner = EmbedOwned { @@ -160,21 +157,11 @@ impl<'ctx> Context<'ctx> { m.write(0, payload)?; owner.mapped = Some(m); } - Err(Error::Driver { - operation: "cuMemHostAlloc", - .. - }) => { + Err(Error::Driver { operation: "cuMemHostAlloc", .. }) => { admission(self, bytes)?; owner.device = Some(self.allocate(bytes)?); - owner - .device - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(payload)?; - eprintln!( - "strata: native embedding: cannot pin {} MiB, kept in VRAM instead", - bytes >> 20 - ); + owner.device.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(payload)?; + eprintln!("strata: native embedding: cannot pin {} MiB, kept in VRAM instead", bytes >> 20); } Err(error) => return Err(error), } @@ -183,8 +170,6 @@ impl<'ctx> Context<'ctx> { if let Err(primary) = operation { return combine(Err(primary), owner.close()); } - Ok(OriginalNativeEmbed { - inner: Rc::new(owner), - }) + Ok(OriginalNativeEmbed { inner: Rc::new(owner) }) } } diff --git a/crates/cuda-driver/src/native_head/impl_headowned.rs b/crates/cuda-driver/src/native_head/impl_headowned.rs index 44f231c3..61897d43 100644 --- a/crates/cuda-driver/src/native_head/impl_headowned.rs +++ b/crates/cuda-driver/src/native_head/impl_headowned.rs @@ -8,8 +8,7 @@ impl HeadOwned<'_> { if !std::ptr::eq(c, self.context) { return Err(Error::ContextMismatch); } - if self.failed.get() || c.is_poisoned() || self.weights.is_none() || self.kernels.is_none() - { + if self.failed.get() || c.is_poisoned() || self.weights.is_none() || self.kernels.is_none() { Err(Error::ContextPoisoned) } else { Ok(()) @@ -52,16 +51,13 @@ impl HeadOwned<'_> { scratch = combine(scratch, b.release()); } } - let weights = self - .weights - .take() - .map_or(Ok(()), |b| match Rc::try_unwrap(b) { - Ok(b) => b.release(), - Err(b) => { - drop(b); - Ok(()) - } - }); + let weights = self.weights.take().map_or(Ok(()), |b| match Rc::try_unwrap(b) { + Ok(b) => b.release(), + Err(b) => { + drop(b); + Ok(()) + } + }); let guard = self.context.enter()?; let module = self.kernels.take().map_or(Ok(()), Kernels::close); let pop = guard.finish(); @@ -89,24 +85,16 @@ impl<'ctx> Context<'ctx> { if !native_head_supported(kind) { return Err(Error::UnsupportedQwenOperation); } - let bytes = native_head_row_bytes(kind, n)? - .checked_mul(vocab) - .ok_or(Error::InvalidSize)?; + let bytes = native_head_row_bytes(kind, n)?.checked_mul(vocab).ok_or(Error::InvalidSize)?; if payload.len() != bytes { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: payload.len(), - }); + return Err(Error::ShapeMismatch { expected: bytes, actual: payload.len() }); } // Unsealed assets refuse before admission/allocation; modules have a real owner // before pop so an uncertain Context never drops their driver dependencies. if native_asset().is_none() || iq_asset().is_none() || sampler_asset().is_none() { return Err(Error::UnsupportedQwenOperation); } - admission( - self, - bytes.checked_add(n / 32 * 36).ok_or(Error::InvalidSize)?, - )?; + admission(self, bytes.checked_add(n / 32 * 36).ok_or(Error::InvalidSize)?)?; let mut owner = HeadOwned { context: self, weights: None, @@ -143,9 +131,7 @@ impl<'ctx> Context<'ctx> { if let Err(primary) = op { return combine(Err(primary), owner.close()); } - Ok(OriginalNativeHead { - inner: Rc::new(owner), - }) + Ok(OriginalNativeHead { inner: Rc::new(owner) }) } } impl<'ctx> OriginalNativeHead<'ctx> { @@ -172,9 +158,7 @@ impl<'ctx> OriginalNativeHead<'ctx> { /// allocation; retaining it adds no staging buffer or data copy. pub fn retain_weights(&self) -> Result>> { self.inner.validate(self.inner.context)?; - Ok(Rc::clone( - self.inner.weights.as_ref().ok_or(Error::ContextPoisoned)?, - )) + Ok(Rc::clone(self.inner.weights.as_ref().ok_or(Error::ContextPoisoned)?)) } pub fn rows(&self, t: usize) -> Result> { OriginalNativeHeadRows::new(self.inner.clone(), t) @@ -189,11 +173,7 @@ impl<'ctx> OriginalNativeHead<'ctx> { ) -> Result> { self.inner.validate(self.inner.context)?; stream.validate_context(self.inner.context)?; - let q8 = self - .inner - .scalar_q8 - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let q8 = self.inner.scalar_q8.as_ref().ok_or(Error::ContextPoisoned)?; let mut commands = projection_commands(&self.inner, mixed, q8, logits, 1)?; let kernels = self.inner.kernels.as_ref().ok_or(Error::ContextPoisoned)?; for command in &commands { diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeembed.rs b/crates/cuda-driver/src/native_head/impl_originalnativeembed.rs index a12fa541..f75ede1e 100644 --- a/crates/cuda-driver/src/native_head/impl_originalnativeembed.rs +++ b/crates/cuda-driver/src/native_head/impl_originalnativeembed.rs @@ -47,33 +47,16 @@ impl<'ctx> OriginalNativeEmbed<'ctx> { if let Some(d) = &self.inner.device { disjoint(d, output)?; } - let input = self - .inner - .address()? - .checked_add(id as u64 * self.inner.row as u64) - .ok_or(Error::InvalidSize)?; + let input = self.inner.address()?.checked_add(id as u64 * self.inner.row as u64).ok_or(Error::InvalidSize)?; let mut command = cmd( "head_embed_one", [(self.inner.n / 256) as u32, 1, 1], [32, 1, 1], - vec![ - Arg::I32(self.inner.kind as i32), - Arg::Address(input), - Arg::Address(address(output)?), - ], + vec![Arg::I32(self.inner.kind as i32), Arg::Address(input), Arg::Address(address(output)?)], )?; - self.inner - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .admit(&command)?; - let operation = stream.with_enqueue(|h| { - self.inner - .kernels - .as_ref() - .ok_or(Error::ContextPoisoned)? - .launch(h, &mut command) - }); + self.inner.kernels.as_ref().ok_or(Error::ContextPoisoned)?.admit(&command)?; + let operation = + stream.with_enqueue(|h| self.inner.kernels.as_ref().ok_or(Error::ContextPoisoned)?.launch(h, &mut command)); if let Err(primary) = operation { let sync = stream.synchronize(); if sync.is_err() || self.inner.context.is_poisoned() { @@ -81,26 +64,14 @@ impl<'ctx> OriginalNativeEmbed<'ctx> { } return combine(Err(primary), sync); } - Ok(NativeEmbedFlight { - embed: self, - stream, - _output: output, - commands: Some(command), - active: true, - }) + Ok(NativeEmbedFlight { embed: self, stream, _output: output, commands: Some(command), active: true }) } pub fn rows(&self, t: usize) -> Result> { if t == 0 || t > i32::MAX as usize { return Err(Error::InvalidQwenShape); } let charge = t - .checked_mul( - self.inner - .n - .checked_mul(4) - .and_then(|n| n.checked_add(4)) - .ok_or(Error::InvalidSize)?, - ) + .checked_mul(self.inner.n.checked_mul(4).and_then(|n| n.checked_add(4)).ok_or(Error::InvalidSize)?) .ok_or(Error::InvalidSize)?; admission(self.inner.context, charge)?; let tokens = self.inner.context.allocate(t * 4)?; @@ -151,11 +122,7 @@ impl Drop for NativeEmbedFlight<'_, '_> { impl<'ctx> OriginalNativeEmbedRows<'ctx> { pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { self.embed.validate(c)?; - if self.tokens.is_none() || self.output.is_none() { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } + if self.tokens.is_none() || self.output.is_none() { Err(Error::ContextPoisoned) } else { Ok(()) } } pub fn tokens_mut(&mut self) -> Result<&mut DeviceBuffer<'ctx>> { self.validate_context(self.embed.context)?; @@ -180,11 +147,7 @@ impl<'ctx> OriginalNativeEmbedRows<'ctx> { } let mut c = cmd( "head_embed_rows", - [ - (self.embed.n / 256) as u32, - self.t.try_into().map_err(|_| Error::InvalidSize)?, - 1, - ], + [(self.embed.n / 256) as u32, self.t.try_into().map_err(|_| Error::InvalidSize)?, 1], [32, 1, 1], vec![ Arg::I32(self.embed.kind as i32), @@ -195,10 +158,7 @@ impl<'ctx> OriginalNativeEmbedRows<'ctx> { Arg::Address(address(output)?), ], )?; - self.commands - .borrow_mut() - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; + self.commands.borrow_mut().try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; let module = self.embed.kernels.as_ref().ok_or(Error::ContextPoisoned)?; module.admit(&c)?; let result = module.launch(capture.stream_handle(self.embed.context)?, &mut c); @@ -221,10 +181,7 @@ impl<'ctx> OriginalNativeEmbedRows<'ctx> { if sync.is_err() || c.is_poisoned() { c.poison(); c.retain_driver(); - for b in [self.tokens.take(), self.output.take()] - .into_iter() - .flatten() - { + for b in [self.tokens.take(), self.output.take()].into_iter().flatten() { std::mem::forget(b); } std::mem::forget(std::mem::take(self.commands.get_mut())); diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs index 4e07ebda..21214a0e 100644 --- a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs +++ b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2.rs @@ -3,16 +3,13 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalNativeHeadRows<'ctx> { pub(in super::super) fn new(head: Rc>, t: usize) -> Result { if !(1..=8).contains(&t) { return Err(Error::InvalidQwenShape); } head.validate(head.context)?; - let charge = t - .checked_mul(head.n * 4 + head.n / 32 * 36 + head.vocab * 4) - .ok_or(Error::InvalidSize)?; + let charge = t.checked_mul(head.n * 4 + head.n / 32 * 36 + head.vocab * 4).ok_or(Error::InvalidSize)?; admission(head.context, charge)?; let mut owner = Self { head, @@ -71,10 +68,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { b.as_ref().ok_or(Error::ContextPoisoned) } pub(in super::super) fn output_address(&self) -> Result { - self.mapped - .as_ref() - .ok_or(Error::ContextPoisoned)? - .address(0, self.t * 4) + self.mapped.as_ref().ok_or(Error::ContextPoisoned)?.address(0, self.t * 4) } pub(in super::super) fn projection(&self) -> Result> { self.validate_context(self.head.context)?; @@ -108,10 +102,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { ) } pub(in super::super) fn prepare_commands(&self, commands: &[Command]) -> Result<()> { - self.commands - .borrow_mut() - .try_reserve_exact(commands.len()) - .map_err(|_| Error::HostAllocation)?; + self.commands.borrow_mut().try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?; let k = self.head.kernels.as_ref().ok_or(Error::ContextPoisoned)?; for c in commands { k.module(c.name)?.admit(c)?; @@ -157,11 +148,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { if let Err(primary) = op { return combine(Err(primary), stream.synchronize()); } - Ok(NativeHeadFlight { - rows: self, - stream, - active: true, - }) + Ok(NativeHeadFlight { rows: self, stream, active: true }) } // Called ONLY by the genuine graph bridge after an actual launched graph drain, // or by NativeHeadFlight after its same-stream wait. No caller completion flag. @@ -170,14 +157,8 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { stream: &mut OriginalGpuStream<'ctx>, sampling: NativeHeadSampling<'_, 'ctx>, ) -> Result { - let NativeHeadSampling { - position: pos0, - params, - history, - history_len, - path, - enabled: head_sampling, - } = sampling; + let NativeHeadSampling { position: pos0, params, history, history_len, path, enabled: head_sampling } = + sampling; self.validate_context(self.head.context)?; stream.validate_context(self.head.context)?; params.validate()?; @@ -201,10 +182,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { admit_history_prefix( self.head.context, h, - self.t - .checked_mul(history_len) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::InvalidSize)?, + self.t.checked_mul(history_len).and_then(|n| n.checked_mul(4)).ok_or(Error::InvalidSize)?, )?; disjoint(h, self.buffer(&self.mixed)?)?; disjoint(h, self.buffer(&self.q8)?)?; @@ -213,13 +191,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { } else { (None, 0) }; - let mut commands = self.sample_commands( - p, - history, - history_len, - path, - stream.native_head_stream_key()?, - )?; + let mut commands = self.sample_commands(p, history, history_len, path, stream.native_head_stream_key()?)?; self.prepare_commands(&commands)?; let span_sample = crate::host_profile::span("head.sample_sync"); let operation = stream.with_enqueue(|h| self.submit(h, std::mem::take(&mut commands))); @@ -229,21 +201,10 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { self.commands.borrow_mut().clear(); } let _span_ids = crate::host_profile::span("head.read_ids"); - let ids = self - .mapped - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_i32(self.t)?; - if ids - .iter() - .any(|&id| id < 0 || id as usize >= self.head.vocab) - { + let ids = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?.read_i32(self.t)?; + if ids.iter().any(|&id| id < 0 || id as usize >= self.head.vocab) { return Err(Error::InvalidDriverValue("Original NativeHead sampled id")); } - Ok(NativeHeadSelection { - ids, - position: pos0, - vocabulary: self.head.vocab, - }) + Ok(NativeHeadSelection { ids, position: pos0, vocabulary: self.head.vocab }) } } diff --git a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs index 096ddc73..ad42b804 100644 --- a/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs +++ b/crates/cuda-driver/src/native_head/impl_originalnativeheadrows/impl_originalnativeheadrows_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalNativeHeadRows<'ctx> { pub(in super::super) fn sample_commands( &self, @@ -18,11 +17,8 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { let output = self.output_address()?; let v = self.head.vocab as i32; let t = self.t as i32; - let shared = if history != 0 && history_len > 0 && p.penalty_last_n > 0 { - self.head.vocab.div_ceil(32) * 4 - } else { - 0 - }; + let shared = + if history != 0 && history_len > 0 && p.penalty_last_n > 0 { self.head.vocab.div_ceil(32) * 4 } else { 0 }; let mut c = Vec::new(); c.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; if p.greedy || p.temperature <= 0.0 { @@ -66,12 +62,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { None }; if let Some(scratch) = scratch { - let k = if p.top_k > 0 && p.top_k < 64 { - p.top_k - } else { - 64 - } - .min(v); + let k = if p.top_k > 0 && p.top_k < 64 { p.top_k } else { 64 }.min(v); c.push(cmd( "sampler_split_part_kernel", [blocks as u32, self.t as u32, 1], @@ -126,17 +117,11 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { } // Same per-(device, actual stream) lifetime as Original. All fixed-T banks // share this model owner; streams never share a scratch buffer. - let mut slots = self - .head - .sampling - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?; + let mut slots = self.head.sampling.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; let at = match slots.iter().position(|slot| slot.stream == stream_key) { Some(at) => at, None => { - slots - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; + slots.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; slots.push(SamplingScratch { stream: stream_key, buffer: None, @@ -154,9 +139,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { if slot.failed != 0 && entries >= slot.failed { return Ok(None); } - slot.retired - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; + slot.retired.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; let want = (2 * slot.entries).min(CAP).max(entries); for n in [want, entries] { // Admission refusal is the original allocation-failure fallback; do not @@ -175,11 +158,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { slot.entries = n; return slot.buffer.as_ref().map(address).transpose(); } - Err(Error::BudgetExceeded) - | Err(Error::Driver { - operation: "cuMemAlloc_v2", - code: 2, - }) => {} + Err(Error::BudgetExceeded) | Err(Error::Driver { operation: "cuMemAlloc_v2", code: 2 }) => {} Err(e) => return Err(e), } } @@ -195,11 +174,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { self.close_inner() } pub(in super::super) fn close_inner(&mut self) -> Result<()> { - if self.mixed.is_none() - && self.q8.is_none() - && self.logits.is_none() - && self.mapped.is_none() - { + if self.mixed.is_none() && self.q8.is_none() && self.logits.is_none() && self.mapped.is_none() { return Ok(()); } self.failed.set(true); @@ -208,10 +183,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { if sync.is_err() || context.is_poisoned() { context.poison(); context.retain_driver(); - for b in [self.mixed.take(), self.q8.take(), self.logits.take()] - .into_iter() - .flatten() - { + for b in [self.mixed.take(), self.q8.take(), self.logits.take()].into_iter().flatten() { std::mem::forget(b); } if let Some(m) = self.mapped.take() { @@ -222,10 +194,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> { } self.commands.get_mut().clear(); let mut result = Ok(()); - for b in [self.mixed.take(), self.q8.take(), self.logits.take()] - .into_iter() - .flatten() - { + for b in [self.mixed.take(), self.q8.take(), self.logits.take()].into_iter().flatten() { result = combine(result, b.release()); } let guard = context.enter()?; diff --git a/crates/cuda-driver/src/native_head/native_asset_fn.rs b/crates/cuda-driver/src/native_head/native_asset_fn.rs index b2a9f345..eb7d9305 100644 --- a/crates/cuda-driver/src/native_head/native_asset_fn.rs +++ b/crates/cuda-driver/src/native_head/native_asset_fn.rs @@ -14,10 +14,7 @@ pub(super) fn sampler_asset() -> Option<&'static [u8]> { } impl Default for NativeHeadDispatch { fn default() -> Self { - Self { - multi_exact: true, - old_iq: false, - } + Self { multi_exact: true, old_iq: false } } } impl NativeHeadDispatch { @@ -34,23 +31,14 @@ impl NativeHeadDispatch { let b = v.to_string_lossy(); !b.is_empty() && !b.starts_with('0') }); - Self { - multi_exact: true, - old_iq, - } + Self { multi_exact: true, old_iq } } } pub fn native_head_supported(kind: u32) -> bool { - matches!( - kind, - 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42 - ) + matches!(kind, 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42) } pub fn native_embed_supported(kind: u32) -> bool { - matches!( - kind, - 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42 - ) + matches!(kind, 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42) } pub fn native_head_row_bytes(kind: u32, n: usize) -> Result { let (block, bytes) = match kind { @@ -86,11 +74,7 @@ pub(super) fn geometry(n: usize, v: usize) -> Result<()> { } pub(super) fn admission(c: &Context<'_>, charge: usize) -> Result<()> { let total = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?; - if c.allocated_bytes() - .checked_add(total) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < total - { + if c.allocated_bytes().checked_add(total).is_none_or(|n| n > c.budget) || c.memory_info()?.0 < total { return Err(Error::BudgetExceeded); } Ok(()) @@ -110,14 +94,9 @@ pub(super) fn admit(c: &Context<'_>, b: &DeviceBuffer<'_>, bytes: usize) -> Resu return Err(Error::ContextMismatch); } if b.len() != bytes { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: b.len(), - }); + return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() }); } - b.handle - .ok_or(Error::ContextPoisoned)? - .validate_projection_extent(bytes, 4) + b.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(bytes, 4) } // Original serve allocates all kVerifyMaxT*4096 history slots once, while // each request lends only its actual contiguous T*h prefix to the sampler. @@ -126,22 +105,12 @@ pub(super) fn admit_history_prefix(c: &Context<'_>, b: &DeviceBuffer<'_>, bytes: return Err(Error::ContextMismatch); } if bytes == 0 || bytes > b.len() { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: b.len(), - }); + return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() }); } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.len(), 0, bytes)? - .validate_projection_extent(bytes, 4) + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), 0, bytes)?.validate_projection_extent(bytes, 4) } pub(super) fn disjoint(a: &DeviceBuffer<'_>, b: &DeviceBuffer<'_>) -> Result<()> { - if a.handle.ok_or(Error::ContextPoisoned)?.overlaps( - a.len(), - b.handle.ok_or(Error::ContextPoisoned)?, - b.len(), - ) { + if a.handle.ok_or(Error::ContextPoisoned)?.overlaps(a.len(), b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { Err(Error::OutputAliasesInput) } else { Ok(()) @@ -149,7 +118,11 @@ pub(super) fn disjoint(a: &DeviceBuffer<'_>, b: &DeviceBuffer<'_>) -> Result<()> } /// The greedy argmax entry: the Original's, or the load-hoisted chain variant (bit-identical picks) when `LELEKA_CHAIN=head`. pub(super) fn greedy_entry() -> &'static str { - if crate::original_verify::chain::flags().head { crate::original_verify::chain::E_SAMPLER_GREEDY } else { "sampler_greedy_kernel" } + if crate::original_verify::chain::flags().head { + crate::original_verify::chain::E_SAMPLER_GREEDY + } else { + "sampler_greedy_kernel" + } } pub(super) fn cmd(name: &'static str, grid: [u32; 3], block: [u32; 3], args: Vec) -> Result { Command::new(name, grid, block, 0, args) @@ -159,12 +132,7 @@ impl Kernels { let n = native_asset().ok_or(Error::UnsupportedQwenOperation)?; let i = iq_asset().ok_or(Error::UnsupportedQwenOperation)?; let s = sampler_asset().ok_or(Error::UnsupportedQwenOperation)?; - let mut owner = Self { - native: None, - iq: None, - sampler: None, - chain: None, - }; + let mut owner = Self { native: None, iq: None, sampler: None, chain: None }; let op = (|| { owner.native = Some(Module::load(n, NATIVE_ENTRIES)?); owner.iq = Some(Module::load(i, IQ_ENTRIES)?); diff --git a/crates/cuda-driver/src/native_head/projection_commands_fn.rs b/crates/cuda-driver/src/native_head/projection_commands_fn.rs index df487917..4dce8bec 100644 --- a/crates/cuda-driver/src/native_head/projection_commands_fn.rs +++ b/crates/cuda-driver/src/native_head/projection_commands_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn projection_commands( head: &HeadOwned<'_>, mixed: &DeviceBuffer<'_>, @@ -16,20 +15,11 @@ pub(super) fn projection_commands( admit(head.context, mixed, t * head.n * 4)?; admit(head.context, q8, t * head.n / 32 * 36)?; admit(head.context, logits, t * head.vocab * 4)?; - for (a, b) in [ - (mixed, q8), - (mixed, logits), - (q8, logits), - (weights, mixed), - (weights, q8), - (weights, logits), - ] { + for (a, b) in [(mixed, q8), (mixed, logits), (q8, logits), (weights, mixed), (weights, q8), (weights, logits)] { disjoint(a, b)?; } let mut commands = Vec::new(); - commands - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; commands.push(cmd( "head_quant", [(head.n * t).div_ceil(256) as u32, 1, 1], diff --git a/crates/cuda-driver/src/native_head_ffi.rs b/crates/cuda-driver/src/native_head_ffi.rs index 2da22768..2c076ac0 100644 --- a/crates/cuda-driver/src/native_head_ffi.rs +++ b/crates/cuda-driver/src/native_head_ffi.rs @@ -5,19 +5,8 @@ type Handle = *mut c_void; type Load = unsafe extern "C" fn(*mut Handle, *const c_void) -> i32; type Destroy = unsafe extern "C" fn(Handle) -> i32; type Function = unsafe extern "C" fn(*mut Handle, Handle, *const i8) -> i32; -type Launch = unsafe extern "C" fn( - Handle, - u32, - u32, - u32, - u32, - u32, - u32, - u32, - Handle, - *mut *mut c_void, - *mut *mut c_void, -) -> i32; +type Launch = + unsafe extern "C" fn(Handle, u32, u32, u32, u32, u32, u32, u32, Handle, *mut *mut c_void, *mut *mut c_void) -> i32; pub(super) enum Arg { Address(u64), I32(i32), @@ -57,17 +46,8 @@ impl Command { args: Vec, ) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(args.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - name, - grid, - block, - shared, - args: args.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(args.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { name, grid, block, shared, args: args.into_boxed_slice(), pointers }) } } struct Library(Handle); @@ -89,14 +69,7 @@ pub(super) struct Module { unload: Destroy, } fn check(op: &'static str, c: i32) -> Result<()> { - if c == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: c, - }) - } + if c == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: c }) } } impl Module { pub(super) fn load(ptx: &'static [u8], entries: &'static [&'static str]) -> Result { @@ -104,20 +77,14 @@ impl Module { return Err(Error::InvalidDriverValue("NativeHead sealed PTX")); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } fn sym(l: &Library, n: &'static CStr) -> Result { // SAFETY: the handle is a live dlopen handle and the symbol name is a NUL-terminated literal; null is rejected right below. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; - if p.is_null() { - Err(Error::MissingSymbol(n.to_str().unwrap_or("NativeHead ABI"))) - } else { - Ok(p) - } + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("NativeHead ABI"))) } else { Ok(p) } } macro_rules! symbol { ($n:literal,$t:ty) => { @@ -135,17 +102,12 @@ impl Module { handle: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let operation = (|| { let mut h = std::ptr::null_mut(); // SAFETY: arch_ptx::image yields the 'static, NUL-terminated PTX (NUL checked at entry; sm86 companions come from // sealed_ptx::pinned which re-checks it); `m` is a valid out-pointer and the driver is done with the image on return. - check("cuModuleLoadData", unsafe { - load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if h.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } @@ -155,9 +117,7 @@ impl Module { let mut f = std::ptr::null_mut(); // SAFETY: the module handle was loaded just above and is still owned by `owner`; the entry name is a 'static // NUL-terminated literal; the function out-pointer is valid. - check("cuModuleGetFunction", unsafe { - function(&mut f, h, c.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { function(&mut f, h, c.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); } @@ -182,12 +142,7 @@ impl Module { } pub(super) fn launch(&self, stream: usize, c: &mut Command) -> Result<()> { self.admit(c)?; - let f = self - .functions - .iter() - .find(|(n, _)| *n == c.name) - .ok_or(Error::UnsupportedQwenOperation)? - .1; + let f = self.functions.iter().find(|(n, _)| *n == c.name).ok_or(Error::UnsupportedQwenOperation)?.1; c.pointers.clear(); for arg in c.args.iter_mut() { c.pointers.push(arg.pointer()); diff --git a/crates/cuda-driver/src/native_head_mapped.rs b/crates/cuda-driver/src/native_head_mapped.rs index 07b64b49..d639facc 100644 --- a/crates/cuda-driver/src/native_head_mapped.rs +++ b/crates/cuda-driver/src/native_head_mapped.rs @@ -1,11 +1,7 @@ //! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free. use crate::{Error, Result}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; use std::ffi::c_void; @@ -24,14 +20,7 @@ mod enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -58,9 +47,7 @@ mod enabled { return Err(Error::InvalidSize); } // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -74,23 +61,14 @@ mod enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - bytes, - free, - }; + let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, bytes, free }; // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -100,9 +78,7 @@ mod enabled { } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { let p = self.host.ok_or(Error::ContextPoisoned)?; @@ -124,8 +100,7 @@ mod enabled { pub(crate) fn read_i32(&self, n: usize) -> Result> { let p = self.range(0, n.checked_mul(4).ok_or(Error::InvalidSize)?)?; let mut out = Vec::new(); - out.try_reserve_exact(n) - .map_err(|_| Error::HostAllocation)?; + out.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; for i in 0..n { // SAFETY: range(0, n*4) proved [p, p+4n) is inside the live allocation; p is 256-aligned (checked at alloc) so every // i32 is aligned. The block is not CPU-zeroed: the sampler/embed kernels write all n words before this read (callers @@ -229,11 +204,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::MappedAllocation; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/native_parity.rs b/crates/cuda-driver/src/native_parity.rs index d9fda036..23c001a3 100644 --- a/crates/cuda-driver/src/native_parity.rs +++ b/crates/cuda-driver/src/native_parity.rs @@ -79,37 +79,37 @@ const ENTRIES: &[&str] = &[ mod sealed_ptx_fn; #[allow(unused_imports)] -use sealed_ptx_fn::sealed_ptx; -#[allow(unused_imports)] -use sealed_ptx_fn::message; -#[allow(unused_imports)] -use sealed_ptx_fn::first; -#[allow(unused_imports)] -pub use sealed_ptx_fn::native_parity_iq_supported; -#[allow(unused_imports)] -pub use sealed_ptx_fn::native_parity_embed_supported; -#[allow(unused_imports)] -pub use sealed_ptx_fn::native_parity_row_bytes; -#[allow(unused_imports)] -use sealed_ptx_fn::split; -#[allow(unused_imports)] -use sealed_ptx_fn::layout; -#[allow(unused_imports)] -use sealed_ptx_fn::command; -#[allow(unused_imports)] use sealed_ptx_fn::address; #[allow(unused_imports)] use sealed_ptx_fn::bytes_f32; #[allow(unused_imports)] use sealed_ptx_fn::bytes_i32; #[allow(unused_imports)] +use sealed_ptx_fn::command; +#[allow(unused_imports)] +use sealed_ptx_fn::first; +#[allow(unused_imports)] use sealed_ptx_fn::floats; -mod impl_state; +#[allow(unused_imports)] +use sealed_ptx_fn::layout; +#[allow(unused_imports)] +use sealed_ptx_fn::message; +#[allow(unused_imports)] +pub use sealed_ptx_fn::native_parity_embed_supported; +#[allow(unused_imports)] +pub use sealed_ptx_fn::native_parity_iq_supported; +#[allow(unused_imports)] +pub use sealed_ptx_fn::native_parity_row_bytes; +#[allow(unused_imports)] +use sealed_ptx_fn::sealed_ptx; +#[allow(unused_imports)] +use sealed_ptx_fn::split; mod impl_nativeparity; mod impl_nativeparityexpert; +mod impl_state; #[allow(unused_imports)] -use impl_nativeparityexpert::read; +use impl_nativeparityexpert::down_entry; #[allow(unused_imports)] use impl_nativeparityexpert::gu_entry; #[allow(unused_imports)] -use impl_nativeparityexpert::down_entry; +use impl_nativeparityexpert::read; diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs index 0af6435e..5892798b 100644 --- a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs +++ b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> NativeParity<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> BenchResult { let ptx = sealed_ptx().ok_or("Original parity asset is unsealed")?; @@ -33,16 +32,10 @@ impl<'ctx> NativeParity<'ctx> { entries: Vec::new(), }; let admit = (|| { - state - .entries - .try_reserve_exact(ENTRIES.len()) - .map_err(|_| "parity function allocation")?; + state.entries.try_reserve_exact(ENTRIES.len()).map_err(|_| "parity function allocation")?; for &name in ENTRIES { let c = CString::new(name).map_err(|_| "parity entry NUL")?; - state.entries.push(( - name, - message(state.api.as_ref().ok_or("parity ABI")?.function(module, &c))?, - )); + state.entries.push((name, message(state.api.as_ref().ok_or("parity ABI")?.function(module, &c))?)); } Ok(()) })(); @@ -60,18 +53,11 @@ impl<'ctx> NativeParity<'ctx> { let b = x.as_encoded_bytes(); !b.is_empty() && b[0] != b'0' }); - Ok(Self { - state: Rc::new(state), - old, - }) + Ok(Self { state: Rc::new(state), old }) } pub(in super::super) fn idle(&self) -> BenchResult<()> { self.state.healthy()?; - if self.state.active.get() { - Err("Original parity expert still owned".into()) - } else { - Ok(()) - } + if self.state.active.get() { Err("Original parity expert still owned".into()) } else { Ok(()) } } pub(in super::super) fn expert(&self, e: &NativeParityExpert<'ctx>) -> BenchResult<()> { self.state.healthy()?; @@ -108,31 +94,14 @@ impl<'ctx> NativeParity<'ctx> { }; self.state.active.set(true); let prepare = (|| { - e.buffers - .try_reserve_exact(10) - .map_err(|_| "parity expert directory")?; - for n in [ - blob.len(), - NT * H * 4, - NT * (H / 32) * 36, - 25344, - NT * H * 4, - 8, - 8, - 4, - NT * 4, - NT * 4, - ] { + e.buffers.try_reserve_exact(10).map_err(|_| "parity expert directory")?; + for n in [blob.len(), NT * H * 4, NT * (H / 32) * 36, 25344, NT * H * 4, 8, 8, 4, NT * 4, NT * 4] { e.buffers.push(message(self.state.context.allocate(n))?); } self.state.upload(&e.buffers[0], blob)?; self.state.upload(&e.buffers[1], &bytes_f32(input)?)?; - self.state.upload( - &e.buffers[5], - &address(&e.buffers[0], 0, blob.len())?.to_le_bytes(), - )?; - self.state - .upload(&e.buffers[6], &bytes_i32(&[0, NT as i32])?)?; + self.state.upload(&e.buffers[5], &address(&e.buffers[0], 0, blob.len())?.to_le_bytes())?; + self.state.upload(&e.buffers[6], &bytes_i32(&[0, NT as i32])?)?; self.state.upload(&e.buffers[7], &1i32.to_le_bytes())?; self.state.upload(&e.buffers[8], &bytes_i32(&[0, 1, 2])?)?; self.state.upload(&e.buffers[9], &bytes_i32(&[0, 1, 2])?)?; @@ -193,12 +162,7 @@ impl<'ctx> NativeParity<'ctx> { "parity_swiglu", [8, 1, 1], [256, 1, 1], - vec![ - Arg::Address(gate), - Arg::Address(up), - Arg::Address(hidden), - Arg::I64(1920), - ], + vec![Arg::Address(gate), Arg::Address(up), Arg::Address(hidden), Arg::I64(1920)], )?, command( "parity_quant", diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs index 88f41401..85f14288 100644 --- a/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs +++ b/crates/cuda-driver/src/native_parity/impl_nativeparity/impl_nativeparity_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> NativeParity<'ctx> { pub fn dequantize_expert_role( &mut self, @@ -19,11 +18,7 @@ impl<'ctx> NativeParity<'ctx> { let (ty, off, nbytes) = match role { 0 => (e.layout.gu, 0, e.layout.up as usize), 1 => (e.layout.gu, e.layout.up as usize, e.layout.up as usize), - _ => ( - e.layout.down, - e.layout.d as usize, - e.layout.bytes as usize - e.layout.d as usize, - ), + _ => (e.layout.down, e.layout.d as usize, e.layout.bytes as usize - e.layout.d as usize), }; let a = address(&e.buffers[0], off, nbytes)?; self.state.enqueue(vec![ @@ -31,47 +26,28 @@ impl<'ctx> NativeParity<'ctx> { "parity_dequant_f32", [6400, 1, 1], [32, 1, 1], - vec![ - Arg::I32(ty), - Arg::Address(a), - Arg::Address(address(&diag[0], 0, H * FF * 4)?), - ], + vec![Arg::I32(ty), Arg::Address(a), Arg::Address(address(&diag[0], 0, H * FF * 4)?)], )?, command( "parity_dequant_f16", [6400, 1, 1], [32, 1, 1], - vec![ - Arg::I32(ty), - Arg::Address(a), - Arg::Address(address(&diag[1], 0, H * FF * 2)?), - ], + vec![Arg::I32(ty), Arg::Address(a), Arg::Address(address(&diag[1], 0, H * FF * 2)?)], )?, ])?; self.state.drain()?; let f = floats(read(&self.state, &diag[0], H * FF * 4)?)?; let raw = read(&self.state, &diag[1], H * FF * 2)?; let mut h = Vec::new(); - h.try_reserve_exact(H * FF) - .map_err(|_| "half readback allocation")?; + h.try_reserve_exact(H * FF).map_err(|_| "half readback allocation")?; for v in raw.chunks_exact(2) { h.push(u16::from_le_bytes([v[0], v[1]])); } Ok((f, h)) } - pub fn embed_expert_gate( - &mut self, - e: &NativeParityExpert<'ctx>, - rows: &[i32], - ) -> BenchResult> { + pub fn embed_expert_gate(&mut self, e: &NativeParityExpert<'ctx>, rows: &[i32]) -> BenchResult> { self.expert(e)?; - if rows.len() != FF - || rows - .iter() - .enumerate() - .any(|(i, &r)| r != (FF - 1 - i) as i32) - || e.enqueued.get() - { + if rows.len() != FF || rows.iter().enumerate().any(|(i, &r)| r != (FF - 1 - i) as i32) || e.enqueued.get() { return Err("Original gate embedding token extent/order".into()); } e.diagnostics()?; @@ -98,11 +74,7 @@ impl<'ctx> NativeParity<'ctx> { } e.release() } - pub fn q5_one_min( - &mut self, - weights: &[u8], - input: &[f32], - ) -> BenchResult<(Vec, Vec)> { + pub fn q5_one_min(&mut self, weights: &[u8], input: &[f32]) -> BenchResult<(Vec, Vec)> { self.idle()?; if weights.len() != 64 * 20 * 24 || input.len() != 640 { return Err("Original Q5_1 extent".into()); @@ -120,11 +92,7 @@ impl<'ctx> NativeParity<'ctx> { "parity_quant", [3, 1, 1], [256, 1, 1], - vec![ - Arg::Address(address(&b[1], 0, 2560)?), - Arg::Address(address(&b[2], 0, 720)?), - Arg::I64(640), - ], + vec![Arg::Address(address(&b[1], 0, 2560)?), Arg::Address(address(&b[2], 0, 720)?), Arg::I64(640)], )?, command( "parity_mmvq_7", @@ -142,18 +110,11 @@ impl<'ctx> NativeParity<'ctx> { )?, ])?; self.state.drain()?; - Ok(( - floats(read(&self.state, &b[3], 256)?)?, - read(&self.state, &b[2], 720)?, - )) + Ok((floats(read(&self.state, &b[3], 256)?)?, read(&self.state, &b[2], 720)?)) })(); first(result, owned.release()) } - pub fn bf16_embedding( - &mut self, - table: &[u16], - ids: &[i32], - ) -> BenchResult<(Vec, Vec)> { + pub fn bf16_embedding(&mut self, table: &[u16], ids: &[i32]) -> BenchResult<(Vec, Vec)> { self.idle()?; if table.len() != 61 * H || ids.len() != 97 || ids.iter().any(|&i| !(0..61).contains(&i)) { return Err("Original BF16 embedding extent".into()); @@ -165,8 +126,7 @@ impl<'ctx> NativeParity<'ctx> { } let b = &owned.buffers; let mut raw = Vec::new(); - raw.try_reserve_exact(table.len() * 2) - .map_err(|_| "BF16 staging allocation")?; + raw.try_reserve_exact(table.len() * 2).map_err(|_| "BF16 staging allocation")?; for h in table { raw.extend_from_slice(&h.to_le_bytes()); } diff --git a/crates/cuda-driver/src/native_parity/impl_nativeparityexpert.rs b/crates/cuda-driver/src/native_parity/impl_nativeparityexpert.rs index 6f5921e2..a6d20727 100644 --- a/crates/cuda-driver/src/native_parity/impl_nativeparityexpert.rs +++ b/crates/cuda-driver/src/native_parity/impl_nativeparityexpert.rs @@ -7,11 +7,7 @@ impl<'ctx> NativeParityExpert<'ctx> { pub(super) fn diagnostics(&self) -> BenchResult<()> { let mut d = self.diagnostic.borrow_mut(); if !d.is_empty() { - return if d.len() == 3 { - Ok(()) - } else { - Err("partial diagnostic owners".into()) - }; + return if d.len() == 3 { Ok(()) } else { Err("partial diagnostic owners".into()) }; } d.try_reserve_exact(3).map_err(|_| "diagnostic directory")?; for n in [H * FF * 4, H * FF * 2, FF * 4] { @@ -19,9 +15,7 @@ impl<'ctx> NativeParityExpert<'ctx> { } { let mut reverse = Vec::new(); - reverse - .try_reserve_exact(FF) - .map_err(|_| "reverse token allocation")?; + reverse.try_reserve_exact(FF).map_err(|_| "reverse token allocation")?; for r in 0..FF { reverse.push((FF - 1 - r) as i32); } @@ -51,9 +45,7 @@ impl Drop for NativeParityExpert<'_> { impl<'ctx> Temporary<'ctx> { pub(super) fn new(state: Rc>) -> BenchResult { let mut buffers = Vec::new(); - buffers - .try_reserve_exact(4) - .map_err(|_| "temporary owner directory")?; + buffers.try_reserve_exact(4).map_err(|_| "temporary owner directory")?; Ok(Self { state, buffers }) } pub(super) fn release(mut self) -> BenchResult<()> { @@ -76,19 +68,13 @@ pub(super) fn read(state: &State<'_>, b: &DeviceBuffer<'_>, bytes: usize) -> Ben let whole = message(b.handle.ok_or(Error::ContextPoisoned))?; let handle = message(whole.checked_subspan(b.len(), 0, bytes))?; let mut output = Vec::new(); - output - .try_reserve_exact(bytes) - .map_err(|_| "readback allocation")?; + output.try_reserve_exact(bytes).map_err(|_| "readback allocation")?; output.resize(bytes, 0); let guard = message(b.context.enter())?; let copy = message(b.context.driver.api.copy_to(handle, &mut output)); // The same blocking DtoH copy as cudaMemcpy in the Original benchmark. // On a failed copy, drain before host/destination owners can be reclaimed. - let sync = if copy.is_err() { - message(b.context.driver.api.synchronize()) - } else { - Ok(()) - }; + let sync = if copy.is_err() { message(b.context.driver.api.synchronize()) } else { Ok(()) }; let pop = message(guard.finish()); if copy.is_err() { state.failed.set(true); diff --git a/crates/cuda-driver/src/native_parity/impl_state.rs b/crates/cuda-driver/src/native_parity/impl_state.rs index a0e8f285..ec3a725c 100644 --- a/crates/cuda-driver/src/native_parity/impl_state.rs +++ b/crates/cuda-driver/src/native_parity/impl_state.rs @@ -18,14 +18,9 @@ impl State<'_> { } let handle = b.handle.ok_or("Original upload released")?; let mut staging = Vec::new(); - staging - .try_reserve_exact(payload.len()) - .map_err(|_| "Original upload staging")?; + staging.try_reserve_exact(payload.len()).map_err(|_| "Original upload staging")?; staging.extend_from_slice(payload); - self.staging - .borrow_mut() - .try_reserve_exact(1) - .map_err(|_| "Original staging directory")?; + self.staging.borrow_mut().try_reserve_exact(1).map_err(|_| "Original staging directory")?; let guard = message(self.context.enter())?; self.pending.set(true); let copy = message(self.context.driver.api.copy_from(handle, &staging)); @@ -46,10 +41,7 @@ impl State<'_> { let api = self.api.as_ref().ok_or("parity ABI closed")?; let stream = self.stream.get().ok_or("parity stream closed")?; // Reserve every retained argument before the first queued instruction. - self.commands - .borrow_mut() - .try_reserve_exact(commands.len()) - .map_err(|_| "parity command allocation")?; + self.commands.borrow_mut().try_reserve_exact(commands.len()).map_err(|_| "parity command allocation")?; for c in &commands { if !self.entries.iter().any(|(n, _)| *n == c.name) { return Err("unregistered parity kernel".into()); @@ -59,12 +51,7 @@ impl State<'_> { let mut launch = Ok(()); self.pending.set(true); for c in &mut commands { - let f = self - .entries - .iter() - .find(|(n, _)| *n == c.name) - .ok_or("parity entry")? - .1; + let f = self.entries.iter().find(|(n, _)| *n == c.name).ok_or("parity entry")?.1; if let Err(e) = message(api.launch(f, stream, c)) { launch = Err(e); break; @@ -99,10 +86,7 @@ impl State<'_> { } }; let sync = message( - self.api - .as_ref() - .ok_or("parity ABI closed")? - .sync(self.stream.get().ok_or("parity stream closed")?), + self.api.as_ref().ok_or("parity ABI closed")?.sync(self.stream.get().ok_or("parity stream closed")?), ); let pop = message(guard.finish()); if sync.is_err() || pop.is_err() { @@ -123,21 +107,12 @@ impl State<'_> { std::mem::forget(std::mem::take(self.commands.get_mut())); std::mem::forget(std::mem::take(self.staging.get_mut())); self.context.retain_driver(); - return first( - drain, - Err("Original parity completion/context uncertain".into()), - ); + return first(drain, Err("Original parity completion/context uncertain".into())); } let guard = message(self.context.enter())?; let api = self.api.as_ref().ok_or("parity ABI closed")?; - let unload = self - .module - .take() - .map_or(Ok(()), |m| message(api.unload(m))); - let destroy = self - .stream - .take() - .map_or(Ok(()), |s| message(api.destroy(s))); + let unload = self.module.take().map_or(Ok(()), |m| message(api.unload(m))); + let destroy = self.stream.take().map_or(Ok(()), |s| message(api.destroy(s))); let pop = message(guard.finish()); if unload.is_err() || destroy.is_err() || pop.is_err() { self.uncertain(); diff --git a/crates/cuda-driver/src/native_parity/sealed_ptx_fn.rs b/crates/cuda-driver/src/native_parity/sealed_ptx_fn.rs index 4227661c..531ee23a 100644 --- a/crates/cuda-driver/src/native_parity/sealed_ptx_fn.rs +++ b/crates/cuda-driver/src/native_parity/sealed_ptx_fn.rs @@ -17,10 +17,7 @@ pub(super) fn first(primary: BenchResult, secondary: BenchResult<()>) -> B } } pub fn native_parity_iq_supported(t: i32) -> bool { - matches!( - t, - 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42 | 11 | 12 | 13 | 7 | 8 - ) + matches!(t, 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42 | 11 | 12 | 13 | 7 | 8) } pub fn native_parity_embed_supported(t: i32) -> bool { native_parity_iq_supported(t) || t == 30 @@ -49,9 +46,7 @@ pub(super) fn split(t: i32) -> bool { matches!(t, 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42) } pub(super) fn layout(gu: i32, down: i32) -> BenchResult { - if !matches!(gu, 16 | 17 | 18 | 21 | 22 | 23 | 29 | 42 | 12 | 13 | 8) - || !matches!(down, 20 | 23 | 42 | 7 | 8) - { + if !matches!(gu, 16 | 17 | 18 | 21 | 22 | 23 | 29 | 42 | 12 | 13 | 8) || !matches!(down, 20 | 23 | 42 | 7 | 8) { return Err("Original grouped format unsupported".into()); } let g = native_parity_row_bytes(gu, H); @@ -70,18 +65,11 @@ pub(super) fn layout(gu: i32, down: i32) -> BenchResult { bytes: (off + H * d) as u64, }) } -pub(super) fn command( - name: &'static str, - grid: [u32; 3], - block: [u32; 3], - args: Vec, -) -> BenchResult { +pub(super) fn command(name: &'static str, grid: [u32; 3], block: [u32; 3], args: Vec) -> BenchResult { message(Command::new(name, grid, block, args)) } pub(super) fn address(b: &DeviceBuffer<'_>, offset: usize, bytes: usize) -> BenchResult { - let h = b - .handle - .ok_or_else(|| "parity buffer released".to_string())?; + let h = b.handle.ok_or_else(|| "parity buffer released".to_string())?; message(h.checked_subspan(b.len(), offset, bytes)).map(|h| h.qwen_address()) } pub(super) fn bytes_f32(v: &[f32]) -> BenchResult> { @@ -95,8 +83,7 @@ pub(super) fn bytes_f32(v: &[f32]) -> BenchResult> { } pub(super) fn bytes_i32(v: &[i32]) -> BenchResult> { let mut b = Vec::new(); - b.try_reserve_exact(v.len() * 4) - .map_err(|_| "token allocation")?; + b.try_reserve_exact(v.len() * 4).map_err(|_| "token allocation")?; for x in v { b.extend_from_slice(&x.to_le_bytes()); } @@ -104,12 +91,9 @@ pub(super) fn bytes_i32(v: &[i32]) -> BenchResult> { } pub(super) fn floats(v: Vec) -> BenchResult> { let mut out = Vec::new(); - out.try_reserve_exact(v.len() / 4) - .map_err(|_| "F32 readback allocation")?; + out.try_reserve_exact(v.len() / 4).map_err(|_| "F32 readback allocation")?; for x in v.chunks_exact(4) { - out.push(f32::from_le_bytes( - x.try_into().map_err(|_| "F32 readback extent")?, - )); + out.push(f32::from_le_bytes(x.try_into().map_err(|_| "F32 readback extent")?)); } Ok(out) } diff --git a/crates/cuda-driver/src/native_parity_ffi.rs b/crates/cuda-driver/src/native_parity_ffi.rs index c6d325c5..9edbc0cb 100644 --- a/crates/cuda-driver/src/native_parity_ffi.rs +++ b/crates/cuda-driver/src/native_parity_ffi.rs @@ -6,19 +6,8 @@ type Create = unsafe extern "C" fn(*mut Handle, u32) -> i32; type Call = unsafe extern "C" fn(Handle) -> i32; type Load = unsafe extern "C" fn(*mut Handle, *const c_void) -> i32; type Function = unsafe extern "C" fn(*mut Handle, Handle, *const i8) -> i32; -type Launch = unsafe extern "C" fn( - Handle, - u32, - u32, - u32, - u32, - u32, - u32, - u32, - Handle, - *mut *mut c_void, - *mut *mut c_void, -) -> i32; +type Launch = + unsafe extern "C" fn(Handle, u32, u32, u32, u32, u32, u32, u32, Handle, *mut *mut c_void, *mut *mut c_void) -> i32; #[derive(Clone, Copy)] #[repr(C)] pub(crate) struct Layout { @@ -57,23 +46,10 @@ pub(crate) struct Command { pointers: Vec<*mut c_void>, } impl Command { - pub(crate) fn new( - name: &'static str, - grid: [u32; 3], - block: [u32; 3], - args: Vec, - ) -> Result { + pub(crate) fn new(name: &'static str, grid: [u32; 3], block: [u32; 3], args: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(args.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - name, - grid, - block, - args: args.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(args.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { name, grid, block, args: args.into_boxed_slice(), pointers }) } } struct Library(Handle); @@ -97,32 +73,17 @@ pub(crate) struct Api { launch: Launch, } fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } impl Api { pub(crate) fn load() -> Result { - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } fn symbol(l: &Library, n: &'static CStr) -> Result { let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; - if p.is_null() { - Err(Error::MissingSymbol( - n.to_str().unwrap_or("native parity ABI"), - )) - } else { - Ok(p) - } + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("native parity ABI"))) } else { Ok(p) } } macro_rules! sym { ($n:literal,$ty:ty) => { @@ -143,36 +104,20 @@ impl Api { pub(crate) fn create(&self) -> Result { let mut s = std::ptr::null_mut(); check("cuStreamCreate", unsafe { (self.create)(&mut s, 0) })?; - if s.is_null() { - Err(Error::InvalidDriverValue("cuStreamCreate")) - } else { - Ok(s as usize) - } + if s.is_null() { Err(Error::InvalidDriverValue("cuStreamCreate")) } else { Ok(s as usize) } } pub(crate) fn module(&self, ptx: &[u8]) -> Result { if ptx.last() != Some(&0) { return Err(Error::InvalidDriverValue("native parity PTX NUL")); } let mut m = std::ptr::null_mut(); - check("cuModuleLoadData", unsafe { - (self.load)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; - if m.is_null() { - Err(Error::InvalidDriverValue("cuModuleLoadData")) - } else { - Ok(m as usize) - } + check("cuModuleLoadData", unsafe { (self.load)(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; + if m.is_null() { Err(Error::InvalidDriverValue("cuModuleLoadData")) } else { Ok(m as usize) } } pub(crate) fn function(&self, module: usize, name: &CStr) -> Result { let mut f = std::ptr::null_mut(); - check("cuModuleGetFunction", unsafe { - (self.function)(&mut f, module as Handle, name.as_ptr()) - })?; - if f.is_null() { - Err(Error::InvalidDriverValue("cuModuleGetFunction")) - } else { - Ok(f as usize) - } + check("cuModuleGetFunction", unsafe { (self.function)(&mut f, module as Handle, name.as_ptr()) })?; + if f.is_null() { Err(Error::InvalidDriverValue("cuModuleGetFunction")) } else { Ok(f as usize) } } pub(crate) fn launch(&self, function: usize, stream: usize, c: &mut Command) -> Result<()> { c.pointers.clear(); diff --git a/crates/cuda-driver/src/native_prompt_device.rs b/crates/cuda-driver/src/native_prompt_device.rs index 8dc09e2c..9ce2b07d 100644 --- a/crates/cuda-driver/src/native_prompt_device.rs +++ b/crates/cuda-driver/src/native_prompt_device.rs @@ -1,13 +1,11 @@ //! Original physical prompt R/PLE/GR phases. Every product holds the same //! exclusive arena lease. No per-row payload download or history snapshot bank. //! Runtime alone authenticates source/row/prior and commits canonical state. -use crate::original_prefill_arena::{ - OriginalPleSpan as P, OriginalPromptRows, OriginalPromptSpan as S, -}; +use crate::original_prefill_arena::{OriginalPleSpan as P, OriginalPromptRows, OriginalPromptSpan as S}; use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule}; use crate::{ - Context, DeviceBuffer, Error, GrNativeProfile, NativeBatchWorkspace, PleBf16Mode, - PleClosedWeights, Result, combine, ffi::BufferHandle, + Context, DeviceBuffer, Error, GrNativeProfile, NativeBatchWorkspace, PleBf16Mode, PleClosedWeights, Result, + combine, ffi::BufferHandle, }; use std::ffi::CStr; const RESERVE: usize = 128 << 20; @@ -16,22 +14,15 @@ mod stage_impl; pub use stage_impl::PromptInputStage; const PLE_PTX: &[u8] = concat!(include_str!("ple_prompt_device.ptx"), "\0").as_bytes(); const PLE_SHA: [u8; 32] = [ - 0x41, 0x2e, 0xd1, 0xdc, 0xcd, 0x1f, 0xc6, 0x2c, 0x5c, 0xf6, 0xc7, 0x50, 0xad, 0x8d, 0x2f, 0x45, - 0x20, 0x5f, 0x6d, 0x19, 0xfa, 0xfc, 0x00, 0x23, 0xd6, 0x4a, 0x33, 0xd3, 0x12, 0x95, 0x09, 0x34, -]; -const PLE_ENTRIES: &[&CStr] = &[ - c"ple_rms", - c"ple_gate", - c"ple_broadcast", - c"ple_conv", - c"ple_history", - c"ple_finite", + 0x41, 0x2e, 0xd1, 0xdc, 0xcd, 0x1f, 0xc6, 0x2c, 0x5c, 0xf6, 0xc7, 0x50, 0xad, 0x8d, 0x2f, 0x45, 0x20, 0x5f, 0x6d, + 0x19, 0xfa, 0xfc, 0x00, 0x23, 0xd6, 0x4a, 0x33, 0xd3, 0x12, 0x95, 0x09, 0x34, ]; +const PLE_ENTRIES: &[&CStr] = &[c"ple_rms", c"ple_gate", c"ple_broadcast", c"ple_conv", c"ple_history", c"ple_finite"]; const PACK_PTX: &[u8] = concat!(include_str!("ple_bf16_pack.ptx"), "\0").as_bytes(); const GR_PTX: &[u8] = concat!(include_str!("gr_prompt_device.ptx"), "\0").as_bytes(); const GR_SHA: [u8; 32] = [ - 0x39, 0xc4, 0xea, 0xcc, 0x21, 0x1f, 0xa4, 0x5f, 0xe3, 0x68, 0xee, 0x50, 0x2d, 0x3d, 0x3f, 0xf2, - 0x12, 0x41, 0xe6, 0xfe, 0x24, 0xd5, 0xd1, 0x21, 0x1c, 0x6e, 0x18, 0xef, 0x0d, 0x37, 0x28, 0x70, + 0x39, 0xc4, 0xea, 0xcc, 0x21, 0x1f, 0xa4, 0x5f, 0xe3, 0x68, 0xee, 0x50, 0x2d, 0x3d, 0x3f, 0xf2, 0x12, 0x41, 0xe6, + 0xfe, 0x24, 0xd5, 0xd1, 0x21, 0x1c, 0x6e, 0x18, 0xef, 0x0d, 0x37, 0x28, 0x70, ]; const GR_ENTRIES: &[&CStr] = &[ c"gr_norm_rs_kernel", @@ -111,14 +102,14 @@ use crate::prefill_stage::fused_scans; mod impl_originaldeviceblock; mod impl_originalplehistory; #[allow(unused_imports)] -use impl_originalplehistory::kernel; -#[allow(unused_imports)] -use impl_originalplehistory::scan_ple; -#[allow(unused_imports)] -use impl_originalplehistory::scan_gr; -#[allow(unused_imports)] use impl_originalplehistory::bytes; #[allow(unused_imports)] use impl_originalplehistory::encode; -mod impl_originalpromptdevice; +#[allow(unused_imports)] +use impl_originalplehistory::kernel; +#[allow(unused_imports)] +use impl_originalplehistory::scan_gr; +#[allow(unused_imports)] +use impl_originalplehistory::scan_ple; mod impl_drop_for_originalpromptdevice; +mod impl_originalpromptdevice; diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs b/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs index c49a7c51..848d8871 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originaldeviceblock.rs @@ -28,13 +28,8 @@ impl<'ctx> Context<'ctx> { if self.is_poisoned() { return Err(Error::ContextPoisoned); } - let required = 368640usize - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if self - .allocated_bytes() - .checked_add(required) - .is_none_or(|x| x > self.budget_bytes()) + let required = 368640usize.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if self.allocated_bytes().checked_add(required).is_none_or(|x| x > self.budget_bytes()) || self.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -45,11 +40,7 @@ impl<'ctx> Context<'ctx> { let _ = buffer.release(); return Err(e); } - Ok(OriginalPleHistory { - context: self, - buffer: Some(buffer), - failed: false, - }) + Ok(OriginalPleHistory { context: self, buffer: Some(buffer), failed: false }) } } impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { @@ -104,11 +95,7 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { self.lease.drain()?; let context = self.lease.context(); let (handle, span_bytes) = self.lease.common_span(S::R)?; - let row = handle.checked_subspan( - span_bytes, - index.checked_mul(40960).ok_or(Error::InvalidSize)?, - 40960, - )?; + let row = handle.checked_subspan(span_bytes, index.checked_mul(40960).ok_or(Error::InvalidSize)?, 40960)?; let mut raw = bytes(40960)?; let guard = match context.enter() { Ok(guard) => guard, @@ -127,20 +114,12 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { if drain.is_err() || restore.is_err() { std::mem::forget(raw); context.retain_driver(); - return combine(combine(operation, drain), restore) - .map(|()| unreachable!("failed final row drain")); + return combine(combine(operation, drain), restore).map(|()| unreachable!("failed final row drain")); } combine(combine(operation, drain), restore)?; let mut values = Vec::new(); - values - .try_reserve_exact(10240) - .map_err(|_| Error::HostAllocation)?; - values.extend( - raw.as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(10240).map_err(|_| Error::HostAllocation)?; + values.extend(raw.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); if values.iter().any(|value| !value.is_finite()) { return Err(Error::NonFiniteMmqOutput("Original final prompt row")); } @@ -156,11 +135,7 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { self.lease.drain()?; let context = self.lease.context(); let (handle, span_bytes) = self.lease.common_span(S::R)?; - let row = handle.checked_subspan( - span_bytes, - index.checked_mul(40960).ok_or(Error::InvalidSize)?, - 40960, - )?; + let row = handle.checked_subspan(span_bytes, index.checked_mul(40960).ok_or(Error::InvalidSize)?, 40960)?; let mut raw = bytes(40960)?; let guard = match context.enter() { Ok(guard) => guard, @@ -179,20 +154,12 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> { if drain.is_err() || restore.is_err() { std::mem::forget(raw); context.retain_driver(); - return combine(combine(operation, drain), restore) - .map(|()| unreachable!("failed final row drain")); + return combine(combine(operation, drain), restore).map(|()| unreachable!("failed final row drain")); } combine(combine(operation, drain), restore)?; let mut values = Vec::new(); - values - .try_reserve_exact(10240) - .map_err(|_| Error::HostAllocation)?; - values.extend( - raw.as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(10240).map_err(|_| Error::HostAllocation)?; + values.extend(raw.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); if values.iter().any(|value| !value.is_finite()) { return Err(Error::NonFiniteMmqOutput("Original final prompt row")); } diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalplehistory.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalplehistory.rs index 7901303c..46f11e32 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalplehistory.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalplehistory.rs @@ -25,14 +25,8 @@ impl OriginalPleHistory<'_> { let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; let raw = b.copy_to_owned(368640)?; let mut out = Vec::new(); - out.try_reserve_exact(92160) - .map_err(|_| Error::HostAllocation)?; - out.extend( - raw.as_chunks::<4>() - .0 - .iter() - .map(|x| f32::from_le_bytes(*x)), - ); + out.try_reserve_exact(92160).map_err(|_| Error::HostAllocation)?; + out.extend(raw.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); if out.iter().any(|x| !x.is_finite()) { return Err(Error::NonFiniteMmqOutput("PLE history")); } @@ -65,58 +59,26 @@ impl Drop for OriginalPleHistory<'_> { } } pub(super) fn kernel(v: &mut Vec, family: u8, index: usize, grid: usize, block: u32, args: Vec) { - v.push(C::Kernel { - family, - index, - grid: grid as u32, - block, - args: KernelArguments::new(args), - }) + v.push(C::Kernel { family, index, grid: grid as u32, block, args: KernelArguments::new(args) }) } -pub(super) fn scan_ple( - v: &mut Vec, - data: BufferHandle, - status: BufferHandle, - width: usize, - t: usize, - role: i32, -) { +pub(super) fn scan_ple(v: &mut Vec, data: BufferHandle, status: BufferHandle, width: usize, t: usize, role: i32) { kernel( v, 1, 5, (width * t).div_ceil(256), 256, - vec![ - A::Address(data), - A::Address(status), - A::I32(width as i32), - A::I32(t as i32), - A::I32(role), - ], + vec![A::Address(data), A::Address(status), A::I32(width as i32), A::I32(t as i32), A::I32(role)], ) } -pub(super) fn scan_gr( - v: &mut Vec, - data: BufferHandle, - status: BufferHandle, - width: usize, - t: usize, - role: u32, -) { +pub(super) fn scan_gr(v: &mut Vec, data: BufferHandle, status: BufferHandle, width: usize, t: usize, role: u32) { kernel( v, 2, 4, (width * t).div_ceil(256), 256, - vec![ - A::Address(data), - A::Address(status), - A::I64(width as i64), - A::I64(t as i64), - A::U32(role), - ], + vec![A::Address(data), A::Address(status), A::I64(width as i64), A::I64(t as i64), A::U32(role)], ) } pub(super) fn bytes(n: usize) -> Result> { diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs index bca7d624..fa4cd453 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { pub fn device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -36,10 +34,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return Err(Error::ContextPoisoned); } let required = count.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|x| x > context.budget_bytes()) + if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -72,10 +67,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { owner.pack = Some(KernelModule::load(PACK_PTX, &[c"ple_pack"])?); owner.ple = Some(KernelModule::load(PLE_PTX, PLE_ENTRIES)?); owner.gr = Some(KernelModule::load(GR_PTX, GR_ENTRIES)?); - owner.stage = Some(KernelModule::load( - crate::prefill_stage::PTX, - crate::prefill_stage::ENTRIES, - )?); + owner.stage = Some(KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)?); Ok(()) })(); let pop = guard.finish(); @@ -152,14 +144,8 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } } for enabled_roles in [ - ( - self.profile == GrNativeProfile::HighAndLow, - [S::XLow, S::LoLow], - ), - ( - self.profile == GrNativeProfile::HighAndLow, - [S::MixedLow, S::MixedLow], - ), + (self.profile == GrNativeProfile::HighAndLow, [S::XLow, S::LoLow]), + (self.profile == GrNativeProfile::HighAndLow, [S::MixedLow, S::MixedLow]), ] { if enabled_roles.0 { for role in enabled_roles.1 { @@ -175,11 +161,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } pub(in super::super) fn span(rows: &OriginalPromptRows<'_, '_, '_>, role: S, width: usize) -> Result { let (h, n) = rows.common_span(role)?; - h.checked_subspan( - n, - 0, - rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?, - ) + h.checked_subspan(n, 0, rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?) } pub(in super::super) fn weight( &self, diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs index 8e886454..7d09aa3b 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { /// `initialize` over the rows in place: each row's 10240 residual-stream values and 2560 PLE embedding /// values, in row order. The same finite refusal and the same device bytes, staged in one pass per buffer @@ -58,12 +56,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return Err(err); } }; - let op = self - .context - .driver - .api - .copy_from(rh, &s) - .and_then(|()| self.context.driver.api.copy_from(eh, &e)); + let op = self.context.driver.api.copy_from(rh, &s).and_then(|()| self.context.driver.api.copy_from(eh, &e)); let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); if op.is_err() || sync.is_err() || pop.is_err() { @@ -123,13 +116,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { let started = std::time::Instant::now(); let mut label = "gemm"; op = match cmd { - C::Kernel { - family, - index, - grid, - block, - args, - } => { + C::Kernel { family, index, grid, block, args } => { let module = match family { 0 => self.pack.as_ref(), 1 => self.ple.as_ref(), @@ -147,16 +134,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } module.launch(*index, *grid, *block, blas.stream(), args) } - C::Gemm { - input, - weight, - output, - t, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta), + C::Gemm { input, weight, output, t, n, k, alpha, beta } => { + blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, alpha, beta) + } }; if timed && op.is_ok() { op = blas.synchronize(); diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs index bf22a617..322c487c 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_3.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { pub fn apply_ple<'arena, 'loan>( &mut self, @@ -30,33 +28,20 @@ impl<'ctx> OriginalPromptDevice<'ctx> { let value = self.weight(lease, workspace, weights.value, 13107200, 2)?; let mut aux = [key; 4]; for (i, w) in weights.aux.iter().enumerate() { - aux[i] = self.weight( - lease, - workspace, - w, - if i == 3 { 81920 } else { 40960 }, - if i == 3 { 2 } else { 4 }, - )?; + aux[i] = + self.weight(lease, workspace, w, if i == 3 { 81920 } else { 40960 }, if i == 3 { 2 } else { 4 })?; } let sb = lease.ple_subbatch_capacity()?; let total = lease.rows(); for first in (0..total).step_by(sb) { let t = sb.min(total - first); - let rh = Self::span(lease, S::R, 40960)?.checked_subspan( - total * 40960, - first * 40960, - t * 40960, - )?; - let eh = Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan( - total * 10240, - first * 10240, - t * 10240, - )?; + let rh = Self::span(lease, S::R, 40960)?.checked_subspan(total * 40960, first * 40960, t * 40960)?; + let eh = + Self::span(lease, S::PleEmbedding, 10240)?.checked_subspan(total * 10240, first * 10240, t * 10240)?; let get = |role: P| -> Result { let (h, n) = lease.ple_span(role, t)?; workspace.reject_alias(h, n)?; - if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) - { + if h.overlaps(n, hist, 368640) || h.overlaps(n, self.status()?, self.capacity * 40) { return Err(Error::OutputAliasesInput); } for (w, wn) in [ @@ -79,28 +64,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> { let val = get(P::Value)?; let gate = get(P::Gate)?; let packed = get(P::PackedEmbedding)?; - let low = if self.mode == PleBf16Mode::HighAndLow { - Some(get(P::PackedEmbeddingLow)?) - } else { - None - }; - for (h, n) in [ - (rh, t * 40960), - (eh, t * 10240), - (self.status()?, self.capacity * 40), - ] { + let low = if self.mode == PleBf16Mode::HighAndLow { Some(get(P::PackedEmbeddingLow)?) } else { None }; + for (h, n) in [(rh, t * 40960), (eh, t * 10240), (self.status()?, self.capacity * 40)] { if h.overlaps(n, hist, 368640) { return Err(Error::OutputAliasesInput); } } - for (w, n) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { + for (w, n) in + [(key, 52428800), (value, 13107200), (aux[0], 40960), (aux[1], 40960), (aux[2], 40960), (aux[3], 81920)] + { if w.overlaps(n, hist, 368640) { return Err(Error::OutputAliasesInput); } @@ -124,48 +96,16 @@ impl<'ctx> OriginalPromptDevice<'ctx> { ], ); for (out, n, w, role) in [(kh, 10240, key, 0), (val, 2560, value, 1)] { - v.push(C::Gemm { - input: packed, - weight: w, - output: out, - t: t as i32, - n, - k: 2560, - alpha: 1., - beta: 0., - }); + v.push(C::Gemm { input: packed, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 0. }); if let Some(l) = low { - v.push(C::Gemm { - input: l, - weight: w, - output: out, - t: t as i32, - n, - k: 2560, - alpha: 1., - beta: 1., - }) + v.push(C::Gemm { input: l, weight: w, output: out, t: t as i32, n, k: 2560, alpha: 1., beta: 1. }) } scan_ple(&mut v, out, flags, n as usize, t, role); } // Literal native_ple_postops_batch reuses Key and Qn in place. - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)], - ); + kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(kh), A::Address(aux[0]), A::Address(kh)]); scan_ple(&mut v, kh, flags, 10240, t, 2); - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)], - ); + kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(rh), A::Address(aux[1]), A::Address(qn)]); scan_ple(&mut v, qn, flags, 10240, t, 3); kernel( &mut v, @@ -173,12 +113,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 1, t * 4, 512, - vec![ - A::Address(kh), - A::Address(qn), - A::Address(gate), - A::F32(1. / 2560.0f32.sqrt()), - ], + vec![A::Address(kh), A::Address(qn), A::Address(gate), A::F32(1. / 2560.0f32.sqrt())], ); scan_ple(&mut v, gate, flags, 4, t, 4); kernel( @@ -187,22 +122,10 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 2, t * 40, 256, - vec![ - A::Address(val), - A::Address(gate), - A::Address(gated), - A::I32(t as i32), - ], + vec![A::Address(val), A::Address(gate), A::Address(gated), A::I32(t as i32)], ); scan_ple(&mut v, gated, flags, 10240, t, 5); - kernel( - &mut v, - 1, - 0, - t * 4, - 1024, - vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)], - ); + kernel(&mut v, 1, 0, t * 4, 1024, vec![A::Address(gated), A::Address(aux[2]), A::Address(qn)]); scan_ple(&mut v, qn, flags, 10240, t, 6); kernel( &mut v, @@ -220,14 +143,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { A::I32(t as i32), ], ); - kernel( - &mut v, - 1, - 4, - 40, - 256, - vec![A::Address(hist), A::Address(qn), A::I32(t as i32)], - ); + kernel(&mut v, 1, 4, 40, 256, vec![A::Address(hist), A::Address(qn), A::I32(t as i32)]); scan_ple(&mut v, hist, flags, 92160, 1, 8); scan_ple(&mut v, rh, flags, 10240, t, 9); if let Err(e) = self.run( diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs index dac6ead7..646c89d3 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_4.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { pub fn read_gr<'arena, 'loan>( &mut self, @@ -22,8 +20,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { weights: [&DeviceBuffer<'_>; 4], epsilon: f32, ) -> Result> { - if !std::ptr::eq(normed.gamma, weights[0]) || normed.epsilon.to_bits() != epsilon.to_bits() - { + if !std::ptr::eq(normed.gamma, weights[0]) || normed.epsilon.to_bits() != epsilon.to_bits() { return Err(Error::InvalidQwenShape); } self.read_gr_impl(normed.residual, workspace, weights, epsilon, true) diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs index 31bbe2dd..af1d73df 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { pub(in super::super) fn read_gr_impl<'arena, 'loan>( &mut self, @@ -38,11 +36,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { h[i] = Self::span(lease, r, n)?; } if self.profile == GrNativeProfile::HighAndLow { - for (i, r, n) in [ - (3, S::XLow, 20480), - (6, S::LoLow, 640), - (10, S::MixedLow, 5120), - ] { + for (i, r, n) in [(3, S::XLow, 20480), (6, S::LoLow, 640), (10, S::MixedLow, 5120)] { h[i] = Self::span(lease, r, n)?; } } @@ -51,11 +45,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; } let low = |i| { - if self.profile == GrNativeProfile::HighAndLow { - A::Address(h[i]) - } else { - A::NullAddress - } + if self.profile == GrNativeProfile::HighAndLow { A::Address(h[i]) } else { A::NullAddress } }; let flags = self.status()?; let mut v = Vec::new(); @@ -106,37 +96,13 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 5, (t * 10240).div_ceil(256), 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(flags), - A::I64(t as i64), - ], + vec![A::Address(h[0]), A::Address(h[1]), A::Address(w[0]), A::Address(flags), A::I64(t as i64)], ); } let gemm = |v: &mut Vec, input, lo, weight, out, n, k| { - v.push(C::Gemm { - input: h[input], - weight, - output: h[out], - t: t as i32, - n, - k, - alpha: 1., - beta: 0., - }); + v.push(C::Gemm { input: h[input], weight, output: h[out], t: t as i32, n, k, alpha: 1., beta: 0. }); if self.profile == GrNativeProfile::HighAndLow { - v.push(C::Gemm { - input: h[lo], - weight, - output: h[out], - t: t as i32, - n, - k, - alpha: 1., - beta: 1., - }) + v.push(C::Gemm { input: h[lo], weight, output: h[out], t: t as i32, n, k, alpha: 1., beta: 1. }) } }; gemm(&mut v, 2, 3, w[1], 4, 320, 10240); @@ -147,21 +113,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 1, (t * 320).div_ceil(256), 256, - vec![ - A::Address(h[4]), - A::Address(h[5]), - low(6), - A::I64((t * 320) as i64), - ], - ); - kernel( - &mut v, - 2, - 6, - (t * 320).div_ceil(256), - 256, - vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)], + vec![A::Address(h[4]), A::Address(h[5]), low(6), A::I64((t * 320) as i64)], ); + kernel(&mut v, 2, 6, (t * 320).div_ceil(256), 256, vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)]); gemm(&mut v, 5, 6, w[2], 7, 10240, 320); if !fused { scan_gr(&mut v, h[7], flags, 10240, t, 3); @@ -244,8 +198,6 @@ impl<'ctx> OriginalPromptDevice<'ctx> { "GR native candidate", ], )?; - Ok(OriginalDeviceGrRead { - lease: residual.lease, - }) + Ok(OriginalDeviceGrRead { lease: residual.lease }) } } diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs index e1a52482..5c8e1b97 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_6.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { /// A completed real attention/MoE producer moved the read lease into Block. /// Recheck its full actual Block before the Original ascending R write. @@ -24,9 +22,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { // Prewrite full Block scan/drain rejects numerical errors before R is // modified. No host floats are treated as a device-completion witness. let mut check = Vec::new(); - check - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; + check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; scan_gr(&mut check, b, flags, 2560, t, 7); self.run( lease, @@ -35,16 +31,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { t, 8, &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native block", - ], + &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native block"], )?; self.profile_tag = "inject"; let mut v = Vec::new(); @@ -56,14 +43,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 6, (t * 10240).div_ceil(256), 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::I64(t as i64), - A::Address(flags), - ], + vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64), A::Address(flags)], ); } else { kernel( @@ -72,13 +52,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 3, (t * 10240).div_ceil(256), 256, - vec![ - A::Address(r), - A::Address(b), - A::Address(inj), - A::I64(4), - A::I64(t as i64), - ], + vec![A::Address(r), A::Address(b), A::Address(inj), A::I64(4), A::I64(t as i64)], ); scan_gr(&mut v, r, flags, 10240, t, 7); } @@ -89,20 +63,9 @@ impl<'ctx> OriginalPromptDevice<'ctx> { t, 8, &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native candidate", - ], + &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"], )?; - Ok(OriginalDeviceResidual { - lease: block.read.lease, - }) + Ok(OriginalDeviceResidual { lease: block.read.lease }) } pub fn inject_gr_fused<'weight, 'arena, 'loan>( &mut self, @@ -131,9 +94,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { A::NullAddress }; let mut check = Vec::new(); - check - .try_reserve_exact(1) - .map_err(|_| Error::HostAllocation)?; + check.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; scan_gr(&mut check, b, flags, 2560, t, 7); self.run( lease, @@ -142,16 +103,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { t, 8, &[7], - &[ - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native block", - ], + &["unused", "unused", "unused", "unused", "unused", "unused", "unused", "GR native block"], )?; self.profile_tag = "injectf"; let mut v = Vec::new(); @@ -203,13 +155,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { 5, (t * 10240).div_ceil(256), 256, - vec![ - A::Address(r), - A::Address(rs), - A::Address(w), - A::Address(flags), - A::I64(t as i64), - ], + vec![A::Address(r), A::Address(rs), A::Address(w), A::Address(flags), A::I64(t as i64)], ); } self.run( @@ -219,21 +165,10 @@ impl<'ctx> OriginalPromptDevice<'ctx> { t, 8, &[7, 0], - &[ - "GR native next norm", - "unused", - "unused", - "unused", - "unused", - "unused", - "unused", - "GR native candidate", - ], + &["GR native next norm", "unused", "unused", "unused", "unused", "unused", "unused", "GR native candidate"], )?; Ok(OriginalDeviceNormedResidual { - residual: OriginalDeviceResidual { - lease: block.read.lease, - }, + residual: OriginalDeviceResidual { lease: block.read.lease }, gamma, epsilon, }) diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs index b92541b6..428013b6 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_7.rs @@ -3,21 +3,11 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalPromptDevice<'ctx> { pub(in super::super) fn close_inner(&mut self) -> Result<()> { self.failed = true; let mut result = Ok(()); - for m in [ - self.pack.take(), - self.ple.take(), - self.gr.take(), - self.stage.take(), - ] - .into_iter() - .flatten() - { + for m in [self.pack.take(), self.ple.take(), self.gr.take(), self.stage.take()].into_iter().flatten() { let r = if self.context.is_poisoned() { std::mem::forget(m); Err(Error::ContextPoisoned) @@ -36,10 +26,7 @@ impl<'ctx> OriginalPromptDevice<'ctx> { } result = combine(result, r); } - for b in [self.status.take(), self.stage_scratch.take()] - .into_iter() - .flatten() - { + for b in [self.status.take(), self.stage_scratch.take()].into_iter().flatten() { let r = if self.context.is_poisoned() { std::mem::forget(b); Err(Error::ContextPoisoned) diff --git a/crates/cuda-driver/src/native_prompt_device_stage.rs b/crates/cuda-driver/src/native_prompt_device_stage.rs index 6382be21..2871fa05 100644 --- a/crates/cuda-driver/src/native_prompt_device_stage.rs +++ b/crates/cuda-driver/src/native_prompt_device_stage.rs @@ -52,18 +52,13 @@ impl<'ctx> OriginalPromptDevice<'ctx> { { return Err(Error::InvalidQwenShape); } - if !std::ptr::eq(input.ple_cache.context, self.context) - || !std::ptr::eq(input.ple_books.context, self.context) + if !std::ptr::eq(input.ple_cache.context, self.context) || !std::ptr::eq(input.ple_books.context, self.context) { return Err(Error::ContextMismatch); } let rh = Self::span(&lease, S::R, 40960)?; let eh = Self::span(&lease, S::PleEmbedding, 10240)?; - let bh = Self::span(&lease, S::Block, 10240)?.checked_subspan( - t * 10240, - 0, - unique * 10240, - )?; + let bh = Self::span(&lease, S::Block, 10240)?.checked_subspan(t * 10240, 0, unique * 10240)?; let cache_h = input.ple_cache.handle.ok_or(Error::ContextPoisoned)?; let books_h = input.ple_books.handle.ok_or(Error::ContextPoisoned)?; cache_h.validate_projection_extent(64 << 20, 1)?; @@ -87,22 +82,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> { workspace.reject_alias(sh, total)?; let slots_h = sh.checked_subspan(total, 0, t * 64)?; let index_h = sh.checked_subspan(total, slot_bytes, t * 4)?; - let updates_h = if misses > 0 { - Some(sh.checked_subspan(total, slot_bytes + index_bytes, misses * 56)?) - } else { - None - }; + let updates_h = + if misses > 0 { Some(sh.checked_subspan(total, slot_bytes + index_bytes, misses * 56)?) } else { None }; let flags = self.status()?; let mut slot_raw = bytes(t * 64)?; for (x, b) in input.ple_slots.iter().zip(slot_raw.as_chunks_mut::<4>().0) { b.copy_from_slice(&x.to_le_bytes()) } let mut index_raw = bytes(t * 4)?; - for (x, b) in input - .embedding_index - .iter() - .zip(index_raw.as_chunks_mut::<4>().0) - { + for (x, b) in input.embedding_index.iter().zip(index_raw.as_chunks_mut::<4>().0) { b.copy_from_slice(&x.to_le_bytes()) } let guard = match self.context.enter() { diff --git a/crates/cuda-driver/src/nvml.rs b/crates/cuda-driver/src/nvml.rs index 619e3b35..6e95369e 100644 --- a/crates/cuda-driver/src/nvml.rs +++ b/crates/cuda-driver/src/nvml.rs @@ -109,17 +109,23 @@ mod imp { unsafe { let init: Init = std::mem::transmute(symbol(library, c"nvmlInit_v2")?); let get_handle: GetHandle = std::mem::transmute(symbol(library, c"nvmlDeviceGetHandleByIndex_v2")?); - let utilization: GetUtilization = std::mem::transmute(symbol(library, c"nvmlDeviceGetUtilizationRates")?); + let utilization: GetUtilization = + std::mem::transmute(symbol(library, c"nvmlDeviceGetUtilizationRates")?); let memory: GetMemory = std::mem::transmute(symbol(library, c"nvmlDeviceGetMemoryInfo")?); - let power = symbol(library, c"nvmlDeviceGetPowerUsage").map(|p| std::mem::transmute::<*mut c_void, GetPower>(p)); - let clock = symbol(library, c"nvmlDeviceGetClockInfo").map(|p| std::mem::transmute::<*mut c_void, GetClock>(p)); - let temperature = symbol(library, c"nvmlDeviceGetTemperature").map(|p| std::mem::transmute::<*mut c_void, GetTemperature>(p)); - let pcie = symbol(library, c"nvmlDeviceGetPcieThroughput").map(|p| std::mem::transmute::<*mut c_void, GetPcie>(p)); + let power = symbol(library, c"nvmlDeviceGetPowerUsage") + .map(|p| std::mem::transmute::<*mut c_void, GetPower>(p)); + let clock = symbol(library, c"nvmlDeviceGetClockInfo") + .map(|p| std::mem::transmute::<*mut c_void, GetClock>(p)); + let temperature = symbol(library, c"nvmlDeviceGetTemperature") + .map(|p| std::mem::transmute::<*mut c_void, GetTemperature>(p)); + let pcie = symbol(library, c"nvmlDeviceGetPcieThroughput") + .map(|p| std::mem::transmute::<*mut c_void, GetPcie>(p)); // Renamed from ...ClocksThrottleReasons to ...ClocksEventReasons in R535; either answers. let throttle = symbol(library, c"nvmlDeviceGetCurrentClocksEventReasons") .or_else(|| symbol(library, c"nvmlDeviceGetCurrentClocksThrottleReasons")) .map(|p| std::mem::transmute::<*mut c_void, GetThrottle>(p)); - let get_name = symbol(library, c"nvmlDeviceGetName").map(|p| std::mem::transmute::<*mut c_void, GetName>(p)); + let get_name = + symbol(library, c"nvmlDeviceGetName").map(|p| std::mem::transmute::<*mut c_void, GetName>(p)); if init() != 0 { return None; } @@ -135,7 +141,19 @@ mod imp { .then(|| std::ffi::CStr::from_ptr(buffer.as_ptr()).to_string_lossy().into_owned()) .filter(|name| !name.is_empty()) }); - Some(Handle { library, device, index, utilization, memory, power, clock, temperature, pcie, throttle, name }) + Some(Handle { + library, + device, + index, + utilization, + memory, + power, + clock, + temperature, + pcie, + throttle, + name, + }) } })(); if built.is_none() { @@ -151,7 +169,9 @@ mod imp { let mut utilization = Utilization::default(); let mut memory = MemoryInfo::default(); // SAFETY: valid device handle, correctly sized out-parameters. - let (ok_util, ok_mem) = unsafe { ((self.utilization)(self.device, &mut utilization) == 0, (self.memory)(self.device, &mut memory) == 0) }; + let (ok_util, ok_mem) = unsafe { + ((self.utilization)(self.device, &mut utilization) == 0, (self.memory)(self.device, &mut memory) == 0) + }; if !ok_util && !ok_mem { return None; } diff --git a/crates/cuda-driver/src/original_conversation_state.rs b/crates/cuda-driver/src/original_conversation_state.rs index 41c525bc..cd19b588 100644 --- a/crates/cuda-driver/src/original_conversation_state.rs +++ b/crates/cuda-driver/src/original_conversation_state.rs @@ -53,9 +53,16 @@ pub enum OriginalRegion { Gdn, /// The PLE history window. PleHist, - Idx { owned: usize, kind: OriginalIdxKind }, + Idx { + owned: usize, + kind: OriginalIdxKind, + }, /// `resident` selects the VRAM slots over the authoritative copy. - Kv { layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool }, + Kv { + layer: OriginalKvLayer, + pool: OriginalKvPool, + resident: bool, + }, } /// The model geometry fields the session layout knows. `ssm_k_heads` is not @@ -127,8 +134,22 @@ pub struct OriginalSessionFacts { /// Authoritative mapped-host K/V and the drafter ring: memory the session /// arena does not contain. Implemented by the owner of those allocations. pub trait OriginalHostKv { - fn read(&mut self, layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool, offset: usize, dst: &mut [u8]) -> Result<()>; - fn write(&mut self, layer: OriginalKvLayer, pool: OriginalKvPool, resident: bool, offset: usize, src: &[u8]) -> Result<()>; + fn read( + &mut self, + layer: OriginalKvLayer, + pool: OriginalKvPool, + resident: bool, + offset: usize, + dst: &mut [u8], + ) -> Result<()>; + fn write( + &mut self, + layer: OriginalKvLayer, + pool: OriginalKvPool, + resident: bool, + offset: usize, + src: &[u8], + ) -> Result<()>; /// `kv_stream_reset` on a streamed layer's device map. fn reset_stream_map(&mut self, owned: usize) -> Result<()>; /// `kv_ring_restore` of host blocks `[begin, end)` into a ring's slots. diff --git a/crates/cuda-driver/src/original_conversation_state/tests.rs b/crates/cuda-driver/src/original_conversation_state/tests.rs index 513ad14e..c9d8d357 100644 --- a/crates/cuda-driver/src/original_conversation_state/tests.rs +++ b/crates/cuda-driver/src/original_conversation_state/tests.rs @@ -22,8 +22,7 @@ fn policy() -> OriginalSessionKvPolicy { // whole = [117669888, 368640, 1536, 512, 4]). #[test] fn running_state_regions_match_the_original_conversation_sizes() { - let layout = - OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); let facts = layout.conversation_facts(); assert_eq!((facts.qsa_alloc, facts.gdn_alloc), (12, 36)); assert_eq!(facts.gdn_state_bytes, 117_669_888); @@ -40,13 +39,14 @@ fn running_state_regions_match_the_original_conversation_sizes() { #[test] fn kv_regions_follow_the_state_format_and_streaming_mode() { - let layout = - OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); + let layout = OriginalSessionLayout::new(OriginalSessionGeometry::original(), 4096, 10, 0, -1, policy()).unwrap(); let kv = |pool, resident| { layout.conversation_span(OriginalRegion::Kv { layer: OriginalKvLayer::Owned(0), pool, resident }) }; // INT8, resident: K/V codes and both scale pools are arena spans. - for pool in [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::KScale, OriginalKvPool::VScale, OriginalKvPool::Pooled] { + for pool in + [OriginalKvPool::K, OriginalKvPool::V, OriginalKvPool::KScale, OriginalKvPool::VScale, OriginalKvPool::Pooled] + { assert!(kv(pool, false).unwrap().is_some(), "{pool:?}"); } // The drafter's K/V is never in the session arena. diff --git a/crates/cuda-driver/src/original_expert_cache.rs b/crates/cuda-driver/src/original_expert_cache.rs index a6e06cc2..98c96e27 100644 --- a/crates/cuda-driver/src/original_expert_cache.rs +++ b/crates/cuda-driver/src/original_expert_cache.rs @@ -17,10 +17,7 @@ enum State { NeedsRefill, } enum RetainedFill<'ctx> { - Mapped { - bank: Rc>, - spans: [ResidentExpertBankSpan; 3], - }, + Mapped { bank: Rc>, spans: [ResidentExpertBankSpan; 3] }, File(crate::OriginalFileExpertBlob<'ctx>), } /// Immutable residency of the unlent prefix, borrowed alongside the actual @@ -56,6 +53,6 @@ pub struct OriginalExpertCache<'ctx> { swaps: u64, } +mod impl_drop_for_originalexpertcache; mod impl_originalcacheprefix; mod impl_originalexpertcache; -mod impl_drop_for_originalexpertcache; diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalcacheprefix.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalcacheprefix.rs index 2d9aff16..c723ab4e 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalcacheprefix.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalcacheprefix.rs @@ -4,11 +4,7 @@ use super::*; impl OriginalCachePrefix<'_> { - pub(crate) fn completed_slot_span( - &self, - layer: usize, - expert: usize, - ) -> Result> { + pub(crate) fn completed_slot_span(&self, layer: usize, expert: usize) -> Result> { let slot = self.table.slot_of(layer, expert); if slot < 0 { return Ok(None); @@ -29,10 +25,7 @@ impl<'ctx> Context<'ctx> { experts: usize, blob_bytes: usize, ) -> Result> { - OriginalExpertCache::open( - self, - OriginalExpertSlots::uniform(slots, layers, experts, blob_bytes)?, - ) + OriginalExpertCache::open(self, OriginalExpertSlots::uniform(slots, layers, experts, blob_bytes)?) } pub fn original_expert_cache_sized( &'ctx self, @@ -40,9 +33,6 @@ impl<'ctx> Context<'ctx> { layers: usize, experts: usize, ) -> Result> { - OriginalExpertCache::open( - self, - OriginalExpertSlots::sized(slot_bytes, layers, experts)?, - ) + OriginalExpertCache::open(self, OriginalExpertSlots::sized(slot_bytes, layers, experts)?) } } diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs index 45e35014..45e0e423 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalExpertCache<'ctx> { pub(crate) fn validate_file_source_context(&self, c: &Context<'_>) -> Result<()> { self.ensure_live()?; @@ -40,21 +38,14 @@ impl<'ctx> OriginalExpertCache<'ctx> { let bytes = table.bytes(); // Literal Original free-VRAM check before the one contiguous cudaMalloc. if context.memory_info()?.0 < bytes - || context - .allocated_bytes() - .checked_add(bytes) - .is_none_or(|n| n > context.budget_bytes()) + || context.allocated_bytes().checked_add(bytes).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::BudgetExceeded); } let mut states = Vec::new(); let mut owners = Vec::new(); - states - .try_reserve_exact(table.slots()) - .map_err(|_| Error::HostAllocation)?; - owners - .try_reserve_exact(table.slots()) - .map_err(|_| Error::HostAllocation)?; + states.try_reserve_exact(table.slots()).map_err(|_| Error::HostAllocation)?; + owners.try_reserve_exact(table.slots()).map_err(|_| Error::HostAllocation)?; states.resize(table.slots(), State::Empty); owners.resize(table.slots(), None); let mut cache = Self { @@ -80,19 +71,10 @@ impl<'ctx> OriginalExpertCache<'ctx> { let guard = context.enter()?; let operation = (|| { cache.api = Some(api::AsyncApi::load()?); - let handle = cache - .buffer - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; + let handle = cache.buffer.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; handle.validate_extent(bytes)?; cache.attempted = true; - cache - .api - .as_ref() - .ok_or(Error::ContextPoisoned)? - .zero(handle.qwen_address(), bytes)?; + cache.api.as_ref().ok_or(Error::ContextPoisoned)?.zero(handle.qwen_address(), bytes)?; Ok(()) })(); let result = combine(operation, guard.finish()); @@ -128,10 +110,10 @@ impl<'ctx> OriginalExpertCache<'ctx> { let result = (|| { let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.zero( - b.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), - b.bytes, - )?; + self.api + .as_ref() + .ok_or(Error::ContextPoisoned)? + .zero(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), b.bytes)?; self.context.driver.api.synchronize()?; self.attempted = false; Ok(()) diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs index 58f0eb8c..1659f938 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalExpertCache<'ctx> { /// `cudaEventRecord(adapt_ev, adapt_stream)` after a batch of swaps; nothing to do without swaps. pub fn arm_swaps(&mut self) -> Result<()> { @@ -133,12 +131,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { self.ensure_live()?; let (offset, bytes) = self.table.slot_span(slot)?; let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(( - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, bytes)?, - bytes, - )) + Ok((b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, bytes)?, bytes)) } /// Same encoded gate/up/down layout as Original native_expert::Format. /// Three immutable registered role slices replace the contiguous host blob; @@ -192,27 +185,18 @@ impl<'ctx> OriginalExpertCache<'ctx> { let mut total = 0usize; for span in &spans { bank.cache_source(span)?; - total = total - .checked_add(span.bytes().len()) - .ok_or(Error::InvalidSize)?; + total = total.checked_add(span.bytes().len()).ok_or(Error::InvalidSize)?; } if total > capacity { - return Err(Error::ShapeMismatch { - expected: capacity, - actual: total, - }); + return Err(Error::ShapeMismatch { expected: capacity, actual: total }); } - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.pending.try_reserve(1).map_err(|_| Error::HostAllocation)?; let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; // Retain the real Arc/Rc-backed registered source BEFORE any enqueue. self.pending.push(RetainedFill::Mapped { bank, spans }); let guard = self.context.enter()?; let operation = (|| { - let RetainedFill::Mapped { bank, spans } = - self.pending.last().ok_or(Error::ContextPoisoned)? - else { + let RetainedFill::Mapped { bank, spans } = self.pending.last().ok_or(Error::ContextPoisoned)? else { return Err(Error::InvalidSize); }; let stream = if own_stream { diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs index c90edad4..c257f08e 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_3.rs @@ -3,61 +3,41 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalExpertCache<'ctx> { /// Original contiguous G/U/D startup/refill: one actual H2D on the default /// stream. The authentic assembled source and its admitted FD/context stay /// owned by this cache until the batch fence. A table admission is not a hit. - pub fn fill_file_slot_queued( - &mut self, - slot: usize, - blob: crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { + pub fn fill_file_slot_queued(&mut self, slot: usize, blob: crate::OriginalFileExpertBlob<'ctx>) -> Result<()> { self.ensure_live()?; blob.validate_context(self.context)?; let digest = blob.source_digest(); if self.file_source_digest.is_some_and(|bound| bound != digest) || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) - || self - .pending - .iter() - .any(|fill| matches!(fill, RetainedFill::Mapped { .. })) + || self.pending.iter().any(|fill| matches!(fill, RetainedFill::Mapped { .. })) { return Err(Error::InvalidSize); } - if self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) + if self.owners.get(slot).copied().flatten() != Some((usize::from(blob.layer()), blob.expert() as usize)) || self.states.get(slot) == Some(&State::Queued) { return Err(Error::InvalidSize); } let (handle, capacity) = self.slot_handle(slot)?; if blob.bytes().len() > capacity { - return Err(Error::ShapeMismatch { - expected: capacity, - actual: blob.bytes().len(), - }); + return Err(Error::ShapeMismatch { expected: capacity, actual: blob.bytes().len() }); } - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.pending.try_reserve(1).map_err(|_| Error::HostAllocation)?; let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; self.pending.push(RetainedFill::File(blob)); self.file_source_digest = Some(digest); let guard = self.context.enter()?; let copy = (|| { - let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? - else { + let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? else { return Err(Error::InvalidSize); }; blob.validate_context(self.context)?; self.attempted = true; - self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy( - handle.qwen_address(), - blob.bytes(), - api::Stream(0), - ) + self.api.as_ref().ok_or(Error::ContextPoisoned)?.copy(handle.qwen_address(), blob.bytes(), api::Stream(0)) })(); let result = combine(copy, guard.finish()); if result.is_err() { @@ -77,23 +57,17 @@ impl<'ctx> OriginalExpertCache<'ctx> { .capacity() .checked_mul(std::mem::size_of::>()) .ok_or(Error::BudgetExceeded)?; - self.pending - .iter() - .try_fold(metadata, |n, fill| match fill { - RetainedFill::File(blob) => n - .checked_add(blob.bytes().len()) - .and_then(|n| n.checked_add(blob.retained_metadata_bytes())) - .ok_or(Error::BudgetExceeded), - RetainedFill::Mapped { .. } => Ok(n), - }) + self.pending.iter().try_fold(metadata, |n, fill| match fill { + RetainedFill::File(blob) => n + .checked_add(blob.bytes().len()) + .and_then(|n| n.checked_add(blob.retained_metadata_bytes())) + .ok_or(Error::BudgetExceeded), + RetainedFill::Mapped { .. } => Ok(n), + }) } /// Startup uses Original's blocking cudaMemcpy semantics, rather than /// substituting a queued batch. The same owned blob survives uncertain DMA. - pub fn fill_file_slot_blocking( - &mut self, - slot: usize, - blob: crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { + pub fn fill_file_slot_blocking(&mut self, slot: usize, blob: crate::OriginalFileExpertBlob<'ctx>) -> Result<()> { self.ensure_live()?; blob.validate_context(self.context)?; if !self.pending.is_empty() { @@ -102,25 +76,21 @@ impl<'ctx> OriginalExpertCache<'ctx> { let digest = blob.source_digest(); if self.file_source_digest.is_some_and(|bound| bound != digest) || self.file_source_digest.is_none() && self.states.iter().any(|s| *s != State::Empty) - || self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) + || self.owners.get(slot).copied().flatten() != Some((usize::from(blob.layer()), blob.expert() as usize)) { return Err(Error::InvalidSize); } let (handle, capacity) = self.slot_handle(slot)?; let count = blob.bytes().len(); let handle = handle.checked_subspan(capacity, 0, count)?; - self.pending - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.pending.try_reserve(1).map_err(|_| Error::HostAllocation)?; let next_fills = self.fills.checked_add(1).ok_or(Error::InvalidSize)?; self.pending.push(RetainedFill::File(blob)); self.file_source_digest = Some(digest); let guard = self.context.enter()?; self.attempted = true; let copy = (|| { - let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? - else { + let RetainedFill::File(blob) = self.pending.last().ok_or(Error::ContextPoisoned)? else { return Err(Error::InvalidSize); }; blob.validate_context(self.context)?; @@ -137,16 +107,11 @@ impl<'ctx> OriginalExpertCache<'ctx> { self.pending.clear(); Ok(()) } - pub fn verify_file_slot( - &mut self, - slot: usize, - blob: &crate::OriginalFileExpertBlob<'ctx>, - ) -> Result<()> { + pub fn verify_file_slot(&mut self, slot: usize, blob: &crate::OriginalFileExpertBlob<'ctx>) -> Result<()> { self.sync_queued()?; blob.validate_context(self.context)?; if self.file_source_digest != Some(blob.source_digest()) - || self.owners.get(slot).copied().flatten() - != Some((usize::from(blob.layer()), blob.expert() as usize)) + || self.owners.get(slot).copied().flatten() != Some((usize::from(blob.layer()), blob.expert() as usize)) || self.states.get(slot) != Some(&State::Filled) { return Err(Error::InvalidSize); @@ -155,8 +120,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { let count = blob.bytes().len(); let handle = handle.checked_subspan(capacity, 0, count)?; let mut got = Vec::new(); - got.try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; + got.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; got.resize(count, 0); let guard = self.context.enter()?; let copy = self.context.driver.api.copy_to(handle, &mut got); @@ -169,9 +133,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { combine(combine(copy, sync), guard.finish())?; if got.as_slice() != blob.bytes() { self.states[slot] = State::NeedsRefill; - return Err(Error::InvalidDriverValue( - "Original expert cache source byte mismatch", - )); + return Err(Error::InvalidDriverValue("Original expert cache source byte mismatch")); } Ok(()) } @@ -184,11 +146,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { return Ok(()); } let guard = self.context.enter()?; - let wait = self - .api - .as_ref() - .ok_or(Error::ContextPoisoned)? - .synchronize_stream(api::Stream(0)); + let wait = self.api.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_stream(api::Stream(0)); let wait = match (wait, self.fill_stream, self.api.as_ref()) { (Ok(()), Some(stream), Some(api)) => api.synchronize_stream(stream), (wait, _, _) => wait, diff --git a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs index efd423b0..1a35f32a 100644 --- a/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs +++ b/crates/cuda-driver/src/original_expert_cache/impl_originalexpertcache/impl_originalexpertcache_4.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalExpertCache<'ctx> { /// Actual startup byte audit against the same retained source. Neither /// finite values nor successful allocation substitutes for this readback. @@ -27,14 +25,11 @@ impl<'ctx> OriginalExpertCache<'ctx> { { return Err(Error::InvalidSize); } - let count = spans.iter().try_fold(0usize, |n, s| { - n.checked_add(s.bytes().len()).ok_or(Error::InvalidSize) - })?; + let count = spans.iter().try_fold(0usize, |n, s| n.checked_add(s.bytes().len()).ok_or(Error::InvalidSize))?; let (handle, capacity) = self.slot_handle(slot)?; let handle = handle.checked_subspan(capacity, 0, count)?; let mut got = Vec::new(); - got.try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; + got.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; got.resize(count, 0); let guard = self.context.enter()?; let copy = self.context.driver.api.copy_to(handle, &mut got); @@ -50,9 +45,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { let source = bank.cache_source(span)?; if got[offset..offset + source.len()] != *source { self.states[slot] = State::NeedsRefill; - return Err(Error::InvalidDriverValue( - "Original expert cache source byte mismatch", - )); + return Err(Error::InvalidDriverValue("Original expert cache source byte mismatch")); } offset += source.len(); } @@ -76,8 +69,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { needed: impl FnMut(usize) -> Result, ) -> Result> { self.ensure_live()?; - self.table - .choose_loan(requested, auto, auto_max, context, lend_percent, needed) + self.table.choose_loan(requested, auto, auto_max, context, lend_percent, needed) } /// generate.cpp `part_slots`: the slots from the end of the cache that hold `bytes_needed`. pub fn lend_slots(&self, bytes_needed: usize) -> Result { @@ -106,10 +98,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { *state = State::NeedsRefill; } } - let prefix = OriginalCachePrefix { - table: &self.table, - states: &self.states[..first], - }; + let prefix = OriginalCachePrefix { table: &self.table, states: &self.states[..first] }; OriginalPrefillArena::from_cache_tail( self.buffer.as_mut().ok_or(Error::ContextPoisoned)?, offset, @@ -121,11 +110,7 @@ impl<'ctx> OriginalExpertCache<'ctx> { pub fn needs_refill(&self, slot: usize) -> Result> { self.ensure_live()?; let state = self.states.get(slot).ok_or(Error::InvalidSize)?; - Ok(if *state == State::NeedsRefill { - self.owners[slot] - } else { - None - }) + Ok(if *state == State::NeedsRefill { self.owners[slot] } else { None }) } pub(in super::super) fn poison(&mut self) { self.failed = true; diff --git a/crates/cuda-driver/src/original_expert_slots.rs b/crates/cuda-driver/src/original_expert_slots.rs index 5585b0ae..66219ef7 100644 --- a/crates/cuda-driver/src/original_expert_slots.rs +++ b/crates/cuda-driver/src/original_expert_slots.rs @@ -17,20 +17,13 @@ pub(crate) struct OriginalExpertSlots { fn vec_of(count: usize, value: T) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; result.resize(count, value); Ok(result) } impl OriginalExpertSlots { - pub(crate) fn uniform( - slots: usize, - layers: usize, - experts: usize, - blob: usize, - ) -> Result { + pub(crate) fn uniform(slots: usize, layers: usize, experts: usize, blob: usize) -> Result { if slots == 0 || layers == 0 || experts == 0 || blob == 0 || slots > i32::MAX as usize { return Err(Error::InvalidSize); } @@ -64,20 +57,11 @@ impl OriginalExpertSlots { for size in sizes { let aligned = size.checked_add(255).ok_or(Error::InvalidSize)? & !255; offsets.push( - offsets - .last() - .copied() - .ok_or(Error::InvalidSize)? - .checked_add(aligned) - .ok_or(Error::InvalidSize)?, + offsets.last().copied().ok_or(Error::InvalidSize)?.checked_add(aligned).ok_or(Error::InvalidSize)?, ); } - let mut table = Self::uniform( - sizes.len(), - layers, - experts, - sizes.iter().copied().max().ok_or(Error::InvalidSize)?, - )?; + let mut table = + Self::uniform(sizes.len(), layers, experts, sizes.iter().copied().max().ok_or(Error::InvalidSize)?)?; table.offsets = Some(offsets); Ok(table) } @@ -88,19 +72,13 @@ impl OriginalExpertSlots { } } pub(crate) fn bytes(&self) -> usize { - self.offsets - .as_ref() - .map_or(self.slots * self.blob, |v| *v.last().unwrap()) + self.offsets.as_ref().map_or(self.slots * self.blob, |v| *v.last().unwrap()) } pub(crate) fn slots(&self) -> usize { self.slots } pub(crate) fn resident(&self) -> usize { - if self.per_layer { - self.admitted - } else { - self.next_free - } + if self.per_layer { self.admitted } else { self.next_free } } pub(crate) fn set_per_layer_admission(&mut self, on: bool) { self.per_layer = on; @@ -113,14 +91,7 @@ impl OriginalExpertSlots { return (0, 0); } let q = self.slots / self.n_layers; - ( - layer * q, - if layer == self.n_layers - 1 { - self.slots - } else { - (layer + 1) * q - }, - ) + (layer * q, if layer == self.n_layers - 1 { self.slots } else { (layer + 1) * q }) } pub(crate) fn slot_of(&self, layer: usize, expert: usize) -> i32 { if layer >= self.n_layers || expert >= self.n_expert { @@ -197,10 +168,7 @@ impl OriginalExpertSlots { } Ok(k) } else { - Ok(bytes_needed - .checked_add(self.blob - 1) - .ok_or(Error::InvalidSize)? - / self.blob) + Ok(bytes_needed.checked_add(self.blob - 1).ok_or(Error::InvalidSize)? / self.blob) } } /// Includes the exact128-slot floor and85/90-percent rule from plan_lend. @@ -218,9 +186,7 @@ impl OriginalExpertSlots { let keep = k.checked_add(128).ok_or(Error::InvalidSize)? <= self.slots; let ratio = !percent || k.checked_mul(100).ok_or(Error::InvalidSize)? - <= lend_percent - .checked_mul(self.slots) - .ok_or(Error::InvalidSize)?; + <= lend_percent.checked_mul(self.slots).ok_or(Error::InvalidSize)?; Ok(keep && ratio) }; if auto { diff --git a/crates/cuda-driver/src/original_expert_stager.rs b/crates/cuda-driver/src/original_expert_stager.rs index aab6c164..3c3da868 100644 --- a/crates/cuda-driver/src/original_expert_stager.rs +++ b/crates/cuda-driver/src/original_expert_stager.rs @@ -4,8 +4,8 @@ use crate::ffi::original_stager as abi; use crate::{Context, DeviceBuffer, Error, OriginalGpuStream, Result, combine}; use leleka_model_format::qwen4exp::{ - FileExpertSourceLease, LayerRole, ResidentExpertBankLease, ResidentExpertBankMember, - ResidentExpertBankSpan, TensorRole, + FileExpertSourceLease, LayerRole, ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan, + TensorRole, }; use std::{ io::Read, @@ -103,12 +103,9 @@ pub struct OriginalStagerCompleted<'ctx> { #[path = "original_stream_all.rs"] mod stream_all; pub use stream_all::{ - OriginalStreamAll, OriginalStreamAllCompleted, OriginalStreamAllForward, - OriginalStreamAllOptions, -}; -pub(crate) use stream_all::{ - OriginalStreamAllGatheredGroup, OriginalStreamAllGroupProducer, OriginalStreamAllMember, + OriginalStreamAll, OriginalStreamAllCompleted, OriginalStreamAllForward, OriginalStreamAllOptions, }; +pub(crate) use stream_all::{OriginalStreamAllGatheredGroup, OriginalStreamAllGroupProducer, OriginalStreamAllMember}; /// Source-owned actual contiguous G/U/D assembly, never a finite/pinned or /// current-row certificate. The source FD and genuine Context remain retained @@ -126,8 +123,6 @@ mod tests; mod impl_originalstageroptions; mod impl_shared; -#[allow(unused_imports)] -use impl_shared::worker; #[cfg(windows)] #[allow(unused_imports)] use impl_shared::available_memory; @@ -136,6 +131,8 @@ use impl_shared::available_memory; use impl_shared::available_memory; #[allow(unused_imports)] use impl_shared::metadata; +#[allow(unused_imports)] +use impl_shared::worker; mod impl_context; mod impl_originalexpertstager; mod impl_originalstagerbatch; diff --git a/crates/cuda-driver/src/original_expert_stager/impl_context.rs b/crates/cuda-driver/src/original_expert_stager/impl_context.rs index 5ffdc3f9..42f8a478 100644 --- a/crates/cuda-driver/src/original_expert_stager/impl_context.rs +++ b/crates/cuda-driver/src/original_expert_stager/impl_context.rs @@ -14,15 +14,7 @@ impl Context<'_> { if self.is_poisoned() { return Err(Error::ContextPoisoned); } - self.open_original_stager( - Source { - lease: Some(lease), - members, - file: None, - }, - options, - host_allowance, - ) + self.open_original_stager(Source { lease: Some(lease), members, file: None }, options, host_allowance) } pub fn original_file_expert_stager( &self, @@ -38,14 +30,7 @@ impl Context<'_> { } let map = abi::ExpertFileMap::open(&lease)?; self.open_original_stager( - Source { - lease: None, - members: Vec::new(), - file: Some(FileSource { - lease: std::rc::Rc::new(lease), - map, - }), - }, + Source { lease: None, members: Vec::new(), file: Some(FileSource { lease: std::rc::Rc::new(lease), map }) }, options, host_allowance, ) @@ -75,35 +60,22 @@ impl Context<'_> { return Err(Error::BudgetExceeded); } if host_bytes > host_allowance - || available_memory()? - < host_bytes - .checked_add(HEADROOM) - .ok_or(Error::BudgetExceeded)? + || available_memory()? < host_bytes.checked_add(HEADROOM).ok_or(Error::BudgetExceeded)? { return Err(Error::BudgetExceeded); } let api = Arc::new(abi::Api::load()?); let mut slots = Vec::new(); - slots - .try_reserve_exact(ring) - .map_err(|_| Error::HostAllocation)?; + slots.try_reserve_exact(ring).map_err(|_| Error::HostAllocation)?; let mut worker_slots = Vec::new(); - worker_slots - .try_reserve_exact(ring) - .map_err(|_| Error::HostAllocation)?; + worker_slots.try_reserve_exact(ring).map_err(|_| Error::HostAllocation)?; let mut raw_jobs = Vec::new(); - raw_jobs - .try_reserve_exact(MAX_JOBS) - .map_err(|_| Error::HostAllocation)?; + raw_jobs.try_reserve_exact(MAX_JOBS).map_err(|_| Error::HostAllocation)?; let mut ready = Vec::new(); - ready - .try_reserve_exact(MAX_JOBS * 2) - .map_err(|_| Error::HostAllocation)?; + ready.try_reserve_exact(MAX_JOBS * 2).map_err(|_| Error::HostAllocation)?; ready.resize_with(MAX_JOBS * 2, || AtomicU8::new(0)); let mut workers = Vec::new(); - workers - .try_reserve_exact(threads) - .map_err(|_| Error::HostAllocation)?; + workers.try_reserve_exact(threads).map_err(|_| Error::HostAllocation)?; // Reject allocator overcapacity before allocating CUDA resources/publishing jobs. if slots.capacity() > ring || worker_slots.capacity() > ring @@ -167,11 +139,7 @@ impl Context<'_> { return combine(Err(primary), cleanup); } let shared = Arc::new(Shared { - work: Mutex::new(Work { - generation: 0, - quit: false, - jobs: raw_jobs, - }), + work: Mutex::new(Work { generation: 0, quit: false, jobs: raw_jobs }), cv: Condvar::new(), head: AtomicU64::new(0), issued: AtomicUsize::new(0), @@ -202,10 +170,7 @@ impl Context<'_> { for _ in 0..threads { let api = owner.api.clone(); let shared = owner.shared.clone(); - match thread::Builder::new() - .stack_size(WORKER_STACK) - .spawn(move || worker(api, shared, token)) - { + match thread::Builder::new().stack_size(WORKER_STACK).spawn(move || worker(api, shared, token)) { Ok(thread) => owner.workers.push(thread), Err(_) => return combine(Err(Error::HostAllocation), owner.close_inner()), } diff --git a/crates/cuda-driver/src/original_expert_stager/impl_originalexpertstager.rs b/crates/cuda-driver/src/original_expert_stager/impl_originalexpertstager.rs index b2e6b61b..ca8eacec 100644 --- a/crates/cuda-driver/src/original_expert_stager/impl_originalexpertstager.rs +++ b/crates/cuda-driver/src/original_expert_stager/impl_originalexpertstager.rs @@ -46,10 +46,7 @@ impl<'ctx> OriginalExpertStager<'ctx> { if !std::ptr::eq(buffer.context, self.context) { return Err(Error::ContextMismatch); } - buffer - .handle - .ok_or(Error::ContextPoisoned)? - .validate_extent(buffer.bytes)?; + buffer.handle.ok_or(Error::ContextPoisoned)?.validate_extent(buffer.bytes)?; } let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?; let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; @@ -58,11 +55,7 @@ impl<'ctx> OriginalExpertStager<'ctx> { source.job(job, self.blob_bytes)?; } { - let mut work = self - .shared - .work - .lock() - .map_err(|_| Error::ContextPoisoned)?; + let mut work = self.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; work.jobs.clear(); for job in &jobs { work.jobs.push(source.job(job, self.blob_bytes)?); @@ -71,36 +64,20 @@ impl<'ctx> OriginalExpertStager<'ctx> { ready.store(0, Ordering::Relaxed); } let n = jobs.len(); - self.flight = Some(Flight { - jobs, - destinations, - stream, - next: 0, - drained: false, - }); + self.flight = Some(Flight { jobs, destinations, stream, next: 0, drained: false }); self.generation = generation; self.shared.issued.store(0, Ordering::Release); - self.shared.head.store( - (u64::from(generation) << 32) | ((n as u64) << 16), - Ordering::Release, - ); + self.shared.head.store((u64::from(generation) << 32) | ((n as u64) << 16), Ordering::Release); // Publication under the same predicate mutex prevents a late old-generation // worker seeing generation before its head/actual retained job owners exist. work.generation = generation; } self.shared.cv.notify_all(); - Ok(OriginalStagerBatch { - stager: self, - finished: false, - }) + Ok(OriginalStagerBatch { stager: self, finished: false }) } pub(super) fn drain(&mut self) -> Result<()> { self.shared.stop(self.generation); - let workers = if self.shared.failed.load(Ordering::Acquire) { - Err(self.shared.error()) - } else { - Ok(()) - }; + let workers = if self.shared.failed.load(Ordering::Acquire) { Err(self.shared.error()) } else { Ok(()) }; let dma = self.flight.as_mut().map_or(Ok(()), |flight| { if flight.drained { return Ok(()); @@ -132,10 +109,7 @@ impl<'ctx> OriginalExpertStager<'ctx> { self.shared.cv.notify_all(); for worker in self.workers.drain(..) { if worker.join().is_err() { - result = combine( - result, - Err(Error::InvalidDriverValue("Original Stager join")), - ); + result = combine(result, Err(Error::InvalidDriverValue("Original Stager join"))); } } if self.shared.failed.load(Ordering::Acquire) { @@ -206,10 +180,7 @@ impl<'ctx> OriginalExpertStager<'ctx> { if self.flight.as_ref().is_some_and(|f| !f.drained) { return Err(Error::InvalidSize); } - Ok(self.flight.take().map(|f| OriginalStagerCompleted { - destinations: f.destinations, - stream: f.stream, - })) + Ok(self.flight.take().map(|f| OriginalStagerCompleted { destinations: f.destinations, stream: f.stream })) } pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/original_expert_stager/impl_originalstagerbatch.rs b/crates/cuda-driver/src/original_expert_stager/impl_originalstagerbatch.rs index 120c90a6..b964e4ab 100644 --- a/crates/cuda-driver/src/original_expert_stager/impl_originalstagerbatch.rs +++ b/crates/cuda-driver/src/original_expert_stager/impl_originalstagerbatch.rs @@ -20,20 +20,14 @@ impl<'ctx> OriginalStagerBatch<'_, 'ctx> { if job != flight.next || job >= flight.jobs.len() { return Err(Error::InvalidSize); } - let buffer = flight - .destinations - .get(destination) - .ok_or(Error::InvalidSize)?; + let buffer = flight.destinations.get(destination).ok_or(Error::InvalidSize)?; let raw = self .stager .source .as_ref() .ok_or(Error::ContextPoisoned)? .job(&flight.jobs[job], self.stager.blob_bytes)?; - let target = buffer - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(buffer.bytes, offset, raw.bytes())?; + let target = buffer.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(buffer.bytes, offset, raw.bytes())?; while self.stager.shared.ready[job].load(Ordering::Acquire) == 0 { if self.stager.shared.failed.load(Ordering::Acquire) { return Err(self.stager.shared.error()); @@ -45,9 +39,7 @@ impl<'ctx> OriginalStagerBatch<'_, 'ctx> { let event = self.stager.slots[slot].event; let api = &self.stager.api; let flight = self.stager.flight.as_mut().ok_or(Error::InvalidSize)?; - let result = flight - .stream - .with_enqueue(|stream| api.issue(target, host, raw.bytes(), stream, event)); + let result = flight.stream.with_enqueue(|stream| api.issue(target, host, raw.bytes(), stream, event)); if result.is_err() { self.stager.shared.failed.store(true, Ordering::Release); self.stager.context.poison(); @@ -61,30 +53,17 @@ impl<'ctx> OriginalStagerBatch<'_, 'ctx> { /// Only real destination objects can be consumed by closed GPU producers. /// This is addressability, not a finite or copy-completion certificate. The /// caller must install its genuine copied/used event ordering independently. - pub fn with_destinations( - &self, - callback: impl FnOnce(&[DeviceBuffer<'ctx>]) -> Result, - ) -> Result { + pub fn with_destinations(&self, callback: impl FnOnce(&[DeviceBuffer<'ctx>]) -> Result) -> Result { if self.stager.is_failed() { return Err(Error::ContextPoisoned); } - callback( - &self - .stager - .flight - .as_ref() - .ok_or(Error::InvalidSize)? - .destinations, - ) + callback(&self.stager.flight.as_ref().ok_or(Error::InvalidSize)?.destinations) } pub fn finish(mut self) -> Result> { self.stager.drain()?; let flight = self.stager.flight.take().ok_or(Error::InvalidSize)?; self.finished = true; - Ok(OriginalStagerCompleted { - destinations: flight.destinations, - stream: flight.stream, - }) + Ok(OriginalStagerCompleted { destinations: flight.destinations, stream: flight.stream }) } } impl Drop for OriginalStagerBatch<'_, '_> { @@ -122,24 +101,13 @@ impl OriginalFileExpertBlob<'_> { if context.is_poisoned() { return Err(Error::ContextPoisoned); } - self.source - .validate_current() - .map_err(|_| Error::InvalidSize)?; - let total = [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .try_fold(0usize, |n, r| { - n.checked_add( - self.source - .member(self.layer, r) - .map_err(|_| Error::InvalidSize)? - .expert_bytes(), - ) - .ok_or(Error::InvalidSize) - })?; + self.source.validate_current().map_err(|_| Error::InvalidSize)?; + let total = [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] + .into_iter() + .try_fold(0usize, |n, r| { + n.checked_add(self.source.member(self.layer, r).map_err(|_| Error::InvalidSize)?.expert_bytes()) + .ok_or(Error::InvalidSize) + })?; if self.expert >= 512 || self.bytes.len() != total { return Err(Error::InvalidSize); } @@ -153,25 +121,16 @@ impl<'ctx> OriginalExpertStager<'ctx> { } let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; let file = source.file.as_ref().ok_or(Error::InvalidQwenShape)?; - file.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; + file.lease.validate_current().map_err(|_| Error::InvalidSize)?; Ok(file.lease.as_ref()) } - pub fn file_blob( - &self, - layer: u8, - expert: u32, - host_allowance: usize, - ) -> Result> { + pub fn file_blob(&self, layer: u8, expert: u32, host_allowance: usize) -> Result> { if self.is_failed() { return Err(Error::ContextPoisoned); } let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; let file = source.file.as_ref().ok_or(Error::InvalidQwenShape)?; - file.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; + file.lease.validate_current().map_err(|_| Error::InvalidSize)?; let raw = source.raw_at(layer, expert, self.blob_bytes)?; let charge = raw .bytes() @@ -188,9 +147,7 @@ impl<'ctx> OriginalExpertStager<'ctx> { return Err(Error::BudgetExceeded); } let bytes = raw.owned_blob()?; - file.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; + file.lease.validate_current().map_err(|_| Error::InvalidSize)?; let blob = OriginalFileExpertBlob { context: self.context, source: std::rc::Rc::clone(&file.lease), @@ -212,13 +169,8 @@ impl OriginalExpertStager<'_> { } let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; let file = source.file.as_ref().ok_or(Error::InvalidQwenShape)?; - file.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; + file.lease.validate_current().map_err(|_| Error::InvalidSize)?; source.raw_at(layer, expert, self.blob_bytes)?; - Ok(OriginalStagerJob { - spans: None, - file: Some((layer, expert)), - }) + Ok(OriginalStagerJob { spans: None, file: Some((layer, expert)) }) } } diff --git a/crates/cuda-driver/src/original_expert_stager/impl_originalstageroptions.rs b/crates/cuda-driver/src/original_expert_stager/impl_originalstageroptions.rs index e95c2f5f..0fdbb9e5 100644 --- a/crates/cuda-driver/src/original_expert_stager/impl_originalstageroptions.rs +++ b/crates/cuda-driver/src/original_expert_stager/impl_originalstageroptions.rs @@ -15,38 +15,24 @@ impl OriginalStagerOptions { while let Some(c @ b'0'..=b'9') = b.next() { value = value.saturating_mul(10).saturating_add(i32::from(c - b'0')); } - if negative { - value.saturating_neg() - } else { - value - } + if negative { value.saturating_neg() } else { value } } Self { - ring_override: std::env::var("STRATA_STAGER_RING") - .ok() - .as_deref() - .map(atoi), - thread_override: std::env::var("STRATA_STAGER_THREADS") - .ok() - .as_deref() - .map(atoi), + ring_override: std::env::var("STRATA_STAGER_RING").ok().as_deref().map(atoi), + thread_override: std::env::var("STRATA_STAGER_THREADS").ok().as_deref().map(atoi), } } pub(super) fn dimensions(self) -> (usize, usize) { let hw = thread::available_parallelism().map_or(1, usize::from); ( self.ring_override.unwrap_or(16).clamp(2, 256) as usize, - self.thread_override - .map_or((hw / 4).clamp(2, 4), |t| t.clamp(1, 32) as usize), + self.thread_override.map_or((hw / 4).clamp(2, 4), |t| t.clamp(1, 32) as usize), ) } } impl OriginalStagerJob { pub fn new(spans: [ResidentExpertBankSpan; 3]) -> Self { - Self { - spans: Some(spans), - file: None, - } + Self { spans: Some(spans), file: None } } pub fn layer(&self) -> Result { if let Some((layer, _)) = self.file { @@ -58,10 +44,7 @@ impl OriginalStagerJob { } } pub fn expert(&self) -> u32 { - self.file.map_or_else( - || self.spans.as_ref().map_or(512, |s| s[0].expert()), - |(_, e)| e, - ) + self.file.map_or_else(|| self.spans.as_ref().map_or(512, |s| s[0].expert()), |(_, e)| e) } } impl Source { @@ -81,32 +64,17 @@ impl Source { if layer >= 48 || expert >= 512 { return Err(Error::InvalidSize); } - let roles = [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ]; + let roles = [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts]; let mut parts: [&[u8]; 3] = [&[]; 3]; for (i, r) in roles.into_iter().enumerate() { if let Some(file) = &self.file { - let m = file - .lease - .member(layer, r) - .map_err(|_| Error::InvalidSize)?; - let offset = (expert as u64) - .checked_mul(m.expert_bytes() as u64) - .ok_or(Error::InvalidSize)?; - parts[i] = file.map.part( - m.absolute_start() - .checked_add(offset) - .ok_or(Error::InvalidSize)?, - m.expert_bytes(), - )?; + let m = file.lease.member(layer, r).map_err(|_| Error::InvalidSize)?; + let offset = (expert as u64).checked_mul(m.expert_bytes() as u64).ok_or(Error::InvalidSize)?; + parts[i] = file + .map + .part(m.absolute_start().checked_add(offset).ok_or(Error::InvalidSize)?, m.expert_bytes())?; } else { - let m = self - .members - .get(usize::from(layer) * 3 + i) - .ok_or(Error::InvalidSize)?; + let m = self.members.get(usize::from(layer) * 3 + i).ok_or(Error::InvalidSize)?; if m.role() != (TensorRole::Layer { layer, role: r }) { return Err(Error::InvalidQwenShape); } @@ -123,18 +91,9 @@ impl Source { let mut maximum = 0; for l in 0..48u8 { let mut n = 0usize; - for r in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for r in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { n = n - .checked_add( - f.lease - .member(l, r) - .map_err(|_| Error::InvalidSize)? - .expert_bytes(), - ) + .checked_add(f.lease.member(l, r).map_err(|_| Error::InvalidSize)?.expert_bytes()) .ok_or(Error::InvalidSize)?; } maximum = maximum.max(n); @@ -150,13 +109,8 @@ impl Source { let mut maximum = 0usize; for layer in 0..48u8 { let mut bytes = 0usize; - for (index, role) in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .enumerate() + for (index, role) in + [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts].into_iter().enumerate() { let m = &self.members[usize::from(layer) * 3 + index]; if m.role() != (TensorRole::Layer { layer, role }) @@ -166,9 +120,7 @@ impl Source { { return Err(Error::InvalidQwenShape); } - bytes = bytes - .checked_add(m.bytes().len() / 512) - .ok_or(Error::InvalidSize)?; + bytes = bytes.checked_add(m.bytes().len() / 512).ok_or(Error::InvalidSize)?; } maximum = maximum.max(bytes); } @@ -181,24 +133,13 @@ impl Source { if j.file != Some((layer, expert)) || layer >= 48 || expert >= 512 { return Err(Error::InvalidSize); } - let roles = [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ]; + let roles = [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts]; let mut parts: [&[u8]; 3] = [&[]; 3]; for (i, r) in roles.into_iter().enumerate() { - let m = file - .lease - .member(layer, r) - .map_err(|_| Error::InvalidSize)?; + let m = file.lease.member(layer, r).map_err(|_| Error::InvalidSize)?; let absolute = m .absolute_start() - .checked_add( - (expert as u64) - .checked_mul(m.expert_bytes() as u64) - .ok_or(Error::InvalidSize)?, - ) + .checked_add((expert as u64).checked_mul(m.expert_bytes() as u64).ok_or(Error::InvalidSize)?) .ok_or(Error::InvalidSize)?; parts[i] = file.map.part(absolute, m.expert_bytes())?; } @@ -215,17 +156,11 @@ impl Source { || span.role() != member.role() || span.expert() != expert || span.bytes().len() != bytes - || span.offset() - != bytes - .checked_mul(expert as usize) - .ok_or(Error::InvalidSize)? + || span.offset() != bytes.checked_mul(expert as usize).ok_or(Error::InvalidSize)? { return Err(Error::InvalidQwenShape); } } - abi::CopyJob::from_slices( - [spans[0].bytes(), spans[1].bytes(), spans[2].bytes()], - capacity, - ) + abi::CopyJob::from_slices([spans[0].bytes(), spans[1].bytes(), spans[2].bytes()], capacity) } } diff --git a/crates/cuda-driver/src/original_expert_stager/impl_shared.rs b/crates/cuda-driver/src/original_expert_stager/impl_shared.rs index fd33cd37..d38150d7 100644 --- a/crates/cuda-driver/src/original_expert_stager/impl_shared.rs +++ b/crates/cuda-driver/src/original_expert_stager/impl_shared.rs @@ -14,11 +14,7 @@ impl Shared { self.cv.notify_all(); } pub(super) fn error(&self) -> Error { - self.error - .lock() - .ok() - .and_then(|mut e| e.take()) - .unwrap_or(Error::ContextPoisoned) + self.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned) } pub(super) fn claim(&self, generation: u32) -> Option { let mut cur = self.head.load(Ordering::Acquire); @@ -32,10 +28,7 @@ impl Shared { return None; } // SeqCst on the success path: see `enter_claim`. - match self - .head - .compare_exchange_weak(cur, cur + 1, Ordering::SeqCst, Ordering::Acquire) - { + match self.head.compare_exchange_weak(cur, cur + 1, Ordering::SeqCst, Ordering::Acquire) { Ok(_) => return Some(j), Err(next) => cur = next, } @@ -53,8 +46,7 @@ impl Shared { Some((active, j)) } pub(super) fn stop(&self, generation: u32) { - self.head - .store(u64::from(generation) << 32, Ordering::SeqCst); + self.head.store(u64::from(generation) << 32, Ordering::SeqCst); self.issued.store(1 << 30, Ordering::Release); while self.active.load(Ordering::SeqCst) != 0 { thread::yield_now(); @@ -77,10 +69,7 @@ pub(super) fn worker(api: Arc, shared: Arc, context: usize) { loop { { let mut work = shared.work.lock().map_err(|_| Error::ContextPoisoned)?; - while !work.quit - && !shared.failed.load(Ordering::Acquire) - && work.generation == seen - { + while !work.quit && !shared.failed.load(Ordering::Acquire) && work.generation == seen { work = shared.cv.wait(work).map_err(|_| Error::ContextPoisoned)?; } if work.quit || shared.failed.load(Ordering::Acquire) { @@ -158,10 +147,7 @@ pub(super) fn available_memory() -> Result { if available.is_some() { return Err(Error::BudgetExceeded); } - let number = p - .next() - .and_then(|n| n.parse::().ok()) - .ok_or(Error::BudgetExceeded)?; + let number = p.next().and_then(|n| n.parse::().ok()).ok_or(Error::BudgetExceeded)?; if p.next() != Some("kB") || p.next().is_some() { return Err(Error::BudgetExceeded); } @@ -171,9 +157,7 @@ pub(super) fn available_memory() -> Result { } pub(super) fn metadata(ring: usize, threads: usize) -> Result { MAX_JOBS - .checked_mul( - size_of::() + size_of::() + 2 * size_of::(), - ) + .checked_mul(size_of::() + size_of::() + 2 * size_of::()) .and_then(|n| { n.checked_add( 512 * (2 * size_of::() + size_of::()) diff --git a/crates/cuda-driver/src/original_expert_stager_ffi/check_fn.rs b/crates/cuda-driver/src/original_expert_stager_ffi/check_fn.rs index aafe3db7..5044a145 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi/check_fn.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi/check_fn.rs @@ -4,14 +4,7 @@ use super::*; pub(super) fn check(name: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: name, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code }) } } impl Drop for Api { fn drop(&mut self) { diff --git a/crates/cuda-driver/src/original_expert_stager_ffi/impl_api.rs b/crates/cuda-driver/src/original_expert_stager_ffi/impl_api.rs index 73bc4c66..afae26a8 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi/impl_api.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi/impl_api.rs @@ -6,15 +6,11 @@ use super::*; impl Api { pub(crate) fn record(&self, event: usize, stream: usize) -> Result<()> { // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). - check("cuEventRecord", unsafe { - (self.event_record)(event as Handle, stream as Handle) - }) + check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) }) } pub(crate) fn wait(&self, stream: usize, event: usize) -> Result<()> { // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). - check("cuStreamWaitEvent", unsafe { - (self.stream_wait)(stream as Handle, event as Handle, 0) - }) + check("cuStreamWaitEvent", unsafe { (self.stream_wait)(stream as Handle, event as Handle, 0) }) } pub(crate) fn copy_slot( &self, @@ -30,12 +26,7 @@ impl Api { // SAFETY: destination extent validated, `0 < bytes <= source.bytes`, `source.address != 0`: a slot buffer the stager keeps // (pinned: cuMemFreeHost'd, pageable: Vec dropped) only after the slot's recorded event was synchronized (`close_inner`). check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy)( - destination.0, - source.address as *const c_void, - bytes, - stream as Handle, - ) + (self.copy)(destination.0, source.address as *const c_void, bytes, stream as Handle) }) } @@ -59,11 +50,7 @@ impl Api { fn symbol(l: Handle, n: &'static CStr) -> Result { // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l, n.as_ptr()) }; - if p.is_null() { - Err(Error::MissingSymbol(n.to_str().unwrap_or("Stager symbol"))) - } else { - Ok(p) - } + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("Stager symbol"))) } else { Ok(p) } } macro_rules! sym { ($n:literal,$t:ty) => { @@ -100,26 +87,15 @@ impl Api { if p.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - return Ok(HostBuffer { - address: p as usize, - bytes, - pinned: true, - pageable: None, - }); + return Ok(HostBuffer { address: p as usize, bytes, pinned: true, pageable: None }); } // Original cudaHostAlloc-default refusal uses pageable fallback. Driver calls // have no runtime last-error slot to clear. All other event/copy errors remain fatal. let mut data = Vec::new(); - data.try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + data.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; data.resize(bytes, 0); let address = data.as_mut_ptr() as usize; - Ok(HostBuffer { - address, - bytes, - pinned: false, - pageable: Some(data), - }) + Ok(HostBuffer { address, bytes, pinned: false, pageable: Some(data) }) } pub(crate) fn free_buffer(&self, buffer: &mut HostBuffer) -> Result<()> { if buffer.address == 0 { @@ -128,9 +104,7 @@ impl Api { if buffer.pinned { // SAFETY: `address` is the base `cuMemHostAlloc` returned for this (`pinned`) buffer and is freed once (zeroed after). // Callers free only after every DMA from it completed (events synchronized) and the Context is entered. - check("cuMemFreeHost", unsafe { - (self.host_free)(buffer.address as Handle) - })?; + check("cuMemFreeHost", unsafe { (self.host_free)(buffer.address as Handle) })?; } buffer.address = 0; buffer.pageable.take(); @@ -140,11 +114,7 @@ impl Api { let mut p = std::ptr::null_mut(); // SAFETY: valid out pointer; flags DISABLE_TIMING. check("cuEventCreate", unsafe { (self.event_create)(&mut p, 2) })?; - if p.is_null() { - Err(Error::InvalidDriverValue("cuEventCreate")) - } else { - Ok(p as usize) - } + if p.is_null() { Err(Error::InvalidDriverValue("cuEventCreate")) } else { Ok(p as usize) } } /// A timing event (LELEKA_PREFILL_COPY_STATS): the same as `event_create` with timestamps enabled. pub(crate) fn event_create_timing(&self) -> Result { @@ -160,15 +130,11 @@ impl Api { } pub(crate) fn event_destroy(&self, event: usize) -> Result<()> { // SAFETY: event created by `event_create`, destroyed once by the owner after it was synchronized. - check("cuEventDestroy_v2", unsafe { - (self.event_destroy)(event as Handle) - }) + check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event as Handle) }) } pub(crate) fn event_sync(&self, event: usize) -> Result<()> { // SAFETY: live event handle owned by the caller. - check("cuEventSynchronize", unsafe { - (self.event_sync)(event as Handle) - }) + check("cuEventSynchronize", unsafe { (self.event_sync)(event as Handle) }) } /// `cuEventQuery`: `Ok(true)` once complete, `Ok(false)` while pending (CUDA_ERROR_NOT_READY = 600). pub(crate) fn event_query(&self, event: usize) -> Result { @@ -181,13 +147,7 @@ impl Api { } /// One H2D copy of `bytes` from a host address the caller retains (a page-locked bank range) into /// `destination` on `stream`. - pub(crate) fn copy_raw( - &self, - destination: BufferHandle, - source: usize, - bytes: usize, - stream: usize, - ) -> Result<()> { + pub(crate) fn copy_raw(&self, destination: BufferHandle, source: usize, bytes: usize, stream: usize) -> Result<()> { destination.validate_extent(bytes)?; if bytes == 0 || source == 0 { return Err(Error::InvalidSize); @@ -203,19 +163,13 @@ impl Api { } pub(crate) fn worker_enter(&self, context: usize) -> Result<()> { // SAFETY: `context` is the live CUcontext token of the actor's Context; popped again by `worker_leave` on the same thread. - check("cuCtxPushCurrent_v2", unsafe { - (self.push)(context as Handle) - }) + check("cuCtxPushCurrent_v2", unsafe { (self.push)(context as Handle) }) } pub(crate) fn worker_leave(&self, context: usize) -> Result<()> { let mut p = std::ptr::null_mut(); // SAFETY: valid out pointer. check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut p) })?; - if p as usize == context { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } + if p as usize == context { Ok(()) } else { Err(Error::UnexpectedContext) } } pub(crate) fn issue( &self, @@ -231,16 +185,9 @@ impl Api { } // SAFETY: as `copy_slot`: validated destination extent; `source` is a slot buffer owned by the stager until its event (recorded below) completed. check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy)( - destination.0, - source.address as *const c_void, - bytes, - stream as Handle, - ) + (self.copy)(destination.0, source.address as *const c_void, bytes, stream as Handle) })?; // SAFETY: C ABI call with plain handle values; the event/stream are live handles owned by the caller (never dereferenced here). - check("cuEventRecord", unsafe { - (self.event_record)(event as Handle, stream as Handle) - }) + check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) }) } } diff --git a/crates/cuda-driver/src/original_expert_stager_ffi/impl_hostbuffer.rs b/crates/cuda-driver/src/original_expert_stager_ffi/impl_hostbuffer.rs index bd5c225d..cf6116a7 100644 --- a/crates/cuda-driver/src/original_expert_stager_ffi/impl_hostbuffer.rs +++ b/crates/cuda-driver/src/original_expert_stager_ffi/impl_hostbuffer.rs @@ -11,11 +11,7 @@ impl HostBuffer { self.pageable.as_ref().map_or(self.bytes, Vec::capacity) } pub(crate) fn slot(&self, event: usize) -> WorkerSlot { - WorkerSlot { - address: self.address, - bytes: self.bytes, - event, - } + WorkerSlot { address: self.address, bytes: self.bytes, event } } } impl CopyJob { @@ -69,9 +65,7 @@ impl CopyJob { } } impl ExpertFileMap { - pub(crate) fn open( - owner: &leleka_model_format::qwen4exp::FileExpertSourceLease, - ) -> Result { + pub(crate) fn open(owner: &leleka_model_format::qwen4exp::FileExpertSourceLease) -> Result { #[cfg(unix)] use std::os::fd::AsRawFd; owner.validate_current().map_err(|_| Error::InvalidSize)?; @@ -85,14 +79,7 @@ impl ExpertFileMap { // missing pages; this is the same contract as `VerifiedGgufFile`, not detectable here. #[cfg(unix)] let ptr = unsafe { - libc::mmap( - std::ptr::null_mut(), - bytes, - libc::PROT_READ, - libc::MAP_SHARED, - owner.file().as_raw_fd(), - 0, - ) + libc::mmap(std::ptr::null_mut(), bytes, libc::PROT_READ, libc::MAP_SHARED, owner.file().as_raw_fd(), 0) }; #[cfg(unix)] if ptr == libc::MAP_FAILED { @@ -117,10 +104,7 @@ impl ExpertFileMap { } return Err(Error::InvalidSize); } - let map = Self { - address: ptr as usize, - bytes, - }; + let map = Self { address: ptr as usize, bytes }; owner.validate_current().map_err(|_| Error::InvalidSize)?; Ok(map) } @@ -150,17 +134,12 @@ impl Drop for ExpertFileMap { impl CopyJob { pub(crate) fn owned_blob(&self) -> Result> { let mut data = Vec::new(); - data.try_reserve_exact(self.bytes) - .map_err(|_| Error::HostAllocation)?; + data.try_reserve_exact(self.bytes).map_err(|_| Error::HostAllocation)?; if data.capacity() > self.bytes { return Err(Error::BudgetExceeded); } data.resize(self.bytes, 0); - self.copy_to(WorkerSlot { - address: data.as_mut_ptr() as usize, - bytes: data.len(), - event: 0, - })?; + self.copy_to(WorkerSlot { address: data.as_mut_ptr() as usize, bytes: data.len(), event: 0 })?; Ok(data.into_boxed_slice()) } } diff --git a/crates/cuda-driver/src/original_file_expert_source.rs b/crates/cuda-driver/src/original_file_expert_source.rs index 0928e192..48e16b51 100644 --- a/crates/cuda-driver/src/original_file_expert_source.rs +++ b/crates/cuda-driver/src/original_file_expert_source.rs @@ -123,8 +123,8 @@ use impl_default_for_originalresidentoptions::atoi; use impl_default_for_originalresidentoptions::key; #[allow(unused_imports)] use impl_default_for_originalresidentoptions::vec_filled; -mod impl_originalfileexpertsource; mod impl_drop_for_originalfileexpertsource; +mod impl_originalfileexpertsource; #[cfg(windows)] #[allow(unused_imports)] use impl_drop_for_originalfileexpertsource::available_memory; diff --git a/crates/cuda-driver/src/original_file_expert_source/available_memory_fn.rs b/crates/cuda-driver/src/original_file_expert_source/available_memory_fn.rs index 0694e548..517e5bf8 100644 --- a/crates/cuda-driver/src/original_file_expert_source/available_memory_fn.rs +++ b/crates/cuda-driver/src/original_file_expert_source/available_memory_fn.rs @@ -12,9 +12,7 @@ pub(super) fn available_memory() -> Result { fn text(p: &Path) -> Result { let f = std::fs::File::open(p).map_err(|_| Error::BudgetExceeded)?; let mut s = String::new(); - f.take(65537) - .read_to_string(&mut s) - .map_err(|_| Error::BudgetExceeded)?; + f.take(65537).read_to_string(&mut s).map_err(|_| Error::BudgetExceeded)?; if s.len() > 65536 { return Err(Error::BudgetExceeded); } @@ -23,10 +21,7 @@ pub(super) fn available_memory() -> Result { fn value(p: &Path) -> Result { let s = text(p)?; let mut f = s.split_ascii_whitespace(); - let n = f - .next() - .and_then(|n| n.parse::().ok()) - .ok_or(Error::BudgetExceeded)?; + let n = f.next().and_then(|n| n.parse::().ok()).ok_or(Error::BudgetExceeded)?; if f.next().is_some() { return Err(Error::BudgetExceeded); } @@ -37,10 +32,7 @@ pub(super) fn available_memory() -> Result { for l in info.lines() { let mut f = l.split_ascii_whitespace(); if f.next() == Some("MemAvailable:") { - let n = f - .next() - .and_then(|n| n.parse::().ok()) - .ok_or(Error::BudgetExceeded)?; + let n = f.next().and_then(|n| n.parse::().ok()).ok_or(Error::BudgetExceeded)?; if f.next() != Some("kB") { return Err(Error::BudgetExceeded); } @@ -89,10 +81,7 @@ pub(super) fn available_memory() -> Result { for l in stat.lines() { let mut f = l.split_ascii_whitespace(); let k = f.next().ok_or(Error::BudgetExceeded)?; - let n = f - .next() - .and_then(|n| n.parse::().ok()) - .ok_or(Error::BudgetExceeded)?; + let n = f.next().and_then(|n| n.parse::().ok()).ok_or(Error::BudgetExceeded)?; if f.next().is_some() { return Err(Error::BudgetExceeded); } @@ -118,10 +107,7 @@ pub(super) fn available_memory() -> Result { } } _ => { - if path != root - || path.join("memory.max").exists() - || !path.join("cgroup.controllers").exists() - { + if path != root || path.join("memory.max").exists() || !path.join("cgroup.controllers").exists() { return Err(Error::BudgetExceeded); } } @@ -140,11 +126,7 @@ pub(super) fn available_memory() -> Result { usize::try_from(bytes).map_err(|_| Error::BudgetExceeded) } impl<'ctx> OriginalFileExpertSource<'ctx> { - pub(crate) fn stream_source( - &self, - l: usize, - e: usize, - ) -> Result> { + pub(crate) fn stream_source(&self, l: usize, e: usize) -> Result> { self.live()?; key(l, e)?; if self.transient(l, e) { @@ -185,12 +167,7 @@ impl OriginalFileStreamSource<'_, '_> { out.copy_from_slice(b.bytes); Ok(()) } - Self::Transient { - source, - layer, - expert, - .. - } => source.copy_blob(*layer, *expert, out), + Self::Transient { source, layer, expert, .. } => source.copy_blob(*layer, *expert, out), } } pub(crate) fn raw_parts(&self) -> Option<[&[u8]; 3]> { diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_default_for_originalresidentoptions.rs b/crates/cuda-driver/src/original_file_expert_source/impl_default_for_originalresidentoptions.rs index 0d5b68c5..3f8bd121 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_default_for_originalresidentoptions.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_default_for_originalresidentoptions.rs @@ -20,21 +20,14 @@ impl OriginalResidentOptions { /// the genuine operator policy/profile, not inferred from arbitrary bytes. pub fn from_environment() -> Self { let mut s = Self::default(); - s.partial_pin = std::env::var("STRATA_PARTIAL_PIN") - .ok() - .is_some_and(|v| atoi(&v) != 0); - s.partial_pin_cap = - abi::partial_pin_cap(std::env::var("STRATA_PARTIAL_PIN_GIB").ok().as_deref()); + s.partial_pin = std::env::var("STRATA_PARTIAL_PIN").ok().is_some_and(|v| atoi(&v) != 0); + s.partial_pin_cap = abi::partial_pin_cap(std::env::var("STRATA_PARTIAL_PIN_GIB").ok().as_deref()); s } } pub(super) fn atoi(v: &str) -> i32 { let b = v.trim_start(); - let (sign, b) = if let Some(b) = b.strip_prefix('-') { - (-1, b) - } else { - (1, b.strip_prefix('+').unwrap_or(b)) - }; + let (sign, b) = if let Some(b) = b.strip_prefix('-') { (-1, b) } else { (1, b.strip_prefix('+').unwrap_or(b)) }; let mut n = 0i32; for c in b.bytes() { if !c.is_ascii_digit() { @@ -71,39 +64,19 @@ impl OriginalFileSourceBlob<'_, '_> { } pub fn role_bytes(&self) -> Result<[usize; 3]> { let mut out = [0; 3]; - for (i, r) in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .enumerate() + for (i, r) in + [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts].into_iter().enumerate() { - out[i] = self - .source - .lease - .member(self.layer as u8, r) - .map_err(|_| Error::InvalidSize)? - .expert_bytes(); + out[i] = self.source.lease.member(self.layer as u8, r).map_err(|_| Error::InvalidSize)?.expert_bytes(); } Ok(out) } pub fn role_kinds(&self) -> Result<[u32; 3]> { let mut out = [0; 3]; - for (i, r) in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .enumerate() + for (i, r) in + [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts].into_iter().enumerate() { - out[i] = self - .source - .lease - .member(self.layer as u8, r) - .map_err(|_| Error::InvalidSize)? - .raw_kind(); + out[i] = self.source.lease.member(self.layer as u8, r).map_err(|_| Error::InvalidSize)?.raw_kind(); } Ok(out) } @@ -113,11 +86,7 @@ impl OriginalFileSourceBlob<'_, '_> { if second.checked_add(n[2]) != Some(self.bytes.len()) { return Err(Error::InvalidSize); } - Ok([ - &self.bytes[..n[0]], - &self.bytes[n[0]..second], - &self.bytes[second..], - ]) + Ok([&self.bytes[..n[0]], &self.bytes[n[0]..second], &self.bytes[second..]]) } pub fn pinned(&self) -> bool { self.alias.is_some() @@ -147,18 +116,9 @@ impl<'ctx> Context<'ctx> { let mut layer_bytes = [0usize; LAYERS]; let mut maximum = 0usize; for (l, n) in layer_bytes.iter_mut().enumerate() { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { *n = (*n) - .checked_add( - lease - .member(l as u8, role) - .map_err(|_| Error::InvalidSize)? - .expert_bytes(), - ) + .checked_add(lease.member(l as u8, role).map_err(|_| Error::InvalidSize)?.expert_bytes()) .ok_or(Error::InvalidSize)?; } maximum = maximum.max(*n); diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_drop_for_originalfileexpertsource.rs b/crates/cuda-driver/src/original_file_expert_source/impl_drop_for_originalfileexpertsource.rs index d970bdcb..f013598b 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_drop_for_originalfileexpertsource.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_drop_for_originalfileexpertsource.rs @@ -19,9 +19,7 @@ impl OriginalFileExpertSource<'_> { } let bytes = n.checked_mul(self.maximum).ok_or(Error::InvalidSize)?; self.admit_extra(bytes)?; - self.staged - .try_reserve_exact(n.saturating_sub(self.staged.len())) - .map_err(|_| Error::HostAllocation)?; + self.staged.try_reserve_exact(n.saturating_sub(self.staged.len())).map_err(|_| Error::HostAllocation)?; self.metadata_bytes()?; let guard = self.context.enter().inspect_err(|_| { self.failed = true; @@ -62,8 +60,7 @@ impl OriginalFileExpertSource<'_> { stream.validate_context(self.context)?; if !self.ready || swaps.is_empty() { let mut kept = Vec::new(); - kept.try_reserve_exact(swaps.len()) - .map_err(|_| Error::HostAllocation)?; + kept.try_reserve_exact(swaps.len()).map_err(|_| Error::HostAllocation)?; kept.extend_from_slice(swaps); return Ok(kept); } @@ -71,18 +68,13 @@ impl OriginalFileExpertSource<'_> { return Err(Error::InvalidSize); } let mut kept = Vec::new(); - kept.try_reserve_exact(swaps.len()) - .map_err(|_| Error::HostAllocation)?; + kept.try_reserve_exact(swaps.len()).map_err(|_| Error::HostAllocation)?; let mut candidates: Vec<(Exchange, crate::ffi::BufferHandle, usize)> = Vec::new(); - candidates - .try_reserve_exact(swaps.len().min(self.exchange_capacity)) - .map_err(|_| Error::HostAllocation)?; + candidates.try_reserve_exact(swaps.len().min(self.exchange_capacity)).map_err(|_| Error::HostAllocation)?; if self.overrides.is_empty() { self.overrides = vec_filled(N, NONE)?; } - self.staged - .try_reserve(candidates.capacity()) - .map_err(|_| Error::HostAllocation)?; + self.staged.try_reserve(candidates.capacity()).map_err(|_| Error::HostAllocation)?; self.metadata_bytes()?; for &s in swaps { let incoming = key(s.layer, s.incoming)?; @@ -95,34 +87,19 @@ impl OriginalFileExpertSource<'_> { if q >= self.exchange_capacity { continue; } - let Some((handle, capacity)) = cache.completed_file_source_member( - self.context, - s.layer, - s.outgoing, - self.source_digest(), - )? + let Some((handle, capacity)) = + cache.completed_file_source_member(self.context, s.layer, s.outgoing, self.source_digest())? else { continue; }; let bytes = self.layer_bytes[s.layer]; if bytes > capacity || self.overrides[outgoing] != NONE - || candidates - .iter() - .any(|(x, _, _)| x.incoming == incoming || x.outgoing == outgoing) + || candidates.iter().any(|(x, _, _)| x.incoming == incoming || x.outgoing == outgoing) { return Err(Error::InvalidSize); } - candidates.push(( - Exchange { - incoming, - outgoing, - q, - bytes, - }, - handle, - capacity, - )); + candidates.push((Exchange { incoming, outgoing, q, bytes }, handle, capacity)); kept.push(s); } if candidates.is_empty() { @@ -180,17 +157,9 @@ impl OriginalFileExpertSource<'_> { let mut applied = 0; for x in &self.staged { let off = self.offsets[x.incoming]; - if self.overrides[x.outgoing] == x.q && off != NONE && self.offsets[x.outgoing] == NONE - { - let from = self - .exchange - .as_ref() - .ok_or(Error::InvalidSize)? - .part(x.q * self.maximum, x.bytes)?; - self.arena - .as_ref() - .ok_or(Error::InvalidSize)? - .overwrite(off, from)?; + if self.overrides[x.outgoing] == x.q && off != NONE && self.offsets[x.outgoing] == NONE { + let from = self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(x.q * self.maximum, x.bytes)?; + self.arena.as_ref().ok_or(Error::InvalidSize)?.overwrite(off, from)?; self.offsets[x.outgoing] = off; self.offsets[x.incoming] = NONE; applied += 1; diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs index f237e845..0e752a71 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2.rs @@ -3,16 +3,13 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalFileExpertSource<'ctx> { pub(in super::super) fn live(&self) -> Result<()> { if self.closed || self.failed || self.context.is_poisoned() { return Err(Error::ContextPoisoned); } self.metadata_bytes()?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) + self.lease.validate_current().map_err(|_| Error::InvalidSize) } pub(crate) fn validate_context(&self, c: &Context<'_>) -> Result<()> { self.live()?; @@ -24,31 +21,15 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { pub(in super::super) fn parts(&self, l: usize, e: usize) -> Result<[&[u8]; 3]> { key(l, e)?; let mut p = [&[][..]; 3]; - for (i, r) in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] - .into_iter() - .enumerate() + for (i, r) in + [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts].into_iter().enumerate() { - let m = self - .lease - .member(l as u8, r) - .map_err(|_| Error::InvalidSize)?; + let m = self.lease.member(l as u8, r).map_err(|_| Error::InvalidSize)?; let first = m .absolute_start() - .checked_add( - (e as u64) - .checked_mul(m.expert_bytes() as u64) - .ok_or(Error::InvalidSize)?, - ) + .checked_add((e as u64).checked_mul(m.expert_bytes() as u64).ok_or(Error::InvalidSize)?) .ok_or(Error::InvalidSize)?; - p[i] = self - .map - .as_ref() - .ok_or(Error::ContextPoisoned)? - .part(first, m.expert_bytes())?; + p[i] = self.map.as_ref().ok_or(Error::ContextPoisoned)?.part(first, m.expert_bytes())?; } Ok(p) } @@ -74,15 +55,10 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { self.ready } pub fn has_resident(&self, l: usize, e: usize) -> bool { - key(l, e) - .ok() - .and_then(|i| self.offsets.get(i)) - .is_some_and(|o| *o != NONE) + key(l, e).ok().and_then(|i| self.offsets.get(i)).is_some_and(|o| *o != NONE) } pub fn transient(&self, l: usize, e: usize) -> bool { - key(l, e).is_ok_and(|i| { - !self.has_resident(l, e) && self.overrides.get(i).copied().unwrap_or(NONE) == NONE - }) + key(l, e).is_ok_and(|i| !self.has_resident(l, e) && self.overrides.get(i).copied().unwrap_or(NONE) == NONE) } pub fn pcie_layer(&self, l: usize) -> bool { l < LAYERS && self.ready && self.pinned_bytes() > 0 @@ -137,10 +113,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { .ok_or(Error::BudgetExceeded) } pub(in super::super) fn admit_extra(&self, n: usize) -> Result<()> { - if self - .charged_bytes()? - .checked_add(n) - .is_none_or(|n| n > SOURCE_CAP) + if self.charged_bytes()?.checked_add(n).is_none_or(|n| n > SOURCE_CAP) || available_memory()? < n.checked_add(8 * GIB).ok_or(Error::BudgetExceeded)? { return Err(Error::BudgetExceeded); diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs index f703a50e..b093b3e3 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalFileExpertSource<'ctx> { /// Genuine original primary cache membership, complete fill and Context fence, /// not caller-provided booleans. Additional/rank lists retain Original validation. @@ -44,9 +43,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } } let (mut offsets, mut bytes) = self.plan(&primary, additional)?; - let mut lend = options - .lend_from_slot - .filter(|s| *s < cache.slots() && additional.is_empty()); + let mut lend = options.lend_from_slot.filter(|s| *s < cache.slots() && additional.is_empty()); let physical = available_memory()?; let room = physical.saturating_sub(options.headroom_bytes); let mut budget = options.budget_bytes; @@ -100,8 +97,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } if keep_from < cache.slots() { let mut core = Vec::new(); - core.try_reserve_exact(primary.len()) - .map_err(|_| Error::HostAllocation)?; + core.try_reserve_exact(primary.len()).map_err(|_| Error::HostAllocation)?; core.extend(primary.iter().copied().filter(|p| p.2 < keep_from)); (offsets, bytes) = self.plan(&core, additional)?; } @@ -119,9 +115,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { ) .ok_or(Error::BudgetExceeded)?; if prospective_meta > META_CAP - || bytes - .checked_add(prospective_meta) - .is_none_or(|n| n > SOURCE_CAP) + || bytes.checked_add(prospective_meta).is_none_or(|n| n > SOURCE_CAP) || bytes .checked_add(5 * stack) .and_then(|n| n.checked_add(prospective_meta)) @@ -158,9 +152,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { for (i, &off) in offsets.iter().enumerate() { if off != NONE && off < want - && off - .checked_add(self.layer_bytes[i / EXPERTS]) - .is_some_and(|end| end > want) + && off.checked_add(self.layer_bytes[i / EXPERTS]).is_some_and(|end| end > want) { cut = off; break; @@ -180,13 +172,10 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { // Closed raw records derived only from retained mapped source and actual arena. // Six Original layer workers; one actor participates. No Context/Rc is sent. let mut per_layer = Vec::new(); - per_layer - .try_reserve_exact(LAYERS) - .map_err(|_| Error::HostAllocation)?; + per_layer.try_reserve_exact(LAYERS).map_err(|_| Error::HostAllocation)?; for l in 0..LAYERS { let mut jobs = Vec::new(); - jobs.try_reserve_exact(EXPERTS) - .map_err(|_| Error::HostAllocation)?; + jobs.try_reserve_exact(EXPERTS).map_err(|_| Error::HostAllocation)?; for e in 0..EXPERTS { let off = offsets[l * EXPERTS + e]; if off != NONE { @@ -218,9 +207,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { }; thread::scope(|s| { let mut workers = Vec::new(); - workers - .try_reserve_exact(5) - .map_err(|_| Error::HostAllocation)?; + workers.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; for _ in 0..5 { workers.push( thread::Builder::new() @@ -240,9 +227,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { return Err(e); } - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize)?; + self.lease.validate_current().map_err(|_| Error::InvalidSize)?; Ok(()) })(); let pop = guard.finish(); @@ -276,11 +261,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { self.arena = Some(arena); self.offsets = offsets; self.ready = true; - self.lent_slots = if lend.is_some() { - cache.slots() - keep_from - } else { - 0 - }; + self.lent_slots = if lend.is_some() { cache.slots() - keep_from } else { 0 }; Ok(()) } } diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs index 771b31d9..d8b7c515 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalFileExpertSource<'ctx> { pub(in super::super) fn plan( &self, @@ -38,9 +37,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { let i = l * EXPERTS + e; if omit[i] == 0 { offsets[i] = bytes; - bytes = bytes - .checked_add(self.layer_bytes[l]) - .ok_or(Error::InvalidSize)?; + bytes = bytes.checked_add(self.layer_bytes[l]).ok_or(Error::InvalidSize)?; } } } @@ -59,35 +56,21 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { .stage .iter() .enumerate() - .filter(|(_, s)| { - !s.busy - && (s.epoch.wrapping_add(3) <= self.epoch || s.used.wrapping_add(256) <= seq) - }) + .filter(|(_, s)| !s.busy && (s.epoch.wrapping_add(3) <= self.epoch || s.used.wrapping_add(256) <= seq)) .min_by_key(|(_, s)| s.used) .map(|(i, _)| i); - self.stage_of - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.stage_of.try_reserve(1).map_err(|_| Error::HostAllocation)?; let v = if let Some(v) = victim { self.stage_of.remove(&self.stage[v].key); v } else { self.admit_extra(self.maximum + size_of::())?; - self.stage - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.stage.try_reserve(1).map_err(|_| Error::HostAllocation)?; let mut data = Vec::new(); - data.try_reserve_exact(self.maximum) - .map_err(|_| Error::HostAllocation)?; + data.try_reserve_exact(self.maximum).map_err(|_| Error::HostAllocation)?; data.resize(self.maximum, 0); let v = self.stage.len(); - self.stage.push(Stage { - data: data.into_boxed_slice(), - key: NONE, - epoch: 0, - used: 0, - busy: false, - }); + self.stage.push(Stage { data: data.into_boxed_slice(), key: NONE, epoch: 0, used: 0, busy: false }); v }; self.metadata_bytes()?; @@ -108,19 +91,13 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { let owned = parts.map(|p| (p.as_ptr() as usize, p.len())); let stage = &mut self.stage[v]; abi::copy_parts_to(owned, &mut stage.data)?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) + self.lease.validate_current().map_err(|_| Error::InvalidSize) })(); let mut c = self.counts.get(); c.file_us = c.file_us.wrapping_add(t.elapsed().as_micros() as u64); if operation.is_ok() { - c.file_read_bytes = c - .file_read_bytes - .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); - c.file_blob_bytes = c - .file_blob_bytes - .wrapping_add(self.layer_bytes[k / EXPERTS] as u64); + c.file_read_bytes = c.file_read_bytes.wrapping_add(self.layer_bytes[k / EXPERTS] as u64); + c.file_blob_bytes = c.file_blob_bytes.wrapping_add(self.layer_bytes[k / EXPERTS] as u64); } self.counts.set(c); self.stage[v].busy = false; @@ -153,13 +130,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { let a = self.arena.as_ref().ok_or(Error::InvalidSize)?; (a.part(off, n)?, a.alias(off, n)?) } else if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { - ( - self.exchange - .as_ref() - .ok_or(Error::InvalidSize)? - .part(q * self.maximum, n)?, - None, - ) + (self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(q * self.maximum, n)?, None) } else { let v = *self.stage_of.get(&k).ok_or(Error::InvalidSize)?; let s = &self.stage[v]; @@ -176,13 +147,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } c.reads = c.reads.wrapping_add(1); self.counts.set(c); - Ok(OriginalFileSourceBlob { - source: self, - layer: l, - expert: e, - bytes, - alias, - }) + Ok(OriginalFileSourceBlob { source: self, layer: l, expert: e, bytes, alias }) } pub fn copy_blob(&self, l: usize, e: usize, out: &mut [u8]) -> Result<()> { self.live()?; @@ -193,21 +158,11 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } let off = self.offsets.get(k).copied().unwrap_or(NONE); if off != NONE { - out.copy_from_slice( - self.arena - .as_ref() - .ok_or(Error::InvalidSize)? - .part(off, n)?, - ); + out.copy_from_slice(self.arena.as_ref().ok_or(Error::InvalidSize)?.part(off, n)?); return Ok(()); } if let Some(q) = self.overrides.get(k).copied().filter(|q| *q != NONE) { - out.copy_from_slice( - self.exchange - .as_ref() - .ok_or(Error::InvalidSize)? - .part(q * self.maximum, n)?, - ); + out.copy_from_slice(self.exchange.as_ref().ok_or(Error::InvalidSize)?.part(q * self.maximum, n)?); return Ok(()); } let t = Instant::now(); @@ -219,9 +174,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } self.counts.set(c); result?; - self.lease - .validate_current() - .map_err(|_| Error::InvalidSize) + self.lease.validate_current().map_err(|_| Error::InvalidSize) } pub fn warm(&mut self, l: usize, experts: &[i64]) -> Result<()> { self.live()?; diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs index 62ffece4..d6e613ea 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalFileExpertSource<'ctx> { pub(in super::super) fn prefetch_impl(&mut self, l: usize, experts: &[i64]) -> Result<()> { self.live()?; @@ -11,16 +10,13 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { return Ok(()); } let mut todo = Vec::new(); - todo.try_reserve_exact(experts.len().min(N)) - .map_err(|_| Error::HostAllocation)?; + todo.try_reserve_exact(experts.len().min(N)).map_err(|_| Error::HostAllocation)?; for &e in experts { if e < 0 || e >= EXPERTS as i64 { continue; } let k = l * EXPERTS + e as usize; - if self.has_resident(l, e as usize) - || self.overrides.get(k).copied().unwrap_or(NONE) != NONE - { + if self.has_resident(l, e as usize) || self.overrides.get(k).copied().unwrap_or(NONE) != NONE { continue; } let (v, fill) = self.claim_stage(k)?; @@ -38,19 +34,14 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { return Ok(()); } let mut jobs = Vec::new(); - jobs.try_reserve_exact(todo.len()) - .map_err(|_| Error::HostAllocation)?; + jobs.try_reserve_exact(todo.len()).map_err(|_| Error::HostAllocation)?; for &(v, k) in &todo { - let raw = self - .parts(l, k % EXPERTS)? - .map(|p| (p.as_ptr() as usize, p.len())); + let raw = self.parts(l, k % EXPERTS)?.map(|p| (p.as_ptr() as usize, p.len())); jobs.push(abi::copy_parts_record(raw, &mut self.stage[v].data)?); } let next = AtomicUsize::new(0); let mut result: Vec, u64)>>> = Vec::new(); - result - .try_reserve_exact(todo.len()) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(todo.len()).map_err(|_| Error::HostAllocation)?; result.resize_with(todo.len(), || Mutex::new(None)); let work = || loop { let i = next.fetch_add(1, Ordering::Relaxed); @@ -65,16 +56,10 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { }; let nt = jobs.len().min(self.fetch_threads); let stack = abi::worker_stack_bytes()?; - self.admit_extra( - nt.saturating_sub(1) - .checked_mul(stack) - .ok_or(Error::BudgetExceeded)?, - )?; + self.admit_extra(nt.saturating_sub(1).checked_mul(stack).ok_or(Error::BudgetExceeded)?)?; let spawned = thread::scope(|s| { let mut workers = Vec::new(); - workers - .try_reserve_exact(nt.saturating_sub(1)) - .map_err(|_| Error::HostAllocation)?; + workers.try_reserve_exact(nt.saturating_sub(1)).map_err(|_| Error::HostAllocation)?; for _ in 1..nt { workers.push( thread::Builder::new() @@ -91,10 +76,7 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { } Ok(()) }); - let source = self - .lease - .validate_current() - .map_err(|_| Error::InvalidSize); + let source = self.lease.validate_current().map_err(|_| Error::InvalidSize); let mut first = None; for (i, &(v, k)) in todo.iter().enumerate() { let completed = result[i].lock().ok().and_then(|mut r| r.take()); diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi.rs b/crates/cuda-driver/src/original_file_expert_source_ffi.rs index a5451df3..1943183e 100644 --- a/crates/cuda-driver/src/original_file_expert_source_ffi.rs +++ b/crates/cuda-driver/src/original_file_expert_source_ffi.rs @@ -49,12 +49,12 @@ use check_fn::check; #[path = "original_file_expert_source_ffi/impl_arena.rs"] mod impl_arena; #[allow(unused_imports)] -pub(crate) use impl_arena::warm; -#[allow(unused_imports)] pub(crate) use impl_arena::copy_parts_record; #[allow(unused_imports)] pub(crate) use impl_arena::copy_parts_to; #[allow(unused_imports)] -pub(crate) use impl_arena::worker_stack_bytes; -#[allow(unused_imports)] pub(crate) use impl_arena::partial_pin_cap; +#[allow(unused_imports)] +pub(crate) use impl_arena::warm; +#[allow(unused_imports)] +pub(crate) use impl_arena::worker_stack_bytes; diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi/check_fn.rs b/crates/cuda-driver/src/original_file_expert_source_ffi/check_fn.rs index c953c68e..7aa57d0b 100644 --- a/crates/cuda-driver/src/original_file_expert_source_ffi/check_fn.rs +++ b/crates/cuda-driver/src/original_file_expert_source_ffi/check_fn.rs @@ -4,14 +4,7 @@ use super::*; pub(super) fn check(n: &'static str, c: i32) -> Result<()> { - if c == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: n, - code: c, - }) - } + if c == 0 { Ok(()) } else { Err(Error::Driver { operation: n, code: c }) } } impl Drop for Api { fn drop(&mut self) { @@ -42,13 +35,7 @@ impl Api { fn symbol(l: P, n: &'static CStr) -> Result

{ // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l, n.as_ptr()) }; - if p.is_null() { - Err(Error::MissingSymbol( - n.to_str().unwrap_or("FileExpertSource symbol"), - )) - } else { - Ok(p) - } + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("FileExpertSource symbol"))) } else { Ok(p) } } macro_rules! sym { ($n:literal,$t:ty) => { @@ -70,15 +57,7 @@ impl Api { } pub(crate) fn allocate(&self, bytes: usize, pin: bool) -> Result { if bytes == 0 { - return Ok(Arena { - address: 0, - bytes: 0, - alias: 0, - full_pin: false, - partial: 0, - locked: 0, - lock_off: 0, - }); + return Ok(Arena { address: 0, bytes: 0, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 }); } if pin { let mut p = std::ptr::null_mut(); @@ -106,15 +85,7 @@ impl Api { if p.is_null() { return Err(Error::HostAllocation); } - Ok(Arena { - address: p as usize, - bytes, - alias: 0, - full_pin: false, - partial: 0, - locked: 0, - lock_off: 0, - }) + Ok(Arena { address: p as usize, bytes, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 }) } pub(crate) fn exchange_allocate(&self, bytes: usize) -> Result { if bytes == 0 { @@ -138,15 +109,7 @@ impl Api { if p.is_null() { return Err(Error::HostAllocation); } - Ok(Arena { - address: p as usize, - bytes, - alias: 0, - full_pin: false, - partial: 0, - locked: 0, - lock_off: 0, - }) + Ok(Arena { address: p as usize, bytes, alias: 0, full_pin: false, partial: 0, locked: 0, lock_off: 0 }) } pub(crate) fn exchange_copy( &self, @@ -157,22 +120,14 @@ impl Api { stream: usize, ) -> Result<()> { source.validate_extent(bytes)?; - if bytes == 0 - || offset.checked_add(bytes).is_none_or(|n| n > arena.bytes) - || arena.address == 0 - { + if bytes == 0 || offset.checked_add(bytes).is_none_or(|n| n > arena.bytes) || arena.address == 0 { return Err(Error::InvalidSize); } // SAFETY: `offset + bytes <= arena.bytes` (checked above), so the destination is inside the live arena; `source` extent validated. // A pinned (`full_pin`) arena is written asynchronously: `stage_swaps` synchronizes the stream before any `part` read and before `close`; // a `malloc` arena is pageable, so the driver completes the copy before returning. check("cuMemcpyDtoHAsync_v2", unsafe { - (self.dtoh)( - (arena.address + offset) as P, - source.qwen_address(), - bytes, - stream as P, - ) + (self.dtoh)((arena.address + offset) as P, source.qwen_address(), bytes, stream as P) }) } pub(crate) fn register_prefix(&self, arena: &mut Arena, bytes: usize) -> Result { @@ -190,9 +145,7 @@ impl Api { arena.alias = alias; } else { // SAFETY: identical base that was just registered. - check("cuMemHostUnregister", unsafe { - (self.unregister)(arena.address as P) - })?; + check("cuMemHostUnregister", unsafe { (self.unregister)(arena.address as P) })?; arena.partial = 0; } // Original stops after the first accepted registration even if alias fails. @@ -208,9 +161,7 @@ impl Api { } else { if arena.partial > 0 { // SAFETY: identical base that `register_prefix` registered (`partial > 0`); unregistered once, before the block is freed. - check("cuMemHostUnregister", unsafe { - (self.unregister)(arena.address as P) - })?; + check("cuMemHostUnregister", unsafe { (self.unregister)(arena.address as P) })?; arena.partial = 0; } if arena.locked > 0 { diff --git a/crates/cuda-driver/src/original_file_expert_source_ffi/impl_arena.rs b/crates/cuda-driver/src/original_file_expert_source_ffi/impl_arena.rs index e939b62f..fada8290 100644 --- a/crates/cuda-driver/src/original_file_expert_source_ffi/impl_arena.rs +++ b/crates/cuda-driver/src/original_file_expert_source_ffi/impl_arena.rs @@ -8,11 +8,7 @@ impl Arena { self.bytes } pub(crate) fn pin_limit(&self) -> usize { - if self.full_pin { - self.bytes - } else { - self.partial - } + if self.full_pin { self.bytes } else { self.partial } } pub(crate) fn locked(&self) -> usize { self.locked @@ -41,11 +37,7 @@ impl Arena { if offset.checked_add(n).is_none_or(|n| n > self.bytes) { return Err(Error::InvalidSize); } - Ok(Copy { - source, - destination: self.address.checked_add(offset).ok_or(Error::InvalidSize)?, - bytes: n, - }) + Ok(Copy { source, destination: self.address.checked_add(offset).ok_or(Error::InvalidSize)?, bytes: n }) } pub(crate) fn part(&self, offset: usize, bytes: usize) -> Result<&[u8]> { if offset.checked_add(bytes).is_none_or(|n| n > self.bytes) || self.address == 0 { @@ -58,12 +50,7 @@ impl Arena { Ok(unsafe { std::slice::from_raw_parts((self.address + offset) as *const u8, bytes) }) } pub(crate) fn overwrite(&self, offset: usize, source: &[u8]) -> Result<()> { - if source.is_empty() - || offset - .checked_add(source.len()) - .is_none_or(|n| n > self.bytes) - || self.address == 0 - { + if source.is_empty() || offset.checked_add(source.len()).is_none_or(|n| n > self.bytes) || self.address == 0 { return Err(Error::InvalidSize); } let d = self.address.checked_add(offset).ok_or(Error::InvalidSize)?; @@ -87,17 +74,12 @@ impl Arena { if self.alias == 0 || offset + bytes > self.pin_limit() { return Ok(None); } - self.alias - .checked_add(offset as u64) - .map(Some) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).map(Some).ok_or(Error::InvalidSize) } } impl Copy { pub(crate) fn into_slice(parts: [&[u8]; 3], out: &mut [u8]) -> Result { - let n = parts.iter().try_fold(0usize, |n, p| { - n.checked_add(p.len()).ok_or(Error::InvalidSize) - })?; + let n = parts.iter().try_fold(0usize, |n, p| n.checked_add(p.len()).ok_or(Error::InvalidSize))?; if n > out.len() { return Err(Error::InvalidSize); } @@ -140,21 +122,11 @@ pub(crate) fn warm(parts: [&[u8]; 3]) { } pub(crate) fn copy_parts_record(parts: [(usize, usize); 3], out: &mut [u8]) -> Result { - let n = parts.iter().try_fold(0usize, |n, (_, b)| { - n.checked_add(*b).ok_or(Error::InvalidSize) - })?; - if n > out.len() - || parts - .iter() - .any(|(p, b)| *p == 0 || *b == 0 || p.checked_add(*b).is_none()) - { + let n = parts.iter().try_fold(0usize, |n, (_, b)| n.checked_add(*b).ok_or(Error::InvalidSize))?; + if n > out.len() || parts.iter().any(|(p, b)| *p == 0 || *b == 0 || p.checked_add(*b).is_none()) { return Err(Error::InvalidSize); } - Ok(Copy { - source: parts, - destination: out.as_mut_ptr() as usize, - bytes: n, - }) + Ok(Copy { source: parts, destination: out.as_mut_ptr() as usize, bytes: n }) } pub(crate) fn copy_parts_to(parts: [(usize, usize); 3], out: &mut [u8]) -> Result<()> { copy_parts_record(parts, out)?.run() @@ -162,10 +134,7 @@ pub(crate) fn copy_parts_to(parts: [(usize, usize); 3], out: &mut [u8]) -> Resul /// Original std::thread's Linux default pthread stack derives from the startup /// RLIMIT_STACK. Root must preserve this launch limit; no system limit is set. pub(crate) fn worker_stack_bytes() -> Result { - let mut limit = libc::rlimit { - rlim_cur: 0, - rlim_max: 0, - }; + let mut limit = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; // SAFETY: valid pointer to a local `rlimit`. if unsafe { libc::getrlimit(libc::RLIMIT_STACK, &mut limit) } != 0 || limit.rlim_cur == 0 @@ -183,9 +152,7 @@ pub(crate) fn partial_pin_cap(value: Option<&str>) -> usize { let v = value.and_then(|v| std::ffi::CString::new(v).ok()); // Original atof positive-prefix semantics (including whitespace/exponent). // SAFETY: `v` is a NUL-terminated `CString`; the end pointer is null. - let n = v.as_ref().map_or(24.0, |v| unsafe { - libc::strtod(v.as_ptr(), std::ptr::null_mut()) - }); + let n = v.as_ref().map_or(24.0, |v| unsafe { libc::strtod(v.as_ptr(), std::ptr::null_mut()) }); let n = if n > 0.0 { n } else { 24.0 }; (n * 1073741824.0) as usize } diff --git a/crates/cuda-driver/src/original_gpu_head_bridge.rs b/crates/cuda-driver/src/original_gpu_head_bridge.rs index 4793f609..fff78f83 100644 --- a/crates/cuda-driver/src/original_gpu_head_bridge.rs +++ b/crates/cuda-driver/src/original_gpu_head_bridge.rs @@ -2,20 +2,13 @@ //! Child of original_gpu_schedule; uses its actual private graph/stream owners. use super::*; use crate::{ - DeviceBuffer, NativeHeadSampling, NativeHeadSelection, OriginalNativeHead, - OriginalNativeHeadGraphResources, + DeviceBuffer, NativeHeadSampling, NativeHeadSelection, OriginalNativeHead, OriginalNativeHeadGraphResources, }; impl<'ctx, R: OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R> { pub fn validate_native_head(&self, head: &OriginalNativeHead<'ctx>) -> Result<()> { self.validate()?; head.validate_context(self.context)?; - if !self - .resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .native_head_rows()? - .belongs_to(head) - { + if !self.resources.as_ref().ok_or(Error::ContextPoisoned)?.native_head_rows()?.belongs_to(head) { return Err(Error::ContextMismatch); } Ok(()) @@ -28,12 +21,7 @@ impl<'ctx, R: OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R> self.validate()?; stream.validate_context(self.context)?; // A captured but never replayed graph does not contain completed logits. - if !self.launched - || !self - .last - .as_ref() - .is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) - { + if !self.launched || !self.last.as_ref().is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) { return Err(Error::InvalidQwenShape); } let receipt = stream.synchronize_with_receipt()?; @@ -57,12 +45,7 @@ impl<'ctx, R: OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R> consume: impl FnOnce(NativeHeadSelection, &DeviceBuffer<'ctx>) -> Result, ) -> Result { let selection = self.native_head_after_launch(stream, sampling)?; - let logits = self - .resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .native_head_rows()? - .completed_logits()?; + let logits = self.resources.as_ref().ok_or(Error::ContextPoisoned)?.native_head_rows()?.completed_logits()?; consume(selection, logits) } } diff --git a/crates/cuda-driver/src/original_gpu_schedule.rs b/crates/cuda-driver/src/original_gpu_schedule.rs index 664cadcc..ee2ffb8e 100644 --- a/crates/cuda-driver/src/original_gpu_schedule.rs +++ b/crates/cuda-driver/src/original_gpu_schedule.rs @@ -144,19 +144,11 @@ pub struct OriginalGraphRegistry<'ctx, R: OriginalGraphResources> { captures: u64, } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_gpu_head_bridge.rs"] mod native_head_bridge; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_gpu_verify_bridge.rs"] mod verifier_bridge; @@ -218,28 +210,28 @@ mod oom_tests { mod transport_fn; #[allow(unused_imports)] -use transport_fn::transport; -#[allow(unused_imports)] -use transport_fn::poison; -#[allow(unused_imports)] -use transport_fn::healthy; -#[allow(unused_imports)] -pub(crate) use transport_fn::is_graph_out_of_memory; -#[allow(unused_imports)] -use transport_fn::poisons; -#[allow(unused_imports)] use transport_fn::call; #[allow(unused_imports)] use transport_fn::call_unless; #[allow(unused_imports)] +use transport_fn::healthy; +#[allow(unused_imports)] use transport_fn::injected_window_oom; +#[allow(unused_imports)] +pub(crate) use transport_fn::is_graph_out_of_memory; +#[allow(unused_imports)] +use transport_fn::poison; +#[allow(unused_imports)] +use transport_fn::poisons; +#[allow(unused_imports)] +use transport_fn::transport; mod impl_originalgpustream; mod set_side_streams_wanted_fn; #[allow(unused_imports)] -pub(crate) use set_side_streams_wanted_fn::set_side_streams_wanted; +use set_side_streams_wanted_fn::drop_side; #[allow(unused_imports)] use set_side_streams_wanted_fn::make_side; #[allow(unused_imports)] -use set_side_streams_wanted_fn::drop_side; +pub(crate) use set_side_streams_wanted_fn::set_side_streams_wanted; mod impl_originalgpugraph; mod impl_originalgraphkey; diff --git a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpugraph.rs b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpugraph.rs index c77ef81e..3e335238 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpugraph.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpugraph.rs @@ -6,10 +6,7 @@ use super::*; impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { pub(super) fn validate(&self) -> Result { healthy(self.context)?; - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(self.context)?; + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(self.context)?; self.exec.ok_or(Error::ContextPoisoned) } pub fn nodes(&self) -> Option { @@ -31,19 +28,11 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { if s.inner.capture.get() { return Err(Error::InvalidQwenShape); } - if self.launched - && self - .last - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) - { + if self.launched && self.last.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) { return Err(Error::ContextMismatch); } let ex = self.validate()?; - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_replay_context(self.context)?; + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.validate_replay_context(self.context)?; let st = s.inner.validate()?; let sequence = s.inner.bump()?; self.last = Some(s.inner.clone()); @@ -57,22 +46,13 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { Ok(()) }) } - pub fn launch<'g>( - &'g mut self, - s: &OriginalGpuStream<'ctx>, - ) -> Result> { + pub fn launch<'g>(&'g mut self, s: &OriginalGpuStream<'ctx>) -> Result> { self.enqueue(s)?; - Ok(OriginalGraphFlight { - graph: self, - active: true, - }) + Ok(OriginalGraphFlight { graph: self, active: true }) } /// Actual completion receipt from the final same-stream fence. No caller /// boolean or other Context/stream can authorize retirement. - pub fn resources_after_stream_drain( - &mut self, - done: &OriginalStreamDrained<'ctx>, - ) -> Result<&R> { + pub fn resources_after_stream_drain(&mut self, done: &OriginalStreamDrained<'ctx>) -> Result<&R> { self.validate()?; healthy(self.context)?; if self.launched { @@ -112,17 +92,9 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { if !self.launched { return Ok(true); } - let stream = self - .last - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; + let stream = self.last.as_ref().ok_or(Error::ContextPoisoned)?.validate()?; let q = call(self.context, &self.api, |a| { - if let Some(e) = self.done { - a.event_query(e) - } else { - a.stream_query(stream) - } + if let Some(e) = self.done { a.event_query(e) } else { a.stream_query(stream) } })?; if q { self.launched = false; @@ -134,11 +106,7 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { if !self.launched { return Ok(()); } - let s = self - .last - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; + let s = self.last.as_ref().ok_or(Error::ContextPoisoned)?.validate()?; call(self.context, &self.api, |a| a.stream_sync(s))?; self.launched = false; Ok(()) @@ -167,11 +135,8 @@ impl<'ctx, R: OriginalGraphResources> OriginalGpuGraph<'ctx, R> { } let stream = self.last.as_ref().and_then(|s| s.handle.get()); let r = call(self.context, &self.api, |a| { - let drained = if self.launched { - stream.map_or(Err(Error::ContextPoisoned), |s| a.stream_sync(s)) - } else { - Ok(()) - }; + let drained = + if self.launched { stream.map_or(Err(Error::ContextPoisoned), |s| a.stream_sync(s)) } else { Ok(()) }; if drained.is_err() { return drained; } diff --git a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpustream.rs b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpustream.rs index 55edb67c..6333f29b 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpustream.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgpustream.rs @@ -11,9 +11,7 @@ impl<'ctx> OriginalGpuStream<'ctx> { self.inner.validate().map(|_| ()) } pub fn is_failed(&self) -> bool { - self.inner.failed.get() - || self.inner.context.is_poisoned() - || self.inner.handle.get().is_none() + self.inner.failed.get() || self.inner.context.is_poisoned() || self.inner.handle.get().is_none() } pub fn priority(&self) -> Result { self.inner.run(|a, h| a.stream_priority(h)) @@ -75,11 +73,7 @@ impl<'ctx> OriginalGpuStream<'ctx> { return Err(Error::InvalidQwenShape); } let _sequence = self.inner.bump()?; - let guard = self - .inner - .context - .enter() - .inspect_err(|_| poison(self.inner.context))?; + let guard = self.inner.context.enter().inspect_err(|_| poison(self.inner.context))?; let op = f(h); let pop = guard.finish(); if op.as_ref().err().is_some_and(transport) || pop.is_err() { @@ -117,7 +111,9 @@ impl<'ctx> OriginalGpuStream<'ctx> { last_sequence: 0, }; // SIDE_MIXER: the side streams and their events exist before the capture begins (stream / event creation is not a capture-time call) - let side = if policy == OriginalCapturePolicy::VerifierWindow && SIDE_STREAMS_WANTED.load(std::sync::atomic::Ordering::Relaxed) { + let side = if policy == OriginalCapturePolicy::VerifierWindow + && SIDE_STREAMS_WANTED.load(std::sync::atomic::Ordering::Relaxed) + { match make_side(self.inner.context, &self.inner.api) { Ok(side) => Some(side), Err(e) => { @@ -142,21 +138,13 @@ impl<'ctx> OriginalGpuStream<'ctx> { } }; // Body errors are primary, but EndCapture is always attempted before retirement. - let mut token = OriginalCapture { - stream: &self.inner, - side, - target: Cell::new(None), - }; + let mut token = OriginalCapture { stream: &self.inner, side, target: Cell::new(None) }; let body_result = match g.resources.as_mut() { Some(r) => body(&mut token, r), None => Err(Error::ContextPoisoned), }; - let resource_result = g - .resources - .as_ref() - .map_or(Err(Error::ContextPoisoned), |r| { - r.validate_context(self.inner.context) - }); + let resource_result = + g.resources.as_ref().map_or(Err(Error::ContextPoisoned), |r| r.validate_context(self.inner.context)); let body_result = combine(body_result, resource_result); let end = self.inner.api.end(h); self.inner.capture.set(false); @@ -193,10 +181,7 @@ impl<'ctx> OriginalGpuStream<'ctx> { let n = call(g.context, &g.api, |a| a.nodes(graph))?; g.nodes = Some(n); if n == 0 { - return combine( - Err(Error::InvalidDriverValue("Original capture ZERO nodes")), - g.close_inner(), - ); + return combine(Err(Error::InvalidDriverValue("Original capture ZERO nodes")), g.close_inner()); } } // Instantiating needs device memory of its own; on a card filled to the limit it can be refused. That refusal is not sticky and @@ -206,7 +191,10 @@ impl<'ctx> OriginalGpuStream<'ctx> { &g.api, |a| { if injected_window_oom(policy) { - return Err(Error::Driver { operation: "cuGraphInstantiateWithFlags", code: CUDA_ERROR_OUT_OF_MEMORY }); + return Err(Error::Driver { + operation: "cuGraphInstantiateWithFlags", + code: CUDA_ERROR_OUT_OF_MEMORY, + }); } a.instantiate(graph) }, @@ -217,7 +205,9 @@ impl<'ctx> OriginalGpuStream<'ctx> { Err(primary) => { capture_timing::add(1, captured.elapsed().as_secs_f64() * 1e3); if is_graph_out_of_memory(&primary) { - eprintln!("leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped"); + eprintln!( + "leleka-serve graph instantiate out of memory ({policy:?}); the context stays usable, the graph is dropped" + ); } return combine(Err(primary), g.close_inner()); } @@ -229,16 +219,15 @@ impl<'ctx> OriginalGpuStream<'ctx> { a.graph_destroy(graph)?; g.graph = None; } - if matches!( - policy, - OriginalCapturePolicy::Mtp | OriginalCapturePolicy::VerifierWindow - ) { + if matches!(policy, OriginalCapturePolicy::Mtp | OriginalCapturePolicy::VerifierWindow) { let upload = a.upload(g.exec.ok_or(Error::ContextPoisoned)?, h); // The upload only warms the graph up (the first launch would do it): running out of memory there costs the warm-up, // not the engine (upstream 2a9a67c1). let upload = match upload { Err(e) if is_graph_out_of_memory(&e) => { - eprintln!("leleka-serve graph upload out of memory ({policy:?}); skipped, the first launch uploads"); + eprintln!( + "leleka-serve graph upload out of memory ({policy:?}); skipped, the first launch uploads" + ); Ok(()) } other => other, @@ -256,10 +245,7 @@ impl<'ctx> OriginalGpuStream<'ctx> { } pub fn synchronize_with_receipt(&self) -> Result> { self.synchronize()?; - Ok(OriginalStreamDrained { - stream: self.inner.clone(), - sequence: self.inner.sequence.get(), - }) + Ok(OriginalStreamDrained { stream: self.inner.clone(), sequence: self.inner.sequence.get() }) } pub fn close(self) -> Result<()> { if Rc::strong_count(&self.inner) != 1 { diff --git a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgraphkey.rs b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgraphkey.rs index d87b8f02..5629d6e8 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/impl_originalgraphkey.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/impl_originalgraphkey.rs @@ -6,9 +6,7 @@ use super::*; impl OriginalGraphKey { pub(super) fn validate(self) -> Result<()> { let valid = match self { - Self::LayerPre(l) | Self::LayerPost(l) | Self::LayerPreA(l) | Self::LayerPreB(l) => { - l < 48 - } + Self::LayerPre(l) | Self::LayerPost(l) | Self::LayerPreA(l) | Self::LayerPreB(l) => l < 48, Self::LayerPrefix { layer, stages } => layer < 48 && (1..=5).contains(&stages), Self::Token | Self::VerifyCommit => true, Self::VerifyWindow(t) => (1..=8).contains(&t), @@ -16,19 +14,13 @@ impl OriginalGraphKey { Self::MtpStep { step, .. } => (1..=6).contains(&step), Self::Registry { tokens, .. } => tokens > 0, }; - if valid { - Ok(()) - } else { - Err(Error::InvalidQwenShape) - } + if valid { Ok(()) } else { Err(Error::InvalidQwenShape) } } pub(super) fn policy(self) -> OriginalCapturePolicy { match self { Self::VerifyWindow(_) => OriginalCapturePolicy::VerifierWindow, Self::VerifyCommit => OriginalCapturePolicy::VerifierCommit, - Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } => { - OriginalCapturePolicy::Mtp - } + Self::MtpPrefill { .. } | Self::MtpRound { .. } | Self::MtpStep { .. } => OriginalCapturePolicy::Mtp, Self::Registry { .. } => OriginalCapturePolicy::Registry, _ => OriginalCapturePolicy::Session, } @@ -39,36 +31,23 @@ impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { healthy(context)?; Self::planned_metadata_bytes(capacity)?; let mut entries = Vec::new(); - entries - .try_reserve_exact(capacity) - .map_err(|_| Error::HostAllocation)?; + entries.try_reserve_exact(capacity).map_err(|_| Error::HostAllocation)?; if entries .capacity() - .checked_mul(std::mem::size_of::<( - OriginalGraphKey, - OriginalGpuGraph<'ctx, R>, - )>()) + .checked_mul(std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>()) .and_then(|n| n.checked_add(std::mem::size_of::())) .is_none_or(|n| n > 16 * 1024 * 1024) { return Err(Error::BudgetExceeded); } - Ok(Self { - context, - entries, - capacity, - captures: 0, - }) + Ok(Self { context, entries, capacity, captures: 0 }) } pub fn planned_metadata_bytes(capacity: usize) -> Result { if !(1..=512).contains(&capacity) { return Err(Error::InvalidQwenShape); } let bytes = capacity - .checked_mul(std::mem::size_of::<( - OriginalGraphKey, - OriginalGpuGraph<'ctx, R>, - )>()) + .checked_mul(std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>()) .and_then(|n| n.checked_add(std::mem::size_of::())) .ok_or(Error::BudgetExceeded)?; if bytes > 16 * 1024 * 1024 { @@ -77,8 +56,7 @@ impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { Ok(bytes) } pub fn metadata_bytes(&self) -> usize { - self.entries.capacity() - * std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>() + self.entries.capacity() * std::mem::size_of::<(OriginalGraphKey, OriginalGpuGraph<'ctx, R>)>() + std::mem::size_of::() } pub fn captures(&self) -> u64 { @@ -90,17 +68,10 @@ impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { pub fn is_empty(&self) -> bool { self.entries.is_empty() } - pub fn find_mut( - &mut self, - key: OriginalGraphKey, - ) -> Result>> { + pub fn find_mut(&mut self, key: OriginalGraphKey) -> Result>> { key.validate()?; healthy(self.context)?; - Ok(self - .entries - .iter_mut() - .find(|(k, _)| *k == key) - .map(|(_, g)| g)) + Ok(self.entries.iter_mut().find(|(k, _)| *k == key).map(|(_, g)| g)) } pub fn record( &mut self, @@ -117,10 +88,7 @@ impl<'ctx, R: OriginalGraphResources> OriginalGraphRegistry<'ctx, R> { if self.entries.len() == self.capacity { return Err(Error::BudgetExceeded); } - let captures = self - .captures - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let captures = self.captures.checked_add(1).ok_or(Error::InvalidQwenShape)?; let graph = stream.capture_owned(key.policy(), prepare()?, body)?; let index = self.entries.len(); self.entries.push((key, graph)); diff --git a/crates/cuda-driver/src/original_gpu_schedule/set_side_streams_wanted_fn.rs b/crates/cuda-driver/src/original_gpu_schedule/set_side_streams_wanted_fn.rs index 25097b34..5fb778df 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/set_side_streams_wanted_fn.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/set_side_streams_wanted_fn.rs @@ -102,11 +102,7 @@ impl<'ctx> OriginalGpuEvent<'ctx> { if s.inner.capture.get() { return Err(Error::InvalidQwenShape); } - if self - .source - .as_ref() - .is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) - { + if self.source.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &s.inner)) { return Err(Error::ContextMismatch); } let e = self.handle()?; @@ -126,17 +122,8 @@ impl<'ctx> OriginalGpuEvent<'ctx> { let e = self.handle()?; let h = s.inner.validate()?; let _sequence = s.inner.bump()?; - if !self - .waiters - .iter() - .flatten() - .any(|x| Rc::ptr_eq(x, &s.inner)) - { - let index = self - .waiters - .iter() - .position(Option::is_none) - .ok_or(Error::BudgetExceeded)?; + if !self.waiters.iter().flatten().any(|x| Rc::ptr_eq(x, &s.inner)) { + let index = self.waiters.iter().position(Option::is_none).ok_or(Error::BudgetExceeded)?; self.waiters[index] = Some(s.inner.clone()); } call(self.context, &self.api, |a| a.stream_wait(h, e)) @@ -183,11 +170,7 @@ impl<'ctx> OriginalGpuEvent<'ctx> { return Err(Error::ContextPoisoned); } let r = call(self.context, &self.api, |a| { - let mut op = if self.recorded { - a.event_sync(e) - } else { - Ok(()) - }; + let mut op = if self.recorded { a.event_sync(e) } else { Ok(()) }; for s in self.waiters.iter().flatten() { op = combine(op, a.stream_sync(s.validate()?)); } diff --git a/crates/cuda-driver/src/original_gpu_schedule/transport_fn.rs b/crates/cuda-driver/src/original_gpu_schedule/transport_fn.rs index 4e657a97..95722104 100644 --- a/crates/cuda-driver/src/original_gpu_schedule/transport_fn.rs +++ b/crates/cuda-driver/src/original_gpu_schedule/transport_fn.rs @@ -15,11 +15,7 @@ pub(super) fn poison(c: &Context<'_>) { c.retain_driver(); } pub(super) fn healthy(c: &Context<'_>) -> Result<()> { - if c.is_poisoned() || c.handle.is_none() { - Err(Error::ContextPoisoned) - } else { - Ok(()) - } + if c.is_poisoned() || c.handle.is_none() { Err(Error::ContextPoisoned) } else { Ok(()) } } /// A graph instantiate (or upload) that ran out of device memory. Recoverable: the call did not run, no state changed, and the /// driver returns the memory-allocation error without a sticky error (upstream a8c1d4b7 / 2a9a67c1: their engine died on it). @@ -38,7 +34,12 @@ pub(super) fn call(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) call_unless(c, api, f, |_| false) } /// `call`, except that an error `recoverable` accepts does not poison the context (the caller undoes what it did and goes on). -pub(super) fn call_unless(c: &Context<'_>, api: &abi::Api, f: impl FnOnce(&abi::Api) -> Result, recoverable: fn(&Error) -> bool) -> Result { +pub(super) fn call_unless( + c: &Context<'_>, + api: &abi::Api, + f: impl FnOnce(&abi::Api) -> Result, + recoverable: fn(&Error) -> bool, +) -> Result { healthy(c)?; let guard = c.enter().inspect_err(|_| poison(c))?; let op = f(api); @@ -56,16 +57,14 @@ pub(super) fn injected_window_oom(policy: OriginalCapturePolicy) -> bool { if policy != OriginalCapturePolicy::VerifierWindow { return false; } - let at = *AT.get_or_init(|| std::env::var("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); + let at = *AT.get_or_init(|| { + std::env::var("LELEKA_TEST_WINDOW_INSTANTIATE_OOM_AT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0) + }); at != 0 && SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1 == at } impl Stream<'_> { pub(super) fn bump(&self) -> Result { - let next = self - .sequence - .get() - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let next = self.sequence.get().checked_add(1).ok_or(Error::InvalidQwenShape)?; self.sequence.set(next); Ok(next) } @@ -152,10 +151,8 @@ impl Context<'_> { pub fn original_gpu_stream(&self, kind: OriginalStreamKind) -> Result> { healthy(self)?; let api = Rc::new(abi::Api::load()?); - let h = call(self, &api, |a| { - a.stream_create(kind == OriginalStreamKind::NonBlocking) - }) - .inspect_err(|_| std::mem::forget(api.clone()))?; + let h = call(self, &api, |a| a.stream_create(kind == OriginalStreamKind::NonBlocking)) + .inspect_err(|_| std::mem::forget(api.clone()))?; Ok(OriginalGpuStream { inner: Rc::new(Stream { context: self, @@ -170,10 +167,8 @@ impl Context<'_> { pub fn original_gpu_event(&self, kind: OriginalEventKind) -> Result> { healthy(self)?; let api = Rc::new(abi::Api::load()?); - let h = call(self, &api, |a| { - a.event_create(kind == OriginalEventKind::Timing) - }) - .inspect_err(|_| std::mem::forget(api.clone()))?; + let h = call(self, &api, |a| a.event_create(kind == OriginalEventKind::Timing)) + .inspect_err(|_| std::mem::forget(api.clone()))?; Ok(OriginalGpuEvent { context: self, api, diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs index 5f150ee6..3580931c 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi.rs @@ -1,17 +1,9 @@ //! Private CUDA Driver ABI, matching Original runtime stream/event/graph calls. use crate::{Error, Result}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_gpu_schedule_ffi/platform.rs"] mod platform; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use platform::Api; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs index 8068b053..c5f334c4 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform.rs @@ -21,7 +21,8 @@ type GraphStream = unsafe extern "C" fn(Handle, Handle) -> i32; type CopyH2d = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32; type HostFn = unsafe extern "C" fn(*mut c_void); /// `cuMemcpyBatchAsync_v2` (CUDA 12.8+/13): dsts, srcs, sizes, count, attrs, attrsIdxs, numAttrs, stream. -type CopyBatch = unsafe extern "C" fn(*mut u64, *mut u64, *mut usize, usize, *mut BatchAttributes, *mut usize, usize, Handle) -> i32; +type CopyBatch = + unsafe extern "C" fn(*mut u64, *mut u64, *mut usize, usize, *mut BatchAttributes, *mut usize, usize, Handle) -> i32; /// `cuStreamWriteValue32_v2`: stream, device address, value, flags. type WriteValue = unsafe extern "C" fn(Handle, u64, u32, u32) -> i32; /// `CUmemcpyAttributes`: srcAccessOrder, srcLocHint {type, id}, dstLocHint {type, id}, flags. @@ -72,16 +73,16 @@ pub(crate) struct Api { #[path = "platform/impl_drop_for_library.rs"] mod impl_drop_for_library; -#[allow(unused_imports)] -use impl_drop_for_library::check; -#[allow(unused_imports)] -use impl_drop_for_library::raise_after_copies; -#[cfg(target_os = "linux")] -#[allow(unused_imports)] -use impl_drop_for_library::noop_host_fn; #[cfg(target_os = "linux")] #[allow(unused_imports)] use impl_drop_for_library::callback_warmup_enabled; +#[allow(unused_imports)] +use impl_drop_for_library::check; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +use impl_drop_for_library::noop_host_fn; +#[allow(unused_imports)] +use impl_drop_for_library::raise_after_copies; #[path = "platform/impl_api.rs"] mod impl_api; #[path = "platform/impl_api_2.rs"] diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs index bf27ce28..6cf44a76 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api.rs @@ -6,9 +6,7 @@ use super::*; impl Api { pub(crate) fn load() -> Result { // SAFETY: fixed NUL-terminated library name and flags. - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -16,9 +14,7 @@ impl Api { // SAFETY: live dlopen handle and a NUL-terminated static symbol name. let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; if p.is_null() { - Err(Error::MissingSymbol( - n.to_str().unwrap_or("Original schedule symbol"), - )) + Err(Error::MissingSymbol(n.to_str().unwrap_or("Original schedule symbol"))) } else { Ok(p) } @@ -72,9 +68,7 @@ impl Api { pub(crate) fn stream_create(&self, nonblocking: bool) -> Result { let mut s = std::ptr::null_mut(); // SAFETY: valid out pointer; the caller's Context is entered. - check("cuStreamCreate", unsafe { - (self.create)(&mut s, u32::from(nonblocking)) - })?; + check("cuStreamCreate", unsafe { (self.create)(&mut s, u32::from(nonblocking)) })?; if s.is_null() { return Err(Error::InvalidDriverValue("cuStreamCreate")); } @@ -99,9 +93,13 @@ impl Api { // SAFETY: C ABI call on the live handle; no host memory is passed. let synced = if launched == 0 { unsafe { (self.sync)(s) } } else { launched }; if synced == 0 { - eprintln!("leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)"); + eprintln!( + "leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)" + ); } else { - eprintln!("leleka-serve: could not warm up the GPU host-callback thread (driver code {synced}); continuing"); + eprintln!( + "leleka-serve: could not warm up the GPU host-callback thread (driver code {synced}); continuing" + ); } } #[cfg(not(target_os = "linux"))] @@ -118,32 +116,22 @@ impl Api { pub(crate) fn stream_query(&self, s: usize) -> Result { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. let q = unsafe { (self.query)(s as Handle) }; - if q == 600 { - Ok(false) - } else { - check("cuStreamQuery", q).map(|()| true) - } + if q == 600 { Ok(false) } else { check("cuStreamQuery", q).map(|()| true) } } pub(crate) fn stream_priority(&self, s: usize) -> Result { let mut p = 0; // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuStreamGetPriority", unsafe { - (self.priority)(s as Handle, &mut p) - })?; + check("cuStreamGetPriority", unsafe { (self.priority)(s as Handle, &mut p) })?; Ok(p) } pub(crate) fn stream_wait(&self, s: usize, e: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuStreamWaitEvent", unsafe { - (self.wait)(s as Handle, e as Handle, 0) - }) + check("cuStreamWaitEvent", unsafe { (self.wait)(s as Handle, e as Handle, 0) }) } pub(crate) fn event_create(&self, timing: bool) -> Result { let mut e = std::ptr::null_mut(); // SAFETY: valid out pointer; flags select timing / DISABLE_TIMING. - check("cuEventCreate", unsafe { - (self.event_create)(&mut e, if timing { 0 } else { 2 }) - })?; + check("cuEventCreate", unsafe { (self.event_create)(&mut e, if timing { 0 } else { 2 }) })?; if e.is_null() { return Err(Error::InvalidDriverValue("cuEventCreate")); } @@ -151,37 +139,25 @@ impl Api { } pub(crate) fn event_destroy(&self, e: usize) -> Result<()> { // SAFETY: event created through this Api; destroyed once by `OriginalGpuEvent::close_inner` after it (and its waiter streams) were synchronized. - check("cuEventDestroy_v2", unsafe { - (self.event_destroy)(e as Handle) - }) + check("cuEventDestroy_v2", unsafe { (self.event_destroy)(e as Handle) }) } pub(crate) fn event_record(&self, e: usize, s: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuEventRecord", unsafe { - (self.event_record)(e as Handle, s as Handle) - }) + check("cuEventRecord", unsafe { (self.event_record)(e as Handle, s as Handle) }) } pub(crate) fn event_query(&self, e: usize) -> Result { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. let q = unsafe { (self.event_query)(e as Handle) }; - if q == 600 { - Ok(false) - } else { - check("cuEventQuery", q).map(|()| true) - } + if q == 600 { Ok(false) } else { check("cuEventQuery", q).map(|()| true) } } pub(crate) fn event_sync(&self, e: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { - (self.event_sync)(e as Handle) - })) + crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe { (self.event_sync)(e as Handle) })) } pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result { let mut ms = 0.; // SAFETY: valid out pointer; both events were created with timing enabled and recorded (checked by the caller). - check("cuEventElapsedTime", unsafe { - (self.elapsed)(&mut ms, a as Handle, b as Handle) - })?; + check("cuEventElapsedTime", unsafe { (self.elapsed)(&mut ms, a as Handle, b as Handle) })?; if !ms.is_finite() || ms < 0. { return Err(Error::InvalidDriverValue("cuEventElapsedTime")); } @@ -189,16 +165,12 @@ impl Api { } pub(crate) fn begin(&self, s: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuStreamBeginCapture_v2", unsafe { - (self.begin)(s as Handle, 1) - }) + check("cuStreamBeginCapture_v2", unsafe { (self.begin)(s as Handle, 1) }) } // ThreadLocal pub(crate) fn end(&self, s: usize) -> Result { let mut g = std::ptr::null_mut(); // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuStreamEndCapture", unsafe { - (self.end)(s as Handle, &mut g) - })?; + check("cuStreamEndCapture", unsafe { (self.end)(s as Handle, &mut g) })?; if g.is_null() { return Err(Error::InvalidDriverValue("cuStreamEndCapture")); } @@ -207,17 +179,13 @@ impl Api { pub(crate) fn nodes(&self, g: usize) -> Result { let mut n = 0; // SAFETY: live graph; a null node array with a valid count out pointer only queries the count. - check("cuGraphGetNodes", unsafe { - (self.nodes)(g as Handle, std::ptr::null_mut(), &mut n) - })?; + check("cuGraphGetNodes", unsafe { (self.nodes)(g as Handle, std::ptr::null_mut(), &mut n) })?; Ok(n) } pub(crate) fn instantiate(&self, g: usize) -> Result { let mut e = std::ptr::null_mut(); // SAFETY: C ABI call on a live handle; the out pointer is a valid local. - check("cuGraphInstantiateWithFlags", unsafe { - (self.instantiate)(&mut e, g as Handle, 0) - })?; + check("cuGraphInstantiateWithFlags", unsafe { (self.instantiate)(&mut e, g as Handle, 0) })?; if e.is_null() { return Err(Error::InvalidDriverValue("cuGraphInstantiateWithFlags")); } @@ -225,26 +193,18 @@ impl Api { } pub(crate) fn graph_destroy(&self, g: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuGraphDestroy", unsafe { - (self.graph_destroy)(g as Handle) - }) + check("cuGraphDestroy", unsafe { (self.graph_destroy)(g as Handle) }) } pub(crate) fn exec_destroy(&self, e: usize) -> Result<()> { // SAFETY: executable created through this Api; destroyed once by `OriginalGpuGraph::close_inner` after its stream was drained. - check("cuGraphExecDestroy", unsafe { - (self.exec_destroy)(e as Handle) - }) + check("cuGraphExecDestroy", unsafe { (self.exec_destroy)(e as Handle) }) } pub(crate) fn upload(&self, e: usize, s: usize) -> Result<()> { // SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed. - check("cuGraphUpload", unsafe { - (self.upload)(e as Handle, s as Handle) - }) + check("cuGraphUpload", unsafe { (self.upload)(e as Handle, s as Handle) }) } pub(crate) fn launch(&self, e: usize, s: usize) -> Result<()> { // SAFETY: live executable and stream; the graph's resources (`R`: device/mapped owners) are retained by `OriginalGpuGraph` until drained. - check("cuGraphLaunch", unsafe { - (self.launch)(e as Handle, s as Handle) - }) + check("cuGraphLaunch", unsafe { (self.launch)(e as Handle, s as Handle) }) } } diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs index 4ce69e1c..af3c8997 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_api_2.rs @@ -9,15 +9,15 @@ impl Api { pub(crate) fn copy_h2d(&self, dst: u64, src: &[u8], s: usize) -> Result<()> { // SAFETY: `dst` is a validated device range; `src` is a registered bank slice the caller keeps alive and registered // until this stream's next fence (documented contract of `enqueue_copy_h2d`). - check("cuMemcpyHtoDAsync_v2", unsafe { - (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) - }) + check("cuMemcpyHtoDAsync_v2", unsafe { (self.copy_h2d)(dst, src.as_ptr().cast(), src.len(), s as Handle) }) } /// Every `(destination, source)` piece of a group in stream order: one `cuMemcpyBatchAsync` when `batch` and the /// driver has it, else one `cuMemcpyHtoDAsync` per piece. The caller keeps every source (a registered bank) and /// destination alive until the stream's fence. pub(crate) fn copy_h2d_many(&self, pieces: &[(u64, &[u8])], s: usize, batch: bool) -> Result<()> { - if let (true, Some(f), false) = (batch, self.copy_batch, self.batch_refused.load(std::sync::atomic::Ordering::Relaxed)) { + if let (true, Some(f), false) = + (batch, self.copy_batch, self.batch_refused.load(std::sync::atomic::Ordering::Relaxed)) + { let mut dsts: Vec = pieces.iter().map(|p| p.0).collect(); let mut srcs: Vec = pieces.iter().map(|p| p.1.as_ptr() as u64).collect(); let mut sizes: Vec = pieces.iter().map(|p| p.1.len()).collect(); @@ -27,7 +27,16 @@ impl Api { // SAFETY: `dsts/srcs/sizes/attr/index` are locals alive across the call and consumed by the driver during it (CUDA copies the // descriptor arrays); `count`/`numAttrs` match; the source bytes stay retained by the caller until the stream fence (srcAccessOrder STREAM). let code = unsafe { - f(dsts.as_mut_ptr(), srcs.as_mut_ptr(), sizes.as_mut_ptr(), pieces.len(), &mut attr, &mut index, 1, s as Handle) + f( + dsts.as_mut_ptr(), + srcs.as_mut_ptr(), + sizes.as_mut_ptr(), + pieces.len(), + &mut attr, + &mut index, + 1, + s as Handle, + ) }; if code == 0 { return Ok(()); @@ -55,7 +64,9 @@ impl Api { /// refusal) the host callback raising the mapped host word. pub(crate) fn raise_flag_after(&self, s: usize, host_word: usize, device_address: u64, value: u32) -> Result<()> { use std::sync::atomic::Ordering::Relaxed; - if let (Some(f), false, true) = (self.write_value, self.write_refused.load(Relaxed), device_address != 0 && device_address % 4 == 0) { + if let (Some(f), false, true) = + (self.write_value, self.write_refused.load(Relaxed), device_address != 0 && device_address % 4 == 0) + { // SAFETY: as `write_u32_after`; the alias is non-null and 4-byte aligned (checked in the condition). if unsafe { f(s as Handle, device_address, value, 0) } == 0 { return Ok(()); @@ -73,9 +84,8 @@ impl Api { let data = Box::into_raw(Box::new(Raise { word, value })); // SAFETY: `data` is a leaked `Box` owned by the callback from here on (reclaimed there, or below if the launch is refused); // `word` is a live 4-byte-aligned mapped host word whose owner synchronizes the Context before freeing it. - let launched = check("cuLaunchHostFunc", unsafe { - (self.host_fn)(s as Handle, raise_after_copies, data.cast()) - }); + let launched = + check("cuLaunchHostFunc", unsafe { (self.host_fn)(s as Handle, raise_after_copies, data.cast()) }); if launched.is_err() { // SAFETY: the driver refused the launch, so the callback will never take this Box. drop(unsafe { Box::from_raw(data) }); diff --git a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs index 0355569a..05c6f102 100644 --- a/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs +++ b/crates/cuda-driver/src/original_gpu_schedule_ffi/platform/impl_drop_for_library.rs @@ -14,14 +14,7 @@ impl Drop for Library { } } pub(super) fn check(name: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: name, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code: n }) } } /// `cudaLaunchHostFunc` body of `Verifier::fetch_dma`: `raise_flag(flag, value)` (only rises). pub(super) unsafe extern "C" fn raise_after_copies(data: *mut c_void) { diff --git a/crates/cuda-driver/src/original_gpu_verify_bridge.rs b/crates/cuda-driver/src/original_gpu_verify_bridge.rs index fd8cb214..cacae23b 100644 --- a/crates/cuda-driver/src/original_gpu_verify_bridge.rs +++ b/crates/cuda-driver/src/original_gpu_verify_bridge.rs @@ -3,9 +3,7 @@ use super::*; use crate::original_verify::OriginalVerifyGraphResources; use crate::{NativeHeadSampling, NativeHeadSelection, OriginalNativeHeadGraphResources}; -impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> - OriginalGpuGraph<'ctx, R> -{ +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R> { pub fn verifier_head_after_drain( &mut self, stream: &mut OriginalGpuStream<'ctx>, @@ -15,10 +13,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour self.validate()?; stream.validate_context(self.context)?; if !self.launched - || !self - .last - .as_ref() - .is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) + || !self.last.as_ref().is_some_and(|s| Rc::ptr_eq(s, &stream.inner)) || !Rc::ptr_eq(&stream.inner, &done.stream) || done.sequence < self.last_sequence { @@ -31,11 +26,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour if rows.len() != r.native_head_rows()?.rows() * geometry.vocabulary * 4 { return Err(Error::InvalidQwenShape); } - r.verifier_journal().validate_completed_logits( - stream, - rows, - rows.len() / (geometry.vocabulary * 4), - )?; + r.verifier_journal().validate_completed_logits(stream, rows, rows.len() / (geometry.vocabulary * 4))?; self.resources .as_mut() .ok_or(Error::ContextPoisoned)? @@ -44,22 +35,12 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour } } -impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> - OriginalGpuGraph<'ctx, R> -{ +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalGpuGraph<'ctx, R> { pub(crate) fn verifier_uses_ple(&self) -> Result { self.validate()?; - Ok(self - .resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .verifier_journal() - .has_ple()) + Ok(self.resources.as_ref().ok_or(Error::ContextPoisoned)?.verifier_journal().has_ple()) } - pub(crate) fn verifier_begin_window( - &self, - bank: &crate::OriginalVerifyBank<'ctx>, - ) -> Result<()> { + pub(crate) fn verifier_begin_window(&self, bank: &crate::OriginalVerifyBank<'ctx>) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); @@ -74,10 +55,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour } Ok(()) } - pub(crate) fn verifier_complete_commit( - &self, - bank: &crate::OriginalVerifyBank<'ctx>, - ) -> Result<()> { + pub(crate) fn verifier_complete_commit(&self, bank: &crate::OriginalVerifyBank<'ctx>) -> Result<()> { self.validate()?; if self.launched { return Err(Error::InvalidQwenShape); @@ -100,10 +78,6 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour if self.launched || self.last.is_none() || self.last_sequence == 0 { return Err(Error::InvalidQwenShape); } - self.resources - .as_ref() - .ok_or(Error::ContextPoisoned)? - .native_head_rows()? - .completed_logits() + self.resources.as_ref().ok_or(Error::ContextPoisoned)?.native_head_rows()?.completed_logits() } } diff --git a/crates/cuda-driver/src/original_moe_prompt_device.rs b/crates/cuda-driver/src/original_moe_prompt_device.rs index 09696311..b360de68 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device.rs @@ -7,9 +7,8 @@ use crate::ffi::BufferHandle; use crate::original_prefill_arena::OriginalPromptSpan as S; use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule}; use crate::{ - Context, DeviceBuffer, Error, GdnNativeFormat, MappedExpertBank, MmqFormat, MmqWorkspace, - NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalPromptRows, - PrefillPhase, Result, combine, + Context, DeviceBuffer, Error, GdnNativeFormat, MappedExpertBank, MmqFormat, MmqWorkspace, NativeBatchWorkspace, + OriginalDeviceBlock, OriginalDeviceGrRead, OriginalPromptRows, PrefillPhase, Result, combine, }; use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use std::ffi::CStr; @@ -76,14 +75,14 @@ mod blank_fn; #[allow(unused_imports)] use blank_fn::blank; #[allow(unused_imports)] -use blank_fn::kernel; -#[allow(unused_imports)] -use blank_fn::gemm; -#[allow(unused_imports)] -use blank_fn::phase; -#[allow(unused_imports)] use blank_fn::common; #[allow(unused_imports)] use blank_fn::dequant_index; -mod impl_originalmoepromptdevice; +#[allow(unused_imports)] +use blank_fn::gemm; +#[allow(unused_imports)] +use blank_fn::kernel; +#[allow(unused_imports)] +use blank_fn::phase; mod impl_drop_for_originalmoepromptdevice; +mod impl_originalmoepromptdevice; diff --git a/crates/cuda-driver/src/original_moe_prompt_device/blank_fn.rs b/crates/cuda-driver/src/original_moe_prompt_device/blank_fn.rs index 8e819bf7..2155505a 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/blank_fn.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/blank_fn.rs @@ -51,19 +51,11 @@ pub(super) fn gemm( } pub(super) fn phase(rows: &OriginalPromptRows<'_, '_, '_>, name: &str, width: usize) -> Result { let (h, n) = rows.span(PrefillPhase::Moe, name)?; - h.checked_subspan( - n, - 0, - rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?, - ) + h.checked_subspan(n, 0, rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?) } pub(super) fn common(rows: &OriginalPromptRows<'_, '_, '_>, role: S, width: usize) -> Result { let (h, n) = rows.common_span(role)?; - h.checked_subspan( - n, - 0, - rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?, - ) + h.checked_subspan(n, 0, rows.rows().checked_mul(width).ok_or(Error::InvalidSize)?) } pub(super) fn dequant_index(format: GdnNativeFormat) -> usize { match format { @@ -76,10 +68,7 @@ pub(super) fn dequant_index(format: GdnNativeFormat) -> usize { } } impl<'ctx> Context<'ctx> { - pub fn original_moe_prompt_device( - &'ctx self, - capacity: usize, - ) -> Result> { + pub fn original_moe_prompt_device(&'ctx self, capacity: usize) -> Result> { OriginalMoePromptDevice::new(self, capacity) } } diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs index 14d50430..3a791cd8 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_drop_for_originalmoepromptdevice.rs @@ -19,17 +19,11 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo &self.counts } pub fn metadata_bytes(&self) -> Result { - [ - self.order.capacity(), - self.counts.capacity(), - self.source_rows.capacity(), - self.slot_map.capacity(), - ] - .into_iter() - .try_fold(std::mem::size_of::(), |n, c| { - n.checked_add(c.checked_mul(4).ok_or(Error::BudgetExceeded)?) - .ok_or(Error::BudgetExceeded) - }) + [self.order.capacity(), self.counts.capacity(), self.source_rows.capacity(), self.slot_map.capacity()] + .into_iter() + .try_fold(std::mem::size_of::(), |n, c| { + n.checked_add(c.checked_mul(4).ok_or(Error::BudgetExceeded)?).ok_or(Error::BudgetExceeded) + }) } /// Same moved read is retained through both copy/compute drains and the /// caller's one final shared/combine finish. @@ -54,11 +48,8 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo } } self.upload_slot_table()?; - let mut program = workspace.prepare_original_expert_layer_device( - &self.read, - &self.counts, - &self.source_rows, - )?; + let mut program = + workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?; program.execute_original_copy_ring(&self.read, layer, schedule, bank, formats, sources)?; program.finish()?; self.completed_experts = self.order.len(); @@ -83,20 +74,12 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo return Err(Error::InvalidQwenShape); } } - let mut program = workspace.prepare_original_expert_layer_device( - &self.read, - &self.counts, - &self.source_rows, - )?; + let mut program = + workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?; for group in (0..self.order.len()).step_by(16) { let end = (group + 16).min(self.order.len()); for index in group..end { - if !program.stage_expert_from_prompt_cache( - &self.read, - layer, - self.order[index] as usize, - formats, - )? { + if !program.stage_expert_from_prompt_cache(&self.read, layer, self.order[index] as usize, formats)? { program.stage_expert_retained(formats, bank, &sources[index])?; } } @@ -188,19 +171,9 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo if self.completed_experts != 0 { return Err(Error::InvalidQwenShape); } - let mut program = workspace.prepare_original_expert_layer_device( - &self.read, - &self.counts, - &self.source_rows, - )?; - program.execute_original_stream_all( - &self.read, - forward, - layer, - &self.order, - formats, - host_allowance, - )?; + let mut program = + workspace.prepare_original_expert_layer_device(&self.read, &self.counts, &self.source_rows)?; + program.execute_original_stream_all(&self.read, forward, layer, &self.order, formats, host_allowance)?; program.finish()?; self.completed_experts = self.order.len(); Ok(()) diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs index 053ed653..5240b358 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMoePromptDevice<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>, capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { @@ -15,23 +14,13 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { if context.is_poisoned() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(wanted) - .is_none_or(|n| n > context.budget_bytes()) + if context.allocated_bytes().checked_add(wanted).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < wanted { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - capacity, - status: None, - scratch: None, - moe: None, - dequant: None, - failed: false, - }; + let mut owner = + Self { context, capacity, status: None, scratch: None, moe: None, dequant: None, failed: false }; let operation = (|| { owner.status = Some(context.allocate(STATUS)?); owner.scratch = Some(context.allocate(SCRATCH)?); @@ -49,8 +38,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { Ok(owner) } pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.scratch.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len) + self.scratch.as_ref().map_or(0, DeviceBuffer::len) } pub(in super::super) fn handle(&self, buffer: &Option>, amount: usize) -> Result { if self.failed || self.context.is_poisoned() { @@ -60,9 +48,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { if b.bytes < amount || !std::ptr::eq(b.context, self.context) { return Err(Error::InvalidQwenShape); } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, 0, amount) + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, 0, amount) } pub(in super::super) fn weight( &self, @@ -72,10 +58,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { amount: usize, ) -> Result { if buffer.bytes != amount { - return Err(Error::ShapeMismatch { - expected: amount, - actual: buffer.bytes, - }); + return Err(Error::ShapeMismatch { expected: amount, actual: buffer.bytes }); } if !std::ptr::eq(buffer.context, self.context) { return Err(Error::ContextMismatch); @@ -90,10 +73,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { } // Every MoE scratch role can alias another phase; actual source weights // are separate whole owners and must overlap none of this phase's spans. - for name in [ - "logits", "w", "ids", "slot_dev", "src_dev", "GU", "Dm", "sgate", "sup", "sh_h", - "shared", "sg", - ] { + for name in ["logits", "w", "ids", "slot_dev", "src_dev", "GU", "Dm", "sgate", "sup", "sh_h", "shared", "sg"] { let (a, n) = rows.span(PrefillPhase::Moe, name)?; if h.overlaps(amount, a, n) { return Err(Error::OutputAliasesInput); @@ -115,9 +95,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { half: bool, slot: usize, ) -> Result<()> { - let status = self - .handle(&self.status, STATUS)? - .checked_subspan(STATUS, slot * 4, 4)?; + let status = self.handle(&self.status, STATUS)?.checked_subspan(STATUS, slot * 4, 4)?; kernel( commands, false, @@ -151,31 +129,11 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { break; } operation = match command { - Command::Kernel { - dequant, - index, - grid, - args, - } => { + Command::Kernel { dequant, index, grid, args } => { let module = if *dequant { &self.dequant } else { &self.moe }; - module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - *index, - *grid, - 256, - blas.stream(), - args, - ) + module.as_ref().ok_or(Error::ContextPoisoned)?.launch(*index, *grid, 256, blas.stream(), args) } - Command::Gemm { - bf16, - input, - weight, - output, - t, - n, - k, - beta, - } => { + Command::Gemm { bf16, input, weight, output, t, n, k, beta } => { if *bf16 { blas.gemm_bf16(*input, *weight, *output, *t, *n, *k, &1.0, beta) } else { @@ -209,12 +167,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { } } for (slot, label) in labels.iter().enumerate() { - if u32::from_le_bytes( - got[slot * 4..slot * 4 + 4] - .try_into() - .map_err(|_| Error::InvalidSize)?, - ) != 0 - { + if u32::from_le_bytes(got[slot * 4..slot * 4 + 4].try_into().map_err(|_| Error::InvalidSize)?) != 0 { return Err(Error::NonFiniteMmqOutput(label)); } } diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs index 281d449a..29134905 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMoePromptDevice<'ctx> { /// Weights are the actual router, shared scalar gate, shared gate/up/down. /// Runtime authenticates their binding/role; driver admits their whole owners. @@ -23,11 +22,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { workspace.validate_context(self.context)?; let high = common(rows, S::MixedHigh, 5120)?; let half = common(rows, S::MixedHalf, 5120)?; - let low_image = if low { - Some(common(rows, S::MixedLow, 5120)?) - } else { - None - }; + let low_image = if low { Some(common(rows, S::MixedLow, 5120)?) } else { None }; let logits = phase(rows, "logits", 512 * 4)?; let ids = phase(rows, "ids", 10 * 4)?; let w = phase(rows, "w", 10 * 4)?; @@ -40,22 +35,13 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { let scalar = self.weight(rows, workspace, weights[1], 2560 * 2)?; let dims = [(640, 2560), (640, 2560), (2560, 640)]; let mut native = Vec::new(); - native - .try_reserve_exact(3) - .map_err(|_| Error::HostAllocation)?; + native.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; for (index, (n, k)) in dims.iter().copied().enumerate() { - native.push(self.weight( - rows, - workspace, - weights[index + 2], - formats[index].matrix_bytes(n, k)?, - )?); + native.push(self.weight(rows, workspace, weights[index + 2], formats[index].matrix_bytes(n, k)?)?); } let scratch = self.handle(&self.scratch, SCRATCH)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(32) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; self.scan(&mut commands, half, t * 2560, true, 0)?; gemm(&mut commands, true, high, router, logits, t, 512, 2560, 0.0)?; if let Some(lo) = low_image { @@ -67,12 +53,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { dequant: false, index: 4, grid: t.div_ceil(8) as u32, - args: KernelArguments::new(vec![ - A::Address(logits), - A::Address(ids), - A::Address(w), - A::I64(t as i64), - ]), + args: KernelArguments::new(vec![A::Address(logits), A::Address(ids), A::Address(w), A::I64(t as i64)]), }); self.scan(&mut commands, w, t * 10, false, 2)?; for index in 0..3 { @@ -92,17 +73,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { A::Address(scratch), ], )?; - gemm( - &mut commands, - false, - if index == 2 { h } else { half }, - scratch, - destination, - t, - n, - k, - 0.0, - )?; + gemm(&mut commands, false, if index == 2 { h } else { half }, scratch, destination, t, n, k, 0.0)?; self.scan(&mut commands, destination, t * n, false, [3, 4, 6][index])?; if index == 1 { kernel( @@ -110,12 +81,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { false, 5, t * 640, - vec![ - A::Address(gate), - A::Address(up), - A::Address(h), - A::I64(t as i64), - ], + vec![A::Address(gate), A::Address(up), A::Address(h), A::I64(t as i64)], )?; self.scan(&mut commands, h, t * 640, true, 5)?; } @@ -174,14 +140,10 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { } let mut cursor = offsets; let mut source_rows = Vec::new(); - source_rows - .try_reserve_exact(t * 10) - .map_err(|_| Error::HostAllocation)?; + source_rows.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; source_rows.resize(t * 10, 0); let mut slot_map = Vec::new(); - slot_map - .try_reserve_exact(t * 10) - .map_err(|_| Error::HostAllocation)?; + slot_map.try_reserve_exact(t * 10).map_err(|_| Error::HostAllocation)?; for (i, word) in raw.as_chunks::<4>().0.iter().enumerate() { let id = i32::from_le_bytes(*word) as usize; let p = cursor[id]; @@ -191,12 +153,8 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> { } let mut order = Vec::new(); let mut actual_counts = Vec::new(); - order - .try_reserve_exact(512) - .map_err(|_| Error::HostAllocation)?; - actual_counts - .try_reserve_exact(512) - .map_err(|_| Error::HostAllocation)?; + order.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; + actual_counts.try_reserve_exact(512).map_err(|_| Error::HostAllocation)?; for (id, count) in counts.iter().copied().enumerate() { if count > 0 { order.push(id as u32); diff --git a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs index 62fbfe04..89390659 100644 --- a/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs +++ b/crates/cuda-driver/src/original_moe_prompt_device/impl_originalmoepromptdevice/impl_originalmoepromptdevice_3.rs @@ -3,14 +3,9 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalMoePromptDevice<'ctx> { pub(in super::super) fn close_inner(&mut self) -> Result<()> { - if self.status.is_none() - && self.scratch.is_none() - && self.moe.is_none() - && self.dequant.is_none() - { + if self.status.is_none() && self.scratch.is_none() && self.moe.is_none() && self.dequant.is_none() { return Ok(()); } if self.context.is_poisoned() { diff --git a/crates/cuda-driver/src/original_mtp_actor.rs b/crates/cuda-driver/src/original_mtp_actor.rs index ea0f4977..511525e9 100644 --- a/crates/cuda-driver/src/original_mtp_actor.rs +++ b/crates/cuda-driver/src/original_mtp_actor.rs @@ -21,21 +21,12 @@ //! There is no reset(): conversation resume is `kv_restore` on the retained //! state. This is not a numerical, serving or device-completion certificate. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "original_mtp_actor_loaded.rs"] mod loaded; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub use loaded::{OriginalMtpActor, OriginalMtpLoadEvidence, OriginalMtpLoadMeter}; - /// Original `load` default. It becomes an effective window only after actual /// geometry/KV admission; storing this number does not select a ring. pub const DEFAULT_WINDOW: i64 = 32768; @@ -61,10 +52,7 @@ pub struct DraftSettings { impl Default for DraftSettings { fn default() -> Self { - Self { - prompt_len: 0, - max_drafts: DEFAULT_MAX_DRAFTS, - } + Self { prompt_len: 0, max_drafts: DEFAULT_MAX_DRAFTS } } } @@ -113,11 +101,7 @@ pub fn chain_end_within_cells(continuation_end: i32, draft_cell: usize, max_cell } pub fn validate_max_t(max_t: i32) -> ActorResult<()> { - if (1..=VERIFY_MAX_T).contains(&max_t) { - Ok(()) - } else { - Err(ActorRefusal::MaxTOutOfRange) - } + if (1..=VERIFY_MAX_T).contains(&max_t) { Ok(()) } else { Err(ActorRefusal::MaxTOutOfRange) } } /// Exact destructor slots of `~MtpDrafter`, in order. The loaded actor's diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded.rs b/crates/cuda-driver/src/original_mtp_actor_loaded.rs index ab70a467..740254bb 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded.rs @@ -20,9 +20,9 @@ use crate::original_mtp_coupled::{ use crate::original_mtp_draft_head::OriginalMtpDraftHead; use crate::original_mtp_loader::{CoupledPlan, KvPlan, OriginalMtpLoadPlan}; use crate::{ - CompletedOriginalMtpDraft, Context, Error, MtpInt8Snapshot, MtpOriginalInt8, - NativeHeadSelection, OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, - OriginalVerifyWindow, Result, SamplerParams, + CompletedOriginalMtpDraft, Context, Error, MtpInt8Snapshot, MtpOriginalInt8, NativeHeadSelection, + OriginalMtpDrafter, OriginalMtpFullPolicy, OriginalMtpRetainedFullWeights, OriginalVerifyWindow, Result, + SamplerParams, }; use std::rc::Rc; @@ -66,7 +66,7 @@ mod inconsistent_fn; use inconsistent_fn::inconsistent; #[allow(unused_imports)] use inconsistent_fn::mismatch; -#[path = "original_mtp_actor_loaded/impl_originalmtpactor.rs"] -mod impl_originalmtpactor; #[path = "original_mtp_actor_loaded/impl_drop_for_originalmtpactor.rs"] mod impl_drop_for_originalmtpactor; +#[path = "original_mtp_actor_loaded/impl_originalmtpactor.rs"] +mod impl_originalmtpactor; diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs index a4a0095f..7508e6f2 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalMtpActor<'ctx> { /// End of `MtpDrafter::load` + `bind`: take ownership of the assembled /// drafter and verify, against the owners themselves, every fact the plan @@ -47,8 +45,7 @@ impl<'ctx> OriginalMtpActor<'ctx> { ring: &MtpOriginalInt8<'ctx>, weights: &OriginalMtpRetainedFullWeights<'ctx>, evidence: OriginalMtpLoadEvidence, - ) -> std::result::Result<(KvPlan, SetupDisposition, CoupledDraftHost), OriginalMtpLoadFailure> - { + ) -> std::result::Result<(KvPlan, SetupDisposition, CoupledDraftHost), OriginalMtpLoadFailure> { let capture = *plan.capture(); drafter.validate_context(context).map_err(inconsistent)?; ring.validate_context(context).map_err(inconsistent)?; @@ -58,9 +55,7 @@ impl<'ctx> OriginalMtpActor<'ctx> { } // `cudaGetDevice` at load: capture, context and ledger must agree. if context.device_ordinal() != capture.device || evidence.device != capture.device { - return Err(mismatch( - "the drafter's device differs from the captured one", - )); + return Err(mismatch("the drafter's device differs from the captured one")); } if weights.id_vocabulary() as u64 != capture.vocabulary { return Err(mismatch("the draft vocabulary differs from output.weight")); @@ -81,31 +76,23 @@ impl<'ctx> OriginalMtpActor<'ctx> { let mut preference = CoupledPreference::from_observed_env(None); preference.set(capture.coupled_requested); let disposition = setup_disposition(&preference, capture.vocabulary as usize, subset); - let planned = plan - .coupled(subset.map(|n| n as u64)) - .map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; + let planned = + plan.coupled(subset.map(|n| n as u64)).map_err(|e| OriginalMtpLoadFailure::new(e.message(), None))?; let expected = match planned { CoupledPlan::Off => SetupDisposition::Disabled, CoupledPlan::ArgmaxVocabularyTooWide => SetupDisposition::ArgmaxFallback, CoupledPlan::Allocate { .. } => SetupDisposition::NeedsActualDeviceSetup, }; let layout_coupled = drafter.loaded_coupled().map_err(inconsistent)?; - if disposition != expected - || layout_coupled != (disposition == SetupDisposition::NeedsActualDeviceSetup) - { - return Err(mismatch( - "the coupled resources do not match the setup plan", - )); + if disposition != expected || layout_coupled != (disposition == SetupDisposition::NeedsActualDeviceSetup) { + return Err(mismatch("the coupled resources do not match the setup plan")); } let mut host = CoupledDraftHost::unselected(); if disposition == SetupDisposition::NeedsActualDeviceSetup { // setup_coupled ends with cudaDeviceSynchronize before coupled_ok. - context.synchronize().map_err(|e| { - OriginalMtpLoadFailure::new( - "mtp: coupled setup: device synchronize failed", - Some(e), - ) - })?; + context + .synchronize() + .map_err(|e| OriginalMtpLoadFailure::new("mtp: coupled setup: device synchronize failed", Some(e)))?; let receipt = CoupledSetupReceipt::after_setup(disposition, layout_coupled, true) .ok_or_else(|| mismatch("the coupled setup receipt was not issued"))?; host.arm(receipt); @@ -152,15 +139,10 @@ impl<'ctx> OriginalMtpActor<'ctx> { return Err(Error::ContextMismatch); } self.weights.validate_context(c)?; - self.drafter - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate_context(c) + self.drafter.as_ref().ok_or(Error::ContextPoisoned)?.validate_context(c) } pub fn is_failed(&self) -> bool { - self.drafter - .as_ref() - .is_none_or(OriginalMtpDrafter::is_failed) + self.drafter.as_ref().is_none_or(OriginalMtpDrafter::is_failed) } /// stderr line of `load`, for the operator log. pub fn load_report(&self) -> String { @@ -176,12 +158,8 @@ impl<'ctx> OriginalMtpActor<'ctx> { line.push_str(&format!("; draft head over {n} tokens")); } match self.disposition { - SetupDisposition::NeedsActualDeviceSetup => { - line.push_str("; coupled draft sampling on") - } - SetupDisposition::ArgmaxFallback => { - line.push_str("; coupled sampler too wide, argmax drafts") - } + SetupDisposition::NeedsActualDeviceSetup => line.push_str("; coupled draft sampling on"), + SetupDisposition::ArgmaxFallback => line.push_str("; coupled sampler too wide, argmax drafts"), SetupDisposition::Disabled => {} } line @@ -189,10 +167,7 @@ impl<'ctx> OriginalMtpActor<'ctx> { /// `idle()`: synchronize the capture stream (`cs_`) and nothing else. pub fn idle(&mut self) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .idle_public() + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.idle_public() } /// Scalar draft K/V prefill on the actor's own scalar owner (short prompts; see `OriginalMtpDrafter::record_scalar_prefill`). @@ -211,32 +186,30 @@ impl<'ctx> OriginalMtpActor<'ctx> { cancelled: impl FnMut() -> bool, ) -> Result { self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.record_scalar_prefill( - residual, workspace, ring, prior, tokens, cell0, first_needed, retained, policy, cancelled, + residual, + workspace, + ring, + prior, + tokens, + cell0, + first_needed, + retained, + policy, + cancelled, ) } /// Release everything the drafter bound to the verifier bank of the request that just ended (see /// `OriginalMtpDrafter::release_verifier_bindings`). Call it before the verifier is closed. pub fn release_verifier_bindings(&mut self) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .release_verifier_bindings() + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.release_verifier_bindings() } /// `kv_restore(upto)`: refill the draft ring's window for a sequence that /// continues at `upto` from the host pages `prior` authenticates. A no-op /// when the ring is fully resident, exactly as in Original. - pub fn kv_restore( - &mut self, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - upto: i64, - ) -> Result<()> { - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .resume_public_kv(ring, prior, upto) + pub fn kv_restore(&mut self, ring: &mut MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot, upto: i64) -> Result<()> { + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.resume_public_kv(ring, prior, upto) } /// `coupled()`. @@ -250,8 +223,6 @@ impl<'ctx> OriginalMtpActor<'ctx> { /// `set_draft_history`: `tail` is what the session holds after the commit, /// `next` the window's pick at the last accepted row. pub fn set_draft_history(&mut self, tail: &[i32], next: i32) -> Result<()> { - self.coupled - .set_draft_history(tail, next) - .map_err(|_| Error::InvalidQwenShape) + self.coupled.set_draft_history(tail, next).map_err(|_| Error::InvalidQwenShape) } } diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs index a7b63789..edc33546 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/impl_originalmtpactor/impl_originalmtpactor_2_2.rs @@ -3,14 +3,9 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> OriginalMtpActor<'ctx> { - pub(in super::super) fn staged_coupled(&self) -> Option<(SamplerParams, Box<[i32; 4096]>)> { - self.coupled - .staged_host_values() - .map(|(p, h)| (*p, Box::new(*h))) + self.coupled.staged_host_values().map(|(p, h)| (*p, Box::new(*h))) } /// `draft(T, tokens, p, a, drafts, ...)` over a completed verifier window. @@ -29,20 +24,17 @@ impl<'ctx> OriginalMtpActor<'ctx> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let max_drafts = self.settings.max_drafts(); - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_from_verifier( - ring, - prior, - window, - selection, - accepted_row, - max_drafts, - min_probability, - policy, - coupled, - ) + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_from_verifier( + ring, + prior, + window, + selection, + accepted_row, + max_drafts, + min_probability, + policy, + coupled, + ) } /// `draft_from_verifier` split around the host's work (`OriginalMtpDrafter::launch_from_verifier`); `after` is the @@ -100,20 +92,17 @@ impl<'ctx> OriginalMtpActor<'ctx> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let max_drafts = self.settings.max_drafts(); - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_first_from_verifier( - ring, - prior, - window, - selection, - rows, - max_drafts, - min_probability, - policy, - coupled, - ) + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_from_verifier( + ring, + prior, + window, + selection, + rows, + max_drafts, + min_probability, + policy, + coupled, + ) } /// Public array form of `draft` (`drafts`/`probs` out-arguments). @@ -133,22 +122,19 @@ impl<'ctx> OriginalMtpActor<'ctx> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let settings = self.settings; - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_public( - ring, - prior, - window, - selection, - accepted_row, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_public( + ring, + prior, + window, + selection, + accepted_row, + &settings, + min_probability, + policy, + coupled, + drafts, + probabilities, + ) } /// Public array form of `draft_first`. @@ -168,22 +154,19 @@ impl<'ctx> OriginalMtpActor<'ctx> { let staged = self.staged_coupled(); let coupled = staged.as_ref().map(|(p, h)| (*p, &**h)); let settings = self.settings; - self.drafter - .as_mut() - .ok_or(Error::ContextPoisoned)? - .draft_first_public( - ring, - prior, - window, - selection, - rows, - &settings, - min_probability, - policy, - coupled, - drafts, - probabilities, - ) + self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.draft_first_public( + ring, + prior, + window, + selection, + rows, + &settings, + min_probability, + policy, + coupled, + drafts, + probabilities, + ) } /// `~MtpDrafter()`: stream drain, graphs and owners via the drafter's @@ -193,8 +176,6 @@ impl<'ctx> OriginalMtpActor<'ctx> { } pub(in super::super) fn close_inner(&mut self) -> Result<()> { self.coupled.close(); - self.drafter - .take() - .map_or(Ok(()), OriginalMtpDrafter::close) + self.drafter.take().map_or(Ok(()), OriginalMtpDrafter::close) } } diff --git a/crates/cuda-driver/src/original_mtp_actor_loaded/inconsistent_fn.rs b/crates/cuda-driver/src/original_mtp_actor_loaded/inconsistent_fn.rs index c991abf4..42885ca0 100644 --- a/crates/cuda-driver/src/original_mtp_actor_loaded/inconsistent_fn.rs +++ b/crates/cuda-driver/src/original_mtp_actor_loaded/inconsistent_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn inconsistent(cause: Error) -> OriginalMtpLoadFailure { OriginalMtpLoadFailure::new("mtp: the loaded owners are inconsistent", Some(cause)) } @@ -12,10 +11,7 @@ pub(super) fn mismatch(what: &'static str) -> OriginalMtpLoadFailure { } impl OriginalMtpLoadMeter { pub fn start(context: &Context<'_>) -> Self { - Self { - allocated: context.allocated_bytes(), - device: context.device_ordinal(), - } + Self { allocated: context.allocated_bytes(), device: context.device_ordinal() } } pub fn finish<'ctx>( self, @@ -31,9 +27,7 @@ impl OriginalMtpLoadMeter { .checked_sub(self.allocated) .filter(|_| context.device_ordinal() == self.device) .ok_or_else(|| mismatch("the load ledger is not monotonic on its device"))?; - let vram = (vram as u64) - .checked_add(preloaded_bytes) - .ok_or_else(|| mismatch("the load ledger overflows"))?; + let vram = (vram as u64).checked_add(preloaded_bytes).ok_or_else(|| mismatch("the load ledger overflows"))?; Ok(OriginalMtpLoadEvidence { vram_bytes: vram, device: self.device, diff --git a/crates/cuda-driver/src/original_mtp_bank.rs b/crates/cuda-driver/src/original_mtp_bank.rs index 61339150..4f6634ba 100644 --- a/crates/cuda-driver/src/original_mtp_bank.rs +++ b/crates/cuda-driver/src/original_mtp_bank.rs @@ -37,10 +37,7 @@ pub struct OriginalMtpLoadFailure { } impl OriginalMtpLoadFailure { pub(crate) fn new(message: impl Into, cause: Option) -> Self { - Self { - message: message.into(), - cause, - } + Self { message: message.into(), cause } } pub fn message(&self) -> &str { &self.message @@ -118,14 +115,8 @@ impl<'ctx> OriginalMtpRtBank<'ctx> { &self.tensors } /// `f32()/bf16()/q8()`: the tensor with this name and exactly this kind. - pub fn tensor( - &self, - name: &str, - kind: OriginalMtpTensorKind, - ) -> Option<&OriginalMtpRtTensor<'ctx>> { - self.tensors - .iter() - .find(|t| t.entry.name == name && t.entry.kind == kind) + pub fn tensor(&self, name: &str, kind: OriginalMtpTensorKind) -> Option<&OriginalMtpRtTensor<'ctx>> { + self.tensors.iter().find(|t| t.entry.name == name && t.entry.kind == kind) } pub fn experts(&self) -> Rc> { Rc::clone(&self.experts) @@ -154,11 +145,7 @@ impl<'ctx> OriginalMtpRtBank<'ctx> { .map(|t| &*t.buffer) .chain(std::iter::once(&*self.experts)) .all(|b| std::ptr::eq(b.context, c)); - if owned { - Ok(()) - } else { - Err(Error::ContextMismatch) - } + if owned { Ok(()) } else { Err(Error::ContextMismatch) } } } @@ -174,10 +161,7 @@ impl<'ctx> Context<'ctx> { n_expert: usize, ) -> Result, OriginalMtpLoadFailure> { if self.is_poisoned() { - return Err(OriginalMtpLoadFailure::new( - "mtp: the CUDA context is poisoned", - Some(Error::ContextPoisoned), - )); + return Err(OriginalMtpLoadFailure::new("mtp: the CUDA context is poisoned", Some(Error::ContextPoisoned))); } if n_expert == 0 { return Err(LoaderError::Geometry.into()); @@ -189,30 +173,19 @@ impl<'ctx> Context<'ctx> { index.validate_finite(&blob)?; let plan = WeightBankPlan::new(blob.len() as u64, n_expert as u64)?; let need = usize::try_from(plan.device_bytes).map_err(|_| LoaderError::Overflow)?; - if self - .allocated_bytes() - .checked_add(need) - .is_none_or(|total| total > self.budget_bytes()) - { + if self.allocated_bytes().checked_add(need).is_none_or(|total| total > self.budget_bytes()) { return Err(self.dense_failure(blob.len(), Error::BudgetExceeded)); } let mut tensors = Vec::new(); - tensors - .try_reserve_exact(index.tensors().len()) - .map_err(|_| RtError::Host)?; + tensors.try_reserve_exact(index.tensors().len()).map_err(|_| RtError::Host)?; for entry in index.tensors() { let bytes = index.slice(entry, &blob)?; - let mut buffer = self - .allocate(bytes.len()) - .map_err(|e| self.dense_failure(blob.len(), e))?; - buffer.copy_from(bytes).map_err(|e| { - OriginalMtpLoadFailure::new("mtp: dense weights upload failed", Some(e)) - })?; - tensors.push(OriginalMtpRtTensor { - entry: entry.clone(), - buffer: Rc::new(buffer), - }); + let mut buffer = self.allocate(bytes.len()).map_err(|e| self.dense_failure(blob.len(), e))?; + buffer + .copy_from(bytes) + .map_err(|e| OriginalMtpLoadFailure::new("mtp: dense weights upload failed", Some(e)))?; + tensors.push(OriginalMtpRtTensor { entry: entry.clone(), buffer: Rc::new(buffer) }); } // Original frees the host blob at the end of its dense block. drop(blob); @@ -226,10 +199,7 @@ impl<'ctx> Context<'ctx> { EXPERT_READ_BYTES as usize, || -> Result<(), OriginalMtpLoadFailure> { let buffer = self.allocate(size).map_err(|e| { - OriginalMtpLoadFailure::new( - format!("mtp: the {n_expert} experts do not fit in VRAM"), - Some(e), - ) + OriginalMtpLoadFailure::new(format!("mtp: the {n_expert} experts do not fit in VRAM"), Some(e)) })?; *experts.borrow_mut() = Some(buffer); Ok(()) @@ -240,15 +210,12 @@ impl<'ctx> Context<'ctx> { } let mut slot = experts.borrow_mut(); let buffer = slot.as_mut().ok_or_else(|| { - OriginalMtpLoadFailure::new( - "mtp: expert bank is absent", - Some(Error::ContextPoisoned), - ) + OriginalMtpLoadFailure::new("mtp: expert bank is absent", Some(Error::ContextPoisoned)) })?; let at = usize::try_from(offset).map_err(|_| LoaderError::Overflow)?; - buffer.copy_from_range(at, chunk).map_err(|e| { - OriginalMtpLoadFailure::new("mtp: experts.bin upload failed", Some(e)) - }) + buffer + .copy_from_range(at, chunk) + .map_err(|e| OriginalMtpLoadFailure::new("mtp: experts.bin upload failed", Some(e))) }, ); match streamed { @@ -258,9 +225,9 @@ impl<'ctx> Context<'ctx> { } // Original checks the nine names only after both banks exist. index.check_required(REQUIRED_Q8_NAMES)?; - let experts = experts.into_inner().ok_or_else(|| { - OriginalMtpLoadFailure::new("mtp: expert bank is absent", Some(Error::ContextPoisoned)) - })?; + let experts = experts + .into_inner() + .ok_or_else(|| OriginalMtpLoadFailure::new("mtp: expert bank is absent", Some(Error::ContextPoisoned)))?; Ok(OriginalMtpRtBank { context: self, directory: directory.to_owned(), diff --git a/crates/cuda-driver/src/original_mtp_bank_gpu.rs b/crates/cuda-driver/src/original_mtp_bank_gpu.rs index 24caa237..2369bb27 100644 --- a/crates/cuda-driver/src/original_mtp_bank_gpu.rs +++ b/crates/cuda-driver/src/original_mtp_bank_gpu.rs @@ -38,58 +38,32 @@ fn rt_bank_places_every_tensor_and_the_expert_chunks_exactly() { let index = rt::DenseIndex::parse(&text).unwrap(); let tensor_bytes: usize = index.tensors().iter().map(|t| t.bytes as usize).sum(); assert!(tensor_bytes < blob.len(), "the fixture must contain alignment padding"); - assert_eq!( - context.allocated_bytes() - baseline, - tensor_bytes + experts.len() - ); + assert_eq!(context.allocated_bytes() - baseline, tensor_bytes + experts.len()); assert_eq!(bank.expert_count(), 3); bank.validate_context(&context).unwrap(); assert_eq!(read(&bank.experts()), experts); for entry in index.tensors() { let tensor = bank.tensor(&entry.name, entry.kind).expect(&entry.name); - assert_eq!( - (tensor.rows() as u64, tensor.columns() as u64), - (entry.rows, entry.columns) - ); - assert_eq!( - read(&tensor.buffer()), - index.slice(entry, &blob).unwrap(), - "{}", - entry.name - ); + assert_eq!((tensor.rows() as u64, tensor.columns() as u64), (entry.rows, entry.columns)); + assert_eq!(read(&tensor.buffer()), index.slice(entry, &blob).unwrap(), "{}", entry.name); } // kind is part of the lookup: the q8 tensor is not a bf16 one - assert!( - bank.tensor("fc_hidden.weight", OriginalMtpTensorKind::Bf16) - .is_none() - ); + assert!(bank.tensor("fc_hidden.weight", OriginalMtpTensorKind::Bf16).is_none()); drop(bank); assert_eq!(context.allocated_bytes(), baseline); // Original order: the nine-name check is LAST, after both banks were placed // (so a missing name leaves no allocation behind once the failure drops). - let missing: String = text - .lines() - .filter(|l| !l.starts_with("self_attn.v_proj.weight ")) - .map(|l| format!("{l}\n")) - .collect(); + let missing: String = + text.lines().filter(|l| !l.starts_with("self_attn.v_proj.weight ")).map(|l| format!("{l}\n")).collect(); fx::write(&dir, "dense.txt", missing.as_bytes()); - let error = context - .original_mtp_rt_bank(&dir.0, 3) - .err() - .expect("missing name"); - assert_eq!( - error.message(), - "mtp: self_attn.v_proj.weight is missing (q8_0)" - ); + let error = context.original_mtp_rt_bank(&dir.0, 3).err().expect("missing name"); + assert_eq!(error.message(), "mtp: self_attn.v_proj.weight is missing (q8_0)"); assert_eq!(context.allocated_bytes(), baseline); // truncated experts are found only after the dense bank was uploaded fx::write(&dir, "dense.txt", text.as_bytes()); fx::write(&dir, "experts.bin", &experts[..experts.len() - 1]); - let error = context - .original_mtp_rt_bank(&dir.0, 3) - .err() - .expect("truncated"); + let error = context.original_mtp_rt_bank(&dir.0, 3).err().expect("truncated"); assert_eq!(error.message(), "mtp: experts.bin is truncated"); assert_eq!(context.allocated_bytes(), baseline); // an Inf scale half in the second chunk refuses before the checks run @@ -98,31 +72,17 @@ fn rt_bank_places_every_tensor_and_the_expert_chunks_exactly() { bad[at] = 0x00; bad[at + 1] = 0x7c; fx::write(&dir, "experts.bin", &bad); - let error = context - .original_mtp_rt_bank(&dir.0, 3) - .err() - .expect("non-finite"); + let error = context.original_mtp_rt_bank(&dir.0, 3).err().expect("non-finite"); assert!(error.message().contains("non-finite"), "{error}"); // the budget refusal plays cudaMalloc's: Original text plus the sizes - let tight = device - .create_context(blob.len() + 16) - .expect("tight context"); + let tight = device.create_context(blob.len() + 16).expect("tight context"); fx::write(&dir, "experts.bin", &experts); let error = tight.original_mtp_rt_bank(&dir.0, 3).err().expect("budget"); - assert!( - error - .message() - .starts_with("mtp: dense weights allocation failed"), - "{error}" - ); + assert!(error.message().starts_with("mtp: dense weights allocation failed"), "{error}"); assert_eq!(tight.allocated_bytes(), 0); } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] #[ignore = "Root-only: needs a CUDA device"] fn draft_head_gather_matches_a_host_gather_for_each_kernel_width() { @@ -138,50 +98,28 @@ fn draft_head_gather_matches_a_host_gather_for_each_kernel_width() { // 64 cols -> 68 B (4-byte kernel), 32 cols -> 34 B (byte kernel). for columns in [2560usize, 64, 32] { let row_bytes = crate::native_head_row_bytes(8, columns).unwrap(); - let host: Vec = (0..vocabulary * row_bytes) - .map(|i| (i * 31 + columns) as u8) - .collect(); + let host: Vec = (0..vocabulary * row_bytes).map(|i| (i * 31 + columns) as u8).collect(); let mut head = context.allocate(host.len()).unwrap(); head.copy_from(&host).unwrap(); // absent file: Original ignores it - assert!( - context - .original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary) - .unwrap() - .is_none() - ); - fx::write( - &dir, - "draft_vocab.bin", - &ids.iter().flat_map(|i| i.to_le_bytes()).collect::>(), - ); - let draft = context - .original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary) - .unwrap() - .expect("subset head"); + assert!(context.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary).unwrap().is_none()); + fx::write(&dir, "draft_vocab.bin", &ids.iter().flat_map(|i| i.to_le_bytes()).collect::>()); + let draft = + context.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary).unwrap().expect("subset head"); assert_eq!((draft.count(), draft.row_bytes()), (ids.len(), row_bytes)); - let expected: Vec = ids - .iter() - .flat_map(|&id| host[id as usize * row_bytes..(id as usize + 1) * row_bytes].to_vec()) - .collect(); + let expected: Vec = + ids.iter().flat_map(|&id| host[id as usize * row_bytes..(id as usize + 1) * row_bytes].to_vec()).collect(); assert_eq!(read(&draft.rows()), expected, "columns {columns}"); - let ids_back: Vec = read(&draft.ids()) - .chunks_exact(4) - .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); + let ids_back: Vec = + read(&draft.ids()).chunks_exact(4).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); assert_eq!(ids_back, ids); - let inverse: Vec = read(&draft.inverse()) - .chunks_exact(4) - .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); + let inverse: Vec = + read(&draft.inverse()).chunks_exact(4).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); assert_eq!(inverse, subset_inverse(vocabulary, &ids).unwrap()); assert_eq!(inverse[3], 1, "first occurrence wins"); // an id outside the vocabulary never reaches the kernel fx::write(&dir, "draft_vocab.bin", &50i32.to_le_bytes()); - let error = context - .original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary) - .err() - .expect("range"); + let error = context.original_mtp_draft_head(&dir.0, &head, 8, columns, vocabulary).err().expect("range"); assert!(error.message().contains("outside the vocabulary")); std::fs::remove_file(dir.0.join("draft_vocab.bin")).unwrap(); } diff --git a/crates/cuda-driver/src/original_mtp_coupled.rs b/crates/cuda-driver/src/original_mtp_coupled.rs index 2f704bcc..c5b9cd43 100644 --- a/crates/cuda-driver/src/original_mtp_coupled.rs +++ b/crates/cuda-driver/src/original_mtp_coupled.rs @@ -33,10 +33,8 @@ use crate::original_sampler::SamplerParams; pub(crate) const HISTORY_CAPACITY: usize = 4096; pub(crate) const MAX_DRAFT_ROWS: usize = 8; pub(crate) const MAX_COUPLED_VOCABULARY: usize = 262_144; -pub(crate) const SETUP_ALLOCATION_ERROR: &str = - "mtp: the coupled draft sampler's buffers do not fit"; -pub(crate) const SETUP_TOKEN_MAP_ERROR: &str = - "mtp: the coupled draft sampler's token map does not fit"; +pub(crate) const SETUP_ALLOCATION_ERROR: &str = "mtp: the coupled draft sampler's buffers do not fit"; +pub(crate) const SETUP_TOKEN_MAP_ERROR: &str = "mtp: the coupled draft sampler's token map does not fit"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum CoupledError { @@ -50,7 +48,9 @@ type PolicyResult = std::result::Result; /// Preference only: original's once-read STRATA_SPEC_COUPLED value is enabled /// for any nonempty C-string other than exactly "0". The explicit CLI setter /// overrides that preference. Neither path certifies loaded device resources. -pub(crate) struct CoupledPreference { enabled: bool } +pub(crate) struct CoupledPreference { + enabled: bool, +} impl CoupledPreference { pub fn from_observed_env(value: Option<&[u8]>) -> Self { let enabled = value.is_some_and(|bytes| { @@ -60,8 +60,12 @@ impl CoupledPreference { }); Self { enabled } } - pub fn set(&mut self, enabled: bool) { self.enabled = enabled; } - pub fn enabled(&self) -> bool { self.enabled } + pub fn set(&mut self, enabled: bool) { + self.enabled = enabled; + } + pub fn enabled(&self) -> bool { + self.enabled + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -73,21 +77,26 @@ pub(crate) enum SetupDisposition { } /// Eligibility only; selected subset width is used when a real subset exists. /// This does not allocate or duplicate loader resource accounting. -pub(crate) fn setup_disposition(preference: &CoupledPreference, - vocabulary: usize, subset: Option) -> SetupDisposition { - if !preference.enabled() { return SetupDisposition::Disabled; } +pub(crate) fn setup_disposition( + preference: &CoupledPreference, + vocabulary: usize, + subset: Option, +) -> SetupDisposition { + if !preference.enabled() { + return SetupDisposition::Disabled; + } let width = subset.unwrap_or(vocabulary); if width == 0 || width > MAX_COUPLED_VOCABULARY { SetupDisposition::ArgmaxFallback - } else { SetupDisposition::NeedsActualDeviceSetup } + } else { + SetupDisposition::NeedsActualDeviceSetup + } } /// Literal valid-domain arithmetic; checked signed overflow is a Rust boundary /// refusal, not a new wraparound position. No window/source authority is minted. pub(crate) fn draft_cell(position: i64, accepted: i32, step: i32) -> PolicyResult { - position.checked_add(i64::from(accepted)) - .and_then(|v| v.checked_add(i64::from(step))) - .ok_or(CoupledError::Overflow) + position.checked_add(i64::from(accepted)).and_then(|v| v.checked_add(i64::from(step))).ok_or(CoupledError::Overflow) } /// Counter is cell+1, NOT the staged params.counter. This includes first-draft /// cell p-1. The CUDA kernel reads actual step_rec[0] on every graph replay. @@ -103,8 +112,7 @@ pub(crate) fn params_at_cell(params: &SamplerParams, cell: i64) -> PolicyResult< Ok(copy) } pub(crate) fn history_length(penalty_last_n: i32) -> usize { - if penalty_last_n <= 0 { 0 } - else { (penalty_last_n as usize).min(HISTORY_CAPACITY) } + if penalty_last_n <= 0 { 0 } else { (penalty_last_n as usize).min(HISTORY_CAPACITY) } } pub(crate) fn history_start(step: usize, history_len: usize) -> PolicyResult { if step >= MAX_DRAFT_ROWS || history_len > HISTORY_CAPACITY { @@ -118,8 +126,12 @@ pub(crate) fn history_start(step: usize, history_len: usize) -> PolicyResult PolicyResult<()> { - if output.len() > HISTORY_CAPACITY { return Err(CoupledError::InvalidGeometry); } - if output.is_empty() { return Ok(()); } + if output.len() > HISTORY_CAPACITY { + return Err(CoupledError::InvalidGeometry); + } + if output.is_empty() { + return Ok(()); + } let available = tail.len().checked_add(1).ok_or(CoupledError::Overflow)?; let take = output.len().min(available); let prefix = output.len() - take; @@ -143,7 +155,10 @@ pub(crate) fn subset_inverse(vocabulary: usize, subset_ids: &[i32]) -> PolicyRes inverse.try_reserve_exact(vocabulary).map_err(|_| CoupledError::HostAllocation)?; inverse.resize(vocabulary, -1); for (index, id) in subset_ids.iter().copied().enumerate() { - if id >= 0 && let Some(slot) = inverse.get_mut(id as usize) && *slot < 0 { + if id >= 0 + && let Some(slot) = inverse.get_mut(id as usize) + && *slot < 0 + { *slot = index as i32; } } @@ -157,13 +172,8 @@ impl CoupledSetupReceipt { /// `layout_coupled`: the retained full-forward layout was built with /// coupled resources. `synchronized`: the `cudaDeviceSynchronize` that ends /// `setup_coupled` completed. Anything else yields no receipt. - pub(crate) fn after_setup( - disposition: SetupDisposition, - layout_coupled: bool, - synchronized: bool, - ) -> Option { - (disposition == SetupDisposition::NeedsActualDeviceSetup && layout_coupled && synchronized) - .then_some(Self(())) + pub(crate) fn after_setup(disposition: SetupDisposition, layout_coupled: bool, synchronized: bool) -> Option { + (disposition == SetupDisposition::NeedsActualDeviceSetup && layout_coupled && synchronized).then_some(Self(())) } } @@ -179,10 +189,14 @@ pub(crate) struct CoupledDraftHost { } impl CoupledDraftHost { pub fn unselected() -> Self { - Self { coupled_ok: false, active: false, params: None, + Self { + coupled_ok: false, + active: false, + params: None, // Plain host storage. Actual mapped owner is zeroed by mapped() // then set to -1 by successful original setup; no such setup here. - history: [0; HISTORY_CAPACITY] } + history: [0; HISTORY_CAPACITY], + } } /// `coupled_ok_ = true`, reachable only with the setup receipt. pub fn arm(&mut self, _receipt: CoupledSetupReceipt) { @@ -193,21 +207,29 @@ impl CoupledDraftHost { } pub fn set_draft_sampling(&mut self, params: &SamplerParams) { self.active = self.coupled_ok && !params.greedy && params.temperature > 0.0; - if !self.active { return; } + if !self.active { + return; + } self.params = Some(*params); self.history.fill(-1); } pub fn set_draft_history(&mut self, tail: &[i32], next: i32) -> PolicyResult<()> { - if !self.active { return Ok(()); } + if !self.active { + return Ok(()); + } let params = self.params.as_ref().ok_or(CoupledError::MissingDeviceOwner)?; let h = history_length(params.penalty_last_n); history_base(tail, next, &mut self.history[HISTORY_CAPACITY - h..]) } - pub fn is_active(&self) -> bool { self.active } + pub fn is_active(&self) -> bool { + self.active + } /// No public mutable storage: when actually integrated, host updates must /// occur only after the previous real captured round has synchronized. pub fn staged_host_values(&self) -> Option<(&SamplerParams, &[i32; HISTORY_CAPACITY])> { - if !self.active { return None; } + if !self.active { + return None; + } self.params.as_ref().map(|params| (params, &self.history)) } pub fn close(&mut self) { @@ -218,7 +240,9 @@ impl CoupledDraftHost { } } impl Drop for CoupledDraftHost { - fn drop(&mut self) { self.close(); } + fn drop(&mut self) { + self.close(); + } } #[cfg(test)] @@ -234,8 +258,7 @@ mod tests { } fn armed() -> CoupledDraftHost { let mut host = CoupledDraftHost::unselected(); - let receipt = CoupledSetupReceipt::after_setup( - SetupDisposition::NeedsActualDeviceSetup, true, true).unwrap(); + let receipt = CoupledSetupReceipt::after_setup(SetupDisposition::NeedsActualDeviceSetup, true, true).unwrap(); host.arm(receipt); host } @@ -243,9 +266,14 @@ mod tests { #[test] fn preference_follows_the_environment_presence_rule() { for (value, enabled) in [ - (None, false), (Some(&b""[..]), false), (Some(&b"0"[..]), false), - (Some(&b"1"[..]), true), (Some(&b"00"[..]), true), (Some(&b"off"[..]), true), - (Some(&b"0\0junk"[..]), false), (Some(&b"\0"[..]), false), + (None, false), + (Some(&b""[..]), false), + (Some(&b"0"[..]), false), + (Some(&b"1"[..]), true), + (Some(&b"00"[..]), true), + (Some(&b"off"[..]), true), + (Some(&b"0\0junk"[..]), false), + (Some(&b"\0"[..]), false), ] { assert_eq!(CoupledPreference::from_observed_env(value).enabled(), enabled, "{value:?}"); } @@ -278,10 +306,7 @@ mod tests { (ArgmaxFallback, true, true, false), (Disabled, true, true, false), ] { - assert_eq!( - CoupledSetupReceipt::after_setup(disposition, coupled_layout, synchronized).is_some(), - minted - ); + assert_eq!(CoupledSetupReceipt::after_setup(disposition, coupled_layout, synchronized).is_some(), minted); } let host = CoupledDraftHost::unselected(); assert!(!host.is_ready()); diff --git a/crates/cuda-driver/src/original_mtp_draft_head.rs b/crates/cuda-driver/src/original_mtp_draft_head.rs index 9f035607..3e5f4882 100644 --- a/crates/cuda-driver/src/original_mtp_draft_head.rs +++ b/crates/cuda-driver/src/original_mtp_draft_head.rs @@ -82,49 +82,31 @@ impl<'ctx> Context<'ctx> { DraftVocab::Subset(ids) => ids, }; rt::validate_subset(&ids, vocabulary)?; - let refuse = |cause: Error| { - OriginalMtpLoadFailure::new("mtp: the draft head does not fit", Some(cause)) - }; + let refuse = |cause: Error| OriginalMtpLoadFailure::new("mtp: the draft head does not fit", Some(cause)); if !crate::native_head_supported(head_kind) { return Err(refuse(Error::UnsupportedQwenOperation)); } let row_bytes = crate::native_head_row_bytes(head_kind, columns).map_err(refuse)?; - let expected = row_bytes - .checked_mul(vocabulary) - .ok_or_else(|| refuse(Error::InvalidSize))?; + let expected = row_bytes.checked_mul(vocabulary).ok_or_else(|| refuse(Error::InvalidSize))?; if !std::ptr::eq(head.context, self) { return Err(refuse(Error::ContextMismatch)); } if head.len() != expected { - return Err(refuse(Error::ShapeMismatch { - expected, - actual: head.len(), - })); + return Err(refuse(Error::ShapeMismatch { expected, actual: head.len() })); } let count = ids.len(); let id_bytes: Vec = ids.iter().flat_map(|id| id.to_le_bytes()).collect(); let mut forward = self.allocate(id_bytes.len()).map_err(refuse)?; - let rows = self - .allocate( - count - .checked_mul(row_bytes) - .ok_or_else(|| refuse(Error::InvalidSize))?, - ) - .map_err(refuse)?; + let rows = + self.allocate(count.checked_mul(row_bytes).ok_or_else(|| refuse(Error::InvalidSize))?).map_err(refuse)?; forward.copy_from(&id_bytes).map_err(refuse)?; self.gather_rows(head, &forward, &rows, row_bytes, count) - .map_err(|cause| { - OriginalMtpLoadFailure::new("mtp: the draft head gather failed", Some(cause)) - })?; + .map_err(|cause| OriginalMtpLoadFailure::new("mtp: the draft head gather failed", Some(cause)))?; // First-occurrence inverse map from the same host list that was uploaded. - let inverse = - subset_inverse(vocabulary, &ids).map_err(|_| refuse(Error::HostAllocation))?; + let inverse = subset_inverse(vocabulary, &ids).map_err(|_| refuse(Error::HostAllocation))?; let inverse_bytes: Vec = inverse.iter().flat_map(|i| i.to_le_bytes()).collect(); let mut inverse_buffer = self.allocate(inverse_bytes.len()).map_err(|cause| { - OriginalMtpLoadFailure::new( - "mtp: the coupled draft sampler's token map does not fit", - Some(cause), - ) + OriginalMtpLoadFailure::new("mtp: the coupled draft sampler's token map does not fit", Some(cause)) })?; inverse_buffer.copy_from(&inverse_bytes).map_err(refuse)?; Ok(Some(OriginalMtpDraftHead { @@ -155,9 +137,8 @@ impl<'ctx> Context<'ctx> { } else { ("verify_gather_rows_1", 1) }; - let address = |b: &DeviceBuffer<'_>| -> Result { - Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) - }; + let address = + |b: &DeviceBuffer<'_>| -> Result { Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) }; let mut command = Command::new( name, [GRID, 1, 1], @@ -175,11 +156,7 @@ impl<'ctx> Context<'ctx> { let operation = (|| { let module = gather_rows_module()?; let launched = module.launch(0, &mut command); - let drained = if launched.is_ok() { - self.driver.api.synchronize() - } else { - Ok(()) - }; + let drained = if launched.is_ok() { self.driver.api.synchronize() } else { Ok(()) }; combine(combine(launched, drained), module.close()) })(); let pop = guard.finish(); diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab.rs b/crates/cuda-driver/src/original_mtp_draft_vocab.rs index 35181fa5..c46dbcd1 100644 --- a/crates/cuda-driver/src/original_mtp_draft_vocab.rs +++ b/crates/cuda-driver/src/original_mtp_draft_vocab.rs @@ -105,12 +105,7 @@ pub(crate) enum Selection { /// The selected file does not exist: use `rt/draft_vocab.bin` and say so. Fallback { requested: String }, /// A checked subset file. - Verified { - label: &'static str, - path: PathBuf, - sha256: &'static str, - bytes: Vec, - }, + Verified { label: &'static str, path: PathBuf, sha256: &'static str, bytes: Vec }, } pub(crate) fn hex(digest: &[u8]) -> String { @@ -127,11 +122,7 @@ pub(crate) fn select(directory: &Path, setting: &Setting) -> Result Result { +pub(crate) fn select_in(directory: &Path, setting: &Setting, table: &[KnownSubset]) -> Result { let (path, wanted) = match setting { Setting::Default => return Ok(Selection::Default), Setting::Named(index) => (directory.join(table[*index].file), Some(*index)), @@ -144,10 +135,7 @@ pub(crate) fn select_in( return Ok(Selection::Fallback { requested }); } Err(error) => { - return Err(refuse( - &path, - &format!("cannot be inspected ({})", error.kind()), - )); + return Err(refuse(&path, &format!("cannot be inspected ({})", error.kind()))); } }; if metadata.file_type().is_symlink() || !metadata.is_file() { @@ -161,15 +149,10 @@ pub(crate) fn select_in( return Err(RtError::DraftVocabTooLarge); } let mut bytes = Vec::new(); - bytes - .try_reserve_exact(length as usize) - .map_err(|_| RtError::Host)?; + bytes.try_reserve_exact(length as usize).map_err(|_| RtError::Host)?; let mut file = fs::File::open(&path).map_err(|_| refuse(&path, "cannot be opened"))?; // one bounded read: a file that grew since the lstat is cut at `length + 1` and refused below - file.by_ref() - .take(length + 1) - .read_to_end(&mut bytes) - .map_err(|_| refuse(&path, "cannot be read"))?; + file.by_ref().take(length + 1).read_to_end(&mut bytes).map_err(|_| refuse(&path, "cannot be read"))?; if bytes.len() as u64 != length { return Err(refuse(&path, "changed while it was read")); } @@ -184,10 +167,7 @@ pub(crate) fn select_in( &format!( "has sha256 {actual}, which is {}; refused", match wanted { - Some(index) => format!( - "not the recorded {} subset {}", - table[index].name, table[index].sha256 - ), + Some(index) => format!("not the recorded {} subset {}", table[index].name, table[index].sha256), None => "none of the recorded subsets (default, en, cyrillic, fr)".to_string(), } ), @@ -197,21 +177,11 @@ pub(crate) fn select_in( // unreachable with a matching digest; kept so a wrong table row cannot pass silently return Err(refuse(&path, "does not hold the recorded number of ids")); } - Ok(Selection::Verified { - label: known.name, - path, - sha256: known.sha256, - bytes, - }) + Ok(Selection::Verified { label: known.name, path, sha256: known.sha256, bytes }) } pub(crate) fn ids_of(bytes: &[u8]) -> Vec { - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|b| i32::from_le_bytes(*b)) - .collect() + bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() } /// The subset the draft head binds, or `None` to take the default file's own reading. @@ -238,15 +208,10 @@ pub(crate) fn probe_bytes(directory: &Path, selection: &Selection) -> Option Option { match selection { Selection::Default => None, - Selection::Fallback { requested } => Some(format!( - "leleka-serve draft-vocab: {ENV} file {requested} not found, FALLBACK to rt/draft_vocab.bin" - )), - Selection::Verified { - label, - path, - sha256, - bytes, - } => Some(format!( + Selection::Fallback { requested } => { + Some(format!("leleka-serve draft-vocab: {ENV} file {requested} not found, FALLBACK to rt/draft_vocab.bin")) + } + Selection::Verified { label, path, sha256, bytes } => Some(format!( "leleka-serve draft-vocab: {ENV} subset={label} ids={} sha256={sha256} file={}", bytes.len() / 4, path.display() diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs b/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs index 0a303102..3c4535fd 100644 --- a/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs +++ b/crates/cuda-driver/src/original_mtp_draft_vocab/tests.rs @@ -14,27 +14,17 @@ fn raw(ids: &[i32]) -> Vec { #[test] fn setting_parses_names_paths_and_the_default_spellings() { for off in [None, Some(""), Some("0"), Some("off"), Some("default")] { - assert_eq!( - Setting::parse(off.map(OsStr::new)), - Setting::Default, - "{off:?}" - ); + assert_eq!(Setting::parse(off.map(OsStr::new)), Setting::Default, "{off:?}"); } assert_eq!(Setting::parse(Some(OsStr::new("en"))), Setting::Named(1)); - assert_eq!( - Setting::parse(Some(OsStr::new("cyrillic"))), - Setting::Named(2) - ); + assert_eq!(Setting::parse(Some(OsStr::new("cyrillic"))), Setting::Named(2)); assert_eq!(Setting::parse(Some(OsStr::new("fr"))), Setting::Named(3)); assert_eq!( Setting::parse(Some(OsStr::new("/data/x/draft_vocab_en.bin"))), Setting::Path(PathBuf::from("/data/x/draft_vocab_en.bin")) ); // case matters: "EN" is a (missing) path, not the English subset - assert_eq!( - Setting::parse(Some(OsStr::new("EN"))), - Setting::Path(PathBuf::from("EN")) - ); + assert_eq!(Setting::parse(Some(OsStr::new("EN"))), Setting::Path(PathBuf::from("EN"))); } #[test] @@ -43,20 +33,10 @@ fn recorded_table_is_consistent() { assert_eq!(KNOWN[0].file, "draft_vocab.bin"); for k in &KNOWN { assert_eq!(k.sha256.len(), 64, "{}", k.name); - assert!( - k.sha256 - .bytes() - .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), - "{}", - k.name - ); + assert!(k.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), "{}", k.name); assert_eq!( k.file, - if k.name == "default" { - "draft_vocab.bin".to_string() - } else { - format!("draft_vocab_{}.bin", k.name) - } + if k.name == "default" { "draft_vocab.bin".to_string() } else { format!("draft_vocab_{}.bin", k.name) } ); assert!(k.ids as u64 <= DRAFT_VOCAB_MAX_IDS); } @@ -65,10 +45,7 @@ fn recorded_table_is_consistent() { digests.dedup(); assert_eq!(digests.len(), KNOWN.len()); // sha256 of the empty input pins the hex spelling used for the comparison - assert_eq!( - hex(&Sha256::digest(b"")), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); + assert_eq!(hex(&Sha256::digest(b"")), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); } #[test] @@ -88,43 +65,22 @@ fn missing_file_falls_back_to_the_default_file_with_a_log_line() { write(&dir, "draft_vocab.bin", &raw(&ids)); for setting in [Setting::Named(1), Setting::Path(dir.0.join("nowhere.bin"))] { let selection = select(&dir.0, &setting).unwrap(); - assert!( - matches!(selection, Selection::Fallback { .. }), - "{setting:?}" - ); + assert!(matches!(selection, Selection::Fallback { .. }), "{setting:?}"); assert!(describe(&selection).unwrap().contains("FALLBACK")); assert_eq!(subset(&selection), None); // the reserve probe and the reader then see rt/draft_vocab.bin assert_eq!(probe_bytes(&dir.0, &selection), Some(12)); } - assert_eq!( - read_draft_vocab_with(&dir.0, &Setting::Named(1)).unwrap(), - DraftVocab::Subset(ids.to_vec()) - ); - assert_eq!( - observed_draft_vocab_bytes_with(&dir.0, &Setting::Named(1)), - Some(12) - ); + assert_eq!(read_draft_vocab_with(&dir.0, &Setting::Named(1)).unwrap(), DraftVocab::Subset(ids.to_vec())); + assert_eq!(observed_draft_vocab_bytes_with(&dir.0, &Setting::Named(1)), Some(12)); } /// A table whose digests belong to synthetic files, so the accepted path runs without the upstream data. fn table_for(default: &[u8], en: &[u8]) -> [KnownSubset; 2] { - let leak = |bytes: &[u8]| -> &'static str { - Box::leak(hex(&Sha256::digest(bytes)).into_boxed_str()) - }; + let leak = |bytes: &[u8]| -> &'static str { Box::leak(hex(&Sha256::digest(bytes)).into_boxed_str()) }; [ - KnownSubset { - name: "default", - file: "draft_vocab.bin", - sha256: leak(default), - ids: default.len() / 4, - }, - KnownSubset { - name: "en", - file: "draft_vocab_en.bin", - sha256: leak(en), - ids: en.len() / 4, - }, + KnownSubset { name: "default", file: "draft_vocab.bin", sha256: leak(default), ids: default.len() / 4 }, + KnownSubset { name: "en", file: "draft_vocab_en.bin", sha256: leak(en), ids: en.len() / 4 }, ] } @@ -138,14 +94,9 @@ fn matching_digest_is_accepted_and_reads_the_selected_ids() { write(&dir, "draft_vocab_en.bin", &en); write(&dir, "elsewhere.bin", &en); let table = table_for(&default, &en); - for setting in [ - Setting::Named(1), - Setting::Path(dir.0.join("elsewhere.bin")), - ] { + for setting in [Setting::Named(1), Setting::Path(dir.0.join("elsewhere.bin"))] { let selection = select_in(&dir.0, &setting, &table).unwrap(); - let Selection::Verified { label, bytes, .. } = &selection else { - panic!("{selection:?}") - }; + let Selection::Verified { label, bytes, .. } = &selection else { panic!("{selection:?}") }; assert_eq!((*label, bytes.len()), ("en", 16)); assert_eq!( crate::original_mtp_rt::read_selected_draft_vocab(&dir.0, &selection).unwrap(), @@ -153,31 +104,14 @@ fn matching_digest_is_accepted_and_reads_the_selected_ids() { ); assert_eq!(probe_bytes(&dir.0, &selection), Some(16)); let line = describe(&selection).unwrap(); - assert!( - line.contains("subset=en") && line.contains("ids=4"), - "{line}" - ); + assert!(line.contains("subset=en") && line.contains("ids=4"), "{line}"); } // the digest of another recorded subset does not satisfy a name: `en` pointing at the default bytes is refused write(&dir, "draft_vocab_en.bin", &default); - assert!(matches!( - select_in(&dir.0, &Setting::Named(1), &table).unwrap_err(), - RtError::DraftVocabSelection(_) - )); + assert!(matches!(select_in(&dir.0, &Setting::Named(1), &table).unwrap_err(), RtError::DraftVocabSelection(_))); // but the same file given as a path is a recorded subset (the default one) - let by_path = select_in( - &dir.0, - &Setting::Path(dir.0.join("draft_vocab_en.bin")), - &table, - ) - .unwrap(); - assert!(matches!( - by_path, - Selection::Verified { - label: "default", - .. - } - )); + let by_path = select_in(&dir.0, &Setting::Path(dir.0.join("draft_vocab_en.bin")), &table).unwrap(); + assert!(matches!(by_path, Selection::Verified { label: "default", .. })); // a changed byte is refused let mut changed = en.clone(); changed[0] ^= 1; @@ -194,9 +128,7 @@ fn wrong_digest_is_refused_for_a_name_and_for_a_path() { let digest = hex(&Sha256::digest(&bytes)); for setting in [Setting::Named(1), Setting::Path(dir.0.join("other.bin"))] { let error = select(&dir.0, &setting).unwrap_err(); - let RtError::DraftVocabSelection(text) = &error else { - panic!("{error:?}") - }; + let RtError::DraftVocabSelection(text) = &error else { panic!("{error:?}") }; assert!(text.contains(&digest), "{text}"); assert!(text.contains("refused"), "{text}"); // the load path surfaces the same refusal and the reserve probe does not claim a size for it @@ -208,17 +140,10 @@ fn wrong_digest_is_refused_for_a_name_and_for_a_path() { #[test] fn malformed_files_are_refused_not_ignored() { let dir = TempDir::new("dv-shape"); - for (name, bytes) in [ - ("empty.bin", &b""[..]), - ("odd.bin", &b"abcdef"[..]), - ("three.bin", &b"abc"[..]), - ] { + for (name, bytes) in [("empty.bin", &b""[..]), ("odd.bin", &b"abcdef"[..]), ("three.bin", &b"abc"[..])] { write(&dir, name, bytes); let error = select(&dir.0, &Setting::Path(dir.0.join(name))).unwrap_err(); - assert!( - matches!(error, RtError::DraftVocabSelection(_)), - "{name}: {error:?}" - ); + assert!(matches!(error, RtError::DraftVocabSelection(_)), "{name}: {error:?}"); } // a directory is not a subset file std::fs::create_dir(dir.0.join("dir.bin")).unwrap(); @@ -226,15 +151,8 @@ fn malformed_files_are_refused_not_ignored() { select(&dir.0, &Setting::Path(dir.0.join("dir.bin"))).unwrap_err(), RtError::DraftVocabSelection(_) )); - write( - &dir, - "huge.bin", - &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], - ); - assert_eq!( - select(&dir.0, &Setting::Path(dir.0.join("huge.bin"))).unwrap_err(), - RtError::DraftVocabTooLarge - ); + write(&dir, "huge.bin", &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4]); + assert_eq!(select(&dir.0, &Setting::Path(dir.0.join("huge.bin"))).unwrap_err(), RtError::DraftVocabTooLarge); } #[cfg(unix)] @@ -273,16 +191,10 @@ fn draft_tokens_round_trip_to_full_ids() { let wide = subset_inverse(vocabulary, &default).unwrap(); let narrow = subset_inverse(vocabulary, &english).unwrap(); for dropped in default.iter().filter(|id| !english.contains(id)) { - assert!( - wide[*dropped as usize] >= 0 && narrow[*dropped as usize] < 0, - "id {dropped}" - ); + assert!(wide[*dropped as usize] >= 0 && narrow[*dropped as usize] < 0, "id {dropped}"); } // an id past the vocabulary is refused before any device gather reads a head row with it - assert_eq!( - validate_subset(&[0, 64], vocabulary), - Err(RtError::DraftVocabOutOfRange) - ); + assert_eq!(validate_subset(&[0, 64], vocabulary), Err(RtError::DraftVocabOutOfRange)); } /// The real upstream files, when `LELEKA_TEST_DRAFT_VOCAB_DIR` names a directory holding `draft_vocab*.bin` @@ -298,32 +210,15 @@ fn recorded_digests_match_the_upstream_files_when_present() { let vocabulary = 248_320usize; let mut lists = Vec::new(); for (index, k) in KNOWN.iter().enumerate() { - let setting = if index == 0 { - Setting::Path(dir.join(k.file)) - } else { - Setting::Named(index) - }; + let setting = if index == 0 { Setting::Path(dir.join(k.file)) } else { Setting::Named(index) }; let selection = select(&dir, &setting).unwrap(); - let Selection::Verified { - label, - sha256, - bytes, - .. - } = &selection - else { - panic!("{} {selection:?}", k.name) - }; + let Selection::Verified { label, sha256, bytes, .. } = &selection else { panic!("{} {selection:?}", k.name) }; assert_eq!((*label, *sha256), (k.name, k.sha256)); let ids = ids_of(bytes); assert_eq!(ids.len(), k.ids); validate_subset(&ids, vocabulary).unwrap(); let inverse = subset_inverse(vocabulary, &ids).unwrap(); - assert_eq!( - inverse.iter().filter(|i| **i >= 0).count(), - ids.len(), - "{}: duplicate ids", - k.name - ); + assert_eq!(inverse.iter().filter(|i| **i >= 0).count(), ids.len(), "{}: duplicate ids", k.name); for (row, &id) in ids.iter().enumerate() { assert_eq!(inverse[id as usize], row as i32); } @@ -331,9 +226,6 @@ fn recorded_digests_match_the_upstream_files_when_present() { } let default: std::collections::HashSet = lists[0].iter().copied().collect(); assert!(lists[1].windows(2).all(|w| w[0] < w[1]), "en is ascending"); - assert!( - lists[1].iter().all(|id| default.contains(id)), - "en is inside the default list" - ); + assert!(lists[1].iter().all(|id| default.contains(id)), "en is inside the default list"); assert_eq!(lists[0].len() - lists[1].len(), 65_774); } diff --git a/crates/cuda-driver/src/original_mtp_loader.rs b/crates/cuda-driver/src/original_mtp_loader.rs index 1df16c63..0bd12d40 100644 --- a/crates/cuda-driver/src/original_mtp_loader.rs +++ b/crates/cuda-driver/src/original_mtp_loader.rs @@ -64,10 +64,18 @@ pub(crate) const LOAD_ORDER: &[&str] = &[ /// Destructor order from mtp.cpp:102–128. Unknown-completion retention must be /// supplied by the Rust driver, rather than pretending a failed drain is done. pub(crate) const RELEASE_ORDER: &[&str] = &[ - "capture stream synchronize", "prefill graph executables", "prefill device arena", - "round/step and coupled graph executables", "coupled params/ring/inverse/scratch", - "coupled mapped params/history", "capture stream", "dense", "experts", - "KV state arena", "scratch arena", "head logits/subset head/subset IDs", + "capture stream synchronize", + "prefill graph executables", + "prefill device arena", + "round/step and coupled graph executables", + "coupled params/ring/inverse/scratch", + "coupled mapped params/history", + "capture stream", + "dense", + "experts", + "KV state arena", + "scratch arena", + "head logits/subset head/subset IDs", "six mapped token/step/position/row/output/probability owners", ]; @@ -82,12 +90,23 @@ pub struct WeightBankPlan { pub expert_host_peak: u64, } #[derive(Debug, Clone, Copy)] -pub struct ReadRange { pub offset: u64, pub bytes: u64 } -pub struct ExpertReads { offset: u64, end: u64 } +pub struct ReadRange { + pub offset: u64, + pub bytes: u64, +} +pub struct ExpertReads { + offset: u64, + end: u64, +} pub(crate) const REQUIRED_Q8_NAMES: &[&str] = &[ - "fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", - "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", - "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", + "fc_embedding.weight", + "fc_hidden.weight", + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight", ]; @@ -95,24 +114,47 @@ pub(crate) const REQUIRED_Q8_NAMES: &[&str] = &[ /// already selected Original startup settings; this plan does not read env vars. #[derive(Debug, Clone, Copy)] pub(crate) struct KvInputs { - pub max_cells: u64, pub max_t: u64, pub requested_window: i64, - pub resident_cells: u64, pub ring_off: bool, pub main_off: bool, - pub heads: u64, pub kv_heads: u64, pub head_dim: u64, pub index_dim: u64, - pub int8: bool, pub hybrid: bool, pub q4: bool, pub int8_rotated: bool, + pub max_cells: u64, + pub max_t: u64, + pub requested_window: i64, + pub resident_cells: u64, + pub ring_off: bool, + pub main_off: bool, + pub heads: u64, + pub kv_heads: u64, + pub head_dim: u64, + pub index_dim: u64, + pub int8: bool, + pub hybrid: bool, + pub q4: bool, + pub int8_rotated: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KvMode { Resident, Streamed, WindowRing } +pub enum KvMode { + Resident, + Streamed, + WindowRing, +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum KvFormat { F16, Int8 { rotated: bool }, Q4 } +pub enum KvFormat { + F16, + Int8 { rotated: bool }, + Q4, +} #[derive(Debug, Clone, Copy)] pub struct KvPlan { - pub mode: KvMode, pub format: KvFormat, - pub pages: u64, pub slots: u64, pub pooled_rows: u64, - pub effective_window: u64, pub attention_capacity: u64, + pub mode: KvMode, + pub format: KvFormat, + pub pages: u64, + pub slots: u64, + pub pooled_rows: u64, + pub effective_window: u64, + pub attention_capacity: u64, pub attention_scratch_floats: u64, pub state_device_allocation: u64, pub authoritative_host_allocation: u64, - pub state_mapped_step_bytes: u64, pub state_mapped_position_bytes: u64, + pub state_mapped_step_bytes: u64, + pub state_mapped_position_bytes: u64, } #[derive(Debug, Clone, Copy)] @@ -120,8 +162,15 @@ pub enum CoupledPlan { Off, /// Literal setup_coupled succeeds without enabling it when scratch==0. ArgmaxVocabularyTooWide, - Allocate { params: u64, ring: u64, scratch: u64, inverse_map: u64, - mapped_params: u64, mapped_history: u64, device_total: u64 }, + Allocate { + params: u64, + ring: u64, + scratch: u64, + inverse_map: u64, + mapped_params: u64, + mapped_history: u64, + device_total: u64, + }, } /// Original bind_bytes is an upper estimate, deliberately distinct from actual @@ -129,9 +178,13 @@ pub enum CoupledPlan { /// otherwise Original ignores it. Existing actual owners add zero new charge. #[derive(Debug, Clone, Copy)] pub(crate) struct BindInputs { - pub max_t: u64, pub vocabulary: u64, pub head_row_bytes: u64, - pub logits_already_owned: bool, pub subset_already_owned: bool, - pub observed_subset_file_bytes: Option, pub coupled_enabled: bool, + pub max_t: u64, + pub vocabulary: u64, + pub head_row_bytes: u64, + pub logits_already_owned: bool, + pub subset_already_owned: bool, + pub observed_subset_file_bytes: Option, + pub coupled_enabled: bool, pub coupled_params_already_owned: bool, } @@ -200,17 +253,17 @@ mod impl_loadererror; #[allow(unused_imports)] use impl_loadererror::add; #[allow(unused_imports)] -use impl_loadererror::mul; -#[allow(unused_imports)] -use impl_loadererror::ceil; -#[allow(unused_imports)] use impl_loadererror::aligned; #[allow(unused_imports)] -pub(crate) use impl_loadererror::mapped_staging; -#[allow(unused_imports)] -pub(crate) use impl_loadererror::coupled_plan; -#[allow(unused_imports)] pub(crate) use impl_loadererror::bind_bytes; #[allow(unused_imports)] +use impl_loadererror::ceil; +#[allow(unused_imports)] +pub(crate) use impl_loadererror::coupled_plan; +#[allow(unused_imports)] +pub(crate) use impl_loadererror::mapped_staging; +#[allow(unused_imports)] +use impl_loadererror::mul; +#[allow(unused_imports)] pub use impl_loadererror::original_mtp_bind_reserve; mod impl_originalmtploadplan; diff --git a/crates/cuda-driver/src/original_mtp_loader/impl_loadererror.rs b/crates/cuda-driver/src/original_mtp_loader/impl_loadererror.rs index 5192be86..b6784c8a 100644 --- a/crates/cuda-driver/src/original_mtp_loader/impl_loadererror.rs +++ b/crates/cuda-driver/src/original_mtp_loader/impl_loadererror.rs @@ -22,7 +22,9 @@ pub(super) fn mul(a: u64, b: u64) -> PlanResult { a.checked_mul(b).ok_or(LoaderError::Overflow) } pub(super) fn ceil(n: u64, d: u64) -> PlanResult { - if d == 0 { return Err(LoaderError::Geometry); } + if d == 0 { + return Err(LoaderError::Geometry); + } Ok(add(n, d - 1)? / d) } pub(super) fn aligned(n: u64, alignment: u64) -> PlanResult { @@ -32,7 +34,8 @@ impl WeightBankPlan { pub fn new(dense_file_bytes: u64, actual_experts: u64) -> PlanResult { let expert_device_bytes = mul(actual_experts, EXPERT_BLOB_BYTES)?; Ok(Self { - dense_file_bytes, expert_device_bytes, + dense_file_bytes, + expert_device_bytes, device_bytes: add(dense_file_bytes, expert_device_bytes)?, dense_host_peak: dense_file_bytes, // Original creates the full chunk even when the last read is short. @@ -46,7 +49,9 @@ impl WeightBankPlan { impl Iterator for ExpertReads { type Item = ReadRange; fn next(&mut self) -> Option { - if self.offset == self.end { return None; } + if self.offset == self.end { + return None; + } let bytes = EXPERT_READ_BYTES.min(self.end - self.offset); let range = ReadRange { offset: self.offset, bytes }; self.offset += bytes; @@ -54,22 +59,32 @@ impl Iterator for ExpertReads { } } impl KvInputs { - pub fn plan(self) -> PlanResult { self.plan_mode(false) } + pub fn plan(self) -> PlanResult { + self.plan_mode(false) + } /// Only an ACTUAL failed mapped state-init, with nonzero original kv_mode, /// authorizes the caller to free/reset the state and use this retry plan. /// This method itself does not observe such failure or select the fallback. - pub fn fully_resident_retry(self) -> PlanResult { self.plan_mode(true) } + pub fn fully_resident_retry(self) -> PlanResult { + self.plan_mode(true) + } pub(super) fn plan_mode(self, force_resident: bool) -> PlanResult { - if self.max_cells == 0 || !(1..=8).contains(&self.max_t) - || self.heads == 0 || self.kv_heads == 0 || self.index_dim == 0 - || self.head_dim != 256 || self.heads != mul(self.kv_heads, 12)? { + if self.max_cells == 0 + || !(1..=8).contains(&self.max_t) + || self.heads == 0 + || self.kv_heads == 0 + || self.index_dim == 0 + || self.head_dim != 256 + || self.heads != mul(self.kv_heads, 12)? + { return Err(LoaderError::Geometry); } let pages = ceil(self.max_cells, 4)?; - let window = if self.requested_window > 0 - && (self.requested_window as u64) < self.max_cells { + let window = if self.requested_window > 0 && (self.requested_window as u64) < self.max_cells { self.requested_window as u64 - } else { 0 }; + } else { + 0 + }; let mut mode = KvMode::Resident; let mut slots = pages; let mut pooled_rows = add(self.max_cells / 4, 2)?; @@ -92,13 +107,18 @@ impl KvInputs { } // mtp.cpp disables keyless and hybrid for its state. Hybrid input sets // INT8 on, but layer.cpp still gives a selected whole Q4 format priority. - let format = if self.q4 { KvFormat::Q4 } - else if self.int8 || self.hybrid { KvFormat::Int8 { rotated: self.int8_rotated } } - else { KvFormat::F16 }; + let format = if self.q4 { + KvFormat::Q4 + } else if self.int8 || self.hybrid { + KvFormat::Int8 { rotated: self.int8_rotated } + } else { + KvFormat::F16 + }; let bytes_per_cell = match format { KvFormat::F16 => mul(mul(self.kv_heads, self.head_dim)?, 4)?, - KvFormat::Int8 { .. } => add(mul(mul(self.kv_heads, self.head_dim)?, 2)?, - mul(mul(self.kv_heads, self.head_dim / 64)?, 4)?)?, + KvFormat::Int8 { .. } => { + add(mul(mul(self.kv_heads, self.head_dim)?, 2)?, mul(mul(self.kv_heads, self.head_dim / 64)?, 4)?)? + } KvFormat::Q4 => mul(mul(self.kv_heads, self.head_dim / 32)?, 36)?, }; let pool = mul(mul(slots, 4)?, bytes_per_cell)?; @@ -117,30 +137,52 @@ impl KvInputs { device = add(device, 16 + 16)?; // four step ints + attention status/alignment device = add(device, mul(self.heads, 4)?)?; device = add(aligned(device, 16)?, 256)?; - let host = if mode == KvMode::Resident { 0 } - else { add(mul(mul(pages, 4)?, bytes_per_cell)?, 4 * 256)? }; + let host = if mode == KvMode::Resident { 0 } else { add(mul(mul(pages, 4)?, bytes_per_cell)?, 4 * 256)? }; let cap = aligned(if window > 0 { window } else { self.max_cells }, 64)?; let scratch = add(mul(mul(ceil(cap, 64)?, self.heads)?, 258)?, 64)?; - Ok(KvPlan { mode, format, pages, slots, pooled_rows, - effective_window: window, attention_capacity: cap, + Ok(KvPlan { + mode, + format, + pages, + slots, + pooled_rows, + effective_window: window, + attention_capacity: cap, attention_scratch_floats: scratch, - state_device_allocation: device, authoritative_host_allocation: host, - state_mapped_step_bytes: 20, state_mapped_position_bytes: mul(self.heads, 4)?, + state_device_allocation: device, + authoritative_host_allocation: host, + state_mapped_step_bytes: 20, + state_mapped_position_bytes: mul(self.heads, 4)?, }) } } /// Six separate Original mapped allocations; no concatenated replacement. pub(crate) fn mapped_staging(max_t: u64, heads: u64) -> PlanResult<[u64; 6]> { - if !(1..=8).contains(&max_t) || heads == 0 { return Err(LoaderError::Geometry); } - Ok([add(mul(max_t, 4)?, 64)?, add(mul(max_t, 32)?, 64)?, - add(mul(mul(max_t, heads)?, 8)?, 64)?, 64, - add(mul(max_t, 4)?, 64)?, add(mul(max_t, 4)?, 64)?]) + if !(1..=8).contains(&max_t) || heads == 0 { + return Err(LoaderError::Geometry); + } + Ok([ + add(mul(max_t, 4)?, 64)?, + add(mul(max_t, 32)?, 64)?, + add(mul(mul(max_t, heads)?, 8)?, 64)?, + 64, + add(mul(max_t, 4)?, 64)?, + add(mul(max_t, 4)?, 64)?, + ]) } -pub(crate) fn coupled_plan(enabled: bool, max_t: u64, vocabulary: u64, - subset_vocabulary: Option) -> PlanResult { - if !(1..=8).contains(&max_t) { return Err(LoaderError::Geometry); } - if !enabled { return Ok(CoupledPlan::Off); } +pub(crate) fn coupled_plan( + enabled: bool, + max_t: u64, + vocabulary: u64, + subset_vocabulary: Option, +) -> PlanResult { + if !(1..=8).contains(&max_t) { + return Err(LoaderError::Geometry); + } + if !enabled { + return Ok(CoupledPlan::Off); + } let sampled = subset_vocabulary.unwrap_or(vocabulary); if sampled == 0 || ceil(sampled, 4096)? > 64 { return Ok(CoupledPlan::ArgmaxVocabularyTooWide); @@ -148,24 +190,40 @@ pub(crate) fn coupled_plan(enabled: bool, max_t: u64, vocabulary: u64, let ring = mul(add(COUPLED_HISTORY, max_t)?, 4)?; let scratch = mul(ceil(sampled, 4096)?, 64 * 8)?; let inverse_map = if subset_vocabulary.is_some() { mul(vocabulary, 4)? } else { 0 }; - Ok(CoupledPlan::Allocate { params: 64, ring, scratch, inverse_map, - mapped_params: 64, mapped_history: COUPLED_HISTORY * 4, + Ok(CoupledPlan::Allocate { + params: 64, + ring, + scratch, + inverse_map, + mapped_params: 64, + mapped_history: COUPLED_HISTORY * 4, device_total: add(add(add(64, ring)?, scratch)?, inverse_map)?, }) } pub(crate) fn bind_bytes(input: BindInputs) -> PlanResult { - let BindInputs { max_t, vocabulary, head_row_bytes, logits_already_owned, - subset_already_owned, observed_subset_file_bytes, coupled_enabled, - coupled_params_already_owned } = input; - if !(1..=8).contains(&max_t) { return Err(LoaderError::Geometry); } + let BindInputs { + max_t, + vocabulary, + head_row_bytes, + logits_already_owned, + subset_already_owned, + observed_subset_file_bytes, + coupled_enabled, + coupled_params_already_owned, + } = input; + if !(1..=8).contains(&max_t) { + return Err(LoaderError::Geometry); + } let mut bytes = if logits_already_owned { 0 } else { mul(mul(max_t, vocabulary)?, 4)? }; - if !subset_already_owned && let Some(size) = observed_subset_file_bytes - && size >= 4 && size % 4 == 0 { + if !subset_already_owned + && let Some(size) = observed_subset_file_bytes + && size >= 4 + && size % 4 == 0 + { bytes = add(bytes, add(mul(size / 4, head_row_bytes)?, size)?)?; } if coupled_enabled && !coupled_params_already_owned { - bytes = add(bytes, add(add(mul(vocabulary, 4)?, - mul(add(COUPLED_HISTORY, max_t)?, 4)?)?, 64 * 64 * 8 + 4096)?)?; + bytes = add(bytes, add(add(mul(vocabulary, 4)?, mul(add(COUPLED_HISTORY, max_t)?, 4)?)?, 64 * 64 * 8 + 4096)?)?; } Ok(bytes) } diff --git a/crates/cuda-driver/src/original_mtp_loader/tests.rs b/crates/cuda-driver/src/original_mtp_loader/tests.rs index 00657a57..ba8b808b 100644 --- a/crates/cuda-driver/src/original_mtp_loader/tests.rs +++ b/crates/cuda-driver/src/original_mtp_loader/tests.rs @@ -65,10 +65,9 @@ fn hybrid_selects_int8_and_whole_q4_is_refused_for_the_retained_owner() { let hybrid = OriginalMtpKvStartup { int8: false, hybrid: true, int8_rotated: true, ..kv() }; let plan = OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: hybrid, ..capture() }, 1).unwrap(); assert_eq!(plan.kv().format, KvFormat::Int8 { rotated: true }); - for refused in [ - OriginalMtpKvStartup { q4: true, ..kv() }, - OriginalMtpKvStartup { int8: false, hybrid: false, ..kv() }, - ] { + for refused in + [OriginalMtpKvStartup { q4: true, ..kv() }, OriginalMtpKvStartup { int8: false, hybrid: false, ..kv() }] + { assert_eq!( OriginalMtpLoadPlan::new(OriginalMtpCapture { kv: refused, ..capture() }, 1).unwrap_err(), LoaderError::ClosedProfile("draft K/V format") @@ -134,10 +133,7 @@ fn bind_reserve_is_the_literal_upper_estimate() { assert_eq!(plan.bind_reserve(Some(ignored), 1440).unwrap(), logits); } let coupled = OriginalMtpLoadPlan::new(OriginalMtpCapture { coupled_requested: true, ..capture() }, 1).unwrap(); - assert_eq!( - coupled.bind_reserve(None, 1440).unwrap(), - logits + 248_320 * 4 + (4096 + 4) * 4 + 64 * 64 * 8 + 4096 - ); + assert_eq!(coupled.bind_reserve(None, 1440).unwrap(), logits + 248_320 * 4 + (4096 + 4) * 4 + 64 * 64 * 8 + 4096); } #[test] @@ -180,10 +176,7 @@ fn coupled_setup_plan_follows_setup_coupled() { other => panic!("{other:?}"), } // 65 lists or a zero-width subset: successful argmax fallback, not coupled-ready - assert!(matches!( - coupled_plan(true, 4, 262_145, None).unwrap(), - CoupledPlan::ArgmaxVocabularyTooWide - )); + assert!(matches!(coupled_plan(true, 4, 262_145, None).unwrap(), CoupledPlan::ArgmaxVocabularyTooWide)); assert!(matches!(coupled_plan(true, 4, 10, Some(0)).unwrap(), CoupledPlan::ArgmaxVocabularyTooWide)); assert!(matches!(coupled_plan(true, 4, 262_144, None).unwrap(), CoupledPlan::Allocate { .. })); assert_eq!(coupled_plan(true, 0, 10, None).unwrap_err(), LoaderError::Geometry); @@ -224,11 +217,7 @@ fn staging_and_kv_geometry_validation() { /// The pure constants above restate the closed owners. This compile-checked /// test (runs on Linux/CI, not on the macOS harness) pins them to the /// session geometry and ring window the retained code actually uses. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[test] fn closed_profile_constants_match_the_retained_owners() { let g = crate::original_session_state::OriginalSessionGeometry::original(); diff --git a/crates/cuda-driver/src/original_mtp_round_lifecycle.rs b/crates/cuda-driver/src/original_mtp_round_lifecycle.rs index cf8f873e..a70fbd01 100644 --- a/crates/cuda-driver/src/original_mtp_round_lifecycle.rs +++ b/crates/cuda-driver/src/original_mtp_round_lifecycle.rs @@ -20,7 +20,10 @@ const PUBLIC_RECORD_WORDS: usize = 1 + 4 + PUBLIC_HEADS; /// The Original static environment-presence decision is supplied explicitly by /// the model's startup parser. No environment lookup or mode inference here. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum OriginalMtpPrefillSync { Once, PerGroup } +pub(crate) enum OriginalMtpPrefillSync { + Once, + PerGroup, +} /// These operations grant no readiness or source authority. The binding must /// use this plan's retained real residual and existing scalar capture resources. @@ -51,38 +54,6 @@ pub(crate) struct OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx> { sync: OriginalMtpPrefillSync, } -impl<'source, 'arena, 'loan, 'ctx> OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx> { - pub(crate) fn residual(&self) -> Option<&OriginalDeviceResidual<'arena, 'loan, 'ctx>> { - self.residual - } - pub(crate) fn tokens(&self) -> &[i32] { self.tokens } - /// Bulk path uploads every row, including rows in skipped groups. Mapped - /// path has no whole-prompt records allocation, matching the Original branch. - pub(crate) fn bulk_records(&self) -> &[u8] { &self.records } - pub(crate) fn metadata_bytes(&self) -> Result { - std::mem::size_of::().checked_add(self.records.capacity()) - .ok_or(Error::BudgetExceeded) - } - pub(crate) fn first_needed(&self) -> i64 { self.first_needed } - pub(crate) fn actions(&self) -> OriginalMtpPrefillActions<'_, 'source, 'arena, 'loan, 'ctx> { - OriginalMtpPrefillActions { plan: self, row: 0, stage: 0, initial: 0, final_sync: false } - } - /// Exactly the four step words and all per-head positions for an actual row. - /// The mapped writer uses this only AFTER that group's capture succeeds. - pub(crate) fn mapped_row(&self, row: usize) -> Result<(i32, [i32; 4], [i32; PUBLIC_HEADS])> { - let token = *self.tokens.get(row).ok_or(Error::InvalidSize)?; - let cell = self.cell0.checked_add(row).ok_or(Error::InvalidSize)?; - let step = public_step(cell)?; - Ok((token, step, [step[0]; PUBLIC_HEADS])) - } -} - -fn public_step(cell: usize) -> Result<[i32; 4]> { - let end = cell.checked_add(1).ok_or(Error::InvalidSize)?; - if end > MTP_ORIGINAL_MAX_CELLS { return Err(Error::InvalidQwenShape); } - Ok([cell as i32, end as i32, (end / 4) as i32, end as i32]) -} - pub(crate) struct OriginalMtpPrefillActions<'plan, 'source, 'arena, 'loan, 'ctx> { plan: &'plan OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx>, row: usize, @@ -90,263 +61,20 @@ pub(crate) struct OriginalMtpPrefillActions<'plan, 'source, 'arena, 'loan, 'ctx> initial: u8, final_sync: bool, } -impl Iterator for OriginalMtpPrefillActions<'_, '_, '_, '_, '_> { - type Item = OriginalMtpPrefillAction; - fn next(&mut self) -> Option { - use OriginalMtpPrefillAction as A; - let p = self.plan; - let n = p.tokens.len(); - let bulk = p.sync == OriginalMtpPrefillSync::Once && n > 0; - if bulk && self.initial < 2 { - let action = if self.initial == 0 { A::EnsureDeviceRecords { words: n * PUBLIC_RECORD_WORDS } } - else { A::UploadAllRecords }; - self.initial += 1; - return Some(action); - } - while self.row < n { - let row = self.row; - let t = p.max_t.min(n - row); - if self.stage == 0 && (p.cell0 + row + t) as i64 <= p.first_needed { - self.row += t; - return Some(A::SkippedGroup { row, rows: t }); - } - let action = if bulk { - match self.stage { - 0 => A::Capture { rows: t, device_inputs: true }, - 1 => A::CopyTokens { source_word: row, words: t }, - 2 => A::CopySteps { source_word: n + 4 * row, words: 4 * t }, - 3 => A::CopyPositions { source_word: 5 * n + PUBLIC_HEADS * row, words: PUBLIC_HEADS * t }, - 4 => A::CopyResidual { source_byte: row * PUBLIC_RESIDUAL_BYTES, bytes: t * PUBLIC_RESIDUAL_BYTES }, - _ => A::Launch { rows: t, device_inputs: true }, - } - } else { - match self.stage { - 0 => A::Capture { rows: t, device_inputs: false }, - 1 => A::WriteMappedRecords { row, rows: t }, - 2 => A::CopyResidual { source_byte: row * PUBLIC_RESIDUAL_BYTES, bytes: t * PUBLIC_RESIDUAL_BYTES }, - 3 => A::Launch { rows: t, device_inputs: false }, - _ => A::Synchronize, - } - }; - self.stage += 1; - if self.stage == if bulk { 6 } else { 5 } { self.stage = 0; self.row += t; } - return Some(action); - } - // Bulk n>0 synchronizes once even when EVERY group was skipped. n==0 - // follows the old mapped branch and performs no synchronization. - if bulk && !self.final_sync { self.final_sync = true; return Some(A::Synchronize); } - None - } -} /// Range and wrapping copies are derived only from the admitted actual ring. /// PRIVATE fields deliberately prevent externally manufactured resume plans. -struct OriginalMtpResumePlan { begin: usize, end: usize, slots: usize } -impl OriginalMtpResumePlan { - fn from_ring(ring: &MtpOriginalInt8<'_>, upto: i64) -> Result> { - ring.validate()?; - // Existing selected owner represents Original mode2 unless its genuine - // fully-resident fallback succeeded. Optional alternate modes are not - // accepted by this type and are not guessed from a caller integer. - if upto <= 0 || ring.fully_resident()? { return Ok(None); } - let upto = usize::try_from(upto).map_err(|_|Error::InvalidSize)?; - if upto > MTP_ORIGINAL_MAX_CELLS || ring.slots == 0 { return Err(Error::InvalidQwenShape); } - let end = upto.div_ceil(4); - Ok(Some(Self { begin: end.saturating_sub(ring.slots), end, slots: ring.slots })) - } +struct OriginalMtpResumePlan { + begin: usize, + end: usize, + slots: usize, } -impl<'ctx> OriginalMtpDrafter<'ctx> { - pub(crate) fn loaded_max_t(&self) -> Result { - self.validate_context(self.context)?; - Ok(self.max_t) - } - /// Whether the retained layout carries the coupled-sampler resources - /// (`setup_coupled` succeeded to allocation), as built by the loader. - pub(crate) fn loaded_coupled(&self) -> Result { - self.validate_context(self.context)?; - Ok(self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.coupled) - } - /// Original header idle: no other stream, event or device-wide wait replaces - /// cs_. Closed loaded owner always has that real stream; an unloaded actor - /// remains the separate original_mtp_actor module. - pub(crate) fn idle_public(&mut self) -> Result<()> { - self.validate_context(self.context)?; - let result = self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize(); - if result.is_err() { self.failed = true; self.context.poison(); self.context.retain_driver(); } - result - } - - /// Concrete genuine-source preparation for the literal public prefill host - /// loop. This returns NO successful-KV product and enqueues no CUDA work. - #[allow(clippy::too_many_arguments)] - pub(crate) fn plan_public_prefill<'source, 'arena, 'loan>( - &self, residual: Option<&'source OriginalDeviceResidual<'arena, 'loan, 'ctx>>, - ring: &MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot, - tokens: &'source [i32], cell0: usize, settings: &DraftSettings, - sync: OriginalMtpPrefillSync, - ) -> Result> { - self.validate_context(self.context)?; - ring.validate_context(self.context)?; - ring.validate_snapshot(prior)?; - if ring.max_t != self.max_t { return Err(Error::InvalidQwenShape); } - if cell0.checked_add(tokens.len()).is_none_or(|e|e>MTP_ORIGINAL_MAX_CELLS) { - return Err(Error::InvalidProjectionShape); - } - match residual { - Some(r) if r.context_matches(self.context) && r.rows() == tokens.len() => {}, - None if tokens.is_empty() => {}, - Some(r) if !r.context_matches(self.context) => return Err(Error::ContextMismatch), - _ => return Err(Error::InvalidProjectionShape), - } - // Loaded existing owner is the literal fixed-window branch. A future - // custom-window SessionState must expose its own authenticated geometry, - // not pass a guessed cutoff to this method. - let first_needed = settings.first_needed(MTP_ORIGINAL_WINDOW as i64) - .map_err(|_|Error::InvalidSize)?; - let mut plan = OriginalMtpPrefillPlan { residual, tokens, records: Vec::new(), cell0, - first_needed, max_t: self.max_t, sync }; - if sync == OriginalMtpPrefillSync::Once && !tokens.is_empty() { - let n = tokens.len(); - let bytes = n.checked_mul(PUBLIC_RECORD_WORDS * 4).ok_or(Error::InvalidSize)?; - plan.records.try_reserve_exact(bytes).map_err(|_|Error::HostAllocation)?; - plan.records.resize(bytes, 0); - for (i, token) in tokens.iter().enumerate() { - plan.records[i * 4..i * 4 + 4].copy_from_slice(&token.to_ne_bytes()); - let step = public_step(cell0 + i)?; - for (j, value) in step.into_iter().enumerate() { - let offset = (n + i * 4 + j) * 4; - plan.records[offset..offset + 4].copy_from_slice(&value.to_ne_bytes()); - } - for h in 0..PUBLIC_HEADS { - let offset = (5 * n + i * PUBLIC_HEADS + h) * 4; - plan.records[offset..offset + 4].copy_from_slice(&step[0].to_ne_bytes()); - } - } - } - Ok(plan) - } - - /// Literal kv_restore wrapping-run copies from actual mapped host pools to - /// actual resident slots, on cs_. No full snapshot rematerialization, table - /// reset, generation remint or NativeBatchWorkspace stream substitutes here. - /// The caller supplies the genuine current canonical prior, whose pages - /// authenticate the host coverage the continuation is allowed to restore. - pub(crate) fn resume_public_kv( - &mut self, ring: &mut MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot, upto: i64, - ) -> Result<()> { - self.validate_context(self.context)?; - ring.validate_context(self.context)?; - if ring.max_t != self.max_t { return Err(Error::InvalidQwenShape); } - let Some(plan) = OriginalMtpResumePlan::from_ring(ring, upto)? else { return Ok(()); }; - ring.validate_snapshot(prior)?; - if prior.0.end < upto as usize || - ring.current.as_ref().is_none_or(|current|!Rc::ptr_eq(¤t.0, &prior.0)) { - return Err(Error::InvalidQwenShape); - } - let physical = ring.retain_physical_resources()?; - let module = Rc::clone(self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.modules - .first().ok_or(Error::ContextPoisoned)?); - // At most two wrapping runs * four actual INT8 runs. ALL bounds and - // source/whole-owner loans are established before the first command. - let mut copies = [(0u64, 0u64, 0usize); 8]; - let mut count = 0; - let mut block = plan.begin; - while block < plan.end { - let slot = block % plan.slots; - let run = (plan.end - block).min(plan.slots - slot); - for (i, page_bytes) in PAGE_BYTES.into_iter().enumerate() { - let bytes = run.checked_mul(page_bytes).ok_or(Error::InvalidSize)?; - copies[count] = (ring.sub(i, slot * page_bytes, bytes)?, - ring.mapped()?.address(HOST_OFFSETS[i] + block * page_bytes, bytes)?, bytes); - count += 1; - } - block += run; - } - let previous = ring.current.take(); - let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; - let copied = stream.with_enqueue(|handle| { - for (dst, src, bytes) in copies.iter().take(count).copied() { - module.copy(dst, src, bytes, handle)?; - } - Ok(()) - }); - // Always attempt the real stream drain after entering the operation, - // preserve the first copy error, retain actual sources on uncertainty. - let drained = stream.synchronize(); - if copied.is_err() || drained.is_err() { - self.failed = true; ring.failed = true; - self.context.poison(); self.context.retain_driver(); - std::mem::forget(physical); - std::mem::forget(module); - return combine(copied, drained); - } - ring.current = previous; - physical.validate_context(self.context)?; - Ok(()) - } - - /// Public-array adapter over the genuine existing graph executor. It NEVER - /// reads token/probability output before actual graph drain, and retains the - /// completed ring/window product in its return value for subsequent replay. - #[allow(clippy::too_many_arguments)] - pub(crate) fn draft_public( - &mut self, ring: &mut MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, selection: NativeHeadSelection, accepted_row: usize, - settings: &DraftSettings, min_probability: f32, policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - drafts: &mut [i32], probabilities: Option<&mut [f32]>, - ) -> Result> { - self.validate_public_output_extent(drafts, probabilities.as_deref())?; - let completion = self.draft_from_verifier(ring, prior, window, selection, accepted_row, - settings.max_drafts(), min_probability, policy, coupled)?; - completion.validate_current(ring)?; - self.copy_public_draft_output(&completion, drafts, probabilities)?; - Ok(completion) - } - - /// Existing direct first-round executor makes T real synchronous D2D copies - /// of the authentic single-row verifier R, then stages T copies of its real - /// matching head token. Caller shape errors are refused BEFORE those copies. - #[allow(clippy::too_many_arguments)] - pub(crate) fn draft_first_public( - &mut self, ring: &mut MtpOriginalInt8<'ctx>, prior: &MtpInt8Snapshot, - window: OriginalVerifyWindow<'ctx>, selection: NativeHeadSelection, rows: usize, - settings: &DraftSettings, min_probability: f32, policy: &OriginalMtpFullPolicy, - coupled: Option<(SamplerParams, &[i32; 4096])>, - drafts: &mut [i32], probabilities: Option<&mut [f32]>, - ) -> Result> { - self.validate_public_output_extent(drafts, probabilities.as_deref())?; - if rows == 0 || rows > self.max_t { return Err(Error::InvalidQwenShape); } - let completion = self.draft_first_from_verifier(ring, prior, window, selection, rows, - settings.max_drafts(), min_probability, policy, coupled)?; - completion.validate_current(ring)?; - self.copy_public_draft_output(&completion, drafts, probabilities)?; - Ok(completion) - } - fn validate_public_output_extent(&self, drafts: &[i32], probabilities: Option<&[f32]>) -> Result<()> { - self.validate_context(self.context)?; - // draft0 runs even for max_t==1 and max_drafts<=0. Original array API - // expects callers to provide this physical word, despite its T-1 prose. - let extent = self.max_t.saturating_sub(1).max(1); - if drafts.len() < extent || probabilities.is_some_and(|p|p.len() < extent) { - return Err(Error::InvalidSize); - } - Ok(()) - } - fn copy_public_draft_output(&self, completion: &CompletedOriginalMtpDraft<'ctx>, - drafts: &mut [i32], mut probabilities: Option<&mut [f32]>) -> Result<()> { - let count = completion.count(); - let extent = self.max_t.saturating_sub(1).max(1); - if count == 0 || count > extent { return Err(Error::InvalidDriverValue("Original MTP draft count")); } - for (j, token) in completion.ids().iter().enumerate() { - drafts[j] = *token; - if let Some(p) = probabilities.as_deref_mut() { p[j] = completion.probabilities()[j]; } - } - for j in count..self.max_t.saturating_sub(1) { - drafts[j] = 0; - if let Some(p) = probabilities.as_deref_mut() { p[j] = 0.0; } - } - Ok(()) - } -} +#[path = "original_mtp_round_lifecycle/impl_originalmtpprefillplan.rs"] +mod impl_originalmtpprefillplan; +#[allow(unused_imports)] +use impl_originalmtpprefillplan::public_step; +#[path = "original_mtp_round_lifecycle/impl_originalmtpdrafter.rs"] +mod impl_originalmtpdrafter; +#[path = "original_mtp_round_lifecycle/impl_originalmtpdrafter_2.rs"] +mod impl_originalmtpdrafter_2; diff --git a/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs new file mode 100644 index 00000000..07943e9c --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter.rs @@ -0,0 +1,247 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDrafter. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalMtpDrafter<'ctx> { + pub(crate) fn loaded_max_t(&self) -> Result { + self.validate_context(self.context)?; + Ok(self.max_t) + } + /// Whether the retained layout carries the coupled-sampler resources + /// (`setup_coupled` succeeded to allocation), as built by the loader. + pub(crate) fn loaded_coupled(&self) -> Result { + self.validate_context(self.context)?; + Ok(self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.coupled) + } + /// Original header idle: no other stream, event or device-wide wait replaces + /// cs_. Closed loaded owner always has that real stream; an unloaded actor + /// remains the separate original_mtp_actor module. + pub(crate) fn idle_public(&mut self) -> Result<()> { + self.validate_context(self.context)?; + let result = self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize(); + if result.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + result + } + + /// Concrete genuine-source preparation for the literal public prefill host + /// loop. This returns NO successful-KV product and enqueues no CUDA work. + #[allow(clippy::too_many_arguments)] + pub(crate) fn plan_public_prefill<'source, 'arena, 'loan>( + &self, + residual: Option<&'source OriginalDeviceResidual<'arena, 'loan, 'ctx>>, + ring: &MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &'source [i32], + cell0: usize, + settings: &DraftSettings, + sync: OriginalMtpPrefillSync, + ) -> Result> { + self.validate_context(self.context)?; + ring.validate_context(self.context)?; + ring.validate_snapshot(prior)?; + if ring.max_t != self.max_t { + return Err(Error::InvalidQwenShape); + } + if cell0.checked_add(tokens.len()).is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) { + return Err(Error::InvalidProjectionShape); + } + match residual { + Some(r) if r.context_matches(self.context) && r.rows() == tokens.len() => {} + None if tokens.is_empty() => {} + Some(r) if !r.context_matches(self.context) => return Err(Error::ContextMismatch), + _ => return Err(Error::InvalidProjectionShape), + } + // Loaded existing owner is the literal fixed-window branch. A future + // custom-window SessionState must expose its own authenticated geometry, + // not pass a guessed cutoff to this method. + let first_needed = settings.first_needed(MTP_ORIGINAL_WINDOW as i64).map_err(|_| Error::InvalidSize)?; + let mut plan = OriginalMtpPrefillPlan { + residual, + tokens, + records: Vec::new(), + cell0, + first_needed, + max_t: self.max_t, + sync, + }; + if sync == OriginalMtpPrefillSync::Once && !tokens.is_empty() { + let n = tokens.len(); + let bytes = n.checked_mul(PUBLIC_RECORD_WORDS * 4).ok_or(Error::InvalidSize)?; + plan.records.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; + plan.records.resize(bytes, 0); + for (i, token) in tokens.iter().enumerate() { + plan.records[i * 4..i * 4 + 4].copy_from_slice(&token.to_ne_bytes()); + let step = public_step(cell0 + i)?; + for (j, value) in step.into_iter().enumerate() { + let offset = (n + i * 4 + j) * 4; + plan.records[offset..offset + 4].copy_from_slice(&value.to_ne_bytes()); + } + for h in 0..PUBLIC_HEADS { + let offset = (5 * n + i * PUBLIC_HEADS + h) * 4; + plan.records[offset..offset + 4].copy_from_slice(&step[0].to_ne_bytes()); + } + } + } + Ok(plan) + } + + /// Literal kv_restore wrapping-run copies from actual mapped host pools to + /// actual resident slots, on cs_. No full snapshot rematerialization, table + /// reset, generation remint or NativeBatchWorkspace stream substitutes here. + /// The caller supplies the genuine current canonical prior, whose pages + /// authenticate the host coverage the continuation is allowed to restore. + pub(crate) fn resume_public_kv( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + upto: i64, + ) -> Result<()> { + self.validate_context(self.context)?; + ring.validate_context(self.context)?; + if ring.max_t != self.max_t { + return Err(Error::InvalidQwenShape); + } + let Some(plan) = OriginalMtpResumePlan::from_ring(ring, upto)? else { + return Ok(()); + }; + ring.validate_snapshot(prior)?; + if prior.0.end < upto as usize || ring.current.as_ref().is_none_or(|current| !Rc::ptr_eq(¤t.0, &prior.0)) + { + return Err(Error::InvalidQwenShape); + } + let physical = ring.retain_physical_resources()?; + let module = Rc::clone( + self.full.as_ref().ok_or(Error::ContextPoisoned)?.inner.modules.first().ok_or(Error::ContextPoisoned)?, + ); + // At most two wrapping runs * four actual INT8 runs. ALL bounds and + // source/whole-owner loans are established before the first command. + let mut copies = [(0u64, 0u64, 0usize); 8]; + let mut count = 0; + let mut block = plan.begin; + while block < plan.end { + let slot = block % plan.slots; + let run = (plan.end - block).min(plan.slots - slot); + for (i, page_bytes) in PAGE_BYTES.into_iter().enumerate() { + let bytes = run.checked_mul(page_bytes).ok_or(Error::InvalidSize)?; + copies[count] = ( + ring.sub(i, slot * page_bytes, bytes)?, + ring.mapped()?.address(HOST_OFFSETS[i] + block * page_bytes, bytes)?, + bytes, + ); + count += 1; + } + block += run; + } + let previous = ring.current.take(); + let stream = self.stream.as_mut().ok_or(Error::ContextPoisoned)?; + let copied = stream.with_enqueue(|handle| { + for (dst, src, bytes) in copies.iter().take(count).copied() { + module.copy(dst, src, bytes, handle)?; + } + Ok(()) + }); + // Always attempt the real stream drain after entering the operation, + // preserve the first copy error, retain actual sources on uncertainty. + let drained = stream.synchronize(); + if copied.is_err() || drained.is_err() { + self.failed = true; + ring.failed = true; + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(physical); + std::mem::forget(module); + return combine(copied, drained); + } + ring.current = previous; + physical.validate_context(self.context)?; + Ok(()) + } + + /// Public-array adapter over the genuine existing graph executor. It NEVER + /// reads token/probability output before actual graph drain, and retains the + /// completed ring/window product in its return value for subsequent replay. + #[allow(clippy::too_many_arguments)] + pub(crate) fn draft_public( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + accepted_row: usize, + settings: &DraftSettings, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + coupled: Option<(SamplerParams, &[i32; 4096])>, + drafts: &mut [i32], + probabilities: Option<&mut [f32]>, + ) -> Result> { + self.validate_public_output_extent(drafts, probabilities.as_deref())?; + let completion = self.draft_from_verifier( + ring, + prior, + window, + selection, + accepted_row, + settings.max_drafts(), + min_probability, + policy, + coupled, + )?; + completion.validate_current(ring)?; + self.copy_public_draft_output(&completion, drafts, probabilities)?; + Ok(completion) + } + + /// Existing direct first-round executor makes T real synchronous D2D copies + /// of the authentic single-row verifier R, then stages T copies of its real + /// matching head token. Caller shape errors are refused BEFORE those copies. + #[allow(clippy::too_many_arguments)] + pub(crate) fn draft_first_public( + &mut self, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + rows: usize, + settings: &DraftSettings, + min_probability: f32, + policy: &OriginalMtpFullPolicy, + coupled: Option<(SamplerParams, &[i32; 4096])>, + drafts: &mut [i32], + probabilities: Option<&mut [f32]>, + ) -> Result> { + self.validate_public_output_extent(drafts, probabilities.as_deref())?; + if rows == 0 || rows > self.max_t { + return Err(Error::InvalidQwenShape); + } + let completion = self.draft_first_from_verifier( + ring, + prior, + window, + selection, + rows, + settings.max_drafts(), + min_probability, + policy, + coupled, + )?; + completion.validate_current(ring)?; + self.copy_public_draft_output(&completion, drafts, probabilities)?; + Ok(completion) + } + pub(super) fn validate_public_output_extent(&self, drafts: &[i32], probabilities: Option<&[f32]>) -> Result<()> { + self.validate_context(self.context)?; + // draft0 runs even for max_t==1 and max_drafts<=0. Original array API + // expects callers to provide this physical word, despite its T-1 prose. + let extent = self.max_t.saturating_sub(1).max(1); + if drafts.len() < extent || probabilities.is_some_and(|p| p.len() < extent) { + return Err(Error::InvalidSize); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter_2.rs b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter_2.rs new file mode 100644 index 00000000..e9f7f2e0 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpdrafter_2.rs @@ -0,0 +1,32 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpDrafter (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalMtpDrafter<'ctx> { + pub(super) fn copy_public_draft_output( + &self, + completion: &CompletedOriginalMtpDraft<'ctx>, + drafts: &mut [i32], + mut probabilities: Option<&mut [f32]>, + ) -> Result<()> { + let count = completion.count(); + let extent = self.max_t.saturating_sub(1).max(1); + if count == 0 || count > extent { + return Err(Error::InvalidDriverValue("Original MTP draft count")); + } + for (j, token) in completion.ids().iter().enumerate() { + drafts[j] = *token; + if let Some(p) = probabilities.as_deref_mut() { + p[j] = completion.probabilities()[j]; + } + } + for j in count..self.max_t.saturating_sub(1) { + drafts[j] = 0; + if let Some(p) = probabilities.as_deref_mut() { + p[j] = 0.0; + } + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpprefillplan.rs b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpprefillplan.rs new file mode 100644 index 00000000..02c561e3 --- /dev/null +++ b/crates/cuda-driver/src/original_mtp_round_lifecycle/impl_originalmtpprefillplan.rs @@ -0,0 +1,117 @@ +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefillPlan, fn public_step, impl Iterator_for_OriginalMtpPrefillActions, impl OriginalMtpResumePlan. + +#[allow(unused_imports)] +use super::*; + +impl<'source, 'arena, 'loan, 'ctx> OriginalMtpPrefillPlan<'source, 'arena, 'loan, 'ctx> { + pub(crate) fn residual(&self) -> Option<&OriginalDeviceResidual<'arena, 'loan, 'ctx>> { + self.residual + } + pub(crate) fn tokens(&self) -> &[i32] { + self.tokens + } + /// Bulk path uploads every row, including rows in skipped groups. Mapped + /// path has no whole-prompt records allocation, matching the Original branch. + pub(crate) fn bulk_records(&self) -> &[u8] { + &self.records + } + pub(crate) fn metadata_bytes(&self) -> Result { + std::mem::size_of::().checked_add(self.records.capacity()).ok_or(Error::BudgetExceeded) + } + pub(crate) fn first_needed(&self) -> i64 { + self.first_needed + } + pub(crate) fn actions(&self) -> OriginalMtpPrefillActions<'_, 'source, 'arena, 'loan, 'ctx> { + OriginalMtpPrefillActions { plan: self, row: 0, stage: 0, initial: 0, final_sync: false } + } + /// Exactly the four step words and all per-head positions for an actual row. + /// The mapped writer uses this only AFTER that group's capture succeeds. + pub(crate) fn mapped_row(&self, row: usize) -> Result<(i32, [i32; 4], [i32; PUBLIC_HEADS])> { + let token = *self.tokens.get(row).ok_or(Error::InvalidSize)?; + let cell = self.cell0.checked_add(row).ok_or(Error::InvalidSize)?; + let step = public_step(cell)?; + Ok((token, step, [step[0]; PUBLIC_HEADS])) + } +} + +pub(super) fn public_step(cell: usize) -> Result<[i32; 4]> { + let end = cell.checked_add(1).ok_or(Error::InvalidSize)?; + if end > MTP_ORIGINAL_MAX_CELLS { + return Err(Error::InvalidQwenShape); + } + Ok([cell as i32, end as i32, (end / 4) as i32, end as i32]) +} +impl Iterator for OriginalMtpPrefillActions<'_, '_, '_, '_, '_> { + type Item = OriginalMtpPrefillAction; + fn next(&mut self) -> Option { + use OriginalMtpPrefillAction as A; + let p = self.plan; + let n = p.tokens.len(); + let bulk = p.sync == OriginalMtpPrefillSync::Once && n > 0; + if bulk && self.initial < 2 { + let action = if self.initial == 0 { + A::EnsureDeviceRecords { words: n * PUBLIC_RECORD_WORDS } + } else { + A::UploadAllRecords + }; + self.initial += 1; + return Some(action); + } + while self.row < n { + let row = self.row; + let t = p.max_t.min(n - row); + if self.stage == 0 && (p.cell0 + row + t) as i64 <= p.first_needed { + self.row += t; + return Some(A::SkippedGroup { row, rows: t }); + } + let action = if bulk { + match self.stage { + 0 => A::Capture { rows: t, device_inputs: true }, + 1 => A::CopyTokens { source_word: row, words: t }, + 2 => A::CopySteps { source_word: n + 4 * row, words: 4 * t }, + 3 => A::CopyPositions { source_word: 5 * n + PUBLIC_HEADS * row, words: PUBLIC_HEADS * t }, + 4 => A::CopyResidual { source_byte: row * PUBLIC_RESIDUAL_BYTES, bytes: t * PUBLIC_RESIDUAL_BYTES }, + _ => A::Launch { rows: t, device_inputs: true }, + } + } else { + match self.stage { + 0 => A::Capture { rows: t, device_inputs: false }, + 1 => A::WriteMappedRecords { row, rows: t }, + 2 => A::CopyResidual { source_byte: row * PUBLIC_RESIDUAL_BYTES, bytes: t * PUBLIC_RESIDUAL_BYTES }, + 3 => A::Launch { rows: t, device_inputs: false }, + _ => A::Synchronize, + } + }; + self.stage += 1; + if self.stage == if bulk { 6 } else { 5 } { + self.stage = 0; + self.row += t; + } + return Some(action); + } + // Bulk n>0 synchronizes once even when EVERY group was skipped. n==0 + // follows the old mapped branch and performs no synchronization. + if bulk && !self.final_sync { + self.final_sync = true; + return Some(A::Synchronize); + } + None + } +} +impl OriginalMtpResumePlan { + pub(super) fn from_ring(ring: &MtpOriginalInt8<'_>, upto: i64) -> Result> { + ring.validate()?; + // Existing selected owner represents Original mode2 unless its genuine + // fully-resident fallback succeeded. Optional alternate modes are not + // accepted by this type and are not guessed from a caller integer. + if upto <= 0 || ring.fully_resident()? { + return Ok(None); + } + let upto = usize::try_from(upto).map_err(|_| Error::InvalidSize)?; + if upto > MTP_ORIGINAL_MAX_CELLS || ring.slots == 0 { + return Err(Error::InvalidQwenShape); + } + let end = upto.div_ceil(4); + Ok(Some(Self { begin: end.saturating_sub(ring.slots), end, slots: ring.slots })) + } +} diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs index 74ae3811..638ecd6b 100644 --- a/crates/cuda-driver/src/original_mtp_rt.rs +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -41,7 +41,9 @@ pub(crate) const EXPERT_SCALE_OFFSET: u64 = 1_228_800; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum RtError { - CannotOpenIndex { directory: String }, + CannotOpenIndex { + directory: String, + }, IndexTooLarge, IndexNotAscii, MalformedLine(String), @@ -121,12 +123,7 @@ pub(crate) mod fixtures { ("mlp.shared_expert.gate_proj.weight", "q8_0", 1, 64), ("mlp.shared_expert.up_proj.weight", "q8_0", 1, 64), ("mlp.shared_expert.down_proj.weight", "q8_0", 2, 32), - ( - "attn_hyper_connection.block_inject_weight.weight", - "bf16", - 4, - 8, - ), + ("attn_hyper_connection.block_inject_weight.weight", "bf16", 4, 8), ("mlp.gate.weight", "bf16", 5, 8), ("attn_hyper_connection.hc_norm.weight", "f32", 1, 16), ("self_attn.k_norm.weight", "f32", 1, 8), @@ -166,10 +163,7 @@ pub(crate) mod fixtures { for (index, (name, kind, rows, columns)) in TENSORS.iter().enumerate() { blob.resize(blob.len().div_ceil(256) * 256, 0); let bytes = tensor_bytes(kind, *rows, *columns); - text.push_str(&format!( - "{name} {kind} {rows} {columns} {} {bytes}\n", - blob.len() - )); + text.push_str(&format!("{name} {kind} {rows} {columns} {} {bytes}\n", blob.len())); let at = blob.len(); blob.resize(at + bytes as usize, 0); for (i, b) in blob[at..].iter_mut().enumerate() { @@ -215,31 +209,31 @@ use impl_rterror::open_regular; use impl_rterror::zeroed; mod read_index_fn; #[allow(unused_imports)] -pub(crate) use read_index_fn::read_index; -#[allow(unused_imports)] -pub(crate) use read_index_fn::read_dense; +pub(crate) use read_index_fn::draft_vocab_path; #[allow(unused_imports)] pub(crate) use read_index_fn::expert_bank_bytes; #[allow(unused_imports)] pub(crate) use read_index_fn::expert_scales_finite; #[allow(unused_imports)] -pub(crate) use read_index_fn::stream_experts; -#[allow(unused_imports)] -pub(crate) use read_index_fn::draft_vocab_path; +use read_index_fn::observed_default_bytes; #[allow(unused_imports)] pub(crate) use read_index_fn::observed_draft_vocab_bytes; #[allow(unused_imports)] pub(crate) use read_index_fn::observed_draft_vocab_bytes_with; #[allow(unused_imports)] -use read_index_fn::observed_default_bytes; +use read_index_fn::read_default_draft_vocab; +#[allow(unused_imports)] +pub(crate) use read_index_fn::read_dense; #[allow(unused_imports)] pub(crate) use read_index_fn::read_draft_vocab; #[cfg(test)] #[allow(unused_imports)] pub(crate) use read_index_fn::read_draft_vocab_with; #[allow(unused_imports)] +pub(crate) use read_index_fn::read_index; +#[allow(unused_imports)] pub(crate) use read_index_fn::read_selected_draft_vocab; #[allow(unused_imports)] -use read_index_fn::read_default_draft_vocab; +pub(crate) use read_index_fn::stream_experts; #[allow(unused_imports)] pub(crate) use read_index_fn::validate_subset; diff --git a/crates/cuda-driver/src/original_mtp_rt/impl_rterror.rs b/crates/cuda-driver/src/original_mtp_rt/impl_rterror.rs index acecf0e2..9874633a 100644 --- a/crates/cuda-driver/src/original_mtp_rt/impl_rterror.rs +++ b/crates/cuda-driver/src/original_mtp_rt/impl_rterror.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl RtError { /// Original error text where `mtp.cpp` has one, otherwise an `mtp:` text in /// the same style. Never contains file contents beyond the offending line. @@ -29,9 +28,7 @@ impl RtError { Self::DenseTooLarge => "mtp: dense.bin is too large".into(), Self::ExpertSizeOverflow => "mtp: the expert bank size overflows".into(), Self::DraftVocabTooLarge => "mtp: draft_vocab.bin is too large".into(), - Self::DraftVocabOutOfRange => { - "mtp: draft_vocab.bin holds an id outside the vocabulary".into() - } + Self::DraftVocabOutOfRange => "mtp: draft_vocab.bin holds an id outside the vocabulary".into(), Self::DraftVocabSelection(text) => format!("mtp: {text}"), Self::Host => "mtp: host allocation failed".into(), } @@ -105,26 +102,14 @@ impl DenseIndex { if tensors.len() >= MAX_TENSORS { return Err(RtError::TooManyTensors); } - if name.len() > 180 - || !name - .bytes() - .all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b)) - { + if name.len() > 180 || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"._".contains(&b)) { return Err(RtError::InvalidName(name.chars().take(64).collect())); } if tensors.iter().any(|t| t.name == name) { return Err(RtError::DuplicateTensor(name.to_owned())); } - let kind = OriginalMtpTensorKind::parse(kind) - .ok_or_else(|| RtError::UnknownKind(name.to_owned()))?; - tensors.push(TensorEntry { - name: name.to_owned(), - kind, - rows, - columns, - offset, - bytes, - }); + let kind = OriginalMtpTensorKind::parse(kind).ok_or_else(|| RtError::UnknownKind(name.to_owned()))?; + tensors.push(TensorEntry { name: name.to_owned(), kind, rows, columns, offset, bytes }); } Ok(Self { tensors }) } @@ -146,10 +131,7 @@ impl DenseIndex { { return Err(RtError::Geometry(t.name.clone())); } - if t.offset - .checked_add(t.bytes) - .is_none_or(|end| end > dense_bytes) - { + if t.offset.checked_add(t.bytes).is_none_or(|end| end > dense_bytes) { return Err(RtError::OutOfRange(t.name.clone())); } } @@ -159,9 +141,7 @@ impl DenseIndex { /// `f32()/bf16()/q8()` of mtp.cpp:131-141: first entry with this name AND /// this kind. Names are unique after `parse`, so "first" is the only one. pub(crate) fn find(&self, name: &str, kind: OriginalMtpTensorKind) -> Option<&TensorEntry> { - self.tensors - .iter() - .find(|t| t.name == name && t.kind == kind) + self.tensors.iter().find(|t| t.name == name && t.kind == kind) } /// The nine-name check of mtp.cpp:204-205, in source order. Callers run it @@ -177,13 +157,10 @@ impl DenseIndex { /// Slice of one tensor inside a validated `dense.bin` image. pub(crate) fn slice<'a>(&self, entry: &TensorEntry, dense: &'a [u8]) -> RtResult<&'a [u8]> { - let start = - usize::try_from(entry.offset).map_err(|_| RtError::OutOfRange(entry.name.clone()))?; + let start = usize::try_from(entry.offset).map_err(|_| RtError::OutOfRange(entry.name.clone()))?; let end = usize::try_from(entry.offset.saturating_add(entry.bytes)) .map_err(|_| RtError::OutOfRange(entry.name.clone()))?; - dense - .get(start..end) - .ok_or_else(|| RtError::OutOfRange(entry.name.clone())) + dense.get(start..end).ok_or_else(|| RtError::OutOfRange(entry.name.clone())) } /// Finite admission of every indexed tensor (the runtime pack reader does @@ -192,15 +169,15 @@ impl DenseIndex { for t in &self.tensors { let bytes = self.slice(t, dense)?; let finite = match t.kind { - OriginalMtpTensorKind::Bf16 => bytes - .chunks_exact(2) - .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7f80 != 0x7f80), - OriginalMtpTensorKind::F32 => bytes - .chunks_exact(4) - .all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()), - OriginalMtpTensorKind::Q8_0 => bytes - .chunks_exact(34) - .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00), + OriginalMtpTensorKind::Bf16 => { + bytes.chunks_exact(2).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7f80 != 0x7f80) + } + OriginalMtpTensorKind::F32 => { + bytes.chunks_exact(4).all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()) + } + OriginalMtpTensorKind::Q8_0 => { + bytes.chunks_exact(34).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) + } }; if !finite { return Err(RtError::NonFinite(t.name.clone())); @@ -223,11 +200,7 @@ pub(super) fn open_regular(path: &Path) -> Option { #[cfg(all(target_os = "linux", target_pointer_width = "64"))] let file = { use std::os::unix::fs::OpenOptionsExt; - fs::OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(path) - .ok()? + fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path).ok()? }; #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] let file = File::open(path).ok()?; diff --git a/crates/cuda-driver/src/original_mtp_rt/read_index_fn.rs b/crates/cuda-driver/src/original_mtp_rt/read_index_fn.rs index dae1b433..beb2b83a 100644 --- a/crates/cuda-driver/src/original_mtp_rt/read_index_fn.rs +++ b/crates/cuda-driver/src/original_mtp_rt/read_index_fn.rs @@ -3,19 +3,14 @@ #[allow(unused_imports)] use super::*; - pub(crate) fn read_index(directory: &Path) -> RtResult { - let open = || RtError::CannotOpenIndex { - directory: directory.display().to_string(), - }; + let open = || RtError::CannotOpenIndex { directory: directory.display().to_string() }; let file = open_regular(&directory.join("dense.txt")).ok_or_else(open)?; if file.metadata().map_err(|_| open())?.len() > INDEX_LIMIT { return Err(RtError::IndexTooLarge); } let mut bytes = Vec::new(); - file.take(INDEX_LIMIT + 1) - .read_to_end(&mut bytes) - .map_err(|_| open())?; + file.take(INDEX_LIMIT + 1).read_to_end(&mut bytes).map_err(|_| open())?; if bytes.len() as u64 > INDEX_LIMIT { return Err(RtError::IndexTooLarge); } @@ -33,16 +28,13 @@ pub(crate) fn read_dense(directory: &Path) -> RtResult> { } let mut blob = zeroed(usize::try_from(length).map_err(|_| RtError::DenseTooLarge)?)?; let mut file = file; - file.read_exact(&mut blob) - .map_err(|_| RtError::CannotReadDense)?; + file.read_exact(&mut blob).map_err(|_| RtError::CannotReadDense)?; Ok(blob) } /// `n_expert * BLOB` with checked arithmetic. pub(crate) fn expert_bank_bytes(n_expert: u64, blob: u64) -> RtResult { - n_expert - .checked_mul(blob) - .ok_or(RtError::ExpertSizeOverflow) + n_expert.checked_mul(blob).ok_or(RtError::ExpertSizeOverflow) } /// The absolute scale-half ranges of experts.bin inside `[offset, offset+len)` @@ -62,10 +54,7 @@ pub(crate) fn expert_scales_finite(offset: u64, chunk: &[u8], blob: u64) -> bool let stop = (at - within + blob).min(end); let from = (at - offset) as usize; let to = (stop - offset) as usize; - if chunk[from..to] - .chunks_exact(2) - .any(|h| u16::from_le_bytes([h[0], h[1]]) & 0x7c00 == 0x7c00) - { + if chunk[from..to].chunks_exact(2).any(|h| u16::from_le_bytes([h[0], h[1]]) & 0x7c00 == 0x7c00) { return false; } at = stop; @@ -84,8 +73,7 @@ pub(crate) fn stream_experts( before_read: impl FnOnce() -> std::result::Result<(), E>, mut sink: impl FnMut(u64, &[u8]) -> std::result::Result<(), E>, ) -> std::result::Result<(), StreamError> { - let mut file = open_regular(&directory.join("experts.bin")) - .ok_or(StreamError::Rt(RtError::CannotOpenExperts))?; + let mut file = open_regular(&directory.join("experts.bin")).ok_or(StreamError::Rt(RtError::CannotOpenExperts))?; before_read().map_err(StreamError::Sink)?; if chunk_bytes == 0 { return Err(StreamError::Rt(RtError::Host)); @@ -95,8 +83,7 @@ pub(crate) fn stream_experts( while offset < bytes { let n = (chunk.len() as u64).min(bytes - offset); let piece = &mut chunk[..n as usize]; - file.read_exact(piece) - .map_err(|_| StreamError::Rt(RtError::ExpertsTruncated))?; + file.read_exact(piece).map_err(|_| StreamError::Rt(RtError::ExpertsTruncated))?; sink(offset, piece).map_err(StreamError::Sink)?; offset += n; } @@ -121,12 +108,7 @@ pub(crate) fn observed_draft_vocab_bytes_with(directory: &Path, setting: &dv::Se } pub(super) fn observed_default_bytes(directory: &Path) -> Option { - Some( - open_regular(&draft_vocab_path(directory))? - .metadata() - .ok()? - .len(), - ) + Some(open_regular(&draft_vocab_path(directory))?.metadata().ok()?.len()) } /// `bind` reads `draft_vocab.bin` (mtp.cpp:393-396). Original ignores a file @@ -174,10 +156,7 @@ pub(super) fn read_default_draft_vocab(directory: &Path) -> RtResult /// Every id must name a vocabulary row before the device gather reads it. pub(crate) fn validate_subset(ids: &[i32], vocabulary: usize) -> RtResult<()> { - if ids.is_empty() - || vocabulary == 0 - || ids.iter().any(|&id| id < 0 || id as usize >= vocabulary) - { + if ids.is_empty() || vocabulary == 0 || ids.iter().any(|&id| id < 0 || id as usize >= vocabulary) { return Err(RtError::DraftVocabOutOfRange); } Ok(()) diff --git a/crates/cuda-driver/src/original_mtp_rt/tests.rs b/crates/cuda-driver/src/original_mtp_rt/tests.rs index 2bcc392e..39168e7a 100644 --- a/crates/cuda-driver/src/original_mtp_rt/tests.rs +++ b/crates/cuda-driver/src/original_mtp_rt/tests.rs @@ -15,7 +15,7 @@ const REQUIRED: &[&str] = &[ "mlp.shared_expert.down_proj.weight", ]; -#[path = "tests/parses_getline_loop_and_skips.rs"] -mod parses_getline_loop_and_skips; #[path = "tests/expert_stream_error_paths_use.rs"] mod expert_stream_error_paths_use; +#[path = "tests/parses_getline_loop_and_skips.rs"] +mod parses_getline_loop_and_skips; diff --git a/crates/cuda-driver/src/original_mtp_rt/tests/expert_stream_error_paths_use.rs b/crates/cuda-driver/src/original_mtp_rt/tests/expert_stream_error_paths_use.rs index fb6d9682..0670332b 100644 --- a/crates/cuda-driver/src/original_mtp_rt/tests/expert_stream_error_paths_use.rs +++ b/crates/cuda-driver/src/original_mtp_rt/tests/expert_stream_error_paths_use.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn expert_stream_error_paths_use_original_order_and_text() { let dir = TempDir::new("experts-err"); @@ -50,28 +49,16 @@ fn expert_stream_error_paths_use_original_order_and_text() { ); assert_eq!(outcome, Err(StreamError::Rt(RtError::ExpertsTruncated))); assert_eq!(chunks, 2); // two complete chunks were delivered before the short read - assert_eq!( - RtError::ExpertsTruncated.message(), - "mtp: experts.bin is truncated" - ); + assert_eq!(RtError::ExpertsTruncated.message(), "mtp: experts.bin is truncated"); // a sink failure stops the loop - let outcome = stream_experts( - &dir.0, - 20, - 8, - || Ok(()), - |o, _| if o == 8 { Err("h2d") } else { Ok(()) }, - ); + let outcome = stream_experts(&dir.0, 20, 8, || Ok(()), |o, _| if o == 8 { Err("h2d") } else { Ok(()) }); assert_eq!(outcome, Err(StreamError::Sink("h2d"))); assert!(matches!( stream_experts::<()>(&dir.0, 20, 0, || Ok(()), |_, _| Ok(())), Err(StreamError::Rt(RtError::Host)) )); assert_eq!(expert_bank_bytes(512, 1_382_400).unwrap(), 707_788_800); - assert_eq!( - expert_bank_bytes(u64::MAX, 2), - Err(RtError::ExpertSizeOverflow) - ); + assert_eq!(expert_bank_bytes(u64::MAX, 2), Err(RtError::ExpertSizeOverflow)); } #[test] @@ -82,11 +69,7 @@ fn expert_scale_scan_handles_chunk_boundaries_inside_blobs() { let mut offset = 0usize; while offset < bank.len() { let end = (offset + chunk).min(bank.len()); - assert!(expert_scales_finite( - offset as u64, - &bank[offset..end], - blob - )); + assert!(expert_scales_finite(offset as u64, &bank[offset..end], blob)); offset = end; } } @@ -127,21 +110,11 @@ fn draft_vocab_follows_the_original_size_filter() { let ids = [5i32, 0, 9, 5]; let raw: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); write(&dir, "draft_vocab.bin", &raw); - assert_eq!( - read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), - DraftVocab::Subset(ids.to_vec()) - ); + assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default).unwrap(), DraftVocab::Subset(ids.to_vec())); validate_subset(&ids, 10).unwrap(); assert_eq!(validate_subset(&ids, 9), Err(RtError::DraftVocabOutOfRange)); - assert_eq!( - validate_subset(&[-1], 10), - Err(RtError::DraftVocabOutOfRange) - ); + assert_eq!(validate_subset(&[-1], 10), Err(RtError::DraftVocabOutOfRange)); assert_eq!(validate_subset(&[], 10), Err(RtError::DraftVocabOutOfRange)); - write( - &dir, - "draft_vocab.bin", - &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4], - ); + write(&dir, "draft_vocab.bin", &vec![0u8; (DRAFT_VOCAB_MAX_IDS as usize + 1) * 4]); assert_eq!(read_draft_vocab_with(&dir.0, &dv::Setting::Default), Err(RtError::DraftVocabTooLarge)); } diff --git a/crates/cuda-driver/src/original_mtp_rt/tests/parses_getline_loop_and_skips.rs b/crates/cuda-driver/src/original_mtp_rt/tests/parses_getline_loop_and_skips.rs index 08cde364..14eddc47 100644 --- a/crates/cuda-driver/src/original_mtp_rt/tests/parses_getline_loop_and_skips.rs +++ b/crates/cuda-driver/src/original_mtp_rt/tests/parses_getline_loop_and_skips.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn parses_getline_loop_and_skips_empty_lines() { let (text, blob) = dense(); @@ -11,32 +10,16 @@ fn parses_getline_loop_and_skips_empty_lines() { assert_eq!(index.tensors().len(), TENSORS.len()); index.validate_extents(blob.len() as u64).unwrap(); index.check_required(REQUIRED).unwrap(); - let q = index - .find("self_attn.q_proj.weight", OriginalMtpTensorKind::Q8_0) - .unwrap(); + let q = index.find("self_attn.q_proj.weight", OriginalMtpTensorKind::Q8_0).unwrap(); assert_eq!((q.rows, q.columns, q.bytes), (3, 32, 102)); assert_eq!(q.offset % 256, 0); // kind-specific lookup: a bf16 tensor is not a q8 one. - assert!( - index - .find("mlp.gate.weight", OriginalMtpTensorKind::Q8_0) - .is_none() - ); - assert!( - index - .find("mlp.gate.weight", OriginalMtpTensorKind::Bf16) - .is_some() - ); + assert!(index.find("mlp.gate.weight", OriginalMtpTensorKind::Q8_0).is_none()); + assert!(index.find("mlp.gate.weight", OriginalMtpTensorKind::Bf16).is_some()); // CRLF and a missing final newline parse like std::getline + >>. let crlf = text.replace('\n', "\r\n"); - assert_eq!( - DenseIndex::parse(&crlf).unwrap().tensors().len(), - TENSORS.len() - ); - assert_eq!( - DenseIndex::parse(text.trim_end()).unwrap().tensors().len(), - TENSORS.len() - ); + assert_eq!(DenseIndex::parse(&crlf).unwrap().tensors().len(), TENSORS.len()); + assert_eq!(DenseIndex::parse(text.trim_end()).unwrap().tensors().len(), TENSORS.len()); assert_eq!(DenseIndex::parse("").unwrap().tensors().len(), 0); } @@ -53,39 +36,15 @@ fn malformed_index_lines_carry_the_original_message() { format!("{text}tail\n"), ] { let error = DenseIndex::parse(&bad).unwrap_err(); - assert!( - matches!(error, RtError::MalformedLine(_)), - "{bad:?} -> {error:?}" - ); - assert!( - error - .message() - .starts_with("mtp: malformed dense.txt line: ") - ); + assert!(matches!(error, RtError::MalformedLine(_)), "{bad:?} -> {error:?}"); + assert!(error.message().starts_with("mtp: malformed dense.txt line: ")); } - assert_eq!( - DenseIndex::parse("n é 1 1 0 1\n").unwrap_err(), - RtError::IndexNotAscii - ); - assert!(matches!( - DenseIndex::parse("a.b-c q8_0 1 32 0 34\n"), - Err(RtError::InvalidName(_)) - )); - assert!(matches!( - DenseIndex::parse("a q4 1 32 0 34\n"), - Err(RtError::UnknownKind(_)) - )); - assert!(matches!( - DenseIndex::parse("a f32 1 4 0 16\na bf16 1 4 256 8\n"), - Err(RtError::DuplicateTensor(_)) - )); - let many: String = (0..=MAX_TENSORS) - .map(|i| format!("t{i} f32 1 1 0 4\n")) - .collect(); - assert_eq!( - DenseIndex::parse(&many).unwrap_err(), - RtError::TooManyTensors - ); + assert_eq!(DenseIndex::parse("n é 1 1 0 1\n").unwrap_err(), RtError::IndexNotAscii); + assert!(matches!(DenseIndex::parse("a.b-c q8_0 1 32 0 34\n"), Err(RtError::InvalidName(_)))); + assert!(matches!(DenseIndex::parse("a q4 1 32 0 34\n"), Err(RtError::UnknownKind(_)))); + assert!(matches!(DenseIndex::parse("a f32 1 4 0 16\na bf16 1 4 256 8\n"), Err(RtError::DuplicateTensor(_)))); + let many: String = (0..=MAX_TENSORS).map(|i| format!("t{i} f32 1 1 0 4\n")).collect(); + assert_eq!(DenseIndex::parse(&many).unwrap_err(), RtError::TooManyTensors); } #[test] @@ -96,42 +55,21 @@ fn extent_validation_is_exact_and_bounded() { assert!(index.validate_extents(end - 1).is_err()); index.validate_extents(end + 5).unwrap(); for edit in [ - ( - "self_attn.q_proj.weight q8_0 3 32", - "self_attn.q_proj.weight q8_0 3 31", - ), - ( - "self_attn.q_proj.weight q8_0 3 32", - "self_attn.q_proj.weight q8_0 0 32", - ), + ("self_attn.q_proj.weight q8_0 3 32", "self_attn.q_proj.weight q8_0 3 31"), + ("self_attn.q_proj.weight q8_0 3 32", "self_attn.q_proj.weight q8_0 0 32"), ("mlp.gate.weight bf16 5 8", "mlp.gate.weight bf16 6 8"), ("fc_hidden.weight q8_0 2 64", "fc_hidden.weight q8_0 2 32"), - ( - "self_attn.k_norm.weight f32 1 8", - "self_attn.k_norm.weight f32 2 8", - ), + ("self_attn.k_norm.weight f32 1 8", "self_attn.k_norm.weight f32 2 8"), ] { let broken = DenseIndex::parse(&text.replacen(edit.0, edit.1, 1)).unwrap(); - assert!( - matches!(broken.validate_extents(end), Err(RtError::Geometry(_))), - "{edit:?}" - ); + assert!(matches!(broken.validate_extents(end), Err(RtError::Geometry(_))), "{edit:?}"); } let beyond = DenseIndex::parse("x f32 1 4 4294967296 16\n").unwrap(); - assert!(matches!( - beyond.validate_extents(end), - Err(RtError::OutOfRange(_)) - )); + assert!(matches!(beyond.validate_extents(end), Err(RtError::OutOfRange(_)))); let wrap = DenseIndex::parse("x f32 1 4 18446744073709551615 16\n").unwrap(); - assert!(matches!( - wrap.validate_extents(end), - Err(RtError::OutOfRange(_)) - )); + assert!(matches!(wrap.validate_extents(end), Err(RtError::OutOfRange(_)))); let huge = DenseIndex::parse("x q8_0 4294967296 32 0 1\n").unwrap(); - assert!(matches!( - huge.validate_extents(u64::MAX), - Err(RtError::Geometry(_)) - )); + assert!(matches!(huge.validate_extents(u64::MAX), Err(RtError::Geometry(_)))); } #[test] @@ -139,11 +77,8 @@ fn required_names_are_checked_in_source_order_by_kind() { let (text, _) = dense(); for (i, name) in REQUIRED.iter().enumerate() { // dropping the line and retyping it as bf16 both make it "missing (q8_0)" - let dropped: String = text - .lines() - .filter(|l| !l.starts_with(&format!("{name} "))) - .map(|l| format!("{l}\n")) - .collect(); + let dropped: String = + text.lines().filter(|l| !l.starts_with(&format!("{name} "))).map(|l| format!("{l}\n")).collect(); let retyped = text.replacen(&format!("{name} q8_0"), &format!("{name} bf16"), 1); for broken in [dropped, retyped] { let index = DenseIndex::parse(&broken).unwrap(); @@ -156,17 +91,12 @@ fn required_names_are_checked_in_source_order_by_kind() { let two = DenseIndex::parse( &text .lines() - .filter(|l| { - !l.starts_with("fc_hidden.weight ") && !l.starts_with("fc_embedding.weight ") - }) + .filter(|l| !l.starts_with("fc_hidden.weight ") && !l.starts_with("fc_embedding.weight ")) .map(|l| format!("{l}\n")) .collect::(), ) .unwrap(); - assert_eq!( - two.check_required(REQUIRED).unwrap_err(), - RtError::MissingRequired(REQUIRED[0]) - ); + assert_eq!(two.check_required(REQUIRED).unwrap_err(), RtError::MissingRequired(REQUIRED[0])); } #[test] @@ -187,15 +117,9 @@ fn finite_admission_rejects_each_dtype() { } else { broken[at..at + 2].copy_from_slice(&bytes); } - assert_eq!( - index.validate_finite(&broken).unwrap_err(), - RtError::NonFinite(name.to_owned()) - ); + assert_eq!(index.validate_finite(&broken).unwrap_err(), RtError::NonFinite(name.to_owned())); } - assert!(matches!( - index.validate_finite(&blob[..blob.len() - 1]), - Err(RtError::OutOfRange(_)) - )); + assert!(matches!(index.validate_finite(&blob[..blob.len() - 1]), Err(RtError::OutOfRange(_)))); } #[test] @@ -203,17 +127,10 @@ fn index_and_dense_readers_follow_original_file_semantics() { let dir = TempDir::new("read"); let (text, blob) = dense(); let missing = read_index(&dir.0).unwrap_err(); - assert!( - missing - .message() - .contains("/dense.txt (run tools/mtp_rt.py)") - ); + assert!(missing.message().contains("/dense.txt (run tools/mtp_rt.py)")); write(&dir, "dense.txt", text.as_bytes()); assert_eq!(read_index(&dir.0).unwrap().tensors().len(), TENSORS.len()); - assert_eq!( - read_dense(&dir.0).unwrap_err().message(), - "mtp: cannot read dense.bin" - ); + assert_eq!(read_dense(&dir.0).unwrap_err().message(), "mtp: cannot read dense.bin"); write(&dir, "dense.bin", &blob); assert_eq!(read_dense(&dir.0).unwrap(), blob); write(&dir, "dense.bin", b""); @@ -234,10 +151,7 @@ fn symlinked_and_non_regular_files_are_refused() { assert_eq!(read_dense(&dir.0).unwrap_err(), RtError::CannotReadDense); write(&dir, "real.txt", text.as_bytes()); std::os::unix::fs::symlink(dir.0.join("real.txt"), dir.0.join("dense.txt")).unwrap(); - assert!(matches!( - read_index(&dir.0), - Err(RtError::CannotOpenIndex { .. }) - )); + assert!(matches!(read_index(&dir.0), Err(RtError::CannotOpenIndex { .. }))); fs::create_dir(dir.0.join("experts.bin")).unwrap(); let outcome = stream_experts::<()>(&dir.0, 4, 4, || Ok(()), |_, _| Ok(())); assert_eq!(outcome, Err(StreamError::Rt(RtError::CannotOpenExperts))); @@ -273,10 +187,7 @@ fn expert_stream_matches_the_chunk_plan_and_ignores_trailing_bytes() { ) .unwrap(); assert_eq!(stored, bank); - let expected: Vec<_> = (0..total) - .step_by(chunk) - .map(|o| (o, (chunk as u64).min(total - o))) - .collect(); + let expected: Vec<_> = (0..total).step_by(chunk).map(|o| (o, (chunk as u64).min(total - o))).collect(); assert_eq!(seen, expected); } } diff --git a/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs b/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs index e0151541..0f9ffa76 100644 --- a/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs +++ b/crates/cuda-driver/src/original_pcie_copy_gpu_smoke.rs @@ -91,7 +91,11 @@ fn run(batch: bool, memory: Memory) { } let at = 16 * rng.below(((SOURCE - len) / 16) as u64) as usize; let (lo, hi) = (base + at, base + at + len); - let cuts: Vec<(usize, usize)> = if lo < locked_end && hi > locked_end { vec![(lo, locked_end), (locked_end, hi)] } else { vec![(lo, hi)] }; + let cuts: Vec<(usize, usize)> = if lo < locked_end && hi > locked_end { + vec![(lo, locked_end), (locked_end, hi)] + } else { + vec![(lo, hi)] + }; for (a, b) in cuts { let piece = &source[a - base..b - base]; expected[cursor..cursor + piece.len()].copy_from_slice(piece); @@ -101,7 +105,9 @@ fn run(batch: bool, memory: Memory) { cursor = cursor.next_multiple_of(PAGE); } stream.enqueue_copy_h2d_many(&pieces, batch).unwrap_or_else(|e| panic!("round {round}: enqueue failed: {e:?}")); - stream.synchronize().unwrap_or_else(|e| panic!("round {round}: stream failed after {} pieces: {e:?}", pieces.len())); + stream + .synchronize() + .unwrap_or_else(|e| panic!("round {round}: stream failed after {} pieces: {e:?}", pieces.len())); let mut got = vec![0u8; DEST]; dest.copy_to(&mut got).unwrap_or_else(|e| panic!("round {round}: readback failed: {e:?}")); if let Some(i) = (0..DEST).find(|&i| got[i] != expected[i]) { diff --git a/crates/cuda-driver/src/original_prefill_arena.rs b/crates/cuda-driver/src/original_prefill_arena.rs index 2186f00e..258925a0 100644 --- a/crates/cuda-driver/src/original_prefill_arena.rs +++ b/crates/cuda-driver/src/original_prefill_arena.rs @@ -2,17 +2,38 @@ //! Subspans never become owning DeviceBuffers and are never independently freed. //! A whole prompt-row lease is exclusive; producers must carry it to their //! drained output product. Allocation and a lease alone certify no model state. +use crate::original_expert_cache::OriginalCachePrefix; use crate::original_prefill_layout::{OriginalPrefillLayout, PrefillLayoutOptions, PrefillPhase}; use crate::{Context, DeviceBuffer, Error, Result, ffi}; -use crate::original_expert_cache::OriginalCachePrefix; #[derive(Clone, Copy, Debug)] pub(crate) enum OriginalPromptSpan { - R, PleEmbedding, GrRS, XHigh, XLow, Lo, LoHigh, LoLow, - Gated, Mixed, MixedHigh, MixedLow, MixedHalf, Inject, Block, + R, + PleEmbedding, + GrRS, + XHigh, + XLow, + Lo, + LoHigh, + LoLow, + Gated, + Mixed, + MixedHigh, + MixedLow, + MixedHalf, + Inject, + Block, } #[derive(Clone, Copy, Debug)] -pub(crate) enum OriginalPleSpan { Key, Qn, Gated, Value, Gate, PackedEmbedding, PackedEmbeddingLow } +pub(crate) enum OriginalPleSpan { + Key, + Qn, + Gated, + Value, + Gate, + PackedEmbedding, + PackedEmbeddingLow, +} enum Backing<'loan, 'ctx> { Owned(DeviceBuffer<'ctx>), @@ -20,7 +41,10 @@ enum Backing<'loan, 'ctx> { } impl<'loan, 'ctx> Backing<'loan, 'ctx> { fn buffer(&self) -> &DeviceBuffer<'ctx> { - match self { Self::Owned(buffer) => buffer, Self::Borrowed(buffer) => buffer } + match self { + Self::Owned(buffer) => buffer, + Self::Borrowed(buffer) => buffer, + } } } @@ -41,10 +65,14 @@ pub struct OriginalPrefillArena<'loan, 'ctx> { #[derive(Clone)] pub struct OriginalPromptLeaseIdentity(std::rc::Rc<()>); impl OriginalPromptLeaseIdentity { - pub fn same_lease(&self, other: &Self) -> bool { std::rc::Rc::ptr_eq(&self.0, &other.0) } + pub fn same_lease(&self, other: &Self) -> bool { + std::rc::Rc::ptr_eq(&self.0, &other.0) + } /// One pointer in Rows plus the actual Rc strong/weak header; clones do not /// allocate. Root's host phase ledger must include this per live row lease. - pub const fn metadata_bytes() -> usize { 3 * std::mem::size_of::() } + pub const fn metadata_bytes() -> usize { + 3 * std::mem::size_of::() + } } pub struct OriginalPromptRows<'arena, 'loan, 'ctx> { @@ -57,20 +85,29 @@ pub struct OriginalPromptRows<'arena, 'loan, 'ctx> { impl<'ctx> Context<'ctx> { pub fn original_prefill_arena( - &'ctx self, options: PrefillLayoutOptions, + &'ctx self, + options: PrefillLayoutOptions, ) -> Result> { let layout = options.carve()?; - let total = layout.borrowed_bytes.checked_add(layout.separately_owned_bytes) - .ok_or(Error::BudgetExceeded)?; - if self.is_poisoned() { return Err(Error::ContextPoisoned); } - if self.allocated_bytes().checked_add(total).is_none_or(|n| n > self.budget) - || self.memory_info()?.0 < total { return Err(Error::BudgetExceeded); } + let total = layout.borrowed_bytes.checked_add(layout.separately_owned_bytes).ok_or(Error::BudgetExceeded)?; + if self.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if self.allocated_bytes().checked_add(total).is_none_or(|n| n > self.budget) || self.memory_info()?.0 < total { + return Err(Error::BudgetExceeded); + } let buffer = self.allocate(layout.borrowed_bytes)?; - let kv_owned = if layout.separately_owned_bytes == 0 { None } - else { Some(self.allocate(layout.separately_owned_bytes)?) }; + let kv_owned = + if layout.separately_owned_bytes == 0 { None } else { Some(self.allocate(layout.separately_owned_bytes)?) }; Ok(OriginalPrefillArena { - context: self, backing: Backing::Owned(buffer), offset: 0, - bytes: layout.borrowed_bytes, layout, kv_owned, bf16x2: options.bf16x2, failed: false, + context: self, + backing: Backing::Owned(buffer), + offset: 0, + bytes: layout.borrowed_bytes, + layout, + kv_owned, + bf16x2: options.bf16x2, + failed: false, cache_prefix: None, }) } @@ -80,48 +117,95 @@ impl<'loan, 'ctx> OriginalPrefillArena<'loan, 'ctx> { /// Called only by the physical expert-arena tail loan. The mutable backing /// borrow prevents freeing or refilling the lent bytes before this owner ends. pub(crate) fn from_cache_tail( - buffer: &'loan mut DeviceBuffer<'ctx>, offset: usize, bytes: usize, + buffer: &'loan mut DeviceBuffer<'ctx>, + offset: usize, + bytes: usize, options: PrefillLayoutOptions, prefix: OriginalCachePrefix<'loan>, ) -> Result { let context = buffer.context; let layout = options.carve()?; - if context.is_poisoned() { return Err(Error::ContextPoisoned); } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } if layout.borrowed_bytes > bytes || layout.source_bytes_needed > bytes { return Err(Error::BudgetExceeded); } - buffer.handle.ok_or(Error::ContextPoisoned)? + buffer + .handle + .ok_or(Error::ContextPoisoned)? .checked_subspan(buffer.bytes, offset, bytes)? .validate_projection_extent(bytes, 256)?; - let kv_owned = if layout.separately_owned_bytes == 0 { None } - else { Some(context.allocate(layout.separately_owned_bytes)?) }; - Ok(Self { context, backing: Backing::Borrowed(buffer), offset, bytes, - layout, kv_owned, bf16x2: options.bf16x2, failed: false, cache_prefix: Some(prefix) }) + let kv_owned = if layout.separately_owned_bytes == 0 { + None + } else { + Some(context.allocate(layout.separately_owned_bytes)?) + }; + Ok(Self { + context, + backing: Backing::Borrowed(buffer), + offset, + bytes, + layout, + kv_owned, + bf16x2: options.bf16x2, + failed: false, + cache_prefix: Some(prefix), + }) + } + pub fn capacity(&self) -> usize { + self.layout.capacity } - pub fn capacity(&self) -> usize { self.layout.capacity } pub fn physically_owned_bytes(&self) -> usize { - let base = match &self.backing { Backing::Owned(_) => self.bytes, Backing::Borrowed(_) => 0 }; + let base = match &self.backing { + Backing::Owned(_) => self.bytes, + Backing::Borrowed(_) => 0, + }; base + self.kv_owned.as_ref().map_or(0, DeviceBuffer::len) } pub fn borrowed_cache_bytes(&self) -> usize { - match &self.backing { Backing::Borrowed(_) => self.bytes, Backing::Owned(_) => 0 } + match &self.backing { + Backing::Borrowed(_) => self.bytes, + Backing::Owned(_) => 0, + } } pub fn begin_rows(&mut self, rows: usize) -> Result> { - if self.failed || self.context.is_poisoned() { return Err(Error::ContextPoisoned); } - if rows == 0 || rows > self.layout.capacity { return Err(Error::InvalidQwenShape); } + if self.failed || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if rows == 0 || rows > self.layout.capacity { + return Err(Error::InvalidQwenShape); + } let b = self.backing.buffer(); - if !std::ptr::eq(self.context, b.context) { return Err(Error::ContextMismatch); } + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, self.offset, self.bytes)?; - Ok(OriginalPromptRows { arena: self, rows, identity: OriginalPromptLeaseIdentity(std::rc::Rc::new(())), drained: false }) + Ok(OriginalPromptRows { + arena: self, + rows, + identity: OriginalPromptLeaseIdentity(std::rc::Rc::new(())), + drained: false, + }) } } impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { - pub fn rows(&self) -> usize { self.rows } - pub fn lease_identity(&self) -> OriginalPromptLeaseIdentity { self.identity.clone() } - pub fn capacity(&self) -> usize { self.arena.layout.capacity } - pub(crate) fn context(&self) -> &'ctx Context<'ctx> { self.arena.context } - pub(crate) fn is_failed(&self) -> bool { self.arena.failed || self.arena.context.is_poisoned() } + pub fn rows(&self) -> usize { + self.rows + } + pub fn lease_identity(&self) -> OriginalPromptLeaseIdentity { + self.identity.clone() + } + pub fn capacity(&self) -> usize { + self.arena.layout.capacity + } + pub(crate) fn context(&self) -> &'ctx Context<'ctx> { + self.arena.context + } + pub(crate) fn is_failed(&self) -> bool { + self.arena.failed || self.arena.context.is_poisoned() + } pub(crate) fn mark_failed(&mut self) { self.arena.failed = true; self.arena.context.poisoned.set(true); @@ -129,12 +213,16 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { /// Actual prefill cache hit from the unlent prefix of the very allocation /// backing this row lease. The lent scratch range can never be read as a /// resident expert. This remains a private nonowning driver handle. - pub(crate) fn cache_expert_span( - &self, layer: usize, expert: usize, - ) -> Result> { - if self.is_failed() { return Err(Error::ContextPoisoned); } - let Some(prefix) = self.arena.cache_prefix.as_ref() else { return Ok(None); }; - let Some((offset, bytes)) = prefix.completed_slot_span(layer, expert)? else { return Ok(None); }; + pub(crate) fn cache_expert_span(&self, layer: usize, expert: usize) -> Result> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + let Some(prefix) = self.arena.cache_prefix.as_ref() else { + return Ok(None); + }; + let Some((offset, bytes)) = prefix.completed_slot_span(layer, expert)? else { + return Ok(None); + }; if offset.checked_add(bytes).is_none_or(|end| end > self.arena.offset) { return Err(Error::OutputAliasesInput); } @@ -143,13 +231,20 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { } pub(crate) fn common_span(&self, role: OriginalPromptSpan) -> Result<(ffi::BufferHandle, usize)> { let name = match role { - OriginalPromptSpan::R => "R", OriginalPromptSpan::PleEmbedding => "ple_emb", - OriginalPromptSpan::GrRS => "grs", OriginalPromptSpan::XHigh => "xn16", - OriginalPromptSpan::XLow => "xn16_lo", OriginalPromptSpan::Lo => "lo", - OriginalPromptSpan::LoHigh => "lo16", OriginalPromptSpan::LoLow => "lo16_lo", - OriginalPromptSpan::Gated => "gated", OriginalPromptSpan::Mixed => "mixed", - OriginalPromptSpan::MixedHigh => "mixed_bf", OriginalPromptSpan::MixedLow => "mixed_bf_lo", - OriginalPromptSpan::MixedHalf => "mixed_h", OriginalPromptSpan::Inject => "inj", + OriginalPromptSpan::R => "R", + OriginalPromptSpan::PleEmbedding => "ple_emb", + OriginalPromptSpan::GrRS => "grs", + OriginalPromptSpan::XHigh => "xn16", + OriginalPromptSpan::XLow => "xn16_lo", + OriginalPromptSpan::Lo => "lo", + OriginalPromptSpan::LoHigh => "lo16", + OriginalPromptSpan::LoLow => "lo16_lo", + OriginalPromptSpan::Gated => "gated", + OriginalPromptSpan::Mixed => "mixed", + OriginalPromptSpan::MixedHigh => "mixed_bf", + OriginalPromptSpan::MixedLow => "mixed_bf_lo", + OriginalPromptSpan::MixedHalf => "mixed_h", + OriginalPromptSpan::Inject => "inj", OriginalPromptSpan::Block => "bo", }; self.span(PrefillPhase::Common, name) @@ -157,47 +252,58 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { /// Literal stage_dev slots in this real exclusive prompt arena. No owning /// device view is fabricated and the whole row lease outlives both streams. pub(crate) fn copy_ring_slots(&self) -> Result { - if self.is_failed() { return Err(Error::ContextPoisoned); } + if self.is_failed() { + return Err(Error::ContextPoisoned); + } let count = self.arena.layout.ring_slots; - if !(8..=512).contains(&count) { return Err(Error::InvalidQwenShape); } + if !(8..=512).contains(&count) { + return Err(Error::InvalidQwenShape); + } Ok(count) } pub(crate) fn copy_ring_span(&self, index: usize) -> Result<(ffi::BufferHandle, usize)> { - if self.is_failed() { return Err(Error::ContextPoisoned); } + if self.is_failed() { + return Err(Error::ContextPoisoned); + } let span = self.arena.layout.staging_span(index).ok_or(Error::InvalidQwenShape)?; if span.name != "stage_dev" || span.phase != PrefillPhase::Common { return Err(Error::InvalidQwenShape); } let b = self.arena.backing.buffer(); let offset = self.arena.offset.checked_add(span.offset).ok_or(Error::InvalidSize)?; - let handle = b.handle.ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, span.bytes)?; + let handle = b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, span.bytes)?; handle.validate_projection_extent(span.bytes, 256)?; Ok((handle, span.bytes)) } /// Genuine unused shared region after final physical R, borrowed from /// this exclusive actual row lease. No second region allocation or owner. - pub(crate) fn draft_kv_region(&self)->Result<(ffi::BufferHandle,usize)>{ - if self.is_failed(){return Err(Error::ContextPoisoned);} - let bytes=self.arena.layout.shared_region_bytes; - let offset=self.arena.offset.checked_add(self.arena.layout.shared_region_offset).ok_or(Error::InvalidSize)?; - let b=self.arena.backing.buffer(); - let h=b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes,offset,bytes)?; - h.validate_projection_extent(bytes,256)?;Ok((h,bytes)) + pub(crate) fn draft_kv_region(&self) -> Result<(ffi::BufferHandle, usize)> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + let bytes = self.arena.layout.shared_region_bytes; + let offset = self.arena.offset.checked_add(self.arena.layout.shared_region_offset).ok_or(Error::InvalidSize)?; + let b = self.arena.backing.buffer(); + let h = b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, bytes)?; + h.validate_projection_extent(bytes, 256)?; + Ok((h, bytes)) } pub(crate) fn ple_subbatch_capacity(&self) -> Result { // Literal prefill.cpp PLE SB = min(T, region_bytes/per_token). - let per_token = (3 * 10240 + 2560 + 4) * 4 - + 2560 * if self.arena.bf16x2 { 4 } else { 2 } + 4096; + let per_token = (3 * 10240 + 2560 + 4) * 4 + 2560 * if self.arena.bf16x2 { 4 } else { 2 } + 4096; let capacity = self.rows.min(self.arena.layout.shared_region_bytes / per_token); - if capacity == 0 { return Err(Error::BudgetExceeded); } + if capacity == 0 { + return Err(Error::BudgetExceeded); + } Ok(capacity) } - pub(crate) fn ple_span( - &self, role: OriginalPleSpan, rows: usize, - ) -> Result<(ffi::BufferHandle, usize)> { - if self.is_failed() { return Err(Error::ContextPoisoned); } - if rows == 0 || rows > self.ple_subbatch_capacity()? { return Err(Error::InvalidQwenShape); } + pub(crate) fn ple_span(&self, role: OriginalPleSpan, rows: usize) -> Result<(ffi::BufferHandle, usize)> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + if rows == 0 || rows > self.ple_subbatch_capacity()? { + return Err(Error::InvalidQwenShape); + } if matches!(role, OriginalPleSpan::PackedEmbeddingLow) && !self.arena.bf16x2 { return Err(Error::InvalidQwenShape); } @@ -212,37 +318,39 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { ]; let mut offset = self.arena.layout.shared_region_offset; for (candidate, columns, width) in shapes { - let bytes = rows.checked_mul(columns).and_then(|n| n.checked_mul(width)) - .ok_or(Error::InvalidSize)?; + let bytes = rows.checked_mul(columns).and_then(|n| n.checked_mul(width)).ok_or(Error::InvalidSize)?; if std::mem::discriminant(&candidate) == std::mem::discriminant(&role) { let end = offset.checked_add(bytes).ok_or(Error::InvalidSize)?; - let limit = self.arena.layout.shared_region_offset - .checked_add(self.arena.layout.shared_region_bytes).ok_or(Error::InvalidSize)?; - if end > limit { return Err(Error::BudgetExceeded); } + let limit = self + .arena + .layout + .shared_region_offset + .checked_add(self.arena.layout.shared_region_bytes) + .ok_or(Error::InvalidSize)?; + if end > limit { + return Err(Error::BudgetExceeded); + } let b = self.arena.backing.buffer(); let offset = self.arena.offset.checked_add(offset).ok_or(Error::InvalidSize)?; - let handle = b.handle.ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, bytes)?; + let handle = b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, bytes)?; handle.validate_projection_extent(bytes, 256)?; return Ok((handle, bytes)); } // Original local carve_f adds only255, unlike global Alloc::take. - offset = offset.checked_add(bytes.checked_add(255).ok_or(Error::InvalidSize)? & !255) + offset = offset + .checked_add(bytes.checked_add(255).ok_or(Error::InvalidSize)? & !255) .ok_or(Error::InvalidSize)?; } Err(Error::InvalidQwenShape) } - pub(crate) fn span( - &self, phase: PrefillPhase, name: &str, - ) -> Result<(ffi::BufferHandle, usize)> { + pub(crate) fn span(&self, phase: PrefillPhase, name: &str) -> Result<(ffi::BufferHandle, usize)> { if self.arena.failed || self.arena.context.is_poisoned() { return Err(Error::ContextPoisoned); } let span = self.arena.layout.span(phase, name).ok_or(Error::InvalidQwenShape)?; let b = self.arena.backing.buffer(); let offset = self.arena.offset.checked_add(span.offset).ok_or(Error::InvalidSize)?; - let handle = b.handle.ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, span.bytes)?; + let handle = b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, span.bytes)?; handle.validate_projection_extent(span.bytes, 256)?; Ok((handle, span.bytes)) } @@ -251,20 +359,26 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> { /// the actual producing phase product. Explicit Original streams are still /// required for source-equivalent stream ordering at the caller seam. pub(crate) fn drain(&mut self) -> Result<()> { - if self.drained { return Ok(()); } + if self.drained { + return Ok(()); + } // deferred guard words (LELEKA_PREFILL_DEFER_GUARDS) are looked at before anything leaves the device if let Err(e) = crate::deferred_status::resolve(self.arena.context) { self.arena.failed = true; return Err(e); } let result = self.arena.context.synchronize(); - if result.is_err() { self.arena.failed = true; } + if result.is_err() { + self.arena.failed = true; + } self.drained = result.is_ok(); result } } impl Drop for OriginalPromptRows<'_, '_, '_> { fn drop(&mut self) { - if !self.drained && self.drain().is_err() { self.arena.failed = true; } + if !self.drained && self.drain().is_err() { + self.arena.failed = true; + } } } diff --git a/crates/cuda-driver/src/original_prefill_layout.rs b/crates/cuda-driver/src/original_prefill_layout.rs index 6622423e..3d7a0823 100644 --- a/crates/cuda-driver/src/original_prefill_layout.rs +++ b/crates/cuda-driver/src/original_prefill_layout.rs @@ -19,7 +19,12 @@ const MMQ_GROUP: usize = 16; const MMQ_TAIL: usize = 4096; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PrefillPhase { Common, Gdn, Qsa, Moe } +pub enum PrefillPhase { + Common, + Gdn, + Qsa, + Moe, +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PrefillSpan { @@ -75,8 +80,12 @@ pub struct OriginalPrefillLayout { pub ring_slots: usize, } -fn add(a: usize, b: usize) -> Result { a.checked_add(b).ok_or(Error::InvalidSize) } -fn mul(a: usize, b: usize) -> Result { a.checked_mul(b).ok_or(Error::InvalidSize) } +fn add(a: usize, b: usize) -> Result { + a.checked_add(b).ok_or(Error::InvalidSize) +} +fn mul(a: usize, b: usize) -> Result { + a.checked_mul(b).ok_or(Error::InvalidSize) +} struct Alloc { used: usize, @@ -112,10 +121,17 @@ fn q8_bytes(rows: usize, columns: usize) -> Result { fn gdn(t: usize) -> Result { let mut a = Alloc::new(PrefillPhase::Gdn); for (name, columns, width) in [ - ("qkv", C, 4), ("z", ZV, 4), ("ab", 2 * HV, 4), - ("gate", HV, 4), ("beta", HV, 4), ("hbuf", C, 4), - ("y", ZV, 4), ("y_h", ZV, 2), - ] { a.rows(name, t, columns, width)?; } + ("qkv", C, 4), + ("z", ZV, 4), + ("ab", 2 * HV, 4), + ("gate", HV, 4), + ("beta", HV, 4), + ("hbuf", C, 4), + ("y", ZV, 4), + ("y_h", ZV, 2), + ] { + a.rows(name, t, columns, width)?; + } Ok(a) } @@ -123,11 +139,18 @@ fn qsa(o: &PrefillLayoutOptions) -> Result { let mut a = Alloc::new(PrefillPhase::Qsa); let t = o.capacity; for (name, columns, width) in [ - ("Kc", 512, 4), ("Vc", 512, 4), ("Qf", 12288, 4), - ("q", ZV, 4), ("idx_raw", 128, 4), ("q_idx", 512, 4), - ("attn", ZV, 4), ("attn_h", ZV, 2), + ("Kc", 512, 4), + ("Vc", 512, 4), + ("Qf", 12288, 4), + ("q", ZV, 4), + ("idx_raw", 128, 4), + ("q_idx", 512, 4), + ("attn", ZV, 4), + ("attn_h", ZV, 2), ("sel_ids", o.qsa_selection, 4), - ] { a.rows(name, t, columns, width)?; } + ] { + a.rows(name, t, columns, width)?; + } a.rows("sel_scores", 256, o.qsa_max_blocks, 4)?; // qsa_decode_attn_scratch_floats: ceil(cap/64)*heads*(256+2)+64. let chunks = add(o.qsa_selection, 63)? / 64; @@ -141,15 +164,21 @@ fn moe(o: &PrefillLayoutOptions) -> Result { let tk = mul(t, K)?; let mut a = Alloc::new(PrefillPhase::Moe); a.rows("logits", t, o.n_expert, 4)?; - for name in ["w", "ids", "slot_dev", "src_dev"] { a.take(name, tk, 4)?; } - if o.mmq_fallback { a.rows("Xs", tk, N, 2)?; } + for name in ["w", "ids", "slot_dev", "src_dev"] { + a.take(name, tk, 4)?; + } + if o.mmq_fallback { + a.rows("Xs", tk, N, 2)?; + } a.rows("GU", tk, 1280, 4)?; - if o.mmq_fallback { a.rows("Hh", tk, 640, 2)?; } + if o.mmq_fallback { + a.rows("Hh", tk, 640, 2)?; + } a.rows("Dm", tk, N, 4)?; - for (name, columns, width) in [ - ("sgate", 640, 4), ("sup", 640, 4), ("sh_h", 640, 2), - ("shared", N, 4), ("sg", 1, 4), - ] { a.rows(name, t, columns, width)?; } + for (name, columns, width) in [("sgate", 640, 4), ("sup", 640, 4), ("sh_h", 640, 2), ("shared", N, 4), ("sg", 1, 4)] + { + a.rows(name, t, columns, width)?; + } if o.mmq_any { a.take("Xq", q8_bytes(tk, N)?, 1)?; a.rows("H", tk, 640, 4)?; @@ -166,16 +195,24 @@ fn take_kv(a: &mut Alloc, stage: PrefillKvStage) -> Result<()> { a.rows("kv_v_pool", rows, head_dim, 2)?; } PrefillKvStage::Q4 { rows, head_dim } => { - if head_dim == 0 || !head_dim.is_multiple_of(32) { return Err(Error::InvalidSize); } + if head_dim == 0 || !head_dim.is_multiple_of(32) { + return Err(Error::InvalidSize); + } let per_head = mul(head_dim / 32, 18)?; a.rows("kv_k_q4", rows, per_head, 1)?; a.rows("kv_v_q4", rows, per_head, 1)?; } PrefillKvStage::Int8 { rows, head_dim, without_key } => { - if head_dim == 0 || !head_dim.is_multiple_of(64) { return Err(Error::InvalidSize); } - if !without_key { a.rows("kv_k_q", rows, head_dim, 1)?; } + if head_dim == 0 || !head_dim.is_multiple_of(64) { + return Err(Error::InvalidSize); + } + if !without_key { + a.rows("kv_k_q", rows, head_dim, 1)?; + } a.rows("kv_v_q", rows, head_dim, 1)?; - if !without_key { a.rows("kv_k_scale", rows, head_dim / 64, 2)?; } + if !without_key { + a.rows("kv_k_scale", rows, head_dim / 64, 2)?; + } a.rows("kv_v_scale", rows, head_dim / 64, 2)?; } } @@ -188,23 +225,34 @@ impl PrefillLayoutOptions { return Err(Error::InvalidSize); } let selected = self.ring_override.unwrap_or(if self.pinned_share >= 0.9 { 384 } else { 96 }); - if self.ring_override == Some(8) { return Ok(8); } + if self.ring_override == Some(8) { + return Ok(8); + } Ok(if self.capacity >= self.stream_all_min { selected.clamp(16, 512) } else { 8 }) } pub fn carve(&self) -> Result { - if self.capacity == 0 || self.n_expert == 0 || self.n_expert > i32::MAX as usize - || self.qsa_heads == 0 || self.qsa_selection == 0 || self.qsa_max_blocks == 0 - || self.max_expert_blob == 0 || self.bf16x2_hc && !self.bf16x2 + if self.capacity == 0 + || self.n_expert == 0 + || self.n_expert > i32::MAX as usize + || self.qsa_heads == 0 + || self.qsa_selection == 0 + || self.qsa_max_blocks == 0 + || self.max_expert_blob == 0 + || self.bf16x2_hc && !self.bf16x2 || self.mmq_any && (self.mmq_gu_max == 0 || self.mmq_down_max == 0) - { return Err(Error::InvalidSize); } + { + return Err(Error::InvalidSize); + } let t = self.capacity; let mut a = Alloc::new(PrefillPhase::Common); a.take("gemm_scratch", GEMM_SCRATCH, 2)?; a.take("gemm_workspace", GEMM_WS, 1)?; a.rows("emb", t, N, 4)?; a.rows("R", t, D, 4)?; - if self.gr_unfused { a.rows("xn", t, D, 4)?; } + if self.gr_unfused { + a.rows("xn", t, D, 4)?; + } a.rows("grs", t, HC, 4)?; a.rows("xn16", t, D, 2)?; a.rows("lo", t, LR, 4)?; @@ -219,13 +267,17 @@ impl PrefillLayoutOptions { a.rows("xn16_lo", t, D, 2)?; a.rows("lo16_lo", t, LR, 2)?; } - if self.bf16x2 { a.rows("mixed_bf_lo", t, N, 2)?; } + if self.bf16x2 { + a.rows("mixed_bf_lo", t, N, 2)?; + } a.rows("steps_dev", t, 4, 4)?; let mut shared = [gdn(t)?, qsa(self)?, moe(self)?]; let shared_region_bytes = shared.iter().map(|x| x.used).max().ok_or(Error::InvalidSize)?; let shared_region_offset = a.take("attention_moe_region", shared_region_bytes, 1)?; for layout in &mut shared { - for span in &mut layout.spans { span.offset = add(span.offset, shared_region_offset)?; } + for span in &mut layout.spans { + span.offset = add(span.offset, shared_region_offset)?; + } a.spans.try_reserve(layout.spans.len()).map_err(|_| Error::HostAllocation)?; a.spans.append(&mut layout.spans); } @@ -243,25 +295,39 @@ impl PrefillLayoutOptions { let ring_slots = self.original_ring_slots()?; // Names intentionally share one role; the index is the span occurrence. // room for three page-aligned supersets (claude/ledger: LELEKA_PREFILL_ALIGNED_COPY, default on) - let slot_bytes = if crate::mapped_expert_bank::aligned_copy_enabled() { add(self.max_expert_blob, crate::mapped_expert_bank::ALIGNED_COPY_SLACK)? } else { self.max_expert_blob }; - for _ in 0..ring_slots { a.take("stage_dev", slot_bytes, 1)?; } + let slot_bytes = if crate::mapped_expert_bank::aligned_copy_enabled() { + add(self.max_expert_blob, crate::mapped_expert_bank::ALIGNED_COPY_SLACK)? + } else { + self.max_expert_blob + }; + for _ in 0..ring_slots { + a.take("stage_dev", slot_bytes, 1)?; + } a.rows("ple_emb", t, N, 4)?; a.take("ple_norm", D, 4)?; let mut owned = Alloc::new(PrefillPhase::Common); - if self.kv_stage_own { take_kv(&mut owned, self.kv_stage)?; } - else { take_kv(&mut a, self.kv_stage)?; } + if self.kv_stage_own { + take_kv(&mut owned, self.kv_stage)?; + } else { + take_kv(&mut a, self.kv_stage)?; + } // Preserve Original's deliberately separate sizing sequence: it reserves // T*D FP32 `xn` even in fused mode, but does not count carve's T*HC `grs`. let xn = (add(mul(mul(t, D)?, 4)?, 511)? & !255) as usize; let grs = (add(mul(mul(t, HC)?, 4)?, 511)? & !255) as usize; - let source_count = if self.gr_unfused { a.used.checked_sub(grs) } - else { add(a.used, xn)?.checked_sub(grs) }.ok_or(Error::InvalidSize)?; + let source_count = if self.gr_unfused { a.used.checked_sub(grs) } else { add(a.used, xn)?.checked_sub(grs) } + .ok_or(Error::InvalidSize)?; let source_bytes_needed = add(source_count, 8 << 20)?; Ok(OriginalPrefillLayout { - capacity: t, spans: a.spans, borrowed_bytes: a.used, - separately_owned_bytes: owned.used, separately_owned_spans: owned.spans, + capacity: t, + spans: a.spans, + borrowed_bytes: a.used, + separately_owned_bytes: owned.used, + separately_owned_spans: owned.spans, source_bytes_needed, - shared_region_offset, shared_region_bytes, ring_slots, + shared_region_offset, + shared_region_bytes, + ring_slots, }) } } diff --git a/crates/cuda-driver/src/original_prefill_schedule.rs b/crates/cuda-driver/src/original_prefill_schedule.rs index 6541b4bb..fe765a4e 100644 --- a/crates/cuda-driver/src/original_prefill_schedule.rs +++ b/crates/cuda-driver/src/original_prefill_schedule.rs @@ -45,14 +45,23 @@ pub struct RingPolicy { #[derive(Clone, Debug, PartialEq, Eq)] pub enum PleOp { /// `ple_gather(c0, buf)` on the host thread (batch read of the chunk's rows into pinned buffer `buf`). - Gather { c0: usize, buf: usize }, + Gather { + c0: usize, + buf: usize, + }, /// `gather_batch_device` into `ple_emb` (KAR GPU cache): the rows never go through the pinned buffers. GatherDevice, /// `cudaMemcpyAsync(ple_emb, ple_emb_host[buf])` on the compute stream. - Upload { buf: usize }, - RecordCopied { buf: usize }, + Upload { + buf: usize, + }, + RecordCopied { + buf: usize, + }, /// `cudaEventSynchronize(ple_copied[buf])` on the host: that buffer's upload (a chunk ago) is done. - SyncCopied { buf: usize }, + SyncCopied { + buf: usize, + }, /// `std::async(ple_gather)`: the next chunk is read on a thread while the GPU runs this one. Async, } @@ -204,11 +213,11 @@ mod tests; mod impl_default_for_ringpolicy; #[allow(unused_imports)] -pub use impl_default_for_ringpolicy::ring_slots; -#[allow(unused_imports)] pub use impl_default_for_ringpolicy::chunks; #[allow(unused_imports)] pub use impl_default_for_ringpolicy::fuse_after_half; +#[allow(unused_imports)] +pub use impl_default_for_ringpolicy::ring_slots; mod impl_planner; #[allow(unused_imports)] pub use impl_planner::check_trace; diff --git a/crates/cuda-driver/src/original_prefill_schedule/impl_planner.rs b/crates/cuda-driver/src/original_prefill_schedule/impl_planner.rs index 9413c732..93cae30f 100644 --- a/crates/cuda-driver/src/original_prefill_schedule/impl_planner.rs +++ b/crates/cuda-driver/src/original_prefill_schedule/impl_planner.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Planner { pub fn new() -> Self { Self::default() @@ -56,7 +55,11 @@ impl Planner { } self.push(SchedOp::Chunk(chunk_index)); let stream_all = cfg.ring > STAGE && cfg.rows >= cfg.stream_all_min; - let seq = if stream_all { StreamSequence::build(src, lb, le) } else { StreamSequence { entries: vec![], seq_start: vec![0; src.n_layers + 1], jobs: vec![] } }; + let seq = if stream_all { + StreamSequence::build(src, lb, le) + } else { + StreamSequence { entries: vec![], seq_start: vec![0; src.n_layers + 1], jobs: vec![] } + }; if stream_all && !seq.jobs.is_empty() { self.push(SchedOp::StagerStart(seq.jobs.clone())); } diff --git a/crates/cuda-driver/src/original_prefill_schedule/tests.rs b/crates/cuda-driver/src/original_prefill_schedule/tests.rs index 7475b90b..176c52f0 100644 --- a/crates/cuda-driver/src/original_prefill_schedule/tests.rs +++ b/crates/cuda-driver/src/original_prefill_schedule/tests.rs @@ -25,7 +25,8 @@ fn golden_expert_stream_traces_match_the_extracted_original() { let (pin_mod, tr_mod) = (u(&p["pinned_mod"]), u(&p["transient_mod"])); let resident = move |_l: usize, e: usize| res_mod != 0 && e % res_mod == res_rem; let pinned = move |_l: usize, e: usize| pin_mod != 0 && e % pin_mod == 0; - let transient = move |l: usize, e: usize| !(pin_mod != 0 && e % pin_mod == 0) && tr_mod != 0 && (e + l) % tr_mod == 0; + let transient = + move |l: usize, e: usize| !(pin_mod != 0 && e % pin_mod == 0) && tr_mod != 0 && (e + l) % tr_mod == 0; let view = SourceView { n_layers, n_expert, @@ -34,8 +35,14 @@ fn golden_expert_stream_traces_match_the_extracted_original() { pinned: &pinned, transient: &transient, }; - let orders: Vec> = p["orders"].as_array().unwrap().iter().map(|o| o.as_array().unwrap().iter().map(u).collect()).collect(); - let cfg = StreamConfig { ring: u(&p["ring"]), stager_ring: u(&p["stager_ring"]), rows: u(&p["rows"]), stream_all_min: STREAM_ALL_MIN_DEFAULT }; + let orders: Vec> = + p["orders"].as_array().unwrap().iter().map(|o| o.as_array().unwrap().iter().map(u).collect()).collect(); + let cfg = StreamConfig { + ring: u(&p["ring"]), + stager_ring: u(&p["stager_ring"]), + rows: u(&p["rows"]), + stream_all_min: STREAM_ALL_MIN_DEFAULT, + }; let mut planner = Planner::new(); for chunk in 0..u(&p["chunks"]) { planner.plan_chunk(chunk, &cfg, &view, lb, le, &orders).unwrap_or_else(|e| panic!("{name}: {e:?}")); @@ -107,7 +114,11 @@ fn ring_slots_is_the_original_rule() { assert_eq!(ring_slots(4096, &RingPolicy { pinned_share: 0.9, ..d }), 384); // the layer split's override (#340) assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 200, ..d }), 200); - assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 4, ..d }), 16, "the setter's value is clamped, not honoured as STAGE"); + assert_eq!( + ring_slots(4096, &RingPolicy { ring_override: 4, ..d }), + 16, + "the setter's value is clamped, not honoured as STAGE" + ); assert_eq!(ring_slots(4096, &RingPolicy { ring_override: 9999, ..d }), RING_MAX); // STRATA_PREFILL_RING wins, and exactly STAGE selects routed-only staging for any chunk size assert_eq!(ring_slots(4096, &RingPolicy { env_ring: Some(100), ring_override: 200, ..d }), 100); @@ -144,7 +155,14 @@ fn stream_sequence_orders_layers_then_experts_and_skips_resident() { let resident = |l: usize, e: usize| (l + e) % 3 == 0; let pinned = |_l: usize, e: usize| e % 2 == 0; let transient = |_l: usize, e: usize| e == 5; - let view = SourceView { n_layers: 5, n_expert: 8, cache_present: true, resident: &resident, pinned: &pinned, transient: &transient }; + let view = SourceView { + n_layers: 5, + n_expert: 8, + cache_present: true, + resident: &resident, + pinned: &pinned, + transient: &transient, + }; let seq = StreamSequence::build(&view, 1, 3); assert_eq!(seq.seq_start.len(), 6); assert_eq!(seq.seq_start[0], 0); @@ -166,7 +184,14 @@ fn the_checker_rejects_unsafe_schedules() { // build a safe trace, then break it three ways let none = |_: usize, _: usize| false; let pinned = |_: usize, _: usize| true; - let view = SourceView { n_layers: 2, n_expert: 40, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; + let view = SourceView { + n_layers: 2, + n_expert: 40, + cache_present: false, + resident: &none, + pinned: &pinned, + transient: &none, + }; let cfg = StreamConfig { ring: 16, stager_ring: 16, rows: 2048, stream_all_min: 1024 }; let orders = vec![(0..40).collect::>(), (0..40).collect::>()]; let mut planner = Planner::new(); @@ -203,7 +228,14 @@ fn the_checker_rejects_unsafe_schedules() { fn staged_path_never_uses_more_than_eight_slots_and_keeps_the_lookahead() { let none = |_: usize, _: usize| false; let pinned = |_: usize, e: usize| e % 2 == 0; - let view = SourceView { n_layers: 3, n_expert: 64, cache_present: false, resident: &none, pinned: &pinned, transient: &none }; + let view = SourceView { + n_layers: 3, + n_expert: 64, + cache_present: false, + resident: &none, + pinned: &pinned, + transient: &none, + }; // ring 384 but only 100 rows: below stream_all_min, so the staged walk runs let cfg = StreamConfig { ring: 384, stager_ring: 16, rows: 100, stream_all_min: 1024 }; let order: Vec = (0..64).collect(); @@ -217,14 +249,16 @@ fn staged_path_never_uses_more_than_eight_slots_and_keeps_the_lookahead() { // the first compute of a layer happens only after STAGE experts were staged ahead (lookahead 7 + the expert) let layer0 = planner.ops.iter().position(|o| matches!(o, SchedOp::Layer(0))).unwrap(); let first_compute = planner.ops[layer0..].iter().position(|o| matches!(o, SchedOp::Compute { .. })).unwrap(); - let copies_before = planner.ops[layer0..layer0 + first_compute].iter().filter(|o| matches!(o, SchedOp::RecordCopied(_))).count(); + let copies_before = + planner.ops[layer0..layer0 + first_compute].iter().filter(|o| matches!(o, SchedOp::RecordCopied(_))).count(); assert_eq!(copies_before, STAGE); } #[test] fn rejects_unsorted_or_out_of_range_routing() { let none = |_: usize, _: usize| false; - let view = SourceView { n_layers: 1, n_expert: 4, cache_present: false, resident: &none, pinned: &none, transient: &none }; + let view = + SourceView { n_layers: 1, n_expert: 4, cache_present: false, resident: &none, pinned: &none, transient: &none }; let cfg = StreamConfig { ring: 8, stager_ring: 16, rows: 10, stream_all_min: 1024 }; assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![2, 1]]), Err(PlanError::OrderNotAscending)); assert_eq!(Planner::new().plan_chunk(0, &cfg, &view, 0, 1, &[vec![0, 4]]), Err(PlanError::RoutedIdOutOfRange)); diff --git a/crates/cuda-driver/src/original_prefill_schedule_crosscheck.rs b/crates/cuda-driver/src/original_prefill_schedule_crosscheck.rs index 91e413af..7443d174 100644 --- a/crates/cuda-driver/src/original_prefill_schedule_crosscheck.rs +++ b/crates/cuda-driver/src/original_prefill_schedule_crosscheck.rs @@ -1,9 +1,9 @@ //! Linux-side agreement tests between the pure `original_prefill_schedule` model and the driver owners that carry the //! same Original rules (`PrefillLayoutOptions::original_ring_slots`, `OriginalStreamAllOptions::eligible`). //! (The pure model itself is host-tested on any platform by oracle/run_forward_leaves_host_tests.sh.) +use crate::OriginalStreamAllOptions; use crate::original_prefill_layout::{PrefillKvStage, PrefillLayoutOptions}; use crate::original_prefill_schedule::{RingPolicy, STAGE, ring_slots}; -use crate::OriginalStreamAllOptions; fn options(capacity: usize, pinned_share: f64, ring_override: Option) -> PrefillLayoutOptions { PrefillLayoutOptions { @@ -36,7 +36,12 @@ fn layout_ring_slots_agree_with_the_original_rule() { let layout = options(capacity, share, over).original_ring_slots().unwrap(); let model = ring_slots( capacity, - &RingPolicy { env_ring: over.map(|v| v as i64), ring_override: 0, pinned_share: share, stream_all_min: 1024 }, + &RingPolicy { + env_ring: over.map(|v| v as i64), + ring_override: 0, + pinned_share: share, + stream_all_min: 1024, + }, ); assert_eq!(layout, model, "capacity {capacity} share {share} override {over:?}"); } diff --git a/crates/cuda-driver/src/original_sampler.rs b/crates/cuda-driver/src/original_sampler.rs index b5dab786..22fea3cf 100644 --- a/crates/cuda-driver/src/original_sampler.rs +++ b/crates/cuda-driver/src/original_sampler.rs @@ -19,7 +19,13 @@ const ENTRIES: &[&CStr] = &[ ]; // Root supplies only a pinned NUL-terminated compiled Original asset after integration. // No executable placeholder and no environment substitution. -const ASSET_PIN: Option<(usize, [u8; 32])> = Some((475756, [89, 26, 163, 221, 165, 47, 65, 240, 209, 149, 65, 108, 240, 147, 150, 37, 104, 210, 248, 61, 111, 118, 42, 150, 120, 190, 97, 148, 108, 236, 183, 91])); +const ASSET_PIN: Option<(usize, [u8; 32])> = Some(( + 475756, + [ + 89, 26, 163, 221, 165, 47, 65, 240, 209, 149, 65, 108, 240, 147, 150, 37, 104, 210, 248, 61, 111, 118, 42, 150, + 120, 190, 97, 148, 108, 236, 183, 91, + ], +)); pub use crate::original_sampler_params::SamplerParams; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SamplerPath { @@ -54,7 +60,7 @@ pub struct OriginalSampler<'ctx> { mod asset_fn; #[allow(unused_imports)] use asset_fn::asset; -mod impl_originalsampler; mod impl_drop_for_originalsampler; +mod impl_originalsampler; #[allow(unused_imports)] pub(crate) use impl_drop_for_originalsampler::sampler_asset_sealed; diff --git a/crates/cuda-driver/src/original_sampler/asset_fn.rs b/crates/cuda-driver/src/original_sampler/asset_fn.rs index 82bdb841..d27d0c9f 100644 --- a/crates/cuda-driver/src/original_sampler/asset_fn.rs +++ b/crates/cuda-driver/src/original_sampler/asset_fn.rs @@ -8,22 +8,11 @@ pub(super) fn asset() -> Option<&'static [u8]> { } impl Launch { pub(super) fn new(entry: usize, grid: [u32; 2], block: u32, shared: u32, args: Vec) -> Self { - Self { - entry, - grid, - block, - shared, - args: Command::new(args), - } + Self { entry, grid, block, shared, args: Command::new(args) } } } impl Context<'_> { - pub fn original_sampler( - &self, - rows: usize, - vocab: usize, - history: usize, - ) -> Result> { + pub fn original_sampler(&self, rows: usize, vocab: usize, history: usize) -> Result> { OriginalSampler::new(self, rows, vocab, history) } } diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs index 76855b4c..aeaad3c5 100644 --- a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalSampler<'ctx> { pub(in super::super) fn new( context: &'ctx Context<'ctx>, @@ -15,26 +14,10 @@ impl<'ctx> OriginalSampler<'ctx> { return Err(Error::InvalidQwenShape); } let ptx = asset().ok_or(Error::UnsupportedQwenOperation)?; - let sizes = [ - 0, - rows * history.max(1) * 4, - rows * 4, - 64, - (HIST + DRAFTS) * 4, - 4, - 4, - vocab * 4, - vocab * 4, - ]; - let charge = sizes - .iter() - .try_fold(0usize, |a, b| a.checked_add(*b)) - .ok_or(Error::InvalidSize)?; + let sizes = [0, rows * history.max(1) * 4, rows * 4, 64, (HIST + DRAFTS) * 4, 4, 4, vocab * 4, vocab * 4]; + let charge = sizes.iter().try_fold(0usize, |a, b| a.checked_add(*b)).ok_or(Error::InvalidSize)?; let required = charge.checked_add(RESERVE).ok_or(Error::InvalidSize)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -82,12 +65,7 @@ impl<'ctx> OriginalSampler<'ctx> { Ok(owner) } pub fn allocated_bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .chain(self.retired.iter()) - .map(DeviceBuffer::len) - .sum() + self.buffers.iter().flatten().chain(self.retired.iter()).map(DeviceBuffer::len).sum() } pub fn host_bytes(&self) -> usize { self.mapped.as_ref().map_or(0, MappedAllocation::bytes) @@ -105,17 +83,10 @@ impl<'ctx> OriginalSampler<'ctx> { Ok(()) } pub(in super::super) fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) + self.buffers.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned) } pub(in super::super) fn address(&self, i: usize) -> Result { - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address()) + Ok(self.buffer(i)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) } pub(in super::super) fn admit(&self, buffer: &DeviceBuffer<'_>, bytes: usize) -> Result<()> { self.validate_context(self.context)?; @@ -123,10 +94,7 @@ impl<'ctx> OriginalSampler<'ctx> { return Err(Error::ContextMismatch); } if buffer.bytes != bytes { - return Err(Error::ShapeMismatch { - expected: bytes, - actual: buffer.bytes, - }); + return Err(Error::ShapeMismatch { expected: bytes, actual: buffer.bytes }); } let h = buffer.handle.ok_or(Error::ContextPoisoned)?; h.validate_projection_extent(bytes, 4)?; @@ -152,18 +120,12 @@ impl<'ctx> OriginalSampler<'ctx> { if self.scratch_failed != 0 && entries >= self.scratch_failed { return Ok(false); } - self.retired - .try_reserve(1) - .map_err(|_| Error::HostAllocation)?; + self.retired.try_reserve(1).map_err(|_| Error::HostAllocation)?; let want = (self.scratch_entries * 2).min(CAP).max(entries); for n in [want, entries] { let bytes = n * 8; let required = bytes + RESERVE; - if self - .context - .allocated_bytes() - .checked_add(required) - .is_none_or(|v| v > self.context.budget) + if self.context.allocated_bytes().checked_add(required).is_none_or(|v| v > self.context.budget) || self.context.memory_info()?.0 < required { continue; @@ -176,11 +138,7 @@ impl<'ctx> OriginalSampler<'ctx> { self.scratch_entries = n; return Ok(true); } - Err(Error::BudgetExceeded) - | Err(Error::Driver { - operation: "cuMemAlloc_v2", - code: 2, - }) => {} + Err(Error::BudgetExceeded) | Err(Error::Driver { operation: "cuMemAlloc_v2", code: 2 }) => {} Err(error) => { self.failed = true; return Err(error); @@ -191,10 +149,7 @@ impl<'ctx> OriginalSampler<'ctx> { Ok(false) } pub(in super::super) fn upload(&mut self, i: usize, bytes: &[u8]) -> Result<()> { - let r = self.buffers[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(bytes); + let r = self.buffers[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(bytes); if r.is_err() { self.failed = true; } diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs index 71c20984..a0176f9b 100644 --- a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalSampler<'ctx> { pub(in super::super) fn run( &mut self, @@ -14,15 +13,12 @@ impl<'ctx> OriginalSampler<'ctx> { self.validate_context(self.context)?; let mut ids = Vec::new(); if read_ids { - ids.try_reserve_exact(self.rows * 4) - .map_err(|_| Error::HostAllocation)?; + ids.try_reserve_exact(self.rows * 4).map_err(|_| Error::HostAllocation)?; ids.resize(self.rows * 4, 0); } let mut probability = Vec::new(); if prob { - probability - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; + probability.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; probability.resize(4, 0); } let guard = self.context.enter()?; @@ -39,16 +35,15 @@ impl<'ctx> OriginalSampler<'ctx> { } } if operation.is_ok() && read_ids { - operation = self.context.driver.api.copy_to( - self.buffer(2)?.handle.ok_or(Error::ContextPoisoned)?, - &mut ids, - ); + operation = + self.context.driver.api.copy_to(self.buffer(2)?.handle.ok_or(Error::ContextPoisoned)?, &mut ids); } if operation.is_ok() && prob { - operation = self.context.driver.api.copy_to( - self.buffer(5)?.handle.ok_or(Error::ContextPoisoned)?, - &mut probability, - ); + operation = self + .context + .driver + .api + .copy_to(self.buffer(5)?.handle.ok_or(Error::ContextPoisoned)?, &mut probability); } let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); @@ -61,14 +56,7 @@ impl<'ctx> OriginalSampler<'ctx> { return combine(combine(operation, sync), pop).map(|()| (Vec::new(), [0; 4])); } combine(combine(operation, sync), pop)?; - Ok(( - ids, - if prob { - probability.try_into().expect("four bytes") - } else { - [0; 4] - }, - )) + Ok((ids, if prob { probability.try_into().expect("four bytes") } else { [0; 4] })) } /// One actual verify window. Histories are actual row-specific IDs from the /// caller's consumed tail/window, not a capability or inferred accepted prefix. @@ -99,31 +87,20 @@ impl<'ctx> OriginalSampler<'ctx> { && params.temperature > 0.0 && self.split_scratch(rows.max(16) * self.vocab.div_ceil(4096) * 64)?; let mut h = Vec::new(); - h.try_reserve_exact(self.rows * self.history.max(1) * 4) - .map_err(|_| Error::HostAllocation)?; + h.try_reserve_exact(self.rows * self.history.max(1) * 4).map_err(|_| Error::HostAllocation)?; for id in histories { h.extend_from_slice(&id.to_le_bytes()); } h.resize(self.rows * self.history.max(1) * 4, 0xff); self.upload(1, &h)?; let source = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); - let history = if self.history > 0 { - Arg::Address(self.address(1)?) - } else { - Arg::NullAddress - }; + let history = if self.history > 0 { Arg::Address(self.address(1)?) } else { Arg::NullAddress }; let output = self.address(2)?; let nv = self.vocab as i32; let nt = rows as i32; - let shared = if params.penalty_last_n > 0 { - self.vocab.div_ceil(32) as u32 * 4 - } else { - 0 - }; + let shared = if params.penalty_last_n > 0 { self.vocab.div_ceil(32) as u32 * 4 } else { 0 }; let mut commands = Vec::new(); - commands - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; + commands.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; if params.greedy || params.temperature <= 0.0 { commands.push(Launch::new( 0, @@ -158,12 +135,7 @@ impl<'ctx> OriginalSampler<'ctx> { ], )); } else if split { - let k = (if params.top_k > 0 && params.top_k < 64 { - params.top_k - } else { - 64 - }) - .min(nv); + let k = (if params.top_k > 0 && params.top_k < 64 { params.top_k } else { 64 }).min(nv); let blocks = self.vocab.div_ceil(4096) as i32; commands.push(Launch::new( 3, @@ -217,8 +189,7 @@ impl<'ctx> OriginalSampler<'ctx> { } let (bytes, _) = result?; let mut ids = Vec::new(); - ids.try_reserve_exact(rows) - .map_err(|_| Error::HostAllocation)?; + ids.try_reserve_exact(rows).map_err(|_| Error::HostAllocation)?; for b in bytes[..rows * 4].chunks_exact(4) { let id = i32::from_le_bytes(b.try_into().expect("word")); if id < 0 || id >= nv { diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs index a25b5422..c10bde1b 100644 --- a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalSampler<'ctx> { /// Install the actual draft-head vocabulary once. Empty means whole vocabulary. /// Literal `MtpDrafter::setup_coupled`: `sub_to_id` is the draft head's raw `dvocab_` array @@ -15,18 +14,14 @@ impl<'ctx> OriginalSampler<'ctx> { return Err(Error::InvalidQwenShape); } let mut forward = Vec::new(); - forward - .try_reserve_exact(self.vocab) - .map_err(|_| Error::HostAllocation)?; + forward.try_reserve_exact(self.vocab).map_err(|_| Error::HostAllocation)?; forward.resize(self.vocab, -1i32); forward[..subset.len()].copy_from_slice(subset); - let inverse = crate::original_mtp_coupled::subset_inverse(self.vocab, subset) - .map_err(|_| Error::InvalidQwenShape)?; + let inverse = + crate::original_mtp_coupled::subset_inverse(self.vocab, subset).map_err(|_| Error::InvalidQwenShape)?; for (slot, values) in [(7, forward), (8, inverse)] { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(self.vocab * 4) - .map_err(|_| Error::HostAllocation)?; + bytes.try_reserve_exact(self.vocab * 4).map_err(|_| Error::HostAllocation)?; for v in values { bytes.extend_from_slice(&v.to_le_bytes()); } @@ -41,9 +36,7 @@ impl<'ctx> OriginalSampler<'ctx> { self.validate_context(self.context)?; params.validate()?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(HIST * 4) - .map_err(|_| Error::HostAllocation)?; + bytes.try_reserve_exact(HIST * 4).map_err(|_| Error::HostAllocation)?; for v in base { bytes.extend_from_slice(&v.to_le_bytes()); } @@ -84,12 +77,7 @@ impl<'ctx> OriginalSampler<'ctx> { } /// Actual single draft logits, genuine caller's cell, successive j in one round. /// Literal penalties -> widest split -> coupled merge writes the real ring. - pub fn sample_coupled( - &mut self, - logits: &mut DeviceBuffer<'_>, - cell: i32, - j: usize, - ) -> Result<(i32, f32)> { + pub fn sample_coupled(&mut self, logits: &mut DeviceBuffer<'_>, cell: i32, j: usize) -> Result<(i32, f32)> { // cell -1 is `draft_first` for a window at p = 0 (counter 0); see coupled_draft_counter. if cell < -1 || j >= DRAFTS || self.next_draft != Some(j) { return Err(Error::InvalidQwenShape); @@ -102,16 +90,8 @@ impl<'ctx> OriginalSampler<'ctx> { self.upload(6, &cell.to_le_bytes())?; let blocks = nv.div_ceil(4096) as i32; let kpart = nv.min(64) as i32; - let sub = if self.subset.is_some() { - Arg::Address(self.address(7)?) - } else { - Arg::NullAddress - }; - let inverse = if self.subset.is_some() { - Arg::Address(self.address(8)?) - } else { - Arg::NullAddress - }; + let sub = if self.subset.is_some() { Arg::Address(self.address(7)?) } else { Arg::NullAddress }; + let inverse = if self.subset.is_some() { Arg::Address(self.address(8)?) } else { Arg::NullAddress }; let l = logits.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); let mut commands = [ Launch::new( @@ -174,11 +154,7 @@ impl<'ctx> OriginalSampler<'ctx> { let (ids, p) = result?; let id = i32::from_le_bytes(ids[..4].try_into().expect("word")); let probability = f32::from_le_bytes(p); - if id < 0 - || id as usize >= self.vocab - || !probability.is_finite() - || !(0.0..=1.0).contains(&probability) - { + if id < 0 || id as usize >= self.vocab || !probability.is_finite() || !(0.0..=1.0).contains(&probability) { self.failed = true; return Err(Error::InvalidDriverValue("Original coupled pick")); } diff --git a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs index 5b287656..f016b7eb 100644 --- a/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs +++ b/crates/cuda-driver/src/original_sampler/impl_originalsampler/impl_originalsampler_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> OriginalSampler<'ctx> { pub(in super::super) fn close_inner(&mut self) -> Result<()> { if self.module.is_none() diff --git a/crates/cuda-driver/src/original_sampler_ffi.rs b/crates/cuda-driver/src/original_sampler_ffi.rs index e42fb52e..c3e9fde9 100644 --- a/crates/cuda-driver/src/original_sampler_ffi.rs +++ b/crates/cuda-driver/src/original_sampler_ffi.rs @@ -1,30 +1,73 @@ //! Private closed Original sampler module ABI. No caller raw pointers or dynamic symbol resolver. -use crate::{Error, Result, combine}; use crate::original_sampler::SamplerParams; +use crate::{Error, Result, combine}; use std::ffi::CStr; -pub(crate) enum Arg { Address(u64), NullAddress, I32(i32), Params(SamplerParams) } -pub(crate) struct Command { values: Vec, null: u64, pointers: Vec<*mut std::ffi::c_void>, addresses: Vec } -impl Command { pub(crate) fn new(values: Vec) -> Self { Self { values, null: 0, pointers: Vec::new(), addresses: Vec::new() } } } -#[cfg(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64"))] +pub(crate) enum Arg { + Address(u64), + NullAddress, + I32(i32), + Params(SamplerParams), +} +pub(crate) struct Command { + values: Vec, + null: u64, + pointers: Vec<*mut std::ffi::c_void>, + addresses: Vec, +} +impl Command { + pub(crate) fn new(values: Vec) -> Self { + Self { values, null: 0, pointers: Vec::new(), addresses: Vec::new() } + } +} +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { -use super::*; -use libc::{c_int,c_uint,c_void}; -type Destroy=unsafe extern "C" fn(*mut c_void)->c_int; -type ModuleLoad=unsafe extern "C" fn(*mut *mut c_void,*const c_void)->c_int; -type ModuleFunction=unsafe extern "C" fn(*mut *mut c_void,*mut c_void,*const libc::c_char)->c_int; -type Launch=unsafe extern "C" fn(*mut c_void,c_uint,c_uint,c_uint,c_uint,c_uint,c_uint,c_uint,*mut c_void,*mut *mut c_void,*mut *mut c_void)->c_int; -struct Library(*mut c_void); -impl Library { fn open(name:&'static CStr)->Result { -// SAFETY: fixed private library name and owned dlopen reference. -let p=unsafe{libc::dlopen(name.as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)}; -if p.is_null(){Err(Error::LibraryUnavailable)}else{Ok(Self(p))} } } -impl Drop for Library {fn drop(&mut self){ // SAFETY: actual owned dlopen handle. -unsafe{libc::dlclose(self.0);} }} -macro_rules! symbol {($l:ident,$s:literal,$t:ty)=>{{ -// SAFETY: exact fixed Linux CUDA symbol and signature. -let p=unsafe{libc::dlsym($l.0,$s.as_ptr())}; if p.is_null(){return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI")));} -unsafe{std::mem::transmute::<*mut c_void,$t>(p)} }}; } -fn check(op:&'static str,c:c_int)->Result<()> {if c==0{Ok(())}else{Err(Error::Driver{operation:op,code:c})}} + use super::*; + use libc::{c_int, c_uint, c_void}; + type Destroy = unsafe extern "C" fn(*mut c_void) -> c_int; + type ModuleLoad = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; + type ModuleFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; + type Launch = unsafe extern "C" fn( + *mut c_void, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, + ) -> c_int; + struct Library(*mut c_void); + impl Library { + fn open(name: &'static CStr) -> Result { + // SAFETY: fixed private library name and owned dlopen reference. + let p = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if p.is_null() { Err(Error::LibraryUnavailable) } else { Ok(Self(p)) } + } + } + impl Drop for Library { + fn drop(&mut self) { + // SAFETY: actual owned dlopen handle. + unsafe { + libc::dlclose(self.0); + } + } + } + macro_rules! symbol { + ($l:ident,$s:literal,$t:ty) => {{ + // SAFETY: exact fixed Linux CUDA symbol and signature. + let p = unsafe { libc::dlsym($l.0, $s.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol($s.to_str().expect("fixed ABI"))); + } + unsafe { std::mem::transmute::<*mut c_void, $t>(p) } + }}; + } + fn check(op: &'static str, c: c_int) -> Result<()> { + if c == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: c }) } + } pub(crate) struct KernelModule { _library: Option, module: Option, @@ -47,24 +90,17 @@ fn check(op:&'static str,c:c_int)->Result<()> {if c==0{Ok(())}else{Err(Error::Dr module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } owner.module = Some(m as usize); for entry in entries { let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. - check("cuModuleGetFunction", unsafe { - function(&mut f, m, entry.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); } @@ -88,17 +124,11 @@ fn check(op:&'static str,c:c_int)->Result<()> {if c==0{Ok(())}else{Err(Error::Dr if grid[0] == 0 || grid[1] == 0 || !matches!(block, 32 | 128 | 256 | 1024) || shared > 32768 { return Err(Error::InvalidQwenShape); } - let function = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.pointers.clear(); - args.pointers - .try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; + args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; + args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; args.addresses.resize(args.values.len(), 0); for (index, arg) in args.values.iter_mut().enumerate() { args.pointers.push(match arg { @@ -107,7 +137,7 @@ fn check(op:&'static str,c:c_int)->Result<()> {if c==0{Ok(())}else{Err(Error::Dr // the unspecified Rust representation of BufferHandle. args.addresses[index] = *x; (&mut args.addresses[index] as *mut u64).cast() - }, + } Arg::NullAddress => (&mut args.null as *mut u64).cast(), Arg::I32(x) => (x as *mut i32).cast(), Arg::Params(x) => (x as *mut SamplerParams).cast(), @@ -156,13 +186,28 @@ fn check(op:&'static str,c:c_int)->Result<()> {if c==0{Ok(())}else{Err(Error::Dr } } } -#[cfg(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64"))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::KernelModule; -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] pub(crate) struct KernelModule; -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] impl KernelModule { -pub(crate) fn load(_: &'static[u8],_: &'static[&'static CStr])->Result{Err(Error::UnsupportedPlatform)} -pub(crate) fn launch(&self,_:usize,_:[u32;2],_:u32,_:u32,args:&mut Command)->Result<()> {let _=(&args.values,&args.null,&args.pointers,&args.addresses);Err(Error::UnsupportedPlatform)} -pub(crate) fn close(self)->Result<()> {Ok(())} + pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn launch(&self, _: usize, _: [u32; 2], _: u32, _: u32, args: &mut Command) -> Result<()> { + let _ = (&args.values, &args.null, &args.pointers, &args.addresses); + Err(Error::UnsupportedPlatform) + } + pub(crate) fn close(self) -> Result<()> { + Ok(()) + } } diff --git a/crates/cuda-driver/src/original_sampler_mapped.rs b/crates/cuda-driver/src/original_sampler_mapped.rs index 0a9d9f56..c527d06f 100644 --- a/crates/cuda-driver/src/original_sampler_mapped.rs +++ b/crates/cuda-driver/src/original_sampler_mapped.rs @@ -1,11 +1,7 @@ //! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free. use crate::{Error, Result}; const BYTES: usize = 64 + 4096 * 4; // mapped request parameters and authentic penalty-ring base. -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; use std::ffi::c_void; @@ -24,14 +20,7 @@ mod enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -54,9 +43,7 @@ mod enabled { impl MappedAllocation { pub(crate) fn new() -> Result { // SAFETY: NUL-terminated literal name; the returned handle is owned by `Library` (dlclose on Drop) and null-checked next. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -70,22 +57,14 @@ mod enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - free, - }; + let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, free }; // SAFETY: `ptr` is the live cuMemHostAlloc block just allocated; the out-pointer is a valid u64 and flags are 0. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -101,9 +80,7 @@ mod enabled { } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { let p = self.host.ok_or(Error::ContextPoisoned)?; @@ -183,12 +160,7 @@ mod enabled { } } fn owner(b: &Block) -> MappedAllocation { - MappedAllocation { - library: None, - host: Some(b.addr()), - alias: b.addr() as u64, - free: fake_free, - } + MappedAllocation { library: None, host: Some(b.addr()), alias: b.addr() as u64, free: fake_free } } #[test] fn mapped_audit_sampler_params_and_history_fit_exactly_and_close_frees_once() { @@ -213,11 +185,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::MappedAllocation; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/original_sampler_params.rs b/crates/cuda-driver/src/original_sampler_params.rs index ecd0ac09..9b3113d5 100644 --- a/crates/cuda-driver/src/original_sampler_params.rs +++ b/crates/cuda-driver/src/original_sampler_params.rs @@ -21,9 +21,7 @@ pub struct SamplerParams { pub greedy: bool, tail: [u8; 7], } -const _: () = assert!( - std::mem::size_of::() == 64 && std::mem::align_of::() == 8 -); +const _: () = assert!(std::mem::size_of::() == 64 && std::mem::align_of::() == 8); impl Default for SamplerParams { fn default() -> Self { Self { @@ -46,16 +44,9 @@ impl Default for SamplerParams { } impl SamplerParams { pub fn validate(&self) -> Result<()> { - if ![ - self.top_p, - self.min_p, - self.temperature, - self.penalty_repeat, - self.penalty_freq, - self.penalty_present, - ] - .iter() - .all(|v| v.is_finite()) + if ![self.top_p, self.min_p, self.temperature, self.penalty_repeat, self.penalty_freq, self.penalty_present] + .iter() + .all(|v| v.is_finite()) || self.top_p < 0.0 || self.top_p > 1.0 || self.top_k < 0 @@ -130,12 +121,7 @@ mod tests { let samples = abi["samples"].as_array().unwrap(); assert!(samples.len() >= 12); for sample in samples { - let want: Vec = sample["bytes"] - .as_array() - .unwrap() - .iter() - .map(|b| b.as_u64().unwrap() as u8) - .collect(); + let want: Vec = sample["bytes"].as_array().unwrap().iter().map(|b| b.as_u64().unwrap() as u8).collect(); assert_eq!(params(&sample["params"]).bytes().to_vec(), want); } let p = params(&samples[3]["params"]); diff --git a/crates/cuda-driver/src/original_serve_assets.rs b/crates/cuda-driver/src/original_serve_assets.rs index b5b42ebc..8feeaf83 100644 --- a/crates/cuda-driver/src/original_serve_assets.rs +++ b/crates/cuda-driver/src/original_serve_assets.rs @@ -90,10 +90,12 @@ mod tests { // The three native-head assets, the sampler, the two verifier PTX and the two MTP session assets, // then one entry per window producer the recorder still cannot capture and per unsealed window asset. assert_eq!(count, 8 + crate::UNBOUND_PRODUCERS.len() + crate::unsealed_window_assets().len()); - assert!(status - .iter() - .filter(|a| matches!(a.kind, OriginalAssetKind::WindowProducer | OriginalAssetKind::WindowAsset)) - .all(|a| !a.sealed)); + assert!( + status + .iter() + .filter(|a| matches!(a.kind, OriginalAssetKind::WindowProducer | OriginalAssetKind::WindowAsset)) + .all(|a| !a.sealed) + ); assert_eq!(original_serve_assets_sealed(), status.iter().all(|a| a.sealed)); } } diff --git a/crates/cuda-driver/src/original_session_qsa_init.rs b/crates/cuda-driver/src/original_session_qsa_init.rs index c69e7ee8..0b77823e 100644 --- a/crates/cuda-driver/src/original_session_qsa_init.rs +++ b/crates/cuda-driver/src/original_session_qsa_init.rs @@ -8,8 +8,9 @@ //! a failed pinned allocation leaves session initialization failed, and no //! cache/index state can be published. -use super::{OriginalRopeScaling, OriginalRopeTable, OriginalSessionQsaLayout, - OriginalSessionSpan, OriginalSessionState}; +use super::{ + OriginalRopeScaling, OriginalRopeTable, OriginalSessionQsaLayout, OriginalSessionSpan, OriginalSessionState, +}; use crate::{Error, Result}; /// Opaque RAII mapped-host owner. The backend decides its concrete driver type; @@ -30,8 +31,13 @@ pub(crate) trait OriginalQsaInitBackend { /// Device zero on one actual span, queued on the session initialization stream. fn zero_device(&mut self, span: OriginalSessionSpan) -> Result<()>; /// `rope_table_set`; called only for native n_rot==64 primary tables. - fn register_native_rope(&mut self, cos: OriginalSessionSpan, sin: OriginalSessionSpan, - positions: usize, scaling: OriginalRopeScaling) -> Result<()>; + fn register_native_rope( + &mut self, + cos: OriginalSessionSpan, + sin: OriginalSessionSpan, + positions: usize, + scaling: OriginalRopeScaling, + ) -> Result<()>; /// Literal final `cudaDeviceSynchronize` after table/map initialization. fn synchronize(&mut self) -> Result<()>; } @@ -48,22 +54,29 @@ pub(crate) struct OriginalQsaInitResources { fn bytes_i32(values: &[i32]) -> Vec { let mut result = Vec::with_capacity(values.len() * 4); - for value in values { result.extend_from_slice(&value.to_le_bytes()); } + for value in values { + result.extend_from_slice(&value.to_le_bytes()); + } result } fn bytes_f32(values: &[f32]) -> Vec { let mut result = Vec::with_capacity(values.len() * 4); - for value in values { result.extend_from_slice(&value.to_ne_bytes()); } + for value in values { + result.extend_from_slice(&value.to_ne_bytes()); + } result } fn zero_spans(layout: &OriginalSessionQsaLayout) -> Result> { let mut out = Vec::new(); out.try_reserve_exact(9).map_err(|_| Error::HostAllocation)?; - for name in ["k_q", "k_scale", "v_q4", "k_q4", "v_q", "v_scale", "k_pool", "v_pool", - "idx_tail", "idx_dead", "idx_pooled"] { - if let Ok(span) = layout.span(name) { out.push(span); } + for name in + ["k_q", "k_scale", "v_q4", "k_q4", "v_q", "v_scale", "k_pool", "v_pool", "idx_tail", "idx_dead", "idx_pooled"] + { + if let Ok(span) = layout.span(name) { + out.push(span); + } } Ok(out) } @@ -73,19 +86,26 @@ impl<'ctx> OriginalSessionState<'ctx> { /// has `owns_rope`; all later states share its exact two device spans. #[allow(clippy::too_many_arguments)] pub(crate) fn initialize_qsa( - &mut self, backend: &mut B, ordinal: usize, n_rot: usize, + &mut self, + backend: &mut B, + ordinal: usize, + n_rot: usize, scaling: OriginalRopeScaling, ) -> Result> { self.validate_context(self.context)?; let primary_ordinal = self.layout.qsa_ord0; - let layout = self.layout.qsa.get(ordinal).and_then(Option::as_ref) - .ok_or(Error::InvalidQwenShape)?.clone(); - if ordinal < primary_ordinal || ordinal >= primary_ordinal + self.layout.qsa_alloc - || n_rot != 64 || layout.host_step_bytes != 20 { + let layout = self.layout.qsa.get(ordinal).and_then(Option::as_ref).ok_or(Error::InvalidQwenShape)?.clone(); + if ordinal < primary_ordinal + || ordinal >= primary_ordinal + self.layout.qsa_alloc + || n_rot != 64 + || layout.host_step_bytes != 20 + { return Err(Error::InvalidQwenShape); } // Source rejects K8V4 with resident streaming before host allocation. - if layout.kv_hybrid && layout.mode == 1 { return Err(Error::UnsupportedQwenOperation); } + if layout.kv_hybrid && layout.mode == 1 { + return Err(Error::UnsupportedQwenOperation); + } // Exactly two mandatory mapped allocations, then initialized host_step[kStepCount]=0. let mut host_step = backend.mapped_host(layout.host_step_bytes)?; @@ -98,7 +118,9 @@ impl<'ctx> OriginalSessionState<'ctx> { let upload = table.upload_plan(layout.cos, layout.sin)?; backend.upload(upload.cos, &bytes_f32(&table.cos))?; backend.upload(upload.sin, &bytes_f32(&table.sin))?; - if upload.registry_required { backend.register_native_rope(upload.cos, upload.sin, self.layout.max_cells, scaling)?; } + if upload.registry_required { + backend.register_native_rope(upload.cos, upload.sin, self.layout.max_cells, scaling)?; + } self.layout.qsa[ordinal].as_mut().ok_or(Error::InvalidQwenShape)?.owns_rope = true; } else { let primary = self.layout.qsa_primary()?; @@ -111,7 +133,9 @@ impl<'ctx> OriginalSessionState<'ctx> { 0 => { let mut identity = Vec::new(); identity.try_reserve_exact(layout.pages).map_err(|_| Error::HostAllocation)?; - for page in 0..layout.pages { identity.push(i32::try_from(page).map_err(|_| Error::InvalidSize)?); } + for page in 0..layout.pages { + identity.push(i32::try_from(page).map_err(|_| Error::InvalidSize)?); + } backend.upload(layout.span("page_table")?, &bytes_i32(&identity))?; } 1 => backend.reset_stream_map(&layout)?, @@ -128,8 +152,12 @@ impl<'ctx> OriginalSessionState<'ctx> { pub(crate) fn zero_qsa(&self, backend: &mut B, ordinal: usize) -> Result<()> { self.validate_context(self.context)?; let layout = self.layout.qsa.get(ordinal).and_then(Option::as_ref).ok_or(Error::InvalidQwenShape)?; - for span in zero_spans(layout)? { backend.zero_device(span)?; } - if layout.mode == 1 { backend.reset_stream_map(layout)?; } + for span in zero_spans(layout)? { + backend.zero_device(span)?; + } + if layout.mode == 1 { + backend.reset_stream_map(layout)?; + } Ok(()) } } diff --git a/crates/cuda-driver/src/original_session_rope.rs b/crates/cuda-driver/src/original_session_rope.rs index c4a6dd3b..5e169f00 100644 --- a/crates/cuda-driver/src/original_session_rope.rs +++ b/crates/cuda-driver/src/original_session_rope.rs @@ -8,13 +8,17 @@ //! angles on the device. Rust and the Original must be compared on the target //! libc before this module is used as a numerical-parity claim. -use super::{add, mul, OriginalSessionSpan}; +use super::{OriginalSessionSpan, add, mul}; use crate::{Error, Result}; const PI: f64 = 3.14159265358979323846; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum OriginalRopeScalingType { None, Linear, YaRN } +pub(crate) enum OriginalRopeScalingType { + None, + Linear, + YaRN, +} /// Direct field-for-field source port of `strata::kernels::RopeScaling`. #[derive(Clone, Copy, Debug, PartialEq)] @@ -48,19 +52,25 @@ impl Default for OriginalRopeScaling { impl OriginalRopeScaling { pub(crate) fn freq_scale(self) -> f64 { - if self.kind == OriginalRopeScalingType::None { 1.0 } - else if self.freq_scale_in > 0.0 { self.freq_scale_in } - else { 1.0 / self.factor } + if self.kind == OriginalRopeScalingType::None { + 1.0 + } else if self.freq_scale_in > 0.0 { + self.freq_scale_in + } else { + 1.0 / self.factor + } } pub(crate) fn mscale(self) -> f64 { - if self.ext_factor == 0.0 { self.attn_factor } - else { self.attn_factor * (1.0 + 0.1 * (1.0 / self.freq_scale()).ln()) } + if self.ext_factor == 0.0 { + self.attn_factor + } else { + self.attn_factor * (1.0 + 0.1 * (1.0 / self.freq_scale()).ln()) + } } fn corr_dim(self, n_rot: usize, beta: f64) -> f64 { - n_rot as f64 * (self.orig_ctx / (beta * 2.0 * PI)).ln() - / (2.0 * self.freq_base.ln()) + n_rot as f64 * (self.orig_ctx / (beta * 2.0 * PI)).ln() / (2.0 * self.freq_base.ln()) } pub(crate) fn corr_dims(self, n_rot: usize) -> (f64, f64) { @@ -72,17 +82,31 @@ impl OriginalRopeScaling { /// Equivalent to `rope_scaling_invalid`: values inert under `none` remain /// accepted by source policy after frequency-base validation. pub(crate) fn validate(self) -> Result<()> { - if !self.freq_base.is_finite() || self.freq_base <= 1.0 { return Err(Error::InvalidQwenShape); } - if self.kind == OriginalRopeScalingType::None { return Ok(()); } - if !self.factor.is_finite() || self.factor < 1.0 - || !self.freq_scale_in.is_finite() || self.freq_scale_in < 0.0 - || !self.freq_scale().is_finite() || self.freq_scale() <= 0.0 - || !self.orig_ctx.is_finite() || self.orig_ctx < 1.0 - || !self.ext_factor.is_finite() || self.ext_factor < 0.0 - || !self.attn_factor.is_finite() || self.attn_factor <= 0.0 - || !self.beta_fast.is_finite() || self.beta_fast <= 0.0 - || !self.beta_slow.is_finite() || self.beta_slow <= 0.0 - || !self.mscale().is_finite() || self.mscale() <= 0.0 { + if !self.freq_base.is_finite() || self.freq_base <= 1.0 { + return Err(Error::InvalidQwenShape); + } + if self.kind == OriginalRopeScalingType::None { + return Ok(()); + } + if !self.factor.is_finite() + || self.factor < 1.0 + || !self.freq_scale_in.is_finite() + || self.freq_scale_in < 0.0 + || !self.freq_scale().is_finite() + || self.freq_scale() <= 0.0 + || !self.orig_ctx.is_finite() + || self.orig_ctx < 1.0 + || !self.ext_factor.is_finite() + || self.ext_factor < 0.0 + || !self.attn_factor.is_finite() + || self.attn_factor <= 0.0 + || !self.beta_fast.is_finite() + || self.beta_fast <= 0.0 + || !self.beta_slow.is_finite() + || self.beta_slow <= 0.0 + || !self.mscale().is_finite() + || self.mscale() <= 0.0 + { return Err(Error::InvalidQwenShape); } Ok(()) @@ -105,7 +129,9 @@ pub(crate) struct OriginalRopeTable { impl OriginalRopeTable { pub(crate) fn build(n_rot: usize, max_positions: usize, scaling: OriginalRopeScaling) -> Result { - if n_rot == 0 || n_rot % 2 != 0 || max_positions == 0 { return Err(Error::InvalidQwenShape); } + if n_rot == 0 || n_rot % 2 != 0 || max_positions == 0 { + return Err(Error::InvalidQwenShape); + } scaling.validate()?; let half = n_rot / 2; let len = mul(max_positions, half)?; @@ -118,41 +144,49 @@ impl OriginalRopeTable { if scaling.kind == OriginalRopeScalingType::None { // `build_rope_table(int,double,...)`, statement order preserved. - for p in 0..max_positions { for i in 0..half { - let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64); - let ang = p as f64 * inv; - cos[p * half + i] = ang.cos() as f32; - sin[p * half + i] = ang.sin() as f32; - }} + for p in 0..max_positions { + for i in 0..half { + let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64); + let ang = p as f64 * inv; + cos[p * half + i] = ang.cos() as f32; + sin[p * half + i] = ang.sin() as f32; + } + } } else { let fs = scaling.freq_scale(); let ms = scaling.mscale(); let (low, high) = scaling.corr_dims(n_rot); let correct = scaling.ext_factor != 0.0; - for p in 0..max_positions { for i in 0..half { - let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64); - let extrap = p as f64 * inv; - let interp = fs * extrap; - let mut ang = interp; - if correct { - let ramp = yarn_ramp(low as f32, high as f32, i) as f64 * scaling.ext_factor; - ang = interp * (1.0 - ramp) + extrap * ramp; + for p in 0..max_positions { + for i in 0..half { + let inv = scaling.freq_base.powf(-2.0 * i as f64 / n_rot as f64); + let extrap = p as f64 * inv; + let interp = fs * extrap; + let mut ang = interp; + if correct { + let ramp = yarn_ramp(low as f32, high as f32, i) as f64 * scaling.ext_factor; + ang = interp * (1.0 - ramp) + extrap * ramp; + } + cos[p * half + i] = (ang.cos() * ms) as f32; + sin[p * half + i] = (ang.sin() * ms) as f32; } - cos[p * half + i] = (ang.cos() * ms) as f32; - sin[p * half + i] = (ang.sin() * ms) as f32; - }} + } } Ok(Self { n_rot, max_positions, scaling, cos, sin }) } - pub(crate) fn bytes(&self) -> Result { mul(add(self.cos.len(), self.sin.len())?, 4) } + pub(crate) fn bytes(&self) -> Result { + mul(add(self.cos.len(), self.sin.len())?, 4) + } /// Exact destination selection. The caller must copy `cos` then `sin`, /// call the native registry only for n_rot==64, and synchronize before /// a capture that can observe the table. pub(crate) fn upload_plan(&self, cos: OriginalSessionSpan, sin: OriginalSessionSpan) -> Result { let bytes = mul(self.cos.len(), 4)?; - if cos.bytes != bytes || sin.bytes != bytes { return Err(Error::InvalidSize); } + if cos.bytes != bytes || sin.bytes != bytes { + return Err(Error::InvalidSize); + } Ok(OriginalRopeUpload { cos, sin, bytes, registry_required: self.n_rot == 64 }) } } diff --git a/crates/cuda-driver/src/original_session_state.rs b/crates/cuda-driver/src/original_session_state.rs index 4d1ca8a2..3afe6db9 100644 --- a/crates/cuda-driver/src/original_session_state.rs +++ b/crates/cuda-driver/src/original_session_state.rs @@ -2,252 +2,162 @@ //! Carved spans are offsets in one retained ACTUAL whole arena, never device //! allocations, initialized QSA products, current-row or session certificates. //! Root must supply the actual QSA mapped-staging/table-builder/registry adapters. -#[path="original_session_rope.rs"] mod rope; +#[path = "original_session_rope.rs"] +mod rope; pub(crate) use rope::{OriginalRopeScaling, OriginalRopeScalingType, OriginalRopeTable, OriginalRopeUpload}; -#[path="original_session_qsa_init.rs"] mod qsa_init; #[allow(dead_code)] -#[path="original_conversation_state.rs"] mod conversation; -#[allow(unused_imports)] -pub use conversation::{OriginalGeometryFacts,OriginalHostKv,OriginalIdxKind,OriginalKvLayer,OriginalKvPool,OriginalQsaFacts,OriginalRegion,OriginalSessionBytes,OriginalSessionControl,OriginalSessionFacts}; +#[path = "original_conversation_state.rs"] +mod conversation; +#[path = "original_session_qsa_init.rs"] +mod qsa_init; +use crate::{Context, DeviceBuffer, Error, Result, combine}; #[allow(unused_imports)] pub(crate) use conversation::OriginalConversationAccess; -use crate::{Context, DeviceBuffer, Error, Result, combine}; +#[allow(unused_imports)] +pub use conversation::{ + OriginalGeometryFacts, OriginalHostKv, OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, + OriginalRegion, OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, +}; use std::rc::Rc; const ALIGN: usize = 256; const PLE_HIST: usize = 9; const PLE_DIM: usize = 10240; -fn add(a:usize,b:usize)->Result{a.checked_add(b).ok_or(Error::InvalidSize)} -fn mul(a:usize,b:usize)->Result{a.checked_mul(b).ok_or(Error::InvalidSize)} -fn product(v:&[usize])->Result{v.iter().try_fold(1usize,|n,&v|mul(n,v))} -fn align(n:usize,a:usize)->Result{Ok(add(n,a-1)?/a*a)} -fn q8k(n:usize)->Result{mul(n/256,292)} -fn sum(v:&[usize])->Result{v.iter().try_fold(0usize,|n,&v|add(n,v))} -fn sum16(v:&[usize])->Result{v.iter().try_fold(0usize,|n,&v|add(n,align(v,16)?))} /// ModelGeometry values, supplied from the authentic loaded model by Root. /// This type sizes memory and carries no model-source authority. -#[derive(Clone,Copy,Debug,PartialEq,Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct OriginalSessionGeometry { - pub n_embd:usize,pub n_layers:usize,pub qsa_interval:usize, - pub state_size:usize,pub value_heads:usize,pub conv_width:usize, - pub conv_channels:usize,pub value_dim:usize, - pub heads:usize,pub kv_heads:usize,pub head_dim:usize, - pub index_heads:usize,pub index_dim:usize,pub hc:usize,pub hc_lr:usize, - pub experts:usize,pub n_ff:usize, -} -impl OriginalSessionGeometry { - pub(crate) fn original()->Self{Self{n_embd:2560,n_layers:48,qsa_interval:4,state_size:128,value_heads:48,conv_width:4,conv_channels:10240,value_dim:6144,heads:24,kv_heads:2,head_dim:256,index_heads:4,index_dim:128,hc:4,hc_lr:320,experts:512,n_ff:640}} - fn validate(self)->Result<()>{ - if [self.n_embd,self.n_layers,self.qsa_interval,self.state_size,self.value_heads,self.conv_width,self.conv_channels,self.value_dim,self.heads,self.kv_heads,self.head_dim,self.index_heads,self.index_dim,self.hc,self.hc_lr,self.experts,self.n_ff].contains(&0)||self.conv_width<1{return Err(Error::InvalidQwenShape)} - // The actual linked split-K scratch kernel has HD=256, CHUNK=64. - if self.head_dim!=256{return Err(Error::UnsupportedQwenOperation)} - Ok(()) - } - fn recurrence_bytes(self)->Result{product(&[self.state_size,self.value_heads,self.state_size,4])} - fn history_bytes(self)->Result{product(&[self.conv_channels,self.conv_width-1,4])} - fn state_bytes(self)->Result{add(self.recurrence_bytes()?,self.history_bytes()?)} - fn gdn_parts(self)->Result<[usize;16]>{Ok([q8k(self.n_embd)?,mul(self.n_embd/32,34)?,mul(self.n_embd,2)?,mul(self.conv_channels,4)?,mul(self.conv_channels,4)?,mul(self.conv_channels,4)?,mul(self.value_heads,4)?,mul(self.value_heads,4)?,mul(self.value_heads,4)?,product(&[self.value_heads,self.state_size,4])?,mul(self.value_dim,4)?,mul(self.value_dim,4)?,q8k(self.value_dim)?,mul(self.value_dim/32,34)?,self.recurrence_bytes()?,self.history_bytes()?])} - fn gr_parts(self)->Result<[usize;5]>{let n=mul(self.hc,self.n_embd)?;Ok([mul(n,4)?,mul(n,2)?,mul(self.hc_lr,2)?,mul(n,4)?,mul(self.hc_lr,4)?])} - fn shared_bytes(self)->Result{sum(&[mul(align(mul(self.n_ff,4)?,16)?,2)?,align(mul(self.n_ff/32,34)?,16)?,align(q8k(self.n_ff)?,16)?,32])} - fn moe_parts(self,k:usize)->Result<[usize;9]>{Ok([mul(self.n_embd,2)?,mul(self.n_embd,2)?,mul(self.experts,4)?,mul(k,4)?,mul(k,4)?,mul(self.n_embd,4)?,self.shared_bytes()?,mul(self.n_embd/32,34)?,q8k(self.n_embd)?])} - fn block_parts(self)->Result<[usize;8]>{Ok([product(&[self.hc,self.n_embd,4])?,mul(self.n_embd,4)?,mul(self.n_embd,4)?,mul(self.hc,4)?,mul(self.hc,4)?,mul(self.hc,4)?,q8k(self.n_embd)?,sum16(&self.gr_parts()?)?])} - fn block_charge(self)->Result{let p=self.block_parts()?;add(align(add(sum(&p)?,32)?,16)?,256)} - fn qsa_scratch_parts(self,cells:usize)->Result<[usize;18]>{ - let cap=2051usize;let q=mul(self.heads,self.head_dim)?;let kv=mul(self.kv_heads,self.head_dim)?; - let attn=add(product(&[cap.div_ceil(64),self.heads,258])?,64)?; - Ok([q8k(self.n_embd)?,mul(self.n_embd/32,34)?,mul(self.n_embd,2)?,mul(q,8)?,mul(q,4)?,mul(kv,4)?,mul(kv,4)?,mul(self.index_dim,4)?,product(&[self.index_heads,self.index_dim,4])?,mul(cells,4)?,mul(cap,4)?,mul(mul(cap,kv)?,2)?,mul(mul(cap,kv)?,2)?,mul(q,4)?,mul(q,2)?,mul(q,4)?,q8k(q)?,mul(attn,4)?]) - } - fn qsa_scratch_charge(self,cells:usize)->Result{add(align(add(sum(&self.qsa_scratch_parts(cells)?)?,16)?,16)?,256)} + pub n_embd: usize, + pub n_layers: usize, + pub qsa_interval: usize, + pub state_size: usize, + pub value_heads: usize, + pub conv_width: usize, + pub conv_channels: usize, + pub value_dim: usize, + pub heads: usize, + pub kv_heads: usize, + pub head_dim: usize, + pub index_heads: usize, + pub index_dim: usize, + pub hc: usize, + pub hc_lr: usize, + pub experts: usize, + pub n_ff: usize, } /// Snapshot of Original startup globals. Main/ring OFF env decisions must be /// resolved once by the actual operator adapter, never inferred during replay. -#[derive(Clone,Copy,Debug,PartialEq,Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct OriginalSessionKvPolicy { - pub resident_cells:usize,pub main_off:bool,pub ring_off:bool,pub ring_cells:isize,pub without_key:bool, - pub int8:bool,pub int8_rotate:bool,pub q4:bool,pub hybrid:bool, + pub resident_cells: usize, + pub main_off: bool, + pub ring_off: bool, + pub ring_cells: isize, + pub without_key: bool, + pub int8: bool, + pub int8_rotate: bool, + pub q4: bool, + pub hybrid: bool, } -#[derive(Clone,Copy,Debug,PartialEq,Eq)] -pub(crate) struct OriginalSessionSpan{pub offset:usize,pub bytes:usize} -impl OriginalSessionSpan { - pub(crate) fn end(self)->Result{add(self.offset,self.bytes)} - fn at(self,relative:usize,bytes:usize)->Result{if add(relative,bytes)?>self.bytes{return Err(Error::InvalidSize)}Ok(Self{offset:add(self.offset,relative)?,bytes})} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct OriginalSessionSpan { + pub offset: usize, + pub bytes: usize, } -#[derive(Clone,Debug)] +#[derive(Clone, Debug)] pub(crate) struct OriginalSessionQsaLayout { - pub ordinal:usize,pub arena:OriginalSessionSpan,pub mode:u8,pub pages:usize,pub slots:usize,pub pooled_rows:usize, - pub regions:Vec<(&'static str,OriginalSessionSpan)>, - pub cos:OriginalSessionSpan,pub sin:OriginalSessionSpan, - pub host_step_bytes:usize,pub host_position_bytes:usize,pub host_kv_bytes:usize, - pub kv_int8:bool,pub kv_q4:bool,pub kv_hybrid:bool,pub kv_rotate:bool, - owns_rope:bool, + pub ordinal: usize, + pub arena: OriginalSessionSpan, + pub mode: u8, + pub pages: usize, + pub slots: usize, + pub pooled_rows: usize, + pub regions: Vec<(&'static str, OriginalSessionSpan)>, + pub cos: OriginalSessionSpan, + pub sin: OriginalSessionSpan, + pub host_step_bytes: usize, + pub host_position_bytes: usize, + pub host_kv_bytes: usize, + pub kv_int8: bool, + pub kv_q4: bool, + pub kv_hybrid: bool, + pub kv_rotate: bool, + owns_rope: bool, } -impl OriginalSessionQsaLayout { - pub(crate) fn span(&self,name:&str)->Result{self.regions.iter().find_map(|(n,s)|(*n==name).then_some(*s)).ok_or(Error::InvalidQwenShape)} +struct Cursor { + base: usize, + used: usize, } -struct Cursor{base:usize,used:usize} -impl Cursor{ - fn take(&mut self,bytes:usize,a:usize)->Result{let s=OriginalSessionSpan{offset:add(self.base,self.used)?,bytes};self.used=align(add(self.used,bytes)?,a)?;Ok(s)} -} -fn parts(arena:OriginalSessionSpan,bytes:[usize;N])->Result<[OriginalSessionSpan;N]>{ - let mut c=Cursor{base:arena.offset,used:0};let mut out=[OriginalSessionSpan{offset:0,bytes:0};N]; - for(i,n)in bytes.into_iter().enumerate(){out[i]=c.take(n,16)?;} - if c.used>arena.bytes{return Err(Error::InvalidSize)}Ok(out) -} -struct QsaPrice{mode:u8,pages:usize,slots:usize,pooled_rows:usize,charge:usize} -fn qsa_price(g:OriginalSessionGeometry,cells:usize,p:OriginalSessionKvPolicy,rope:bool)->Result{ - // Literal layer.cpp498..519 kv_plan: negative ring_cells forces full - // residence, positive chooses the drafter ring (mode2), zero chooses the - // main clock-resident tier (mode1). OFF decisions are startup snapshots. - let pages=cells.div_ceil(4);let mut slots=pages;let mut mode=0; - let mut pooled_rows=add(cells/4,2)?; - if p.resident_cells>0&&p.ring_cells>=0&&!(if p.ring_cells>0{p.ring_off}else{p.main_off}){ - if p.ring_cells>0{ - let ring=(p.ring_cells as usize).div_ceil(4); - if ring)->Result{ - let mut c=Cursor{base:arena.offset,used:0};let mut regions=Vec::new();regions.try_reserve_exact(28).map_err(|_|Error::HostAllocation)?; - let mut take=|name,n|->Result{let s=c.take(n,16)?;regions.push((name,s));Ok(s)}; - let rows=product(&[price.slots,g.kv_heads,4])?;let codes=mul(rows,g.head_dim)?;let scales=product(&[rows,g.head_dim/64,2])?;let q4=product(&[rows,g.head_dim/32,18])?; - let hybrid=p.hybrid&&p.ring_cells<=0;let int8=p.int8&&!p.q4&&!hybrid;let q4_mode=p.q4&&!hybrid; - if hybrid{take("k_q",codes)?;take("k_scale",scales)?;take("v_q4",q4)?;} - else if q4_mode{take("k_q4",q4)?;take("v_q4",q4)?;} - else if int8{if !p.without_key{take("k_q",codes)?;}take("v_q",codes)?;if !p.without_key{take("k_scale",scales)?;}take("v_scale",scales)?;} - else{take("k_pool",mul(codes,2)?)?;take("v_pool",mul(codes,2)?)?;} - take("page_table",mul(price.pages,4)?)?; - if price.mode==1{for n in ["slot_block","slot_stamp","slot_ref","miss_block","miss_slot"]{take(n,mul(price.slots,4)?)?;}take("ctl",64)?;} - take("idx_tail",product(&[3,g.index_dim,4])?)?;take("idx_dead",mul(g.index_dim,4)?)?;take("idx_pooled",product(&[price.pooled_rows,g.index_dim,4])?)?;take("idx_block_pos",4)?; - let(cos,sin)=if let Some(s)=share{s}else{(take("cos",product(&[cells,32,4])?)?,take("sin",product(&[cells,32,4])?)?)}; - take("step",16)?;take("attention_status",4)?;take("pos_dev",mul(g.heads,4)?)?;drop(take); - if c.used>arena.bytes{return Err(Error::InvalidSize)} - let host_kv_bytes=if price.mode==0{0}else{let block=if q4_mode{product(&[4,g.kv_heads,g.head_dim/32,18,2])?}else if int8{product(&[4,g.kv_heads,add(mul(g.head_dim,2)?,mul(g.head_dim/64,4)?)?])?}else{product(&[4,g.kv_heads,g.head_dim,4])?};add(mul(price.pages,block)?,1024)?}; - Ok(OriginalSessionQsaLayout{ordinal,arena,mode:price.mode,pages:price.pages,slots:price.slots,pooled_rows:price.pooled_rows,regions,cos,sin,host_step_bytes:20,host_position_bytes:mul(g.heads,4)?,host_kv_bytes,kv_int8:int8,kv_q4:q4_mode,kv_hybrid:hybrid,kv_rotate:q4_mode||(int8&&p.int8_rotate),owns_rope:false}) -} - -/// Pure session_bytes, independent of QSA host initialization and pointer carve. -/// Exact Original clamp/count/sum/align256+4096 sequence on valid geometries. -pub(crate) fn session_bytes(g:OriginalSessionGeometry,cells:usize,k:usize,lo:i64,hi:i64,p:OriginalSessionKvPolicy)->Result{ - g.validate()?;if cells==0||cells>i32::MAX as usize||k==0||k>64{return Err(Error::InvalidQwenShape)} - let lo=usize::try_from(lo.max(0)).map_err(|_|Error::InvalidSize)?; - let hi=if hi<0||hi as u64>g.n_layers as u64{g.n_layers}else{hi as usize}; - if lo>hi{return Err(Error::InvalidQwenShape)} - let i=g.qsa_interval.max(1);let qr=hi/i-lo/i;let all_q=g.n_layers/g.qsa_interval; - let qn=qr.max(usize::from(all_q>0));let gn=(hi-lo).saturating_sub(qr); - let qbytes=if all_q==0{0}else{add(qsa_price(g,cells,p,true)?.charge,mul(qn-1,qsa_price(g,cells,p,false)?.charge)?)?}; - add(align(sum(&[sum16(&g.gdn_parts()?)?,mul(gn,g.state_bytes()?)?,qbytes,g.qsa_scratch_charge(cells)?,sum16(&g.moe_parts(k)?)?,g.block_charge()?,product(&[PLE_HIST,PLE_DIM,4])?])?,ALIGN)?,4096) +struct QsaPrice { + mode: u8, + pages: usize, + slots: usize, + pooled_rows: usize, + charge: usize, } /// Two distinct Original counts: advertised session_bytes vs aligned init used. /// Metadata describes actual byte layout; it does not certify initialized state. pub(crate) struct OriginalSessionLayout { - pub geometry:OriginalSessionGeometry,pub policy:OriginalSessionKvPolicy,pub max_cells:usize,pub k:usize, - pub layer_lo:usize,pub layer_hi:usize,pub qsa_ord0:usize,pub qsa_alloc:usize,pub gdn_ord0:usize,pub gdn_alloc:usize, - pub session_bytes:usize,pub init_used:usize, - pub gdn:[OriginalSessionSpan;16],pub gdn_state:OriginalSessionSpan, - pub qsa_state_arena:OriginalSessionSpan,pub qsa:Vec>, - pub qsa_buffers:[OriginalSessionSpan;18],pub moe:[OriginalSessionSpan;9],pub block:[OriginalSessionSpan;8],pub gr:[OriginalSessionSpan;5],pub ple_hist:OriginalSessionSpan, -} -impl OriginalSessionLayout { - pub(crate) fn new(g:OriginalSessionGeometry,cells:usize,k:usize,lo:i64,hi:i64,p:OriginalSessionKvPolicy)->Result{ - g.validate()?;if cells==0||cells>i32::MAX as usize||k==0||k>64{return Err(Error::InvalidQwenShape)} - let layer_lo=usize::try_from(lo.max(0)).map_err(|_|Error::InvalidSize)?; - let layer_hi=if hi<0||hi as u64>g.n_layers as u64{g.n_layers}else{hi as usize}; - if layer_lo>=layer_hi||layer_hi>g.n_layers{return Err(Error::InvalidQwenShape)} - let i=g.qsa_interval.max(1);let all_q=g.n_layers/g.qsa_interval;let qsa_ord0=layer_lo/i;let qr=layer_hi/i-qsa_ord0; - let qsa_alloc=qr.max(usize::from(all_q>0));let gdn_ord0=layer_lo-layer_lo/i;let gdn_alloc=(layer_hi-layer_lo).saturating_sub(qr); - if add(qsa_ord0,qsa_alloc)?>all_q{return Err(Error::InvalidQwenShape)} - let gp=g.gdn_parts()?;let gdn_bytes=sum16(&gp)?;let state=mul(gdn_alloc,g.state_bytes()?)?; - let first=qsa_price(g,cells,p,true)?;let rest=qsa_price(g,cells,p,false)?; - let qsa_bytes=if all_q>0{add(first.charge,mul(qsa_alloc-1,rest.charge)?)?}else{0}; - let qb=g.qsa_scratch_charge(cells)?;let mp=g.moe_parts(k)?;let mb=sum16(&mp)?;let bb=g.block_charge()?;let hist=product(&[PLE_HIST,PLE_DIM,4])?; - let session_bytes=session_bytes(g,cells,k,lo,hi,p)?; - let mut c=Cursor{base:0,used:0};let ga=c.take(gdn_bytes,ALIGN)?;let gdn_state=c.take(state,ALIGN)?; - let qsa_state_arena=c.take(qsa_bytes,ALIGN)?;let qa=c.take(qb,ALIGN)?; - let mut qsa:Vec>=Vec::new();qsa.try_reserve_exact(all_q).map_err(|_|Error::HostAllocation)?;qsa.resize_with(all_q,||None); - for j in 0..qsa_alloc{ - let offset=if j==0{0}else{add(first.charge,mul(j-1,rest.charge)?)?};let price=if j==0{&first}else{&rest}; - let share=if j==0{None}else{let primary=qsa[qsa_ord0].as_ref().ok_or(Error::InvalidQwenShape)?;Some((primary.cos,primary.sin))}; - qsa[qsa_ord0+j]=Some(qsa_carve(g,cells,p,qsa_ord0+j,qsa_state_arena.at(offset,price.charge)?,price,share)?); - } - let ma=c.take(mb,ALIGN)?;let ba=c.take(bb,ALIGN)?;let ple_hist=c.take(hist,ALIGN)?; - if c.used>session_bytes{return Err(Error::InvalidSize)} - let block=parts(ba,g.block_parts()?)?;let gr=parts(block[7],g.gr_parts()?)?; - Ok(Self{geometry:g,policy:p,max_cells:cells,k,layer_lo,layer_hi,qsa_ord0,qsa_alloc,gdn_ord0,gdn_alloc,session_bytes,init_used:c.used,gdn:parts(ga,gp)?,gdn_state,qsa_state_arena,qsa,qsa_buffers:parts(qa,g.qsa_scratch_parts(cells)?)?,moe:parts(ma,mp)?,block,gr,ple_hist}) - } - pub(crate) fn gdn_point_at(&self,layer:usize)->Result>{ - if layer=self.layer_hi{return Err(Error::InvalidQwenShape)}let g=self.geometry; - if layer%g.qsa_interval==g.qsa_interval-1{return Ok(None)} - let ordinal=layer-layer/g.qsa_interval;let local=ordinal.checked_sub(self.gdn_ord0).ok_or(Error::InvalidQwenShape)?; - if local>=self.gdn_alloc{return Err(Error::InvalidQwenShape)}let off=mul(local,g.state_bytes()?)?; - Ok(Some((self.gdn_state.at(off,g.recurrence_bytes()?)?,self.gdn_state.at(add(off,g.recurrence_bytes()?)?,g.history_bytes()?)?))) - } - pub(crate) fn qsa_primary(&self)->Result<&OriginalSessionQsaLayout>{self.qsa.get(self.qsa_ord0).and_then(Option::as_ref).ok_or(Error::UnsupportedQwenOperation)} + pub geometry: OriginalSessionGeometry, + pub policy: OriginalSessionKvPolicy, + pub max_cells: usize, + pub k: usize, + pub layer_lo: usize, + pub layer_hi: usize, + pub qsa_ord0: usize, + pub qsa_alloc: usize, + pub gdn_ord0: usize, + pub gdn_alloc: usize, + pub session_bytes: usize, + pub init_used: usize, + pub gdn: [OriginalSessionSpan; 16], + pub gdn_state: OriginalSessionSpan, + pub qsa_state_arena: OriginalSessionSpan, + pub qsa: Vec>, + pub qsa_buffers: [OriginalSessionSpan; 18], + pub moe: [OriginalSessionSpan; 9], + pub block: [OriginalSessionSpan; 8], + pub gr: [OriginalSessionSpan; 5], + pub ple_hist: OriginalSessionSpan, } /// Owns the arena and host pointer-array metadata. It deliberately has no /// initialized()/ready() API: qsa_state_init dependencies are not supplied here. -pub(crate) struct OriginalSessionState<'ctx>{ - context:&'ctx Context<'ctx>,arena:Option>>,layout:OriginalSessionLayout, - pub ple_prev:[i32;2],pub ple_token:i32,released:bool,registry_uncertain:bool, +pub(crate) struct OriginalSessionState<'ctx> { + context: &'ctx Context<'ctx>, + arena: Option>>, + layout: OriginalSessionLayout, + pub ple_prev: [i32; 2], + pub ple_token: i32, + released: bool, + registry_uncertain: bool, } -impl<'ctx> OriginalSessionState<'ctx>{ - pub(crate) fn session_init_carve(context:&'ctx Context<'ctx>,arena:Rc>,layout:OriginalSessionLayout)->Result{ - if !std::ptr::eq(context,arena.context){return Err(Error::ContextMismatch)} - if context.is_poisoned(){return Err(Error::ContextPoisoned)} - if arena.len()0&&layout.policy.hybrid&&layout.qsa_primary()?.mode==1{return Err(Error::UnsupportedQwenOperation)} - Ok(Self{context,arena:Some(arena),layout,ple_prev:[-1,-1],ple_token:-1,released:false,registry_uncertain:false}) - } - pub(crate) fn validate_context(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.released||c.is_poisoned(){return Err(Error::ContextPoisoned)}if self.registry_uncertain{return Err(Error::UnsupportedQwenOperation)}self.arena.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned).map(|_|())} - pub(crate) fn layout(&self)->&OriginalSessionLayout{&self.layout} - pub(crate) fn with_carved_arena(&self,c:&Context<'_>,f:impl FnOnce(&DeviceBuffer<'ctx>,&OriginalSessionLayout)->Result)->Result{self.validate_context(c)?;f(self.arena.as_ref().ok_or(Error::ContextPoisoned)?,&self.layout)} - /// Root's exact table builder/upload/rope_table_set dependency must execute - /// before returning Ok. This is a registry ownership hook, NOT finite proof. - pub(crate) fn register_primary_rope(&mut self,register:impl FnOnce(&DeviceBuffer<'ctx>,OriginalSessionSpan,OriginalSessionSpan,usize)->Result<()>)->Result<()>{ - self.validate_context(self.context)?;let q=self.layout.qsa_primary()?;if q.owns_rope{return Err(Error::InvalidQwenShape)}let cos=q.cos;let sin=q.sin; - self.registry_uncertain=true; - register(self.arena.as_ref().ok_or(Error::ContextPoisoned)?,cos,sin,self.layout.max_cells)?; - self.registry_uncertain=false; - self.layout.qsa[self.layout.qsa_ord0].as_mut().ok_or(Error::InvalidQwenShape)?.owns_rope=true;Ok(()) - } - /// Exact session_release global-array index order is j, NOT ord0+j. - /// Root must resolve the Original nonzero-stage registry bug explicitly. - /// No allocation is freed by this call; release registry BEFORE freeing arena. - pub(crate) fn session_release(&mut self,mut release:impl FnMut(&DeviceBuffer<'ctx>,OriginalSessionSpan)->Result<()>)->Result<()>{ - self.validate_context(self.context)?;let arena=self.arena.as_ref().ok_or(Error::ContextPoisoned)?;let mut result=Ok(()); - for j in 0..self.layout.qsa_alloc{if let Some(q)=self.layout.qsa.get_mut(j).and_then(Option::as_mut){if q.owns_rope{let r=release(arena,q.cos);if r.is_ok(){q.owns_rope=false;}result=combine(result,r);}}} - result - } - /// Frees only Rust pointer-array ownership; arena is caller/model-owned Rc. - /// Registered tables must already have been released, including stage primary. - pub(crate) fn close(mut self)->Result<()>{self.validate_context(self.context)?;if self.registry_uncertain||self.layout.qsa.iter().flatten().any(|q|q.owns_rope){return Err(Error::UnsupportedQwenOperation)}self.released=true;self.arena.take();Ok(())} -} -impl Drop for OriginalSessionState<'_>{fn drop(&mut self){ - // No fake unregister on Drop. If registry still names this arena (or Context - // is uncertain), retain the actual allocation instead of dangling table refs. - if self.registry_uncertain||self.context.is_poisoned()||self.layout.qsa.iter().flatten().any(|q|q.owns_rope){if let Some(a)=self.arena.take(){std::mem::forget(a)}} -}} + +mod add_fn; +#[allow(unused_imports)] +use add_fn::add; +#[allow(unused_imports)] +use add_fn::align; +#[allow(unused_imports)] +use add_fn::mul; +#[allow(unused_imports)] +use add_fn::parts; +#[allow(unused_imports)] +use add_fn::product; +#[allow(unused_imports)] +use add_fn::q8k; +#[allow(unused_imports)] +use add_fn::sum; +#[allow(unused_imports)] +use add_fn::sum16; +mod qsa_price_fn; +#[allow(unused_imports)] +use qsa_price_fn::qsa_carve; +#[allow(unused_imports)] +use qsa_price_fn::qsa_price; +#[allow(unused_imports)] +pub(crate) use qsa_price_fn::session_bytes; +mod impl_originalsessionlayout; diff --git a/crates/cuda-driver/src/original_session_state/add_fn.rs b/crates/cuda-driver/src/original_session_state/add_fn.rs new file mode 100644 index 00000000..85b69667 --- /dev/null +++ b/crates/cuda-driver/src/original_session_state/add_fn.rs @@ -0,0 +1,213 @@ +//! Moved out of the parent module by STRA-338: fn add, fn mul, fn product, fn align, fn q8k, fn sum .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn add(a: usize, b: usize) -> Result { + a.checked_add(b).ok_or(Error::InvalidSize) +} +pub(super) fn mul(a: usize, b: usize) -> Result { + a.checked_mul(b).ok_or(Error::InvalidSize) +} +pub(super) fn product(v: &[usize]) -> Result { + v.iter().try_fold(1usize, |n, &v| mul(n, v)) +} +pub(super) fn align(n: usize, a: usize) -> Result { + Ok(add(n, a - 1)? / a * a) +} +pub(super) fn q8k(n: usize) -> Result { + mul(n / 256, 292) +} +pub(super) fn sum(v: &[usize]) -> Result { + v.iter().try_fold(0usize, |n, &v| add(n, v)) +} +pub(super) fn sum16(v: &[usize]) -> Result { + v.iter().try_fold(0usize, |n, &v| add(n, align(v, 16)?)) +} +impl OriginalSessionGeometry { + pub(crate) fn original() -> Self { + Self { + n_embd: 2560, + n_layers: 48, + qsa_interval: 4, + state_size: 128, + value_heads: 48, + conv_width: 4, + conv_channels: 10240, + value_dim: 6144, + heads: 24, + kv_heads: 2, + head_dim: 256, + index_heads: 4, + index_dim: 128, + hc: 4, + hc_lr: 320, + experts: 512, + n_ff: 640, + } + } + pub(super) fn validate(self) -> Result<()> { + if [ + self.n_embd, + self.n_layers, + self.qsa_interval, + self.state_size, + self.value_heads, + self.conv_width, + self.conv_channels, + self.value_dim, + self.heads, + self.kv_heads, + self.head_dim, + self.index_heads, + self.index_dim, + self.hc, + self.hc_lr, + self.experts, + self.n_ff, + ] + .contains(&0) + || self.conv_width < 1 + { + return Err(Error::InvalidQwenShape); + } + // The actual linked split-K scratch kernel has HD=256, CHUNK=64. + if self.head_dim != 256 { + return Err(Error::UnsupportedQwenOperation); + } + Ok(()) + } + pub(super) fn recurrence_bytes(self) -> Result { + product(&[self.state_size, self.value_heads, self.state_size, 4]) + } + pub(super) fn history_bytes(self) -> Result { + product(&[self.conv_channels, self.conv_width - 1, 4]) + } + pub(super) fn state_bytes(self) -> Result { + add(self.recurrence_bytes()?, self.history_bytes()?) + } + pub(super) fn gdn_parts(self) -> Result<[usize; 16]> { + Ok([ + q8k(self.n_embd)?, + mul(self.n_embd / 32, 34)?, + mul(self.n_embd, 2)?, + mul(self.conv_channels, 4)?, + mul(self.conv_channels, 4)?, + mul(self.conv_channels, 4)?, + mul(self.value_heads, 4)?, + mul(self.value_heads, 4)?, + mul(self.value_heads, 4)?, + product(&[self.value_heads, self.state_size, 4])?, + mul(self.value_dim, 4)?, + mul(self.value_dim, 4)?, + q8k(self.value_dim)?, + mul(self.value_dim / 32, 34)?, + self.recurrence_bytes()?, + self.history_bytes()?, + ]) + } + pub(super) fn gr_parts(self) -> Result<[usize; 5]> { + let n = mul(self.hc, self.n_embd)?; + Ok([mul(n, 4)?, mul(n, 2)?, mul(self.hc_lr, 2)?, mul(n, 4)?, mul(self.hc_lr, 4)?]) + } + pub(super) fn shared_bytes(self) -> Result { + sum(&[ + mul(align(mul(self.n_ff, 4)?, 16)?, 2)?, + align(mul(self.n_ff / 32, 34)?, 16)?, + align(q8k(self.n_ff)?, 16)?, + 32, + ]) + } + pub(super) fn moe_parts(self, k: usize) -> Result<[usize; 9]> { + Ok([ + mul(self.n_embd, 2)?, + mul(self.n_embd, 2)?, + mul(self.experts, 4)?, + mul(k, 4)?, + mul(k, 4)?, + mul(self.n_embd, 4)?, + self.shared_bytes()?, + mul(self.n_embd / 32, 34)?, + q8k(self.n_embd)?, + ]) + } + pub(super) fn block_parts(self) -> Result<[usize; 8]> { + Ok([ + product(&[self.hc, self.n_embd, 4])?, + mul(self.n_embd, 4)?, + mul(self.n_embd, 4)?, + mul(self.hc, 4)?, + mul(self.hc, 4)?, + mul(self.hc, 4)?, + q8k(self.n_embd)?, + sum16(&self.gr_parts()?)?, + ]) + } + pub(super) fn block_charge(self) -> Result { + let p = self.block_parts()?; + add(align(add(sum(&p)?, 32)?, 16)?, 256) + } + pub(super) fn qsa_scratch_parts(self, cells: usize) -> Result<[usize; 18]> { + let cap = 2051usize; + let q = mul(self.heads, self.head_dim)?; + let kv = mul(self.kv_heads, self.head_dim)?; + let attn = add(product(&[cap.div_ceil(64), self.heads, 258])?, 64)?; + Ok([ + q8k(self.n_embd)?, + mul(self.n_embd / 32, 34)?, + mul(self.n_embd, 2)?, + mul(q, 8)?, + mul(q, 4)?, + mul(kv, 4)?, + mul(kv, 4)?, + mul(self.index_dim, 4)?, + product(&[self.index_heads, self.index_dim, 4])?, + mul(cells, 4)?, + mul(cap, 4)?, + mul(mul(cap, kv)?, 2)?, + mul(mul(cap, kv)?, 2)?, + mul(q, 4)?, + mul(q, 2)?, + mul(q, 4)?, + q8k(q)?, + mul(attn, 4)?, + ]) + } + pub(super) fn qsa_scratch_charge(self, cells: usize) -> Result { + add(align(add(sum(&self.qsa_scratch_parts(cells)?)?, 16)?, 16)?, 256) + } +} +impl OriginalSessionSpan { + pub(crate) fn end(self) -> Result { + add(self.offset, self.bytes) + } + pub(super) fn at(self, relative: usize, bytes: usize) -> Result { + if add(relative, bytes)? > self.bytes { + return Err(Error::InvalidSize); + } + Ok(Self { offset: add(self.offset, relative)?, bytes }) + } +} +impl OriginalSessionQsaLayout { + pub(crate) fn span(&self, name: &str) -> Result { + self.regions.iter().find_map(|(n, s)| (*n == name).then_some(*s)).ok_or(Error::InvalidQwenShape) + } +} +impl Cursor { + pub(super) fn take(&mut self, bytes: usize, a: usize) -> Result { + let s = OriginalSessionSpan { offset: add(self.base, self.used)?, bytes }; + self.used = align(add(self.used, bytes)?, a)?; + Ok(s) + } +} +pub(super) fn parts(arena: OriginalSessionSpan, bytes: [usize; N]) -> Result<[OriginalSessionSpan; N]> { + let mut c = Cursor { base: arena.offset, used: 0 }; + let mut out = [OriginalSessionSpan { offset: 0, bytes: 0 }; N]; + for (i, n) in bytes.into_iter().enumerate() { + out[i] = c.take(n, 16)?; + } + if c.used > arena.bytes { + return Err(Error::InvalidSize); + } + Ok(out) +} diff --git a/crates/cuda-driver/src/original_session_state/impl_originalsessionlayout.rs b/crates/cuda-driver/src/original_session_state/impl_originalsessionlayout.rs new file mode 100644 index 00000000..e174426f --- /dev/null +++ b/crates/cuda-driver/src/original_session_state/impl_originalsessionlayout.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSessionLayout, impl OriginalSessionState, impl Drop_for_OriginalSessionState. + +#[allow(unused_imports)] +use super::*; + +impl OriginalSessionLayout { + pub(crate) fn new( + g: OriginalSessionGeometry, + cells: usize, + k: usize, + lo: i64, + hi: i64, + p: OriginalSessionKvPolicy, + ) -> Result { + g.validate()?; + if cells == 0 || cells > i32::MAX as usize || k == 0 || k > 64 { + return Err(Error::InvalidQwenShape); + } + let layer_lo = usize::try_from(lo.max(0)).map_err(|_| Error::InvalidSize)?; + let layer_hi = if hi < 0 || hi as u64 > g.n_layers as u64 { g.n_layers } else { hi as usize }; + if layer_lo >= layer_hi || layer_hi > g.n_layers { + return Err(Error::InvalidQwenShape); + } + let i = g.qsa_interval.max(1); + let all_q = g.n_layers / g.qsa_interval; + let qsa_ord0 = layer_lo / i; + let qr = layer_hi / i - qsa_ord0; + let qsa_alloc = qr.max(usize::from(all_q > 0)); + let gdn_ord0 = layer_lo - layer_lo / i; + let gdn_alloc = (layer_hi - layer_lo).saturating_sub(qr); + if add(qsa_ord0, qsa_alloc)? > all_q { + return Err(Error::InvalidQwenShape); + } + let gp = g.gdn_parts()?; + let gdn_bytes = sum16(&gp)?; + let state = mul(gdn_alloc, g.state_bytes()?)?; + let first = qsa_price(g, cells, p, true)?; + let rest = qsa_price(g, cells, p, false)?; + let qsa_bytes = if all_q > 0 { add(first.charge, mul(qsa_alloc - 1, rest.charge)?)? } else { 0 }; + let qb = g.qsa_scratch_charge(cells)?; + let mp = g.moe_parts(k)?; + let mb = sum16(&mp)?; + let bb = g.block_charge()?; + let hist = product(&[PLE_HIST, PLE_DIM, 4])?; + let session_bytes = session_bytes(g, cells, k, lo, hi, p)?; + let mut c = Cursor { base: 0, used: 0 }; + let ga = c.take(gdn_bytes, ALIGN)?; + let gdn_state = c.take(state, ALIGN)?; + let qsa_state_arena = c.take(qsa_bytes, ALIGN)?; + let qa = c.take(qb, ALIGN)?; + let mut qsa: Vec> = Vec::new(); + qsa.try_reserve_exact(all_q).map_err(|_| Error::HostAllocation)?; + qsa.resize_with(all_q, || None); + for j in 0..qsa_alloc { + let offset = if j == 0 { 0 } else { add(first.charge, mul(j - 1, rest.charge)?)? }; + let price = if j == 0 { &first } else { &rest }; + let share = if j == 0 { + None + } else { + let primary = qsa[qsa_ord0].as_ref().ok_or(Error::InvalidQwenShape)?; + Some((primary.cos, primary.sin)) + }; + qsa[qsa_ord0 + j] = + Some(qsa_carve(g, cells, p, qsa_ord0 + j, qsa_state_arena.at(offset, price.charge)?, price, share)?); + } + let ma = c.take(mb, ALIGN)?; + let ba = c.take(bb, ALIGN)?; + let ple_hist = c.take(hist, ALIGN)?; + if c.used > session_bytes { + return Err(Error::InvalidSize); + } + let block = parts(ba, g.block_parts()?)?; + let gr = parts(block[7], g.gr_parts()?)?; + Ok(Self { + geometry: g, + policy: p, + max_cells: cells, + k, + layer_lo, + layer_hi, + qsa_ord0, + qsa_alloc, + gdn_ord0, + gdn_alloc, + session_bytes, + init_used: c.used, + gdn: parts(ga, gp)?, + gdn_state, + qsa_state_arena, + qsa, + qsa_buffers: parts(qa, g.qsa_scratch_parts(cells)?)?, + moe: parts(ma, mp)?, + block, + gr, + ple_hist, + }) + } + pub(crate) fn gdn_point_at(&self, layer: usize) -> Result> { + if layer < self.layer_lo || layer >= self.layer_hi { + return Err(Error::InvalidQwenShape); + } + let g = self.geometry; + if layer % g.qsa_interval == g.qsa_interval - 1 { + return Ok(None); + } + let ordinal = layer - layer / g.qsa_interval; + let local = ordinal.checked_sub(self.gdn_ord0).ok_or(Error::InvalidQwenShape)?; + if local >= self.gdn_alloc { + return Err(Error::InvalidQwenShape); + } + let off = mul(local, g.state_bytes()?)?; + Ok(Some(( + self.gdn_state.at(off, g.recurrence_bytes()?)?, + self.gdn_state.at(add(off, g.recurrence_bytes()?)?, g.history_bytes()?)?, + ))) + } + pub(crate) fn qsa_primary(&self) -> Result<&OriginalSessionQsaLayout> { + self.qsa.get(self.qsa_ord0).and_then(Option::as_ref).ok_or(Error::UnsupportedQwenOperation) + } +} +impl<'ctx> OriginalSessionState<'ctx> { + pub(crate) fn session_init_carve( + context: &'ctx Context<'ctx>, + arena: Rc>, + layout: OriginalSessionLayout, + ) -> Result { + if !std::ptr::eq(context, arena.context) { + return Err(Error::ContextMismatch); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if arena.len() < layout.session_bytes { + return Err(Error::ShapeMismatch { expected: layout.session_bytes, actual: arena.len() }); + } + arena.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(arena.len(), 256)?; + // Original init returns 0 for streamed hybrid before host construction. + if layout.qsa_alloc > 0 && layout.policy.hybrid && layout.qsa_primary()?.mode == 1 { + return Err(Error::UnsupportedQwenOperation); + } + Ok(Self { + context, + arena: Some(arena), + layout, + ple_prev: [-1, -1], + ple_token: -1, + released: false, + registry_uncertain: false, + }) + } + pub(crate) fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if self.released || c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if self.registry_uncertain { + return Err(Error::UnsupportedQwenOperation); + } + self.arena.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned).map(|_| ()) + } + pub(crate) fn layout(&self) -> &OriginalSessionLayout { + &self.layout + } + pub(crate) fn with_carved_arena( + &self, + c: &Context<'_>, + f: impl FnOnce(&DeviceBuffer<'ctx>, &OriginalSessionLayout) -> Result, + ) -> Result { + self.validate_context(c)?; + f(self.arena.as_ref().ok_or(Error::ContextPoisoned)?, &self.layout) + } + /// Root's exact table builder/upload/rope_table_set dependency must execute + /// before returning Ok. This is a registry ownership hook, NOT finite proof. + pub(crate) fn register_primary_rope( + &mut self, + register: impl FnOnce(&DeviceBuffer<'ctx>, OriginalSessionSpan, OriginalSessionSpan, usize) -> Result<()>, + ) -> Result<()> { + self.validate_context(self.context)?; + let q = self.layout.qsa_primary()?; + if q.owns_rope { + return Err(Error::InvalidQwenShape); + } + let cos = q.cos; + let sin = q.sin; + self.registry_uncertain = true; + register(self.arena.as_ref().ok_or(Error::ContextPoisoned)?, cos, sin, self.layout.max_cells)?; + self.registry_uncertain = false; + self.layout.qsa[self.layout.qsa_ord0].as_mut().ok_or(Error::InvalidQwenShape)?.owns_rope = true; + Ok(()) + } + /// Exact session_release global-array index order is j, NOT ord0+j. + /// Root must resolve the Original nonzero-stage registry bug explicitly. + /// No allocation is freed by this call; release registry BEFORE freeing arena. + pub(crate) fn session_release( + &mut self, + mut release: impl FnMut(&DeviceBuffer<'ctx>, OriginalSessionSpan) -> Result<()>, + ) -> Result<()> { + self.validate_context(self.context)?; + let arena = self.arena.as_ref().ok_or(Error::ContextPoisoned)?; + let mut result = Ok(()); + for j in 0..self.layout.qsa_alloc { + if let Some(q) = self.layout.qsa.get_mut(j).and_then(Option::as_mut) { + if q.owns_rope { + let r = release(arena, q.cos); + if r.is_ok() { + q.owns_rope = false; + } + result = combine(result, r); + } + } + } + result + } + /// Frees only Rust pointer-array ownership; arena is caller/model-owned Rc. + /// Registered tables must already have been released, including stage primary. + pub(crate) fn close(mut self) -> Result<()> { + self.validate_context(self.context)?; + if self.registry_uncertain || self.layout.qsa.iter().flatten().any(|q| q.owns_rope) { + return Err(Error::UnsupportedQwenOperation); + } + self.released = true; + self.arena.take(); + Ok(()) + } +} +impl Drop for OriginalSessionState<'_> { + fn drop(&mut self) { + // No fake unregister on Drop. If registry still names this arena (or Context + // is uncertain), retain the actual allocation instead of dangling table refs. + if self.registry_uncertain + || self.context.is_poisoned() + || self.layout.qsa.iter().flatten().any(|q| q.owns_rope) + { + if let Some(a) = self.arena.take() { + std::mem::forget(a) + } + } + } +} diff --git a/crates/cuda-driver/src/original_session_state/qsa_price_fn.rs b/crates/cuda-driver/src/original_session_state/qsa_price_fn.rs new file mode 100644 index 00000000..3d9184d3 --- /dev/null +++ b/crates/cuda-driver/src/original_session_state/qsa_price_fn.rs @@ -0,0 +1,209 @@ +//! Moved out of the parent module by STRA-338: fn qsa_price, fn qsa_carve, fn session_bytes. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn qsa_price( + g: OriginalSessionGeometry, + cells: usize, + p: OriginalSessionKvPolicy, + rope: bool, +) -> Result { + // Literal layer.cpp498..519 kv_plan: negative ring_cells forces full + // residence, positive chooses the drafter ring (mode2), zero chooses the + // main clock-resident tier (mode1). OFF decisions are startup snapshots. + let pages = cells.div_ceil(4); + let mut slots = pages; + let mut mode = 0; + let mut pooled_rows = add(cells / 4, 2)?; + if p.resident_cells > 0 && p.ring_cells >= 0 && !(if p.ring_cells > 0 { p.ring_off } else { p.main_off }) { + if p.ring_cells > 0 { + let ring = (p.ring_cells as usize).div_ceil(4); + if ring < pages { + slots = ring; + mode = 2; + pooled_rows = 2; + } + } else { + let resident = p.resident_cells.max(20480).div_ceil(4); + if resident < pages { + slots = resident; + mode = 1; + } + } + } + let rows = product(&[slots, 4, g.kv_heads])?; + let q4 = mul(g.head_dim / 32, 18)?; + let q8cell = mul(g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?)?; + // Preserve kv_pool_bytes decision priority, including without_key before + // hybrid/Q4. Unsupported combinations remain an init dependency, not recast. + let pool = if p.without_key { + add(mul(mul(slots, 4)?, q8cell)? / 2, 64)? + } else if p.hybrid && p.ring_cells <= 0 { + add(sum(&[mul(rows, g.head_dim)?, product(&[rows, g.head_dim / 64, 2])?, mul(rows, q4)?])?, 64)? + } else if p.q4 { + add(product(&[slots, 4, g.kv_heads, q4, 2])?, 64)? + } else if p.int8 || p.hybrid { + add(product(&[slots, 4, q8cell])?, 64)? + } else { + product(&[slots, g.kv_heads, 4, g.head_dim, 4])? + }; + let mut n = add(pool, 64)?; + n = add(n, mul(pages, 4)?)?; + if mode == 1 { + n = add(n, add(add(mul(slots, 20)?, 64)?, 96)?)?; + } + for b in [product(&[3, g.index_dim, 4])?, mul(g.index_dim, 4)?, product(&[pooled_rows, g.index_dim, 4])?, 16] { + n = add(n, b)?; + } + if rope { + n = add(n, product(&[cells, 32, 4, 2])?)?; + } + n = sum(&[n, 16, 16, mul(g.heads, 4)?])?; + Ok(QsaPrice { mode, pages, slots, pooled_rows, charge: add(align(n, 16)?, 256)? }) +} +pub(super) fn qsa_carve( + g: OriginalSessionGeometry, + cells: usize, + p: OriginalSessionKvPolicy, + ordinal: usize, + arena: OriginalSessionSpan, + price: &QsaPrice, + share: Option<(OriginalSessionSpan, OriginalSessionSpan)>, +) -> Result { + let mut c = Cursor { base: arena.offset, used: 0 }; + let mut regions = Vec::new(); + regions.try_reserve_exact(28).map_err(|_| Error::HostAllocation)?; + let mut take = |name, n| -> Result { + let s = c.take(n, 16)?; + regions.push((name, s)); + Ok(s) + }; + let rows = product(&[price.slots, g.kv_heads, 4])?; + let codes = mul(rows, g.head_dim)?; + let scales = product(&[rows, g.head_dim / 64, 2])?; + let q4 = product(&[rows, g.head_dim / 32, 18])?; + let hybrid = p.hybrid && p.ring_cells <= 0; + let int8 = p.int8 && !p.q4 && !hybrid; + let q4_mode = p.q4 && !hybrid; + if hybrid { + take("k_q", codes)?; + take("k_scale", scales)?; + take("v_q4", q4)?; + } else if q4_mode { + take("k_q4", q4)?; + take("v_q4", q4)?; + } else if int8 { + if !p.without_key { + take("k_q", codes)?; + } + take("v_q", codes)?; + if !p.without_key { + take("k_scale", scales)?; + } + take("v_scale", scales)?; + } else { + take("k_pool", mul(codes, 2)?)?; + take("v_pool", mul(codes, 2)?)?; + } + take("page_table", mul(price.pages, 4)?)?; + if price.mode == 1 { + for n in ["slot_block", "slot_stamp", "slot_ref", "miss_block", "miss_slot"] { + take(n, mul(price.slots, 4)?)?; + } + take("ctl", 64)?; + } + take("idx_tail", product(&[3, g.index_dim, 4])?)?; + take("idx_dead", mul(g.index_dim, 4)?)?; + take("idx_pooled", product(&[price.pooled_rows, g.index_dim, 4])?)?; + take("idx_block_pos", 4)?; + let (cos, sin) = if let Some(s) = share { + s + } else { + (take("cos", product(&[cells, 32, 4])?)?, take("sin", product(&[cells, 32, 4])?)?) + }; + take("step", 16)?; + take("attention_status", 4)?; + take("pos_dev", mul(g.heads, 4)?)?; + drop(take); + if c.used > arena.bytes { + return Err(Error::InvalidSize); + } + let host_kv_bytes = if price.mode == 0 { + 0 + } else { + let block = if q4_mode { + product(&[4, g.kv_heads, g.head_dim / 32, 18, 2])? + } else if int8 { + product(&[4, g.kv_heads, add(mul(g.head_dim, 2)?, mul(g.head_dim / 64, 4)?)?])? + } else { + product(&[4, g.kv_heads, g.head_dim, 4])? + }; + add(mul(price.pages, block)?, 1024)? + }; + Ok(OriginalSessionQsaLayout { + ordinal, + arena, + mode: price.mode, + pages: price.pages, + slots: price.slots, + pooled_rows: price.pooled_rows, + regions, + cos, + sin, + host_step_bytes: 20, + host_position_bytes: mul(g.heads, 4)?, + host_kv_bytes, + kv_int8: int8, + kv_q4: q4_mode, + kv_hybrid: hybrid, + kv_rotate: q4_mode || (int8 && p.int8_rotate), + owns_rope: false, + }) +} + +/// Pure session_bytes, independent of QSA host initialization and pointer carve. +/// Exact Original clamp/count/sum/align256+4096 sequence on valid geometries. +pub(crate) fn session_bytes( + g: OriginalSessionGeometry, + cells: usize, + k: usize, + lo: i64, + hi: i64, + p: OriginalSessionKvPolicy, +) -> Result { + g.validate()?; + if cells == 0 || cells > i32::MAX as usize || k == 0 || k > 64 { + return Err(Error::InvalidQwenShape); + } + let lo = usize::try_from(lo.max(0)).map_err(|_| Error::InvalidSize)?; + let hi = if hi < 0 || hi as u64 > g.n_layers as u64 { g.n_layers } else { hi as usize }; + if lo > hi { + return Err(Error::InvalidQwenShape); + } + let i = g.qsa_interval.max(1); + let qr = hi / i - lo / i; + let all_q = g.n_layers / g.qsa_interval; + let qn = qr.max(usize::from(all_q > 0)); + let gn = (hi - lo).saturating_sub(qr); + let qbytes = if all_q == 0 { + 0 + } else { + add(qsa_price(g, cells, p, true)?.charge, mul(qn - 1, qsa_price(g, cells, p, false)?.charge)?)? + }; + add( + align( + sum(&[ + sum16(&g.gdn_parts()?)?, + mul(gn, g.state_bytes()?)?, + qbytes, + g.qsa_scratch_charge(cells)?, + sum16(&g.moe_parts(k)?)?, + g.block_charge()?, + product(&[PLE_HIST, PLE_DIM, 4])?, + ])?, + ALIGN, + )?, + 4096, + ) +} diff --git a/crates/cuda-driver/src/original_stream_all.rs b/crates/cuda-driver/src/original_stream_all.rs index ae9379f7..a34bc6ef 100644 --- a/crates/cuda-driver/src/original_stream_all.rs +++ b/crates/cuda-driver/src/original_stream_all.rs @@ -3,54 +3,88 @@ //! private to a synchronous scope: a caller cannot forget an asynchronous //! guard and reuse/free the borrowed actual arena while its issuer is running. use super::*; -use crate::{OriginalPromptRows,ffi::BufferHandle}; -const GPU_RING_MAX:usize=512; -#[derive(Clone,Copy)] -pub struct OriginalStreamAllOptions {pub minimum_rows:usize,pub issuer:bool} -#[derive(Clone,Copy)] -struct Entry {layer:u8,expert:u32,bytes:usize,job:usize} -pub(super) struct EventBank{copied:Vec,used:Vec,live:Vec} +use crate::{OriginalPromptRows, ffi::BufferHandle}; +const GPU_RING_MAX: usize = 512; +#[derive(Clone, Copy)] +pub struct OriginalStreamAllOptions { + pub minimum_rows: usize, + pub issuer: bool, +} +#[derive(Clone, Copy)] +struct Entry { + layer: u8, + expert: u32, + bytes: usize, + job: usize, +} +pub(super) struct EventBank { + copied: Vec, + used: Vec, + live: Vec, +} struct Issuer { - entries:Vec,targets:Vec,events:Arc, - issued:AtomicUsize,consumed:AtomicUsize,stop:AtomicBool,failed:AtomicBool, - error:Mutex>,ring:usize, + entries: Vec, + targets: Vec, + events: Arc, + issued: AtomicUsize, + consumed: AtomicUsize, + stop: AtomicBool, + failed: AtomicBool, + error: Mutex>, + ring: usize, } /// Only borrowed by run_stream_all's consumer; no standalone constructor, /// owned pending result or arbitrary pointer method. GPU producer callbacks /// are crate-private and consume checked actual cache/arena handles. -pub struct OriginalStreamAll<'s,'arena,'loan,'ctx>{ - stager:&'s mut OriginalExpertStager<'ctx>,rows:Option>, - copy:Option>,compute:Option>, - issuer:Arc,thread:Option>,layer_start:[usize;49], - first:u8,end:u8,next_layer:u8,cursor:usize,finished:bool, +pub struct OriginalStreamAll<'s, 'arena, 'loan, 'ctx> { + stager: &'s mut OriginalExpertStager<'ctx>, + rows: Option>, + copy: Option>, + compute: Option>, + issuer: Arc, + thread: Option>, + layer_start: [usize; 49], + first: u8, + end: u8, + next_layer: u8, + cursor: usize, + finished: bool, +} +pub struct OriginalStreamAllCompleted<'arena, 'loan, 'ctx> { + rows: OriginalPromptRows<'arena, 'loan, 'ctx>, + copy: OriginalGpuStream<'ctx>, + compute: OriginalGpuStream<'ctx>, + streamed: usize, } -pub struct OriginalStreamAllCompleted<'arena,'loan,'ctx>{rows:OriginalPromptRows<'arena,'loan,'ctx>,copy:OriginalGpuStream<'ctx>,compute:OriginalGpuStream<'ctx>,streamed:usize} // Closed whole-forward consumer. The original issuer implementation above is // unchanged; only actual Rows ownership leaves its internal scope temporarily. // This scope is borrowed synchronously and has no pending/extract operation. -pub struct OriginalStreamAllForward<'f,'s,'arena,'loan,'ctx> { - scope: &'f mut OriginalStreamAll<'s,'arena,'loan,'ctx>, - lease: crate::OriginalPromptLeaseIdentity, - rows: usize, - resident: Vec>, +pub struct OriginalStreamAllForward<'f, 's, 'arena, 'loan, 'ctx> { + scope: &'f mut OriginalStreamAll<'s, 'arena, 'loan, 'ctx>, + lease: crate::OriginalPromptLeaseIdentity, + rows: usize, + resident: Vec>, } // Original1751..1784: each blob's LAST read is its gather into real // persistent grp_gu/grp_d. Release that ring slot immediately after gather, // NOT after collecting raw pointers or waiting for all sparse group members. -const ORIGINAL_MMQ_GROUP:usize=16; +const ORIGINAL_MMQ_GROUP: usize = 16; /// Private callback loan from a current real cache prefix or copied Stage slot. /// This transport view certifies no format, binding, finite or session state. -pub(crate) struct OriginalStreamAllMember<'member,'ctx> { - context:&'ctx crate::Context<'ctx>, - expert:u32,blob:BufferHandle,bytes:usize, - _borrow:std::marker::PhantomData<&'member ()>, +pub(crate) struct OriginalStreamAllMember<'member, 'ctx> { + context: &'ctx crate::Context<'ctx>, + expert: u32, + blob: BufferHandle, + bytes: usize, + _borrow: std::marker::PhantomData<&'member ()>, } /// The actual members whose gathers returned, not their already released Stage /// pointers. Root's producer owns the real persistent copied MMQ bank throughout. pub(crate) struct OriginalStreamAllGatheredGroup<'group> { - first:usize,experts:&'group [u32], + first: usize, + experts: &'group [u32], } /// Closed driver producer implemented only by the actual MMQ layer adapter. /// gather MUST enqueue its final blob read into its real grp_gu/grp_d slot @@ -58,9 +92,23 @@ pub(crate) struct OriginalStreamAllGatheredGroup<'group> { /// grouped GU/SwiGLU/Q8/Down/scatter on the SAME compute stream. A success return /// is scheduling progress only; numerical/current-row guards stay with producer. pub(crate) trait OriginalStreamAllGroupProducer<'ctx> { - fn validate(&self,context:&crate::Context<'ctx>,rows:&OriginalPromptRows<'_,'_,'ctx>,layer:u8)->Result<()>; - fn gather(&mut self,member:&OriginalStreamAllMember<'_,'ctx>,group_slot:usize,stream:&mut OriginalGpuStream<'ctx>)->Result<()>; - fn project(&mut self,group:&OriginalStreamAllGatheredGroup<'_>,stream:&mut OriginalGpuStream<'ctx>)->Result<()>; + fn validate( + &self, + context: &crate::Context<'ctx>, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + layer: u8, + ) -> Result<()>; + fn gather( + &mut self, + member: &OriginalStreamAllMember<'_, 'ctx>, + group_slot: usize, + stream: &mut OriginalGpuStream<'ctx>, + ) -> Result<()>; + fn project( + &mut self, + group: &OriginalStreamAllGatheredGroup<'_>, + stream: &mut OriginalGpuStream<'ctx>, + ) -> Result<()>; } #[path = "original_stream_all/impl_originalstreamalloptions.rs"] diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalexpertstager.rs b/crates/cuda-driver/src/original_stream_all/impl_originalexpertstager.rs index 9979c318..caf837d9 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalexpertstager.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalexpertstager.rs @@ -4,166 +4,312 @@ use super::*; impl<'ctx> OriginalExpertStager<'ctx> { - /// Moves the genuine physical row lease through the whole forward consumer. - /// Success must return that same lease. On error a consumed/dropped carrier - /// may return None: stop/join/drain and poison happen inside this synchronous - /// call before the actual parent arena/cache borrow can be used again. - pub fn run_stream_all_forward<'arena,'loan,T>( - &mut self,rows:OriginalPromptRows<'arena,'loan,'ctx>, - copy:OriginalGpuStream<'ctx>,compute:OriginalGpuStream<'ctx>, - first:u8,end:u8,options:OriginalStreamAllOptions,host_allowance:usize, - consumer:impl FnOnce(&mut OriginalStreamAllForward<'_,'_,'arena,'loan,'ctx>,OriginalPromptRows<'arena,'loan,'ctx>) - ->(Result,Option>), - ) ->Result<(T,OriginalStreamAllCompleted<'arena,'loan,'ctx>)> { - if first>=end||end>48{return Err(Error::InvalidQwenShape);} - if !std::ptr::eq(rows.context(),self.context){return Err(Error::ContextMismatch);} - let count=usize::from(end-first).checked_mul(512).ok_or(Error::BudgetExceeded)?; - let extra=count.checked_mul(size_of::>()) - .and_then(|n|n.checked_add(size_of::>())) - .and_then(|n|n.checked_add(crate::OriginalPromptLeaseIdentity::metadata_bytes())) - .ok_or(Error::BudgetExceeded)?; - // Add to the original run's conservative MAX_JOBS metadata before any job - // publication or issuer activity; physical/source caps remain shared. - let original=MAX_JOBS.checked_mul(size_of::()) - .and_then(|n|n.checked_add(GPU_RING_MAX*size_of::()+size_of::()+size_of::>()+size_of::>())) - .ok_or(Error::BudgetExceeded)?; - if self.metadata_bytes.checked_add(original).and_then(|n|n.checked_add(extra)).is_none_or(|n|n>META_CAP){return Err(Error::BudgetExceeded);} - let remaining=host_allowance.checked_sub(extra).ok_or(Error::BudgetExceeded)?; - let source=self.source.as_ref().ok_or(Error::ContextPoisoned)?;source.validate()?; - let total=original.checked_add(extra).and_then(|n|n.checked_add(if options.issuer{WORKER_STACK}else{0})).ok_or(Error::BudgetExceeded)?; - if total>host_allowance||available_memory()?SOURCE_CAP){return Err(Error::BudgetExceeded);} - let mut resident=Vec::new();resident.try_reserve_exact(count).map_err(|_|Error::HostAllocation)?; - if resident.capacity()>count{return Err(Error::BudgetExceeded);} - for layer in first..end {for expert in 0..512 {resident.push(rows.cache_expert_span(usize::from(layer),expert)?);}} - let lease=rows.lease_identity();let row_count=rows.rows(); - self.run_stream_all(rows,copy,compute,first,end,options,remaining,move|scope| { - let actual=scope.rows.take().ok_or(Error::ContextPoisoned)?; - let mut forward=OriginalStreamAllForward{scope,lease,rows:row_count,resident}; - let invoked=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||consumer(&mut forward,actual))); - let (result,returned)=match invoked { - Ok(value)=>value, - Err(panic)=>{ - forward.scope.stager.context.poison();forward.scope.stager.context.retain_driver(); - // Original outer scope catches this unwind and unconditionally joins and - // drains before resuming; no successful physical lease escapes. - std::panic::resume_unwind(panic) + /// Moves the genuine physical row lease through the whole forward consumer. + /// Success must return that same lease. On error a consumed/dropped carrier + /// may return None: stop/join/drain and poison happen inside this synchronous + /// call before the actual parent arena/cache borrow can be used again. + pub fn run_stream_all_forward<'arena, 'loan, T>( + &mut self, + rows: OriginalPromptRows<'arena, 'loan, 'ctx>, + copy: OriginalGpuStream<'ctx>, + compute: OriginalGpuStream<'ctx>, + first: u8, + end: u8, + options: OriginalStreamAllOptions, + host_allowance: usize, + consumer: impl FnOnce( + &mut OriginalStreamAllForward<'_, '_, 'arena, 'loan, 'ctx>, + OriginalPromptRows<'arena, 'loan, 'ctx>, + ) -> (Result, Option>), + ) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> { + if first >= end || end > 48 { + return Err(Error::InvalidQwenShape); + } + if !std::ptr::eq(rows.context(), self.context) { + return Err(Error::ContextMismatch); + } + let count = usize::from(end - first).checked_mul(512).ok_or(Error::BudgetExceeded)?; + let extra = count + .checked_mul(size_of::>()) + .and_then(|n| n.checked_add(size_of::>())) + .and_then(|n| n.checked_add(crate::OriginalPromptLeaseIdentity::metadata_bytes())) + .ok_or(Error::BudgetExceeded)?; + // Add to the original run's conservative MAX_JOBS metadata before any job + // publication or issuer activity; physical/source caps remain shared. + let original = MAX_JOBS + .checked_mul(size_of::()) + .and_then(|n| { + n.checked_add( + GPU_RING_MAX * size_of::() + + size_of::() + + size_of::>() + + size_of::>(), + ) + }) + .ok_or(Error::BudgetExceeded)?; + if self.metadata_bytes.checked_add(original).and_then(|n| n.checked_add(extra)).is_none_or(|n| n > META_CAP) { + return Err(Error::BudgetExceeded); + } + let remaining = host_allowance.checked_sub(extra).ok_or(Error::BudgetExceeded)?; + let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; + source.validate()?; + let total = original + .checked_add(extra) + .and_then(|n| n.checked_add(if options.issuer { WORKER_STACK } else { 0 })) + .ok_or(Error::BudgetExceeded)?; + if total > host_allowance + || available_memory()? < total.checked_add(HEADROOM).ok_or(Error::BudgetExceeded)? + || source + .charge() + .checked_add(self.host_bytes as u64) + .and_then(|n| n.checked_add(total as u64)) + .is_none_or(|n| n > SOURCE_CAP) + { + return Err(Error::BudgetExceeded); + } + let mut resident = Vec::new(); + resident.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; + if resident.capacity() > count { + return Err(Error::BudgetExceeded); + } + for layer in first..end { + for expert in 0..512 { + resident.push(rows.cache_expert_span(usize::from(layer), expert)?); + } + } + let lease = rows.lease_identity(); + let row_count = rows.rows(); + self.run_stream_all(rows, copy, compute, first, end, options, remaining, move |scope| { + let actual = scope.rows.take().ok_or(Error::ContextPoisoned)?; + let mut forward = OriginalStreamAllForward { scope, lease, rows: row_count, resident }; + let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut forward, actual))); + let (result, returned) = match invoked { + Ok(value) => value, + Err(panic) => { + forward.scope.stager.context.poison(); + forward.scope.stager.context.retain_driver(); + // Original outer scope catches this unwind and unconditionally joins and + // drains before resuming; no successful physical lease escapes. + std::panic::resume_unwind(panic) + } + }; + match returned { + Some(mut actual) => { + let valid = forward.validate_rows(&actual); + if valid.is_err() { + actual.mark_failed(); + } + forward.scope.rows = Some(actual); + combine(result, valid) + } + None => { + forward.scope.stager.context.poison(); + forward.scope.stager.context.retain_driver(); + combine(result, Err(Error::ContextPoisoned)) + } + } + }) } - }; - match returned { - Some(mut actual)=>{ - let valid=forward.validate_rows(&actual); - if valid.is_err(){actual.mark_failed();} - forward.scope.rows=Some(actual); - combine(result,valid) - }, - None=>{ - forward.scope.stager.context.poison();forward.scope.stager.context.retain_driver(); - combine(result,Err(Error::ContextPoisoned)) +} +impl OriginalStreamAllForward<'_, '_, '_, '_, '_> { + /// Actual lease identity only, never model/finite/session authority. + pub fn validate_rows(&self, rows: &OriginalPromptRows<'_, '_, '_>) -> Result<()> { + self.scope.healthy()?; + if rows.is_failed() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(rows.context(), self.scope.stager.context) { + return Err(Error::ContextMismatch); + } + if rows.rows() != self.rows || !self.lease.same_lease(&rows.lease_identity()) { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + // The closed consumer already owns the actual Rows. Do not borrow Rows + // across this callback: real phase producers move that same carrier. Each + // producer still validates its genuine Rows/source/phase independently. + pub(crate) fn with_compute( + &mut self, + consumer: impl FnOnce(&mut OriginalGpuStream<'_>) -> Result, + ) -> Result { + self.scope.healthy()?; + consumer(self.scope.compute.as_mut().ok_or(Error::ContextPoisoned)?) + } + /// The cache prefix and Stage handles were admitted from the genuine Rows + /// before it moved. The exact ascending all-expert issuer/copy/used order is + /// identical to consume_layer above; this method returns no numerical proof. + pub(crate) fn consume_layer( + &mut self, + rows: &OriginalPromptRows<'_, '_, '_>, + layer: u8, + experts: &[u32], + mut producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>, + ) -> Result<()> { + self.validate_rows(rows)?; + let scope = &mut self.scope; + if layer != scope.next_layer + || layer < scope.first + || layer >= scope.end + || experts.len() > 512 + || experts.windows(2).any(|p| p[0] >= p[1]) + || experts.iter().any(|e| *e >= 512) + { + return Err(Error::InvalidQwenShape); + } + let layer_end = scope.layer_start[layer as usize + 1]; + for &e in experts { + scope.release_unused(e, layer_end)?; + scope.healthy()?; + if scope.cursor < layer_end && scope.issuer.entries[scope.cursor].expert == e { + let k = scope.cursor; + let entry = scope.issuer.entries[k]; + if entry.layer != layer { + return Err(Error::InvalidQwenShape); + } + while scope.issuer.issued.load(Ordering::Acquire) <= k { + scope.healthy()?; + thread::yield_now(); + } + let sl = k % scope.issuer.ring; + let api = &scope.stager.api; + let copied = scope.issuer.events.copied[sl]; + let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?; + compute.with_enqueue(|s| api.wait(s, copied))?; + producer(e, scope.issuer.targets[sl], entry.bytes, compute)?; + compute.with_enqueue(|s| api.record(scope.issuer.events.used[sl], s))?; + scope.cursor += 1; + scope.give_back()?; + } else { + let index = usize::from(layer - scope.first) * 512 + e as usize; + let (h, n) = self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)?; + producer(e, h, n, scope.compute.as_mut().ok_or(Error::ContextPoisoned)?)?; + } + } + scope.release_unused(512, layer_end)?; + scope.next_layer += 1; + Ok(()) } - } - }) - } } -impl OriginalStreamAllForward<'_,'_,'_,'_,'_> { - /// Actual lease identity only, never model/finite/session authority. - pub fn validate_rows(&self,rows:&OriginalPromptRows<'_,'_,'_>)->Result<()> { - self.scope.healthy()?; - if rows.is_failed(){return Err(Error::ContextPoisoned);} - if !std::ptr::eq(rows.context(),self.scope.stager.context){return Err(Error::ContextMismatch);} - if rows.rows()!=self.rows||!self.lease.same_lease(&rows.lease_identity()){return Err(Error::InvalidQwenShape);} - Ok(()) - } - // The closed consumer already owns the actual Rows. Do not borrow Rows - // across this callback: real phase producers move that same carrier. Each - // producer still validates its genuine Rows/source/phase independently. - pub(crate) fn with_compute(&mut self,consumer:impl FnOnce(&mut OriginalGpuStream<'_>)->Result)->Result { - self.scope.healthy()?; - consumer(self.scope.compute.as_mut().ok_or(Error::ContextPoisoned)?) - } - /// The cache prefix and Stage handles were admitted from the genuine Rows - /// before it moved. The exact ascending all-expert issuer/copy/used order is - /// identical to consume_layer above; this method returns no numerical proof. - pub(crate) fn consume_layer(&mut self,rows:&OriginalPromptRows<'_,'_,'_>,layer:u8,experts:&[u32],mut producer:impl FnMut(u32,BufferHandle,usize,&mut OriginalGpuStream<'_>)->Result<()>)->Result<()> { - self.validate_rows(rows)?; - let scope=&mut self.scope; - if layer!=scope.next_layer||layer=scope.end||experts.len()>512||experts.windows(2).any(|p|p[0]>=p[1])||experts.iter().any(|e|*e>=512){return Err(Error::InvalidQwenShape);} - let layer_end=scope.layer_start[layer as usize+1]; - for &e in experts { - scope.release_unused(e,layer_end)?;scope.healthy()?; - if scope.cursor OriginalStreamAllMember<'member,'ctx> { - pub(crate) fn expert(&self)->u32{self.expert} - pub(crate) fn context(&self)->&'ctx crate::Context<'ctx>{self.context} - // Driver-only real gather adapter. Never exported to runtime/user code. - pub(crate) fn checked_blob(&self)->Result<(BufferHandle,usize)>{self.blob.validate_extent(self.bytes)?;Ok((self.blob,self.bytes))} +impl<'member, 'ctx> OriginalStreamAllMember<'member, 'ctx> { + pub(crate) fn expert(&self) -> u32 { + self.expert + } + pub(crate) fn context(&self) -> &'ctx crate::Context<'ctx> { + self.context + } + // Driver-only real gather adapter. Never exported to runtime/user code. + pub(crate) fn checked_blob(&self) -> Result<(BufferHandle, usize)> { + self.blob.validate_extent(self.bytes)?; + Ok((self.blob, self.bytes)) + } } impl OriginalStreamAllGatheredGroup<'_> { - pub(crate) fn first(&self)->usize{self.first} - pub(crate) fn experts(&self)->&[u32]{self.experts} -} -impl<'f,'s,'arena,'loan,'ctx> OriginalStreamAllForward<'f,'s,'arena,'loan,'ctx> { - /// Literal ascending global stream walk with default16/actual lastpartial. - /// No whole-group raw Stage retention, so arbitrarily sparse IDs continue to - /// release unused entries and advance the real copied/used ring normally. - pub(crate) fn consume_layer_grouped>( - &mut self,rows:&OriginalPromptRows<'_,'_,'ctx>,layer:u8,experts:&[u32],producer:&mut P, - )->Result<()> { - self.validate_rows(rows)?; - let scope=&mut self.scope; - if layer!=scope.next_layer||layer=scope.end||experts.len()>512||experts.windows(2).any(|p|p[0]>=p[1])||experts.iter().any(|e|*e>=512){return Err(Error::InvalidQwenShape);} - producer.validate(scope.stager.context,rows,layer)?; - let layer_end=scope.layer_start[layer as usize+1]; - let mut group_ids=[0u32;ORIGINAL_MMQ_GROUP]; - for (j,&expert) in experts.iter().enumerate() { - scope.release_unused(expert,layer_end)?;scope.healthy()?; - let group_slot=j%ORIGINAL_MMQ_GROUP;group_ids[group_slot]=expert; - let last=group_slot+1==ORIGINAL_MMQ_GROUP||j+1==experts.len(); - if scope.cursor usize { + self.first } - // Exact Original used mark AFTER actual gather's last source read, BEFORE - // the grouped math for the last member. No new host/device synchronization. - compute.with_enqueue(|s|api.record(scope.issuer.events.used[slot],s))?; - if last{producer.project(&OriginalStreamAllGatheredGroup{first:j-group_slot,experts:&group_ids[..group_slot+1]},compute)?;} - // Original gives back this chronological slot after its compute callback - // (including final-member group launches) returns. - scope.cursor+=1;scope.give_back()?; - }else{ - let index=usize::from(layer-scope.first)*512+expert as usize; - let (blob,bytes)=self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)?; - let compute=scope.compute.as_mut().ok_or(Error::ContextPoisoned)?; - { - let member=OriginalStreamAllMember{context:scope.stager.context,expert,blob,bytes,_borrow:std::marker::PhantomData}; - producer.gather(&member,group_slot,compute)?; + pub(crate) fn experts(&self) -> &[u32] { + self.experts + } +} +impl<'f, 's, 'arena, 'loan, 'ctx> OriginalStreamAllForward<'f, 's, 'arena, 'loan, 'ctx> { + /// Literal ascending global stream walk with default16/actual lastpartial. + /// No whole-group raw Stage retention, so arbitrarily sparse IDs continue to + /// release unused entries and advance the real copied/used ring normally. + pub(crate) fn consume_layer_grouped>( + &mut self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + layer: u8, + experts: &[u32], + producer: &mut P, + ) -> Result<()> { + self.validate_rows(rows)?; + let scope = &mut self.scope; + if layer != scope.next_layer + || layer < scope.first + || layer >= scope.end + || experts.len() > 512 + || experts.windows(2).any(|p| p[0] >= p[1]) + || experts.iter().any(|e| *e >= 512) + { + return Err(Error::InvalidQwenShape); + } + producer.validate(scope.stager.context, rows, layer)?; + let layer_end = scope.layer_start[layer as usize + 1]; + let mut group_ids = [0u32; ORIGINAL_MMQ_GROUP]; + for (j, &expert) in experts.iter().enumerate() { + scope.release_unused(expert, layer_end)?; + scope.healthy()?; + let group_slot = j % ORIGINAL_MMQ_GROUP; + group_ids[group_slot] = expert; + let last = group_slot + 1 == ORIGINAL_MMQ_GROUP || j + 1 == experts.len(); + if scope.cursor < layer_end && scope.issuer.entries[scope.cursor].expert == expert { + let k = scope.cursor; + let entry = scope.issuer.entries[k]; + if entry.layer != layer { + return Err(Error::InvalidQwenShape); + } + while scope.issuer.issued.load(Ordering::Acquire) <= k { + scope.healthy()?; + thread::yield_now(); + } + let slot = k % scope.issuer.ring; + let api = &scope.stager.api; + let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?; + compute.with_enqueue(|s| api.wait(s, scope.issuer.events.copied[slot]))?; + { + let member = OriginalStreamAllMember { + context: scope.stager.context, + expert, + blob: scope.issuer.targets[slot], + bytes: entry.bytes, + _borrow: std::marker::PhantomData, + }; + producer.gather(&member, group_slot, compute)?; + } + // Exact Original used mark AFTER actual gather's last source read, BEFORE + // the grouped math for the last member. No new host/device synchronization. + compute.with_enqueue(|s| api.record(scope.issuer.events.used[slot], s))?; + if last { + producer.project( + &OriginalStreamAllGatheredGroup { + first: j - group_slot, + experts: &group_ids[..group_slot + 1], + }, + compute, + )?; + } + // Original gives back this chronological slot after its compute callback + // (including final-member group launches) returns. + scope.cursor += 1; + scope.give_back()?; + } else { + let index = usize::from(layer - scope.first) * 512 + expert as usize; + let (blob, bytes) = self.resident.get(index).copied().flatten().ok_or(Error::InvalidQwenShape)?; + let compute = scope.compute.as_mut().ok_or(Error::ContextPoisoned)?; + { + let member = OriginalStreamAllMember { + context: scope.stager.context, + expert, + blob, + bytes, + _borrow: std::marker::PhantomData, + }; + producer.gather(&member, group_slot, compute)?; + } + if last { + producer.project( + &OriginalStreamAllGatheredGroup { + first: j - group_slot, + experts: &group_ids[..group_slot + 1], + }, + compute, + )?; + } + } + } + scope.release_unused(512, layer_end)?; + scope.next_layer += 1; + Ok(()) } - if last{producer.project(&OriginalStreamAllGatheredGroup{first:j-group_slot,experts:&group_ids[..group_slot+1]},compute)?;} - } - } - scope.release_unused(512,layer_end)?;scope.next_layer+=1;Ok(()) - } } diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs index ca497426..8eb71496 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs @@ -3,195 +3,11 @@ #[allow(unused_imports)] use super::*; -impl OriginalStreamAllOptions { - pub fn from_environment()->Self { - fn atoi(s:&str)->i64{let mut bytes=s.trim_start().bytes().peekable();let negative=bytes.peek()==Some(&b'-');if bytes.peek().is_some_and(|c|*c==b'-'||*c==b'+'){bytes.next();}let mut n=0i64;while let Some(c@b'0'..=b'9')=bytes.next(){n=n.saturating_mul(10).saturating_add(i64::from(c-b'0'));}if negative{n.saturating_neg()}else{n}} - Self{minimum_rows:std::env::var("STRATA_PREFILL_STREAM_MIN").ok().as_deref().map_or(1024,|s|atoi(s).max(0) as usize),issuer:std::env::var("STRATA_PREFILL_ISSUER").ok().as_deref().is_none_or(|s|atoi(s)!=0)} - } - pub fn eligible(self,actual_rows:usize,actual_ring:usize)->bool{actual_ring>8&&actual_rows>=self.minimum_rows} -} -impl EventBank{ - pub(in super::super) fn retire(&self,api:&abi::Api)->Result<()>{let mut result=Ok(());for (i,live) in self.live.iter().enumerate(){if live.load(Ordering::Acquire){result=combine(result,api.event_sync(self.copied[i]));result=combine(result,api.event_sync(self.used[i]));}}if result.is_ok(){for e in self.copied.iter().chain(&self.used){result=combine(result,api.event_destroy(*e));}}result} -} -impl Issuer { - pub(super) fn fail(&self,error:Error){self.failed.store(true,Ordering::Release);self.stop.store(true,Ordering::Release);if let Ok(mut first)=self.error.lock(){if first.is_none(){*first=Some(error);}}} - pub(super) fn error(&self)->Error{self.error.lock().ok().and_then(|mut e|e.take()).unwrap_or(Error::ContextPoisoned)} - pub(super) fn issue_one(&self,api:&abi::Api,stager:&Shared,copy:usize,k:usize)->Result<()> { - if self.failed.load(Ordering::Acquire)||stager.failed.load(Ordering::Acquire){return Err(Error::ContextPoisoned);} - let entry=self.entries.get(k).ok_or(Error::InvalidSize)?;let sl=k%self.ring; - // stage_live is equivalent to k>=ring for this fresh chronological sequence. - if self.events.live[sl].load(Ordering::Acquire) {api.wait(copy,self.events.used[sl])?;} - while stager.ready[entry.job].load(Ordering::Acquire)==0 { - if self.stop.load(Ordering::Acquire){return Ok(());}if stager.failed.load(Ordering::Acquire){return Err(Error::ContextPoisoned);}thread::yield_now(); - } - let hs=stager.slots[entry.job%stager.slots.len()]; - api.copy_slot(self.targets[sl],hs,entry.bytes,copy)?; // exactly ONE contiguous GUD H2D - api.record(hs.event,copy)?; - stager.issued.store(entry.job+1,Ordering::Release); - api.record(self.events.copied[sl],copy)?; - self.events.live[sl].store(true,Ordering::Release); - self.issued.store(k+1,Ordering::Release);Ok(()) - } -} -pub(super) fn issuer_thread(api:Arc,shared:Arc,stager:Arc,context:usize,copy:usize){ - let entered=api.worker_enter(context); - if let Err(e)=entered{shared.fail(e);return;} - let result=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||{ - for k in 0..shared.entries.len(){ - while k>=shared.consumed.load(Ordering::Acquire).saturating_add(shared.ring){ - if shared.stop.load(Ordering::Acquire){return Ok(());}thread::yield_now(); - } - if shared.stop.load(Ordering::Acquire){return Ok(());} - shared.issue_one(&api,&stager,copy,k)?; - }Ok(()) - })); - match result{Ok(Ok(()))=>{},Ok(Err(e))=>shared.fail(e),Err(_)=>shared.fail(Error::InvalidDriverValue("Original issuer panic"))} - if let Err(e)=api.worker_leave(context){shared.fail(e);} -} -impl<'arena,'loan,'ctx> OriginalStreamAllCompleted<'arena,'loan,'ctx>{ - pub fn streamed_experts(&self)->usize{self.streamed} - pub fn into_parts(self)->(OriginalPromptRows<'arena,'loan,'ctx>,OriginalGpuStream<'ctx>,OriginalGpuStream<'ctx>){(self.rows,self.copy,self.compute)} -} -impl<'ctx> OriginalExpertStager<'ctx>{ - /// Scope guarantees join/drain even on panic. No callback can extract the - /// physical parent owner or issuer addresses; source-current/finite/actual - /// runtime row checks remain mandatory at the caller's producer boundary. - pub fn run_stream_all<'arena,'loan,T>(&mut self,rows:OriginalPromptRows<'arena,'loan,'ctx>,copy:OriginalGpuStream<'ctx>,compute:OriginalGpuStream<'ctx>, - first:u8,end:u8,options:OriginalStreamAllOptions,host_allowance:usize, - consumer:impl FnOnce(&mut OriginalStreamAll<'_,'arena,'loan,'ctx>)->Result) - ->Result<(T,OriginalStreamAllCompleted<'arena,'loan,'ctx>)>{ - if self.is_failed()||self.external||self.flight.is_some(){return Err(Error::ContextPoisoned);} - if first>=end||end>48{return Err(Error::InvalidQwenShape);} - if !std::ptr::eq(rows.context(),self.context){return Err(Error::ContextMismatch);} - copy.validate_context(self.context)?;compute.validate_context(self.context)?; - let ring=rows.copy_ring_slots()?; - if !options.eligible(rows.rows(),ring){return Err(Error::InvalidQwenShape);} - let source=self.source.as_ref().ok_or(Error::ContextPoisoned)?;source.validate()?; - let metadata_bytes=MAX_JOBS.checked_mul(size_of::()).and_then(|n|n.checked_add(GPU_RING_MAX*size_of::()+size_of::()+size_of::>()+size_of::>())).filter(|n|*n<=META_CAP).ok_or(Error::BudgetExceeded)?; - if self.metadata_bytes.checked_add(metadata_bytes).is_none_or(|n|n>META_CAP){return Err(Error::BudgetExceeded);} - let extra=metadata_bytes.checked_add(if options.issuer{WORKER_STACK}else{0}).ok_or(Error::BudgetExceeded)?; - if extra>host_allowance||available_memory()?SOURCE_CAP){return Err(Error::BudgetExceeded);} - let mut entries=Vec::new();let mut targets=Vec::new();let mut copied=Vec::new();let mut used=Vec::new(); - entries.try_reserve_exact(MAX_JOBS).map_err(|_|Error::HostAllocation)?; - targets.try_reserve_exact(GPU_RING_MAX).map_err(|_|Error::HostAllocation)?; - if entries.capacity()>MAX_JOBS||targets.capacity()>GPU_RING_MAX{return Err(Error::BudgetExceeded);} - for s in 0..ring {let (h,n)=rows.copy_ring_span(s)?;h.validate_extent(n)?;if nGPU_RING_MAX||used.capacity()>GPU_RING_MAX{return Err(Error::BudgetExceeded);} - let mut live=Vec::new();live.try_reserve_exact(GPU_RING_MAX).map_err(|_|Error::HostAllocation)?; - if live.capacity()>GPU_RING_MAX{return Err(Error::BudgetExceeded);}live.resize_with(GPU_RING_MAX,||AtomicBool::new(false)); - let guard=self.context.enter().inspect_err(|_|{self.context.poison();self.context.retain_driver();})?; - let creation:Result<()>=(||{for _ in 0..GPU_RING_MAX{copied.push(self.api.event_create()?);used.push(self.api.event_create()?);}Ok(())})(); - let pop=guard.finish();if pop.is_err(){self.context.poison();self.context.retain_driver();} - if let Err(primary)=combine(creation,pop){ - if self.context.is_poisoned(){std::mem::forget(copied);std::mem::forget(used);std::mem::forget(self.api.clone());return Err(primary);} - let cleanup=(||{let guard=self.context.enter()?;let mut r=Ok(());for e in copied.iter().chain(&used){r=combine(r,self.api.event_destroy(*e));}combine(r,guard.finish())})(); - if cleanup.is_err(){self.context.poison();self.context.retain_driver();std::mem::forget(copied);std::mem::forget(used);std::mem::forget(self.api.clone());}return combine(Err(primary),cleanup); - } - self.stream_events=Some(Arc::new(EventBank{copied,used,live})); - } - let events=self.stream_events.as_ref().ok_or(Error::ContextPoisoned)?.clone(); - let issuer=Arc::new(Issuer{entries,targets,events,issued:AtomicUsize::new(0),consumed:AtomicUsize::new(0),stop:AtomicBool::new(false),failed:AtomicBool::new(false),error:Mutex::new(None),ring}); - let mut scope=OriginalStreamAll{stager:self,rows:Some(rows),copy:Some(copy),compute:Some(compute),issuer,thread:None,layer_start,first,end,next_layer:first,cursor:layer_start[first as usize],finished:false}; - { - let mut work=scope.stager.shared.work.lock().map_err(|_|Error::ContextPoisoned)?; - for ready in scope.stager.shared.ready.iter().take(work.jobs.len()){ready.store(0,Ordering::Relaxed);} - scope.stager.external=true;scope.stager.generation=generation;scope.stager.shared.issued.store(0,Ordering::Release); - scope.stager.shared.head.store((u64::from(generation)<<32)|((work.jobs.len() as u64)<<16),Ordering::Release);work.generation=generation; - } - scope.stager.shared.cv.notify_all(); - let start=if options.issuer{ - let api=scope.stager.api.clone();let shared=scope.issuer.clone();let stager=scope.stager.shared.clone();let token=abi::Api::context_token(scope.stager.context.handle.ok_or(Error::ContextPoisoned)?); - let stream=scope.copy.as_mut().ok_or(Error::InvalidSize)?.with_enqueue(Ok)?; - match thread::Builder::new().stack_size(WORKER_STACK).spawn(move||issuer_thread(api,shared,stager,token,stream)){Ok(t)=>{scope.thread=Some(t);Ok(())},Err(_)=>Err(Error::HostAllocation)} - }else{scope.issue_inline(ring)}; - if let Err(primary)=start{return combine(Err(primary),scope.cleanup());} - let invoked=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||consumer(&mut scope))); - let result=match invoked {Ok(result)=>result,Err(panic)=>{let _=scope.cleanup();std::panic::resume_unwind(panic)}}; - let complete=if result.is_ok() && (scope.next_layer!=end||scope.cursor!=scope.issuer.entries.len()){Err(Error::InvalidQwenShape)}else{Ok(())}; - let result=combine(result,complete);let cleanup=scope.cleanup();let value=combine(result,cleanup)?; - let completed=OriginalStreamAllCompleted{rows:scope.rows.take().ok_or(Error::ContextPoisoned)?,copy:scope.copy.take().ok_or(Error::ContextPoisoned)?,compute:scope.compute.take().ok_or(Error::ContextPoisoned)?,streamed:scope.issuer.issued.load(Ordering::Acquire)}; - Ok((value,completed)) - } -} -impl OriginalStreamAll<'_,'_,'_,'_>{ - pub(super) fn issue_inline(&mut self,limit:usize)->Result<()> { - while self.issuer.issued.load(Ordering::Acquire)Result<()> {if self.stager.is_failed()||self.issuer.failed.load(Ordering::Acquire){Err(Error::ContextPoisoned)}else{Ok(())}} - pub(super) fn give_back(&mut self)->Result<()> { - self.issuer.consumed.store(self.cursor,Ordering::Release); - if self.thread.is_none(){self.issue_inline(self.cursor.saturating_add(self.issuer.ring))?;}Ok(()) - } - pub(super) fn release_unused(&mut self,end_expert:u32,layer_end:usize)->Result<()> { - while self.cursor)->Result<()>)->Result<()> { - self.healthy()?; - if layer!=self.next_layer||layer=self.end||experts.len()>512||experts.windows(2).any(|p|p[0]>=p[1])||experts.iter().any(|e|*e>=512){return Err(Error::InvalidQwenShape);} - let layer_end=self.layer_start[layer as usize+1]; - for &e in experts { - self.release_unused(e,layer_end)?;self.healthy()?; - if self.cursorResult<()> { - if self.finished{return Ok(());} - self.issuer.stop.store(true,Ordering::Release); - let mut result=Ok(()); - if let Some(t)=self.thread.take(){if t.join().is_err(){result=Err(Error::InvalidDriverValue("Original issuer join"));}} - if self.issuer.failed.load(Ordering::Acquire){result=combine(result,Err(self.issuer.error()));} - self.stager.shared.stop(self.stager.generation); - if let Some(source)=self.stager.source.as_ref(){if let Some(file)=&source.file{result=combine(result,file.lease.validate_current().map_err(|_|Error::InvalidSize));}} - if self.stager.shared.failed.load(Ordering::Acquire){result=combine(result,Err(self.stager.shared.error()));} - result=combine(result,self.copy.as_ref().map_or(Err(Error::ContextPoisoned),OriginalGpuStream::synchronize)); - result=combine(result,self.compute.as_ref().map_or(Err(Error::ContextPoisoned),OriginalGpuStream::synchronize)); - if result.is_err()||self.stager.context.is_poisoned(){ - self.stager.shared.failed.store(true,Ordering::Release);self.stager.context.poison();self.stager.context.retain_driver(); - if let Some(mut rows)=self.rows.take(){rows.mark_failed();std::mem::forget(rows);} - if let Some(s)=self.copy.take(){std::mem::forget(s);}if let Some(s)=self.compute.take(){std::mem::forget(s);} - std::mem::forget(self.issuer.clone());std::mem::forget(self.stager.api.clone()); - } - self.stager.external=false;self.finished=true;result - } -} -impl Drop for OriginalStreamAll<'_,'_,'_,'_>{fn drop(&mut self){let _=self.cleanup();}} +#[path = "impl_originalstreamalloptions/impl_originalstreamalloptions_2.rs"] +mod impl_originalstreamalloptions_2; +#[allow(unused_imports)] +pub(super) use impl_originalstreamalloptions_2::issuer_thread; +#[path = "impl_originalstreamalloptions/impl_originalexpertstager.rs"] +mod impl_originalexpertstager; +#[path = "impl_originalstreamalloptions/impl_originalstreamall.rs"] +mod impl_originalstreamall; diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs new file mode 100644 index 00000000..a306cb24 --- /dev/null +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs @@ -0,0 +1,247 @@ +//! Moved out of the parent module by STRA-338: impl OriginalExpertStager. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalExpertStager<'ctx> { + /// Scope guarantees join/drain even on panic. No callback can extract the + /// physical parent owner or issuer addresses; source-current/finite/actual + /// runtime row checks remain mandatory at the caller's producer boundary. + pub fn run_stream_all<'arena, 'loan, T>( + &mut self, + rows: OriginalPromptRows<'arena, 'loan, 'ctx>, + copy: OriginalGpuStream<'ctx>, + compute: OriginalGpuStream<'ctx>, + first: u8, + end: u8, + options: OriginalStreamAllOptions, + host_allowance: usize, + consumer: impl FnOnce(&mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>) -> Result, + ) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> { + if self.is_failed() || self.external || self.flight.is_some() { + return Err(Error::ContextPoisoned); + } + if first >= end || end > 48 { + return Err(Error::InvalidQwenShape); + } + if !std::ptr::eq(rows.context(), self.context) { + return Err(Error::ContextMismatch); + } + copy.validate_context(self.context)?; + compute.validate_context(self.context)?; + let ring = rows.copy_ring_slots()?; + if !options.eligible(rows.rows(), ring) { + return Err(Error::InvalidQwenShape); + } + let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; + source.validate()?; + let metadata_bytes = MAX_JOBS + .checked_mul(size_of::()) + .and_then(|n| { + n.checked_add( + GPU_RING_MAX * size_of::() + + size_of::() + + size_of::>() + + size_of::>(), + ) + }) + .filter(|n| *n <= META_CAP) + .ok_or(Error::BudgetExceeded)?; + if self.metadata_bytes.checked_add(metadata_bytes).is_none_or(|n| n > META_CAP) { + return Err(Error::BudgetExceeded); + } + let extra = + metadata_bytes.checked_add(if options.issuer { WORKER_STACK } else { 0 }).ok_or(Error::BudgetExceeded)?; + if extra > host_allowance + || available_memory()? < extra.checked_add(HEADROOM).ok_or(Error::BudgetExceeded)? + || source + .charge() + .checked_add(self.host_bytes as u64) + .and_then(|n| n.checked_add(extra as u64)) + .is_none_or(|n| n > SOURCE_CAP) + { + return Err(Error::BudgetExceeded); + } + let mut entries = Vec::new(); + let mut targets = Vec::new(); + let mut copied = Vec::new(); + let mut used = Vec::new(); + entries.try_reserve_exact(MAX_JOBS).map_err(|_| Error::HostAllocation)?; + targets.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if entries.capacity() > MAX_JOBS || targets.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + for s in 0..ring { + let (h, n) = rows.copy_ring_span(s)?; + h.validate_extent(n)?; + if n < self.blob_bytes { + return Err(Error::InvalidSize); + } + targets.push(h); + } + let mut layer_start = [0usize; 49]; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?; + { + let mut work = self.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; + work.jobs.clear(); + for l in first..end { + layer_start[l as usize] = entries.len(); + for e in 0..512u32 { + if rows.cache_expert_span(l as usize, e as usize)?.is_some() { + continue; + } + let raw = source.raw_at(l, e, self.blob_bytes)?; + let job = work.jobs.len(); + entries.push(Entry { layer: l, expert: e, bytes: raw.bytes(), job }); + work.jobs.push(raw); + } + } + for l in end..=48 { + layer_start[l as usize] = entries.len(); + } + } + // Persistent Original RING_MAX copied/used bank. Constructor metadata + // reserves it; same real events/stage_live survive subsequent prompt chunks. + if self.stream_events.is_none() { + copied.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + used.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if copied.capacity() > GPU_RING_MAX || used.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + let mut live = Vec::new(); + live.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if live.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + live.resize_with(GPU_RING_MAX, || AtomicBool::new(false)); + let guard = self.context.enter().inspect_err(|_| { + self.context.poison(); + self.context.retain_driver(); + })?; + let creation: Result<()> = (|| { + for _ in 0..GPU_RING_MAX { + copied.push(self.api.event_create()?); + used.push(self.api.event_create()?); + } + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + if let Err(primary) = combine(creation, pop) { + if self.context.is_poisoned() { + std::mem::forget(copied); + std::mem::forget(used); + std::mem::forget(self.api.clone()); + return Err(primary); + } + let cleanup = (|| { + let guard = self.context.enter()?; + let mut r = Ok(()); + for e in copied.iter().chain(&used) { + r = combine(r, self.api.event_destroy(*e)); + } + combine(r, guard.finish()) + })(); + if cleanup.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(copied); + std::mem::forget(used); + std::mem::forget(self.api.clone()); + } + return combine(Err(primary), cleanup); + } + self.stream_events = Some(Arc::new(EventBank { copied, used, live })); + } + let events = self.stream_events.as_ref().ok_or(Error::ContextPoisoned)?.clone(); + let issuer = Arc::new(Issuer { + entries, + targets, + events, + issued: AtomicUsize::new(0), + consumed: AtomicUsize::new(0), + stop: AtomicBool::new(false), + failed: AtomicBool::new(false), + error: Mutex::new(None), + ring, + }); + let mut scope = OriginalStreamAll { + stager: self, + rows: Some(rows), + copy: Some(copy), + compute: Some(compute), + issuer, + thread: None, + layer_start, + first, + end, + next_layer: first, + cursor: layer_start[first as usize], + finished: false, + }; + { + let mut work = scope.stager.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; + for ready in scope.stager.shared.ready.iter().take(work.jobs.len()) { + ready.store(0, Ordering::Relaxed); + } + scope.stager.external = true; + scope.stager.generation = generation; + scope.stager.shared.issued.store(0, Ordering::Release); + scope + .stager + .shared + .head + .store((u64::from(generation) << 32) | ((work.jobs.len() as u64) << 16), Ordering::Release); + work.generation = generation; + } + scope.stager.shared.cv.notify_all(); + let start = if options.issuer { + let api = scope.stager.api.clone(); + let shared = scope.issuer.clone(); + let stager = scope.stager.shared.clone(); + let token = abi::Api::context_token(scope.stager.context.handle.ok_or(Error::ContextPoisoned)?); + let stream = scope.copy.as_mut().ok_or(Error::InvalidSize)?.with_enqueue(Ok)?; + match thread::Builder::new() + .stack_size(WORKER_STACK) + .spawn(move || issuer_thread(api, shared, stager, token, stream)) + { + Ok(t) => { + scope.thread = Some(t); + Ok(()) + } + Err(_) => Err(Error::HostAllocation), + } + } else { + scope.issue_inline(ring) + }; + if let Err(primary) = start { + return combine(Err(primary), scope.cleanup()); + } + let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut scope))); + let result = match invoked { + Ok(result) => result, + Err(panic) => { + let _ = scope.cleanup(); + std::panic::resume_unwind(panic) + } + }; + let complete = if result.is_ok() && (scope.next_layer != end || scope.cursor != scope.issuer.entries.len()) { + Err(Error::InvalidQwenShape) + } else { + Ok(()) + }; + let result = combine(result, complete); + let cleanup = scope.cleanup(); + let value = combine(result, cleanup)?; + let completed = OriginalStreamAllCompleted { + rows: scope.rows.take().ok_or(Error::ContextPoisoned)?, + copy: scope.copy.take().ok_or(Error::ContextPoisoned)?, + compute: scope.compute.take().ok_or(Error::ContextPoisoned)?, + streamed: scope.issuer.issued.load(Ordering::Acquire), + }; + Ok((value, completed)) + } +} diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamall.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamall.rs new file mode 100644 index 00000000..0340c04a --- /dev/null +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamall.rs @@ -0,0 +1,157 @@ +//! Moved out of the parent module by STRA-338: impl OriginalStreamAll, impl Drop_for_OriginalStreamAll. + +#[allow(unused_imports)] +use super::*; + +impl OriginalStreamAll<'_, '_, '_, '_> { + pub(in super::super) fn issue_inline(&mut self, limit: usize) -> Result<()> { + while self.issuer.issued.load(Ordering::Acquire) < limit.min(self.issuer.entries.len()) { + let k = self.issuer.issued.load(Ordering::Acquire); + let api = &self.stager.api; + let shared = &self.issuer; + let stager = &self.stager.shared; + let r = + self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|s| shared.issue_one(api, stager, s, k)); + if let Err(e) = r { + self.issuer.failed.store(true, Ordering::Release); + return Err(e); + } + } + Ok(()) + } + pub(in super::super) fn healthy(&self) -> Result<()> { + if self.stager.is_failed() || self.issuer.failed.load(Ordering::Acquire) { + Err(Error::ContextPoisoned) + } else { + Ok(()) + } + } + pub(in super::super) fn give_back(&mut self) -> Result<()> { + self.issuer.consumed.store(self.cursor, Ordering::Release); + if self.thread.is_none() { + self.issue_inline(self.cursor.saturating_add(self.issuer.ring))?; + } + Ok(()) + } + pub(in super::super) fn release_unused(&mut self, end_expert: u32, layer_end: usize) -> Result<()> { + while self.cursor < layer_end && self.issuer.entries[self.cursor].expert < end_expert { + self.healthy()?; + let sl = self.cursor % self.issuer.ring; + let api = &self.stager.api; + let event = self.issuer.events.used[sl]; + self.compute.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(|s| api.record(event, s))?; + self.cursor += 1; + self.give_back()?; + } + Ok(()) + } + /// Actual producer reads/gathers the blob within this closed callback. It + /// must enqueue its last blob read before returning; used is recorded then. + /// No whole finite/model capability is returned by stream transport itself. + pub(crate) fn consume_layer( + &mut self, + layer: u8, + experts: &[u32], + mut producer: impl FnMut(u32, BufferHandle, usize, &mut OriginalGpuStream<'_>) -> Result<()>, + ) -> Result<()> { + self.healthy()?; + if layer != self.next_layer + || layer < self.first + || layer >= self.end + || experts.len() > 512 + || experts.windows(2).any(|p| p[0] >= p[1]) + || experts.iter().any(|e| *e >= 512) + { + return Err(Error::InvalidQwenShape); + } + let layer_end = self.layer_start[layer as usize + 1]; + for &e in experts { + self.release_unused(e, layer_end)?; + self.healthy()?; + if self.cursor < layer_end && self.issuer.entries[self.cursor].expert == e { + let k = self.cursor; + let entry = self.issuer.entries[k]; + if entry.layer != layer { + return Err(Error::InvalidQwenShape); + } + while self.issuer.issued.load(Ordering::Acquire) <= k { + self.healthy()?; + thread::yield_now(); + } + let sl = k % self.issuer.ring; + let api = &self.stager.api; + let copied = self.issuer.events.copied[sl]; + let compute = self.compute.as_mut().ok_or(Error::ContextPoisoned)?; + compute.with_enqueue(|s| api.wait(s, copied))?; + producer(e, self.issuer.targets[sl], entry.bytes, compute)?; + compute.with_enqueue(|s| api.record(self.issuer.events.used[sl], s))?; + self.cursor += 1; + self.give_back()?; + } else { + let (h, n) = self + .rows + .as_ref() + .ok_or(Error::ContextPoisoned)? + .cache_expert_span(layer as usize, e as usize)? + .ok_or(Error::InvalidQwenShape)?; + producer(e, h, n, self.compute.as_mut().ok_or(Error::ContextPoisoned)?)?; + } + } + self.release_unused(512, layer_end)?; + self.next_layer += 1; + Ok(()) + } + pub(in super::super) fn cleanup(&mut self) -> Result<()> { + if self.finished { + return Ok(()); + } + self.issuer.stop.store(true, Ordering::Release); + let mut result = Ok(()); + if let Some(t) = self.thread.take() { + if t.join().is_err() { + result = Err(Error::InvalidDriverValue("Original issuer join")); + } + } + if self.issuer.failed.load(Ordering::Acquire) { + result = combine(result, Err(self.issuer.error())); + } + self.stager.shared.stop(self.stager.generation); + if let Some(source) = self.stager.source.as_ref() { + if let Some(file) = &source.file { + result = combine(result, file.lease.validate_current().map_err(|_| Error::InvalidSize)); + } + } + if self.stager.shared.failed.load(Ordering::Acquire) { + result = combine(result, Err(self.stager.shared.error())); + } + result = + combine(result, self.copy.as_ref().map_or(Err(Error::ContextPoisoned), OriginalGpuStream::synchronize)); + result = + combine(result, self.compute.as_ref().map_or(Err(Error::ContextPoisoned), OriginalGpuStream::synchronize)); + if result.is_err() || self.stager.context.is_poisoned() { + self.stager.shared.failed.store(true, Ordering::Release); + self.stager.context.poison(); + self.stager.context.retain_driver(); + if let Some(mut rows) = self.rows.take() { + rows.mark_failed(); + std::mem::forget(rows); + } + if let Some(s) = self.copy.take() { + std::mem::forget(s); + } + if let Some(s) = self.compute.take() { + std::mem::forget(s); + } + std::mem::forget(self.issuer.clone()); + std::mem::forget(self.stager.api.clone()); + } + self.stager.external = false; + self.finished = true; + result + } +} +impl Drop for OriginalStreamAll<'_, '_, '_, '_> { + fn drop(&mut self) { + let _ = self.cleanup(); + } +} diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamalloptions_2.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamalloptions_2.rs new file mode 100644 index 00000000..2f807442 --- /dev/null +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalstreamalloptions_2.rs @@ -0,0 +1,136 @@ +//! Moved out of the parent module by STRA-338: impl OriginalStreamAllOptions, impl EventBank, impl Issuer, fn issuer_thread, impl OriginalStreamAllCompleted. + +#[allow(unused_imports)] +use super::*; + +impl OriginalStreamAllOptions { + pub fn from_environment() -> Self { + fn atoi(s: &str) -> i64 { + let mut bytes = s.trim_start().bytes().peekable(); + let negative = bytes.peek() == Some(&b'-'); + if bytes.peek().is_some_and(|c| *c == b'-' || *c == b'+') { + bytes.next(); + } + let mut n = 0i64; + while let Some(c @ b'0'..=b'9') = bytes.next() { + n = n.saturating_mul(10).saturating_add(i64::from(c - b'0')); + } + if negative { n.saturating_neg() } else { n } + } + Self { + minimum_rows: std::env::var("STRATA_PREFILL_STREAM_MIN") + .ok() + .as_deref() + .map_or(1024, |s| atoi(s).max(0) as usize), + issuer: std::env::var("STRATA_PREFILL_ISSUER").ok().as_deref().is_none_or(|s| atoi(s) != 0), + } + } + pub fn eligible(self, actual_rows: usize, actual_ring: usize) -> bool { + actual_ring > 8 && actual_rows >= self.minimum_rows + } +} +impl EventBank { + pub(in super::super::super) fn retire(&self, api: &abi::Api) -> Result<()> { + let mut result = Ok(()); + for (i, live) in self.live.iter().enumerate() { + if live.load(Ordering::Acquire) { + result = combine(result, api.event_sync(self.copied[i])); + result = combine(result, api.event_sync(self.used[i])); + } + } + if result.is_ok() { + for e in self.copied.iter().chain(&self.used) { + result = combine(result, api.event_destroy(*e)); + } + } + result + } +} +impl Issuer { + pub(in super::super) fn fail(&self, error: Error) { + self.failed.store(true, Ordering::Release); + self.stop.store(true, Ordering::Release); + if let Ok(mut first) = self.error.lock() { + if first.is_none() { + *first = Some(error); + } + } + } + pub(in super::super) fn error(&self) -> Error { + self.error.lock().ok().and_then(|mut e| e.take()).unwrap_or(Error::ContextPoisoned) + } + pub(in super::super) fn issue_one(&self, api: &abi::Api, stager: &Shared, copy: usize, k: usize) -> Result<()> { + if self.failed.load(Ordering::Acquire) || stager.failed.load(Ordering::Acquire) { + return Err(Error::ContextPoisoned); + } + let entry = self.entries.get(k).ok_or(Error::InvalidSize)?; + let sl = k % self.ring; + // stage_live is equivalent to k>=ring for this fresh chronological sequence. + if self.events.live[sl].load(Ordering::Acquire) { + api.wait(copy, self.events.used[sl])?; + } + while stager.ready[entry.job].load(Ordering::Acquire) == 0 { + if self.stop.load(Ordering::Acquire) { + return Ok(()); + } + if stager.failed.load(Ordering::Acquire) { + return Err(Error::ContextPoisoned); + } + thread::yield_now(); + } + let hs = stager.slots[entry.job % stager.slots.len()]; + api.copy_slot(self.targets[sl], hs, entry.bytes, copy)?; // exactly ONE contiguous GUD H2D + api.record(hs.event, copy)?; + stager.issued.store(entry.job + 1, Ordering::Release); + api.record(self.events.copied[sl], copy)?; + self.events.live[sl].store(true, Ordering::Release); + self.issued.store(k + 1, Ordering::Release); + Ok(()) + } +} +pub(in super::super) fn issuer_thread( + api: Arc, + shared: Arc, + stager: Arc, + context: usize, + copy: usize, +) { + let entered = api.worker_enter(context); + if let Err(e) = entered { + shared.fail(e); + return; + } + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + for k in 0..shared.entries.len() { + while k >= shared.consumed.load(Ordering::Acquire).saturating_add(shared.ring) { + if shared.stop.load(Ordering::Acquire) { + return Ok(()); + } + thread::yield_now(); + } + if shared.stop.load(Ordering::Acquire) { + return Ok(()); + } + shared.issue_one(&api, &stager, copy, k)?; + } + Ok(()) + })); + match result { + Ok(Ok(())) => {} + Ok(Err(e)) => shared.fail(e), + Err(_) => shared.fail(Error::InvalidDriverValue("Original issuer panic")), + } + if let Err(e) = api.worker_leave(context) { + shared.fail(e); + } +} +impl<'arena, 'loan, 'ctx> OriginalStreamAllCompleted<'arena, 'loan, 'ctx> { + pub fn streamed_experts(&self) -> usize { + self.streamed + } + pub fn into_parts( + self, + ) -> (OriginalPromptRows<'arena, 'loan, 'ctx>, OriginalGpuStream<'ctx>, OriginalGpuStream<'ctx>) { + (self.rows, self.copy, self.compute) + } +} diff --git a/crates/cuda-driver/src/original_verify.rs b/crates/cuda-driver/src/original_verify.rs index b7260677..d7c89184 100644 --- a/crates/cuda-driver/src/original_verify.rs +++ b/crates/cuda-driver/src/original_verify.rs @@ -1,132 +1,268 @@ //! Original Verifier physical arena, retained GDN operands and accepted-prefix //! commit. Numerical owners only: the runtime must bind genuine current session //! lineage before each window and publication. No prompt-GEMM fallback. -#[path="original_verify_ffi.rs"] #[allow(unsafe_code)] pub(crate) mod abi; -#[path="original_verify_mapped.rs"] #[allow(unsafe_code)] mod mapped; -#[path="original_verify_layout.rs"] mod layout; -#[path="original_verify_diag.rs"] #[allow(unsafe_code)] mod diag; -#[path="original_verify_profile.rs"] mod profile; -#[path="original_verify_logits.rs"] mod logits; -#[path="original_verify_window_plan.rs"] pub(crate) mod window_plan; -#[path="original_verify_window_record.rs"] pub(crate) mod window_record; -#[path="original_verify_window_kernels.rs"] pub(crate) mod kernels; -#[path="original_verify_window_proj.rs"] pub(crate) mod proj; -#[path="original_verify_window_gr.rs"] pub(crate) mod gr; -#[path="original_verify_window_qsa.rs"] pub(crate) mod qsa; -#[path="original_verify_window_moe.rs"] pub(crate) mod moe; -#[path="original_verify_window_chain.rs"] pub(crate) mod chain; -#[path="original_verify_window_sm120.rs"] pub(crate) mod sm120; -#[path="original_verify_window_draft.rs"] pub(crate) mod draft; -#[path="original_verify_window_planner.rs"] pub(crate) mod planner; -#[cfg(test)] #[path="original_verify_window_gpu.rs"] mod window_gpu; -pub use layout::{OriginalVerifyGeometry,OriginalVerifyLayout,OriginalVerifySpan}; -pub use diag::{OriginalVerifyDiag,original_verify_diagnostics,original_verify_live_count,original_verify_release_live,write_original_verify_diagnostics}; -pub use profile::{OriginalVerifyProfile,PROFILE_STAMPS_PER_LAYER,profile_stamp_slot,profile_stamp_words}; -pub use logits::{RowLogprob,analyse_row,logpos_topk_from_environment,top_k,write_row_line,write_window_logprobs}; -use abi::{Arg,Command,Module}; +#[path = "original_verify_ffi.rs"] +#[allow(unsafe_code)] +pub(crate) mod abi; +#[path = "original_verify_window_chain.rs"] +pub(crate) mod chain; +#[path = "original_verify_diag.rs"] +#[allow(unsafe_code)] +mod diag; +#[path = "original_verify_window_draft.rs"] +pub(crate) mod draft; +#[path = "original_verify_window_gr.rs"] +pub(crate) mod gr; +#[path = "original_verify_window_kernels.rs"] +pub(crate) mod kernels; +#[path = "original_verify_layout.rs"] +mod layout; +#[path = "original_verify_logits.rs"] +mod logits; +#[path = "original_verify_mapped.rs"] +#[allow(unsafe_code)] +mod mapped; +#[path = "original_verify_window_moe.rs"] +pub(crate) mod moe; +#[path = "original_verify_window_planner.rs"] +pub(crate) mod planner; +#[path = "original_verify_profile.rs"] +mod profile; +#[path = "original_verify_window_proj.rs"] +pub(crate) mod proj; +#[path = "original_verify_window_qsa.rs"] +pub(crate) mod qsa; +#[path = "original_verify_window_sm120.rs"] +pub(crate) mod sm120; +#[cfg(test)] +#[path = "original_verify_window_gpu.rs"] +mod window_gpu; +#[path = "original_verify_window_plan.rs"] +pub(crate) mod window_plan; +#[path = "original_verify_window_record.rs"] +pub(crate) mod window_record; +use crate::original_gpu_schedule::{OriginalCapture, OriginalGraphResources, resources}; +use crate::{Context, DeviceBuffer, Error, Result, combine}; +use abi::{Arg, Command, Module}; +pub use diag::{ + OriginalVerifyDiag, original_verify_diagnostics, original_verify_live_count, original_verify_release_live, + write_original_verify_diagnostics, +}; +pub use layout::{OriginalVerifyGeometry, OriginalVerifyLayout, OriginalVerifySpan}; +pub use logits::{RowLogprob, analyse_row, logpos_topk_from_environment, top_k, write_row_line, write_window_logprobs}; use mapped::MappedAllocation; -use crate::{Context,DeviceBuffer,Error,Result,combine}; -use crate::original_gpu_schedule::{OriginalCapture,OriginalGraphResources,resources}; -use std::{cell::{Cell,RefCell},rc::Rc}; -const ASSET:&[u8]=concat!(include_str!("original_verify.ptx"),"\0").as_bytes(); -const QSA_ASSET:&[u8]=concat!(include_str!("original_verify_qsa.ptx"),"\0").as_bytes(); -const ASSET_SHA:[u8;32]=[208,218,218,103,21,251,128,139,179,40,130,145,253,74,92,41,231,143,215,250,110,112,242,185,77,34,15,134,11,180,51,83]; -const QSA_ASSET_SHA:[u8;32]=[245,123,65,130,226,25,43,231,245,211,25,231,165,224,47,170,95,194,69,192,97,66,108,210,191,193,57,207,69,58,220,5]; -const QSA_ENTRIES:&[&str]=&["verify_qsa_append_analytic","verify_qsa_append_table"]; -const RESERVE:usize=128<<20; -const STATE_WORDS:usize=128*48*128; -const HISTORY_WORDS:usize=10240*3; -const LAYER_BYTES:usize=(STATE_WORDS+HISTORY_WORDS)*4; -const CANONICAL_BYTES:usize=36*LAYER_BYTES; -const EPS:f32=1e-6; -const ENTRIES:&[&str]=&["verify_gdn_conv_l2_multi_kernel","verify_gdn_conv_commit_kernel","verify_gdn_ab_multi_kernel","verify_gdn_step_norm_multi_kernel","verify_embedding_gather_dev_kernel","verify_broadcast_streams_kernel","verify_copy_indexed_kernel","verify_fetch_blobs_kernel","verify_rebase_ptrs_kernel","verify_add_streams_broadcast_kernel","verify_ident_hits_kernel","verify_gather_rows_16","verify_gather_rows_4","verify_gather_rows_1","verify_map_ids_kernel","verify_row_top_prob_kernel","verify_mtp_select_kernel","verify_dense_steps_kernel","verify_window_ids_kernel","verify_wait_flag_ge_kernel","verify_resident_plan_kernel","verify_wait_flag_ge_or_kernel","verify_copy_i32_unless_kernel","verify_copy_or_zero_kernel","verify_gpu_stamp_kernel","verify_copy_from_mapped_kernel","verify_copy_rows_from_mapped_kernel","verify_doorbell_publish_kernel","verify_copy_i32_from_mapped_kernel","verify_clear_status","verify_scan_logits"]; +pub use profile::{OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, profile_stamp_slot, profile_stamp_words}; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; +const ASSET: &[u8] = concat!(include_str!("original_verify.ptx"), "\0").as_bytes(); +const QSA_ASSET: &[u8] = concat!(include_str!("original_verify_qsa.ptx"), "\0").as_bytes(); +const ASSET_SHA: [u8; 32] = [ + 208, 218, 218, 103, 21, 251, 128, 139, 179, 40, 130, 145, 253, 74, 92, 41, 231, 143, 215, 250, 110, 112, 242, 185, + 77, 34, 15, 134, 11, 180, 51, 83, +]; +const QSA_ASSET_SHA: [u8; 32] = [ + 245, 123, 65, 130, 226, 25, 43, 231, 245, 211, 25, 231, 165, 224, 47, 170, 95, 194, 69, 192, 97, 66, 108, 210, 191, + 193, 57, 207, 69, 58, 220, 5, +]; +const QSA_ENTRIES: &[&str] = &["verify_qsa_append_analytic", "verify_qsa_append_table"]; +const RESERVE: usize = 128 << 20; +const STATE_WORDS: usize = 128 * 48 * 128; +const HISTORY_WORDS: usize = 10240 * 3; +const LAYER_BYTES: usize = (STATE_WORDS + HISTORY_WORDS) * 4; +const CANONICAL_BYTES: usize = 36 * LAYER_BYTES; +const EPS: f32 = 1e-6; +const ENTRIES: &[&str] = &[ + "verify_gdn_conv_l2_multi_kernel", + "verify_gdn_conv_commit_kernel", + "verify_gdn_ab_multi_kernel", + "verify_gdn_step_norm_multi_kernel", + "verify_embedding_gather_dev_kernel", + "verify_broadcast_streams_kernel", + "verify_copy_indexed_kernel", + "verify_fetch_blobs_kernel", + "verify_rebase_ptrs_kernel", + "verify_add_streams_broadcast_kernel", + "verify_ident_hits_kernel", + "verify_gather_rows_16", + "verify_gather_rows_4", + "verify_gather_rows_1", + "verify_map_ids_kernel", + "verify_row_top_prob_kernel", + "verify_mtp_select_kernel", + "verify_dense_steps_kernel", + "verify_window_ids_kernel", + "verify_wait_flag_ge_kernel", + "verify_resident_plan_kernel", + "verify_wait_flag_ge_or_kernel", + "verify_copy_i32_unless_kernel", + "verify_copy_or_zero_kernel", + "verify_gpu_stamp_kernel", + "verify_copy_from_mapped_kernel", + "verify_copy_rows_from_mapped_kernel", + "verify_doorbell_publish_kernel", + "verify_copy_i32_from_mapped_kernel", + "verify_clear_status", + "verify_scan_logits", +]; /// Real contiguous Original canonical state/history allocation. Constructor /// takes the ACTUAL prompt-end F32 bytes; no implicit zero/new-session relabel. /// Runtime authenticates those bytes against its GdnPrior before calling. -struct Canonical<'ctx>{context:&'ctx Context<'ctx>,buffer:Option>,failed:Cell} -pub struct OriginalVerifyCanonicalGdn<'ctx>{inner:Rc>} +struct Canonical<'ctx> { + context: &'ctx Context<'ctx>, + buffer: Option>, + failed: Cell, +} +pub struct OriginalVerifyCanonicalGdn<'ctx> { + inner: Rc>, +} -struct Physical<'ctx>{context:&'ctx Context<'ctx>,layout:OriginalVerifyLayout,arena:Option>,prof:Option>,mapped:[RefCell>;15],module:Option,qsa_module:Option,window:RefCell,Vec<&'static str>)>>,generation:Cell,failed:Cell} +struct Physical<'ctx> { + context: &'ctx Context<'ctx>, + layout: OriginalVerifyLayout, + arena: Option>, + prof: Option>, + mapped: [RefCell>; 15], + module: Option, + qsa_module: Option, + window: RefCell, Vec<&'static str>)>>, + generation: Cell, + failed: Cell, +} /// One genuine fixed max-T bank. Root keeps this in every captured graph's /// resource aggregate; commands retain the stable ABI through final graph drain. -pub struct OriginalVerifyBank<'ctx>{physical:Rc>,last_t:usize,last_position:usize,last_tokens:[i32;8],generation:u64,last_keep:usize,released:bool, - /// Registered expert banks a window's PCIe DMA reads (`publish_gpu_plan`), held until the copy-stream fence. - pcie_sources:Vec>>, - /// `Verifier::set_pcie_mode` of the recorded window graphs (0 DMA, 2 copy kernel): how `publish_gpu_plan` stages, - /// and with the copy kernel the per-layer gate/up/down lengths the graphs copy (every published span must match). - pub(crate) pcie_mode:u8,pub(crate) pcie_roles:Option<[[usize;3];48]>} +pub struct OriginalVerifyBank<'ctx> { + physical: Rc>, + last_t: usize, + last_position: usize, + last_tokens: [i32; 8], + generation: u64, + last_keep: usize, + released: bool, + /// Registered expert banks a window's PCIe DMA reads (`publish_gpu_plan`), held until the copy-stream fence. + pcie_sources: Vec>>, + /// `Verifier::set_pcie_mode` of the recorded window graphs (0 DMA, 2 copy kernel): how `publish_gpu_plan` stages, + /// and with the copy kernel the per-layer gate/up/down lengths the graphs copy (every published span must match). + pub(crate) pcie_mode: u8, + pub(crate) pcie_roles: Option<[[usize; 3]; 48]>, +} /// Actual final residual row from a COMPLETED all-T verification graph. This /// retains the true arena; old generation refuses before every driver consumer. /// It carries no session/target provenance: Root binds the genuine txn separately. -pub struct OriginalVerifyRow<'ctx>{physical:Rc>,generation:u64,row:usize,position:usize} +pub struct OriginalVerifyRow<'ctx> { + physical: Rc>, + generation: u64, + row: usize, + position: usize, +} /// Actual whole residual/token bank from a successful completed window. /// Retains the real allocation, not a mapped-host alias or runtime capability. /// Consumers validate again before capture/replay; next staging invalidates it. -pub struct OriginalVerifyWindow<'ctx>{physical:Rc>,generation:u64,rows:usize,position:usize,sampled_ids:[i32;8]} +pub struct OriginalVerifyWindow<'ctx> { + physical: Rc>, + generation: u64, + rows: usize, + position: usize, + sampled_ids: [i32; 8], +} /// All actual GDN non-matrix source operands. Matrix projections are Root's /// genuine native MMVQ producer, ordered before the retained operand consumers. -#[derive(Clone,Copy)] +#[derive(Clone, Copy)] #[repr(usize)] -pub enum OriginalVerifyGdnStage{Conv=0,AlphaBeta=1,Recurrence=2} -pub struct OriginalVerifyGdnWeights<'a,'ctx>{pub conv:&'a DeviceBuffer<'ctx>,pub alpha:&'a DeviceBuffer<'ctx>,pub beta:&'a DeviceBuffer<'ctx>,pub dt:&'a DeviceBuffer<'ctx>,pub a:&'a DeviceBuffer<'ctx>,pub norm:&'a DeviceBuffer<'ctx>} -pub struct OriginalVerifyGdnJournal<'a,'ctx>{physical:Rc>,canonical:Rc>,weights:[OriginalVerifyGdnWeights<'a,'ctx>;36],ple:Option<&'a DeviceBuffer<'ctx>>,commands:RefCell>} +pub enum OriginalVerifyGdnStage { + Conv = 0, + AlphaBeta = 1, + Recurrence = 2, +} +pub struct OriginalVerifyGdnWeights<'a, 'ctx> { + pub conv: &'a DeviceBuffer<'ctx>, + pub alpha: &'a DeviceBuffer<'ctx>, + pub beta: &'a DeviceBuffer<'ctx>, + pub dt: &'a DeviceBuffer<'ctx>, + pub a: &'a DeviceBuffer<'ctx>, + pub norm: &'a DeviceBuffer<'ctx>, +} +pub struct OriginalVerifyGdnJournal<'a, 'ctx> { + physical: Rc>, + canonical: Rc>, + weights: [OriginalVerifyGdnWeights<'a, 'ctx>; 36], + ple: Option<&'a DeviceBuffer<'ctx>>, + commands: RefCell>, +} /// Only real driver graph aggregates can implement this sealed association. /// Root's all-layer aggregate returns its retained journal; runtime cannot mint it. -pub trait OriginalVerifyGraphResources<'ctx>:OriginalGraphResources{ - fn verifier_qsa(&self)->&crate::OriginalVerifyQsaJournal<'_, 'ctx>; - fn verifier_journal(&self)->&OriginalVerifyGdnJournal<'_, 'ctx>; +pub trait OriginalVerifyGraphResources<'ctx>: OriginalGraphResources { + fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx>; + fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx>; } /// The concrete all-owner resource aggregate for one captured verification /// graph. It retains the GDN state journal, the twelve QSA index images, and /// the exact native-head output rows as one affine owner. A graph cannot pair /// a journal from one context with a head or QSA checkpoint from another. -pub struct OriginalVerifyResources<'a,'ctx>{ - context:&'ctx Context<'ctx>, - journal:OriginalVerifyGdnJournal<'a,'ctx>, - qsa:Rc>, - head:crate::OriginalNativeHeadRows<'ctx>, +pub struct OriginalVerifyResources<'a, 'ctx> { + context: &'ctx Context<'ctx>, + journal: OriginalVerifyGdnJournal<'a, 'ctx>, + qsa: Rc>, + head: crate::OriginalNativeHeadRows<'ctx>, } -#[path="original_verify_schedule.rs"] mod schedule; -#[path="original_verify_gpu_plan.rs"] mod gpu_plan; -pub use gpu_plan::{MAX_PCIE_FETCHES,OriginalVerifyGpuPlan,OriginalVerifyPcieSource}; -#[cfg(any(test,feature="expert-tier-probe"))] #[path="original_verify_expert_probe.rs"] mod expert_probe; -#[cfg(any(test,feature="expert-tier-probe"))] pub use expert_probe::{OriginalExpertTierProbe,expert_probe_geometry}; -pub use schedule::{OriginalVerifier,OriginalVerifyWindowResult,OriginalVerifyCpuRows,OriginalVerifyCpuSink}; -#[path="original_verify_window_ops.rs"] mod window_ops; -pub use window_ops::{OriginalVerifyExpertLayout,OriginalVerifyWindowResources,UNBOUND_PRODUCERS,unsealed_window_assets}; -pub use gr::{HcHalfBuffers,HcLayerBuffers,HcOutputBuffers,OriginalVerifyGrBinding,PleBuffers,PleKeyBuffer,PLE_SCRATCH_BYTES}; -pub use moe::{OriginalVerifyExpertFormats,OriginalVerifyMoeBinding,OriginalVerifyMoeLayerWeights}; -pub use qsa::{OriginalVerifyQsaBinding,OriginalVerifyQsaKvBinding,OriginalVerifyQsaLayerWeights,OriginalVerifyQsaPolicy,QsaRope}; -pub use window_record::{ExpertTier,HcHalf,Projection,QuantSource,Rows,WindowOps,WindowPolicy,record_window}; -pub use proj::{OriginalVerifyGdnProjections,OriginalVerifyNativeMatrix,OriginalVerifyProjBinding,OriginalVerifyQsaProjections}; -pub use window_plan::{PlanLayout,WINDOW_LAYERS}; +#[path = "original_verify_gpu_plan.rs"] +mod gpu_plan; +#[path = "original_verify_schedule.rs"] +mod schedule; +pub use gpu_plan::{MAX_PCIE_FETCHES, OriginalVerifyGpuPlan, OriginalVerifyPcieSource}; +#[cfg(any(test, feature = "expert-tier-probe"))] +#[path = "original_verify_expert_probe.rs"] +mod expert_probe; +#[cfg(any(test, feature = "expert-tier-probe"))] +pub use expert_probe::{OriginalExpertTierProbe, expert_probe_geometry}; +pub use schedule::{OriginalVerifier, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyWindowResult}; +#[path = "original_verify_window_ops.rs"] +mod window_ops; +pub use gr::{ + HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyGrBinding, PLE_SCRATCH_BYTES, PleBuffers, + PleKeyBuffer, +}; +pub use moe::{OriginalVerifyExpertFormats, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights}; +pub use proj::{ + OriginalVerifyGdnProjections, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, OriginalVerifyQsaProjections, +}; +pub use qsa::{ + OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, OriginalVerifyQsaPolicy, + QsaRope, +}; +pub use window_ops::{ + OriginalVerifyExpertLayout, OriginalVerifyWindowResources, UNBOUND_PRODUCERS, unsealed_window_assets, +}; +pub use window_plan::{PlanLayout, WINDOW_LAYERS}; +pub use window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window}; mod share_window_modules_fn; #[allow(unused_imports)] -use share_window_modules_fn::share_window_modules; -#[allow(unused_imports)] use share_window_modules_fn::admission; #[allow(unused_imports)] -use share_window_modules_fn::handle; -#[allow(unused_imports)] use share_window_modules_fn::admit; #[allow(unused_imports)] -use share_window_modules_fn::poison; -#[allow(unused_imports)] -use share_window_modules_fn::transport; -#[allow(unused_imports)] -use share_window_modules_fn::zero; -#[allow(unused_imports)] use share_window_modules_fn::check_commands; #[allow(unused_imports)] use share_window_modules_fn::command; #[allow(unused_imports)] +pub(crate) use share_window_modules_fn::gather_rows_module; +#[allow(unused_imports)] +use share_window_modules_fn::handle; +#[allow(unused_imports)] +use share_window_modules_fn::poison; +#[allow(unused_imports)] use share_window_modules_fn::sealed_asset; #[allow(unused_imports)] -pub(crate) use share_window_modules_fn::gather_rows_module; +use share_window_modules_fn::share_window_modules; +#[allow(unused_imports)] +use share_window_modules_fn::transport; +#[allow(unused_imports)] +use share_window_modules_fn::zero; mod impl_originalverifygdnjournal; #[allow(unused_imports)] pub(crate) use impl_originalverifygdnjournal::verify_assets_sealed; diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal.rs index 2fb67273..7f1ba056 100644 --- a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal.rs +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal.rs @@ -3,190 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{ - /// The device history image the window rows advance (and the commit graph sets from `hist_snap`): the one buffer all aggregates share. - pub(crate) fn ple_buffer(&self)->Option<&DeviceBuffer<'ctx>>{self.ple} - pub(crate) fn submit(&self,capture:&mut OriginalCapture<'_, 'ctx>,commands:Vec)->Result<()>{capture.validate_context(self.physical.context)?;let stream=capture.stream_handle(self.physical.context)?;let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?}let mut retained=self.commands.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;retained.try_reserve_exact(commands.len()).map_err(|_|Error::HostAllocation)?;let first=retained.len();retained.extend(commands);check_commands(&retained)?;for c in &mut retained[first..]{if let Err(e)=module.launch(stream,c){if transport(&e){self.physical.failed.set(true);poison(self.physical.context)}return Err(e)}}Ok(())} - pub(crate) fn submit_qsa(&self,capture:&mut OriginalCapture<'_, 'ctx>,commands:Vec)->Result<()>{ - capture.validate_context(self.physical.context)?;let stream=capture.stream_handle(self.physical.context)?;let module=self.physical.qsa_module.as_ref().ok_or(Error::ContextPoisoned)?; - for c in &commands{module.admit(c)?;}let mut retained=self.commands.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;retained.try_reserve_exact(commands.len()).map_err(|_|Error::HostAllocation)?;let first=retained.len();retained.extend(commands);check_commands(&retained)?; - for c in &mut retained[first..]{if let Err(error)=module.launch(stream,c){if transport(&error){self.physical.failed.set(true);poison(self.physical.context)}return Err(error)}}Ok(()) - } - /// Pre-capture: load the sealed PTX assets the window producers will launch from. - pub(crate) fn ensure_window_assets(&self,specs:&[&'static kernels::AssetSpec])->Result<()>{self.physical.ensure_window_assets(specs)} - pub(crate) fn configure_window_shared(&self,attrs:&[(&'static kernels::AssetSpec,&'static str,usize)])->Result<()>{self.physical.configure_window_shared(attrs)} - pub(crate) fn window_device_attribute(&self,attribute:i32)->Result{self.physical.window_device_attribute(attribute)} - /// Launch window kernels (any loaded sealed asset) on the capture stream, in order. - pub(crate) fn submit_launches(&self,capture:&mut OriginalCapture<'_, 'ctx>,launches:Vec)->Result<()>{ - capture.validate_context(self.physical.context)?;let stream=capture.stream_handle(self.physical.context)?; - let mut commands=Vec::new();commands.try_reserve_exact(launches.len()).map_err(|_|Error::HostAllocation)?;for l in &launches{commands.push(l.command()?)} - let modules=self.physical.window.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - for(l,c)in launches.iter().zip(&commands){let m=modules.iter().find(|(n,_,_)|*n==l.asset.key()).ok_or(Error::InvalidDriverValue(l.asset.unsealed))?;m.1.admit(c)?} - let mut retained=self.commands.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;retained.try_reserve_exact(commands.len()).map_err(|_|Error::HostAllocation)?;let first=retained.len();retained.extend(commands);check_commands(&retained)?; - for(i,c)in retained[first..].iter_mut().enumerate(){let m=modules.iter().find(|(n,_,_)|*n==launches[i].asset.key()).ok_or(Error::InvalidDriverValue(launches[i].asset.unsealed))?;if let Err(e)=m.1.launch(stream,c){if transport(&e){self.physical.failed.set(true);poison(self.physical.context)}return Err(e)}}Ok(()) - } - pub(crate) fn context(&self)->&'ctx Context<'ctx>{self.physical.context} - pub(crate) fn address(&self,name:&str,offset:usize,bytes:usize)->Result{self.physical.span(name,offset,bytes)} - /// Literal mapped token/step/position copies at the start of each T graph. - pub fn capture_inputs(&self,capture:&mut OriginalCapture<'_, 'ctx>,t:usize)->Result<()>{ - let g=self.geometry();if !(1..=g.max_t).contains(&t){return Err(Error::InvalidQwenShape)}let mut commands=Vec::new();commands.try_reserve_exact(4).map_err(|_|Error::HostAllocation)?; - for(name,slot,count)in [("tok",0,t),("step",1,t*4),("pos",2,g.max_t*(g.heads+g.kv_heads+g.index_heads))]{commands.push(command("verify_copy_i32_from_mapped_kernel",[1,1,1],[128,1,1],vec![Arg::Address(self.physical.span(name,0,count*4)?),Arg::Address(self.physical.mapped_address(slot,0,count*4)?),Arg::I32(count as i32)])?);} - if self.ple.is_some(){let words=t*g.n;commands.push(command("verify_copy_from_mapped_kernel",[(words/4).div_ceil(256).min(64)as u32,1,1],[256,1,1],vec![Arg::Address(self.physical.span("ple",0,words*4)?),Arg::Address(self.physical.mapped_address(4,0,words*4)?),Arg::I64((words/4)as i64)])?);}self.submit(capture,commands) - } - /// Literal `gpu_stamp(prof_, l*33+i, cs)` of `STRATA_VERIFY_PROFILE`; recorded for group 0 only - /// and a no-op when the profile is off, so the captured graph is Original's either way. - pub fn capture_stamp(&self,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize,stage:usize)->Result<()>{ - let Some(b)=self.physical.prof.as_ref()else{return Ok(())}; - if layer>48||stage>=profile::PROFILE_STAMPS_PER_LAYER||(layer==48&&stage>1){return Err(Error::InvalidQwenShape)} - let slot=profile::profile_stamp_slot(layer,stage); - self.submit(capture,vec![command("verify_gpu_stamp_kernel",[1,1,1],[1,1,1],vec![Arg::Address(handle(b)?.qwen_address()),Arg::I32(slot as i32)])?]) - } - /// Real group doorbell after the original router. The host may borrow only - /// this completed group's mapped rows, while the captured GPU waits for M/A/B. - pub fn capture_doorbell(&self,capture:&mut OriginalCapture<'_, 'ctx>,begin:usize,end:usize)->Result<()>{let g=self.geometry();if begin>=end||end>g.max_t{return Err(Error::InvalidQwenShape)}let n=end-begin; - if chain::flags().glue{ - let a=|name:&str,off:usize,bytes:usize|self.physical.span(name,off,bytes); - return self.submit_launches(capture,vec![kernels::Launch::new(&chain::CHAIN,chain::E_DOORBELL,[1,1,1],[1024,1,1],0,vec![kernels::A::P(a("mixed",begin*g.n*4,n*g.n*4)?),kernels::A::P(a("ids",begin*g.k*4,n*g.k*4)?),kernels::A::P(a("w",begin*g.k*4,n*g.k*4)?),kernels::A::I32((n*g.n)as i32),kernels::A::I32((n*g.k)as i32),kernels::A::P(self.physical.mapped_address(6,begin*g.n*4,n*g.n*4)?),kernels::A::P(self.physical.mapped_address(7,begin*g.k*4,n*g.k*4)?),kernels::A::P(self.physical.mapped_address(8,begin*g.k*4,n*g.k*4)?),kernels::A::P(self.physical.mapped_address(9,0,4)?)])?]); - } - self.submit(capture,vec![command("verify_doorbell_publish_kernel",[1,1,1],[1024,1,1],vec![Arg::Address(self.physical.span("mixed",begin*g.n*4,n*g.n*4)?),Arg::Address(self.physical.span("ids",begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.span("w",begin*g.k*4,n*g.k*4)?),Arg::I32((n*g.n)as i32),Arg::I32((n*g.k)as i32),Arg::Address(self.physical.mapped_address(6,begin*g.n*4,n*g.n*4)?),Arg::Address(self.physical.mapped_address(7,begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.mapped_address(8,begin*g.k*4,n*g.k*4)?),Arg::Address(self.physical.mapped_address(9,0,4)?)])?]) - } - /// Exact batch convolution, BF16 MMVF alpha/beta, and recurrence. Canonical - /// state/history are READ ONLY; retained qkv/h/gate/beta banks span all36 layers. - pub fn capture_layer_stage(&self,stage:OriginalVerifyGdnStage,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize,begin:usize,end:usize)->Result<()>{ - self.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if layer>=36||begin>=end||end>g.max_t{return Err(Error::InvalidQwenShape)}let n=end-begin;let w=&self.weights[layer];let c=self.physical.context; - let qkv=self.physical.span("qkv_L",layer*g.max_t*g.channels*4,g.max_t*g.channels*4)?; - let h=self.physical.span("h_L",layer*g.max_t*g.channels*4,g.max_t*g.channels*4)?; - let gate=self.physical.span("gate_L",layer*g.max_t*g.value_heads*4,g.max_t*g.value_heads*4)?; - let beta=self.physical.span("beta_L",layer*g.max_t*g.value_heads*4,g.max_t*g.value_heads*4)?; - let mut commands=Vec::new();commands.try_reserve_exact(3).map_err(|_|Error::HostAllocation)?; - commands.push(command("verify_gdn_conv_l2_multi_kernel",[80,n as u32,1],[128,1,1],vec![Arg::Address(self.canonical.span(layer,true)?),Arg::Address(qkv),Arg::Address(admit(c,w.conv,10240*4*4)?),Arg::Address(h),Arg::I32(10240),Arg::I32(32),Arg::F32(EPS),Arg::I32(begin as i32)])?); - commands.push(command("verify_gdn_ab_multi_kernel",[12,1,1],[256,1,1],vec![Arg::Address(self.physical.span("mixed",begin*g.n*4,n*g.n*4)?),Arg::Address(admit(c,w.alpha,48*2560*2)?),Arg::Address(admit(c,w.beta,48*2560*2)?),Arg::Address(admit(c,w.dt,48*4)?),Arg::Address(admit(c,w.a,48*4)?),Arg::Address(gate+(begin*48*4) as u64),Arg::Address(beta+(begin*48*4) as u64),Arg::I32(2560),Arg::I32(48),Arg::I32(n as i32)])?); - commands.push(command("verify_gdn_step_norm_multi_kernel",[48,1,1],[128,4,1],vec![Arg::Address(self.canonical.span(layer,false)?),Arg::Address(h),Arg::I32(10240),Arg::Address(gate),Arg::Address(beta),Arg::Address(self.physical.span("z",0,g.max_t*6144*4)?),Arg::Address(admit(c,w.norm,128*4)?),Arg::F32(EPS),Arg::Address(self.physical.span("y",0,g.max_t*6144*4)?),Arg::I32(16),Arg::I32(48),Arg::I32(end as i32),Arg::Address(0),Arg::I32(begin as i32)])?); - if chain::flags().ab&&matches!(stage,OriginalVerifyGdnStage::AlphaBeta){ - let x=self.physical.span("mixed",begin*g.n*4,n*g.n*4)?; - return self.submit_launches(capture,vec![kernels::Launch::new(&chain::CHAIN,chain::E_GDN_AB,[96,1,1],[32,1,1],0,vec![kernels::A::P(x),kernels::A::P(admit(c,w.alpha,48*2560*2)?),kernels::A::P(admit(c,w.beta,48*2560*2)?),kernels::A::P(admit(c,w.dt,48*4)?),kernels::A::P(admit(c,w.a,48*4)?),kernels::A::P(gate+(begin*48*4) as u64),kernels::A::P(beta+(begin*48*4) as u64),kernels::A::I32(2560),kernels::A::I32(48),kernels::A::I32(n as i32)])?]); - } - let mut selected=Vec::new();selected.try_reserve_exact(1).map_err(|_|Error::HostAllocation)?;selected.push(commands.swap_remove(stage as usize));self.submit(capture,selected) - } - /// First node of the literal commit graph: accepted count/row/positions. - pub fn capture_commit_begin(&self,capture:&mut OriginalCapture<'_, 'ctx>)->Result<()>{ - self.validate_context(self.physical.context)?;let g=self.physical.layout.geometry; - self.submit(capture,vec![command("verify_copy_i32_from_mapped_kernel",[1,1,1],[128,1,1],vec![Arg::Address(self.physical.span("commit",0,(g.max_t+2)*4)?),Arg::Address(self.physical.mapped_address(3,0,(g.max_t+2)*4)?),Arg::I32((g.max_t+2)as i32)])?]) - } - /// Exactly one actual GDN layer at its original place among all48 layers. - /// QSA layers are committed by the retained QSA journal between these calls. - pub fn capture_commit_layer(&self,capture:&mut OriginalCapture<'_, 'ctx>,i:usize)->Result<()>{ - self.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if i>=36{return Err(Error::InvalidQwenShape)}let commit=self.physical.span("commit",0,(g.max_t+2)*4)?; - let qkv=self.physical.span("qkv_L",i*g.max_t*10240*4,g.max_t*10240*4)?;let h=self.physical.span("h_L",i*g.max_t*10240*4,g.max_t*10240*4)?;let gate=self.physical.span("gate_L",i*g.max_t*48*4,g.max_t*48*4)?;let beta=self.physical.span("beta_L",i*g.max_t*48*4,g.max_t*48*4)?; - self.submit(capture,vec![ - command("verify_gdn_conv_commit_kernel",[40,1,1],[256,1,1],vec![Arg::Address(self.canonical.span(i,true)?),Arg::Address(qkv),Arg::I32(10240),Arg::Address(commit)])?, - command("verify_gdn_step_norm_multi_kernel",[48,1,1],[128,4,1],vec![Arg::Address(self.canonical.span(i,false)?),Arg::Address(h),Arg::I32(10240),Arg::Address(gate),Arg::Address(beta),Arg::Address(self.physical.span("z",0,g.max_t*6144*4)?),Arg::Address(admit(self.physical.context,self.weights[i].norm,128*4)?),Arg::F32(EPS),Arg::Address(self.physical.span("y_dummy",0,g.max_t*6144*4)?),Arg::I32(16),Arg::I32(48),Arg::I32(g.max_t as i32),Arg::Address(commit),Arg::I32(0)])? - ]) - } - /// Load the sealed `draft_commit.ptx` module before the commit graph is captured (module loading is not capturable). - pub(crate) fn load_draft_commit_asset(&self)->Result<()>{self.physical.ensure_window_assets(&[&draft::DRAFT_COMMIT,&draft::DRAFT_COMMIT_QSA])} - /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the 36 GDN layers' conv history commit and recurrence replay of `capture_commit_layer` in ONE launch - /// (`draft_commit_gdn_layers`: grid (48 heads + 20 conv blocks, 36 layers)). The per-layer operands are affine in the layer (checked against the per-layer spans below). - pub(crate) fn capture_commit_gdn_fused(&self,capture:&mut OriginalCapture<'_, 'ctx>)->Result<()>{ - self.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;let t=g.max_t; - let commit=self.physical.span("commit",0,(t+2)*4)?; - let state0=self.canonical.span(0,false)?;let hist0=self.canonical.span(0,true)?; - let rows=t*10240*4;let small=t*48*4; - let qkv=self.physical.span("qkv_L",0,rows)?;let h=self.physical.span("h_L",0,rows)?;let gate=self.physical.span("gate_L",0,small)?;let beta=self.physical.span("beta_L",0,small)?; - // affine layout: layer i of every operand is base + i * stride (the per-layer spans `capture_commit_layer` binds) - for i in [1usize,17,35]{ - if self.canonical.span(i,false)?!=state0+(i*LAYER_BYTES)as u64||self.canonical.span(i,true)?!=hist0+(i*LAYER_BYTES)as u64 - ||self.physical.span("qkv_L",i*rows,rows)?!=qkv+(i*rows)as u64||self.physical.span("h_L",i*rows,rows)?!=h+(i*rows)as u64 - ||self.physical.span("gate_L",i*small,small)?!=gate+(i*small)as u64||self.physical.span("beta_L",i*small,small)?!=beta+(i*small)as u64{return Err(Error::InvalidQwenShape)} - } - if hist0,frame:usize,begin:usize,end:usize)->Result<()>{ - if self.physical.layout.span("dbg_ladder").is_err(){return Ok(())} - let g=self.physical.layout.geometry;let row=g.hc*g.n;if frame>=96||end>g.max_t||begin>=end{return Err(Error::InvalidQwenShape)} - let mut commands=Vec::new(); - for t in begin..end{commands.push(command("verify_copy_from_mapped_kernel",[64,1,1],[256,1,1],vec![Arg::Address(self.physical.span("dbg_ladder",(frame*g.max_t+t)*row*4,row*4)?),Arg::Address(self.physical.span("R",t*row*4,row*4)?),Arg::I64((row/4)as i64)])?);} - self.submit(capture,commands) - } - pub fn capture_ple_snapshot(&self,capture:&mut OriginalCapture<'_, 'ctx>,row:usize)->Result<()>{ - let g=self.physical.layout.geometry;if row>=g.max_t{return Err(Error::InvalidQwenShape)}let history=self.ple.ok_or(Error::InvalidQwenShape)?;let words=9*10240;let src=admit(self.physical.context,history,words*4)?; - self.submit(capture,vec![command("verify_copy_from_mapped_kernel",[64,1,1],[256,1,1],vec![Arg::Address(self.physical.span("hist_snap",row*words*4,words*4)?),Arg::Address(src),Arg::I64((words/4)as i64)])?]) - } - /// Post-drain integer exponent scan over the ACTUAL whole head output. This - /// is an integration finite gate, never an id-as-finite certificate. The four - /// byte status reuses retired hit_count scratch; no active kernel can alias it. - pub(crate) fn validate_completed_logits(&self,stream:&mut crate::OriginalGpuStream<'ctx>,logits:&DeviceBuffer<'ctx>,rows:usize)->Result<()>{ - let _span_validate=crate::host_profile::span("head.validate_logits");self.validate_context(self.physical.context)?;stream.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if !(1..=g.max_t).contains(&rows){return Err(Error::InvalidQwenShape)}let words=rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?;let src=admit(self.physical.context,logits,words.checked_mul(4).ok_or(Error::InvalidSize)?)?; - let arena=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;if handle(logits)?.overlaps(logits.len(),handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)}let status=self.span("hit_count",0,4)?; - let mut commands=vec![command("verify_clear_status",[1,1,1],[32,1,1],vec![Arg::Address(status.qwen_address())])?,command("verify_scan_logits",[words.div_ceil(256).min(65535)as u32,1,1],[256,1,1],vec![Arg::Address(src),Arg::U64(words as u64),Arg::Address(status.qwen_address())])?]; - let module=self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?;for c in &commands{module.admit(c)?;}let span_vs=crate::host_profile::span("head.validate_stream");let launched=stream.with_enqueue(|h|{for c in &mut commands{module.launch(h,c)?;}Ok(())});let sync=stream.synchronize();drop(span_vs);if sync.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(commands);return combine(launched,sync)}combine(launched,sync)?; - let span_vc=crate::host_profile::span("head.validate_ctx_copy");let mut bytes=zero(4)?;let guard=self.physical.context.enter()?;let copy=self.physical.context.driver.api.copy_to(status,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish();drop(span_vc);if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop)}combine(combine(copy,sync),pop)?;if u32::from_le_bytes(bytes[..4].try_into().map_err(|_|Error::InvalidSize)?)!=0{return Err(Error::NonFiniteMmqOutput("Original Verifier full logits"))}Ok(()) - } - /// Actual original PLE history image; selected accepted row, never final-image - /// metadata relabel. Borrowed destination must survive the graph aggregate. - pub fn capture_ple_commit(&self,capture:&mut OriginalCapture<'_, 'ctx>)->Result<()>{let history=self.ple.ok_or(Error::InvalidQwenShape)?;let bytes=9*10240*4;let dst=admit(self.physical.context,history,bytes)?;let arena=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;if handle(history)?.overlaps(bytes,handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)}self.submit(capture,vec![command("verify_copy_indexed_kernel",[64,1,1],[256,1,1],vec![Arg::Address(dst),Arg::Address(self.physical.span("hist_snap",0,self.physical.layout.geometry.max_t*bytes)?),Arg::I64((9*10240)as i64),Arg::Address(self.physical.span("commit",4,4)?),Arg::I64((9*10240)as i64)])?])} - /// Closed driver sibling producers resolve physical slices through the actual - /// bank owner, not by constructing false whole DeviceBuffers around aliases. - pub(crate) fn span(&self,name:&str,offset:usize,bytes:usize)->Result{let s=self.physical.layout.span(name)?;if bytes==0||offset.checked_add(bytes).is_none_or(|e|e>s.bytes){return Err(Error::InvalidSize)}let b=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;handle(b)?.checked_subspan(b.len(),s.offset+offset,bytes)} -} -impl<'a,'ctx> OriginalVerifyResources<'a,'ctx>{ - pub fn new(context:&'ctx Context<'ctx>,journal:OriginalVerifyGdnJournal<'a,'ctx>, - qsa:Rc>,head:crate::OriginalNativeHeadRows<'ctx>)->Result{ - journal.validate_context(context)?; - qsa.validate_context(context)?; - head.validate_context(context)?; - Ok(Self{context,journal,qsa,head}) - } -} -impl resources::Sealed for OriginalVerifyResources<'_, '_>{} -impl OriginalGraphResources for OriginalVerifyResources<'_, '_>{ - fn validate_context(&self,context:&Context<'_>)->Result<()>{ - if !std::ptr::eq(self.context,context){return Err(Error::ContextMismatch)} - self.journal.validate_context(context)?; - self.qsa.validate_context(context)?; - self.head.validate_context(context) - } -} -impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx>{ - fn verifier_qsa(&self)->&crate::OriginalVerifyQsaJournal<'_, 'ctx>{self.qsa.as_ref()} - fn verifier_journal(&self)->&OriginalVerifyGdnJournal<'_, 'ctx>{&self.journal} -} -impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx>{ - fn native_head_rows(&self)->Result<&crate::OriginalNativeHeadRows<'ctx>>{Ok(&self.head)} - fn native_head_rows_mut(&mut self)->Result<&mut crate::OriginalNativeHeadRows<'ctx>>{Ok(&mut self.head)} -} - -impl OriginalVerifyGdnJournal<'_, '_>{ - pub(crate) fn has_ple(&self)->bool{self.ple.is_some()} - pub(crate) fn ple_history_address(&self)->Result>{self.ple.map(|b|Ok(handle(b)?.qwen_address())).transpose()} - pub(crate) fn canonical_identity(&self)->usize{Rc::as_ptr(&self.canonical)as usize} - pub(crate) fn geometry(&self)->OriginalVerifyGeometry{self.physical.layout.geometry} - pub fn validate_bank(&self,bank:&OriginalVerifyBank<'_>)->Result<()>{if !Rc::ptr_eq(&self.physical,&bank.physical){return Err(Error::InvalidQwenShape)}self.validate_context(self.physical.context)} -} - -impl OriginalVerifyWindow<'_>{ - /// Structural geometry admission, not a numerical/session authority. - pub(crate) fn validate_mtp_geometry(&self)->Result<()>{self.validate_context(self.physical.context)?;let g=self.physical.layout.geometry;if g.hc!=4||g.n!=2560||!(1..=8).contains(&self.rows){return Err(Error::InvalidQwenShape);}Ok(())} - /// Only cached MTP graph address comparison may use the retained old physical - /// owner after a newer completed generation supersedes it. This method mints - /// no current-window readiness and the new window must validate independently. - pub(crate) fn retained_residual_address_for_mtp(&self)->Result{self.physical.validate(self.physical.context)?;let s=self.physical.layout.span("R")?;let b=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;Ok(handle(b)?.checked_subspan(b.len(),s.offset,self.rows*40960)?.qwen_address())} -} - -impl OriginalVerifyWindow<'_>{ - /// Current actual R scratch extent. Extra rows authorize only literal MTP - /// draft_first repetition; they are NOT completed verifier rows or sampled IDs. - pub(crate) fn actual_mtp_residual_bank(&self,rows:usize)->Result{self.validate_mtp_geometry()?;if rows==0||rows>self.physical.layout.geometry.max_t||rows>8{return Err(Error::InvalidQwenShape);}let s=self.physical.layout.span("R")?;let b=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;if rows*40960>s.bytes{return Err(Error::InvalidSize);}handle(b)?.checked_subspan(b.len(),s.offset,rows*40960)} -} - -/// Sealed-state of the two compiled verifier assets: the embedded PTX must match its pinned digest -/// (the same check `OriginalVerifyBank::new` performs). Probe only. -pub(crate) fn verify_assets_sealed() -> [(&'static str, bool); 2] { - [("original_verify", sealed_asset(ASSET,ASSET_SHA).is_ok()),("original_verify_qsa", sealed_asset(QSA_ASSET,QSA_ASSET_SHA).is_ok())] -} +mod impl_originalverifygdnjournal_2; +mod impl_originalverifygdnjournal_2_2; +mod impl_originalverifygdnjournal_3; +mod impl_originalverifywindow; +#[allow(unused_imports)] +pub(crate) use impl_originalverifywindow::verify_assets_sealed; diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs new file mode 100644 index 00000000..87f604bb --- /dev/null +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2.rs @@ -0,0 +1,224 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyGdnJournal. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { + /// The device history image the window rows advance (and the commit graph sets from `hist_snap`): the one buffer all aggregates share. + pub(crate) fn ple_buffer(&self) -> Option<&DeviceBuffer<'ctx>> { + self.ple + } + pub(crate) fn submit(&self, capture: &mut OriginalCapture<'_, 'ctx>, commands: Vec) -> Result<()> { + capture.validate_context(self.physical.context)?; + let stream = capture.stream_handle(self.physical.context)?; + let module = self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?; + for c in &commands { + module.admit(c)? + } + let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?; + let first = retained.len(); + retained.extend(commands); + check_commands(&retained)?; + for c in &mut retained[first..] { + if let Err(e) = module.launch(stream, c) { + if transport(&e) { + self.physical.failed.set(true); + poison(self.physical.context) + } + return Err(e); + } + } + Ok(()) + } + pub(crate) fn submit_qsa(&self, capture: &mut OriginalCapture<'_, 'ctx>, commands: Vec) -> Result<()> { + capture.validate_context(self.physical.context)?; + let stream = capture.stream_handle(self.physical.context)?; + let module = self.physical.qsa_module.as_ref().ok_or(Error::ContextPoisoned)?; + for c in &commands { + module.admit(c)?; + } + let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?; + let first = retained.len(); + retained.extend(commands); + check_commands(&retained)?; + for c in &mut retained[first..] { + if let Err(error) = module.launch(stream, c) { + if transport(&error) { + self.physical.failed.set(true); + poison(self.physical.context) + } + return Err(error); + } + } + Ok(()) + } + /// Pre-capture: load the sealed PTX assets the window producers will launch from. + pub(crate) fn ensure_window_assets(&self, specs: &[&'static kernels::AssetSpec]) -> Result<()> { + self.physical.ensure_window_assets(specs) + } + pub(crate) fn configure_window_shared( + &self, + attrs: &[(&'static kernels::AssetSpec, &'static str, usize)], + ) -> Result<()> { + self.physical.configure_window_shared(attrs) + } + pub(crate) fn window_device_attribute(&self, attribute: i32) -> Result { + self.physical.window_device_attribute(attribute) + } + /// Launch window kernels (any loaded sealed asset) on the capture stream, in order. + pub(crate) fn submit_launches( + &self, + capture: &mut OriginalCapture<'_, 'ctx>, + launches: Vec, + ) -> Result<()> { + capture.validate_context(self.physical.context)?; + let stream = capture.stream_handle(self.physical.context)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(launches.len()).map_err(|_| Error::HostAllocation)?; + for l in &launches { + commands.push(l.command()?) + } + let modules = self.physical.window.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + for (l, c) in launches.iter().zip(&commands) { + let m = modules + .iter() + .find(|(n, _, _)| *n == l.asset.key()) + .ok_or(Error::InvalidDriverValue(l.asset.unsealed))?; + m.1.admit(c)? + } + let mut retained = self.commands.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + retained.try_reserve_exact(commands.len()).map_err(|_| Error::HostAllocation)?; + let first = retained.len(); + retained.extend(commands); + check_commands(&retained)?; + for (i, c) in retained[first..].iter_mut().enumerate() { + let m = modules + .iter() + .find(|(n, _, _)| *n == launches[i].asset.key()) + .ok_or(Error::InvalidDriverValue(launches[i].asset.unsealed))?; + if let Err(e) = m.1.launch(stream, c) { + if transport(&e) { + self.physical.failed.set(true); + poison(self.physical.context) + } + return Err(e); + } + } + Ok(()) + } + pub(crate) fn context(&self) -> &'ctx Context<'ctx> { + self.physical.context + } + pub(crate) fn address(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.physical.span(name, offset, bytes) + } + /// Literal mapped token/step/position copies at the start of each T graph. + pub fn capture_inputs(&self, capture: &mut OriginalCapture<'_, 'ctx>, t: usize) -> Result<()> { + let g = self.geometry(); + if !(1..=g.max_t).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let mut commands = Vec::new(); + commands.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; + for (name, slot, count) in + [("tok", 0, t), ("step", 1, t * 4), ("pos", 2, g.max_t * (g.heads + g.kv_heads + g.index_heads))] + { + commands.push(command( + "verify_copy_i32_from_mapped_kernel", + [1, 1, 1], + [128, 1, 1], + vec![ + Arg::Address(self.physical.span(name, 0, count * 4)?), + Arg::Address(self.physical.mapped_address(slot, 0, count * 4)?), + Arg::I32(count as i32), + ], + )?); + } + if self.ple.is_some() { + let words = t * g.n; + commands.push(command( + "verify_copy_from_mapped_kernel", + [(words / 4).div_ceil(256).min(64) as u32, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(self.physical.span("ple", 0, words * 4)?), + Arg::Address(self.physical.mapped_address(4, 0, words * 4)?), + Arg::I64((words / 4) as i64), + ], + )?); + } + self.submit(capture, commands) + } + /// Literal `gpu_stamp(prof_, l*33+i, cs)` of `STRATA_VERIFY_PROFILE`; recorded for group 0 only + /// and a no-op when the profile is off, so the captured graph is Original's either way. + pub fn capture_stamp(&self, capture: &mut OriginalCapture<'_, 'ctx>, layer: usize, stage: usize) -> Result<()> { + let Some(b) = self.physical.prof.as_ref() else { return Ok(()) }; + if layer > 48 || stage >= profile::PROFILE_STAMPS_PER_LAYER || (layer == 48 && stage > 1) { + return Err(Error::InvalidQwenShape); + } + let slot = profile::profile_stamp_slot(layer, stage); + self.submit( + capture, + vec![command( + "verify_gpu_stamp_kernel", + [1, 1, 1], + [1, 1, 1], + vec![Arg::Address(handle(b)?.qwen_address()), Arg::I32(slot as i32)], + )?], + ) + } + /// Real group doorbell after the original router. The host may borrow only + /// this completed group's mapped rows, while the captured GPU waits for M/A/B. + pub fn capture_doorbell(&self, capture: &mut OriginalCapture<'_, 'ctx>, begin: usize, end: usize) -> Result<()> { + let g = self.geometry(); + if begin >= end || end > g.max_t { + return Err(Error::InvalidQwenShape); + } + let n = end - begin; + if chain::flags().glue { + let a = |name: &str, off: usize, bytes: usize| self.physical.span(name, off, bytes); + return self.submit_launches( + capture, + vec![kernels::Launch::new( + &chain::CHAIN, + chain::E_DOORBELL, + [1, 1, 1], + [1024, 1, 1], + 0, + vec![ + kernels::A::P(a("mixed", begin * g.n * 4, n * g.n * 4)?), + kernels::A::P(a("ids", begin * g.k * 4, n * g.k * 4)?), + kernels::A::P(a("w", begin * g.k * 4, n * g.k * 4)?), + kernels::A::I32((n * g.n) as i32), + kernels::A::I32((n * g.k) as i32), + kernels::A::P(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?), + kernels::A::P(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?), + kernels::A::P(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?), + kernels::A::P(self.physical.mapped_address(9, 0, 4)?), + ], + )?], + ); + } + self.submit( + capture, + vec![command( + "verify_doorbell_publish_kernel", + [1, 1, 1], + [1024, 1, 1], + vec![ + Arg::Address(self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?), + Arg::Address(self.physical.span("ids", begin * g.k * 4, n * g.k * 4)?), + Arg::Address(self.physical.span("w", begin * g.k * 4, n * g.k * 4)?), + Arg::I32((n * g.n) as i32), + Arg::I32((n * g.k) as i32), + Arg::Address(self.physical.mapped_address(6, begin * g.n * 4, n * g.n * 4)?), + Arg::Address(self.physical.mapped_address(7, begin * g.k * 4, n * g.k * 4)?), + Arg::Address(self.physical.mapped_address(8, begin * g.k * 4, n * g.k * 4)?), + Arg::Address(self.physical.mapped_address(9, 0, 4)?), + ], + )?], + ) + } +} diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs new file mode 100644 index 00000000..f83656a0 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_2_2.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyGdnJournal (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { + /// Exact batch convolution, BF16 MMVF alpha/beta, and recurrence. Canonical + /// state/history are READ ONLY; retained qkv/h/gate/beta banks span all36 layers. + pub fn capture_layer_stage( + &self, + stage: OriginalVerifyGdnStage, + capture: &mut OriginalCapture<'_, 'ctx>, + layer: usize, + begin: usize, + end: usize, + ) -> Result<()> { + self.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + if layer >= 36 || begin >= end || end > g.max_t { + return Err(Error::InvalidQwenShape); + } + let n = end - begin; + let w = &self.weights[layer]; + let c = self.physical.context; + let qkv = self.physical.span("qkv_L", layer * g.max_t * g.channels * 4, g.max_t * g.channels * 4)?; + let h = self.physical.span("h_L", layer * g.max_t * g.channels * 4, g.max_t * g.channels * 4)?; + let gate = self.physical.span("gate_L", layer * g.max_t * g.value_heads * 4, g.max_t * g.value_heads * 4)?; + let beta = self.physical.span("beta_L", layer * g.max_t * g.value_heads * 4, g.max_t * g.value_heads * 4)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + commands.push(command( + "verify_gdn_conv_l2_multi_kernel", + [80, n as u32, 1], + [128, 1, 1], + vec![ + Arg::Address(self.canonical.span(layer, true)?), + Arg::Address(qkv), + Arg::Address(admit(c, w.conv, 10240 * 4 * 4)?), + Arg::Address(h), + Arg::I32(10240), + Arg::I32(32), + Arg::F32(EPS), + Arg::I32(begin as i32), + ], + )?); + commands.push(command( + "verify_gdn_ab_multi_kernel", + [12, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?), + Arg::Address(admit(c, w.alpha, 48 * 2560 * 2)?), + Arg::Address(admit(c, w.beta, 48 * 2560 * 2)?), + Arg::Address(admit(c, w.dt, 48 * 4)?), + Arg::Address(admit(c, w.a, 48 * 4)?), + Arg::Address(gate + (begin * 48 * 4) as u64), + Arg::Address(beta + (begin * 48 * 4) as u64), + Arg::I32(2560), + Arg::I32(48), + Arg::I32(n as i32), + ], + )?); + commands.push(command( + "verify_gdn_step_norm_multi_kernel", + [48, 1, 1], + [128, 4, 1], + vec![ + Arg::Address(self.canonical.span(layer, false)?), + Arg::Address(h), + Arg::I32(10240), + Arg::Address(gate), + Arg::Address(beta), + Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?), + Arg::Address(admit(c, w.norm, 128 * 4)?), + Arg::F32(EPS), + Arg::Address(self.physical.span("y", 0, g.max_t * 6144 * 4)?), + Arg::I32(16), + Arg::I32(48), + Arg::I32(end as i32), + Arg::Address(0), + Arg::I32(begin as i32), + ], + )?); + if chain::flags().ab && matches!(stage, OriginalVerifyGdnStage::AlphaBeta) { + let x = self.physical.span("mixed", begin * g.n * 4, n * g.n * 4)?; + return self.submit_launches( + capture, + vec![kernels::Launch::new( + &chain::CHAIN, + chain::E_GDN_AB, + [96, 1, 1], + [32, 1, 1], + 0, + vec![ + kernels::A::P(x), + kernels::A::P(admit(c, w.alpha, 48 * 2560 * 2)?), + kernels::A::P(admit(c, w.beta, 48 * 2560 * 2)?), + kernels::A::P(admit(c, w.dt, 48 * 4)?), + kernels::A::P(admit(c, w.a, 48 * 4)?), + kernels::A::P(gate + (begin * 48 * 4) as u64), + kernels::A::P(beta + (begin * 48 * 4) as u64), + kernels::A::I32(2560), + kernels::A::I32(48), + kernels::A::I32(n as i32), + ], + )?], + ); + } + let mut selected = Vec::new(); + selected.try_reserve_exact(1).map_err(|_| Error::HostAllocation)?; + selected.push(commands.swap_remove(stage as usize)); + self.submit(capture, selected) + } + /// First node of the literal commit graph: accepted count/row/positions. + pub fn capture_commit_begin(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { + self.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + self.submit( + capture, + vec![command( + "verify_copy_i32_from_mapped_kernel", + [1, 1, 1], + [128, 1, 1], + vec![ + Arg::Address(self.physical.span("commit", 0, (g.max_t + 2) * 4)?), + Arg::Address(self.physical.mapped_address(3, 0, (g.max_t + 2) * 4)?), + Arg::I32((g.max_t + 2) as i32), + ], + )?], + ) + } + /// Exactly one actual GDN layer at its original place among all48 layers. + /// QSA layers are committed by the retained QSA journal between these calls. + pub fn capture_commit_layer(&self, capture: &mut OriginalCapture<'_, 'ctx>, i: usize) -> Result<()> { + self.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + if i >= 36 { + return Err(Error::InvalidQwenShape); + } + let commit = self.physical.span("commit", 0, (g.max_t + 2) * 4)?; + let qkv = self.physical.span("qkv_L", i * g.max_t * 10240 * 4, g.max_t * 10240 * 4)?; + let h = self.physical.span("h_L", i * g.max_t * 10240 * 4, g.max_t * 10240 * 4)?; + let gate = self.physical.span("gate_L", i * g.max_t * 48 * 4, g.max_t * 48 * 4)?; + let beta = self.physical.span("beta_L", i * g.max_t * 48 * 4, g.max_t * 48 * 4)?; + self.submit( + capture, + vec![ + command( + "verify_gdn_conv_commit_kernel", + [40, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(self.canonical.span(i, true)?), + Arg::Address(qkv), + Arg::I32(10240), + Arg::Address(commit), + ], + )?, + command( + "verify_gdn_step_norm_multi_kernel", + [48, 1, 1], + [128, 4, 1], + vec![ + Arg::Address(self.canonical.span(i, false)?), + Arg::Address(h), + Arg::I32(10240), + Arg::Address(gate), + Arg::Address(beta), + Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?), + Arg::Address(admit(self.physical.context, self.weights[i].norm, 128 * 4)?), + Arg::F32(EPS), + Arg::Address(self.physical.span("y_dummy", 0, g.max_t * 6144 * 4)?), + Arg::I32(16), + Arg::I32(48), + Arg::I32(g.max_t as i32), + Arg::Address(commit), + Arg::I32(0), + ], + )?, + ], + ) + } + /// Load the sealed `draft_commit.ptx` module before the commit graph is captured (module loading is not capturable). + pub(crate) fn load_draft_commit_asset(&self) -> Result<()> { + self.physical.ensure_window_assets(&[&draft::DRAFT_COMMIT, &draft::DRAFT_COMMIT_QSA]) + } + /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the 36 GDN layers' conv history commit and recurrence replay of `capture_commit_layer` in ONE launch + /// (`draft_commit_gdn_layers`: grid (48 heads + 20 conv blocks, 36 layers)). The per-layer operands are affine in the layer (checked against the per-layer spans below). + pub(crate) fn capture_commit_gdn_fused(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { + self.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + let t = g.max_t; + let commit = self.physical.span("commit", 0, (t + 2) * 4)?; + let state0 = self.canonical.span(0, false)?; + let hist0 = self.canonical.span(0, true)?; + let rows = t * 10240 * 4; + let small = t * 48 * 4; + let qkv = self.physical.span("qkv_L", 0, rows)?; + let h = self.physical.span("h_L", 0, rows)?; + let gate = self.physical.span("gate_L", 0, small)?; + let beta = self.physical.span("beta_L", 0, small)?; + // affine layout: layer i of every operand is base + i * stride (the per-layer spans `capture_commit_layer` binds) + for i in [1usize, 17, 35] { + if self.canonical.span(i, false)? != state0 + (i * LAYER_BYTES) as u64 + || self.canonical.span(i, true)? != hist0 + (i * LAYER_BYTES) as u64 + || self.physical.span("qkv_L", i * rows, rows)? != qkv + (i * rows) as u64 + || self.physical.span("h_L", i * rows, rows)? != h + (i * rows) as u64 + || self.physical.span("gate_L", i * small, small)? != gate + (i * small) as u64 + || self.physical.span("beta_L", i * small, small)? != beta + (i * small) as u64 + { + return Err(Error::InvalidQwenShape); + } + } + if hist0 < state0 || (hist0 - state0) as usize != STATE_WORDS * 4 { + return Err(Error::InvalidQwenShape); + } + self.submit_launches( + capture, + vec![kernels::Launch::new( + &draft::DRAFT_COMMIT, + draft::E_GDN, + [48 + 20, 36, 1], + [128, 4, 1], + 0, + vec![kernels::A::Words(vec![ + state0, + LAYER_BYTES as u64, + (STATE_WORDS * 4) as u64, + qkv, + h, + gate, + beta, + commit, + t as u64, + ])], + )?], + ) + } +} diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs new file mode 100644 index 00000000..76404d0b --- /dev/null +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifygdnjournal_3.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyGdnJournal (3), impl OriginalVerifyResources, impl resources_Sealed_for, impl OriginalGraphResources_for_OriginalVerifyResources, impl OriginalVerifyGraphResources_for_OriginalVerifyResources, impl crate_OriginalNativeHeadGraphResources_for .... + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> { + /// Retain the actual PLE history after each chronological row, before its + /// subsequent overwrite. Only the actual producer's capture calls this. + /// Bring-up diagnostic (LELEKA_TRACE_LADDER): copy rows `[begin,end)` of the residual R into frame `frame` of the + /// `dbg_ladder` region (frame = 2*layer + half). A no-op when the region was not laid out. + pub fn capture_ladder( + &self, + capture: &mut OriginalCapture<'_, 'ctx>, + frame: usize, + begin: usize, + end: usize, + ) -> Result<()> { + if self.physical.layout.span("dbg_ladder").is_err() { + return Ok(()); + } + let g = self.physical.layout.geometry; + let row = g.hc * g.n; + if frame >= 96 || end > g.max_t || begin >= end { + return Err(Error::InvalidQwenShape); + } + let mut commands = Vec::new(); + for t in begin..end { + commands.push(command( + "verify_copy_from_mapped_kernel", + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(self.physical.span("dbg_ladder", (frame * g.max_t + t) * row * 4, row * 4)?), + Arg::Address(self.physical.span("R", t * row * 4, row * 4)?), + Arg::I64((row / 4) as i64), + ], + )?); + } + self.submit(capture, commands) + } + pub fn capture_ple_snapshot(&self, capture: &mut OriginalCapture<'_, 'ctx>, row: usize) -> Result<()> { + let g = self.physical.layout.geometry; + if row >= g.max_t { + return Err(Error::InvalidQwenShape); + } + let history = self.ple.ok_or(Error::InvalidQwenShape)?; + let words = 9 * 10240; + let src = admit(self.physical.context, history, words * 4)?; + self.submit( + capture, + vec![command( + "verify_copy_from_mapped_kernel", + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(self.physical.span("hist_snap", row * words * 4, words * 4)?), + Arg::Address(src), + Arg::I64((words / 4) as i64), + ], + )?], + ) + } + /// Post-drain integer exponent scan over the ACTUAL whole head output. This + /// is an integration finite gate, never an id-as-finite certificate. The four + /// byte status reuses retired hit_count scratch; no active kernel can alias it. + pub(crate) fn validate_completed_logits( + &self, + stream: &mut crate::OriginalGpuStream<'ctx>, + logits: &DeviceBuffer<'ctx>, + rows: usize, + ) -> Result<()> { + let _span_validate = crate::host_profile::span("head.validate_logits"); + self.validate_context(self.physical.context)?; + stream.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + if !(1..=g.max_t).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + let words = rows.checked_mul(g.vocabulary).ok_or(Error::InvalidSize)?; + let src = admit(self.physical.context, logits, words.checked_mul(4).ok_or(Error::InvalidSize)?)?; + let arena = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + if handle(logits)?.overlaps(logits.len(), handle(arena)?, arena.len()) { + return Err(Error::OutputAliasesInput); + } + let status = self.span("hit_count", 0, 4)?; + let mut commands = vec![ + command("verify_clear_status", [1, 1, 1], [32, 1, 1], vec![Arg::Address(status.qwen_address())])?, + command( + "verify_scan_logits", + [words.div_ceil(256).min(65535) as u32, 1, 1], + [256, 1, 1], + vec![Arg::Address(src), Arg::U64(words as u64), Arg::Address(status.qwen_address())], + )?, + ]; + let module = self.physical.module.as_ref().ok_or(Error::ContextPoisoned)?; + for c in &commands { + module.admit(c)?; + } + let span_vs = crate::host_profile::span("head.validate_stream"); + let launched = stream.with_enqueue(|h| { + for c in &mut commands { + module.launch(h, c)?; + } + Ok(()) + }); + let sync = stream.synchronize(); + drop(span_vs); + if sync.is_err() { + self.physical.failed.set(true); + poison(self.physical.context); + std::mem::forget(commands); + return combine(launched, sync); + } + combine(launched, sync)?; + let span_vc = crate::host_profile::span("head.validate_ctx_copy"); + let mut bytes = zero(4)?; + let guard = self.physical.context.enter()?; + let copy = self.physical.context.driver.api.copy_to(status, &mut bytes); + let sync = self.physical.context.driver.api.synchronize(); + let pop = guard.finish(); + drop(span_vc); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + self.physical.failed.set(true); + poison(self.physical.context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop); + } + combine(combine(copy, sync), pop)?; + if u32::from_le_bytes(bytes[..4].try_into().map_err(|_| Error::InvalidSize)?) != 0 { + return Err(Error::NonFiniteMmqOutput("Original Verifier full logits")); + } + Ok(()) + } + /// Actual original PLE history image; selected accepted row, never final-image + /// metadata relabel. Borrowed destination must survive the graph aggregate. + pub fn capture_ple_commit(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> { + let history = self.ple.ok_or(Error::InvalidQwenShape)?; + let bytes = 9 * 10240 * 4; + let dst = admit(self.physical.context, history, bytes)?; + let arena = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + if handle(history)?.overlaps(bytes, handle(arena)?, arena.len()) { + return Err(Error::OutputAliasesInput); + } + self.submit( + capture, + vec![command( + "verify_copy_indexed_kernel", + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::Address(dst), + Arg::Address(self.physical.span("hist_snap", 0, self.physical.layout.geometry.max_t * bytes)?), + Arg::I64((9 * 10240) as i64), + Arg::Address(self.physical.span("commit", 4, 4)?), + Arg::I64((9 * 10240) as i64), + ], + )?], + ) + } + /// Closed driver sibling producers resolve physical slices through the actual + /// bank owner, not by constructing false whole DeviceBuffers around aliases. + pub(crate) fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + let s = self.physical.layout.span(name)?; + if bytes == 0 || offset.checked_add(bytes).is_none_or(|e| e > s.bytes) { + return Err(Error::InvalidSize); + } + let b = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + handle(b)?.checked_subspan(b.len(), s.offset + offset, bytes) + } +} +impl<'a, 'ctx> OriginalVerifyResources<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + journal: OriginalVerifyGdnJournal<'a, 'ctx>, + qsa: Rc>, + head: crate::OriginalNativeHeadRows<'ctx>, + ) -> Result { + journal.validate_context(context)?; + qsa.validate_context(context)?; + head.validate_context(context)?; + Ok(Self { context, journal, qsa, head }) + } +} +impl resources::Sealed for OriginalVerifyResources<'_, '_> {} +impl OriginalGraphResources for OriginalVerifyResources<'_, '_> { + fn validate_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(self.context, context) { + return Err(Error::ContextMismatch); + } + self.journal.validate_context(context)?; + self.qsa.validate_context(context)?; + self.head.validate_context(context) + } +} +impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx> { + fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx> { + self.qsa.as_ref() + } + fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> { + &self.journal + } +} +impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx> { + fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> { + Ok(&self.head) + } + fn native_head_rows_mut(&mut self) -> Result<&mut crate::OriginalNativeHeadRows<'ctx>> { + Ok(&mut self.head) + } +} + +impl OriginalVerifyGdnJournal<'_, '_> { + pub(crate) fn has_ple(&self) -> bool { + self.ple.is_some() + } + pub(crate) fn ple_history_address(&self) -> Result> { + self.ple.map(|b| Ok(handle(b)?.qwen_address())).transpose() + } + pub(crate) fn canonical_identity(&self) -> usize { + Rc::as_ptr(&self.canonical) as usize + } + pub(crate) fn geometry(&self) -> OriginalVerifyGeometry { + self.physical.layout.geometry + } + pub fn validate_bank(&self, bank: &OriginalVerifyBank<'_>) -> Result<()> { + if !Rc::ptr_eq(&self.physical, &bank.physical) { + return Err(Error::InvalidQwenShape); + } + self.validate_context(self.physical.context) + } +} diff --git a/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs new file mode 100644 index 00000000..ce5efa64 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/impl_originalverifygdnjournal/impl_originalverifywindow.rs @@ -0,0 +1,51 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyWindow, impl OriginalVerifyWindow, fn verify_assets_sealed. + +#[allow(unused_imports)] +use super::*; + +impl OriginalVerifyWindow<'_> { + /// Structural geometry admission, not a numerical/session authority. + pub(crate) fn validate_mtp_geometry(&self) -> Result<()> { + self.validate_context(self.physical.context)?; + let g = self.physical.layout.geometry; + if g.hc != 4 || g.n != 2560 || !(1..=8).contains(&self.rows) { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + /// Only cached MTP graph address comparison may use the retained old physical + /// owner after a newer completed generation supersedes it. This method mints + /// no current-window readiness and the new window must validate independently. + pub(crate) fn retained_residual_address_for_mtp(&self) -> Result { + self.physical.validate(self.physical.context)?; + let s = self.physical.layout.span("R")?; + let b = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(handle(b)?.checked_subspan(b.len(), s.offset, self.rows * 40960)?.qwen_address()) + } +} + +impl OriginalVerifyWindow<'_> { + /// Current actual R scratch extent. Extra rows authorize only literal MTP + /// draft_first repetition; they are NOT completed verifier rows or sampled IDs. + pub(crate) fn actual_mtp_residual_bank(&self, rows: usize) -> Result { + self.validate_mtp_geometry()?; + if rows == 0 || rows > self.physical.layout.geometry.max_t || rows > 8 { + return Err(Error::InvalidQwenShape); + } + let s = self.physical.layout.span("R")?; + let b = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + if rows * 40960 > s.bytes { + return Err(Error::InvalidSize); + } + handle(b)?.checked_subspan(b.len(), s.offset, rows * 40960) + } +} + +/// Sealed-state of the two compiled verifier assets: the embedded PTX must match its pinned digest +/// (the same check `OriginalVerifyBank::new` performs). Probe only. +pub(crate) fn verify_assets_sealed() -> [(&'static str, bool); 2] { + [ + ("original_verify", sealed_asset(ASSET, ASSET_SHA).is_ok()), + ("original_verify_qsa", sealed_asset(QSA_ASSET, QSA_ASSET_SHA).is_ok()), + ] +} diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs index adb7c368..4bb0887d 100644 --- a/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn.rs @@ -3,192 +3,29 @@ #[allow(unused_imports)] use super::*; -/// `LELEKA_WINDOW_MODULE_CACHE=off`: every verifier bank loads its window modules again (A/B control). -pub(super) fn share_window_modules()->bool{static ON:std::sync::OnceLock=std::sync::OnceLock::new();*ON.get_or_init(||!std::env::var("LELEKA_WINDOW_MODULE_CACHE").is_ok_and(|v|v=="off"||v=="0"))} -pub(super) fn admission(c:&Context<'_>,n:usize)->Result<()>{let need=n.checked_add(RESERVE).ok_or(Error::InvalidSize)?;if c.is_poisoned(){return Err(Error::ContextPoisoned)}if c.allocated_bytes().checked_add(need).is_none_or(|x|x>c.budget_bytes())||c.memory_info()?.0)->Result{b.handle.ok_or(Error::ContextPoisoned)} -pub(super) fn admit(c:&Context<'_>,b:&DeviceBuffer<'_>,bytes:usize)->Result{if !std::ptr::eq(c,b.context){return Err(Error::ContextMismatch)}if b.len()!=bytes{return Err(Error::ShapeMismatch{expected:bytes,actual:b.len()})}handle(b)?.validate_projection_extent(bytes,4)?;Ok(handle(b)?.qwen_address())} -pub(super) fn poison(c:&Context<'_>){c.poison();c.retain_driver()} -pub(super) fn transport(e:&Error)->bool{match e{Error::Driver{..}|Error::ContextPoisoned|Error::UnexpectedContext=>true,Error::Multiple{primary,secondary}=>transport(primary)||transport(secondary),_=>false}} -pub(super) fn zero(n:usize)->Result>{let mut b=Vec::new();b.try_reserve_exact(n).map_err(|_|Error::HostAllocation)?;b.resize(n,0);Ok(b)} -pub(super) fn check_commands(c:&Vec)->Result<()>{let mut bytes=c.capacity().checked_mul(std::mem::size_of::()).ok_or(Error::InvalidSize)?;for x in c{bytes=bytes.checked_add(x.abi_bytes()?).ok_or(Error::InvalidSize)?;}if bytes>16<<20{return Err(Error::HostAllocation)}Ok(())} -pub(super) fn command(name:&'static str,grid:[u32;3],block:[u32;3],args:Vec)->Result{Command::new(name,grid,block,0,args)} -pub(super) fn sealed_asset(asset:&'static[u8],digest:[u8;32])->Result<&'static[u8]>{ - if asset.len()<2||asset.last()!=Some(&0)||asset[..asset.len()-1].contains(&0)||crate::qwen_ffi::sha256(&asset[..asset.len()-1])!=digest{return Err(Error::UnsupportedQwenOperation)} - Ok(asset) -} -/// Sealed `verify_gather_rows_*` kernels for the Original draft-head gather of -/// `MtpDrafter::bind` (`gather_rows`, mtp.cpp:406). The caller must hold the -/// owning context current and close the module while it still is. -pub(crate) fn gather_rows_module()->Result{Module::load(sealed_asset(ASSET,ASSET_SHA)?,ENTRIES)} -impl<'ctx> Context<'ctx>{ - pub fn original_verify_canonical_gdn(&'ctx self,states:[&[f32];36],histories:[&[f32];36])->Result>{ - let _span_canonical=crate::host_profile::span("drv.canonical_gdn"); - for i in 0..36{if states[i].len()!=STATE_WORDS||histories[i].len()!=HISTORY_WORDS{return Err(Error::InvalidQwenShape)}} - admission(self,CANONICAL_BYTES)?;let mut owner=Canonical{context:self,buffer:Some(self.allocate(CANONICAL_BYTES)?),failed:Cell::new(false)}; - // One pass per layer converts to little-endian bytes and checks every word finite (two plain slice loops, not a chained - // iterator: they compile to wide copies); a non-finite word refuses the intake before the layer is uploaded. - let operation=(||{let mut bytes=zero(LAYER_BYTES)?;for i in 0..36{let(head,tail)=bytes.split_at_mut(STATE_WORDS*4);let mut finite=true; - for(x,b)in states[i].iter().zip(head.chunks_exact_mut(4)){finite&=x.is_finite();b.copy_from_slice(&x.to_le_bytes())} - for(x,b)in histories[i].iter().zip(tail.chunks_exact_mut(4)){finite&=x.is_finite();b.copy_from_slice(&x.to_le_bytes())} - if !finite{return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"))} - owner.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i*LAYER_BYTES,&bytes)?;}Ok(())})(); - if let Err(primary)=operation{return combine(Err(primary),owner.close_inner())}Ok(OriginalVerifyCanonicalGdn{inner:Rc::new(owner)}) - } - pub fn original_verify_bank(&'ctx self,geometry:OriginalVerifyGeometry)->Result>{OriginalVerifyBank::new(self,geometry)} -} -impl Canonical<'_>{ - pub fn allocated_bytes(&self)->usize{self.buffer.as_ref().map_or(0,DeviceBuffer::len)} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.failed.get()||self.context.is_poisoned(){return Err(Error::ContextPoisoned)}admit(c,self.buffer.as_ref().ok_or(Error::ContextPoisoned)?,CANONICAL_BYTES).map(|_|())} - pub(super) fn span(&self,layer:usize,history:bool)->Result{self.validate_context(self.context)?;if layer>=36{return Err(Error::InvalidQwenShape)}let b=self.buffer.as_ref().ok_or(Error::ContextPoisoned)?;let offset=layer*LAYER_BYTES+if history{STATE_WORDS*4}else{0};let bytes=if history{HISTORY_WORDS*4}else{STATE_WORDS*4};Ok(handle(b)?.checked_subspan(b.len(),offset,bytes)?.qwen_address())} - pub fn with_layer(&self,layer:usize,read:impl FnOnce(&[f32],&[f32])->Result)->Result{ - self.validate_context(self.context)?;if layer>=36{return Err(Error::InvalidQwenShape)}let mut bytes=zero(LAYER_BYTES)?;let b=self.buffer.as_ref().ok_or(Error::ContextPoisoned)?;let h=handle(b)?.checked_subspan(b.len(),layer*LAYER_BYTES,LAYER_BYTES)?; - let guard=self.context.enter()?;let copy=self.context.driver.api.copy_to(h,&mut bytes);let sync=self.context.driver.api.synchronize();let pop=guard.finish();if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(self.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!())}combine(combine(copy,sync),pop)?; - let mut values=Vec::new();values.try_reserve_exact(STATE_WORDS+HISTORY_WORDS).map_err(|_|Error::HostAllocation)?;values.extend(bytes.as_chunks::<4>().0.iter().map(|b|f32::from_le_bytes(*b)));if values.iter().any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("Original committed GDN"))}read(&values[..STATE_WORDS],&values[STATE_WORDS..]) - } - pub(super) fn close_inner(&mut self)->Result<()>{self.failed.set(true);let Some(b)=self.buffer.take()else{return Ok(())};if self.context.is_poisoned(){std::mem::forget(b);return Err(Error::ContextPoisoned)}b.release()} -} -impl Drop for Canonical<'_>{fn drop(&mut self){let _=self.close_inner();}} -impl OriginalVerifyCanonicalGdn<'_>{ - pub fn allocated_bytes(&self)->usize{self.inner.allocated_bytes()} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{self.inner.validate_context(c)} - pub fn with_layer(&self,layer:usize,read:impl FnOnce(&[f32],&[f32])->Result)->Result{if Rc::strong_count(&self.inner)!=1{return Err(Error::InvalidQwenShape)}self.inner.with_layer(layer,read)} - pub fn close(self)->Result<()>{match Rc::try_unwrap(self.inner){Ok(mut owner)=>owner.close_inner(),Err(_)=>Err(Error::InvalidQwenShape)}} -} -impl Physical<'_>{ - pub(super) fn validate(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.failed.get()||c.is_poisoned()||self.module.is_none()||self.qsa_module.is_none(){return Err(Error::ContextPoisoned)}admit(c,self.arena.as_ref().ok_or(Error::ContextPoisoned)?,self.layout.bytes).map(|_|())} - pub(super) fn span(&self,name:&str,offset:usize,bytes:usize)->Result{self.validate(self.context)?;let s=self.layout.span(name)?;let b=self.arena.as_ref().ok_or(Error::ContextPoisoned)?;if bytes==0||offset.checked_add(bytes).is_none_or(|n|n>s.bytes){return Err(Error::InvalidSize)}Ok(handle(b)?.checked_subspan(b.len(),s.offset+offset,bytes)?.qwen_address())} - /// Load (once) the sealed PTX modules a window producer launches from. Runs before any capture - /// (module loading is not capturable). Specs naming the same PTX file share one module (entries - /// unioned). Every sealed module is loaded; the first unsealed one fails closed AFTER that, by name. - pub(super) fn ensure_window_assets(&self,specs:&[&'static kernels::AssetSpec])->Result<()>{ - self.validate(self.context)?; - let started=std::time::Instant::now(); - let mut groups:Vec<(&'static str,&'static kernels::AssetSpec,Vec<&'static str>)>=Vec::new(); - for s in specs{match groups.iter_mut().find(|g|g.0==s.key()){Some(g)=>{for e in s.entries{if !g.2.contains(e){g.2.push(e)}}},None=>groups.push((s.key(),s,s.entries.to_vec()))}} - let mut ready=Vec::new();let mut unsealed:Result<()>=Ok(()); - {let mut loaded=self.window.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?; - let cache=self.context.window_modules.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - for(key,spec,entries)in groups{ - if let Some((_,_,have))=loaded.iter().find(|(n,_,_)|*n==key){if entries.iter().all(|e|have.contains(e)){continue}return Err(Error::InvalidDriverValue("Original verifier window module is already loaded without an entry a later graph needs"))} - // A module an earlier bank of this context loaded (sealed and admitted then) is shared, not loaded again: - // the same sealed image, the same entries, unloaded with the context. - if let Some((_,m,have))=cache.iter().find(|(n,_,have)|share_window_modules()&&*n==key&&entries.iter().all(|e|have.contains(e))){loaded.try_reserve(1).map_err(|_|Error::HostAllocation)?;loaded.push((key,Rc::clone(m),have.clone()));continue} - match spec.sealed(){Ok(ptx)=>ready.push((key,ptx,entries)),Err(error)=>{if unsealed.is_ok(){unsealed=Err(error)}}} - }} - if ready.is_empty(){crate::original_gpu_schedule::capture_timing::add(2,started.elapsed().as_secs_f64()*1e3);return unsealed} - let guard=self.context.enter()?;let mut result=Ok(()); - for(key,ptx,entries)in ready{match Module::load(ptx,&entries){Ok(m)=>{let m=Rc::new(m); - match self.context.window_modules.try_borrow_mut(){Ok(mut c)=>{c.retain(|(n,_,_)|*n!=key);if c.try_reserve(1).is_ok(){c.push((key,Rc::clone(&m),entries.clone()))}},Err(_)=>{result=combine(result,Err(Error::InvalidQwenShape));break}} - match self.window.try_borrow_mut(){Ok(mut w)=>w.push((key,m,entries)),Err(_)=>{result=combine(result,Err(Error::InvalidQwenShape));break}}},Err(error)=>{result=combine(result,Err(error));break}}} - let pop=guard.finish();if result.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)} - crate::original_gpu_schedule::capture_timing::add(2,started.elapsed().as_secs_f64()*1e3); - combine(combine(result,pop),unsealed) - } - /// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` of loaded window entries, once, before any capture - /// (what Original does for the fused GR down kernels). - pub(super) fn configure_window_shared(&self,attrs:&[(&'static kernels::AssetSpec,&'static str,usize)])->Result<()>{ - self.validate(self.context)?;if attrs.is_empty(){return Ok(())} - let guard=self.context.enter()?;let mut result=Ok(()); - {let loaded=self.window.try_borrow().map_err(|_|Error::InvalidQwenShape)?;for(spec,entry,bytes)in attrs{match loaded.iter().find(|(n,_,_)|*n==spec.key()){Some((_,m,_))=>{result=combine(result,m.set_max_dynamic_shared(entry,*bytes))},None=>{result=combine(result,Err(Error::InvalidDriverValue(spec.unsealed)))}}}} - let pop=guard.finish();if result.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)}combine(result,pop) - } - /// `cuDeviceGetAttribute` of the verifier context's device (compute capability and shared-memory limits that Original - /// reads when it picks kernel variants). - pub(super) fn window_device_attribute(&self,attribute:i32)->Result{ - self.validate(self.context)?;let guard=self.context.enter()?; - let value=match self.module.as_ref(){Some(m)=>m.device_attribute(attribute),None=>Err(Error::ContextPoisoned)}; - let pop=guard.finish();if value.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)}pop?;value - } - pub(super) fn mapped_address(&self,i:usize,offset:usize,bytes:usize)->Result{self.mapped.get(i).ok_or(Error::InvalidQwenShape)?.try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.address(offset,bytes)} - pub(super) fn close(&mut self)->Result<()>{if self.arena.is_none()&&self.prof.is_none()&&self.module.is_none()&&self.qsa_module.is_none()&&self.window.get_mut().is_empty(){return Ok(())}self.failed.set(true);if self.context.is_poisoned(){if let Some(b)=self.arena.take(){std::mem::forget(b)}if let Some(b)=self.prof.take(){std::mem::forget(b)}if let Some(m)=self.module.take(){std::mem::forget(m)}if let Some(m)=self.qsa_module.take(){std::mem::forget(m)}for(_,m,_)in self.window.get_mut().drain(..){std::mem::forget(m)}for m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){std::mem::forget(m)}return Err(Error::ContextPoisoned)}let sync=self.context.synchronize();if sync.is_err(){poison(self.context);return combine(sync,self.close())}let mut result=combine(self.arena.take().map_or(Ok(()),DeviceBuffer::release),self.prof.take().map_or(Ok(()),DeviceBuffer::release));if self.context.is_poisoned(){return combine(result,self.close())}let guard=match self.context.enter(){Ok(g)=>g,Err(e)=>return combine(combine(result,Err(e)),self.close())};for mut m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){result=combine(result,m.close());if result.is_err(){std::mem::forget(m)}}let mut unload=combine(self.module.take().map_or(Ok(()),Module::close),self.qsa_module.take().map_or(Ok(()),Module::close));for(_,m,_)in self.window.get_mut().drain(..){if let Ok(m)=Rc::try_unwrap(m){unload=combine(unload,m.close());}}let pop=guard.finish();if unload.is_err()||pop.is_err(){poison(self.context)}combine(combine(result,unload),pop)} -} -impl Drop for Physical<'_>{fn drop(&mut self){let _=self.close();}} -impl<'ctx> OriginalVerifyBank<'ctx>{ - pub(super) fn new(context:&'ctx Context<'ctx>,geometry:OriginalVerifyGeometry)->Result{ - let layout=OriginalVerifyLayout::new(geometry)?;let asset=sealed_asset(ASSET,ASSET_SHA)?;let qsa_asset=sealed_asset(QSA_ASSET,QSA_ASSET_SHA)?;admission(context,layout.bytes)?; - let mut owner=Physical{context,layout,arena:None,prof:None,mapped:std::array::from_fn(|_|RefCell::new(None)),module:None,qsa_module:None,window:RefCell::new(Vec::new()),generation:Cell::new(0),failed:Cell::new(false)}; - let operation=(||{ - let guard=context.enter()?; - let loaded=(||{ - owner.module=Some(Module::load(asset,ENTRIES)?);owner.qsa_module=Some(Module::load(qsa_asset,QSA_ENTRIES)?); - // Original mapped staging is retained and memset before the arena carve. - for(i,n)in owner.layout.mapped_bytes.into_iter().enumerate(){*owner.mapped[i].get_mut()=Some(MappedAllocation::new(n)?);owner.mapped[i].get_mut().as_mut().ok_or(Error::ContextPoisoned)?.initialize_zero()?;} - admission(context,owner.layout.bytes)?;owner.arena=Some(context.allocate(owner.layout.bytes)?); - let arena=owner.arena.as_ref().ok_or(Error::ContextPoisoned)?;context.driver.api.zero(handle(arena)?.qwen_address(),arena.len())?; - // STRATA_VERIFY_PROFILE: the device stamp words (Verifier::init `prof_`); a failed allocation just turns the profile off. - if std::env::var_os("STRATA_VERIFY_PROFILE").is_some(){let bytes=profile::profile_stamp_words(48)*8;if let Ok(b)=context.allocate(bytes){let zeroed=handle(&b).and_then(|h|context.driver.api.zero(h.qwen_address(),bytes));if zeroed.is_ok(){owner.prof=Some(b)}else{let _=b.release();}}} - Ok(()) - })();let sync=context.driver.api.synchronize();let pop=guard.finish();if loaded.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(context)}combine(combine(loaded,sync),pop) - })();if let Err(primary)=operation{return combine(Err(primary),owner.close())}Ok(Self{physical:Rc::new(owner),last_t:0,last_position:0,last_tokens:[0;8],generation:0,last_keep:0,released:false,pcie_sources:Vec::new(),pcie_mode:0,pcie_roles:None}) - } - pub(crate) fn staged_window(&self)->Result<(u64,usize,usize)>{self.validate_context(self.physical.context)?;if self.last_t==0||self.released{return Err(Error::InvalidQwenShape)}Ok((self.generation,self.last_position,self.last_t))} - pub(crate) fn staged_keep(&self)->Result{self.staged_window()?;if !(1..=self.last_t).contains(&self.last_keep){return Err(Error::InvalidQwenShape)}Ok(self.last_keep)} - pub(crate) fn completed_row(&self,row:usize)->Result>{self.staged_window()?;if row>=self.last_t{return Err(Error::InvalidQwenShape)}let bytes=self.geometry().hc*self.geometry().n*4;self.physical.span("R",row*bytes,bytes)?;Ok(OriginalVerifyRow{physical:self.physical.clone(),generation:self.generation,row,position:self.last_position+row})} - pub fn allocated_bytes(&self)->usize{self.physical.layout.bytes} - pub fn mapped_bytes(&self)->usize{self.physical.layout.mapped_bytes.iter().sum()} - pub fn geometry(&self)->OriginalVerifyGeometry{self.physical.layout.geometry} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{self.physical.validate(c)} - /// Called only after the previous actual window/commit graph has drained. The - /// mutable borrow is held by the actor, not copied into an unrelated certificate. - pub(crate) fn stage(&mut self,tokens:&[i32],position:usize)->Result{ - self.validate_context(self.physical.context)?;let g=self.geometry();let t=tokens.len();if self.released||!(1..=g.max_t).contains(&t)||position.checked_add(t).is_none_or(|e|e>g.max_cells)||tokens.iter().any(|x|*x<0||*x as usize>=g.vocabulary){return Err(Error::InvalidQwenShape)} - let generation=self.generation.checked_add(1).ok_or(Error::InvalidSize)?; - // Invalidate every escaped completed row/window BEFORE the first mapped write. - // A failed partial staging cannot retain old generation authority. - self.generation=generation;self.physical.generation.set(generation);self.last_t=0;self.last_keep=0; - let mapped=&self.physical.mapped; - for(i,&token)in tokens.iter().enumerate(){let p=position+i;mapped[0].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.write(i*4,&token.to_le_bytes())?;for(j,v)in[p,p+1,(p+1)/4,(p+1).min(g.selection)].into_iter().enumerate(){mapped[1].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.write((i*4+j)*4,&(v as i32).to_le_bytes())?} - for(offset,heads)in[(0,g.heads),(g.max_t*g.heads,g.kv_heads),(g.max_t*(g.heads+g.kv_heads),g.index_heads)]{for h in 0..heads{mapped[2].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.write((offset+i*heads+h)*4,&(p as i32).to_le_bytes())?}} - } - for flag in 9..=12{mapped[flag].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,0)?}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); - self.last_t=t;self.last_position=position;self.last_tokens[..t].copy_from_slice(tokens);self.generation=generation;self.physical.generation.set(generation);self.last_keep=0;Ok(generation) - } - pub(crate) fn stage_ple(&mut self,values:&[f32])->Result<()>{self.validate_context(self.physical.context)?;if self.last_t==0||values.len()!=self.last_t*self.geometry().n||values.iter().any(|x|!x.is_finite()){return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[4].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=slot.as_mut().ok_or(Error::ContextPoisoned)?;let mut bytes=Vec::new();bytes.try_reserve_exact(values.len()*4).map_err(|_|Error::HostAllocation)?;for x in values{bytes.extend_from_slice(&x.to_le_bytes())}m.write(0,&bytes)?;Ok(())} - pub(crate) fn stage_commit(&mut self,keep:usize)->Result<()>{self.validate_context(self.physical.context)?;if !(1..=self.last_t).contains(&keep){return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[3].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let m=slot.as_mut().ok_or(Error::ContextPoisoned)?;m.write(0,&(keep as i32).to_le_bytes())?;m.write(4,&(keep as i32-1).to_le_bytes())?;for t in 0..self.geometry().max_t{let p=if tResult<()>{self.released=true;let m=&self.physical.mapped;for i in 10..=12{m[i].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,u32::MAX)?}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(())} - /// Host words the live release/diagnostic registry may read and raise. - pub(in crate::original_verify) fn host_words(&self)->Result{let w=|i:usize|->Result{self.physical.mapped.get(i).ok_or(Error::InvalidQwenShape)?.try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.host_address(0,4)};Ok(diag::HostWords{seq:w(9)?,served:w(10)?,plan:w(11)?,copies:w(12)?})} - pub fn profile_enabled(&self)->bool{self.physical.prof.is_some()} - /// The window's GPU stage stamps, read only after the genuine post-window fences. - pub(crate) fn read_profile(&self)->Result>{ - let b=self.physical.prof.as_ref().ok_or(Error::InvalidQwenShape)?;self.validate_context(self.physical.context)?; - let words=profile::profile_stamp_words(48);let mut bytes=zero(words*8)?;let guard=self.physical.context.enter()?; - let copy=self.physical.context.driver.api.copy_to(handle(b)?,&mut bytes);let sync=self.physical.context.driver.api.synchronize();let pop=guard.finish(); - if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){self.physical.failed.set(true);poison(self.physical.context);std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!())} - combine(combine(copy,sync),pop)?;Ok(bytes.as_chunks::<8>().0.iter().map(|b|u64::from_le_bytes(*b)).collect()) - } - pub fn doorbell_sequence(&self)->Result{self.physical.mapped[9].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)} - pub(crate) fn publish_empty_plan(&mut self,group:usize,ring:u32)->Result<()>{if group>1||ring==0||ring>96{return Err(Error::InvalidQwenShape)}let m=&self.physical.mapped;let mut slot=m[14].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let p=slot.as_mut().ok_or(Error::ContextPoisoned)?;let base=group*self.physical.layout.plan_i32*4;for o in [0,4,8,16,(self.physical.layout.plan_i32-self.geometry().max_t*self.geometry().k-2)*4]{p.write(base+o,&0i32.to_le_bytes())?}m[11].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,ring)?;m[12].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.raise_u32(0,ring)} - pub(crate) fn retain_pcie_source(&mut self,bank:Rc>)->Result<()>{if !self.pcie_sources.iter().any(|b|Rc::ptr_eq(b,&bank)){self.pcie_sources.try_reserve(1).map_err(|_|Error::HostAllocation)?;self.pcie_sources.push(bank)}Ok(())} - /// Only after the copy stream drained (the window's own fence). - pub(crate) fn release_pcie_sources(&mut self){self.pcie_sources.clear()} - pub fn close(self)->Result<()>{let Self{physical,pcie_sources,..}=self;let closed=match Rc::try_unwrap(physical){Ok(mut owner)=>owner.close(),Err(_)=>Err(Error::InvalidQwenShape)};drop(pcie_sources);closed} - /// Fixed real layer operands and borrowed source weights remain alive inside - /// the graph aggregate. No host-made readiness or arbitrary handles enter. - pub fn gdn_journal<'a>(&self,canonical:&mut OriginalVerifyCanonicalGdn<'ctx>,weights:[OriginalVerifyGdnWeights<'a,'ctx>;36],ple:Option<&'a DeviceBuffer<'ctx>>)->Result>{ - self.validate_context(self.physical.context)?;canonical.validate_context(self.physical.context)?; - let owned=canonical.inner.buffer.as_ref().ok_or(Error::ContextPoisoned)?;let arena=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; - if handle(owned)?.overlaps(owned.len(),handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)} - for w in &weights{for(b,n)in[(w.conv,10240*4*4),(w.alpha,48*2560*2),(w.beta,48*2560*2),(w.dt,48*4),(w.a,48*4),(w.norm,128*4)]{admit(self.physical.context,b,n)?;if handle(b)?.overlaps(n,handle(owned)?,owned.len())||handle(b)?.overlaps(n,handle(arena)?,arena.len()){return Err(Error::OutputAliasesInput)}}} - if let Some(history)=ple{admit(self.physical.context,history,9*10240*4)?;if handle(history)?.overlaps(history.len(),handle(arena)?,arena.len())||handle(history)?.overlaps(history.len(),handle(owned)?,owned.len()){return Err(Error::OutputAliasesInput)}} - Ok(OriginalVerifyGdnJournal{physical:self.physical.clone(),canonical:canonical.inner.clone(),weights,ple,commands:RefCell::new(Vec::new())}) - } -} -impl<'ctx> OriginalVerifyRow<'ctx>{pub fn position(&self)->usize{self.position}pub fn validate_context(&self,c:&Context<'_>)->Result<()>{self.physical.validate(c)?;if self.physical.generation.get()!=self.generation{return Err(Error::InvalidQwenShape)}Ok(())}pub(crate) fn residual(&self)->Result{self.validate_context(self.physical.context)?;let bytes=self.physical.layout.geometry.hc*self.physical.layout.geometry.n*4;let s=self.physical.layout.span("R")?;let b=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;handle(b)?.checked_subspan(b.len(),s.offset+self.row*bytes,bytes)}} -impl<'ctx> OriginalVerifyWindow<'ctx>{ - pub fn rows(&self)->usize{self.rows} - pub fn first_position(&self)->usize{self.position} - pub fn generation(&self)->u64{self.generation} - pub fn sampled_ids(&self)->Result<&[i32]>{self.validate_context(self.physical.context)?;Ok(&self.sampled_ids[..self.rows])} - /// Exact outputs of this completed graph, not merely matching dimensions. - pub fn validate_selection(&self,s:&crate::NativeHeadSelection)->Result<()>{self.validate_context(self.physical.context)?;if s.position()!=self.position as u64||s.vocabulary()!=self.physical.layout.geometry.vocabulary||s.ids()!=&self.sampled_ids[..self.rows]{return Err(Error::InvalidQwenShape)}Ok(())} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{self.physical.validate(c)?;if self.physical.generation.get()!=self.generation{return Err(Error::InvalidQwenShape)}Ok(())} - pub(crate) fn residuals(&self)->Result{self.alias("R",self.rows*self.physical.layout.geometry.hc*self.physical.layout.geometry.n*4)} - pub(crate) fn tokens(&self)->Result{self.alias("tok",self.rows*4)} - pub(super) fn alias(&self,name:&str,bytes:usize)->Result{self.validate_context(self.physical.context)?;let span=self.physical.layout.span(name)?;if bytes>span.bytes{return Err(Error::InvalidSize)}let b=self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;handle(b)?.checked_subspan(b.len(),span.offset,bytes)} -} -/// The journal resolves arena spans for the pure window plans. -impl kernels::ArenaMap for OriginalVerifyGdnJournal<'_, '_>{fn span(&self,name:&str,offset:usize,bytes:usize)->Result{self.physical.span(name,offset,bytes)}} -impl resources::Sealed for OriginalVerifyGdnJournal<'_, '_>{} -impl OriginalGraphResources for OriginalVerifyGdnJournal<'_, '_>{fn validate_context(&self,c:&Context<'_>)->Result<()>{self.physical.validate(c)?;self.canonical.validate_context(c)}} +mod share_window_modules_fn_2; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::admission; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::admit; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::check_commands; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::command; +#[allow(unused_imports)] +pub(crate) use share_window_modules_fn_2::gather_rows_module; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::handle; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::poison; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::sealed_asset; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::share_window_modules; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::transport; +#[allow(unused_imports)] +pub(super) use share_window_modules_fn_2::zero; +mod impl_originalverifybank; +mod impl_originalverifybank_2; +mod impl_physical; diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank.rs new file mode 100644 index 00000000..6effed69 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank.rs @@ -0,0 +1,248 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyBank. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalVerifyBank<'ctx> { + pub(in super::super) fn new(context: &'ctx Context<'ctx>, geometry: OriginalVerifyGeometry) -> Result { + let layout = OriginalVerifyLayout::new(geometry)?; + let asset = sealed_asset(ASSET, ASSET_SHA)?; + let qsa_asset = sealed_asset(QSA_ASSET, QSA_ASSET_SHA)?; + admission(context, layout.bytes)?; + let mut owner = Physical { + context, + layout, + arena: None, + prof: None, + mapped: std::array::from_fn(|_| RefCell::new(None)), + module: None, + qsa_module: None, + window: RefCell::new(Vec::new()), + generation: Cell::new(0), + failed: Cell::new(false), + }; + let operation = (|| { + let guard = context.enter()?; + let loaded = (|| { + owner.module = Some(Module::load(asset, ENTRIES)?); + owner.qsa_module = Some(Module::load(qsa_asset, QSA_ENTRIES)?); + // Original mapped staging is retained and memset before the arena carve. + for (i, n) in owner.layout.mapped_bytes.into_iter().enumerate() { + *owner.mapped[i].get_mut() = Some(MappedAllocation::new(n)?); + owner.mapped[i].get_mut().as_mut().ok_or(Error::ContextPoisoned)?.initialize_zero()?; + } + admission(context, owner.layout.bytes)?; + owner.arena = Some(context.allocate(owner.layout.bytes)?); + let arena = owner.arena.as_ref().ok_or(Error::ContextPoisoned)?; + context.driver.api.zero(handle(arena)?.qwen_address(), arena.len())?; + // STRATA_VERIFY_PROFILE: the device stamp words (Verifier::init `prof_`); a failed allocation just turns the profile off. + if std::env::var_os("STRATA_VERIFY_PROFILE").is_some() { + let bytes = profile::profile_stamp_words(48) * 8; + if let Ok(b) = context.allocate(bytes) { + let zeroed = handle(&b).and_then(|h| context.driver.api.zero(h.qwen_address(), bytes)); + if zeroed.is_ok() { + owner.prof = Some(b) + } else { + let _ = b.release(); + } + } + } + Ok(()) + })(); + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if loaded.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + poison(context) + } + combine(combine(loaded, sync), pop) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close()); + } + Ok(Self { + physical: Rc::new(owner), + last_t: 0, + last_position: 0, + last_tokens: [0; 8], + generation: 0, + last_keep: 0, + released: false, + pcie_sources: Vec::new(), + pcie_mode: 0, + pcie_roles: None, + }) + } + pub(crate) fn staged_window(&self) -> Result<(u64, usize, usize)> { + self.validate_context(self.physical.context)?; + if self.last_t == 0 || self.released { + return Err(Error::InvalidQwenShape); + } + Ok((self.generation, self.last_position, self.last_t)) + } + pub(crate) fn staged_keep(&self) -> Result { + self.staged_window()?; + if !(1..=self.last_t).contains(&self.last_keep) { + return Err(Error::InvalidQwenShape); + } + Ok(self.last_keep) + } + pub(crate) fn completed_row(&self, row: usize) -> Result> { + self.staged_window()?; + if row >= self.last_t { + return Err(Error::InvalidQwenShape); + } + let bytes = self.geometry().hc * self.geometry().n * 4; + self.physical.span("R", row * bytes, bytes)?; + Ok(OriginalVerifyRow { + physical: self.physical.clone(), + generation: self.generation, + row, + position: self.last_position + row, + }) + } + pub fn allocated_bytes(&self) -> usize { + self.physical.layout.bytes + } + pub fn mapped_bytes(&self) -> usize { + self.physical.layout.mapped_bytes.iter().sum() + } + pub fn geometry(&self) -> OriginalVerifyGeometry { + self.physical.layout.geometry + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate(c) + } + /// Called only after the previous actual window/commit graph has drained. The + /// mutable borrow is held by the actor, not copied into an unrelated certificate. + pub(crate) fn stage(&mut self, tokens: &[i32], position: usize) -> Result { + self.validate_context(self.physical.context)?; + let g = self.geometry(); + let t = tokens.len(); + if self.released + || !(1..=g.max_t).contains(&t) + || position.checked_add(t).is_none_or(|e| e > g.max_cells) + || tokens.iter().any(|x| *x < 0 || *x as usize >= g.vocabulary) + { + return Err(Error::InvalidQwenShape); + } + let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?; + // Invalidate every escaped completed row/window BEFORE the first mapped write. + // A failed partial staging cannot retain old generation authority. + self.generation = generation; + self.physical.generation.set(generation); + self.last_t = 0; + self.last_keep = 0; + let mapped = &self.physical.mapped; + for (i, &token) in tokens.iter().enumerate() { + let p = position + i; + mapped[0] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .write(i * 4, &token.to_le_bytes())?; + for (j, v) in [p, p + 1, (p + 1) / 4, (p + 1).min(g.selection)].into_iter().enumerate() { + mapped[1] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .write((i * 4 + j) * 4, &(v as i32).to_le_bytes())? + } + for (offset, heads) in + [(0, g.heads), (g.max_t * g.heads, g.kv_heads), (g.max_t * (g.heads + g.kv_heads), g.index_heads)] + { + for h in 0..heads { + mapped[2] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .write((offset + i * heads + h) * 4, &(p as i32).to_le_bytes())? + } + } + } + for flag in 9..=12 { + mapped[flag] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, 0)? + } + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + self.last_t = t; + self.last_position = position; + self.last_tokens[..t].copy_from_slice(tokens); + self.generation = generation; + self.physical.generation.set(generation); + self.last_keep = 0; + Ok(generation) + } + pub(crate) fn stage_ple(&mut self, values: &[f32]) -> Result<()> { + self.validate_context(self.physical.context)?; + if self.last_t == 0 || values.len() != self.last_t * self.geometry().n || values.iter().any(|x| !x.is_finite()) + { + return Err(Error::InvalidQwenShape); + } + let m = &self.physical.mapped; + let mut slot = m[4].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let m = slot.as_mut().ok_or(Error::ContextPoisoned)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::HostAllocation)?; + for x in values { + bytes.extend_from_slice(&x.to_le_bytes()) + } + m.write(0, &bytes)?; + Ok(()) + } + pub(crate) fn stage_commit(&mut self, keep: usize) -> Result<()> { + self.validate_context(self.physical.context)?; + if !(1..=self.last_t).contains(&keep) { + return Err(Error::InvalidQwenShape); + } + let m = &self.physical.mapped; + let mut slot = m[3].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let m = slot.as_mut().ok_or(Error::ContextPoisoned)?; + m.write(0, &(keep as i32).to_le_bytes())?; + m.write(4, &(keep as i32 - 1).to_le_bytes())?; + for t in 0..self.geometry().max_t { + let p = if t < keep { (self.last_position + t) as i32 } else { -1 }; + m.write((2 + t) * 4, &p.to_le_bytes())? + } + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + self.last_keep = keep; + Ok(()) + } + pub(crate) fn release_gpu_waits(&mut self) -> Result<()> { + self.released = true; + let m = &self.physical.mapped; + for i in 10..=12 { + m[i].try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, u32::MAX)? + } + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + /// Host words the live release/diagnostic registry may read and raise. + pub(in crate::original_verify) fn host_words(&self) -> Result { + let w = |i: usize| -> Result { + self.physical + .mapped + .get(i) + .ok_or(Error::InvalidQwenShape)? + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .host_address(0, 4) + }; + Ok(diag::HostWords { seq: w(9)?, served: w(10)?, plan: w(11)?, copies: w(12)? }) + } + pub fn profile_enabled(&self) -> bool { + self.physical.prof.is_some() + } +} diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs new file mode 100644 index 00000000..d1bf269a --- /dev/null +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_originalverifybank_2.rs @@ -0,0 +1,206 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyBank (2), impl OriginalVerifyRow, impl OriginalVerifyWindow, impl kernels_ArenaMap_for, impl resources_Sealed_for, impl OriginalGraphResources_for_OriginalVerifyGdnJournal. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalVerifyBank<'ctx> { + /// The window's GPU stage stamps, read only after the genuine post-window fences. + pub(crate) fn read_profile(&self) -> Result> { + let b = self.physical.prof.as_ref().ok_or(Error::InvalidQwenShape)?; + self.validate_context(self.physical.context)?; + let words = profile::profile_stamp_words(48); + let mut bytes = zero(words * 8)?; + let guard = self.physical.context.enter()?; + let copy = self.physical.context.driver.api.copy_to(handle(b)?, &mut bytes); + let sync = self.physical.context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + self.physical.failed.set(true); + poison(self.physical.context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!()); + } + combine(combine(copy, sync), pop)?; + Ok(bytes.as_chunks::<8>().0.iter().map(|b| u64::from_le_bytes(*b)).collect()) + } + pub fn doorbell_sequence(&self) -> Result { + self.physical.mapped[9] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0) + } + pub(crate) fn publish_empty_plan(&mut self, group: usize, ring: u32) -> Result<()> { + if group > 1 || ring == 0 || ring > 96 { + return Err(Error::InvalidQwenShape); + } + let m = &self.physical.mapped; + let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let p = slot.as_mut().ok_or(Error::ContextPoisoned)?; + let base = group * self.physical.layout.plan_i32 * 4; + for o in [0, 4, 8, 16, (self.physical.layout.plan_i32 - self.geometry().max_t * self.geometry().k - 2) * 4] { + p.write(base + o, &0i32.to_le_bytes())? + } + m[11] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, ring)?; + m[12] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .raise_u32(0, ring) + } + pub(crate) fn retain_pcie_source(&mut self, bank: Rc>) -> Result<()> { + if !self.pcie_sources.iter().any(|b| Rc::ptr_eq(b, &bank)) { + self.pcie_sources.try_reserve(1).map_err(|_| Error::HostAllocation)?; + self.pcie_sources.push(bank) + } + Ok(()) + } + /// Only after the copy stream drained (the window's own fence). + pub(crate) fn release_pcie_sources(&mut self) { + self.pcie_sources.clear() + } + pub fn close(self) -> Result<()> { + let Self { physical, pcie_sources, .. } = self; + let closed = match Rc::try_unwrap(physical) { + Ok(mut owner) => owner.close(), + Err(_) => Err(Error::InvalidQwenShape), + }; + drop(pcie_sources); + closed + } + /// Fixed real layer operands and borrowed source weights remain alive inside + /// the graph aggregate. No host-made readiness or arbitrary handles enter. + pub fn gdn_journal<'a>( + &self, + canonical: &mut OriginalVerifyCanonicalGdn<'ctx>, + weights: [OriginalVerifyGdnWeights<'a, 'ctx>; 36], + ple: Option<&'a DeviceBuffer<'ctx>>, + ) -> Result> { + self.validate_context(self.physical.context)?; + canonical.validate_context(self.physical.context)?; + let owned = canonical.inner.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + let arena = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + if handle(owned)?.overlaps(owned.len(), handle(arena)?, arena.len()) { + return Err(Error::OutputAliasesInput); + } + for w in &weights { + for (b, n) in [ + (w.conv, 10240 * 4 * 4), + (w.alpha, 48 * 2560 * 2), + (w.beta, 48 * 2560 * 2), + (w.dt, 48 * 4), + (w.a, 48 * 4), + (w.norm, 128 * 4), + ] { + admit(self.physical.context, b, n)?; + if handle(b)?.overlaps(n, handle(owned)?, owned.len()) + || handle(b)?.overlaps(n, handle(arena)?, arena.len()) + { + return Err(Error::OutputAliasesInput); + } + } + } + if let Some(history) = ple { + admit(self.physical.context, history, 9 * 10240 * 4)?; + if handle(history)?.overlaps(history.len(), handle(arena)?, arena.len()) + || handle(history)?.overlaps(history.len(), handle(owned)?, owned.len()) + { + return Err(Error::OutputAliasesInput); + } + } + Ok(OriginalVerifyGdnJournal { + physical: self.physical.clone(), + canonical: canonical.inner.clone(), + weights, + ple, + commands: RefCell::new(Vec::new()), + }) + } +} +impl<'ctx> OriginalVerifyRow<'ctx> { + pub fn position(&self) -> usize { + self.position + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate(c)?; + if self.physical.generation.get() != self.generation { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub(crate) fn residual(&self) -> Result { + self.validate_context(self.physical.context)?; + let bytes = self.physical.layout.geometry.hc * self.physical.layout.geometry.n * 4; + let s = self.physical.layout.span("R")?; + let b = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + handle(b)?.checked_subspan(b.len(), s.offset + self.row * bytes, bytes) + } +} +impl<'ctx> OriginalVerifyWindow<'ctx> { + pub fn rows(&self) -> usize { + self.rows + } + pub fn first_position(&self) -> usize { + self.position + } + pub fn generation(&self) -> u64 { + self.generation + } + pub fn sampled_ids(&self) -> Result<&[i32]> { + self.validate_context(self.physical.context)?; + Ok(&self.sampled_ids[..self.rows]) + } + /// Exact outputs of this completed graph, not merely matching dimensions. + pub fn validate_selection(&self, s: &crate::NativeHeadSelection) -> Result<()> { + self.validate_context(self.physical.context)?; + if s.position() != self.position as u64 + || s.vocabulary() != self.physical.layout.geometry.vocabulary + || s.ids() != &self.sampled_ids[..self.rows] + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate(c)?; + if self.physical.generation.get() != self.generation { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub(crate) fn residuals(&self) -> Result { + self.alias("R", self.rows * self.physical.layout.geometry.hc * self.physical.layout.geometry.n * 4) + } + pub(crate) fn tokens(&self) -> Result { + self.alias("tok", self.rows * 4) + } + pub(in super::super) fn alias(&self, name: &str, bytes: usize) -> Result { + self.validate_context(self.physical.context)?; + let span = self.physical.layout.span(name)?; + if bytes > span.bytes { + return Err(Error::InvalidSize); + } + let b = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + handle(b)?.checked_subspan(b.len(), span.offset, bytes) + } +} +/// The journal resolves arena spans for the pure window plans. +impl kernels::ArenaMap for OriginalVerifyGdnJournal<'_, '_> { + fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.physical.span(name, offset, bytes) + } +} +impl resources::Sealed for OriginalVerifyGdnJournal<'_, '_> {} +impl OriginalGraphResources for OriginalVerifyGdnJournal<'_, '_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate(c)?; + self.canonical.validate_context(c) + } +} diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs new file mode 100644 index 00000000..6e174487 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/impl_physical.rs @@ -0,0 +1,249 @@ +//! Moved out of the parent module by STRA-338: impl Physical, impl Drop_for_Physical. + +#[allow(unused_imports)] +use super::*; + +impl Physical<'_> { + pub(in super::super) fn validate(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if self.failed.get() || c.is_poisoned() || self.module.is_none() || self.qsa_module.is_none() { + return Err(Error::ContextPoisoned); + } + admit(c, self.arena.as_ref().ok_or(Error::ContextPoisoned)?, self.layout.bytes).map(|_| ()) + } + pub(in super::super) fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.validate(self.context)?; + let s = self.layout.span(name)?; + let b = self.arena.as_ref().ok_or(Error::ContextPoisoned)?; + if bytes == 0 || offset.checked_add(bytes).is_none_or(|n| n > s.bytes) { + return Err(Error::InvalidSize); + } + Ok(handle(b)?.checked_subspan(b.len(), s.offset + offset, bytes)?.qwen_address()) + } + /// Load (once) the sealed PTX modules a window producer launches from. Runs before any capture + /// (module loading is not capturable). Specs naming the same PTX file share one module (entries + /// unioned). Every sealed module is loaded; the first unsealed one fails closed AFTER that, by name. + pub(in super::super) fn ensure_window_assets(&self, specs: &[&'static kernels::AssetSpec]) -> Result<()> { + self.validate(self.context)?; + let started = std::time::Instant::now(); + let mut groups: Vec<(&'static str, &'static kernels::AssetSpec, Vec<&'static str>)> = Vec::new(); + for s in specs { + match groups.iter_mut().find(|g| g.0 == s.key()) { + Some(g) => { + for e in s.entries { + if !g.2.contains(e) { + g.2.push(e) + } + } + } + None => groups.push((s.key(), s, s.entries.to_vec())), + } + } + let mut ready = Vec::new(); + let mut unsealed: Result<()> = Ok(()); + { + let mut loaded = self.window.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let cache = self.context.window_modules.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + for (key, spec, entries) in groups { + if let Some((_, _, have)) = loaded.iter().find(|(n, _, _)| *n == key) { + if entries.iter().all(|e| have.contains(e)) { + continue; + } + return Err(Error::InvalidDriverValue( + "Original verifier window module is already loaded without an entry a later graph needs", + )); + } + // A module an earlier bank of this context loaded (sealed and admitted then) is shared, not loaded again: + // the same sealed image, the same entries, unloaded with the context. + if let Some((_, m, have)) = cache.iter().find(|(n, _, have)| { + share_window_modules() && *n == key && entries.iter().all(|e| have.contains(e)) + }) { + loaded.try_reserve(1).map_err(|_| Error::HostAllocation)?; + loaded.push((key, Rc::clone(m), have.clone())); + continue; + } + match spec.sealed() { + Ok(ptx) => ready.push((key, ptx, entries)), + Err(error) => { + if unsealed.is_ok() { + unsealed = Err(error) + } + } + } + } + } + if ready.is_empty() { + crate::original_gpu_schedule::capture_timing::add(2, started.elapsed().as_secs_f64() * 1e3); + return unsealed; + } + let guard = self.context.enter()?; + let mut result = Ok(()); + for (key, ptx, entries) in ready { + match Module::load(ptx, &entries) { + Ok(m) => { + let m = Rc::new(m); + match self.context.window_modules.try_borrow_mut() { + Ok(mut c) => { + c.retain(|(n, _, _)| *n != key); + if c.try_reserve(1).is_ok() { + c.push((key, Rc::clone(&m), entries.clone())) + } + } + Err(_) => { + result = combine(result, Err(Error::InvalidQwenShape)); + break; + } + } + match self.window.try_borrow_mut() { + Ok(mut w) => w.push((key, m, entries)), + Err(_) => { + result = combine(result, Err(Error::InvalidQwenShape)); + break; + } + } + } + Err(error) => { + result = combine(result, Err(error)); + break; + } + } + } + let pop = guard.finish(); + if result.as_ref().err().is_some_and(transport) || pop.is_err() { + self.failed.set(true); + poison(self.context) + } + crate::original_gpu_schedule::capture_timing::add(2, started.elapsed().as_secs_f64() * 1e3); + combine(combine(result, pop), unsealed) + } + /// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` of loaded window entries, once, before any capture + /// (what Original does for the fused GR down kernels). + pub(in super::super) fn configure_window_shared( + &self, + attrs: &[(&'static kernels::AssetSpec, &'static str, usize)], + ) -> Result<()> { + self.validate(self.context)?; + if attrs.is_empty() { + return Ok(()); + } + let guard = self.context.enter()?; + let mut result = Ok(()); + { + let loaded = self.window.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + for (spec, entry, bytes) in attrs { + match loaded.iter().find(|(n, _, _)| *n == spec.key()) { + Some((_, m, _)) => result = combine(result, m.set_max_dynamic_shared(entry, *bytes)), + None => result = combine(result, Err(Error::InvalidDriverValue(spec.unsealed))), + } + } + } + let pop = guard.finish(); + if result.as_ref().err().is_some_and(transport) || pop.is_err() { + self.failed.set(true); + poison(self.context) + } + combine(result, pop) + } + /// `cuDeviceGetAttribute` of the verifier context's device (compute capability and shared-memory limits that Original + /// reads when it picks kernel variants). + pub(in super::super) fn window_device_attribute(&self, attribute: i32) -> Result { + self.validate(self.context)?; + let guard = self.context.enter()?; + let value = match self.module.as_ref() { + Some(m) => m.device_attribute(attribute), + None => Err(Error::ContextPoisoned), + }; + let pop = guard.finish(); + if value.as_ref().err().is_some_and(transport) || pop.is_err() { + self.failed.set(true); + poison(self.context) + } + pop?; + value + } + pub(in super::super) fn mapped_address(&self, i: usize, offset: usize, bytes: usize) -> Result { + self.mapped + .get(i) + .ok_or(Error::InvalidQwenShape)? + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .address(offset, bytes) + } + pub(in super::super) fn close(&mut self) -> Result<()> { + if self.arena.is_none() + && self.prof.is_none() + && self.module.is_none() + && self.qsa_module.is_none() + && self.window.get_mut().is_empty() + { + return Ok(()); + } + self.failed.set(true); + if self.context.is_poisoned() { + if let Some(b) = self.arena.take() { + std::mem::forget(b) + } + if let Some(b) = self.prof.take() { + std::mem::forget(b) + } + if let Some(m) = self.module.take() { + std::mem::forget(m) + } + if let Some(m) = self.qsa_module.take() { + std::mem::forget(m) + } + for (_, m, _) in self.window.get_mut().drain(..) { + std::mem::forget(m) + } + for m in self.mapped.iter_mut().filter_map(|m| m.get_mut().take()) { + std::mem::forget(m) + } + return Err(Error::ContextPoisoned); + } + let sync = self.context.synchronize(); + if sync.is_err() { + poison(self.context); + return combine(sync, self.close()); + } + let mut result = combine( + self.arena.take().map_or(Ok(()), DeviceBuffer::release), + self.prof.take().map_or(Ok(()), DeviceBuffer::release), + ); + if self.context.is_poisoned() { + return combine(result, self.close()); + } + let guard = match self.context.enter() { + Ok(g) => g, + Err(e) => return combine(combine(result, Err(e)), self.close()), + }; + for mut m in self.mapped.iter_mut().filter_map(|m| m.get_mut().take()) { + result = combine(result, m.close()); + if result.is_err() { + std::mem::forget(m) + } + } + let mut unload = combine( + self.module.take().map_or(Ok(()), Module::close), + self.qsa_module.take().map_or(Ok(()), Module::close), + ); + for (_, m, _) in self.window.get_mut().drain(..) { + if let Ok(m) = Rc::try_unwrap(m) { + unload = combine(unload, m.close()); + } + } + let pop = guard.finish(); + if unload.is_err() || pop.is_err() { + poison(self.context) + } + combine(combine(result, unload), pop) + } +} +impl Drop for Physical<'_> { + fn drop(&mut self) { + let _ = self.close(); + } +} diff --git a/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs b/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs new file mode 100644 index 00000000..0d27d585 --- /dev/null +++ b/crates/cuda-driver/src/original_verify/share_window_modules_fn/share_window_modules_fn_2.rs @@ -0,0 +1,214 @@ +//! Moved out of the parent module by STRA-338: fn share_window_modules, fn admission, fn handle, fn admit, fn poison, fn transport .... + +#[allow(unused_imports)] +use super::*; + +/// `LELEKA_WINDOW_MODULE_CACHE=off`: every verifier bank loads its window modules again (A/B control). +pub(in super::super) fn share_window_modules() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| !std::env::var("LELEKA_WINDOW_MODULE_CACHE").is_ok_and(|v| v == "off" || v == "0")) +} +pub(in super::super) fn admission(c: &Context<'_>, n: usize) -> Result<()> { + let need = n.checked_add(RESERVE).ok_or(Error::InvalidSize)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if c.allocated_bytes().checked_add(need).is_none_or(|x| x > c.budget_bytes()) || c.memory_info()?.0 < need { + return Err(Error::BudgetExceeded); + } + Ok(()) +} +pub(in super::super) fn handle(b: &DeviceBuffer<'_>) -> Result { + b.handle.ok_or(Error::ContextPoisoned) +} +pub(in super::super) fn admit(c: &Context<'_>, b: &DeviceBuffer<'_>, bytes: usize) -> Result { + if !std::ptr::eq(c, b.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() }); + } + handle(b)?.validate_projection_extent(bytes, 4)?; + Ok(handle(b)?.qwen_address()) +} +pub(in super::super) fn poison(c: &Context<'_>) { + c.poison(); + c.retain_driver() +} +pub(in super::super) fn transport(e: &Error) -> bool { + match e { + Error::Driver { .. } | Error::ContextPoisoned | Error::UnexpectedContext => true, + Error::Multiple { primary, secondary } => transport(primary) || transport(secondary), + _ => false, + } +} +pub(in super::super) fn zero(n: usize) -> Result> { + let mut b = Vec::new(); + b.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + b.resize(n, 0); + Ok(b) +} +pub(in super::super) fn check_commands(c: &Vec) -> Result<()> { + let mut bytes = c.capacity().checked_mul(std::mem::size_of::()).ok_or(Error::InvalidSize)?; + for x in c { + bytes = bytes.checked_add(x.abi_bytes()?).ok_or(Error::InvalidSize)?; + } + if bytes > 16 << 20 { + return Err(Error::HostAllocation); + } + Ok(()) +} +pub(in super::super) fn command( + name: &'static str, + grid: [u32; 3], + block: [u32; 3], + args: Vec, +) -> Result { + Command::new(name, grid, block, 0, args) +} +pub(in super::super) fn sealed_asset(asset: &'static [u8], digest: [u8; 32]) -> Result<&'static [u8]> { + if asset.len() < 2 + || asset.last() != Some(&0) + || asset[..asset.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&asset[..asset.len() - 1]) != digest + { + return Err(Error::UnsupportedQwenOperation); + } + Ok(asset) +} +/// Sealed `verify_gather_rows_*` kernels for the Original draft-head gather of +/// `MtpDrafter::bind` (`gather_rows`, mtp.cpp:406). The caller must hold the +/// owning context current and close the module while it still is. +pub(crate) fn gather_rows_module() -> Result { + Module::load(sealed_asset(ASSET, ASSET_SHA)?, ENTRIES) +} +impl<'ctx> Context<'ctx> { + pub fn original_verify_canonical_gdn( + &'ctx self, + states: [&[f32]; 36], + histories: [&[f32]; 36], + ) -> Result> { + let _span_canonical = crate::host_profile::span("drv.canonical_gdn"); + for i in 0..36 { + if states[i].len() != STATE_WORDS || histories[i].len() != HISTORY_WORDS { + return Err(Error::InvalidQwenShape); + } + } + admission(self, CANONICAL_BYTES)?; + let mut owner = + Canonical { context: self, buffer: Some(self.allocate(CANONICAL_BYTES)?), failed: Cell::new(false) }; + // One pass per layer converts to little-endian bytes and checks every word finite (two plain slice loops, not a chained + // iterator: they compile to wide copies); a non-finite word refuses the intake before the layer is uploaded. + let operation = (|| { + let mut bytes = zero(LAYER_BYTES)?; + for i in 0..36 { + let (head, tail) = bytes.split_at_mut(STATE_WORDS * 4); + let mut finite = true; + for (x, b) in states[i].iter().zip(head.chunks_exact_mut(4)) { + finite &= x.is_finite(); + b.copy_from_slice(&x.to_le_bytes()) + } + for (x, b) in histories[i].iter().zip(tail.chunks_exact_mut(4)) { + finite &= x.is_finite(); + b.copy_from_slice(&x.to_le_bytes()) + } + if !finite { + return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake")); + } + owner.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i * LAYER_BYTES, &bytes)?; + } + Ok(()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close_inner()); + } + Ok(OriginalVerifyCanonicalGdn { inner: Rc::new(owner) }) + } + pub fn original_verify_bank(&'ctx self, geometry: OriginalVerifyGeometry) -> Result> { + OriginalVerifyBank::new(self, geometry) + } +} +impl Canonical<'_> { + pub fn allocated_bytes(&self) -> usize { + self.buffer.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if self.failed.get() || self.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + admit(c, self.buffer.as_ref().ok_or(Error::ContextPoisoned)?, CANONICAL_BYTES).map(|_| ()) + } + pub(in super::super) fn span(&self, layer: usize, history: bool) -> Result { + self.validate_context(self.context)?; + if layer >= 36 { + return Err(Error::InvalidQwenShape); + } + let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + let offset = layer * LAYER_BYTES + if history { STATE_WORDS * 4 } else { 0 }; + let bytes = if history { HISTORY_WORDS * 4 } else { STATE_WORDS * 4 }; + Ok(handle(b)?.checked_subspan(b.len(), offset, bytes)?.qwen_address()) + } + pub fn with_layer(&self, layer: usize, read: impl FnOnce(&[f32], &[f32]) -> Result) -> Result { + self.validate_context(self.context)?; + if layer >= 36 { + return Err(Error::InvalidQwenShape); + } + let mut bytes = zero(LAYER_BYTES)?; + let b = self.buffer.as_ref().ok_or(Error::ContextPoisoned)?; + let h = handle(b)?.checked_subspan(b.len(), layer * LAYER_BYTES, LAYER_BYTES)?; + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(h, &mut bytes); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + poison(self.context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!()); + } + combine(combine(copy, sync), pop)?; + let mut values = Vec::new(); + values.try_reserve_exact(STATE_WORDS + HISTORY_WORDS).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + if values.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("Original committed GDN")); + } + read(&values[..STATE_WORDS], &values[STATE_WORDS..]) + } + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + self.failed.set(true); + let Some(b) = self.buffer.take() else { return Ok(()) }; + if self.context.is_poisoned() { + std::mem::forget(b); + return Err(Error::ContextPoisoned); + } + b.release() + } +} +impl Drop for Canonical<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +impl OriginalVerifyCanonicalGdn<'_> { + pub fn allocated_bytes(&self) -> usize { + self.inner.allocated_bytes() + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.inner.validate_context(c) + } + pub fn with_layer(&self, layer: usize, read: impl FnOnce(&[f32], &[f32]) -> Result) -> Result { + if Rc::strong_count(&self.inner) != 1 { + return Err(Error::InvalidQwenShape); + } + self.inner.with_layer(layer, read) + } + pub fn close(self) -> Result<()> { + match Rc::try_unwrap(self.inner) { + Ok(mut owner) => owner.close_inner(), + Err(_) => Err(Error::InvalidQwenShape), + } + } +} diff --git a/crates/cuda-driver/src/original_verify_expert_probe.rs b/crates/cuda-driver/src/original_verify_expert_probe.rs index e9368e20..8a8b8992 100644 --- a/crates/cuda-driver/src/original_verify_expert_probe.rs +++ b/crates/cuda-driver/src/original_verify_expert_probe.rs @@ -138,7 +138,11 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> { layer: usize, activation: &[f32], ids: &[i32], - pool: impl FnOnce(OriginalVerifyCpuRows<'_>, &mut OriginalVerifyCpuSink<'_, 'ctx>, &mut OriginalGpuStream<'ctx>) -> Result<()>, + pool: impl FnOnce( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, ) -> Result> { let g = self.bank()?.geometry(); let (n, k) = (g.n, g.k); @@ -188,7 +192,12 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> { }; let physical = self.bank()?.physical.clone(); let wait = |index: usize| -> Result { - command("verify_wait_flag_ge_kernel", [1, 1, 1], [1, 1, 1], vec![Arg::Address(physical.mapped_address(index, 0, 4)?), Arg::I32(ring as i32)]) + command( + "verify_wait_flag_ge_kernel", + [1, 1, 1], + [1, 1, 1], + vec![Arg::Address(physical.mapped_address(index, 0, 4)?), Arg::I32(ring as i32)], + ) }; let plan_copy = command( "verify_copy_i32_from_mapped_kernel", @@ -247,7 +256,12 @@ impl<'ctx> OriginalExpertTierProbe<'ctx> { ) }); let finished = served.and_then(|()| { - let a = physical.mapped[11].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?; + let a = physical.mapped[11] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0)?; if a != ring { self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(0, ring)?; } diff --git a/crates/cuda-driver/src/original_verify_ffi.rs b/crates/cuda-driver/src/original_verify_ffi.rs index 3476ca01..51c0facc 100644 --- a/crates/cuda-driver/src/original_verify_ffi.rs +++ b/crates/cuda-driver/src/original_verify_ffi.rs @@ -1,49 +1,239 @@ //! Private fixed Original OriginalVerify CUDA ABI. No public pointers or symbol names. -use crate::{Error,Result,combine}; -use std::ffi::{CStr,c_void}; -type Handle=*mut c_void; -type Load=unsafe extern "C" fn(*mut Handle,*const c_void)->i32; -type Destroy=unsafe extern "C" fn(Handle)->i32; -type Function=unsafe extern "C" fn(*mut Handle,Handle,*const i8)->i32; -type Launch=unsafe extern "C" fn(Handle,u32,u32,u32,u32,u32,u32,u32,Handle,*mut *mut c_void,*mut *mut c_void)->i32; -type SetAttr=unsafe extern "C" fn(Handle,i32,i32)->i32; -type DeviceOf=unsafe extern "C" fn(*mut i32)->i32; -type DeviceAttr=unsafe extern "C" fn(*mut i32,i32,i32)->i32; +use crate::{Error, Result, combine}; +use std::ffi::{CStr, c_void}; +type Handle = *mut c_void; +type Load = unsafe extern "C" fn(*mut Handle, *const c_void) -> i32; +type Destroy = unsafe extern "C" fn(Handle) -> i32; +type Function = unsafe extern "C" fn(*mut Handle, Handle, *const i8) -> i32; +type Launch = + unsafe extern "C" fn(Handle, u32, u32, u32, u32, u32, u32, u32, Handle, *mut *mut c_void, *mut *mut c_void) -> i32; +type SetAttr = unsafe extern "C" fn(Handle, i32, i32) -> i32; +type DeviceOf = unsafe extern "C" fn(*mut i32) -> i32; +type DeviceAttr = unsafe extern "C" fn(*mut i32, i32, i32) -> i32; /// `Words` is one by-value kernel struct parameter (e.g. `GrMulti`): its bytes are the little-endian u64 words. -pub(crate) enum Arg{Address(u64),I32(i32),I64(i64),U64(u64),F32(f32),Words(Box<[u64]>)} -impl Arg{fn pointer(&mut self)->*mut c_void{match self{Self::Address(v)|Self::U64(v)=>(v as *mut u64).cast(),Self::I32(v)=>(v as *mut i32).cast(),Self::I64(v)=>(v as *mut i64).cast(),Self::F32(v)=>(v as *mut f32).cast(),Self::Words(v)=>v.as_mut_ptr().cast()}}} +pub(crate) enum Arg { + Address(u64), + I32(i32), + I64(i64), + U64(u64), + F32(f32), + Words(Box<[u64]>), +} +impl Arg { + fn pointer(&mut self) -> *mut c_void { + match self { + Self::Address(v) | Self::U64(v) => (v as *mut u64).cast(), + Self::I32(v) => (v as *mut i32).cast(), + Self::I64(v) => (v as *mut i64).cast(), + Self::F32(v) => (v as *mut f32).cast(), + Self::Words(v) => v.as_mut_ptr().cast(), + } + } +} /// `cluster` > 0: launched with `cuLaunchKernelEx` as a thread-block cluster of that many CTAs along x (sm_90+, row 2.5); 0: `cuLaunchKernel`. -pub(crate) struct Command{pub name:&'static str,pub grid:[u32;3],pub block:[u32;3],pub shared:u32,pub cluster:u32,args:Box<[Arg]>,pointers:Vec<*mut c_void>} -impl Command{pub(crate) fn abi_bytes(&self)->Result{self.args.len().checked_mul(std::mem::size_of::()).and_then(|n|self.pointers.capacity().checked_mul(std::mem::size_of::<*mut c_void>()).and_then(|m|n.checked_add(m))).ok_or(Error::InvalidSize)} - pub(crate) fn new(name:&'static str,grid:[u32;3],block:[u32;3],shared:u32,args:Vec)->Result{let mut pointers=Vec::new();pointers.try_reserve_exact(args.len()).map_err(|_|Error::HostAllocation)?;Ok(Self{name,grid,block,shared,cluster:0,args:args.into_boxed_slice(),pointers})} - pub(crate) fn with_cluster(mut self,cluster:u32)->Self{self.cluster=cluster;self}} +pub(crate) struct Command { + pub name: &'static str, + pub grid: [u32; 3], + pub block: [u32; 3], + pub shared: u32, + pub cluster: u32, + args: Box<[Arg]>, + pointers: Vec<*mut c_void>, +} +impl Command { + pub(crate) fn abi_bytes(&self) -> Result { + self.args + .len() + .checked_mul(std::mem::size_of::()) + .and_then(|n| { + self.pointers.capacity().checked_mul(std::mem::size_of::<*mut c_void>()).and_then(|m| n.checked_add(m)) + }) + .ok_or(Error::InvalidSize) + } + pub(crate) fn new( + name: &'static str, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result { + let mut pointers = Vec::new(); + pointers.try_reserve_exact(args.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { name, grid, block, shared, cluster: 0, args: args.into_boxed_slice(), pointers }) + } + pub(crate) fn with_cluster(mut self, cluster: u32) -> Self { + self.cluster = cluster; + self + } +} struct Library(Handle); -impl Drop for Library{fn drop(&mut self){if !self.0.is_null(){unsafe{libc::dlclose(self.0);}}}} -pub(crate) struct Module{library:Option,handle:Option,functions:Vec<(&'static str,usize)>,launch:Launch,launch_ex:Option,unload:Destroy,set_attr:SetAttr,device:DeviceOf,device_attr:DeviceAttr} -fn check(op:&'static str,c:i32)->Result<()>{if c==0{Ok(())}else{Err(Error::Driver{operation:op,code:c})}} -impl Module{ - pub(crate) fn load(ptx:&'static[u8],entries:&[&'static str])->Result{ - if ptx.last()!=Some(&0)||entries.is_empty(){return Err(Error::InvalidDriverValue("OriginalVerify sealed PTX"));} - let library=Library(unsafe{libc::dlopen(c"libcuda.so.1".as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)});if library.0.is_null(){return Err(Error::LibraryUnavailable);} - fn sym(l:&Library,n:&'static CStr)->Result{let p=unsafe{libc::dlsym(l.0,n.as_ptr())};if p.is_null(){Err(Error::MissingSymbol(n.to_str().unwrap_or("OriginalVerify ABI")))}else{Ok(p)}} - macro_rules! symbol{($n:literal,$t:ty)=>{unsafe{std::mem::transmute::(sym(&library,$n)?)} };} - let load=symbol!(c"cuModuleLoadData",Load);let function=symbol!(c"cuModuleGetFunction",Function); - let launch_ex=sym(&library,c"cuLaunchKernelEx").ok().map(|p|unsafe{std::mem::transmute::(p)}); - let mut owner=Self{launch:symbol!(c"cuLaunchKernel",Launch),launch_ex,unload:symbol!(c"cuModuleUnload",Destroy),set_attr:symbol!(c"cuFuncSetAttribute",SetAttr),device:symbol!(c"cuCtxGetDevice",DeviceOf),device_attr:symbol!(c"cuDeviceGetAttribute",DeviceAttr),library:Some(library),handle:None,functions:Vec::new()}; - owner.functions.try_reserve_exact(entries.len()).map_err(|_|Error::HostAllocation)?; - let operation=(||{let mut h=std::ptr::null_mut();check("cuModuleLoadData",unsafe{load(&mut h,crate::arch_ptx::image(ptx).as_ptr().cast())})?;if h.is_null(){return Err(Error::InvalidDriverValue("cuModuleLoadData"));}owner.handle=Some(h as usize);for &name in entries{let c=std::ffi::CString::new(name).map_err(|_|Error::InvalidSize)?;let mut f=std::ptr::null_mut();check("cuModuleGetFunction",unsafe{function(&mut f,h,c.as_ptr())})?;if f.is_null(){return Err(Error::InvalidDriverValue("cuModuleGetFunction"));}owner.functions.push((name,f as usize));}Ok(())})(); - if let Err(primary)=operation{return combine(Err(primary),owner.close());}Ok(owner) - } - pub(crate) fn admit(&self,c:&Command)->Result<()>{if self.handle.is_none()||!self.functions.iter().any(|(n,_)|*n==c.name)||c.grid.contains(&0)||c.block.contains(&0){return Err(Error::InvalidQwenShape);}Ok(())} - pub(crate) fn launch(&self,stream:usize,c:&mut Command)->Result<()>{self.admit(c)?;let f=self.functions.iter().find(|(n,_)|*n==c.name).ok_or(Error::UnsupportedQwenOperation)?.1;c.pointers.clear();for arg in c.args.iter_mut(){c.pointers.push(arg.pointer());} - if c.cluster>0{let launch_ex=self.launch_ex.ok_or(Error::MissingSymbol("cuLaunchKernelEx"))?;if c.grid[0]%c.cluster!=0{return Err(Error::InvalidQwenShape);}let mut attribute=crate::launch_ex::LaunchAttribute::cluster_x(c.cluster);let config=crate::launch_ex::LaunchConfig{grid:c.grid,block:c.block,smem:c.shared,stream:stream as Handle,attrs:&mut attribute,num_attrs:1};return check("cuLaunchKernelEx",unsafe{launch_ex(&config,f as Handle,c.pointers.as_mut_ptr(),std::ptr::null_mut())});} - check("cuLaunchKernel",unsafe{(self.launch)(f as Handle,c.grid[0],c.grid[1],c.grid[2],c.block[0],c.block[1],c.block[2],c.shared,stream as Handle,c.pointers.as_mut_ptr(),std::ptr::null_mut())})} - /// `cuFuncSetAttribute(CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES)` of one loaded entry (Original sets it once - /// before any launch/capture for kernels that stage more than 48 KiB). - pub(crate) fn set_max_dynamic_shared(&self,name:&str,bytes:usize)->Result<()>{let f=self.functions.iter().find(|(n,_)|*n==name).ok_or(Error::UnsupportedQwenOperation)?.1;check("cuFuncSetAttribute",unsafe{(self.set_attr)(f as Handle,8,i32::try_from(bytes).map_err(|_|Error::InvalidSize)?)})} - /// `cuDeviceGetAttribute` of the context's current device (97 = max shared per block opt-in, 8 = per block, 75/76 = cc). - pub(crate) fn device_attribute(&self,attribute:i32)->Result{let mut device=0;check("cuCtxGetDevice",unsafe{(self.device)(&mut device)})?;let mut value=0;check("cuDeviceGetAttribute",unsafe{(self.device_attr)(&mut value,attribute,device)})?;Ok(value)} - pub(crate) fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{if let Some(h)=self.handle.take(){let result=check("cuModuleUnload",unsafe{(self.unload)(h as Handle)});if result.is_err(){if let Some(l)=self.library.take(){std::mem::forget(l);}}result}else{Ok(())}} +impl Drop for Library { + fn drop(&mut self) { + if !self.0.is_null() { + unsafe { + libc::dlclose(self.0); + } + } + } +} +pub(crate) struct Module { + library: Option, + handle: Option, + functions: Vec<(&'static str, usize)>, + launch: Launch, + launch_ex: Option, + unload: Destroy, + set_attr: SetAttr, + device: DeviceOf, + device_attr: DeviceAttr, +} +fn check(op: &'static str, c: i32) -> Result<()> { + if c == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: c }) } +} +impl Module { + pub(crate) fn load(ptx: &'static [u8], entries: &[&'static str]) -> Result { + if ptx.last() != Some(&0) || entries.is_empty() { + return Err(Error::InvalidDriverValue("OriginalVerify sealed PTX")); + } + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); + if library.0.is_null() { + return Err(Error::LibraryUnavailable); + } + fn sym(l: &Library, n: &'static CStr) -> Result { + let p = unsafe { libc::dlsym(l.0, n.as_ptr()) }; + if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("OriginalVerify ABI"))) } else { Ok(p) } + } + macro_rules! symbol { + ($n:literal,$t:ty) => { + unsafe { std::mem::transmute::(sym(&library, $n)?) } + }; + } + let load = symbol!(c"cuModuleLoadData", Load); + let function = symbol!(c"cuModuleGetFunction", Function); + let launch_ex = sym(&library, c"cuLaunchKernelEx") + .ok() + .map(|p| unsafe { std::mem::transmute::(p) }); + let mut owner = Self { + launch: symbol!(c"cuLaunchKernel", Launch), + launch_ex, + unload: symbol!(c"cuModuleUnload", Destroy), + set_attr: symbol!(c"cuFuncSetAttribute", SetAttr), + device: symbol!(c"cuCtxGetDevice", DeviceOf), + device_attr: symbol!(c"cuDeviceGetAttribute", DeviceAttr), + library: Some(library), + handle: None, + functions: Vec::new(), + }; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; + let operation = (|| { + let mut h = std::ptr::null_mut(); + check("cuModuleLoadData", unsafe { load(&mut h, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; + if h.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + owner.handle = Some(h as usize); + for &name in entries { + let c = std::ffi::CString::new(name).map_err(|_| Error::InvalidSize)?; + let mut f = std::ptr::null_mut(); + check("cuModuleGetFunction", unsafe { function(&mut f, h, c.as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + owner.functions.push((name, f as usize)); + } + Ok(()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + pub(crate) fn admit(&self, c: &Command) -> Result<()> { + if self.handle.is_none() + || !self.functions.iter().any(|(n, _)| *n == c.name) + || c.grid.contains(&0) + || c.block.contains(&0) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub(crate) fn launch(&self, stream: usize, c: &mut Command) -> Result<()> { + self.admit(c)?; + let f = self.functions.iter().find(|(n, _)| *n == c.name).ok_or(Error::UnsupportedQwenOperation)?.1; + c.pointers.clear(); + for arg in c.args.iter_mut() { + c.pointers.push(arg.pointer()); + } + if c.cluster > 0 { + let launch_ex = self.launch_ex.ok_or(Error::MissingSymbol("cuLaunchKernelEx"))?; + if c.grid[0] % c.cluster != 0 { + return Err(Error::InvalidQwenShape); + } + let mut attribute = crate::launch_ex::LaunchAttribute::cluster_x(c.cluster); + let config = crate::launch_ex::LaunchConfig { + grid: c.grid, + block: c.block, + smem: c.shared, + stream: stream as Handle, + attrs: &mut attribute, + num_attrs: 1, + }; + return check("cuLaunchKernelEx", unsafe { + launch_ex(&config, f as Handle, c.pointers.as_mut_ptr(), std::ptr::null_mut()) + }); + } + check("cuLaunchKernel", unsafe { + (self.launch)( + f as Handle, + c.grid[0], + c.grid[1], + c.grid[2], + c.block[0], + c.block[1], + c.block[2], + c.shared, + stream as Handle, + c.pointers.as_mut_ptr(), + std::ptr::null_mut(), + ) + }) + } + /// `cuFuncSetAttribute(CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES)` of one loaded entry (Original sets it once + /// before any launch/capture for kernels that stage more than 48 KiB). + pub(crate) fn set_max_dynamic_shared(&self, name: &str, bytes: usize) -> Result<()> { + let f = self.functions.iter().find(|(n, _)| *n == name).ok_or(Error::UnsupportedQwenOperation)?.1; + check("cuFuncSetAttribute", unsafe { + (self.set_attr)(f as Handle, 8, i32::try_from(bytes).map_err(|_| Error::InvalidSize)?) + }) + } + /// `cuDeviceGetAttribute` of the context's current device (97 = max shared per block opt-in, 8 = per block, 75/76 = cc). + pub(crate) fn device_attribute(&self, attribute: i32) -> Result { + let mut device = 0; + check("cuCtxGetDevice", unsafe { (self.device)(&mut device) })?; + let mut value = 0; + check("cuDeviceGetAttribute", unsafe { (self.device_attr)(&mut value, attribute, device) })?; + Ok(value) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + if let Some(h) = self.handle.take() { + let result = check("cuModuleUnload", unsafe { (self.unload)(h as Handle) }); + if result.is_err() { + if let Some(l) = self.library.take() { + std::mem::forget(l); + } + } + result + } else { + Ok(()) + } + } +} +impl Drop for Module { + fn drop(&mut self) { + let _ = self.close_inner(); + } } -impl Drop for Module{fn drop(&mut self){let _=self.close_inner();}} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan.rs b/crates/cuda-driver/src/original_verify_gpu_plan.rs index 3b79ad1b..a300dd7d 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan.rs @@ -13,8 +13,8 @@ //! Every pointer comes from an owner, never from the caller: a VRAM group names a cache slot whose fill has //! completed and whose owner is the routed expert of every entry of the group (checked against the mapped ids //! the doorbell published), a PCIe group names the three registered bank spans of that same expert. -use super::*; use super::window_plan::{PlanLayout, staging_blobs_per_group}; +use super::*; use crate::{MappedExpertBank, OriginalExpertCache, OriginalGpuStream}; use leleka_model_format::qwen4exp::{ResidentExpertBankSpan, TensorRole}; @@ -28,30 +28,6 @@ pub struct OriginalVerifyGpuPlan { vram: Vec<(usize, Vec)>, pcie: Vec>, } -impl OriginalVerifyGpuPlan { - pub fn new() -> Self { - Self::default() - } - pub fn push_vram(&mut self, slot: usize, entries: Vec) { - self.vram.push((slot, entries)); - } - pub fn push_pcie(&mut self, entries: Vec) { - self.pcie.push(entries); - } - pub fn vram(&self) -> &[(usize, Vec)] { - &self.vram - } - pub fn pcie(&self) -> &[Vec] { - &self.pcie - } - /// Entries the GPU computes (`counts[1]`). - pub fn entries(&self) -> usize { - self.vram.iter().map(|(_, e)| e.len()).sum::() + self.pcie.iter().map(Vec::len).sum::() - } - pub fn is_empty(&self) -> bool { - self.vram.is_empty() && self.pcie.is_empty() - } -} /// The registered source of the plan's PCIe groups: `spans[q]` are the gate/up/down spans of PCIe group `q`'s /// expert. `Some` also routes flag B through the copy stream even when nothing is staged, so the flag only @@ -61,313 +37,31 @@ pub struct OriginalVerifyPcieSource<'s, 'ctx> { pub spans: &'s [[ResidentExpertBankSpan; 3]], } -/// The literal `GpuPlanSink` writes of one group into a `layout.words` int32 block (little-endian bytes): -/// VRAM groups first (`ptr`, `start`), `start[groups] = entries`, then the PCIe groups (`ptr2`, `start2`), -/// `start2[fetches] = entries`, and the counts. `dst[e] = i`, `tok[e] = i / k`. Refuses an entry outside the -/// group's `n_entries`, a repeated entry, an empty group, and more groups or entries than the block holds. -pub(crate) fn encode_plan_block( - layout: &PlanLayout, - cap: usize, - k: usize, - n_entries: usize, - vram: &[(u64, &[u16])], - pcie: &[(u64, &[u16])], -) -> Result> { - if k == 0 || n_entries > cap || n_entries > 128 || vram.len() > cap || pcie.len() > cap.min(MAX_PCIE_FETCHES) { - return Err(Error::InvalidQwenShape); - } - let mut words = vec![0i32; layout.words]; - let mut seen = [false; 128]; - let mut entries = 0usize; - let put_u64 = |words: &mut Vec, at: usize, value: u64| { - words[at] = value as u32 as i32; - words[at + 1] = (value >> 32) as u32 as i32; - }; - let mut add_entries = |words: &mut Vec, list: &[u16], entries: &mut usize| -> Result<()> { - if list.is_empty() { - return Err(Error::InvalidQwenShape); - } - for &i in list { - let i = usize::from(i); - if i >= n_entries || std::mem::replace(&mut seen[i], true) || *entries >= cap { - return Err(Error::InvalidQwenShape); - } - words[layout.dst + *entries] = i as i32; - words[layout.tok + *entries] = (i / k) as i32; - *entries += 1; - } - Ok(()) - }; - for (g, (ptr, list)) in vram.iter().enumerate() { - if *ptr == 0 { - return Err(Error::InvalidQwenShape); - } - put_u64(&mut words, layout.ptr + 2 * g, *ptr); - words[layout.start + g] = entries as i32; - add_entries(&mut words, list, &mut entries)?; - } - words[layout.start + vram.len()] = entries as i32; - for (q, (ptr, list)) in pcie.iter().enumerate() { - if *ptr == 0 { - return Err(Error::InvalidQwenShape); - } - put_u64(&mut words, layout.ptr2 + 2 * q, *ptr); - words[layout.start2 + q] = entries as i32; - add_entries(&mut words, list, &mut entries)?; - } - words[layout.start2 + pcie.len()] = entries as i32; - words[layout.counts] = vram.len() as i32; - words[layout.counts + 1] = entries as i32; - words[layout.counts + 2] = pcie.len() as i32; - Ok(words.iter().flat_map(|w| w.to_le_bytes()).collect()) -} - -fn span_layer(span: &ResidentExpertBankSpan) -> Option { - match span.role() { - TensorRole::Layer { layer, .. } => Some(usize::from(layer)), - _ => None, - } -} - -impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { - /// The plan block's entry capacity (`GpuPlanSink::cap` = `max_t * k`). - pub fn plan_capacity(&self) -> usize { - let g = self.bank.geometry(); - g.max_t * g.k - } - /// Staging blobs of this group (`staging_cap`: 16, or 8 in a split window). - pub fn staging_capacity(&self) -> usize { - staging_blobs_per_group(self.groups) - } - /// Whether the PCIe copies of this group have landed (flag B reached this group's ring value): a read of one - /// mapped host word, for the share controller to see which leg of a layer finishes last. - pub fn copies_landed(&self) -> Result { - let b = self.bank.physical.mapped[12].try_borrow().map_err(|_| Error::InvalidQwenShape)?; - Ok(b.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)? >= self.ring) - } - /// The routed ids of this group's rows (`rows * k`), as the doorbell published them. - fn group_ids(&self) -> Result> { - let g = self.bank.geometry(); - let mapped = self.bank.physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; - let mapped = mapped.as_ref().ok_or(Error::ContextPoisoned)?; - let mut ids = Vec::new(); - ids.try_reserve_exact(self.rows * g.k).map_err(|_| Error::HostAllocation)?; - for i in 0..self.rows * g.k { - ids.push(mapped.read_u32((self.first * g.k + i) * 4)? as i32); - } - Ok(ids) - } - - /// Publish this group's GPU plan and raise flag A; stage its PCIe share by DMA on `copy` and raise flag B - /// after it (or at once). Call at most once per group, before the CPU's own share is written; the run loop - /// then skips its empty plan. A refusal publishes nothing (the run loop's empty plan follows, and the pool - /// must then fail the group). - pub fn publish_gpu_plan( - &mut self, - plan: &OriginalVerifyGpuPlan, - cache: &OriginalExpertCache<'ctx>, - pcie: Option>, - copy: &mut OriginalGpuStream<'ctx>, - ) -> Result<()> { - let context = self.bank.physical.context; - self.bank.validate_context(context)?; - cache.validate_file_source_context(context)?; - copy.validate_context(context)?; - let g = self.bank.geometry(); - let layout = PlanLayout::new(g.max_t * g.k); - let cap = g.max_t * g.k; - let a = self.bank.physical.mapped[11].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?; - if a >= self.ring { - return Err(Error::InvalidQwenShape); - } - let ids = self.group_ids()?; - // VRAM groups: a completed slot owned by the routed expert of every entry, in this layer. - let mut vram = Vec::new(); - vram.try_reserve_exact(plan.vram.len()).map_err(|_| Error::HostAllocation)?; - for (slot, entries) in &plan.vram { - let (layer, expert) = cache.slot_owner(*slot).ok_or(Error::InvalidQwenShape)?; - if layer != self.layer || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(expert as i32)) { - return Err(Error::InvalidQwenShape); - } - let (handle, _) = cache.completed_slot(*slot)?; - vram.push((handle.qwen_address(), entries.as_slice())); - } - // PCIe groups: staging slot q of this group's half, each the bank spans of that entry's expert. - let per = staging_blobs_per_group(self.groups); - let mut stride = 0usize; - let spans = match &pcie { - Some(source) => source.spans, - None => &[], - }; - if spans.len() != plan.pcie.len() || plan.pcie.len() > per.min(MAX_PCIE_FETCHES) { - return Err(Error::InvalidQwenShape); - } - for (q, entries) in plan.pcie.iter().enumerate() { - let s = &spans[q]; - let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; - if !source.bank.cache_context_matches(context) - || !source.bank.eligible(s) - || span_layer(&s[0]) != Some(self.layer) - || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(s[0].expert() as i32)) - { - return Err(Error::InvalidQwenShape); - } - let bytes = s.iter().try_fold(0usize, |n, x| n.checked_add(x.bytes().len()).ok_or(Error::InvalidSize))?; - if bytes == 0 || bytes > g.max_expert_blob || (stride != 0 && bytes != stride) { - return Err(Error::InvalidQwenShape); - } - stride = bytes; - } - let staging = if plan.pcie.is_empty() { - 0 - } else { - self.bank.physical.span("staging", self.group * per * g.max_expert_blob, per * g.max_expert_blob)? - }; - let kernel = self.bank.pcie_mode == 2; - // The copy kernel (pcie mode 2) reads every PCIe expert's three spans through their device aliases: each must - // have exactly the length the graphs copy for this layer. - let mut aliases: Vec<[u64; 3]> = Vec::new(); - if kernel && !plan.pcie.is_empty() { - let roles = self.bank.pcie_roles.as_ref().and_then(|r| r.get(self.layer)).copied().ok_or(Error::InvalidQwenShape)?; - let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; - if 3 * plan.pcie.len() > cap { - return Err(Error::InvalidQwenShape); - } - aliases.try_reserve_exact(spans.len()).map_err(|_| Error::HostAllocation)?; - for s in spans { - let mut a = [0u64; 3]; - for (r, part) in s.iter().enumerate() { - if part.bytes().len() != roles[r] { - return Err(Error::InvalidQwenShape); - } - a[r] = source.bank.pcie_alias(part)?; - } - aliases.push(a); - } - } - let pcie_ptrs: Vec<(u64, &[u16])> = plan - .pcie - .iter() - .enumerate() - .map(|(q, e)| (if kernel { aliases[q][0] } else { staging + (q * stride) as u64 }, e.as_slice())) - .collect(); - let mut block = encode_plan_block(&layout, cap, g.k, self.rows * g.k, &vram, &pcie_ptrs)?; - // pcie mode 2: `ptr2[3 q + r]` = span r of PCIe group q; the graph's copy kernel stages them and rebases ptr2[q]. - for (q, a) in aliases.iter().enumerate() { - for (r, &alias) in a.iter().enumerate() { - let at = (layout.ptr2 + 2 * (3 * q + r)) * 4; - block[at..at + 8].copy_from_slice(&alias.to_le_bytes()); - } - } - { - let m = &self.bank.physical.mapped; - let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; - slot.as_mut().ok_or(Error::ContextPoisoned)?.write(self.group * layout.mapped_stride() * 4, &block)?; - m[11].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0, self.ring)?; - } - let flag_b = self.bank.physical.mapped[12].try_borrow().map_err(|_| Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.host_address(0, 4)?; - if kernel { - // No host CUDA call inside the window (generate.cpp's reason for `--pcie-mode kernel`): the copy kernel - // reads the registered bytes after flag B, so the bank stays retained until the window's fence. - if !plan.pcie.is_empty() { - self.bank.retain_pcie_source(Rc::clone(pcie.as_ref().ok_or(Error::InvalidQwenShape)?.bank))?; - } - return self.bank.physical.mapped[12] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .raise_u32(0, self.ring); - } - match pcie { - None => self.bank.physical.mapped[12] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .raise_u32(0, self.ring), - Some(source) => { - if !plan.pcie.is_empty() { - // The bank's registered bytes are read by the copy engine after this call returns: the bank - // stays retained by the verifier until the window's copy-stream fence. - self.bank.retain_pcie_source(Rc::clone(source.bank))?; - } - let (many, batch, write) = dma_options(); - if many { - let mut pieces: Vec<(u64, &[u8])> = Vec::new(); - for (q, s) in spans.iter().enumerate() { - let mut offset = staging + (q * stride) as u64; - for part in s { - let bytes = source.bank.cache_source(part)?; - for (at, n) in source.bank.copy_pieces(bytes) { - pieces.push((offset + at as u64, &bytes[at..at + n])); - } - offset += bytes.len() as u64; - } - } - if !pieces.is_empty() { - copy.enqueue_copy_h2d_many(&pieces, batch)?; - } - } else { - for (q, s) in spans.iter().enumerate() { - let mut offset = staging + (q * stride) as u64; - for part in s { - let bytes = source.bank.cache_source(part)?; - for (at, n) in source.bank.copy_pieces(bytes) { - copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?; - } - offset += bytes.len() as u64; - } - } - } - if write { - let device_b = self.bank.physical.mapped[12] - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .as_ref() - .ok_or(Error::ContextPoisoned)? - .address(0, 4)?; - return copy.enqueue_raise_flag(flag_b, device_b, self.ring); - } - copy.enqueue_raise_u32(flag_b, self.ring) - } - } - } -} - -/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except where noted (job 981: +6 % over the -/// per-piece path on the 5090): `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, `LELEKA_PCIE_DMA_BATCH=off` to one -/// `cuMemcpyBatchAsync`-free loop inside the entry, `LELEKA_PCIE_FLAGB=host` raises flag B with a host callback instead of -/// `cuStreamWriteValue32`. A driver without the batch / write calls takes the loop / host callback by itself. -/// -/// The batch call is off by default on native Windows and under WSL2: on the RTX 3080 laptop `cuMemcpyBatchAsync_v2` from page-locked -/// host memory raises CUDA error 700 for any piece, source access order or registration flag, which killed the first decode window -/// of every request with a PCIe share (docs/windows.md, "PCIe tier on the laptop"; `pcie_copy_gpu_raw_batch_page_locked` repeats the -/// check). The stream write of flag B is also opt-in under WSL2 only. `=on` / `=write` force either call. -pub(crate) fn dma_options() -> (bool, bool, bool) { - static OPTIONS: std::sync::OnceLock<(bool, bool, bool)> = std::sync::OnceLock::new(); - *OPTIONS.get_or_init(|| { - let wsl = std::fs::read_to_string("/proc/sys/kernel/osrelease").is_ok_and(|v| v.to_ascii_lowercase().contains("microsoft")); - dma_options_for(wsl, cfg!(windows), |name| std::env::var(name).unwrap_or_default()) - }) -} - -/// `dma_options` for a platform and an environment: `wsl` (WSL2 passthrough) makes the batch copy and the stream write opt-in, -/// `windows` (native) the batch copy only. -fn dma_options_for(wsl: bool, windows: bool, env: impl Fn(&str) -> String) -> (bool, bool, bool) { - let default = |name: &str, off_by_default: bool| match env(name).as_str() { - "on" | "write" => true, - "off" | "host" => false, - _ => !off_by_default, - }; - (env("LELEKA_PCIE_DMA_MANY") != "off", default("LELEKA_PCIE_DMA_BATCH", wsl || windows), default("LELEKA_PCIE_FLAGB", wsl) && env("LELEKA_PCIE_FLAGB") != "host") -} - // Model-free GPU smoke of the PCIe staging copy: pageable / page-locked / mixed sources, one call per piece and the batch call. -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] #[path = "original_pcie_copy_gpu_smoke.rs"] mod pcie_copy_smoke; #[cfg(test)] #[path = "original_verify_gpu_plan/tests.rs"] mod tests; + +#[path = "original_verify_gpu_plan/impl_originalverifygpuplan.rs"] +mod impl_originalverifygpuplan; +#[allow(unused_imports)] +pub(crate) use impl_originalverifygpuplan::encode_plan_block; +#[allow(unused_imports)] +use impl_originalverifygpuplan::span_layer; +#[path = "original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs"] +mod impl_schedule_originalverifycpusink; +#[allow(unused_imports)] +pub(crate) use impl_schedule_originalverifycpusink::dma_options; +#[path = "original_verify_gpu_plan/dma_options_for_fn.rs"] +mod dma_options_for_fn; +#[allow(unused_imports)] +use dma_options_for_fn::dma_options_for; diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs b/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs new file mode 100644 index 00000000..4247ae7e --- /dev/null +++ b/crates/cuda-driver/src/original_verify_gpu_plan/dma_options_for_fn.rs @@ -0,0 +1,19 @@ +//! Moved out of the parent module by STRA-338: fn dma_options_for. + +#[allow(unused_imports)] +use super::*; + +/// `dma_options` for a platform and an environment: `wsl` (WSL2 passthrough) makes the batch copy and the stream write opt-in, +/// `windows` (native) the batch copy only. +pub(super) fn dma_options_for(wsl: bool, windows: bool, env: impl Fn(&str) -> String) -> (bool, bool, bool) { + let default = |name: &str, off_by_default: bool| match env(name).as_str() { + "on" | "write" => true, + "off" | "host" => false, + _ => !off_by_default, + }; + ( + env("LELEKA_PCIE_DMA_MANY") != "off", + default("LELEKA_PCIE_DMA_BATCH", wsl || windows), + default("LELEKA_PCIE_FLAGB", wsl) && env("LELEKA_PCIE_FLAGB") != "host", + ) +} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs b/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs new file mode 100644 index 00000000..77cd2e4e --- /dev/null +++ b/crates/cuda-driver/src/original_verify_gpu_plan/impl_originalverifygpuplan.rs @@ -0,0 +1,97 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyGpuPlan, fn encode_plan_block, fn span_layer. + +#[allow(unused_imports)] +use super::*; + +impl OriginalVerifyGpuPlan { + pub fn new() -> Self { + Self::default() + } + pub fn push_vram(&mut self, slot: usize, entries: Vec) { + self.vram.push((slot, entries)); + } + pub fn push_pcie(&mut self, entries: Vec) { + self.pcie.push(entries); + } + pub fn vram(&self) -> &[(usize, Vec)] { + &self.vram + } + pub fn pcie(&self) -> &[Vec] { + &self.pcie + } + /// Entries the GPU computes (`counts[1]`). + pub fn entries(&self) -> usize { + self.vram.iter().map(|(_, e)| e.len()).sum::() + self.pcie.iter().map(Vec::len).sum::() + } + pub fn is_empty(&self) -> bool { + self.vram.is_empty() && self.pcie.is_empty() + } +} + +/// The literal `GpuPlanSink` writes of one group into a `layout.words` int32 block (little-endian bytes): +/// VRAM groups first (`ptr`, `start`), `start[groups] = entries`, then the PCIe groups (`ptr2`, `start2`), +/// `start2[fetches] = entries`, and the counts. `dst[e] = i`, `tok[e] = i / k`. Refuses an entry outside the +/// group's `n_entries`, a repeated entry, an empty group, and more groups or entries than the block holds. +pub(crate) fn encode_plan_block( + layout: &PlanLayout, + cap: usize, + k: usize, + n_entries: usize, + vram: &[(u64, &[u16])], + pcie: &[(u64, &[u16])], +) -> Result> { + if k == 0 || n_entries > cap || n_entries > 128 || vram.len() > cap || pcie.len() > cap.min(MAX_PCIE_FETCHES) { + return Err(Error::InvalidQwenShape); + } + let mut words = vec![0i32; layout.words]; + let mut seen = [false; 128]; + let mut entries = 0usize; + let put_u64 = |words: &mut Vec, at: usize, value: u64| { + words[at] = value as u32 as i32; + words[at + 1] = (value >> 32) as u32 as i32; + }; + let mut add_entries = |words: &mut Vec, list: &[u16], entries: &mut usize| -> Result<()> { + if list.is_empty() { + return Err(Error::InvalidQwenShape); + } + for &i in list { + let i = usize::from(i); + if i >= n_entries || std::mem::replace(&mut seen[i], true) || *entries >= cap { + return Err(Error::InvalidQwenShape); + } + words[layout.dst + *entries] = i as i32; + words[layout.tok + *entries] = (i / k) as i32; + *entries += 1; + } + Ok(()) + }; + for (g, (ptr, list)) in vram.iter().enumerate() { + if *ptr == 0 { + return Err(Error::InvalidQwenShape); + } + put_u64(&mut words, layout.ptr + 2 * g, *ptr); + words[layout.start + g] = entries as i32; + add_entries(&mut words, list, &mut entries)?; + } + words[layout.start + vram.len()] = entries as i32; + for (q, (ptr, list)) in pcie.iter().enumerate() { + if *ptr == 0 { + return Err(Error::InvalidQwenShape); + } + put_u64(&mut words, layout.ptr2 + 2 * q, *ptr); + words[layout.start2 + q] = entries as i32; + add_entries(&mut words, list, &mut entries)?; + } + words[layout.start2 + pcie.len()] = entries as i32; + words[layout.counts] = vram.len() as i32; + words[layout.counts + 1] = entries as i32; + words[layout.counts + 2] = pcie.len() as i32; + Ok(words.iter().flat_map(|w| w.to_le_bytes()).collect()) +} + +pub(super) fn span_layer(span: &ResidentExpertBankSpan) -> Option { + match span.role() { + TensorRole::Layer { layer, .. } => Some(usize::from(layer)), + _ => None, + } +} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs new file mode 100644 index 00000000..d94828b3 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_gpu_plan/impl_schedule_originalverifycpusink.rs @@ -0,0 +1,249 @@ +//! Moved out of the parent module by STRA-338: impl schedule_OriginalVerifyCpuSink, fn dma_options. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> { + /// The plan block's entry capacity (`GpuPlanSink::cap` = `max_t * k`). + pub fn plan_capacity(&self) -> usize { + let g = self.bank.geometry(); + g.max_t * g.k + } + /// Staging blobs of this group (`staging_cap`: 16, or 8 in a split window). + pub fn staging_capacity(&self) -> usize { + staging_blobs_per_group(self.groups) + } + /// Whether the PCIe copies of this group have landed (flag B reached this group's ring value): a read of one + /// mapped host word, for the share controller to see which leg of a layer finishes last. + pub fn copies_landed(&self) -> Result { + let b = self.bank.physical.mapped[12].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + Ok(b.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)? >= self.ring) + } + /// The routed ids of this group's rows (`rows * k`), as the doorbell published them. + pub(super) fn group_ids(&self) -> Result> { + let g = self.bank.geometry(); + let mapped = self.bank.physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let mapped = mapped.as_ref().ok_or(Error::ContextPoisoned)?; + let mut ids = Vec::new(); + ids.try_reserve_exact(self.rows * g.k).map_err(|_| Error::HostAllocation)?; + for i in 0..self.rows * g.k { + ids.push(mapped.read_u32((self.first * g.k + i) * 4)? as i32); + } + Ok(ids) + } + + /// Publish this group's GPU plan and raise flag A; stage its PCIe share by DMA on `copy` and raise flag B + /// after it (or at once). Call at most once per group, before the CPU's own share is written; the run loop + /// then skips its empty plan. A refusal publishes nothing (the run loop's empty plan follows, and the pool + /// must then fail the group). + pub fn publish_gpu_plan( + &mut self, + plan: &OriginalVerifyGpuPlan, + cache: &OriginalExpertCache<'ctx>, + pcie: Option>, + copy: &mut OriginalGpuStream<'ctx>, + ) -> Result<()> { + let context = self.bank.physical.context; + self.bank.validate_context(context)?; + cache.validate_file_source_context(context)?; + copy.validate_context(context)?; + let g = self.bank.geometry(); + let layout = PlanLayout::new(g.max_t * g.k); + let cap = g.max_t * g.k; + let a = self.bank.physical.mapped[11] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0)?; + if a >= self.ring { + return Err(Error::InvalidQwenShape); + } + let ids = self.group_ids()?; + // VRAM groups: a completed slot owned by the routed expert of every entry, in this layer. + let mut vram = Vec::new(); + vram.try_reserve_exact(plan.vram.len()).map_err(|_| Error::HostAllocation)?; + for (slot, entries) in &plan.vram { + let (layer, expert) = cache.slot_owner(*slot).ok_or(Error::InvalidQwenShape)?; + if layer != self.layer || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(expert as i32)) { + return Err(Error::InvalidQwenShape); + } + let (handle, _) = cache.completed_slot(*slot)?; + vram.push((handle.qwen_address(), entries.as_slice())); + } + // PCIe groups: staging slot q of this group's half, each the bank spans of that entry's expert. + let per = staging_blobs_per_group(self.groups); + let mut stride = 0usize; + let spans = match &pcie { + Some(source) => source.spans, + None => &[], + }; + if spans.len() != plan.pcie.len() || plan.pcie.len() > per.min(MAX_PCIE_FETCHES) { + return Err(Error::InvalidQwenShape); + } + for (q, entries) in plan.pcie.iter().enumerate() { + let s = &spans[q]; + let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; + if !source.bank.cache_context_matches(context) + || !source.bank.eligible(s) + || span_layer(&s[0]) != Some(self.layer) + || entries.iter().any(|&i| ids.get(usize::from(i)).copied() != Some(s[0].expert() as i32)) + { + return Err(Error::InvalidQwenShape); + } + let bytes = s.iter().try_fold(0usize, |n, x| n.checked_add(x.bytes().len()).ok_or(Error::InvalidSize))?; + if bytes == 0 || bytes > g.max_expert_blob || (stride != 0 && bytes != stride) { + return Err(Error::InvalidQwenShape); + } + stride = bytes; + } + let staging = if plan.pcie.is_empty() { + 0 + } else { + self.bank.physical.span("staging", self.group * per * g.max_expert_blob, per * g.max_expert_blob)? + }; + let kernel = self.bank.pcie_mode == 2; + // The copy kernel (pcie mode 2) reads every PCIe expert's three spans through their device aliases: each must + // have exactly the length the graphs copy for this layer. + let mut aliases: Vec<[u64; 3]> = Vec::new(); + if kernel && !plan.pcie.is_empty() { + let roles = self + .bank + .pcie_roles + .as_ref() + .and_then(|r| r.get(self.layer)) + .copied() + .ok_or(Error::InvalidQwenShape)?; + let source = pcie.as_ref().ok_or(Error::InvalidQwenShape)?; + if 3 * plan.pcie.len() > cap { + return Err(Error::InvalidQwenShape); + } + aliases.try_reserve_exact(spans.len()).map_err(|_| Error::HostAllocation)?; + for s in spans { + let mut a = [0u64; 3]; + for (r, part) in s.iter().enumerate() { + if part.bytes().len() != roles[r] { + return Err(Error::InvalidQwenShape); + } + a[r] = source.bank.pcie_alias(part)?; + } + aliases.push(a); + } + } + let pcie_ptrs: Vec<(u64, &[u16])> = plan + .pcie + .iter() + .enumerate() + .map(|(q, e)| (if kernel { aliases[q][0] } else { staging + (q * stride) as u64 }, e.as_slice())) + .collect(); + let mut block = encode_plan_block(&layout, cap, g.k, self.rows * g.k, &vram, &pcie_ptrs)?; + // pcie mode 2: `ptr2[3 q + r]` = span r of PCIe group q; the graph's copy kernel stages them and rebases ptr2[q]. + for (q, a) in aliases.iter().enumerate() { + for (r, &alias) in a.iter().enumerate() { + let at = (layout.ptr2 + 2 * (3 * q + r)) * 4; + block[at..at + 8].copy_from_slice(&alias.to_le_bytes()); + } + } + { + let m = &self.bank.physical.mapped; + let mut slot = m[14].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + slot.as_mut().ok_or(Error::ContextPoisoned)?.write(self.group * layout.mapped_stride() * 4, &block)?; + m[11] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, self.ring)?; + } + let flag_b = self.bank.physical.mapped[12] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .host_address(0, 4)?; + if kernel { + // No host CUDA call inside the window (generate.cpp's reason for `--pcie-mode kernel`): the copy kernel + // reads the registered bytes after flag B, so the bank stays retained until the window's fence. + if !plan.pcie.is_empty() { + self.bank.retain_pcie_source(Rc::clone(pcie.as_ref().ok_or(Error::InvalidQwenShape)?.bank))?; + } + return self.bank.physical.mapped[12] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .raise_u32(0, self.ring); + } + match pcie { + None => self.bank.physical.mapped[12] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .raise_u32(0, self.ring), + Some(source) => { + if !plan.pcie.is_empty() { + // The bank's registered bytes are read by the copy engine after this call returns: the bank + // stays retained by the verifier until the window's copy-stream fence. + self.bank.retain_pcie_source(Rc::clone(source.bank))?; + } + let (many, batch, write) = dma_options(); + if many { + let mut pieces: Vec<(u64, &[u8])> = Vec::new(); + for (q, s) in spans.iter().enumerate() { + let mut offset = staging + (q * stride) as u64; + for part in s { + let bytes = source.bank.cache_source(part)?; + for (at, n) in source.bank.copy_pieces(bytes) { + pieces.push((offset + at as u64, &bytes[at..at + n])); + } + offset += bytes.len() as u64; + } + } + if !pieces.is_empty() { + copy.enqueue_copy_h2d_many(&pieces, batch)?; + } + } else { + for (q, s) in spans.iter().enumerate() { + let mut offset = staging + (q * stride) as u64; + for part in s { + let bytes = source.bank.cache_source(part)?; + for (at, n) in source.bank.copy_pieces(bytes) { + copy.enqueue_copy_h2d(offset + at as u64, &bytes[at..at + n])?; + } + offset += bytes.len() as u64; + } + } + } + if write { + let device_b = self.bank.physical.mapped[12] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .address(0, 4)?; + return copy.enqueue_raise_flag(flag_b, device_b, self.ring); + } + copy.enqueue_raise_u32(flag_b, self.ring) + } + } + } +} + +/// DMA staging options (`--pcie-mode dma`), read once. All three are on by default except where noted (job 981: +6 % over the +/// per-piece path on the 5090): `LELEKA_PCIE_DMA_MANY=off` goes back to one driver entry per piece, `LELEKA_PCIE_DMA_BATCH=off` to one +/// `cuMemcpyBatchAsync`-free loop inside the entry, `LELEKA_PCIE_FLAGB=host` raises flag B with a host callback instead of +/// `cuStreamWriteValue32`. A driver without the batch / write calls takes the loop / host callback by itself. +/// +/// The batch call is off by default on native Windows and under WSL2: on the RTX 3080 laptop `cuMemcpyBatchAsync_v2` from page-locked +/// host memory raises CUDA error 700 for any piece, source access order or registration flag, which killed the first decode window +/// of every request with a PCIe share (docs/windows.md, "PCIe tier on the laptop"; `pcie_copy_gpu_raw_batch_page_locked` repeats the +/// check). The stream write of flag B is also opt-in under WSL2 only. `=on` / `=write` force either call. +pub(crate) fn dma_options() -> (bool, bool, bool) { + static OPTIONS: std::sync::OnceLock<(bool, bool, bool)> = std::sync::OnceLock::new(); + *OPTIONS.get_or_init(|| { + let wsl = std::fs::read_to_string("/proc/sys/kernel/osrelease") + .is_ok_and(|v| v.to_ascii_lowercase().contains("microsoft")); + dma_options_for(wsl, cfg!(windows), |name| std::env::var(name).unwrap_or_default()) + }) +} diff --git a/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs b/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs index 1532c9c3..5b0b9717 100644 --- a/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs +++ b/crates/cuda-driver/src/original_verify_gpu_plan/tests.rs @@ -8,14 +8,27 @@ fn words(bytes: &[u8]) -> Vec { #[test] fn the_batch_copy_is_off_on_windows_and_wsl_and_the_switches_still_force_it() { - let env = |pairs: &'static [(&'static str, &'static str)]| move |name: &str| pairs.iter().find(|p| p.0 == name).map_or(String::new(), |p| p.1.to_string()); + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| pairs.iter().find(|p| p.0 == name).map_or(String::new(), |p| p.1.to_string()) + }; // (many, batch, flag B by stream write) assert_eq!(dma_options_for(false, false, env(&[])), (true, true, true), "Linux keeps everything on"); - assert_eq!(dma_options_for(false, true, env(&[])), (true, false, true), "native Windows: no batch, stream write kept"); + assert_eq!( + dma_options_for(false, true, env(&[])), + (true, false, true), + "native Windows: no batch, stream write kept" + ); assert_eq!(dma_options_for(true, false, env(&[])), (true, false, false), "WSL2: neither"); assert_eq!(dma_options_for(false, true, env(&[("LELEKA_PCIE_DMA_BATCH", "on")])).1, true); assert_eq!(dma_options_for(true, false, env(&[("LELEKA_PCIE_FLAGB", "write")])).2, true); - assert_eq!(dma_options_for(false, false, env(&[("LELEKA_PCIE_DMA_BATCH", "off"), ("LELEKA_PCIE_DMA_MANY", "off"), ("LELEKA_PCIE_FLAGB", "host")])), (false, false, false)); + assert_eq!( + dma_options_for( + false, + false, + env(&[("LELEKA_PCIE_DMA_BATCH", "off"), ("LELEKA_PCIE_DMA_MANY", "off"), ("LELEKA_PCIE_FLAGB", "host")]) + ), + (false, false, false) + ); } #[test] diff --git a/crates/cuda-driver/src/original_verify_layout.rs b/crates/cuda-driver/src/original_verify_layout.rs index 0b8b0426..8dfb5dcc 100644 --- a/crates/cuda-driver/src/original_verify_layout.rs +++ b/crates/cuda-driver/src/original_verify_layout.rs @@ -1,57 +1,193 @@ //! Literal Verifier::init count/carve. Spans describe bytes, never completion. -use crate::{Error,Result}; -#[derive(Clone,Copy,Debug)] -pub struct OriginalVerifyGeometry{ - pub max_t:usize,pub n:usize,pub hc:usize,pub lr:usize,pub ff:usize,pub experts:usize,pub k:usize, - pub channels:usize,pub value_heads:usize,pub key_heads:usize,pub heads:usize,pub kv_heads:usize, - pub head_dim:usize,pub index_heads:usize,pub index_dim:usize,pub index_block:usize, - pub selection:usize,pub max_cells:usize,pub vocabulary:usize,pub max_expert_blob:usize, +use crate::{Error, Result}; +#[derive(Clone, Copy, Debug)] +pub struct OriginalVerifyGeometry { + pub max_t: usize, + pub n: usize, + pub hc: usize, + pub lr: usize, + pub ff: usize, + pub experts: usize, + pub k: usize, + pub channels: usize, + pub value_heads: usize, + pub key_heads: usize, + pub heads: usize, + pub kv_heads: usize, + pub head_dim: usize, + pub index_heads: usize, + pub index_dim: usize, + pub index_block: usize, + pub selection: usize, + pub max_cells: usize, + pub vocabulary: usize, + pub max_expert_blob: usize, } -#[derive(Clone,Copy,Debug)] -pub struct OriginalVerifySpan{pub name:&'static str,pub offset:usize,pub bytes:usize} -pub struct OriginalVerifyLayout{pub geometry:OriginalVerifyGeometry,pub spans:Vec,pub bytes:usize,pub plan_i32:usize,pub mapped_bytes:[usize;15]} -fn add(a:usize,b:usize)->Result{a.checked_add(b).ok_or(Error::InvalidSize)} -fn mul(a:usize,b:usize)->Result{a.checked_mul(b).ok_or(Error::InvalidSize)} -fn align(n:usize,a:usize)->Result{Ok(add(n,a-1)?&!(a-1))} -impl OriginalVerifyGeometry{ - pub fn validate(self)->Result<()>{ - if !(2..=8).contains(&self.max_t)||self.n!=2560||self.hc!=4||self.lr!=320||self.ff!=640||self.experts!=512||self.k!=10||self.channels!=10240||self.value_heads!=48||self.key_heads!=16||self.heads!=24||self.kv_heads!=2||self.head_dim!=256||self.index_heads!=4||self.index_dim!=128||self.index_block!=4||self.selection!=2051||self.max_cellscrate::MAX_CONTEXT_CELLS||self.max_cells%4!=0||self.vocabulary==0||self.vocabulary>i32::MAX as usize||self.max_expert_blob==0||self.max_expert_blob>8*1024*1024||self.max_expert_blob%16!=0{return Err(Error::InvalidQwenShape)}Ok(()) - } +#[derive(Clone, Copy, Debug)] +pub struct OriginalVerifySpan { + pub name: &'static str, + pub offset: usize, + pub bytes: usize, } -impl OriginalVerifyLayout{ - pub fn new(g:OriginalVerifyGeometry)->Result{ - g.validate()?;let t=g.max_t;let cap=t*g.k;let ptr_off=align(4+(cap+1)+cap+cap,2)?; - let plan_i32=add(add(ptr_off,4*cap)?,cap+2)?; - let max_in=g.n.max(g.value_heads*128).max(g.heads*g.head_dim); - let scratch_floats=add(mul(g.selection.div_ceil(64),g.heads*(g.head_dim+2))?,64)?; - let max_blocks=g.max_cells/g.index_block+2; - let s2=add(add(align(cap*2*g.ff*4,16)?,align(cap*(g.ff/32)*34,16)?)?,add(2*align(cap*(g.ff/32)*4,16)?,align(g.n/32*4,16)?)?)?; - let native=add(3*align(cap*g.ff*4,256)?,align(cap*(g.ff/32)*36,256)?)?; - let mut spans=Vec::new();spans.try_reserve_exact(64).map_err(|_|Error::HostAllocation)?;let mut used=0usize; - let mut take=|name,count,width|->Result<()>{let bytes=mul(count,width)?;let offset=align(used,256)?;used=add(offset,bytes)?;spans.push(OriginalVerifySpan{name,offset,bytes});Ok(())}; - for(name,count,width)in[ - ("tok",t,4),("step",t*4,4),("pos",t*(g.heads+g.kv_heads+g.index_heads),4),("commit",2+t,4), - ("ple",t*g.n,4),("emb",t*g.n,4),("R",t*g.hc*g.n,4),("mixed",t*g.n,4),("bo",t*g.n,4), - ("inj",t*g.hc,4),("inj2",t*g.hc,4),("lo",t*g.lr,4),("rs",t*g.hc,4),("xn",t*g.hc*g.n,4), - ("xq",t*(max_in/32)*36,1),("qkv_L",36*t*g.channels,4),("h_L",36*t*g.channels,4), - ("gate_L",36*t*g.value_heads,4),("beta_L",36*t*g.value_heads,4), - ("z",t*g.value_heads*128,4),("y",t*g.value_heads*128,4),("y_dummy",t*g.value_heads*128,4), - ("qfull",t*g.heads*2*g.head_dim,4),("qcur",t*g.heads*g.head_dim,4), - ("kcur",t*g.kv_heads*g.head_dim,4),("vcur",t*g.kv_heads*g.head_dim,4), - ("idx_raw_L",12*t*g.index_dim,4),("qidx",t*g.index_heads*g.index_dim,4), - ("scores",t*max_blocks,4),("sel",t*g.selection,4),("attn",t*g.heads*g.head_dim,4), - ("attn32",t*g.heads*g.head_dim,4),("attn_scratch",t*scratch_floats,4), - ("tail_snap",12*(g.index_block-1)*g.index_dim,4),("logits",t*g.experts,4), - ("w",t*g.k,4),("ids",t*g.k,4),("shared",t*g.n,4),("parts",t*g.k*g.n,4), - ("hit_out",t*g.k*g.n,4),("hit_slot",t*g.k,4),("hit_dst",t*g.k,4),("hit_count",4,4), - ("plan",2*(plan_i32+16),4),("staging",16*g.max_expert_blob,1), - ("hit_xq",t*(g.n/32)*34,1),("hit_xs",t*(g.n/32),4),("nat_xq",t*(g.n/32)*36,1), - ("hit_scratch",s2.max(native),1),("head_mixed",t*g.n,4),("head_inj",g.hc,4), - ("sh_bf16",t*g.n,2),("sh_gate",t*g.ff,4),("sh_up",t*g.ff,4),("sh_g",t+4,4), - ("head_logits",t*g.vocabulary,4),("hist_snap",t*9*g.hc*g.n,4), - ]{take(name,count,width)?;}if std::env::var_os("LELEKA_TRACE_LADDER").is_some(){take("dbg_ladder",96*t*g.hc*g.n,4)?;}drop(take); - let mapped_bytes=[t*4,t*4*4,t*(g.heads+g.kv_heads+g.index_heads)*4,(2+t)*4+16,t*g.n*4,t*4+16,t*g.n*4,t*g.k*4,t*g.k*4,64,64,64,64,t*g.k*g.n*4,plan_i32*4*2+64]; - Ok(Self{geometry:g,spans,bytes:align(used,256)?,plan_i32,mapped_bytes}) - } - pub fn span(&self,name:&str)->Result{self.spans.iter().copied().find(|s|s.name==name).ok_or(Error::InvalidQwenShape)} +pub struct OriginalVerifyLayout { + pub geometry: OriginalVerifyGeometry, + pub spans: Vec, + pub bytes: usize, + pub plan_i32: usize, + pub mapped_bytes: [usize; 15], +} +fn add(a: usize, b: usize) -> Result { + a.checked_add(b).ok_or(Error::InvalidSize) +} +fn mul(a: usize, b: usize) -> Result { + a.checked_mul(b).ok_or(Error::InvalidSize) +} +fn align(n: usize, a: usize) -> Result { + Ok(add(n, a - 1)? & !(a - 1)) +} +impl OriginalVerifyGeometry { + pub fn validate(self) -> Result<()> { + if !(2..=8).contains(&self.max_t) + || self.n != 2560 + || self.hc != 4 + || self.lr != 320 + || self.ff != 640 + || self.experts != 512 + || self.k != 10 + || self.channels != 10240 + || self.value_heads != 48 + || self.key_heads != 16 + || self.heads != 24 + || self.kv_heads != 2 + || self.head_dim != 256 + || self.index_heads != 4 + || self.index_dim != 128 + || self.index_block != 4 + || self.selection != 2051 + || self.max_cells < self.max_t + || self.max_cells > crate::MAX_CONTEXT_CELLS + || self.max_cells % 4 != 0 + || self.vocabulary == 0 + || self.vocabulary > i32::MAX as usize + || self.max_expert_blob == 0 + || self.max_expert_blob > 8 * 1024 * 1024 + || self.max_expert_blob % 16 != 0 + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } +} +impl OriginalVerifyLayout { + pub fn new(g: OriginalVerifyGeometry) -> Result { + g.validate()?; + let t = g.max_t; + let cap = t * g.k; + let ptr_off = align(4 + (cap + 1) + cap + cap, 2)?; + let plan_i32 = add(add(ptr_off, 4 * cap)?, cap + 2)?; + let max_in = g.n.max(g.value_heads * 128).max(g.heads * g.head_dim); + let scratch_floats = add(mul(g.selection.div_ceil(64), g.heads * (g.head_dim + 2))?, 64)?; + let max_blocks = g.max_cells / g.index_block + 2; + let s2 = add( + add(align(cap * 2 * g.ff * 4, 16)?, align(cap * (g.ff / 32) * 34, 16)?)?, + add(2 * align(cap * (g.ff / 32) * 4, 16)?, align(g.n / 32 * 4, 16)?)?, + )?; + let native = add(3 * align(cap * g.ff * 4, 256)?, align(cap * (g.ff / 32) * 36, 256)?)?; + let mut spans = Vec::new(); + spans.try_reserve_exact(64).map_err(|_| Error::HostAllocation)?; + let mut used = 0usize; + let mut take = |name, count, width| -> Result<()> { + let bytes = mul(count, width)?; + let offset = align(used, 256)?; + used = add(offset, bytes)?; + spans.push(OriginalVerifySpan { name, offset, bytes }); + Ok(()) + }; + for (name, count, width) in [ + ("tok", t, 4), + ("step", t * 4, 4), + ("pos", t * (g.heads + g.kv_heads + g.index_heads), 4), + ("commit", 2 + t, 4), + ("ple", t * g.n, 4), + ("emb", t * g.n, 4), + ("R", t * g.hc * g.n, 4), + ("mixed", t * g.n, 4), + ("bo", t * g.n, 4), + ("inj", t * g.hc, 4), + ("inj2", t * g.hc, 4), + ("lo", t * g.lr, 4), + ("rs", t * g.hc, 4), + ("xn", t * g.hc * g.n, 4), + ("xq", t * (max_in / 32) * 36, 1), + ("qkv_L", 36 * t * g.channels, 4), + ("h_L", 36 * t * g.channels, 4), + ("gate_L", 36 * t * g.value_heads, 4), + ("beta_L", 36 * t * g.value_heads, 4), + ("z", t * g.value_heads * 128, 4), + ("y", t * g.value_heads * 128, 4), + ("y_dummy", t * g.value_heads * 128, 4), + ("qfull", t * g.heads * 2 * g.head_dim, 4), + ("qcur", t * g.heads * g.head_dim, 4), + ("kcur", t * g.kv_heads * g.head_dim, 4), + ("vcur", t * g.kv_heads * g.head_dim, 4), + ("idx_raw_L", 12 * t * g.index_dim, 4), + ("qidx", t * g.index_heads * g.index_dim, 4), + ("scores", t * max_blocks, 4), + ("sel", t * g.selection, 4), + ("attn", t * g.heads * g.head_dim, 4), + ("attn32", t * g.heads * g.head_dim, 4), + ("attn_scratch", t * scratch_floats, 4), + ("tail_snap", 12 * (g.index_block - 1) * g.index_dim, 4), + ("logits", t * g.experts, 4), + ("w", t * g.k, 4), + ("ids", t * g.k, 4), + ("shared", t * g.n, 4), + ("parts", t * g.k * g.n, 4), + ("hit_out", t * g.k * g.n, 4), + ("hit_slot", t * g.k, 4), + ("hit_dst", t * g.k, 4), + ("hit_count", 4, 4), + ("plan", 2 * (plan_i32 + 16), 4), + ("staging", 16 * g.max_expert_blob, 1), + ("hit_xq", t * (g.n / 32) * 34, 1), + ("hit_xs", t * (g.n / 32), 4), + ("nat_xq", t * (g.n / 32) * 36, 1), + ("hit_scratch", s2.max(native), 1), + ("head_mixed", t * g.n, 4), + ("head_inj", g.hc, 4), + ("sh_bf16", t * g.n, 2), + ("sh_gate", t * g.ff, 4), + ("sh_up", t * g.ff, 4), + ("sh_g", t + 4, 4), + ("head_logits", t * g.vocabulary, 4), + ("hist_snap", t * 9 * g.hc * g.n, 4), + ] { + take(name, count, width)?; + } + if std::env::var_os("LELEKA_TRACE_LADDER").is_some() { + take("dbg_ladder", 96 * t * g.hc * g.n, 4)?; + } + drop(take); + let mapped_bytes = [ + t * 4, + t * 4 * 4, + t * (g.heads + g.kv_heads + g.index_heads) * 4, + (2 + t) * 4 + 16, + t * g.n * 4, + t * 4 + 16, + t * g.n * 4, + t * g.k * 4, + t * g.k * 4, + 64, + 64, + 64, + 64, + t * g.k * g.n * 4, + plan_i32 * 4 * 2 + 64, + ]; + Ok(Self { geometry: g, spans, bytes: align(used, 256)?, plan_i32, mapped_bytes }) + } + pub fn span(&self, name: &str) -> Result { + self.spans.iter().copied().find(|s| s.name == name).ok_or(Error::InvalidQwenShape) + } } diff --git a/crates/cuda-driver/src/original_verify_logits.rs b/crates/cuda-driver/src/original_verify_logits.rs index b61b958e..56a97b01 100644 --- a/crates/cuda-driver/src/original_verify_logits.rs +++ b/crates/cuda-driver/src/original_verify_logits.rs @@ -103,10 +103,7 @@ pub fn top_k(row: &[f32], k: usize) -> Vec<(i32, f64)> { let lse = maxv + sum.ln(); let mut order: Vec = (0..row.len() as i32).collect(); order.sort_by(|&a, &b| { - row[b as usize] - .partial_cmp(&row[a as usize]) - .unwrap_or(std::cmp::Ordering::Equal) - .then(a.cmp(&b)) + row[b as usize].partial_cmp(&row[a as usize]).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b)) }); order.truncate(k); order.into_iter().map(|id| (id, f64::from(row[id as usize]) - lse)).collect() diff --git a/crates/cuda-driver/src/original_verify_mapped.rs b/crates/cuda-driver/src/original_verify_mapped.rs index 8fe57ed3..2d8b3a37 100644 --- a/crates/cuda-driver/src/original_verify_mapped.rs +++ b/crates/cuda-driver/src/original_verify_mapped.rs @@ -1,11 +1,7 @@ //! Private fixed mapped-host allocation. Caller holds actual Context and drains before CPU access/free. use crate::{Error, Result}; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; use std::ffi::c_void; @@ -23,14 +19,7 @@ mod enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -45,22 +34,52 @@ mod enabled { /// fold over the exponent bits so it vectorizes (the per-element early exit of `any` does not); it runs over a whole /// verify group's CPU output (rows x top-10 x hidden floats) once per layer on the decode critical path. /// `LELEKA_SINK_SCAN=legacy` (A/B arm) keeps the element-wise `any` scan. - pub(crate) fn all_finite(rows:&[f32])->bool{ - static LEGACY:std::sync::OnceLock=std::sync::OnceLock::new(); - if *LEGACY.get_or_init(||std::env::var("LELEKA_SINK_SCAN").as_deref()==Ok("legacy")){return !rows.iter().any(|v|!v.is_finite())} - let mut bad=0u32; - for chunk in rows.chunks(256){let mut m=0u32;for v in chunk{m|=u32::from(v.to_bits()&0x7f80_0000==0x7f80_0000);}bad|=m;} - bad==0 + pub(crate) fn all_finite(rows: &[f32]) -> bool { + static LEGACY: std::sync::OnceLock = std::sync::OnceLock::new(); + if *LEGACY.get_or_init(|| std::env::var("LELEKA_SINK_SCAN").as_deref() == Ok("legacy")) { + return !rows.iter().any(|v| !v.is_finite()); + } + let mut bad = 0u32; + for chunk in rows.chunks(256) { + let mut m = 0u32; + for v in chunk { + m |= u32::from(v.to_bits() & 0x7f80_0000 == 0x7f80_0000); + } + bad |= m; + } + bad == 0 } #[cfg(test)] #[test] - fn all_finite_is_the_is_finite_predicate(){ - let specials=[0.0f32,-0.0,1.0,-3.0e38,f32::MAX,f32::MIN_POSITIVE,1e-45,f32::INFINITY,f32::NEG_INFINITY,f32::NAN,-f32::NAN,f32::from_bits(0x7f80_0001),f32::from_bits(0xffc0_0000)]; - for len in [0usize,1,7,255,256,257,1000]{ - for at in [0usize,len/2,len.saturating_sub(1)]{ - for &s in &specials{ - let mut v=vec![0.5f32;len];if len>0{v[at]=s;} - assert_eq!(all_finite(&v),!v.iter().any(|x|!x.is_finite()),"len {len} at {at} value {:#x}",s.to_bits()); + fn all_finite_is_the_is_finite_predicate() { + let specials = [ + 0.0f32, + -0.0, + 1.0, + -3.0e38, + f32::MAX, + f32::MIN_POSITIVE, + 1e-45, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + -f32::NAN, + f32::from_bits(0x7f80_0001), + f32::from_bits(0xffc0_0000), + ]; + for len in [0usize, 1, 7, 255, 256, 257, 1000] { + for at in [0usize, len / 2, len.saturating_sub(1)] { + for &s in &specials { + let mut v = vec![0.5f32; len]; + if len > 0 { + v[at] = s; + } + assert_eq!( + all_finite(&v), + !v.iter().any(|x| !x.is_finite()), + "len {len} at {at} value {:#x}", + s.to_bits() + ); } } } @@ -69,15 +88,15 @@ mod enabled { library: Option, host: Option, alias: u64, - bytes:usize, + bytes: usize, free: Free, } impl MappedAllocation { - pub(crate) fn new(bytes:usize) -> Result { - if bytes==0{return Err(Error::InvalidSize);} - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + pub(crate) fn new(bytes: usize) -> Result { + if bytes == 0 { + return Err(Error::InvalidSize); + } + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -89,22 +108,13 @@ mod enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - bytes, - free, - }; - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, bytes, free }; + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -112,12 +122,14 @@ mod enabled { // Verifier mapped() uses the same full host memset before publication. Ok(owner) } - pub(crate) fn initialize_zero(&mut self)->Result<()>{let p=self.range(0,self.bytes)?;unsafe{std::ptr::write_bytes(p as *mut u8,0,self.bytes)};Ok(())} + pub(crate) fn initialize_zero(&mut self) -> Result<()> { + let p = self.range(0, self.bytes)?; + unsafe { std::ptr::write_bytes(p as *mut u8, 0, self.bytes) }; + Ok(()) + } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } /// Host-side address of a fixed mapped range, for the thread-safe live /// release/diagnostic registry. The owner deregisters before `close`. @@ -139,26 +151,85 @@ mod enabled { Ok(()) } - pub(crate) fn read_u32(&self,offset:usize)->Result{let p=self.range(offset,4)?;if p%4!=0{return Err(Error::InvalidSize)}Ok(unsafe{std::ptr::read_volatile(p as *const u32)})} - pub(crate) fn publish_u32(&mut self,offset:usize,value:u32)->Result<()>{let p=self.range(offset,4)?;if p%4!=0{return Err(Error::InvalidSize)}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);unsafe{std::ptr::write_volatile(p as *mut u32,value)};Ok(())} - pub(crate) fn raise_u32(&mut self,offset:usize,value:u32)->Result<()>{let p=self.range(offset,4)?;if p%4!=0{return Err(Error::InvalidSize)}let atomic=unsafe{&*(p as *const std::sync::atomic::AtomicU32)};atomic.fetch_max(value,std::sync::atomic::Ordering::SeqCst);Ok(())} + pub(crate) fn read_u32(&self, offset: usize) -> Result { + let p = self.range(offset, 4)?; + if p % 4 != 0 { + return Err(Error::InvalidSize); + } + Ok(unsafe { std::ptr::read_volatile(p as *const u32) }) + } + pub(crate) fn publish_u32(&mut self, offset: usize, value: u32) -> Result<()> { + let p = self.range(offset, 4)?; + if p % 4 != 0 { + return Err(Error::InvalidSize); + } + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + unsafe { std::ptr::write_volatile(p as *mut u32, value) }; + Ok(()) + } + pub(crate) fn raise_u32(&mut self, offset: usize, value: u32) -> Result<()> { + let p = self.range(offset, 4)?; + if p % 4 != 0 { + return Err(Error::InvalidSize); + } + let atomic = unsafe { &*(p as *const std::sync::atomic::AtomicU32) }; + atomic.fetch_max(value, std::sync::atomic::Ordering::SeqCst); + Ok(()) + } #[allow(clippy::too_many_arguments)] // Exact borrowed mapped operand boundary. - pub(crate) fn with_cpu_rows(activation:&Self,ids:&Self,weights:&Self,first:usize,rows:usize,n:usize,k:usize,consume:impl FnOnce(&[f32],&[i32],&[f32])->Result)->Result{ - let x=activation.range(first.checked_mul(n).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?,rows.checked_mul(n).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?)?; - let i=ids.range(first.checked_mul(k).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?,rows.checked_mul(k).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?)?; - let w=weights.range(first.checked_mul(k).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?,rows.checked_mul(k).and_then(|x|x.checked_mul(4)).ok_or(Error::InvalidSize)?)?; - if x%4!=0||i%4!=0||w%4!=0{return Err(Error::InvalidSize)} + pub(crate) fn with_cpu_rows( + activation: &Self, + ids: &Self, + weights: &Self, + first: usize, + rows: usize, + n: usize, + k: usize, + consume: impl FnOnce(&[f32], &[i32], &[f32]) -> Result, + ) -> Result { + let x = activation.range( + first.checked_mul(n).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + rows.checked_mul(n).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + )?; + let i = ids.range( + first.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + rows.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + )?; + let w = weights.range( + first.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + rows.checked_mul(k).and_then(|x| x.checked_mul(4)).ok_or(Error::InvalidSize)?, + )?; + if x % 4 != 0 || i % 4 != 0 || w % 4 != 0 { + return Err(Error::InvalidSize); + } // The real doorbell seq was observed first. The captured GPU cannot // overwrite this group's mapped rows until its actual host flags. std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); - consume(unsafe{std::slice::from_raw_parts(x as *const f32,rows*n)},unsafe{std::slice::from_raw_parts(i as *const i32,rows*k)},unsafe{std::slice::from_raw_parts(w as *const f32,rows*k)}) + consume( + unsafe { std::slice::from_raw_parts(x as *const f32, rows * n) }, + unsafe { std::slice::from_raw_parts(i as *const i32, rows * k) }, + unsafe { std::slice::from_raw_parts(w as *const f32, rows * k) }, + ) } - pub(crate) fn with_cpu_output(&mut self,offset:usize,count:usize,produce:impl FnOnce(&mut [f32])->Result)->Result{ - let p=self.range(offset,count.checked_mul(4).ok_or(Error::InvalidSize)?)?;if p%4!=0{return Err(Error::InvalidSize)} + pub(crate) fn with_cpu_output( + &mut self, + offset: usize, + count: usize, + produce: impl FnOnce(&mut [f32]) -> Result, + ) -> Result { + let p = self.range(offset, count.checked_mul(4).ok_or(Error::InvalidSize)?)?; + if p % 4 != 0 { + return Err(Error::InvalidSize); + } // Only the controller's just-observed group doorbell can construct // this borrow. GPU miss consumers still wait for its unpublished M. - let rows=unsafe{std::slice::from_raw_parts_mut(p as *mut f32,count)}; - let result=produce(rows)?;if !all_finite(rows){return Err(Error::NonFiniteMmqOutput("Original Verifier CPU misses"))}std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);Ok(result) + let rows = unsafe { std::slice::from_raw_parts_mut(p as *mut f32, count) }; + let result = produce(rows)?; + if !all_finite(rows) { + return Err(Error::NonFiniteMmqOutput("Original Verifier CPU misses")); + } + std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst); + Ok(result) } pub(crate) fn close(&mut self) -> Result<()> { if let Some(p) = self.host { @@ -179,11 +250,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::MappedAllocation; #[cfg(not(all( feature = "cuda-driver", @@ -197,7 +264,7 @@ pub(crate) struct MappedAllocation; target_pointer_width = "64" )))] impl MappedAllocation { - pub(crate) fn new(_bytes:usize) -> Result { + pub(crate) fn new(_bytes: usize) -> Result { Err(Error::UnsupportedPlatform) } pub(crate) fn address(&self, _: usize, _: usize) -> Result { @@ -209,9 +276,15 @@ impl MappedAllocation { pub(crate) fn host_address(&self, _: usize, _: usize) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn read_u32(&self,_:usize)->Result{Err(Error::UnsupportedPlatform)} - pub(crate) fn publish_u32(&mut self,_:usize,_:u32)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn raise_u32(&mut self,_:usize,_:u32)->Result<()>{Err(Error::UnsupportedPlatform)} + pub(crate) fn read_u32(&self, _: usize) -> Result { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn publish_u32(&mut self, _: usize, _: u32) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn raise_u32(&mut self, _: usize, _: u32) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn close(&mut self) -> Result<()> { Ok(()) } diff --git a/crates/cuda-driver/src/original_verify_schedule.rs b/crates/cuda-driver/src/original_verify_schedule.rs index 2a56d3d5..517fc476 100644 --- a/crates/cuda-driver/src/original_verify_schedule.rs +++ b/crates/cuda-driver/src/original_verify_schedule.rs @@ -2,270 +2,73 @@ //! the full native layer producers; this controller never substitutes prompt //! GEMM arithmetic or per-token forward calls for a verification window. use super::*; -use crate::{OriginalGpuStream,OriginalGpuEvent,OriginalGpuGraph,OriginalCapturePolicy,OriginalStreamKind,OriginalEventKind,NativeHeadSampling,NativeHeadSelection}; use crate::OriginalNativeHeadGraphResources; -use std::time::{Duration,Instant}; +use crate::{ + NativeHeadSampling, NativeHeadSelection, OriginalCapturePolicy, OriginalEventKind, OriginalGpuEvent, + OriginalGpuGraph, OriginalGpuStream, OriginalStreamKind, +}; use std::io::Write; -/// `STRATA_COMMIT_SYNC`, read once (it sat on the per-round commit path). -fn commit_sync_forced()->bool{static ON:std::sync::OnceLock=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var_os("STRATA_COMMIT_SYNC").is_some())} +use std::time::{Duration, Instant}; /// CPU source callback receives borrowed actual mapped layer rows. No tensor or /// source certificate is minted; Root keeps descriptor/cache owners through it. -pub struct OriginalVerifyCpuRows<'a>{pub layer:usize,pub group:usize,pub first_row:usize,pub activation:&'a [f32],pub ids:&'a [i32],pub route_weights:&'a [f32]} +pub struct OriginalVerifyCpuRows<'a> { + pub layer: usize, + pub group: usize, + pub first_row: usize, + pub activation: &'a [f32], + pub ids: &'a [i32], + pub route_weights: &'a [f32], +} /// Borrowed real mapped destination; CPU writes it directly before M publication. /// This cannot escape the actual group callback or publish flags independently. /// `layer`, `group`, `groups` and `ring` name the doorbell this callback serves; the GPU plan of the group /// (`publish_gpu_plan`, original_verify_gpu_plan.rs) is published through the same sink. -pub struct OriginalVerifyCpuSink<'a,'ctx>{pub(super) bank:&'a mut OriginalVerifyBank<'ctx>,pub(super) first:usize,pub(super) rows:usize,pub(super) layer:usize,pub(super) group:usize,pub(super) groups:usize,pub(super) ring:u32} -impl OriginalVerifyCpuSink<'_, '_>{pub fn with_output(&mut self,produce:impl FnOnce(&mut [f32])->Result)->Result{let g=self.bank.geometry();let mut m=self.bank.physical.mapped[13].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;m.as_mut().ok_or(Error::ContextPoisoned)?.with_cpu_output(self.first*g.k*g.n*4,self.rows*g.k*g.n,produce)}} -pub struct OriginalVerifyWindowResult{pub selection:NativeHeadSelection,pub generation:u64,pub first_position:usize,pub rows:usize} -pub struct OriginalVerifier<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>>{ - bank:Option>,compute:Option>,copy:Option>, - window:[Option>;8],commit:Option>,event:Option>, - split:bool,groups:[usize;8],commit_pending:bool,window_ready:bool,active:bool,failed:bool,windows:u64,commits:u64,resource_keys:Option<(usize,usize)>,completed_generation:Option,completed_ids:[i32;8], - registration:Option,released:bool,profile:OriginalVerifyProfile,test_stall:u64, +pub struct OriginalVerifyCpuSink<'a, 'ctx> { + pub(super) bank: &'a mut OriginalVerifyBank<'ctx>, + pub(super) first: usize, + pub(super) rows: usize, + pub(super) layer: usize, + pub(super) group: usize, + pub(super) groups: usize, + pub(super) ring: u32, } -impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx,R>{ - pub fn new(context:&'ctx Context<'ctx>,geometry:OriginalVerifyGeometry)->Result{ - let mut owner=Self{bank:None,compute:None,copy:None,window:std::array::from_fn(|_|None),commit:None,event:None,split:false,groups:[0;8],commit_pending:false,window_ready:false,active:false,failed:false,windows:0,commits:0,resource_keys:None,completed_generation:None,completed_ids:[0;8],registration:None,released:false,profile:OriginalVerifyProfile::default(),test_stall:0}; - let operation=(||{owner.bank=Some(context.original_verify_bank(geometry)?); - // #267 test hook, off unless set: withhold the last layer's flag in the N-th window (1-based). - owner.test_stall=std::env::var("STRATA_TEST_VERIFY_STALL").ok().and_then(|v|v.trim().parse::().ok()).unwrap_or(0); - owner.registration=Some(diag::Registration::new(owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.host_words()?));owner.copy=Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);owner.compute=Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?);owner.event=Some(context.original_gpu_event(OriginalEventKind::Completion)?);Ok(())})(); - if let Err(primary)=operation{return combine(Err(primary),owner.close_inner())}Ok(owner) - } - pub fn bank(&self)->Result<&OriginalVerifyBank<'ctx>>{self.bank.as_ref().ok_or(Error::ContextPoisoned)} - pub fn allocated_bytes(&self)->usize{self.bank.as_ref().map_or(0,OriginalVerifyBank::allocated_bytes)} - fn record_keys(&mut self,r:&R)->Result<()>{r.verifier_journal().validate_bank(self.bank()?)?;r.verifier_qsa().validate_context(self.bank()?.physical.context)?;let keys=(r.verifier_journal().canonical_identity(),r.verifier_qsa().identity());if self.resource_keys.is_some_and(|old|old!=keys){return Err(Error::InvalidQwenShape)}self.resource_keys=Some(keys);Ok(())} - /// `Verifier::set_pcie_mode` of the graphs about to be recorded (0 DMA, 2 copy kernel; 1, the mapped arena, is not - /// ported): fixed by the first recorded window, so `publish_gpu_plan` stages the way every graph reads. - pub(crate) fn set_pcie_mode(&mut self,mode:u8,roles:Option<[[usize;3];48]>)->Result<()>{if self.active||!matches!(mode,0|2)||(mode==2&&roles.is_none()){return Err(Error::InvalidQwenShape)}let recorded=self.window.iter().any(Option::is_some)||self.commit.is_some();let bank=self.bank.as_mut().ok_or(Error::ContextPoisoned)?;if recorded&&(bank.pcie_mode!=mode||bank.pcie_roles!=roles){return Err(Error::InvalidQwenShape)}bank.pcie_mode=mode;bank.pcie_roles=roles;Ok(())} - pub fn set_split(&mut self,on:bool)->Result<()>{if self.window.iter().any(Option::is_some)||self.active{return Err(Error::InvalidQwenShape)}self.split=on;Ok(())} - pub fn record_window(&mut self,t:usize,resources:R,record:impl FnOnce(&mut OriginalCapture<'_, 'ctx>,&mut R,usize)->Result<()>)->Result<()>{ - if self.failed||self.active||!(1..=self.bank()?.geometry().max_t).contains(&t)||self.window[t-1].is_some(){return Err(Error::InvalidQwenShape)}self.record_keys(&resources)?; - if resources.native_head_rows()?.rows()!=t||resources.native_head_rows()?.completed_logits()?.len()!=t*self.bank()?.geometry().vocabulary*4{return Err(Error::InvalidQwenShape)} - let groups=window_plan::window_groups(t,self.split);let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?; - let graph=stream.capture_owned(OriginalCapturePolicy::VerifierWindow,resources,|capture,r|{r.verifier_journal().capture_inputs(capture,t)?;record(capture,r,groups)})?; - if crate::host_profile::enabled(){eprintln!("DBG graph window t={t} groups={groups} nodes={:?}",graph.nodes());} - self.window[t-1]=Some(graph);self.groups[t-1]=groups;Ok(()) - } - pub fn record_commit(&mut self,resources:R,mut record_extra:impl FnMut(&mut OriginalCapture<'_, 'ctx>,&mut R,usize)->Result<()>)->Result<()>{ - if self.failed||self.active||self.commit.is_some(){return Err(Error::InvalidQwenShape)}self.record_keys(&resources)?; - // sm_120 only: the fused kernels have no sm_86 companion (ptx-sm86/MANIFEST.json), another card keeps the Original's commit graph - let fused_commit=crate::original_verify::draft::fused_commit()&&resources.verifier_journal().window_device_attribute(crate::original_verify::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?==12; - if fused_commit{resources.verifier_journal().load_draft_commit_asset()?;} - let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?; - self.commit=Some(stream.capture_owned(OriginalCapturePolicy::VerifierCommit,resources,|capture,r|{ - r.verifier_journal().capture_commit_begin(capture)?;let mut gi=0;let mut qi=0; - // draft-round: the layers are independent; one launch per kind (GDN, QSA) instead of 182 nodes. A QSA with retained angle tables keeps its per-layer commit. - if fused_commit{ - r.verifier_journal().capture_commit_gdn_fused(capture)?; - if r.verifier_qsa().capture_commit_fused(r.verifier_journal(),capture)?{ - for layer in (3..48).step_by(4){record_extra(capture,r,layer)?;} - if r.verifier_journal().ple.is_some(){r.verifier_journal().capture_ple_commit(capture)?;}return Ok(()) - } - for layer in 0..48{if layer%4==3{r.verifier_qsa().capture_commit_layer(r.verifier_journal(),capture,qi)?;record_extra(capture,r,layer)?;qi+=1}} - if r.verifier_journal().ple.is_some(){r.verifier_journal().capture_ple_commit(capture)?;}return Ok(()) - } - for layer in 0..48{if layer%4==3{r.verifier_qsa().capture_commit_layer(r.verifier_journal(),capture,qi)?;record_extra(capture,r,layer)?;qi+=1}else{r.verifier_journal().capture_commit_layer(capture,gi)?;gi+=1}} - if r.verifier_journal().ple.is_some(){r.verifier_journal().capture_ple_commit(capture)?;}Ok(()) - })?);if crate::host_profile::enabled(){eprintln!("DBG graph commit nodes={:?}",self.commit.as_ref().and_then(|g|g.nodes()));}Ok(()) - } - /// Cached real all-T graph; CPU/GPU split and mapped flag rings match Original. - /// Callback must finish actual expert/source work before returning. An error - /// releases every wait and drains both streams before preserving that primary. - pub fn run(&mut self,tokens:&[i32],position:usize,ple:Option<&[f32]>,sampling:NativeHeadSampling<'_,'ctx>,mut pool:impl FnMut(OriginalVerifyCpuRows<'_>,&mut OriginalVerifyCpuSink<'_,'ctx>,&mut OriginalGpuStream<'ctx>)->Result<()>)->Result{ - // #267: a released verifier (a window the GPU never finished) refuses every later window. - if self.released||self.registration.as_ref().is_some_and(diag::Registration::is_released){return Err(Error::InvalidDriverValue("Verifier released: an earlier window never finished on the GPU (#267)"))} - if self.failed||self.active||self.window_ready||self.commit.is_none(){return Err(Error::InvalidQwenShape)}if sampling.position!=position as u64{return Err(Error::InvalidQwenShape)}let t=tokens.len();if !(1..=self.bank()?.geometry().max_t).contains(&t)||self.window[t-1].is_none(){return Err(Error::InvalidQwenShape)} - let wants_ple=self.window[t-1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?; - if wants_ple!=ple.is_some(){return Err(Error::InvalidQwenShape)} - // The preceding asynchronous commit has the same compute stream. Its actual - // mapped records are overwritten only after that completed receipt/window. - let span_wait=crate::host_profile::span("drv.run_wait_commit"); - self.wait_commit()?; - drop(span_wait); - let span_stage=crate::host_profile::span("drv.stage"); - let generation=self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens,position)?; - if let Some(ple)=ple{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)?} - drop(span_stage); - let span_begin=crate::host_profile::span("drv.begin_window"); - self.window[t-1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?; - drop(span_begin); - self.active=true;if let Some(r)=&self.registration{r.begin_window(t,position as u64)} - let operation=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||->Result{ - let span_launch=crate::host_profile::span("drv.launch"); - self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; - let _=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; - drop(span_launch); - let groups=self.groups[t-1];for k in 0..window_plan::window_rings(groups){ - let layer=k/groups;let group=k%groups;let want=window_plan::ring(layer,groups,group);let start=Instant::now();let mut last_flush=start;let mut spins=0u32; - if let Some(r)=&self.registration{r.layer_step(want)} - let span_bell=crate::host_profile::span("drv.doorbell_wait"); - loop{if self.bank()?.doorbell_sequence()?>=want{break}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue}let now=Instant::now();if self.registration.as_ref().is_some_and(diag::Registration::is_released){return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)"))}if now.duration_since(last_flush)>Duration::from_micros(2000){last_flush=now;let q=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;if q&&self.bank()?.doorbell_sequence()?Duration::from_secs(20){return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"))}} - drop(span_bell); - let (begin,end)=window_plan::group_rows(t,groups,group);let rows=end-begin;let g=self.bank()?.geometry();let physical=self.bank()?.physical.clone(); - let x=physical.mapped[6].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - let ids=physical.mapped[7].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - let w=physical.mapped[8].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - MappedAllocation::with_cpu_rows(x.as_ref().ok_or(Error::ContextPoisoned)?,ids.as_ref().ok_or(Error::ContextPoisoned)?,w.as_ref().ok_or(Error::ContextPoisoned)?,begin,rows,g.n,g.k,|activation,ids,route_weights|pool(OriginalVerifyCpuRows{layer,group,first_row:begin,activation,ids,route_weights},&mut OriginalVerifyCpuSink{bank:self.bank.as_mut().ok_or(Error::ContextPoisoned)?,first:begin,rows,layer,group,groups,ring:want},self.copy.as_mut().ok_or(Error::ContextPoisoned)?))?; - drop((x,ids,w)); - // A pool with no GPU plan publishes the literal empty plan; actual DMA - // producers publish A and raise B only from completed host callbacks. - let span_flag=crate::host_profile::span("drv.group_publish"); - let flag=self.bank()?.physical.mapped[11].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?; - if flag!=want{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group,want)?} - let stalled=self.test_stall>0&&self.windows+1==self.test_stall&&k+1==window_plan::window_rings(groups); - if !stalled{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,want)?;} - drop(span_flag); - } - // Original order: compute fence, then copy-stream fence (no late flag B), - // then request sampling with Philox counter tied to actual position. - let span_sync=crate::host_profile::span("drv.sync_compute"); - let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; - drop(span_sync); - let span_copy=crate::host_profile::span("drv.sync_copy"); - self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; - drop(span_copy); - // Every PCIe copy of the window has landed: the registered sources it read may go. - self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources(); - // The window's GPU stage stamps (single-group windows only, as in Original). - if groups==1&&self.bank()?.profile_enabled(){let stamps=self.bank()?.read_profile()?;self.profile.add_window(&stamps,48,|l|l%4==3);} - let _span_head=crate::host_profile::span("drv.head"); - self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain(self.compute.as_mut().ok_or(Error::ContextPoisoned)?,&receipt,sampling) - })); - if let Some(r)=&self.registration{r.end_window()} - match operation{Ok(Ok(selection))=>{if selection.ids().len()!=t||selection.position()!=position as u64||selection.vocabulary()!=self.bank()?.geometry().vocabulary{self.failed=true;return combine(Err(Error::InvalidQwenShape),self.abort_gpu_waits())}self.completed_ids[..t].copy_from_slice(selection.ids());self.active=false;self.window_ready=true;self.completed_generation=Some(generation);self.windows=self.windows.checked_add(1).ok_or(Error::InvalidSize)?;Ok(OriginalVerifyWindowResult{selection,generation,first_position:position,rows:t})},Ok(Err(primary))=>{self.failed=true;let cleanup=self.abort_gpu_waits();combine(Err(primary),cleanup)},Err(panic)=>{self.failed=true;let _=self.abort_gpu_waits();std::panic::resume_unwind(panic)}} - } - /// n_keep is meaningful only after the actual preceding window completes. - /// Root prepares all genuine accepted-prefix publication permits AFTER this - /// commit completion; this controller does not forge session capabilities. - pub fn commit(&mut self,n_keep:usize,async_commit:bool)->Result<()>{ - if self.failed||self.active||!self.window_ready{return Err(Error::InvalidQwenShape)}let span_commit=crate::host_profile::span("drv.commit_enqueue");self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?; - let operation=(||{self.commit.as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.window_ready=false; - let forced=commit_sync_forced(); - if async_commit&&!forced{self.event.as_mut().ok_or(Error::ContextPoisoned)?.record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit_pending=true;Ok(())} - else{let receipt=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())} - })();drop(span_commit);if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(()) - } - /// The pending asynchronous commit's completion event (generate.cpp: what the next work on the commit's stream - /// follows), for another stream to wait on the device. `None` when no commit is outstanding. - pub fn pending_commit_event(&mut self)->Option<&mut OriginalGpuEvent<'ctx>>{if !self.commit_pending||self.failed{return None}self.event.as_mut()} - pub fn wait_commit(&mut self)->Result<()>{if !self.commit_pending{return Ok(())}let _span_wait=crate::host_profile::span("drv.commit_event_wait");let operation=(||{self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?;self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?;self.commits=self.commits.checked_add(1).ok_or(Error::InvalidSize)?;Ok(())})();self.commit_pending=false;if let Err(primary)=operation{self.failed=true;return combine(Err(primary),self.abort_gpu_waits())}Ok(())} - /// Take back a completed window that no commit was enqueued for, so that `run` can stage the same rows again (the serve loop's - /// NaN guard: the window read as non-finite, both checkpoints were restored, the round starts over). The GDN canonical state is not - /// written before a commit (the commit graph recomputes it from the journal); the QSA journal writes back the index state and the PLE - /// history (the window advances it row by row) as they were when the window began (`discard_window` there, which needs - /// `OriginalVerifyQsaJournal::set_window_snapshots(true)`). No window outstanding is - /// not an error unless the verifier already failed or was released (then there is nothing to run the rows on). After an error - /// here the verifier is failed. - pub fn discard_window(&mut self)->Result<()>{ - if !self.window_ready{return if self.failed||self.released||self.active||self.commit_pending{Err(Error::InvalidQwenShape)}else{Ok(())}} - if self.failed||self.released||self.active||self.commit_pending{return Err(Error::InvalidQwenShape)} - let operation={ - let bank=self.bank.as_ref().ok_or(Error::ContextPoisoned)?; - let resources=self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_wait()?; - resources.verifier_qsa().discard_window(bank,resources.verifier_journal().ple_buffer()) - }; - match operation{Ok(())=>{self.window_ready=false;self.completed_generation=None;Ok(())},Err(primary)=>{self.failed=true;combine(Err(primary),self.abort_gpu_waits())}} - } - /// Original final_R row, minted only after a genuine completed window. - pub fn final_row(&self,row:usize)->Result>{self.require_completed_window()?;self.bank()?.completed_row(row)} - fn require_completed_window(&self)->Result<()>{if self.failed||self.active||self.completed_generation!=Some(self.bank()?.generation){return Err(Error::InvalidQwenShape)}self.bank()?.staged_window()?;Ok(())} - /// Same actual device R/tok retained by the completed verifier graph; no - /// caller-generated boolean or captured-only graph can mint this handoff. - pub fn completed_window(&self)->Result>{self.require_completed_window()?;let b=self.bank()?;Ok(OriginalVerifyWindow{physical:b.physical.clone(),generation:b.generation,rows:b.last_t,position:b.last_position,sampled_ids:self.completed_ids})} - pub fn accepted_tokens(&mut self)->Result<&[i32]>{if self.active||self.failed||self.window_ready{return Err(Error::InvalidQwenShape)}self.wait_commit()?;if self.commits==0{return Err(Error::InvalidQwenShape)}let b=self.bank()?;Ok(&b.last_tokens[..b.staged_keep()?])} - pub fn with_committed_gdn(&mut self,layer:usize,consume:impl FnOnce(&[f32],&[f32])->Result)->Result{ - if self.active||self.failed||self.window_ready{return Err(Error::InvalidQwenShape)}self.wait_commit()?;if self.commits==0{return Err(Error::InvalidQwenShape)} - let commit=self.commit.as_mut().ok_or(Error::InvalidQwenShape)?; - let resources=commit.resources_after_wait()?;resources.verifier_journal().canonical.with_layer(layer,consume) - } - pub fn with_committed_qsa(&mut self,layer:usize,consume:impl FnOnce(&mut crate::OriginalQsaResidentIndex<'ctx>)->Result)->Result{if self.active||self.failed||self.window_ready{return Err(Error::InvalidQwenShape)}self.wait_commit()?;if self.commits==0{return Err(Error::InvalidQwenShape)}let commit=self.commit.as_mut().ok_or(Error::InvalidQwenShape)?;let resources=commit.resources_after_wait()?;resources.verifier_qsa().with_committed_index(layer,consume)} - /// The twelve committed QSA index checkpoints of `with_committed_qsa(l, |i| i.checkpoint(ws))`, taken in one batch - /// after the commit event (no context-wide synchronize per layer). - pub fn checkpoint_committed_qsa_all(&mut self,ws:&mut crate::NativeBatchWorkspace<'ctx>)->Result<[crate::OriginalQsaIndexCheckpoint<'ctx>;12]>{if self.active||self.failed||self.window_ready{return Err(Error::InvalidQwenShape)}self.wait_commit()?;if self.commits==0{return Err(Error::InvalidQwenShape)}let commit=self.commit.as_mut().ok_or(Error::InvalidQwenShape)?;let resources=commit.resources_after_wait()?;resources.verifier_qsa().checkpoint_committed_all(ws)} - /// The watchdog's view of this verifier's window (issue #31 `Verifier::diag`). `None` once closed. - pub fn diag(&self)->Option{self.registration.as_ref().map(diag::Registration::snapshot)} - pub fn write_diag(&self,f:&mut dyn Write)->std::io::Result<()>{match self.diag(){Some(d)=>d.write_to(f),None=>Ok(())}} - /// True once a release ran: every later window is refused. - pub fn is_released(&self)->bool{self.released||self.registration.as_ref().is_some_and(diag::Registration::is_released)} - /// #267 `release_gpu_waits(timeout_ms)` on the owner thread: raise every flag the window's spin - /// kernels wait on past any ring so a window the GPU cannot finish drains, then wait up to - /// `timeout` for both streams. `Ok(true)` when they finished. This verifier then refuses every - /// later window (the window ran on whatever the flags guarded). A watchdog THREAD uses - /// `original_verify_release_live`, which needs no driver call. - pub fn release_gpu_waits(&mut self,timeout:Duration)->Result{ - self.released=true;if let Some(r)=&self.registration{r.mark_released()} - let mut result=self.bank.as_mut().map_or(Ok(()),OriginalVerifyBank::release_gpu_waits);let start=Instant::now();let mut drained=true; - for stream in [self.compute.as_ref(),self.copy.as_ref()].into_iter().flatten(){loop{match stream.query(){Ok(true)=>break,Ok(false)=>{if start.elapsed()>timeout{drained=false;break}std::thread::sleep(Duration::from_millis(1))},Err(error)=>{result=combine(result,Err(error));drained=false;break}}}} - result.map(|()|drained) - } - /// `STRATA_VERIFY_PROFILE=1` GPU stage times of the windows since the last call, as one line; - /// empty when the profile is off or nothing was measured. - pub fn profile_report(&mut self)->String{self.profile.report()} - /// The completed window whose head logits may be read: a genuine `run` of the CURRENT staged - /// generation. A graph that was only captured (or one superseded by a newer stage) never qualifies. - fn with_completed_logits(&self,read:impl FnOnce(&DeviceBuffer<'ctx>,usize,usize,usize)->Result)->Result{ - self.require_completed_window()?;let bank=self.bank()?;let t=bank.last_t;let vocabulary=bank.geometry().vocabulary; - let logits=self.window.get(t.wrapping_sub(1)).and_then(Option::as_ref).ok_or(Error::InvalidQwenShape)?.verifier_completed_logits()?; - if logits.len()!=t.checked_mul(vocabulary).and_then(|n|n.checked_mul(4)).ok_or(Error::InvalidSize)?{return Err(Error::InvalidQwenShape)} - read(logits,t,vocabulary,bank.last_position) - } - fn read_logit_rows(&self,logits:&DeviceBuffer<'ctx>,first_row:usize,rows:usize,vocabulary:usize)->Result>{ - let context=self.bank()?.physical.context;let bytes_len=rows.checked_mul(vocabulary).and_then(|n|n.checked_mul(4)).ok_or(Error::InvalidSize)?; - let span=handle(logits)?.checked_subspan(logits.len(),first_row*vocabulary*4,bytes_len)?; - let mut bytes=zero(bytes_len)?;let guard=context.enter()?;let copy=context.driver.api.copy_to(span,&mut bytes);let sync=context.driver.api.synchronize();let pop=guard.finish(); - if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(context);std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!())} - combine(combine(copy,sync),pop)?; - let mut values=Vec::new();values.try_reserve_exact(rows*vocabulary).map_err(|_|Error::HostAllocation)?;values.extend(bytes.as_chunks::<4>().0.iter().map(|b|f32::from_le_bytes(*b)));Ok(values) - } - /// `Verifier::copy_logits`: row `t` of the last completed window's head logits, `vocabulary` floats. - pub fn copy_logits(&self,t:usize,host:&mut [f32])->Result<()>{ - self.with_completed_logits(|logits,rows,vocabulary,_|{if t>=rows||host.len()!=vocabulary{return Err(Error::InvalidQwenShape)}host.copy_from_slice(&self.read_logit_rows(logits,t,1,vocabulary)?);Ok(())}) - } - /// `Verifier::window_logprobs` with `STRATA_LOGPOS_TOPK` from the environment: one line per row of - /// the last completed window. `targets[t]` is the token at `first_position + t + 1`. - pub fn window_logprobs(&self,targets:&[i32],extra_id:i32,out:&mut dyn Write)->Result<()>{self.window_logprobs_topk(targets,extra_id,logpos_topk_from_environment(),out)} - pub fn window_logprobs_topk(&self,targets:&[i32],extra_id:i32,topk:usize,out:&mut dyn Write)->Result<()>{ - self.with_completed_logits(|logits,rows,vocabulary,first|{ - if targets.is_empty()||targets.len()>rows{return Err(Error::InvalidQwenShape)} - let values=self.read_logit_rows(logits,0,targets.len(),vocabulary)?; - write_window_logprobs(out,&values,vocabulary,targets,first as i64,extra_id,topk).map_err(|_|Error::InvalidDriverValue("window_logprobs output")) - }) - } - /// Bring-up diagnostic: the final residual R (`hc*n` f32 per row, all rows) of the last completed window and its first - /// position. Read-only; same completion guard as the logits readers. - pub fn window_residual_rows(&self)->Result<(usize,usize,Vec)>{ - self.require_completed_window()?;let bank=self.bank()?;let t=bank.last_t;let g=bank.geometry();let bytes_len=t.checked_mul(g.hc).and_then(|n|n.checked_mul(g.n)).and_then(|n|n.checked_mul(4)).ok_or(Error::InvalidSize)?; - let s=bank.physical.layout.span("R")?;let b=bank.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;let span=handle(b)?.checked_subspan(b.len(),s.offset,bytes_len)?; - let context=bank.physical.context;let mut bytes=zero(bytes_len)?;let guard=context.enter()?;let copy=context.driver.api.copy_to(span,&mut bytes);let sync=context.driver.api.synchronize();let pop=guard.finish(); - if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(context);std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!())} - combine(combine(copy,sync),pop)?; - let mut values=Vec::new();values.try_reserve_exact(bytes_len/4).map_err(|_|Error::HostAllocation)?;values.extend(bytes.as_chunks::<4>().0.iter().map(|b|f32::from_le_bytes(*b)));Ok((t,bank.last_position,values)) - } - /// Bring-up diagnostic: the `dbg_ladder` frames (96 x rows x hc*n f32, frame = 2*layer + half) of the last completed window, - /// `None` when the region was not laid out (LELEKA_TRACE_LADDER unset at bank creation). - pub fn window_ladder_rows(&self)->Result>>{ - self.require_completed_window()?;let bank=self.bank()?;let t=bank.last_t;let g=bank.geometry();let row=g.hc*g.n; - let Ok(s)=bank.physical.layout.span("dbg_ladder") else{return Ok(None)};let b=bank.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; - let total=96*g.max_t*row*4;let span=handle(b)?.checked_subspan(b.len(),s.offset,total)?; - let context=bank.physical.context;let mut bytes=zero(total)?;let guard=context.enter()?;let copy=context.driver.api.copy_to(span,&mut bytes);let sync=context.driver.api.synchronize();let pop=guard.finish(); - if copy.as_ref().err().is_some_and(transport)||sync.is_err()||pop.is_err(){poison(context);std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!())} - combine(combine(copy,sync),pop)?; - let mut values=Vec::new();values.try_reserve_exact(96*t*row).map_err(|_|Error::HostAllocation)?; - for frame in 0..96{let at=frame*g.max_t*row*4;values.extend(bytes[at..at+t*row*4].as_chunks::<4>().0.iter().map(|b|f32::from_le_bytes(*b)));} - Ok(Some(values)) - } - pub fn windows(&self)->u64{self.windows} - fn abort_gpu_waits(&mut self)->Result<()>{ - self.released=true;if let Some(r)=&self.registration{r.mark_released()} - let mut result=self.bank.as_mut().map_or(Ok(()),OriginalVerifyBank::release_gpu_waits);let start=Instant::now(); - // Original #267 bounded release: no blocking wait on a spin kernel forever. - for s in [self.compute.as_ref(),self.copy.as_ref()].into_iter().flatten(){loop{match s.query(){Ok(true)=>break,Ok(false)=>{if start.elapsed()>Duration::from_millis(5000){if let Some(bank)=&self.bank{poison(bank.physical.context)}result=combine(result,Err(Error::InvalidDriverValue("Verifier release timeout")));break}std::thread::sleep(Duration::from_millis(1));},Err(error)=>{result=combine(result,Err(error));break}}}} - if result.is_ok(){for graph in self.window.iter_mut().filter_map(Option::as_mut){result=combine(result,graph.verifier_abandon_after_drain());}if let Some(graph)=self.commit.as_mut(){result=combine(result,graph.verifier_abandon_after_drain());}} - self.active=false;self.commit_pending=false;result - } - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{let mut result=if self.active||self.failed||self.window_ready{self.abort_gpu_waits()}else{self.wait_commit()};for graph in self.window.iter_mut().filter_map(Option::take).chain(self.commit.take()){result=combine(result,graph.close())}if let Some(e)=self.event.take(){result=combine(result,e.close())}if let Some(s)=self.compute.take(){result=combine(result,s.close())}if let Some(s)=self.copy.take(){result=combine(result,s.close())}self.registration=None;if let Some(b)=self.bank.take(){result=combine(result,b.close())}result} +pub struct OriginalVerifyWindowResult { + pub selection: NativeHeadSelection, + pub generation: u64, + pub first_position: usize, + pub rows: usize, } -impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>> Drop for OriginalVerifier<'ctx,R>{fn drop(&mut self){let _=self.close_inner();}} +pub struct OriginalVerifier<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> { + bank: Option>, + compute: Option>, + copy: Option>, + window: [Option>; 8], + commit: Option>, + event: Option>, + split: bool, + groups: [usize; 8], + commit_pending: bool, + window_ready: bool, + active: bool, + failed: bool, + windows: u64, + commits: u64, + resource_keys: Option<(usize, usize)>, + completed_generation: Option, + completed_ids: [i32; 8], + registration: Option, + released: bool, + profile: OriginalVerifyProfile, + test_stall: u64, +} + +#[path = "original_verify_schedule/commit_sync_forced_fn.rs"] +mod commit_sync_forced_fn; +#[allow(unused_imports)] +use commit_sync_forced_fn::commit_sync_forced; +#[path = "original_verify_schedule/impl_originalverifier_2.rs"] +mod impl_originalverifier_2; +#[path = "original_verify_schedule/impl_originalverifier_3.rs"] +mod impl_originalverifier_3; +#[path = "original_verify_schedule/impl_originalverifier_4.rs"] +mod impl_originalverifier_4; diff --git a/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs b/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs new file mode 100644 index 00000000..cac30eca --- /dev/null +++ b/crates/cuda-driver/src/original_verify_schedule/commit_sync_forced_fn.rs @@ -0,0 +1,201 @@ +//! Moved out of the parent module by STRA-338: fn commit_sync_forced, impl OriginalVerifyCpuSink, impl OriginalVerifier. + +#[allow(unused_imports)] +use super::*; + +/// `STRATA_COMMIT_SYNC`, read once (it sat on the per-round commit path). +pub(super) fn commit_sync_forced() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_COMMIT_SYNC").is_some()) +} +impl OriginalVerifyCpuSink<'_, '_> { + pub fn with_output(&mut self, produce: impl FnOnce(&mut [f32]) -> Result) -> Result { + let g = self.bank.geometry(); + let mut m = self.bank.physical.mapped[13].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + m.as_mut().ok_or(Error::ContextPoisoned)?.with_cpu_output( + self.first * g.k * g.n * 4, + self.rows * g.k * g.n, + produce, + ) + } +} +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + pub fn new(context: &'ctx Context<'ctx>, geometry: OriginalVerifyGeometry) -> Result { + let mut owner = Self { + bank: None, + compute: None, + copy: None, + window: std::array::from_fn(|_| None), + commit: None, + event: None, + split: false, + groups: [0; 8], + commit_pending: false, + window_ready: false, + active: false, + failed: false, + windows: 0, + commits: 0, + resource_keys: None, + completed_generation: None, + completed_ids: [0; 8], + registration: None, + released: false, + profile: OriginalVerifyProfile::default(), + test_stall: 0, + }; + let operation = (|| { + owner.bank = Some(context.original_verify_bank(geometry)?); + // #267 test hook, off unless set: withhold the last layer's flag in the N-th window (1-based). + owner.test_stall = + std::env::var("STRATA_TEST_VERIFY_STALL").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0); + owner.registration = + Some(diag::Registration::new(owner.bank.as_ref().ok_or(Error::ContextPoisoned)?.host_words()?)); + owner.copy = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?); + owner.compute = Some(context.original_gpu_stream(OriginalStreamKind::NonBlocking)?); + owner.event = Some(context.original_gpu_event(OriginalEventKind::Completion)?); + Ok(()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close_inner()); + } + Ok(owner) + } + pub fn bank(&self) -> Result<&OriginalVerifyBank<'ctx>> { + self.bank.as_ref().ok_or(Error::ContextPoisoned) + } + pub fn allocated_bytes(&self) -> usize { + self.bank.as_ref().map_or(0, OriginalVerifyBank::allocated_bytes) + } + pub(super) fn record_keys(&mut self, r: &R) -> Result<()> { + r.verifier_journal().validate_bank(self.bank()?)?; + r.verifier_qsa().validate_context(self.bank()?.physical.context)?; + let keys = (r.verifier_journal().canonical_identity(), r.verifier_qsa().identity()); + if self.resource_keys.is_some_and(|old| old != keys) { + return Err(Error::InvalidQwenShape); + } + self.resource_keys = Some(keys); + Ok(()) + } + /// `Verifier::set_pcie_mode` of the graphs about to be recorded (0 DMA, 2 copy kernel; 1, the mapped arena, is not + /// ported): fixed by the first recorded window, so `publish_gpu_plan` stages the way every graph reads. + pub(crate) fn set_pcie_mode(&mut self, mode: u8, roles: Option<[[usize; 3]; 48]>) -> Result<()> { + if self.active || !matches!(mode, 0 | 2) || (mode == 2 && roles.is_none()) { + return Err(Error::InvalidQwenShape); + } + let recorded = self.window.iter().any(Option::is_some) || self.commit.is_some(); + let bank = self.bank.as_mut().ok_or(Error::ContextPoisoned)?; + if recorded && (bank.pcie_mode != mode || bank.pcie_roles != roles) { + return Err(Error::InvalidQwenShape); + } + bank.pcie_mode = mode; + bank.pcie_roles = roles; + Ok(()) + } + pub fn set_split(&mut self, on: bool) -> Result<()> { + if self.window.iter().any(Option::is_some) || self.active { + return Err(Error::InvalidQwenShape); + } + self.split = on; + Ok(()) + } + pub fn record_window( + &mut self, + t: usize, + resources: R, + record: impl FnOnce(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>, + ) -> Result<()> { + if self.failed + || self.active + || !(1..=self.bank()?.geometry().max_t).contains(&t) + || self.window[t - 1].is_some() + { + return Err(Error::InvalidQwenShape); + } + self.record_keys(&resources)?; + if resources.native_head_rows()?.rows() != t + || resources.native_head_rows()?.completed_logits()?.len() != t * self.bank()?.geometry().vocabulary * 4 + { + return Err(Error::InvalidQwenShape); + } + let groups = window_plan::window_groups(t, self.split); + let stream = self.compute.as_mut().ok_or(Error::ContextPoisoned)?; + let graph = stream.capture_owned(OriginalCapturePolicy::VerifierWindow, resources, |capture, r| { + r.verifier_journal().capture_inputs(capture, t)?; + record(capture, r, groups) + })?; + if crate::host_profile::enabled() { + eprintln!("DBG graph window t={t} groups={groups} nodes={:?}", graph.nodes()); + } + self.window[t - 1] = Some(graph); + self.groups[t - 1] = groups; + Ok(()) + } + pub fn record_commit( + &mut self, + resources: R, + mut record_extra: impl FnMut(&mut OriginalCapture<'_, 'ctx>, &mut R, usize) -> Result<()>, + ) -> Result<()> { + if self.failed || self.active || self.commit.is_some() { + return Err(Error::InvalidQwenShape); + } + self.record_keys(&resources)?; + // sm_120 only: the fused kernels have no sm_86 companion (ptx-sm86/MANIFEST.json), another card keeps the Original's commit graph + let fused_commit = crate::original_verify::draft::fused_commit() + && resources + .verifier_journal() + .window_device_attribute(crate::original_verify::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)? + == 12; + if fused_commit { + resources.verifier_journal().load_draft_commit_asset()?; + } + let stream = self.compute.as_mut().ok_or(Error::ContextPoisoned)?; + self.commit = Some(stream.capture_owned(OriginalCapturePolicy::VerifierCommit, resources, |capture, r| { + r.verifier_journal().capture_commit_begin(capture)?; + let mut gi = 0; + let mut qi = 0; + // draft-round: the layers are independent; one launch per kind (GDN, QSA) instead of 182 nodes. A QSA with retained angle tables keeps its per-layer commit. + if fused_commit { + r.verifier_journal().capture_commit_gdn_fused(capture)?; + if r.verifier_qsa().capture_commit_fused(r.verifier_journal(), capture)? { + for layer in (3..48).step_by(4) { + record_extra(capture, r, layer)?; + } + if r.verifier_journal().ple.is_some() { + r.verifier_journal().capture_ple_commit(capture)?; + } + return Ok(()); + } + for layer in 0..48 { + if layer % 4 == 3 { + r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?; + record_extra(capture, r, layer)?; + qi += 1 + } + } + if r.verifier_journal().ple.is_some() { + r.verifier_journal().capture_ple_commit(capture)?; + } + return Ok(()); + } + for layer in 0..48 { + if layer % 4 == 3 { + r.verifier_qsa().capture_commit_layer(r.verifier_journal(), capture, qi)?; + record_extra(capture, r, layer)?; + qi += 1 + } else { + r.verifier_journal().capture_commit_layer(capture, gi)?; + gi += 1 + } + } + if r.verifier_journal().ple.is_some() { + r.verifier_journal().capture_ple_commit(capture)?; + } + Ok(()) + })?); + if crate::host_profile::enabled() { + eprintln!("DBG graph commit nodes={:?}", self.commit.as_ref().and_then(|g| g.nodes())); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs new file mode 100644 index 00000000..e911f00e --- /dev/null +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs @@ -0,0 +1,255 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifier (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + /// Cached real all-T graph; CPU/GPU split and mapped flag rings match Original. + /// Callback must finish actual expert/source work before returning. An error + /// releases every wait and drains both streams before preserving that primary. + pub fn run( + &mut self, + tokens: &[i32], + position: usize, + ple: Option<&[f32]>, + sampling: NativeHeadSampling<'_, 'ctx>, + mut pool: impl FnMut( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, + ) -> Result { + // #267: a released verifier (a window the GPU never finished) refuses every later window. + if self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) { + return Err(Error::InvalidDriverValue( + "Verifier released: an earlier window never finished on the GPU (#267)", + )); + } + if self.failed || self.active || self.window_ready || self.commit.is_none() { + return Err(Error::InvalidQwenShape); + } + if sampling.position != position as u64 { + return Err(Error::InvalidQwenShape); + } + let t = tokens.len(); + if !(1..=self.bank()?.geometry().max_t).contains(&t) || self.window[t - 1].is_none() { + return Err(Error::InvalidQwenShape); + } + let wants_ple = self.window[t - 1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?; + if wants_ple != ple.is_some() { + return Err(Error::InvalidQwenShape); + } + // The preceding asynchronous commit has the same compute stream. Its actual + // mapped records are overwritten only after that completed receipt/window. + let span_wait = crate::host_profile::span("drv.run_wait_commit"); + self.wait_commit()?; + drop(span_wait); + let span_stage = crate::host_profile::span("drv.stage"); + let generation = self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens, position)?; + if let Some(ple) = ple { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)? + } + drop(span_stage); + let span_begin = crate::host_profile::span("drv.begin_window"); + self.window[t - 1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?; + drop(span_begin); + self.active = true; + if let Some(r) = &self.registration { + r.begin_window(t, position as u64) + } + let operation = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result { + let span_launch = crate::host_profile::span("drv.launch"); + self.window[t - 1] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + let _ = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; + drop(span_launch); + let groups = self.groups[t - 1]; + for k in 0..window_plan::window_rings(groups) { + let layer = k / groups; + let group = k % groups; + let want = window_plan::ring(layer, groups, group); + let start = Instant::now(); + let mut last_flush = start; + let mut spins = 0u32; + if let Some(r) = &self.registration { + r.layer_step(want) + } + let span_bell = crate::host_profile::span("drv.doorbell_wait"); + loop { + if self.bank()?.doorbell_sequence()? >= want { + break; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + let now = Instant::now(); + if self.registration.as_ref().is_some_and(diag::Registration::is_released) { + return Err(Error::InvalidDriverValue( + "Verifier window released while waiting for a layer (#267)", + )); + } + if now.duration_since(last_flush) > Duration::from_micros(2000) { + last_flush = now; + let q = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; + if q && self.bank()?.doorbell_sequence()? < want { + return Err(Error::InvalidDriverValue("Verifier layer never rang")); + } + } + if now.duration_since(start) > Duration::from_secs(20) { + return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout")); + } + } + drop(span_bell); + let (begin, end) = window_plan::group_rows(t, groups, group); + let rows = end - begin; + let g = self.bank()?.geometry(); + let physical = self.bank()?.physical.clone(); + let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + MappedAllocation::with_cpu_rows( + x.as_ref().ok_or(Error::ContextPoisoned)?, + ids.as_ref().ok_or(Error::ContextPoisoned)?, + w.as_ref().ok_or(Error::ContextPoisoned)?, + begin, + rows, + g.n, + g.k, + |activation, ids, route_weights| { + pool( + OriginalVerifyCpuRows { layer, group, first_row: begin, activation, ids, route_weights }, + &mut OriginalVerifyCpuSink { + bank: self.bank.as_mut().ok_or(Error::ContextPoisoned)?, + first: begin, + rows, + layer, + group, + groups, + ring: want, + }, + self.copy.as_mut().ok_or(Error::ContextPoisoned)?, + ) + }, + )?; + drop((x, ids, w)); + // A pool with no GPU plan publishes the literal empty plan; actual DMA + // producers publish A and raise B only from completed host callbacks. + let span_flag = crate::host_profile::span("drv.group_publish"); + let flag = self.bank()?.physical.mapped[11] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0)?; + if flag != want { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group, want)? + } + let stalled = self.test_stall > 0 + && self.windows + 1 == self.test_stall + && k + 1 == window_plan::window_rings(groups); + if !stalled { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, want)?; + } + drop(span_flag); + } + // Original order: compute fence, then copy-stream fence (no late flag B), + // then request sampling with Philox counter tied to actual position. + let span_sync = crate::host_profile::span("drv.sync_compute"); + let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; + drop(span_sync); + let span_copy = crate::host_profile::span("drv.sync_copy"); + self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; + drop(span_copy); + // Every PCIe copy of the window has landed: the registered sources it read may go. + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources(); + // The window's GPU stage stamps (single-group windows only, as in Original). + if groups == 1 && self.bank()?.profile_enabled() { + let stamps = self.bank()?.read_profile()?; + self.profile.add_window(&stamps, 48, |l| l % 4 == 3); + } + let _span_head = crate::host_profile::span("drv.head"); + self.window[t - 1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain( + self.compute.as_mut().ok_or(Error::ContextPoisoned)?, + &receipt, + sampling, + ) + })); + if let Some(r) = &self.registration { + r.end_window() + } + match operation { + Ok(Ok(selection)) => { + if selection.ids().len() != t + || selection.position() != position as u64 + || selection.vocabulary() != self.bank()?.geometry().vocabulary + { + self.failed = true; + return combine(Err(Error::InvalidQwenShape), self.abort_gpu_waits()); + } + self.completed_ids[..t].copy_from_slice(selection.ids()); + self.active = false; + self.window_ready = true; + self.completed_generation = Some(generation); + self.windows = self.windows.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(OriginalVerifyWindowResult { selection, generation, first_position: position, rows: t }) + } + Ok(Err(primary)) => { + self.failed = true; + let cleanup = self.abort_gpu_waits(); + combine(Err(primary), cleanup) + } + Err(panic) => { + self.failed = true; + let _ = self.abort_gpu_waits(); + std::panic::resume_unwind(panic) + } + } + } + /// n_keep is meaningful only after the actual preceding window completes. + /// Root prepares all genuine accepted-prefix publication permits AFTER this + /// commit completion; this controller does not forge session capabilities. + pub fn commit(&mut self, n_keep: usize, async_commit: bool) -> Result<()> { + if self.failed || self.active || !self.window_ready { + return Err(Error::InvalidQwenShape); + } + let span_commit = crate::host_profile::span("drv.commit_enqueue"); + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_commit(n_keep)?; + let operation = (|| { + self.commit + .as_mut() + .ok_or(Error::ContextPoisoned)? + .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.window_ready = false; + let forced = commit_sync_forced(); + if async_commit && !forced { + self.event + .as_mut() + .ok_or(Error::ContextPoisoned)? + .record(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.commit_pending = true; + Ok(()) + } else { + let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; + self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_stream_drain(&receipt)?; + self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?; + self.commits = self.commits.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(()) + } + })(); + drop(span_commit); + if let Err(primary) = operation { + self.failed = true; + return combine(Err(primary), self.abort_gpu_waits()); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs new file mode 100644 index 00000000..d0335e24 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_3.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifier (3). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + /// The pending asynchronous commit's completion event (generate.cpp: what the next work on the commit's stream + /// follows), for another stream to wait on the device. `None` when no commit is outstanding. + pub fn pending_commit_event(&mut self) -> Option<&mut OriginalGpuEvent<'ctx>> { + if !self.commit_pending || self.failed { + return None; + } + self.event.as_mut() + } + pub fn wait_commit(&mut self) -> Result<()> { + if !self.commit_pending { + return Ok(()); + } + let _span_wait = crate::host_profile::span("drv.commit_event_wait"); + let operation = (|| { + self.event.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; + self.commit + .as_mut() + .ok_or(Error::ContextPoisoned)? + .resources_after_event(self.event.as_ref().ok_or(Error::ContextPoisoned)?)?; + self.commit.as_ref().ok_or(Error::ContextPoisoned)?.verifier_complete_commit(self.bank()?)?; + self.commits = self.commits.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(()) + })(); + self.commit_pending = false; + if let Err(primary) = operation { + self.failed = true; + return combine(Err(primary), self.abort_gpu_waits()); + } + Ok(()) + } + /// Take back a completed window that no commit was enqueued for, so that `run` can stage the same rows again (the serve loop's + /// NaN guard: the window read as non-finite, both checkpoints were restored, the round starts over). The GDN canonical state is not + /// written before a commit (the commit graph recomputes it from the journal); the QSA journal writes back the index state and the PLE + /// history (the window advances it row by row) as they were when the window began (`discard_window` there, which needs + /// `OriginalVerifyQsaJournal::set_window_snapshots(true)`). No window outstanding is + /// not an error unless the verifier already failed or was released (then there is nothing to run the rows on). After an error + /// here the verifier is failed. + pub fn discard_window(&mut self) -> Result<()> { + if !self.window_ready { + return if self.failed || self.released || self.active || self.commit_pending { + Err(Error::InvalidQwenShape) + } else { + Ok(()) + }; + } + if self.failed || self.released || self.active || self.commit_pending { + return Err(Error::InvalidQwenShape); + } + let operation = { + let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?; + let resources = self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_wait()?; + resources.verifier_qsa().discard_window(bank, resources.verifier_journal().ple_buffer()) + }; + match operation { + Ok(()) => { + self.window_ready = false; + self.completed_generation = None; + Ok(()) + } + Err(primary) => { + self.failed = true; + combine(Err(primary), self.abort_gpu_waits()) + } + } + } + /// Original final_R row, minted only after a genuine completed window. + pub fn final_row(&self, row: usize) -> Result> { + self.require_completed_window()?; + self.bank()?.completed_row(row) + } + pub(super) fn require_completed_window(&self) -> Result<()> { + if self.failed || self.active || self.completed_generation != Some(self.bank()?.generation) { + return Err(Error::InvalidQwenShape); + } + self.bank()?.staged_window()?; + Ok(()) + } + /// Same actual device R/tok retained by the completed verifier graph; no + /// caller-generated boolean or captured-only graph can mint this handoff. + pub fn completed_window(&self) -> Result> { + self.require_completed_window()?; + let b = self.bank()?; + Ok(OriginalVerifyWindow { + physical: b.physical.clone(), + generation: b.generation, + rows: b.last_t, + position: b.last_position, + sampled_ids: self.completed_ids, + }) + } + pub fn accepted_tokens(&mut self) -> Result<&[i32]> { + if self.active || self.failed || self.window_ready { + return Err(Error::InvalidQwenShape); + } + self.wait_commit()?; + if self.commits == 0 { + return Err(Error::InvalidQwenShape); + } + let b = self.bank()?; + Ok(&b.last_tokens[..b.staged_keep()?]) + } + pub fn with_committed_gdn( + &mut self, + layer: usize, + consume: impl FnOnce(&[f32], &[f32]) -> Result, + ) -> Result { + if self.active || self.failed || self.window_ready { + return Err(Error::InvalidQwenShape); + } + self.wait_commit()?; + if self.commits == 0 { + return Err(Error::InvalidQwenShape); + } + let commit = self.commit.as_mut().ok_or(Error::InvalidQwenShape)?; + let resources = commit.resources_after_wait()?; + resources.verifier_journal().canonical.with_layer(layer, consume) + } + pub fn with_committed_qsa( + &mut self, + layer: usize, + consume: impl FnOnce(&mut crate::OriginalQsaResidentIndex<'ctx>) -> Result, + ) -> Result { + if self.active || self.failed || self.window_ready { + return Err(Error::InvalidQwenShape); + } + self.wait_commit()?; + if self.commits == 0 { + return Err(Error::InvalidQwenShape); + } + let commit = self.commit.as_mut().ok_or(Error::InvalidQwenShape)?; + let resources = commit.resources_after_wait()?; + resources.verifier_qsa().with_committed_index(layer, consume) + } + /// The twelve committed QSA index checkpoints of `with_committed_qsa(l, |i| i.checkpoint(ws))`, taken in one batch + /// after the commit event (no context-wide synchronize per layer). + pub fn checkpoint_committed_qsa_all( + &mut self, + ws: &mut crate::NativeBatchWorkspace<'ctx>, + ) -> Result<[crate::OriginalQsaIndexCheckpoint<'ctx>; 12]> { + if self.active || self.failed || self.window_ready { + return Err(Error::InvalidQwenShape); + } + self.wait_commit()?; + if self.commits == 0 { + return Err(Error::InvalidQwenShape); + } + let commit = self.commit.as_mut().ok_or(Error::InvalidQwenShape)?; + let resources = commit.resources_after_wait()?; + resources.verifier_qsa().checkpoint_committed_all(ws) + } + /// The watchdog's view of this verifier's window (issue #31 `Verifier::diag`). `None` once closed. + pub fn diag(&self) -> Option { + self.registration.as_ref().map(diag::Registration::snapshot) + } + pub fn write_diag(&self, f: &mut dyn Write) -> std::io::Result<()> { + match self.diag() { + Some(d) => d.write_to(f), + None => Ok(()), + } + } + /// True once a release ran: every later window is refused. + pub fn is_released(&self) -> bool { + self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) + } + /// #267 `release_gpu_waits(timeout_ms)` on the owner thread: raise every flag the window's spin + /// kernels wait on past any ring so a window the GPU cannot finish drains, then wait up to + /// `timeout` for both streams. `Ok(true)` when they finished. This verifier then refuses every + /// later window (the window ran on whatever the flags guarded). A watchdog THREAD uses + /// `original_verify_release_live`, which needs no driver call. + pub fn release_gpu_waits(&mut self, timeout: Duration) -> Result { + self.released = true; + if let Some(r) = &self.registration { + r.mark_released() + } + let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits); + let start = Instant::now(); + let mut drained = true; + for stream in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() { + loop { + match stream.query() { + Ok(true) => break, + Ok(false) => { + if start.elapsed() > timeout { + drained = false; + break; + } + std::thread::sleep(Duration::from_millis(1)) + } + Err(error) => { + result = combine(result, Err(error)); + drained = false; + break; + } + } + } + } + result.map(|()| drained) + } + /// `STRATA_VERIFY_PROFILE=1` GPU stage times of the windows since the last call, as one line; + /// empty when the profile is off or nothing was measured. + pub fn profile_report(&mut self) -> String { + self.profile.report() + } + /// The completed window whose head logits may be read: a genuine `run` of the CURRENT staged + /// generation. A graph that was only captured (or one superseded by a newer stage) never qualifies. + pub(super) fn with_completed_logits( + &self, + read: impl FnOnce(&DeviceBuffer<'ctx>, usize, usize, usize) -> Result, + ) -> Result { + self.require_completed_window()?; + let bank = self.bank()?; + let t = bank.last_t; + let vocabulary = bank.geometry().vocabulary; + let logits = self + .window + .get(t.wrapping_sub(1)) + .and_then(Option::as_ref) + .ok_or(Error::InvalidQwenShape)? + .verifier_completed_logits()?; + if logits.len() != t.checked_mul(vocabulary).and_then(|n| n.checked_mul(4)).ok_or(Error::InvalidSize)? { + return Err(Error::InvalidQwenShape); + } + read(logits, t, vocabulary, bank.last_position) + } +} diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs new file mode 100644 index 00000000..dafb171b --- /dev/null +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_4.rs @@ -0,0 +1,197 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifier (4), impl Drop_for_OriginalVerifier. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + pub(super) fn read_logit_rows( + &self, + logits: &DeviceBuffer<'ctx>, + first_row: usize, + rows: usize, + vocabulary: usize, + ) -> Result> { + let context = self.bank()?.physical.context; + let bytes_len = rows.checked_mul(vocabulary).and_then(|n| n.checked_mul(4)).ok_or(Error::InvalidSize)?; + let span = handle(logits)?.checked_subspan(logits.len(), first_row * vocabulary * 4, bytes_len)?; + let mut bytes = zero(bytes_len)?; + let guard = context.enter()?; + let copy = context.driver.api.copy_to(span, &mut bytes); + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + poison(context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!()); + } + combine(combine(copy, sync), pop)?; + let mut values = Vec::new(); + values.try_reserve_exact(rows * vocabulary).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + Ok(values) + } + /// `Verifier::copy_logits`: row `t` of the last completed window's head logits, `vocabulary` floats. + pub fn copy_logits(&self, t: usize, host: &mut [f32]) -> Result<()> { + self.with_completed_logits(|logits, rows, vocabulary, _| { + if t >= rows || host.len() != vocabulary { + return Err(Error::InvalidQwenShape); + } + host.copy_from_slice(&self.read_logit_rows(logits, t, 1, vocabulary)?); + Ok(()) + }) + } + /// `Verifier::window_logprobs` with `STRATA_LOGPOS_TOPK` from the environment: one line per row of + /// the last completed window. `targets[t]` is the token at `first_position + t + 1`. + pub fn window_logprobs(&self, targets: &[i32], extra_id: i32, out: &mut dyn Write) -> Result<()> { + self.window_logprobs_topk(targets, extra_id, logpos_topk_from_environment(), out) + } + pub fn window_logprobs_topk(&self, targets: &[i32], extra_id: i32, topk: usize, out: &mut dyn Write) -> Result<()> { + self.with_completed_logits(|logits, rows, vocabulary, first| { + if targets.is_empty() || targets.len() > rows { + return Err(Error::InvalidQwenShape); + } + let values = self.read_logit_rows(logits, 0, targets.len(), vocabulary)?; + write_window_logprobs(out, &values, vocabulary, targets, first as i64, extra_id, topk) + .map_err(|_| Error::InvalidDriverValue("window_logprobs output")) + }) + } + /// Bring-up diagnostic: the final residual R (`hc*n` f32 per row, all rows) of the last completed window and its first + /// position. Read-only; same completion guard as the logits readers. + pub fn window_residual_rows(&self) -> Result<(usize, usize, Vec)> { + self.require_completed_window()?; + let bank = self.bank()?; + let t = bank.last_t; + let g = bank.geometry(); + let bytes_len = t + .checked_mul(g.hc) + .and_then(|n| n.checked_mul(g.n)) + .and_then(|n| n.checked_mul(4)) + .ok_or(Error::InvalidSize)?; + let s = bank.physical.layout.span("R")?; + let b = bank.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + let span = handle(b)?.checked_subspan(b.len(), s.offset, bytes_len)?; + let context = bank.physical.context; + let mut bytes = zero(bytes_len)?; + let guard = context.enter()?; + let copy = context.driver.api.copy_to(span, &mut bytes); + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + poison(context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!()); + } + combine(combine(copy, sync), pop)?; + let mut values = Vec::new(); + values.try_reserve_exact(bytes_len / 4).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + Ok((t, bank.last_position, values)) + } + /// Bring-up diagnostic: the `dbg_ladder` frames (96 x rows x hc*n f32, frame = 2*layer + half) of the last completed window, + /// `None` when the region was not laid out (LELEKA_TRACE_LADDER unset at bank creation). + pub fn window_ladder_rows(&self) -> Result>> { + self.require_completed_window()?; + let bank = self.bank()?; + let t = bank.last_t; + let g = bank.geometry(); + let row = g.hc * g.n; + let Ok(s) = bank.physical.layout.span("dbg_ladder") else { return Ok(None) }; + let b = bank.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?; + let total = 96 * g.max_t * row * 4; + let span = handle(b)?.checked_subspan(b.len(), s.offset, total)?; + let context = bank.physical.context; + let mut bytes = zero(total)?; + let guard = context.enter()?; + let copy = context.driver.api.copy_to(span, &mut bytes); + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() { + poison(context); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!()); + } + combine(combine(copy, sync), pop)?; + let mut values = Vec::new(); + values.try_reserve_exact(96 * t * row).map_err(|_| Error::HostAllocation)?; + for frame in 0..96 { + let at = frame * g.max_t * row * 4; + values.extend(bytes[at..at + t * row * 4].as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b))); + } + Ok(Some(values)) + } + pub fn windows(&self) -> u64 { + self.windows + } + pub(super) fn abort_gpu_waits(&mut self) -> Result<()> { + self.released = true; + if let Some(r) = &self.registration { + r.mark_released() + } + let mut result = self.bank.as_mut().map_or(Ok(()), OriginalVerifyBank::release_gpu_waits); + let start = Instant::now(); + // Original #267 bounded release: no blocking wait on a spin kernel forever. + for s in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() { + loop { + match s.query() { + Ok(true) => break, + Ok(false) => { + if start.elapsed() > Duration::from_millis(5000) { + if let Some(bank) = &self.bank { + poison(bank.physical.context) + } + result = combine(result, Err(Error::InvalidDriverValue("Verifier release timeout"))); + break; + } + std::thread::sleep(Duration::from_millis(1)); + } + Err(error) => { + result = combine(result, Err(error)); + break; + } + } + } + } + if result.is_ok() { + for graph in self.window.iter_mut().filter_map(Option::as_mut) { + result = combine(result, graph.verifier_abandon_after_drain()); + } + if let Some(graph) = self.commit.as_mut() { + result = combine(result, graph.verifier_abandon_after_drain()); + } + } + self.active = false; + self.commit_pending = false; + result + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + let mut result = + if self.active || self.failed || self.window_ready { self.abort_gpu_waits() } else { self.wait_commit() }; + for graph in self.window.iter_mut().filter_map(Option::take).chain(self.commit.take()) { + result = combine(result, graph.close()) + } + if let Some(e) = self.event.take() { + result = combine(result, e.close()) + } + if let Some(s) = self.compute.take() { + result = combine(result, s.close()) + } + if let Some(s) = self.copy.take() { + result = combine(result, s.close()) + } + self.registration = None; + if let Some(b) = self.bank.take() { + result = combine(result, b.close()) + } + result + } +} +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> Drop + for OriginalVerifier<'ctx, R> +{ + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_chain.rs b/crates/cuda-driver/src/original_verify_window_chain.rs index 3d548717..a24dcb53 100644 --- a/crates/cuda-driver/src/original_verify_window_chain.rs +++ b/crates/cuda-driver/src/original_verify_window_chain.rs @@ -38,8 +38,29 @@ pub(crate) const E_QSA_MERGE_N: &str = "chain_qsa_decode_merge_n"; pub(crate) static CHAIN: AssetSpec = AssetSpec { name: "chain_window.ptx", ptx: concat!(include_str!("chain_window.ptx"), "\0").as_bytes(), - sha: [163, 171, 220, 65, 134, 182, 109, 81, 168, 12, 142, 245, 47, 99, 111, 24, 147, 162, 19, 107, 136, 124, 214, 84, 135, 134, 254, 162, 121, 239, 113, 186], - entries: &[E_COPY_I32, E_WAIT_COPY_I32, E_COPY_ROWS, E_DOORBELL, E_GDN_AB, E_GR_SPLIT, E_GR_UP16, E_GR_UP8, E_GR_DOWN_NB2, E_GR_DOWN_NB3, E_GR_DOWN_T2W8, E_QSA_CHUNK, E_SWIGLU_QUANT, E_SCALE_SIGMOID, E_SAMPLER_GREEDY, E_ROW_TOP_PROB, E_QSA_MERGE_N], + sha: [ + 163, 171, 220, 65, 134, 182, 109, 81, 168, 12, 142, 245, 47, 99, 111, 24, 147, 162, 19, 107, 136, 124, 214, 84, + 135, 134, 254, 162, 121, 239, 113, 186, + ], + entries: &[ + E_COPY_I32, + E_WAIT_COPY_I32, + E_COPY_ROWS, + E_DOORBELL, + E_GDN_AB, + E_GR_SPLIT, + E_GR_UP16, + E_GR_UP8, + E_GR_DOWN_NB2, + E_GR_DOWN_NB3, + E_GR_DOWN_T2W8, + E_QSA_CHUNK, + E_SWIGLU_QUANT, + E_SCALE_SIGMOID, + E_SAMPLER_GREEDY, + E_ROW_TOP_PROB, + E_QSA_MERGE_N, + ], unsealed: "Original verifier asset unsealed: chain_window.ptx (latency-hoisted chain kernels)", }; @@ -161,7 +182,10 @@ mod tests { let all = ChainFlags::parse(env(&[("LELEKA_CHAIN", "all")])); assert_eq!(all, ChainFlags { glue: true, ab: true, gr: true, qsa: false, tiny: true, head: true, mtp: true }); let some = ChainFlags::parse(env(&[("LELEKA_CHAIN", "glue, qsa")])); - assert_eq!(some, ChainFlags { glue: true, ab: false, gr: false, qsa: true, tiny: false, head: false, mtp: false }); + assert_eq!( + some, + ChainFlags { glue: true, ab: false, gr: false, qsa: true, tiny: false, head: false, mtp: false } + ); } #[test] @@ -169,7 +193,10 @@ mod tests { let f = ChainFlags::parse(env(&[("LELEKA_CHAIN", "all"), ("LELEKA_CHAIN_GR", "0")])); assert_eq!(f, ChainFlags { glue: true, ab: true, gr: false, qsa: false, tiny: true, head: true, mtp: true }); let g = ChainFlags::parse(env(&[("LELEKA_CHAIN_AB", "1")])); - assert_eq!(g, ChainFlags { glue: false, ab: true, gr: false, qsa: false, tiny: false, head: false, mtp: false }); + assert_eq!( + g, + ChainFlags { glue: false, ab: true, gr: false, qsa: false, tiny: false, head: false, mtp: false } + ); } // ---- q8_1 division flavour of the SwiGLU + quantize fusion (upstream 7d1016f3). `chain_swiglu_quant_kernel` replaces the pair // `swiglu_entries_kernel` + `quantize_q8_1_kernel` of mtp_original_full_head_iq (the window's routed-expert path, moe.rs). A fused @@ -183,9 +210,13 @@ mod tests { while let Some(at) = ptx[from..].find(".entry ") { let start = from + at; let header_end = ptx[start..].find('(').map_or(ptx.len(), |e| start + e); - let end = ptx[start..].find(" + let end = ptx[start..] + .find( + " } -").map_or(ptx.len(), |e| start + e); +", + ) + .map_or(ptx.len(), |e| start + e); if ptx[start..header_end].contains(name) { assert!(found.is_none(), "two entries match {name}"); found = Some(&ptx[start..end]); @@ -201,11 +232,15 @@ mod tests { let mut ops = std::collections::BTreeMap::new(); for line in body.lines() { let line = line.trim(); - let line = if line.starts_with('@') { line.split_once(' ').map_or("", |(_, rest)| rest.trim()) } else { line }; + let line = + if line.starts_with('@') { line.split_once(' ').map_or("", |(_, rest)| rest.trim()) } else { line }; let Some(op) = line.split_whitespace().next() else { continue }; let op = op.trim_end_matches(';'); let memory = op.starts_with("ld.") || op.starts_with("st.") || op.starts_with("mov."); - let numeric = (!memory && op.contains(".f32")) || op.starts_with("cvt.rz") || op.starts_with("cvt.rn") || op.starts_with("shfl."); + let numeric = (!memory && op.contains(".f32")) + || op.starts_with("cvt.rz") + || op.starts_with("cvt.rn") + || op.starts_with("shfl."); if numeric { *ops.entry(op.to_owned()).or_insert(0) += 1; } @@ -213,7 +248,10 @@ mod tests { ops } - fn sum(a: std::collections::BTreeMap, b: std::collections::BTreeMap) -> std::collections::BTreeMap { + fn sum( + a: std::collections::BTreeMap, + b: std::collections::BTreeMap, + ) -> std::collections::BTreeMap { let mut out = a; for (k, v) in b { *out.entry(k).or_insert(0) += v; @@ -228,14 +266,20 @@ mod tests { // IEEE division everywhere: swiglu (g / (1 + e^-g)), the block scale (amax / 127), the code (x / d) assert_eq!(fused.get("div.rn.f32"), Some(&3), "{fused:?}"); assert!(fused.keys().all(|k| !k.starts_with("div.") || k == "div.rn.f32"), "{fused:?}"); - assert!(fused.keys().all(|k| !k.contains(".ftz") && !k.contains("approx") || k == "ex2.approx.f32"), "{fused:?}"); + assert!( + fused.keys().all(|k| !k.contains(".ftz") && !k.contains("approx") || k == "ex2.approx.f32"), + "{fused:?}" + ); // the fused kernel executes exactly the numeric instructions of the pair it replaces, flavour for flavour assert_eq!(fused, sum(swiglu, quantize)); } #[test] fn the_swiglu_quant_fusion_divides_like_the_pair_it_replaces() { - parity_of(include_str!("chain_window.ptx"), &String::from_utf8_lossy(include_bytes!("mtp_original_full_head_iq.ptx"))); + parity_of( + include_str!("chain_window.ptx"), + &String::from_utf8_lossy(include_bytes!("mtp_original_full_head_iq.ptx")), + ); } #[test] @@ -249,9 +293,15 @@ mod tests { #[test] fn the_parity_check_flags_a_fast_math_quantizer() { // the fast-math quantizer copy (native_head_iq, `--use_fast_math`) is a different flavour: this check must tell them apart - let fast = numeric_ops(entry_body(&String::from_utf8_lossy(include_bytes!("native_head_iq.ptx")), "quantize_q8_1_kernel")); + let fast = numeric_ops(entry_body( + &String::from_utf8_lossy(include_bytes!("native_head_iq.ptx")), + "quantize_q8_1_kernel", + )); assert!(fast.contains_key("div.approx.ftz.f32"), "{fast:?}"); - let precise = numeric_ops(entry_body(&String::from_utf8_lossy(include_bytes!("mtp_original_full_head_iq.ptx")), "quantize_q8_1_kernel")); + let precise = numeric_ops(entry_body( + &String::from_utf8_lossy(include_bytes!("mtp_original_full_head_iq.ptx")), + "quantize_q8_1_kernel", + )); assert!(precise.contains_key("div.rn.f32") && !precise.contains_key("div.approx.ftz.f32")); assert_ne!(fast, precise); } diff --git a/crates/cuda-driver/src/original_verify_window_draft.rs b/crates/cuda-driver/src/original_verify_window_draft.rs index 759c1bce..d5ed705b 100644 --- a/crates/cuda-driver/src/original_verify_window_draft.rs +++ b/crates/cuda-driver/src/original_verify_window_draft.rs @@ -13,7 +13,10 @@ pub(crate) const E_QSA: &str = "draft_commit_qsa_layers"; pub(crate) static DRAFT_COMMIT: AssetSpec = AssetSpec { name: "draft_commit.ptx", ptx: concat!(include_str!("draft_commit.ptx"), "\0").as_bytes(), - sha: [42, 84, 134, 220, 68, 111, 65, 245, 130, 212, 5, 3, 242, 10, 36, 211, 62, 194, 218, 187, 182, 163, 8, 18, 113, 83, 194, 204, 47, 192, 99, 150], + sha: [ + 42, 84, 134, 220, 68, 111, 65, 245, 130, 212, 5, 3, 242, 10, 36, 211, 62, 194, 218, 187, 182, 163, 8, 18, 113, + 83, 194, 204, 47, 192, 99, 150, + ], entries: &[E_GDN], unsealed: "Original verifier asset unsealed: draft_commit.ptx (fused verifier commit graph, GDN layers)", }; @@ -22,7 +25,10 @@ pub(crate) static DRAFT_COMMIT: AssetSpec = AssetSpec { pub(crate) static DRAFT_COMMIT_QSA: AssetSpec = AssetSpec { name: "draft_commit_qsa.ptx", ptx: concat!(include_str!("draft_commit_qsa.ptx"), "\0").as_bytes(), - sha: [223, 201, 194, 216, 75, 207, 191, 33, 97, 151, 192, 218, 191, 162, 203, 165, 182, 75, 182, 169, 170, 199, 204, 83, 70, 33, 188, 104, 184, 119, 48, 157], + sha: [ + 223, 201, 194, 216, 75, 207, 191, 33, 97, 151, 192, 218, 191, 162, 203, 165, 182, 75, 182, 169, 170, 199, 204, + 83, 70, 33, 188, 104, 184, 119, 48, 157, + ], entries: &[E_QSA], unsealed: "Original verifier asset unsealed: draft_commit_qsa.ptx (fused verifier commit graph, QSA layers)", }; diff --git a/crates/cuda-driver/src/original_verify_window_gpu.rs b/crates/cuda-driver/src/original_verify_window_gpu.rs index fbaa89cc..f61bf2ff 100644 --- a/crates/cuda-driver/src/original_verify_window_gpu.rs +++ b/crates/cuda-driver/src/original_verify_window_gpu.rs @@ -21,7 +21,8 @@ fn sealed_window_assets_load_on_the_device_and_export_every_named_entry() { // asset that is unsealed (none when every pin holds) is then reported by name. let result = bank.physical.ensure_window_assets(&all); let sealed = all.iter().filter(|a| a.sealed().is_ok()).map(|a| a.key()).collect::>(); - let loaded = bank.physical.window.borrow().iter().map(|(name, _, _)| *name).collect::>(); + let loaded = + bank.physical.window.borrow().iter().map(|(name, _, _)| *name).collect::>(); assert_eq!(loaded, sealed); match window_ops::unsealed_window_assets().first() { Some(_) => assert!(matches!(result, Err(Error::InvalidDriverValue(m)) if m.contains("unsealed"))), @@ -100,7 +101,12 @@ fn the_pcie_span_copy_stages_gate_up_down_like_the_dma_path() { [1, 1, 1], [128, 1, 1], 0, - vec![Arg::Address(address(&table)), Arg::Address(address(&count)), Arg::U64(address(&staging)), Arg::I64(stride as i64)], + vec![ + Arg::Address(address(&table)), + Arg::Address(address(&count)), + Arg::U64(address(&staging)), + Arg::I64(stride as i64), + ], ) .expect("command"); verify.launch(0, &mut rebase).expect("launch rebase"); diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs index f70ef15f..691322aa 100644 --- a/crates/cuda-driver/src/original_verify_window_gr.rs +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -73,8 +73,8 @@ pub(crate) static GR_FUSED: AssetSpec = AssetSpec { name: "mtp_original_full_fused_gr.ptx", ptx: include_bytes!("mtp_original_full_fused_gr.ptx"), sha: [ - 172, 84, 0, 167, 151, 43, 63, 36, 38, 72, 194, 222, 113, 239, 79, 23, 132, 102, 211, 139, 19, 146, 168, 58, 149, - 145, 179, 178, 78, 146, 197, 155, + 172, 84, 0, 167, 151, 43, 63, 36, 38, 72, 194, 222, 113, 239, 79, 23, 132, 102, 211, 139, 19, 146, 168, 58, + 149, 145, 179, 178, 78, 146, 197, 155, ], entries: &[E_NORM, E_SPLIT, E_STAGED, E_UP, E_DOWN1280, E_DOWN2560], unsealed: "Original verifier asset unsealed: mtp_original_full_fused_gr.ptx (fused hc read)", @@ -83,8 +83,8 @@ pub(crate) static GR_NORM: AssetSpec = AssetSpec { name: "mtp_original_full_gr_norm.ptx", ptx: include_bytes!("mtp_original_full_gr_norm.ptx"), sha: [ - 6, 214, 23, 123, 72, 44, 182, 116, 19, 198, 89, 106, 2, 145, 180, 218, 177, 133, 3, 50, 22, - 74, 146, 18, 175, 246, 123, 158, 253, 242, 17, 32, + 6, 214, 23, 123, 72, 44, 182, 116, 19, 198, 89, 106, 2, 145, 180, 218, 177, 133, 3, 50, 22, 74, 146, 18, 175, + 246, 123, 158, 253, 242, 17, 32, ], entries: &["mtp_full_gr_norm"], unsealed: "Original verifier asset unsealed: mtp_original_full_gr_norm.ptx (native weighted RMS norm)", @@ -93,8 +93,8 @@ pub(crate) static GR_POST: AssetSpec = AssetSpec { name: "mtp_original_full_gr_post.ptx", ptx: include_bytes!("mtp_original_full_gr_post.ptx"), sha: [ - 155, 71, 156, 15, 65, 42, 224, 7, 115, 129, 92, 154, 109, 137, 215, 244, 195, 247, 169, 240, - 246, 145, 135, 109, 232, 5, 235, 56, 23, 141, 151, 144, + 155, 71, 156, 15, 65, 42, 224, 7, 115, 129, 92, 154, 109, 137, 215, 244, 195, 247, 169, 240, 246, 145, 135, + 109, 232, 5, 235, 56, 23, 141, 151, 144, ], entries: &["mtp_full_down_silu", "mtp_full_pre_final", "mtp_full_native_write"], unsealed: "Original verifier asset unsealed: mtp_original_full_gr_post.ptx (native hc silu / gate / write)", @@ -103,8 +103,8 @@ pub(crate) static PLE_BATCH: AssetSpec = AssetSpec { name: "ple_native_batch.ptx", ptx: concat!(include_str!("ple_native_batch.ptx"), "\0").as_bytes(), sha: [ - 95, 165, 201, 48, 244, 12, 180, 157, 158, 121, 163, 94, 25, 17, 198, 133, 129, 249, 44, 9, - 119, 80, 239, 242, 140, 36, 94, 40, 112, 150, 74, 64, + 95, 165, 201, 48, 244, 12, 180, 157, 158, 121, 163, 94, 25, 17, 198, 133, 129, 249, 44, 9, 119, 80, 239, 242, + 140, 36, 94, 40, 112, 150, 74, 64, ], entries: &["ple_gate", "ple_rms", "ple_broadcast", "ple_conv", "ple_history"], unsealed: "Original verifier asset unsealed: ple_native_batch.ptx (native PLE post-ops)", @@ -307,34 +307,34 @@ mod assets_fn; #[allow(unused_imports)] pub(crate) use assets_fn::assets; #[allow(unused_imports)] -pub(crate) use assets_fn::shared_attributes; -#[allow(unused_imports)] -pub(crate) use assets_fn::tiled_down_geometry; -#[allow(unused_imports)] use assets_fn::check_geometry; #[allow(unused_imports)] use assets_fn::check_rows; #[allow(unused_imports)] -use assets_fn::row_span; -#[allow(unused_imports)] -use assets_fn::refuse; +use assets_fn::chunk_words; #[allow(unused_imports)] use assets_fn::multi_words; #[allow(unused_imports)] -use assets_fn::chunk_words; +use assets_fn::refuse; +#[allow(unused_imports)] +use assets_fn::row_span; +#[allow(unused_imports)] +pub(crate) use assets_fn::shared_attributes; +#[allow(unused_imports)] +pub(crate) use assets_fn::tiled_down_geometry; #[path = "original_verify_window_gr/plan_hc_read_fn.rs"] mod plan_hc_read_fn; #[allow(unused_imports)] -pub(crate) use plan_hc_read_fn::plan_hc_read; -#[allow(unused_imports)] -use plan_hc_read_fn::write_row; -#[allow(unused_imports)] pub(crate) use plan_hc_read_fn::plan_final_write; #[allow(unused_imports)] +pub(crate) use plan_hc_read_fn::plan_hc_read; +#[allow(unused_imports)] pub(crate) use plan_hc_read_fn::plan_head_mix; +#[allow(unused_imports)] +use plan_hc_read_fn::write_row; #[path = "original_verify_window_gr/plan_ple_row_fn.rs"] mod plan_ple_row_fn; #[allow(unused_imports)] -pub(crate) use plan_ple_row_fn::plan_ple_row; -#[allow(unused_imports)] pub(crate) use plan_ple_row_fn::plan_ple_layer1; +#[allow(unused_imports)] +pub(crate) use plan_ple_row_fn::plan_ple_row; diff --git a/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs index 7d509514..978af02b 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/assets_fn.rs @@ -3,18 +3,9 @@ #[allow(unused_imports)] use super::*; - /// Every module this family may launch from (the lead preloads them BEFORE capture). pub(crate) fn assets() -> Vec<&'static AssetSpec> { - vec![ - &GR_FUSED, - &GR_NORM, - &GR_POST, - &PLE_BATCH, - &proj::BF16, - &proj::HEAD_NATIVE, - &proj::HEAD_IQ, - ] + vec![&GR_FUSED, &GR_NORM, &GR_POST, &PLE_BATCH, &proj::BF16, &proj::HEAD_NATIVE, &proj::HEAD_IQ] } impl GrVariant { /// `env_variant()`: `STRATA_HC_SPLIT` unset / empty / other = staged, `0` plain, `1` split. @@ -112,7 +103,11 @@ pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'st // the chain down kernels stage up to 3 x 6 tokens (92,160 B) or 2 x 8 tokens (81,920 B) of activations let bytes = cfg.usable_shared.min(3 * 6 * (STAGED_TILE * 4)) as usize; out.push((&super::super::chain::CHAIN, super::super::chain::E_GR_DOWN_NB3, bytes)); - out.push((&super::super::chain::CHAIN, super::super::chain::E_GR_DOWN_NB2, cfg.usable_shared.min(2 * 8 * (STAGED_TILE * 4)) as usize)); + out.push(( + &super::super::chain::CHAIN, + super::super::chain::E_GR_DOWN_NB2, + cfg.usable_shared.min(2 * 8 * (STAGED_TILE * 4)) as usize, + )); } out } diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs index a6f615c4..17c59da7 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_hc_read_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `gr_read_group(half, apply, inj_prev, inj_out)` of `pre(l, group)` for the window rows /// `[tb, te)`: `fused_gr_read_multi(fa, n, xn_ + tb * HC * N, ...)`. /// @@ -43,7 +42,14 @@ pub(crate) fn plan_hc_read( // norm: variant >= split is [n, 4] blocks, the plain read [n] blocks let chain_gr = super::super::chain::flags().gr && cfg.variant == GrVariant::Staged; let norm = if chain_gr { - Launch::new(&super::super::chain::CHAIN, super::super::chain::E_GR_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + Launch::new( + &super::super::chain::CHAIN, + super::super::chain::E_GR_SPLIT, + [n as u32, HC as u32, 1], + [THREADS, 1, 1], + 0, + vec![A::Words(full.clone())], + )? } else if cfg.variant == GrVariant::Plain { Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? } else { @@ -86,7 +92,8 @@ pub(crate) fn plan_hc_read( } if chain_gr && staged { // same arithmetic as the staged kernel; the whole weight row in registers and three (two above six tokens) tile buffers in flight - let (entry, buffers) = if ct <= 6 { (super::super::chain::E_GR_DOWN_NB3, 3) } else { (super::super::chain::E_GR_DOWN_NB2, 2) }; + let (entry, buffers) = + if ct <= 6 { (super::super::chain::E_GR_DOWN_NB3, 3) } else { (super::super::chain::E_GR_DOWN_NB2, 2) }; let shared = buffers * ct as u32 * (STAGED_TILE * 4); if shared > cfg.usable_shared { return Err(Error::InvalidProjectionShape); @@ -115,7 +122,11 @@ pub(crate) fn plan_hc_read( let up = if chain_gr { // 16 columns per block (160 blocks) with every load of the block's rows hoisted; chain_gr_up8 (320 blocks) is the alternative shape - let (entry, blocks) = if super::super::chain::up8() { (super::super::chain::E_GR_UP8, UP_BLOCKS * 2) } else { (super::super::chain::E_GR_UP16, UP_BLOCKS) }; + let (entry, blocks) = if super::super::chain::up8() { + (super::super::chain::E_GR_UP8, UP_BLOCKS * 2) + } else { + (super::super::chain::E_GR_UP16, UP_BLOCKS) + }; Launch::new(&super::super::chain::CHAIN, entry, [blocks, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])? } else { Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])? diff --git a/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs b/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs index 8865b994..8a0cd401 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/plan_ple_row_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // ------------------------------------------------------------------------------------------------ // ple_layer1 // ------------------------------------------------------------------------------------------------ @@ -70,7 +69,14 @@ pub(crate) fn plan_ple_row( // native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate, // gated=d_gated, normalized=d_norm, conv=d_conv, result=hidden}) let rms = |input: u64, gamma: u64, output: u64| { - Launch::new(&PLE_BATCH, "ple_rms", [HC as u32, 1, 1], [1024, 1, 1], 0, vec![A::P(input), A::P(gamma), A::P(output)]) + Launch::new( + &PLE_BATCH, + "ple_rms", + [HC as u32, 1, 1], + [1024, 1, 1], + 0, + vec![A::P(input), A::P(gamma), A::P(output)], + ) }; out.push(rms(key, a.norm_key, query)?); out.push(rms(r, a.norm_query, norm)?); diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests.rs b/crates/cuda-driver/src/original_verify_window_gr/tests.rs index a5135d85..d7645025 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests.rs @@ -1,7 +1,7 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). -use super::*; use super::super::kernels::{LayoutMap, test_geometry}; +use super::*; const BASE: u64 = 0x7000_0000_0000; @@ -45,7 +45,7 @@ fn ple_addrs(key: PleKey) -> PleAddrs { } } -#[path = "tests/tiled_down_projection_covers.rs"] -mod tiled_down_projection_covers; #[path = "tests/head_mix_is_the_native.rs"] mod head_mix_is_the_native; +#[path = "tests/tiled_down_projection_covers.rs"] +mod tiled_down_projection_covers; diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs index 870afcb3..5cafe3c5 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/head_mix_is_the_native.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // ------------------------------------------------------------------------------------ head #[test] fn head_mix_is_the_native_unfused_gr_read_per_token() { @@ -106,7 +105,15 @@ fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { // conv + residual: hidden = Rt in place assert_eq!( l[8].args, - vec![A::P(0x6100_0000), A::P(s + 81_920), A::P(0x5400_0000), A::P(r), A::P(s + 122_880), A::P(s + 163_840), A::I32(1)] + vec![ + A::P(0x6100_0000), + A::P(s + 81_920), + A::P(0x5400_0000), + A::P(r), + A::P(s + 122_880), + A::P(s + 163_840), + A::I32(1) + ] ); assert_eq!((l[8].grid, l[8].block), ([40, 1, 1], [256, 1, 1])); // history advance reads the normalized row from the workspace @@ -131,10 +138,7 @@ fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() { assert_eq!(l[1].args, vec![A::P(emb), A::P(q8), A::I32(2560)]); // 2560 / 64 = 40 blocks < 64 per iteration: the "small" layout, 4 rows per block assert_eq!((l[2].grid, l[2].block), ([2560, 1, 1], [32, 4, 1])); - assert_eq!( - l[2].args, - vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)] - ); + assert_eq!(l[2].args, vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)]); // an unsupported native key type fails closed let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 }); assert_eq!( diff --git a/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs b/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs index dca8cfab..68871425 100644 --- a/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs +++ b/crates/cuda-driver/src/original_verify_window_gr/tests/tiled_down_projection_covers.rs @@ -10,7 +10,12 @@ fn the_tiled_down_projection_covers_every_row_and_token_with_four_two_token_tile let (grid, shared) = tiled_down_geometry(tokens); assert_eq!(grid[0], DOWN_BLOCKS, "41 blocks of 8 rows cover the 320 down rows and the 4 inject rows"); assert_eq!(grid[0] as usize * 8, 328); - assert_eq!(grid[1] as usize * 2 >= tokens && (grid[1] as usize - 1) * 2 < tokens, true, "{tokens} tokens in {} groups of two", grid[1]); + assert_eq!( + grid[1] as usize * 2 >= tokens && (grid[1] as usize - 1) * 2 < tokens, + true, + "{tokens} tokens in {} groups of two", + grid[1] + ); assert_eq!(shared, 4 * tokens.min(2) as u32 * 5120); assert!(shared <= 40_960); } @@ -119,7 +124,10 @@ fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { let w = weights(); let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); // norm: split, one block per token and stream - assert_eq!((plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), (E_SPLIT, [8, 4, 1], [256, 1, 1], 0)); + assert_eq!( + (plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), + (E_SPLIT, [8, 4, 1], [256, 1, 1], 0) + ); // down: ONE launch, 41 blocks, dynamic shared = 8 tokens * 2 * 1280 * 4 assert_eq!(plan.down.len(), 1); let d = &plan.down[0]; @@ -186,10 +194,12 @@ fn split_windows_read_their_own_rows_and_offset_the_scratch() { fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() { let m = arena(); let g = test_geometry(); - let plain = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + let plain = + plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1])); assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4)); - let split = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + let split = + plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1])); assert_eq!(split.down[0].entry, E_DOWN2560); let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152); @@ -265,7 +275,10 @@ fn final_write_is_native_post_in_place_per_row() { for (i, launch) in l.iter().enumerate() { let t = 2 + i; assert!(std::ptr::eq(launch.asset, &GR_POST)); - assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0)); + assert_eq!( + (launch.entry, launch.grid, launch.block, launch.shared), + ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0) + ); assert_eq!( launch.args, vec![ diff --git a/crates/cuda-driver/src/original_verify_window_kernels.rs b/crates/cuda-driver/src/original_verify_window_kernels.rs index 0cbea84c..ff019c31 100644 --- a/crates/cuda-driver/src/original_verify_window_kernels.rs +++ b/crates/cuda-driver/src/original_verify_window_kernels.rs @@ -165,7 +165,8 @@ impl Launch { self } pub(crate) fn command(&self) -> Result { - Command::new(self.entry, self.grid, self.block, self.shared, self.args.iter().map(A::abi).collect()).map(|c| c.with_cluster(self.cluster)) + Command::new(self.entry, self.grid, self.block, self.shared, self.args.iter().map(A::abi).collect()) + .map(|c| c.with_cluster(self.cluster)) } /// Short text used by unit tests and by diagnostics: `asset:entry <<>>`. pub(crate) fn label(&self) -> String { @@ -235,13 +236,8 @@ pub(crate) fn test_geometry() -> super::OriginalVerifyGeometry { #[cfg(test)] mod tests { use super::*; - static SPEC: AssetSpec = AssetSpec { - name: "demo", - ptx: b"// demo\n\0", - sha: [0; 32], - entries: &["a", "b"], - unsealed: "demo unsealed", - }; + static SPEC: AssetSpec = + AssetSpec { name: "demo", ptx: b"// demo\n\0", sha: [0; 32], entries: &["a", "b"], unsealed: "demo unsealed" }; #[test] fn launch_refuses_foreign_entries_and_empty_geometry() { @@ -255,9 +251,16 @@ mod tests { fn a_pin_mismatch_fails_closed_with_the_asset_name() { // all-zero digest cannot match any PTX assert_eq!(SPEC.sealed().unwrap_err(), Error::InvalidDriverValue("demo unsealed")); - static MARK: AssetSpec = AssetSpec { name: "m", ptx: b"UNSEALED placeholder\n\0", sha: [0; 32], entries: &[], unsealed: "m unsealed" }; + static MARK: AssetSpec = AssetSpec { + name: "m", + ptx: b"UNSEALED placeholder\n\0", + sha: [0; 32], + entries: &[], + unsealed: "m unsealed", + }; assert_eq!(MARK.sealed().unwrap_err(), Error::InvalidDriverValue("m unsealed")); - static NONUL: AssetSpec = AssetSpec { name: "n", ptx: b"abc", sha: [0; 32], entries: &[], unsealed: "n unsealed" }; + static NONUL: AssetSpec = + AssetSpec { name: "n", ptx: b"abc", sha: [0; 32], entries: &[], unsealed: "n unsealed" }; assert_eq!(NONUL.sealed().unwrap_err(), Error::InvalidDriverValue("n unsealed")); } diff --git a/crates/cuda-driver/src/original_verify_window_moe.rs b/crates/cuda-driver/src/original_verify_window_moe.rs index d00aea4b..69b557bd 100644 --- a/crates/cuda-driver/src/original_verify_window_moe.rs +++ b/crates/cuda-driver/src/original_verify_window_moe.rs @@ -54,7 +54,10 @@ const E_TO_BF16: &str = pub(crate) static ELEMENT: AssetSpec = AssetSpec { name: "mtp_original_full_element.ptx", ptx: include_bytes!("mtp_original_full_element.ptx"), - sha: [143,223,223,142,246,22,105,140,18,48,31,125,244,113,111,192,34,191,52,180,25,9,158,76,151,39,41,146,11,213,244,167], + sha: [ + 143, 223, 223, 142, 246, 22, 105, 140, 18, 48, 31, 125, 244, 113, 111, 192, 34, 191, 52, 180, 25, 9, 158, 76, + 151, 39, 41, 146, 11, 213, 244, 167, + ], entries: &[E_TO_BF16], unsealed: "Original verifier asset unsealed: mtp_original_full_element.ptx (f32_to_bf16_bulk)", }; @@ -64,18 +67,23 @@ const E_ROUTE: &str = "mtp_full_route"; pub(crate) static ROUTER: AssetSpec = AssetSpec { name: "mtp_original_full_router.ptx", ptx: include_bytes!("mtp_original_full_router.ptx"), - sha: [190,110,60,145,228,246,131,20,100,245,153,55,135,240,191,249,105,188,93,40,57,95,36,34,107,136,103,107,48,105,168,203], + sha: [ + 190, 110, 60, 145, 228, 246, 131, 20, 100, 245, 153, 55, 135, 240, 191, 249, 105, 188, 93, 40, 57, 95, 36, 34, + 107, 136, 103, 107, 48, 105, 168, 203, + ], entries: &[E_ROUTE], unsealed: "Original verifier asset unsealed: mtp_original_full_router.ptx (native router top-10)", }; -const E_ROUTER_TOP10: &str = - "_ZN6strata7kernels67_GLOBAL__N__bb863e17_34_mtp_original_full_router_legacy_cu_731ba72319router_top10_kernelEPKfiiiPiPf"; +const E_ROUTER_TOP10: &str = "_ZN6strata7kernels67_GLOBAL__N__bb863e17_34_mtp_original_full_router_legacy_cu_731ba72319router_top10_kernelEPKfiiiPiPf"; /// `router_top10.cu` (`router_top10`, the generic router when the native one is off). pub(crate) static ROUTER_LEGACY: AssetSpec = AssetSpec { name: "mtp_original_full_router_legacy.ptx", ptx: include_bytes!("mtp_original_full_router_legacy.ptx"), - sha: [165,132,18,36,151,87,204,53,30,184,51,46,128,126,121,241,179,218,88,101,87,77,15,183,23,158,245,88,223,112,175,36], + sha: [ + 165, 132, 18, 36, 151, 87, 204, 53, 30, 184, 51, 46, 128, 126, 121, 241, 179, 218, 88, 101, 87, 77, 15, 183, + 23, 158, 245, 88, 223, 112, 175, 36, + ], entries: &[E_ROUTER_TOP10], unsealed: "Original verifier asset unsealed: mtp_original_full_router_legacy.ptx (router_top10)", }; @@ -86,25 +94,24 @@ const E_SCALAR_GATE: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18scalar_gate_kernelEPKtS3_Pfi"; const E_SIGMOID: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f28native_scalar_sigmoid_kernelEPf"; -const E_SIGMOID_MULTI: &str = - "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_kernelEPf"; +const E_SIGMOID_MULTI: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_kernelEPf"; const E_SCALE_ROWS: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f17scale_rows_kernelEPfPKfi"; -const E_MOE_COMBINE: &str = - "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18moe_combine_kernelEPKfS3_S3_Pfiii"; +const E_MOE_COMBINE: &str = "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18moe_combine_kernelEPKfS3_S3_Pfiii"; /// `shared_expert.cu` (the Original TU: `shared_expert_multi`'s kernels and `moe_combine`). pub(crate) static SHARED: AssetSpec = AssetSpec { name: "mtp_original_full_shared.ptx", ptx: include_bytes!("mtp_original_full_shared.ptx"), - sha: [179,111,67,38,146,228,63,121,72,162,83,140,34,202,181,94,246,124,98,91,141,68,97,198,124,162,162,117,25,185,224,240], + sha: [ + 179, 111, 67, 38, 146, 228, 63, 121, 72, 162, 83, 140, 34, 202, 181, 94, 246, 124, 98, 91, 141, 68, 97, 198, + 124, 162, 162, 117, 25, 185, 224, 240, + ], entries: &[E_NATIVE_SWIGLU, E_SCALAR_GATE, E_SIGMOID, E_SIGMOID_MULTI, E_SCALE_ROWS, E_MOE_COMBINE], unsealed: "Original verifier asset unsealed: mtp_original_full_shared.ptx (shared expert)", }; -const E_SWIGLU_ENTRIES: &str = - "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx"; -const E_QUANTIZE_Q8_1: &str = - "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x"; +const E_SWIGLU_ENTRIES: &str = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx"; +const E_QUANTIZE_Q8_1: &str = "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x"; /// `iq_kernels.cu`: the entry-wise SwiGLU and the q8_1 quantizer of `native_expert_grouped` / /// `quantize_q8_1_rows`. The same PTX file as `proj::HEAD_IQ` (same pin); `proj` names only the MMVQ heads, /// so the window's MoE owns this entry list under a distinct asset name (the lead's loader must key modules by @@ -112,7 +119,10 @@ const E_QUANTIZE_Q8_1: &str = pub(crate) static HEAD_IQ_EXPERT: AssetSpec = AssetSpec { name: "mtp_original_full_head_iq.ptx#window-moe", ptx: include_bytes!("mtp_original_full_head_iq.ptx"), - sha: [229,116,82,204,172,119,42,138,138,119,37,59,198,201,100,235,183,188,97,253,178,233,117,39,169,119,95,140,207,60,59,159], + sha: [ + 229, 116, 82, 204, 172, 119, 42, 138, 138, 119, 37, 59, 198, 201, 100, 235, 183, 188, 97, 253, 178, 233, 117, + 39, 169, 119, 95, 140, 207, 60, 59, 159, + ], entries: &[E_SWIGLU_ENTRIES, E_QUANTIZE_Q8_1], unsealed: "Original verifier asset unsealed: mtp_original_full_head_iq.ptx (expert swiglu / q8_1 quantize)", }; @@ -123,7 +133,10 @@ const E_ADD_HITS: &str = pub(crate) static S2_HITS: AssetSpec = AssetSpec { name: "mtp_original_full_s2.ptx", ptx: include_bytes!("mtp_original_full_s2.ptx"), - sha: [251,185,23,213,144,234,128,51,138,123,223,7,178,202,109,69,143,167,39,99,186,39,158,87,107,204,30,236,136,54,253,85], + sha: [ + 251, 185, 23, 213, 144, 234, 128, 51, 138, 123, 223, 7, 178, 202, 109, 69, 143, 167, 39, 99, 186, 39, 158, 87, + 107, 204, 30, 236, 136, 54, 253, 85, + ], entries: &[E_ADD_HITS], unsealed: "Original verifier asset unsealed: mtp_original_full_s2.ptx (moe_hit_add)", }; @@ -133,7 +146,10 @@ const E_COMBINE: &str = "mtp_full_combine"; pub(crate) static COMBINE: AssetSpec = AssetSpec { name: "mtp_original_full_combine.ptx", ptx: include_bytes!("mtp_original_full_combine.ptx"), - sha: [34,83,254,45,100,19,80,244,68,90,10,105,196,160,252,34,184,92,47,255,202,124,189,83,111,254,93,41,18,248,31,183], + sha: [ + 34, 83, 254, 45, 100, 19, 80, 244, 68, 90, 10, 105, 196, 160, 252, 34, 184, 92, 47, 255, 202, 124, 189, 83, + 111, 254, 93, 41, 18, 248, 31, 183, + ], entries: &[E_COMBINE], unsealed: "Original verifier asset unsealed: mtp_original_full_combine.ptx (native MoE combine)", }; @@ -161,9 +177,21 @@ const DOWN_ENTRIES: &[(u32, &str)] = &[ (8, "window_moe_down_8"), ]; const EXPERT_ENTRIES: &[&str] = &[ - "window_moe_gu_16", "window_moe_gu_17", "window_moe_gu_18", "window_moe_gu_21", "window_moe_gu_22", - "window_moe_gu_23", "window_moe_gu_29", "window_moe_gu_42", "window_moe_gu_12", "window_moe_gu_13", - "window_moe_gu_8", "window_moe_down_20", "window_moe_down_23", "window_moe_down_42", "window_moe_down_7", + "window_moe_gu_16", + "window_moe_gu_17", + "window_moe_gu_18", + "window_moe_gu_21", + "window_moe_gu_22", + "window_moe_gu_23", + "window_moe_gu_29", + "window_moe_gu_42", + "window_moe_gu_12", + "window_moe_gu_13", + "window_moe_gu_8", + "window_moe_down_20", + "window_moe_down_23", + "window_moe_down_42", + "window_moe_down_7", "window_moe_down_8", ]; /// The grouped native-expert gate/up and down kernels (new source `original_verify_window_moe_experts.cu`: the @@ -172,7 +200,10 @@ const EXPERT_ENTRIES: &[&str] = &[ pub(crate) static EXPERTS: AssetSpec = AssetSpec { name: "original_verify_window_moe_experts.ptx", ptx: include_bytes!("original_verify_window_moe_experts.ptx"), - sha: [36, 210, 140, 205, 156, 58, 91, 190, 219, 235, 147, 59, 79, 235, 55, 111, 132, 10, 116, 226, 26, 68, 130, 23, 72, 140, 6, 238, 35, 130, 17, 87], + sha: [ + 36, 210, 140, 205, 156, 58, 91, 190, 219, 235, 147, 59, 79, 235, 55, 111, 132, 10, 116, 226, 26, 68, 130, 23, + 72, 140, 6, 238, 35, 130, 17, 87, + ], entries: EXPERT_ENTRIES, unsealed: "Original verifier asset unsealed: original_verify_window_moe_experts.ptx (grouped native expert gate/up and down)", }; @@ -183,7 +214,10 @@ pub(crate) static EXPERTS: AssetSpec = AssetSpec { pub(crate) static PCIE: AssetSpec = AssetSpec { name: "original_verify_window_pcie.ptx", ptx: include_bytes!("original_verify_window_pcie.ptx"), - sha: [203, 235, 50, 63, 118, 71, 104, 47, 238, 158, 211, 241, 47, 183, 183, 165, 179, 235, 25, 47, 33, 102, 198, 236, 150, 184, 29, 85, 195, 186, 185, 209], + sha: [ + 203, 235, 50, 63, 118, 71, 104, 47, 238, 158, 211, 241, 47, 183, 183, 165, 179, 235, 25, 47, 33, 102, 198, 236, + 150, 184, 29, 85, 195, 186, 185, 209, + ], entries: &["verify_fetch_spans_kernel"], unsealed: "Original verifier asset unsealed: original_verify_window_pcie.ptx (PCIe span staging copy)", }; @@ -193,7 +227,10 @@ pub(crate) static PCIE: AssetSpec = AssetSpec { pub(crate) static PCIE_FAST: AssetSpec = AssetSpec { name: "original_verify_window_pcie_fast.ptx", ptx: include_bytes!("original_verify_window_pcie_fast.ptx"), - sha: [116, 7, 133, 159, 141, 136, 129, 102, 63, 58, 100, 110, 190, 40, 140, 49, 19, 140, 206, 50, 39, 193, 197, 217, 226, 229, 146, 100, 142, 215, 122, 234], + sha: [ + 116, 7, 133, 159, 141, 136, 129, 102, 63, 58, 100, 110, 190, 40, 140, 49, 19, 140, 206, 50, 39, 193, 197, 217, + 226, 229, 146, 100, 142, 215, 122, 234, + ], entries: &[ "verify_fetch_spans_k1u4_kernel", "verify_fetch_spans_k1u8_kernel", @@ -293,46 +330,46 @@ mod tests; #[path = "original_verify_window_moe/pcie_fast_kernel_fn.rs"] mod pcie_fast_kernel_fn; #[allow(unused_imports)] -pub(crate) use pcie_fast_kernel_fn::pcie_fast_kernel; +use pcie_fast_kernel_fn::align256; #[allow(unused_imports)] pub(crate) use pcie_fast_kernel_fn::assets; #[allow(unused_imports)] -pub(crate) use pcie_fast_kernel_fn::shared_attributes; -#[allow(unused_imports)] -use pcie_fast_kernel_fn::gu_qk; +use pcie_fast_kernel_fn::check_rows; #[allow(unused_imports)] use pcie_fast_kernel_fn::d_qk; #[allow(unused_imports)] use pcie_fast_kernel_fn::expert_blob; #[allow(unused_imports)] -use pcie_fast_kernel_fn::check_rows; +use pcie_fast_kernel_fn::f32s; +#[allow(unused_imports)] +use pcie_fast_kernel_fn::gu_qk; #[allow(unused_imports)] use pcie_fast_kernel_fn::items; #[allow(unused_imports)] -use pcie_fast_kernel_fn::f32s; +pub(crate) use pcie_fast_kernel_fn::pcie_fast_kernel; #[allow(unused_imports)] use pcie_fast_kernel_fn::plan_word; #[allow(unused_imports)] -use pcie_fast_kernel_fn::align256; +pub(crate) use pcie_fast_kernel_fn::shared_attributes; #[path = "original_verify_window_moe/plan_f32_to_bf16_fn.rs"] mod plan_f32_to_bf16_fn; #[allow(unused_imports)] +pub(crate) use plan_f32_to_bf16_fn::expert_scratch; +#[allow(unused_imports)] use plan_f32_to_bf16_fn::plan_f32_to_bf16; #[allow(unused_imports)] +pub(crate) use plan_f32_to_bf16_fn::plan_quantize_expert_input; +#[allow(unused_imports)] use plan_f32_to_bf16_fn::plan_route; #[allow(unused_imports)] pub(crate) use plan_f32_to_bf16_fn::plan_router; #[allow(unused_imports)] pub(crate) use plan_f32_to_bf16_fn::plan_shared_expert; -#[allow(unused_imports)] -pub(crate) use plan_f32_to_bf16_fn::plan_quantize_expert_input; -#[allow(unused_imports)] -pub(crate) use plan_f32_to_bf16_fn::expert_scratch; #[path = "original_verify_window_moe/plan_expert_groups_fn.rs"] mod plan_expert_groups_fn; #[allow(unused_imports)] +pub(crate) use plan_expert_groups_fn::plan_combine; +#[allow(unused_imports)] pub(crate) use plan_expert_groups_fn::plan_expert_groups; #[allow(unused_imports)] pub(crate) use plan_expert_groups_fn::plan_hit_add; -#[allow(unused_imports)] -pub(crate) use plan_expert_groups_fn::plan_combine; diff --git a/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs index d3a0600a..5fe9e136 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/pcie_fast_kernel_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `LELEKA_PCIE_KERNEL` = `k1u4|k1u8|k1u16|k2u4|k2u8|k2u16` selects an alternative staging copy kernel of the copy-kernel /// PCIe mode (default: the sealed `verify_fetch_spans_kernel`); `LELEKA_PCIE_GRID=BLOCKSxTHREADS` its launch shape /// (default 384x256, the Original's `48 * 8` blocks of 256). diff --git a/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs index 9499e5de..eeded43b 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/plan_expert_groups_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `grouped(gp, gs, gn)` of `post`: `native_expert_grouped(L, ...)` for one tier, `L` the layer's native /// layout and `cap = n * K` groups / entries. pub(crate) fn plan_expert_groups( @@ -82,7 +81,11 @@ pub(crate) fn plan_expert_groups( }; let mut launches = Vec::with_capacity(4); // sm_120 GU_SWIGLU: one launch for gate/up + SwiGLU + q8_1 where the layer's format has the fused kernel (80 dots a row at n_embd 2560, n_ff a multiple of 32) - let fused = if knobs.gu_swiglu && blob.n_embd == 2560 && blob.n_ff % 32 == 0 { super::super::sm120::gu_swiglu_entry(blob.gu_type) } else { None }; + let fused = if knobs.gu_swiglu && blob.n_embd == 2560 && blob.n_ff % 32 == 0 { + super::super::sm120::gu_swiglu_entry(blob.gu_type) + } else { + None + }; if let Some(entry) = fused { // upstream's 88-byte NativeExpertLayout: the 64 bytes above, then tail_off, had_block (+ padding) and d_signs, all zero let mut fused_words = words.clone(); @@ -93,27 +96,35 @@ pub(crate) fn plan_expert_groups( [(n_ff / 32) as u32, cap as u32, 1], [512, 1, 1], 0, - vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_tok), A::P(x_q8_1), A::Words(fused_words), A::P(hq)], + vec![ + A::P(grp_ptr), + A::P(grp_start), + A::P(n_groups), + A::P(ent_tok), + A::P(x_q8_1), + A::Words(fused_words), + A::P(hq), + ], )?); } else { - launches.push(Launch::new( - &EXPERTS, - gu_entry, - [(2 * n_ff).div_ceil(8) as u32, cap as u32, 1], - [256, 1, 1], - 0, - vec![ - A::P(grp_ptr), - A::P(grp_start), - A::P(n_groups), - A::P(ent_tok), - A::P(x_q8_1), - A::Words(words.clone()), - A::P(gate), - A::P(up), - ], - )?); - launches.extend(swiglu_quant(tiny)?); + launches.push(Launch::new( + &EXPERTS, + gu_entry, + [(2 * n_ff).div_ceil(8) as u32, cap as u32, 1], + [256, 1, 1], + 0, + vec![ + A::P(grp_ptr), + A::P(grp_start), + A::P(n_groups), + A::P(ent_tok), + A::P(x_q8_1), + A::Words(words.clone()), + A::P(gate), + A::P(up), + ], + )?); + launches.extend(swiglu_quant(tiny)?); } launches.push(Launch::new( &EXPERTS, diff --git a/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs b/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs index fbc8ad24..15259a3f 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/plan_f32_to_bf16_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `f32_to_bf16_bulk(x, y, count)`: `to_bf16_kernel<<>>(x, y, count)`. pub(super) fn plan_f32_to_bf16(x: u64, y: u64, count: usize) -> Result { Launch::new( @@ -22,14 +21,7 @@ pub(super) fn plan_f32_to_bf16(x: u64, y: u64, count: usize) -> Result { /// `route<<>>(logits, ids, weights)` (`native_router_top10(_multi)`). pub(super) fn plan_route(logits: u64, ids: u64, weights: u64, tokens: usize) -> Result { - Launch::new( - &ROUTER, - E_ROUTE, - [tokens as u32, 1, 1], - [32, 8, 1], - 0, - vec![A::P(logits), A::P(ids), A::P(weights)], - ) + Launch::new(&ROUTER, E_ROUTE, [tokens as u32, 1, 1], [32, 8, 1], 0, vec![A::P(logits), A::P(ids), A::P(weights)]) } /// The router of a group: Router logits and top-10 for rows `[tb, te)`. diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests.rs b/crates/cuda-driver/src/original_verify_window_moe/tests.rs index d2f1577d..bf90f4ab 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests.rs @@ -70,7 +70,7 @@ fn assert_abi(launches: &[Launch]) { #[path = "tests/alternative_pcie_staging_copy.rs"] mod alternative_pcie_staging_copy; -#[path = "tests/shared_gate_without_native_bf16.rs"] -mod shared_gate_without_native_bf16; #[path = "tests/hit_add_scans_the_cpu.rs"] mod hit_add_scans_the_cpu; +#[path = "tests/shared_gate_without_native_bf16.rs"] +mod shared_gate_without_native_bf16; diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs index ea0b0f07..1f546723 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/alternative_pcie_staging_copy.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn the_alternative_pcie_staging_copy_kernels_are_sealed() { PCIE_FAST.assert_sealed_and_fail_closed(); @@ -165,10 +164,7 @@ fn generic_router_is_the_original_router_top10_launch() { ); assert_abi(&l); // the batched launch needs the native router - assert_eq!( - plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), - Error::InvalidQwenShape - ); + assert_eq!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), Error::InvalidQwenShape); } #[test] @@ -271,7 +267,10 @@ fn shared_expert_without_dec_batch_converts_and_gates_one_row_at_a_time() { let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(1, 3, 0), false).unwrap(); // 2 conversions, the six projection / activation launches, 2 x (mmvf + sigmoid), scale assert_eq!(l.len(), 2 + 6 + 4 + 1); - assert_eq!((l[0].grid, l[0].args.clone()), ([10, 1, 1], vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(at(&m, "sh_bf16", 2560 * 2)), A::I64(2560)])); + assert_eq!( + (l[0].grid, l[0].args.clone()), + ([10, 1, 1], vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(at(&m, "sh_bf16", 2560 * 2)), A::I64(2560)]) + ); assert_eq!(l[1].args[1], A::P(at(&m, "sh_bf16", 2 * 2560 * 2))); // the projections are still two-row launches, but the gate is per token assert_eq!(l[3].entry, "head_n8_t2_large"); diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs index d9e830fa..292f23cd 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/hit_add_scans_the_cpu.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // ---- hit add, combine ---------------------------------------------------------------------- #[test] diff --git a/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs b/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs index 94399b13..6235cb50 100644 --- a/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs +++ b/crates/cuda-driver/src/original_verify_window_moe/tests/shared_gate_without_native_bf16.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn shared_gate_without_native_bf16_extra_reads_the_bf16_activation() { let m = map(); @@ -66,10 +65,7 @@ fn expert_blob_layout_matches_native_expert_layout() { assert_eq!((b.up_off, b.down_off), (640 * 660, 2 * 640 * 660)); assert_eq!(b.bytes, 844_800 + 2560 * 360); assert_eq!(b.bytes % 16, 0); - assert_eq!( - b.words(), - vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400] - ); + assert_eq!(b.words(), vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]); // Q4_K gate/up (144 B per 256) and Q8_0 down (34 B per 32) let q = expert_blob(12, 8, 2560, 640).unwrap(); assert_eq!((q.gu_row, q.d_row, q.bytes), (1440, 680, 2 * 640 * 1440 + 2560 * 680)); @@ -173,10 +169,7 @@ fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() { [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(165)), A::P(at(&m, "nat_xq", 3 * 2880))] ); assert_eq!(l[0].grid, [160, 20, 1]); - assert_eq!( - l[3].args[..4], - [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(85))] - ); + assert_eq!(l[3].args[..4], [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(85))]); // output rows of the group start at tb*K*N assert_eq!(l[3].args[6], A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4))); assert_eq!(l[3].grid, [320, 20, 1]); @@ -223,7 +216,10 @@ fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_do assert_eq!((fused[0].grid, fused[0].block, fused[0].shared), ([20, 30, 1], [512, 1, 1], 0)); // the arguments: the same group tables, activations and q8_1 output as the three kernels, upstream's 88-byte layout let gu = &off[0].args; - let scratch_hq = match &off[2].args[1] { A::P(p) => *p, _ => unreachable!() }; + let scratch_hq = match &off[2].args[1] { + A::P(p) => *p, + _ => unreachable!(), + }; assert_eq!(fused[0].args[..5], gu[..5]); assert_eq!(fused[0].args[6], A::P(scratch_hq)); match (&fused[0].args[5], &gu[5]) { @@ -238,8 +234,14 @@ fn gu_swiglu_replaces_gate_up_swiglu_and_quantize_by_one_launch_and_keeps_the_do assert_eq!(fused[1].args, off[3].args); assert_eq!(fused[1].entry, off[3].entry); // layers whose gate/up format has no fused kernel keep the three-kernel plan; so does a knobs set without the switch - assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], "window_moe_gu_12"); - assert_eq!(entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], "sm120_moe_gu_swiglu_22"); + assert_eq!( + entries(&plan_expert_groups(&m, &g, &on, &f, 7, rows(0, 3, 0), ExpertTier::Vram).unwrap())[0], + "window_moe_gu_12" + ); + assert_eq!( + entries(&plan_expert_groups(&m, &g, &on, &f, 8, rows(0, 3, 0), ExpertTier::Pcie).unwrap())[0], + "sm120_moe_gu_swiglu_22" + ); assert_eq!(entries(&off).len(), 4); } diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index b5fdd120..80d9f37e 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -21,20 +21,18 @@ //! : `, and a kernel asset that is not sealed refuses the whole window //! BEFORE capture with `... asset unsealed: ()` (`unsealed_window_assets` //! lists them). A partially bound window can therefore never be recorded or replayed. -use super::*; +use super::chain; use super::gr::{self, GrConfig, OriginalVerifyGrBinding}; use super::kernels::{A, AssetSpec, Launch}; -use super::chain; -use super::sm120; -use super::window_plan::gdn_index; use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding}; use super::planner::{Planner, WindowWeights}; use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs}; use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope}; +use super::sm120; +use super::window_plan::gdn_index; use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group}; -use super::window_record::{ - ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window, -}; +use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window}; +use super::*; use crate::{OriginalNativeEmbedRows, OriginalNativeHeadGraphResources}; /// Producers with no genuine capturable owner in this tree: none. Every `WindowOps` call is bound; what is @@ -73,7 +71,13 @@ pub struct OriginalVerifyWindowResources<'a, 'ctx> { } macro_rules! unattached { ($producer:literal, $what:literal) => { - Error::InvalidDriverValue(concat!("Original verifier producer unbound: ", $producer, ": ", $what, " not attached")) + Error::InvalidDriverValue(concat!( + "Original verifier producer unbound: ", + $producer, + ": ", + $what, + " not attached" + )) }; } @@ -95,14 +99,14 @@ mod all_window_assets_fn; #[allow(unused_imports)] pub(super) use all_window_assets_fn::all_window_assets; #[allow(unused_imports)] -pub use all_window_assets_fn::unsealed_window_assets; -#[allow(unused_imports)] use all_window_assets_fn::unsealed_keys; +#[allow(unused_imports)] +pub use all_window_assets_fn::unsealed_window_assets; +#[path = "original_verify_window_ops/impl_originalverifier.rs"] +mod impl_originalverifier; #[path = "original_verify_window_ops/impl_originalverifywindowops.rs"] mod impl_originalverifywindowops; #[path = "original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs"] mod impl_windowops_for_originalverifywindowops; -#[path = "original_verify_window_ops/impl_originalverifier.rs"] -mod impl_originalverifier; #[allow(unused_imports)] pub(crate) use impl_originalverifier::graph_oom_at; diff --git a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs index ad2e6bce..d80a937f 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/all_window_assets_fn.rs @@ -3,12 +3,19 @@ #[allow(unused_imports)] use super::*; - /// Every kernel asset a window can launch from (all families), regardless of what is attached. pub(in super::super) fn all_window_assets() -> Vec<&'static AssetSpec> { let mut all = Vec::new(); all.extend(proj::mmvq_assets()); - for family in [gr::assets(), qsa::assets(), qsa::cluster_assets(&qsa::OriginalVerifyQsaPolicy { cluster_topk: true, ..qsa::OriginalVerifyQsaPolicy::mode17() }), moe::assets()] { + for family in [ + gr::assets(), + qsa::assets(), + qsa::cluster_assets(&qsa::OriginalVerifyQsaPolicy { + cluster_topk: true, + ..qsa::OriginalVerifyQsaPolicy::mode17() + }), + moe::assets(), + ] { for spec in family { if !all.iter().any(|a: &&AssetSpec| std::ptr::eq(*a, spec)) { all.push(spec); @@ -58,7 +65,9 @@ impl OriginalVerifyExpertLayout { pub fn role_bytes(&self, layer: usize) -> Result<[usize; 3]> { self.role_bytes .as_ref() - .ok_or(Error::InvalidDriverValue("Original verifier producer unbound: pcie_stage: expert span sizes not attached"))? + .ok_or(Error::InvalidDriverValue( + "Original verifier producer unbound: pcie_stage: expert span sizes not attached", + ))? .get(layer) .copied() .ok_or(Error::InvalidQwenShape) diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs index 02f7bd3e..4bae9670 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifier.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { /// Record the T-token window graph for `t` (split windows use two groups). /// `resources` is this graph's own aggregate (its head rows hold `t` rows). @@ -23,7 +22,12 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?; policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok(); static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| eprintln!("leleka-serve qsa decode top-k: {} (compute capability {cc})", if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" })); + SAID.call_once(|| { + eprintln!( + "leleka-serve qsa decode top-k: {} (compute capability {cc})", + if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" } + ) + }); } // the sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per recording { @@ -84,5 +88,9 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { /// A graph instantiate that ran out of device memory, named by the graph that did not fit (`window` = its T, 0 = the commit graph). /// Any other error, and an out-of-memory that came with a cleanup failure (`Multiple`), stays as it is. pub(crate) fn graph_oom_at(error: Error, window: usize) -> Error { - if crate::original_gpu_schedule::is_graph_out_of_memory(&error) { Error::GraphOutOfMemory { window } } else { error } + if crate::original_gpu_schedule::is_graph_out_of_memory(&error) { + Error::GraphOutOfMemory { window } + } else { + error + } } diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs index 959df13d..f48ee78b 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_originalverifywindowops.rs @@ -15,7 +15,13 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { pub(super) fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> { let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?; self.capture.side_fork(0)?; - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, g, rows.begin, rows.end)?; + self.resources.base.journal.capture_layer_stage( + OriginalVerifyGdnStage::AlphaBeta, + self.capture, + g, + rows.begin, + rows.end, + )?; self.capture.side_end(0)?; self.capture.side_fork(1)?; self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?; diff --git a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs index e3c81d8f..76af0ae2 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/impl_windowops_for_originalverifywindowops.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { fn embed(&mut self) -> Result<()> { let g = self.geometry(); @@ -64,13 +63,25 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.plan_launch(|p| p.mmvq(layer, projection, rows)) } fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()> { - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Conv, self.capture, layer, rows.begin, rows.end) + self.resources.base.journal.capture_layer_stage( + OriginalVerifyGdnStage::Conv, + self.capture, + layer, + rows.begin, + rows.end, + ) } fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> { if self.side_gdn() { return Ok(()); // issued on side stream 0 by `issue_gdn_side` } - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, layer, rows.begin, rows.end) + self.resources.base.journal.capture_layer_stage( + OriginalVerifyGdnStage::AlphaBeta, + self.capture, + layer, + rows.begin, + rows.end, + ) } fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> { if self.side_gdn() { @@ -78,7 +89,13 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { self.capture.side_join(0)?; self.capture.side_join(1)?; } - self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Recurrence, self.capture, layer, rows.begin, rows.end) + self.resources.base.journal.capture_layer_stage( + OriginalVerifyGdnStage::Recurrence, + self.capture, + layer, + rows.begin, + rows.end, + ) } fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { self.plan_launch(|p| p.qsa_index_k(q, rows, batched)) @@ -133,7 +150,11 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { let layout = self.plan(); let flag = self.mapped_flag(11)?; let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + let mapped = self.journal().physical.mapped_address( + 14, + rows.group * layout.mapped_stride() * 4, + layout.words * 4, + )?; return self.launch(vec![Launch::new( &chain::CHAIN, chain::E_WAIT_COPY_I32, @@ -147,7 +168,8 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { // The pool's GPU plan, copied from mapped host memory into this group's device block. let layout = self.plan(); let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?; - let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; + let mapped = + self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?; self.submit(vec![command( "verify_copy_i32_from_mapped_kernel", [1, 1, 1], diff --git a/crates/cuda-driver/src/original_verify_window_ops/tests.rs b/crates/cuda-driver/src/original_verify_window_ops/tests.rs index f745de10..d5f90738 100644 --- a/crates/cuda-driver/src/original_verify_window_ops/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_ops/tests.rs @@ -42,7 +42,8 @@ fn every_window_asset_is_sealed_and_a_corrupted_pin_is_reported_by_name() { } // Fail-closed reporting is alive: a one-byte-corrupted copy, a wrong digest and a zero pin of a sealed asset // are each reported by module key (once), and the untouched specs stay out of the list. - let corrupted = moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); + let corrupted = + moe::EXPERTS.derived(crate::sealed_ptx::test_support::one_byte_corrupted(moe::EXPERTS.ptx), moe::EXPERTS.sha); let wrong_digest = qsa::GATE.derived(qsa::GATE.ptx, [7; 32]); let zero_pin = gr::assets()[0].derived(gr::assets()[0].ptx, [0; 32]); assert_eq!( diff --git a/crates/cuda-driver/src/original_verify_window_plan.rs b/crates/cuda-driver/src/original_verify_window_plan.rs index 7ba91a13..5f9ef9a6 100644 --- a/crates/cuda-driver/src/original_verify_window_plan.rs +++ b/crates/cuda-driver/src/original_verify_window_plan.rs @@ -190,11 +190,16 @@ mod tests { let s = schedule(2, 3); let text: Vec = s .iter() - .map(|x| format!("{}{}{}", if x.phase == Phase::Pre { "pre" } else { "post" }, x.layer, ['A', 'B'][x.group])) + .map(|x| { + format!("{}{}{}", if x.phase == Phase::Pre { "pre" } else { "post" }, x.layer, ['A', 'B'][x.group]) + }) .collect(); assert_eq!( text, - ["pre0A", "pre0B", "post0A", "pre1A", "post0B", "pre1B", "post1A", "pre2A", "post1B", "pre2B", "post2A", "post2B"] + [ + "pre0A", "pre0B", "post0A", "pre1A", "post0B", "pre1B", "post1A", "pre2A", "post1B", "pre2B", "post2A", + "post2B" + ] ); // B's mixer of layer l never precedes A's mixer of the same layer, and no group's post // precedes its own pre @@ -295,7 +300,8 @@ mod tests { assert!(at(Phase::Pre, l, 1) < at(Phase::Post, l, 0)); } // each pre rings once, in the order the host serves - let rings: Vec = s.iter().filter(|x| x.phase == Phase::Pre).map(|x| ring(x.layer, 2, x.group)).collect(); + let rings: Vec = + s.iter().filter(|x| x.phase == Phase::Pre).map(|x| ring(x.layer, 2, x.group)).collect(); assert_eq!(rings, (1..=2 * layers as u32).collect::>()); } } diff --git a/crates/cuda-driver/src/original_verify_window_planner.rs b/crates/cuda-driver/src/original_verify_window_planner.rs index 6d305af9..9af239ed 100644 --- a/crates/cuda-driver/src/original_verify_window_planner.rs +++ b/crates/cuda-driver/src/original_verify_window_planner.rs @@ -5,6 +5,7 @@ //! `WindowWeights` source. The real `OriginalVerifyWindowOps` submits those launches on the //! capture stream; the tests run the whole recorder through `PlanOps` (no driver) to pin //! the complete launch order of a window against verify.cpp. +use super::OriginalVerifyGeometry; use super::gr::{self, GrConfig, HcAddrs, HeadAddrs, PleAddrs, PleConfig}; use super::kernels::{ArenaMap, Launch}; use super::moe::{self, MoeKnobs, MoeLayerAddrs, OriginalVerifyExpertFormats}; @@ -12,7 +13,6 @@ use super::proj::{self, GdnProjectionAddrs, QsaProjectionAddrs}; use super::qsa::{QsaLayerAddrs, QsaRope, QsaWindow}; use super::window_plan::{gdn_index, qsa_index}; use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowPolicy}; -use super::OriginalVerifyGeometry; use crate::{Error, Result}; /// Where the planners read model weights and fixed state addresses from. The real source is the @@ -66,7 +66,11 @@ impl<'p> Planner<'p> { Self::moe_knobs_of(&self.policy) } fn ple_config(&self) -> PleConfig { - PleConfig { native_value_bf16: self.policy.native_ple, native_postops: self.policy.native_ple, dispatch: self.policy.dispatch } + PleConfig { + native_value_bf16: self.policy.native_ple, + native_postops: self.policy.native_ple, + dispatch: self.policy.dispatch, + } } fn qsa_window(&self) -> Result> { QsaWindow::new(self.arena, self.geo, self.policy.qsa, self.weights.rope()?) @@ -153,7 +157,15 @@ impl<'p> Planner<'p> { moe::plan_quantize_expert_input(self.arena, &self.geo, &self.moe_knobs(), rows) } pub(crate) fn expert_groups(&self, layer: usize, rows: Rows, tier: ExpertTier) -> Result> { - moe::plan_expert_groups(self.arena, &self.geo, &self.moe_knobs(), self.weights.expert_formats()?, layer, rows, tier) + moe::plan_expert_groups( + self.arena, + &self.geo, + &self.moe_knobs(), + self.weights.expert_formats()?, + layer, + rows, + tier, + ) } pub(crate) fn hit_add(&self, rows: Rows) -> Result> { moe::plan_hit_add(self.arena, &self.geo, rows) diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests.rs b/crates/cuda-driver/src/original_verify_window_planner/tests.rs index 896811eb..14461ace 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests.rs @@ -21,7 +21,11 @@ fn w(a: u64) -> NativeWeight { impl WindowWeights for Fake { fn gdn_projections(&self, g: usize) -> Result { let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; - Ok(GdnProjectionAddrs { qkv: w(b), gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, out: NativeWeight { ty: 12, data: b + 0x200_0000 } }) + Ok(GdnProjectionAddrs { + qkv: w(b), + gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, + out: NativeWeight { ty: 12, data: b + 0x200_0000 }, + }) } fn qsa_projections(&self, q: usize) -> Result { let b = 0x20_0000_0000u64 + q as u64 * 0x1000_0000; @@ -54,12 +58,26 @@ impl WindowWeights for Fake { fn qsa(&self, q: usize) -> Result { let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; Ok(QsaLayerAddrs { - weights: QsaWeightAddrs { q_norm: b, k_norm: b + 0x1_0000, index_q_norm: b + 0x2_0000, index_k_proj: b + 0x100_0000, index_q_proj: b + 0x200_0000 }, + weights: QsaWeightAddrs { + q_norm: b, + k_norm: b + 0x1_0000, + index_q_norm: b + 0x2_0000, + index_k_proj: b + 0x100_0000, + index_q_proj: b + 0x200_0000, + }, kv: OriginalVerifyQsaKvBinding { resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], table: b + 0x1300_0000, host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], - resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000], + resolver: [ + b + 0x1300_0000, + b + 0x1310_0000, + b + 0x1320_0000, + b + 0x1330_0000, + b + 0x1340_0000, + b + 0x1350_0000, + b + 0x1360_0000, + ], slots: 8192, pooled: b + 0x1400_0000, pooled_bytes: 1026 * 512, @@ -89,9 +107,20 @@ impl WindowWeights for Fake { /// Readable name of a launched kernel: the entry, or for a mangled Original kernel its base name. fn kernel(l: &Launch) -> String { const BASES: [&str; 14] = [ - "mmvf_multi_kernel", "mmvf_kernel", "to_bf16_kernel", "native_swiglu_kernel", "scalar_gate_kernel", - "native_scalar_sigmoid_multi_kernel", "native_scalar_sigmoid_kernel", "scale_rows_kernel", "moe_combine_kernel", - "swiglu_entries_kernel", "quantize_q8_1_kernel", "add_hits_kernel", "router_top10_kernel", "block_scores_kernel", + "mmvf_multi_kernel", + "mmvf_kernel", + "to_bf16_kernel", + "native_swiglu_kernel", + "scalar_gate_kernel", + "native_scalar_sigmoid_multi_kernel", + "native_scalar_sigmoid_kernel", + "scale_rows_kernel", + "moe_combine_kernel", + "swiglu_entries_kernel", + "quantize_q8_1_kernel", + "add_hits_kernel", + "router_top10_kernel", + "block_scores_kernel", ]; if !l.entry.starts_with("_ZN") { return l.entry.to_string(); @@ -122,8 +151,12 @@ impl PlanOps<'_> { } } impl WindowOps for PlanOps<'_> { - fn embed(&mut self) -> Result<()> { self.mark("embed".into()) } - fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.mark(format!("stamp {l}.{s}")) } + fn embed(&mut self) -> Result<()> { + self.mark("embed".into()) + } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { + self.mark(format!("stamp {l}.{s}")) + } fn ple_layer1(&mut self, rows: Rows) -> Result<()> { let per = self.planner.ple_layer1(rows)?; for (row, launches) in per { @@ -145,9 +178,15 @@ impl WindowOps for PlanOps<'_> { let x = self.planner.mmvq(l, p, r); self.plan(&format!("mmvq {p:?}"), x) } - fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) } - fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_ab g{g}")) } - fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_rec g{g}")) } + fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { + self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) + } + fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { + self.mark(format!("gdn_ab g{g}")) + } + fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { + self.mark(format!("gdn_rec g{g}")) + } fn qsa_index_k(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { let x = self.planner.qsa_index_k(q, r, b); self.plan("index_k", x) @@ -156,12 +195,16 @@ impl WindowOps for PlanOps<'_> { let x = self.planner.qsa_k_norm_rope(q, r, b); self.plan("k_norm_rope", x) } - fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.mark(format!("tail q{q}")) } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { + self.mark(format!("tail q{q}")) + } fn qsa_kv_append(&mut self, q: usize, r: Rows) -> Result<()> { let x = self.planner.qsa_kv_append(q, r); self.plan("kv_append", x) } - fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { self.mark(format!("indexer_append q{q}")) } + fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { + self.mark(format!("indexer_append q{q}")) + } fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { let x = self.planner.qsa_q_path(q, r, b); self.plan("q_path", x) @@ -190,7 +233,9 @@ impl WindowOps for PlanOps<'_> { let x = self.planner.router(l, r, b); self.plan("router", x) } - fn doorbell(&mut self, _: Rows) -> Result<()> { self.mark("doorbell".into()) } + fn doorbell(&mut self, _: Rows) -> Result<()> { + self.mark("doorbell".into()) + } fn shared_expert(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { let x = self.planner.shared_expert(l, r, b); self.plan("shared", x) @@ -199,15 +244,25 @@ impl WindowOps for PlanOps<'_> { let x = self.planner.quantize_expert_input(r); self.plan("xq", x) } - fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { self.mark(format!("waitA {ring}")) } + fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { + self.mark(format!("waitA {ring}")) + } fn expert_groups(&mut self, l: usize, r: Rows, t: ExpertTier) -> Result<()> { let x = self.planner.expert_groups(l, r, t); self.plan(&format!("experts {t:?}"), x) } - fn wait_copies(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitB {ring}")) } - fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { self.mark("pcie_stage".into()) } - fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitM {ring}")) } - fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { self.mark("cpu_rows".into()) } + fn wait_copies(&mut self, ring: u32) -> Result<()> { + self.mark(format!("waitB {ring}")) + } + fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { + self.mark("pcie_stage".into()) + } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { + self.mark(format!("waitM {ring}")) + } + fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { + self.mark("cpu_rows".into()) + } fn hit_add(&mut self, r: Rows) -> Result<()> { let x = self.planner.hit_add(r); self.plan("hit_add", x) diff --git a/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs b/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs index 2bd1b30c..d03887f8 100644 --- a/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs +++ b/crates/cuda-driver/src/original_verify_window_planner/tests/every_window_size_and_group.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn every_window_size_and_group_split_plans_without_error() { for groups in [1usize, 2] { @@ -31,7 +30,10 @@ fn a_gdn_layer_records_verify_cpp_order_with_the_sealed_kernels() { let k = names(pre); let pos = |needle: &str| k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}")); assert!(pos("") < pos(" = order.iter().map(|n| pos(n)).collect(); assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); @@ -79,11 +96,15 @@ fn post_records_vram_then_pcie_experts_hit_add_and_combine() { let post = section(&log, "waitA 1", "stamp 0.24"); let k = names(post); let order = ["waitA 1", " = order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); + let at: Vec = + order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); assert!(at.windows(2).all(|w| w[0] < w[1]), "{at:?}"); // each tier is gate/up, swiglu, quantize, down let vram = names(section(&log, "")); - assert_eq!(&vram[1..vram.len() - 1], ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"]); + assert_eq!( + &vram[1..vram.len() - 1], + ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"] + ); // the last layer writes the residual once per row let last = section(&log, "stamp 47.24", "stamp 48.0"); assert_eq!(names(last).iter().filter(|s| **s == "mtp_full_native_write").count(), 2); @@ -93,7 +114,8 @@ fn post_records_vram_then_pcie_experts_hit_add_and_combine() { fn split_windows_interleave_groups_but_keep_each_group_in_order() { let log = record(5, 2, false); // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts - let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with(" = + log.iter().enumerate().filter(|(_, s)| s.starts_with(" (unchanged staged down) -> up; 96 reads per window assert_eq!(on.iter().filter(|s| *s == "chain_gr_split").count(), 96 + 0); assert_eq!(on.iter().filter(|s| *s == "chain_gr_up8").count(), 96); - assert_eq!(on.iter().filter(|s| s.starts_with("chain_gr_down_t2w8_nb") || s.starts_with("chain_gr_down_w8_nb")).count(), 96, "the down projection is the 8-warp register-row kernel"); + assert_eq!( + on.iter().filter(|s| s.starts_with("chain_gr_down_t2w8_nb") || s.starts_with("chain_gr_down_w8_nb")).count(), + 96, + "the down projection is the 8-warp register-row kernel" + ); assert!(!on.iter().any(|s| s == "mtp_scalar_gr_staged")); assert!(!on.iter().any(|s| s == "mtp_scalar_gr_split" || s == "mtp_scalar_gr_up")); assert_eq!(on.iter().filter(|s| *s == "chain_qsa_decode_chunk").count(), 12); diff --git a/crates/cuda-driver/src/original_verify_window_proj.rs b/crates/cuda-driver/src/original_verify_window_proj.rs index b4564dc8..1e4e2b4e 100644 --- a/crates/cuda-driver/src/original_verify_window_proj.rs +++ b/crates/cuda-driver/src/original_verify_window_proj.rs @@ -10,75 +10,292 @@ //! with the activation rows `n_in/32*36` bytes apart and outputs `n_out` floats apart. //! * bf16 gemv: `mtp_full_mmvf{B}` for one row, the `_multi_kernel` instantiation //! for 2..=8 rows (the weight row read once, every row its single-row order). +use super::OriginalVerifyGeometry; use super::kernels::{A, ArenaMap, AssetSpec, Launch}; use super::window_plan::{gdn_index, qsa_index}; use super::window_record::{Projection, QuantSource, Rows}; -use super::OriginalVerifyGeometry; -use crate::{Context, DeviceBuffer}; use crate::native_head::native_head_row_bytes; +use crate::{Context, DeviceBuffer}; use crate::{Error, NativeHeadDispatch, Result}; #[path = "mtp_original_full_head_dispatch.rs"] mod head_dispatch; -const HEAD_NATIVE_ENTRIES:&[&str]=&[ - "head_quant", "head_n2_s0", "head_n2_s1", "head_n2_t2_large", "head_n2_t2_small", "head_n2_t2_upstream", - "head_n2_t3_large", "head_n2_t3_small", "head_n2_t3_upstream", "head_n2_t4_large", "head_n2_t4_small", - "head_n2_t4_upstream", "head_n2_t5_large", "head_n2_t5_small", "head_n2_t5_upstream", "head_n2_t6_large", - "head_n2_t6_small", "head_n2_t6_upstream", "head_n2_t7_large", "head_n2_t7_small", "head_n2_t7_upstream", - "head_n2_t8_large", "head_n2_t8_small", "head_n2_t8_upstream", "head_n6_s0", "head_n6_s1", "head_n6_t2_large", - "head_n6_t2_small", "head_n6_t2_upstream", "head_n6_t3_large", "head_n6_t3_small", "head_n6_t3_upstream", - "head_n6_t4_large", "head_n6_t4_small", "head_n6_t4_upstream", "head_n6_t5_large", "head_n6_t5_small", - "head_n6_t5_upstream", "head_n6_t6_large", "head_n6_t6_small", "head_n6_t6_upstream", "head_n6_t7_large", - "head_n6_t7_small", "head_n6_t7_upstream", "head_n6_t8_large", "head_n6_t8_small", "head_n6_t8_upstream", - "head_n8_s0", "head_n8_s1", "head_n8_t2_large", "head_n8_t2_small", "head_n8_t2_upstream", "head_n8_t3_large", - "head_n8_t3_small", "head_n8_t3_upstream", "head_n8_t4_large", "head_n8_t4_small", "head_n8_t4_upstream", - "head_n8_t5_large", "head_n8_t5_small", "head_n8_t5_upstream", "head_n8_t6_large", "head_n8_t6_small", - "head_n8_t6_upstream", "head_n8_t7_large", "head_n8_t7_small", "head_n8_t7_upstream", "head_n8_t8_large", - "head_n8_t8_small", "head_n8_t8_upstream", "head_n20_s0", "head_n20_s1", "head_n20_t2_large", "head_n20_t2_small", - "head_n20_t2_upstream", "head_n20_t3_large", "head_n20_t3_small", "head_n20_t3_upstream", "head_n20_t4_large", - "head_n20_t4_small", "head_n20_t4_upstream", "head_n20_t5_large", "head_n20_t5_small", "head_n20_t5_upstream", - "head_n20_t6_large", "head_n20_t6_small", "head_n20_t6_upstream", "head_n20_t7_large", "head_n20_t7_small", - "head_n20_t7_upstream", "head_n20_t8_large", "head_n20_t8_small", "head_n20_t8_upstream", "head_n11_s0", - "head_n11_s1", "head_n11_t2_large", "head_n11_t2_small", "head_n11_t2_upstream", "head_n11_t3_large", - "head_n11_t3_small", "head_n11_t3_upstream", "head_n11_t4_large", "head_n11_t4_small", "head_n11_t4_upstream", - "head_n11_t5_large", "head_n11_t5_small", "head_n11_t5_upstream", "head_n11_t6_large", "head_n11_t6_small", - "head_n11_t6_upstream", "head_n11_t7_large", "head_n11_t7_small", "head_n11_t7_upstream", "head_n11_t8_large", - "head_n11_t8_small", "head_n11_t8_upstream", "head_n12_s0", "head_n12_s1", "head_n12_t2_large", - "head_n12_t2_small", "head_n12_t2_upstream", "head_n12_t3_large", "head_n12_t3_small", "head_n12_t3_upstream", - "head_n12_t4_large", "head_n12_t4_small", "head_n12_t4_upstream", "head_n12_t5_large", "head_n12_t5_small", - "head_n12_t5_upstream", "head_n12_t6_large", "head_n12_t6_small", "head_n12_t6_upstream", "head_n12_t7_large", - "head_n12_t7_small", "head_n12_t7_upstream", "head_n12_t8_large", "head_n12_t8_small", "head_n12_t8_upstream", - "head_n13_s0", "head_n13_s1", "head_n13_t2_large", "head_n13_t2_small", "head_n13_t2_upstream", - "head_n13_t3_large", "head_n13_t3_small", "head_n13_t3_upstream", "head_n13_t4_large", "head_n13_t4_small", - "head_n13_t4_upstream", "head_n13_t5_large", "head_n13_t5_small", "head_n13_t5_upstream", "head_n13_t6_large", - "head_n13_t6_small", "head_n13_t6_upstream", "head_n13_t7_large", "head_n13_t7_small", "head_n13_t7_upstream", - "head_n13_t8_large", "head_n13_t8_small", "head_n13_t8_upstream", "head_n14_s0", "head_n14_s1", - "head_n14_t2_large", "head_n14_t2_small", "head_n14_t2_upstream", "head_n14_t3_large", "head_n14_t3_small", - "head_n14_t3_upstream", "head_n14_t4_large", "head_n14_t4_small", "head_n14_t4_upstream", "head_n14_t5_large", - "head_n14_t5_small", "head_n14_t5_upstream", "head_n14_t6_large", "head_n14_t6_small", "head_n14_t6_upstream", - "head_n14_t7_large", "head_n14_t7_small", "head_n14_t7_upstream", "head_n14_t8_large", "head_n14_t8_small", - "head_n14_t8_upstream", "head_n23_s0", "head_n23_s1", "head_n23_t2_large", "head_n23_t2_small", - "head_n23_t2_upstream", "head_n23_t3_large", "head_n23_t3_small", "head_n23_t3_upstream", "head_n23_t4_large", - "head_n23_t4_small", "head_n23_t4_upstream", "head_n23_t5_large", "head_n23_t5_small", "head_n23_t5_upstream", - "head_n23_t6_large", "head_n23_t6_small", "head_n23_t6_upstream", "head_n23_t7_large", "head_n23_t7_small", - "head_n23_t7_upstream", "head_n23_t8_large", "head_n23_t8_small", "head_n23_t8_upstream", "head_n42_s0", - "head_n42_s1", "head_n42_t2_large", "head_n42_t2_small", "head_n42_t2_upstream", "head_n42_t3_large", - "head_n42_t3_small", "head_n42_t3_upstream", "head_n42_t4_large", "head_n42_t4_small", "head_n42_t4_upstream", - "head_n42_t5_large", "head_n42_t5_small", "head_n42_t5_upstream", "head_n42_t6_large", "head_n42_t6_small", - "head_n42_t6_upstream", "head_n42_t7_large", "head_n42_t7_small", "head_n42_t7_upstream", "head_n42_t8_large", - "head_n42_t8_small", "head_n42_t8_upstream", +const HEAD_NATIVE_ENTRIES: &[&str] = &[ + "head_quant", + "head_n2_s0", + "head_n2_s1", + "head_n2_t2_large", + "head_n2_t2_small", + "head_n2_t2_upstream", + "head_n2_t3_large", + "head_n2_t3_small", + "head_n2_t3_upstream", + "head_n2_t4_large", + "head_n2_t4_small", + "head_n2_t4_upstream", + "head_n2_t5_large", + "head_n2_t5_small", + "head_n2_t5_upstream", + "head_n2_t6_large", + "head_n2_t6_small", + "head_n2_t6_upstream", + "head_n2_t7_large", + "head_n2_t7_small", + "head_n2_t7_upstream", + "head_n2_t8_large", + "head_n2_t8_small", + "head_n2_t8_upstream", + "head_n6_s0", + "head_n6_s1", + "head_n6_t2_large", + "head_n6_t2_small", + "head_n6_t2_upstream", + "head_n6_t3_large", + "head_n6_t3_small", + "head_n6_t3_upstream", + "head_n6_t4_large", + "head_n6_t4_small", + "head_n6_t4_upstream", + "head_n6_t5_large", + "head_n6_t5_small", + "head_n6_t5_upstream", + "head_n6_t6_large", + "head_n6_t6_small", + "head_n6_t6_upstream", + "head_n6_t7_large", + "head_n6_t7_small", + "head_n6_t7_upstream", + "head_n6_t8_large", + "head_n6_t8_small", + "head_n6_t8_upstream", + "head_n8_s0", + "head_n8_s1", + "head_n8_t2_large", + "head_n8_t2_small", + "head_n8_t2_upstream", + "head_n8_t3_large", + "head_n8_t3_small", + "head_n8_t3_upstream", + "head_n8_t4_large", + "head_n8_t4_small", + "head_n8_t4_upstream", + "head_n8_t5_large", + "head_n8_t5_small", + "head_n8_t5_upstream", + "head_n8_t6_large", + "head_n8_t6_small", + "head_n8_t6_upstream", + "head_n8_t7_large", + "head_n8_t7_small", + "head_n8_t7_upstream", + "head_n8_t8_large", + "head_n8_t8_small", + "head_n8_t8_upstream", + "head_n20_s0", + "head_n20_s1", + "head_n20_t2_large", + "head_n20_t2_small", + "head_n20_t2_upstream", + "head_n20_t3_large", + "head_n20_t3_small", + "head_n20_t3_upstream", + "head_n20_t4_large", + "head_n20_t4_small", + "head_n20_t4_upstream", + "head_n20_t5_large", + "head_n20_t5_small", + "head_n20_t5_upstream", + "head_n20_t6_large", + "head_n20_t6_small", + "head_n20_t6_upstream", + "head_n20_t7_large", + "head_n20_t7_small", + "head_n20_t7_upstream", + "head_n20_t8_large", + "head_n20_t8_small", + "head_n20_t8_upstream", + "head_n11_s0", + "head_n11_s1", + "head_n11_t2_large", + "head_n11_t2_small", + "head_n11_t2_upstream", + "head_n11_t3_large", + "head_n11_t3_small", + "head_n11_t3_upstream", + "head_n11_t4_large", + "head_n11_t4_small", + "head_n11_t4_upstream", + "head_n11_t5_large", + "head_n11_t5_small", + "head_n11_t5_upstream", + "head_n11_t6_large", + "head_n11_t6_small", + "head_n11_t6_upstream", + "head_n11_t7_large", + "head_n11_t7_small", + "head_n11_t7_upstream", + "head_n11_t8_large", + "head_n11_t8_small", + "head_n11_t8_upstream", + "head_n12_s0", + "head_n12_s1", + "head_n12_t2_large", + "head_n12_t2_small", + "head_n12_t2_upstream", + "head_n12_t3_large", + "head_n12_t3_small", + "head_n12_t3_upstream", + "head_n12_t4_large", + "head_n12_t4_small", + "head_n12_t4_upstream", + "head_n12_t5_large", + "head_n12_t5_small", + "head_n12_t5_upstream", + "head_n12_t6_large", + "head_n12_t6_small", + "head_n12_t6_upstream", + "head_n12_t7_large", + "head_n12_t7_small", + "head_n12_t7_upstream", + "head_n12_t8_large", + "head_n12_t8_small", + "head_n12_t8_upstream", + "head_n13_s0", + "head_n13_s1", + "head_n13_t2_large", + "head_n13_t2_small", + "head_n13_t2_upstream", + "head_n13_t3_large", + "head_n13_t3_small", + "head_n13_t3_upstream", + "head_n13_t4_large", + "head_n13_t4_small", + "head_n13_t4_upstream", + "head_n13_t5_large", + "head_n13_t5_small", + "head_n13_t5_upstream", + "head_n13_t6_large", + "head_n13_t6_small", + "head_n13_t6_upstream", + "head_n13_t7_large", + "head_n13_t7_small", + "head_n13_t7_upstream", + "head_n13_t8_large", + "head_n13_t8_small", + "head_n13_t8_upstream", + "head_n14_s0", + "head_n14_s1", + "head_n14_t2_large", + "head_n14_t2_small", + "head_n14_t2_upstream", + "head_n14_t3_large", + "head_n14_t3_small", + "head_n14_t3_upstream", + "head_n14_t4_large", + "head_n14_t4_small", + "head_n14_t4_upstream", + "head_n14_t5_large", + "head_n14_t5_small", + "head_n14_t5_upstream", + "head_n14_t6_large", + "head_n14_t6_small", + "head_n14_t6_upstream", + "head_n14_t7_large", + "head_n14_t7_small", + "head_n14_t7_upstream", + "head_n14_t8_large", + "head_n14_t8_small", + "head_n14_t8_upstream", + "head_n23_s0", + "head_n23_s1", + "head_n23_t2_large", + "head_n23_t2_small", + "head_n23_t2_upstream", + "head_n23_t3_large", + "head_n23_t3_small", + "head_n23_t3_upstream", + "head_n23_t4_large", + "head_n23_t4_small", + "head_n23_t4_upstream", + "head_n23_t5_large", + "head_n23_t5_small", + "head_n23_t5_upstream", + "head_n23_t6_large", + "head_n23_t6_small", + "head_n23_t6_upstream", + "head_n23_t7_large", + "head_n23_t7_small", + "head_n23_t7_upstream", + "head_n23_t8_large", + "head_n23_t8_small", + "head_n23_t8_upstream", + "head_n42_s0", + "head_n42_s1", + "head_n42_t2_large", + "head_n42_t2_small", + "head_n42_t2_upstream", + "head_n42_t3_large", + "head_n42_t3_small", + "head_n42_t3_upstream", + "head_n42_t4_large", + "head_n42_t4_small", + "head_n42_t4_upstream", + "head_n42_t5_large", + "head_n42_t5_small", + "head_n42_t5_upstream", + "head_n42_t6_large", + "head_n42_t6_small", + "head_n42_t6_upstream", + "head_n42_t7_large", + "head_n42_t7_small", + "head_n42_t7_upstream", + "head_n42_t8_large", + "head_n42_t8_small", + "head_n42_t8_upstream", ]; -const HEAD_IQ_ENTRIES:&[&str]=&[ - "head_i7_old", "head_i16_old", "head_i16_c1", "head_i16_c2", "head_i16_c4", "head_i16_c8", "head_i17_old", - "head_i17_c1", "head_i17_c2", "head_i17_c4", "head_i17_c8", "head_i18_old", "head_i18_c1", "head_i18_c2", - "head_i18_c4", "head_i18_c8", "head_i21_old", "head_i21_c1", "head_i21_c2", "head_i21_c4", "head_i21_c8", - "head_i22_old", "head_i22_c1", "head_i22_c2", "head_i22_c4", "head_i22_c8", "head_i29_old", "head_i29_c1", - "head_i29_c2", "head_i29_c4", "head_i29_c8", +const HEAD_IQ_ENTRIES: &[&str] = &[ + "head_i7_old", + "head_i16_old", + "head_i16_c1", + "head_i16_c2", + "head_i16_c4", + "head_i16_c8", + "head_i17_old", + "head_i17_c1", + "head_i17_c2", + "head_i17_c4", + "head_i17_c8", + "head_i18_old", + "head_i18_c1", + "head_i18_c2", + "head_i18_c4", + "head_i18_c8", + "head_i21_old", + "head_i21_c1", + "head_i21_c2", + "head_i21_c4", + "head_i21_c8", + "head_i22_old", + "head_i22_c1", + "head_i22_c2", + "head_i22_c4", + "head_i22_c8", + "head_i29_old", + "head_i29_c1", + "head_i29_c2", + "head_i29_c4", + "head_i29_c8", ]; -const BF16_ENTRIES:&[&str]=&[ - "mtp_full_mmvf32", "mtp_full_mmvf64", "mtp_full_mmvf96", "mtp_full_mmvf128", "mtp_full_mmvf160", - "mtp_full_mmvf192", "mtp_full_mmvf224", "mtp_full_mmvf256", +const BF16_ENTRIES: &[&str] = &[ + "mtp_full_mmvf32", + "mtp_full_mmvf64", + "mtp_full_mmvf96", + "mtp_full_mmvf128", + "mtp_full_mmvf160", + "mtp_full_mmvf192", + "mtp_full_mmvf224", + "mtp_full_mmvf256", "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi32ELi4EEEvPKflPKtPflii", "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi32ELi8EEEvPKflPKtPflii", "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi64ELi4EEEvPKflPKtPflii", @@ -100,21 +317,30 @@ const BF16_ENTRIES:&[&str]=&[ pub(crate) static HEAD_NATIVE: AssetSpec = AssetSpec { name: "mtp_original_full_head_native.ptx", ptx: include_bytes!("mtp_original_full_head_native.ptx"), - sha: [248,32,158,28,159,191,151,139,197,123,96,176,181,246,237,202,177,144,94,73,164,171,58,169,130,96,78,62,104,15,164,55], + sha: [ + 248, 32, 158, 28, 159, 191, 151, 139, 197, 123, 96, 176, 181, 246, 237, 202, 177, 144, 94, 73, 164, 171, 58, + 169, 130, 96, 78, 62, 104, 15, 164, 55, + ], entries: HEAD_NATIVE_ENTRIES, unsealed: "Original verifier asset unsealed: mtp_original_full_head_native.ptx (native MMVQ / q8_1 quantize)", }; pub(crate) static HEAD_IQ: AssetSpec = AssetSpec { name: "mtp_original_full_head_iq.ptx", ptx: include_bytes!("mtp_original_full_head_iq.ptx"), - sha: [229,116,82,204,172,119,42,138,138,119,37,59,198,201,100,235,183,188,97,253,178,233,117,39,169,119,95,140,207,60,59,159], + sha: [ + 229, 116, 82, 204, 172, 119, 42, 138, 138, 119, 37, 59, 198, 201, 100, 235, 183, 188, 97, 253, 178, 233, 117, + 39, 169, 119, 95, 140, 207, 60, 59, 159, + ], entries: HEAD_IQ_ENTRIES, unsealed: "Original verifier asset unsealed: mtp_original_full_head_iq.ptx (IQ-type MMVQ)", }; pub(crate) static BF16: AssetSpec = AssetSpec { name: "mtp_original_full_bf16.ptx", ptx: include_bytes!("mtp_original_full_bf16.ptx"), - sha: [161,109,252,252,154,73,204,171,37,216,3,2,147,213,130,111,143,117,226,134,143,174,27,108,76,239,112,107,109,252,61,8], + sha: [ + 161, 109, 252, 252, 154, 73, 204, 171, 37, 216, 3, 2, 147, 213, 130, 111, 143, 117, 226, 134, 143, 174, 27, + 108, 76, 239, 112, 107, 109, 252, 61, 8, + ], entries: BF16_ENTRIES, unsealed: "Original verifier asset unsealed: mtp_original_full_bf16.ptx (bf16 MMVF)", }; @@ -174,39 +400,39 @@ mod tests; #[path = "original_verify_window_proj/q8_1_row_bytes_fn.rs"] mod q8_1_row_bytes_fn; #[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::q8_1_row_bytes; -#[allow(unused_imports)] pub(crate) use q8_1_row_bytes_fn::is_iq_kind; #[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::mmvq_assets; -#[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::mmvq_asset; -#[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::plan_quantize_q8_1; -#[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::plan_mmvq; -#[allow(unused_imports)] pub(crate) use q8_1_row_bytes_fn::mmvf_block_size; #[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::mmvq_asset; +#[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::mmvq_assets; +#[allow(unused_imports)] use q8_1_row_bytes_fn::multi_entry; #[allow(unused_imports)] -use q8_1_row_bytes_fn::single_entry; +pub(crate) use q8_1_row_bytes_fn::native_matrix_bytes; #[allow(unused_imports)] pub(crate) use q8_1_row_bytes_fn::plan_bf16_gemv; #[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::plan_mmvq; +#[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::plan_quantize_q8_1; +#[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::plan_window_mmvq; +#[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::plan_window_quantize; +#[allow(unused_imports)] +use q8_1_row_bytes_fn::projection_first_row; +#[allow(unused_imports)] +use q8_1_row_bytes_fn::projection_shape; +#[allow(unused_imports)] +pub(crate) use q8_1_row_bytes_fn::q8_1_row_bytes; +#[allow(unused_imports)] use q8_1_row_bytes_fn::quant_source_span; #[allow(unused_imports)] pub(crate) use q8_1_row_bytes_fn::quant_source_width; #[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::plan_window_quantize; -#[allow(unused_imports)] -use q8_1_row_bytes_fn::projection_shape; -#[allow(unused_imports)] -use q8_1_row_bytes_fn::projection_first_row; -#[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::plan_window_mmvq; -#[allow(unused_imports)] -pub(crate) use q8_1_row_bytes_fn::native_matrix_bytes; +use q8_1_row_bytes_fn::single_entry; #[path = "original_verify_window_proj/admit_matrix_fn.rs"] mod admit_matrix_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/original_verify_window_proj/admit_matrix_fn.rs b/crates/cuda-driver/src/original_verify_window_proj/admit_matrix_fn.rs index 3467022d..3b9f4459 100644 --- a/crates/cuda-driver/src/original_verify_window_proj/admit_matrix_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_proj/admit_matrix_fn.rs @@ -31,7 +31,12 @@ impl<'a, 'ctx> OriginalVerifyProjBinding<'a, 'ctx> { } Ok(this) } - pub(crate) fn gdn_addrs(&self, context: &Context<'_>, geo: &OriginalVerifyGeometry, gdn_index: usize) -> Result { + pub(crate) fn gdn_addrs( + &self, + context: &Context<'_>, + geo: &OriginalVerifyGeometry, + gdn_index: usize, + ) -> Result { let m = self.gdn.get(gdn_index).ok_or(Error::InvalidQwenShape)?; let zv = geo.value_heads * 128; Ok(GdnProjectionAddrs { @@ -40,7 +45,12 @@ impl<'a, 'ctx> OriginalVerifyProjBinding<'a, 'ctx> { out: admit_matrix(context, &m.out, zv, geo.n)?, }) } - pub(crate) fn qsa_addrs(&self, context: &Context<'_>, geo: &OriginalVerifyGeometry, qsa_index: usize) -> Result { + pub(crate) fn qsa_addrs( + &self, + context: &Context<'_>, + geo: &OriginalVerifyGeometry, + qsa_index: usize, + ) -> Result { let m = self.qsa.get(qsa_index).ok_or(Error::InvalidQwenShape)?; let kv = geo.kv_heads * geo.head_dim; Ok(QsaProjectionAddrs { diff --git a/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs b/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs index 45aab029..6f854ee1 100644 --- a/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_proj/q8_1_row_bytes_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Bytes of one q8_1-quantized activation row of `n_in` elements (`n_in/32` blocks of 36). pub(crate) const fn q8_1_row_bytes(n_in: usize) -> usize { n_in / 32 * 36 @@ -28,7 +27,14 @@ pub(crate) fn plan_quantize_q8_1(x: u64, xq: u64, n_in: usize, rows: usize) -> R } let total = n_in * rows; let count = i32::try_from(total).map_err(|_| Error::InvalidSize)?; - Launch::new(&HEAD_NATIVE, "head_quant", [total.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, vec![A::P(x), A::P(xq), A::I32(count)]) + Launch::new( + &HEAD_NATIVE, + "head_quant", + [total.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::P(x), A::P(xq), A::I32(count)], + ) } /// `native_mmvq(type, w, xq, y, n_in, n_out, rows)`. `y` rows are `n_out` floats apart, `xq` rows @@ -45,7 +51,8 @@ pub(crate) fn plan_mmvq( if n_in == 0 || n_in % 32 != 0 || n_out == 0 || !(1..=8).contains(&rows) { return Err(Error::InvalidQwenShape); } - let (n_in32, n_out32) = (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?); + let (n_in32, n_out32) = + (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?); let (entry, grid, block, iq) = head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?; let mut args = vec![A::P(w.data)]; if iq { @@ -98,10 +105,18 @@ pub(crate) fn plan_bf16_gemv( if !(1..=8).contains(&n_tok) || n_in == 0 || n_in % 2 != 0 || n_out == 0 || ldx % 2 != 0 || x % 8 != 0 { return Err(Error::InvalidQwenShape); } - let (n_in32, grid) = (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, u32::try_from(n_out).map_err(|_| Error::InvalidSize)?); + let (n_in32, grid) = + (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, u32::try_from(n_out).map_err(|_| Error::InvalidSize)?); let block = mmvf_block_size(n_in); if n_tok == 1 && ldy >= n_out { - return Launch::new(&BF16, single_entry(block)?, [grid, 1, 1], [block, 1, 1], 0, vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)]); + return Launch::new( + &BF16, + single_entry(block)?, + [grid, 1, 1], + [block, 1, 1], + 0, + vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)], + ); } let nt = if n_tok <= 4 { 4 } else { 8 }; Launch::new( @@ -114,7 +129,6 @@ pub(crate) fn plan_bf16_gemv( ) } - // ------------------------------------------------------------------------------------------------ // The window's projection producers: `quantize_q8_1` and `mmvq` of `record_window`. // ------------------------------------------------------------------------------------------------ @@ -170,13 +184,20 @@ pub(super) fn projection_shape( Projection::GdnOut if gdn.is_some() => Ok((zv, n, "bo", n)), Projection::QsaK if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "kcur", geo.kv_heads * geo.head_dim)), Projection::QsaV if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "vcur", geo.kv_heads * geo.head_dim)), - Projection::QsaQ if qsa.is_some() => Ok((n, geo.heads * 2 * geo.head_dim, "qfull", geo.heads * 2 * geo.head_dim)), + Projection::QsaQ if qsa.is_some() => { + Ok((n, geo.heads * 2 * geo.head_dim, "qfull", geo.heads * 2 * geo.head_dim)) + } Projection::QsaOut if qsa.is_some() => Ok((geo.heads * geo.head_dim, n, "bo", n)), _ => Err(Error::InvalidQwenShape), } } /// Rows of the layer-major retained banks (`qkv_L`) a GDN layer owns: `gdn_index * max_t`. -pub(super) fn projection_first_row(geo: &OriginalVerifyGeometry, projection: Projection, layer: usize, begin: usize) -> usize { +pub(super) fn projection_first_row( + geo: &OriginalVerifyGeometry, + projection: Projection, + layer: usize, + begin: usize, +) -> usize { match (projection, gdn_index(layer)) { (Projection::GdnQkv, Some(g)) => g * geo.max_t + begin, _ => begin, diff --git a/crates/cuda-driver/src/original_verify_window_proj/tests.rs b/crates/cuda-driver/src/original_verify_window_proj/tests.rs index 8f67846c..8e0f314d 100644 --- a/crates/cuda-driver/src/original_verify_window_proj/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_proj/tests.rs @@ -43,7 +43,10 @@ fn mmvq_follows_the_native_head_dispatch() { // not exact: the upstream layout let up = NativeHeadDispatch { multi_exact: false, old_iq: false }; assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 640, 3, up).unwrap().entry, "head_n8_t3_upstream"); - assert_eq!(plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!( + plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(), + Error::UnsupportedQwenOperation + ); assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 0, 1, d).unwrap_err(), Error::InvalidQwenShape); } @@ -102,7 +105,10 @@ fn window_quantize_reads_the_groups_rows_and_writes_the_start_of_xq() { let l = plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(2, 5)).unwrap(); assert_eq!(l.entry, "head_quant"); assert_eq!(l.grid, [(3 * 2560usize).div_ceil(256) as u32, 1, 1]); - assert_eq!(l.args, vec![A::P(0x4000_0000 + off("mixed") + 2 * 2560 * 4), A::P(0x4000_0000 + off("xq")), A::I32(7680)]); + assert_eq!( + l.args, + vec![A::P(0x4000_0000 + off("mixed") + 2 * 2560 * 4), A::P(0x4000_0000 + off("xq")), A::I32(7680)] + ); // GDN y rows are 48 heads x 128, QSA attn32 rows 24 x 256: both 6144 wide let y = plan_window_quantize(&m, &geo, QuantSource::GdnY, rows(0, 8)).unwrap(); assert_eq!(y.args, vec![A::P(0x4000_0000 + off("y")), A::P(0x4000_0000 + off("xq")), A::I32(8 * 6144)]); @@ -127,7 +133,13 @@ fn window_mmvq_addresses_follow_the_original_output_banks() { assert_eq!((qkv.entry, qkv.grid, qkv.block), ("head_n8_t2_large", [10240, 1, 1], [32, 4, 1])); assert_eq!( qkv.args, - vec![A::P(0xAA00), A::P(0x4000_0000 + off("xq")), A::P(0x4000_0000 + off("qkv_L") + (3 * 8 + 3) as u64 * 10240 * 4), A::I32(2560), A::I32(10240)] + vec![ + A::P(0xAA00), + A::P(0x4000_0000 + off("xq")), + A::P(0x4000_0000 + off("qkv_L") + (3 * 8 + 3) as u64 * 10240 * 4), + A::I32(2560), + A::I32(10240) + ] ); let gate = plan_window_mmvq(&m, &geo, 0, Projection::GdnGate, &w, rows(0, 1), d).unwrap(); assert_eq!((gate.entry, gate.grid), ("head_n8_s0", [6144, 1, 1])); diff --git a/crates/cuda-driver/src/original_verify_window_qsa.rs b/crates/cuda-driver/src/original_verify_window_qsa.rs index e906c85b..6d7f22dd 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa.rs @@ -52,8 +52,8 @@ pub(crate) static DECODE_POSTOPS: AssetSpec = AssetSpec { name: "qsa_decode_postops.ptx", ptx: include_bytes!("qsa_decode_postops.ptx"), sha: [ - 253, 118, 230, 248, 69, 87, 215, 242, 166, 42, 197, 110, 22, 213, 228, 247, 136, 98, 231, - 86, 239, 152, 82, 176, 77, 89, 25, 153, 33, 58, 81, 25, + 253, 118, 230, 248, 69, 87, 215, 242, 166, 42, 197, 110, 22, 213, 228, 247, 136, 98, 231, 86, 239, 152, 82, + 176, 77, 89, 25, 153, 33, 58, 81, 25, ], entries: DECODE_POSTOPS_ENTRIES, unsealed: "Original verifier asset unsealed: qsa_decode_postops.ptx (QSA RMS norm / RoPE)", @@ -63,8 +63,8 @@ pub(crate) static SPLIT: AssetSpec = AssetSpec { name: "qsa_prompt_postops.ptx", ptx: include_bytes!("qsa_prompt_postops.ptx"), sha: [ - 72, 106, 115, 176, 107, 58, 52, 242, 152, 245, 126, 146, 194, 12, 200, 57, 77, 197, 157, - 123, 216, 75, 92, 204, 248, 218, 83, 170, 80, 129, 172, 159, + 72, 106, 115, 176, 107, 58, 52, 242, 152, 245, 126, 146, 194, 12, 200, 57, 77, 197, 157, 123, 216, 75, 92, 204, + 248, 218, 83, 170, 80, 129, 172, 159, ], entries: SPLIT_ENTRIES, unsealed: "Original verifier asset unsealed: qsa_prompt_postops.ptx (QSA q/gate split)", @@ -96,8 +96,8 @@ pub(crate) static RESOLVER: AssetSpec = AssetSpec { name: "qsa_prompt_resolver.ptx", ptx: include_bytes!("qsa_prompt_resolver.ptx"), sha: [ - 141, 62, 203, 174, 203, 242, 132, 69, 186, 100, 72, 91, 223, 243, 217, 26, 33, 216, 123, 133, 213, 147, 154, - 1, 82, 239, 47, 36, 20, 72, 14, 34, + 141, 62, 203, 174, 203, 242, 132, 69, 186, 100, 72, 91, 223, 243, 217, 26, 33, 216, 123, 133, 213, 147, 154, 1, + 82, 239, 47, 36, 20, 72, 14, 34, ], entries: RESOLVER_ENTRIES, unsealed: "Original verifier asset unsealed: qsa_prompt_resolver.ptx (KV streaming resolve)", @@ -117,7 +117,10 @@ pub(crate) static ATTENTION: AssetSpec = AssetSpec { pub(crate) static GATE: AssetSpec = AssetSpec { name: "original_verify_window_qsa_gate.ptx", ptx: include_bytes!("original_verify_window_qsa_gate.ptx"), - sha: [16, 128, 124, 76, 98, 216, 191, 75, 231, 92, 251, 26, 80, 119, 252, 62, 0, 220, 143, 64, 234, 102, 155, 34, 220, 255, 123, 120, 83, 171, 121, 73], + sha: [ + 16, 128, 124, 76, 98, 216, 191, 75, 231, 92, 251, 26, 80, 119, 252, 62, 0, 220, 143, 64, 234, 102, 155, 34, + 220, 255, 123, 120, 83, 171, 121, 73, + ], entries: GATE_ENTRIES, unsealed: "Original verifier asset unsealed: original_verify_window_qsa_gate.ptx (QSA output gate, native_qsa.cu --use_fast_math)", }; @@ -269,14 +272,14 @@ pub(crate) use assets_fn::cluster_assets; #[allow(unused_imports)] pub(crate) use assets_fn::daily_assets; #[allow(unused_imports)] -pub(crate) use assets_fn::shared_attributes; +use assets_fn::declared_i32; +#[allow(unused_imports)] +use assets_fn::grid_u32; #[allow(unused_imports)] use assets_fn::max_blocks; #[allow(unused_imports)] use assets_fn::scratch_floats; #[allow(unused_imports)] -use assets_fn::declared_i32; -#[allow(unused_imports)] -use assets_fn::grid_u32; +pub(crate) use assets_fn::shared_attributes; #[path = "original_verify_window_qsa/impl_qsawindow.rs"] mod impl_qsawindow; diff --git a/crates/cuda-driver/src/original_verify_window_qsa/assets_fn.rs b/crates/cuda-driver/src/original_verify_window_qsa/assets_fn.rs index 9d619193..e7c96ec1 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/assets_fn.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/assets_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Every module a QSA producer may launch from; the lead preloads them before capture. The cluster module is not in this list: it is /// loaded only when the policy asks for the cluster top-k (`cluster_assets`), since a card below sm_90 cannot load it. pub(crate) fn assets() -> Vec<&'static AssetSpec> { @@ -21,7 +20,10 @@ pub(crate) fn daily_assets(policy: &OriginalVerifyQsaPolicy) -> Vec<&'static Ass /// No QSA kernel needs more than the 48 KiB static shared memory (chunk kernel: 15.5 KiB, multi-query /// scores: 16.5 KiB), so no `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` is required; the cluster top-k holds the keys of /// ceil(max_blocks / 8) blocks in dynamic shared memory next to ~19 KiB of static, past the 48 KiB limit, and opts in once here. -pub(crate) fn shared_attributes(policy: &OriginalVerifyQsaPolicy, g: &OriginalVerifyGeometry) -> Vec<(&'static AssetSpec, &'static str, usize)> { +pub(crate) fn shared_attributes( + policy: &OriginalVerifyQsaPolicy, + g: &OriginalVerifyGeometry, +) -> Vec<(&'static AssetSpec, &'static str, usize)> { if policy.cluster_topk { vec![(&CLUSTER, CLUSTER_ENTRIES[0], crate::qsa_cluster::dynamic_smem(max_blocks(g)) as usize)] } else { @@ -51,7 +53,9 @@ impl OriginalVerifyQsaPolicy { return Err(refuse!("native QSA is off (rms_norm_weighted / qsa_gate_apply_f32 have no sealed owner)")); } if !self.native_rope { - return Err(refuse!("native RoPE is off (rope_neox_apply with the session cos/sin tables has no sealed owner)")); + return Err(refuse!( + "native RoPE is off (rope_neox_apply with the session cos/sin tables has no sealed owner)" + )); } if self.kv_q4 || self.kv_hybrid || self.kv_rot { return Err(refuse!("q4 / K8V4 / rotated KV has no sealed append, fwht or attention owner")); @@ -73,7 +77,14 @@ impl OriginalVerifyQsaPolicy { } impl QsaRope { /// The Original default: identity scaling at `freq_base` 1e7 (`powf(1e7f, -2/64)`). - pub fn new(theta_scale: f32, freq_scale: f32, corr_low: f32, corr_high: f32, ext_factor: f32, mscale: f32) -> Result { + pub fn new( + theta_scale: f32, + freq_scale: f32, + corr_low: f32, + corr_high: f32, + ext_factor: f32, + mscale: f32, + ) -> Result { for v in [theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale] { if !v.is_finite() { return Err(Error::InvalidQwenShape); @@ -96,7 +107,11 @@ impl QsaRope { } /// The identity constants `(1, 0, 0, 0, 1)` the frozen RoPE PTX bakes. pub fn is_identity(&self) -> bool { - self.freq_scale == 1.0 && self.corr_low == 0.0 && self.corr_high == 0.0 && self.ext_factor == 0.0 && self.mscale == 1.0 + self.freq_scale == 1.0 + && self.corr_low == 0.0 + && self.corr_high == 0.0 + && self.ext_factor == 0.0 + && self.mscale == 1.0 } } impl OriginalVerifyQsaKvBinding { @@ -121,7 +136,10 @@ impl OriginalVerifyQsaKvBinding { if all.clone().any(|&a| a == 0 || a % 16 != 0) { return Err(Error::InvalidQwenShape); } - if self.table != self.resolver[0] || self.slots < leleka_context::geometry::RESOLVE_BLOCK || self.slots > i32::MAX as usize / 4 { + if self.table != self.resolver[0] + || self.slots < leleka_context::geometry::RESOLVE_BLOCK + || self.slots > i32::MAX as usize / 4 + { return Err(Error::InvalidQwenShape); } // pairwise distinct owners (the page table is the resolver's first word) diff --git a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow.rs b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow.rs index 18f3a03d..ccde8c33 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow.rs @@ -3,386 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'a> QsaWindow<'a> { - pub fn new( - arena: &'a dyn ArenaMap, - geometry: OriginalVerifyGeometry, - policy: OriginalVerifyQsaPolicy, - rope: QsaRope, - ) -> Result { - policy.validate()?; - geometry.validate()?; - if geometry.index_block != PAGE_SIZE as usize || geometry.selection != 2051 { - return Err(Error::InvalidQwenShape); - } - Ok(Self { arena, g: geometry, policy, rope }) - } - pub(super) fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { - self.arena.span(name, offset, bytes) - } - pub(super) fn rows(&self, q: usize, rows: Rows, batched: Option) -> Result { - if q >= 12 || rows.begin >= rows.end || rows.end > self.g.max_t { - return Err(Error::InvalidQwenShape); - } - // the recorder passes `dec_batch && n > 1`; a batched launch of one row cannot exist - if batched == Some(true) && rows.len() < 2 { - return Err(Error::InvalidQwenShape); - } - Ok(Span { tb: rows.begin, n: rows.len() }) - } - pub(super) fn rms(&self, data: u64, gamma: u64, rows: usize, cols: usize) -> Result { - Launch::new( - &DECODE_POSTOPS, - "qsa_decode_rms", - [grid_u32(rows)?, 1, 1], - [256, 1, 1], - 0, - vec![A::P(data), A::P(gamma), A::P(data), A::I32(declared_i32(cols)?), A::F32(EPS)], - ) - } - pub(super) fn rope_with(&self, abi: RopeAbi, data: u64, rows: usize, width: usize, positions: u64) -> Result { - if positions % 4 != 0 || rows == 0 || rows > 65535 || (width != 128 && width != 256) { - return Err(Error::InvalidQwenShape); - } - let r = &self.rope; - let mut args = vec![ - A::P(data), - A::P(data), - A::I32(declared_i32(rows)?), - A::I32(declared_i32(width)?), - A::F32(r.theta_scale), - A::P(positions), - ]; - match abi { - RopeAbi::Frozen if !r.is_identity() => { - return Err(refuse!("scaled RoPE needs the regenerated qsa_decode_postops.ptx (ROPE-ARGS ABI 1)")); - } - RopeAbi::Frozen => {} - RopeAbi::Extended => { - args.extend([A::F32(r.freq_scale), A::F32(r.corr_low), A::F32(r.corr_high), A::F32(r.ext_factor), A::F32(r.mscale)]) - } - } - // native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads - Launch::new(&DECODE_POSTOPS, "qsa_decode_rope", [grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], [128, 1, 1], 0, args) - } - pub(super) fn rope(&self, data: u64, rows: usize, width: usize, positions: u64) -> Result { - self.rope_with(rope_abi()?, data, rows, width, positions) - } - /// `norm_rope` of verify.cpp: native RMS norm (in place) then native RoPE (in place). - pub(super) fn norm_rope(&self, data: u64, gamma: u64, rows: usize, cols: usize, positions: u64) -> Result<[Launch; 2]> { - Ok([self.rms(data, gamma, rows, cols)?, self.rope(data, rows, cols, positions)?]) - } - - /// `qsa_index_k`: indexer k projection, `idx_raw[q][row] = mixed[row] * indexer.k_proj`. - pub fn index_k(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { - let s = self.rows(q, rows, Some(batched))?; - let g = &self.g; - let (n_in, id) = (g.n, g.index_dim); - let gemv = |from: usize, count: usize| -> Result { - let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; - let y = self.span("idx_raw_L", (q * g.max_t + from) * id * 4, count * id * 4)?; - plan_bf16_gemv(x, n_in, w.weights.index_k_proj, y, id, n_in, id, count) - }; - if batched { - return Ok(vec![gemv(s.tb, s.n)?]); - } - (s.tb..s.tb + s.n).map(|t| gemv(t, 1)).collect() - } - - /// `qsa_k_norm_rope`: K per-head RMS norm with `attn_k_norm.weight`, then RoPE with the K row positions. - pub fn k_norm_rope(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { - let s = self.rows(q, rows, Some(batched))?; - let g = &self.g; - let (nkv, hd) = (g.kv_heads, g.head_dim); - let mut out = Vec::new(); - if batched { - let data = self.span("kcur", s.tb * nkv * hd * 4, s.n * nkv * hd * 4)?; - // pos_k = pos_ + MT * NH; rows [t][NKV] - let pos = self.span("pos", (g.max_t * g.heads + s.tb * nkv) * 4, s.n * nkv * 4)?; - out.extend(self.norm_rope(data, w.weights.k_norm, s.n * nkv, hd, pos)?); - } else { - for t in s.tb..s.tb + s.n { - let data = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; - let pos = self.span("pos", t * g.heads * 4, nkv * 4)?; - out.extend(self.norm_rope(data, w.weights.k_norm, nkv, hd, pos)?); - } - } - Ok(out) - } - - /// `qsa_kv_append`: one `kv_append_q8_step` per row into the resident pool (if the page is resident) - /// and the host copy. - pub fn kv_append(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { - let s = self.rows(q, rows, None)?; - let g = &self.g; - let (nkv, hd) = (g.kv_heads, g.head_dim); - let kv = &w.kv; - kv.validate(g)?; - let mut out = Vec::with_capacity(s.n); - for t in s.tb..s.tb + s.n { - let step = self.span("step", t * 16, 16)?; - let k = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; - let v = self.span("vcur", t * nkv * hd * 4, nkv * hd * 4)?; - out.push(Launch::new( - &KV_APPEND, - "mtp_original_append", - [grid_u32(nkv)?, grid_u32(hd / 64)?, 2], - [64, 1, 1], - 0, - vec![ - A::P(kv.resident[0]), - A::P(kv.resident[1]), - A::P(kv.resident[2]), - A::P(kv.resident[3]), - A::P(kv.table), - A::P(step), - A::P(k), - A::P(v), - A::I32(declared_i32(nkv)?), - A::I32(declared_i32(hd)?), - A::I32(PAGE_SIZE), - A::P(kv.host[0]), - A::P(kv.host[1]), - A::P(kv.host[2]), - A::P(kv.host[3]), - ], - )?); - } - Ok(out) - } - - /// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions. - pub fn q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { - let s = self.rows(q, rows, Some(batched))?; - let g = &self.g; - let (nh, hd) = (g.heads, g.head_dim); - let split = |from: usize, count: usize| -> Result { - let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; - let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?; - // `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy - Launch::new(&SPLIT, "qsa_split_q", [grid_u32(count * nh)?, 1, 1], [256, 1, 1], 0, vec![A::P(qfull), A::P(qcur), A::I64(count as i64)]) - }; - let mut out = Vec::new(); - if batched { - out.push(split(s.tb, s.n)?); - let data = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; - let pos = self.span("pos", s.tb * nh * 4, s.n * nh * 4)?; - out.extend(self.norm_rope(data, w.weights.q_norm, s.n * nh, hd, pos)?); - } else { - for t in s.tb..s.tb + s.n { - out.push(split(t, 1)?); - let data = self.span("qcur", t * nh * hd * 4, nh * hd * 4)?; - let pos = self.span("pos", t * nh * 4, nh * 4)?; - out.extend(self.norm_rope(data, w.weights.q_norm, nh, hd, pos)?); - } - } - Ok(out) - } - - /// `qsa_index_q_path`: indexer query projection, RMS norm with `indexer.q_norm.weight`, RoPE. - pub fn index_q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { - let s = self.rows(q, rows, Some(batched))?; - let g = &self.g; - let (n_in, iq, id, nh) = (g.n, g.index_heads, g.index_dim, g.heads); - let gemv = |from: usize, count: usize| -> Result { - let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; - let y = self.span("qidx", from * iq * id * 4, count * iq * id * 4)?; - plan_bf16_gemv(x, n_in, w.weights.index_q_proj, y, iq * id, n_in, iq * id, count) - }; - let mut out = Vec::new(); - if batched { - out.push(gemv(s.tb, s.n)?); - let data = self.span("qidx", s.tb * iq * id * 4, s.n * iq * id * 4)?; - // pos_i = pos_ + MT * (NH + NKV); rows [t][IQ] - let pos = self.span("pos", (g.max_t * (nh + g.kv_heads) + s.tb * iq) * 4, s.n * iq * 4)?; - out.extend(self.norm_rope(data, w.weights.index_q_norm, s.n * iq, id, pos)?); - } else { - for t in s.tb..s.tb + s.n { - out.push(gemv(t, 1)?); - let data = self.span("qidx", t * iq * id * 4, iq * id * 4)?; - let pos = self.span("pos", t * nh * 4, iq * 4)?; - out.extend(self.norm_rope(data, w.weights.index_q_norm, iq, id, pos)?); - } - } - Ok(out) - } - - /// `qsa_block_scores_topk`: `qsa_block_scores` then `qsa_block_topk` over the window group's queries. - pub fn block_scores_topk(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { - let s = self.rows(q, rows, None)?; - let g = &self.g; - w.kv.validate(g)?; - let (mb, cap) = (max_blocks(g), g.selection); - let qidx = self.span("qidx", s.tb * g.index_heads * g.index_dim * 4, s.n * g.index_heads * g.index_dim * 4)?; - let steps = self.span("step", s.tb * 16, s.n * 16)?; - let scores = self.span("scores", s.tb * mb * 4, s.n * mb * 4)?; - let sel = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; - let scored = if self.policy.scores_multi && s.n <= SCORE_MAX_QUERIES { - // block_scores_multi_kernel<<<256, SCORE_WARPS * 32>>> - Launch::new( - &SELECT, - "qsa_decode_scores", - [256, 1, 1], - [256, 1, 1], - 0, - vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I32(s.n as i32), A::I64(mb as i64), A::P(scores)], - )? - } else { - // block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>> - Launch::new( - &SELECT, - SCORE_SINGLE, - [grid_u32(mb.div_ceil(8))?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)], - )? - }; - // Original dispatches the register-resident top-k (`block_topk_reg_kernel`) while max_blocks <= - // 1024 * 33; Original documents it as selecting the identical ids (same radix rule, ties to the - // lowest index), and only `block_topk_kernel` is sealed, so that one is always launched. - let topk = if self.policy.cluster_topk && s.n <= CLUSTER_MAX_QUERIES { - // block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs: the same ids - Launch::new( - &CLUSTER, - CLUSTER_ENTRIES[0], - [crate::qsa_cluster::CLUSTER_CTAS, grid_u32(s.n)?, 1], - [crate::qsa_cluster::BLOCK, 1, 1], - crate::qsa_cluster::dynamic_smem(mb), - vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], - )? - .clustered(crate::qsa_cluster::CLUSTER_CTAS) - } else { - Launch::new( - &SELECT, - "qsa_topk_ref", - [grid_u32(s.n)?, 1, 1], - [256, 1, 1], - 0, - vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], - )? - }; - Ok(vec![scored, topk]) - } - - /// `qsa_kv_resolve`: the selections' blocks resident, device side (`kv_stream_resolve`). - pub fn kv_resolve(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { - let s = self.rows(q, rows, None)?; - let g = &self.g; - w.kv.validate(g)?; - // each query selects whole 4-cell blocks plus a partial one; all of them must fit the miss arrays - if s.n * (g.selection.div_ceil(PAGE_SIZE as usize) + 1) > w.kv.slots { - return Err(refuse!("the window's selections can miss more blocks than the resolver has slots")); - } - let ids = self.span("sel", s.tb * g.selection * 4, s.n * g.selection * 4)?; - let steps = self.span("step", s.tb * 16, s.n * 16)?; - let r = &w.kv.resolver; - let mut resolve: Vec = r.iter().map(|&a| A::P(a)).collect(); - resolve.extend([A::P(ids), A::P(steps), A::I32(s.n as i32), A::I64(w.kv.slots as i64)]); - let mut copy = vec![A::P(r[4]), A::P(r[5]), A::P(r[6])]; - copy.extend(w.kv.host.iter().chain(&w.kv.resident).map(|&a| A::P(a))); - Ok(vec![ - Launch::new(&RESOLVER, "leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1], 0, resolve)?, - Launch::new(&RESOLVER, "leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1], 0, copy)?, - ]) - } - - /// `qsa_decode_attention`: `qsa_decode_attn_batch` (chunk grid `[chunks, n_head_kv, n]`, merge grid `[n_head, n]`). - pub fn decode_attention(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { - let s = self.rows(q, rows, None)?; - let g = &self.g; - w.kv.validate(g)?; - let (nh, nkv, hd, cap) = (g.heads, g.kv_heads, g.head_dim, g.selection); - let chunks = cap.div_ceil(ATTN_CHUNK); - let stride = scratch_floats(g); - let qcur = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; - let ids = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; - let steps = self.span("step", s.tb * 16, s.n * 16)?; - let acc = self.span("attn_scratch", s.tb * stride * 4, s.n * stride * 4)?; - let part_m = acc + (chunks * nh * hd * 4) as u64; - let part_l = part_m + (chunks * nh * 4) as u64; - let attn = self.span("attn", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; - // 1.0f / sqrtf(256.0f) - let scale = 1.0f32 / (hd as f32).sqrt(); - let r = &w.kv.resident; - let (chunk_asset, chunk_entry) = if self.policy.attn_daily { - (&super::super::sm120::ATTN_DAILY, super::super::sm120::E_ATTN_CHUNK_DAILY) - } else if super::super::chain::flags().qsa { - (&super::super::chain::CHAIN, super::super::chain::E_QSA_CHUNK) - } else { - (&ATTENTION, "leleka_qsa_decode_chunk") - }; - let chunk = Launch::new( - chunk_asset, - chunk_entry, - [grid_u32(chunks)?, grid_u32(nkv)?, grid_u32(s.n)?], - [256, 1, 1], - 0, - vec![ - A::P(qcur), - A::P(r[0]), - A::P(r[1]), - A::P(r[2]), - A::P(r[3]), - A::P(w.kv.table), - A::P(ids), - A::P(steps), - A::I32(declared_i32(nkv)?), - A::I32(PAGE_SIZE), - A::F32(scale), - A::P(acc), - A::P(part_m), - A::P(part_l), - A::I32(declared_i32(chunks)?), - A::I32(declared_i32(cap)?), - A::I64(stride as i64), - ], - )?; - let merge = if self.policy.attn_daily { - Launch::new( - &super::super::sm120::ATTN_DAILY, - super::super::sm120::E_ATTN_MERGE_V2, - [grid_u32(nh)?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![A::P(acc), A::P(part_m), A::P(part_l), A::I32(declared_i32(chunks)?), A::P(steps), A::P(attn), A::I64(stride as i64)], - )? - } else { - Launch::new( - &ATTENTION, - "leleka_qsa_decode_merge", - [grid_u32(nh)?, grid_u32(s.n)?, 1], - [256, 1, 1], - 0, - vec![A::P(acc), A::P(part_m), A::P(part_l), A::I32(declared_i32(chunks)?), A::P(attn), A::I64(stride as i64)], - )? - }; - Ok(vec![chunk, merge]) - } - - /// `qsa_gate`: `native_qsa_gate_apply(attn, qfull, attn32, heads, HD)`; batched = one launch over `n * NH` heads. - pub fn gate(&self, q: usize, rows: Rows, batched: bool) -> Result> { - let s = self.rows(q, rows, Some(batched))?; - let g = &self.g; - let (nh, hd) = (g.heads, g.head_dim); - let one = |from: usize, count: usize| -> Result { - let heads = count * nh; - let attn = self.span("attn", from * nh * hd * 4, count * nh * hd * 4)?; - let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; - let out = self.span("attn32", from * nh * hd * 4, count * nh * hd * 4)?; - Launch::new( - &GATE, - "verify_window_qsa_gate", - [grid_u32((heads * hd).div_ceil(256))?, 1, 1], - [256, 1, 1], - 0, - vec![A::P(attn), A::P(qfull), A::P(out), A::I32(declared_i32(heads)?), A::I32(declared_i32(hd)?)], - ) - }; - if batched { - return Ok(vec![one(s.tb, s.n)?]); - } - (s.tb..s.tb + s.n).map(|t| one(t, 1)).collect() - } -} +#[path = "impl_qsawindow/impl_qsawindow_2.rs"] +mod impl_qsawindow_2; +#[path = "impl_qsawindow/impl_qsawindow_2_2.rs"] +mod impl_qsawindow_2_2; diff --git a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs new file mode 100644 index 00000000..5121fdd8 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: impl QsaWindow. + +#[allow(unused_imports)] +use super::*; + +impl<'a> QsaWindow<'a> { + pub fn new( + arena: &'a dyn ArenaMap, + geometry: OriginalVerifyGeometry, + policy: OriginalVerifyQsaPolicy, + rope: QsaRope, + ) -> Result { + policy.validate()?; + geometry.validate()?; + if geometry.index_block != PAGE_SIZE as usize || geometry.selection != 2051 { + return Err(Error::InvalidQwenShape); + } + Ok(Self { arena, g: geometry, policy, rope }) + } + pub(in super::super) fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.arena.span(name, offset, bytes) + } + pub(in super::super) fn rows(&self, q: usize, rows: Rows, batched: Option) -> Result { + if q >= 12 || rows.begin >= rows.end || rows.end > self.g.max_t { + return Err(Error::InvalidQwenShape); + } + // the recorder passes `dec_batch && n > 1`; a batched launch of one row cannot exist + if batched == Some(true) && rows.len() < 2 { + return Err(Error::InvalidQwenShape); + } + Ok(Span { tb: rows.begin, n: rows.len() }) + } + pub(in super::super) fn rms(&self, data: u64, gamma: u64, rows: usize, cols: usize) -> Result { + Launch::new( + &DECODE_POSTOPS, + "qsa_decode_rms", + [grid_u32(rows)?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(data), A::P(gamma), A::P(data), A::I32(declared_i32(cols)?), A::F32(EPS)], + ) + } + pub(in super::super) fn rope_with( + &self, + abi: RopeAbi, + data: u64, + rows: usize, + width: usize, + positions: u64, + ) -> Result { + if positions % 4 != 0 || rows == 0 || rows > 65535 || (width != 128 && width != 256) { + return Err(Error::InvalidQwenShape); + } + let r = &self.rope; + let mut args = vec![ + A::P(data), + A::P(data), + A::I32(declared_i32(rows)?), + A::I32(declared_i32(width)?), + A::F32(r.theta_scale), + A::P(positions), + ]; + match abi { + RopeAbi::Frozen if !r.is_identity() => { + return Err(refuse!("scaled RoPE needs the regenerated qsa_decode_postops.ptx (ROPE-ARGS ABI 1)")); + } + RopeAbi::Frozen => {} + RopeAbi::Extended => args.extend([ + A::F32(r.freq_scale), + A::F32(r.corr_low), + A::F32(r.corr_high), + A::F32(r.ext_factor), + A::F32(r.mscale), + ]), + } + // native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads + Launch::new( + &DECODE_POSTOPS, + "qsa_decode_rope", + [grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], + [128, 1, 1], + 0, + args, + ) + } + pub(in super::super) fn rope(&self, data: u64, rows: usize, width: usize, positions: u64) -> Result { + self.rope_with(rope_abi()?, data, rows, width, positions) + } + /// `norm_rope` of verify.cpp: native RMS norm (in place) then native RoPE (in place). + pub(in super::super) fn norm_rope( + &self, + data: u64, + gamma: u64, + rows: usize, + cols: usize, + positions: u64, + ) -> Result<[Launch; 2]> { + Ok([self.rms(data, gamma, rows, cols)?, self.rope(data, rows, cols, positions)?]) + } + + /// `qsa_index_k`: indexer k projection, `idx_raw[q][row] = mixed[row] * indexer.k_proj`. + pub fn index_k(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (n_in, id) = (g.n, g.index_dim); + let gemv = |from: usize, count: usize| -> Result { + let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; + let y = self.span("idx_raw_L", (q * g.max_t + from) * id * 4, count * id * 4)?; + plan_bf16_gemv(x, n_in, w.weights.index_k_proj, y, id, n_in, id, count) + }; + if batched { + return Ok(vec![gemv(s.tb, s.n)?]); + } + (s.tb..s.tb + s.n).map(|t| gemv(t, 1)).collect() + } + + /// `qsa_k_norm_rope`: K per-head RMS norm with `attn_k_norm.weight`, then RoPE with the K row positions. + pub fn k_norm_rope(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nkv, hd) = (g.kv_heads, g.head_dim); + let mut out = Vec::new(); + if batched { + let data = self.span("kcur", s.tb * nkv * hd * 4, s.n * nkv * hd * 4)?; + // pos_k = pos_ + MT * NH; rows [t][NKV] + let pos = self.span("pos", (g.max_t * g.heads + s.tb * nkv) * 4, s.n * nkv * 4)?; + out.extend(self.norm_rope(data, w.weights.k_norm, s.n * nkv, hd, pos)?); + } else { + for t in s.tb..s.tb + s.n { + let data = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; + let pos = self.span("pos", t * g.heads * 4, nkv * 4)?; + out.extend(self.norm_rope(data, w.weights.k_norm, nkv, hd, pos)?); + } + } + Ok(out) + } + + /// `qsa_kv_append`: one `kv_append_q8_step` per row into the resident pool (if the page is resident) + /// and the host copy. + pub fn kv_append(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + let (nkv, hd) = (g.kv_heads, g.head_dim); + let kv = &w.kv; + kv.validate(g)?; + let mut out = Vec::with_capacity(s.n); + for t in s.tb..s.tb + s.n { + let step = self.span("step", t * 16, 16)?; + let k = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; + let v = self.span("vcur", t * nkv * hd * 4, nkv * hd * 4)?; + out.push(Launch::new( + &KV_APPEND, + "mtp_original_append", + [grid_u32(nkv)?, grid_u32(hd / 64)?, 2], + [64, 1, 1], + 0, + vec![ + A::P(kv.resident[0]), + A::P(kv.resident[1]), + A::P(kv.resident[2]), + A::P(kv.resident[3]), + A::P(kv.table), + A::P(step), + A::P(k), + A::P(v), + A::I32(declared_i32(nkv)?), + A::I32(declared_i32(hd)?), + A::I32(PAGE_SIZE), + A::P(kv.host[0]), + A::P(kv.host[1]), + A::P(kv.host[2]), + A::P(kv.host[3]), + ], + )?); + } + Ok(out) + } + + /// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions. + pub fn q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nh, hd) = (g.heads, g.head_dim); + let split = |from: usize, count: usize| -> Result { + let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; + let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?; + // `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy + Launch::new( + &SPLIT, + "qsa_split_q", + [grid_u32(count * nh)?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(qfull), A::P(qcur), A::I64(count as i64)], + ) + }; + let mut out = Vec::new(); + if batched { + out.push(split(s.tb, s.n)?); + let data = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + let pos = self.span("pos", s.tb * nh * 4, s.n * nh * 4)?; + out.extend(self.norm_rope(data, w.weights.q_norm, s.n * nh, hd, pos)?); + } else { + for t in s.tb..s.tb + s.n { + out.push(split(t, 1)?); + let data = self.span("qcur", t * nh * hd * 4, nh * hd * 4)?; + let pos = self.span("pos", t * nh * 4, nh * 4)?; + out.extend(self.norm_rope(data, w.weights.q_norm, nh, hd, pos)?); + } + } + Ok(out) + } + + /// `qsa_index_q_path`: indexer query projection, RMS norm with `indexer.q_norm.weight`, RoPE. + pub fn index_q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (n_in, iq, id, nh) = (g.n, g.index_heads, g.index_dim, g.heads); + let gemv = |from: usize, count: usize| -> Result { + let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; + let y = self.span("qidx", from * iq * id * 4, count * iq * id * 4)?; + plan_bf16_gemv(x, n_in, w.weights.index_q_proj, y, iq * id, n_in, iq * id, count) + }; + let mut out = Vec::new(); + if batched { + out.push(gemv(s.tb, s.n)?); + let data = self.span("qidx", s.tb * iq * id * 4, s.n * iq * id * 4)?; + // pos_i = pos_ + MT * (NH + NKV); rows [t][IQ] + let pos = self.span("pos", (g.max_t * (nh + g.kv_heads) + s.tb * iq) * 4, s.n * iq * 4)?; + out.extend(self.norm_rope(data, w.weights.index_q_norm, s.n * iq, id, pos)?); + } else { + for t in s.tb..s.tb + s.n { + out.push(gemv(t, 1)?); + let data = self.span("qidx", t * iq * id * 4, iq * id * 4)?; + let pos = self.span("pos", t * nh * 4, iq * 4)?; + out.extend(self.norm_rope(data, w.weights.index_q_norm, iq, id, pos)?); + } + } + Ok(out) + } +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs new file mode 100644 index 00000000..496d3c23 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_qsa/impl_qsawindow/impl_qsawindow_2_2.rs @@ -0,0 +1,207 @@ +//! Moved out of the parent module by STRA-338: impl QsaWindow (2). + +#[allow(unused_imports)] +use super::*; + +impl<'a> QsaWindow<'a> { + /// `qsa_block_scores_topk`: `qsa_block_scores` then `qsa_block_topk` over the window group's queries. + pub fn block_scores_topk(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + let (mb, cap) = (max_blocks(g), g.selection); + let qidx = self.span("qidx", s.tb * g.index_heads * g.index_dim * 4, s.n * g.index_heads * g.index_dim * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let scores = self.span("scores", s.tb * mb * 4, s.n * mb * 4)?; + let sel = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; + let scored = if self.policy.scores_multi && s.n <= SCORE_MAX_QUERIES { + // block_scores_multi_kernel<<<256, SCORE_WARPS * 32>>> + Launch::new( + &SELECT, + "qsa_decode_scores", + [256, 1, 1], + [256, 1, 1], + 0, + vec![ + A::P(w.kv.pooled), + A::P(w.kv.dead), + A::P(qidx), + A::P(steps), + A::I32(s.n as i32), + A::I64(mb as i64), + A::P(scores), + ], + )? + } else { + // block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>> + Launch::new( + &SELECT, + SCORE_SINGLE, + [grid_u32(mb.div_ceil(8))?, grid_u32(s.n)?, 1], + [256, 1, 1], + 0, + vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)], + )? + }; + // Original dispatches the register-resident top-k (`block_topk_reg_kernel`) while max_blocks <= + // 1024 * 33; Original documents it as selecting the identical ids (same radix rule, ties to the + // lowest index), and only `block_topk_kernel` is sealed, so that one is always launched. + let topk = if self.policy.cluster_topk && s.n <= CLUSTER_MAX_QUERIES { + // block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs: the same ids + Launch::new( + &CLUSTER, + CLUSTER_ENTRIES[0], + [crate::qsa_cluster::CLUSTER_CTAS, grid_u32(s.n)?, 1], + [crate::qsa_cluster::BLOCK, 1, 1], + crate::qsa_cluster::dynamic_smem(mb), + vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], + )? + .clustered(crate::qsa_cluster::CLUSTER_CTAS) + } else { + Launch::new( + &SELECT, + "qsa_topk_ref", + [grid_u32(s.n)?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)], + )? + }; + Ok(vec![scored, topk]) + } + + /// `qsa_kv_resolve`: the selections' blocks resident, device side (`kv_stream_resolve`). + pub fn kv_resolve(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + // each query selects whole 4-cell blocks plus a partial one; all of them must fit the miss arrays + if s.n * (g.selection.div_ceil(PAGE_SIZE as usize) + 1) > w.kv.slots { + return Err(refuse!("the window's selections can miss more blocks than the resolver has slots")); + } + let ids = self.span("sel", s.tb * g.selection * 4, s.n * g.selection * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let r = &w.kv.resolver; + let mut resolve: Vec = r.iter().map(|&a| A::P(a)).collect(); + resolve.extend([A::P(ids), A::P(steps), A::I32(s.n as i32), A::I64(w.kv.slots as i64)]); + let mut copy = vec![A::P(r[4]), A::P(r[5]), A::P(r[6])]; + copy.extend(w.kv.host.iter().chain(&w.kv.resident).map(|&a| A::P(a))); + Ok(vec![ + Launch::new(&RESOLVER, "leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1], 0, resolve)?, + Launch::new(&RESOLVER, "leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1], 0, copy)?, + ]) + } + + /// `qsa_decode_attention`: `qsa_decode_attn_batch` (chunk grid `[chunks, n_head_kv, n]`, merge grid `[n_head, n]`). + pub fn decode_attention(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + let (nh, nkv, hd, cap) = (g.heads, g.kv_heads, g.head_dim, g.selection); + let chunks = cap.div_ceil(ATTN_CHUNK); + let stride = scratch_floats(g); + let qcur = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + let ids = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let acc = self.span("attn_scratch", s.tb * stride * 4, s.n * stride * 4)?; + let part_m = acc + (chunks * nh * hd * 4) as u64; + let part_l = part_m + (chunks * nh * 4) as u64; + let attn = self.span("attn", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + // 1.0f / sqrtf(256.0f) + let scale = 1.0f32 / (hd as f32).sqrt(); + let r = &w.kv.resident; + let (chunk_asset, chunk_entry) = if self.policy.attn_daily { + (&super::super::super::sm120::ATTN_DAILY, super::super::super::sm120::E_ATTN_CHUNK_DAILY) + } else if super::super::super::chain::flags().qsa { + (&super::super::super::chain::CHAIN, super::super::super::chain::E_QSA_CHUNK) + } else { + (&ATTENTION, "leleka_qsa_decode_chunk") + }; + let chunk = Launch::new( + chunk_asset, + chunk_entry, + [grid_u32(chunks)?, grid_u32(nkv)?, grid_u32(s.n)?], + [256, 1, 1], + 0, + vec![ + A::P(qcur), + A::P(r[0]), + A::P(r[1]), + A::P(r[2]), + A::P(r[3]), + A::P(w.kv.table), + A::P(ids), + A::P(steps), + A::I32(declared_i32(nkv)?), + A::I32(PAGE_SIZE), + A::F32(scale), + A::P(acc), + A::P(part_m), + A::P(part_l), + A::I32(declared_i32(chunks)?), + A::I32(declared_i32(cap)?), + A::I64(stride as i64), + ], + )?; + let merge = if self.policy.attn_daily { + Launch::new( + &super::super::super::sm120::ATTN_DAILY, + super::super::super::sm120::E_ATTN_MERGE_V2, + [grid_u32(nh)?, grid_u32(s.n)?, 1], + [256, 1, 1], + 0, + vec![ + A::P(acc), + A::P(part_m), + A::P(part_l), + A::I32(declared_i32(chunks)?), + A::P(steps), + A::P(attn), + A::I64(stride as i64), + ], + )? + } else { + Launch::new( + &ATTENTION, + "leleka_qsa_decode_merge", + [grid_u32(nh)?, grid_u32(s.n)?, 1], + [256, 1, 1], + 0, + vec![ + A::P(acc), + A::P(part_m), + A::P(part_l), + A::I32(declared_i32(chunks)?), + A::P(attn), + A::I64(stride as i64), + ], + )? + }; + Ok(vec![chunk, merge]) + } + + /// `qsa_gate`: `native_qsa_gate_apply(attn, qfull, attn32, heads, HD)`; batched = one launch over `n * NH` heads. + pub fn gate(&self, q: usize, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nh, hd) = (g.heads, g.head_dim); + let one = |from: usize, count: usize| -> Result { + let heads = count * nh; + let attn = self.span("attn", from * nh * hd * 4, count * nh * hd * 4)?; + let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; + let out = self.span("attn32", from * nh * hd * 4, count * nh * hd * 4)?; + Launch::new( + &GATE, + "verify_window_qsa_gate", + [grid_u32((heads * hd).div_ceil(256))?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(attn), A::P(qfull), A::P(out), A::I32(declared_i32(heads)?), A::I32(declared_i32(hd)?)], + ) + }; + if batched { + return Ok(vec![one(s.tb, s.n)?]); + } + (s.tb..s.tb + s.n).map(|t| one(t, 1)).collect() + } +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa/tests.rs b/crates/cuda-driver/src/original_verify_window_qsa/tests.rs index b6afbe4e..1ce55634 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/tests.rs @@ -62,9 +62,9 @@ fn rope_param_count() -> usize { } } -#[path = "tests/sealed_assets_are_pinned.rs"] -mod sealed_assets_are_pinned; #[path = "tests/q_path_per_token_splits.rs"] mod q_path_per_token_splits; +#[path = "tests/sealed_assets_are_pinned.rs"] +mod sealed_assets_are_pinned; #[path = "tests/weight_sizes_are_the_original.rs"] mod weight_sizes_are_the_original; diff --git a/crates/cuda-driver/src/original_verify_window_qsa/tests/q_path_per_token_splits.rs b/crates/cuda-driver/src/original_verify_window_qsa/tests/q_path_per_token_splits.rs index 8a5ed65e..345a9143 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/tests/q_path_per_token_splits.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/tests/q_path_per_token_splits.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn q_path_per_token_splits_and_rotates_each_token_in_order() { let (m, g) = setup(); @@ -11,7 +10,10 @@ fn q_path_per_token_splits_and_rotates_each_token_in_order() { let l = w.q_path(7, &layer(), rows(0, 2), false).unwrap(); assert_eq!(l.len(), 6); let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); - assert_eq!(names, ["qsa_split_q", "qsa_decode_rms", "qsa_decode_rope", "qsa_split_q", "qsa_decode_rms", "qsa_decode_rope"]); + assert_eq!( + names, + ["qsa_split_q", "qsa_decode_rms", "qsa_decode_rope", "qsa_split_q", "qsa_decode_rms", "qsa_decode_rope"] + ); assert_eq!(l[0].grid, [24, 1, 1]); assert_eq!(l[3].args, vec![A::P(at(&m, "qfull", 24 * 512 * 4)), A::P(at(&m, "qcur", 24 * 256 * 4)), A::I64(1)]); assert_eq!(l[5].args[5], A::P(at(&m, "pos", 24 * 4))); @@ -38,7 +40,10 @@ fn index_q_path_projects_512_outputs_then_norms_and_rotates_index_rows() { ] ); assert_eq!(l[0].grid, [512, 1, 1]); - assert_eq!((l[1].grid, l[1].args[1].clone(), l[1].args[3].clone()), ([4 * n as u32, 1, 1], A::P(W.index_q_norm), A::I32(128))); + assert_eq!( + (l[1].grid, l[1].args[1].clone(), l[1].args[3].clone()), + ([4 * n as u32, 1, 1], A::P(W.index_q_norm), A::I32(128)) + ); assert_eq!(l[2].grid, [1, 4 * n as u32, 1]); assert_eq!(l[2].args[3], A::I32(128)); // pos_i = pos + MT * (NH + NKV) @@ -81,7 +86,13 @@ fn scores_use_the_multi_query_kernel_then_the_radix_topk() { assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_topk_ref", [n as u32, 1, 1], [256, 1, 1])); assert_eq!( l[1].args, - vec![A::P(at(&m, "scores", 0)), A::P(at(&m, "step", 0)), A::I64(1026), A::I64(2051), A::P(at(&m, "sel", 0))] + vec![ + A::P(at(&m, "scores", 0)), + A::P(at(&m, "step", 0)), + A::I64(1026), + A::I64(2051), + A::P(at(&m, "sel", 0)) + ] ); l.iter().for_each(assert_abi); } @@ -176,7 +187,10 @@ fn attention_chunk_and_merge_grids_cover_33_chunks_per_query() { for n in 1..=8usize { let l = w.decode_attention(2, &layer(), rows(0, n)).unwrap(); assert_eq!(l.len(), 2); - assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("leleka_qsa_decode_chunk", [33, 2, n as u32], [256, 1, 1], 0)); + assert_eq!( + (l[0].entry, l[0].grid, l[0].block, l[0].shared), + ("leleka_qsa_decode_chunk", [33, 2, n as u32], [256, 1, 1], 0) + ); let acc = at(&m, "attn_scratch", 0); assert_eq!( l[0].args, @@ -235,7 +249,13 @@ fn gate_is_one_launch_over_n_times_24_heads_when_batched() { assert_eq!((l[0].entry, l[0].grid, l[0].block), ("verify_window_qsa_gate", [24 * n as u32, 1, 1], [256, 1, 1])); assert_eq!( l[0].args, - vec![A::P(at(&m, "attn", 0)), A::P(at(&m, "qfull", 0)), A::P(at(&m, "attn32", 0)), A::I32(24 * n as i32), A::I32(256)] + vec![ + A::P(at(&m, "attn", 0)), + A::P(at(&m, "qfull", 0)), + A::P(at(&m, "attn32", 0)), + A::I32(24 * n as i32), + A::I32(256) + ] ); } let l = w.gate(1, rows(2, 5), false).unwrap(); diff --git a/crates/cuda-driver/src/original_verify_window_qsa/tests/sealed_assets_are_pinned.rs b/crates/cuda-driver/src/original_verify_window_qsa/tests/sealed_assets_are_pinned.rs index 730b8032..4a243b02 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/tests/sealed_assets_are_pinned.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/tests/sealed_assets_are_pinned.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn sealed_assets_are_pinned_and_export_every_named_entry() { for spec in assets() { @@ -146,7 +145,12 @@ fn index_k_is_one_multi_gemv_when_batched_and_a_single_gemv_per_token_otherwise( assert_eq!(launch.entry, "mtp_full_mmvf256"); assert_eq!( launch.args, - vec![A::P(at(&m, "mixed", t * 2560 * 4)), A::P(W.index_k_proj), A::P(at(&m, "idx_raw_L", t * 128 * 4)), A::I32(2560)] + vec![ + A::P(at(&m, "mixed", t * 2560 * 4)), + A::P(W.index_k_proj), + A::P(at(&m, "idx_raw_L", t * 128 * 4)), + A::I32(2560) + ] ); assert_abi(launch); } @@ -222,7 +226,10 @@ fn kv_append_is_one_step_driven_launch_per_row_with_the_host_mirror() { assert_eq!(l.len(), 3); for (i, launch) in l.iter().enumerate() { let t = 1 + i; - assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_original_append", [2, 4, 2], [64, 1, 1], 0)); + assert_eq!( + (launch.entry, launch.grid, launch.block, launch.shared), + ("mtp_original_append", [2, 4, 2], [64, 1, 1], 0) + ); assert_eq!( launch.args, vec![ diff --git a/crates/cuda-driver/src/original_verify_window_qsa/tests/weight_sizes_are_the_original.rs b/crates/cuda-driver/src/original_verify_window_qsa/tests/weight_sizes_are_the_original.rs index 2cf5b2b3..6557e82a 100644 --- a/crates/cuda-driver/src/original_verify_window_qsa/tests/weight_sizes_are_the_original.rs +++ b/crates/cuda-driver/src/original_verify_window_qsa/tests/weight_sizes_are_the_original.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn weight_sizes_are_the_original_tensor_shapes() { let g = test_geometry(); diff --git a/crates/cuda-driver/src/original_verify_window_record.rs b/crates/cuda-driver/src/original_verify_window_record.rs index 45bc2135..db93ddf0 100644 --- a/crates/cuda-driver/src/original_verify_window_record.rs +++ b/crates/cuda-driver/src/original_verify_window_record.rs @@ -5,9 +5,7 @@ //! or per-token forward substitutes. Pure: it is unit-tested with a trace //! producer, and the real producer (`OriginalVerifyWindowOps`) fails closed on //! any kernel family that has no genuine capturable owner yet. -use super::window_plan::{ - Phase, WINDOW_LAYERS, gdn_index, group_rows, is_qsa_layer, qsa_index, ring, schedule, -}; +use super::window_plan::{Phase, WINDOW_LAYERS, gdn_index, group_rows, is_qsa_layer, qsa_index, ring, schedule}; use crate::{Error, Result}; /// Rows `[begin, end)` of one split-window group. @@ -133,7 +131,6 @@ impl WindowPolicy { return Err(Error::UnsupportedQwenOperation); } self.qsa.validate() - } } diff --git a/crates/cuda-driver/src/original_verify_window_record/tests.rs b/crates/cuda-driver/src/original_verify_window_record/tests.rs index 49ad881a..49f34421 100644 --- a/crates/cuda-driver/src/original_verify_window_record/tests.rs +++ b/crates/cuda-driver/src/original_verify_window_record/tests.rs @@ -18,42 +18,108 @@ fn r(rows: Rows) -> String { format!("{}..{}g{}", rows.begin, rows.end, rows.group) } impl WindowOps for Trace { - fn embed(&mut self) -> Result<()> { self.note("embed".into()) } - fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.note(format!("stamp {l}.{s}")) } - fn ple_layer1(&mut self, x: Rows) -> Result<()> { self.note(format!("ple {}", r(x))) } + fn embed(&mut self) -> Result<()> { + self.note("embed".into()) + } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { + self.note(format!("stamp {l}.{s}")) + } + fn ple_layer1(&mut self, x: Rows) -> Result<()> { + self.note(format!("ple {}", r(x))) + } fn hc_read(&mut self, l: usize, h: HcHalf, a: bool, x: Rows) -> Result<()> { self.note(format!("hc {l} {:?} apply={a} {}", h, r(x))) } - fn quantize_q8_1(&mut self, l: usize, s: QuantSource, x: Rows) -> Result<()> { self.note(format!("quant {l} {s:?} {}", r(x))) } - fn mmvq(&mut self, l: usize, p: Projection, x: Rows) -> Result<()> { self.note(format!("mmvq {l} {p:?} {}", r(x))) } - fn gdn_conv(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("conv g{g} {}", r(x))) } - fn gdn_alpha_beta(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("ab g{g} {}", r(x))) } - fn gdn_recurrence(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("rec g{g} {}", r(x))) } - fn qsa_index_k(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("idxk q{q} {} b={b}", r(x))) } - fn qsa_k_norm_rope(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("knr q{q} {} b={b}", r(x))) } - fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.note(format!("tail q{q}")) } - fn qsa_kv_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("kv q{q} {}", r(x))) } - fn qsa_indexer_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("iapp q{q} {}", r(x))) } - fn qsa_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("qpath q{q} {} b={b}", r(x))) } - fn qsa_index_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("iqpath q{q} {} b={b}", r(x))) } - fn qsa_block_scores_topk(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("scores q{q} {}", r(x))) } - fn qsa_kv_resolve(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("resolve q{q} {}", r(x))) } - fn qsa_decode_attention(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("attn q{q} {}", r(x))) } - fn qsa_gate(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("gate q{q} {} b={b}", r(x))) } - fn router(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("router {l} {} b={b}", r(x))) } - fn doorbell(&mut self, x: Rows) -> Result<()> { self.note(format!("doorbell {}", r(x))) } - fn shared_expert(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("shared {l} {} b={b}", r(x))) } - fn quantize_expert_input(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("xq {l} {}", r(x))) } - fn wait_plan(&mut self, ring: u32, x: Rows) -> Result<()> { self.note(format!("waitA {ring} {}", r(x))) } - fn expert_groups(&mut self, l: usize, x: Rows, t: ExpertTier) -> Result<()> { self.note(format!("experts {l} {t:?} {}", r(x))) } - fn wait_copies(&mut self, ring: u32) -> Result<()> { self.note(format!("waitB {ring}")) } - fn pcie_stage(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("stage {l} {}", r(x))) } - fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.note(format!("waitM {ring}")) } - fn copy_cpu_rows(&mut self, x: Rows, only: bool) -> Result<()> { self.note(format!("cpurows {} only={only}", r(x))) } - fn hit_add(&mut self, x: Rows) -> Result<()> { self.note(format!("hitadd {}", r(x))) } - fn combine(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("combine {l} {} b={b}", r(x))) } - fn final_write(&mut self, x: Rows) -> Result<()> { self.note(format!("final {}", r(x))) } - fn head(&mut self, t: usize) -> Result<()> { self.note(format!("head {t}")) } + fn quantize_q8_1(&mut self, l: usize, s: QuantSource, x: Rows) -> Result<()> { + self.note(format!("quant {l} {s:?} {}", r(x))) + } + fn mmvq(&mut self, l: usize, p: Projection, x: Rows) -> Result<()> { + self.note(format!("mmvq {l} {p:?} {}", r(x))) + } + fn gdn_conv(&mut self, g: usize, x: Rows) -> Result<()> { + self.note(format!("conv g{g} {}", r(x))) + } + fn gdn_alpha_beta(&mut self, g: usize, x: Rows) -> Result<()> { + self.note(format!("ab g{g} {}", r(x))) + } + fn gdn_recurrence(&mut self, g: usize, x: Rows) -> Result<()> { + self.note(format!("rec g{g} {}", r(x))) + } + fn qsa_index_k(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("idxk q{q} {} b={b}", r(x))) + } + fn qsa_k_norm_rope(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("knr q{q} {} b={b}", r(x))) + } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { + self.note(format!("tail q{q}")) + } + fn qsa_kv_append(&mut self, q: usize, x: Rows) -> Result<()> { + self.note(format!("kv q{q} {}", r(x))) + } + fn qsa_indexer_append(&mut self, q: usize, x: Rows) -> Result<()> { + self.note(format!("iapp q{q} {}", r(x))) + } + fn qsa_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("qpath q{q} {} b={b}", r(x))) + } + fn qsa_index_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("iqpath q{q} {} b={b}", r(x))) + } + fn qsa_block_scores_topk(&mut self, q: usize, x: Rows) -> Result<()> { + self.note(format!("scores q{q} {}", r(x))) + } + fn qsa_kv_resolve(&mut self, q: usize, x: Rows) -> Result<()> { + self.note(format!("resolve q{q} {}", r(x))) + } + fn qsa_decode_attention(&mut self, q: usize, x: Rows) -> Result<()> { + self.note(format!("attn q{q} {}", r(x))) + } + fn qsa_gate(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("gate q{q} {} b={b}", r(x))) + } + fn router(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("router {l} {} b={b}", r(x))) + } + fn doorbell(&mut self, x: Rows) -> Result<()> { + self.note(format!("doorbell {}", r(x))) + } + fn shared_expert(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("shared {l} {} b={b}", r(x))) + } + fn quantize_expert_input(&mut self, l: usize, x: Rows) -> Result<()> { + self.note(format!("xq {l} {}", r(x))) + } + fn wait_plan(&mut self, ring: u32, x: Rows) -> Result<()> { + self.note(format!("waitA {ring} {}", r(x))) + } + fn expert_groups(&mut self, l: usize, x: Rows, t: ExpertTier) -> Result<()> { + self.note(format!("experts {l} {t:?} {}", r(x))) + } + fn wait_copies(&mut self, ring: u32) -> Result<()> { + self.note(format!("waitB {ring}")) + } + fn pcie_stage(&mut self, l: usize, x: Rows) -> Result<()> { + self.note(format!("stage {l} {}", r(x))) + } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { + self.note(format!("waitM {ring}")) + } + fn copy_cpu_rows(&mut self, x: Rows, only: bool) -> Result<()> { + self.note(format!("cpurows {} only={only}", r(x))) + } + fn hit_add(&mut self, x: Rows) -> Result<()> { + self.note(format!("hitadd {}", r(x))) + } + fn combine(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { + self.note(format!("combine {l} {} b={b}", r(x))) + } + fn final_write(&mut self, x: Rows) -> Result<()> { + self.note(format!("final {}", r(x))) + } + fn head(&mut self, t: usize) -> Result<()> { + self.note(format!("head {t}")) + } } fn record(t: usize, groups: usize, ple: bool) -> Vec { @@ -296,7 +362,8 @@ fn split_window_stamps_group_zero_only_and_interleaves_cpu_with_gpu_work() { fn every_ring_is_waited_exactly_three_times_and_in_run_order() { for groups in [1usize, 2] { let log = record(4, groups, true); - let a: Vec = log.iter().filter_map(|s| s.strip_prefix("waitA ")?.split(' ').next()?.parse().ok()).collect(); + let a: Vec = + log.iter().filter_map(|s| s.strip_prefix("waitA ")?.split(' ').next()?.parse().ok()).collect(); assert_eq!(a, (1..=(48 * groups) as u32).collect::>()); for flag in ["waitB ", "waitM "] { let v: Vec = log.iter().filter_map(|s| s.strip_prefix(flag)?.parse().ok()).collect(); diff --git a/crates/cuda-driver/src/original_verify_window_sm120.rs b/crates/cuda-driver/src/original_verify_window_sm120.rs index e83cafab..db5e1c10 100644 --- a/crates/cuda-driver/src/original_verify_window_sm120.rs +++ b/crates/cuda-driver/src/original_verify_window_sm120.rs @@ -25,7 +25,10 @@ pub(crate) const E_ATTN_MERGE_V2: &str = "leleka_qsa_decode_merge_v2"; pub(crate) static ATTN_DAILY: AssetSpec = AssetSpec { name: "sm120_attn_daily.ptx", ptx: concat!(include_str!("sm120_attn_daily.ptx"), "\0").as_bytes(), - sha: [73, 254, 226, 193, 238, 114, 44, 253, 105, 185, 137, 63, 194, 92, 42, 62, 145, 177, 230, 181, 184, 134, 234, 111, 57, 33, 127, 124, 167, 213, 98, 213], + sha: [ + 73, 254, 226, 193, 238, 114, 44, 253, 105, 185, 137, 63, 194, 92, 42, 62, 145, 177, 230, 181, 184, 134, 234, + 111, 57, 33, 127, 124, 167, 213, 98, 213, + ], entries: &[E_ATTN_CHUNK_DAILY, E_ATTN_MERGE_V2], unsealed: "Original verifier asset unsealed: sm120_attn_daily.ptx (ATTN_DAILY decode attention chunk and merge)", }; @@ -45,7 +48,10 @@ pub(crate) const GU_SWIGLU_TYPES: [u32; 6] = [16, 17, 18, 21, 22, 23]; pub(crate) static GU_SWIGLU: AssetSpec = AssetSpec { name: "sm120_gu_swiglu.ptx", ptx: concat!(include_str!("sm120_gu_swiglu.ptx"), "\0").as_bytes(), - sha: [107, 0, 213, 80, 35, 131, 13, 91, 78, 112, 245, 194, 119, 44, 69, 22, 61, 118, 18, 91, 59, 9, 185, 31, 8, 119, 145, 191, 64, 140, 101, 123], + sha: [ + 107, 0, 213, 80, 35, 131, 13, 91, 78, 112, 245, 194, 119, 44, 69, 22, 61, 118, 18, 91, 59, 9, 185, 31, 8, 119, + 145, 191, 64, 140, 101, 123, + ], entries: &E_GU_SWIGLU, unsealed: "Original verifier asset unsealed: sm120_gu_swiglu.ptx (GU_SWIGLU fused expert gate/up + SwiGLU + q8_1)", }; diff --git a/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs b/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs index c092443b..051e1a47 100644 --- a/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs +++ b/crates/cuda-driver/src/owned_gate_up_upload_gpu.rs @@ -3,7 +3,14 @@ use super::*; const ENABLE: &str = "LELEKA_STRA172_RUN_OWNED_GATE_UP_UPLOAD"; #[derive(Default, Debug)] -struct Report { bytes: usize, words: usize, differences: usize, guards: usize, refusals: usize, witness_errors: usize } +struct Report { + bytes: usize, + words: usize, + differences: usize, + guards: usize, + refusals: usize, + witness_errors: usize, +} fn read(buffer: &DeviceBuffer<'_>) -> Result> { let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes)?; @@ -23,7 +30,15 @@ fn raw(kind: MmqFormat) -> Vec { bytes } fn shape(kind: MmqFormat) -> ProjectionSpec { - ProjectionSpec { kind: ProjectionKind::Routed(if kind == MmqFormat::Iq3XxsGateUp { RoutedFormat::IQ3_XXS } else { RoutedFormat::IQ2_S }), rows: 640, columns: 2560 } + ProjectionSpec { + kind: ProjectionKind::Routed(if kind == MmqFormat::Iq3XxsGateUp { + RoutedFormat::IQ3_XXS + } else { + RoutedFormat::IQ2_S + }), + rows: 640, + columns: 2560, + } } fn consumed(bytes: &[u8], report: &mut Report) -> Vec { let original = bytes.to_vec().into_boxed_slice(); @@ -35,13 +50,19 @@ fn consumed(bytes: &[u8], report: &mut Report) -> Vec { fn compare_bytes(original: &[u8], actual: &[u8], report: &mut Report) { report.witness_errors += usize::from(original.len() != actual.len()); report.bytes += original.len(); - report.differences += original.iter().zip(actual).filter(|(a,b)| a != b).count(); + report.differences += original.iter().zip(actual).filter(|(a, b)| a != b).count(); } fn refused(result: Result, expected: Error, report: &mut Report) -> Result<()> { report.guards += 1; match result { - Err(error) if error == expected => { report.refusals += 1; Ok(()) } - Ok(_) => { report.witness_errors += 1; Ok(()) } + Err(error) if error == expected => { + report.refusals += 1; + Ok(()) + } + Ok(_) => { + report.witness_errors += 1; + Ok(()) + } Err(error) => Err(error), } } @@ -96,12 +117,16 @@ fn products(context: &Context<'_>, foreign: &Context<'_>, kind: MmqFormat, repor let expected = expected.as_mut().ok_or(Error::ContextPoisoned)?; let actual = actual.as_mut().ok_or(Error::ContextPoisoned)?; for pattern in [0usize, 1, 2] { - let input: Vec<_> = (0usize..2560).flat_map(|index| { - let value = if pattern == 2 { - f32::from_bits(if index.is_multiple_of(2) { 0x8000_0000 } else { 0 }) - } else { ((index * 13 + pattern * 19) % 43) as f32 / 16.0 - 1.25 }; - value.to_le_bytes() - }).collect(); + let input: Vec<_> = (0usize..2560) + .flat_map(|index| { + let value = if pattern == 2 { + f32::from_bits(if index.is_multiple_of(2) { 0x8000_0000 } else { 0 }) + } else { + ((index * 13 + pattern * 19) % 43) as f32 / 16.0 - 1.25 + }; + value.to_le_bytes() + }) + .collect(); activation.copy_from(&input)?; let prepared = context.prepare_routed_gate_up_q8(activation)?; let projected = (|| { @@ -116,9 +141,20 @@ fn products(context: &Context<'_>, foreign: &Context<'_>, kind: MmqFormat, repor } if pattern == 0 { other_original = Some(foreign.mmq_weights(kind, &bytes)?); - refused(other_original.as_ref().ok_or(Error::ContextPoisoned)?.native_gate_up_prepared(&prepared, actual), Error::ContextMismatch, report)?; + refused( + other_original + .as_ref() + .ok_or(Error::ContextPoisoned)? + .native_gate_up_prepared(&prepared, actual), + Error::ContextMismatch, + report, + )?; other = Some(foreign.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report))?); - refused(other.as_ref().ok_or(Error::ContextPoisoned)?.native_gate_up_prepared(&prepared, actual), Error::ContextMismatch, report)?; + refused( + other.as_ref().ok_or(Error::ContextPoisoned)?.native_gate_up_prepared(&prepared, actual), + Error::ContextMismatch, + report, + )?; compare_bytes(&reference, &read(actual)?, report); } Ok(()) @@ -128,9 +164,15 @@ fn products(context: &Context<'_>, foreign: &Context<'_>, kind: MmqFormat, repor Ok(()) })(); let mut cleanup = original.close(); - if let Some(owner) = candidate { cleanup = combine(cleanup, owner.close()); } - if let Some(owner) = other_original { cleanup = combine(cleanup, owner.close()); } - if let Some(owner) = other { cleanup = combine(cleanup, owner.close()); } + if let Some(owner) = candidate { + cleanup = combine(cleanup, owner.close()); + } + if let Some(owner) = other_original { + cleanup = combine(cleanup, owner.close()); + } + if let Some(owner) = other { + cleanup = combine(cleanup, owner.close()); + } for buffer in expected.into_iter().chain(actual).chain(activation) { cleanup = combine(cleanup, buffer.release()); } @@ -141,7 +183,11 @@ fn admission(context: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Res let allocated = context.allocated_bytes(); for actual in [bytes.len() - 1, bytes.len() + 1] { refused(context.mmq_weights(kind, &vec![0; actual]), Error::InvalidProjectionShape, report)?; - refused(context.mmq_weights_owned_gate_up(shape(kind), kind, vec![0; actual]), Error::InvalidProjectionShape, report)?; + refused( + context.mmq_weights_owned_gate_up(shape(kind), kind, vec![0; actual]), + Error::InvalidProjectionShape, + report, + )?; } for bad in [ ProjectionSpec { rows: 639, ..shape(kind) }, @@ -152,13 +198,17 @@ fn admission(context: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Res refused(context.mmq_weights_owned_gate_up(bad, kind, bytes.clone()), Error::InvalidProjectionShape, report)?; } for down in [MmqFormat::Iq4NlDown, MmqFormat::Q2Down] { - refused(context.mmq_weights_owned_gate_up(shape(kind), down, bytes.clone()), Error::UnsupportedProjection, report)?; + refused( + context.mmq_weights_owned_gate_up(shape(kind), down, bytes.clone()), + Error::UnsupportedProjection, + report, + )?; } let width = kind.layout(1)?.block_bytes; for index in [0, bytes.len() - width] { for bits in [0x7e01u16, 0x7c00, 0xfc00] { let mut invalid = bytes.clone(); - invalid[index..index+2].copy_from_slice(&bits.to_le_bytes()); + invalid[index..index + 2].copy_from_slice(&bits.to_le_bytes()); refused(context.mmq_weights(kind, &invalid), Error::InvalidQ8Activation, report)?; refused(context.mmq_weights_owned_gate_up(shape(kind), kind, invalid), Error::InvalidQ8Activation, report)?; } @@ -166,7 +216,10 @@ fn admission(context: &Context<'_>, kind: MmqFormat, report: &mut Report) -> Res report.witness_errors += usize::from(context.allocated_bytes() != allocated || context.is_poisoned()); // Completed prewrite refusals cannot poison a later genuine valid upload. let owner = context.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, report))?; - let verified = (|| { compare_bytes(&bytes, &read(owner.native_buffer()?)?, report); Ok(()) })(); + let verified = (|| { + compare_bytes(&bytes, &read(owner.native_buffer()?)?, report); + Ok(()) + })(); combine(verified, owner.close()) } fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { @@ -187,7 +240,10 @@ fn original_first_owned_gate_up_bytes_products_refusals_and_cleanup() { let context = device.create_context(8 * 1024 * 1024).expect("Context"); let foreign = match device.create_context(8 * 1024 * 1024) { Ok(value) => value, - Err(primary) => { let cleanup = context.close(); panic!("foreign {primary:?}; cleanup={cleanup:?}"); } + Err(primary) => { + let cleanup = context.close(); + panic!("foreign {primary:?}; cleanup={cleanup:?}"); + } }; let operation = (|| { let mut report = run(&context, &foreign)?; @@ -197,8 +253,10 @@ fn original_first_owned_gate_up_bytes_products_refusals_and_cleanup() { let old = tiny.mmq_weights(kind, &bytes); let new = tiny.mmq_weights_owned_gate_up(shape(kind), kind, consumed(&bytes, &mut report)); report.guards += 1; - report.refusals += usize::from(matches!(&old, Err(Error::BudgetExceeded)) && matches!(&new, Err(Error::BudgetExceeded))); - drop(old); drop(new); + report.refusals += + usize::from(matches!(&old, Err(Error::BudgetExceeded)) && matches!(&new, Err(Error::BudgetExceeded))); + drop(old); + drop(new); report.witness_errors += usize::from(tiny.allocated_bytes() != 0 || tiny.is_poisoned()); tiny.close()?; } diff --git a/crates/cuda-driver/src/ple_batch_ffi.rs b/crates/cuda-driver/src/ple_batch_ffi.rs index 1f5b429f..a8473f06 100644 --- a/crates/cuda-driver/src/ple_batch_ffi.rs +++ b/crates/cuda-driver/src/ple_batch_ffi.rs @@ -23,17 +23,9 @@ pub(crate) enum InputType { F16, } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled; -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::{Blas, KernelModule}; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled.rs index 7079fef5..70b4e7df 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled.rs @@ -30,8 +30,7 @@ type Gemm = unsafe extern "C" fn( ) -> c_int; type StreamCreate = unsafe extern "C" fn(*mut *mut c_void, c_uint) -> c_int; type ModuleLoad = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; -type ModuleFunction = - unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; +type ModuleFunction = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; type Launch = unsafe extern "C" fn( *mut c_void, c_uint, @@ -52,9 +51,7 @@ macro_rules! symbol { // SAFETY: private fixed symbol/signature; not a caller resolver. let p = unsafe { libc::dlsym($l.0, $name.as_ptr()) }; if p.is_null() { - return Err(Error::MissingSymbol( - $name.to_str().expect("static ASCII ABI"), - )); + return Err(Error::MissingSymbol($name.to_str().expect("static ASCII ABI"))); } // SAFETY: exact Linux64 ABI paired with the static name above. unsafe { std::mem::transmute::<*mut c_void, $ty>(p) } diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs index dd5dbc7f..f5dbe97e 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs @@ -213,42 +213,75 @@ impl Blas { /// interleaved Alpha/Beta and the Original router/shared scalar. #[allow(clippy::too_many_arguments)] pub(crate) fn gemm_gdn( - &self, bf16: bool, x: BufferHandle, w: BufferHandle, y: BufferHandle, - t: i32, n: i32, k: i32, ldy: i32, y_offset: usize, beta: &f32, + &self, + bf16: bool, + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + t: i32, + n: i32, + k: i32, + ldy: i32, + y_offset: usize, + beta: &f32, ) -> Result<()> { - if !(1..=8192).contains(&t) { return Err(Error::InvalidQwenShape); } + if !(1..=8192).contains(&t) { + return Err(Error::InvalidQwenShape); + } if bf16 { - let interleaved=(n,k,ldy)==(48,2560,96)&&matches!(y_offset,0|48); - let moe=matches!((n,k),(512,2560)|(1,2560))&&ldy==n&&y_offset==0; - if (!interleaved&&!moe)||(*beta!=0.0&&*beta!=1.0) {return Err(Error::InvalidQwenShape);} - } else if !matches!((n,k),(10240,2560)|(6144,2560)|(2560,6144)|(640,2560)|(2560,640)) - || ldy!=n || y_offset!=0 || *beta!=0.0 { return Err(Error::InvalidQwenShape); } - x.validate_projection_extent(t as usize*k as usize*2,2)?; - w.validate_projection_extent(n as usize*k as usize*2,2)?; - let whole=t as usize*ldy as usize*4; - y.validate_projection_extent(whole,4)?; - let consumed=((t as usize-1)*ldy as usize+n as usize)*4; - let output=y.checked_subspan(whole,y_offset*4,consumed)?; - let dtype=if bf16 {14} else {2}; - let alpha=1.0f32; + let interleaved = (n, k, ldy) == (48, 2560, 96) && matches!(y_offset, 0 | 48); + let moe = matches!((n, k), (512, 2560) | (1, 2560)) && ldy == n && y_offset == 0; + if (!interleaved && !moe) || (*beta != 0.0 && *beta != 1.0) { + return Err(Error::InvalidQwenShape); + } + } else if !matches!((n, k), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640)) + || ldy != n + || y_offset != 0 + || *beta != 0.0 + { + return Err(Error::InvalidQwenShape); + } + x.validate_projection_extent(t as usize * k as usize * 2, 2)?; + w.validate_projection_extent(n as usize * k as usize * 2, 2)?; + let whole = t as usize * ldy as usize * 4; + y.validate_projection_extent(whole, 4)?; + let consumed = ((t as usize - 1) * ldy as usize + n as usize) * 4; + let output = y.checked_subspan(whole, y_offset * 4, consumed)?; + let dtype = if bf16 { 14 } else { 2 }; + let alpha = 1.0f32; // SAFETY: fixed shapes/stride/offset from authentic WHOLE loans. // The exclusive actual workspace and producer-owned arguments, // buffers and weights are retained through its same-stream drain. // Default cuBLAS HOST scalar mode consumes alpha/beta in this call. - check("cublasGemmEx",unsafe{(self.gemm)( - self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, - 1,0,n,t,k,(&alpha as *const f32).cast(), - w.qwen_address() as *const c_void,dtype,k, - x.qwen_address() as *const c_void,dtype,k, - (beta as *const f32).cast(),output.qwen_address() as *mut c_void, - 0,ldy,68,-1, - )}) + check("cublasGemmEx", unsafe { + (self.gemm)( + self.handle.ok_or(Error::ContextPoisoned)? as *mut c_void, + 1, + 0, + n, + t, + k, + (&alpha as *const f32).cast(), + w.qwen_address() as *const c_void, + dtype, + k, + x.qwen_address() as *const c_void, + dtype, + k, + (beta as *const f32).cast(), + output.qwen_address() as *mut c_void, + 0, + ldy, + 68, + -1, + ) + }) } pub(crate) fn synchronize(&self) -> Result<()> { // SAFETY: actual private stream remains owned through this call. - crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { - (self.sync)(self.stream() as *mut c_void) - })) + crate::compute_drain::timed(7, || { + check("cuStreamSynchronize", unsafe { (self.sync)(self.stream() as *mut c_void) }) + }) } pub(crate) fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs index 9b0c8ab6..8aeb10c3 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas_2.rs @@ -8,19 +8,12 @@ impl Blas { let mut result = Ok(()); if let Some(h) = self.handle.take() { // SAFETY: actual handle after drain or constructor partial admission. - result = check("cublasDestroy_v2", unsafe { - (self.destroy)(h as *mut c_void) - }); + result = check("cublasDestroy_v2", unsafe { (self.destroy)(h as *mut c_void) }); } if let Some(s) = self.stream.take() { crate::compute_drain::unregister(s); // SAFETY: actual created stream, no undisclosed outstanding commands. - result = combine( - result, - check("cuStreamDestroy_v2", unsafe { - (self.stream_destroy)(s as *mut c_void) - }), - ); + result = combine(result, check("cuStreamDestroy_v2", unsafe { (self.stream_destroy)(s as *mut c_void) })); } if result.is_err() { // Unknown vendor cleanup retains its callable libraries. @@ -54,24 +47,17 @@ impl KernelModule { module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); // SAFETY: actual immutable pinned NUL PTX. - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } owner.module = Some(m as usize); for entry in entries { let mut f = std::ptr::null_mut(); // SAFETY: real module, static declared symbol. - check("cuModuleGetFunction", unsafe { - function(&mut f, m, entry.as_ptr()) - })?; + check("cuModuleGetFunction", unsafe { function(&mut f, m, entry.as_ptr()) })?; if f.is_null() { return Err(Error::InvalidDriverValue("cuModuleGetFunction")); } @@ -95,17 +81,11 @@ impl KernelModule { if grid == 0 || !matches!(block, 128 | 256 | 512 | 1024) || stream == 0 { return Err(Error::InvalidQwenShape); } - let function = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; args.pointers.clear(); - args.pointers - .try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; + args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; args.addresses.clear(); - args.addresses.try_reserve_exact(args.values.len()) - .map_err(|_| Error::HostAllocation)?; + args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?; args.addresses.resize(args.values.len(), 0); for (index, arg) in args.values.iter_mut().enumerate() { args.pointers.push(match arg { @@ -114,7 +94,7 @@ impl KernelModule { // the unspecified Rust representation of BufferHandle. args.addresses[index] = x.qwen_address(); (&mut args.addresses[index] as *mut u64).cast() - }, + } BatchArg::NullAddress => (&mut args.null as *mut u64).cast(), BatchArg::I32(x) => (x as *mut i32).cast(), BatchArg::I64(x) => (x as *mut i64).cast(), @@ -154,7 +134,14 @@ impl KernelModule { stream: usize, args: &mut KernelArguments, ) -> Result<()> { - if grid[0] == 0 || grid[1] == 0 || block == 0 || block > 1024 || cluster_x == 0 || grid[0] % cluster_x != 0 || stream == 0 { + if grid[0] == 0 + || grid[1] == 0 + || block == 0 + || block > 1024 + || cluster_x == 0 + || grid[0] % cluster_x != 0 + || stream == 0 + { return Err(Error::InvalidQwenShape); } let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs index 7a35e119..f1376ebf 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_library.rs @@ -7,11 +7,7 @@ impl Library { pub(super) fn open(name: &'static CStr) -> Result { // SAFETY: fixed private library name, owned dlopen reference. let ptr = unsafe { libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; - if ptr.is_null() { - Err(Error::LibraryUnavailable) - } else { - Ok(Self(ptr)) - } + if ptr.is_null() { Err(Error::LibraryUnavailable) } else { Ok(Self(ptr)) } } } impl Drop for Library { @@ -23,12 +19,5 @@ impl Drop for Library { } } pub(super) fn check(op: &'static str, code: c_int) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } diff --git a/crates/cuda-driver/src/ple_batch_ffi/impl_kernelarguments.rs b/crates/cuda-driver/src/ple_batch_ffi/impl_kernelarguments.rs index 412375ec..b0cd32fa 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/impl_kernelarguments.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/impl_kernelarguments.rs @@ -5,12 +5,7 @@ use super::*; impl KernelArguments { pub(crate) fn new(values: Vec) -> Self { - Self { - values: values.into_boxed_slice(), - null: 0, - pointers: Vec::new(), - addresses: Vec::new(), - } + Self { values: values.into_boxed_slice(), null: 0, pointers: Vec::new(), addresses: Vec::new() } } } #[cfg(not(all( @@ -68,9 +63,20 @@ impl Blas { } #[allow(clippy::too_many_arguments)] pub(crate) fn gemm_gdn( - &self, _: bool, _: BufferHandle, _: BufferHandle, _: BufferHandle, - _: i32, _: i32, _: i32, _: i32, _: usize, _: &f32, - ) -> Result<()> { Err(Error::UnsupportedPlatform) } + &self, + _: bool, + _: BufferHandle, + _: BufferHandle, + _: BufferHandle, + _: i32, + _: i32, + _: i32, + _: i32, + _: usize, + _: &f32, + ) -> Result<()> { + Err(Error::UnsupportedPlatform) + } pub(crate) fn synchronize(&self) -> Result<()> { Err(Error::UnsupportedPlatform) } @@ -87,19 +93,21 @@ impl KernelModule { pub(crate) fn load(_: &'static [u8], _: &'static [&'static CStr]) -> Result { Err(Error::UnsupportedPlatform) } - pub(crate) fn launch( - &self, - _: usize, - _: u32, - _: u32, - _: usize, - args: &mut KernelArguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: u32, _: u32, _: usize, args: &mut KernelArguments) -> Result<()> { let _ = (&args.values, &args.null, &args.pointers, &args.addresses); Err(Error::UnsupportedPlatform) } #[allow(clippy::too_many_arguments)] - pub(crate) fn launch_cluster(&self, _: usize, _: [u32; 2], _: u32, _: u32, _: u32, _: usize, _: &mut KernelArguments) -> Result<()> { + pub(crate) fn launch_cluster( + &self, + _: usize, + _: [u32; 2], + _: u32, + _: u32, + _: u32, + _: usize, + _: &mut KernelArguments, + ) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn close(self) -> Result<()> { diff --git a/crates/cuda-driver/src/ple_batch_queue.rs b/crates/cuda-driver/src/ple_batch_queue.rs index ffc85367..233aaa45 100644 --- a/crates/cuda-driver/src/ple_batch_queue.rs +++ b/crates/cuda-driver/src/ple_batch_queue.rs @@ -3,14 +3,14 @@ //! binding, token, position, journal or session capability. use crate::ple_batch_ffi::{BatchArg as A, Blas, KernelArguments, KernelModule}; use crate::{ - Context, DeviceBuffer, Error, NativeBatchWorkspace, PleClosedRefusal, PleClosedWeights, Result, - combine, ffi::BufferHandle, + Context, DeviceBuffer, Error, NativeBatchWorkspace, PleClosedRefusal, PleClosedWeights, Result, combine, + ffi::BufferHandle, }; use std::ffi::CStr; const SIZES: [usize; 15] = [ - 655360, 2621440, 368640, 2621440, 655360, 2621440, 2621440, 1024, 2621440, 2621440, 2621440, - 23592960, 327680, 327680, 2560, + 655360, 2621440, 368640, 2621440, 655360, 2621440, 2621440, 1024, 2621440, 2621440, 2621440, 23592960, 327680, + 327680, 2560, ]; pub const PLE_BATCH_QUEUE_BYTES: usize = 44_281_344; const RESERVE: usize = 128 * 1024 * 1024; @@ -26,20 +26,19 @@ const REFUSALS: [PleClosedRefusal; 10] = [ PleClosedRefusal::History, PleClosedRefusal::Streams, ]; -const ENTRIES: [&CStr; 7] = [ - c"ple_rms", - c"ple_gate", - c"ple_broadcast", - c"ple_conv", - c"ple_history", - c"ple_snapshots", - c"ple_finite", -]; +const ENTRIES: [&CStr; 7] = + [c"ple_rms", c"ple_gate", c"ple_broadcast", c"ple_conv", c"ple_history", c"ple_snapshots", c"ple_finite"]; // Root must replace BOTH with an actual compiled asset+SHA after source intake. // The placeholder never becomes a runnable success stand-in. const PACK_ENTRIES: [&CStr; 1] = [c"ple_pack"]; -const PTX_SHA256: Option<[u8; 32]> = Some([95, 165, 201, 48, 244, 12, 180, 157, 158, 121, 163, 94, 25, 17, 198, 133, 129, 249, 44, 9, 119, 80, 239, 242, 140, 36, 94, 40, 112, 150, 74, 64]); -const PACK_PTX_SHA256: Option<[u8; 32]> = Some([1, 89, 40, 237, 226, 2, 66, 198, 49, 81, 48, 123, 213, 2, 191, 152, 244, 251, 88, 11, 173, 43, 125, 52, 114, 238, 187, 161, 18, 149, 48, 179]); +const PTX_SHA256: Option<[u8; 32]> = Some([ + 95, 165, 201, 48, 244, 12, 180, 157, 158, 121, 163, 94, 25, 17, 198, 133, 129, 249, 44, 9, 119, 80, 239, 242, 140, + 36, 94, 40, 112, 150, 74, 64, +]); +const PACK_PTX_SHA256: Option<[u8; 32]> = Some([ + 1, 89, 40, 237, 226, 2, 66, 198, 49, 81, 48, 123, 213, 2, 191, 152, 244, 251, 88, 11, 173, 43, 125, 52, 114, 238, + 187, 161, 18, 149, 48, 179, +]); const PACK_PTX_BYTES: Option = Some(8276); const PACK_PTX: &[u8] = concat!(include_str!("ple_bf16_pack.ptx"), "\0").as_bytes(); const PTX_BYTES: Option = Some(19699); @@ -50,7 +49,8 @@ pub enum PleBf16Mode { HighAndLow, } pub struct PleBatchQueue<'ctx> { - capacity: usize, sizes: [usize;15], + capacity: usize, + sizes: [usize; 15], context: &'ctx Context<'ctx>, buffers: [Option>; 15], pack_module: Option, @@ -69,37 +69,24 @@ pub struct PleBatchCompletion<'loan, 'ctx> { flags: Box<[u32]>, } enum Command { - Kernel { - index: usize, - grid: u32, - block: u32, - args: Box, - }, - Gemm { - input: BufferHandle, - weight: BufferHandle, - output: BufferHandle, - rows: i32, - n: i32, - alpha: f32, - beta: f32, - }, + Kernel { index: usize, grid: u32, block: u32, args: Box }, + Gemm { input: BufferHandle, weight: BufferHandle, output: BufferHandle, rows: i32, n: i32, alpha: f32, beta: f32 }, } mod assets_fn; #[allow(unused_imports)] use assets_fn::assets; -mod impl_plebatchqueue; mod impl_drop_for_plebatchqueue; +mod impl_plebatchqueue; +#[allow(unused_imports)] +use impl_drop_for_plebatchqueue::decode; +#[allow(unused_imports)] +use impl_drop_for_plebatchqueue::float_owner; +#[allow(unused_imports)] +use impl_drop_for_plebatchqueue::float_staging; #[allow(unused_imports)] use impl_drop_for_plebatchqueue::push; #[allow(unused_imports)] use impl_drop_for_plebatchqueue::scan; #[allow(unused_imports)] use impl_drop_for_plebatchqueue::staging; -#[allow(unused_imports)] -use impl_drop_for_plebatchqueue::float_staging; -#[allow(unused_imports)] -use impl_drop_for_plebatchqueue::float_owner; -#[allow(unused_imports)] -use impl_drop_for_plebatchqueue::decode; diff --git a/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs b/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs index 1d6a5168..6a23d864 100644 --- a/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs +++ b/crates/cuda-driver/src/ple_batch_queue/assets_fn.rs @@ -32,10 +32,7 @@ impl PleBatchCompletion<'_, '_> { } /// Earliest chronological row, then the original ten-stage guard order. pub fn numerical_refusal(&self) -> Option<(usize, PleClosedRefusal)> { - self.flags - .iter() - .enumerate() - .find_map(|(i, flag)| (*flag != 0).then_some((i / 10, REFUSALS[i % 10]))) + self.flags.iter().enumerate().find_map(|(i, flag)| (*flag != 0).then_some((i / 10, REFUSALS[i % 10]))) } /// Single-use chronological consumption, from the actual completed whole /// result and history snapshot owners. None means the recorded numerical @@ -71,24 +68,20 @@ impl PleBatchCompletion<'_, '_> { context.retain_driver(); // Those genuine owners were retained, so no later statement may // borrow them even if a compiler cannot infer the failed drain. - return combine(combine(operation, sync), pop) - .and_then(|()| Err(Error::ContextPoisoned)); + return combine(combine(operation, sync), pop).and_then(|()| Err(Error::ContextPoisoned)); } combine(combine(operation, sync), pop)?; decode(&sb, &mut sv); decode(&hb, &mut hv); self.next += 1; - Ok(Some(PleBatchRow { - streams: sv.into_boxed_slice(), - history: hv.into_boxed_slice(), - })) + Ok(Some(PleBatchRow { streams: sv.into_boxed_slice(), history: hv.into_boxed_slice() })) } } impl Context<'_> { pub fn ple_batch_queue(&self, mode: PleBf16Mode) -> Result> { PleBatchQueue::new(self, mode) } - pub fn ple_batch_queue_for_prompt(&self, mode:PleBf16Mode, capacity:usize)->Result> { - PleBatchQueue::new_capacity(self,mode,capacity) + pub fn ple_batch_queue_for_prompt(&self, mode: PleBf16Mode, capacity: usize) -> Result> { + PleBatchQueue::new_capacity(self, mode, capacity) } } diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_drop_for_plebatchqueue.rs b/crates/cuda-driver/src/ple_batch_queue/impl_drop_for_plebatchqueue.rs index 5113c9fe..b7ddb9a0 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_drop_for_plebatchqueue.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_drop_for_plebatchqueue.rs @@ -11,37 +11,21 @@ impl Drop for PleBatchQueue<'_> { impl Command { pub(super) fn launch(&mut self, blas: &Blas, pack: &KernelModule, module: &KernelModule) -> Result<()> { match self { - Self::Kernel { - index, - grid, - block, - args, - } => { + Self::Kernel { index, grid, block, args } => { if *index == 0 { pack.launch(0, *grid, *block, blas.stream(), args) } else { module.launch(*index - 1, *grid, *block, blas.stream(), args) } } - Self::Gemm { - input, - weight, - output, - rows, - n, - alpha, - beta, - } => blas.gemm_bf16(*input, *weight, *output, *rows, *n, 2560, alpha, beta), + Self::Gemm { input, weight, output, rows, n, alpha, beta } => { + blas.gemm_bf16(*input, *weight, *output, *rows, *n, 2560, alpha, beta) + } } } } pub(super) fn push(commands: &mut Vec, index: usize, grid: u32, block: u32, args: Vec) { - commands.push(Command::Kernel { - index, - grid, - block, - args: Box::new(KernelArguments::new(args)), - }); + commands.push(Command::Kernel { index, grid, block, args: Box::new(KernelArguments::new(args)) }); } pub(super) fn scan( commands: &mut Vec, @@ -56,19 +40,12 @@ pub(super) fn scan( 7, (words as u32 * rows as u32).div_ceil(256), 256, - vec![ - A::Address(data), - A::Address(status), - A::I32(words), - A::I32(rows), - A::I32(role), - ], + vec![A::Address(data), A::Address(status), A::I32(words), A::I32(rows), A::I32(role)], ); } pub(super) fn staging(count: usize) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(count) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; v.resize(count, 0); Ok(v) } @@ -81,8 +58,7 @@ pub(super) fn float_staging(values: &[f32]) -> Result> { } pub(super) fn float_owner(words: usize) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(words) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(words).map_err(|_| Error::HostAllocation)?; v.resize(words, 0.0); Ok(v) } diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs index f5e2d617..e84f1ba4 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2.rs @@ -3,31 +3,42 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> PleBatchQueue<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>, mode: PleBf16Mode) -> Result { - Self::new_capacity(context,mode,64) + Self::new_capacity(context, mode, 64) } - pub(in super::super) fn new_capacity(context:&'ctx Context<'ctx>,mode:PleBf16Mode,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - let mut sizes=SIZES; for (i,size) in sizes.iter_mut().enumerate() {if i!=2 {*size=(*size/64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;}} + pub(in super::super) fn new_capacity( + context: &'ctx Context<'ctx>, + mode: PleBf16Mode, + capacity: usize, + ) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let mut sizes = SIZES; + for (i, size) in sizes.iter_mut().enumerate() { + if i != 2 { + *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + } let ptx = assets()?; // explicit pending refusal before any allocation/module. if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - let required = sizes.iter().try_fold(0usize,|sum,n|sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + let required = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? .checked_add(RESERVE) .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); } let mut owner = Self { - capacity, sizes, context, + capacity, + sizes, + context, buffers: std::array::from_fn(|_| None), pack_module: None, module: None, @@ -60,11 +71,15 @@ impl<'ctx> PleBatchQueue<'ctx> { } Ok(owner) } - pub fn prompt_device_bytes(capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - Ok(368640+(PLE_BATCH_QUEUE_BYTES-368640)/64*capacity) + pub fn prompt_device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + Ok(368640 + (PLE_BATCH_QUEUE_BYTES - 368640) / 64 * capacity) + } + pub fn capacity(&self) -> usize { + self.capacity } - pub fn capacity(&self)->usize {self.capacity} pub fn allocated_bytes(&self) -> usize { self.buffers.iter().flatten().map(DeviceBuffer::len).sum() } diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs index 859f910e..bfe6c938 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> PleBatchQueue<'ctx> { /// Literal original batch profile, explicit hi-only or hi+low; no automatic /// equivalence to the old F32 MMVF reduction is asserted. Actual binding, @@ -28,66 +27,33 @@ impl<'ctx> PleBatchQueue<'ctx> { if !(1..=self.capacity).contains(&rows) || streams.len() != rows * 10240 || history.len() != 92160 { return Err(Error::InvalidQwenShape); } - if embedding - .iter() - .chain(streams) - .chain(history) - .any(|v| !v.is_finite()) - { + if embedding.iter().chain(streams).chain(history).any(|v| !v.is_finite()) { return Err(Error::InvalidDriverValue("PLE batch source finite")); } let key = self.weight(weights.key, 52428800, 2)?; let value = self.weight(weights.value, 13107200, 2)?; let mut aux = [h[0]; 4]; for (i, w) in weights.aux.iter().enumerate() { - aux[i] = self.weight( - w, - if i == 3 { 81920 } else { 40960 }, - if i == 3 { 2 } else { 4 }, - )?; + aux[i] = self.weight(w, if i == 3 { 81920 } else { 40960 }, if i == 3 { 2 } else { 4 })?; } - for (weight, bytes) in [ - (key, 52428800), - (value, 13107200), - (aux[0], 40960), - (aux[1], 40960), - (aux[2], 40960), - (aux[3], 81920), - ] { + for (weight, bytes) in + [(key, 52428800), (value, 13107200), (aux[0], 40960), (aux[1], 40960), (aux[2], 40960), (aux[3], 81920)] + { workspace.reject_alias(weight, bytes)?; } let t = rows as i32; let mut commands = Vec::new(); - commands - .try_reserve_exact(24) - .map_err(|_| Error::HostAllocation)?; - let pack_low = if self.mode == PleBf16Mode::HighAndLow { - A::Address(h[13]) - } else { - A::NullAddress - }; + commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; + let pack_low = if self.mode == PleBf16Mode::HighAndLow { A::Address(h[13]) } else { A::NullAddress }; push( &mut commands, 0, (rows * 2560).div_ceil(256) as u32, 256, - vec![ - A::Address(h[0]), - A::Address(h[12]), - pack_low, - A::I64(i64::from(t) * 2560), - ], + vec![A::Address(h[0]), A::Address(h[12]), pack_low, A::I64(i64::from(t) * 2560)], ); for (out, n, w) in [(3, 10240, key), (4, 2560, value)] { - commands.push(Command::Gemm { - input: h[12], - weight: w, - output: h[out], - rows: t, - n, - alpha: 1.0, - beta: 0.0, - }); + commands.push(Command::Gemm { input: h[12], weight: w, output: h[out], rows: t, n, alpha: 1.0, beta: 0.0 }); if self.mode == PleBf16Mode::HighAndLow { commands.push(Command::Gemm { input: h[13], @@ -99,42 +65,18 @@ impl<'ctx> PleBatchQueue<'ctx> { beta: 1.0, }); } - scan( - &mut commands, - h[out], - h[14], - n, - t, - if out == 3 { 0 } else { 1 }, - ); + scan(&mut commands, h[out], h[14], n, t, if out == 3 { 0 } else { 1 }); } - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])], - ); + push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])]); scan(&mut commands, h[5], h[14], 10240, t, 2); - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])], - ); + push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])]); scan(&mut commands, h[6], h[14], 10240, t, 3); push( &mut commands, 2, (rows * 4) as u32, 512, - vec![ - A::Address(h[5]), - A::Address(h[6]), - A::Address(h[7]), - A::F32(1.0 / 2560.0f32.sqrt()), - ], + vec![A::Address(h[5]), A::Address(h[6]), A::Address(h[7]), A::F32(1.0 / 2560.0f32.sqrt())], ); scan(&mut commands, h[7], h[14], 4, t, 4); push( @@ -142,21 +84,10 @@ impl<'ctx> PleBatchQueue<'ctx> { 3, (rows * 40) as u32, 256, - vec![ - A::Address(h[4]), - A::Address(h[7]), - A::Address(h[8]), - A::I32(t), - ], + vec![A::Address(h[4]), A::Address(h[7]), A::Address(h[8]), A::I32(t)], ); scan(&mut commands, h[8], h[14], 10240, t, 5); - push( - &mut commands, - 1, - (rows * 4) as u32, - 1024, - vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])], - ); + push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])]); scan(&mut commands, h[9], h[14], 10240, t, 6); push( &mut commands, @@ -179,21 +110,10 @@ impl<'ctx> PleBatchQueue<'ctx> { 6, (rows * 360) as u32, 256, - vec![ - A::Address(h[2]), - A::Address(h[9]), - A::Address(h[11]), - A::I32(t), - ], + vec![A::Address(h[2]), A::Address(h[9]), A::Address(h[11]), A::I32(t)], ); scan(&mut commands, h[11], h[14], 92160, t, 8); - push( - &mut commands, - 5, - 40, - 256, - vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)], - ); + push(&mut commands, 5, 40, 256, vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)]); scan(&mut commands, h[1], h[14], 10240, t, 9); let e = float_staging(embedding)?; let s = float_staging(streams)?; @@ -201,9 +121,7 @@ impl<'ctx> PleBatchQueue<'ctx> { let zero = staging(rows * 40)?; let mut statuses = staging(rows * 40)?; let mut flags = Vec::new(); - flags - .try_reserve_exact(rows * 10) - .map_err(|_| Error::HostAllocation)?; + flags.try_reserve_exact(rows * 10).map_err(|_| Error::HostAllocation)?; flags.resize(rows * 10, 0); let context = self.context; let guard = context.enter()?; @@ -257,11 +175,6 @@ impl<'ctx> PleBatchQueue<'ctx> { return Err(Error::InvalidDriverValue("PLE batch finite status")); } } - Ok(PleBatchCompletion { - owner: self, - rows, - next: 0, - flags: flags.into_boxed_slice(), - }) + Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: flags.into_boxed_slice() }) } } diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs index 4abe4da7..4c526641 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> PleBatchQueue<'ctx> { pub fn close(mut self) -> Result<()> { self.close_inner() @@ -25,10 +24,7 @@ impl<'ctx> PleBatchQueue<'ctx> { } } }; - for module in [self.pack_module.take(), self.module.take()] - .into_iter() - .flatten() - { + for module in [self.pack_module.take(), self.module.take()].into_iter().flatten() { let close = if self.context.is_poisoned() { std::mem::forget(module); Err(Error::ContextPoisoned) diff --git a/crates/cuda-driver/src/ple_closed_queue.rs b/crates/cuda-driver/src/ple_closed_queue.rs index c01f12e3..f0e274e3 100644 --- a/crates/cuda-driver/src/ple_closed_queue.rs +++ b/crates/cuda-driver/src/ple_closed_queue.rs @@ -2,14 +2,18 @@ //! Completion owns real final readbacks; it has no session/row/history authority. use super::*; -const SIZES: [usize; 14] = [ - 10240, 40960, 368640, 40960, 10240, 40960, 40960, 16, - 40960, 40960, 40960, 368640, 40960, 40, -]; +const SIZES: [usize; 14] = + [10240, 40960, 368640, 40960, 10240, 40960, 40960, 16, 40960, 40960, 40960, 368640, 40960, 40]; const CHARGE: usize = 1_085_496; const RESERVE: usize = 128 * 1024 * 1024; -const OPS: [Operation; 6] = [Operation::Bf16, Operation::PleNorm, - Operation::PleGate, Operation::PleBroadcast, Operation::PleConv, Operation::PleResidual]; +const OPS: [Operation; 6] = [ + Operation::Bf16, + Operation::PleNorm, + Operation::PleGate, + Operation::PleBroadcast, + Operation::PleConv, + Operation::PleResidual, +]; const OUTPUTS: [usize; 10] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; pub struct PleClosedWeights<'a, 'buffer> { @@ -18,11 +22,30 @@ pub struct PleClosedWeights<'a, 'buffer> { pub aux: [&'a DeviceBuffer<'buffer>; 4], } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PleClosedRefusal { Key, Value, KeyNorm, QueryNorm, Gate, Gated, Normalized, Conv, History, Streams } -const REFUSALS: [PleClosedRefusal; 10] = [PleClosedRefusal::Key, PleClosedRefusal::Value, - PleClosedRefusal::KeyNorm, PleClosedRefusal::QueryNorm, PleClosedRefusal::Gate, - PleClosedRefusal::Gated, PleClosedRefusal::Normalized, PleClosedRefusal::Conv, - PleClosedRefusal::History, PleClosedRefusal::Streams]; +pub enum PleClosedRefusal { + Key, + Value, + KeyNorm, + QueryNorm, + Gate, + Gated, + Normalized, + Conv, + History, + Streams, +} +const REFUSALS: [PleClosedRefusal; 10] = [ + PleClosedRefusal::Key, + PleClosedRefusal::Value, + PleClosedRefusal::KeyNorm, + PleClosedRefusal::QueryNorm, + PleClosedRefusal::Gate, + PleClosedRefusal::Gated, + PleClosedRefusal::Normalized, + PleClosedRefusal::Conv, + PleClosedRefusal::History, + PleClosedRefusal::Streams, +]; /// Fourteen exact whole owners; each call overwrites every actual role/status. pub struct PleClosedQueue<'ctx> { @@ -41,234 +64,24 @@ pub struct PleClosedCompletion<'loan, 'ctx> { streams: Box<[f32]>, history: Box<[f32]>, } -impl PleClosedCompletion<'_, '_> { - pub fn numerical_refusal(&self) -> Option { - self.flags.iter().zip(REFUSALS).find_map(|(flag, stage)| (*flag != 0).then_some(stage)) - } - /// Only successful full-role finite completion exposes usable host state. - pub fn into_parts(self) -> std::result::Result { - if let Some(error) = self.numerical_refusal() { return Err(error); } - debug_assert!(!self.owner.is_failed()); - Ok((self.streams, self.history)) - } -} -impl Context<'_> { - pub fn ple_closed_queue(&self) -> Result> { PleClosedQueue::new(self) } -} -impl<'ctx> PleClosedQueue<'ctx> { - fn new(context: &'ctx Context<'ctx>) -> Result { - if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - for operation in OPS { - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; - } - let required = CHARGE.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) - || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); } - let mut owner = Self { context, buffers: std::array::from_fn(|_| None), module: None, - functions: None, finite: None, failed: false }; - let operation = (|| { - for (i, bytes) in SIZES.into_iter().enumerate() { owner.buffers[i] = Some(context.allocate(bytes)?); } - let guard = context.enter()?; - let load = (|| { - let mut functions = [None; 6]; - for (i, operation) in OPS.into_iter().enumerate() { - let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; - functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); - } - owner.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators"))); - let module = context.driver.api.load_mmq_resident()?; - owner.module = Some(module); - owner.finite = Some([context.driver.api.mmq_resident_function(module, 0)?, - context.driver.api.mmq_resident_function(module, 1)?]); - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { context.poisoned.set(true); } - combine(load, pop)?; - owner.handles()?; - if context.memory_info()?.0 < RESERVE { return Err(Error::BudgetExceeded); } - Ok(()) - })(); - if let Err(error) = operation { return combine(Err(error), owner.close()); } - Ok(owner) - } - pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { - if !std::ptr::eq(self.context, context) { return Err(Error::ContextMismatch); } - self.handles().map(|_| ()) - } - pub fn allocated_bytes(&self) -> usize { self.buffers.iter().flatten().map(DeviceBuffer::len).sum() } - pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() || self.context.handle.is_none() } - fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { self.buffers[index].as_ref().ok_or(Error::ContextPoisoned) } - fn handles(&self) -> Result<[ffi::BufferHandle; 14]> { - if self.is_failed() || self.functions.is_none() || self.finite.is_none() { return Err(Error::ContextPoisoned); } - let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; - let mut handles = [first; 14]; - for (i, bytes) in SIZES.into_iter().enumerate() { - let buffer = self.buffer(i)?; - if !std::ptr::eq(buffer.context, self.context) { return Err(Error::ContextMismatch); } - if buffer.bytes != bytes { return Err(Error::InvalidQwenShape); } - let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, 4)?; - for (j, other) in handles.iter().take(i).enumerate() { - if handle.overlaps(bytes, *other, SIZES[j]) { return Err(Error::OutputAliasesInput); } - } - handles[i] = handle; - } - if self.context.allocated_bytes() > self.context.budget { return Err(Error::BudgetExceeded); } - Ok(handles) - } - fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result<()> { - if !std::ptr::eq(weight.context, self.context) { return Err(Error::ContextMismatch); } - if weight.bytes != bytes { return Err(Error::InvalidQwenShape); } - let handle = weight.handle.ok_or(Error::ContextPoisoned)?; - handle.validate_projection_extent(bytes, alignment)?; - for (owned, count) in self.handles()?.into_iter().zip(SIZES) { - if handle.overlaps(bytes, owned, count) { return Err(Error::OutputAliasesInput); } - } - Ok(()) - } - fn qwen(&self, commands: &mut Vec, operation: Operation, - buffers: &[&DeviceBuffer<'_>], layout: qwen_ffi::Layout) -> Result<()> { - let (_, layout, handles) = admission(self.context, buffers, Admission { - operation, layout: Ok(layout), asset: qwen_ffi::asset(operation), epsilon: 0.0, in_place: false })?; - let index = OPS.iter().position(|op| *op == operation).ok_or(Error::UnsupportedQwenOperation)?; - let function = self.functions.ok_or(Error::ContextPoisoned)?[index]; - commands.push(Command::Qwen(function, operation, Box::new(Arguments::with_layout(operation, layout, handles, 0.0)))); - Ok(()) - } - fn scan(&self, commands: &mut Vec, role: usize) -> Result<()> { - let handles = self.handles()?; - let output = OUTPUTS[role]; - let status = handles[13].checked_subspan(40, role * 4, 4)?; - let words = u32::try_from(SIZES[output] / 4).map_err(|_| Error::InvalidQwenShape)?; - commands.push(Command::Guard(self.finite.ok_or(Error::ContextPoisoned)?[1], words, - ffi::MmqResidentArguments::finite(handles[output], status, 0, words, 0))); - Ok(()) - } - /// All actual weights are borrowed through the completed drain. No source, - /// history, position, phase or session authority can be minted by this API. - pub fn compose<'loan>(&'loan mut self, weights: PleClosedWeights<'_, '_>, - embedding: &[f32], streams: &[f32], history: &[f32]) -> Result> { - let handles = self.handles()?; - for (values, words) in [(embedding, 2560), (streams, 10240), (history, 92160)] { - if values.len() != words { return Err(Error::InvalidQwenShape); } - if values.iter().any(|v| !v.is_finite()) { return Err(Error::InvalidDriverValue("PLE finite source")); } - } - self.weight(weights.key, 52_428_800, 2)?; - self.weight(weights.value, 13_107_200, 2)?; - for weight in weights.aux.iter().take(3) { self.weight(weight, 40960, 4)?; } - self.weight(weights.aux[3], 81920, 2)?; - let mut commands = Vec::new(); commands.try_reserve_exact(19).map_err(|_| Error::HostAllocation)?; - self.qwen(&mut commands, Operation::Bf16, &[weights.key, self.buffer(0)?, self.buffer(3)?], qwen_ffi::bf16_layout(10240, 2560)?)?; - self.scan(&mut commands, 0)?; - self.qwen(&mut commands, Operation::Bf16, &[weights.value, self.buffer(0)?, self.buffer(4)?], qwen_ffi::bf16_layout(2560, 2560)?)?; - self.scan(&mut commands, 1)?; - self.qwen(&mut commands, Operation::PleNorm, &[self.buffer(3)?, weights.aux[0], self.buffer(5)?], Operation::PleNorm.layout())?; - self.scan(&mut commands, 2)?; - self.qwen(&mut commands, Operation::PleNorm, &[self.buffer(1)?, weights.aux[1], self.buffer(6)?], Operation::PleNorm.layout())?; - self.scan(&mut commands, 3)?; - self.qwen(&mut commands, Operation::PleGate, &[self.buffer(5)?, self.buffer(6)?, self.buffer(7)?], Operation::PleGate.layout())?; - self.scan(&mut commands, 4)?; - self.qwen(&mut commands, Operation::PleBroadcast, &[self.buffer(4)?, self.buffer(7)?, self.buffer(8)?], Operation::PleBroadcast.layout())?; - self.scan(&mut commands, 5)?; - self.qwen(&mut commands, Operation::PleNorm, &[self.buffer(8)?, weights.aux[2], self.buffer(9)?], Operation::PleNorm.layout())?; - self.scan(&mut commands, 6)?; - self.qwen(&mut commands, Operation::PleConv, &[self.buffer(2)?, self.buffer(9)?, weights.aux[3], self.buffer(10)?, self.buffer(11)?], Operation::PleConv.layout())?; - self.scan(&mut commands, 7)?; self.scan(&mut commands, 8)?; - self.qwen(&mut commands, Operation::PleResidual, &[self.buffer(1)?, self.buffer(8)?, self.buffer(10)?, self.buffer(12)?], Operation::PleResidual.layout())?; - self.scan(&mut commands, 9)?; - let mut embedding_bytes = float_staging(embedding)?; - let mut streams_bytes = float_staging(streams)?; - let mut history_bytes = float_staging(history)?; - let mut statuses = staging(40)?; - let mut streams_out = staging(40960)?; - let mut history_out = staging(368640)?; - let mut streams_values = float_owner(10240)?; - let mut history_values = float_owner(92160)?; - let mut reset = ffi::MmqResidentArguments::zero(handles[13], 10); - let context = self.context; - let guard = context.enter()?; - let mut operation = context.driver.api.copy_from(handles[0], &embedding_bytes); - if operation.is_ok() { operation = context.driver.api.copy_from(handles[1], &streams_bytes); } - if operation.is_ok() { operation = context.driver.api.copy_from(handles[2], &history_bytes); } - if operation.is_ok() { operation = context.driver.api.launch_mmq_resident(self.finite.ok_or(Error::ContextPoisoned)?[0], 10, &mut reset); } - for command in &mut commands { - if operation.is_err() { break; } - operation = command.launch(context); - } - if operation.is_ok() { operation = context.driver.api.copy_to(handles[13], &mut statuses); } - if operation.is_ok() { operation = context.driver.api.copy_to(handles[12], &mut streams_out); } - if operation.is_ok() { operation = context.driver.api.copy_to(handles[11], &mut history_out); } - let sync = context.driver.api.synchronize(); - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || pop.is_err() { self.failed = true; context.poisoned.set(true); } - if sync.is_err() || pop.is_err() { - std::mem::forget((commands, reset, embedding_bytes, streams_bytes, history_bytes, - statuses, streams_out, history_out, streams_values, history_values, weights)); - context.retain_driver(); - return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain")); - } - combine(combine(operation, sync), pop)?; - let mut flags = [0; 10]; - for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { - *flag = u32::from_le_bytes(*bytes); - if *flag > 1 { self.failed = true; context.poisoned.set(true); return Err(Error::InvalidDriverValue("PLE finite status")); } - } - for (value, bytes) in streams_values.iter_mut().zip(streams_out.as_chunks::<4>().0) { *value = f32::from_le_bytes(*bytes); } - for (value, bytes) in history_values.iter_mut().zip(history_out.as_chunks::<4>().0) { *value = f32::from_le_bytes(*bytes); } - // Staging is no longer exposed or used once the actual completion drains. - embedding_bytes.clear(); streams_bytes.clear(); history_bytes.clear(); - Ok(PleClosedCompletion { owner: self, flags, streams: streams_values.into_boxed_slice(), history: history_values.into_boxed_slice() }) - } - pub fn close(mut self) -> Result<()> { self.close_inner() } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; self.functions = None; self.finite = None; - let mut result = Ok(()); - for slot in &mut self.buffers { - if let Some(buffer) = slot.take() { - let release = if self.context.is_poisoned() { std::mem::forget(buffer); Err(Error::ContextPoisoned) } else { buffer.release() }; - if release.is_err() { self.context.poisoned.set(true); } - result = combine(result, release); - } - } - if let Some(module) = self.module.take() { - let release = if self.context.is_poisoned() { self.context.retain_driver(); Err(Error::ContextPoisoned) } - else { match self.context.enter() { Ok(guard) => { - let unload = self.context.driver.api.unload(module); let pop = guard.finish(); combine(unload, pop) - }, Err(error) => Err(error) } }; - if release.is_err() { self.context.poisoned.set(true); self.context.retain_driver(); } - result = combine(result, release); - } - result - } -} -impl Drop for PleClosedQueue<'_> { fn drop(&mut self) { let _ = self.close_inner(); } } -fn staging(bytes: usize) -> Result> { - let mut result = Vec::new(); result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; - result.resize(bytes, 0); Ok(result) -} -fn float_staging(values: &[f32]) -> Result> { - let mut bytes = staging(values.len().checked_mul(4).ok_or(Error::HostAllocation)?)?; - for (value, out) in values.iter().zip(bytes.as_chunks_mut::<4>().0) { out.copy_from_slice(&value.to_le_bytes()); } - Ok(bytes) -} -fn float_owner(count: usize) -> Result> { - let mut result = Vec::new(); result.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; - result.resize(count, 0.0); Ok(result) -} enum Command { Qwen(ffi::FunctionHandle, Operation, Box), Guard(ffi::FunctionHandle, u32, ffi::MmqResidentArguments), } -impl Command { - fn launch(&mut self, context: &Context<'_>) -> Result<()> { - match self { - Self::Qwen(function, operation, arguments) => context.driver.api.launch_qwen(*function, *operation, arguments), - Self::Guard(function, grid, arguments) => context.driver.api.launch_mmq_resident(*function, *grid, arguments), - } - } -} #[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "ple_closed_queue_gpu.rs"] mod gpu; + +#[path = "ple_closed_queue/impl_pleclosedcompletion.rs"] +mod impl_pleclosedcompletion; +#[path = "ple_closed_queue/impl_pleclosedqueue_2.rs"] +mod impl_pleclosedqueue_2; +#[allow(unused_imports)] +use impl_pleclosedqueue_2::float_staging; +#[allow(unused_imports)] +use impl_pleclosedqueue_2::staging; +#[path = "ple_closed_queue/float_owner_fn.rs"] +mod float_owner_fn; +#[allow(unused_imports)] +use float_owner_fn::float_owner; diff --git a/crates/cuda-driver/src/ple_closed_queue/float_owner_fn.rs b/crates/cuda-driver/src/ple_closed_queue/float_owner_fn.rs new file mode 100644 index 00000000..35c1999a --- /dev/null +++ b/crates/cuda-driver/src/ple_closed_queue/float_owner_fn.rs @@ -0,0 +1,23 @@ +//! Moved out of the parent module by STRA-338: fn float_owner, impl Command. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn float_owner(count: usize) -> Result> { + let mut result = Vec::new(); + result.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; + result.resize(count, 0.0); + Ok(result) +} +impl Command { + pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { + match self { + Self::Qwen(function, operation, arguments) => { + context.driver.api.launch_qwen(*function, *operation, arguments) + } + Self::Guard(function, grid, arguments) => { + context.driver.api.launch_mmq_resident(*function, *grid, arguments) + } + } + } +} diff --git a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs new file mode 100644 index 00000000..652dc53f --- /dev/null +++ b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedcompletion.rs @@ -0,0 +1,180 @@ +//! Moved out of the parent module by STRA-338: impl PleClosedCompletion, impl Context, impl PleClosedQueue. + +#[allow(unused_imports)] +use super::*; + +impl PleClosedCompletion<'_, '_> { + pub fn numerical_refusal(&self) -> Option { + self.flags.iter().zip(REFUSALS).find_map(|(flag, stage)| (*flag != 0).then_some(stage)) + } + /// Only successful full-role finite completion exposes usable host state. + pub fn into_parts(self) -> std::result::Result { + if let Some(error) = self.numerical_refusal() { + return Err(error); + } + debug_assert!(!self.owner.is_failed()); + Ok((self.streams, self.history)) + } +} +impl Context<'_> { + pub fn ple_closed_queue(&self) -> Result> { + PleClosedQueue::new(self) + } +} +impl<'ctx> PleClosedQueue<'ctx> { + pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { + if context.is_poisoned() || context.handle.is_none() { + return Err(Error::ContextPoisoned); + } + for operation in OPS { + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; + } + let required = CHARGE.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + context, + buffers: std::array::from_fn(|_| None), + module: None, + functions: None, + finite: None, + failed: false, + }; + let operation = (|| { + for (i, bytes) in SIZES.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(bytes)?); + } + let guard = context.enter()?; + let load = (|| { + let mut functions = [None; 6]; + for (i, operation) in OPS.into_iter().enumerate() { + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + functions[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); + } + owner.functions = Some(functions.map(|f| f.expect("six admitted original PLE operators"))); + let module = context.driver.api.load_mmq_resident()?; + owner.module = Some(module); + owner.finite = Some([ + context.driver.api.mmq_resident_function(module, 0)?, + context.driver.api.mmq_resident_function(module, 1)?, + ]); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poisoned.set(true); + } + combine(load, pop)?; + owner.handles()?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(error) = operation { + return combine(Err(error), owner.close()); + } + Ok(owner) + } + pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(self.context, context) { + return Err(Error::ContextMismatch); + } + self.handles().map(|_| ()) + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() || self.context.handle.is_none() + } + pub(super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> { + self.buffers[index].as_ref().ok_or(Error::ContextPoisoned) + } + pub(super) fn handles(&self) -> Result<[ffi::BufferHandle; 14]> { + if self.is_failed() || self.functions.is_none() || self.finite.is_none() { + return Err(Error::ContextPoisoned); + } + let first = self.buffer(0)?.handle.ok_or(Error::ContextPoisoned)?; + let mut handles = [first; 14]; + for (i, bytes) in SIZES.into_iter().enumerate() { + let buffer = self.buffer(i)?; + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, 4)?; + for (j, other) in handles.iter().take(i).enumerate() { + if handle.overlaps(bytes, *other, SIZES[j]) { + return Err(Error::OutputAliasesInput); + } + } + handles[i] = handle; + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(handles) + } + pub(super) fn weight(&self, weight: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result<()> { + if !std::ptr::eq(weight.context, self.context) { + return Err(Error::ContextMismatch); + } + if weight.bytes != bytes { + return Err(Error::InvalidQwenShape); + } + let handle = weight.handle.ok_or(Error::ContextPoisoned)?; + handle.validate_projection_extent(bytes, alignment)?; + for (owned, count) in self.handles()?.into_iter().zip(SIZES) { + if handle.overlaps(bytes, owned, count) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + pub(super) fn qwen( + &self, + commands: &mut Vec, + operation: Operation, + buffers: &[&DeviceBuffer<'_>], + layout: qwen_ffi::Layout, + ) -> Result<()> { + let (_, layout, handles) = admission( + self.context, + buffers, + Admission { + operation, + layout: Ok(layout), + asset: qwen_ffi::asset(operation), + epsilon: 0.0, + in_place: false, + }, + )?; + let index = OPS.iter().position(|op| *op == operation).ok_or(Error::UnsupportedQwenOperation)?; + let function = self.functions.ok_or(Error::ContextPoisoned)?[index]; + commands.push(Command::Qwen( + function, + operation, + Box::new(Arguments::with_layout(operation, layout, handles, 0.0)), + )); + Ok(()) + } + pub(super) fn scan(&self, commands: &mut Vec, role: usize) -> Result<()> { + let handles = self.handles()?; + let output = OUTPUTS[role]; + let status = handles[13].checked_subspan(40, role * 4, 4)?; + let words = u32::try_from(SIZES[output] / 4).map_err(|_| Error::InvalidQwenShape)?; + commands.push(Command::Guard( + self.finite.ok_or(Error::ContextPoisoned)?[1], + words, + ffi::MmqResidentArguments::finite(handles[output], status, 0, words, 0), + )); + Ok(()) + } +} diff --git a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs new file mode 100644 index 00000000..0e437505 --- /dev/null +++ b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs @@ -0,0 +1,246 @@ +//! Moved out of the parent module by STRA-338: impl PleClosedQueue (2), impl Drop_for_PleClosedQueue, fn staging, fn float_staging. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> PleClosedQueue<'ctx> { + /// All actual weights are borrowed through the completed drain. No source, + /// history, position, phase or session authority can be minted by this API. + pub fn compose<'loan>( + &'loan mut self, + weights: PleClosedWeights<'_, '_>, + embedding: &[f32], + streams: &[f32], + history: &[f32], + ) -> Result> { + let handles = self.handles()?; + for (values, words) in [(embedding, 2560), (streams, 10240), (history, 92160)] { + if values.len() != words { + return Err(Error::InvalidQwenShape); + } + if values.iter().any(|v| !v.is_finite()) { + return Err(Error::InvalidDriverValue("PLE finite source")); + } + } + self.weight(weights.key, 52_428_800, 2)?; + self.weight(weights.value, 13_107_200, 2)?; + for weight in weights.aux.iter().take(3) { + self.weight(weight, 40960, 4)?; + } + self.weight(weights.aux[3], 81920, 2)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(19).map_err(|_| Error::HostAllocation)?; + self.qwen( + &mut commands, + Operation::Bf16, + &[weights.key, self.buffer(0)?, self.buffer(3)?], + qwen_ffi::bf16_layout(10240, 2560)?, + )?; + self.scan(&mut commands, 0)?; + self.qwen( + &mut commands, + Operation::Bf16, + &[weights.value, self.buffer(0)?, self.buffer(4)?], + qwen_ffi::bf16_layout(2560, 2560)?, + )?; + self.scan(&mut commands, 1)?; + self.qwen( + &mut commands, + Operation::PleNorm, + &[self.buffer(3)?, weights.aux[0], self.buffer(5)?], + Operation::PleNorm.layout(), + )?; + self.scan(&mut commands, 2)?; + self.qwen( + &mut commands, + Operation::PleNorm, + &[self.buffer(1)?, weights.aux[1], self.buffer(6)?], + Operation::PleNorm.layout(), + )?; + self.scan(&mut commands, 3)?; + self.qwen( + &mut commands, + Operation::PleGate, + &[self.buffer(5)?, self.buffer(6)?, self.buffer(7)?], + Operation::PleGate.layout(), + )?; + self.scan(&mut commands, 4)?; + self.qwen( + &mut commands, + Operation::PleBroadcast, + &[self.buffer(4)?, self.buffer(7)?, self.buffer(8)?], + Operation::PleBroadcast.layout(), + )?; + self.scan(&mut commands, 5)?; + self.qwen( + &mut commands, + Operation::PleNorm, + &[self.buffer(8)?, weights.aux[2], self.buffer(9)?], + Operation::PleNorm.layout(), + )?; + self.scan(&mut commands, 6)?; + self.qwen( + &mut commands, + Operation::PleConv, + &[self.buffer(2)?, self.buffer(9)?, weights.aux[3], self.buffer(10)?, self.buffer(11)?], + Operation::PleConv.layout(), + )?; + self.scan(&mut commands, 7)?; + self.scan(&mut commands, 8)?; + self.qwen( + &mut commands, + Operation::PleResidual, + &[self.buffer(1)?, self.buffer(8)?, self.buffer(10)?, self.buffer(12)?], + Operation::PleResidual.layout(), + )?; + self.scan(&mut commands, 9)?; + let mut embedding_bytes = float_staging(embedding)?; + let mut streams_bytes = float_staging(streams)?; + let mut history_bytes = float_staging(history)?; + let mut statuses = staging(40)?; + let mut streams_out = staging(40960)?; + let mut history_out = staging(368640)?; + let mut streams_values = float_owner(10240)?; + let mut history_values = float_owner(92160)?; + let mut reset = ffi::MmqResidentArguments::zero(handles[13], 10); + let context = self.context; + let guard = context.enter()?; + let mut operation = context.driver.api.copy_from(handles[0], &embedding_bytes); + if operation.is_ok() { + operation = context.driver.api.copy_from(handles[1], &streams_bytes); + } + if operation.is_ok() { + operation = context.driver.api.copy_from(handles[2], &history_bytes); + } + if operation.is_ok() { + operation = + context.driver.api.launch_mmq_resident(self.finite.ok_or(Error::ContextPoisoned)?[0], 10, &mut reset); + } + for command in &mut commands { + if operation.is_err() { + break; + } + operation = command.launch(context); + } + if operation.is_ok() { + operation = context.driver.api.copy_to(handles[13], &mut statuses); + } + if operation.is_ok() { + operation = context.driver.api.copy_to(handles[12], &mut streams_out); + } + if operation.is_ok() { + operation = context.driver.api.copy_to(handles[11], &mut history_out); + } + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + context.poisoned.set(true); + } + if sync.is_err() || pop.is_err() { + std::mem::forget(( + commands, + reset, + embedding_bytes, + streams_bytes, + history_bytes, + statuses, + streams_out, + history_out, + streams_values, + history_values, + weights, + )); + context.retain_driver(); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain")); + } + combine(combine(operation, sync), pop)?; + let mut flags = [0; 10]; + for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { + *flag = u32::from_le_bytes(*bytes); + if *flag > 1 { + self.failed = true; + context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE finite status")); + } + } + for (value, bytes) in streams_values.iter_mut().zip(streams_out.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + for (value, bytes) in history_values.iter_mut().zip(history_out.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + // Staging is no longer exposed or used once the actual completion drains. + embedding_bytes.clear(); + streams_bytes.clear(); + history_bytes.clear(); + Ok(PleClosedCompletion { + owner: self, + flags, + streams: streams_values.into_boxed_slice(), + history: history_values.into_boxed_slice(), + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.functions = None; + self.finite = None; + let mut result = Ok(()); + for slot in &mut self.buffers { + if let Some(buffer) = slot.take() { + let release = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if release.is_err() { + self.context.poisoned.set(true); + } + result = combine(result, release); + } + } + if let Some(module) = self.module.take() { + let release = if self.context.is_poisoned() { + self.context.retain_driver(); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = self.context.driver.api.unload(module); + let pop = guard.finish(); + combine(unload, pop) + } + Err(error) => Err(error), + } + }; + if release.is_err() { + self.context.poisoned.set(true); + self.context.retain_driver(); + } + result = combine(result, release); + } + result + } +} +impl Drop for PleClosedQueue<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +pub(super) fn staging(bytes: usize) -> Result> { + let mut result = Vec::new(); + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; + result.resize(bytes, 0); + Ok(result) +} +pub(super) fn float_staging(values: &[f32]) -> Result> { + let mut bytes = staging(values.len().checked_mul(4).ok_or(Error::HostAllocation)?)?; + for (value, out) in values.iter().zip(bytes.as_chunks_mut::<4>().0) { + out.copy_from_slice(&value.to_le_bytes()); + } + Ok(bytes) +} diff --git a/crates/cuda-driver/src/ple_closed_queue_gpu.rs b/crates/cuda-driver/src/ple_closed_queue_gpu.rs index 76ad7f93..9bb1211e 100644 --- a/crates/cuda-driver/src/ple_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/ple_closed_queue_gpu.rs @@ -4,36 +4,55 @@ use crate::Driver; fn upload<'ctx>(context: &'ctx Context<'ctx>, bytes: &[u8]) -> Result> { let mut owner = context.allocate(bytes.len())?; - if let Err(error) = owner.copy_from(bytes) { return combine(Err(error), owner.release()); } + if let Err(error) = owner.copy_from(bytes) { + return combine(Err(error), owner.release()); + } Ok(owner) } fn bf16(count: usize, seed: usize) -> Vec { - (0..count).flat_map(|i| { - let value = ((i.wrapping_mul(3).wrapping_add(seed) % 17) as f32 - 8.0) / 4096.0; - ((value.to_bits() >> 16) as u16).to_le_bytes() - }).collect() + (0..count) + .flat_map(|i| { + let value = ((i.wrapping_mul(3).wrapping_add(seed) % 17) as f32 - 8.0) / 4096.0; + ((value.to_bits() >> 16) as u16).to_le_bytes() + }) + .collect() } fn values(count: usize, seed: usize, zeros: bool) -> Vec { - (0..count).map(|i| if zeros { if i % 2 == 0 { -0.0 } else { 0.0 } } - else { ((i + seed) % 19) as f32 / 128.0 - 9.0 / 128.0 }).collect() + (0..count) + .map( + |i| { + if zeros { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i + seed) % 19) as f32 / 128.0 - 9.0 / 128.0 } + }, + ) + .collect() } fn read(buffer: &DeviceBuffer<'_>) -> Result> { let mut bytes = staging(buffer.bytes)?; buffer.copy_to(&mut bytes)?; Ok(bytes.as_chunks::<4>().0.iter().map(|b| u32::from_le_bytes(*b)).collect()) } -struct Reference { products: Vec>, refusal: Option } +struct Reference { + products: Vec>, + refusal: Option, +} fn record(products: &mut Vec>, output: &DeviceBuffer<'_>) -> Result { let words = read(output)?; let valid = words.iter().all(|word| f32::from_bits(*word).is_finite()); products.push(words); Ok(valid) } -fn original(context: &Context<'_>, weights: [&DeviceBuffer<'_>; 6], - embedding: &[f32], streams: &[f32], history: &[f32]) -> Result { +fn original( + context: &Context<'_>, + weights: [&DeviceBuffer<'_>; 6], + embedding: &[f32], + streams: &[f32], + history: &[f32], +) -> Result { let mut buffers: [Option>; 13] = std::array::from_fn(|_| None); let operation = (|| { - for (i, size) in SIZES[..13].iter().enumerate() { buffers[i] = Some(context.allocate(*size)?); } + for (i, size) in SIZES[..13].iter().enumerate() { + buffers[i] = Some(context.allocate(*size)?); + } for (slot, values) in [(0, embedding), (1, streams), (2, history)] { buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&float_staging(values)?)?; } @@ -46,23 +65,37 @@ fn original(context: &Context<'_>, weights: [&DeviceBuffer<'_>; 6], let get = |i: usize| inputs[i].as_ref().ok_or(Error::ContextPoisoned); if role == 7 { let (conv, next) = outputs.split_at_mut(1); - context.ple_conv_history_f32(get(2)?, get(9)?, weights[5], + context.ple_conv_history_f32( + get(2)?, + get(9)?, + weights[5], conv[0].as_mut().ok_or(Error::ContextPoisoned)?, - next[0].as_mut().ok_or(Error::ContextPoisoned)?)?; + next[0].as_mut().ok_or(Error::ContextPoisoned)?, + )?; } else { - let output = outputs[0].as_mut().ok_or(Error::ContextPoisoned)?; - match role { - 0 => context.bf16_f32(weights[0], get(0)?, output, crate::Bf16ProjectionShape { rows: 10240, columns: 2560 })?, - 1 => context.bf16_f32(weights[1], get(0)?, output, crate::Bf16ProjectionShape { rows: 2560, columns: 2560 })?, - 2 => context.ple_grouped_norm_f32(get(3)?, weights[2], output)?, - 3 => context.ple_grouped_norm_f32(get(1)?, weights[3], output)?, - 4 => context.ple_signed_gate_f32(get(5)?, get(6)?, output)?, - 5 => context.ple_broadcast_f32(get(4)?, get(7)?, output)?, - 6 => context.ple_grouped_norm_f32(get(8)?, weights[4], output)?, - 8 => (), - 9 => context.ple_residual_f32(get(1)?, get(8)?, get(10)?, output)?, - _ => unreachable!(), - } + let output = outputs[0].as_mut().ok_or(Error::ContextPoisoned)?; + match role { + 0 => context.bf16_f32( + weights[0], + get(0)?, + output, + crate::Bf16ProjectionShape { rows: 10240, columns: 2560 }, + )?, + 1 => context.bf16_f32( + weights[1], + get(0)?, + output, + crate::Bf16ProjectionShape { rows: 2560, columns: 2560 }, + )?, + 2 => context.ple_grouped_norm_f32(get(3)?, weights[2], output)?, + 3 => context.ple_grouped_norm_f32(get(1)?, weights[3], output)?, + 4 => context.ple_signed_gate_f32(get(5)?, get(6)?, output)?, + 5 => context.ple_broadcast_f32(get(4)?, get(7)?, output)?, + 6 => context.ple_grouped_norm_f32(get(8)?, weights[4], output)?, + 8 => (), + 9 => context.ple_residual_f32(get(1)?, get(8)?, get(10)?, output)?, + _ => unreachable!(), + } } if !record(&mut products, buffers[index].as_ref().ok_or(Error::ContextPoisoned)?)? { return Ok(Reference { products, refusal: Some(REFUSALS[role]) }); @@ -71,7 +104,11 @@ fn original(context: &Context<'_>, weights: [&DeviceBuffer<'_>; 6], Ok(Reference { products, refusal: None }) })(); let mut cleanup = Ok(()); - for slot in &mut buffers { if let Some(buffer) = slot.take() { cleanup = combine(cleanup, buffer.release()); } } + for slot in &mut buffers { + if let Some(buffer) = slot.take() { + cleanup = combine(cleanup, buffer.release()); + } + } drop(buffers); combine(operation, cleanup) } @@ -79,22 +116,38 @@ fn refs<'a, 'b>(weights: &'a [DeviceBuffer<'b>]) -> [&'a DeviceBuffer<'b>; 6] { [&weights[0], &weights[1], &weights[2], &weights[3], &weights[4], &weights[5]] } type QueuedProducts = (Option, Vec>); -fn queued(queue: &mut PleClosedQueue<'_>, weights: [&DeviceBuffer<'_>; 6], - embedding: &[f32], streams: &[f32], history: &[f32]) -> Result { - let result = queue.compose(PleClosedWeights { key: weights[0], value: weights[1], - aux: [weights[2], weights[3], weights[4], weights[5]] }, embedding, streams, history)?; +fn queued( + queue: &mut PleClosedQueue<'_>, + weights: [&DeviceBuffer<'_>; 6], + embedding: &[f32], + streams: &[f32], + history: &[f32], +) -> Result { + let result = queue.compose( + PleClosedWeights { key: weights[0], value: weights[1], aux: [weights[2], weights[3], weights[4], weights[5]] }, + embedding, + streams, + history, + )?; let refusal = result.numerical_refusal(); - let mut products = Vec::new(); products.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; - for index in OUTPUTS { products.push(read(result.owner.buffer(index)?)?); } + let mut products = Vec::new(); + products.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; + for index in OUTPUTS { + products.push(read(result.owner.buffer(index)?)?); + } let flags = result.flags; drop(result); - if flags.iter().any(|f| *f > 1) { return Err(Error::InvalidDriverValue("PLE fixture flags")); } + if flags.iter().any(|f| *f > 1) { + return Err(Error::InvalidDriverValue("PLE fixture flags")); + } Ok((refusal, products)) } #[test] #[ignore] fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { - if std::env::var("LELEKA_STRA169_RUN_PLE_CLOSED_QUEUE").as_deref() != Ok("yes") { return; } + if std::env::var("LELEKA_STRA169_RUN_PLE_CLOSED_QUEUE").as_deref() != Ok("yes") { + return; + } let driver = Driver::load().expect("actual driver"); let device = driver.device(0).expect("actual device"); let context = device.create_context(512 * 1024 * 1024).expect("actual context"); @@ -106,73 +159,154 @@ fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() { weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; weights.push(upload(&context, &bf16(10240 * 2560, 2))?); weights.push(upload(&context, &bf16(2560 * 2560, 3))?); - for _ in 0..3 { weights.push(upload(&context, &float_staging(&vec![1.0; 10240])?)?); } + for _ in 0..3 { + weights.push(upload(&context, &float_staging(&vec![1.0; 10240])?)?); + } weights.push(upload(&context, &bf16(4 * 10240, 4))?); queue = Some(context.ple_closed_queue()?); let q = queue.as_mut().ok_or(Error::ContextPoisoned)?; - let mut words = 0usize; let mut differences = 0usize; let mut guards = 0usize; + let mut words = 0usize; + let mut differences = 0usize; + let mut guards = 0usize; let mut history = values(92160, 5, false); for case in 0..4 { let embedding = values(2560, case * 3, case == 2); let streams = values(10240, case * 5, case == 2); let old = original(&context, refs(&weights), &embedding, &streams, &history)?; let (refusal, products) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if old.refusal.is_some() || refusal.is_some() { differences += 1; } + if old.refusal.is_some() || refusal.is_some() { + differences += 1; + } for (a, b) in old.products.iter().zip(&products) { - words += a.len(); differences += a.iter().zip(b).filter(|(a, b)| a != b).count(); - if a.len() != b.len() { differences += 1; } + words += a.len(); + differences += a.iter().zip(b).filter(|(a, b)| a != b).count(); + if a.len() != b.len() { + differences += 1; + } } // The genuine previous candidate history supplies the next causal // row; it must equal the original complete history first. history = products[8].iter().map(|word| f32::from_bits(*word)).collect(); } - let embedding = values(2560, 3, false); let streams = values(10240, 5, false); - for (weight, offset, bytes) in [(0, 52_428_798, vec![0x80, 0x7f]), - (1, 13_107_198, vec![0x80, 0x7f]), (2, 40956, f32::NAN.to_le_bytes().to_vec()), - (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), (4, 40956, f32::NAN.to_le_bytes().to_vec()), - (5, 81918, vec![0xc0, 0x7f])] { - let mut saved = staging(weights[weight].bytes)?; weights[weight].copy_to(&mut saved)?; + let embedding = values(2560, 3, false); + let streams = values(10240, 5, false); + for (weight, offset, bytes) in [ + (0, 52_428_798, vec![0x80, 0x7f]), + (1, 13_107_198, vec![0x80, 0x7f]), + (2, 40956, f32::NAN.to_le_bytes().to_vec()), + (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), + (4, 40956, f32::NAN.to_le_bytes().to_vec()), + (5, 81918, vec![0xc0, 0x7f]), + ] { + let mut saved = staging(weights[weight].bytes)?; + weights[weight].copy_to(&mut saved)?; weights[weight].copy_from_range(offset, &bytes)?; let old = original(&context, refs(&weights), &embedding, &streams, &history)?; let (refusal, _) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if old.refusal.is_none() || old.refusal != refusal { differences += 1; } + if old.refusal.is_none() || old.refusal != refusal { + differences += 1; + } guards += 1; weights[weight].copy_from(&saved)?; let old = original(&context, refs(&weights), &embedding, &streams, &history)?; let (refusal, products) = queued(q, refs(&weights), &embedding, &streams, &history)?; - if refusal.is_some() || old.refusal.is_some() { differences += 1; } - for (a, b) in old.products.iter().zip(products) { words += a.len(); differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); } + if refusal.is_some() || old.refusal.is_some() { + differences += 1; + } + for (a, b) in old.products.iter().zip(products) { + words += a.len(); + differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); + } guards += 1; } let before = read(q.buffer(12)?)?; - let mut invalid = embedding.clone(); invalid[2559] = f32::NAN; - if q.compose(PleClosedWeights { key: &weights[0], value: &weights[1], aux: [&weights[2], &weights[3], &weights[4], &weights[5]] }, &invalid, &streams, &history).is_ok() { differences += 1; } + let mut invalid = embedding.clone(); + invalid[2559] = f32::NAN; + if q.compose( + PleClosedWeights { + key: &weights[0], + value: &weights[1], + aux: [&weights[2], &weights[3], &weights[4], &weights[5]], + }, + &invalid, + &streams, + &history, + ) + .is_ok() + { + differences += 1; + } guards += 1; - if q.compose(PleClosedWeights { key: &weights[0], value: &weights[1], aux: [&weights[2], &weights[3], &weights[4], &weights[5]] }, &embedding[..2559], &streams, &history).is_ok() { differences += 1; } + if q.compose( + PleClosedWeights { + key: &weights[0], + value: &weights[1], + aux: [&weights[2], &weights[3], &weights[4], &weights[5]], + }, + &embedding[..2559], + &streams, + &history, + ) + .is_ok() + { + differences += 1; + } guards += 1; foreign_weight = Some(foreign.allocate(1024)?); - if q.compose(PleClosedWeights { key: foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, value: &weights[1], aux: [&weights[2], &weights[3], &weights[4], &weights[5]] }, &embedding, &streams, &history).is_ok() { differences += 1; } + if q.compose( + PleClosedWeights { + key: foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, + value: &weights[1], + aux: [&weights[2], &weights[3], &weights[4], &weights[5]], + }, + &embedding, + &streams, + &history, + ) + .is_ok() + { + differences += 1; + } guards += 1; - if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { differences += 1; } + if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { + differences += 1; + } guards += 1; - if read(q.buffer(12)?)? != before { differences += 1; } + if read(q.buffer(12)?)? != before { + differences += 1; + } Ok((words, differences, guards)) })(); let mut cleanup = Ok(()); - if let Some(q) = queue.take() { cleanup = combine(cleanup, q.close()); } + if let Some(q) = queue.take() { + cleanup = combine(cleanup, q.close()); + } drop(queue); - if let Some(buffer) = foreign_weight.take() { cleanup = combine(cleanup, buffer.release()); } + if let Some(buffer) = foreign_weight.take() { + cleanup = combine(cleanup, buffer.release()); + } drop(foreign_weight); - for buffer in weights.drain(..) { cleanup = combine(cleanup, buffer.release()); } + for buffer in weights.drain(..) { + cleanup = combine(cleanup, buffer.release()); + } drop(weights); - let allocated = context.allocated_bytes(); let foreign_allocated = foreign.allocated_bytes(); - cleanup = combine(cleanup, foreign.close()); cleanup = combine(cleanup, context.close()); + let allocated = context.allocated_bytes(); + let foreign_allocated = foreign.allocated_bytes(); + cleanup = combine(cleanup, foreign.close()); + cleanup = combine(cleanup, context.close()); let (words, differences, guards) = combine(result, cleanup).expect("original-first PLE and full cleanup"); - assert_eq!(allocated, 0); assert_eq!(foreign_allocated, 0); assert_eq!(differences, 0); + assert_eq!(allocated, 0); + assert_eq!(foreign_allocated, 0); + assert_eq!(differences, 0); assert_eq!(guards, 16); - eprintln!("PLE_CLOSED_QUEUE PASS words={words} differences={differences} guards={guards} original_first=true causal_history=true allocated0=true"); + eprintln!( + "PLE_CLOSED_QUEUE PASS words={words} differences={differences} guards={guards} original_first=true causal_history=true allocated0=true" + ); let tiny = device.create_context(CHARGE + RESERVE - 1).expect("actual budget context"); let refused = matches!(tiny.ple_closed_queue(), Err(Error::BudgetExceeded)); - let allocated = tiny.allocated_bytes(); let closed = tiny.close(); - assert!(refused); assert_eq!(allocated, 0); assert!(closed.is_ok()); + let allocated = tiny.allocated_bytes(); + let closed = tiny.close(); + assert!(refused); + assert_eq!(allocated, 0); + assert!(closed.is_ok()); } diff --git a/crates/cuda-driver/src/ple_value_full_gpu.rs b/crates/cuda-driver/src/ple_value_full_gpu.rs index 54d0586f..3b959672 100644 --- a/crates/cuda-driver/src/ple_value_full_gpu.rs +++ b/crates/cuda-driver/src/ple_value_full_gpu.rs @@ -26,24 +26,14 @@ fn tile_bytes(tile: usize) -> Vec { fn embedding(zero: bool) -> Vec { (0usize..2560) .flat_map(|i| { - let x = if zero { - if i.is_multiple_of(2) { -0.0f32 } else { 0. } - } else { - ((i % 17) as f32 - 8.) / 64. - }; + let x = if zero { if i.is_multiple_of(2) { -0.0f32 } else { 0. } } else { ((i % 17) as f32 - 8.) / 64. }; x.to_le_bytes() }) .collect() } fn exact(actual: &[u8], expected: &[u8]) { assert_eq!(actual.len(), expected.len()); - for (i, (a, b)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(expected.as_chunks::<4>().0) - .enumerate() - { + for (i, (a, b)) in actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0).enumerate() { assert!(f32::from_le_bytes(*a).is_finite() && f32::from_le_bytes(*b).is_finite()); assert_eq!(a, b, "word {i}"); } @@ -55,13 +45,7 @@ fn original(ctx: &Context<'_>, input: &DeviceBuffer<'_>) -> Vec { let matrix = upload(ctx, &tile_bytes(tile)); ctx.ple_value_bf16_f32(input, &matrix, &mut out).unwrap(); let bytes = read(&out); - assert!( - bytes - .as_chunks::<4>() - .0 - .iter() - .all(|word| f32::from_le_bytes(*word).is_finite()) - ); + assert!(bytes.as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_finite())); values.extend_from_slice(&bytes); matrix.release().unwrap(); } @@ -90,8 +74,7 @@ fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { let expected = original(&ctx, &input); // Qualified old40 kernels FIRST. assert_eq!(ctx.allocated_bytes(), charged); out.copy_from(&sentinel).unwrap(); - ctx.ple_value_full_bf16_f32(&input, &weights, &mut out) - .unwrap(); + ctx.ple_value_full_bf16_f32(&input, &weights, &mut out).unwrap(); exact(&read(&out), &expected); assert_eq!(read(&input), bytes); assert_eq!(read(&weights), packed); @@ -107,18 +90,11 @@ fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { let saved: [u8; 2] = packed[last..].try_into().unwrap(); packed[last..].copy_from_slice(&0x7fc1u16.to_le_bytes()); weights.copy_from(&packed).unwrap(); - ctx.ple_value_full_bf16_f32(&input, &weights, &mut out) - .unwrap(); + ctx.ple_value_full_bf16_f32(&input, &weights, &mut out).unwrap(); let malformed = read(&out); exact(&malformed[..OUTPUT - 4], &ordinary[..OUTPUT - 4]); assert!(f32::from_le_bytes(malformed[OUTPUT - 4..].try_into().unwrap()).is_nan()); - assert!( - malformed - .as_chunks::<4>() - .0 - .iter() - .any(|word| !f32::from_le_bytes(*word).is_finite()) - ); + assert!(malformed.as_chunks::<4>().0.iter().any(|word| !f32::from_le_bytes(*word).is_finite())); assert_eq!(ctx.allocated_bytes(), charged); packed[last..].copy_from_slice(&saved); weights.copy_from(&packed).unwrap(); @@ -144,14 +120,8 @@ fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { let mut foreign_out = upload(&foreign, &sentinel); let foreign_input = upload(&foreign, &embedding(false)); out.copy_from(&sentinel).unwrap(); - assert_eq!( - ctx.ple_value_full_bf16_f32(&foreign_input, &weights, &mut out), - Err(Error::ContextMismatch) - ); - assert_eq!( - ctx.ple_value_full_bf16_f32(&input, &weights, &mut foreign_out), - Err(Error::ContextMismatch) - ); + assert_eq!(ctx.ple_value_full_bf16_f32(&foreign_input, &weights, &mut out), Err(Error::ContextMismatch)); + assert_eq!(ctx.ple_value_full_bf16_f32(&input, &weights, &mut foreign_out), Err(Error::ContextMismatch)); assert_eq!(read(&out), sentinel); assert_eq!(read(&foreign_out), sentinel); assert_eq!(ctx.allocated_bytes(), charged); @@ -163,10 +133,7 @@ fn whole_value_matches_original_40_tiles_and_refuses_closed_shapes() { // The actual allocator enforces precharge; no fake kernel budget mutation. let tiny = device.create_context(WEIGHTS + EMBEDDING - 1).unwrap(); let only_weight = tiny.allocate(WEIGHTS).unwrap(); - assert!(matches!( - tiny.allocate(EMBEDDING), - Err(Error::BudgetExceeded) - )); + assert!(matches!(tiny.allocate(EMBEDDING), Err(Error::BudgetExceeded))); assert_eq!(tiny.allocated_bytes(), WEIGHTS); only_weight.release().unwrap(); assert_eq!(tiny.allocated_bytes(), 0); diff --git a/crates/cuda-driver/src/prefill_stage.rs b/crates/cuda-driver/src/prefill_stage.rs index 50e3711c..72543c1c 100644 --- a/crates/cuda-driver/src/prefill_stage.rs +++ b/crates/cuda-driver/src/prefill_stage.rs @@ -132,12 +132,12 @@ pub(crate) fn fast_dequant() -> bool { /// Frozen by `scripts/gpu-bringup/seal_pins.py` after `compile_assets.py` (extra-seal-plan.json, group prefill-stage). pub(crate) const PIN: PtxPin = PtxPin { source_sha256: [ - 62, 247, 28, 124, 51, 213, 225, 210, 87, 103, 7, 80, 80, 6, 194, 177, 126, 226, 97, 251, - 127, 238, 115, 78, 196, 57, 156, 88, 242, 97, 4, 252, + 62, 247, 28, 124, 51, 213, 225, 210, 87, 103, 7, 80, 80, 6, 194, 177, 126, 226, 97, 251, 127, 238, 115, 78, + 196, 57, 156, 88, 242, 97, 4, 252, ], ptx_sha256: [ - 111, 143, 179, 187, 209, 17, 113, 201, 57, 2, 151, 213, 210, 201, 203, 144, 118, 212, 182, - 81, 242, 167, 4, 43, 241, 111, 76, 175, 137, 165, 179, 132, + 111, 143, 179, 187, 209, 17, 113, 201, 57, 2, 151, 213, 210, 201, 203, 144, 118, 212, 182, 81, 242, 167, 4, 43, + 241, 111, 76, 175, 137, 165, 179, 132, ], }; pub(crate) fn admit() -> Result<(), KarDecodeError> { diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu.rs index 32db9cd8..b9be3092 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu.rs @@ -90,10 +90,20 @@ fn gdn_stage_kernels_equal_the_originals_bit_for_bit() { vec![( index, (n * k).div_ceil(256) as u32, - vec![A::Address(hd(&weight)), A::I64(row_bytes as i64), A::I64((n * k) as i64), A::I64((k / 32) as i64), A::Address(hd(&out_new))], + vec![ + A::Address(hd(&weight)), + A::I64(row_bytes as i64), + A::I64((n * k) as i64), + A::I64((k / 32) as i64), + A::Address(hd(&out_new)), + ], )], ); - assert_eq!(download(&out_old, n * k * 2), download(&out_new, n * k * 2), "{format:?}: dequantized FP16 weights"); + assert_eq!( + download(&out_old, n * k * 2), + download(&out_new, n * k * 2), + "{format:?}: dequantized FP16 weights" + ); eprintln!("PREFILL-GDN dequant {format:?}: {} FP16 values equal", n * k); } @@ -114,18 +124,51 @@ fn gdn_stage_kernels_equal_the_originals_bit_for_bit() { let status_new = upload(&context, &[0u8; 64]); let word = |b: &DeviceBuffer<'_>, i: usize| hd(b).checked_subspan(64, i * 4, 4).expect("word"); let scan = |data: &DeviceBuffer<'_>, count: usize, slot: usize| { - (Kernel::FiniteF32, linear(count).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(data)), ffi::KernelArg::Pointer(word(&status_old, slot)), ffi::KernelArg::U32(count as u32)]) + ( + Kernel::FiniteF32, + linear(count).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(data)), + ffi::KernelArg::Pointer(word(&status_old, slot)), + ffi::KernelArg::U32(count as u32), + ], + ) }; old.run(vec![ - (Kernel::ConvTiled, [80, t.div_ceil(64) as u32, 1], [128, 1, 1], vec![ffi::KernelArg::Pointer(hd(&hist_d)), ffi::KernelArg::Pointer(hd(&qkv_d)), ffi::KernelArg::Pointer(hd(&w_d)), ffi::KernelArg::Pointer(hd(&h_old)), ffi::KernelArg::I64(t as i64)]), + ( + Kernel::ConvTiled, + [80, t.div_ceil(64) as u32, 1], + [128, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&hist_d)), + ffi::KernelArg::Pointer(hd(&qkv_d)), + ffi::KernelArg::Pointer(hd(&w_d)), + ffi::KernelArg::Pointer(hd(&h_old)), + ffi::KernelArg::I64(t as i64), + ], + ), scan(&qkv_d, t * 10240, 0), scan(&h_old, t * 10240, 1), ]); - run_stage(&context, stream, &stage, vec![( - crate::prefill_stage::GDN_CONV_TILED, - 40 * t.div_ceil(64) as u32, - vec![A::Address(hd(&hist_d)), A::Address(hd(&qkv_d)), A::Address(hd(&w_d)), A::Address(hd(&h_new)), A::I64(t as i64), A::Address(word(&status_new, 0)), A::Address(word(&status_new, 1))], - )]); + run_stage( + &context, + stream, + &stage, + vec![( + crate::prefill_stage::GDN_CONV_TILED, + 40 * t.div_ceil(64) as u32, + vec![ + A::Address(hd(&hist_d)), + A::Address(hd(&qkv_d)), + A::Address(hd(&w_d)), + A::Address(hd(&h_new)), + A::I64(t as i64), + A::Address(word(&status_new, 0)), + A::Address(word(&status_new, 1)), + ], + )], + ); assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: conv output"); assert_eq!(words(&status_old, 2), words(&status_new, 2), "case {case}: conv status words (qkv, conv)"); @@ -134,14 +177,33 @@ fn gdn_stage_kernels_equal_the_originals_bit_for_bit() { let status_l2_old = upload(&context, &[0u8; 64]); let status_l2_new = upload(&context, &[0u8; 64]); old.run(vec![ - (Kernel::L2, [32, t as u32, 1], [128, 1, 1], vec![ffi::KernelArg::Pointer(hd(&h_old)), ffi::KernelArg::F32(eps)]), - (Kernel::FiniteF32, linear(t * 10240).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(&h_old)), ffi::KernelArg::Pointer(hd(&status_l2_old)), ffi::KernelArg::U32((t * 10240) as u32)]), + ( + Kernel::L2, + [32, t as u32, 1], + [128, 1, 1], + vec![ffi::KernelArg::Pointer(hd(&h_old)), ffi::KernelArg::F32(eps)], + ), + ( + Kernel::FiniteF32, + linear(t * 10240).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&h_old)), + ffi::KernelArg::Pointer(hd(&status_l2_old)), + ffi::KernelArg::U32((t * 10240) as u32), + ], + ), ]); - run_stage(&context, stream, &stage, vec![( - crate::prefill_stage::GDN_L2, - (32 * t).div_ceil(2) as u32, - vec![A::Address(hd(&h_new)), A::F32(eps), A::I64(t as i64), A::Address(hd(&status_l2_new))], - )]); + run_stage( + &context, + stream, + &stage, + vec![( + crate::prefill_stage::GDN_L2, + (32 * t).div_ceil(2) as u32, + vec![A::Address(hd(&h_new)), A::F32(eps), A::I64(t as i64), A::Address(hd(&status_l2_new))], + )], + ); assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: L2 output"); // the original scans the whole row (including the V channels the convolution guard already covers) assert_eq!(words(&status_l2_old, 1), words(&status_l2_new, 1), "case {case}: L2 status"); @@ -161,31 +223,127 @@ fn gdn_stage_kernels_equal_the_originals_bit_for_bit() { let (so, sn) = (upload(&context, &[0u8; 64]), upload(&context, &[0u8; 64])); let wo = |i: usize| word(&so, i); old.run(vec![ - (Kernel::FiniteF32, linear(t * 6144).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(&y_old)), ffi::KernelArg::Pointer(wo(1)), ffi::KernelArg::U32((t * 6144) as u32)]), - (Kernel::OutNorm, [t as u32, 48, 1], [128, 1, 1], vec![ffi::KernelArg::Pointer(hd(&z_d)), ffi::KernelArg::Pointer(hd(&g_d)), ffi::KernelArg::F32(eps), ffi::KernelArg::Pointer(hd(&y_old)), ffi::KernelArg::Pointer(hd(&yh_old))]), - (Kernel::FiniteF32, linear(t * 6144).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(&y_old)), ffi::KernelArg::Pointer(wo(2)), ffi::KernelArg::U32((t * 6144) as u32)]), - (Kernel::FiniteF16, linear(t * 6144).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(&yh_old)), ffi::KernelArg::Pointer(wo(3)), ffi::KernelArg::U32((t * 6144) as u32)]), - (Kernel::FiniteF32, linear(t * 6144).unwrap().0, [256, 1, 1], vec![ffi::KernelArg::Pointer(hd(&z_d)), ffi::KernelArg::Pointer(wo(0)), ffi::KernelArg::U32((t * 6144) as u32)]), + ( + Kernel::FiniteF32, + linear(t * 6144).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&y_old)), + ffi::KernelArg::Pointer(wo(1)), + ffi::KernelArg::U32((t * 6144) as u32), + ], + ), + ( + Kernel::OutNorm, + [t as u32, 48, 1], + [128, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&z_d)), + ffi::KernelArg::Pointer(hd(&g_d)), + ffi::KernelArg::F32(eps), + ffi::KernelArg::Pointer(hd(&y_old)), + ffi::KernelArg::Pointer(hd(&yh_old)), + ], + ), + ( + Kernel::FiniteF32, + linear(t * 6144).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&y_old)), + ffi::KernelArg::Pointer(wo(2)), + ffi::KernelArg::U32((t * 6144) as u32), + ], + ), + ( + Kernel::FiniteF16, + linear(t * 6144).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&yh_old)), + ffi::KernelArg::Pointer(wo(3)), + ffi::KernelArg::U32((t * 6144) as u32), + ], + ), + ( + Kernel::FiniteF32, + linear(t * 6144).unwrap().0, + [256, 1, 1], + vec![ + ffi::KernelArg::Pointer(hd(&z_d)), + ffi::KernelArg::Pointer(wo(0)), + ffi::KernelArg::U32((t * 6144) as u32), + ], + ), ]); - run_stage(&context, stream, &stage, vec![( - crate::prefill_stage::GDN_OUT_NORM, - (48 * t).div_ceil(2) as u32, - vec![A::Address(hd(&z_d)), A::Address(hd(&g_d)), A::F32(eps), A::Address(hd(&y_new)), A::Address(hd(&yh_new)), A::I64(t as i64), A::Address(word(&sn, 0)), A::Address(word(&sn, 1)), A::Address(word(&sn, 2)), A::Address(word(&sn, 3))], - )]); + run_stage( + &context, + stream, + &stage, + vec![( + crate::prefill_stage::GDN_OUT_NORM, + (48 * t).div_ceil(2) as u32, + vec![ + A::Address(hd(&z_d)), + A::Address(hd(&g_d)), + A::F32(eps), + A::Address(hd(&y_new)), + A::Address(hd(&yh_new)), + A::I64(t as i64), + A::Address(word(&sn, 0)), + A::Address(word(&sn, 1)), + A::Address(word(&sn, 2)), + A::Address(word(&sn, 3)), + ], + )], + ); assert_eq!(download(&y_old, t * 6144 * 4), download(&y_new, t * 6144 * 4), "case {case}: y"); assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_new, t * 6144 * 2), "case {case}: y16"); assert_eq!(words(&so, 4), words(&sn, 4), "case {case}: out-norm status words (z, readout, y, y16)"); // row 2.4: the variant without the dead FP32 store writes the same y16 and status words and leaves y holding the readout - let (y_ns, yh_ns, sns) = (upload(&context, &f32_bytes(&oc)), upload(&context, &vec![0u8; t * 6144 * 2]), upload(&context, &[0u8; 64])); - run_stage(&context, stream, &stage, vec![( - crate::prefill_stage::GDN_OUT_NORM_Y16, - (48 * t).div_ceil(2) as u32, - vec![A::Address(hd(&z_d)), A::Address(hd(&g_d)), A::F32(eps), A::Address(hd(&y_ns)), A::Address(hd(&yh_ns)), A::I64(t as i64), A::Address(word(&sns, 0)), A::Address(word(&sns, 1)), A::Address(word(&sns, 2)), A::Address(word(&sns, 3))], - )]); - assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_ns, t * 6144 * 2), "case {case}: y16 of the no-store variant"); + let (y_ns, yh_ns, sns) = ( + upload(&context, &f32_bytes(&oc)), + upload(&context, &vec![0u8; t * 6144 * 2]), + upload(&context, &[0u8; 64]), + ); + run_stage( + &context, + stream, + &stage, + vec![( + crate::prefill_stage::GDN_OUT_NORM_Y16, + (48 * t).div_ceil(2) as u32, + vec![ + A::Address(hd(&z_d)), + A::Address(hd(&g_d)), + A::F32(eps), + A::Address(hd(&y_ns)), + A::Address(hd(&yh_ns)), + A::I64(t as i64), + A::Address(word(&sns, 0)), + A::Address(word(&sns, 1)), + A::Address(word(&sns, 2)), + A::Address(word(&sns, 3)), + ], + )], + ); + assert_eq!( + download(&yh_old, t * 6144 * 2), + download(&yh_ns, t * 6144 * 2), + "case {case}: y16 of the no-store variant" + ); assert_eq!(words(&so, 4), words(&sns, 4), "case {case}: status words of the no-store variant"); - assert_eq!(download(&y_ns, t * 6144 * 4), f32_bytes(&oc), "case {case}: the no-store variant leaves y untouched"); - eprintln!("PREFILL-GDN case {case}: conv/L2/out-norm equal; statuses conv {:?} l2 {:?} norm {:?}", words(&status_new, 2), words(&status_l2_new, 1), words(&sn, 4)); + assert_eq!( + download(&y_ns, t * 6144 * 4), + f32_bytes(&oc), + "case {case}: the no-store variant leaves y untouched" + ); + eprintln!( + "PREFILL-GDN case {case}: conv/L2/out-norm equal; statuses conv {:?} l2 {:?} norm {:?}", + words(&status_new, 2), + words(&status_l2_new, 1), + words(&sn, 4) + ); } } @@ -223,7 +381,8 @@ fn gdn_recurrence_equals_the_original_bit_for_bit() { upload(&context, &f32_bytes(&gate)), upload(&context, &f32_bytes(&beta)), ); - let (sout_o, sout_n) = (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); + let (sout_o, sout_n) = + (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); let (oc_o, oc_n) = (upload(&context, &vec![0u8; t * 6144 * 4]), upload(&context, &vec![0u8; t * 6144 * 4])); let (wo, wn) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); old.run(vec![( @@ -258,7 +417,11 @@ fn gdn_recurrence_equals_the_original_bit_for_bit() { let new_ms = started.elapsed().as_secs_f64() * 1e3; guard.finish().expect("finish"); assert_eq!(download(&oc_o, t * 6144 * 4), download(&oc_n, t * 6144 * 4), "case {case} (t={t}): readout"); - assert_eq!(download(&sout_o, state_len * 4), download(&sout_n, state_len * 4), "case {case} (t={t}): next state"); + assert_eq!( + download(&sout_o, state_len * 4), + download(&sout_n, state_len * 4), + "case {case} (t={t}): next state" + ); assert_eq!(words(&wo, 1), words(&wn, 1), "case {case}: state witness"); // timing of both, drained let started = std::time::Instant::now(); @@ -278,7 +441,11 @@ fn gdn_recurrence_equals_the_original_bit_for_bit() { ], )]); let old_ms = started.elapsed().as_secs_f64() * 1e3; - eprintln!("PREFILL-GDN rec case {case} t={t}: equal (state {} floats, witness {:?}); original {old_ms:.3} ms, new {new_ms:.3} ms", state_len, words(&wn, 1)); + eprintln!( + "PREFILL-GDN rec case {case} t={t}: equal (state {} floats, witness {:?}); original {old_ms:.3} ms, new {new_ms:.3} ms", + state_len, + words(&wn, 1) + ); } } @@ -304,7 +471,23 @@ fn gdn_recurrence_kh_equals_the_original_bit_for_bit() { let mut rng = Rng(0x0badc0ffee0ddf00); let state_len = 128 * 48 * 128; // (token count, variant): 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow - for (case, (t, variant)) in [(1usize, 0u8), (2, 0), (7, 0), (8, 0), (9, 0), (200, 0), (200, 1), (201, 2), (200, 3), (1500, 0), (2048, 0), (8192, 0)].into_iter().enumerate() { + for (case, (t, variant)) in [ + (1usize, 0u8), + (2, 0), + (7, 0), + (8, 0), + (9, 0), + (200, 0), + (200, 1), + (201, 2), + (200, 3), + (1500, 0), + (2048, 0), + (8192, 0), + ] + .into_iter() + .enumerate() + { let mut state: Vec = (0..state_len).map(|_| rng.f(0.05)).collect(); let mut h: Vec = (0..t * 10240).map(|_| rng.f(0.2)).collect(); let gate: Vec = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect(); @@ -325,7 +508,8 @@ fn gdn_recurrence_kh_equals_the_original_bit_for_bit() { upload(&context, &f32_bytes(&gate)), upload(&context, &f32_bytes(&beta)), ); - let (sout_o, sout_k) = (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); + let (sout_o, sout_k) = + (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4])); let (oc_o, oc_k) = (upload(&context, &vec![0u8; t * 6144 * 4]), upload(&context, &vec![0u8; t * 6144 * 4])); let (wo, wk) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); let old_launch = |sout: &DeviceBuffer<'_>, oc: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>| { @@ -364,8 +548,16 @@ fn gdn_recurrence_kh_equals_the_original_bit_for_bit() { context.driver.api.synchronize().expect("sync"); guard.finish().expect("finish"); // compare the bytes as words: a NaN payload is a value too - assert_eq!(download(&oc_o, t * 6144 * 4), download(&oc_k, t * 6144 * 4), "case {case} (t={t}, variant {variant}): readout"); - assert_eq!(download(&sout_o, state_len * 4), download(&sout_k, state_len * 4), "case {case} (t={t}, variant {variant}): next state"); + assert_eq!( + download(&oc_o, t * 6144 * 4), + download(&oc_k, t * 6144 * 4), + "case {case} (t={t}, variant {variant}): readout" + ); + assert_eq!( + download(&sout_o, state_len * 4), + download(&sout_k, state_len * 4), + "case {case} (t={t}, variant {variant}): next state" + ); assert_eq!(words(&wo, 1), words(&wk, 1), "case {case}: state witness"); let w = words(&wk, 1)[0]; if variant == 1 || variant == 2 { @@ -398,23 +590,27 @@ fn gdn_recurrence_kh_equals_the_original_bit_for_bit() { context.driver.api.synchronize().expect("sync"); let rec_ms = t2.elapsed().as_secs_f64() * 1e3 / reps as f64; guard.finish().expect("finish"); - eprintln!("PREFILL-GDN rec-kh timing t={t}: original gdn_rec_cols_pipe {old_ms:.3} ms, leleka_prefill_gdn_rec {rec_ms:.3} ms, kh {kh_ms:.3} ms per launch (mean of {reps}, warm)"); + eprintln!( + "PREFILL-GDN rec-kh timing t={t}: original gdn_rec_cols_pipe {old_ms:.3} ms, leleka_prefill_gdn_rec {rec_ms:.3} ms, kh {kh_ms:.3} ms per launch (mean of {reps}, warm)" + ); } - eprintln!("PREFILL-GDN rec-kh case {case} t={t} variant {variant}: readout, state and witness ({w}) equal the original"); + eprintln!( + "PREFILL-GDN rec-kh case {case} t={t} variant {variant}: readout, state and witness ({w}) equal the original" + ); } } #[path = "prefill_stage_gdn_gpu/impl_rng.rs"] mod impl_rng; #[allow(unused_imports)] -use impl_rng::f32_bytes; +use impl_rng::download; #[allow(unused_imports)] -use impl_rng::upload; +use impl_rng::f32_bytes; #[allow(unused_imports)] use impl_rng::hd; #[allow(unused_imports)] -use impl_rng::download; +use impl_rng::run_stage; +#[allow(unused_imports)] +use impl_rng::upload; #[allow(unused_imports)] use impl_rng::words; -#[allow(unused_imports)] -use impl_rng::run_stage; diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs index 96ec5a38..6de3b0bc 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/impl_rng.rs @@ -55,7 +55,12 @@ impl Old<'_> { guard.finish().expect("finish"); } } -pub(super) fn run_stage(context: &Context<'_>, stream: usize, module: &KernelModule, launches: Vec<(usize, u32, Vec)>) { +pub(super) fn run_stage( + context: &Context<'_>, + stream: usize, + module: &KernelModule, + launches: Vec<(usize, u32, Vec)>, +) { let guard = context.enter().expect("enter"); let mut keep = Vec::new(); for (index, grid, args) in launches { diff --git a/crates/cuda-driver/src/prefill_stage_gpu.rs b/crates/cuda-driver/src/prefill_stage_gpu.rs index 08cd3be8..8f10afcf 100644 --- a/crates/cuda-driver/src/prefill_stage_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gpu.rs @@ -120,7 +120,9 @@ fn staged_input_equals_the_per_token_kernels_bit_for_bit() { embedding.iter().for_each(|v| embedding_bytes.extend_from_slice(&v.to_le_bytes())); let index: Vec = (0..t).map(|_| (rng.next() % unique as u64) as u32).collect(); let mut cache = context.allocate(64 << 20).expect("cache"); - let mut prompt = context.original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly).expect("prompt device"); + let mut prompt = context + .original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly) + .expect("prompt device"); let mut workspace = context.native_batch_workspace().expect("workspace"); let mut arena = context.original_prefill_arena(options(capacity)).expect("arena"); let lease = arena.begin_rows(t).expect("rows"); diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu.rs index 2cd80f63..048e995f 100644 --- a/crates/cuda-driver/src/prefill_stage_gr_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu.rs @@ -7,51 +7,9 @@ use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule}; const ENABLE: &str = "LELEKA_PREFILL_STAGE_GPU"; struct Rng(u64); -impl Rng { - fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } -} - -fn f32_bytes(v: &[f32]) -> Vec { - let mut out = Vec::with_capacity(v.len() * 4); - v.iter().for_each(|x| out.extend_from_slice(&x.to_le_bytes())); - out -} -fn upload<'c>(context: &'c Context<'c>, bytes: &[u8]) -> DeviceBuffer<'c> { - let mut b = context.allocate(bytes.len().max(16)).expect("alloc"); - let mut padded = bytes.to_vec(); - padded.resize(b.len(), 0); - b.copy_from(&padded).expect("upload"); - b -} -fn h(b: &DeviceBuffer<'_>) -> BufferHandle { - b.handle.expect("handle") -} -fn download(b: &DeviceBuffer<'_>) -> Vec { - b.copy_to_owned(b.len()).expect("download") -} type Launch<'m> = (&'m KernelModule, usize, usize, u32, Vec); -/// Runs the launches in order on the workspace stream and drains. -fn run_all(context: &Context<'_>, workspace: &NativeBatchWorkspace<'_>, launches: Vec>) { - let blas = workspace.blas().expect("blas"); - let guard = context.enter().expect("enter"); - let mut keep = Vec::new(); - for (module, index, grid, block, args) in launches { - let mut args = KernelArguments::new(args); - module.launch(index, grid as u32, block, blas.stream(), &mut args).expect("launch"); - keep.push(args); - } - blas.synchronize().expect("sync"); - guard.finish().expect("finish"); - drop(keep); -} - #[test] #[ignore = "Root-only: needs a CUDA device"] fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { @@ -85,7 +43,8 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { _ => {} } let flags_len = t * 8 * 4; - let (rb, wb, gb, bob, injb) = (f32_bytes(&r), f32_bytes(&gamma), f32_bytes(&g), f32_bytes(&bo), f32_bytes(&inj)); + let (rb, wb, gb, bob, injb) = + (f32_bytes(&r), f32_bytes(&gamma), f32_bytes(&g), f32_bytes(&bo), f32_bytes(&inj)); let mk = |n: usize| upload(&context, &vec![0u8; n]); // ---- norm @@ -97,9 +56,48 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { &context, &workspace, vec![ - (&gr, 0, t * 4, 256, vec![A::Address(h(&r_old)), A::Address(h(&w)), A::F32(eps), A::Address(h(&rs_o)), A::Address(h(&xn_o)), A::NullAddress]), - (&gr, 5, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&r_old)), A::Address(h(&rs_o)), A::Address(h(&w)), A::Address(h(&fl_o)), A::I64(t as i64)]), - (&stage, 3, t * 4, 256, vec![A::Address(h(&r_new)), A::Address(h(&w)), A::F32(eps), A::Address(h(&rs_n)), A::Address(h(&xn_n)), A::NullAddress, A::Address(h(&fl_n))]), + ( + &gr, + 0, + t * 4, + 256, + vec![ + A::Address(h(&r_old)), + A::Address(h(&w)), + A::F32(eps), + A::Address(h(&rs_o)), + A::Address(h(&xn_o)), + A::NullAddress, + ], + ), + ( + &gr, + 5, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h(&r_old)), + A::Address(h(&rs_o)), + A::Address(h(&w)), + A::Address(h(&fl_o)), + A::I64(t as i64), + ], + ), + ( + &stage, + 3, + t * 4, + 256, + vec![ + A::Address(h(&r_new)), + A::Address(h(&w)), + A::F32(eps), + A::Address(h(&rs_n)), + A::Address(h(&xn_n)), + A::NullAddress, + A::Address(h(&fl_n)), + ], + ), ], ); assert_eq!(download(&rs_o)[..t * 16], download(&rs_n)[..t * 16], "case {case}: rs"); @@ -115,11 +113,69 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { &context, &workspace, vec![ - (&gr, 2, (t * 2560).div_ceil(256), 256, vec![A::Address(h(&r_old)), A::Address(h(&rs_o)), A::Address(h(&w)), A::Address(h(&g_dev)), A::Address(h(&mx_o)), A::Address(h(&m16_o)), A::I64(t as i64), A::Address(h(&mh_o)), A::NullAddress]), - (&gr, 7, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&r_old)), A::Address(h(&rs_o)), A::Address(h(&w)), A::Address(h(&g_dev)), A::Address(h(&fl2_o)), A::I64(t as i64)]), - (&gr, 4, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&g_dev)), A::Address(h(&fl2_o)), A::I64(10240), A::I64(t as i64), A::U32(3)]), - (&gr, 4, (t * 2560).div_ceil(256), 256, vec![A::Address(h(&mx_o)), A::Address(h(&fl2_o)), A::I64(2560), A::I64(t as i64), A::U32(5)]), - (&stage, 4, (t * 2560).div_ceil(256), 256, vec![A::Address(h(&r_new)), A::Address(h(&rs_n)), A::Address(h(&w)), A::Address(h(&g_dev)), A::Address(h(&mx_n)), A::Address(h(&m16_n)), A::I64(t as i64), A::Address(h(&mh_n)), A::NullAddress, A::Address(h(&fl2_n))]), + ( + &gr, + 2, + (t * 2560).div_ceil(256), + 256, + vec![ + A::Address(h(&r_old)), + A::Address(h(&rs_o)), + A::Address(h(&w)), + A::Address(h(&g_dev)), + A::Address(h(&mx_o)), + A::Address(h(&m16_o)), + A::I64(t as i64), + A::Address(h(&mh_o)), + A::NullAddress, + ], + ), + ( + &gr, + 7, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h(&r_old)), + A::Address(h(&rs_o)), + A::Address(h(&w)), + A::Address(h(&g_dev)), + A::Address(h(&fl2_o)), + A::I64(t as i64), + ], + ), + ( + &gr, + 4, + (t * 10240).div_ceil(256), + 256, + vec![A::Address(h(&g_dev)), A::Address(h(&fl2_o)), A::I64(10240), A::I64(t as i64), A::U32(3)], + ), + ( + &gr, + 4, + (t * 2560).div_ceil(256), + 256, + vec![A::Address(h(&mx_o)), A::Address(h(&fl2_o)), A::I64(2560), A::I64(t as i64), A::U32(5)], + ), + ( + &stage, + 4, + (t * 2560).div_ceil(256), + 256, + vec![ + A::Address(h(&r_new)), + A::Address(h(&rs_n)), + A::Address(h(&w)), + A::Address(h(&g_dev)), + A::Address(h(&mx_n)), + A::Address(h(&m16_n)), + A::I64(t as i64), + A::Address(h(&mh_n)), + A::NullAddress, + A::Address(h(&fl2_n)), + ], + ), ], ); assert_eq!(download(&mx_o)[..t * 10240], download(&mx_n)[..t * 10240], "case {case}: mixed"); @@ -136,10 +192,61 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { &context, &workspace, vec![ - (&gr, 8, t * 4, 256, vec![A::Address(h(&rw_o)), A::Address(h(&bo_d)), A::Address(h(&inj_d)), A::I64(4), A::Address(h(&w)), A::F32(eps), A::Address(h(&rs2_o)), A::Address(h(&xn2_o)), A::NullAddress]), - (&gr, 4, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&rw_o)), A::Address(h(&fl3_o)), A::I64(10240), A::I64(t as i64), A::U32(7)]), - (&gr, 5, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&rw_o)), A::Address(h(&rs2_o)), A::Address(h(&w)), A::Address(h(&fl3_o)), A::I64(t as i64)]), - (&stage, 5, t * 4, 256, vec![A::Address(h(&rw_n)), A::Address(h(&bo_d)), A::Address(h(&inj_d)), A::I64(4), A::Address(h(&w)), A::F32(eps), A::Address(h(&rs2_n)), A::Address(h(&xn2_n)), A::NullAddress, A::Address(h(&fl3_n))]), + ( + &gr, + 8, + t * 4, + 256, + vec![ + A::Address(h(&rw_o)), + A::Address(h(&bo_d)), + A::Address(h(&inj_d)), + A::I64(4), + A::Address(h(&w)), + A::F32(eps), + A::Address(h(&rs2_o)), + A::Address(h(&xn2_o)), + A::NullAddress, + ], + ), + ( + &gr, + 4, + (t * 10240).div_ceil(256), + 256, + vec![A::Address(h(&rw_o)), A::Address(h(&fl3_o)), A::I64(10240), A::I64(t as i64), A::U32(7)], + ), + ( + &gr, + 5, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h(&rw_o)), + A::Address(h(&rs2_o)), + A::Address(h(&w)), + A::Address(h(&fl3_o)), + A::I64(t as i64), + ], + ), + ( + &stage, + 5, + t * 4, + 256, + vec![ + A::Address(h(&rw_n)), + A::Address(h(&bo_d)), + A::Address(h(&inj_d)), + A::I64(4), + A::Address(h(&w)), + A::F32(eps), + A::Address(h(&rs2_n)), + A::Address(h(&xn2_n)), + A::NullAddress, + A::Address(h(&fl3_n)), + ], + ), ], ); assert_eq!(download(&rw_o)[..t * 40960], download(&rw_n)[..t * 40960], "case {case}: R after fused write"); @@ -154,9 +261,40 @@ fn gr_fused_guards_equal_the_separate_guard_kernels_bit_for_bit() { &context, &workspace, vec![ - (&gr, 3, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&rp_o)), A::Address(h(&bo_d)), A::Address(h(&inj_d)), A::I64(4), A::I64(t as i64)]), - (&gr, 4, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&rp_o)), A::Address(h(&fl4_o)), A::I64(10240), A::I64(t as i64), A::U32(7)]), - (&stage, 6, (t * 10240).div_ceil(256), 256, vec![A::Address(h(&rp_n)), A::Address(h(&bo_d)), A::Address(h(&inj_d)), A::I64(4), A::I64(t as i64), A::Address(h(&fl4_n))]), + ( + &gr, + 3, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h(&rp_o)), + A::Address(h(&bo_d)), + A::Address(h(&inj_d)), + A::I64(4), + A::I64(t as i64), + ], + ), + ( + &gr, + 4, + (t * 10240).div_ceil(256), + 256, + vec![A::Address(h(&rp_o)), A::Address(h(&fl4_o)), A::I64(10240), A::I64(t as i64), A::U32(7)], + ), + ( + &stage, + 6, + (t * 10240).div_ceil(256), + 256, + vec![ + A::Address(h(&rp_n)), + A::Address(h(&bo_d)), + A::Address(h(&inj_d)), + A::I64(4), + A::I64(t as i64), + A::Address(h(&fl4_n)), + ], + ), ], ); assert_eq!(download(&rp_o)[..t * 40960], download(&rp_n)[..t * 40960], "case {case}: R after write"); @@ -186,11 +324,26 @@ fn gr_kernels_run_near_their_traffic_floor_at_chunk_size() { guard.finish().expect("finish"); let t = 8192usize; let mut rng = Rng(0x1234_5678_9abc_def0); - let rnd = |rng: &mut Rng, n: usize, scale: f32| -> Vec { (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() }; - let (r, gamma, g, bo, inj) = (rnd(&mut rng, t * 10240, 3.0), rnd(&mut rng, 10240, 2.0), rnd(&mut rng, t * 10240, 4.0), rnd(&mut rng, t * 2560, 1.0), rnd(&mut rng, t * 4, 2.0)); + let rnd = |rng: &mut Rng, n: usize, scale: f32| -> Vec { + (0..n).map(|_| ((rng.next() % 20001) as f32 / 10000.0 - 1.0) * scale).collect() + }; + let (r, gamma, g, bo, inj) = ( + rnd(&mut rng, t * 10240, 3.0), + rnd(&mut rng, 10240, 2.0), + rnd(&mut rng, t * 10240, 4.0), + rnd(&mut rng, t * 2560, 1.0), + rnd(&mut rng, t * 4, 2.0), + ); let mk = |n: usize| upload(&context, &vec![0u8; n]); - let (r_d, w_d, g_d, bo_d, inj_d) = (upload(&context, &f32_bytes(&r)), upload(&context, &f32_bytes(&gamma)), upload(&context, &f32_bytes(&g)), upload(&context, &f32_bytes(&bo)), upload(&context, &f32_bytes(&inj))); - let (rs, xn, mx, m16, mh, fl) = (mk(t * 16), mk(t * 20480), mk(t * 10240), mk(t * 5120), mk(t * 5120), mk(t * 8 * 4)); + let (r_d, w_d, g_d, bo_d, inj_d) = ( + upload(&context, &f32_bytes(&r)), + upload(&context, &f32_bytes(&gamma)), + upload(&context, &f32_bytes(&g)), + upload(&context, &f32_bytes(&bo)), + upload(&context, &f32_bytes(&inj)), + ); + let (rs, xn, mx, m16, mh, fl) = + (mk(t * 16), mk(t * 20480), mk(t * 10240), mk(t * 5120), mk(t * 5120), mk(t * 8 * 4)); let eps = 1e-6f32; let blas = workspace.blas().expect("blas"); let time = |what: &str, bytes: f64, launch: &mut dyn FnMut()| { @@ -204,7 +357,11 @@ fn gr_kernels_run_near_their_traffic_floor_at_chunk_size() { blas.synchronize().expect("sync"); let us = started.elapsed().as_secs_f64() * 1e6 / 20.0; guard.finish().expect("finish"); - eprintln!("PREFILL-GR-TRAFFIC {what}: {us:.0} us per call, {:.0} MB moved, {:.2} TB/s", bytes / 1e6, bytes / us / 1e6); + eprintln!( + "PREFILL-GR-TRAFFIC {what}: {us:.0} us per call, {:.0} MB moved, {:.2} TB/s", + bytes / 1e6, + bytes / us / 1e6 + ); }; let r_bytes = (t * 40960) as f64; let mut keep = Vec::new(); @@ -214,12 +371,75 @@ fn gr_kernels_run_near_their_traffic_floor_at_chunk_size() { keep.push(a); }; time("norm_rs (R in, xn16 out)", r_bytes + (t * 20480) as f64, &mut || { - run(3, t * 4, vec![A::Address(h(&r_d)), A::Address(h(&w_d)), A::F32(eps), A::Address(h(&rs)), A::Address(h(&xn)), A::NullAddress, A::Address(h(&fl))]) - }); - time("mix_r (R, g in; mixed f32 + bf16 + f16 out)", 2.0 * r_bytes + (t * (10240 + 5120 + 5120)) as f64, &mut || { - run(4, (t * 2560).div_ceil(256), vec![A::Address(h(&r_d)), A::Address(h(&rs)), A::Address(h(&w_d)), A::Address(h(&g_d)), A::Address(h(&mx)), A::Address(h(&m16)), A::I64(t as i64), A::Address(h(&mh)), A::NullAddress, A::Address(h(&fl))]) - }); - time("write_norm_rs (R in+out, bo in, xn16 out)", 2.0 * r_bytes + (t * 10240) as f64 + (t * 20480) as f64, &mut || { - run(5, t * 4, vec![A::Address(h(&r_d)), A::Address(h(&bo_d)), A::Address(h(&inj_d)), A::I64(4), A::Address(h(&w_d)), A::F32(eps), A::Address(h(&rs)), A::Address(h(&xn)), A::NullAddress, A::Address(h(&fl))]) + run( + 3, + t * 4, + vec![ + A::Address(h(&r_d)), + A::Address(h(&w_d)), + A::F32(eps), + A::Address(h(&rs)), + A::Address(h(&xn)), + A::NullAddress, + A::Address(h(&fl)), + ], + ) }); + time( + "mix_r (R, g in; mixed f32 + bf16 + f16 out)", + 2.0 * r_bytes + (t * (10240 + 5120 + 5120)) as f64, + &mut || { + run( + 4, + (t * 2560).div_ceil(256), + vec![ + A::Address(h(&r_d)), + A::Address(h(&rs)), + A::Address(h(&w_d)), + A::Address(h(&g_d)), + A::Address(h(&mx)), + A::Address(h(&m16)), + A::I64(t as i64), + A::Address(h(&mh)), + A::NullAddress, + A::Address(h(&fl)), + ], + ) + }, + ); + time( + "write_norm_rs (R in+out, bo in, xn16 out)", + 2.0 * r_bytes + (t * 10240) as f64 + (t * 20480) as f64, + &mut || { + run( + 5, + t * 4, + vec![ + A::Address(h(&r_d)), + A::Address(h(&bo_d)), + A::Address(h(&inj_d)), + A::I64(4), + A::Address(h(&w_d)), + A::F32(eps), + A::Address(h(&rs)), + A::Address(h(&xn)), + A::NullAddress, + A::Address(h(&fl)), + ], + ) + }, + ); } + +#[path = "prefill_stage_gr_gpu/impl_rng.rs"] +mod impl_rng; +#[allow(unused_imports)] +use impl_rng::download; +#[allow(unused_imports)] +use impl_rng::f32_bytes; +#[allow(unused_imports)] +use impl_rng::h; +#[allow(unused_imports)] +use impl_rng::run_all; +#[allow(unused_imports)] +use impl_rng::upload; diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu/impl_rng.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu/impl_rng.rs new file mode 100644 index 00000000..f8db8332 --- /dev/null +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu/impl_rng.rs @@ -0,0 +1,47 @@ +//! Moved out of the parent module by STRA-338: impl Rng, fn f32_bytes, fn upload, fn h, fn download, fn run_all. + +#[allow(unused_imports)] +use super::*; + +impl Rng { + pub(super) fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } +} + +pub(super) fn f32_bytes(v: &[f32]) -> Vec { + let mut out = Vec::with_capacity(v.len() * 4); + v.iter().for_each(|x| out.extend_from_slice(&x.to_le_bytes())); + out +} +pub(super) fn upload<'c>(context: &'c Context<'c>, bytes: &[u8]) -> DeviceBuffer<'c> { + let mut b = context.allocate(bytes.len().max(16)).expect("alloc"); + let mut padded = bytes.to_vec(); + padded.resize(b.len(), 0); + b.copy_from(&padded).expect("upload"); + b +} +pub(super) fn h(b: &DeviceBuffer<'_>) -> BufferHandle { + b.handle.expect("handle") +} +pub(super) fn download(b: &DeviceBuffer<'_>) -> Vec { + b.copy_to_owned(b.len()).expect("download") +} + +/// Runs the launches in order on the workspace stream and drains. +pub(super) fn run_all(context: &Context<'_>, workspace: &NativeBatchWorkspace<'_>, launches: Vec>) { + let blas = workspace.blas().expect("blas"); + let guard = context.enter().expect("enter"); + let mut keep = Vec::new(); + for (module, index, grid, block, args) in launches { + let mut args = KernelArguments::new(args); + module.launch(index, grid as u32, block, blas.stream(), &mut args).expect("launch"); + keep.push(args); + } + blas.synchronize().expect("sync"); + guard.finish().expect("finish"); + drop(keep); +} diff --git a/crates/cuda-driver/src/q6_k_shape_fn.rs b/crates/cuda-driver/src/q6_k_shape_fn.rs index b125ac9c..3e8ff324 100644 --- a/crates/cuda-driver/src/q6_k_shape_fn.rs +++ b/crates/cuda-driver/src/q6_k_shape_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result { if rows == 0 || columns == 0 || !columns.is_multiple_of(256) { return Err(Error::InvalidQ6KProjectionShape); @@ -14,15 +13,11 @@ pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result { return Err(Error::InvalidQ6KProjectionShape); } let checked_bytes = |elements: usize, width: usize| -> Result { - let bytes = elements - .checked_mul(width) - .ok_or(Error::InvalidQ6KProjectionShape)?; + let bytes = elements.checked_mul(width).ok_or(Error::InvalidQ6KProjectionShape)?; valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; Ok(bytes) }; - let weight_blocks = rows - .checked_mul(columns / 256) - .ok_or(Error::InvalidQ6KProjectionShape)?; + let weight_blocks = rows.checked_mul(columns / 256).ok_or(Error::InvalidQ6KProjectionShape)?; let weight_bytes = checked_bytes(weight_blocks, 210)?; let activation_bytes = checked_bytes(columns, 4)?; let output_bytes = checked_bytes(rows, 4)?; @@ -44,17 +39,14 @@ pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result { rows: rows_abi, columns: columns_abi, quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ6KProjectionShape)?, - projection_grid: u32::try_from(projection_ctas) - .map_err(|_| Error::InvalidQ6KProjectionShape)?, + projection_grid: u32::try_from(projection_ctas).map_err(|_| Error::InvalidQ6KProjectionShape)?, }) } pub(super) fn matvec_shape(rows: usize, columns: usize) -> Result { let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?; let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?; let bytes = |elements: Option| -> Result { - let bytes = elements - .and_then(|v| v.checked_mul(4)) - .ok_or(Error::InvalidMatvecShape)?; + let bytes = elements.and_then(|v| v.checked_mul(4)).ok_or(Error::InvalidMatvecShape)?; valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?; Ok(bytes) }; @@ -99,15 +91,9 @@ pub(super) fn vector_shape(bytes: usize) -> Result<(u32, u32)> { return Err(Error::InvalidVectorShape); } let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?; - let grid = u64::from(count) - .checked_add(127) - .ok_or(Error::InvalidVectorShape)? - / 128; + let grid = u64::from(count).checked_add(127).ok_or(Error::InvalidVectorShape)? / 128; if grid == 0 || grid > i32::MAX as u64 { return Err(Error::InvalidVectorShape); } - Ok(( - count, - u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?, - )) + Ok((count, u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?)) } diff --git a/crates/cuda-driver/src/q6_layer_preview.rs b/crates/cuda-driver/src/q6_layer_preview.rs index b2936651..25c92978 100644 --- a/crates/cuda-driver/src/q6_layer_preview.rs +++ b/crates/cuda-driver/src/q6_layer_preview.rs @@ -6,25 +6,14 @@ fn shape(rows: usize, columns: usize, tokens: usize) -> Result<(Q6KShape, usize, } let s = q6_k_shape(rows, columns)?; let mul = |bytes: usize| -> Result { - let bytes = bytes - .checked_mul(tokens) - .ok_or(Error::InvalidQ6KProjectionShape)?; + let bytes = bytes.checked_mul(tokens).ok_or(Error::InvalidQ6KProjectionShape)?; valid_size(bytes).map_err(|_| Error::InvalidQ6KProjectionShape)?; Ok(bytes) }; - let (x, q, y) = ( - mul(s.activation_bytes)?, - mul(s.scratch_bytes)?, - mul(s.output_bytes)?, - ); + let (x, q, y) = (mul(s.activation_bytes)?, mul(s.scratch_bytes)?, mul(s.output_bytes)?); Ok((s, x, q, y)) } -fn ranges( - s: &Q6KShape, - qbytes: usize, - ybytes: usize, - handles: [ffi::BufferHandle; 3], -) -> Result<()> { +fn ranges(s: &Q6KShape, qbytes: usize, ybytes: usize, handles: [ffi::BufferHandle; 3]) -> Result<()> { let [w, q, y] = handles; w.validate_projection_extent(s.weight_bytes, 2)?; q.validate_projection_extent(qbytes, 4)?; @@ -70,14 +59,8 @@ mod installed { }; let resolved = (|| { Ok([ - context - .driver - .api - .fixed_function(module, FixedOperation::Q6KQuantize)?, - context - .driver - .api - .fixed_function(module, FixedOperation::Q6KProject)?, + context.driver.api.fixed_function(module, FixedOperation::Q6KQuantize)?, + context.driver.api.fixed_function(module, FixedOperation::Q6KProject)?, ]) })(); let kernels = match resolved { @@ -155,12 +138,8 @@ mod installed { s.columns, ); let guard = context.enter()?; - let launched = context.driver.api.quantize_q6_batch( - self.kernels[0], - s.quant_grid, - tokens as u32, - &mut args, - ); + let launched = + context.driver.api.quantize_q6_batch(self.kernels[0], s.quant_grid, tokens as u32, &mut args); self.quant_attempts.set(self.quant_attempts.get() + 1); context.complete_launch(launched, args, guard)?; let mut bytes = [0; 4]; @@ -185,19 +164,9 @@ mod installed { } return combine(Err(e), scratch.release()); } - Ok(Prepared { - scratch, - rows, - columns, - tokens, - }) + Ok(Prepared { scratch, rows, columns, tokens }) } - pub fn project( - &self, - w: &DeviceBuffer<'_>, - q: &Prepared<'_>, - y: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn project(&self, w: &DeviceBuffer<'_>, q: &Prepared<'_>, y: &mut DeviceBuffer<'_>) -> Result<()> { self.live()?; let context = self.context; if !std::ptr::eq(context, w.context) @@ -216,12 +185,8 @@ mod installed { ranges(&s, qbytes, ybytes, [wh, qh, yh])?; let mut args = ffi::Q6ProjectionArguments::new(wh, qh, yh, s.rows, s.columns); let guard = context.enter()?; - let launched = context.driver.api.project_q6_batch( - self.kernels[1], - s.projection_grid, - q.tokens as u32, - &mut args, - ); + let launched = + context.driver.api.project_q6_batch(self.kernels[1], s.projection_grid, q.tokens as u32, &mut args); self.project_attempts.set(self.project_attempts.get() + 1); context.complete_launch(launched, args, guard) } diff --git a/crates/cuda-driver/src/qsa_cluster.rs b/crates/cuda-driver/src/qsa_cluster.rs index 664f1ca6..0ea9ba43 100644 --- a/crates/cuda-driver/src/qsa_cluster.rs +++ b/crates/cuda-driver/src/qsa_cluster.rs @@ -31,12 +31,12 @@ pub fn requested(default_on: bool) -> bool { /// Frozen by `scripts/gpu-bringup/reseal_own.py` after `compile_assets.py` (extra-seal-plan.json, group qsa-cluster). pub(crate) const PIN: PtxPin = PtxPin { source_sha256: [ - 147, 254, 188, 163, 187, 132, 34, 2, 87, 206, 153, 133, 97, 24, 148, 223, 219, 213, 206, - 202, 11, 223, 165, 148, 222, 70, 39, 17, 38, 243, 17, 103, + 147, 254, 188, 163, 187, 132, 34, 2, 87, 206, 153, 133, 97, 24, 148, 223, 219, 213, 206, 202, 11, 223, 165, + 148, 222, 70, 39, 17, 38, 243, 17, 103, ], ptx_sha256: [ - 60, 132, 16, 98, 99, 168, 233, 124, 37, 148, 140, 163, 88, 27, 187, 220, 19, 80, 17, 95, - 215, 11, 103, 205, 137, 16, 98, 13, 232, 205, 25, 25, + 60, 132, 16, 98, 99, 168, 233, 124, 37, 148, 140, 163, 88, 27, 187, 220, 19, 80, 17, 95, 215, 11, 103, 205, + 137, 16, 98, 13, 232, 205, 25, 25, ], }; pub(crate) fn admit() -> Result<(), KarDecodeError> { @@ -47,10 +47,16 @@ pub(crate) fn admit() -> Result<(), KarDecodeError> { mod tests { #[test] fn the_asset_is_the_sealed_one_and_the_dynamic_shared_memory_holds_one_eighth_of_the_keys() { - assert!(super::admit().is_ok(), "qsa_cluster.ptx does not match its pin (reseal with scripts/gpu-bringup/reseal_own.py)"); + assert!( + super::admit().is_ok(), + "qsa_cluster.ptx does not match its pin (reseal with scripts/gpu-bringup/reseal_own.py)" + ); let text = std::str::from_utf8(&super::PTX[..super::PTX.len() - 1]).expect("PTX is text"); assert!(text.contains(".visible .entry leleka_qsa_topk_cluster(")); - assert!(text.contains("barrier.cluster.arrive") && text.contains("mapa.u64"), "the kernel must use cluster barriers and distributed shared memory"); + assert!( + text.contains("barrier.cluster.arrive") && text.contains("mapa.u64"), + "the kernel must use cluster barriers and distributed shared memory" + ); // 65,538 blocks of a 262,144-cell context: 8,193 keys of 4 bytes per CTA assert_eq!(super::dynamic_smem(65_538), 8_193 * 4); assert_eq!(super::dynamic_smem(8), 4); diff --git a/crates/cuda-driver/src/qsa_index_ffi.rs b/crates/cuda-driver/src/qsa_index_ffi.rs index 08a3711b..1a7ba05a 100644 --- a/crates/cuda-driver/src/qsa_index_ffi.rs +++ b/crates/cuda-driver/src/qsa_index_ffi.rs @@ -1,23 +1,46 @@ //! Private fixed Original QSA entries. No stream/Blas ownership or public grid API. -use crate::{Error,Result,combine,ffi::BufferHandle}; +use crate::{Error, Result, combine, ffi::BufferHandle}; use std::ffi::CStr; -pub(crate) enum Arg { Address(BufferHandle),I32(i32),I64(i64),U32(u32),F32(f32) } -enum Value { Address(u64),I32(i32),I64(i64),U32(u32),F32(f32) } -pub(crate) struct Arguments { values:Box<[Value]>, pointers:Vec<*mut std::ffi::c_void> } +pub(crate) enum Arg { + Address(BufferHandle), + I32(i32), + I64(i64), + U32(u32), + F32(f32), +} +enum Value { + Address(u64), + I32(i32), + I64(i64), + U32(u32), + F32(f32), +} +pub(crate) struct Arguments { + values: Box<[Value]>, + pointers: Vec<*mut std::ffi::c_void>, +} impl Arguments { /// The arguments of `shape` followed, where its kernel takes them, by the serving context's RoPE constants. - pub(crate) fn for_launch(shape:Launch,mut values:Vec)->Result { + pub(crate) fn for_launch(shape: Launch, mut values: Vec) -> Result { if shape.carries_rope() { - let serving=crate::serving_context::serving_context(); - values.extend(rope_tail(rope_abi()?,serving.rope_is_scaled(),serving.rope_args)?); + let serving = crate::serving_context::serving_context(); + values.extend(rope_tail(rope_abi()?, serving.rope_is_scaled(), serving.rope_args)?); } Self::new(values) } - pub(crate) fn new(values:Vec)->Result { - let mut pointers=Vec::new();pointers.try_reserve_exact(values.len()).map_err(|_|Error::HostAllocation)?; - let mut stored=Vec::new();stored.try_reserve_exact(values.len()).map_err(|_|Error::HostAllocation)?; - stored.extend(values.into_iter().map(|a|match a{Arg::Address(h)=>Value::Address(h.qwen_address()),Arg::I32(v)=>Value::I32(v),Arg::I64(v)=>Value::I64(v),Arg::U32(v)=>Value::U32(v),Arg::F32(v)=>Value::F32(v)})); - Ok(Self{values:stored.into_boxed_slice(),pointers}) + pub(crate) fn new(values: Vec) -> Result { + let mut pointers = Vec::new(); + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + let mut stored = Vec::new(); + stored.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + stored.extend(values.into_iter().map(|a| match a { + Arg::Address(h) => Value::Address(h.qwen_address()), + Arg::I32(v) => Value::I32(v), + Arg::I64(v) => Value::I64(v), + Arg::U32(v) => Value::U32(v), + Arg::F32(v) => Value::F32(v), + })); + Ok(Self { values: stored.into_boxed_slice(), pointers }) } } // ---- ROPE-ARGS ABI 1 ------------------------------------------------------------------------------------- @@ -63,7 +86,11 @@ pub(crate) fn rope_abi() -> Result { } /// The trailing arguments for `abi` and the configured serving RoPE, or the refusal. -pub(crate) fn rope_tail(abi: RopeAbi, scaled: bool, r: leleka_context::rope_scaling::RopeKernelArgs) -> Result> { +pub(crate) fn rope_tail( + abi: RopeAbi, + scaled: bool, + r: leleka_context::rope_scaling::RopeKernelArgs, +) -> Result> { match (abi, scaled) { (RopeAbi::Frozen, false) => Ok(Vec::new()), (RopeAbi::Frozen, true) => Err(Error::UnsupportedQwenOperation), @@ -77,115 +104,148 @@ pub(crate) fn rope_tail(abi: RopeAbi, scaled: bool, r: leleka_context::rope_scal } } -#[derive(Clone,Copy)] -pub(crate) enum Entry {First,Blocks,Tail,Rms, Rope,Split,Scan,ScoreScan,Round,Tc,ScoreTail,Topk,DecodeAppend,DecodeScores,DecodeRms,DecodeRope} +#[derive(Clone, Copy)] +pub(crate) enum Entry { + First, + Blocks, + Tail, + Rms, + Rope, + Split, + Scan, + ScoreScan, + Round, + Tc, + ScoreTail, + Topk, + DecodeAppend, + DecodeScores, + DecodeRms, + DecodeRope, +} impl Entry { - fn name(self)-> &'static CStr {match self { - Self::First=>c"qsa_append_first",Self::Blocks=>c"qsa_append_blocks",Self::Tail=>c"qsa_append_tail", - Self::Rms=>c"qsa_rms_rows",Self::Rope=>c"qsa_rope_rows",Self::Split=>c"qsa_split_q", - Self::Round=>c"qsa_round_index_rows",Self::Scan=>c"qsa_index_scan",Self::ScoreScan=>c"qsa_score_scan",Self::Tc=>c"qsa_score_tc", - Self::ScoreTail=>c"qsa_score_tail",Self::Topk=>c"qsa_topk_ref",Self::DecodeAppend=>c"qsa_decode_append",Self::DecodeScores=>c"qsa_decode_scores",Self::DecodeRms=>c"qsa_decode_rms",Self::DecodeRope=>c"qsa_decode_rope"}} - fn index(self)->usize {self as usize} + fn name(self) -> &'static CStr { + match self { + Self::First => c"qsa_append_first", + Self::Blocks => c"qsa_append_blocks", + Self::Tail => c"qsa_append_tail", + Self::Rms => c"qsa_rms_rows", + Self::Rope => c"qsa_rope_rows", + Self::Split => c"qsa_split_q", + Self::Round => c"qsa_round_index_rows", + Self::Scan => c"qsa_index_scan", + Self::ScoreScan => c"qsa_score_scan", + Self::Tc => c"qsa_score_tc", + Self::ScoreTail => c"qsa_score_tail", + Self::Topk => c"qsa_topk_ref", + Self::DecodeAppend => c"qsa_decode_append", + Self::DecodeScores => c"qsa_decode_scores", + Self::DecodeRms => c"qsa_decode_rms", + Self::DecodeRope => c"qsa_decode_rope", + } + } + fn index(self) -> usize { + self as usize + } +} +#[derive(Clone, Copy)] +pub(crate) enum Launch { + First, + Blocks(u32), + Tail, + Rms(u32), + Rope(u32), + Split(u32), + Scan(u32), + ScoreScan(u32), + Round(u32), + Tc { t: u32, reach: u32 }, + ScoreTail(u32), + Topk(u32), + DecodeAppend, + DecodeScores, + DecodeRms(u32), + DecodeRope(u32), } -#[derive(Clone,Copy)] -pub(crate) enum Launch { First,Blocks(u32),Tail,Rms(u32),Rope(u32),Split(u32),Scan(u32),ScoreScan(u32),Round(u32),Tc{t:u32,reach:u32},ScoreTail(u32),Topk(u32),DecodeAppend,DecodeScores,DecodeRms(u32),DecodeRope(u32) } impl Launch { /// The launches whose kernels carry the ROPE-ARGS trailing arguments. fn carries_rope(self) -> bool { matches!(self, Self::First | Self::Blocks(_) | Self::Rope(_) | Self::DecodeAppend | Self::DecodeRope(_)) } - fn shape(self)->Result<(Entry,u32,u32,u32,u32)> { - let (entry,x,y,threads,shared)=match self { - Self::First=>(Entry::First,1,1,256,0),Self::Blocks(n)=>(Entry::Blocks,n,1,256,0),Self::Tail=>(Entry::Tail,3,1,128,0), - Self::Rms(n)=>(Entry::Rms,n,1,256,0),Self::Rope(n)=>(Entry::Rope,n,1,32,0),Self::Split(n)=>(Entry::Split,n.div_ceil(256),1,256,0), - Self::Round(n)=>(Entry::Round,n.div_ceil(256),1,256,0),Self::Scan(n)=>(Entry::Scan,n.div_ceil(256),1,256,0),Self::ScoreScan(n)=>(Entry::ScoreScan,n.div_ceil(256),1,256,0), - Self::Tc{t,reach}=> {if !(1..=256).contains(&t)||reach==0||reach as usize>crate::serving_context::geometry().max_blocks(){return Err(Error::InvalidQwenShape);} (Entry::Tc,reach.div_ceil(128),t.div_ceil(16),128,49920)}, - Self::ScoreTail(t)=>(Entry::ScoreTail,t,1,32,0),Self::Topk(t)=>(Entry::Topk,t,1,256,0), - Self::DecodeRms(n)=>{if ![2,4,24].contains(&n){return Err(Error::InvalidQwenShape);}(Entry::DecodeRms,n,1,256,0)}, - Self::DecodeRope(n)=>{if ![2,4,24].contains(&n){return Err(Error::InvalidQwenShape);}(Entry::DecodeRope,1,n,128,0)}, - Self::DecodeAppend=>(Entry::DecodeAppend,1,1,256,0),Self::DecodeScores=>(Entry::DecodeScores,256,1,256,0), - };if x==0||y==0{return Err(Error::InvalidQwenShape);}Ok((entry,x,y,threads,shared)) + fn shape(self) -> Result<(Entry, u32, u32, u32, u32)> { + let (entry, x, y, threads, shared) = match self { + Self::First => (Entry::First, 1, 1, 256, 0), + Self::Blocks(n) => (Entry::Blocks, n, 1, 256, 0), + Self::Tail => (Entry::Tail, 3, 1, 128, 0), + Self::Rms(n) => (Entry::Rms, n, 1, 256, 0), + Self::Rope(n) => (Entry::Rope, n, 1, 32, 0), + Self::Split(n) => (Entry::Split, n.div_ceil(256), 1, 256, 0), + Self::Round(n) => (Entry::Round, n.div_ceil(256), 1, 256, 0), + Self::Scan(n) => (Entry::Scan, n.div_ceil(256), 1, 256, 0), + Self::ScoreScan(n) => (Entry::ScoreScan, n.div_ceil(256), 1, 256, 0), + Self::Tc { t, reach } => { + if !(1..=256).contains(&t) + || reach == 0 + || reach as usize > crate::serving_context::geometry().max_blocks() + { + return Err(Error::InvalidQwenShape); + } + (Entry::Tc, reach.div_ceil(128), t.div_ceil(16), 128, 49920) + } + Self::ScoreTail(t) => (Entry::ScoreTail, t, 1, 32, 0), + Self::Topk(t) => (Entry::Topk, t, 1, 256, 0), + Self::DecodeRms(n) => { + if ![2, 4, 24].contains(&n) { + return Err(Error::InvalidQwenShape); + } + (Entry::DecodeRms, n, 1, 256, 0) + } + Self::DecodeRope(n) => { + if ![2, 4, 24].contains(&n) { + return Err(Error::InvalidQwenShape); + } + (Entry::DecodeRope, 1, n, 128, 0) + } + Self::DecodeAppend => (Entry::DecodeAppend, 1, 1, 256, 0), + Self::DecodeScores => (Entry::DecodeScores, 256, 1, 256, 0), + }; + if x == 0 || y == 0 { + return Err(Error::InvalidQwenShape); + } + Ok((entry, x, y, threads, shared)) } } -#[cfg(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64"))] -mod enabled { - use super::*;use libc::{c_int,c_uint,c_void}; - type Load=unsafe extern "C" fn(*mut *mut c_void,*const c_void)->c_int; - type Function=unsafe extern "C" fn(*mut *mut c_void,*mut c_void,*const libc::c_char)->c_int; - type Unload=unsafe extern "C" fn(*mut c_void)->c_int; - type Attribute=unsafe extern "C" fn(*mut c_void,c_int,c_int)->c_int; - type CurrentDevice=unsafe extern "C" fn(*mut c_int)->c_int; - type DeviceAttribute=unsafe extern "C" fn(*mut c_int,c_int,c_int)->c_int; - type Kernel=unsafe extern "C" fn(*mut c_void,c_uint,c_uint,c_uint,c_uint,c_uint,c_uint,c_uint,*mut c_void,*mut *mut c_void,*mut *mut c_void)->c_int; - #[cfg_attr(not(windows), link(name="m"))] - unsafe extern "C" {fn powf(x:f32,y:f32)->f32;} - pub(crate) fn theta()->f32 { - // SAFETY: exact Original host libm powf, fixed finite arguments. - unsafe {powf(10000000.0,-2.0/64.0)} - } - fn check(op:&'static str,code:c_int)->Result<()> {if code==0{Ok(())}else{Err(Error::Driver{operation:op,code})}} - struct Library(*mut c_void); - impl Drop for Library {fn drop(&mut self){ // SAFETY: real owned dlopen handle. - unsafe {libc::dlclose(self.0);}}} - macro_rules! symbol {($l:ident,$n:literal,$ty:ty)=>{{ - // SAFETY: fixed private Linux64 CUDA ABI name and signature. - let p=unsafe{libc::dlsym($l.0,$n.as_ptr())};if p.is_null(){return Err(Error::MissingSymbol($n.to_str().expect("ASCII")));} - unsafe{std::mem::transmute::<*mut c_void,$ty>(p)} - }}} - pub(crate) struct Module {library:Option,modules:[Option;4],functions:[usize;16],launch:Kernel,unload:Unload} - impl Module { - pub(crate) fn load(index:&'static[u8],select:&'static[u8],postops:&'static[u8],decode_postops:&'static[u8])->Result { - if index.last()!=Some(&0)||select.last()!=Some(&0)||postops.last()!=Some(&0)||decode_postops.last()!=Some(&0){return Err(Error::InvalidSize);} - // SAFETY: fixed CUDA library, owned reference. - let ptr=unsafe{libc::dlopen(c"libcuda.so.1".as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)}; - if ptr.is_null(){return Err(Error::LibraryUnavailable);}let library=Library(ptr); - let current=symbol!(library,c"cuCtxGetDevice",CurrentDevice);let device_attr=symbol!(library,c"cuDeviceGetAttribute",DeviceAttribute); - let mut device=0;let mut major=0; - // SAFETY: actual current Context device, fixed COMPUTE_CAPABILITY_MAJOR75. - check("cuCtxGetDevice",unsafe{current(&mut device)})?; - check("cuDeviceGetAttribute",unsafe{device_attr(&mut major,75,device)})?; - if major<8{return Err(Error::UnsupportedProjection);} - let load=symbol!(library,c"cuModuleLoadData",Load);let function=symbol!(library,c"cuModuleGetFunction",Function); - let attr=symbol!(library,c"cuFuncSetAttribute",Attribute); - let mut owner=Self{launch:symbol!(library,c"cuLaunchKernel",Kernel),unload:symbol!(library,c"cuModuleUnload",Unload),library:Some(library),modules:[None,None,None,None],functions:[0;16]}; - let operation=(||{ - for (i,asset) in [index,select,postops,decode_postops].into_iter().enumerate(){let mut m=std::ptr::null_mut(); - // SAFETY: pinned NUL asset and valid current Context. - check("cuModuleLoadData",unsafe{load(&mut m,crate::arch_ptx::image(asset).as_ptr().cast())})?; - if m.is_null(){return Err(Error::InvalidDriverValue("cuModuleLoadData"));}owner.modules[i]=Some(m as usize); - } - for e in [Entry::First,Entry::Blocks,Entry::Tail,Entry::Rms,Entry::Rope,Entry::Split,Entry::Scan,Entry::ScoreScan,Entry::Round,Entry::Tc,Entry::ScoreTail,Entry::Topk,Entry::DecodeAppend,Entry::DecodeScores,Entry::DecodeRms,Entry::DecodeRope]{let mut f=std::ptr::null_mut(); - let m=owner.modules[match e {Entry::DecodeRms|Entry::DecodeRope=>3,Entry::Rms|Entry::Rope|Entry::Split=>2,Entry::Tc|Entry::ScoreTail|Entry::Topk|Entry::DecodeScores=>1,_=>0}].ok_or(Error::ContextPoisoned)?; - // SAFETY: real module and fixed export name. - check("cuModuleGetFunction",unsafe{function(&mut f,m as *mut c_void,e.name().as_ptr())})?; - if f.is_null(){return Err(Error::InvalidDriverValue("cuModuleGetFunction"));}owner.functions[e.index()]=f as usize; - } - // SAFETY: actual ScoreTC function, Original fixed attr max dynamic shared8/49,920. - check("cuFuncSetAttribute",unsafe{attr(owner.functions[Entry::Tc.index()] as *mut c_void,8,49920)})?;Ok(()) - })();if let Err(primary)=operation{return combine(Err(primary),owner.close());}Ok(owner) - } - pub(crate) fn launch(&self,shape:Launch,stream:usize,args:&mut Arguments)->Result<()> { - if stream==0{return Err(Error::InvalidDriverValue("QSA stream"));}let(e,x,y,block,shared)=shape.shape()?; - args.pointers.clear();for a in &mut args.values {args.pointers.push(match a{Value::Address(v)=>(v as *mut u64).cast(),Value::I32(v)=>(v as *mut i32).cast(),Value::I64(v)=>(v as *mut i64).cast(),Value::U32(v)=>(v as *mut u32).cast(),Value::F32(v)=>(v as *mut f32).cast()});} - // SAFETY: closed fixed topology; boxed ABI fields and genuine owners retained until real drain. - check("cuLaunchKernel",unsafe{(self.launch)(self.functions[e.index()] as *mut c_void,x,y,1,block,1,1,shared,stream as *mut c_void,args.pointers.as_mut_ptr(),std::ptr::null_mut())}) - } - pub(crate) fn close(mut self)->Result<()> {self.close_inner()} - fn close_inner(&mut self)->Result<()> {let mut result=Ok(());for m in &mut self.modules {if let Some(m)=m.take(){ // SAFETY: real owned module, after actual drain. - result=combine(result,check("cuModuleUnload",unsafe{(self.unload)(m as *mut c_void)}));}} - if result.is_err()&&let Some(l)=self.library.take(){std::mem::forget(l);}result} - } - impl Drop for Module {fn drop(&mut self){let _=self.close_inner();}} -} -#[cfg(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64"))] -pub(crate) use enabled::{Module,theta}; -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +mod enabled; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub(crate) use enabled::{Module, theta}; +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] pub(crate) struct Module; -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] impl Module { - pub(crate) fn load(_:&'static[u8],_:&'static[u8],_:&'static[u8],_:&'static[u8])->Result{Err(Error::UnsupportedPlatform)} - pub(crate) fn launch(&self,_:Launch,_:usize,_:&mut Arguments)->Result<()>{Err(Error::UnsupportedPlatform)} - pub(crate) fn close(self)->Result<()>{Ok(())} + pub(crate) fn load(_: &'static [u8], _: &'static [u8], _: &'static [u8], _: &'static [u8]) -> Result { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn launch(&self, _: Launch, _: usize, _: &mut Arguments) -> Result<()> { + Err(Error::UnsupportedPlatform) + } + pub(crate) fn close(self) -> Result<()> { + Ok(()) + } } -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] -pub(crate) fn theta()->f32 {0.0} // unsupported platform refuses before any producer. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub(crate) fn theta() -> f32 { + 0.0 +} // unsupported platform refuses before any producer. diff --git a/crates/cuda-driver/src/qsa_index_ffi/enabled.rs b/crates/cuda-driver/src/qsa_index_ffi/enabled.rs new file mode 100644 index 00000000..003f4899 --- /dev/null +++ b/crates/cuda-driver/src/qsa_index_ffi/enabled.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use libc::{c_int, c_uint, c_void}; +type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> c_int; +type Function = unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> c_int; +type Unload = unsafe extern "C" fn(*mut c_void) -> c_int; +type Attribute = unsafe extern "C" fn(*mut c_void, c_int, c_int) -> c_int; +type CurrentDevice = unsafe extern "C" fn(*mut c_int) -> c_int; +type DeviceAttribute = unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int; +type Kernel = unsafe extern "C" fn( + *mut c_void, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + c_uint, + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, +) -> c_int; +#[cfg_attr(not(windows), link(name = "m"))] +unsafe extern "C" { + fn powf(x: f32, y: f32) -> f32; +} +pub(crate) fn theta() -> f32 { + // SAFETY: exact Original host libm powf, fixed finite arguments. + unsafe { powf(10000000.0, -2.0 / 64.0) } +} +fn check(op: &'static str, code: c_int) -> Result<()> { + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } +} +struct Library(*mut c_void); +impl Drop for Library { + fn drop(&mut self) { + // SAFETY: real owned dlopen handle. + unsafe { + libc::dlclose(self.0); + } + } +} +macro_rules! symbol { + ($l:ident,$n:literal,$ty:ty) => {{ + // SAFETY: fixed private Linux64 CUDA ABI name and signature. + let p = unsafe { libc::dlsym($l.0, $n.as_ptr()) }; + if p.is_null() { + return Err(Error::MissingSymbol($n.to_str().expect("ASCII"))); + } + unsafe { std::mem::transmute::<*mut c_void, $ty>(p) } + }}; +} +pub(crate) struct Module { + library: Option, + modules: [Option; 4], + functions: [usize; 16], + launch: Kernel, + unload: Unload, +} +impl Module { + pub(crate) fn load( + index: &'static [u8], + select: &'static [u8], + postops: &'static [u8], + decode_postops: &'static [u8], + ) -> Result { + if index.last() != Some(&0) + || select.last() != Some(&0) + || postops.last() != Some(&0) + || decode_postops.last() != Some(&0) + { + return Err(Error::InvalidSize); + } + // SAFETY: fixed CUDA library, owned reference. + let ptr = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if ptr.is_null() { + return Err(Error::LibraryUnavailable); + } + let library = Library(ptr); + let current = symbol!(library, c"cuCtxGetDevice", CurrentDevice); + let device_attr = symbol!(library, c"cuDeviceGetAttribute", DeviceAttribute); + let mut device = 0; + let mut major = 0; + // SAFETY: actual current Context device, fixed COMPUTE_CAPABILITY_MAJOR75. + check("cuCtxGetDevice", unsafe { current(&mut device) })?; + check("cuDeviceGetAttribute", unsafe { device_attr(&mut major, 75, device) })?; + if major < 8 { + return Err(Error::UnsupportedProjection); + } + let load = symbol!(library, c"cuModuleLoadData", Load); + let function = symbol!(library, c"cuModuleGetFunction", Function); + let attr = symbol!(library, c"cuFuncSetAttribute", Attribute); + let mut owner = Self { + launch: symbol!(library, c"cuLaunchKernel", Kernel), + unload: symbol!(library, c"cuModuleUnload", Unload), + library: Some(library), + modules: [None, None, None, None], + functions: [0; 16], + }; + let operation = (|| { + for (i, asset) in [index, select, postops, decode_postops].into_iter().enumerate() { + let mut m = std::ptr::null_mut(); + // SAFETY: pinned NUL asset and valid current Context. + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(asset).as_ptr().cast()) })?; + if m.is_null() { + return Err(Error::InvalidDriverValue("cuModuleLoadData")); + } + owner.modules[i] = Some(m as usize); + } + for e in [ + Entry::First, + Entry::Blocks, + Entry::Tail, + Entry::Rms, + Entry::Rope, + Entry::Split, + Entry::Scan, + Entry::ScoreScan, + Entry::Round, + Entry::Tc, + Entry::ScoreTail, + Entry::Topk, + Entry::DecodeAppend, + Entry::DecodeScores, + Entry::DecodeRms, + Entry::DecodeRope, + ] { + let mut f = std::ptr::null_mut(); + let m = owner.modules[match e { + Entry::DecodeRms | Entry::DecodeRope => 3, + Entry::Rms | Entry::Rope | Entry::Split => 2, + Entry::Tc | Entry::ScoreTail | Entry::Topk | Entry::DecodeScores => 1, + _ => 0, + }] + .ok_or(Error::ContextPoisoned)?; + // SAFETY: real module and fixed export name. + check("cuModuleGetFunction", unsafe { function(&mut f, m as *mut c_void, e.name().as_ptr()) })?; + if f.is_null() { + return Err(Error::InvalidDriverValue("cuModuleGetFunction")); + } + owner.functions[e.index()] = f as usize; + } + // SAFETY: actual ScoreTC function, Original fixed attr max dynamic shared8/49,920. + check("cuFuncSetAttribute", unsafe { attr(owner.functions[Entry::Tc.index()] as *mut c_void, 8, 49920) })?; + Ok(()) + })(); + if let Err(primary) = operation { + return combine(Err(primary), owner.close()); + } + Ok(owner) + } + pub(crate) fn launch(&self, shape: Launch, stream: usize, args: &mut Arguments) -> Result<()> { + if stream == 0 { + return Err(Error::InvalidDriverValue("QSA stream")); + } + let (e, x, y, block, shared) = shape.shape()?; + args.pointers.clear(); + for a in &mut args.values { + args.pointers.push(match a { + Value::Address(v) => (v as *mut u64).cast(), + Value::I32(v) => (v as *mut i32).cast(), + Value::I64(v) => (v as *mut i64).cast(), + Value::U32(v) => (v as *mut u32).cast(), + Value::F32(v) => (v as *mut f32).cast(), + }); + } + // SAFETY: closed fixed topology; boxed ABI fields and genuine owners retained until real drain. + check("cuLaunchKernel", unsafe { + (self.launch)( + self.functions[e.index()] as *mut c_void, + x, + y, + 1, + block, + 1, + 1, + shared, + stream as *mut c_void, + args.pointers.as_mut_ptr(), + std::ptr::null_mut(), + ) + }) + } + pub(crate) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + for m in &mut self.modules { + if let Some(m) = m.take() { + // SAFETY: real owned module, after actual drain. + result = combine(result, check("cuModuleUnload", unsafe { (self.unload)(m as *mut c_void) })); + } + } + if result.is_err() + && let Some(l) = self.library.take() + { + std::mem::forget(l); + } + result + } +} +impl Drop for Module { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/qsa_late.rs b/crates/cuda-driver/src/qsa_late.rs index 4d19a4dd..9bf62b86 100644 --- a/crates/cuda-driver/src/qsa_late.rs +++ b/crates/cuda-driver/src/qsa_late.rs @@ -21,12 +21,12 @@ pub(crate) const TOPK_SAMPLE: usize = 4; /// Frozen by `scripts/gpu-bringup/seal_pins.py` after `compile_assets.py` (extra-seal-plan.json, group qsa-late). pub(crate) const PIN: PtxPin = PtxPin { source_sha256: [ - 64, 47, 113, 181, 108, 16, 68, 196, 128, 106, 244, 32, 149, 48, 241, 195, 61, 244, 215, 40, - 122, 196, 211, 179, 159, 198, 67, 87, 158, 195, 212, 27, + 64, 47, 113, 181, 108, 16, 68, 196, 128, 106, 244, 32, 149, 48, 241, 195, 61, 244, 215, 40, 122, 196, 211, 179, + 159, 198, 67, 87, 158, 195, 212, 27, ], ptx_sha256: [ - 235, 200, 188, 10, 172, 27, 212, 167, 69, 64, 237, 36, 108, 0, 150, 13, 16, 21, 150, 48, 32, - 17, 51, 230, 210, 31, 48, 110, 254, 177, 186, 47, + 235, 200, 188, 10, 172, 27, 212, 167, 69, 64, 237, 36, 108, 0, 150, 13, 16, 21, 150, 48, 32, 17, 51, 230, 210, + 31, 48, 110, 254, 177, 186, 47, ], }; pub(crate) fn admit() -> Result<(), KarDecodeError> { @@ -70,7 +70,14 @@ pub(crate) fn topk_entry(tile_reach: usize) -> (usize, u32) { }), }; static SAID: std::sync::Once = std::sync::Once::new(); - SAID.call_once(|| eprintln!("leleka-serve qsa prompt top-k: {} (tiles of {} blocks and more), override {}", if wide { "wide" } else { "fast" }, TOPK_WIDE_MIN_BLOCKS, TOPK_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed))); + SAID.call_once(|| { + eprintln!( + "leleka-serve qsa prompt top-k: {} (tiles of {} blocks and more), override {}", + if wide { "wide" } else { "fast" }, + TOPK_WIDE_MIN_BLOCKS, + TOPK_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) + ) + }); topk_choice(wide, tile_reach) } fn topk_choice(wide: bool, tile_reach: usize) -> (usize, u32) { @@ -86,7 +93,8 @@ pub(crate) fn usable(context: &crate::Context<'_>) -> bool { #[cfg(feature = "sm86")] { let Ok(guard) = context.enter() else { return false }; - let loadable = crate::arch_ptx::loadable(PTX) && (crate::arch_ptx::native_sm120() || std::env::var("LELEKA_QSA_LATE_SM86").is_ok_and(|v| v == "1")); + let loadable = crate::arch_ptx::loadable(PTX) + && (crate::arch_ptx::native_sm120() || std::env::var("LELEKA_QSA_LATE_SM86").is_ok_and(|v| v == "1")); return guard.finish().is_ok() && loadable; } #[cfg(not(feature = "sm86"))] @@ -105,14 +113,23 @@ mod tests { assert_eq!(super::topk_choice(true, super::TOPK_WIDE_MIN_BLOCKS), (super::TOPK_WIDE, 1024)); assert_eq!(super::topk_choice(true, 65_538), (super::TOPK_WIDE, 1024)); // the entry indices are the positions in ENTRIES - for (i, name) in [(super::TOPK_FAST, "leleka_qsa_topk_fast"), (super::SCORE_SCAN_FAST, "leleka_qsa_score_scan_fast"), (super::TOPK_WIDE, "leleka_qsa_topk_wide"), (super::TOPK_WIDE_FAILED, "leleka_qsa_topk_wide_failed"), (super::TOPK_SAMPLE, "leleka_qsa_topk_sample")] { + for (i, name) in [ + (super::TOPK_FAST, "leleka_qsa_topk_fast"), + (super::SCORE_SCAN_FAST, "leleka_qsa_score_scan_fast"), + (super::TOPK_WIDE, "leleka_qsa_topk_wide"), + (super::TOPK_WIDE_FAILED, "leleka_qsa_topk_wide_failed"), + (super::TOPK_SAMPLE, "leleka_qsa_topk_sample"), + ] { assert_eq!(super::ENTRIES[i].to_str().unwrap(), name); } } #[test] fn the_asset_is_the_sealed_one_and_exports_its_entries() { - assert!(super::admit().is_ok(), "qsa_late.ptx does not match its pin (re-seal with scripts/gpu-bringup/seal_pins.py)"); + assert!( + super::admit().is_ok(), + "qsa_late.ptx does not match its pin (re-seal with scripts/gpu-bringup/seal_pins.py)" + ); let text = std::str::from_utf8(&super::PTX[..super::PTX.len() - 1]).expect("PTX is text"); for entry in super::ENTRIES { assert!(text.contains(entry.to_str().unwrap()), "entry {entry:?} missing"); diff --git a/crates/cuda-driver/src/qsa_late_gpu.rs b/crates/cuda-driver/src/qsa_late_gpu.rs index f462a09c..8228e95d 100644 --- a/crates/cuda-driver/src/qsa_late_gpu.rs +++ b/crates/cuda-driver/src/qsa_late_gpu.rs @@ -40,8 +40,10 @@ fn selection_kernels_equal_the_originals_at_long_positions() { let stream = workspace.blas().expect("blas").stream(); let max_blocks = crate::serving_context::geometry().max_blocks(); let guard = context.enter().expect("enter"); - let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); - let index = KernelModule::load(include_bytes!("qsa_prompt_indexer.ptx"), &[c"qsa_score_scan"]).expect("index module"); + let select = + KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); + let index = + KernelModule::load(include_bytes!("qsa_prompt_indexer.ptx"), &[c"qsa_score_scan"]).expect("index module"); let late = KernelModule::load(PTX, ENTRIES).expect("late module"); guard.finish().expect("finish"); let mut rng = Rng(0x243f6a8885a308d3); @@ -53,9 +55,9 @@ fn selection_kernels_equal_the_originals_at_long_positions() { (100_003, 64, 2), // all equal (261_000, 128, 1), (5_000, 64, 0), - (2_040, 64, 1), // the identity branch (n_kv <= width) for the first rows, selection after - (100, 32, 0), // identity everywhere - (3_999, 40, 2), // n_kv = 4 * n_bid on some rows (empty last block) + (2_040, 64, 1), // the identity branch (n_kv <= width) for the first rows, selection after + (100, 32, 0), // identity everywhere + (3_999, 40, 2), // n_kv = 4 * n_bid on some rows (empty last block) (65_536, 100, 1), ]; for (case, (p0, rows, style)) in cases.into_iter().enumerate() { @@ -93,8 +95,20 @@ fn selection_kernels_equal_the_originals_at_long_positions() { let ids_n = upload(&context, &vec![0xffu8; out_len]); let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); let guard = context.enter().expect("enter"); - let mut a_old = KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(&ids_o))]); - let mut a_new = KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(&ids_n))]); + let mut a_old = KernelArguments::new(vec![ + A::Address(h(&scores_d)), + A::Address(h(&steps_d)), + A::I64(max_blocks as i64), + A::I64(CAP as i64), + A::Address(h(&ids_o)), + ]); + let mut a_new = KernelArguments::new(vec![ + A::Address(h(&scores_d)), + A::Address(h(&steps_d)), + A::I64(max_blocks as i64), + A::I64(CAP as i64), + A::Address(h(&ids_n)), + ]); let t0 = std::time::Instant::now(); select.launch(0, rows as u32, 256, stream, &mut a_old).expect("old topk"); context.driver.api.synchronize().expect("sync"); @@ -106,7 +120,10 @@ fn selection_kernels_equal_the_originals_at_long_positions() { guard.finish().expect("finish"); let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len)); assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ"); - eprintln!("QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms", out_len); + eprintln!( + "QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms", + out_len + ); // the score scan: a clean tile, then a NaN inside a row's blocks, then a NaN beyond its last block let reach = (p0 + rows) / 4 + 1; @@ -128,9 +145,24 @@ fn selection_kernels_equal_the_originals_at_long_positions() { let bad_d = upload(&context, &braw); let (st_o, st_n) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16])); let guard = context.enter().expect("enter"); - let mut so = KernelArguments::new(vec![A::Address(h(&bad_d)), A::Address(h(&steps_d)), A::I32(rows as i32), A::I64(max_blocks as i64), A::Address(h(&st_o)), A::U32(1)]); + let mut so = KernelArguments::new(vec![ + A::Address(h(&bad_d)), + A::Address(h(&steps_d)), + A::I32(rows as i32), + A::I64(max_blocks as i64), + A::Address(h(&st_o)), + A::U32(1), + ]); index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); - let mut sn = KernelArguments::new(vec![A::Address(h(&bad_d)), A::Address(h(&steps_d)), A::I32(rows as i32), A::I64(max_blocks as i64), A::I64(reach as i64), A::Address(h(&st_n)), A::U32(1)]); + let mut sn = KernelArguments::new(vec![ + A::Address(h(&bad_d)), + A::Address(h(&steps_d)), + A::I32(rows as i32), + A::I64(max_blocks as i64), + A::I64(reach as i64), + A::Address(h(&st_n)), + A::U32(1), + ]); late.launch(SCORE_SCAN_FAST, (rows * reach).div_ceil(256) as u32, 256, stream, &mut sn).expect("new scan"); context.driver.api.synchronize().expect("sync"); guard.finish().expect("finish"); @@ -157,7 +189,8 @@ fn topk_variants_equal_the_original_and_are_timed() { let stream = workspace.blas().expect("blas").stream(); let max_blocks = crate::serving_context::geometry().max_blocks(); let guard = context.enter().expect("enter"); - let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); + let select = + KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module"); let late = KernelModule::load(PTX, ENTRIES).expect("late module"); let cluster = KernelModule::load(crate::qsa_cluster::PTX, crate::qsa_cluster::ENTRIES).expect("cluster module"); guard.finish().expect("finish"); @@ -207,7 +240,9 @@ fn topk_variants_equal_the_original_and_are_timed() { 0 => u * 1000.0, 1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32), 2 => 0.0, - _ => (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01, + _ => { + (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01 + } }; } if style != 2 && (p0 + r + 1) % 4 != 0 { @@ -221,7 +256,13 @@ fn topk_variants_equal_the_original_and_are_timed() { let out_len = rows * CAP * 4; let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); let args_for = |ids: &DeviceBuffer<'_>| { - KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(ids))]) + KernelArguments::new(vec![ + A::Address(h(&scores_d)), + A::Address(h(&steps_d)), + A::I64(max_blocks as i64), + A::I64(CAP as i64), + A::Address(h(ids)), + ]) }; let n = rows as u32; // one runner per variant: (name, closure launching it once) @@ -238,7 +279,14 @@ fn topk_variants_equal_the_original_and_are_timed() { late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed"); }), ), - ("cluster", Box::new(|a| cluster.launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a).expect("cluster"))), + ( + "cluster", + Box::new(|a| { + cluster + .launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a) + .expect("cluster") + }), + ), ]; let mut reference: Option> = None; let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:"); @@ -262,7 +310,10 @@ fn topk_variants_equal_the_original_and_are_timed() { let got = download(&ids, out_len); match &reference { None => reference = Some(got), - Some(r) => assert!(*r == got, "case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original"), + Some(r) => assert!( + *r == got, + "case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original" + ), } line.push_str(&format!(" {name} {us:.1} us;")); } @@ -283,12 +334,14 @@ fn decode_scores_are_timed_next_to_the_topk() { let stream = workspace.blas().expect("blas").stream(); let max_blocks = crate::serving_context::geometry().max_blocks(); let guard = context.enter().expect("enter"); - let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_decode_scores", c"qsa_topk_ref"]).expect("select module"); + let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_decode_scores", c"qsa_topk_ref"]) + .expect("select module"); guard.finish().expect("finish"); let mut rng = Rng(0x1234_5678_9abc_def1); for (pos, nq) in [(131_072usize, 4usize), (245_000, 1), (245_000, 4), (245_000, 5)] { let n_bid_max = (pos + nq) / 4; - let pooled: Vec = (0..(max_blocks + 1) * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); + let pooled: Vec = + (0..(max_blocks + 1) * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); let dead: Vec = (0..128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); let qidx: Vec = (0..nq * 4 * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect(); let mut steps = Vec::new(); @@ -299,7 +352,12 @@ fn decode_scores_are_timed_next_to_the_topk() { } } let f = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::>(); - let (pooled_d, dead_d, qidx_d, steps_d) = (upload(&context, &f(&pooled)), upload(&context, &f(&dead)), upload(&context, &f(&qidx)), upload(&context, &steps)); + let (pooled_d, dead_d, qidx_d, steps_d) = ( + upload(&context, &f(&pooled)), + upload(&context, &f(&dead)), + upload(&context, &f(&qidx)), + upload(&context, &steps), + ); let scores_d = upload(&context, &vec![0u8; nq * max_blocks * 4]); let ids_d = upload(&context, &vec![0xffu8; nq * CAP * 4]); let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle"); @@ -314,11 +372,27 @@ fn decode_scores_are_timed_next_to_the_topk() { context.driver.api.synchronize().expect("sync"); t0.elapsed().as_secs_f64() * 1e6 / 20.0 }; - let mut sa = KernelArguments::new(vec![A::Address(h(&pooled_d)), A::Address(h(&dead_d)), A::Address(h(&qidx_d)), A::Address(h(&steps_d)), A::I32(nq as i32), A::I64(max_blocks as i64), A::Address(h(&scores_d))]); + let mut sa = KernelArguments::new(vec![ + A::Address(h(&pooled_d)), + A::Address(h(&dead_d)), + A::Address(h(&qidx_d)), + A::Address(h(&steps_d)), + A::I32(nq as i32), + A::I64(max_blocks as i64), + A::Address(h(&scores_d)), + ]); let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); - let mut ta = KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(&ids_d))]); + let mut ta = KernelArguments::new(vec![ + A::Address(h(&scores_d)), + A::Address(h(&steps_d)), + A::I64(max_blocks as i64), + A::I64(CAP as i64), + A::Address(h(&ids_d)), + ]); let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); guard.finish().expect("finish"); - eprintln!("QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)"); + eprintln!( + "QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)" + ); } } diff --git a/crates/cuda-driver/src/qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_mapped_journal.rs index 2122110d..dd350b13 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal.rs @@ -1,18 +1,43 @@ //! Original positional mapped KV is one authoritative initialized-address owner. //! Prefix checkpoints are coverage, not byte copies or finite certificates. use super::*; -use std::cell::Cell; use crate::OriginalDeviceGrRead; -struct Coverage{end:Cell} +use std::cell::Cell; +struct Coverage { + end: Cell, +} #[derive(Clone)] -pub struct OriginalQsaMappedPrefix{origin:QsaKvOwnerId,epoch:u64,coverage:Rc,end:usize} -pub struct OriginalQsaMappedAppend{first:usize,rows:usize,final_prefix:OriginalQsaMappedPrefix} -pub struct OriginalQsaMappedJournal<'ctx>{owner:QsaPromptKv<'ctx>,epoch:u64,coverage:Rc,end:usize,stage_table:Option,stage_addresses:Option<[u64;4]>,resolver_ready:bool,failed:bool} +pub struct OriginalQsaMappedPrefix { + origin: QsaKvOwnerId, + epoch: u64, + coverage: Rc, + end: usize, +} +pub struct OriginalQsaMappedAppend { + first: usize, + rows: usize, + final_prefix: OriginalQsaMappedPrefix, +} +pub struct OriginalQsaMappedJournal<'ctx> { + owner: QsaPromptKv<'ctx>, + epoch: u64, + coverage: Rc, + end: usize, + stage_table: Option, + stage_addresses: Option<[u64; 4]>, + resolver_ready: bool, + failed: bool, +} /// Model-free GPU proof of the one-token-prompt fix: a journal no prompt append has touched refuses the window /// capture until `ensure_resolver`, which initialises the resolver WITHOUT changing the epoch (prefixes minted /// before stay valid, unlike `reset`) and is idempotent. -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] mod resolver_tests { use super::*; @@ -54,7 +79,12 @@ mod resolver_tests { /// Model-free GPU proof of the prefix-cache transfer (`docs/prefix-cache.md`): parked host K/V pages and index rows /// written back into a journal / index come out byte for byte, the ends and coverage follow, the resolver is reset /// when cells were written, and a span can be written back in pieces. -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] mod parked_tests { use super::*; use crate::OriginalQsaResidentIndex; @@ -143,7 +173,10 @@ mod parked_tests { assert_eq!(index.export_tail(&checkpoint2).unwrap(), tail_bytes); // a restore to the minted checkpoint works like any other index.restore(&mut ws, &checkpoint2).unwrap(); - assert!(index.import(&mut ws, &[(cells / 4, &second)], &tail_bytes, cells).is_err(), "rows beyond end / 4 are refused"); + assert!( + index.import(&mut ws, &[(cells / 4, &second)], &tail_bytes, cells).is_err(), + "rows beyond end / 4 are refused" + ); journal.close().unwrap(); drop(index); @@ -153,7 +186,7 @@ mod parked_tests { } } -#[path = "qsa_mapped_journal/impl_originalqsamappedprefix.rs"] -mod impl_originalqsamappedprefix; #[path = "qsa_mapped_journal/impl_originalqsamappedjournal.rs"] mod impl_originalqsamappedjournal; +#[path = "qsa_mapped_journal/impl_originalqsamappedprefix.rs"] +mod impl_originalqsamappedprefix; diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs index 2ed5a915..53f98298 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs @@ -3,55 +3,61 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalQsaMappedJournal<'ctx>{ - pub fn append_resident_decode(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&OriginalQsaMappedPrefix,inputs:&crate::qsa_prompt_index::OriginalQsaResidentScalarSelection<'_, '_, '_, 'ctx>)->Result{ - let t=1;if inputs.first_position()!=prior.next_position(){return Err(Error::InvalidQwenShape)} +impl<'ctx> OriginalQsaMappedJournal<'ctx> { + pub fn append_resident_decode( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + inputs: &crate::qsa_prompt_index::OriginalQsaResidentScalarSelection<'_, '_, '_, 'ctx>, + ) -> Result { + let t = 1; + if inputs.first_position() != prior.next_position() { + return Err(Error::InvalidQwenShape); + } self.validate_prefix(prior)?; stage.validate(self.owner.context)?; workspace.validate_context(self.owner.context)?; if !(1..=8192).contains(&t) - || prior - .end - .checked_add(t) - .is_none_or(|n| n > crate::serving_context::geometry().cells()) + || prior.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) { return Err(Error::InvalidQwenShape); } let end = prior.end + t; - let (kh,vh)=inputs.with_completed_kv(|k,v|{checked(self.owner.context,k,2048)?;checked(self.owner.context,v,2048)?;Ok((k.handle.ok_or(Error::ContextPoisoned)?,v.handle.ok_or(Error::ContextPoisoned)?))})?; - let (k,v)=(kh.qwen_address(),vh.qwen_address()); - self.owner.reject_original_span(kh,t*512*4)?; - self.owner.reject_original_span(vh,t*512*4)?; - stage.reject_span(kh,t*512*4)?; - stage.reject_span(vh,t*512*4)?; - workspace.reject_alias(kh,t*512*4)?;workspace.reject_alias(vh,t*512*4)?; - if prior.end!=self.end{return Err(Error::InvalidQwenShape)} - let table=stage.table()?; - if self.stage_table.is_some_and(|old|old!=table){return Err(Error::InvalidQwenShape)} + let (kh, vh) = inputs.with_completed_kv(|k, v| { + checked(self.owner.context, k, 2048)?; + checked(self.owner.context, v, 2048)?; + Ok((k.handle.ok_or(Error::ContextPoisoned)?, v.handle.ok_or(Error::ContextPoisoned)?)) + })?; + let (k, v) = (kh.qwen_address(), vh.qwen_address()); + self.owner.reject_original_span(kh, t * 512 * 4)?; + self.owner.reject_original_span(vh, t * 512 * 4)?; + stage.reject_span(kh, t * 512 * 4)?; + stage.reject_span(vh, t * 512 * 4)?; + workspace.reject_alias(kh, t * 512 * 4)?; + workspace.reject_alias(vh, t * 512 * 4)?; + if prior.end != self.end { + return Err(Error::InvalidQwenShape); + } + let table = stage.table()?; + if self.stage_table.is_some_and(|old| old != table) { + return Err(Error::InvalidQwenShape); + } // Whole original mapped storage/staging has fixed addresses. Only new // cells are written; preceding prefix bytes remain actual owners. let status = stage.status()?; status.copy_from(&[0; 4])?; let sa = checked(self.owner.context, status, 4)?; let rp = self.owner.pools.addresses()?; - let sp=[0u64;4]; - if !self.resolver_ready{self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace,self.owner.pools.table()?)?;self.resolver_ready=true;} + let sp = [0u64; 4]; + if !self.resolver_ready { + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace, self.owner.pools.table()?)?; + self.resolver_ready = true; + } let hp = self.owner.host_addresses()?; - let guard = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I32((t * 512) as i32), - Arg::U64(sa), - ])?; - stage.run( - workspace, - 0, - [(t * 512).div_ceil(256) as u32, 1, 1], - 256, - guard, - )?; + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; + stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } @@ -81,7 +87,7 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{ Arg::I32(end as i32), Arg::U64(sa), ])?; - + self.owner.current = None; self.owner.mapped_current = None; stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; @@ -89,8 +95,11 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{ if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } - self.end=end;self.coverage.end.set(end);self.stage_table=Some(table);self.stage_addresses=None; - Ok(OriginalQsaMappedAppend{first:prior.end,rows:t,final_prefix:self.prefix()}) + self.end = end; + self.coverage.end.set(end); + self.stage_table = Some(table); + self.stage_addresses = None; + Ok(OriginalQsaMappedAppend { first: prior.end, rows: t, final_prefix: self.prefix() }) } } @@ -100,45 +109,89 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{ /// /// A span of `n` pages is stored run-major, exactly like the image itself: `[K codes n*2048 | V codes n*2048 | /// K scales n*64 | V scales n*64]` = `n * HOST_PAGE_BYTES` bytes. -impl<'ctx> OriginalQsaMappedJournal<'ctx>{ - /// Bytes of one 4-cell page of the host image (1056 B per cell). - pub const HOST_PAGE_BYTES:usize=QSA_PROMPT_HOST_PAGE_BYTES; - /// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image. - pub fn export_pages(&self,first_page:usize,pages:usize,out:&mut Vec)->Result<()>{ - self.validate_context(self.owner.context)?; - // whole pages up to the one holding the last reachable cell (a request-end checkpoint ends inside a page) - if pages==0||first_page.checked_add(pages).is_none_or(|e|e>self.end.div_ceil(4)){return Err(Error::InvalidQwenShape)} - // the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered after it - self.owner.context.synchronize()?; - out.clear();out.try_reserve_exact(pages*Self::HOST_PAGE_BYTES).map_err(|_|Error::HostAllocation)?;out.resize(pages*Self::HOST_PAGE_BYTES,0); - let m=self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?;let offsets=super::super::offsets()?;let mut at=0; - for(i,&page)in super::super::PAGE.iter().enumerate(){let n=pages*page;m.read(offsets[i]+first_page*page,&mut out[at..at+n])?;at+=n;} - Ok(()) - } - /// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at - /// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix - /// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset - /// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not - /// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`. - pub fn import_pages(&mut self,w:&mut NativeBatchWorkspace<'ctx>,spans:&[(usize,&[u8])],end:usize)->Result{ - self.validate_context(self.owner.context)?;w.validate_context(self.owner.context)?; - if end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} - let page_limit=crate::serving_context::geometry().pages(); - for(first,bytes)in spans{ - if bytes.is_empty()||bytes.len()%Self::HOST_PAGE_BYTES!=0||first.checked_add(bytes.len()/Self::HOST_PAGE_BYTES).is_none_or(|e|e>page_limit)||(first+bytes.len()/Self::HOST_PAGE_BYTES)*4>end.div_ceil(4)*4{return Err(Error::InvalidQwenShape)} - } - // no CPU host write may race a stream use of the old cells - self.owner.context.synchronize().map_err(|e|{self.failed=true;e})?; - if !spans.is_empty(){ - let offsets=super::super::offsets()?;let m=self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; - for(first,bytes)in spans{let pages=bytes.len()/Self::HOST_PAGE_BYTES;let mut at=0; - for(i,&page)in super::super::PAGE.iter().enumerate(){let n=pages*page;m.write(offsets[i]+first*page,&bytes[at..at+n]).map_err(|e|{self.failed=true;e})?;at+=n;}} - let table=self.owner.pools.table()?; - self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w,table).map_err(|e|{self.failed=true;e})?; - self.resolver_ready=true; - } - self.owner.current=None;self.owner.mapped_current=None; - self.coverage.end.set(self.coverage.end.get().min(end));self.coverage=Rc::new(Coverage{end:Cell::new(end)});self.end=end; - Ok(self.prefix()) - } +impl<'ctx> OriginalQsaMappedJournal<'ctx> { + /// Bytes of one 4-cell page of the host image (1056 B per cell). + pub const HOST_PAGE_BYTES: usize = QSA_PROMPT_HOST_PAGE_BYTES; + /// Copy the pages `first_page..first_page + pages` of the reachable prefix out of the host image. + pub fn export_pages(&self, first_page: usize, pages: usize, out: &mut Vec) -> Result<()> { + self.validate_context(self.owner.context)?; + // whole pages up to the one holding the last reachable cell (a request-end checkpoint ends inside a page) + if pages == 0 || first_page.checked_add(pages).is_none_or(|e| e > self.end.div_ceil(4)) { + return Err(Error::InvalidQwenShape); + } + // the GPU wrote these cells through the mapped alias; every public writer drains, this keeps the read ordered after it + self.owner.context.synchronize()?; + out.clear(); + out.try_reserve_exact(pages * Self::HOST_PAGE_BYTES).map_err(|_| Error::HostAllocation)?; + out.resize(pages * Self::HOST_PAGE_BYTES, 0); + let m = self.owner.mapped.as_ref().ok_or(Error::ContextPoisoned)?; + let offsets = super::super::offsets()?; + let mut at = 0; + for (i, &page) in super::super::PAGE.iter().enumerate() { + let n = pages * page; + m.read(offsets[i] + first_page * page, &mut out[at..at + n])?; + at += n; + } + Ok(()) + } + /// Put parked spans `(first_page, bytes)` back into the host image and make the journal's reachable prefix end at + /// `end` cells: the cells below `end` that no span names must already hold the prefix (the caller's live-prefix + /// bookkeeping). Any written cell may have a stale copy in the VRAM resident window, so the resolver is reset + /// (as `QsaPromptKv::restore` does); with no span nothing is written and nothing is reset. The epoch does not + /// change: prefixes minted before are fenced by the new coverage, exactly as after `rollback`. + pub fn import_pages( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + spans: &[(usize, &[u8])], + end: usize, + ) -> Result { + self.validate_context(self.owner.context)?; + w.validate_context(self.owner.context)?; + if end > crate::serving_context::geometry().cells() { + return Err(Error::InvalidQwenShape); + } + let page_limit = crate::serving_context::geometry().pages(); + for (first, bytes) in spans { + if bytes.is_empty() + || bytes.len() % Self::HOST_PAGE_BYTES != 0 + || first.checked_add(bytes.len() / Self::HOST_PAGE_BYTES).is_none_or(|e| e > page_limit) + || (first + bytes.len() / Self::HOST_PAGE_BYTES) * 4 > end.div_ceil(4) * 4 + { + return Err(Error::InvalidQwenShape); + } + } + // no CPU host write may race a stream use of the old cells + self.owner.context.synchronize().map_err(|e| { + self.failed = true; + e + })?; + if !spans.is_empty() { + let offsets = super::super::offsets()?; + let m = self.owner.mapped.as_mut().ok_or(Error::ContextPoisoned)?; + for (first, bytes) in spans { + let pages = bytes.len() / Self::HOST_PAGE_BYTES; + let mut at = 0; + for (i, &page) in super::super::PAGE.iter().enumerate() { + let n = pages * page; + m.write(offsets[i] + first * page, &bytes[at..at + n]).map_err(|e| { + self.failed = true; + e + })?; + at += n; + } + } + let table = self.owner.pools.table()?; + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table).map_err(|e| { + self.failed = true; + e + })?; + self.resolver_ready = true; + } + self.owner.current = None; + self.owner.mapped_current = None; + self.coverage.end.set(self.coverage.end.get().min(end)); + self.coverage = Rc::new(Coverage { end: Cell::new(end) }); + self.end = end; + Ok(self.prefix()) + } } diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix.rs index d5b1fee7..056309d7 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix.rs @@ -3,207 +3,7 @@ #[allow(unused_imports)] use super::*; -impl OriginalQsaMappedPrefix{pub fn next_position(&self)->usize{self.end}pub fn owner_id(&self)->QsaKvOwnerId{self.origin.clone()}pub fn validate_retained(&self)->Result<()>{if self.end>crate::serving_context::geometry().cells()||self.end>self.coverage.end.get(){return Err(Error::InvalidQwenShape)}Ok(())}} -impl OriginalQsaMappedAppend{ - pub fn rows(&self)->usize{self.rows}pub fn first_position(&self)->usize{self.first} - pub fn prefix_after(&self,row:usize)->Result{if row>=self.rows{return Err(Error::InvalidQwenShape)}let end=self.first+row+1;if end>self.final_prefix.coverage.end.get(){return Err(Error::InvalidQwenShape)}Ok(OriginalQsaMappedPrefix{end,..self.final_prefix.clone()})} - pub fn final_prefix(&self)->&OriginalQsaMappedPrefix{&self.final_prefix} -} -impl<'ctx> QsaPromptKv<'ctx>{ - /// Actual fresh owner only. Existing immutable snapshot APIs are not silently - /// promoted to resident storage, nor used after this consuming handoff. - pub fn into_original_mapped_journal(self)->Result>{self.validate()?;if self.current.is_some()||self.mapped_current.is_some(){return Err(Error::InvalidQwenShape)}Ok(OriginalQsaMappedJournal{owner:self,epoch:0,coverage:Rc::new(Coverage{end:Cell::new(0)}),end:0,stage_table:None,stage_addresses:None,resolver_ready:false,failed:false})} -} -impl<'ctx> OriginalQsaMappedJournal<'ctx>{ - pub fn owner_id(&self)->QsaKvOwnerId{self.owner.owner_id()} - pub fn allocated_bytes(&self)->usize{self.owner.allocated_bytes()} - pub fn mapped_host_bytes(&self)->usize{self.owner.pinned_host_bytes()} - pub fn next_position(&self)->usize{self.end} - pub fn is_failed(&self)->bool{self.failed||self.owner.is_failed()} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{self.owner.validate_context(c)?;if self.is_failed(){return Err(Error::ContextPoisoned)}Ok(())} - pub fn empty_prefix(&self)->Result{self.validate_context(self.owner.context)?;if self.end!=0{return Err(Error::InvalidQwenShape)}Ok(self.prefix())} - pub(super) fn prefix(&self)->OriginalQsaMappedPrefix{OriginalQsaMappedPrefix{origin:self.owner.owner_id(),epoch:self.epoch,coverage:self.coverage.clone(),end:self.end}} - /// The prefix currently reachable through this journal (its committed end), for session lineage after a - /// verifier accepted-prefix commit. The journal is the sole authority; this mints no append or copy. - pub fn current_prefix(&self)->Result{self.validate_context(self.owner.context)?;Ok(self.prefix())} - pub fn validate_prefix(&self,p:&OriginalQsaMappedPrefix)->Result<()>{self.validate_context(self.owner.context)?;if !p.origin.same_owner(&self.owner.owner_id())||p.epoch!=self.epoch||p.end>p.coverage.end.get()||p.end>self.end||p.end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)}Ok(())} - pub fn rollback(&mut self,w:&mut NativeBatchWorkspace<'ctx>,p:&OriginalQsaMappedPrefix)->Result<()>{self.validate_prefix(p)?;w.validate_context(self.owner.context)?; - // Every producer has drained before coverage changes. Positional rejected - // cells remain initialized but become unreachable through genuine bounds. - self.owner.context.synchronize().map_err(|e|{self.failed=true;e})?; - // Original commit/rewind changes reachable end only. Future cached cells - // are excluded by the actual prefix bound; the next real append rewrites - // its exact cell in both mapped and resident pools. No extra clock reset. - self.coverage.end.set(self.coverage.end.get().min(p.end));self.coverage=Rc::new(Coverage{end:Cell::new(p.end)});self.end=p.end;Ok(()) - } - pub fn accept_prefix(&mut self,w:&mut NativeBatchWorkspace<'ctx>,batch:&OriginalQsaMappedAppend,accepted:usize)->Result{ - if accepted>batch.rows||self.end!=batch.first+batch.rows{return Err(Error::InvalidQwenShape)}self.validate_prefix(&batch.final_prefix)?; - let p=OriginalQsaMappedPrefix{end:batch.first+accepted,..batch.final_prefix.clone()};self.rollback(w,&p)?;Ok(self.prefix()) - } - pub fn reset(&mut self,w:&mut NativeBatchWorkspace<'ctx>)->Result{self.validate_context(self.owner.context)?;let epoch=self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?;w.validate_context(self.owner.context)?; - self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w,self.owner.pools.table()?)?;self.coverage.end.set(0);self.coverage=Rc::new(Coverage{end:Cell::new(0)});self.epoch=epoch;self.end=0;self.stage_table=None;self.stage_addresses=None;self.resolver_ready=true;Ok(self.prefix()) - } - /// Host publication of the K/V rows a verifier window appended on the GPU (`mtp_original_append` writes the resident pool and - /// the host copy per row): the reachable end moves from `position` to `position + keep`. Rows past `keep` stay initialised but - /// unreachable, as after `rollback`. Only the accepted-prefix commit calls this, after its commit graph drained. - pub(crate) fn publish_window_rows(&mut self,position:usize,keep:usize)->Result<()>{ - self.validate_context(self.owner.context)?; - let end=position.checked_add(keep).ok_or(Error::InvalidSize)?; - if keep==0||self.end!=position||end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} - self.end=end;self.coverage.end.set(end);Ok(()) - } - pub(crate) fn reject_span(&self,h:crate::ffi::BufferHandle,n:usize)->Result<()>{self.owner.reject_original_span(h,n)} - pub(crate) fn completed_addresses(&self,stage:&OriginalQsaResidentTransport<'ctx>,p:&OriginalQsaMappedPrefix,inputs:&crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>)->Result<([u64;4],u64,usize)>{self.validate_prefix(p)?;stage.validate(self.owner.context)?;let table=stage.table()?;if self.stage_table!=Some(table)||self.stage_addresses!=Some(inputs.kv_stage_spans(self.owner.context)?.map(|h|h.qwen_address())){return Err(Error::InvalidQwenShape)}Ok((inputs.kv_stage_spans(self.owner.context)?.map(|h|h.qwen_address()),table,p.end))} - pub fn close(self)->Result<()>{self.owner.close()} - /// Start the KV prefix copy of the layer that is about to run on a side stream (`LELEKA_PREFILL_QSA_PREFETCH`, see `OriginalQsaResidentTransport::begin_prefix`): - /// the same copy `append_resident_arena` makes, from the same host mirror into the same stage spans, started before the layer's projections and indexer. - /// Nothing changes when the switch is off. `read` is the layer's read lease; `prior` the prefix `append_resident_arena` will be given. - pub fn begin_stage_prefix(&self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&OriginalQsaMappedPrefix,read:&OriginalDeviceGrRead<'_,'_,'ctx>)->Result<()>{ - if !OriginalQsaResidentTransport::prefetch_enabled(){return Ok(())} - self.validate_prefix(prior)?;stage.validate(self.owner.context)?;workspace.validate_context(self.owner.context)?; - if !read.context_matches(self.owner.context){return Err(Error::ContextMismatch)} - if prior.end!=self.end{return Err(Error::InvalidQwenShape)} - let stage_spans=crate::qsa_prompt_index::kv_stage_spans_of(read,read.rows())?; - for(i,h)in stage_spans.iter().enumerate(){self.owner.reject_original_span(*h,stage_runs()?[i])?;} - let hp=self.owner.host_addresses()?; - stage.begin_prefix(workspace,hp,stage_spans,prior.end.div_ceil(4)) - } - pub(crate) fn append_resident_arena(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&OriginalQsaMappedPrefix,inputs:&crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>)->Result{ - let t=inputs.rows();if inputs.first_position()!=prior.next_position(){return Err(Error::InvalidQwenShape)} - self.validate_prefix(prior)?; - stage.validate(self.owner.context)?; - workspace.validate_context(self.owner.context)?; - if !(1..=8192).contains(&t) - || prior - .end - .checked_add(t) - .is_none_or(|n| n > crate::serving_context::geometry().cells()) - { - return Err(Error::InvalidQwenShape); - } - let end = prior.end + t; - let (kh,vh)=inputs.kv_spans(self.owner.context)?; - let (k,v)=(kh.qwen_address(),vh.qwen_address()); - self.owner.reject_original_span(kh,t*512*4)?; - self.owner.reject_original_span(vh,t*512*4)?; - stage.reject_span(kh,t*512*4)?; - stage.reject_span(vh,t*512*4)?; - workspace.reject_alias(kh,t*512*4)?;workspace.reject_alias(vh,t*512*4)?; - if prior.end!=self.end{return Err(Error::InvalidQwenShape)} - let table=stage.table()?; - if self.stage_table.is_some_and(|old|old!=table){return Err(Error::InvalidQwenShape)} - // Whole original mapped storage/staging has fixed addresses. Only new - // cells are written; preceding prefix bytes remain actual owners. - let status = stage.status()?; - status.copy_from(&[0; 4])?; - let sa = checked(self.owner.context, status, 4)?; - let rp = self.owner.pools.addresses()?; - let sp = inputs.kv_stage_spans(self.owner.context)?.map(|h|h.qwen_address()); - if !self.resolver_ready{self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace,self.owner.pools.table()?)?;self.resolver_ready=true;} - let hp = self.owner.host_addresses()?; - // Original kv_stage_from_host: shared arena stage belongs to another - // layer/chunk until the authoritative real mapped prefix is copied. - let stage_spans=inputs.kv_stage_spans(self.owner.context)?; - for(i,h)in stage_spans.iter().enumerate(){self.owner.reject_original_span(*h,stage_runs()?[i])?;} - let timed=crate::command_profile::enabled();let started=std::time::Instant::now(); - stage.copy_prefix(workspace,hp,stage_spans,prior.end.div_ceil(4))?; - if timed{crate::command_profile::add("qsa-kv",1,"stage copy_prefix (host -> arena stage)",started.elapsed());} - let started=std::time::Instant::now(); - let guard = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I32((t * 512) as i32), - Arg::U64(sa), - ])?; - stage.run( - workspace, - 0, - [(t * 512).div_ceil(256) as u32, 1, 1], - 256, - guard, - )?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - let args = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I64(prior.end as i64), - Arg::U64(self.owner.pools.table()?), - Arg::I64(4), - Arg::U64(rp[0]), - Arg::U64(rp[1]), - Arg::U64(rp[2]), - Arg::U64(rp[3]), - Arg::U64(sp[0]), - Arg::U64(sp[1]), - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::U64(hp[0]), - Arg::U64(hp[1]), - Arg::U64(hp[2]), - Arg::U64(hp[3]), - ])?; - let scales = Arguments::new(vec![ - Arg::U64(sp[2]), - Arg::U64(sp[3]), - Arg::I32(prior.end as i32), - Arg::I32(end as i32), - Arg::U64(sa), - ])?; - - self.owner.current = None; - self.owner.mapped_current = None; - stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; - stage.run(workspace, 2, [1, 1, 1], 256, scales)?; - if stage.flags()? != 0 { - return Err(Error::InvalidQ8Activation); - } - if timed{crate::command_profile::add("qsa-kv",2,"append kernels (quantize, write, scales)",started.elapsed());} - self.end=end;self.coverage.end.set(end);self.stage_table=Some(table);self.stage_addresses=Some(sp); - Ok(OriginalQsaMappedAppend{first:prior.end,rows:t,final_prefix:self.prefix()}) - } -} - -impl<'ctx> OriginalQsaMappedJournal<'ctx>{ - /// Fixed device addresses the captured verifier window binds for this layer's streamed INT8 KV: - /// (resident pools `[k_q, v_q, k_scale, v_scale]`, page table, host copy `[k_q, v_q, k_scale, v_scale]`, - /// resolver `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`, resident page count). - /// Read only: no coverage, epoch or resolver state changes. - pub(crate) fn window_kv_addresses(&self)->Result<([u64;4],u64,[u64;4],[u64;7],usize)>{ - self.validate_context(self.owner.context)?; - // The captured window launches the resolver against these slots: it must have been reset (zeroed - // page table / slot stamps) by an owner call first, exactly like the prompt paths do lazily. - if !self.resolver_ready{return Err(Error::InvalidDriverValue("Original verifier producer unavailable: qsa_resolve: the streamed KV resolver was not initialised (reset) before the window capture"))} - let table=self.owner.pools.table()?; - let r=self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?;let resolver=r.window_addresses(table)?; - Ok((self.owner.pools.addresses()?,table,self.owner.host_addresses()?,resolver,r.n_slots())) - } - /// Initialise the streamed-KV resolver if no owner call has done so yet, exactly as the first prompt append - /// does lazily (`append_resident_arena`). A ONE-token prompt runs no append before the first verifier window, - /// so the serve path calls this for every layer before the window capture. Unlike `reset` it changes neither - /// the epoch, the coverage nor the reachable end: every prefix minted before stays valid. Idempotent. - pub fn ensure_resolver(&mut self,w:&mut NativeBatchWorkspace<'ctx>)->Result<()>{ - self.validate_context(self.owner.context)?;w.validate_context(self.owner.context)?; - if self.resolver_ready{return Ok(())} - let table=self.owner.pools.table()?; - let result=self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w,table); - if result.is_err()&&self.owner.context.is_poisoned(){self.failed=true;} - result?;self.resolver_ready=true;Ok(()) - } - /// Whether the streamed-KV resolver has been initialised (the window capture requires it). - pub fn resolver_ready(&self)->bool{self.resolver_ready} - pub(crate) fn resolved_addresses(&mut self,w:&mut NativeBatchWorkspace<'ctx>,prefix:&OriginalQsaMappedPrefix,ids:&DeviceBuffer<'_>,steps:&DeviceBuffer<'_>,t:usize)->Result<([u64;4],u64,usize)>{ - self.validate_prefix(prefix)?;w.validate_context(self.owner.context)?;if !(1..=3).contains(&t){return Err(Error::InvalidQwenShape)} - let ids=checked(self.owner.context,ids,t*2051*4)?;let steps=checked(self.owner.context,steps,t*16)?; - let host=self.owner.host_addresses()?;let resident=self.owner.pools.addresses()?;let table=self.owner.pools.table()?; - if !self.resolver_ready{self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w,table)?;self.resolver_ready=true;} - let result=self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.resolve(w,table,ids,steps,t,host,resident); - if result.is_err()&&self.owner.context.is_poisoned(){self.failed=true;}result?;Ok((resident,table,prefix.end)) - } - pub(crate) fn reject_alias(&self,b:&DeviceBuffer<'_>)->Result<()>{self.owner.reject_alias(b)} - /// Resident pages (VRAM slots) of this layer's streamed KV (`--kv-resident` / 4). - pub fn resident_pages(&self)->usize{self.owner.resident_pages()} - /// `kv_stream_counters` of this layer (synchronous; the Original prints them at the end of a request). - pub fn stream_counters(&self)->Result{self.validate_context(self.owner.context)?;self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?.counters()} -} +#[path = "impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs"] +mod impl_originalqsamappedjournal_2; +#[path = "impl_originalqsamappedprefix/impl_originalqsamappedprefix_2.rs"] +mod impl_originalqsamappedprefix_2; diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs new file mode 100644 index 00000000..baf3b00e --- /dev/null +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs @@ -0,0 +1,205 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaMappedJournal (2), impl OriginalQsaMappedJournal. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaMappedJournal<'ctx> { + pub(crate) fn append_resident_arena( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>, + ) -> Result { + let t = inputs.rows(); + if inputs.first_position() != prior.next_position() { + return Err(Error::InvalidQwenShape); + } + self.validate_prefix(prior)?; + stage.validate(self.owner.context)?; + workspace.validate_context(self.owner.context)?; + if !(1..=8192).contains(&t) + || prior.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) + { + return Err(Error::InvalidQwenShape); + } + let end = prior.end + t; + let (kh, vh) = inputs.kv_spans(self.owner.context)?; + let (k, v) = (kh.qwen_address(), vh.qwen_address()); + self.owner.reject_original_span(kh, t * 512 * 4)?; + self.owner.reject_original_span(vh, t * 512 * 4)?; + stage.reject_span(kh, t * 512 * 4)?; + stage.reject_span(vh, t * 512 * 4)?; + workspace.reject_alias(kh, t * 512 * 4)?; + workspace.reject_alias(vh, t * 512 * 4)?; + if prior.end != self.end { + return Err(Error::InvalidQwenShape); + } + let table = stage.table()?; + if self.stage_table.is_some_and(|old| old != table) { + return Err(Error::InvalidQwenShape); + } + // Whole original mapped storage/staging has fixed addresses. Only new + // cells are written; preceding prefix bytes remain actual owners. + let status = stage.status()?; + status.copy_from(&[0; 4])?; + let sa = checked(self.owner.context, status, 4)?; + let rp = self.owner.pools.addresses()?; + let sp = inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address()); + if !self.resolver_ready { + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(workspace, self.owner.pools.table()?)?; + self.resolver_ready = true; + } + let hp = self.owner.host_addresses()?; + // Original kv_stage_from_host: shared arena stage belongs to another + // layer/chunk until the authoritative real mapped prefix is copied. + let stage_spans = inputs.kv_stage_spans(self.owner.context)?; + for (i, h) in stage_spans.iter().enumerate() { + self.owner.reject_original_span(*h, stage_runs()?[i])?; + } + let timed = crate::command_profile::enabled(); + let started = std::time::Instant::now(); + stage.copy_prefix(workspace, hp, stage_spans, prior.end.div_ceil(4))?; + if timed { + crate::command_profile::add("qsa-kv", 1, "stage copy_prefix (host -> arena stage)", started.elapsed()); + } + let started = std::time::Instant::now(); + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; + stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + let args = Arguments::new(vec![ + Arg::U64(k), + Arg::U64(v), + Arg::I64(prior.end as i64), + Arg::U64(self.owner.pools.table()?), + Arg::I64(4), + Arg::U64(rp[0]), + Arg::U64(rp[1]), + Arg::U64(rp[2]), + Arg::U64(rp[3]), + Arg::U64(sp[0]), + Arg::U64(sp[1]), + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::U64(hp[0]), + Arg::U64(hp[1]), + Arg::U64(hp[2]), + Arg::U64(hp[3]), + ])?; + let scales = Arguments::new(vec![ + Arg::U64(sp[2]), + Arg::U64(sp[3]), + Arg::I32(prior.end as i32), + Arg::I32(end as i32), + Arg::U64(sa), + ])?; + + self.owner.current = None; + self.owner.mapped_current = None; + stage.run(workspace, 1, [t as u32, 2, 8], 64, args)?; + stage.run(workspace, 2, [1, 1, 1], 256, scales)?; + if stage.flags()? != 0 { + return Err(Error::InvalidQ8Activation); + } + if timed { + crate::command_profile::add("qsa-kv", 2, "append kernels (quantize, write, scales)", started.elapsed()); + } + self.end = end; + self.coverage.end.set(end); + self.stage_table = Some(table); + self.stage_addresses = Some(sp); + Ok(OriginalQsaMappedAppend { first: prior.end, rows: t, final_prefix: self.prefix() }) + } +} + +impl<'ctx> OriginalQsaMappedJournal<'ctx> { + /// Fixed device addresses the captured verifier window binds for this layer's streamed INT8 KV: + /// (resident pools `[k_q, v_q, k_scale, v_scale]`, page table, host copy `[k_q, v_q, k_scale, v_scale]`, + /// resolver `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`, resident page count). + /// Read only: no coverage, epoch or resolver state changes. + pub(crate) fn window_kv_addresses(&self) -> Result<([u64; 4], u64, [u64; 4], [u64; 7], usize)> { + self.validate_context(self.owner.context)?; + // The captured window launches the resolver against these slots: it must have been reset (zeroed + // page table / slot stamps) by an owner call first, exactly like the prompt paths do lazily. + if !self.resolver_ready { + return Err(Error::InvalidDriverValue( + "Original verifier producer unavailable: qsa_resolve: the streamed KV resolver was not initialised (reset) before the window capture", + )); + } + let table = self.owner.pools.table()?; + let r = self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?; + let resolver = r.window_addresses(table)?; + Ok((self.owner.pools.addresses()?, table, self.owner.host_addresses()?, resolver, r.n_slots())) + } + /// Initialise the streamed-KV resolver if no owner call has done so yet, exactly as the first prompt append + /// does lazily (`append_resident_arena`). A ONE-token prompt runs no append before the first verifier window, + /// so the serve path calls this for every layer before the window capture. Unlike `reset` it changes neither + /// the epoch, the coverage nor the reachable end: every prefix minted before stays valid. Idempotent. + pub fn ensure_resolver(&mut self, w: &mut NativeBatchWorkspace<'ctx>) -> Result<()> { + self.validate_context(self.owner.context)?; + w.validate_context(self.owner.context)?; + if self.resolver_ready { + return Ok(()); + } + let table = self.owner.pools.table()?; + let result = self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table); + if result.is_err() && self.owner.context.is_poisoned() { + self.failed = true; + } + result?; + self.resolver_ready = true; + Ok(()) + } + /// Whether the streamed-KV resolver has been initialised (the window capture requires it). + pub fn resolver_ready(&self) -> bool { + self.resolver_ready + } + pub(crate) fn resolved_addresses( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + prefix: &OriginalQsaMappedPrefix, + ids: &DeviceBuffer<'_>, + steps: &DeviceBuffer<'_>, + t: usize, + ) -> Result<([u64; 4], u64, usize)> { + self.validate_prefix(prefix)?; + w.validate_context(self.owner.context)?; + if !(1..=3).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let ids = checked(self.owner.context, ids, t * 2051 * 4)?; + let steps = checked(self.owner.context, steps, t * 16)?; + let host = self.owner.host_addresses()?; + let resident = self.owner.pools.addresses()?; + let table = self.owner.pools.table()?; + if !self.resolver_ready { + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, table)?; + self.resolver_ready = true; + } + let result = self + .owner + .resolver + .as_mut() + .ok_or(Error::ContextPoisoned)? + .resolve(w, table, ids, steps, t, host, resident); + if result.is_err() && self.owner.context.is_poisoned() { + self.failed = true; + } + result?; + Ok((resident, table, prefix.end)) + } + pub(crate) fn reject_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { + self.owner.reject_alias(b) + } + /// Resident pages (VRAM slots) of this layer's streamed KV (`--kv-resident` / 4). + pub fn resident_pages(&self) -> usize { + self.owner.resident_pages() + } + /// `kv_stream_counters` of this layer (synchronous; the Original prints them at the end of a request). + pub fn stream_counters(&self) -> Result { + self.validate_context(self.owner.context)?; + self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?.counters() + } +} diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedprefix_2.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedprefix_2.rs new file mode 100644 index 00000000..3a0fae10 --- /dev/null +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedprefix_2.rs @@ -0,0 +1,226 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaMappedPrefix, impl OriginalQsaMappedAppend, impl QsaPromptKv, impl OriginalQsaMappedJournal. + +#[allow(unused_imports)] +use super::*; + +impl OriginalQsaMappedPrefix { + pub fn next_position(&self) -> usize { + self.end + } + pub fn owner_id(&self) -> QsaKvOwnerId { + self.origin.clone() + } + pub fn validate_retained(&self) -> Result<()> { + if self.end > crate::serving_context::geometry().cells() || self.end > self.coverage.end.get() { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } +} +impl OriginalQsaMappedAppend { + pub fn rows(&self) -> usize { + self.rows + } + pub fn first_position(&self) -> usize { + self.first + } + pub fn prefix_after(&self, row: usize) -> Result { + if row >= self.rows { + return Err(Error::InvalidQwenShape); + } + let end = self.first + row + 1; + if end > self.final_prefix.coverage.end.get() { + return Err(Error::InvalidQwenShape); + } + Ok(OriginalQsaMappedPrefix { end, ..self.final_prefix.clone() }) + } + pub fn final_prefix(&self) -> &OriginalQsaMappedPrefix { + &self.final_prefix + } +} +impl<'ctx> QsaPromptKv<'ctx> { + /// Actual fresh owner only. Existing immutable snapshot APIs are not silently + /// promoted to resident storage, nor used after this consuming handoff. + pub fn into_original_mapped_journal(self) -> Result> { + self.validate()?; + if self.current.is_some() || self.mapped_current.is_some() { + return Err(Error::InvalidQwenShape); + } + Ok(OriginalQsaMappedJournal { + owner: self, + epoch: 0, + coverage: Rc::new(Coverage { end: Cell::new(0) }), + end: 0, + stage_table: None, + stage_addresses: None, + resolver_ready: false, + failed: false, + }) + } +} +impl<'ctx> OriginalQsaMappedJournal<'ctx> { + pub fn owner_id(&self) -> QsaKvOwnerId { + self.owner.owner_id() + } + pub fn allocated_bytes(&self) -> usize { + self.owner.allocated_bytes() + } + pub fn mapped_host_bytes(&self) -> usize { + self.owner.pinned_host_bytes() + } + pub fn next_position(&self) -> usize { + self.end + } + pub fn is_failed(&self) -> bool { + self.failed || self.owner.is_failed() + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.owner.validate_context(c)?; + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + Ok(()) + } + pub fn empty_prefix(&self) -> Result { + self.validate_context(self.owner.context)?; + if self.end != 0 { + return Err(Error::InvalidQwenShape); + } + Ok(self.prefix()) + } + pub(in super::super) fn prefix(&self) -> OriginalQsaMappedPrefix { + OriginalQsaMappedPrefix { + origin: self.owner.owner_id(), + epoch: self.epoch, + coverage: self.coverage.clone(), + end: self.end, + } + } + /// The prefix currently reachable through this journal (its committed end), for session lineage after a + /// verifier accepted-prefix commit. The journal is the sole authority; this mints no append or copy. + pub fn current_prefix(&self) -> Result { + self.validate_context(self.owner.context)?; + Ok(self.prefix()) + } + pub fn validate_prefix(&self, p: &OriginalQsaMappedPrefix) -> Result<()> { + self.validate_context(self.owner.context)?; + if !p.origin.same_owner(&self.owner.owner_id()) + || p.epoch != self.epoch + || p.end > p.coverage.end.get() + || p.end > self.end + || p.end > crate::serving_context::geometry().cells() + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn rollback(&mut self, w: &mut NativeBatchWorkspace<'ctx>, p: &OriginalQsaMappedPrefix) -> Result<()> { + self.validate_prefix(p)?; + w.validate_context(self.owner.context)?; + // Every producer has drained before coverage changes. Positional rejected + // cells remain initialized but become unreachable through genuine bounds. + self.owner.context.synchronize().map_err(|e| { + self.failed = true; + e + })?; + // Original commit/rewind changes reachable end only. Future cached cells + // are excluded by the actual prefix bound; the next real append rewrites + // its exact cell in both mapped and resident pools. No extra clock reset. + self.coverage.end.set(self.coverage.end.get().min(p.end)); + self.coverage = Rc::new(Coverage { end: Cell::new(p.end) }); + self.end = p.end; + Ok(()) + } + pub fn accept_prefix( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + batch: &OriginalQsaMappedAppend, + accepted: usize, + ) -> Result { + if accepted > batch.rows || self.end != batch.first + batch.rows { + return Err(Error::InvalidQwenShape); + } + self.validate_prefix(&batch.final_prefix)?; + let p = OriginalQsaMappedPrefix { end: batch.first + accepted, ..batch.final_prefix.clone() }; + self.rollback(w, &p)?; + Ok(self.prefix()) + } + pub fn reset(&mut self, w: &mut NativeBatchWorkspace<'ctx>) -> Result { + self.validate_context(self.owner.context)?; + let epoch = self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?; + w.validate_context(self.owner.context)?; + self.owner.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, self.owner.pools.table()?)?; + self.coverage.end.set(0); + self.coverage = Rc::new(Coverage { end: Cell::new(0) }); + self.epoch = epoch; + self.end = 0; + self.stage_table = None; + self.stage_addresses = None; + self.resolver_ready = true; + Ok(self.prefix()) + } + /// Host publication of the K/V rows a verifier window appended on the GPU (`mtp_original_append` writes the resident pool and + /// the host copy per row): the reachable end moves from `position` to `position + keep`. Rows past `keep` stay initialised but + /// unreachable, as after `rollback`. Only the accepted-prefix commit calls this, after its commit graph drained. + pub(crate) fn publish_window_rows(&mut self, position: usize, keep: usize) -> Result<()> { + self.validate_context(self.owner.context)?; + let end = position.checked_add(keep).ok_or(Error::InvalidSize)?; + if keep == 0 || self.end != position || end > crate::serving_context::geometry().cells() { + return Err(Error::InvalidQwenShape); + } + self.end = end; + self.coverage.end.set(end); + Ok(()) + } + pub(crate) fn reject_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { + self.owner.reject_original_span(h, n) + } + pub(crate) fn completed_addresses( + &self, + stage: &OriginalQsaResidentTransport<'ctx>, + p: &OriginalQsaMappedPrefix, + inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>, + ) -> Result<([u64; 4], u64, usize)> { + self.validate_prefix(p)?; + stage.validate(self.owner.context)?; + let table = stage.table()?; + if self.stage_table != Some(table) + || self.stage_addresses != Some(inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address())) + { + return Err(Error::InvalidQwenShape); + } + Ok((inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address()), table, p.end)) + } + pub fn close(self) -> Result<()> { + self.owner.close() + } + /// Start the KV prefix copy of the layer that is about to run on a side stream (`LELEKA_PREFILL_QSA_PREFETCH`, see `OriginalQsaResidentTransport::begin_prefix`): + /// the same copy `append_resident_arena` makes, from the same host mirror into the same stage spans, started before the layer's projections and indexer. + /// Nothing changes when the switch is off. `read` is the layer's read lease; `prior` the prefix `append_resident_arena` will be given. + pub fn begin_stage_prefix( + &self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + read: &OriginalDeviceGrRead<'_, '_, 'ctx>, + ) -> Result<()> { + if !OriginalQsaResidentTransport::prefetch_enabled() { + return Ok(()); + } + self.validate_prefix(prior)?; + stage.validate(self.owner.context)?; + workspace.validate_context(self.owner.context)?; + if !read.context_matches(self.owner.context) { + return Err(Error::ContextMismatch); + } + if prior.end != self.end { + return Err(Error::InvalidQwenShape); + } + let stage_spans = crate::qsa_prompt_index::kv_stage_spans_of(read, read.rows())?; + for (i, h) in stage_spans.iter().enumerate() { + self.owner.reject_original_span(*h, stage_runs()?[i])?; + } + let hp = self.owner.host_addresses()?; + stage.begin_prefix(workspace, hp, stage_spans, prior.end.div_ceil(4)) + } +} diff --git a/crates/cuda-driver/src/qsa_native_batch.rs b/crates/cuda-driver/src/qsa_native_batch.rs index 0988c53a..79d8a78c 100644 --- a/crates/cuda-driver/src/qsa_native_batch.rs +++ b/crates/cuda-driver/src/qsa_native_batch.rs @@ -1,246 +1,48 @@ //! Closed Original prompt K/V/Q and index projections; no decode substitution. //! Registration/export and sealed assets are owned by Root integration. use super::*; -use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule}; use crate::NativeBatchWorkspace; +use crate::ple_batch_ffi::{BatchArg as A, KernelArguments, KernelModule}; const PTX: &[u8] = include_bytes!("qsa_native_batch.ptx"); // Root binds the exact pinned group32 native dequant asset after source integration. const DEQUANT_PTX: Option<&[u8]> = Some(concat!(include_str!("offline_native_dequant_f16.ptx"), "\0").as_bytes()); const RESERVE: usize = 128 * 1024 * 1024; -const SIZES: [usize; 8] = [67108864, 64*6144*4, 64*6144*4, - 64*6144*2, 64*2560*2, 64*2560*2, 64*12288*4, 12]; -pub const QSA_NATIVE_BATCH_BYTES: usize = 67108864 + 64*(6144*4*2+6144*2+2560*2*2+12288*4)+12; +const SIZES: [usize; 8] = + [67108864, 64 * 6144 * 4, 64 * 6144 * 4, 64 * 6144 * 2, 64 * 2560 * 2, 64 * 2560 * 2, 64 * 12288 * 4, 12]; +pub const QSA_NATIVE_BATCH_BYTES: usize = 67108864 + 64 * (6144 * 4 * 2 + 6144 * 2 + 2560 * 2 * 2 + 12288 * 4) + 12; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum QsaNativeKind { Q4K, Q5K, Q6K, Iq4Xs } -impl QsaNativeKind { - fn entry(self)->usize {match self {Self::Q4K=>0,Self::Q5K=>1,Self::Q6K=>2,Self::Iq4Xs=>3}} - fn block(self)->usize { match self { Self::Q4K=>144,Self::Q5K=>176,Self::Q6K=>210,Self::Iq4Xs=>136 } } +pub enum QsaNativeKind { + Q4K, + Q5K, + Q6K, + Iq4Xs, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum QsaNativePacking { HighOnly, HighAndLow } +pub enum QsaNativePacking { + HighOnly, + HighAndLow, +} pub struct QsaNativeProjections { - pub k: Box<[f32]>, pub v: Box<[f32]>, pub q: Box<[f32]>, - pub index_k: Box<[f32]>, pub index_q: Box<[f32]>, + pub k: Box<[f32]>, + pub v: Box<[f32]>, + pub q: Box<[f32]>, + pub index_k: Box<[f32]>, + pub index_q: Box<[f32]>, } pub struct QsaNativeBatchWorkspace<'ctx> { - capacity: usize, sizes: [usize;8], - context: &'ctx Context<'ctx>, buffers: [Option>;8], - packing: QsaNativePacking, module: Option, dequant: Option, - scalars: Box<[f32;3]>, failed: bool, -} -impl Context<'_> { - pub fn qsa_native_batch_workspace(&self, packing:QsaNativePacking)->Result> { - QsaNativeBatchWorkspace::new(self,packing) - } - pub fn qsa_native_batch_workspace_for_prompt(&self, packing:QsaNativePacking, capacity:usize)->Result> { - QsaNativeBatchWorkspace::new_capacity(self,packing,capacity) - } -} -fn encoded(values:&[f32])->Result> { - let mut bytes=Vec::new(); - bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::HostAllocation)?) - .map_err(|_|Error::HostAllocation)?; - bytes.extend(values.iter().flat_map(|v|v.to_le_bytes())); Ok(bytes) -} -impl<'ctx> QsaNativeBatchWorkspace<'ctx> { - fn new(context:&'ctx Context<'ctx>,packing:QsaNativePacking)->Result { - Self::new_capacity(context,packing,64) - } - fn new_capacity(context:&'ctx Context<'ctx>,packing:QsaNativePacking,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - let mut sizes=SIZES; for size in &mut sizes[1..7] {*size=(*size/64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;} - // Source-only asset refuses before allocations; no fake dequant producer. - let dequant_ptx=DEQUANT_PTX.ok_or(Error::InvalidDriverValue("QSA native dequant unsealed"))?; - if PTX.starts_with(b"// UNSEALED") { return Err(Error::InvalidDriverValue("QSA native asset unsealed")); } - if context.is_poisoned() { return Err(Error::ContextPoisoned); } - let required=sizes.iter().try_fold(0usize,|sum,n|sum.checked_add(*n).ok_or(Error::BudgetExceeded))?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(required).is_none_or(|n|n>context.budget_bytes()) - || context.memory_info()?.0Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} - Ok(67108864+capacity*(6144*4*2+6144*2+2560*2*2+12288*4)+12) - } - pub fn capacity(&self)->usize {self.capacity} - pub fn allocated_bytes(&self)->usize {self.buffers.iter().flatten().map(DeviceBuffer::len).sum()} - pub fn is_failed(&self)->bool {self.failed||self.context.is_poisoned()} - fn handle(&self,slot:usize,bytes:usize)->Result { - if self.is_failed() {return Err(Error::ContextPoisoned);} - let b=self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(b.context,self.context)||b.len()!=self.sizes[slot]||bytes==0||bytes>b.len() { - return Err(Error::InvalidQwenShape); - } - b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(),0,bytes) - } - fn admit(&self,t:usize,weights:&[&DeviceBuffer<'_>],ws:&NativeBatchWorkspace<'_>)->Result<()> { - if !(1..=self.capacity).contains(&t) {return Err(Error::InvalidQwenShape);} - ws.validate_context(self.context)?; - for (i,b) in self.buffers.iter().enumerate() { - let b=b.as_ref().ok_or(Error::ContextPoisoned)?; let h=self.handle(i,b.len())?; - ws.reject_alias(h,b.len())?; - for other in self.buffers[..i].iter().flatten() { - if h.overlaps(b.len(),other.handle.ok_or(Error::ContextPoisoned)?,other.len()) {return Err(Error::OutputAliasesInput);} - } - for w in weights { - if !std::ptr::eq(w.context,self.context) {return Err(Error::ContextMismatch);} - let wh=w.handle.ok_or(Error::ContextPoisoned)?; - if h.overlaps(b.len(),wh,w.len()) {return Err(Error::OutputAliasesInput);} - ws.reject_alias(wh,w.len())?; - } - } Ok(()) - } - fn weight(&self,w:&DeviceBuffer<'_>,n:usize,k:usize,kind:Option)->Result { - let bytes=match kind {Some(kind)=>n*(k/256)*kind.block(),None=>n*k*2}; - if !std::ptr::eq(w.context,self.context) {return Err(Error::ContextMismatch);} - if w.len()!=bytes {return Err(Error::InvalidQwenShape);} - let h=w.handle.ok_or(Error::ContextPoisoned)?; h.validate_projection_extent(bytes,2)?; Ok(h) - } - fn upload(&mut self,slot:usize,values:&[f32])->Result<()> { - if values.iter().any(|v|!v.is_finite()) {return Err(Error::InvalidDriverValue("QSA native finite input"));} - let result=self.buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&encoded(values)?); - if result.is_err() {self.failed=true;} result - } - fn download(&mut self,t:usize,n:usize)->Result> { - let size=t*n*4;let handle=self.handle(6,size)?; - let mut bytes=Vec::new();bytes.try_reserve_exact(size).map_err(|_|Error::HostAllocation)?; - bytes.resize(size,0); - let guard=self.context.enter()?; - let copy=self.context.driver.api.copy_to(handle,&mut bytes); - let sync=self.context.driver.api.synchronize();let pop=guard.finish(); - if copy.is_err()||sync.is_err()||pop.is_err() {self.failed=true;} - if sync.is_err()||pop.is_err() { - self.context.poison();self.context.retain_driver();std::mem::forget(bytes); - return combine(combine(copy,sync),pop).map(|()| unreachable!("uncertain readback remains primary")); - } - combine(combine(copy,sync),pop)?; - let mut values=Vec::new(); values.try_reserve_exact(t*n).map_err(|_|Error::HostAllocation)?; - values.extend(bytes.as_chunks::<4>().0.iter().map(|v|f32::from_le_bytes(*v))); - if values.iter().any(|v|!v.is_finite()) {return Err(Error::NonFiniteMmqOutput("QSA native projection"));} - Ok(values.into_boxed_slice()) - } - #[allow(clippy::too_many_arguments)] // Closed role shapes, not arbitrary GEMM. - fn project(&mut self,t:usize,n:usize,k:usize,weight:ffi::BufferHandle,kind:Option, - out_gate:bool,ws:&mut NativeBatchWorkspace<'ctx>)->Result> { - let blas=ws.blas()?; let context=self.context; - let x=self.handle(1,t*k*4)?; let packed=self.handle(3,t*k*2)?; - let high=self.handle(4,t*2560*2)?; let low=self.handle(5,t*2560*2)?; - let y=self.handle(6,t*n*4)?; let scratch=self.handle(0,n*k*2)?; - let status=self.handle(7,12)?; - let mut pack=KernelArguments::new(vec![A::Address(x),A::Address(packed),A::Address(high),A::Address(low),A::I64((t*k)as i64)]); - let mut gate=KernelArguments::new(vec![A::Address(x),A::Address(self.handle(2,t*6144*4)?),A::Address(packed),A::I64((t*6144)as i64)]); - let mut input_scan=KernelArguments::new(vec![A::Address(if kind.is_some(){packed}else{high}),A::Address(status),A::I64((t*k)as i64),A::U32(0),A::U32(if kind.is_some(){0x7c00}else{0x7f80})]); - let mut low_scan=KernelArguments::new(vec![A::Address(low),A::Address(status),A::I64((t*k)as i64),A::U32(0),A::U32(0x7f80)]); - // Exact pinned generic group32 decoder contract; Root binds the asset. - let mut dequant=KernelArguments::new(vec![A::Address(weight),A::I64((k/256*kind.map_or(0,QsaNativeKind::block))as i64),A::I64(0),A::I64(n as i64),A::I64((k/32)as i64),A::Address(scratch)]); - let mut weight_scan=KernelArguments::new(vec![A::Address(scratch),A::Address(status),A::I64((n*k)as i64),A::U32(1),A::U32(0x7c00)]); - let zero=vec![0u8;12]; let mut flags=vec![0u8;12]; - let guard=context.enter()?; - let operation=(|| { - context.driver.api.copy_from(status,&zero)?; - // Pageable legacy H2D/reset must complete before nonblocking vendor stream. - context.driver.api.synchronize()?; - let module=self.module.as_ref().ok_or(Error::ContextPoisoned)?; - module.launch(if out_gate{1}else{0},(t*k).div_ceil(256)as u32,256,blas.stream(),if out_gate{&mut gate}else{&mut pack})?; - module.launch(2,(t*k).div_ceil(256)as u32,256,blas.stream(),&mut input_scan)?; - if kind.is_none()&&self.packing==QsaNativePacking::HighAndLow { - module.launch(2,(t*k).div_ceil(256)as u32,256,blas.stream(),&mut low_scan)?; - } - let [alpha,beta0,beta1]=self.scalars.as_ref(); - if kind.is_some() { - self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch(kind.ok_or(Error::UnsupportedProjection)?.entry(),(n*k/32).div_ceil(256)as u32,256,blas.stream(),&mut dequant)?; - module.launch(2,(n*k).div_ceil(256)as u32,256,blas.stream(),&mut weight_scan)?; - blas.gemm_f16(packed,scratch,y,t as i32,n as i32,k as i32,alpha,beta0)?; - } else { - blas.gemm_bf16(high,weight,y,t as i32,n as i32,k as i32,alpha,beta0)?; - if self.packing==QsaNativePacking::HighAndLow {blas.gemm_bf16(low,weight,y,t as i32,n as i32,k as i32,alpha,beta1)?;} - } Ok(()) - })(); - let sync=blas.synchronize(); - let read=if sync.is_ok(){context.driver.api.copy_to(status,&mut flags)}else{Ok(())}; - let pop=guard.finish(); - if operation.is_err()||sync.is_err()||read.is_err()||pop.is_err() { - self.failed=true; ws.mark_failed(); context.poison();context.retain_driver(); - } - if sync.is_err()||read.is_err()||pop.is_err() { - std::mem::forget((pack,gate,input_scan,low_scan,dequant,weight_scan,zero,flags)); - return combine(combine(combine(operation,sync),read),pop).map(|()| unreachable!("failed drain remains primary")); - } - if operation.is_err() { - // A failed legacy upload may retain pageable staging even when the - // independent vendor stream drained. Preserve primary and operands. - std::mem::forget((pack,gate,input_scan,low_scan,dequant,weight_scan,zero,flags)); - return combine(combine(combine(operation,sync),read),pop).map(|()| unreachable!("failed command remains primary")); - } - combine(combine(combine(operation,sync),read),pop)?; - if flags[8..].iter().any(|v|*v!=0) {self.failed=true;return Err(Error::InvalidDriverValue("QSA native unused finite status"));} - if flags.as_chunks::<4>().0.iter().any(|v|u32::from_le_bytes(*v)>1) { - self.failed=true; return Err(Error::InvalidDriverValue("QSA native unknown finite status")); - } - if flags[..8].iter().any(|v|*v!=0) {return Err(Error::NonFiniteMmqOutput("QSA native packed input/weight"));} - self.download(t,n) - } - pub fn project_inputs(&mut self,t:usize,mixed:&[f32],weights:[&DeviceBuffer<'_>;5], - kinds:[QsaNativeKind;3],ws:&mut NativeBatchWorkspace<'ctx>)->Result { - self.admit(t,&weights,ws)?; - if mixed.len()!=t*2560 {return Err(Error::InvalidQwenShape);} - if !matches!(kinds[0],QsaNativeKind::Q6K|QsaNativeKind::Iq4Xs) - || !matches!(kinds[1],QsaNativeKind::Q5K|QsaNativeKind::Q6K) {return Err(Error::UnsupportedProjection);} - let widths=[512,512,12288,128,512]; let mut handles=[self.handle(0,2)?;5]; - for i in 0..5 {handles[i]=self.weight(weights[i],widths[i],2560,if i<3{Some(kinds[i])}else{None})?;} - self.upload(1,mixed)?; - let k=self.project(t,512,2560,handles[0],Some(kinds[0]),false,ws)?; - let v=self.project(t,512,2560,handles[1],Some(kinds[1]),false,ws)?; - let q=self.project(t,12288,2560,handles[2],Some(kinds[2]),false,ws)?; - let index_k=self.project(t,128,2560,handles[3],None,false,ws)?; - let index_q=self.project(t,512,2560,handles[4],None,false,ws)?; - Ok(QsaNativeProjections{k,v,q,index_k,index_q}) - } - pub fn project_out(&mut self,t:usize,attended:&[f32],gates:&[f32],weight:&DeviceBuffer<'_>, - kind:QsaNativeKind,ws:&mut NativeBatchWorkspace<'ctx>)->Result> { - self.admit(t,&[weight],ws)?; - if attended.len()!=t*6144||gates.len()!=t*6144 {return Err(Error::InvalidQwenShape);} - if !matches!(kind,QsaNativeKind::Q4K|QsaNativeKind::Q6K) {return Err(Error::UnsupportedProjection);} - let w=self.weight(weight,2560,6144,Some(kind))?; - self.upload(1,attended)?;self.upload(2,gates)?; - self.project(t,2560,6144,w,Some(kind),true,ws) - } - pub fn close(mut self)->Result<()> {self.close_inner()} - fn close_inner(&mut self)->Result<()> { - let mut result=Ok(()); - for slot in &mut self.buffers {if let Some(b)=slot.take(){result=combine(result,b.release());}} - let guard=self.context.enter(); - if let Ok(guard)=guard { - if !self.context.is_poisoned() { - if let Some(m)=self.module.take(){result=combine(result,m.close());} - if let Some(m)=self.dequant.take(){result=combine(result,m.close());} - } else {if let Some(m)=self.module.take(){std::mem::forget(m);}if let Some(m)=self.dequant.take(){std::mem::forget(m);}} - result=combine(result,guard.finish()); - } else { - if let Some(m)=self.module.take(){std::mem::forget(m);} - if let Some(m)=self.dequant.take(){std::mem::forget(m);} - result=combine(result,Err(Error::ContextPoisoned)); - } - result - } -} -impl Drop for QsaNativeBatchWorkspace<'_> { - fn drop(&mut self) {let _=self.close_inner();} + capacity: usize, + sizes: [usize; 8], + context: &'ctx Context<'ctx>, + buffers: [Option>; 8], + packing: QsaNativePacking, + module: Option, + dequant: Option, + scalars: Box<[f32; 3]>, + failed: bool, } + +mod impl_qsanativekind; +#[allow(unused_imports)] +use impl_qsanativekind::encoded; +mod impl_qsanativebatchworkspace_2; diff --git a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs new file mode 100644 index 00000000..8fefdc76 --- /dev/null +++ b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativebatchworkspace_2.rs @@ -0,0 +1,238 @@ +//! Moved out of the parent module by STRA-338: impl QsaNativeBatchWorkspace (2), impl Drop_for_QsaNativeBatchWorkspace. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaNativeBatchWorkspace<'ctx> { + #[allow(clippy::too_many_arguments)] // Closed role shapes, not arbitrary GEMM. + pub(super) fn project( + &mut self, + t: usize, + n: usize, + k: usize, + weight: ffi::BufferHandle, + kind: Option, + out_gate: bool, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + let blas = ws.blas()?; + let context = self.context; + let x = self.handle(1, t * k * 4)?; + let packed = self.handle(3, t * k * 2)?; + let high = self.handle(4, t * 2560 * 2)?; + let low = self.handle(5, t * 2560 * 2)?; + let y = self.handle(6, t * n * 4)?; + let scratch = self.handle(0, n * k * 2)?; + let status = self.handle(7, 12)?; + let mut pack = KernelArguments::new(vec![ + A::Address(x), + A::Address(packed), + A::Address(high), + A::Address(low), + A::I64((t * k) as i64), + ]); + let mut gate = KernelArguments::new(vec![ + A::Address(x), + A::Address(self.handle(2, t * 6144 * 4)?), + A::Address(packed), + A::I64((t * 6144) as i64), + ]); + let mut input_scan = KernelArguments::new(vec![ + A::Address(if kind.is_some() { packed } else { high }), + A::Address(status), + A::I64((t * k) as i64), + A::U32(0), + A::U32(if kind.is_some() { 0x7c00 } else { 0x7f80 }), + ]); + let mut low_scan = KernelArguments::new(vec![ + A::Address(low), + A::Address(status), + A::I64((t * k) as i64), + A::U32(0), + A::U32(0x7f80), + ]); + // Exact pinned generic group32 decoder contract; Root binds the asset. + let mut dequant = KernelArguments::new(vec![ + A::Address(weight), + A::I64((k / 256 * kind.map_or(0, QsaNativeKind::block)) as i64), + A::I64(0), + A::I64(n as i64), + A::I64((k / 32) as i64), + A::Address(scratch), + ]); + let mut weight_scan = KernelArguments::new(vec![ + A::Address(scratch), + A::Address(status), + A::I64((n * k) as i64), + A::U32(1), + A::U32(0x7c00), + ]); + let zero = vec![0u8; 12]; + let mut flags = vec![0u8; 12]; + let guard = context.enter()?; + let operation = (|| { + context.driver.api.copy_from(status, &zero)?; + // Pageable legacy H2D/reset must complete before nonblocking vendor stream. + context.driver.api.synchronize()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + module.launch( + if out_gate { 1 } else { 0 }, + (t * k).div_ceil(256) as u32, + 256, + blas.stream(), + if out_gate { &mut gate } else { &mut pack }, + )?; + module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut input_scan)?; + if kind.is_none() && self.packing == QsaNativePacking::HighAndLow { + module.launch(2, (t * k).div_ceil(256) as u32, 256, blas.stream(), &mut low_scan)?; + } + let [alpha, beta0, beta1] = self.scalars.as_ref(); + if kind.is_some() { + self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( + kind.ok_or(Error::UnsupportedProjection)?.entry(), + (n * k / 32).div_ceil(256) as u32, + 256, + blas.stream(), + &mut dequant, + )?; + module.launch(2, (n * k).div_ceil(256) as u32, 256, blas.stream(), &mut weight_scan)?; + blas.gemm_f16(packed, scratch, y, t as i32, n as i32, k as i32, alpha, beta0)?; + } else { + blas.gemm_bf16(high, weight, y, t as i32, n as i32, k as i32, alpha, beta0)?; + if self.packing == QsaNativePacking::HighAndLow { + blas.gemm_bf16(low, weight, y, t as i32, n as i32, k as i32, alpha, beta1)?; + } + } + Ok(()) + })(); + let sync = blas.synchronize(); + let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + } + if sync.is_err() || read.is_err() || pop.is_err() { + std::mem::forget((pack, gate, input_scan, low_scan, dequant, weight_scan, zero, flags)); + return combine(combine(combine(operation, sync), read), pop) + .map(|()| unreachable!("failed drain remains primary")); + } + if operation.is_err() { + // A failed legacy upload may retain pageable staging even when the + // independent vendor stream drained. Preserve primary and operands. + std::mem::forget((pack, gate, input_scan, low_scan, dequant, weight_scan, zero, flags)); + return combine(combine(combine(operation, sync), read), pop) + .map(|()| unreachable!("failed command remains primary")); + } + combine(combine(combine(operation, sync), read), pop)?; + if flags[8..].iter().any(|v| *v != 0) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA native unused finite status")); + } + if flags.as_chunks::<4>().0.iter().any(|v| u32::from_le_bytes(*v) > 1) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA native unknown finite status")); + } + if flags[..8].iter().any(|v| *v != 0) { + return Err(Error::NonFiniteMmqOutput("QSA native packed input/weight")); + } + self.download(t, n) + } + pub fn project_inputs( + &mut self, + t: usize, + mixed: &[f32], + weights: [&DeviceBuffer<'_>; 5], + kinds: [QsaNativeKind; 3], + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result { + self.admit(t, &weights, ws)?; + if mixed.len() != t * 2560 { + return Err(Error::InvalidQwenShape); + } + if !matches!(kinds[0], QsaNativeKind::Q6K | QsaNativeKind::Iq4Xs) + || !matches!(kinds[1], QsaNativeKind::Q5K | QsaNativeKind::Q6K) + { + return Err(Error::UnsupportedProjection); + } + let widths = [512, 512, 12288, 128, 512]; + let mut handles = [self.handle(0, 2)?; 5]; + for i in 0..5 { + handles[i] = self.weight(weights[i], widths[i], 2560, if i < 3 { Some(kinds[i]) } else { None })?; + } + self.upload(1, mixed)?; + let k = self.project(t, 512, 2560, handles[0], Some(kinds[0]), false, ws)?; + let v = self.project(t, 512, 2560, handles[1], Some(kinds[1]), false, ws)?; + let q = self.project(t, 12288, 2560, handles[2], Some(kinds[2]), false, ws)?; + let index_k = self.project(t, 128, 2560, handles[3], None, false, ws)?; + let index_q = self.project(t, 512, 2560, handles[4], None, false, ws)?; + Ok(QsaNativeProjections { k, v, q, index_k, index_q }) + } + pub fn project_out( + &mut self, + t: usize, + attended: &[f32], + gates: &[f32], + weight: &DeviceBuffer<'_>, + kind: QsaNativeKind, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.admit(t, &[weight], ws)?; + if attended.len() != t * 6144 || gates.len() != t * 6144 { + return Err(Error::InvalidQwenShape); + } + if !matches!(kind, QsaNativeKind::Q4K | QsaNativeKind::Q6K) { + return Err(Error::UnsupportedProjection); + } + let w = self.weight(weight, 2560, 6144, Some(kind))?; + self.upload(1, attended)?; + self.upload(2, gates)?; + self.project(t, 2560, 6144, w, Some(kind), true, ws) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + for slot in &mut self.buffers { + if let Some(b) = slot.take() { + result = combine(result, b.release()); + } + } + let guard = self.context.enter(); + if let Ok(guard) = guard { + if !self.context.is_poisoned() { + if let Some(m) = self.module.take() { + result = combine(result, m.close()); + } + if let Some(m) = self.dequant.take() { + result = combine(result, m.close()); + } + } else { + if let Some(m) = self.module.take() { + std::mem::forget(m); + } + if let Some(m) = self.dequant.take() { + std::mem::forget(m); + } + } + result = combine(result, guard.finish()); + } else { + if let Some(m) = self.module.take() { + std::mem::forget(m); + } + if let Some(m) = self.dequant.take() { + std::mem::forget(m); + } + result = combine(result, Err(Error::ContextPoisoned)); + } + result + } +} +impl Drop for QsaNativeBatchWorkspace<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs new file mode 100644 index 00000000..5a6204b1 --- /dev/null +++ b/crates/cuda-driver/src/qsa_native_batch/impl_qsanativekind.rs @@ -0,0 +1,235 @@ +//! Moved out of the parent module by STRA-338: impl QsaNativeKind, impl Context, fn encoded, impl QsaNativeBatchWorkspace. + +#[allow(unused_imports)] +use super::*; + +impl QsaNativeKind { + pub(super) fn entry(self) -> usize { + match self { + Self::Q4K => 0, + Self::Q5K => 1, + Self::Q6K => 2, + Self::Iq4Xs => 3, + } + } + pub(super) fn block(self) -> usize { + match self { + Self::Q4K => 144, + Self::Q5K => 176, + Self::Q6K => 210, + Self::Iq4Xs => 136, + } + } +} +impl Context<'_> { + pub fn qsa_native_batch_workspace(&self, packing: QsaNativePacking) -> Result> { + QsaNativeBatchWorkspace::new(self, packing) + } + pub fn qsa_native_batch_workspace_for_prompt( + &self, + packing: QsaNativePacking, + capacity: usize, + ) -> Result> { + QsaNativeBatchWorkspace::new_capacity(self, packing, capacity) + } +} +pub(super) fn encoded(values: &[f32]) -> Result> { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::HostAllocation)?) + .map_err(|_| Error::HostAllocation)?; + bytes.extend(values.iter().flat_map(|v| v.to_le_bytes())); + Ok(bytes) +} +impl<'ctx> QsaNativeBatchWorkspace<'ctx> { + pub(super) fn new(context: &'ctx Context<'ctx>, packing: QsaNativePacking) -> Result { + Self::new_capacity(context, packing, 64) + } + pub(super) fn new_capacity( + context: &'ctx Context<'ctx>, + packing: QsaNativePacking, + capacity: usize, + ) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let mut sizes = SIZES; + for size in &mut sizes[1..7] { + *size = (*size / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + // Source-only asset refuses before allocations; no fake dequant producer. + let dequant_ptx = DEQUANT_PTX.ok_or(Error::InvalidDriverValue("QSA native dequant unsealed"))?; + if PTX.starts_with(b"// UNSEALED") { + return Err(Error::InvalidDriverValue("QSA native asset unsealed")); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let required = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + capacity, + sizes, + context, + buffers: std::array::from_fn(|_| None), + packing, + module: None, + dequant: None, + scalars: Box::new([1., 0., 1.]), + failed: false, + }; + let operation = (|| { + for (i, n) in sizes.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(n)?); + } + let guard = context.enter()?; + let loaded = (|| { + owner.module = Some(KernelModule::load(PTX, &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"])?); + owner.dequant = Some(KernelModule::load( + dequant_ptx, + &[ + c"leleka_native_dequant_f16_q4_k", + c"leleka_native_dequant_f16_q5_k", + c"leleka_native_dequant_f16_q6_k", + c"leleka_native_dequant_f16_iq4_xs", + ], + )?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + combine(loaded, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(primary) = operation { + let _ = owner.close(); + return Err(primary); + } + Ok(owner) + } + pub fn prompt_device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + Ok(67108864 + capacity * (6144 * 4 * 2 + 6144 * 2 + 2560 * 2 * 2 + 12288 * 4) + 12) + } + pub fn capacity(&self) -> usize { + self.capacity + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(super) fn handle(&self, slot: usize, bytes: usize) -> Result { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + let b = self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(b.context, self.context) || b.len() != self.sizes[slot] || bytes == 0 || bytes > b.len() { + return Err(Error::InvalidQwenShape); + } + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), 0, bytes) + } + pub(super) fn admit(&self, t: usize, weights: &[&DeviceBuffer<'_>], ws: &NativeBatchWorkspace<'_>) -> Result<()> { + if !(1..=self.capacity).contains(&t) { + return Err(Error::InvalidQwenShape); + } + ws.validate_context(self.context)?; + for (i, b) in self.buffers.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + let h = self.handle(i, b.len())?; + ws.reject_alias(h, b.len())?; + for other in self.buffers[..i].iter().flatten() { + if h.overlaps(b.len(), other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { + return Err(Error::OutputAliasesInput); + } + } + for w in weights { + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + let wh = w.handle.ok_or(Error::ContextPoisoned)?; + if h.overlaps(b.len(), wh, w.len()) { + return Err(Error::OutputAliasesInput); + } + ws.reject_alias(wh, w.len())?; + } + } + Ok(()) + } + pub(super) fn weight( + &self, + w: &DeviceBuffer<'_>, + n: usize, + k: usize, + kind: Option, + ) -> Result { + let bytes = match kind { + Some(kind) => n * (k / 256) * kind.block(), + None => n * k * 2, + }; + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + if w.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let h = w.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 2)?; + Ok(h) + } + pub(super) fn upload(&mut self, slot: usize, values: &[f32]) -> Result<()> { + if values.iter().any(|v| !v.is_finite()) { + return Err(Error::InvalidDriverValue("QSA native finite input")); + } + let result = self.buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &encoded(values)?); + if result.is_err() { + self.failed = true; + } + result + } + pub(super) fn download(&mut self, t: usize, n: usize) -> Result> { + let size = t * n * 4; + let handle = self.handle(6, size)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(size).map_err(|_| Error::HostAllocation)?; + bytes.resize(size, 0); + let guard = self.context.enter()?; + let copy = self.context.driver.api.copy_to(handle, &mut bytes); + let sync = self.context.driver.api.synchronize(); + let pop = guard.finish(); + if copy.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + } + if sync.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!("uncertain readback remains primary")); + } + combine(combine(copy, sync), pop)?; + let mut values = Vec::new(); + values.try_reserve_exact(t * n).map_err(|_| Error::HostAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|v| f32::from_le_bytes(*v))); + if values.iter().any(|v| !v.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA native projection")); + } + Ok(values.into_boxed_slice()) + } +} diff --git a/crates/cuda-driver/src/qsa_native_decode.rs b/crates/cuda-driver/src/qsa_native_decode.rs index 2575bb62..ffe72e8a 100644 --- a/crates/cuda-driver/src/qsa_native_decode.rs +++ b/crates/cuda-driver/src/qsa_native_decode.rs @@ -30,11 +30,7 @@ impl<'ctx> QsaNativeDecode<'ctx> { return Err(Error::ContextPoisoned); } let n = QSA_NATIVE_DECODE_BYTES + 128 * 1024 * 1024; - if c.allocated_bytes() - .checked_add(n) - .is_none_or(|x| x > c.budget) - || c.memory_info()?.0 < n - { + if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { return Err(Error::BudgetExceeded); } let g = c.enter().map_err(|error| { @@ -63,14 +59,7 @@ impl<'ctx> QsaNativeDecode<'ctx> { } Err(e) => return combine(Err(e), pop), }; - let mut o = Self { - context: c, - output: None, - scratch: None, - status: None, - module: Some(m), - failed: false, - }; + let mut o = Self { context: c, output: None, scratch: None, status: None, module: Some(m), failed: false }; let r = (|| { o.output = Some(c.allocate(1_572_864)?); o.scratch = Some(c.allocate(52_326_400)?); @@ -97,32 +86,14 @@ impl<'ctx> QsaNativeDecode<'ctx> { if self.is_failed() || self.module.is_none() { return Err(Error::ContextPoisoned); } - checked( - self.context, - self.output.as_ref().ok_or(Error::ContextPoisoned)?, - 1_572_864, - )?; - checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - checked( - self.context, - self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, - 52_326_400, - )?; + checked(self.context, self.output.as_ref().ok_or(Error::ContextPoisoned)?, 1_572_864)?; + checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + checked(self.context, self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, 52_326_400)?; Ok(()) } fn flags(&self) -> Result { - let b = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .copy_to_owned(4)?; - Ok(u32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )) + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; + Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } fn run( &mut self, @@ -136,9 +107,9 @@ impl<'ctx> QsaNativeDecode<'ctx> { self.validate()?; w.validate_context(self.context)?; let g = match self.context.enter() { - Ok(guard)=>guard, - Err(error)=>{ - self.failed=true; + Ok(guard) => guard, + Err(error) => { + self.failed = true; w.mark_failed(); self.context.poison(); self.context.retain_driver(); @@ -192,12 +163,7 @@ impl<'ctx> QsaNativeDecode<'ctx> { for b in [q, ids, steps] { kv.reject_alias(b)?; w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?; - for own in self - .output - .iter() - .chain(self.status.iter()) - .chain(self.scratch.iter()) - { + for own in self.output.iter().chain(self.status.iter()).chain(self.scratch.iter()) { if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( own.bytes, b.handle.ok_or(Error::ContextPoisoned)?, @@ -221,22 +187,10 @@ impl<'ctx> QsaNativeDecode<'ctx> { } } let end = snapshot.next_position(); - self.status - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&[0; 4])?; - let status = checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - let out = self - .output - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); + self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; + let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + let out = + self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), @@ -259,12 +213,8 @@ impl<'ctx> QsaNativeDecode<'ctx> { let scratch = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; let handle = scratch.handle.ok_or(Error::ContextPoisoned)?; let pa = handle.qwen_address(); - let pm = handle - .checked_subspan(scratch.bytes, 811008, 3168)? - .qwen_address(); - let pl = handle - .checked_subspan(scratch.bytes, 814176, 3168)? - .qwen_address(); + let pm = handle.checked_subspan(scratch.bytes, 811008, 3168)?.qwen_address(); + let pl = handle.checked_subspan(scratch.bytes, 814176, 3168)?.qwen_address(); // Each query owns817600B; internal checked offsets mirror original single scratch layout. let args = Arguments::new(vec![ Arg::U64(qh), @@ -295,21 +245,12 @@ impl<'ctx> QsaNativeDecode<'ctx> { Arg::I64(204400), ])?; self.run(w, 2, [24, t as u32, 1], 256, 0, merge)?; - let scan = Arguments::new(vec![ - Arg::U64(out), - Arg::I32((t * 6144) as i32), - Arg::U64(status), - ])?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run(w, 3, [64, 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } - Ok(QsaNativeDecodeCompletion { - owner: self, - _kv: kv, - _snapshot: snapshot, - t, - }) + Ok(QsaNativeDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t }) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -356,40 +297,25 @@ impl QsaNativeDecodeCompletion<'_, '_> { } /// The bank is a real whole64-row allocation; active rows are separately checked. /// No fabricated DeviceBuffer or public raw subspan is returned. - pub fn with_output( - &self, - f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result, - ) -> Result { + pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result) -> Result { self.owner.validate()?; - f( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - self.t, - ) + f(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, self.t) } pub fn into_values(self) -> Result> { self.owner.validate()?; let mut all = Vec::new(); - all.try_reserve_exact(self.t * 6144 * 4) - .map_err(|_| Error::HostAllocation)?; + all.try_reserve_exact(self.t * 6144 * 4).map_err(|_| Error::HostAllocation)?; all.resize(self.t * 6144 * 4, 0); - crate::qsa_prompt_kv::read_range( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - 0, - &mut all, - )?; + crate::qsa_prompt_kv::read_range(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, 0, &mut all)?; let mut values = Vec::new(); - values - .try_reserve_exact(self.t * 6144) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(self.t * 6144).map_err(|_| Error::HostAllocation)?; for b in all[..self.t * 6144 * 4].chunks_exact(4) { - values.push(f32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )); + values.push(f32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)); } Ok(values.into_boxed_slice()) } } -#[path="qsa_resident_decode.rs"] +#[path = "qsa_resident_decode.rs"] mod resident_decode; pub use resident_decode::OriginalQsaResidentDecodeCompletion; diff --git a/crates/cuda-driver/src/qsa_native_gate.rs b/crates/cuda-driver/src/qsa_native_gate.rs index 19fbecdc..35359527 100644 --- a/crates/cuda-driver/src/qsa_native_gate.rs +++ b/crates/cuda-driver/src/qsa_native_gate.rs @@ -21,10 +21,7 @@ impl<'ctx> QsaNativeGate<'ctx> { if context.is_poisoned() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(RESERVE) - .is_none_or(|n| n > context.budget_bytes()) + if context.allocated_bytes().checked_add(RESERVE).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < RESERVE { return Err(Error::BudgetExceeded); @@ -37,10 +34,7 @@ impl<'ctx> QsaNativeGate<'ctx> { return Err(error); } }; - let loaded = Module::load( - include_bytes!("qsa_native_gate.ptx"), - &[c"leleka_qsa_native_gate"], - ); + let loaded = Module::load(include_bytes!("qsa_native_gate.ptx"), &[c"leleka_qsa_native_gate"]); let pop = guard.finish(); let module = match loaded { Ok(module) => { @@ -60,11 +54,7 @@ impl<'ctx> QsaNativeGate<'ctx> { return combine(Err(error), pop); } }; - let owner = Self { - context, - module: Some(module), - failed: false, - }; + let owner = Self { context, module: Some(module), failed: false }; if context.memory_info()?.0 < RESERVE { return combine(Err(Error::BudgetExceeded), owner.close()); } diff --git a/crates/cuda-driver/src/qsa_prompt_attention.rs b/crates/cuda-driver/src/qsa_prompt_attention.rs index fa46dce4..7a057a8f 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention.rs @@ -1,10 +1,10 @@ //! Literal Original selected INT8 v2 MMA/exp2 prompt attention, admitted T1..8192. //! Completion attests real full scans and a drained actual stream, not row provenance. use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module}; -use crate::qsa_prompt_kv::{QsaKvSnapshot, QsaPromptKv, QsaPromptStage, checked}; use crate::qsa_prompt_attention_select::{ DeviceCaps, PoolPresence, PromptAttnKernel, SelectSwitches, Shapes, VARIANT_ENTRIES, select, }; +use crate::qsa_prompt_kv::{QsaKvSnapshot, QsaPromptKv, QsaPromptStage, checked}; use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; /// Actual whole borrowed producer buffers; never a selection/finite certificate. pub struct QsaAttentionInputs<'loan, 'buffers> { @@ -36,13 +36,13 @@ pub struct QsaPromptAttentionCompletion<'loan, 'ctx> { #[path = "qsa_prompt_device_attention.rs"] mod device_attention; -#[path="qsa_resident_attention.rs"] +#[path = "qsa_resident_attention.rs"] mod resident_attention; pub use resident_attention::OriginalQsaResidentAttention; +mod impl_drop_for_qsapromptattention; mod impl_qsaattentioninputs; mod impl_qsapromptattention; -mod impl_drop_for_qsapromptattention; #[allow(unused_imports)] pub(crate) use impl_drop_for_qsapromptattention::guard_grid; diff --git a/crates/cuda-driver/src/qsa_prompt_attention/impl_drop_for_qsapromptattention.rs b/crates/cuda-driver/src/qsa_prompt_attention/impl_drop_for_qsapromptattention.rs index 3ecc781e..074b7c46 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/impl_drop_for_qsapromptattention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/impl_drop_for_qsapromptattention.rs @@ -14,35 +14,20 @@ impl QsaPromptAttentionCompletion<'_, '_> { } /// The bank is a real whole admitted-capacity allocation; active rows are separately checked. /// No fabricated DeviceBuffer or public raw subspan is returned. - pub fn with_output( - &self, - f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result, - ) -> Result { + pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result) -> Result { self.owner.validate()?; - f( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - self.t, - ) + f(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, self.t) } pub fn into_values(self) -> Result> { self.owner.validate()?; let mut all = Vec::new(); - all.try_reserve_exact(self.t * 6144 * 4) - .map_err(|_| Error::HostAllocation)?; + all.try_reserve_exact(self.t * 6144 * 4).map_err(|_| Error::HostAllocation)?; all.resize(self.t * 6144 * 4, 0); - crate::qsa_prompt_kv::read_range( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - 0, - &mut all, - )?; + crate::qsa_prompt_kv::read_range(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, 0, &mut all)?; let mut values = Vec::new(); - values - .try_reserve_exact(self.t * 6144) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(self.t * 6144).map_err(|_| Error::HostAllocation)?; for b in all[..self.t * 6144 * 4].chunks_exact(4) { - values.push(f32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )); + values.push(f32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)); } Ok(values.into_boxed_slice()) } diff --git a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsaattentioninputs.rs b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsaattentioninputs.rs index 005aca69..677f6ceb 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsaattentioninputs.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsaattentioninputs.rs @@ -23,7 +23,7 @@ impl Context<'_> { pub fn qsa_prompt_attention(&self) -> Result> { QsaPromptAttention::new(self) } - pub fn qsa_prompt_attention_for_capacity(&self,capacity:usize)->Result> { - QsaPromptAttention::new_capacity(self,capacity) + pub fn qsa_prompt_attention_for_capacity(&self, capacity: usize) -> Result> { + QsaPromptAttention::new_capacity(self, capacity) } } diff --git a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs index 87213fde..88f10cc9 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention/impl_qsapromptattention.rs @@ -5,30 +5,24 @@ use super::*; impl<'ctx> QsaPromptAttention<'ctx> { pub(super) fn new(c: &'ctx Context<'ctx>) -> Result { - Self::new_capacity(c,64) + Self::new_capacity(c, 64) } - pub(super) fn new_capacity(c:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} + pub(super) fn new_capacity(c: &'ctx Context<'ctx>, capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } if c.is_poisoned() { return Err(Error::ContextPoisoned); } - let output_bytes=capacity.checked_mul(6144*4).ok_or(Error::BudgetExceeded)?; - let n = output_bytes.checked_add(4+128*1024*1024).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(n) - .is_none_or(|x| x > c.budget) - || c.memory_info()?.0 < n - { + let output_bytes = capacity.checked_mul(6144 * 4).ok_or(Error::BudgetExceeded)?; + let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { return Err(Error::BudgetExceeded); } let g = c.enter()?; let load = Module::load( include_bytes!("../qsa_prompt_attention.ptx"), - &[ - c"leleka_qsa_prompt_guard", - c"leleka_qsa_prompt_attn", - c"leleka_qsa_prompt_output_guard", - ], + &[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"], ); let pop = g.finish(); let m = match load { @@ -43,7 +37,8 @@ impl<'ctx> QsaPromptAttention<'ctx> { Err(e) => return combine(Err(e), pop), }; let mut o = Self { - capacity, context: c, + capacity, + context: c, output: None, status: None, module: Some(m), @@ -64,11 +59,17 @@ impl<'ctx> QsaPromptAttention<'ctx> { } Ok(o) } - pub fn prompt_device_bytes(capacity:usize)->Result {if !(1..=8192).contains(&capacity){return Err(Error::InvalidQwenShape);}Ok(capacity*6144*4+4)} - pub fn capacity(&self)->usize {self.capacity} + pub fn prompt_device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + Ok(capacity * 6144 * 4 + 4) + } + pub fn capacity(&self) -> usize { + self.capacity + } pub fn allocated_bytes(&self) -> usize { - self.output.as_ref().map_or(0, DeviceBuffer::len) - + self.status.as_ref().map_or(0, DeviceBuffer::len) + self.output.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len) } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() @@ -77,27 +78,13 @@ impl<'ctx> QsaPromptAttention<'ctx> { if self.is_failed() || self.module.is_none() { return Err(Error::ContextPoisoned); } - checked( - self.context, - self.output.as_ref().ok_or(Error::ContextPoisoned)?, - self.capacity * 6144 * 4, - )?; - checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; + checked(self.context, self.output.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 6144 * 4)?; + checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; Ok(()) } pub(super) fn flags(&self) -> Result { - let b = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .copy_to_owned(4)?; - Ok(u32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )) + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; + Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } #[allow(clippy::too_many_arguments)] pub(super) fn run_in( @@ -117,14 +104,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { let op = dependency.and_then(|()| { (if variants { self.variants.as_ref() } else { self.module.as_ref() }) .ok_or(Error::ContextPoisoned)? - .launch( - index, - grid, - block, - shared, - w.blas()?.stream(), - &mut a, - ) + .launch(index, grid, block, shared, w.blas()?.stream(), &mut a) }); let sync = w.blas()?.synchronize(); let pop = g.finish(); @@ -185,10 +165,7 @@ impl<'ctx> QsaPromptAttention<'ctx> { return Ok(()); } let g = self.context.enter()?; - let load = Module::load( - include_bytes!("../qsa_prompt_attention_variants.ptx"), - &VARIANT_ENTRIES, - ); + let load = Module::load(include_bytes!("../qsa_prompt_attention_variants.ptx"), &VARIANT_ENTRIES); let pop = g.finish(); match load { Ok(m) => { @@ -261,22 +238,10 @@ impl<'ctx> QsaPromptAttention<'ctx> { } } let (pools, table, end) = stage.completed_addresses(kv, snapshot)?; - self.status - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&[0; 4])?; - let status = checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - let out = self - .output - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); + self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; + let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + let out = + self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), @@ -311,21 +276,12 @@ impl<'ctx> QsaPromptAttention<'ctx> { Arg::I32(2051), ])?; self.run_in(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![ - Arg::U64(out), - Arg::I32((t * 6144) as i32), - Arg::U64(status), - ])?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run_in(variants, w, scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } - Ok(QsaPromptAttentionCompletion { - owner: self, - _stage: stage, - _snapshot: snapshot, - t, - }) + Ok(QsaPromptAttentionCompletion { owner: self, _stage: stage, _snapshot: snapshot, t }) } pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs index 76e88b17..02a11409 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs @@ -15,20 +15,11 @@ pub(crate) struct Arguments { impl Arguments { pub(crate) fn new(values: Vec) -> Result { let mut pointers = Vec::new(); - pointers - .try_reserve_exact(values.len()) - .map_err(|_| Error::HostAllocation)?; - Ok(Self { - values: values.into_boxed_slice(), - pointers, - }) + pointers.try_reserve_exact(values.len()).map_err(|_| Error::HostAllocation)?; + Ok(Self { values: values.into_boxed_slice(), pointers }) } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; type Load = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> i32; @@ -61,14 +52,7 @@ mod enabled { } } fn check(op: &'static str, code: i32) -> Result<()> { - if code == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code, - }) - } + if code == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code }) } } macro_rules! sym { ($l:ident,$n:literal,$t:ty) => {{ @@ -93,9 +77,7 @@ mod enabled { if ptx.windows(8).any(|w| w == b"UNSEALED") || ptx.last() != Some(&0) { return Err(Error::UnsupportedQwenOperation); } - let l = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let l = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if l.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -109,19 +91,11 @@ mod enabled { let mut minor = 0; let mut shared = 0; let mut optin = 0; - check("cuDeviceGetAttribute", unsafe { - attr(&mut major, 75, device) - })?; - check("cuDeviceGetAttribute", unsafe { - attr(&mut minor, 76, device) - })?; - check("cuDeviceGetAttribute", unsafe { - attr(&mut shared, 8, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut major, 75, device) })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut minor, 76, device) })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut shared, 8, device) })?; // CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK_OPTIN (the Original's smpbo for the opt-in). - check("cuDeviceGetAttribute", unsafe { - attr(&mut optin, 97, device) - })?; + check("cuDeviceGetAttribute", unsafe { attr(&mut optin, 97, device) })?; if major < 8 || shared < 45584 { return Err(Error::UnsupportedQwenOperation); } @@ -134,15 +108,10 @@ mod enabled { module: None, functions: Vec::new(), }; - owner - .functions - .try_reserve_exact(entries.len()) - .map_err(|_| Error::HostAllocation)?; + owner.functions.try_reserve_exact(entries.len()).map_err(|_| Error::HostAllocation)?; let result = (|| { let mut m = std::ptr::null_mut(); - check("cuModuleLoadData", unsafe { - load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) - })?; + check("cuModuleLoadData", unsafe { load(&mut m, crate::arch_ptx::image(ptx).as_ptr().cast()) })?; if m.is_null() { return Err(Error::InvalidDriverValue("cuModuleLoadData")); } @@ -182,16 +151,11 @@ mod enabled { { return Err(Error::InvalidQwenShape); } - let f = *self - .functions - .get(index) - .ok_or(Error::UnsupportedQwenOperation)?; + let f = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?; if shared > 48 * 1024 { // The Original's cudaFuncSetAttribute(MaxDynamicSharedMemorySize) before a >48 KiB launch // (CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES = 8). - check("cuFuncSetAttribute", unsafe { - (self.func_attr)(f as *mut c_void, 8, shared as i32) - })?; + check("cuFuncSetAttribute", unsafe { (self.func_attr)(f as *mut c_void, 8, shared as i32) })?; } args.pointers.clear(); for v in &mut args.values { @@ -241,11 +205,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::Module; #[cfg(not(all( feature = "cuda-driver", @@ -265,15 +225,7 @@ impl Module { pub(crate) fn caps(&self) -> [u32; 3] { [0; 3] } - pub(crate) fn launch( - &self, - _: usize, - _: [u32; 3], - _: u32, - _: u32, - _: usize, - _: &mut Arguments, - ) -> Result<()> { + pub(crate) fn launch(&self, _: usize, _: [u32; 3], _: u32, _: u32, _: usize, _: &mut Arguments) -> Result<()> { Err(Error::UnsupportedPlatform) } pub(crate) fn close(self) -> Result<()> { diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select.rs b/crates/cuda-driver/src/qsa_prompt_attention_select.rs index ef4c7d67..efbb96d1 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select.rs @@ -50,13 +50,8 @@ pub const ENTRY_V1_INT8: &CStr = c"leleka_qsa_prompt_attn_v1_i8"; pub const ENTRY_FP16: &CStr = c"leleka_qsa_prompt_attn_f16"; pub const ENTRY_K8V4: &CStr = c"leleka_qsa_prompt_attn_k8v4"; /// Module entries of `qsa_prompt_attention_variants.ptx`, in load order (index = launch index). -pub const VARIANT_ENTRIES: [&CStr; 5] = [ - c"leleka_qsa_prompt_guard", - ENTRY_V1_INT8, - ENTRY_FP16, - ENTRY_K8V4, - c"leleka_qsa_prompt_output_guard", -]; +pub const VARIANT_ENTRIES: [&CStr; 5] = + [c"leleka_qsa_prompt_guard", ENTRY_V1_INT8, ENTRY_FP16, ENTRY_K8V4, c"leleka_qsa_prompt_output_guard"]; /// Which pools the caller holds (`QsaAttnPools` null-ness), nothing else. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -130,33 +125,33 @@ mod impl_poolpresence; #[allow(unused_imports)] use impl_poolpresence::align_up; #[allow(unused_imports)] -pub use impl_poolpresence::smem_bytes; -#[allow(unused_imports)] -pub use impl_poolpresence::smem2_bytes; -#[allow(unused_imports)] -pub use impl_poolpresence::select; -#[allow(unused_imports)] pub use impl_poolpresence::hip_wmma_usable; #[allow(unused_imports)] -pub use impl_poolpresence::scale_log2; -#[allow(unused_imports)] pub use impl_poolpresence::launch_slices; #[allow(unused_imports)] -pub use impl_poolpresence::slice_offsets; -#[allow(unused_imports)] pub use impl_poolpresence::pool_row; #[allow(unused_imports)] pub use impl_poolpresence::reference_attention_f64; +#[allow(unused_imports)] +pub use impl_poolpresence::scale_log2; +#[allow(unused_imports)] +pub use impl_poolpresence::select; +#[allow(unused_imports)] +pub use impl_poolpresence::slice_offsets; +#[allow(unused_imports)] +pub use impl_poolpresence::smem_bytes; +#[allow(unused_imports)] +pub use impl_poolpresence::smem2_bytes; mod q_prescale_fn; #[allow(unused_imports)] -pub use q_prescale_fn::q_prescale; -#[allow(unused_imports)] -use q_prescale_fn::pow2f; -#[allow(unused_imports)] pub use q_prescale_fn::f16_hi_lo; #[allow(unused_imports)] pub use q_prescale_fn::f16_round; #[allow(unused_imports)] +pub use q_prescale_fn::f16_to_f32; +#[allow(unused_imports)] pub use q_prescale_fn::f32_to_f16; #[allow(unused_imports)] -pub use q_prescale_fn::f16_to_f32; +use q_prescale_fn::pow2f; +#[allow(unused_imports)] +pub use q_prescale_fn::q_prescale; diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs index d72cdf3b..ddeb8893 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs @@ -5,16 +5,56 @@ use super::*; impl PoolPresence { pub const fn int8() -> Self { - Self { k_pool: false, v_pool: false, k_q: true, v_q: true, k_scale: true, v_scale: true, k_q4: false, v_q4: false, page_table: true } + Self { + k_pool: false, + v_pool: false, + k_q: true, + v_q: true, + k_scale: true, + v_scale: true, + k_q4: false, + v_q4: false, + page_table: true, + } } pub const fn fp16() -> Self { - Self { k_pool: true, v_pool: true, k_q: false, v_q: false, k_scale: false, v_scale: false, k_q4: false, v_q4: false, page_table: true } + Self { + k_pool: true, + v_pool: true, + k_q: false, + v_q: false, + k_scale: false, + v_scale: false, + k_q4: false, + v_q4: false, + page_table: true, + } } pub const fn hybrid_k8v4() -> Self { - Self { k_pool: false, v_pool: false, k_q: true, v_q: false, k_scale: true, v_scale: false, k_q4: false, v_q4: true, page_table: true } + Self { + k_pool: false, + v_pool: false, + k_q: true, + v_q: false, + k_scale: true, + v_scale: false, + k_q4: false, + v_q4: true, + page_table: true, + } } pub const fn q4() -> Self { - Self { k_pool: false, v_pool: false, k_q: false, v_q: false, k_scale: false, v_scale: false, k_q4: true, v_q4: true, page_table: true } + Self { + k_pool: false, + v_pool: false, + k_q: false, + v_q: false, + k_scale: false, + v_scale: false, + k_q4: true, + v_q4: true, + page_table: true, + } } } impl Shapes { @@ -24,10 +64,7 @@ impl Shapes { impl SelectSwitches { /// Literal `getenv` reading: `STRATA_QSA_WARP` equal to "1" or "attn"; `STRATA_PROMPT_ATTN_V1` merely present. pub fn from_values(qsa_warp: Option<&str>, prompt_attn_v1: Option<&str>) -> Self { - Self { - qsa_warp_arm: matches!(qsa_warp, Some("1") | Some("attn")), - prompt_attn_v1: prompt_attn_v1.is_some(), - } + Self { qsa_warp_arm: matches!(qsa_warp, Some("1") | Some("attn")), prompt_attn_v1: prompt_attn_v1.is_some() } } pub fn from_environment() -> Self { Self::from_values( @@ -218,9 +255,7 @@ pub fn reference_attention_f64(q: &[f32], k: &[Vec], v: &[Vec], scale: for h in 0..G { let logits: Vec = k .iter() - .map(|row| { - (0..HD).map(|d| f64::from(q[h * HD + d]) * f64::from(row[d])).sum::() * scale - }) + .map(|row| (0..HD).map(|d| f64::from(q[h * HD + d]) * f64::from(row[d])).sum::() * scale) .collect(); let m = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max); let weights: Vec = logits.iter().map(|x| (x - m).exp()).collect(); diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs index 48f6e6a5..0a869351 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The q pre-scale the kernels apply before the hi/lo FP16 split (exact, power of two): returns `(qe, qup, /// qdown)` where `qm < 2^qe`, `qup = 2^(14-qe)`, `qdown = scale_log2 * 2^(qe-14)`; an all-zero q gives `qe = 0`. pub fn q_prescale(qm: f32, scale_log2: f32) -> (i32, f32, f32) { diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs index df0a5a0c..3d082e1b 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs @@ -74,7 +74,10 @@ fn selection_follows_the_original_decision_tree() { #[test] fn switches_read_the_original_environment_forms() { - assert_eq!(SelectSwitches::from_values(Some("1"), None), SelectSwitches { qsa_warp_arm: true, prompt_attn_v1: false }); + assert_eq!( + SelectSwitches::from_values(Some("1"), None), + SelectSwitches { qsa_warp_arm: true, prompt_attn_v1: false } + ); assert!(SelectSwitches::from_values(Some("attn"), None).qsa_warp_arm); assert!(!SelectSwitches::from_values(Some("0"), None).qsa_warp_arm); assert!(!SelectSwitches::from_values(Some(""), None).qsa_warp_arm); diff --git a/crates/cuda-driver/src/qsa_prompt_device.rs b/crates/cuda-driver/src/qsa_prompt_device.rs index 41b879e5..a3a1881b 100644 --- a/crates/cuda-driver/src/qsa_prompt_device.rs +++ b/crates/cuda-driver/src/qsa_prompt_device.rs @@ -1,152 +1,61 @@ //! Physical Original QSA prompt pipeline. Opaque selection retains the actual //! affine GR read and immutable completed index; no Buffer/address certificate. use super::*; -use crate::{OriginalDeviceGrRead,OriginalDeviceBlock,QsaNativeKind,QsaNativePacking,QsaPromptKv,QsaPromptStage,QsaKvSnapshot,QsaPromptAttention,CompletedQsaKvAppend}; use crate::original_prefill_arena::OriginalPromptSpan as S; use crate::original_prefill_layout::PrefillPhase; -use crate::ple_batch_ffi::{KernelModule,KernelArguments,BatchArg as B}; -const SCRATCH:usize=64<<20; -const GATE_PTX:&[u8]=concat!(include_str!("qsa_prompt_device_gate.ptx"),"\0").as_bytes(); -const GATE_SHA:[u8;32]=[0x69,0xf0,0x3b,0xe1,0x7d,0xb1,0x7a,0xba,0x2f,0x82,0x8c,0xf4,0x37,0x91,0x0a,0x4d,0xb6,0x63,0x23,0x97,0x3d,0xaa,0x8b,0x1a,0x45,0x9c,0x24,0x18,0xf9,0x11,0x45,0xd4]; -pub struct OriginalQsaPromptDevice<'ctx>{ - context:&'ctx Context<'ctx>,capacity:usize,packing:QsaNativePacking,index:Option>, - scratch:Option>,steps:Option>,dequant:Option,pack:Option,gate:Option,failed:bool, +use crate::ple_batch_ffi::{BatchArg as B, KernelArguments, KernelModule}; +use crate::{ + CompletedQsaKvAppend, OriginalDeviceBlock, OriginalDeviceGrRead, QsaKvSnapshot, QsaNativeKind, QsaNativePacking, + QsaPromptAttention, QsaPromptKv, QsaPromptStage, +}; +const SCRATCH: usize = 64 << 20; +const GATE_PTX: &[u8] = concat!(include_str!("qsa_prompt_device_gate.ptx"), "\0").as_bytes(); +const GATE_SHA: [u8; 32] = [ + 0x69, 0xf0, 0x3b, 0xe1, 0x7d, 0xb1, 0x7a, 0xba, 0x2f, 0x82, 0x8c, 0xf4, 0x37, 0x91, 0x0a, 0x4d, 0xb6, 0x63, 0x23, + 0x97, 0x3d, 0xaa, 0x8b, 0x1a, 0x45, 0x9c, 0x24, 0x18, 0xf9, 0x11, 0x45, 0xd4, +]; +pub struct OriginalQsaPromptDevice<'ctx> { + context: &'ctx Context<'ctx>, + capacity: usize, + packing: QsaNativePacking, + index: Option>, + scratch: Option>, + steps: Option>, + dequant: Option, + pack: Option, + gate: Option, + failed: bool, } -pub struct OriginalQsaPromptWeights<'w,'ctx>{pub projections:[&'w DeviceBuffer<'ctx>;6],pub kinds:[QsaNativeKind;4],pub norms:[&'w DeviceBuffer<'ctx>;4]} -pub struct OriginalQsaDeviceSelection<'lease,'arena,'loan,'ctx>{owner:&'lease mut OriginalQsaPromptDevice<'ctx>,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,p0:u32,state:QsaPromptIndexState} -impl<'ctx> Context<'ctx>{pub fn original_qsa_prompt_device(&'ctx self,capacity:usize,packing:QsaNativePacking)->Result>{OriginalQsaPromptDevice::new(self,capacity,packing)}} -fn native_block(kind:QsaNativeKind)->usize{match kind{QsaNativeKind::Q4K=>144,QsaNativeKind::Q5K=>176,QsaNativeKind::Q6K=>210,QsaNativeKind::Iq4Xs=>136}} -fn native_entry(kind:QsaNativeKind)->usize{match kind{QsaNativeKind::Q4K=>0,QsaNativeKind::Q5K=>1,QsaNativeKind::Q6K=>2,QsaNativeKind::Iq4Xs=>3}} -fn arena_span(read:&OriginalDeviceGrRead<'_, '_, '_>,name:&str,width:usize)->Result{let(h,n)=read.lease().span(PrefillPhase::Qsa,name)?;h.checked_subspan(n,0,read.rows()*width)} -fn common(read:&OriginalDeviceGrRead<'_, '_, '_>,role:S,width:usize)->Result{let(h,n)=read.lease().common_span(role)?;h.checked_subspan(n,0,read.rows()*width)} -impl<'ctx> OriginalQsaPromptDevice<'ctx>{ - pub fn device_bytes(capacity:usize)->Result{if !(1..=8192).contains(&capacity){return Err(Error::InvalidQwenShape)} - // Only real index images and a <=256 score tile persist. All row - // projection/normalized/IDs/attn/Out payloads are actual arena spans. - (SCRATCH+{let z=sizes();z[0]+z[1]+z[2]+z[3]}+5*4+64).checked_add(capacity.min(256)*max_blocks()*4).and_then(|x|x.checked_add(capacity*16)).ok_or(Error::BudgetExceeded) - } - fn new(context:&'ctx Context<'ctx>,capacity:usize,packing:QsaNativePacking)->Result{ - let required=Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if GATE_PTX.len()<2||GATE_PTX.last()!=Some(&0)||GATE_PTX[..GATE_PTX.len()-1].contains(&0)||crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len()-1])!=GATE_SHA{return Err(Error::UnsupportedQwenOperation)} - if [INDEX,SELECT,POSTOPS,DECODE_POSTOPS].iter().any(|x|x.starts_with(b"// UNSEALED")){return Err(Error::UnsupportedQwenOperation)} - if context.is_poisoned(){return Err(Error::ContextPoisoned)} - if context.allocated_bytes().checked_add(required).is_none_or(|x|x>context.budget_bytes())||context.memory_info()?.0Result<()>{for(i,n)in sizes.into_iter().enumerate(){owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i]=Some(context.allocate(n)?)} - owner.scratch=Some(context.allocate(SCRATCH)?);owner.steps=Some(context.allocate(capacity*16)?); - let guard=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?; - let load=(||->Result<()>{owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module=Some(Module::load(INDEX,SELECT,POSTOPS,DECODE_POSTOPS)?); - owner.dequant=Some(if crate::prefill_stage::fast_dequant(){KernelModule::load(crate::prefill_stage::PTX,crate::prefill_stage::ENTRIES)?} - else{KernelModule::load(concat!(include_str!("offline_native_dequant_f16.ptx"),"\0").as_bytes(),&[c"leleka_native_dequant_f16_q4_k",c"leleka_native_dequant_f16_q5_k",c"leleka_native_dequant_f16_q6_k",c"leleka_native_dequant_f16_iq4_xs"])?}); - owner.pack=Some(KernelModule::load(concat!(include_str!("qsa_native_batch.ptx"),"\0").as_bytes(),&[c"qsa_pack",c"qsa_gate_pack",c"qsa_scan_half"])?); - owner.gate=Some(KernelModule::load(GATE_PTX,&[c"qsa_prompt_device_gate"])?);Ok(())})(); - let pop=guard.finish();if pop.is_err(){context.poison();context.retain_driver()}combine(load,pop)?; - if context.memory_info()?.0bool{self.failed||self.context.is_poisoned()||self.index.as_ref().is_none_or(QsaPromptIndexWorkspace::is_failed)} - pub fn allocated_bytes(&self)->usize{self.index.as_ref().map_or(0,QsaPromptIndexWorkspace::allocated_bytes)+self.scratch.as_ref().map_or(0,DeviceBuffer::len)+self.steps.as_ref().map_or(0,DeviceBuffer::len)} - fn own(&self,b:&DeviceBuffer<'_>,bytes:usize,alignment:u64)->Result{if !std::ptr::eq(self.context,b.context){return Err(Error::ContextMismatch)}if b.len()!=bytes{return Err(Error::InvalidQwenShape)}let h=b.handle.ok_or(Error::ContextPoisoned)?;h.validate_projection_extent(bytes,alignment)?;Ok(h)} - fn admit(&self,read:&OriginalDeviceGrRead<'_, '_, '_>,w:&OriginalQsaPromptWeights<'_,'ctx>,ws:&NativeBatchWorkspace<'_>)->Result<([ffi::BufferHandle;6],[ffi::BufferHandle;4])>{ - if self.is_failed()||read.lease().is_failed(){return Err(Error::ContextPoisoned)}if !read.context_matches(self.context){return Err(Error::ContextMismatch)}if !(1..=self.capacity).contains(&read.rows()){return Err(Error::InvalidQwenShape)}ws.validate_context(self.context)?; - let sizes=[512*(2560/256)*native_block(w.kinds[0]),512*(2560/256)*native_block(w.kinds[1]),12288*(2560/256)*native_block(w.kinds[2]),128*2560*2,512*2560*2,2560*(6144/256)*native_block(w.kinds[3])]; - let mut matrices=[self.own(w.projections[0],sizes[0],2)?;6];for(i,b)in w.projections.iter().enumerate(){matrices[i]=self.own(b,sizes[i],2)?;ws.reject_alias(matrices[i],sizes[i])?;} - let mut norms=[matrices[0];4];for(i,b)in w.norms.iter().enumerate(){let n=if i<2{1024}else{512};norms[i]=self.own(b,n,4)?;ws.reject_alias(norms[i],n)?;} - let mut all=Vec::new();all.try_reserve_exact(32).map_err(|_|Error::HostAllocation)?; - for b in self.index.as_ref().ok_or(Error::ContextPoisoned)?.buffers.iter().flatten().chain(self.scratch.iter()).chain(self.steps.iter()){all.push((self.own(b,b.len(),4)?,b.len()));} - for(role,width)in[(S::MixedHalf,5120),(S::MixedHigh,5120),(S::Block,10240)]{all.push((common(read,role,width)?,read.rows()*width));} - if self.packing==QsaNativePacking::HighAndLow{all.push((common(read,S::MixedLow,5120)?,read.rows()*5120));} - for(name,width)in[("Kc",2048),("Vc",2048),("Qf",49152),("q",24576),("idx_raw",512),("q_idx",2048),("attn",24576),("attn_h",12288),("sel_ids",CAP*4)]{all.push((arena_span(read,name,width)?,read.rows()*width));} - for(i,(h,n))in all.iter().enumerate(){h.validate_projection_extent(*n,2)?;ws.reject_alias(*h,*n)?;for(a,b)in &all[..i]{if h.overlaps(*n,*a,*b){return Err(Error::OutputAliasesInput)}}for(j,wh)in matrices.iter().enumerate(){if h.overlaps(*n,*wh,sizes[j]){return Err(Error::OutputAliasesInput)}}for(j,wh)in norms.iter().enumerate(){if h.overlaps(*n,*wh,if j<2{1024}else{512}){return Err(Error::OutputAliasesInput)}}} - Ok((matrices,norms)) - } - fn project(&mut self,read:&OriginalDeviceGrRead<'_, '_, '_>,ws:&mut NativeBatchWorkspace<'ctx>,weight:ffi::BufferHandle,kind:Option,n:usize,k:usize,x:ffi::BufferHandle,output:ffi::BufferHandle)->Result<()>{ - let t=read.rows();let status=self.index.as_ref().ok_or(Error::ContextPoisoned)?.handle(10,64)?; - let scratch=self.own(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?,SCRATCH,4)?.checked_subspan(SCRATCH,0,n*k*2)?; - // element-parallel dequantization of prefill_stage.cu (same FP16 bits) unless LELEKA_PREFILL_FAST_DEQUANT=0 - let fast=crate::prefill_stage::fast_dequant(); - let mut dequant=if fast{KernelArguments::new(vec![B::Address(weight),B::I64((k/256*kind.map_or(0,native_block))as i64),B::I64((n*k)as i64),B::I64((k/32)as i64),B::Address(scratch)])} - else{KernelArguments::new(vec![B::Address(weight),B::I64((k/256*kind.map_or(0,native_block))as i64),B::I64(0),B::I64(n as i64),B::I64((k/32)as i64),B::Address(scratch)])}; - let mut input=KernelArguments::new(vec![B::Address(x),B::Address(status),B::I64((t*k)as i64),B::U32(0),B::U32(if kind.is_some(){0x7c00}else{0x7f80})]); - let lower=if self.packing==QsaNativePacking::HighAndLow&&kind.is_none(){Some(common(read,S::MixedLow,5120)?)}else{None}; - let mut low=lower.map(|h|KernelArguments::new(vec![B::Address(h),B::Address(status),B::I64((t*k)as i64),B::U32(0),B::U32(0x7f80)])); - let mut weight_scan=KernelArguments::new(vec![B::Address(scratch),B::Address(status),B::I64((n*k)as i64),B::U32(1),B::U32(0x7c00)]); - let mut scan=Arguments::new(vec![A::Address(output),A::I64((t*n)as i64),A::Address(status),A::U32(2)])?; - let zero=[0u8;64];let mut flags=[0u8;64];let context=self.context;let blas=ws.blas()?; - let guard=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?; - let op=(||->Result<()>{context.driver.api.copy_from(status,&zero)?;context.driver.api.synchronize()?; - self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch(2,(t*k).div_ceil(256)as u32,256,blas.stream(),&mut input)?; - if let Some(args)=&mut low{self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch(2,(t*k).div_ceil(256)as u32,256,blas.stream(),args)?;} - if let Some(kind)=kind{ - if fast{self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch(crate::prefill_stage::DEQUANT_FIRST+match kind{QsaNativeKind::Q4K=>1,QsaNativeKind::Q5K=>2,QsaNativeKind::Q6K=>3,QsaNativeKind::Iq4Xs=>5},(n*k).div_ceil(256)as u32,256,blas.stream(),&mut dequant)?;} - else{self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch(native_entry(kind),(n*k/32).div_ceil(256)as u32,256,blas.stream(),&mut dequant)?;} - self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch(2,(n*k).div_ceil(256)as u32,256,blas.stream(),&mut weight_scan)?;blas.gemm_f16(x,scratch,output,t as i32,n as i32,k as i32,&1.,&0.)?; - }else{blas.gemm_bf16(x,weight,output,t as i32,n as i32,k as i32,&1.,&0.)?;if let Some(lower)=lower{blas.gemm_bf16(lower,weight,output,t as i32,n as i32,k as i32,&1.,&1.)?;}} - self.index.as_ref().and_then(|i|i.module.as_ref()).ok_or(Error::ContextPoisoned)?.launch(Launch::Scan((t*n)as u32),blas.stream(),&mut scan)?;Ok(())})(); - let sync=blas.synchronize();let copy=if sync.is_ok(){context.driver.api.copy_to(status,&mut flags)}else{Ok(())};let all=context.driver.api.synchronize();let pop=guard.finish(); - if op.is_err()||sync.is_err()||copy.is_err()||all.is_err()||pop.is_err(){self.failed=true;context.poison();context.retain_driver()} - if sync.is_err()||all.is_err()||pop.is_err(){std::mem::forget((dequant,input,low,weight_scan,scan));} - let result=combine(combine(combine(combine(op,sync),copy),all),pop);if result.is_err(){ws.mark_failed();return result} - for word in flags.as_chunks::<4>().0{if u32::from_le_bytes(*word)>1{self.failed=true;context.poison();context.retain_driver();return Err(Error::InvalidDriverValue("QSA projection status"))}} - if flags[12..].iter().any(|x|*x!=0){self.failed=true;context.poison();context.retain_driver();return Err(Error::InvalidDriverValue("QSA unused status"))} - if flags[..12].iter().any(|x|*x!=0){return Err(Error::NonFiniteMmqOutput("QSA native projection"))}Ok(()) - } - #[allow(clippy::too_many_arguments)] - pub fn prepare<'lease,'arena,'loan>(&'lease mut self,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,ws:&mut NativeBatchWorkspace<'ctx>,p0:u32,pooled:&[f32],tail:&[f32],dead:&[f32],weights:OriginalQsaPromptWeights<'_,'ctx>)->Result>{ - let t=read.rows();let p=p0 as usize; - if p.checked_add(t).is_none_or(|end|end>crate::serving_context::geometry().cells())||pooled.len()!=p/4*128||tail.len()!=384||dead.len()!=128{return Err(Error::InvalidQwenShape)} - if pooled.iter().chain(tail).chain(dead).any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("QSA prior"))} - let(w,gamma)=self.admit(&read,&weights,ws)?;let half=common(&read,S::MixedHalf,5120)?;let high=common(&read,S::MixedHigh,5120)?; - for(i,name,n)in[(0,"Kc",512),(1,"Vc",512),(2,"Qf",12288),(3,"idx_raw",128),(4,"q_idx",512)]{self.project(&read,ws,w[i],if i<3{Some(weights.kinds[i])}else{None},n,2560,if i<3{half}else{high},arena_span(&read,name,n*4)?)?;} - let steps=self.own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?,self.capacity*16,4)?.checked_subspan(self.capacity*16,0,t*16)?; - let out=[arena_span(&read,"Kc",2048)?,arena_span(&read,"Vc",2048)?,arena_span(&read,"q",24576)?,arena_span(&read,"sel_ids",CAP*4)?,steps]; - let raw=arena_span(&read,"idx_raw",512)?;let qfull=arena_span(&read,"Qf",49152)?;let iq=arena_span(&read,"q_idx",2048)?; - let index=self.index.as_mut().ok_or(Error::ContextPoisoned)?; - index.run_original_arena(p0,t as u32,pooled,tail,dead,raw,qfull,iq,gamma,out,ws,false)?; - let state=index.final_state_original_arena(p,t,tail,raw)?; - Ok(OriginalQsaDeviceSelection{owner:self,read,p0,state}) - } - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{self.failed=true;let mut result=Ok(());for m in [self.dequant.take(),self.pack.take(),self.gate.take()].into_iter().flatten(){let r=if self.context.is_poisoned(){std::mem::forget(m);Err(Error::ContextPoisoned)}else{match self.context.enter(){Ok(g)=>combine(m.close(),g.finish()),Err(e)=>{std::mem::forget(m);Err(e)}}};if r.is_err(){self.context.poison();self.context.retain_driver()}result=combine(result,r)} - for b in [self.scratch.take(),self.steps.take()].into_iter().flatten(){let r=if self.context.is_poisoned(){std::mem::forget(b);Err(Error::ContextPoisoned)}else{b.release()};if r.is_err(){self.context.poison();self.context.retain_driver()}result=combine(result,r)} - if let Some(i)=self.index.take(){let r=if self.context.is_poisoned(){std::mem::forget(i);Err(Error::ContextPoisoned)}else{i.close()};result=combine(result,r)}result} +pub struct OriginalQsaPromptWeights<'w, 'ctx> { + pub projections: [&'w DeviceBuffer<'ctx>; 6], + pub kinds: [QsaNativeKind; 4], + pub norms: [&'w DeviceBuffer<'ctx>; 4], } -impl Drop for OriginalQsaPromptDevice<'_>{fn drop(&mut self){let _=self.close_inner();}} -impl<'lease,'arena,'loan,'ctx> OriginalQsaDeviceSelection<'lease,'arena,'loan,'ctx>{ - pub fn rows(&self)->usize{self.read.rows()}pub fn first_position(&self)->usize{self.p0 as usize}pub fn final_index(&self)->&QsaPromptIndexState{&self.state} - fn validate(&self,c:&Context<'_>)->Result<()>{if self.owner.is_failed()||self.read.lease().is_failed(){return Err(Error::ContextPoisoned)}if !self.read.context_matches(c)||!std::ptr::eq(self.owner.context,c){return Err(Error::ContextMismatch)}Ok(())} - pub(crate) fn kv_spans(&self,c:&Context<'_>)->Result<(ffi::BufferHandle,ffi::BufferHandle)>{self.validate(c)?;Ok((arena_span(&self.read,"Kc",2048)?,arena_span(&self.read,"Vc",2048)?))} - pub(crate) fn attention_spans(&self,c:&Context<'_>)->Result<(ffi::BufferHandle,ffi::BufferHandle,ffi::BufferHandle,ffi::BufferHandle)>{self.validate(c)?;let b=self.owner.steps.as_ref().ok_or(Error::ContextPoisoned)?;Ok((arena_span(&self.read,"q",24576)?,arena_span(&self.read,"sel_ids",CAP*4)?,b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(),0,self.rows()*16)?,arena_span(&self.read,"attn",24576)?))} - /// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native - /// FP16 Out. Only actual completed source/causal runtime may publish state. - #[allow(clippy::too_many_arguments)] - pub fn complete(self,ws:&mut NativeBatchWorkspace<'ctx>,kv:&mut QsaPromptKv<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,attention:&mut QsaPromptAttention<'ctx>,out_weight:&DeviceBuffer<'ctx>,out_kind:QsaNativeKind)->Result<(OriginalDeviceBlock<'arena,'loan,'ctx>,QsaPromptIndexState,CompletedQsaKvAppend)>{ - self.validate(self.owner.context)?; - let t=self.rows();let bytes=2560*(6144/256)*native_block(out_kind);let weight=self.owner.own(out_weight,bytes,2)?; - // Real Out owner admission again; no weight identity is inferred from - // earlier role bytes or a caller range. Runtime rechecks binding role. - ws.reject_alias(weight,bytes)?; - for b in self.owner.index.as_ref().ok_or(Error::ContextPoisoned)?.buffers.iter().flatten().chain(self.owner.scratch.iter()).chain(self.owner.steps.iter()){ - if weight.overlaps(bytes,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} - } - for(name,width)in[("attn",24576),("attn_h",12288),("Qf",49152)]{if weight.overlaps(bytes,arena_span(&self.read,name,width)?,t*width){return Err(Error::OutputAliasesInput)}} - if weight.overlaps(bytes,common(&self.read,S::Block,10240)?,t*10240){return Err(Error::OutputAliasesInput)} - let appended=kv.append_original_arena(ws,stage,prior,&self)?; - attention.attend_original_arena(ws,stage,kv,appended.final_snapshot(),&self)?; - let input=arena_span(&self.read,"attn",24576)?;let qf=arena_span(&self.read,"Qf",49152)?;let half=arena_span(&self.read,"attn_h",12288)?; - let mut args=KernelArguments::new(vec![B::Address(input),B::Address(qf),B::Address(half),B::I64(t as i64)]); - let context=self.owner.context;let blas=ws.blas()?;let guard=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?; - let op=self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(0,(t*6144).div_ceil(256)as u32,256,blas.stream(),&mut args); - let sync=blas.synchronize();let pop=guard.finish();if op.is_err()||sync.is_err()||pop.is_err(){self.owner.failed=true;context.poison();context.retain_driver()} - if sync.is_err()||pop.is_err(){std::mem::forget(args)}let result=combine(combine(op,sync),pop);if result.is_err(){ws.mark_failed();return result.map(|()|unreachable!("failed gate"))} - self.owner.project(&self.read,ws,weight,Some(out_kind),2560,6144,half,common(&self.read,S::Block,10240)?)?; - Ok((self.read.from_completed_block(),self.state,appended)) - } +pub struct OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx> { + owner: &'lease mut OriginalQsaPromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + p0: u32, + state: QsaPromptIndexState, } -#[path="qsa_resident_device.rs"] +#[path = "qsa_resident_device.rs"] mod resident_device; -pub use resident_device::{OriginalQsaResidentSelection,OriginalQsaResidentPromptDevice}; pub(crate) use resident_device::kv_stage_spans_of; +pub use resident_device::{OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection}; + +#[path = "qsa_prompt_device/impl_context.rs"] +mod impl_context; +#[allow(unused_imports)] +use impl_context::arena_span; +#[allow(unused_imports)] +use impl_context::common; +#[allow(unused_imports)] +use impl_context::native_block; +#[allow(unused_imports)] +use impl_context::native_entry; +#[path = "qsa_prompt_device/impl_originalqsapromptdevice.rs"] +mod impl_originalqsapromptdevice; +#[path = "qsa_prompt_device/impl_originalqsapromptdevice_2.rs"] +mod impl_originalqsapromptdevice_2; +#[path = "qsa_prompt_device/impl_originalqsapromptdevice_3.rs"] +mod impl_originalqsapromptdevice_3; diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs new file mode 100644 index 00000000..d41a63af --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs @@ -0,0 +1,42 @@ +//! Moved out of the parent module by STRA-338: impl Context, fn native_block, fn native_entry, fn arena_span, fn common. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> Context<'ctx> { + pub fn original_qsa_prompt_device( + &'ctx self, + capacity: usize, + packing: QsaNativePacking, + ) -> Result> { + OriginalQsaPromptDevice::new(self, capacity, packing) + } +} +pub(super) fn native_block(kind: QsaNativeKind) -> usize { + match kind { + QsaNativeKind::Q4K => 144, + QsaNativeKind::Q5K => 176, + QsaNativeKind::Q6K => 210, + QsaNativeKind::Iq4Xs => 136, + } +} +pub(super) fn native_entry(kind: QsaNativeKind) -> usize { + match kind { + QsaNativeKind::Q4K => 0, + QsaNativeKind::Q5K => 1, + QsaNativeKind::Q6K => 2, + QsaNativeKind::Iq4Xs => 3, + } +} +pub(super) fn arena_span( + read: &OriginalDeviceGrRead<'_, '_, '_>, + name: &str, + width: usize, +) -> Result { + let (h, n) = read.lease().span(PrefillPhase::Qsa, name)?; + h.checked_subspan(n, 0, read.rows() * width) +} +pub(super) fn common(read: &OriginalDeviceGrRead<'_, '_, '_>, role: S, width: usize) -> Result { + let (h, n) = read.lease().common_span(role)?; + h.checked_subspan(n, 0, read.rows() * width) +} diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs new file mode 100644 index 00000000..e81031ff --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice.rs @@ -0,0 +1,229 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + pub fn device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + // Only real index images and a <=256 score tile persist. All row + // projection/normalized/IDs/attn/Out payloads are actual arena spans. + (SCRATCH + + { + let z = sizes(); + z[0] + z[1] + z[2] + z[3] + } + + 5 * 4 + + 64) + .checked_add(capacity.min(256) * max_blocks() * 4) + .and_then(|x| x.checked_add(capacity * 16)) + .ok_or(Error::BudgetExceeded) + } + pub(super) fn new(context: &'ctx Context<'ctx>, capacity: usize, packing: QsaNativePacking) -> Result { + let required = Self::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if GATE_PTX.len() < 2 + || GATE_PTX.last() != Some(&0) + || GATE_PTX[..GATE_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA + { + return Err(Error::UnsupportedQwenOperation); + } + if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { + return Err(Error::UnsupportedQwenOperation); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut sizes = sizes(); + for i in [4, 5, 6, 7, 8] { + sizes[i] = 4 + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + let index = QsaPromptIndexWorkspace { + capacity, + sizes, + context, + buffers: std::array::from_fn(|_| None), + module: None, + late: None, + failed: false, + }; + let mut owner = Self { + context, + capacity, + packing, + index: Some(index), + scratch: None, + steps: None, + dequant: None, + pack: None, + gate: None, + failed: false, + }; + let operation = (|| -> Result<()> { + for (i, n) in sizes.into_iter().enumerate() { + owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?) + } + owner.scratch = Some(context.allocate(SCRATCH)?); + owner.steps = Some(context.allocate(capacity * 16)?); + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let load = (|| -> Result<()> { + owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module = + Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?); + owner.dequant = Some(if crate::prefill_stage::fast_dequant() { + KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)? + } else { + KernelModule::load( + concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(), + &[ + c"leleka_native_dequant_f16_q4_k", + c"leleka_native_dequant_f16_q5_k", + c"leleka_native_dequant_f16_q6_k", + c"leleka_native_dequant_f16_iq4_xs", + ], + )? + }); + owner.pack = Some(KernelModule::load( + concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(), + &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"], + )?); + owner.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + let _ = owner.close(); + return Err(e); + } + Ok(owner) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() || self.index.as_ref().is_none_or(QsaPromptIndexWorkspace::is_failed) + } + pub fn allocated_bytes(&self) -> usize { + self.index.as_ref().map_or(0, QsaPromptIndexWorkspace::allocated_bytes) + + self.scratch.as_ref().map_or(0, DeviceBuffer::len) + + self.steps.as_ref().map_or(0, DeviceBuffer::len) + } + pub(super) fn own(&self, b: &DeviceBuffer<'_>, bytes: usize, alignment: u64) -> Result { + if !std::ptr::eq(self.context, b.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, alignment)?; + Ok(h) + } + pub(super) fn admit( + &self, + read: &OriginalDeviceGrRead<'_, '_, '_>, + w: &OriginalQsaPromptWeights<'_, 'ctx>, + ws: &NativeBatchWorkspace<'_>, + ) -> Result<([ffi::BufferHandle; 6], [ffi::BufferHandle; 4])> { + if self.is_failed() || read.lease().is_failed() { + return Err(Error::ContextPoisoned); + } + if !read.context_matches(self.context) { + return Err(Error::ContextMismatch); + } + if !(1..=self.capacity).contains(&read.rows()) { + return Err(Error::InvalidQwenShape); + } + ws.validate_context(self.context)?; + let sizes = [ + 512 * (2560 / 256) * native_block(w.kinds[0]), + 512 * (2560 / 256) * native_block(w.kinds[1]), + 12288 * (2560 / 256) * native_block(w.kinds[2]), + 128 * 2560 * 2, + 512 * 2560 * 2, + 2560 * (6144 / 256) * native_block(w.kinds[3]), + ]; + let mut matrices = [self.own(w.projections[0], sizes[0], 2)?; 6]; + for (i, b) in w.projections.iter().enumerate() { + matrices[i] = self.own(b, sizes[i], 2)?; + ws.reject_alias(matrices[i], sizes[i])?; + } + let mut norms = [matrices[0]; 4]; + for (i, b) in w.norms.iter().enumerate() { + let n = if i < 2 { 1024 } else { 512 }; + norms[i] = self.own(b, n, 4)?; + ws.reject_alias(norms[i], n)?; + } + let mut all = Vec::new(); + all.try_reserve_exact(32).map_err(|_| Error::HostAllocation)?; + for b in self + .index + .as_ref() + .ok_or(Error::ContextPoisoned)? + .buffers + .iter() + .flatten() + .chain(self.scratch.iter()) + .chain(self.steps.iter()) + { + all.push((self.own(b, b.len(), 4)?, b.len())); + } + for (role, width) in [(S::MixedHalf, 5120), (S::MixedHigh, 5120), (S::Block, 10240)] { + all.push((common(read, role, width)?, read.rows() * width)); + } + if self.packing == QsaNativePacking::HighAndLow { + all.push((common(read, S::MixedLow, 5120)?, read.rows() * 5120)); + } + for (name, width) in [ + ("Kc", 2048), + ("Vc", 2048), + ("Qf", 49152), + ("q", 24576), + ("idx_raw", 512), + ("q_idx", 2048), + ("attn", 24576), + ("attn_h", 12288), + ("sel_ids", CAP * 4), + ] { + all.push((arena_span(read, name, width)?, read.rows() * width)); + } + for (i, (h, n)) in all.iter().enumerate() { + h.validate_projection_extent(*n, 2)?; + ws.reject_alias(*h, *n)?; + for (a, b) in &all[..i] { + if h.overlaps(*n, *a, *b) { + return Err(Error::OutputAliasesInput); + } + } + for (j, wh) in matrices.iter().enumerate() { + if h.overlaps(*n, *wh, sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + for (j, wh) in norms.iter().enumerate() { + if h.overlaps(*n, *wh, if j < 2 { 1024 } else { 512 }) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok((matrices, norms)) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs new file mode 100644 index 00000000..9b81748e --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_2.rs @@ -0,0 +1,242 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + pub(super) fn project( + &mut self, + read: &OriginalDeviceGrRead<'_, '_, '_>, + ws: &mut NativeBatchWorkspace<'ctx>, + weight: ffi::BufferHandle, + kind: Option, + n: usize, + k: usize, + x: ffi::BufferHandle, + output: ffi::BufferHandle, + ) -> Result<()> { + let t = read.rows(); + let status = self.index.as_ref().ok_or(Error::ContextPoisoned)?.handle(10, 64)?; + let scratch = self.own(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?, SCRATCH, 4)?.checked_subspan( + SCRATCH, + 0, + n * k * 2, + )?; + // element-parallel dequantization of prefill_stage.cu (same FP16 bits) unless LELEKA_PREFILL_FAST_DEQUANT=0 + let fast = crate::prefill_stage::fast_dequant(); + let mut dequant = if fast { + KernelArguments::new(vec![ + B::Address(weight), + B::I64((k / 256 * kind.map_or(0, native_block)) as i64), + B::I64((n * k) as i64), + B::I64((k / 32) as i64), + B::Address(scratch), + ]) + } else { + KernelArguments::new(vec![ + B::Address(weight), + B::I64((k / 256 * kind.map_or(0, native_block)) as i64), + B::I64(0), + B::I64(n as i64), + B::I64((k / 32) as i64), + B::Address(scratch), + ]) + }; + let mut input = KernelArguments::new(vec![ + B::Address(x), + B::Address(status), + B::I64((t * k) as i64), + B::U32(0), + B::U32(if kind.is_some() { 0x7c00 } else { 0x7f80 }), + ]); + let lower = if self.packing == QsaNativePacking::HighAndLow && kind.is_none() { + Some(common(read, S::MixedLow, 5120)?) + } else { + None + }; + let mut low = lower.map(|h| { + KernelArguments::new(vec![ + B::Address(h), + B::Address(status), + B::I64((t * k) as i64), + B::U32(0), + B::U32(0x7f80), + ]) + }); + let mut weight_scan = KernelArguments::new(vec![ + B::Address(scratch), + B::Address(status), + B::I64((n * k) as i64), + B::U32(1), + B::U32(0x7c00), + ]); + let mut scan = Arguments::new(vec![A::Address(output), A::I64((t * n) as i64), A::Address(status), A::U32(2)])?; + let zero = [0u8; 64]; + let mut flags = [0u8; 64]; + let context = self.context; + let blas = ws.blas()?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let op = (|| -> Result<()> { + context.driver.api.copy_from(status, &zero)?; + context.driver.api.synchronize()?; + self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 2, + (t * k).div_ceil(256) as u32, + 256, + blas.stream(), + &mut input, + )?; + if let Some(args) = &mut low { + self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 2, + (t * k).div_ceil(256) as u32, + 256, + blas.stream(), + args, + )?; + } + if let Some(kind) = kind { + if fast { + self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( + crate::prefill_stage::DEQUANT_FIRST + + match kind { + QsaNativeKind::Q4K => 1, + QsaNativeKind::Q5K => 2, + QsaNativeKind::Q6K => 3, + QsaNativeKind::Iq4Xs => 5, + }, + (n * k).div_ceil(256) as u32, + 256, + blas.stream(), + &mut dequant, + )?; + } else { + self.dequant.as_ref().ok_or(Error::ContextPoisoned)?.launch( + native_entry(kind), + (n * k / 32).div_ceil(256) as u32, + 256, + blas.stream(), + &mut dequant, + )?; + } + self.pack.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 2, + (n * k).div_ceil(256) as u32, + 256, + blas.stream(), + &mut weight_scan, + )?; + blas.gemm_f16(x, scratch, output, t as i32, n as i32, k as i32, &1., &0.)?; + } else { + blas.gemm_bf16(x, weight, output, t as i32, n as i32, k as i32, &1., &0.)?; + if let Some(lower) = lower { + blas.gemm_bf16(lower, weight, output, t as i32, n as i32, k as i32, &1., &1.)?; + } + } + self.index.as_ref().and_then(|i| i.module.as_ref()).ok_or(Error::ContextPoisoned)?.launch( + Launch::Scan((t * n) as u32), + blas.stream(), + &mut scan, + )?; + Ok(()) + })(); + let sync = blas.synchronize(); + let copy = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let all = context.driver.api.synchronize(); + let pop = guard.finish(); + if op.is_err() || sync.is_err() || copy.is_err() || all.is_err() || pop.is_err() { + self.failed = true; + context.poison(); + context.retain_driver() + } + if sync.is_err() || all.is_err() || pop.is_err() { + std::mem::forget((dequant, input, low, weight_scan, scan)); + } + let result = combine(combine(combine(combine(op, sync), copy), all), pop); + if result.is_err() { + ws.mark_failed(); + return result; + } + for word in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*word) > 1 { + self.failed = true; + context.poison(); + context.retain_driver(); + return Err(Error::InvalidDriverValue("QSA projection status")); + } + } + if flags[12..].iter().any(|x| *x != 0) { + self.failed = true; + context.poison(); + context.retain_driver(); + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..12].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA native projection")); + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn prepare<'lease, 'arena, 'loan>( + &'lease mut self, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + p0: u32, + pooled: &[f32], + tail: &[f32], + dead: &[f32], + weights: OriginalQsaPromptWeights<'_, 'ctx>, + ) -> Result> { + let t = read.rows(); + let p = p0 as usize; + if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) + || pooled.len() != p / 4 * 128 + || tail.len() != 384 + || dead.len() != 128 + { + return Err(Error::InvalidQwenShape); + } + if pooled.iter().chain(tail).chain(dead).any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA prior")); + } + let (w, gamma) = self.admit(&read, &weights, ws)?; + let half = common(&read, S::MixedHalf, 5120)?; + let high = common(&read, S::MixedHigh, 5120)?; + for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] { + self.project( + &read, + ws, + w[i], + if i < 3 { Some(weights.kinds[i]) } else { None }, + n, + 2560, + if i < 3 { half } else { high }, + arena_span(&read, name, n * 4)?, + )?; + } + let steps = self + .own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)? + .checked_subspan(self.capacity * 16, 0, t * 16)?; + let out = [ + arena_span(&read, "Kc", 2048)?, + arena_span(&read, "Vc", 2048)?, + arena_span(&read, "q", 24576)?, + arena_span(&read, "sel_ids", CAP * 4)?, + steps, + ]; + let raw = arena_span(&read, "idx_raw", 512)?; + let qfull = arena_span(&read, "Qf", 49152)?; + let iq = arena_span(&read, "q_idx", 2048)?; + let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?; + index.run_original_arena(p0, t as u32, pooled, tail, dead, raw, qfull, iq, gamma, out, ws, false)?; + let state = index.final_state_original_arena(p, t, tail, raw)?; + Ok(OriginalQsaDeviceSelection { owner: self, read, p0, state }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs new file mode 100644 index 00000000..6b011714 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs @@ -0,0 +1,186 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice (3), impl Drop_for_OriginalQsaPromptDevice, impl OriginalQsaDeviceSelection. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + pub(super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + for m in [self.dequant.take(), self.pack.take(), self.gate.take()].into_iter().flatten() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver() + } + result = combine(result, r) + } + for b in [self.scratch.take(), self.steps.take()].into_iter().flatten() { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver() + } + result = combine(result, r) + } + if let Some(i) = self.index.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(i); + Err(Error::ContextPoisoned) + } else { + i.close() + }; + result = combine(result, r) + } + result + } +} +impl Drop for OriginalQsaPromptDevice<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +impl<'lease, 'arena, 'loan, 'ctx> OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx> { + pub fn rows(&self) -> usize { + self.read.rows() + } + pub fn first_position(&self) -> usize { + self.p0 as usize + } + pub fn final_index(&self) -> &QsaPromptIndexState { + &self.state + } + pub(super) fn validate(&self, c: &Context<'_>) -> Result<()> { + if self.owner.is_failed() || self.read.lease().is_failed() { + return Err(Error::ContextPoisoned); + } + if !self.read.context_matches(c) || !std::ptr::eq(self.owner.context, c) { + return Err(Error::ContextMismatch); + } + Ok(()) + } + pub(crate) fn kv_spans(&self, c: &Context<'_>) -> Result<(ffi::BufferHandle, ffi::BufferHandle)> { + self.validate(c)?; + Ok((arena_span(&self.read, "Kc", 2048)?, arena_span(&self.read, "Vc", 2048)?)) + } + pub(crate) fn attention_spans( + &self, + c: &Context<'_>, + ) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> { + self.validate(c)?; + let b = self.owner.steps.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + arena_span(&self.read, "q", 24576)?, + arena_span(&self.read, "sel_ids", CAP * 4)?, + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), 0, self.rows() * 16)?, + arena_span(&self.read, "attn", 24576)?, + )) + } + /// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native + /// FP16 Out. Only actual completed source/causal runtime may publish state. + #[allow(clippy::too_many_arguments)] + pub fn complete( + self, + ws: &mut NativeBatchWorkspace<'ctx>, + kv: &mut QsaPromptKv<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + attention: &mut QsaPromptAttention<'ctx>, + out_weight: &DeviceBuffer<'ctx>, + out_kind: QsaNativeKind, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, QsaPromptIndexState, CompletedQsaKvAppend)> { + self.validate(self.owner.context)?; + let t = self.rows(); + let bytes = 2560 * (6144 / 256) * native_block(out_kind); + let weight = self.owner.own(out_weight, bytes, 2)?; + // Real Out owner admission again; no weight identity is inferred from + // earlier role bytes or a caller range. Runtime rechecks binding role. + ws.reject_alias(weight, bytes)?; + for b in self + .owner + .index + .as_ref() + .ok_or(Error::ContextPoisoned)? + .buffers + .iter() + .flatten() + .chain(self.owner.scratch.iter()) + .chain(self.owner.steps.iter()) + { + if weight.overlaps(bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + for (name, width) in [("attn", 24576), ("attn_h", 12288), ("Qf", 49152)] { + if weight.overlaps(bytes, arena_span(&self.read, name, width)?, t * width) { + return Err(Error::OutputAliasesInput); + } + } + if weight.overlaps(bytes, common(&self.read, S::Block, 10240)?, t * 10240) { + return Err(Error::OutputAliasesInput); + } + let appended = kv.append_original_arena(ws, stage, prior, &self)?; + attention.attend_original_arena(ws, stage, kv, appended.final_snapshot(), &self)?; + let input = arena_span(&self.read, "attn", 24576)?; + let qf = arena_span(&self.read, "Qf", 49152)?; + let half = arena_span(&self.read, "attn_h", 12288)?; + let mut args = + KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]); + let context = self.owner.context; + let blas = ws.blas()?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let op = self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 0, + (t * 6144).div_ceil(256) as u32, + 256, + blas.stream(), + &mut args, + ); + let sync = blas.synchronize(); + let pop = guard.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + self.owner.failed = true; + context.poison(); + context.retain_driver() + } + if sync.is_err() || pop.is_err() { + std::mem::forget(args) + } + let result = combine(combine(op, sync), pop); + if result.is_err() { + ws.mark_failed(); + return result.map(|()| unreachable!("failed gate")); + } + self.owner.project( + &self.read, + ws, + weight, + Some(out_kind), + 2560, + 6144, + half, + common(&self.read, S::Block, 10240)?, + )?; + Ok((self.read.from_completed_block(), self.state, appended)) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_device_attention.rs b/crates/cuda-driver/src/qsa_prompt_device_attention.rs index 3d06face..e0afa66c 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_attention.rs @@ -1,41 +1,46 @@ //! Same literal attention on the real selected query/IDs/steps/attn arena. use super::*; -impl<'ctx> QsaPromptAttention<'ctx>{ - pub(crate) fn attend_original_arena(&mut self,w:&mut NativeBatchWorkspace<'ctx>,stage:&QsaPromptStage<'ctx>,kv:&QsaPromptKv<'ctx>,snapshot:&QsaKvSnapshot,inputs:&crate::qsa_prompt_index::OriginalQsaDeviceSelection<'_, '_, '_, 'ctx>)->Result<()>{ - let t=inputs.rows(); +impl<'ctx> QsaPromptAttention<'ctx> { + pub(crate) fn attend_original_arena( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + stage: &QsaPromptStage<'ctx>, + kv: &QsaPromptKv<'ctx>, + snapshot: &QsaKvSnapshot, + inputs: &crate::qsa_prompt_index::OriginalQsaDeviceSelection<'_, '_, '_, 'ctx>, + ) -> Result<()> { + let t = inputs.rows(); // Original qsa_prompt_attn_batch choice over the resident INT8 pools: v2 on every sm_80+ card unless the // STRATA_PROMPT_ATTN_V1 debug arm was requested through `set_switches`. - let(variants,guard_ix,attn_ix,scan_ix,shared)=match self.selected_kernel()?{ - PromptAttnKernel::Int8V2=>(false,0,1,2,PromptAttnKernel::Int8V2.smem_bytes()), - PromptAttnKernel::Int8V1=>(true,0,1,4,PromptAttnKernel::Int8V1.smem_bytes()), - PromptAttnKernel::Fp16|PromptAttnKernel::HybridK8V4=>return Err(Error::UnsupportedQwenOperation), + let (variants, guard_ix, attn_ix, scan_ix, shared) = match self.selected_kernel()? { + PromptAttnKernel::Int8V2 => (false, 0, 1, 2, PromptAttnKernel::Int8V2.smem_bytes()), + PromptAttnKernel::Int8V1 => (true, 0, 1, 4, PromptAttnKernel::Int8V1.smem_bytes()), + PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => return Err(Error::UnsupportedQwenOperation), }; - if variants{self.ensure_variants()?;} + if variants { + self.ensure_variants()?; + } self.validate()?; w.validate_context(self.context)?; stage.validate(self.context)?; if !(1..=self.capacity).contains(&t) { return Err(Error::InvalidQwenShape); } - let(hq,hi,hs,out_h)=inputs.attention_spans(self.context)?; - let(qh,ih,sh)=(hq.qwen_address(),hi.qwen_address(),hs.qwen_address()); - for (h,n) in [(hq,t*6144*4),(hi,t*2051*4),(hs,t*16),(out_h,t*6144*4)]{ - stage.reject_original_span(h,n)?;w.reject_alias(h,n)?; - for b in self.output.iter().chain(self.status.iter()){ - if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} + let (hq, hi, hs, out_h) = inputs.attention_spans(self.context)?; + let (qh, ih, sh) = (hq.qwen_address(), hi.qwen_address(), hs.qwen_address()); + for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] { + stage.reject_original_span(h, n)?; + w.reject_alias(h, n)?; + for b in self.output.iter().chain(self.status.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } } } let (pools, table, end) = stage.completed_addresses(kv, snapshot)?; - self.status - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&[0; 4])?; - let status = checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - let out=out_h.qwen_address(); + self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; + let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + let out = out_h.qwen_address(); // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), @@ -70,11 +75,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32(2051), ])?; self.run_in(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![ - Arg::U64(out), - Arg::I32((t * 6144) as i32), - Arg::U64(status), - ])?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run_in(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); diff --git a/crates/cuda-driver/src/qsa_prompt_device_index.rs b/crates/cuda-driver/src/qsa_prompt_device_index.rs index f0dec4aa..09e78c26 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_index.rs @@ -1,112 +1,395 @@ //! Private real-arena continuation of the exact old prompt program. use super::*; -impl<'ctx> QsaPromptIndexWorkspace<'ctx>{ +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { #[allow(clippy::too_many_arguments)] - pub(super) fn run_original_arena(&mut self,p0:u32,t:u32,pooled:&[f32],tail:&[f32],dead:&[f32],raw_h:ffi::BufferHandle,qfull_h:ffi::BufferHandle,iq_h:ffi::BufferHandle, - gamma:[ffi::BufferHandle;4],out:[ffi::BufferHandle;5],ws:&mut NativeBatchWorkspace<'ctx>,decode:bool)->Result<()>{ - let n=t as usize;let p=p0 as usize;let end=p+n;let nb=end/4; - if !pooled.is_empty(){self.upload(0,pooled)?;} + pub(super) fn run_original_arena( + &mut self, + p0: u32, + t: u32, + pooled: &[f32], + tail: &[f32], + dead: &[f32], + raw_h: ffi::BufferHandle, + qfull_h: ffi::BufferHandle, + iq_h: ffi::BufferHandle, + gamma: [ffi::BufferHandle; 4], + out: [ffi::BufferHandle; 5], + ws: &mut NativeBatchWorkspace<'ctx>, + decode: bool, + ) -> Result<()> { + let n = t as usize; + let p = p0 as usize; + let end = p + n; + let nb = end / 4; + if !pooled.is_empty() { + self.upload(0, pooled)?; + } // The current spare is genuine prior state even when this batch completes no block. - let spare=encode(dead)?;let result=self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p/4*128*4,&spare); - if result.is_err(){self.failed=true;}result?; - self.upload(1,tail)?;self.upload(2,dead)?; - let mut steps=Vec::new();steps.try_reserve_exact(n*16).map_err(|_|Error::HostAllocation)?; - for row in 0..n{let pos=p+row;for x in [pos,pos+1,(pos+1)/4,(pos+1).min(CAP)]{steps.extend((x as i32).to_le_bytes());}} - let zero=vec![0u8;64];let mut flags=vec![0u8;64];let status=self.handle(10,64)?;let mut commands:Vec<(Launch,Arguments)>=Vec::new();commands.try_reserve_exact(32+4*n.div_ceil(256)).map_err(|_|Error::HostAllocation)?; - let mut push=|shape,args|->Result<()>{commands.push((shape,Arguments::for_launch(shape,args)?));Ok(())}; - let theta=crate::qsa_index_ffi::theta();if !theta.is_finite()||theta<=0.0{return Err(Error::InvalidDriverValue("QSA theta"));} - let mut decode_positions=Vec::new(); - let positions=if decode { - decode_positions.try_reserve_exact(24*4).map_err(|_|Error::HostAllocation)?; - for _ in 0..24{decode_positions.extend((p0 as i32).to_le_bytes());} - let b=self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; - let full=self.handle(4,self.sizes[4])?; - let h=full.checked_subspan(b.len(),self.sizes[4]-24*4,24*4)?; - h.validate_projection_extent(24*4,4)?; - if h.overlaps(24*4,self.handle(4,n*128*4)?,n*128*4){return Err(Error::OutputAliasesInput);} + let spare = encode(dead)?; + let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare); + if result.is_err() { + self.failed = true; + } + result?; + self.upload(1, tail)?; + self.upload(2, dead)?; + let mut steps = Vec::new(); + steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; + for row in 0..n { + let pos = p + row; + for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { + steps.extend((x as i32).to_le_bytes()); + } + } + let zero = vec![0u8; 64]; + let mut flags = vec![0u8; 64]; + let status = self.handle(10, 64)?; + let mut commands: Vec<(Launch, Arguments)> = Vec::new(); + commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; + let mut push = |shape, args| -> Result<()> { + commands.push((shape, Arguments::for_launch(shape, args)?)); + Ok(()) + }; + let theta = crate::qsa_index_ffi::theta(); + if !theta.is_finite() || theta <= 0.0 { + return Err(Error::InvalidDriverValue("QSA theta")); + } + let mut decode_positions = Vec::new(); + let positions = if decode { + decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; + for _ in 0..24 { + decode_positions.extend((p0 as i32).to_le_bytes()); + } + let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; + let full = self.handle(4, self.sizes[4])?; + let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; + h.validate_projection_extent(24 * 4, 4)?; + if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { + return Err(Error::OutputAliasesInput); + } Some(h) - }else{None}; - let k_h=out[0];let pooled_h=self.handle(0,self.sizes[0])?;let tail_h=self.handle(1,self.sizes[1])?;let dead_h=self.handle(2,self.sizes[2])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(2),vec![A::Address(k_h),A::Address(gamma[1]),A::Address(k_h),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(2),vec![A::Address(k_h),A::Address(k_h),A::I32(2),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*2),vec![A::Address(k_h),A::Address(gamma[1]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*2),vec![A::Address(k_h),A::I64(2),A::I64(256),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(k_h),A::I64((n*512)as i64),A::Address(status),A::U32(0)])?; - push(Launch::Split((n*6144)as u32),vec![A::Address(qfull_h),A::Address(out[2]),A::I64(t as i64)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(24),vec![A::Address(out[2]),A::Address(gamma[0]),A::Address(out[2]),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(24),vec![A::Address(out[2]),A::Address(out[2]),A::I32(24),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*24),vec![A::Address(out[2]),A::Address(gamma[0]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*24),vec![A::Address(out[2]),A::I64(24),A::I64(256),A::I64(6144),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*6144)as u32),vec![A::Address(out[2]),A::I64((n*6144)as i64),A::Address(status),A::U32(1)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(4),vec![A::Address(iq_h),A::Address(gamma[2]),A::Address(iq_h),A::I32(128),A::F32(1e-6)])?; - push(Launch::DecodeRope(4),vec![A::Address(iq_h),A::Address(iq_h),A::I32(4),A::I32(128),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*4),vec![A::Address(iq_h),A::Address(gamma[2]),A::I64(128),A::I64(128),A::F32(1e-6)])?; - push(Launch::Rope(t*4),vec![A::Address(iq_h),A::I64(4),A::I64(128),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(iq_h),A::I64((n*512)as i64),A::Address(status),A::U32(2)])?; - if decode { - push(Launch::DecodeAppend,vec![A::Address(raw_h),A::Address(out[4]),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I32(crate::serving_context::geometry().cells() as i32),A::F32(theta)])?; } else { - if p==0{push(Launch::First,vec![A::Address(raw_h),A::Address(gamma[3]),A::F32(1e-6),A::Address(dead_h),A::Address(pooled_h),A::F32(theta)])?;} - let first=if p<=3{0}else{(p-3).div_ceil(4)};let hi=if end-1>=3{Some((end-4)/4)}else{None}; - if let Some(hi)=hi.filter(|hi|*hi>=first){push(Launch::Blocks((hi-first+1)as u32),vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I64(first as i64),A::I64(hi as i64),A::F32(theta)])?;} - push(Launch::Tail,vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::Address(tail_h)])?; + None + }; + let k_h = out[0]; + let pooled_h = self.handle(0, self.sizes[0])?; + let tail_h = self.handle(1, self.sizes[1])?; + let dead_h = self.handle(2, self.sizes[2])?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(2), + vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(2), + vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 2), + vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 2), + vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)], + )?; + push(Launch::Split((n * 6144) as u32), vec![A::Address(qfull_h), A::Address(out[2]), A::I64(t as i64)])?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(24), + vec![ + A::Address(out[2]), + A::Address(out[2]), + A::I32(24), + A::I32(256), + A::F32(theta), + A::Address(positions), + ], + )?; + } else { + push( + Launch::Rms(t * 24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 24), + vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 6144) as u32), + vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)], + )?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(4), + vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 4), + vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)], + )?; + if decode { + push( + Launch::DecodeAppend, + vec![ + A::Address(raw_h), + A::Address(out[4]), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I32(crate::serving_context::geometry().cells() as i32), + A::F32(theta), + ], + )?; + } else { + if p == 0 { + push( + Launch::First, + vec![ + A::Address(raw_h), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(dead_h), + A::Address(pooled_h), + A::F32(theta), + ], + )?; + } + let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; + let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; + if let Some(hi) = hi.filter(|hi| *hi >= first) { + push( + Launch::Blocks((hi - first + 1) as u32), + vec![ + A::Address(raw_h), + A::I64(t as i64), + A::I64(p0 as i64), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I64(first as i64), + A::I64(hi as i64), + A::F32(theta), + ], + )?; + } + push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?; + } + for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] { + push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?; } - for (h,count) in [(pooled_h,(nb+1)*128),(tail_h,384),(dead_h,128)]{push(Launch::Scan(count as u32),vec![A::Address(h),A::I64(count as i64),A::Address(status),A::U32(3)])?;} // Original prompt selection reuses one 256-row score tile. Every // offset is checked against the actual whole producer allocation. - let tile_rows=if decode {1}else{n.min(256)}; - let scores=self.handle(9,tile_rows*max_blocks()*4)?; + let tile_rows = if decode { 1 } else { n.min(256) }; + let scores = self.handle(9, tile_rows * max_blocks() * 4)?; for first_row in (0..n).step_by(256) { - let count=(n-first_row).min(256);let ct=count as u32; - let iq_tile=iq_h.checked_subspan(n*512*4,first_row*512*4,count*512*4)?; - let steps_tile=out[4].checked_subspan(n*16,first_row*16,count*16)?; - let ids_tile=out[3].checked_subspan(n*CAP*4,first_row*CAP*4,count*CAP*4)?; - let tile_reach=(p+first_row+count)/4+1; + let count = (n - first_row).min(256); + let ct = count as u32; + let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?; + let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?; + let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?; + let tile_reach = (p + first_row + count) / 4 + 1; if decode { - push(Launch::DecodeScores,vec![A::Address(pooled_h),A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I32(1),A::I64(max_blocks() as i64),A::Address(scores)])?; + push( + Launch::DecodeScores, + vec![ + A::Address(pooled_h), + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I32(1), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; } else { - push(Launch::Tc{t:ct,reach:tile_reach as u32},vec![A::Address(pooled_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(count as i64),A::I64(max_blocks() as i64),A::I64(tile_reach as i64),A::Address(scores)])?; - push(Launch::ScoreTail(ct),vec![A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(max_blocks() as i64),A::Address(scores)])?; + push( + Launch::Tc { t: ct, reach: tile_reach as u32 }, + vec![ + A::Address(pooled_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(count as i64), + A::I64(max_blocks() as i64), + A::I64(tile_reach as i64), + A::Address(scores), + ], + )?; + push( + Launch::ScoreTail(ct), + vec![ + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; } - push(Launch::ScoreScan((count*max_blocks())as u32),vec![A::Address(scores),A::Address(steps_tile),A::I32(count as i32),A::I64(max_blocks() as i64),A::Address(status),A::U32(4)])?; - push(Launch::Topk(ct),vec![A::Address(scores),A::Address(steps_tile),A::I64(max_blocks() as i64),A::I64(CAP as i64),A::Address(ids_tile)])?; + push( + Launch::ScoreScan((count * max_blocks()) as u32), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I32(count as i32), + A::I64(max_blocks() as i64), + A::Address(status), + A::U32(4), + ], + )?; + push( + Launch::Topk(ct), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::I64(CAP as i64), + A::Address(ids_tile), + ], + )?; } - push(Launch::Round((n*128)as u32),vec![A::Address(raw_h),A::I64((n*128)as i64)])?; - push(Launch::Scan((n*128)as u32),vec![A::Address(raw_h),A::I64((n*128)as i64),A::Address(status),A::U32(5)])?; - let context=self.context;let blas=ws.blas()?;let guard=match context.enter(){Ok(guard)=>guard,Err(error)=>{self.failed=true;ws.mark_failed();context.poison();context.retain_driver();return Err(error);}}; - let operation=(||{context.driver.api.copy_from(status,&zero)?;context.driver.api.copy_from(out[4],&steps)?; - if let Some(positions)=positions{context.driver.api.copy_from(positions,&decode_positions)?;} + push(Launch::Round((n * 128) as u32), vec![A::Address(raw_h), A::I64((n * 128) as i64)])?; + push( + Launch::Scan((n * 128) as u32), + vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)], + )?; + let context = self.context; + let blas = ws.blas()?; + let guard = match context.enter() { + Ok(guard) => guard, + Err(error) => { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + return Err(error); + } + }; + let operation = (|| { + context.driver.api.copy_from(status, &zero)?; + context.driver.api.copy_from(out[4], &steps)?; + if let Some(positions) = positions { + context.driver.api.copy_from(positions, &decode_positions)?; + } // Pageable uploads/status have a real dependency before the nonblocking shared stream. - context.driver.api.synchronize()?;let module=self.module.as_ref().ok_or(Error::ContextPoisoned)?; - for(shape,args)in &mut commands{module.launch(*shape,blas.stream(),args)?;}Ok(())})(); - let sync=blas.synchronize();let read=if sync.is_ok(){context.driver.api.copy_to(status,&mut flags)}else{Ok(())};let pop=guard.finish(); - if operation.is_err()||sync.is_err()||read.is_err()||pop.is_err(){self.failed=true;ws.mark_failed();context.poison();context.retain_driver(); - std::mem::forget((commands,steps,zero,flags,decode_positions));return combine(combine(combine(operation,sync),read),pop);} - combine(combine(combine(operation,sync),read),pop)?; - for flag in flags.as_chunks::<4>().0{if u32::from_le_bytes(*flag)>1{self.failed=true;return Err(Error::InvalidDriverValue("QSA finite status"));}} - if flags[24..].iter().any(|x|*x!=0){self.failed=true;return Err(Error::InvalidDriverValue("QSA unused status"));} - if flags[..24].iter().any(|x|*x!=0){return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores"));} - let ids=self.read(out[3],n*CAP*4)?; - for row in 0..n{let width=(p+row+1).min(CAP);let mut last=None;for i in 0..width{ - let at=(row*CAP+i)*4;let id=i32::from_le_bytes(ids[at..at+4].try_into().map_err(|_|Error::InvalidSize)?); - if id<0||id as usize>p+row||last.is_some_and(|old|old>=id){return Err(Error::InvalidDriverValue("QSA selected IDs"));}last=Some(id); - }}Ok(()) + context.driver.api.synchronize()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + for (shape, args) in &mut commands { + module.launch(*shape, blas.stream(), args)?; + } + Ok(()) + })(); + let sync = blas.synchronize(); + let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + std::mem::forget((commands, steps, zero, flags, decode_positions)); + return combine(combine(combine(operation, sync), read), pop); + } + combine(combine(combine(operation, sync), read), pop)?; + for flag in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*flag) > 1 { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA finite status")); + } + } + if flags[24..].iter().any(|x| *x != 0) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..24].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); + } + let ids = self.read(out[3], n * CAP * 4)?; + for row in 0..n { + let width = (p + row + 1).min(CAP); + let mut last = None; + for i in 0..width { + let at = (row * CAP + i) * 4; + let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?); + if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) { + return Err(Error::InvalidDriverValue("QSA selected IDs")); + } + last = Some(id); + } + } + Ok(()) + } + pub(super) fn final_state_original_arena( + &mut self, + p0: usize, + t: usize, + initial_tail: &[f32], + raw_h: ffi::BufferHandle, + ) -> Result { + let end = p0 + t; + let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; + let mut values: Vec> = Vec::new(); + values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + for (i, size) in sizes.into_iter().enumerate() { + let bytes = self.read(self.handle(i, size)?, size)?; + let mut v = Vec::new(); + v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; + v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if v.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA final index")); + } + values.push(v.into_boxed_slice()); + } + let bytes = self.read(raw_h, t * 128 * 4)?; + let mut rounded = Vec::new(); + rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; + rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if rounded.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); + } + let mut old_tail = [0.0; 384]; + old_tail.copy_from_slice(initial_tail); + Ok(QsaPromptIndexState { + end: end as u32, + p0: p0 as u32, + t: t as u32, + initial_tail: old_tail, + rounded: rounded.into_boxed_slice(), + pooled: values.remove(0), + tail: values.remove(0), + dead: values.remove(0), + }) } - pub(super) fn final_state_original_arena(&mut self,p0:usize,t:usize,initial_tail:&[f32],raw_h:ffi::BufferHandle)->Result{let end=p0+t;let sizes=[(end/4+1)*128*4,384*4,128*4];let mut values:Vec>=Vec::new();values.try_reserve_exact(3).map_err(|_|Error::HostAllocation)?; - for(i,size)in sizes.into_iter().enumerate(){let bytes=self.read(self.handle(i,size)?,size)?;let mut v=Vec::new();v.try_reserve_exact(size/4).map_err(|_|Error::HostAllocation)?;v.extend(bytes.as_chunks::<4>().0.iter().map(|x|f32::from_le_bytes(*x)));if v.iter().any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("QSA final index"));}values.push(v.into_boxed_slice());} - let bytes=self.read(raw_h,t*128*4)?; - let mut rounded=Vec::new();rounded.try_reserve_exact(t*128).map_err(|_|Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x|f32::from_le_bytes(*x))); - if rounded.iter().any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("QSA rounded index rows"));} - let mut old_tail=[0.0;384];old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState{end:end as u32,p0:p0 as u32,t:t as u32,initial_tail:old_tail,rounded:rounded.into_boxed_slice(),pooled:values.remove(0),tail:values.remove(0),dead:values.remove(0)})} } diff --git a/crates/cuda-driver/src/qsa_prompt_device_kv.rs b/crates/cuda-driver/src/qsa_prompt_device_kv.rs index a3316fe9..711f5071 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_kv.rs @@ -1,39 +1,41 @@ //! Actual normalized K/V arena loans; original snapshot/quantize/readback unchanged. use super::*; -impl<'ctx> QsaPromptKv<'ctx>{ - pub(crate) fn append_original_arena(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&crate::qsa_prompt_index::OriginalQsaDeviceSelection<'_, '_, '_, 'ctx>)->Result{ - let t=inputs.rows();if inputs.first_position()!=prior.next_position(){return Err(Error::InvalidQwenShape)} +impl<'ctx> QsaPromptKv<'ctx> { + pub(crate) fn append_original_arena( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + inputs: &crate::qsa_prompt_index::OriginalQsaDeviceSelection<'_, '_, '_, 'ctx>, + ) -> Result { + let t = inputs.rows(); + if inputs.first_position() != prior.next_position() { + return Err(Error::InvalidQwenShape); + } self.validate_snapshot(prior)?; stage.validate(self.context)?; workspace.validate_context(self.context)?; if !(1..=8192).contains(&t) - || prior - .0 - .end - .checked_add(t) - .is_none_or(|n| n > crate::serving_context::geometry().cells()) + || prior.0.end.checked_add(t).is_none_or(|n| n > crate::serving_context::geometry().cells()) { return Err(Error::InvalidQwenShape); } let end = prior.0.end + t; - let (kh,vh)=inputs.kv_spans(self.context)?; - let (k,v)=(kh.qwen_address(),vh.qwen_address()); - self.reject_original_span(kh,t*512*4)?; - self.reject_original_span(vh,t*512*4)?; - stage.reject_original_span(kh,t*512*4)?; - stage.reject_original_span(vh,t*512*4)?; - workspace.reject_alias(kh,t*512*4)?;workspace.reject_alias(vh,t*512*4)?; + let (kh, vh) = inputs.kv_spans(self.context)?; + let (k, v) = (kh.qwen_address(), vh.qwen_address()); + self.reject_original_span(kh, t * 512 * 4)?; + self.reject_original_span(vh, t * 512 * 4)?; + stage.reject_original_span(kh, t * 512 * 4)?; + stage.reject_original_span(vh, t * 512 * 4)?; + workspace.reject_alias(kh, t * 512 * 4)?; + workspace.reject_alias(vh, t * 512 * 4)?; // Reserve snapshot metadata and completed page storage BEFORE device writes. let mut pages = Vec::new(); - pages - .try_reserve_exact(end.div_ceil(4)) - .map_err(|_| Error::HostAllocation)?; + pages.try_reserve_exact(end.div_ceil(4)).map_err(|_| Error::HostAllocation)?; pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); let first = prior.0.end / 4; let mut completed = Vec::new(); - completed - .try_reserve_exact(end.div_ceil(4)-first) - .map_err(|_| Error::HostAllocation)?; + completed.try_reserve_exact(end.div_ceil(4) - first).map_err(|_| Error::HostAllocation)?; for _ in first..end.div_ceil(4) { let mut a = Vec::new(); a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; @@ -62,19 +64,8 @@ impl<'ctx> QsaPromptKv<'ctx>{ let rp = self.pools.addresses()?; let sp = stage.pools.addresses()?; let hp = self.host_addresses()?; - let guard = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I32((t * 512) as i32), - Arg::U64(sa), - ])?; - stage.run( - workspace, - 0, - [(t * 512).div_ceil(256) as u32, 1, 1], - 256, - guard, - )?; + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; + stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } @@ -114,9 +105,7 @@ impl<'ctx> QsaPromptKv<'ctx>{ } for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { for (i, b) in bufs.iter_mut().enumerate() { - let pool = stage.pools.buffers[i] - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let pool = stage.pools.buffers[i].as_ref().ok_or(Error::ContextPoisoned)?; read_range(pool, p * PAGE[i], b)?; } } @@ -144,23 +133,25 @@ impl<'ctx> QsaPromptKv<'ctx>{ stage.current = Some(result.0.clone()); self.current = Some(result.0.clone()); self.mapped_current = Some(result.0.clone()); - Ok(CompletedQsaKvAppend { - final_snapshot: result, - first: prior.0.end, - rows: t, - }) + Ok(CompletedQsaKvAppend { final_snapshot: result, first: prior.0.end, rows: t }) } - pub(crate) fn reject_original_span(&self,h:crate::ffi::BufferHandle,n:usize)->Result<()>{ - for b in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()){ - if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} - }self.resolver.as_ref().ok_or(Error::ContextPoisoned)?.reject_original_span(h,n) + pub(crate) fn reject_original_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { + for b in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + self.resolver.as_ref().ok_or(Error::ContextPoisoned)?.reject_original_span(h, n) } } -impl QsaPromptStage<'_>{ - pub(crate) fn reject_original_span(&self,h:crate::ffi::BufferHandle,n:usize)->Result<()>{ - for b in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()).chain(self.status.iter()){ - if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} - }Ok(()) +impl QsaPromptStage<'_> { + pub(crate) fn reject_original_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { + for b in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()).chain(self.status.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) } } diff --git a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs index 9a44a0fa..f1fd261a 100644 --- a/crates/cuda-driver/src/qsa_prompt_host_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_host_ffi.rs @@ -3,15 +3,9 @@ use crate::{Error, Result}; /// Original payload + four 256 B cursor alignment allowances, for the configured serving context /// (`276_825_088` at the trained 262144 cells). fn configured_bytes() -> Result { - crate::serving_context::geometry() - .mapped_host_bytes() - .map_err(|_| Error::InvalidSize) + crate::serving_context::geometry().mapped_host_bytes().map_err(|_| Error::InvalidSize) } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] mod enabled { use super::*; use std::ffi::c_void; @@ -32,14 +26,7 @@ mod enabled { } } fn check(op: &'static str, n: i32) -> Result<()> { - if n == 0 { - Ok(()) - } else { - Err(Error::Driver { - operation: op, - code: n, - }) - } + if n == 0 { Ok(()) } else { Err(Error::Driver { operation: op, code: n }) } } macro_rules! sym { ($l:ident,$s:literal,$t:ty) => {{ @@ -62,9 +49,7 @@ mod enabled { impl MappedAllocation { pub(crate) fn new() -> Result { // SAFETY: fixed library name and flags; the returned handle (checked non-null next) is owned by `Library`. - let library = Library(unsafe { - libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) - }); + let library = Library(unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }); if library.0.is_null() { return Err(Error::LibraryUnavailable); } @@ -79,23 +64,14 @@ mod enabled { if ptr.is_null() { return Err(Error::InvalidDriverValue("cuMemHostAlloc")); } - let mut owner = Self { - library: Some(library), - host: Some(ptr as usize), - alias: 0, - bytes, - free, - }; + let mut owner = Self { library: Some(library), host: Some(ptr as usize), alias: 0, bytes, free }; // SAFETY: `ptr` is the base of the live cuMemHostAlloc allocation above (DEVICEMAP), valid out pointer. - let op = check("cuMemHostGetDevicePointer_v2", unsafe { - address(&mut owner.alias, ptr, 0) - }); + let op = check("cuMemHostGetDevicePointer_v2", unsafe { address(&mut owner.alias, ptr, 0) }); if let Err(primary) = op { let _ = owner.close(); return Err(primary); } - if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) - { + if owner.alias == 0 || owner.alias % 256 != 0 || owner.host.is_none_or(|p| p % 256 != 0) { let _ = owner.close(); return Err(Error::InvalidDriverValue("mapped-host-alignment")); } @@ -111,9 +87,7 @@ mod enabled { } pub(crate) fn address(&self, offset: usize, n: usize) -> Result { self.range(offset, n)?; - self.alias - .checked_add(offset as u64) - .ok_or(Error::InvalidSize) + self.alias.checked_add(offset as u64).ok_or(Error::InvalidSize) } fn range(&self, o: usize, n: usize) -> Result { let p = self.host.ok_or(Error::ContextPoisoned)?; @@ -165,11 +139,7 @@ mod enabled { } } } -#[cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use enabled::MappedAllocation; #[cfg(not(all( feature = "cuda-driver", diff --git a/crates/cuda-driver/src/qsa_prompt_index.rs b/crates/cuda-driver/src/qsa_prompt_index.rs index bf191a2d..26061d2a 100644 --- a/crates/cuda-driver/src/qsa_prompt_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_index.rs @@ -1,273 +1,85 @@ //! Closed literal Original prompt RMS/RoPE, three-launch index append and TC/radix selection. //! Output buffers are genuine exact-T owners, not fabricated active-prefix DeviceBuffers. use super::*; -use crate::{NativeBatchWorkspace,qsa_index_ffi::{Arg as A,Arguments,Launch,Module}}; -const INDEX:&[u8]=include_bytes!("qsa_prompt_indexer.ptx"); -const SELECT:&[u8]=include_bytes!("qsa_prompt_select.ptx"); -const POSTOPS:&[u8]=include_bytes!("qsa_prompt_postops.ptx"); -const DECODE_POSTOPS:&[u8]=include_bytes!("qsa_decode_postops.ptx"); -const CAP:usize=2051;const RESERVE:usize=128*1024*1024; -/// Score row stride (blocks plus tail and spare) of the configured serving context: `65538` at 262144 cells. -fn max_blocks()->usize{crate::serving_context::geometry().max_blocks()} -// pooled,tail,dead,block_position,raw,K,V,Qfull,IndexQ,scores,status. -fn sizes()->[usize;11]{let g=crate::serving_context::geometry();[g.pooled_rows()*128*4,384*4,128*4,4,64*128*4,4,4,64*12288*4,64*512*4,64*g.max_blocks()*4,64]} +use crate::{ + NativeBatchWorkspace, + qsa_index_ffi::{Arg as A, Arguments, Launch, Module}, +}; +const INDEX: &[u8] = include_bytes!("qsa_prompt_indexer.ptx"); +const SELECT: &[u8] = include_bytes!("qsa_prompt_select.ptx"); +const POSTOPS: &[u8] = include_bytes!("qsa_prompt_postops.ptx"); +const DECODE_POSTOPS: &[u8] = include_bytes!("qsa_decode_postops.ptx"); +const CAP: usize = 2051; +const RESERVE: usize = 128 * 1024 * 1024; /// Frozen trained-context (262144 cells) value; internal sizing uses `sizes()` of the serving context. -pub const QSA_PROMPT_INDEX_BYTES:usize=65537*128*4+384*4+128*4+4+64*(128+12288+512+65538)*4+64+8; -pub struct QsaPromptIndexWorkspace<'ctx>{capacity:usize,sizes:[usize;11],context:&'ctx Context<'ctx>,buffers:[Option>;11],module:Option,late:Option,failed:bool} -impl Context<'_>{pub fn qsa_prompt_index_workspace(&self)->Result>{QsaPromptIndexWorkspace::new(self)} - pub fn qsa_prompt_index_workspace_for_capacity(&self,capacity:usize)->Result>{QsaPromptIndexWorkspace::new_capacity(self,capacity)}} -fn encode(values:&[f32])->Result>{let mut v=Vec::new();v.try_reserve_exact(values.len()*4).map_err(|_|Error::HostAllocation)?;v.extend(values.iter().flat_map(|x|x.to_le_bytes()));Ok(v)} -impl<'ctx> QsaPromptIndexWorkspace<'ctx>{ - fn new(context:&'ctx Context<'ctx>)->Result{ - Self::new_capacity(context,64) - } - fn new_capacity(context:&'ctx Context<'ctx>,capacity:usize)->Result{ - if !(1..=8192).contains(&capacity){return Err(Error::InvalidQwenShape);} - let mut sizes=sizes();for i in [4,7,8]{sizes[i]=(sizes[i]/64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?;} - sizes[9]=capacity.min(256)*max_blocks()*4; - let output_bytes=capacity*(512*2+6144+CAP+4)*4; - if INDEX.starts_with(b"// UNSEALED")||SELECT.starts_with(b"// UNSEALED")||POSTOPS.starts_with(b"// UNSEALED")||DECODE_POSTOPS.starts_with(b"// UNSEALED"){return Err(Error::InvalidDriverValue("QSA index assets unsealed"));} - if context.is_poisoned(){return Err(Error::ContextPoisoned);}let peak=sizes.iter().try_fold(0usize,|sum,n|sum.checked_add(*n).ok_or(Error::BudgetExceeded))?.checked_add(output_bytes+RESERVE).ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(peak).is_none_or(|n|n>context.budget_bytes())||context.memory_info()?.0Result{ - if !(1..=8192).contains(&capacity){return Err(Error::InvalidQwenShape);} - let s=sizes();Ok(s[0]+s[1]+s[2]+s[3]+8+64+capacity*(128+12288+512)*4+capacity.min(256)*max_blocks()*4) - } - pub fn prompt_output_bytes(capacity:usize)->Result{if !(1..=8192).contains(&capacity){return Err(Error::InvalidQwenShape);}Ok(capacity*(512*2+6144+CAP+4)*4)} - pub fn capacity(&self)->usize{self.capacity} - pub fn allocated_bytes(&self)->usize{self.buffers.iter().flatten().map(DeviceBuffer::len).sum()} - pub fn is_failed(&self)->bool{self.failed||self.context.is_poisoned()} - fn handle(&self,i:usize,n:usize)->Result{let b=self.buffers.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned)?; - if self.is_failed(){return Err(Error::ContextPoisoned);}if !std::ptr::eq(b.context,self.context)||b.len()!=self.sizes[i]||n==0||n>b.len(){return Err(Error::InvalidQwenShape);} - b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(),0,n)} - fn upload(&mut self,i:usize,v:&[f32])->Result<()>{let bytes=encode(v)?;let result=self.buffers[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&bytes);if result.is_err(){self.failed=true;}result} - fn weights(&self,weights:[&DeviceBuffer<'_>;4],ws:&NativeBatchWorkspace<'_>)->Result<[ffi::BufferHandle;4]>{ - ws.validate_context(self.context)?;let mut out=[self.handle(10,4)?;4]; - for(i,w)in weights.into_iter().enumerate(){let n=if i<2{256}else{128}*4; - if !std::ptr::eq(w.context,self.context){return Err(Error::ContextMismatch);}if w.len()!=n{return Err(Error::InvalidQwenShape);} - out[i]=w.handle.ok_or(Error::ContextPoisoned)?;out[i].validate_projection_extent(n,4)?;ws.reject_alias(out[i],n)?; - for(j,b)in self.buffers.iter().enumerate(){let b=b.as_ref().ok_or(Error::ContextPoisoned)?;let h=self.handle(j,b.len())?; - ws.reject_alias(h,b.len())?;if h.overlaps(b.len(),out[i],n){return Err(Error::OutputAliasesInput);} - for earlier in self.buffers[..j].iter().flatten(){if h.overlaps(b.len(),earlier.handle.ok_or(Error::ContextPoisoned)?,earlier.len()){return Err(Error::OutputAliasesInput);}} - } - }Ok(out) - } - #[allow(clippy::too_many_arguments)] // Closed original fixed QSA geometry and genuine prior image. - pub fn append_select<'lease>(&'lease mut self,p0:u32,t:u32,prior_pooled:&[f32],prior_tail:&[f32],prior_dead:&[f32], - raw:&[f32],k:&[f32],v:&[f32],qfull:&[f32],index_q:&[f32],weights:[&DeviceBuffer<'_>;4],ws:&mut NativeBatchWorkspace<'ctx>) - ->Result>{ - self.append_select_inner(p0,t,prior_pooled,prior_tail,prior_dead,raw,k,v,qfull,index_q,weights,ws,false) - } - /// T1 Original decode index: scalar native append and FP32 warp scores. - #[allow(clippy::too_many_arguments)] - pub fn append_select_decode<'lease>(&'lease mut self,p0:u32,prior_pooled:&[f32],prior_tail:&[f32],prior_dead:&[f32], - raw:&[f32],k:&[f32],v:&[f32],qfull:&[f32],index_q:&[f32],weights:[&DeviceBuffer<'_>;4],ws:&mut NativeBatchWorkspace<'ctx>) - ->Result>{ - self.append_select_inner(p0,1,prior_pooled,prior_tail,prior_dead,raw,k,v,qfull,index_q,weights,ws,true) - } - #[allow(clippy::too_many_arguments)] - fn append_select_inner<'lease>(&'lease mut self,p0:u32,t:u32,prior_pooled:&[f32],prior_tail:&[f32],prior_dead:&[f32], - raw:&[f32],k:&[f32],v:&[f32],qfull:&[f32],index_q:&[f32],weights:[&DeviceBuffer<'_>;4],ws:&mut NativeBatchWorkspace<'ctx>,decode:bool) - ->Result>{ - if decode && t!=1 {return Err(Error::InvalidQwenShape);} - let n=t as usize;let p=p0 as usize; - if n==0||n>self.capacity||p.checked_add(n).is_none_or(|e|e>crate::serving_context::geometry().cells())||prior_pooled.len()!=p/4*128 - ||prior_tail.len()!=384||prior_dead.len()!=128||raw.len()!=n*128||k.len()!=n*512||v.len()!=n*512||qfull.len()!=n*12288||index_q.len()!=n*512{return Err(Error::InvalidQwenShape);} - if [prior_pooled,prior_tail,prior_dead,raw,k,v,qfull,index_q].into_iter().any(|x|x.iter().any(|v|!v.is_finite())){return Err(Error::NonFiniteMmqOutput("QSA prompt input/prior"));} - let gamma=self.weights(weights,ws)?;let output_bytes=n*(512*2+6144+CAP+4)*4; - if self.context.allocated_bytes().checked_add(output_bytes+RESERVE).is_none_or(|x|x>self.context.budget_bytes())||self.context.memory_info()?.0>;5]=std::array::from_fn(|_|None); - let sizes=[n*512*4,n*512*4,n*6144*4,n*CAP*4,n*4*4]; - let operation=(||{for(i,size)in sizes.iter().enumerate(){outputs[i]=Some(self.context.allocate(*size)?);}Ok(())})(); - if let Err(primary)=operation{for b in outputs.into_iter().flatten(){let _=b.release();}return Err(primary);} - let handles:[ffi::BufferHandle;5]=std::array::from_fn(|i|outputs[i].as_ref().and_then(|b|b.handle).expect("allocated exact owner")); - let admission=(|| { - for (i,b) in outputs.iter().enumerate(){let b=b.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(b.context,self.context)||b.len()!=sizes[i]{return Err(Error::InvalidQwenShape);} - handles[i].validate_projection_extent(sizes[i],4)?;ws.reject_alias(handles[i],sizes[i])?; - for other in self.buffers.iter().flatten(){if handles[i].overlaps(sizes[i],other.handle.ok_or(Error::ContextPoisoned)?,other.len()){return Err(Error::OutputAliasesInput);}} - for j in 0..i{if handles[i].overlaps(sizes[i],handles[j],sizes[j]){return Err(Error::OutputAliasesInput);}} - for (j,g) in gamma.iter().enumerate(){if handles[i].overlaps(sizes[i],*g,if j<2{1024}else{512}){return Err(Error::OutputAliasesInput);}} - }Ok(()) - })();if let Err(primary)=admission{for b in outputs.into_iter().flatten(){let _=b.release();}return Err(primary);} - let operation=self.run(p0,t,prior_pooled,prior_tail,prior_dead,raw,k,v,qfull,index_q,gamma,handles,ws,decode); - if let Err(primary)=operation{if self.context.is_poisoned(){std::mem::forget(outputs);}else{for b in outputs.into_iter().flatten(){let _=b.release();}}return Err(primary);} - let state=self.final_state(p,n,prior_tail); - match state{Ok(state)=>Ok(QsaPromptSelection{owner:self,outputs,t,p0,state}),Err(primary)=>{if self.context.is_poisoned(){std::mem::forget(outputs);}else{for b in outputs.into_iter().flatten(){let _=b.release();}}Err(primary)}} - } - #[allow(clippy::too_many_arguments)] - fn run(&mut self,p0:u32,t:u32,pooled:&[f32],tail:&[f32],dead:&[f32],raw:&[f32],k:&[f32],v:&[f32],qfull:&[f32],iq:&[f32], - gamma:[ffi::BufferHandle;4],out:[ffi::BufferHandle;5],ws:&mut NativeBatchWorkspace<'ctx>,decode:bool)->Result<()>{ - let n=t as usize;let p=p0 as usize;let end=p+n;let nb=end/4; - if !pooled.is_empty(){self.upload(0,pooled)?;} - // The current spare is genuine prior state even when this batch completes no block. - let spare=encode(dead)?;let result=self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p/4*128*4,&spare); - if result.is_err(){self.failed=true;}result?; - self.upload(1,tail)?;self.upload(2,dead)?; - for(i,x)in [(4,raw),(7,qfull),(8,iq)]{self.upload(i,x)?;} - let mut steps=Vec::new();steps.try_reserve_exact(n*16).map_err(|_|Error::HostAllocation)?; - for row in 0..n{let pos=p+row;for x in [pos,pos+1,(pos+1)/4,(pos+1).min(CAP)]{steps.extend((x as i32).to_le_bytes());}} - let zero=vec![0u8;64];let mut flags=vec![0u8;64];let status=self.handle(10,64)?;let mut commands:Vec<(Launch,Arguments)>=Vec::new();commands.try_reserve_exact(32+4*n.div_ceil(256)).map_err(|_|Error::HostAllocation)?; - let mut push=|shape,args|->Result<()>{commands.push((shape,Arguments::for_launch(shape,args)?));Ok(())}; - let theta=crate::qsa_index_ffi::theta();if !theta.is_finite()||theta<=0.0{return Err(Error::InvalidDriverValue("QSA theta"));} - let mut decode_positions=Vec::new(); - let positions=if decode { - decode_positions.try_reserve_exact(24*4).map_err(|_|Error::HostAllocation)?; - for _ in 0..24{decode_positions.extend((p0 as i32).to_le_bytes());} - let b=self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; - let full=self.handle(4,self.sizes[4])?; - let h=full.checked_subspan(b.len(),self.sizes[4]-24*4,24*4)?; - h.validate_projection_extent(24*4,4)?; - if h.overlaps(24*4,self.handle(4,n*128*4)?,n*128*4){return Err(Error::OutputAliasesInput);} - Some(h) - }else{None}; - let raw_h=self.handle(4,n*128*4)?;let k_h=out[0];let iq_h=self.handle(8,n*512*4)?;let pooled_h=self.handle(0,self.sizes[0])?;let tail_h=self.handle(1,self.sizes[1])?;let dead_h=self.handle(2,self.sizes[2])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(2),vec![A::Address(k_h),A::Address(gamma[1]),A::Address(k_h),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(2),vec![A::Address(k_h),A::Address(k_h),A::I32(2),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*2),vec![A::Address(k_h),A::Address(gamma[1]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*2),vec![A::Address(k_h),A::I64(2),A::I64(256),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(k_h),A::I64((n*512)as i64),A::Address(status),A::U32(0)])?; - push(Launch::Split((n*6144)as u32),vec![A::Address(self.handle(7,n*12288*4)?),A::Address(out[2]),A::I64(t as i64)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(24),vec![A::Address(out[2]),A::Address(gamma[0]),A::Address(out[2]),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(24),vec![A::Address(out[2]),A::Address(out[2]),A::I32(24),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*24),vec![A::Address(out[2]),A::Address(gamma[0]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*24),vec![A::Address(out[2]),A::I64(24),A::I64(256),A::I64(6144),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*6144)as u32),vec![A::Address(out[2]),A::I64((n*6144)as i64),A::Address(status),A::U32(1)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(4),vec![A::Address(iq_h),A::Address(gamma[2]),A::Address(iq_h),A::I32(128),A::F32(1e-6)])?; - push(Launch::DecodeRope(4),vec![A::Address(iq_h),A::Address(iq_h),A::I32(4),A::I32(128),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*4),vec![A::Address(iq_h),A::Address(gamma[2]),A::I64(128),A::I64(128),A::F32(1e-6)])?; - push(Launch::Rope(t*4),vec![A::Address(iq_h),A::I64(4),A::I64(128),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(iq_h),A::I64((n*512)as i64),A::Address(status),A::U32(2)])?; - if decode { - push(Launch::DecodeAppend,vec![A::Address(raw_h),A::Address(out[4]),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I32(crate::serving_context::geometry().cells() as i32),A::F32(theta)])?; - } else { - if p==0{push(Launch::First,vec![A::Address(raw_h),A::Address(gamma[3]),A::F32(1e-6),A::Address(dead_h),A::Address(pooled_h),A::F32(theta)])?;} - let first=if p<=3{0}else{(p-3).div_ceil(4)};let hi=if end-1>=3{Some((end-4)/4)}else{None}; - if let Some(hi)=hi.filter(|hi|*hi>=first){push(Launch::Blocks((hi-first+1)as u32),vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I64(first as i64),A::I64(hi as i64),A::F32(theta)])?;} - push(Launch::Tail,vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::Address(tail_h)])?; - } - for (h,count) in [(pooled_h,(nb+1)*128),(tail_h,384),(dead_h,128)]{push(Launch::Scan(count as u32),vec![A::Address(h),A::I64(count as i64),A::Address(status),A::U32(3)])?;} - // Original prompt selection reuses one 256-row score tile. Every - // offset is checked against the actual whole producer allocation. - let tile_rows=if decode {1}else{n.min(256)}; - let scores=self.handle(9,tile_rows*max_blocks()*4)?; - for first_row in (0..n).step_by(256) { - let count=(n-first_row).min(256);let ct=count as u32; - let iq_tile=iq_h.checked_subspan(n*512*4,first_row*512*4,count*512*4)?; - let steps_tile=out[4].checked_subspan(n*16,first_row*16,count*16)?; - let ids_tile=out[3].checked_subspan(n*CAP*4,first_row*CAP*4,count*CAP*4)?; - let tile_reach=(p+first_row+count)/4+1; - if decode { - push(Launch::DecodeScores,vec![A::Address(pooled_h),A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I32(1),A::I64(max_blocks() as i64),A::Address(scores)])?; - } else { - push(Launch::Tc{t:ct,reach:tile_reach as u32},vec![A::Address(pooled_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(count as i64),A::I64(max_blocks() as i64),A::I64(tile_reach as i64),A::Address(scores)])?; - push(Launch::ScoreTail(ct),vec![A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(max_blocks() as i64),A::Address(scores)])?; - } - push(Launch::ScoreScan((count*max_blocks())as u32),vec![A::Address(scores),A::Address(steps_tile),A::I32(count as i32),A::I64(max_blocks() as i64),A::Address(status),A::U32(4)])?; - push(Launch::Topk(ct),vec![A::Address(scores),A::Address(steps_tile),A::I64(max_blocks() as i64),A::I64(CAP as i64),A::Address(ids_tile)])?; - } - push(Launch::Round((n*128)as u32),vec![A::Address(raw_h),A::I64((n*128)as i64)])?; - push(Launch::Scan((n*128)as u32),vec![A::Address(raw_h),A::I64((n*128)as i64),A::Address(status),A::U32(5)])?; - let k_bytes=encode(k)?;let v_bytes=encode(v)?;let context=self.context;let blas=ws.blas()?;let guard=match context.enter(){Ok(guard)=>guard,Err(error)=>{self.failed=true;ws.mark_failed();context.poison();context.retain_driver();return Err(error);}}; - let operation=(||{context.driver.api.copy_from(status,&zero)?;context.driver.api.copy_from(out[4],&steps)?; - context.driver.api.copy_from(out[0],&k_bytes)?;context.driver.api.copy_from(out[1],&v_bytes)?; - if let Some(positions)=positions{context.driver.api.copy_from(positions,&decode_positions)?;} - // Pageable uploads/status have a real dependency before the nonblocking shared stream. - context.driver.api.synchronize()?;let module=self.module.as_ref().ok_or(Error::ContextPoisoned)?; - for(shape,args)in &mut commands{module.launch(*shape,blas.stream(),args)?;}Ok(())})(); - let sync=blas.synchronize();let read=if sync.is_ok(){context.driver.api.copy_to(status,&mut flags)}else{Ok(())};let pop=guard.finish(); - if operation.is_err()||sync.is_err()||read.is_err()||pop.is_err(){self.failed=true;ws.mark_failed();context.poison();context.retain_driver(); - std::mem::forget((commands,steps,zero,flags,k_bytes,v_bytes,decode_positions));return combine(combine(combine(operation,sync),read),pop);} - combine(combine(combine(operation,sync),read),pop)?; - for flag in flags.as_chunks::<4>().0{if u32::from_le_bytes(*flag)>1{self.failed=true;return Err(Error::InvalidDriverValue("QSA finite status"));}} - if flags[24..].iter().any(|x|*x!=0){self.failed=true;return Err(Error::InvalidDriverValue("QSA unused status"));} - if flags[..24].iter().any(|x|*x!=0){return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores"));} - let ids=self.read(out[3],n*CAP*4)?; - for row in 0..n{let width=(p+row+1).min(CAP);let mut last=None;for i in 0..width{ - let at=(row*CAP+i)*4;let id=i32::from_le_bytes(ids[at..at+4].try_into().map_err(|_|Error::InvalidSize)?); - if id<0||id as usize>p+row||last.is_some_and(|old|old>=id){return Err(Error::InvalidDriverValue("QSA selected IDs"));}last=Some(id); - }}Ok(()) - } - fn read(&mut self,h:ffi::BufferHandle,n:usize)->Result>{let mut bytes=Vec::new();bytes.try_reserve_exact(n).map_err(|_|Error::HostAllocation)?;bytes.resize(n,0); - let g=self.context.enter().map_err(|error|{self.failed=true;self.context.poison();self.context.retain_driver();error})?;let copy=self.context.driver.api.copy_to(h,&mut bytes);let sync=self.context.driver.api.synchronize();let pop=g.finish(); - if copy.is_err()||sync.is_err()||pop.is_err(){self.failed=true;self.context.poison();self.context.retain_driver();std::mem::forget(bytes);return combine(combine(copy,sync),pop).map(|()|unreachable!("failed readback remains primary"));} - combine(combine(copy,sync),pop)?;Ok(bytes)} - fn final_state(&mut self,p0:usize,t:usize,initial_tail:&[f32])->Result{let end=p0+t;let sizes=[(end/4+1)*128*4,384*4,128*4];let mut values:Vec>=Vec::new();values.try_reserve_exact(3).map_err(|_|Error::HostAllocation)?; - for(i,size)in sizes.into_iter().enumerate(){let bytes=self.read(self.handle(i,size)?,size)?;let mut v=Vec::new();v.try_reserve_exact(size/4).map_err(|_|Error::HostAllocation)?;v.extend(bytes.as_chunks::<4>().0.iter().map(|x|f32::from_le_bytes(*x)));if v.iter().any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("QSA final index"));}values.push(v.into_boxed_slice());} - let bytes=self.read(self.handle(4,t*128*4)?,t*128*4)?; - let mut rounded=Vec::new();rounded.try_reserve_exact(t*128).map_err(|_|Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x|f32::from_le_bytes(*x))); - if rounded.iter().any(|x|!x.is_finite()){return Err(Error::NonFiniteMmqOutput("QSA rounded index rows"));} - let mut old_tail=[0.0;384];old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState{end:end as u32,p0:p0 as u32,t:t as u32,initial_tail:old_tail,rounded:rounded.into_boxed_slice(),pooled:values.remove(0),tail:values.remove(0),dead:values.remove(0)})} - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{let mut result=Ok(());self.failed=true; - if let Some(m)=self.late.take(){let close=if self.context.is_poisoned(){std::mem::forget(m);Err(Error::ContextPoisoned)}else{match self.context.enter(){Ok(g)=>combine(m.close(),g.finish()),Err(e)=>{std::mem::forget(m);Err(e)}}};result=combine(result,close);} - if let Some(m)=self.module.take(){let close=if self.context.is_poisoned(){std::mem::forget(m);Err(Error::ContextPoisoned)}else{match self.context.enter(){Ok(g)=>combine(m.close(),g.finish()),Err(e)=>{std::mem::forget(m);Err(e)}}};result=combine(result,close);} - for b in &mut self.buffers{if let Some(b)=b.take(){let close=if self.context.is_poisoned(){std::mem::forget(b);Err(Error::ContextPoisoned)}else{b.release()};result=combine(result,close);}} - if result.is_err(){self.context.poison();self.context.retain_driver();}result} +pub const QSA_PROMPT_INDEX_BYTES: usize = + 65537 * 128 * 4 + 384 * 4 + 128 * 4 + 4 + 64 * (128 + 12288 + 512 + 65538) * 4 + 64 + 8; +pub struct QsaPromptIndexWorkspace<'ctx> { + capacity: usize, + sizes: [usize; 11], + context: &'ctx Context<'ctx>, + buffers: [Option>; 11], + module: Option, + late: Option, + failed: bool, } -impl Drop for QsaPromptIndexWorkspace<'_>{fn drop(&mut self){let _=self.close_inner();}} -pub struct QsaPromptIndexState{end:u32,p0:u32,t:u32,initial_tail:[f32;384],rounded:Box<[f32]>,pooled:Box<[f32]>,tail:Box<[f32]>,dead:Box<[f32]>} -pub struct QsaPromptIndexPrefix<'state>{state:&'state QsaPromptIndexState,end:u32,tail:[f32;384]} -impl QsaPromptIndexPrefix<'_>{pub fn end_position(&self)->u32{self.end}pub fn pooled(&self)->&[f32]{&self.state.pooled[..self.end as usize/4*128]}pub fn tail(&self)->&[f32]{&self.tail}pub fn dead(&self)->&[f32]{&self.state.dead}} -impl QsaPromptIndexState{ - pub fn completed_prefix(&self,rows:u32)->Result>{ - if rows==0||rows>self.t{return Err(Error::InvalidQwenShape);}let mut tail=self.initial_tail; - for row in 0..rows as usize{let slot=(self.p0 as usize+row)%4;if slot<3{tail[slot*128..(slot+1)*128].copy_from_slice(&self.rounded[row*128..(row+1)*128]);}} - Ok(QsaPromptIndexPrefix{state:self,end:self.p0+rows,tail}) - } - pub fn end_position(&self)->u32{self.end}pub fn pooled(&self)->&[f32]{&self.pooled}pub fn tail(&self)->&[f32]{&self.tail}pub fn dead(&self)->&[f32]{&self.dead}} -pub struct QsaPromptSelection<'lease,'ctx>{owner:&'lease mut QsaPromptIndexWorkspace<'ctx>,outputs:[Option>;5],t:u32,p0:u32,state:QsaPromptIndexState} -impl QsaPromptSelection<'_, '_>{ - pub fn rows(&self)->u32{self.t}pub fn first_position(&self)->u32{self.p0}pub fn final_index(&self)->&QsaPromptIndexState{&self.state} - pub fn with_completed_buffers(&self,f:impl FnOnce(&DeviceBuffer<'_>,&DeviceBuffer<'_>,&DeviceBuffer<'_>)->Result)->Result{if self.owner.is_failed(){return Err(Error::ContextPoisoned);}f(self.outputs[2].as_ref().ok_or(Error::ContextPoisoned)?,self.outputs[3].as_ref().ok_or(Error::ContextPoisoned)?,self.outputs[4].as_ref().ok_or(Error::ContextPoisoned)?)} - pub fn with_completed_kv(&self,f:impl FnOnce(&DeviceBuffer<'_>,&DeviceBuffer<'_>)->Result)->Result{if self.owner.is_failed(){return Err(Error::ContextPoisoned);}f(self.outputs[0].as_ref().ok_or(Error::ContextPoisoned)?,self.outputs[1].as_ref().ok_or(Error::ContextPoisoned)?)} +pub struct QsaPromptIndexState { + end: u32, + p0: u32, + t: u32, + initial_tail: [f32; 384], + rounded: Box<[f32]>, + pooled: Box<[f32]>, + tail: Box<[f32]>, + dead: Box<[f32]>, } -impl QsaPromptSelection<'_, '_>{ - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{let mut result=Ok(());for b in &mut self.outputs{if let Some(b)=b.take(){let close=if self.owner.context.is_poisoned(){std::mem::forget(b);Err(Error::ContextPoisoned)}else{b.release()};if close.is_err(){self.owner.failed=true;self.owner.context.poison();self.owner.context.retain_driver();}result=combine(result,close);}}result} +pub struct QsaPromptIndexPrefix<'state> { + state: &'state QsaPromptIndexState, + end: u32, + tail: [f32; 384], +} +pub struct QsaPromptSelection<'lease, 'ctx> { + owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, + outputs: [Option>; 5], + t: u32, + p0: u32, + state: QsaPromptIndexState, } -impl Drop for QsaPromptSelection<'_, '_>{fn drop(&mut self){let _=self.close_inner();}} #[path = "qsa_prompt_device_index.rs"] mod device_index; #[path = "qsa_prompt_device.rs"] mod prompt_device; -pub use prompt_device::{OriginalQsaPromptDevice,OriginalQsaDeviceSelection,OriginalQsaPromptWeights}; pub(crate) use prompt_device::kv_stage_spans_of; +pub use prompt_device::{OriginalQsaDeviceSelection, OriginalQsaPromptDevice, OriginalQsaPromptWeights}; -#[path="qsa_resident_index.rs"] +#[path = "qsa_resident_index.rs"] mod resident_index; -pub use resident_index::{OriginalQsaResidentIndex,OriginalQsaIndexCheckpoint,OriginalQsaIndexBatch}; -#[path="qsa_resident_index_program.rs"] +pub use resident_index::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex}; +#[path = "qsa_resident_index_program.rs"] mod resident_program; -#[path="qsa_resident_transfer.rs"] +#[path = "qsa_resident_transfer.rs"] #[allow(unsafe_code)] pub(crate) mod resident_transfer; -pub use prompt_device::{OriginalQsaResidentSelection,OriginalQsaResidentPromptDevice}; -#[path="qsa_resident_scalar_index.rs"] +pub use prompt_device::{OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection}; +#[path = "qsa_resident_scalar_index.rs"] mod resident_scalar_index; -pub use resident_scalar_index::{OriginalQsaResidentScalarIndex,OriginalQsaResidentScalarSelection}; +pub use resident_scalar_index::{OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection}; -#[cfg(all(feature="cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width="64"))] -pub use resident_index::verification_commit::{OriginalVerifyQsaJournal,OriginalVerifyRope}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub use resident_index::verification_commit::{OriginalVerifyQsaJournal, OriginalVerifyRope}; + +mod max_blocks_fn; +#[allow(unused_imports)] +use max_blocks_fn::encode; +#[allow(unused_imports)] +use max_blocks_fn::max_blocks; +#[allow(unused_imports)] +use max_blocks_fn::sizes; +mod impl_qsapromptindexworkspace; +mod impl_qsapromptindexworkspace_2; +mod impl_qsapromptindexworkspace_3; +mod impl_qsapromptindexworkspace_4; diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs new file mode 100644 index 00000000..281bc150 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { + Self::new_capacity(context, 64) + } + pub(super) fn new_capacity(context: &'ctx Context<'ctx>, capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let mut sizes = sizes(); + for i in [4, 7, 8] { + sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + let output_bytes = capacity * (512 * 2 + 6144 + CAP + 4) * 4; + if INDEX.starts_with(b"// UNSEALED") + || SELECT.starts_with(b"// UNSEALED") + || POSTOPS.starts_with(b"// UNSEALED") + || DECODE_POSTOPS.starts_with(b"// UNSEALED") + { + return Err(Error::InvalidDriverValue("QSA index assets unsealed")); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + let peak = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(output_bytes + RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < peak + { + return Err(Error::BudgetExceeded); + } + let mut owner = Self { + capacity, + sizes, + context, + buffers: std::array::from_fn(|_| None), + module: None, + late: None, + failed: false, + }; + let operation = (|| { + for (i, n) in sizes.into_iter().enumerate() { + owner.buffers[i] = Some(context.allocate(n)?); + } + let g = context.enter().map_err(|error| { + owner.failed = true; + context.poison(); + context.retain_driver(); + error + })?; + let loaded = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS); + let pop = g.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + owner.module = Some(loaded?); + pop?; + if context.memory_info()?.0 < output_bytes + RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(primary) = operation { + let _ = owner.close(); + return Err(primary); + } + Ok(owner) + } + pub fn prompt_device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + let s = sizes(); + Ok(s[0] + + s[1] + + s[2] + + s[3] + + 8 + + 64 + + capacity * (128 + 12288 + 512) * 4 + + capacity.min(256) * max_blocks() * 4) + } + pub fn prompt_output_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } + Ok(capacity * (512 * 2 + 6144 + CAP + 4) * 4) + } + pub fn capacity(&self) -> usize { + self.capacity + } + pub fn allocated_bytes(&self) -> usize { + self.buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(super) fn handle(&self, i: usize, n: usize) -> Result { + let b = self.buffers.get(i).and_then(Option::as_ref).ok_or(Error::ContextPoisoned)?; + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + if !std::ptr::eq(b.context, self.context) || b.len() != self.sizes[i] || n == 0 || n > b.len() { + return Err(Error::InvalidQwenShape); + } + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), 0, n) + } + pub(super) fn upload(&mut self, i: usize, v: &[f32]) -> Result<()> { + let bytes = encode(v)?; + let result = self.buffers[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &bytes); + if result.is_err() { + self.failed = true; + } + result + } + pub(super) fn weights( + &self, + weights: [&DeviceBuffer<'_>; 4], + ws: &NativeBatchWorkspace<'_>, + ) -> Result<[ffi::BufferHandle; 4]> { + ws.validate_context(self.context)?; + let mut out = [self.handle(10, 4)?; 4]; + for (i, w) in weights.into_iter().enumerate() { + let n = if i < 2 { 256 } else { 128 } * 4; + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + if w.len() != n { + return Err(Error::InvalidQwenShape); + } + out[i] = w.handle.ok_or(Error::ContextPoisoned)?; + out[i].validate_projection_extent(n, 4)?; + ws.reject_alias(out[i], n)?; + for (j, b) in self.buffers.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + let h = self.handle(j, b.len())?; + ws.reject_alias(h, b.len())?; + if h.overlaps(b.len(), out[i], n) { + return Err(Error::OutputAliasesInput); + } + for earlier in self.buffers[..j].iter().flatten() { + if h.overlaps(b.len(), earlier.handle.ok_or(Error::ContextPoisoned)?, earlier.len()) { + return Err(Error::OutputAliasesInput); + } + } + } + } + Ok(out) + } + #[allow(clippy::too_many_arguments)] // Closed original fixed QSA geometry and genuine prior image. + pub fn append_select<'lease>( + &'lease mut self, + p0: u32, + t: u32, + prior_pooled: &[f32], + prior_tail: &[f32], + prior_dead: &[f32], + raw: &[f32], + k: &[f32], + v: &[f32], + qfull: &[f32], + index_q: &[f32], + weights: [&DeviceBuffer<'_>; 4], + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.append_select_inner( + p0, + t, + prior_pooled, + prior_tail, + prior_dead, + raw, + k, + v, + qfull, + index_q, + weights, + ws, + false, + ) + } + /// T1 Original decode index: scalar native append and FP32 warp scores. + #[allow(clippy::too_many_arguments)] + pub fn append_select_decode<'lease>( + &'lease mut self, + p0: u32, + prior_pooled: &[f32], + prior_tail: &[f32], + prior_dead: &[f32], + raw: &[f32], + k: &[f32], + v: &[f32], + qfull: &[f32], + index_q: &[f32], + weights: [&DeviceBuffer<'_>; 4], + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.append_select_inner( + p0, + 1, + prior_pooled, + prior_tail, + prior_dead, + raw, + k, + v, + qfull, + index_q, + weights, + ws, + true, + ) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs new file mode 100644 index 00000000..7eace98f --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs @@ -0,0 +1,149 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(super) fn append_select_inner<'lease>( + &'lease mut self, + p0: u32, + t: u32, + prior_pooled: &[f32], + prior_tail: &[f32], + prior_dead: &[f32], + raw: &[f32], + k: &[f32], + v: &[f32], + qfull: &[f32], + index_q: &[f32], + weights: [&DeviceBuffer<'_>; 4], + ws: &mut NativeBatchWorkspace<'ctx>, + decode: bool, + ) -> Result> { + if decode && t != 1 { + return Err(Error::InvalidQwenShape); + } + let n = t as usize; + let p = p0 as usize; + if n == 0 + || n > self.capacity + || p.checked_add(n).is_none_or(|e| e > crate::serving_context::geometry().cells()) + || prior_pooled.len() != p / 4 * 128 + || prior_tail.len() != 384 + || prior_dead.len() != 128 + || raw.len() != n * 128 + || k.len() != n * 512 + || v.len() != n * 512 + || qfull.len() != n * 12288 + || index_q.len() != n * 512 + { + return Err(Error::InvalidQwenShape); + } + if [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q] + .into_iter() + .any(|x| x.iter().any(|v| !v.is_finite())) + { + return Err(Error::NonFiniteMmqOutput("QSA prompt input/prior")); + } + let gamma = self.weights(weights, ws)?; + let output_bytes = n * (512 * 2 + 6144 + CAP + 4) * 4; + if self + .context + .allocated_bytes() + .checked_add(output_bytes + RESERVE) + .is_none_or(|x| x > self.context.budget_bytes()) + || self.context.memory_info()?.0 < output_bytes + RESERVE + { + return Err(Error::BudgetExceeded); + } + let mut outputs: [Option>; 5] = std::array::from_fn(|_| None); + let sizes = [n * 512 * 4, n * 512 * 4, n * 6144 * 4, n * CAP * 4, n * 4 * 4]; + let operation = (|| { + for (i, size) in sizes.iter().enumerate() { + outputs[i] = Some(self.context.allocate(*size)?); + } + Ok(()) + })(); + if let Err(primary) = operation { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } + return Err(primary); + } + let handles: [ffi::BufferHandle; 5] = + std::array::from_fn(|i| outputs[i].as_ref().and_then(|b| b.handle).expect("allocated exact owner")); + let admission = (|| { + for (i, b) in outputs.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(b.context, self.context) || b.len() != sizes[i] { + return Err(Error::InvalidQwenShape); + } + handles[i].validate_projection_extent(sizes[i], 4)?; + ws.reject_alias(handles[i], sizes[i])?; + for other in self.buffers.iter().flatten() { + if handles[i].overlaps(sizes[i], other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { + return Err(Error::OutputAliasesInput); + } + } + for j in 0..i { + if handles[i].overlaps(sizes[i], handles[j], sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + for (j, g) in gamma.iter().enumerate() { + if handles[i].overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) { + return Err(Error::OutputAliasesInput); + } + } + } + Ok(()) + })(); + if let Err(primary) = admission { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } + return Err(primary); + } + let operation = self.run( + p0, + t, + prior_pooled, + prior_tail, + prior_dead, + raw, + k, + v, + qfull, + index_q, + gamma, + handles, + ws, + decode, + ); + if let Err(primary) = operation { + if self.context.is_poisoned() { + std::mem::forget(outputs); + } else { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } + } + return Err(primary); + } + let state = self.final_state(p, n, prior_tail); + match state { + Ok(state) => Ok(QsaPromptSelection { owner: self, outputs, t, p0, state }), + Err(primary) => { + if self.context.is_poisoned() { + std::mem::forget(outputs); + } else { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } + } + Err(primary) + } + } + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs new file mode 100644 index 00000000..c12fdc1f --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs @@ -0,0 +1,371 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (3). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(super) fn run( + &mut self, + p0: u32, + t: u32, + pooled: &[f32], + tail: &[f32], + dead: &[f32], + raw: &[f32], + k: &[f32], + v: &[f32], + qfull: &[f32], + iq: &[f32], + gamma: [ffi::BufferHandle; 4], + out: [ffi::BufferHandle; 5], + ws: &mut NativeBatchWorkspace<'ctx>, + decode: bool, + ) -> Result<()> { + let n = t as usize; + let p = p0 as usize; + let end = p + n; + let nb = end / 4; + if !pooled.is_empty() { + self.upload(0, pooled)?; + } + // The current spare is genuine prior state even when this batch completes no block. + let spare = encode(dead)?; + let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare); + if result.is_err() { + self.failed = true; + } + result?; + self.upload(1, tail)?; + self.upload(2, dead)?; + for (i, x) in [(4, raw), (7, qfull), (8, iq)] { + self.upload(i, x)?; + } + let mut steps = Vec::new(); + steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; + for row in 0..n { + let pos = p + row; + for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { + steps.extend((x as i32).to_le_bytes()); + } + } + let zero = vec![0u8; 64]; + let mut flags = vec![0u8; 64]; + let status = self.handle(10, 64)?; + let mut commands: Vec<(Launch, Arguments)> = Vec::new(); + commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; + let mut push = |shape, args| -> Result<()> { + commands.push((shape, Arguments::for_launch(shape, args)?)); + Ok(()) + }; + let theta = crate::qsa_index_ffi::theta(); + if !theta.is_finite() || theta <= 0.0 { + return Err(Error::InvalidDriverValue("QSA theta")); + } + let mut decode_positions = Vec::new(); + let positions = if decode { + decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; + for _ in 0..24 { + decode_positions.extend((p0 as i32).to_le_bytes()); + } + let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; + let full = self.handle(4, self.sizes[4])?; + let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; + h.validate_projection_extent(24 * 4, 4)?; + if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { + return Err(Error::OutputAliasesInput); + } + Some(h) + } else { + None + }; + let raw_h = self.handle(4, n * 128 * 4)?; + let k_h = out[0]; + let iq_h = self.handle(8, n * 512 * 4)?; + let pooled_h = self.handle(0, self.sizes[0])?; + let tail_h = self.handle(1, self.sizes[1])?; + let dead_h = self.handle(2, self.sizes[2])?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(2), + vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(2), + vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 2), + vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 2), + vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)], + )?; + push( + Launch::Split((n * 6144) as u32), + vec![A::Address(self.handle(7, n * 12288 * 4)?), A::Address(out[2]), A::I64(t as i64)], + )?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(24), + vec![ + A::Address(out[2]), + A::Address(out[2]), + A::I32(24), + A::I32(256), + A::F32(theta), + A::Address(positions), + ], + )?; + } else { + push( + Launch::Rms(t * 24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 24), + vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 6144) as u32), + vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)], + )?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(4), + vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 4), + vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)], + )?; + if decode { + push( + Launch::DecodeAppend, + vec![ + A::Address(raw_h), + A::Address(out[4]), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I32(crate::serving_context::geometry().cells() as i32), + A::F32(theta), + ], + )?; + } else { + if p == 0 { + push( + Launch::First, + vec![ + A::Address(raw_h), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(dead_h), + A::Address(pooled_h), + A::F32(theta), + ], + )?; + } + let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; + let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; + if let Some(hi) = hi.filter(|hi| *hi >= first) { + push( + Launch::Blocks((hi - first + 1) as u32), + vec![ + A::Address(raw_h), + A::I64(t as i64), + A::I64(p0 as i64), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I64(first as i64), + A::I64(hi as i64), + A::F32(theta), + ], + )?; + } + push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?; + } + for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] { + push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?; + } + // Original prompt selection reuses one 256-row score tile. Every + // offset is checked against the actual whole producer allocation. + let tile_rows = if decode { 1 } else { n.min(256) }; + let scores = self.handle(9, tile_rows * max_blocks() * 4)?; + for first_row in (0..n).step_by(256) { + let count = (n - first_row).min(256); + let ct = count as u32; + let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?; + let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?; + let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?; + let tile_reach = (p + first_row + count) / 4 + 1; + if decode { + push( + Launch::DecodeScores, + vec![ + A::Address(pooled_h), + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I32(1), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; + } else { + push( + Launch::Tc { t: ct, reach: tile_reach as u32 }, + vec![ + A::Address(pooled_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(count as i64), + A::I64(max_blocks() as i64), + A::I64(tile_reach as i64), + A::Address(scores), + ], + )?; + push( + Launch::ScoreTail(ct), + vec![ + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; + } + push( + Launch::ScoreScan((count * max_blocks()) as u32), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I32(count as i32), + A::I64(max_blocks() as i64), + A::Address(status), + A::U32(4), + ], + )?; + push( + Launch::Topk(ct), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::I64(CAP as i64), + A::Address(ids_tile), + ], + )?; + } + push(Launch::Round((n * 128) as u32), vec![A::Address(raw_h), A::I64((n * 128) as i64)])?; + push( + Launch::Scan((n * 128) as u32), + vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)], + )?; + let k_bytes = encode(k)?; + let v_bytes = encode(v)?; + let context = self.context; + let blas = ws.blas()?; + let guard = match context.enter() { + Ok(guard) => guard, + Err(error) => { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + return Err(error); + } + }; + let operation = (|| { + context.driver.api.copy_from(status, &zero)?; + context.driver.api.copy_from(out[4], &steps)?; + context.driver.api.copy_from(out[0], &k_bytes)?; + context.driver.api.copy_from(out[1], &v_bytes)?; + if let Some(positions) = positions { + context.driver.api.copy_from(positions, &decode_positions)?; + } + // Pageable uploads/status have a real dependency before the nonblocking shared stream. + context.driver.api.synchronize()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + for (shape, args) in &mut commands { + module.launch(*shape, blas.stream(), args)?; + } + Ok(()) + })(); + let sync = blas.synchronize(); + let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + std::mem::forget((commands, steps, zero, flags, k_bytes, v_bytes, decode_positions)); + return combine(combine(combine(operation, sync), read), pop); + } + combine(combine(combine(operation, sync), read), pop)?; + for flag in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*flag) > 1 { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA finite status")); + } + } + if flags[24..].iter().any(|x| *x != 0) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..24].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); + } + let ids = self.read(out[3], n * CAP * 4)?; + for row in 0..n { + let width = (p + row + 1).min(CAP); + let mut last = None; + for i in 0..width { + let at = (row * CAP + i) * 4; + let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?); + if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) { + return Err(Error::InvalidDriverValue("QSA selected IDs")); + } + last = Some(id); + } + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs new file mode 100644 index 00000000..5b737012 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs @@ -0,0 +1,227 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (4), impl Drop_for_QsaPromptIndexWorkspace, impl QsaPromptIndexPrefix, impl QsaPromptIndexState, impl QsaPromptSelection, impl QsaPromptSelection .... + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + pub(super) fn read(&mut self, h: ffi::BufferHandle, n: usize) -> Result> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + bytes.resize(n, 0); + let g = self.context.enter().map_err(|error| { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + error + })?; + let copy = self.context.driver.api.copy_to(h, &mut bytes); + let sync = self.context.driver.api.synchronize(); + let pop = g.finish(); + if copy.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(bytes); + return combine(combine(copy, sync), pop).map(|()| unreachable!("failed readback remains primary")); + } + combine(combine(copy, sync), pop)?; + Ok(bytes) + } + pub(super) fn final_state(&mut self, p0: usize, t: usize, initial_tail: &[f32]) -> Result { + let end = p0 + t; + let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; + let mut values: Vec> = Vec::new(); + values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; + for (i, size) in sizes.into_iter().enumerate() { + let bytes = self.read(self.handle(i, size)?, size)?; + let mut v = Vec::new(); + v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; + v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if v.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA final index")); + } + values.push(v.into_boxed_slice()); + } + let bytes = self.read(self.handle(4, t * 128 * 4)?, t * 128 * 4)?; + let mut rounded = Vec::new(); + rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; + rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if rounded.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); + } + let mut old_tail = [0.0; 384]; + old_tail.copy_from_slice(initial_tail); + Ok(QsaPromptIndexState { + end: end as u32, + p0: p0 as u32, + t: t as u32, + initial_tail: old_tail, + rounded: rounded.into_boxed_slice(), + pooled: values.remove(0), + tail: values.remove(0), + dead: values.remove(0), + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + self.failed = true; + if let Some(m) = self.late.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + result = combine(result, close); + } + if let Some(m) = self.module.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + }; + result = combine(result, close); + } + for b in &mut self.buffers { + if let Some(b) = b.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + result = combine(result, close); + } + } + if result.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result + } +} +impl Drop for QsaPromptIndexWorkspace<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +impl QsaPromptIndexPrefix<'_> { + pub fn end_position(&self) -> u32 { + self.end + } + pub fn pooled(&self) -> &[f32] { + &self.state.pooled[..self.end as usize / 4 * 128] + } + pub fn tail(&self) -> &[f32] { + &self.tail + } + pub fn dead(&self) -> &[f32] { + &self.state.dead + } +} +impl QsaPromptIndexState { + pub fn completed_prefix(&self, rows: u32) -> Result> { + if rows == 0 || rows > self.t { + return Err(Error::InvalidQwenShape); + } + let mut tail = self.initial_tail; + for row in 0..rows as usize { + let slot = (self.p0 as usize + row) % 4; + if slot < 3 { + tail[slot * 128..(slot + 1) * 128].copy_from_slice(&self.rounded[row * 128..(row + 1) * 128]); + } + } + Ok(QsaPromptIndexPrefix { state: self, end: self.p0 + rows, tail }) + } + pub fn end_position(&self) -> u32 { + self.end + } + pub fn pooled(&self) -> &[f32] { + &self.pooled + } + pub fn tail(&self) -> &[f32] { + &self.tail + } + pub fn dead(&self) -> &[f32] { + &self.dead + } +} +impl QsaPromptSelection<'_, '_> { + pub fn rows(&self) -> u32 { + self.t + } + pub fn first_position(&self) -> u32 { + self.p0 + } + pub fn final_index(&self) -> &QsaPromptIndexState { + &self.state + } + pub fn with_completed_buffers( + &self, + f: impl FnOnce(&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>) -> Result, + ) -> Result { + if self.owner.is_failed() { + return Err(Error::ContextPoisoned); + } + f( + self.outputs[2].as_ref().ok_or(Error::ContextPoisoned)?, + self.outputs[3].as_ref().ok_or(Error::ContextPoisoned)?, + self.outputs[4].as_ref().ok_or(Error::ContextPoisoned)?, + ) + } + pub fn with_completed_kv(&self, f: impl FnOnce(&DeviceBuffer<'_>, &DeviceBuffer<'_>) -> Result) -> Result { + if self.owner.is_failed() { + return Err(Error::ContextPoisoned); + } + f( + self.outputs[0].as_ref().ok_or(Error::ContextPoisoned)?, + self.outputs[1].as_ref().ok_or(Error::ContextPoisoned)?, + ) + } +} +impl QsaPromptSelection<'_, '_> { + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + let mut result = Ok(()); + for b in &mut self.outputs { + if let Some(b) = b.take() { + let close = if self.owner.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + if close.is_err() { + self.owner.failed = true; + self.owner.context.poison(); + self.owner.context.retain_driver(); + } + result = combine(result, close); + } + } + result + } +} +impl Drop for QsaPromptSelection<'_, '_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/max_blocks_fn.rs b/crates/cuda-driver/src/qsa_prompt_index/max_blocks_fn.rs new file mode 100644 index 00000000..f4623d14 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/max_blocks_fn.rs @@ -0,0 +1,40 @@ +//! Moved out of the parent module by STRA-338: fn max_blocks, fn sizes, impl Context, fn encode. + +#[allow(unused_imports)] +use super::*; + +/// Score row stride (blocks plus tail and spare) of the configured serving context: `65538` at 262144 cells. +pub(super) fn max_blocks() -> usize { + crate::serving_context::geometry().max_blocks() +} +// pooled,tail,dead,block_position,raw,K,V,Qfull,IndexQ,scores,status. +pub(super) fn sizes() -> [usize; 11] { + let g = crate::serving_context::geometry(); + [ + g.pooled_rows() * 128 * 4, + 384 * 4, + 128 * 4, + 4, + 64 * 128 * 4, + 4, + 4, + 64 * 12288 * 4, + 64 * 512 * 4, + 64 * g.max_blocks() * 4, + 64, + ] +} +impl Context<'_> { + pub fn qsa_prompt_index_workspace(&self) -> Result> { + QsaPromptIndexWorkspace::new(self) + } + pub fn qsa_prompt_index_workspace_for_capacity(&self, capacity: usize) -> Result> { + QsaPromptIndexWorkspace::new_capacity(self, capacity) + } +} +pub(super) fn encode(values: &[f32]) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(values.len() * 4).map_err(|_| Error::HostAllocation)?; + v.extend(values.iter().flat_map(|x| x.to_le_bytes())); + Ok(v) +} diff --git a/crates/cuda-driver/src/qsa_prompt_kv.rs b/crates/cuda-driver/src/qsa_prompt_kv.rs index 9148a93b..8b41cecd 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv.rs @@ -3,8 +3,8 @@ use crate::qsa_prompt_attention_ffi::{Arg, Arguments, Module}; use crate::qsa_prompt_host_ffi::MappedAllocation; use crate::qsa_prompt_resolver::Resolver; -use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; use crate::serving_context::geometry; +use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; use std::rc::Rc; // The `pub const` sizes below are the frozen TRAINED-context (262144 cells) values and are kept for the // public API; every internal use derives the size of the configured serving context from @@ -23,10 +23,7 @@ pub const QSA_PROMPT_MAX_SNAPSHOT_METADATA_BYTES: usize = std::mem::size_of::() + std::mem::size_of::]>>() + 2 * std::mem::size_of::() - + 65536 - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()); + + 65536 * (std::mem::size_of::>() + std::mem::size_of::() + 2 * std::mem::size_of::()); pub const QSA_PROMPT_MAPPED_HOST_BYTES: usize = 276_825_088; const RESERVE: usize = 128 * 1024 * 1024; const PAGE: [usize; 4] = [2048, 2048, 64, 64]; @@ -85,28 +82,28 @@ pub struct QsaPromptStage<'ctx> { #[path = "qsa_prompt_device_kv.rs"] mod device_kv; -#[path="qsa_mapped_journal.rs"] +#[path = "qsa_mapped_journal.rs"] mod mapped_journal; -pub use mapped_journal::{OriginalQsaMappedJournal,OriginalQsaMappedPrefix,OriginalQsaMappedAppend}; +pub use mapped_journal::{OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix}; -#[path="qsa_resident_transport.rs"] +#[path = "qsa_resident_transport.rs"] mod resident_transport; -pub use resident_transport::{OriginalQsaResidentTransport,set_qsa_prefetch_override}; +pub use resident_transport::{OriginalQsaResidentTransport, set_qsa_prefetch_override}; mod offsets_fn; #[allow(unused_imports)] -use offsets_fn::offsets; -#[allow(unused_imports)] -use offsets_fn::stage_runs; -#[allow(unused_imports)] -use offsets_fn::resident_runs; -#[allow(unused_imports)] -pub(crate) use offsets_fn::checked; -#[allow(unused_imports)] use offsets_fn::admit; #[allow(unused_imports)] use offsets_fn::bytes_i32; -mod impl_qsapromptkv; +#[allow(unused_imports)] +pub(crate) use offsets_fn::checked; +#[allow(unused_imports)] +use offsets_fn::offsets; +#[allow(unused_imports)] +use offsets_fn::resident_runs; +#[allow(unused_imports)] +use offsets_fn::stage_runs; mod impl_drop_for_qsapromptkv; +mod impl_qsapromptkv; #[allow(unused_imports)] pub(crate) use impl_drop_for_qsapromptkv::read_range; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs index 880e268e..96b353e8 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs @@ -10,20 +10,11 @@ impl Drop for QsaPromptKv<'_> { } impl<'ctx> QsaPromptStage<'ctx> { pub(super) fn new(c: &'ctx Context<'ctx>) -> Result { - admit( - c, - geometry() - .stage_bytes() - .map_err(|_| Error::BudgetExceeded)?, - )?; + admit(c, geometry().stage_bytes().map_err(|_| Error::BudgetExceeded)?)?; let g = c.enter()?; let load = Module::load( include_bytes!("../qsa_prompt_kv.ptx"), - &[ - c"leleka_qsa_kv_guard", - c"leleka_qsa_kv_append", - c"leleka_qsa_kv_scale_guard", - ], + &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"], ); let pop = g.finish(); let module = match load { @@ -84,9 +75,7 @@ impl<'ctx> QsaPromptStage<'ctx> { self.validate(self.context)?; owner.validate_context(self.context)?; owner.validate_snapshot(s)?; - if s.0.end > geometry().cells() - || s.0.pages.len() < s.0.end.div_ceil(4) - || s.0.pages.len() > geometry().pages() + if s.0.end > geometry().cells() || s.0.pages.len() < s.0.end.div_ceil(4) || s.0.pages.len() > geometry().pages() { return Err(Error::InvalidQwenShape); } @@ -113,14 +102,8 @@ impl<'ctx> QsaPromptStage<'ctx> { Ok(()) } pub(super) fn flags(&self) -> Result { - let b = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .copy_to_owned(4)?; - Ok(u32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )) + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; + Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } pub(super) fn run( &mut self, @@ -170,14 +153,7 @@ impl<'ctx> QsaPromptStage<'ctx> { Ok((self.pools.addresses()?, self.pools.table()?, s.0.end)) } pub(crate) fn reject_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { - for p in self - .pools - .buffers - .iter() - .flatten() - .chain(self.pools.table.iter()) - .chain(self.status.iter()) - { + for p in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()).chain(self.status.iter()) { if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( p.bytes, b.handle.ok_or(Error::ContextPoisoned)?, @@ -224,10 +200,7 @@ impl Drop for QsaPromptStage<'_> { } } pub(crate) fn read_range(b: &DeviceBuffer<'_>, offset: usize, bytes: &mut Vec) -> Result<()> { - let h = - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, offset, bytes.len())?; + let h = b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.bytes, offset, bytes.len())?; let g = b.context.enter()?; let op = b.context.driver.api.copy_to(h, bytes); let sync = b.context.driver.api.synchronize(); diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs index 0c834230..3adf6ba8 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2.rs @@ -3,15 +3,12 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> QsaPromptKv<'ctx> { pub(in super::super) fn new(c: &'ctx Context<'ctx>) -> Result { let slots = crate::serving_context::kv_resident_pages()?; admit( c, - geometry() - .resident_bytes_with(slots, Resolver::map_bytes(slots)?) - .map_err(|_| Error::BudgetExceeded)?, + geometry().resident_bytes_with(slots, Resolver::map_bytes(slots)?).map_err(|_| Error::BudgetExceeded)?, )?; let mut o = Self { context: c, @@ -33,23 +30,14 @@ impl<'ctx> QsaPromptKv<'ctx> { .and_then(|(_, available)| usize::try_from(available).ok()) .ok_or(Error::HostAllocation)?; #[cfg(unix)] - let text = - std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; + let text = std::fs::read_to_string("/proc/meminfo").map_err(|_| Error::HostAllocation)?; #[cfg(unix)] let available = text .lines() - .find_map(|line| { - line.strip_prefix("MemAvailable:")? - .split_whitespace() - .next()? - .parse::() - .ok() - }) + .find_map(|line| line.strip_prefix("MemAvailable:")?.split_whitespace().next()?.parse::().ok()) .and_then(|n| n.checked_mul(1024)) .ok_or(Error::HostAllocation)?; - let mapped_host = geometry() - .mapped_host_bytes() - .map_err(|_| Error::HostAllocation)?; + let mapped_host = geometry().mapped_host_bytes().map_err(|_| Error::HostAllocation)?; if available < mapped_host + 8 * 1024 * 1024 * 1024 { return Err(Error::HostAllocation); } @@ -84,11 +72,7 @@ impl<'ctx> QsaPromptKv<'ctx> { } pub fn empty_snapshot(&self) -> Result { self.validate()?; - Ok(QsaKvSnapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(Box::new([])), - end: 0, - }))) + Ok(QsaKvSnapshot(Rc::new(Snapshot { origin: self.origin.clone(), pages: Rc::new(Box::new([])), end: 0 }))) } pub fn owner_id(&self) -> QsaKvOwnerId { QsaKvOwnerId(self.origin.clone()) @@ -117,10 +101,7 @@ impl<'ctx> QsaPromptKv<'ctx> { return Err(Error::ContextPoisoned); } self.pools.validate(self.context, resident_runs(self.slots)?)?; - self.resolver - .as_ref() - .ok_or(Error::ContextPoisoned)? - .validate()?; + self.resolver.as_ref().ok_or(Error::ContextPoisoned)?.validate()?; if self.mapped.is_none() { return Err(Error::ContextPoisoned); } @@ -158,10 +139,7 @@ impl<'ctx> QsaPromptKv<'ctx> { self.validate_snapshot(s)?; w.validate_context(self.context)?; if self.current.as_ref().is_some_and(|x| Rc::ptr_eq(x, &s.0)) - && self - .mapped_current - .as_ref() - .is_some_and(|x| Rc::ptr_eq(x, &s.0)) + && self.mapped_current.as_ref().is_some_and(|x| Rc::ptr_eq(x, &s.0)) { return Ok(()); } @@ -184,10 +162,7 @@ impl<'ctx> QsaPromptKv<'ctx> { m.write(offsets[i] + p * PAGE[i], &page.bytes[i])?; } } - self.resolver - .as_mut() - .ok_or(Error::ContextPoisoned)? - .reset(w, self.pools.table()?)?; + self.resolver.as_mut().ok_or(Error::ContextPoisoned)?.reset(w, self.pools.table()?)?; self.mapped_current = Some(s.0.clone()); self.current = Some(s.0.clone()); Ok(()) @@ -210,20 +185,11 @@ impl<'ctx> QsaPromptKv<'ctx> { let host = self.host_addresses()?; let resident = self.pools.addresses()?; let table = self.pools.table()?; - self.resolver - .as_mut() - .ok_or(Error::ContextPoisoned)? - .resolve(w, table, ids, steps, t, host, resident)?; + self.resolver.as_mut().ok_or(Error::ContextPoisoned)?.resolve(w, table, ids, steps, t, host, resident)?; Ok((resident, table, s.0.end)) } pub(crate) fn reject_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { - for own in self - .pools - .buffers - .iter() - .flatten() - .chain(self.pools.table.iter()) - { + for own in self.pools.buffers.iter().flatten().chain(self.pools.table.iter()) { if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( own.bytes, b.handle.ok_or(Error::ContextPoisoned)?, @@ -232,10 +198,7 @@ impl<'ctx> QsaPromptKv<'ctx> { return Err(Error::OutputAliasesInput); } } - self.resolver - .as_ref() - .ok_or(Error::ContextPoisoned)? - .reject_alias(b) + self.resolver.as_ref().ok_or(Error::ContextPoisoned)?.reject_alias(b) } /// Inputs are the genuine full F32 normalized/RoPE K,V outputs, not half cells. /// Successful result is privately minted after quantization/scales/full completion. @@ -246,9 +209,15 @@ impl<'ctx> QsaPromptKv<'ctx> { prior: &QsaKvSnapshot, inputs: &QsaKvInputs<'_, '_>, ) -> Result { - self.append_bounded(workspace,stage,prior,inputs,64) + self.append_bounded(workspace, stage, prior, inputs, 64) } - pub fn append_for_prompt(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>)->Result { - self.append_bounded(workspace,stage,prior,inputs,8192) + pub fn append_for_prompt( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + inputs: &QsaKvInputs<'_, '_>, + ) -> Result { + self.append_bounded(workspace, stage, prior, inputs, 8192) } } diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs index f5306c5d..744aa67a 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_qsapromptkv/impl_qsapromptkv_2_2.rs @@ -3,21 +3,21 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> QsaPromptKv<'ctx> { - pub(in super::super) fn append_bounded(&mut self,workspace:&mut NativeBatchWorkspace<'ctx>,stage:&mut QsaPromptStage<'ctx>,prior:&QsaKvSnapshot,inputs:&QsaKvInputs<'_, '_>,limit:usize)->Result { + pub(in super::super) fn append_bounded( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + prior: &QsaKvSnapshot, + inputs: &QsaKvInputs<'_, '_>, + limit: usize, + ) -> Result { let QsaKvInputs { keys, values, t } = inputs; let (keys, values, t) = (*keys, *values, *t); self.validate_snapshot(prior)?; stage.validate(self.context)?; workspace.validate_context(self.context)?; - if !(1..=limit).contains(&t) - || prior - .0 - .end - .checked_add(t) - .is_none_or(|n| n > geometry().cells()) - { + if !(1..=limit).contains(&t) || prior.0.end.checked_add(t).is_none_or(|n| n > geometry().cells()) { return Err(Error::InvalidQwenShape); } let end = prior.0.end + t; @@ -30,14 +30,7 @@ impl<'ctx> QsaPromptKv<'ctx> { ) { return Err(Error::OutputAliasesInput); } - for p in self - .pools - .buffers - .iter() - .chain(stage.pools.buffers.iter()) - .flatten() - .chain(stage.status.iter()) - { + for p in self.pools.buffers.iter().chain(stage.pools.buffers.iter()).flatten().chain(stage.status.iter()) { for b in [keys, values] { if p.handle.ok_or(Error::ContextPoisoned)?.overlaps( p.bytes, @@ -52,15 +45,11 @@ impl<'ctx> QsaPromptKv<'ctx> { workspace.reject_alias(values.handle.ok_or(Error::ContextPoisoned)?, values.bytes)?; // Reserve snapshot metadata and completed page storage BEFORE device writes. let mut pages = Vec::new(); - pages - .try_reserve_exact(end.div_ceil(4)) - .map_err(|_| Error::HostAllocation)?; + pages.try_reserve_exact(end.div_ceil(4)).map_err(|_| Error::HostAllocation)?; pages.extend(prior.0.pages[..prior.0.end.div_ceil(4)].iter().cloned()); let first = prior.0.end / 4; let mut completed = Vec::new(); - completed - .try_reserve_exact(17) - .map_err(|_| Error::HostAllocation)?; + completed.try_reserve_exact(17).map_err(|_| Error::HostAllocation)?; for _ in first..end.div_ceil(4) { let mut a = Vec::new(); a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; @@ -89,19 +78,8 @@ impl<'ctx> QsaPromptKv<'ctx> { let rp = self.pools.addresses()?; let sp = stage.pools.addresses()?; let hp = self.host_addresses()?; - let guard = Arguments::new(vec![ - Arg::U64(k), - Arg::U64(v), - Arg::I32((t * 512) as i32), - Arg::U64(sa), - ])?; - stage.run( - workspace, - 0, - [(t * 512).div_ceil(256) as u32, 1, 1], - 256, - guard, - )?; + let guard = Arguments::new(vec![Arg::U64(k), Arg::U64(v), Arg::I32((t * 512) as i32), Arg::U64(sa)])?; + stage.run(workspace, 0, [(t * 512).div_ceil(256) as u32, 1, 1], 256, guard)?; if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } @@ -141,9 +119,7 @@ impl<'ctx> QsaPromptKv<'ctx> { } for (p, bufs) in (first..end.div_ceil(4)).zip(completed.iter_mut()) { for (i, b) in bufs.iter_mut().enumerate() { - let pool = stage.pools.buffers[i] - .as_ref() - .ok_or(Error::ContextPoisoned)?; + let pool = stage.pools.buffers[i].as_ref().ok_or(Error::ContextPoisoned)?; read_range(pool, p * PAGE[i], b)?; } } @@ -171,11 +147,7 @@ impl<'ctx> QsaPromptKv<'ctx> { stage.current = Some(result.0.clone()); self.current = Some(result.0.clone()); self.mapped_current = Some(result.0.clone()); - Ok(CompletedQsaKvAppend { - final_snapshot: result, - first: prior.0.end, - rows: t, - }) + Ok(CompletedQsaKvAppend { final_snapshot: result, first: prior.0.end, rows: t }) } pub fn close(mut self) -> Result<()> { self.close_inner() diff --git a/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs b/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs index ae15e5d0..7752b395 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs @@ -16,11 +16,7 @@ pub(super) fn resident_runs(slots: usize) -> Result<[usize; 4]> { leleka_context::geometry::resident_runs(slots).map_err(|_| Error::InvalidSize) } impl<'loan, 'buffers> QsaKvInputs<'loan, 'buffers> { - pub fn new( - keys: &'loan DeviceBuffer<'buffers>, - values: &'loan DeviceBuffer<'buffers>, - t: usize, - ) -> Result { + pub fn new(keys: &'loan DeviceBuffer<'buffers>, values: &'loan DeviceBuffer<'buffers>, t: usize) -> Result { if !(1..=8192).contains(&t) { return Err(Error::InvalidQwenShape); } @@ -51,9 +47,7 @@ impl QsaKvSnapshot { + std::mem::size_of::]>>() + 2 * std::mem::size_of::() + self.0.pages.len() - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) + * (std::mem::size_of::>() + std::mem::size_of::() + 2 * std::mem::size_of::()) } /// Diagnostic comparison of actual encoded logical cells. Completed batch /// snapshots may retain future backing; it is excluded from causal equality. @@ -62,15 +56,21 @@ impl QsaKvSnapshot { return false; } let pages = self.0.end.div_ceil(4); - if self.0.pages.len() < pages || other.0.pages.len() < pages { return false; } + if self.0.pages.len() < pages || other.0.pages.len() < pages { + return false; + } for page in 0..pages { let cells = (self.0.end - page * 4).min(4); let a = &self.0.pages[page]; let b = &other.0.pages[page]; for run in 0..4 { let bytes = cells * if run < 2 { 512 } else { 16 }; - if a.bytes[run].len() < bytes || b.bytes[run].len() < bytes - || a.bytes[run][..bytes] != b.bytes[run][..bytes] { return false; } + if a.bytes[run].len() < bytes + || b.bytes[run].len() < bytes + || a.bytes[run][..bytes] != b.bytes[run][..bytes] + { + return false; + } } } true @@ -101,10 +101,7 @@ impl CompletedQsaKvAppend { } impl<'ctx> Pools<'ctx> { pub(super) fn empty() -> Self { - Self { - buffers: [None, None, None, None], - table: None, - } + Self { buffers: [None, None, None, None], table: None } } pub(super) fn allocate(&mut self, c: &'ctx Context<'ctx>, sizes: [usize; 4]) -> Result<()> { for (i, n) in sizes.into_iter().enumerate() { @@ -116,33 +113,18 @@ impl<'ctx> Pools<'ctx> { pub(super) fn addresses(&self) -> Result<[u64; 4]> { let mut a = [0; 4]; for (i, b) in self.buffers.iter().enumerate() { - a[i] = b - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); + a[i] = b.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); } Ok(a) } pub(super) fn table(&self) -> Result { - Ok(self - .table - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address()) + Ok(self.table.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) } pub(super) fn validate(&self, c: &Context<'_>, sizes: [usize; 4]) -> Result<()> { for (b, n) in self.buffers.iter().zip(sizes) { checked(c, b.as_ref().ok_or(Error::ContextPoisoned)?, n)?; } - checked( - c, - self.table.as_ref().ok_or(Error::ContextPoisoned)?, - geometry().page_table_bytes(), - )?; + checked(c, self.table.as_ref().ok_or(Error::ContextPoisoned)?, geometry().page_table_bytes())?; Ok(()) } pub(super) fn close(&mut self) -> Result<()> { @@ -158,11 +140,7 @@ impl<'ctx> Pools<'ctx> { r } pub(super) fn bytes(&self) -> usize { - self.buffers - .iter() - .flatten() - .map(DeviceBuffer::len) - .sum::() + self.buffers.iter().flatten().map(DeviceBuffer::len).sum::() + self.table.as_ref().map_or(0, DeviceBuffer::len) } } @@ -174,10 +152,7 @@ pub(crate) fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result return Err(Error::ContextMismatch); } if b.bytes != n { - return Err(Error::ShapeMismatch { - expected: n, - actual: b.bytes, - }); + return Err(Error::ShapeMismatch { expected: n, actual: b.bytes }); } let h = b.handle.ok_or(Error::ContextPoisoned)?; h.validate_projection_extent(n, 4)?; @@ -188,19 +163,14 @@ pub(super) fn admit(c: &Context<'_>, n: usize) -> Result<()> { return Err(Error::ContextPoisoned); } let n = n.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(n) - .is_none_or(|x| x > c.budget) - || c.memory_info()?.0 < n - { + if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { return Err(Error::BudgetExceeded); } Ok(()) } pub(super) fn bytes_i32(xs: impl Iterator) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(xs.size_hint().0.saturating_mul(4)) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(xs.size_hint().0.saturating_mul(4)).map_err(|_| Error::HostAllocation)?; for x in xs { v.extend_from_slice(&x.to_le_bytes()); } diff --git a/crates/cuda-driver/src/qsa_prompt_resolver.rs b/crates/cuda-driver/src/qsa_prompt_resolver.rs index d3294a19..b6c05f1d 100644 --- a/crates/cuda-driver/src/qsa_prompt_resolver.rs +++ b/crates/cuda-driver/src/qsa_prompt_resolver.rs @@ -56,11 +56,7 @@ impl<'ctx> Resolver<'ctx> { let g = c.enter()?; let load = Module::load( include_bytes!("qsa_prompt_resolver.ptx"), - &[ - c"leleka_qsa_stream_reset", - c"leleka_qsa_resolve", - c"leleka_qsa_miss_copy", - ], + &[c"leleka_qsa_stream_reset", c"leleka_qsa_resolve", c"leleka_qsa_miss_copy"], ); let pop = g.finish(); let module = match load { @@ -96,11 +92,7 @@ impl<'ctx> Resolver<'ctx> { Ok(o) } pub(crate) fn bytes(&self) -> usize { - self.slots - .iter() - .flatten() - .map(DeviceBuffer::len) - .sum::() + self.slots.iter().flatten().map(DeviceBuffer::len).sum::() + self.ctl.as_ref().map_or(0, DeviceBuffer::len) } pub(crate) fn validate(&self) -> Result<()> { @@ -108,17 +100,9 @@ impl<'ctx> Resolver<'ctx> { return Err(Error::ContextPoisoned); } for b in &self.slots { - checked( - self.context, - b.as_ref().ok_or(Error::ContextPoisoned)?, - self.n_slots * 4, - )?; + checked(self.context, b.as_ref().ok_or(Error::ContextPoisoned)?, self.n_slots * 4)?; } - checked( - self.context, - self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, - CTL_BYTES, - )?; + checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?; Ok(()) } /// The seven resolver device addresses in the order `leleka_qsa_resolve` takes them @@ -126,7 +110,8 @@ impl<'ctx> Resolver<'ctx> { /// captured verifier window; the miss copy kernel takes entries 4..7. pub(crate) fn window_addresses(&self, table: u64) -> Result<[u64; 7]> { self.validate()?; - let slot = |i: usize| checked(self.context, self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, self.n_slots * 4); + let slot = + |i: usize| checked(self.context, self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, self.n_slots * 4); let ctl = checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?; Ok([table, slot(0)?, slot(1)?, slot(2)?, ctl, slot(3)?, slot(4)?]) } @@ -142,11 +127,7 @@ impl<'ctx> Resolver<'ctx> { self.n_slots * 4, )?)); } - v.push(Arg::U64(checked( - self.context, - self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, - CTL_BYTES, - )?)); + v.push(Arg::U64(checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?)); for i in 3..5 { v.push(Arg::U64(checked( self.context, @@ -168,14 +149,7 @@ impl<'ctx> Resolver<'ctx> { w.validate_context(self.context)?; let g = self.context.enter()?; let op = self.context.driver.api.synchronize().and_then(|()| { - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - i, - grid, - block, - 0, - w.blas()?.stream(), - &mut a, - ) + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(i, grid, block, 0, w.blas()?.stream(), &mut a) }); let sync = w.blas()?.synchronize(); let pop = g.finish(); @@ -225,13 +199,8 @@ impl<'ctx> Resolver<'ctx> { a.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; a.extend([Arg::U64(ids), Arg::U64(steps), Arg::I32(t as i32), Arg::I64(self.n_slots as i64)]); let mut copy = Vec::new(); - copy.try_reserve_exact(11) - .map_err(|_| Error::HostAllocation)?; - copy.push(Arg::U64(checked( - self.context, - self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, - CTL_BYTES, - )?)); + copy.try_reserve_exact(11).map_err(|_| Error::HostAllocation)?; + copy.push(Arg::U64(checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, CTL_BYTES)?)); for i in 3..5 { copy.push(Arg::U64(checked( self.context, @@ -306,10 +275,13 @@ impl Drop for Resolver<'_> { } } -impl Resolver<'_>{ - pub(crate) fn reject_original_span(&self,h:crate::ffi::BufferHandle,n:usize)->Result<()>{ - for b in self.slots.iter().flatten().chain(self.ctl.iter()){ - if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} - }Ok(()) +impl Resolver<'_> { + pub(crate) fn reject_original_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { + for b in self.slots.iter().flatten().chain(self.ctl.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) } } diff --git a/crates/cuda-driver/src/qsa_resident_attention.rs b/crates/cuda-driver/src/qsa_resident_attention.rs index 59d8eecd..c844876b 100644 --- a/crates/cuda-driver/src/qsa_resident_attention.rs +++ b/crates/cuda-driver/src/qsa_resident_attention.rs @@ -1,40 +1,45 @@ //! Same literal attention on the real selected query/IDs/steps/attn arena. use super::*; -impl<'ctx> QsaPromptAttention<'ctx>{ - pub(crate) fn attend_resident_arena(&mut self,w:&mut NativeBatchWorkspace<'ctx>,stage:&crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>,kv:&crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>,snapshot:&crate::qsa_prompt_kv::OriginalQsaMappedPrefix,inputs:&crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>)->Result<()>{ - let t=inputs.rows(); +impl<'ctx> QsaPromptAttention<'ctx> { + pub(crate) fn attend_resident_arena( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + stage: &crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>, + kv: &crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>, + snapshot: &crate::qsa_prompt_kv::OriginalQsaMappedPrefix, + inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>, + ) -> Result<()> { + let t = inputs.rows(); // Original qsa_prompt_attn_batch kernel choice (see qsa_prompt_attention_select): v2 unless the debug arm. - let(variants,guard_ix,attn_ix,scan_ix,shared)=match self.selected_kernel()?{ - PromptAttnKernel::Int8V2=>(false,0,1,2,PromptAttnKernel::Int8V2.smem_bytes()), - PromptAttnKernel::Int8V1=>(true,0,1,4,PromptAttnKernel::Int8V1.smem_bytes()), - PromptAttnKernel::Fp16|PromptAttnKernel::HybridK8V4=>return Err(Error::UnsupportedQwenOperation), + let (variants, guard_ix, attn_ix, scan_ix, shared) = match self.selected_kernel()? { + PromptAttnKernel::Int8V2 => (false, 0, 1, 2, PromptAttnKernel::Int8V2.smem_bytes()), + PromptAttnKernel::Int8V1 => (true, 0, 1, 4, PromptAttnKernel::Int8V1.smem_bytes()), + PromptAttnKernel::Fp16 | PromptAttnKernel::HybridK8V4 => return Err(Error::UnsupportedQwenOperation), }; - if variants{self.ensure_variants()?;} + if variants { + self.ensure_variants()?; + } self.validate_resident()?; w.validate_context(self.context)?; stage.validate(self.context)?; if !(1..=self.capacity).contains(&t) { return Err(Error::InvalidQwenShape); } - let(hq,hi,hs,out_h)=inputs.attention_spans(self.context)?; - let(qh,ih,sh)=(hq.qwen_address(),hi.qwen_address(),hs.qwen_address()); - for (h,n) in [(hq,t*6144*4),(hi,t*2051*4),(hs,t*16),(out_h,t*6144*4)]{ - stage.reject_span(h,n)?;w.reject_alias(h,n)?; - for b in self.output.iter().chain(self.status.iter()){ - if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} + let (hq, hi, hs, out_h) = inputs.attention_spans(self.context)?; + let (qh, ih, sh) = (hq.qwen_address(), hi.qwen_address(), hs.qwen_address()); + for (h, n) in [(hq, t * 6144 * 4), (hi, t * 2051 * 4), (hs, t * 16), (out_h, t * 6144 * 4)] { + stage.reject_span(h, n)?; + w.reject_alias(h, n)?; + for b in self.output.iter().chain(self.status.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } } } - let (pools, table, end) = kv.completed_addresses(stage,snapshot,inputs)?; - self.status - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&[0; 4])?; - let status = checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - let out=out_h.qwen_address(); + let (pools, table, end) = kv.completed_addresses(stage, snapshot, inputs)?; + self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; + let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + let out = out_h.qwen_address(); // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), @@ -69,11 +74,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Arg::I32(2051), ])?; self.run_resident(variants, w, attn_ix, [t as u32, 2, 1], 128, shared, args)?; - let scan = Arguments::new(vec![ - Arg::U64(out), - Arg::I32((t * 6144) as i32), - Arg::U64(status), - ])?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run_resident(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); @@ -83,43 +84,77 @@ impl<'ctx> QsaPromptAttention<'ctx>{ } /// Only real module/status persist; attention output lives in the affine arena. -pub struct OriginalQsaResidentAttention<'ctx>{inner:QsaPromptAttention<'ctx>} -impl<'ctx> Context<'ctx>{pub fn original_qsa_resident_attention(&'ctx self,capacity:usize)->Result>{Ok(OriginalQsaResidentAttention{inner:QsaPromptAttention::new_resident(self,capacity)?})}} -impl<'ctx> OriginalQsaResidentAttention<'ctx>{pub const fn device_bytes()->usize{4}pub fn allocated_bytes(&self)->usize{self.inner.allocated_bytes()}pub fn is_failed(&self)->bool{self.inner.is_failed()} - /// Explicit stand-in for the Original's `STRATA_QSA_WARP` / `STRATA_PROMPT_ATTN_V1` reads (default: none). - pub fn set_switches(&mut self,switches:SelectSwitches){self.inner.set_switches(switches)}pub fn close(mut self)->Result<()>{self.inner.close_resident()} - pub(crate) fn attend_resident_arena(&mut self,w:&mut NativeBatchWorkspace<'ctx>,stage:&crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>,kv:&crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>,snapshot:&crate::qsa_prompt_kv::OriginalQsaMappedPrefix,inputs:&crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>)->Result<()>{self.inner.attend_resident_arena(w,stage,kv,snapshot,inputs)} +pub struct OriginalQsaResidentAttention<'ctx> { + inner: QsaPromptAttention<'ctx>, } -impl<'ctx> QsaPromptAttention<'ctx>{ - fn validate_resident(&self)->Result<()>{if self.is_failed()||self.module.is_none()||self.output.is_some(){return Err(Error::ContextPoisoned)}checked(self.context,self.status.as_ref().ok_or(Error::ContextPoisoned)?,4)?;Ok(())} - fn new_resident(c:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidQwenShape);} +impl<'ctx> Context<'ctx> { + pub fn original_qsa_resident_attention(&'ctx self, capacity: usize) -> Result> { + Ok(OriginalQsaResidentAttention { inner: QsaPromptAttention::new_resident(self, capacity)? }) + } +} +impl<'ctx> OriginalQsaResidentAttention<'ctx> { + pub const fn device_bytes() -> usize { + 4 + } + pub fn allocated_bytes(&self) -> usize { + self.inner.allocated_bytes() + } + pub fn is_failed(&self) -> bool { + self.inner.is_failed() + } + /// Explicit stand-in for the Original's `STRATA_QSA_WARP` / `STRATA_PROMPT_ATTN_V1` reads (default: none). + pub fn set_switches(&mut self, switches: SelectSwitches) { + self.inner.set_switches(switches) + } + pub fn close(mut self) -> Result<()> { + self.inner.close_resident() + } + pub(crate) fn attend_resident_arena( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + stage: &crate::qsa_prompt_kv::OriginalQsaResidentTransport<'ctx>, + kv: &crate::qsa_prompt_kv::OriginalQsaMappedJournal<'ctx>, + snapshot: &crate::qsa_prompt_kv::OriginalQsaMappedPrefix, + inputs: &crate::qsa_prompt_index::OriginalQsaResidentSelection<'_, '_, '_, '_, '_, 'ctx>, + ) -> Result<()> { + self.inner.attend_resident_arena(w, stage, kv, snapshot, inputs) + } +} +impl<'ctx> QsaPromptAttention<'ctx> { + fn validate_resident(&self) -> Result<()> { + if self.is_failed() || self.module.is_none() || self.output.is_some() { + return Err(Error::ContextPoisoned); + } + checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + Ok(()) + } + fn new_resident(c: &'ctx Context<'ctx>, capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidQwenShape); + } if c.is_poisoned() { return Err(Error::ContextPoisoned); } - let output_bytes=0usize; - let n = output_bytes.checked_add(4+128*1024*1024).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(n) - .is_none_or(|x| x > c.budget) - || c.memory_info()?.0 < n - { + let output_bytes = 0usize; + let n = output_bytes.checked_add(4 + 128 * 1024 * 1024).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes().checked_add(n).is_none_or(|x| x > c.budget) || c.memory_info()?.0 < n { return Err(Error::BudgetExceeded); } - let g=c.enter().map_err(|e|{c.poison();c.retain_driver();e})?; + let g = c.enter().map_err(|e| { + c.poison(); + c.retain_driver(); + e + })?; let load = Module::load( include_bytes!("qsa_prompt_attention.ptx"), - &[ - c"leleka_qsa_prompt_guard", - c"leleka_qsa_prompt_attn", - c"leleka_qsa_prompt_output_guard", - ], + &[c"leleka_qsa_prompt_guard", c"leleka_qsa_prompt_attn", c"leleka_qsa_prompt_output_guard"], ); let pop = g.finish(); let m = match load { Ok(m) => { if let Err(e) = pop { - c.poison();c.retain_driver(); + c.poison(); + c.retain_driver(); std::mem::forget(m); return Err(e); } @@ -128,7 +163,8 @@ impl<'ctx> QsaPromptAttention<'ctx>{ Err(e) => return combine(Err(e), pop), }; let mut o = Self { - capacity, context: c, + capacity, + context: c, output: None, status: None, module: Some(m), @@ -161,17 +197,18 @@ impl<'ctx> QsaPromptAttention<'ctx>{ ) -> Result<()> { self.validate_resident()?; w.validate_context(self.context)?; - let g=self.context.enter().map_err(|e|{self.failed=true;w.mark_failed();self.context.poison();self.context.retain_driver();e})?; + let g = self.context.enter().map_err(|e| { + self.failed = true; + w.mark_failed(); + self.context.poison(); + self.context.retain_driver(); + e + })?; let dependency = self.context.driver.api.synchronize(); let op = dependency.and_then(|()| { - (if variants { self.variants.as_ref() } else { self.module.as_ref() }).ok_or(Error::ContextPoisoned)?.launch( - index, - grid, - block, - shared, - w.blas()?.stream(), - &mut a, - ) + (if variants { self.variants.as_ref() } else { self.module.as_ref() }) + .ok_or(Error::ContextPoisoned)? + .launch(index, grid, block, shared, w.blas()?.stream(), &mut a) }); let sync = w.blas()?.synchronize(); let pop = g.finish(); @@ -180,33 +217,81 @@ impl<'ctx> QsaPromptAttention<'ctx>{ } if op.is_err() || sync.is_err() || pop.is_err() { self.failed = true; - self.context.poison();self.context.retain_driver(); + self.context.poison(); + self.context.retain_driver(); w.mark_failed(); } combine(combine(op, sync), pop) } } -impl QsaPromptAttention<'_>{ - fn close_resident(&mut self)->Result<()>{ - self.failed=true;let mut result=Ok(()); - if let Some(module)=self.module.take(){ - if self.context.is_poisoned(){std::mem::forget(module);result=Err(Error::ContextPoisoned)}else{ - match self.context.enter(){ - Ok(guard)=>{let unload=module.close();let pop=guard.finish();if unload.is_err()||pop.is_err(){self.context.poison();self.context.retain_driver();}result=combine(unload,pop);}, - Err(error)=>{self.context.poison();self.context.retain_driver();std::mem::forget(module);result=Err(error)} +impl QsaPromptAttention<'_> { + fn close_resident(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + if let Some(module) = self.module.take() { + if self.context.is_poisoned() { + std::mem::forget(module); + result = Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = module.close(); + let pop = guard.finish(); + if unload.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(unload, pop); + } + Err(error) => { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(module); + result = Err(error) + } + } + } + } + if let Some(module) = self.variants.take() { + if self.context.is_poisoned() { + std::mem::forget(module); + result = combine(result, Err(Error::ContextPoisoned)) + } else { + match self.context.enter() { + Ok(guard) => { + let unload = module.close(); + let pop = guard.finish(); + if unload.is_err() || pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + result = combine(result, combine(unload, pop)); + } + Err(error) => { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(module); + result = combine(result, Err(error)) + } + } + } + } + for slot in [&mut self.status, &mut self.output] { + if let Some(buffer) = slot.take() { + if self.context.is_poisoned() { + std::mem::forget(buffer); + result = combine(result, Err(Error::ContextPoisoned)) + } else { + result = combine(result, buffer.release()) + } + } + } + result + } +} +impl Drop for OriginalQsaResidentAttention<'_> { + fn drop(&mut self) { + let _ = self.inner.close_resident(); } - } - } - if let Some(module)=self.variants.take(){ - if self.context.is_poisoned(){std::mem::forget(module);result=combine(result,Err(Error::ContextPoisoned))}else{ - match self.context.enter(){ - Ok(guard)=>{let unload=module.close();let pop=guard.finish();if unload.is_err()||pop.is_err(){self.context.poison();self.context.retain_driver();}result=combine(result,combine(unload,pop));}, - Err(error)=>{self.context.poison();self.context.retain_driver();std::mem::forget(module);result=combine(result,Err(error))} - } - } - } - for slot in [&mut self.status,&mut self.output]{if let Some(buffer)=slot.take(){if self.context.is_poisoned(){std::mem::forget(buffer);result=combine(result,Err(Error::ContextPoisoned))}else{result=combine(result,buffer.release())}}}result - } } -impl Drop for OriginalQsaResidentAttention<'_>{fn drop(&mut self){let _=self.inner.close_resident();}} diff --git a/crates/cuda-driver/src/qsa_resident_decode.rs b/crates/cuda-driver/src/qsa_resident_decode.rs index a1cbeef8..8ea4af55 100644 --- a/crates/cuda-driver/src/qsa_resident_decode.rs +++ b/crates/cuda-driver/src/qsa_resident_decode.rs @@ -1,9 +1,14 @@ //! Literal native decode attention over the real resident mapped journal. //! No page restore, no host snapshot/image. Full scans and actual clock remain. use super::*; -use crate::qsa_prompt_kv::{OriginalQsaMappedJournal,OriginalQsaMappedPrefix}; -pub struct OriginalQsaResidentDecodeCompletion<'loan,'ctx>{owner:&'loan mut QsaNativeDecode<'ctx>,_kv:&'loan mut OriginalQsaMappedJournal<'ctx>,_snapshot:&'loan OriginalQsaMappedPrefix,t:usize} -impl<'ctx> QsaNativeDecode<'ctx>{ +use crate::qsa_prompt_kv::{OriginalQsaMappedJournal, OriginalQsaMappedPrefix}; +pub struct OriginalQsaResidentDecodeCompletion<'loan, 'ctx> { + owner: &'loan mut QsaNativeDecode<'ctx>, + _kv: &'loan mut OriginalQsaMappedJournal<'ctx>, + _snapshot: &'loan OriginalQsaMappedPrefix, + t: usize, +} +impl<'ctx> QsaNativeDecode<'ctx> { pub fn attend_resident<'loan>( &'loan mut self, w: &mut NativeBatchWorkspace<'ctx>, @@ -25,12 +30,7 @@ impl<'ctx> QsaNativeDecode<'ctx>{ for b in [q, ids, steps] { kv.reject_alias(b)?; w.reject_alias(b.handle.ok_or(Error::ContextPoisoned)?, b.bytes)?; - for own in self - .output - .iter() - .chain(self.status.iter()) - .chain(self.scratch.iter()) - { + for own in self.output.iter().chain(self.status.iter()).chain(self.scratch.iter()) { if own.handle.ok_or(Error::ContextPoisoned)?.overlaps( own.bytes, b.handle.ok_or(Error::ContextPoisoned)?, @@ -54,22 +54,10 @@ impl<'ctx> QsaNativeDecode<'ctx>{ } } let end = snapshot.next_position(); - self.status - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&[0; 4])?; - let status = checked( - self.context, - self.status.as_ref().ok_or(Error::ContextPoisoned)?, - 4, - )?; - let out = self - .output - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address(); + self.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0; 4])?; + let status = checked(self.context, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + let out = + self.output.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?.qwen_address(); // Pre-admission scan and fence are mandatory before selected IDs can address pools. let guard = Arguments::new(vec![ Arg::U64(qh), @@ -92,12 +80,8 @@ impl<'ctx> QsaNativeDecode<'ctx>{ let scratch = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; let handle = scratch.handle.ok_or(Error::ContextPoisoned)?; let pa = handle.qwen_address(); - let pm = handle - .checked_subspan(scratch.bytes, 811008, 3168)? - .qwen_address(); - let pl = handle - .checked_subspan(scratch.bytes, 814176, 3168)? - .qwen_address(); + let pm = handle.checked_subspan(scratch.bytes, 811008, 3168)?.qwen_address(); + let pl = handle.checked_subspan(scratch.bytes, 814176, 3168)?.qwen_address(); // Each query owns817600B; internal checked offsets mirror original single scratch layout. let args = Arguments::new(vec![ Arg::U64(qh), @@ -128,53 +112,32 @@ impl<'ctx> QsaNativeDecode<'ctx>{ Arg::I64(204400), ])?; self.run(w, 2, [24, t as u32, 1], 256, 0, merge)?; - let scan = Arguments::new(vec![ - Arg::U64(out), - Arg::I32((t * 6144) as i32), - Arg::U64(status), - ])?; + let scan = Arguments::new(vec![Arg::U64(out), Arg::I32((t * 6144) as i32), Arg::U64(status)])?; self.run(w, 3, [64, 1, 1], 256, 0, scan)?; if self.flags()? != 0 { return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention")); } - Ok(OriginalQsaResidentDecodeCompletion { - owner: self, - _kv: kv, - _snapshot: snapshot, - t, - }) + Ok(OriginalQsaResidentDecodeCompletion { owner: self, _kv: kv, _snapshot: snapshot, t }) } } -impl OriginalQsaResidentDecodeCompletion<'_, '_>{pub fn rows(&self)->usize{self.t} - pub fn with_output( - &self, - f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result, - ) -> Result { +impl OriginalQsaResidentDecodeCompletion<'_, '_> { + pub fn rows(&self) -> usize { + self.t + } + pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>, usize) -> Result) -> Result { self.owner.validate()?; - f( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - self.t, - ) + f(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, self.t) } pub fn into_values(self) -> Result> { self.owner.validate()?; let mut all = Vec::new(); - all.try_reserve_exact(self.t * 6144 * 4) - .map_err(|_| Error::HostAllocation)?; + all.try_reserve_exact(self.t * 6144 * 4).map_err(|_| Error::HostAllocation)?; all.resize(self.t * 6144 * 4, 0); - crate::qsa_prompt_kv::read_range( - self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, - 0, - &mut all, - )?; + crate::qsa_prompt_kv::read_range(self.owner.output.as_ref().ok_or(Error::ContextPoisoned)?, 0, &mut all)?; let mut values = Vec::new(); - values - .try_reserve_exact(self.t * 6144) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(self.t * 6144).map_err(|_| Error::HostAllocation)?; for b in all[..self.t * 6144 * 4].chunks_exact(4) { - values.push(f32::from_le_bytes( - b.try_into().map_err(|_| Error::InvalidSize)?, - )); + values.push(f32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)); } Ok(values.into_boxed_slice()) } diff --git a/crates/cuda-driver/src/qsa_resident_device.rs b/crates/cuda-driver/src/qsa_resident_device.rs index 771c8e16..ab040b10 100644 --- a/crates/cuda-driver/src/qsa_resident_device.rs +++ b/crates/cuda-driver/src/qsa_resident_device.rs @@ -1,134 +1,27 @@ //! Real-arena resident continuation. No host state image or fake pending state. use super::*; -use crate::qsa_prompt_index::{OriginalQsaResidentIndex,OriginalQsaIndexCheckpoint,OriginalQsaIndexBatch}; -use crate::qsa_prompt_kv::{OriginalQsaMappedJournal,OriginalQsaMappedPrefix,OriginalQsaMappedAppend,OriginalQsaResidentTransport}; -pub struct OriginalQsaResidentSelection<'lease,'index,'weights,'arena,'loan,'ctx>{owner:&'lease mut OriginalQsaPromptDevice<'ctx>,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,p0:u32,batch:OriginalQsaIndexBatch<'index,'weights,'ctx>} -impl<'ctx> OriginalQsaPromptDevice<'ctx>{ - #[allow(clippy::too_many_arguments)] - fn prepare_resident<'lease,'index,'weights,'arena,'loan>(&'lease mut self,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,ws:&mut NativeBatchWorkspace<'ctx>,resident:&'index mut OriginalQsaResidentIndex<'ctx>,prior:&OriginalQsaIndexCheckpoint<'ctx>,weights:OriginalQsaPromptWeights<'weights,'ctx>)->Result>{ - resident.validate_checkpoint(prior)?; - if resident.in_flight||resident.unpublished||resident.next_position()!=prior.next_position()||!std::ptr::eq(resident.context,self.context){return Err(Error::InvalidQwenShape)} - let p=prior.next_position();let p0=u32::try_from(p).map_err(|_|Error::InvalidQwenShape)?;let t=read.rows(); - if t==0||t>self.capacity{return Err(Error::InvalidQwenShape)} - if p.checked_add(t).is_none_or(|end|end>crate::serving_context::geometry().cells()){return Err(Error::InvalidQwenShape)} - let needed=(t*512).checked_add(2564+RESERVE).ok_or(Error::BudgetExceeded)?; - if self.context.allocated_bytes().checked_add(needed).is_none_or(|x|x>self.context.budget_bytes())||self.context.memory_info()?.0 OriginalQsaResidentSelection<'lease,'index,'weights,'arena,'loan,'ctx>{ - pub fn rows(&self)->usize{self.read.rows()}pub fn first_position(&self)->usize{self.p0 as usize} - fn validate(&self,c:&Context<'_>)->Result<()>{if self.owner.is_failed()||self.read.lease().is_failed(){return Err(Error::ContextPoisoned)}if !self.read.context_matches(c)||!std::ptr::eq(self.owner.context,c){return Err(Error::ContextMismatch)}Ok(())} - pub(crate) fn kv_spans(&self,c:&Context<'_>)->Result<(ffi::BufferHandle,ffi::BufferHandle)>{self.validate(c)?;Ok((arena_span(&self.read,"Kc",2048)?,arena_span(&self.read,"Vc",2048)?))} - pub(crate) fn attention_spans(&self,c:&Context<'_>)->Result<(ffi::BufferHandle,ffi::BufferHandle,ffi::BufferHandle,ffi::BufferHandle)>{self.validate(c)?;let b=self.owner.steps.as_ref().ok_or(Error::ContextPoisoned)?;Ok((arena_span(&self.read,"q",24576)?,arena_span(&self.read,"sel_ids",CAP*4)?,b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(),0,self.rows()*16)?,arena_span(&self.read,"attn",24576)?))} - pub(crate) fn kv_stage_spans(&self,c:&Context<'_>)->Result<[ffi::BufferHandle;4]>{ - self.validate(c)?;kv_stage_spans_of(&self.read,self.rows()) - } -} -/// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`, `kv_v_scale`), each checked against the layer's -/// working spans. The stage is the same four arena spans for every QSA layer of a chunk, so they are known before the layer's indexer runs. -pub(crate) fn kv_stage_spans_of(read:&OriginalDeviceGrRead<'_,'_,'_>,rows:usize)->Result<[ffi::BufferHandle;4]>{ - {let mut spans=Vec::new();spans.try_reserve_exact(4).map_err(|_|Error::HostAllocation)?; - let runs=crate::serving_context::geometry().stage_runs().map_err(|_|Error::InvalidSize)?; - for(name,bytes)in[("kv_k_q",runs[0]),("kv_v_q",runs[1]),("kv_k_scale",runs[2]),("kv_v_scale",runs[3])]{ - let(h,n)=read.lease().span(PrefillPhase::Common,name)?;if n!=bytes{return Err(Error::InvalidQwenShape)}h.validate_projection_extent(n,256)?; - for(old,size)in &spans{if h.overlaps(n,*old,*size){return Err(Error::OutputAliasesInput)}} - for(q,nq)in [(arena_span(read,"Kc",2048)?,rows*2048),(arena_span(read,"Vc",2048)?,rows*2048),(arena_span(read,"q",24576)?,rows*24576),(arena_span(read,"sel_ids",CAP*4)?,rows*CAP*4),(arena_span(read,"attn",24576)?,rows*24576),(common(read,S::Block,10240)?,rows*10240)]{if h.overlaps(n,q,nq){return Err(Error::OutputAliasesInput)}}spans.push((h,n)); - }Ok([spans[0].0,spans[1].0,spans[2].0,spans[3].0])} -} -impl<'lease,'index,'weights,'arena,'loan,'ctx> OriginalQsaResidentSelection<'lease,'index,'weights,'arena,'loan,'ctx>{ - pub fn abort(mut self,ws:&mut NativeBatchWorkspace<'ctx>,kv:&mut OriginalQsaMappedJournal<'ctx>,prior:&OriginalQsaMappedPrefix)->Result<()>{ - let index=match self.owner.index.as_mut(){Some(w)=>self.batch.abort(ws,w).map(|_|()),None=>Err(Error::ContextPoisoned)};let mapped=kv.rollback(ws,prior);combine(index,mapped) - } - /// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native - /// FP16 Out. Only actual completed source/causal runtime may publish state. - #[allow(clippy::too_many_arguments)] - pub fn complete(mut self,ws:&mut NativeBatchWorkspace<'ctx>,kv:&mut OriginalQsaMappedJournal<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&OriginalQsaMappedPrefix,attention:&mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>,out_weight:&DeviceBuffer<'ctx>,out_kind:QsaNativeKind)->Result<(OriginalDeviceBlock<'arena,'loan,'ctx>,OriginalQsaIndexBatch<'index,'weights,'ctx>,OriginalQsaMappedAppend)>{ - match self.complete_inner(ws,kv,stage,prior,attention,out_weight,out_kind){ - Ok(appended)=>Ok((self.read.from_completed_block(),self.batch,appended)), - Err(primary)=>{let kv_restore=kv.rollback(ws,prior);let index_restore=match self.owner.index.as_mut(){Some(w)=>self.batch.abort(ws,w).map(|_|()),None=>Err(Error::ContextPoisoned)}; - combine(Err(primary),combine(kv_restore,index_restore))} - } - } - #[allow(clippy::too_many_arguments)] - fn complete_inner(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,kv:&mut OriginalQsaMappedJournal<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&OriginalQsaMappedPrefix,attention:&mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>,out_weight:&DeviceBuffer<'ctx>,out_kind:QsaNativeKind)->Result{ - self.validate(self.owner.context)?; - let t=self.rows();let bytes=2560*(6144/256)*native_block(out_kind);let weight=self.owner.own(out_weight,bytes,2)?; - // Real Out owner admission again; no weight identity is inferred from - // earlier role bytes or a caller range. Runtime rechecks binding role. - ws.reject_alias(weight,bytes)?; - for b in self.owner.index.as_ref().ok_or(Error::ContextPoisoned)?.buffers.iter().flatten().chain(self.owner.scratch.iter()).chain(self.owner.steps.iter()){ - if weight.overlaps(bytes,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)} - } - for(name,width)in[("attn",24576),("attn_h",12288),("Qf",49152)]{if weight.overlaps(bytes,arena_span(&self.read,name,width)?,t*width){return Err(Error::OutputAliasesInput)}} - if weight.overlaps(bytes,common(&self.read,S::Block,10240)?,t*10240){return Err(Error::OutputAliasesInput)} - let timed=crate::command_profile::enabled();let mut mark=std::time::Instant::now(); - let appended=kv.append_resident_arena(ws,stage,prior,&self)?; - if timed{crate::command_profile::add("qsa",11,"kv append",mark.elapsed());mark=std::time::Instant::now();} - attention.attend_resident_arena(ws,stage,kv,appended.final_prefix(),&self)?; - if timed{crate::command_profile::add("qsa",12,"attend",mark.elapsed());mark=std::time::Instant::now();} - let input=arena_span(&self.read,"attn",24576)?;let qf=arena_span(&self.read,"Qf",49152)?;let half=arena_span(&self.read,"attn_h",12288)?; - let mut args=KernelArguments::new(vec![B::Address(input),B::Address(qf),B::Address(half),B::I64(t as i64)]); - let context=self.owner.context;let blas=ws.blas()?;let guard=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?; - let op=self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch(0,(t*6144).div_ceil(256)as u32,256,blas.stream(),&mut args); - let sync=blas.synchronize();let pop=guard.finish();if op.is_err()||sync.is_err()||pop.is_err(){self.owner.failed=true;context.poison();context.retain_driver()} - if sync.is_err()||pop.is_err(){std::mem::forget(args)}let result=combine(combine(op,sync),pop);if result.is_err(){ws.mark_failed();return result.map(|()|unreachable!("failed gate"))} - if timed{crate::command_profile::add("qsa",13,"gate",mark.elapsed());mark=std::time::Instant::now();} - self.owner.project(&self.read,ws,weight,Some(out_kind),2560,6144,half,common(&self.read,S::Block,10240)?)?; - if timed{crate::command_profile::add("qsa",14,"proj out",mark.elapsed());} - Ok(appended) - } +use crate::qsa_prompt_index::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex}; +use crate::qsa_prompt_kv::{ + OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, +}; +pub struct OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> { + owner: &'lease mut OriginalQsaPromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + p0: u32, + batch: OriginalQsaIndexBatch<'index, 'weights, 'ctx>, } /// Closed resident-only producer: four 4B placeholders instead of a duplicate /// 33MiB canonical image. Actual image is exclusively placed only while used. -pub struct OriginalQsaResidentPromptDevice<'ctx>{inner:OriginalQsaPromptDevice<'ctx>} -impl<'ctx> Context<'ctx>{pub fn original_qsa_resident_prompt_device(&'ctx self,capacity:usize,packing:QsaNativePacking)->Result>{Ok(OriginalQsaResidentPromptDevice{inner:OriginalQsaPromptDevice::new_resident(self,capacity,packing)?})}} -impl<'ctx> OriginalQsaResidentPromptDevice<'ctx>{ - pub fn device_bytes(capacity:usize)->Result{OriginalQsaPromptDevice::device_bytes(capacity)?.checked_sub({let z=sizes();z[0]+z[1]+z[2]+z[3]}).and_then(|n|n.checked_add(16)).ok_or(Error::BudgetExceeded)} - pub fn allocated_bytes(&self)->usize{self.inner.allocated_bytes()}pub fn is_failed(&self)->bool{self.inner.is_failed()} - #[allow(clippy::too_many_arguments)] - pub fn prepare<'lease,'index,'weights,'arena,'loan>(&'lease mut self,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,ws:&mut NativeBatchWorkspace<'ctx>,resident:&'index mut OriginalQsaResidentIndex<'ctx>,prior:&OriginalQsaIndexCheckpoint<'ctx>,weights:OriginalQsaPromptWeights<'weights,'ctx>)->Result>{self.inner.prepare_resident(read,ws,resident,prior,weights)} - pub fn commit_prefix<'index,'weights>(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,batch:&mut OriginalQsaIndexBatch<'index,'weights,'ctx>,accepted:usize)->Result>{if self.inner.is_failed(){return Err(Error::ContextPoisoned)}batch.commit_prefix(ws,self.inner.index.as_mut().ok_or(Error::ContextPoisoned)?,accepted)} - pub fn close(self)->Result<()>{self.inner.close()} -} -impl<'ctx> OriginalQsaPromptDevice<'ctx>{ - fn new_resident(context:&'ctx Context<'ctx>,capacity:usize,packing:QsaNativePacking)->Result{ - let required=OriginalQsaResidentPromptDevice::device_bytes(capacity)?.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if GATE_PTX.len()<2||GATE_PTX.last()!=Some(&0)||GATE_PTX[..GATE_PTX.len()-1].contains(&0)||crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len()-1])!=GATE_SHA{return Err(Error::UnsupportedQwenOperation)} - if [INDEX,SELECT,POSTOPS,DECODE_POSTOPS].iter().any(|x|x.starts_with(b"// UNSEALED")){return Err(Error::UnsupportedQwenOperation)} - if context.is_poisoned(){return Err(Error::ContextPoisoned)} - if context.allocated_bytes().checked_add(required).is_none_or(|x|x>context.budget_bytes())||context.memory_info()?.0Result<()>{for(i,n)in sizes.into_iter().enumerate(){owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i]=Some(context.allocate(n)?)} - owner.scratch=Some(context.allocate(SCRATCH)?);owner.steps=Some(context.allocate(capacity*16)?); - let guard=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?; - let load=(||->Result<()>{owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module=Some(Module::load(INDEX,SELECT,POSTOPS,DECODE_POSTOPS)?); - owner.dequant=Some(if crate::prefill_stage::fast_dequant(){KernelModule::load(crate::prefill_stage::PTX,crate::prefill_stage::ENTRIES)?}else{KernelModule::load(concat!(include_str!("offline_native_dequant_f16.ptx"),"\0").as_bytes(),&[c"leleka_native_dequant_f16_q4_k",c"leleka_native_dequant_f16_q5_k",c"leleka_native_dequant_f16_q6_k",c"leleka_native_dequant_f16_iq4_xs"])?}); - owner.pack=Some(KernelModule::load(concat!(include_str!("qsa_native_batch.ptx"),"\0").as_bytes(),&[c"qsa_pack",c"qsa_gate_pack",c"qsa_scan_half"])?); - owner.gate=Some(KernelModule::load(GATE_PTX,&[c"qsa_prompt_device_gate"])?);Ok(())})(); - let pop=guard.finish();if pop.is_err(){context.poison();context.retain_driver()}combine(load,pop)?; - if context.memory_info()?.0 { + inner: OriginalQsaPromptDevice<'ctx>, } + +#[path = "qsa_resident_device/impl_originalqsapromptdevice.rs"] +mod impl_originalqsapromptdevice; +#[allow(unused_imports)] +pub(crate) use impl_originalqsapromptdevice::kv_stage_spans_of; +#[path = "qsa_resident_device/impl_originalqsapromptdevice_2.rs"] +mod impl_originalqsapromptdevice_2; +#[path = "qsa_resident_device/impl_originalqsaresidentselection.rs"] +mod impl_originalqsaresidentselection; diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs new file mode 100644 index 00000000..0299528d --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs @@ -0,0 +1,202 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice, impl OriginalQsaResidentSelection, fn kv_stage_spans_of. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(super) fn prepare_resident<'lease, 'index, 'weights, 'arena, 'loan>( + &'lease mut self, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + resident: &'index mut OriginalQsaResidentIndex<'ctx>, + prior: &OriginalQsaIndexCheckpoint<'ctx>, + weights: OriginalQsaPromptWeights<'weights, 'ctx>, + ) -> Result> { + resident.validate_checkpoint(prior)?; + if resident.in_flight + || resident.unpublished + || resident.next_position() != prior.next_position() + || !std::ptr::eq(resident.context, self.context) + { + return Err(Error::InvalidQwenShape); + } + let p = prior.next_position(); + let p0 = u32::try_from(p).map_err(|_| Error::InvalidQwenShape)?; + let t = read.rows(); + if t == 0 || t > self.capacity { + return Err(Error::InvalidQwenShape); + } + if p.checked_add(t).is_none_or(|end| end > crate::serving_context::geometry().cells()) { + return Err(Error::InvalidQwenShape); + } + let needed = (t * 512).checked_add(2564 + RESERVE).ok_or(Error::BudgetExceeded)?; + if self.context.allocated_bytes().checked_add(needed).is_none_or(|x| x > self.context.budget_bytes()) + || self.context.memory_info()?.0 < needed + { + return Err(Error::BudgetExceeded); + } + let start = resident.checkpoint(ws)?; + let raw_rows = self.context.allocate(t * 512)?; + let (w, gamma) = self.admit(&read, &weights, ws)?; + let half = common(&read, S::MixedHalf, 5120)?; + let high = common(&read, S::MixedHigh, 5120)?; + let timed = crate::command_profile::enabled(); + let mut mark = std::time::Instant::now(); + for (i, name, n) in [(0, "Kc", 512), (1, "Vc", 512), (2, "Qf", 12288), (3, "idx_raw", 128), (4, "q_idx", 512)] { + self.project( + &read, + ws, + w[i], + if i < 3 { Some(weights.kinds[i]) } else { None }, + n, + 2560, + if i < 3 { half } else { high }, + arena_span(&read, name, n * 4)?, + )?; + if timed { + crate::command_profile::add( + "qsa", + i + 1, + ["proj K", "proj V", "proj Q", "proj idxK", "proj idxQ"][i], + mark.elapsed(), + ); + mark = std::time::Instant::now(); + } + } + let steps = self + .own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)? + .checked_subspan(self.capacity * 16, 0, t * 16)?; + let out = [ + arena_span(&read, "Kc", 2048)?, + arena_span(&read, "Vc", 2048)?, + arena_span(&read, "q", 24576)?, + arena_span(&read, "sel_ids", CAP * 4)?, + steps, + ]; + let raw = arena_span(&read, "idx_raw", 512)?; + let qfull = arena_span(&read, "Qf", 49152)?; + let iq = arena_span(&read, "q_idx", 2048)?; + let index = self.index.as_mut().ok_or(Error::ContextPoisoned)?; + resident.in_flight = true; + resident.unpublished = true; + let operation = + resident.placed(index, |w| w.run_resident_arena(p0, t as u32, raw, qfull, iq, gamma, out, ws, false)); + if timed { + crate::command_profile::add("qsa", 6, "index+norm+rope run", mark.elapsed()); + mark = std::time::Instant::now(); + } + if let Err(primary) = operation { + let cleanup = resident.restore_private(ws, &start); + if cleanup.is_ok() { + resident.in_flight = false; + } + if self.context.is_poisoned() { + std::mem::forget(raw_rows) + } else { + drop(raw_rows) + } + return combine(Err(primary), cleanup); + } + let retained = raw_rows.handle.ok_or(Error::ContextPoisoned)?; + if let Err(primary) = resident.copy_ranges(ws, &[(raw, retained, t * 512)]) { + let cleanup = resident.restore_private(ws, &start); + if cleanup.is_ok() { + resident.in_flight = false; + } + if self.context.is_poisoned() { + std::mem::forget(raw_rows) + } else { + drop(raw_rows) + } + return combine(Err(primary), cleanup); + } + if timed { + crate::command_profile::add("qsa", 7, "copy raw rows", mark.elapsed()); + } + resident.provisional_end(p + t); + let batch = + OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma: weights.norms[3], rows: t }; + Ok(OriginalQsaResidentSelection { owner: self, read, p0, batch }) + } +} +impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> + OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> +{ + pub fn rows(&self) -> usize { + self.read.rows() + } + pub fn first_position(&self) -> usize { + self.p0 as usize + } + pub(super) fn validate(&self, c: &Context<'_>) -> Result<()> { + if self.owner.is_failed() || self.read.lease().is_failed() { + return Err(Error::ContextPoisoned); + } + if !self.read.context_matches(c) || !std::ptr::eq(self.owner.context, c) { + return Err(Error::ContextMismatch); + } + Ok(()) + } + pub(crate) fn kv_spans(&self, c: &Context<'_>) -> Result<(ffi::BufferHandle, ffi::BufferHandle)> { + self.validate(c)?; + Ok((arena_span(&self.read, "Kc", 2048)?, arena_span(&self.read, "Vc", 2048)?)) + } + pub(crate) fn attention_spans( + &self, + c: &Context<'_>, + ) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> { + self.validate(c)?; + let b = self.owner.steps.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + arena_span(&self.read, "q", 24576)?, + arena_span(&self.read, "sel_ids", CAP * 4)?, + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), 0, self.rows() * 16)?, + arena_span(&self.read, "attn", 24576)?, + )) + } + pub(crate) fn kv_stage_spans(&self, c: &Context<'_>) -> Result<[ffi::BufferHandle; 4]> { + self.validate(c)?; + kv_stage_spans_of(&self.read, self.rows()) + } +} +/// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`, `kv_v_scale`), each checked against the layer's +/// working spans. The stage is the same four arena spans for every QSA layer of a chunk, so they are known before the layer's indexer runs. +pub(crate) fn kv_stage_spans_of( + read: &OriginalDeviceGrRead<'_, '_, '_>, + rows: usize, +) -> Result<[ffi::BufferHandle; 4]> { + { + let mut spans = Vec::new(); + spans.try_reserve_exact(4).map_err(|_| Error::HostAllocation)?; + let runs = crate::serving_context::geometry().stage_runs().map_err(|_| Error::InvalidSize)?; + for (name, bytes) in + [("kv_k_q", runs[0]), ("kv_v_q", runs[1]), ("kv_k_scale", runs[2]), ("kv_v_scale", runs[3])] + { + let (h, n) = read.lease().span(PrefillPhase::Common, name)?; + if n != bytes { + return Err(Error::InvalidQwenShape); + } + h.validate_projection_extent(n, 256)?; + for (old, size) in &spans { + if h.overlaps(n, *old, *size) { + return Err(Error::OutputAliasesInput); + } + } + for (q, nq) in [ + (arena_span(read, "Kc", 2048)?, rows * 2048), + (arena_span(read, "Vc", 2048)?, rows * 2048), + (arena_span(read, "q", 24576)?, rows * 24576), + (arena_span(read, "sel_ids", CAP * 4)?, rows * CAP * 4), + (arena_span(read, "attn", 24576)?, rows * 24576), + (common(read, S::Block, 10240)?, rows * 10240), + ] { + if h.overlaps(n, q, nq) { + return Err(Error::OutputAliasesInput); + } + } + spans.push((h, n)); + } + Ok([spans[0].0, spans[1].0, spans[2].0, spans[3].0]) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs new file mode 100644 index 00000000..3b825f0b --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs @@ -0,0 +1,113 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaPromptDevice<'ctx> { + pub(super) fn new_resident( + context: &'ctx Context<'ctx>, + capacity: usize, + packing: QsaNativePacking, + ) -> Result { + let required = OriginalQsaResidentPromptDevice::device_bytes(capacity)? + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if GATE_PTX.len() < 2 + || GATE_PTX.last() != Some(&0) + || GATE_PTX[..GATE_PTX.len() - 1].contains(&0) + || crate::qwen_ffi::sha256(&GATE_PTX[..GATE_PTX.len() - 1]) != GATE_SHA + { + return Err(Error::UnsupportedQwenOperation); + } + if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { + return Err(Error::UnsupportedQwenOperation); + } + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context.allocated_bytes().checked_add(required).is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut sizes = sizes(); + for n in &mut sizes[..4] { + *n = 4; + } + for i in [4, 5, 6, 7, 8] { + sizes[i] = 4 + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + let index = QsaPromptIndexWorkspace { + capacity, + sizes, + context, + buffers: std::array::from_fn(|_| None), + module: None, + late: None, + failed: false, + }; + let mut owner = Self { + context, + capacity, + packing, + index: Some(index), + scratch: None, + steps: None, + dequant: None, + pack: None, + gate: None, + failed: false, + }; + let operation = (|| -> Result<()> { + for (i, n) in sizes.into_iter().enumerate() { + owner.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?) + } + owner.scratch = Some(context.allocate(SCRATCH)?); + owner.steps = Some(context.allocate(capacity * 16)?); + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let load = (|| -> Result<()> { + owner.index.as_mut().ok_or(Error::ContextPoisoned)?.module = + Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?); + owner.dequant = Some(if crate::prefill_stage::fast_dequant() { + KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES)? + } else { + KernelModule::load( + concat!(include_str!("../offline_native_dequant_f16.ptx"), "\0").as_bytes(), + &[ + c"leleka_native_dequant_f16_q4_k", + c"leleka_native_dequant_f16_q5_k", + c"leleka_native_dequant_f16_q6_k", + c"leleka_native_dequant_f16_iq4_xs", + ], + )? + }); + owner.pack = Some(KernelModule::load( + concat!(include_str!("../qsa_native_batch.ptx"), "\0").as_bytes(), + &[c"qsa_pack", c"qsa_gate_pack", c"qsa_scan_half"], + )?); + owner.gate = Some(KernelModule::load(GATE_PTX, &[c"qsa_prompt_device_gate"])?); + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + combine(load, pop)?; + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + let _ = owner.close(); + return Err(e); + } + Ok(owner) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs new file mode 100644 index 00000000..f717a45c --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentSelection, impl Context, impl OriginalQsaResidentPromptDevice. + +#[allow(unused_imports)] +use super::*; + +impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> + OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> +{ + pub fn abort( + mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + kv: &mut OriginalQsaMappedJournal<'ctx>, + prior: &OriginalQsaMappedPrefix, + ) -> Result<()> { + let index = match self.owner.index.as_mut() { + Some(w) => self.batch.abort(ws, w).map(|_| ()), + None => Err(Error::ContextPoisoned), + }; + let mapped = kv.rollback(ws, prior); + combine(index, mapped) + } + /// Full INT8 append, MMA/exp2 attention, literal strided Qf gate, native + /// FP16 Out. Only actual completed source/causal runtime may publish state. + #[allow(clippy::too_many_arguments)] + pub fn complete( + mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + kv: &mut OriginalQsaMappedJournal<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + attention: &mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>, + out_weight: &DeviceBuffer<'ctx>, + out_kind: QsaNativeKind, + ) -> Result<( + OriginalDeviceBlock<'arena, 'loan, 'ctx>, + OriginalQsaIndexBatch<'index, 'weights, 'ctx>, + OriginalQsaMappedAppend, + )> { + match self.complete_inner(ws, kv, stage, prior, attention, out_weight, out_kind) { + Ok(appended) => Ok((self.read.from_completed_block(), self.batch, appended)), + Err(primary) => { + let kv_restore = kv.rollback(ws, prior); + let index_restore = match self.owner.index.as_mut() { + Some(w) => self.batch.abort(ws, w).map(|_| ()), + None => Err(Error::ContextPoisoned), + }; + combine(Err(primary), combine(kv_restore, index_restore)) + } + } + } + #[allow(clippy::too_many_arguments)] + pub(super) fn complete_inner( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + kv: &mut OriginalQsaMappedJournal<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &OriginalQsaMappedPrefix, + attention: &mut crate::qsa_prompt_attention::OriginalQsaResidentAttention<'ctx>, + out_weight: &DeviceBuffer<'ctx>, + out_kind: QsaNativeKind, + ) -> Result { + self.validate(self.owner.context)?; + let t = self.rows(); + let bytes = 2560 * (6144 / 256) * native_block(out_kind); + let weight = self.owner.own(out_weight, bytes, 2)?; + // Real Out owner admission again; no weight identity is inferred from + // earlier role bytes or a caller range. Runtime rechecks binding role. + ws.reject_alias(weight, bytes)?; + for b in self + .owner + .index + .as_ref() + .ok_or(Error::ContextPoisoned)? + .buffers + .iter() + .flatten() + .chain(self.owner.scratch.iter()) + .chain(self.owner.steps.iter()) + { + if weight.overlaps(bytes, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + for (name, width) in [("attn", 24576), ("attn_h", 12288), ("Qf", 49152)] { + if weight.overlaps(bytes, arena_span(&self.read, name, width)?, t * width) { + return Err(Error::OutputAliasesInput); + } + } + if weight.overlaps(bytes, common(&self.read, S::Block, 10240)?, t * 10240) { + return Err(Error::OutputAliasesInput); + } + let timed = crate::command_profile::enabled(); + let mut mark = std::time::Instant::now(); + let appended = kv.append_resident_arena(ws, stage, prior, &self)?; + if timed { + crate::command_profile::add("qsa", 11, "kv append", mark.elapsed()); + mark = std::time::Instant::now(); + } + attention.attend_resident_arena(ws, stage, kv, appended.final_prefix(), &self)?; + if timed { + crate::command_profile::add("qsa", 12, "attend", mark.elapsed()); + mark = std::time::Instant::now(); + } + let input = arena_span(&self.read, "attn", 24576)?; + let qf = arena_span(&self.read, "Qf", 49152)?; + let half = arena_span(&self.read, "attn_h", 12288)?; + let mut args = + KernelArguments::new(vec![B::Address(input), B::Address(qf), B::Address(half), B::I64(t as i64)]); + let context = self.owner.context; + let blas = ws.blas()?; + let guard = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let op = self.owner.gate.as_ref().ok_or(Error::ContextPoisoned)?.launch( + 0, + (t * 6144).div_ceil(256) as u32, + 256, + blas.stream(), + &mut args, + ); + let sync = blas.synchronize(); + let pop = guard.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + self.owner.failed = true; + context.poison(); + context.retain_driver() + } + if sync.is_err() || pop.is_err() { + std::mem::forget(args) + } + let result = combine(combine(op, sync), pop); + if result.is_err() { + ws.mark_failed(); + return result.map(|()| unreachable!("failed gate")); + } + if timed { + crate::command_profile::add("qsa", 13, "gate", mark.elapsed()); + mark = std::time::Instant::now(); + } + self.owner.project( + &self.read, + ws, + weight, + Some(out_kind), + 2560, + 6144, + half, + common(&self.read, S::Block, 10240)?, + )?; + if timed { + crate::command_profile::add("qsa", 14, "proj out", mark.elapsed()); + } + Ok(appended) + } +} +impl<'ctx> Context<'ctx> { + pub fn original_qsa_resident_prompt_device( + &'ctx self, + capacity: usize, + packing: QsaNativePacking, + ) -> Result> { + Ok(OriginalQsaResidentPromptDevice { inner: OriginalQsaPromptDevice::new_resident(self, capacity, packing)? }) + } +} +impl<'ctx> OriginalQsaResidentPromptDevice<'ctx> { + pub fn device_bytes(capacity: usize) -> Result { + OriginalQsaPromptDevice::device_bytes(capacity)? + .checked_sub({ + let z = sizes(); + z[0] + z[1] + z[2] + z[3] + }) + .and_then(|n| n.checked_add(16)) + .ok_or(Error::BudgetExceeded) + } + pub fn allocated_bytes(&self) -> usize { + self.inner.allocated_bytes() + } + pub fn is_failed(&self) -> bool { + self.inner.is_failed() + } + #[allow(clippy::too_many_arguments)] + pub fn prepare<'lease, 'index, 'weights, 'arena, 'loan>( + &'lease mut self, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + resident: &'index mut OriginalQsaResidentIndex<'ctx>, + prior: &OriginalQsaIndexCheckpoint<'ctx>, + weights: OriginalQsaPromptWeights<'weights, 'ctx>, + ) -> Result> { + self.inner.prepare_resident(read, ws, resident, prior, weights) + } + pub fn commit_prefix<'index, 'weights>( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + batch: &mut OriginalQsaIndexBatch<'index, 'weights, 'ctx>, + accepted: usize, + ) -> Result> { + if self.inner.is_failed() { + return Err(Error::ContextPoisoned); + } + batch.commit_prefix(ws, self.inner.index.as_mut().ok_or(Error::ContextPoisoned)?, accepted) + } + pub fn close(self) -> Result<()> { + self.inner.close() + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index.rs b/crates/cuda-driver/src/qsa_resident_index.rs index 7a16dd83..a0c200aa 100644 --- a/crates/cuda-driver/src/qsa_resident_index.rs +++ b/crates/cuda-driver/src/qsa_resident_index.rs @@ -1,208 +1,63 @@ //! Live Original index image. Only actual checkpoint copies and accepted-key //! replay create prefix authority; a final image cannot be relabelled earlier. -use super::*; -use std::{cell::{Cell,RefCell},rc::{Rc,Weak}}; use super::resident_transfer::Transfer; -fn image_bytes()->usize{sizes()[0]+1536+512+4} -const CHECKPOINT_BYTES:usize=1536+512+512+4; +use super::*; +use std::{ + cell::{Cell, RefCell}, + rc::{Rc, Weak}, +}; +const CHECKPOINT_BYTES: usize = 1536 + 512 + 512 + 4; struct Origin; -struct Coverage{end:Cell} -struct Saved<'ctx>{origin:Rc,epoch:u64,coverage:Rc,end:usize,bytes:DeviceBuffer<'ctx>,pool:Weak>>>} +struct Coverage { + end: Cell, +} +struct Saved<'ctx> { + origin: Rc, + epoch: u64, + coverage: Rc, + end: usize, + bytes: DeviceBuffer<'ctx>, + pool: Weak>>>, +} /// Checkpoint buffers a live index keeps for reuse: a superseded checkpoint returns its 2564 bytes here instead of /// `cuMemFree` (which waits for the device), and the next one takes them instead of `cuMemGetInfo` + `cuMemAlloc`. -const POOLED:usize=64; -impl Drop for Saved<'_>{fn drop(&mut self){ - let Some(pool)=self.pool.upgrade() else{return};if self.bytes.context.is_poisoned()||self.bytes.len()!=CHECKPOINT_BYTES{return} - let Ok(mut pool)=pool.try_borrow_mut() else{return};if pool.len()>=POOLED||pool.try_reserve(1).is_err(){return} - let Some(handle)=self.bytes.handle.take() else{return}; - // The allocation moves to the pool unchanged (still charged to the context); this owner no longer frees it. - pool.push(DeviceBuffer{context:self.bytes.context,handle:Some(handle),bytes:self.bytes.bytes,_thread:std::marker::PhantomData,borrowed:false}); -}} +const POOLED: usize = 64; #[derive(Clone)] pub struct OriginalQsaIndexCheckpoint<'ctx>(Rc>); -impl OriginalQsaIndexCheckpoint<'_>{pub fn next_position(&self)->usize{self.0.end}pub fn device_bytes(&self)->usize{CHECKPOINT_BYTES}pub fn validate_retained(&self,context:&Context<'_>)->Result<()>{if !std::ptr::eq(context,self.0.bytes.context){return Err(Error::ContextMismatch)}if self.0.bytes.context.is_poisoned(){return Err(Error::ContextPoisoned)}if self.0.end>crate::serving_context::geometry().cells()||self.0.end>self.0.coverage.end.get()||self.0.bytes.len()!=CHECKPOINT_BYTES{return Err(Error::InvalidQwenShape)}self.0.bytes.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(CHECKPOINT_BYTES,4)}} -pub struct OriginalQsaResidentIndex<'ctx>{ - pub(super) context:&'ctx Context<'ctx>,origin:Rc,epoch:u64,coverage:Rc,pub(super) end:usize, - image:[Option>;4],copy:Option,failed:bool,pub(super) in_flight:bool,pub(super) unpublished:bool, - pool:Rc>>>, -} -impl<'ctx> Context<'ctx>{pub fn original_qsa_resident_index(&'ctx self)->Result>{OriginalQsaResidentIndex::new(self)}} -impl<'ctx> OriginalQsaResidentIndex<'ctx>{ - pub fn device_bytes()->usize{image_bytes()} - fn new(context:&'ctx Context<'ctx>)->Result{ - let n=image_bytes().checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context.is_poisoned(){return Err(Error::ContextPoisoned)} - if context.allocated_bytes().checked_add(n).is_none_or(|x|x>context.budget_bytes())||context.memory_info()?.0Result<()>{s.copy=Some(Transfer::new()?); - // One-time bounded initialization, never a whole host index image. Each - // upload owns its actual staging until completion; no 33MiB host allocation. - let zero=[0u8;65536];for(i,n)in [sizes()[0],1536,512,4].into_iter().enumerate(){ - s.image[i]=Some(context.allocate(n)?);let b=s.image[i].as_mut().ok_or(Error::ContextPoisoned)?; - for offset in (0..n).step_by(zero.len()){b.copy_from_range(offset,&zero[..(n-offset).min(zero.len())]).map_err(|e|{if !matches!(e,Error::HostAllocation){context.poison();context.retain_driver();}e})?;} - }if context.memory_info()?.0bool{self.failed||self.context.is_poisoned()} - pub fn allocated_bytes(&self)->usize{self.image.iter().flatten().map(DeviceBuffer::len).sum()} - pub fn next_position(&self)->usize{self.end} - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}self.validate()} - pub(super) fn validate(&self)->Result<()>{if self.is_failed()||self.copy.is_none(){return Err(Error::ContextPoisoned)} - for(i,n)in [sizes()[0],1536,512,4].into_iter().enumerate(){let b=self.image[i].as_ref().ok_or(Error::ContextPoisoned)?;if !std::ptr::eq(b.context,self.context)||b.len()!=n{return Err(Error::InvalidQwenShape)}b.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(n,4)?;}Ok(())} - pub fn validate_checkpoint(&self,s:&OriginalQsaIndexCheckpoint<'ctx>)->Result<()>{self.validate()?; - if !Rc::ptr_eq(&self.origin,&s.0.origin)||self.epoch!=s.0.epoch||s.0.end>s.0.coverage.end.get()||s.0.end>crate::serving_context::geometry().cells()||!std::ptr::eq(self.context,s.0.bytes.context)||s.0.bytes.len()!=CHECKPOINT_BYTES{return Err(Error::InvalidQwenShape)}Ok(())} - pub(super) fn h(&self,i:usize,o:usize,n:usize)->Result{let b=self.image[i].as_ref().ok_or(Error::ContextPoisoned)?;b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(),o,n)} - pub(super) fn copy_ranges(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,ranges:&[(ffi::BufferHandle,ffi::BufferHandle,usize)])->Result<()>{ - self.validate()?;ws.validate_context(self.context)?; - let mut copies=Vec::new();copies.try_reserve_exact(ranges.len()).map_err(|_|Error::HostAllocation)?; - for(src,dst,n)in ranges{if *n==0||src.overlaps(*n,*dst,*n){return Err(Error::OutputAliasesInput)}src.validate_projection_extent(*n,1)?;dst.validate_projection_extent(*n,1)?;copies.push((src.qwen_address(),dst.qwen_address(),*n));} - let result=self.copy.as_ref().ok_or(Error::ContextPoisoned)?.copy(self.context,ws,&copies); - if result.is_err(){self.failed=true}result - } - pub fn checkpoint(&mut self,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{self.validate()?;if self.in_flight||self.unpublished{return Err(Error::InvalidQwenShape)}self.save(ws)} - /// A checkpoint buffer: a pooled one, else a new allocation under the usual admission. - fn checkpoint_buffer(&self)->Result>{ - if let Some(b)=self.pool.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.pop(){if std::ptr::eq(b.context,self.context)&&b.len()==CHECKPOINT_BYTES&&b.handle.is_some(){return Ok(b)}let _=b.release();} - let n=CHECKPOINT_BYTES+RESERVE;if self.context.allocated_bytes().checked_add(n).is_none_or(|x|x>self.context.budget_bytes())||self.context.memory_info()?.0 checkpoint bytes). - fn save_ranges(&self,h:ffi::BufferHandle)->Result<[(ffi::BufferHandle,ffi::BufferHandle,usize);4]>{ - Ok([(self.h(1,0,1536)?,h.checked_subspan(CHECKPOINT_BYTES,0,1536)?,1536),(self.h(2,0,512)?,h.checked_subspan(CHECKPOINT_BYTES,1536,512)?,512),(self.h(0,self.end/4*512,512)?,h.checked_subspan(CHECKPOINT_BYTES,2048,512)?,512),(self.h(3,0,4)?,h.checked_subspan(CHECKPOINT_BYTES,2560,4)?,4)]) - } - fn saved(&self,b:DeviceBuffer<'ctx>)->OriginalQsaIndexCheckpoint<'ctx>{ - OriginalQsaIndexCheckpoint(Rc::new(Saved{origin:self.origin.clone(),epoch:self.epoch,coverage:self.coverage.clone(),end:self.end,bytes:b,pool:Rc::downgrade(&self.pool)})) - } - pub(super) fn save(&mut self,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{ - let b=self.checkpoint_buffer()?;let h=b.handle.ok_or(Error::ContextPoisoned)?; - let op=self.save_ranges(h).and_then(|ranges|self.copy_ranges(ws,&ranges)); - if let Err(e)=op{if self.context.is_poisoned(){std::mem::forget(b)}else{let _=b.release();}return Err(e)} - Ok(self.saved(b)) - } - /// `checkpoint` of several committed images at once, AFTER the caller fenced every writer of them (the verifier's - /// commit event): one stream-ordered batch of copies and one stream drain, without the context-wide synchronize a - /// lone checkpoint makes (that waited for the adaptive expert swaps and the draft too). Same bytes as `checkpoint`. - pub(crate) fn checkpoint_fenced_all(indices:&mut [&mut OriginalQsaResidentIndex<'ctx>],ws:&mut NativeBatchWorkspace<'ctx>)->Result>>{ - let first=indices.first().ok_or(Error::InvalidQwenShape)?.context; - for i in indices.iter(){i.validate()?;if !std::ptr::eq(i.context,first){return Err(Error::ContextMismatch)}if i.in_flight||i.unpublished{return Err(Error::InvalidQwenShape)}} - ws.validate_context(first)?; - let mut buffers:Vec>=Vec::new();buffers.try_reserve_exact(indices.len()).map_err(|_|Error::HostAllocation)?; - let mut copies=Vec::new();copies.try_reserve_exact(4*indices.len()).map_err(|_|Error::HostAllocation)?; - let staged=(||->Result<()>{for i in indices.iter(){let b=i.checkpoint_buffer()?;let h=b.handle.ok_or(Error::ContextPoisoned)?;buffers.push(b); - for(src,dst,n)in i.save_ranges(h)?{if n==0||src.overlaps(n,dst,n){return Err(Error::OutputAliasesInput)}src.validate_projection_extent(n,1)?;dst.validate_projection_extent(n,1)?;copies.push((src.qwen_address(),dst.qwen_address(),n));}}Ok(())})(); - let copied=staged.and_then(|()|indices[0].copy.as_ref().ok_or(Error::ContextPoisoned)?.copy_fenced(first,ws,&copies)); - if let Err(e)=copied{for i in indices.iter_mut(){i.failed=true}for b in buffers{if first.is_poisoned(){std::mem::forget(b)}else{let _=b.release();}}return Err(e)} - Ok(indices.iter().zip(buffers).map(|(i,b)|i.saved(b)).collect()) - } - pub fn restore(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,s:&OriginalQsaIndexCheckpoint<'ctx>)->Result<()>{if self.in_flight{return Err(Error::InvalidQwenShape)}self.restore_private(ws,s)} - pub(super) fn restore_private(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,s:&OriginalQsaIndexCheckpoint<'ctx>)->Result<()>{self.validate_checkpoint(s)?; - let h=s.0.bytes.handle.ok_or(Error::ContextPoisoned)?; - self.copy_ranges(ws,&[(h.checked_subspan(CHECKPOINT_BYTES,0,1536)?,self.h(1,0,1536)?,1536),(h.checked_subspan(CHECKPOINT_BYTES,1536,512)?,self.h(2,0,512)?,512),(h.checked_subspan(CHECKPOINT_BYTES,2048,512)?,self.h(0,s.0.end/4*512,512)?,512),(h.checked_subspan(CHECKPOINT_BYTES,2560,4)?,self.h(3,0,4)?,4)])?; - self.coverage.end.set(self.coverage.end.get().min(s.0.end));self.coverage=Rc::new(Coverage{end:Cell::new(s.0.end)});self.end=s.0.end;self.unpublished=false;Ok(()) - } - pub(super) fn placed(&mut self,w:&mut QsaPromptIndexWorkspace<'ctx>,f:impl FnOnce(&mut QsaPromptIndexWorkspace<'ctx>)->Result)->Result{ - self.validate()?;if !std::ptr::eq(self.context,w.context){return Err(Error::ContextMismatch)} - struct Placement<'a,'ctx>{owner:&'a mut OriginalQsaResidentIndex<'ctx>,workspace:&'a mut QsaPromptIndexWorkspace<'ctx>,sizes:[usize;4]} - impl Drop for Placement<'_, '_>{fn drop(&mut self){for i in 0..4{std::mem::swap(&mut self.owner.image[i],&mut self.workspace.buffers[i]);self.workspace.sizes[i]=self.sizes[i];}if self.workspace.is_failed(){self.owner.failed=true}}} - let image_sizes=[sizes()[0],1536,512,4];let sizes=std::array::from_fn(|i|w.sizes[i]);for i in 0..4{std::mem::swap(&mut self.image[i],&mut w.buffers[i]);w.sizes[i]=image_sizes[i];} - let placement=Placement{owner:self,workspace:w,sizes};f(&mut *placement.workspace) - } - pub fn reset(&mut self,ws:&mut NativeBatchWorkspace<'ctx>)->Result<()>{self.validate()?;if self.in_flight{return Err(Error::InvalidQwenShape)}ws.validate_context(self.context)?; - let epoch=self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?;let zero=[0u8;1536]; - for b in self.image[1..].iter_mut().flatten(){let n=b.len();b.copy_from(&zero[..n]).map_err(|e|{if !matches!(e,Error::HostAllocation){self.context.poison();self.context.retain_driver();}e})?;} - self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&zero[..512]).map_err(|e|{if !matches!(e,Error::HostAllocation){self.context.poison();self.context.retain_driver();}e})?; - self.coverage.end.set(0);self.coverage=Rc::new(Coverage{end:Cell::new(0)});self.end=0;self.epoch=epoch;self.unpublished=false;Ok(()) - } - pub(super) fn provisional_end(&mut self,end:usize){self.end=end;self.coverage.end.set(end);} - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{self.failed=true;let mut result=Ok(()); - if let Ok(mut pool)=self.pool.try_borrow_mut(){for b in pool.drain(..){if self.context.is_poisoned(){std::mem::forget(b)}else{result=combine(result,b.release())}}} - if let Some(m)=self.copy.take(){if self.context.is_poisoned()||self.in_flight{std::mem::forget(m);result=Err(Error::ContextPoisoned)}else{drop(m)}} - for b in &mut self.image{if let Some(b)=b.take(){if self.context.is_poisoned()||self.in_flight{std::mem::forget(b);result=combine(result,Err(Error::ContextPoisoned))}else{result=combine(result,b.release())}}}result - } -} -/// The part of the image a verifier window can disturb and the accepted-prefix graph does not put back (a checkpoint's four pieces): -/// the tail, `dead`, the pooled row of the block in progress (`end / 4`, the spare) and the block position. Read before a window -/// and written back to undo it (`OriginalVerifyQsaJournal::discard_window`); the device must be idle. -impl<'ctx> OriginalQsaResidentIndex<'ctx>{ - pub(crate) const WINDOW_STATE_BYTES:usize=CHECKPOINT_BYTES; - pub(crate) fn read_window_state(&self,out:&mut [u8])->Result<()>{ - self.validate()?;if out.len()!=CHECKPOINT_BYTES{return Err(Error::InvalidSize)} - let(tail,rest)=out.split_at_mut(1536);let(dead,rest)=rest.split_at_mut(512);let(row,block)=rest.split_at_mut(512); - self.image[1].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0,tail)?; - self.image[2].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0,dead)?; - self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(self.end/4*512,row)?; - self.image[3].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0,block) - } - pub(crate) fn write_window_state(&mut self,bytes:&[u8])->Result<()>{ - self.validate()?;if bytes.len()!=CHECKPOINT_BYTES{return Err(Error::InvalidSize)} - let at=self.end/4*512; - let result=(||->Result<()>{ - self.image[1].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&bytes[..1536])?; - self.image[2].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&bytes[1536..2048])?; - self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(at,&bytes[2048..2560])?; - self.image[3].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0,&bytes[2560..]) - })(); - if result.is_err(){self.failed=true}result - } -} -impl Drop for OriginalQsaResidentIndex<'_>{fn drop(&mut self){let _=self.close_inner();}} -/// Prefix-cache transfer of the index image (`docs/prefix-cache.md`): the pooled key rows (512 B per 4-cell block) -/// below the checkpoint's end are plain device bytes, and the checkpoint carries the rest (the running pooling state -/// and the tail row). A parked prefix is therefore `rows` bytes plus `CHECKPOINT_BYTES` of tail, and importing one -/// mints a checkpoint of THIS image's lineage (a parked one belongs to no lineage). -impl<'ctx> OriginalQsaResidentIndex<'ctx>{ - /// Bytes of one pooled key row (four cells). - pub const ROW_BYTES:usize=512; - /// Bytes of a checkpoint's tail (`export_tail`). - pub const TAIL_BYTES:usize=CHECKPOINT_BYTES; - /// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host. - pub fn export_rows(&self,first_row:usize,rows:usize,out:&mut Vec)->Result<()>{ - self.validate()?;if self.in_flight||self.unpublished{return Err(Error::InvalidQwenShape)} - if rows==0||first_row.checked_add(rows).is_none_or(|e|e>self.end/4){return Err(Error::InvalidQwenShape)} - out.clear();out.try_reserve_exact(rows*Self::ROW_BYTES).map_err(|_|Error::HostAllocation)?;out.resize(rows*Self::ROW_BYTES,0); - self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row*Self::ROW_BYTES,out) - } - /// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end. - pub fn export_tail(&self,s:&OriginalQsaIndexCheckpoint<'ctx>)->Result>{ - self.validate()?;self.validate_checkpoint(s)?; - let mut out=vec![0u8;CHECKPOINT_BYTES];s.0.bytes.copy_to_range(0,&mut out)?;Ok(out) - } - /// Write the parked spans `(first_row, bytes)` and the tail `tail` (exported at position `end`), set the image's end - /// and return a fresh checkpoint of it. The rows below `end / 4` that no span names must already hold the prefix. - pub fn import(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,spans:&[(usize,&[u8])],tail:&[u8],end:usize)->Result>{ - self.validate()?;if self.in_flight{return Err(Error::InvalidQwenShape)} - if tail.len()!=CHECKPOINT_BYTES||end>crate::serving_context::geometry().cells(){return Err(Error::InvalidQwenShape)} - for(first,bytes)in spans{if bytes.is_empty()||bytes.len()%Self::ROW_BYTES!=0||first.checked_add(bytes.len()/Self::ROW_BYTES).is_none_or(|e|e>end/4){return Err(Error::InvalidQwenShape)}} - for(first,bytes)in spans{self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first*Self::ROW_BYTES,bytes)?;} - let mut b=self.checkpoint_buffer()?; - if let Err(e)=b.copy_from(tail){if self.context.is_poisoned(){std::mem::forget(b)}else{let _=b.release();}return Err(e)} - let parked=OriginalQsaIndexCheckpoint(Rc::new(Saved{origin:self.origin.clone(),epoch:self.epoch,coverage:Rc::new(Coverage{end:Cell::new(end)}),end,bytes:b,pool:Rc::downgrade(&self.pool)})); - self.restore_private(ws,&parked)?;drop(parked); - self.save(ws) - } +pub struct OriginalQsaResidentIndex<'ctx> { + pub(super) context: &'ctx Context<'ctx>, + origin: Rc, + epoch: u64, + coverage: Rc, + pub(super) end: usize, + image: [Option>; 4], + copy: Option, + failed: bool, + pub(super) in_flight: bool, + pub(super) unpublished: bool, + pool: Rc>>>, } /// Actual pending index batch. Forgetting it leaves owner in-flight/refusing new /// use; dropping without an explicit replay likewise refuses publication. -pub struct OriginalQsaIndexBatch<'index,'weights,'ctx>{pub(super) owner:&'index mut OriginalQsaResidentIndex<'ctx>,pub(super) start:OriginalQsaIndexCheckpoint<'ctx>,pub(super) raw:Option>,pub(super) gamma:&'weights DeviceBuffer<'ctx>,pub(super) rows:usize} -impl<'index,'weights,'ctx> OriginalQsaIndexBatch<'index,'weights,'ctx>{ - pub fn first_position(&self)->usize{self.start.next_position()}pub fn rows(&self)->usize{self.rows} - pub fn commit_prefix(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,workspace:&mut QsaPromptIndexWorkspace<'ctx>,accepted:usize)->Result>{ - if !self.owner.in_flight||self.raw.is_none()||accepted>self.rows{return Err(Error::InvalidQwenShape)}if accepted==self.rows{if self.owner.end!=self.start.next_position()+self.rows{return Err(Error::InvalidQwenShape)}let saved=self.owner.save(ws)?;self.owner.in_flight=false;self.owner.unpublished=false;if let Some(raw)=self.raw.take(){raw.release()?;}return Ok(saved)}self.owner.restore_private(ws,&self.start)?; - if accepted>0{let raw=self.raw.as_ref().ok_or(Error::ContextPoisoned)?;let rh=raw.handle.ok_or(Error::ContextPoisoned)?;let gh=self.gamma.handle.ok_or(Error::ContextPoisoned)?; - self.owner.placed(workspace,|w|w.replay_resident_prefix(self.start.next_position(),accepted,rh,gh,ws))?; - } - self.owner.end=self.start.next_position()+accepted;self.owner.coverage.end.set(self.owner.end); - let saved=self.owner.save(ws)?;self.owner.in_flight=false;self.owner.unpublished=false;if let Some(raw)=self.raw.take(){raw.release()?;}Ok(saved) - } - pub fn abort(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,workspace:&mut QsaPromptIndexWorkspace<'ctx>)->Result>{self.commit_prefix(ws,workspace,0)} +pub struct OriginalQsaIndexBatch<'index, 'weights, 'ctx> { + pub(super) owner: &'index mut OriginalQsaResidentIndex<'ctx>, + pub(super) start: OriginalQsaIndexCheckpoint<'ctx>, + pub(super) raw: Option>, + pub(super) gamma: &'weights DeviceBuffer<'ctx>, + pub(super) rows: usize, } -impl Drop for OriginalQsaIndexBatch<'_, '_, '_>{fn drop(&mut self){if let Some(b)=self.raw.take(){if self.owner.context.is_poisoned(){std::mem::forget(b)}else{drop(b)}}// A genuinely drained but abandoned batch is not published. Permit explicit -// restore of its authentic checkpoint after the exclusive borrow ends, while -// checkpoint()/new work refuses this unpublished live image. Forgetting the -// whole batch never runs Drop and leaves in_flight latched. -self.owner.in_flight=false;}} -#[cfg(all(feature="cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width="64"))] -#[path="qsa_verification_commit.rs"] +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[path = "qsa_verification_commit.rs"] pub(crate) mod verification_commit; + +#[path = "qsa_resident_index/image_bytes_fn.rs"] +mod image_bytes_fn; +#[allow(unused_imports)] +use image_bytes_fn::image_bytes; +#[path = "qsa_resident_index/impl_originalqsaindexbatch.rs"] +mod impl_originalqsaindexbatch; +#[path = "qsa_resident_index/impl_originalqsaresidentindex.rs"] +mod impl_originalqsaresidentindex; +#[path = "qsa_resident_index/impl_originalqsaresidentindex_2.rs"] +mod impl_originalqsaresidentindex_2; diff --git a/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs b/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs new file mode 100644 index 00000000..daa6ce88 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs @@ -0,0 +1,57 @@ +//! Moved out of the parent module by STRA-338: fn image_bytes, impl Drop_for_Saved, impl OriginalQsaIndexCheckpoint, impl Context. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn image_bytes() -> usize { + sizes()[0] + 1536 + 512 + 4 +} +impl Drop for Saved<'_> { + fn drop(&mut self) { + let Some(pool) = self.pool.upgrade() else { return }; + if self.bytes.context.is_poisoned() || self.bytes.len() != CHECKPOINT_BYTES { + return; + } + let Ok(mut pool) = pool.try_borrow_mut() else { return }; + if pool.len() >= POOLED || pool.try_reserve(1).is_err() { + return; + } + let Some(handle) = self.bytes.handle.take() else { return }; + // The allocation moves to the pool unchanged (still charged to the context); this owner no longer frees it. + pool.push(DeviceBuffer { + context: self.bytes.context, + handle: Some(handle), + bytes: self.bytes.bytes, + _thread: std::marker::PhantomData, + borrowed: false, + }); + } +} +impl OriginalQsaIndexCheckpoint<'_> { + pub fn next_position(&self) -> usize { + self.0.end + } + pub fn device_bytes(&self) -> usize { + CHECKPOINT_BYTES + } + pub fn validate_retained(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(context, self.0.bytes.context) { + return Err(Error::ContextMismatch); + } + if self.0.bytes.context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if self.0.end > crate::serving_context::geometry().cells() + || self.0.end > self.0.coverage.end.get() + || self.0.bytes.len() != CHECKPOINT_BYTES + { + return Err(Error::InvalidQwenShape); + } + self.0.bytes.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(CHECKPOINT_BYTES, 4) + } +} +impl<'ctx> Context<'ctx> { + pub fn original_qsa_resident_index(&'ctx self) -> Result> { + OriginalQsaResidentIndex::new(self) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaindexbatch.rs b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaindexbatch.rs new file mode 100644 index 00000000..db5be40c --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaindexbatch.rs @@ -0,0 +1,70 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaIndexBatch, impl Drop_for_OriginalQsaIndexBatch. + +#[allow(unused_imports)] +use super::*; + +impl<'index, 'weights, 'ctx> OriginalQsaIndexBatch<'index, 'weights, 'ctx> { + pub fn first_position(&self) -> usize { + self.start.next_position() + } + pub fn rows(&self) -> usize { + self.rows + } + pub fn commit_prefix( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + workspace: &mut QsaPromptIndexWorkspace<'ctx>, + accepted: usize, + ) -> Result> { + if !self.owner.in_flight || self.raw.is_none() || accepted > self.rows { + return Err(Error::InvalidQwenShape); + } + if accepted == self.rows { + if self.owner.end != self.start.next_position() + self.rows { + return Err(Error::InvalidQwenShape); + } + let saved = self.owner.save(ws)?; + self.owner.in_flight = false; + self.owner.unpublished = false; + if let Some(raw) = self.raw.take() { + raw.release()?; + } + return Ok(saved); + } + self.owner.restore_private(ws, &self.start)?; + if accepted > 0 { + let raw = self.raw.as_ref().ok_or(Error::ContextPoisoned)?; + let rh = raw.handle.ok_or(Error::ContextPoisoned)?; + let gh = self.gamma.handle.ok_or(Error::ContextPoisoned)?; + self.owner + .placed(workspace, |w| w.replay_resident_prefix(self.start.next_position(), accepted, rh, gh, ws))?; + } + self.owner.end = self.start.next_position() + accepted; + self.owner.coverage.end.set(self.owner.end); + let saved = self.owner.save(ws)?; + self.owner.in_flight = false; + self.owner.unpublished = false; + if let Some(raw) = self.raw.take() { + raw.release()?; + } + Ok(saved) + } + pub fn abort( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + workspace: &mut QsaPromptIndexWorkspace<'ctx>, + ) -> Result> { + self.commit_prefix(ws, workspace, 0) + } +} +impl Drop for OriginalQsaIndexBatch<'_, '_, '_> { + fn drop(&mut self) { + if let Some(b) = self.raw.take() { + if self.owner.context.is_poisoned() { std::mem::forget(b) } else { drop(b) } + } // A genuinely drained but abandoned batch is not published. Permit explicit + // restore of its authentic checkpoint after the exclusive borrow ends, while + // checkpoint()/new work refuses this unpublished live image. Forgetting the + // whole batch never runs Drop and leaves in_flight latched. + self.owner.in_flight = false; + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex.rs b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex.rs new file mode 100644 index 00000000..a295edf3 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex.rs @@ -0,0 +1,252 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentIndex. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaResidentIndex<'ctx> { + pub fn device_bytes() -> usize { + image_bytes() + } + pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { + let n = image_bytes().checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if context.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if context.allocated_bytes().checked_add(n).is_none_or(|x| x > context.budget_bytes()) + || context.memory_info()?.0 < n + { + return Err(Error::BudgetExceeded); + } + let mut s = Self { + context, + origin: Rc::new(Origin), + epoch: 0, + coverage: Rc::new(Coverage { end: Cell::new(0) }), + end: 0, + image: std::array::from_fn(|_| None), + copy: None, + failed: false, + in_flight: false, + unpublished: false, + pool: Rc::new(RefCell::new(Vec::new())), + }; + let op = (|| -> Result<()> { + s.copy = Some(Transfer::new()?); + // One-time bounded initialization, never a whole host index image. Each + // upload owns its actual staging until completion; no 33MiB host allocation. + let zero = [0u8; 65536]; + for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() { + s.image[i] = Some(context.allocate(n)?); + let b = s.image[i].as_mut().ok_or(Error::ContextPoisoned)?; + for offset in (0..n).step_by(zero.len()) { + b.copy_from_range(offset, &zero[..(n - offset).min(zero.len())]).map_err(|e| { + if !matches!(e, Error::HostAllocation) { + context.poison(); + context.retain_driver(); + } + e + })?; + } + } + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = op { + return combine(Err(e), s.close()); + } + Ok(s) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn allocated_bytes(&self) -> usize { + self.image.iter().flatten().map(DeviceBuffer::len).sum() + } + pub fn next_position(&self) -> usize { + self.end + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + pub(in super::super) fn validate(&self) -> Result<()> { + if self.is_failed() || self.copy.is_none() { + return Err(Error::ContextPoisoned); + } + for (i, n) in [sizes()[0], 1536, 512, 4].into_iter().enumerate() { + let b = self.image[i].as_ref().ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(b.context, self.context) || b.len() != n { + return Err(Error::InvalidQwenShape); + } + b.handle.ok_or(Error::ContextPoisoned)?.validate_projection_extent(n, 4)?; + } + Ok(()) + } + pub fn validate_checkpoint(&self, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result<()> { + self.validate()?; + if !Rc::ptr_eq(&self.origin, &s.0.origin) + || self.epoch != s.0.epoch + || s.0.end > s.0.coverage.end.get() + || s.0.end > crate::serving_context::geometry().cells() + || !std::ptr::eq(self.context, s.0.bytes.context) + || s.0.bytes.len() != CHECKPOINT_BYTES + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub(in super::super) fn h(&self, i: usize, o: usize, n: usize) -> Result { + let b = self.image[i].as_ref().ok_or(Error::ContextPoisoned)?; + b.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(b.len(), o, n) + } + pub(in super::super) fn copy_ranges( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + ranges: &[(ffi::BufferHandle, ffi::BufferHandle, usize)], + ) -> Result<()> { + self.validate()?; + ws.validate_context(self.context)?; + let mut copies = Vec::new(); + copies.try_reserve_exact(ranges.len()).map_err(|_| Error::HostAllocation)?; + for (src, dst, n) in ranges { + if *n == 0 || src.overlaps(*n, *dst, *n) { + return Err(Error::OutputAliasesInput); + } + src.validate_projection_extent(*n, 1)?; + dst.validate_projection_extent(*n, 1)?; + copies.push((src.qwen_address(), dst.qwen_address(), *n)); + } + let result = self.copy.as_ref().ok_or(Error::ContextPoisoned)?.copy(self.context, ws, &copies); + if result.is_err() { + self.failed = true + } + result + } + pub fn checkpoint(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) -> Result> { + self.validate()?; + if self.in_flight || self.unpublished { + return Err(Error::InvalidQwenShape); + } + self.save(ws) + } + /// A checkpoint buffer: a pooled one, else a new allocation under the usual admission. + pub(super) fn checkpoint_buffer(&self) -> Result> { + if let Some(b) = self.pool.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.pop() { + if std::ptr::eq(b.context, self.context) && b.len() == CHECKPOINT_BYTES && b.handle.is_some() { + return Ok(b); + } + let _ = b.release(); + } + let n = CHECKPOINT_BYTES + RESERVE; + if self.context.allocated_bytes().checked_add(n).is_none_or(|x| x > self.context.budget_bytes()) + || self.context.memory_info()?.0 < n + { + return Err(Error::BudgetExceeded); + } + self.context.allocate(CHECKPOINT_BYTES) + } + /// The four checkpoint copies of the current image into `h` (index image -> checkpoint bytes). + pub(super) fn save_ranges( + &self, + h: ffi::BufferHandle, + ) -> Result<[(ffi::BufferHandle, ffi::BufferHandle, usize); 4]> { + Ok([ + (self.h(1, 0, 1536)?, h.checked_subspan(CHECKPOINT_BYTES, 0, 1536)?, 1536), + (self.h(2, 0, 512)?, h.checked_subspan(CHECKPOINT_BYTES, 1536, 512)?, 512), + (self.h(0, self.end / 4 * 512, 512)?, h.checked_subspan(CHECKPOINT_BYTES, 2048, 512)?, 512), + (self.h(3, 0, 4)?, h.checked_subspan(CHECKPOINT_BYTES, 2560, 4)?, 4), + ]) + } + pub(super) fn saved(&self, b: DeviceBuffer<'ctx>) -> OriginalQsaIndexCheckpoint<'ctx> { + OriginalQsaIndexCheckpoint(Rc::new(Saved { + origin: self.origin.clone(), + epoch: self.epoch, + coverage: self.coverage.clone(), + end: self.end, + bytes: b, + pool: Rc::downgrade(&self.pool), + })) + } + pub(in super::super) fn save( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + let b = self.checkpoint_buffer()?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + let op = self.save_ranges(h).and_then(|ranges| self.copy_ranges(ws, &ranges)); + if let Err(e) = op { + if self.context.is_poisoned() { + std::mem::forget(b) + } else { + let _ = b.release(); + } + return Err(e); + } + Ok(self.saved(b)) + } + /// `checkpoint` of several committed images at once, AFTER the caller fenced every writer of them (the verifier's + /// commit event): one stream-ordered batch of copies and one stream drain, without the context-wide synchronize a + /// lone checkpoint makes (that waited for the adaptive expert swaps and the draft too). Same bytes as `checkpoint`. + pub(crate) fn checkpoint_fenced_all( + indices: &mut [&mut OriginalQsaResidentIndex<'ctx>], + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result>> { + let first = indices.first().ok_or(Error::InvalidQwenShape)?.context; + for i in indices.iter() { + i.validate()?; + if !std::ptr::eq(i.context, first) { + return Err(Error::ContextMismatch); + } + if i.in_flight || i.unpublished { + return Err(Error::InvalidQwenShape); + } + } + ws.validate_context(first)?; + let mut buffers: Vec> = Vec::new(); + buffers.try_reserve_exact(indices.len()).map_err(|_| Error::HostAllocation)?; + let mut copies = Vec::new(); + copies.try_reserve_exact(4 * indices.len()).map_err(|_| Error::HostAllocation)?; + let staged = (|| -> Result<()> { + for i in indices.iter() { + let b = i.checkpoint_buffer()?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + buffers.push(b); + for (src, dst, n) in i.save_ranges(h)? { + if n == 0 || src.overlaps(n, dst, n) { + return Err(Error::OutputAliasesInput); + } + src.validate_projection_extent(n, 1)?; + dst.validate_projection_extent(n, 1)?; + copies.push((src.qwen_address(), dst.qwen_address(), n)); + } + } + Ok(()) + })(); + let copied = staged + .and_then(|()| indices[0].copy.as_ref().ok_or(Error::ContextPoisoned)?.copy_fenced(first, ws, &copies)); + if let Err(e) = copied { + for i in indices.iter_mut() { + i.failed = true + } + for b in buffers { + if first.is_poisoned() { + std::mem::forget(b) + } else { + let _ = b.release(); + } + } + return Err(e); + } + Ok(indices.iter().zip(buffers).map(|(i, b)| i.saved(b)).collect()) + } + pub fn restore(&mut self, ws: &mut NativeBatchWorkspace<'ctx>, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result<()> { + if self.in_flight { + return Err(Error::InvalidQwenShape); + } + self.restore_private(ws, s) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs new file mode 100644 index 00000000..2173a319 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentIndex (2), impl OriginalQsaResidentIndex, impl Drop_for_OriginalQsaResidentIndex, impl OriginalQsaResidentIndex. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalQsaResidentIndex<'ctx> { + pub(in super::super) fn restore_private( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + s: &OriginalQsaIndexCheckpoint<'ctx>, + ) -> Result<()> { + self.validate_checkpoint(s)?; + let h = s.0.bytes.handle.ok_or(Error::ContextPoisoned)?; + self.copy_ranges( + ws, + &[ + (h.checked_subspan(CHECKPOINT_BYTES, 0, 1536)?, self.h(1, 0, 1536)?, 1536), + (h.checked_subspan(CHECKPOINT_BYTES, 1536, 512)?, self.h(2, 0, 512)?, 512), + (h.checked_subspan(CHECKPOINT_BYTES, 2048, 512)?, self.h(0, s.0.end / 4 * 512, 512)?, 512), + (h.checked_subspan(CHECKPOINT_BYTES, 2560, 4)?, self.h(3, 0, 4)?, 4), + ], + )?; + self.coverage.end.set(self.coverage.end.get().min(s.0.end)); + self.coverage = Rc::new(Coverage { end: Cell::new(s.0.end) }); + self.end = s.0.end; + self.unpublished = false; + Ok(()) + } + pub(in super::super) fn placed( + &mut self, + w: &mut QsaPromptIndexWorkspace<'ctx>, + f: impl FnOnce(&mut QsaPromptIndexWorkspace<'ctx>) -> Result, + ) -> Result { + self.validate()?; + if !std::ptr::eq(self.context, w.context) { + return Err(Error::ContextMismatch); + } + struct Placement<'a, 'ctx> { + owner: &'a mut OriginalQsaResidentIndex<'ctx>, + workspace: &'a mut QsaPromptIndexWorkspace<'ctx>, + sizes: [usize; 4], + } + impl Drop for Placement<'_, '_> { + fn drop(&mut self) { + for i in 0..4 { + std::mem::swap(&mut self.owner.image[i], &mut self.workspace.buffers[i]); + self.workspace.sizes[i] = self.sizes[i]; + } + if self.workspace.is_failed() { + self.owner.failed = true + } + } + } + let image_sizes = [sizes()[0], 1536, 512, 4]; + let sizes = std::array::from_fn(|i| w.sizes[i]); + for i in 0..4 { + std::mem::swap(&mut self.image[i], &mut w.buffers[i]); + w.sizes[i] = image_sizes[i]; + } + let placement = Placement { owner: self, workspace: w, sizes }; + f(&mut *placement.workspace) + } + pub fn reset(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) -> Result<()> { + self.validate()?; + if self.in_flight { + return Err(Error::InvalidQwenShape); + } + ws.validate_context(self.context)?; + let epoch = self.epoch.checked_add(1).ok_or(Error::InvalidQwenShape)?; + let zero = [0u8; 1536]; + for b in self.image[1..].iter_mut().flatten() { + let n = b.len(); + b.copy_from(&zero[..n]).map_err(|e| { + if !matches!(e, Error::HostAllocation) { + self.context.poison(); + self.context.retain_driver(); + } + e + })?; + } + self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &zero[..512]).map_err(|e| { + if !matches!(e, Error::HostAllocation) { + self.context.poison(); + self.context.retain_driver(); + } + e + })?; + self.coverage.end.set(0); + self.coverage = Rc::new(Coverage { end: Cell::new(0) }); + self.end = 0; + self.epoch = epoch; + self.unpublished = false; + Ok(()) + } + pub(in super::super) fn provisional_end(&mut self, end: usize) { + self.end = end; + self.coverage.end.set(end); + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut result = Ok(()); + if let Ok(mut pool) = self.pool.try_borrow_mut() { + for b in pool.drain(..) { + if self.context.is_poisoned() { std::mem::forget(b) } else { result = combine(result, b.release()) } + } + } + if let Some(m) = self.copy.take() { + if self.context.is_poisoned() || self.in_flight { + std::mem::forget(m); + result = Err(Error::ContextPoisoned) + } else { + drop(m) + } + } + for b in &mut self.image { + if let Some(b) = b.take() { + if self.context.is_poisoned() || self.in_flight { + std::mem::forget(b); + result = combine(result, Err(Error::ContextPoisoned)) + } else { + result = combine(result, b.release()) + } + } + } + result + } +} +/// The part of the image a verifier window can disturb and the accepted-prefix graph does not put back (a checkpoint's four pieces): +/// the tail, `dead`, the pooled row of the block in progress (`end / 4`, the spare) and the block position. Read before a window +/// and written back to undo it (`OriginalVerifyQsaJournal::discard_window`); the device must be idle. +impl<'ctx> OriginalQsaResidentIndex<'ctx> { + pub(crate) const WINDOW_STATE_BYTES: usize = CHECKPOINT_BYTES; + pub(crate) fn read_window_state(&self, out: &mut [u8]) -> Result<()> { + self.validate()?; + if out.len() != CHECKPOINT_BYTES { + return Err(Error::InvalidSize); + } + let (tail, rest) = out.split_at_mut(1536); + let (dead, rest) = rest.split_at_mut(512); + let (row, block) = rest.split_at_mut(512); + self.image[1].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0, tail)?; + self.image[2].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0, dead)?; + self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(self.end / 4 * 512, row)?; + self.image[3].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(0, block) + } + pub(crate) fn write_window_state(&mut self, bytes: &[u8]) -> Result<()> { + self.validate()?; + if bytes.len() != CHECKPOINT_BYTES { + return Err(Error::InvalidSize); + } + let at = self.end / 4 * 512; + let result = (|| -> Result<()> { + self.image[1].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &bytes[..1536])?; + self.image[2].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &bytes[1536..2048])?; + self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(at, &bytes[2048..2560])?; + self.image[3].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &bytes[2560..]) + })(); + if result.is_err() { + self.failed = true + } + result + } +} +impl Drop for OriginalQsaResidentIndex<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +/// Prefix-cache transfer of the index image (`docs/prefix-cache.md`): the pooled key rows (512 B per 4-cell block) +/// below the checkpoint's end are plain device bytes, and the checkpoint carries the rest (the running pooling state +/// and the tail row). A parked prefix is therefore `rows` bytes plus `CHECKPOINT_BYTES` of tail, and importing one +/// mints a checkpoint of THIS image's lineage (a parked one belongs to no lineage). +impl<'ctx> OriginalQsaResidentIndex<'ctx> { + /// Bytes of one pooled key row (four cells). + pub const ROW_BYTES: usize = 512; + /// Bytes of a checkpoint's tail (`export_tail`). + pub const TAIL_BYTES: usize = CHECKPOINT_BYTES; + /// Copy the pooled key rows `first_row..first_row + rows` (all below the current end / 4) to the host. + pub fn export_rows(&self, first_row: usize, rows: usize, out: &mut Vec) -> Result<()> { + self.validate()?; + if self.in_flight || self.unpublished { + return Err(Error::InvalidQwenShape); + } + if rows == 0 || first_row.checked_add(rows).is_none_or(|e| e > self.end / 4) { + return Err(Error::InvalidQwenShape); + } + out.clear(); + out.try_reserve_exact(rows * Self::ROW_BYTES).map_err(|_| Error::HostAllocation)?; + out.resize(rows * Self::ROW_BYTES, 0); + self.image[0].as_ref().ok_or(Error::ContextPoisoned)?.copy_to_range(first_row * Self::ROW_BYTES, out) + } + /// The bytes of a checkpoint of this lineage: everything `import` needs besides the rows below its end. + pub fn export_tail(&self, s: &OriginalQsaIndexCheckpoint<'ctx>) -> Result> { + self.validate()?; + self.validate_checkpoint(s)?; + let mut out = vec![0u8; CHECKPOINT_BYTES]; + s.0.bytes.copy_to_range(0, &mut out)?; + Ok(out) + } + /// Write the parked spans `(first_row, bytes)` and the tail `tail` (exported at position `end`), set the image's end + /// and return a fresh checkpoint of it. The rows below `end / 4` that no span names must already hold the prefix. + pub fn import( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + spans: &[(usize, &[u8])], + tail: &[u8], + end: usize, + ) -> Result> { + self.validate()?; + if self.in_flight { + return Err(Error::InvalidQwenShape); + } + if tail.len() != CHECKPOINT_BYTES || end > crate::serving_context::geometry().cells() { + return Err(Error::InvalidQwenShape); + } + for (first, bytes) in spans { + if bytes.is_empty() + || bytes.len() % Self::ROW_BYTES != 0 + || first.checked_add(bytes.len() / Self::ROW_BYTES).is_none_or(|e| e > end / 4) + { + return Err(Error::InvalidQwenShape); + } + } + for (first, bytes) in spans { + self.image[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(first * Self::ROW_BYTES, bytes)?; + } + let mut b = self.checkpoint_buffer()?; + if let Err(e) = b.copy_from(tail) { + if self.context.is_poisoned() { + std::mem::forget(b) + } else { + let _ = b.release(); + } + return Err(e); + } + let parked = OriginalQsaIndexCheckpoint(Rc::new(Saved { + origin: self.origin.clone(), + epoch: self.epoch, + coverage: Rc::new(Coverage { end: Cell::new(end) }), + end, + bytes: b, + pool: Rc::downgrade(&self.pool), + })); + self.restore_private(ws, &parked)?; + drop(parked); + self.save(ws) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index_program.rs b/crates/cuda-driver/src/qsa_resident_index_program.rs index abb48a5e..4f55df28 100644 --- a/crates/cuda-driver/src/qsa_resident_index_program.rs +++ b/crates/cuda-driver/src/qsa_resident_index_program.rs @@ -1,151 +1,10 @@ //! Same literal index program over real resident image; no prior upload, //! host final image, raw FP16 round, or selected-ID payload readback. use super::*; -impl<'ctx> QsaPromptIndexWorkspace<'ctx>{ - #[allow(clippy::too_many_arguments)] - pub(super) fn run_resident_arena(&mut self,p0:u32,t:u32,raw_h:ffi::BufferHandle,qfull_h:ffi::BufferHandle,iq_h:ffi::BufferHandle, - gamma:[ffi::BufferHandle;4],out:[ffi::BufferHandle;5],ws:&mut NativeBatchWorkspace<'ctx>,decode:bool)->Result<()>{ - let n=t as usize;let p=p0 as usize;let end=p+n;let nb=end/4; - let mut steps=Vec::new();steps.try_reserve_exact(n*16).map_err(|_|Error::HostAllocation)?; - for row in 0..n{let pos=p+row;for x in [pos,pos+1,(pos+1)/4,(pos+1).min(CAP)]{steps.extend((x as i32).to_le_bytes());}} - let zero=vec![0u8;64];let mut flags=vec![0u8;64];let status=self.handle(10,64)?;let mut commands:Vec<(Launch,Arguments)>=Vec::new();commands.try_reserve_exact(32+4*n.div_ceil(256)).map_err(|_|Error::HostAllocation)?; - // (position in `commands` it runs before, grid, qsa_late entry, arguments) - let mut late:Vec<(usize,u32,usize,u32,crate::ple_batch_ffi::KernelArguments)>=Vec::new(); - let fast_select=!decode&&crate::qsa_late::usable(self.context); - let pushed=std::cell::Cell::new(0usize); - let mut push=|shape,args|->Result<()>{commands.push((shape,Arguments::for_launch(shape,args)?));pushed.set(pushed.get()+1);Ok(())}; - let theta=crate::qsa_index_ffi::theta();if !theta.is_finite()||theta<=0.0{return Err(Error::InvalidDriverValue("QSA theta"));} - let mut decode_positions=Vec::new(); - let positions=if decode { - decode_positions.try_reserve_exact(24*4).map_err(|_|Error::HostAllocation)?; - for _ in 0..24{decode_positions.extend((p0 as i32).to_le_bytes());} - let b=self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; - let full=self.handle(4,self.sizes[4])?; - let h=full.checked_subspan(b.len(),self.sizes[4]-24*4,24*4)?; - h.validate_projection_extent(24*4,4)?; - if h.overlaps(24*4,self.handle(4,n*128*4)?,n*128*4){return Err(Error::OutputAliasesInput);} - Some(h) - }else{None}; - let k_h=out[0];let pooled_h=self.handle(0,self.sizes[0])?;let tail_h=self.handle(1,self.sizes[1])?;let dead_h=self.handle(2,self.sizes[2])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(2),vec![A::Address(k_h),A::Address(gamma[1]),A::Address(k_h),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(2),vec![A::Address(k_h),A::Address(k_h),A::I32(2),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*2),vec![A::Address(k_h),A::Address(gamma[1]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*2),vec![A::Address(k_h),A::I64(2),A::I64(256),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(k_h),A::I64((n*512)as i64),A::Address(status),A::U32(0)])?; - push(Launch::Split((n*6144)as u32),vec![A::Address(qfull_h),A::Address(out[2]),A::I64(t as i64)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(24),vec![A::Address(out[2]),A::Address(gamma[0]),A::Address(out[2]),A::I32(256),A::F32(1e-6)])?; - push(Launch::DecodeRope(24),vec![A::Address(out[2]),A::Address(out[2]),A::I32(24),A::I32(256),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*24),vec![A::Address(out[2]),A::Address(gamma[0]),A::I64(256),A::I64(256),A::F32(1e-6)])?; - push(Launch::Rope(t*24),vec![A::Address(out[2]),A::I64(24),A::I64(256),A::I64(6144),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*6144)as u32),vec![A::Address(out[2]),A::I64((n*6144)as i64),A::Address(status),A::U32(1)])?; - if let Some(positions)=positions { - push(Launch::DecodeRms(4),vec![A::Address(iq_h),A::Address(gamma[2]),A::Address(iq_h),A::I32(128),A::F32(1e-6)])?; - push(Launch::DecodeRope(4),vec![A::Address(iq_h),A::Address(iq_h),A::I32(4),A::I32(128),A::F32(theta),A::Address(positions)])?; - }else{ - push(Launch::Rms(t*4),vec![A::Address(iq_h),A::Address(gamma[2]),A::I64(128),A::I64(128),A::F32(1e-6)])?; - push(Launch::Rope(t*4),vec![A::Address(iq_h),A::I64(4),A::I64(128),A::I64(512),A::I64(p0 as i64),A::F32(theta)])?; - } - push(Launch::Scan((n*512)as u32),vec![A::Address(iq_h),A::I64((n*512)as i64),A::Address(status),A::U32(2)])?; - if decode { - push(Launch::DecodeAppend,vec![A::Address(raw_h),A::Address(out[4]),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I32(crate::serving_context::geometry().cells() as i32),A::F32(theta)])?; - } else { - if p==0{push(Launch::First,vec![A::Address(raw_h),A::Address(gamma[3]),A::F32(1e-6),A::Address(dead_h),A::Address(pooled_h),A::F32(theta)])?;} - let first=if p<=3{0}else{(p-3).div_ceil(4)};let hi=if end-1>=3{Some((end-4)/4)}else{None}; - if let Some(hi)=hi.filter(|hi|*hi>=first){push(Launch::Blocks((hi-first+1)as u32),vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::I32(0),A::Address(gamma[3]),A::F32(1e-6),A::Address(tail_h),A::Address(dead_h),A::Address(pooled_h),A::Address(self.handle(3,4)?),A::I64(first as i64),A::I64(hi as i64),A::F32(theta)])?;} - push(Launch::Tail,vec![A::Address(raw_h),A::I64(t as i64),A::I64(p0 as i64),A::Address(tail_h)])?; - } - for (h,count) in [(pooled_h,(nb+1)*128),(tail_h,384),(dead_h,128)]{push(Launch::Scan(count as u32),vec![A::Address(h),A::I64(count as i64),A::Address(status),A::U32(3)])?;} - // Original prompt selection reuses one 256-row score tile. Every - // offset is checked against the actual whole producer allocation. - let tile_rows=if decode {1}else{n.min(256)}; - let scores=self.handle(9,tile_rows*max_blocks()*4)?; - for first_row in (0..n).step_by(256) { - let count=(n-first_row).min(256);let ct=count as u32; - let iq_tile=iq_h.checked_subspan(n*512*4,first_row*512*4,count*512*4)?; - let steps_tile=out[4].checked_subspan(n*16,first_row*16,count*16)?; - let ids_tile=out[3].checked_subspan(n*CAP*4,first_row*CAP*4,count*CAP*4)?; - let tile_reach=(p+first_row+count)/4+1; - if decode { - push(Launch::DecodeScores,vec![A::Address(pooled_h),A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I32(1),A::I64(max_blocks() as i64),A::Address(scores)])?; - } else { - push(Launch::Tc{t:ct,reach:tile_reach as u32},vec![A::Address(pooled_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(count as i64),A::I64(max_blocks() as i64),A::I64(tile_reach as i64),A::Address(scores)])?; - push(Launch::ScoreTail(ct),vec![A::Address(dead_h),A::Address(iq_tile),A::Address(steps_tile),A::I64(max_blocks() as i64),A::Address(scores)])?; - } - if fast_select&&!decode{ - // qsa_late.cu: the same flag over the blocks the tile can hold, and the same ids from coalesced reads - late.push((pushed.get(),(count*tile_reach).div_ceil(256)as u32,crate::qsa_late::SCORE_SCAN_FAST,256,crate::ple_batch_ffi::KernelArguments::new(vec![ - crate::ple_batch_ffi::BatchArg::Address(scores),crate::ple_batch_ffi::BatchArg::Address(steps_tile),crate::ple_batch_ffi::BatchArg::I32(count as i32), - crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64),crate::ple_batch_ffi::BatchArg::I64(tile_reach as i64),crate::ple_batch_ffi::BatchArg::Address(status),crate::ple_batch_ffi::BatchArg::U32(4)]))); - let(topk_entry,topk_block)=crate::qsa_late::topk_entry(tile_reach); - late.push((pushed.get(),ct,topk_entry,topk_block,crate::ple_batch_ffi::KernelArguments::new(vec![ - crate::ple_batch_ffi::BatchArg::Address(scores),crate::ple_batch_ffi::BatchArg::Address(steps_tile),crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64), - crate::ple_batch_ffi::BatchArg::I64(CAP as i64),crate::ple_batch_ffi::BatchArg::Address(ids_tile)]))); - }else{ - push(Launch::ScoreScan((count*max_blocks())as u32),vec![A::Address(scores),A::Address(steps_tile),A::I32(count as i32),A::I64(max_blocks() as i64),A::Address(status),A::U32(4)])?; - push(Launch::Topk(ct),vec![A::Address(scores),A::Address(steps_tile),A::I64(max_blocks() as i64),A::I64(CAP as i64),A::Address(ids_tile)])?; - } - } - push(Launch::Scan((n*128)as u32),vec![A::Address(raw_h),A::I64((n*128)as i64),A::Address(status),A::U32(5)])?; - let context=self.context;let guard=match context.enter(){Ok(guard)=>guard,Err(error)=>{self.failed=true;ws.mark_failed();context.poison();context.retain_driver();return Err(error);}};let blas=ws.blas()?; - let operation=(||{context.driver.api.copy_from(status,&zero)?;context.driver.api.copy_from(out[4],&steps)?; - if let Some(positions)=positions{context.driver.api.copy_from(positions,&decode_positions)?;} - // Pageable uploads/status have a real dependency before the nonblocking shared stream. - context.driver.api.synchronize()?; - // LELEKA_PREFILL_PROFILE_SYNC: every launch drained on its own and charged to its kind (qsa-index#kind) - let timed=crate::command_profile::enabled(); - if !late.is_empty()&&self.late.is_none(){self.late=Some(crate::ple_batch_ffi::KernelModule::load(crate::qsa_late::PTX,crate::qsa_late::ENTRIES)?);} - let module=self.module.as_ref().ok_or(Error::ContextPoisoned)?; - let mut next=0usize; - let mut run_late=|upto:usize,late:&mut Vec<(usize,u32,usize,u32,crate::ple_batch_ffi::KernelArguments)>,next:&mut usize|->Result<()>{ - while *next().0{if u32::from_le_bytes(*flag)>1{self.failed=true;return Err(Error::InvalidDriverValue("QSA finite status"));}} - if flags[24..].iter().any(|x|*x!=0){self.failed=true;return Err(Error::InvalidDriverValue("QSA unused status"));} - if flags[..24].iter().any(|x|*x!=0){return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores"));} - Ok(()) - } -} -impl<'ctx> QsaPromptIndexWorkspace<'ctx>{ - pub(super) fn replay_resident_prefix(&mut self,p0:usize,t:usize,raw:ffi::BufferHandle,gamma:ffi::BufferHandle,ws:&mut NativeBatchWorkspace<'ctx>)->Result<()>{ - if !(1..=8192).contains(&t)||p0.checked_add(t).is_none_or(|x|x>crate::serving_context::geometry().cells()){return Err(Error::InvalidQwenShape)} - ws.validate_context(self.context)?;raw.validate_projection_extent(t*512,4)?;gamma.validate_projection_extent(512,4)?; - let status=self.handle(10,64)?;let pooled=self.handle(0,self.sizes[0])?;let tail=self.handle(1,1536)?;let dead=self.handle(2,512)?;let bp=self.handle(3,4)?; - let mut steps=Vec::new();steps.try_reserve_exact(t*16).map_err(|_|Error::HostAllocation)?; - for row in 0..t{let p=p0+row;for x in [p,p+1,(p+1)/4,(p+1).min(CAP)]{steps.extend((x as i32).to_le_bytes());}} - let mut step=self.context.allocate(t*16)?;step.copy_from(&steps)?;let sh=step.handle.ok_or(Error::ContextPoisoned)?; - let mut commands=Vec::new();commands.try_reserve_exact(t*4).map_err(|_|Error::HostAllocation)?;let theta=crate::qsa_index_ffi::theta(); - if !theta.is_finite()||theta<=0.0{return Err(Error::InvalidDriverValue("QSA theta"))} - for row in 0..t{let p=p0+row;let key=raw.checked_subspan(t*512,row*512,512)?;let pos=sh.checked_subspan(t*16,row*16,4)?; - commands.push((Launch::DecodeAppend,Arguments::for_launch(Launch::DecodeAppend,vec![A::Address(key),A::Address(pos),A::I32(0),A::Address(gamma),A::F32(1e-6),A::Address(tail),A::Address(dead),A::Address(pooled),A::Address(bp),A::I32(crate::serving_context::geometry().cells() as i32),A::F32(theta)])?)); - for(h,n)in[(pooled,((p+1)/4+1)*128),(tail,384),(dead,128)]{commands.push((Launch::Scan(n as u32),Arguments::new(vec![A::Address(h),A::I64(n as i64),A::Address(status),A::U32(0)])?));} - } - let c=self.context;let g=c.enter().map_err(|e|{self.failed=true;ws.mark_failed();c.poison();c.retain_driver();e})?;let blas=ws.blas()?; - let zero=[0u8;64];let mut flags=[0u8;64]; - let op=(||->Result<()>{c.driver.api.copy_from(status,&zero)?;c.driver.api.synchronize()?;for(shape,args)in &mut commands{self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(*shape,blas.stream(),args)?;}Ok(())})(); - let sync=blas.synchronize();let read=if sync.is_ok(){c.driver.api.copy_to(status,&mut flags)}else{Ok(())};let pop=g.finish(); - if op.is_err()||sync.is_err()||read.is_err()||pop.is_err(){self.failed=true;ws.mark_failed();c.poison();c.retain_driver();if sync.is_err()||pop.is_err(){std::mem::forget((commands,step));}return combine(combine(combine(op,sync),read),pop)} - if flags[4..].iter().any(|x|*x!=0)||u32::from_le_bytes(flags[..4].try_into().map_err(|_|Error::InvalidSize)?)>1{self.failed=true;c.poison();c.retain_driver();return Err(Error::InvalidDriverValue("QSA replay finite flags"))} - if flags[0]!=0{return Err(Error::NonFiniteMmqOutput("QSA accepted index replay"))}Ok(()) - } -} -fn launch_label(launch:&Launch)->(usize,&'static str){match launch{ - Launch::First=>(1,"first"),Launch::Blocks(_)=>(2,"blocks (pool)"),Launch::Tail=>(3,"tail"),Launch::Rms(_)=>(4,"rms"),Launch::Rope(_)=>(5,"rope"), - Launch::Split(_)=>(6,"split"),Launch::Scan(_)=>(7,"finite scan"),Launch::ScoreScan(_)=>(8,"score scan"),Launch::Round(_)=>(9,"round"), - Launch::Tc{..}=>(10,"tc scores"),Launch::ScoreTail(_)=>(11,"score tail"),Launch::Topk(_)=>(12,"topk"), - Launch::DecodeAppend=>(13,"decode append"),Launch::DecodeScores=>(14,"decode scores"),Launch::DecodeRms(_)=>(15,"decode rms"),Launch::DecodeRope(_)=>(16,"decode rope")}} +#[path = "qsa_resident_index_program/impl_qsapromptindexworkspace.rs"] +mod impl_qsapromptindexworkspace; +#[path = "qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs"] +mod impl_qsapromptindexworkspace_2; +#[allow(unused_imports)] +use impl_qsapromptindexworkspace_2::launch_label; diff --git a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs new file mode 100644 index 00000000..72d32653 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace.rs @@ -0,0 +1,415 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn run_resident_arena( + &mut self, + p0: u32, + t: u32, + raw_h: ffi::BufferHandle, + qfull_h: ffi::BufferHandle, + iq_h: ffi::BufferHandle, + gamma: [ffi::BufferHandle; 4], + out: [ffi::BufferHandle; 5], + ws: &mut NativeBatchWorkspace<'ctx>, + decode: bool, + ) -> Result<()> { + let n = t as usize; + let p = p0 as usize; + let end = p + n; + let nb = end / 4; + let mut steps = Vec::new(); + steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; + for row in 0..n { + let pos = p + row; + for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { + steps.extend((x as i32).to_le_bytes()); + } + } + let zero = vec![0u8; 64]; + let mut flags = vec![0u8; 64]; + let status = self.handle(10, 64)?; + let mut commands: Vec<(Launch, Arguments)> = Vec::new(); + commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; + // (position in `commands` it runs before, grid, qsa_late entry, arguments) + let mut late: Vec<(usize, u32, usize, u32, crate::ple_batch_ffi::KernelArguments)> = Vec::new(); + let fast_select = !decode && crate::qsa_late::usable(self.context); + let pushed = std::cell::Cell::new(0usize); + let mut push = |shape, args| -> Result<()> { + commands.push((shape, Arguments::for_launch(shape, args)?)); + pushed.set(pushed.get() + 1); + Ok(()) + }; + let theta = crate::qsa_index_ffi::theta(); + if !theta.is_finite() || theta <= 0.0 { + return Err(Error::InvalidDriverValue("QSA theta")); + } + let mut decode_positions = Vec::new(); + let positions = if decode { + decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; + for _ in 0..24 { + decode_positions.extend((p0 as i32).to_le_bytes()); + } + let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; + let full = self.handle(4, self.sizes[4])?; + let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; + h.validate_projection_extent(24 * 4, 4)?; + if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { + return Err(Error::OutputAliasesInput); + } + Some(h) + } else { + None + }; + let k_h = out[0]; + let pooled_h = self.handle(0, self.sizes[0])?; + let tail_h = self.handle(1, self.sizes[1])?; + let dead_h = self.handle(2, self.sizes[2])?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(2), + vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(2), + vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 2), + vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 2), + vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)], + )?; + push(Launch::Split((n * 6144) as u32), vec![A::Address(qfull_h), A::Address(out[2]), A::I64(t as i64)])?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(24), + vec![ + A::Address(out[2]), + A::Address(out[2]), + A::I32(24), + A::I32(256), + A::F32(theta), + A::Address(positions), + ], + )?; + } else { + push( + Launch::Rms(t * 24), + vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 24), + vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 6144) as u32), + vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)], + )?; + if let Some(positions) = positions { + push( + Launch::DecodeRms(4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)], + )?; + push( + Launch::DecodeRope(4), + vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)], + )?; + } else { + push( + Launch::Rms(t * 4), + vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)], + )?; + push( + Launch::Rope(t * 4), + vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)], + )?; + } + push( + Launch::Scan((n * 512) as u32), + vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)], + )?; + if decode { + push( + Launch::DecodeAppend, + vec![ + A::Address(raw_h), + A::Address(out[4]), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I32(crate::serving_context::geometry().cells() as i32), + A::F32(theta), + ], + )?; + } else { + if p == 0 { + push( + Launch::First, + vec![ + A::Address(raw_h), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(dead_h), + A::Address(pooled_h), + A::F32(theta), + ], + )?; + } + let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; + let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; + if let Some(hi) = hi.filter(|hi| *hi >= first) { + push( + Launch::Blocks((hi - first + 1) as u32), + vec![ + A::Address(raw_h), + A::I64(t as i64), + A::I64(p0 as i64), + A::I32(0), + A::Address(gamma[3]), + A::F32(1e-6), + A::Address(tail_h), + A::Address(dead_h), + A::Address(pooled_h), + A::Address(self.handle(3, 4)?), + A::I64(first as i64), + A::I64(hi as i64), + A::F32(theta), + ], + )?; + } + push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?; + } + for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] { + push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?; + } + // Original prompt selection reuses one 256-row score tile. Every + // offset is checked against the actual whole producer allocation. + let tile_rows = if decode { 1 } else { n.min(256) }; + let scores = self.handle(9, tile_rows * max_blocks() * 4)?; + for first_row in (0..n).step_by(256) { + let count = (n - first_row).min(256); + let ct = count as u32; + let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?; + let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?; + let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?; + let tile_reach = (p + first_row + count) / 4 + 1; + if decode { + push( + Launch::DecodeScores, + vec![ + A::Address(pooled_h), + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I32(1), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; + } else { + push( + Launch::Tc { t: ct, reach: tile_reach as u32 }, + vec![ + A::Address(pooled_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(count as i64), + A::I64(max_blocks() as i64), + A::I64(tile_reach as i64), + A::Address(scores), + ], + )?; + push( + Launch::ScoreTail(ct), + vec![ + A::Address(dead_h), + A::Address(iq_tile), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::Address(scores), + ], + )?; + } + if fast_select && !decode { + // qsa_late.cu: the same flag over the blocks the tile can hold, and the same ids from coalesced reads + late.push(( + pushed.get(), + (count * tile_reach).div_ceil(256) as u32, + crate::qsa_late::SCORE_SCAN_FAST, + 256, + crate::ple_batch_ffi::KernelArguments::new(vec![ + crate::ple_batch_ffi::BatchArg::Address(scores), + crate::ple_batch_ffi::BatchArg::Address(steps_tile), + crate::ple_batch_ffi::BatchArg::I32(count as i32), + crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64), + crate::ple_batch_ffi::BatchArg::I64(tile_reach as i64), + crate::ple_batch_ffi::BatchArg::Address(status), + crate::ple_batch_ffi::BatchArg::U32(4), + ]), + )); + let (topk_entry, topk_block) = crate::qsa_late::topk_entry(tile_reach); + late.push(( + pushed.get(), + ct, + topk_entry, + topk_block, + crate::ple_batch_ffi::KernelArguments::new(vec![ + crate::ple_batch_ffi::BatchArg::Address(scores), + crate::ple_batch_ffi::BatchArg::Address(steps_tile), + crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64), + crate::ple_batch_ffi::BatchArg::I64(CAP as i64), + crate::ple_batch_ffi::BatchArg::Address(ids_tile), + ]), + )); + } else { + push( + Launch::ScoreScan((count * max_blocks()) as u32), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I32(count as i32), + A::I64(max_blocks() as i64), + A::Address(status), + A::U32(4), + ], + )?; + push( + Launch::Topk(ct), + vec![ + A::Address(scores), + A::Address(steps_tile), + A::I64(max_blocks() as i64), + A::I64(CAP as i64), + A::Address(ids_tile), + ], + )?; + } + } + push( + Launch::Scan((n * 128) as u32), + vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)], + )?; + let context = self.context; + let guard = match context.enter() { + Ok(guard) => guard, + Err(error) => { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + return Err(error); + } + }; + let blas = ws.blas()?; + let operation = (|| { + context.driver.api.copy_from(status, &zero)?; + context.driver.api.copy_from(out[4], &steps)?; + if let Some(positions) = positions { + context.driver.api.copy_from(positions, &decode_positions)?; + } + // Pageable uploads/status have a real dependency before the nonblocking shared stream. + context.driver.api.synchronize()?; + // LELEKA_PREFILL_PROFILE_SYNC: every launch drained on its own and charged to its kind (qsa-index#kind) + let timed = crate::command_profile::enabled(); + if !late.is_empty() && self.late.is_none() { + self.late = + Some(crate::ple_batch_ffi::KernelModule::load(crate::qsa_late::PTX, crate::qsa_late::ENTRIES)?); + } + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + let mut next = 0usize; + let mut run_late = |upto: usize, + late: &mut Vec<(usize, u32, usize, u32, crate::ple_batch_ffi::KernelArguments)>, + next: &mut usize| + -> Result<()> { + while *next < late.len() && late[*next].0 <= upto { + let started = std::time::Instant::now(); + let (_, grid, entry, block, args) = &mut late[*next]; + self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch( + *entry, + *grid, + *block, + blas.stream(), + args, + )?; + if timed { + blas.synchronize()?; + let topk = *entry != crate::qsa_late::SCORE_SCAN_FAST; + crate::command_profile::add( + "qsa-index", + if topk { 22 } else { 21 }, + if *entry == crate::qsa_late::TOPK_WIDE { + "topk (wide)" + } else if topk { + "topk (fast)" + } else { + "score scan (fast)" + }, + started.elapsed(), + ); + } + *next += 1; + } + Ok(()) + }; + for (i, (shape, args)) in commands.iter_mut().enumerate() { + run_late(i, &mut late, &mut next)?; + let started = std::time::Instant::now(); + module.launch(*shape, blas.stream(), args)?; + if timed { + blas.synchronize()?; + let (i, l) = launch_label(shape); + crate::command_profile::add("qsa-index", i, l, started.elapsed()); + } + } + run_late(usize::MAX, &mut late, &mut next)?; + Ok(()) + })(); + let sync = blas.synchronize(); + let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let pop = guard.finish(); + if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { + self.failed = true; + ws.mark_failed(); + context.poison(); + context.retain_driver(); + std::mem::forget((commands, steps, zero, flags, decode_positions)); + return combine(combine(combine(operation, sync), read), pop); + } + combine(combine(combine(operation, sync), read), pop)?; + for flag in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*flag) > 1 { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA finite status")); + } + } + if flags[24..].iter().any(|x| *x != 0) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..24].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs new file mode 100644 index 00000000..86d05dc4 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs @@ -0,0 +1,140 @@ +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace, fn launch_label. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + pub(in super::super) fn replay_resident_prefix( + &mut self, + p0: usize, + t: usize, + raw: ffi::BufferHandle, + gamma: ffi::BufferHandle, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + if !(1..=8192).contains(&t) || p0.checked_add(t).is_none_or(|x| x > crate::serving_context::geometry().cells()) + { + return Err(Error::InvalidQwenShape); + } + ws.validate_context(self.context)?; + raw.validate_projection_extent(t * 512, 4)?; + gamma.validate_projection_extent(512, 4)?; + let status = self.handle(10, 64)?; + let pooled = self.handle(0, self.sizes[0])?; + let tail = self.handle(1, 1536)?; + let dead = self.handle(2, 512)?; + let bp = self.handle(3, 4)?; + let mut steps = Vec::new(); + steps.try_reserve_exact(t * 16).map_err(|_| Error::HostAllocation)?; + for row in 0..t { + let p = p0 + row; + for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] { + steps.extend((x as i32).to_le_bytes()); + } + } + let mut step = self.context.allocate(t * 16)?; + step.copy_from(&steps)?; + let sh = step.handle.ok_or(Error::ContextPoisoned)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(t * 4).map_err(|_| Error::HostAllocation)?; + let theta = crate::qsa_index_ffi::theta(); + if !theta.is_finite() || theta <= 0.0 { + return Err(Error::InvalidDriverValue("QSA theta")); + } + for row in 0..t { + let p = p0 + row; + let key = raw.checked_subspan(t * 512, row * 512, 512)?; + let pos = sh.checked_subspan(t * 16, row * 16, 4)?; + commands.push(( + Launch::DecodeAppend, + Arguments::for_launch( + Launch::DecodeAppend, + vec![ + A::Address(key), + A::Address(pos), + A::I32(0), + A::Address(gamma), + A::F32(1e-6), + A::Address(tail), + A::Address(dead), + A::Address(pooled), + A::Address(bp), + A::I32(crate::serving_context::geometry().cells() as i32), + A::F32(theta), + ], + )?, + )); + for (h, n) in [(pooled, ((p + 1) / 4 + 1) * 128), (tail, 384), (dead, 128)] { + commands.push(( + Launch::Scan(n as u32), + Arguments::new(vec![A::Address(h), A::I64(n as i64), A::Address(status), A::U32(0)])?, + )); + } + } + let c = self.context; + let g = c.enter().map_err(|e| { + self.failed = true; + ws.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let blas = ws.blas()?; + let zero = [0u8; 64]; + let mut flags = [0u8; 64]; + let op = (|| -> Result<()> { + c.driver.api.copy_from(status, &zero)?; + c.driver.api.synchronize()?; + for (shape, args) in &mut commands { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(*shape, blas.stream(), args)?; + } + Ok(()) + })(); + let sync = blas.synchronize(); + let read = if sync.is_ok() { c.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let pop = g.finish(); + if op.is_err() || sync.is_err() || read.is_err() || pop.is_err() { + self.failed = true; + ws.mark_failed(); + c.poison(); + c.retain_driver(); + if sync.is_err() || pop.is_err() { + std::mem::forget((commands, step)); + } + return combine(combine(combine(op, sync), read), pop); + } + if flags[4..].iter().any(|x| *x != 0) + || u32::from_le_bytes(flags[..4].try_into().map_err(|_| Error::InvalidSize)?) > 1 + { + self.failed = true; + c.poison(); + c.retain_driver(); + return Err(Error::InvalidDriverValue("QSA replay finite flags")); + } + if flags[0] != 0 { + return Err(Error::NonFiniteMmqOutput("QSA accepted index replay")); + } + Ok(()) + } +} + +pub(super) fn launch_label(launch: &Launch) -> (usize, &'static str) { + match launch { + Launch::First => (1, "first"), + Launch::Blocks(_) => (2, "blocks (pool)"), + Launch::Tail => (3, "tail"), + Launch::Rms(_) => (4, "rms"), + Launch::Rope(_) => (5, "rope"), + Launch::Split(_) => (6, "split"), + Launch::Scan(_) => (7, "finite scan"), + Launch::ScoreScan(_) => (8, "score scan"), + Launch::Round(_) => (9, "round"), + Launch::Tc { .. } => (10, "tc scores"), + Launch::ScoreTail(_) => (11, "score tail"), + Launch::Topk(_) => (12, "topk"), + Launch::DecodeAppend => (13, "decode append"), + Launch::DecodeScores => (14, "decode scores"), + Launch::DecodeRms(_) => (15, "decode rms"), + Launch::DecodeRope(_) => (16, "decode rope"), + } +} diff --git a/crates/cuda-driver/src/qsa_resident_scalar_index.rs b/crates/cuda-driver/src/qsa_resident_scalar_index.rs index be2a7071..16003a67 100644 --- a/crates/cuda-driver/src/qsa_resident_scalar_index.rs +++ b/crates/cuda-driver/src/qsa_resident_scalar_index.rs @@ -5,16 +5,11 @@ pub struct OriginalQsaResidentScalarIndex<'ctx> { workspace: QsaPromptIndexWorkspace<'ctx>, } impl<'ctx> Context<'ctx> { - pub fn original_qsa_resident_scalar_index( - &'ctx self, - ) -> Result> { + pub fn original_qsa_resident_scalar_index(&'ctx self) -> Result> { if self.is_poisoned() { return Err(Error::ContextPoisoned); } - if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS] - .iter() - .any(|x| x.starts_with(b"// UNSEALED")) - { + if [INDEX, SELECT, POSTOPS, DECODE_POSTOPS].iter().any(|x| x.starts_with(b"// UNSEALED")) { return Err(Error::UnsupportedQwenOperation); } let mut sizes = sizes(); @@ -25,14 +20,9 @@ impl<'ctx> Context<'ctx> { sizes[7] = 49152; sizes[8] = 2048; sizes[9] = max_blocks() * 4; - let bytes = sizes.iter().try_fold(0usize, |sum, n| { - sum.checked_add(*n).ok_or(Error::BudgetExceeded) - })?; + let bytes = sizes.iter().try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))?; let peak = bytes.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if self - .allocated_bytes() - .checked_add(peak) - .is_none_or(|n| n > self.budget_bytes()) + if self.allocated_bytes().checked_add(peak).is_none_or(|n| n > self.budget_bytes()) || self.memory_info()?.0 < peak { return Err(Error::BudgetExceeded); @@ -110,25 +100,14 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { { return Err(Error::InvalidQwenShape); } - if raw.len() != 128 - || k.len() != 512 - || v.len() != 512 - || qfull.len() != 12288 - || index_q.len() != 512 - { + if raw.len() != 128 || k.len() != 512 || v.len() != 512 || qfull.len() != 12288 || index_q.len() != 512 { return Err(Error::InvalidQwenShape); } - if [raw, k, v, qfull, index_q] - .iter() - .any(|x| x.iter().any(|v| !v.is_finite())) - { + if [raw, k, v, qfull, index_q].iter().any(|x| x.iter().any(|v| !v.is_finite())) { return Err(Error::NonFiniteMmqOutput("QSA native scalar input")); } let peak = 2564 + 512 + (512 * 2 + 6144 + CAP + 4) * 4 + RESERVE; - if context - .allocated_bytes() - .checked_add(peak) - .is_none_or(|n| n > context.budget_bytes()) + if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) || context.memory_info()?.0 < peak { return Err(Error::BudgetExceeded); @@ -143,10 +122,7 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { outputs[i] = Some(context.allocate(n)?) } for (i, values) in [(0, k), (1, v)] { - outputs[i] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .copy_from(&encode(values)?)?; + outputs[i].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&encode(values)?)?; } self.workspace.upload(4, raw)?; self.workspace.upload(7, qfull)?; @@ -159,12 +135,8 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { } return Err(primary); } - let handles = std::array::from_fn(|i| { - outputs[i] - .as_ref() - .and_then(|b| b.handle) - .expect("allocated actual owner") - }); + let handles = + std::array::from_fn(|i| outputs[i].as_ref().and_then(|b| b.handle).expect("allocated actual owner")); resident.in_flight = true; resident.unpublished = true; let operation = resident.placed(&mut self.workspace, |workspace| { @@ -230,18 +202,8 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { return combine(Err(primary), cleanup); } resident.provisional_end(p + 1); - let batch = OriginalQsaIndexBatch { - owner: resident, - start, - raw: Some(raw_rows), - gamma: weights[3], - rows: 1, - }; - Ok(OriginalQsaResidentScalarSelection { - workspace: &mut self.workspace, - outputs, - batch: Some(batch), - }) + let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma: weights[3], rows: 1 }; + Ok(OriginalQsaResidentScalarSelection { workspace: &mut self.workspace, outputs, batch: Some(batch) }) } pub fn commit_prefix( &mut self, @@ -255,13 +217,9 @@ impl<'ctx> OriginalQsaResidentScalarIndex<'ctx> { self.workspace.close() } } -impl<'lease, 'index, 'weights, 'ctx> - OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx> -{ +impl<'lease, 'index, 'weights, 'ctx> OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx> { pub fn first_position(&self) -> usize { - self.batch - .as_ref() - .map_or(0, OriginalQsaIndexBatch::first_position) + self.batch.as_ref().map_or(0, OriginalQsaIndexBatch::first_position) } pub fn with_completed_buffers( &self, @@ -293,11 +251,7 @@ impl<'lease, 'index, 'weights, 'ctx> ws: &mut NativeBatchWorkspace<'ctx>, accepted: usize, ) -> Result> { - let result = self - .batch - .as_mut() - .ok_or(Error::ContextPoisoned)? - .commit_prefix(ws, self.workspace, accepted); + let result = self.batch.as_mut().ok_or(Error::ContextPoisoned)?.commit_prefix(ws, self.workspace, accepted); let cleanup = self.close_outputs(); combine(result, cleanup) } diff --git a/crates/cuda-driver/src/qsa_resident_transfer.rs b/crates/cuda-driver/src/qsa_resident_transfer.rs index 29e158fe..c14c483f 100644 --- a/crates/cuda-driver/src/qsa_resident_transfer.rs +++ b/crates/cuda-driver/src/qsa_resident_transfer.rs @@ -1,128 +1,61 @@ //! Closed unified CUDA copy ABI for actual private resident checkpoint/stage owners. //! No public address/range API. All source owners remain borrowed until drain. -use crate::{Context,Error,NativeBatchWorkspace,Result,combine}; -#[cfg(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64"))] +use crate::{Context, Error, NativeBatchWorkspace, Result, combine}; +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[path = "qsa_resident_transfer/enabled.rs"] +mod enabled; +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] mod enabled { - use super::*; use std::ffi::c_void; - type Copy=unsafe extern "C" fn(u64,u64,usize,*mut c_void)->i32; - type StreamCreate=unsafe extern "C" fn(*mut *mut c_void,u32)->i32; - type EventCreate=unsafe extern "C" fn(*mut *mut c_void,u32)->i32; - type EventRecord=unsafe extern "C" fn(*mut c_void,*mut c_void)->i32; - type StreamWait=unsafe extern "C" fn(*mut c_void,*mut c_void,u32)->i32; - type StreamSync=unsafe extern "C" fn(*mut c_void)->i32; - type Destroy=unsafe extern "C" fn(*mut c_void)->i32; - /// The symbols of the side-stream prefix copy (`begin` / `wait_pending` / `cancel`), absent on a driver without them. - struct Side{stream_create:StreamCreate,event_create:EventCreate,event_record:EventRecord,stream_wait:StreamWait,stream_sync:StreamSync,stream_destroy:Destroy,event_destroy:Destroy} - pub(crate) struct Transfer{library:*mut c_void,copy:Copy,side:Option,handles:std::cell::Cell>,pending:std::cell::Cell} - impl Transfer{ - pub(crate) fn new()->Result{ - // SAFETY: fixed libcuda ABI; no caller resolver or host pointer conversion. The handle is owned by `Transfer` - // (closed in Drop, or on the missing-symbol path below). - let library=unsafe{libc::dlopen(c"libcuda.so.1".as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)}; - if library.is_null(){return Err(Error::LibraryUnavailable)} - // SAFETY: cuMemcpyAsync unified-address Linux64 signature. - let p=unsafe{libc::dlsym(library,c"cuMemcpyAsync".as_ptr())}; - // SAFETY: `library` is the handle just opened and not yet shared; closed once on this error path. - if p.is_null(){unsafe{libc::dlclose(library)};return Err(Error::MissingSymbol("cuMemcpyAsync"))} - // SAFETY: `Copy` is the exact cuMemcpyAsync(dst, src, bytes, stream) signature. - let copy=unsafe{std::mem::transmute::<*mut c_void,Copy>(p)}; - let sym=|n:&std::ffi::CStr|->*mut c_void{unsafe{libc::dlsym(library,n.as_ptr())}}; - let (a,b,c,d,e,f,g)=(sym(c"cuStreamCreate"),sym(c"cuEventCreate"),sym(c"cuEventRecord"),sym(c"cuStreamWaitEvent"),sym(c"cuStreamSynchronize"),sym(c"cuStreamDestroy_v2"),sym(c"cuEventDestroy_v2")); - // SAFETY: the exact libcuda signatures of the seven calls; used only when all of them resolved. - let side=if [a,b,c,d,e,f,g].iter().any(|p|p.is_null()){None}else{unsafe{Some(Side{stream_create:std::mem::transmute::<*mut c_void,StreamCreate>(a),event_create:std::mem::transmute::<*mut c_void,EventCreate>(b), - event_record:std::mem::transmute::<*mut c_void,EventRecord>(c),stream_wait:std::mem::transmute::<*mut c_void,StreamWait>(d),stream_sync:std::mem::transmute::<*mut c_void,StreamSync>(e), - stream_destroy:std::mem::transmute::<*mut c_void,Destroy>(f),event_destroy:std::mem::transmute::<*mut c_void,Destroy>(g)})}}; - Ok(Self{library,copy,side,handles:std::cell::Cell::new(None),pending:std::cell::Cell::new(false)}) - } - /// Whether `begin` can run (the driver exports the stream / event calls). - pub(crate) fn can_overlap(&self)->bool{self.side.is_some()} - pub(crate) fn is_pending(&self)->bool{self.pending.get()} - /// Start `ranges` on a side stream that first waits for everything queued on the compute stream so far, without a host wait: the - /// copy then runs under the compute stream's next kernels. `wait_pending` makes the compute stream wait for its end. Row "256k prefill - /// gap" (docs/upstream-port-plan.md): the QSA layer's prior-KV prefix copy overlapped with the layer's own projections and indexer. - pub(crate) fn begin<'ctx>(&self,c:&'ctx Context<'ctx>,w:&mut NativeBatchWorkspace<'ctx>,ranges:&[(u64,u64,usize)])->Result<()>{ - let side=self.side.as_ref().ok_or(Error::MissingSymbol("cuStreamCreate"))?; - w.validate_context(c)?;if c.is_poisoned(){return Err(Error::ContextPoisoned)} - if self.pending.get(){self.cancel(c)?;} - for(src,dst,n)in ranges{if *n==0||*src==0||*dst==0{return Err(Error::InvalidSize)}let se=src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;let de=dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;if *srcResult<()>{ - let (stream,e1,e2)=match self.handles.get(){Some(h)=>h,None=>{ - let (mut s,mut x,mut y)=(std::ptr::null_mut(),std::ptr::null_mut(),std::ptr::null_mut()); - // SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by this Transfer and destroyed in Drop. - let code=unsafe{(side.stream_create)(&mut s,1)};if code!=0{return Err(Error::Driver{operation:"cuStreamCreate",code})} - let code=unsafe{(side.event_create)(&mut x,2)};if code!=0{return Err(Error::Driver{operation:"cuEventCreate",code})} - let code=unsafe{(side.event_create)(&mut y,2)};if code!=0{return Err(Error::Driver{operation:"cuEventCreate",code})} - let h=(s as usize,x as usize,y as usize);self.handles.set(Some(h));h}}; - // SAFETY: live handles of this context; the compute stream is the workspace's retained stream. - let code=unsafe{(side.event_record)(e1 as *mut c_void,b.stream() as *mut c_void)};if code!=0{return Err(Error::Driver{operation:"cuEventRecord",code})} - let code=unsafe{(side.stream_wait)(stream as *mut c_void,e1 as *mut c_void,0)};if code!=0{return Err(Error::Driver{operation:"cuStreamWaitEvent",code})} - for(src,dst,n)in ranges{ - // SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / the chunk's final drain. - let code=unsafe{(self.copy)(*dst,*src,*n,stream as *mut c_void)};if code!=0{return Err(Error::Driver{operation:"cuMemcpyAsync",code})} + use super::*; + pub(crate) struct Transfer; + impl Transfer { + pub(crate) fn new() -> Result { + Err(Error::LibraryUnavailable) + } + pub(crate) fn copy<'ctx>( + &self, + _: &'ctx Context<'ctx>, + _: &mut NativeBatchWorkspace<'ctx>, + _: &[(u64, u64, usize)], + ) -> Result<()> { + Err(Error::LibraryUnavailable) + } + pub(crate) fn copy_fenced<'ctx>( + &self, + _: &'ctx Context<'ctx>, + _: &mut NativeBatchWorkspace<'ctx>, + _: &[(u64, u64, usize)], + ) -> Result<()> { + Err(Error::LibraryUnavailable) + } + pub(crate) fn can_overlap(&self) -> bool { + false + } + pub(crate) fn is_pending(&self) -> bool { + false + } + pub(crate) fn begin<'ctx>( + &self, + _: &'ctx Context<'ctx>, + _: &mut NativeBatchWorkspace<'ctx>, + _: &[(u64, u64, usize)], + ) -> Result<()> { + Err(Error::LibraryUnavailable) + } + pub(crate) fn wait_pending<'ctx>( + &self, + _: &'ctx Context<'ctx>, + _: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + Ok(()) + } + pub(crate) fn cancel<'ctx>(&self, _: &'ctx Context<'ctx>) -> Result<()> { + Ok(()) + } } - let code=unsafe{(side.event_record)(e2 as *mut c_void,stream as *mut c_void)};if code!=0{return Err(Error::Driver{operation:"cuEventRecord",code})} - self.pending.set(true);Ok(())})(); - let pop=g.finish(); - if op.is_err()||pop.is_err(){w.mark_failed();c.poison();c.retain_driver()} - combine(op,pop) - } - /// Order the compute stream after the side copy (no host wait). A no-op when nothing is pending. - pub(crate) fn wait_pending<'ctx>(&self,c:&'ctx Context<'ctx>,w:&mut NativeBatchWorkspace<'ctx>)->Result<()>{ - if !self.pending.get(){return Ok(())} - let side=self.side.as_ref().ok_or(Error::ContextPoisoned)?;let (_,_,e2)=self.handles.get().ok_or(Error::ContextPoisoned)?; - w.validate_context(c)?;let g=c.enter().map_err(|e|{w.mark_failed();c.poison();c.retain_driver();e})?;let b=w.blas()?; - // SAFETY: live event and the workspace's retained compute stream. - let code=unsafe{(side.stream_wait)(b.stream() as *mut c_void,e2 as *mut c_void,0)}; - let pop=g.finish();self.pending.set(false); - if code!=0||pop.is_err(){w.mark_failed();c.poison();c.retain_driver()} - if code!=0{return Err(Error::Driver{operation:"cuStreamWaitEvent",code})}pop - } - /// Host wait for a pending side copy (an abandoned prefetch: the destination must not be reused or freed under it). - pub(crate) fn cancel<'ctx>(&self,c:&'ctx Context<'ctx>)->Result<()>{ - if !self.pending.get(){return Ok(())} - let side=self.side.as_ref().ok_or(Error::ContextPoisoned)?;let (stream,_,_)=self.handles.get().ok_or(Error::ContextPoisoned)?; - let g=c.enter().map_err(|e|{c.poison();c.retain_driver();e})?; - // SAFETY: live side stream. - let code=unsafe{(side.stream_sync)(stream as *mut c_void)};let pop=g.finish();self.pending.set(false); - if code!=0||pop.is_err(){c.poison();c.retain_driver()} - if code!=0{return Err(Error::Driver{operation:"cuStreamSynchronize",code})}pop - } - pub(crate) fn copy<'ctx>(&self,c:&'ctx Context<'ctx>,w:&mut NativeBatchWorkspace<'ctx>,ranges:&[(u64,u64,usize)])->Result<()>{ - w.validate_context(c)?;if c.is_poisoned(){return Err(Error::ContextPoisoned)} - // Private callers derive each address and checked byte extent from actual - // initialized mapped/device owners; reject overflow and overlap prewrite. - for(src,dst,n)in ranges{if *n==0||*src==0||*dst==0{return Err(Error::InvalidSize)}let se=src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;let de=dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;if *srcResult<()>{c.driver.api.synchronize()?;for(src,dst,n)in ranges{ - // SAFETY: actual checked owner extents, real Context and retained stream; - // source/destination leases live through the final synchronize below. - let code=unsafe{(self.copy)(*dst,*src,*n,b.stream() as *mut c_void)};if code!=0{return Err(Error::Driver{operation:"cuMemcpyAsync",code})} - }Ok(())})();let sync=b.synchronize();let pop=g.finish(); - if op.is_err()||sync.is_err()||pop.is_err(){w.mark_failed();c.poison();c.retain_driver()} - combine(combine(op,sync),pop) - } - /// `copy` for a caller that has already fenced every writer of the sources (a completed verifier commit event): - /// the same stream-ordered copies and drain, without the context-wide synchronize first. - pub(crate) fn copy_fenced<'ctx>(&self,c:&'ctx Context<'ctx>,w:&mut NativeBatchWorkspace<'ctx>,ranges:&[(u64,u64,usize)])->Result<()>{ - w.validate_context(c)?;if c.is_poisoned(){return Err(Error::ContextPoisoned)} - for(src,dst,n)in ranges{if *n==0||*src==0||*dst==0{return Err(Error::InvalidSize)}let se=src.checked_add(*n as u64).ok_or(Error::InvalidSize)?;let de=dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?;if *srcResult<()>{for(src,dst,n)in ranges{ - // SAFETY: as `copy`; the caller's fence replaces the context synchronize. - let code=unsafe{(self.copy)(*dst,*src,*n,b.stream() as *mut c_void)};if code!=0{return Err(Error::Driver{operation:"cuMemcpyAsync",code})} - }Ok(())})();let sync=b.synchronize();let pop=g.finish(); - if op.is_err()||sync.is_err()||pop.is_err(){w.mark_failed();c.poison();c.retain_driver()} - combine(combine(op,sync),pop) - } - } - // SAFETY (Drop): `copy` is never called after drop; libcuda itself stays loaded (the driver holds its own reference), and -// every `Transfer::copy*` drains its stream before returning, so no enqueued copy outlives the dlclose. -impl Drop for Transfer{fn drop(&mut self){ - // the side copy is waited for by `cancel` before a context goes away; here only the handles are released (errors ignored) - if let (Some(side),Some((s,x,y)))=(self.side.as_ref(),self.handles.get()){unsafe{(side.stream_sync)(s as *mut c_void);(side.event_destroy)(x as *mut c_void);(side.event_destroy)(y as *mut c_void);(side.stream_destroy)(s as *mut c_void);}} - if !self.library.is_null(){unsafe{libc::dlclose(self.library)};self.library=std::ptr::null_mut();}}} } -#[cfg(not(all(feature="cuda-driver",any(target_os = "linux", target_os = "windows"),target_pointer_width="64")))] -mod enabled{use super::*;pub(crate) struct Transfer;impl Transfer{pub(crate) fn new()->Result{Err(Error::LibraryUnavailable)}pub(crate) fn copy<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>,_:&[(u64,u64,usize)])->Result<()>{Err(Error::LibraryUnavailable)}pub(crate) fn copy_fenced<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>,_:&[(u64,u64,usize)])->Result<()>{Err(Error::LibraryUnavailable)}pub(crate) fn can_overlap(&self)->bool{false}pub(crate) fn is_pending(&self)->bool{false}pub(crate) fn begin<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>,_:&[(u64,u64,usize)])->Result<()>{Err(Error::LibraryUnavailable)}pub(crate) fn wait_pending<'ctx>(&self,_:&'ctx Context<'ctx>,_:&mut NativeBatchWorkspace<'ctx>)->Result<()>{Ok(())}pub(crate) fn cancel<'ctx>(&self,_:&'ctx Context<'ctx>)->Result<()>{Ok(())}}} pub(crate) use enabled::Transfer; diff --git a/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs new file mode 100644 index 00000000..f99056c9 --- /dev/null +++ b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs @@ -0,0 +1,340 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use std::ffi::c_void; +type Copy = unsafe extern "C" fn(u64, u64, usize, *mut c_void) -> i32; +type StreamCreate = unsafe extern "C" fn(*mut *mut c_void, u32) -> i32; +type EventCreate = unsafe extern "C" fn(*mut *mut c_void, u32) -> i32; +type EventRecord = unsafe extern "C" fn(*mut c_void, *mut c_void) -> i32; +type StreamWait = unsafe extern "C" fn(*mut c_void, *mut c_void, u32) -> i32; +type StreamSync = unsafe extern "C" fn(*mut c_void) -> i32; +type Destroy = unsafe extern "C" fn(*mut c_void) -> i32; +/// The symbols of the side-stream prefix copy (`begin` / `wait_pending` / `cancel`), absent on a driver without them. +struct Side { + stream_create: StreamCreate, + event_create: EventCreate, + event_record: EventRecord, + stream_wait: StreamWait, + stream_sync: StreamSync, + stream_destroy: Destroy, + event_destroy: Destroy, +} +pub(crate) struct Transfer { + library: *mut c_void, + copy: Copy, + side: Option, + handles: std::cell::Cell>, + pending: std::cell::Cell, +} +impl Transfer { + pub(crate) fn new() -> Result { + // SAFETY: fixed libcuda ABI; no caller resolver or host pointer conversion. The handle is owned by `Transfer` + // (closed in Drop, or on the missing-symbol path below). + let library = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if library.is_null() { + return Err(Error::LibraryUnavailable); + } + // SAFETY: cuMemcpyAsync unified-address Linux64 signature. + let p = unsafe { libc::dlsym(library, c"cuMemcpyAsync".as_ptr()) }; + // SAFETY: `library` is the handle just opened and not yet shared; closed once on this error path. + if p.is_null() { + unsafe { libc::dlclose(library) }; + return Err(Error::MissingSymbol("cuMemcpyAsync")); + } + // SAFETY: `Copy` is the exact cuMemcpyAsync(dst, src, bytes, stream) signature. + let copy = unsafe { std::mem::transmute::<*mut c_void, Copy>(p) }; + let sym = |n: &std::ffi::CStr| -> *mut c_void { unsafe { libc::dlsym(library, n.as_ptr()) } }; + let (a, b, c, d, e, f, g) = ( + sym(c"cuStreamCreate"), + sym(c"cuEventCreate"), + sym(c"cuEventRecord"), + sym(c"cuStreamWaitEvent"), + sym(c"cuStreamSynchronize"), + sym(c"cuStreamDestroy_v2"), + sym(c"cuEventDestroy_v2"), + ); + // SAFETY: the exact libcuda signatures of the seven calls; used only when all of them resolved. + let side = if [a, b, c, d, e, f, g].iter().any(|p| p.is_null()) { + None + } else { + unsafe { + Some(Side { + stream_create: std::mem::transmute::<*mut c_void, StreamCreate>(a), + event_create: std::mem::transmute::<*mut c_void, EventCreate>(b), + event_record: std::mem::transmute::<*mut c_void, EventRecord>(c), + stream_wait: std::mem::transmute::<*mut c_void, StreamWait>(d), + stream_sync: std::mem::transmute::<*mut c_void, StreamSync>(e), + stream_destroy: std::mem::transmute::<*mut c_void, Destroy>(f), + event_destroy: std::mem::transmute::<*mut c_void, Destroy>(g), + }) + } + }; + Ok(Self { library, copy, side, handles: std::cell::Cell::new(None), pending: std::cell::Cell::new(false) }) + } + /// Whether `begin` can run (the driver exports the stream / event calls). + pub(crate) fn can_overlap(&self) -> bool { + self.side.is_some() + } + pub(crate) fn is_pending(&self) -> bool { + self.pending.get() + } + /// Start `ranges` on a side stream that first waits for everything queued on the compute stream so far, without a host wait: the + /// copy then runs under the compute stream's next kernels. `wait_pending` makes the compute stream wait for its end. Row "256k prefill + /// gap" (docs/upstream-port-plan.md): the QSA layer's prior-KV prefix copy overlapped with the layer's own projections and indexer. + pub(crate) fn begin<'ctx>( + &self, + c: &'ctx Context<'ctx>, + w: &mut NativeBatchWorkspace<'ctx>, + ranges: &[(u64, u64, usize)], + ) -> Result<()> { + let side = self.side.as_ref().ok_or(Error::MissingSymbol("cuStreamCreate"))?; + w.validate_context(c)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if self.pending.get() { + self.cancel(c)?; + } + for (src, dst, n) in ranges { + if *n == 0 || *src == 0 || *dst == 0 { + return Err(Error::InvalidSize); + } + let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + if *src < de && *dst < se { + return Err(Error::OutputAliasesInput); + } + } + let g = c.enter().map_err(|e| { + w.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let b = w.blas()?; + let op = (|| -> Result<()> { + let (stream, e1, e2) = match self.handles.get() { + Some(h) => h, + None => { + let (mut s, mut x, mut y) = (std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); + // SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by this Transfer and destroyed in Drop. + let code = unsafe { (side.stream_create)(&mut s, 1) }; + if code != 0 { + return Err(Error::Driver { operation: "cuStreamCreate", code }); + } + let code = unsafe { (side.event_create)(&mut x, 2) }; + if code != 0 { + return Err(Error::Driver { operation: "cuEventCreate", code }); + } + let code = unsafe { (side.event_create)(&mut y, 2) }; + if code != 0 { + return Err(Error::Driver { operation: "cuEventCreate", code }); + } + let h = (s as usize, x as usize, y as usize); + self.handles.set(Some(h)); + h + } + }; + // SAFETY: live handles of this context; the compute stream is the workspace's retained stream. + let code = unsafe { (side.event_record)(e1 as *mut c_void, b.stream() as *mut c_void) }; + if code != 0 { + return Err(Error::Driver { operation: "cuEventRecord", code }); + } + let code = unsafe { (side.stream_wait)(stream as *mut c_void, e1 as *mut c_void, 0) }; + if code != 0 { + return Err(Error::Driver { operation: "cuStreamWaitEvent", code }); + } + for (src, dst, n) in ranges { + // SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / the chunk's final drain. + let code = unsafe { (self.copy)(*dst, *src, *n, stream as *mut c_void) }; + if code != 0 { + return Err(Error::Driver { operation: "cuMemcpyAsync", code }); + } + } + let code = unsafe { (side.event_record)(e2 as *mut c_void, stream as *mut c_void) }; + if code != 0 { + return Err(Error::Driver { operation: "cuEventRecord", code }); + } + self.pending.set(true); + Ok(()) + })(); + let pop = g.finish(); + if op.is_err() || pop.is_err() { + w.mark_failed(); + c.poison(); + c.retain_driver() + } + combine(op, pop) + } + /// Order the compute stream after the side copy (no host wait). A no-op when nothing is pending. + pub(crate) fn wait_pending<'ctx>(&self, c: &'ctx Context<'ctx>, w: &mut NativeBatchWorkspace<'ctx>) -> Result<()> { + if !self.pending.get() { + return Ok(()); + } + let side = self.side.as_ref().ok_or(Error::ContextPoisoned)?; + let (_, _, e2) = self.handles.get().ok_or(Error::ContextPoisoned)?; + w.validate_context(c)?; + let g = c.enter().map_err(|e| { + w.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let b = w.blas()?; + // SAFETY: live event and the workspace's retained compute stream. + let code = unsafe { (side.stream_wait)(b.stream() as *mut c_void, e2 as *mut c_void, 0) }; + let pop = g.finish(); + self.pending.set(false); + if code != 0 || pop.is_err() { + w.mark_failed(); + c.poison(); + c.retain_driver() + } + if code != 0 { + return Err(Error::Driver { operation: "cuStreamWaitEvent", code }); + } + pop + } + /// Host wait for a pending side copy (an abandoned prefetch: the destination must not be reused or freed under it). + pub(crate) fn cancel<'ctx>(&self, c: &'ctx Context<'ctx>) -> Result<()> { + if !self.pending.get() { + return Ok(()); + } + let side = self.side.as_ref().ok_or(Error::ContextPoisoned)?; + let (stream, _, _) = self.handles.get().ok_or(Error::ContextPoisoned)?; + let g = c.enter().map_err(|e| { + c.poison(); + c.retain_driver(); + e + })?; + // SAFETY: live side stream. + let code = unsafe { (side.stream_sync)(stream as *mut c_void) }; + let pop = g.finish(); + self.pending.set(false); + if code != 0 || pop.is_err() { + c.poison(); + c.retain_driver() + } + if code != 0 { + return Err(Error::Driver { operation: "cuStreamSynchronize", code }); + } + pop + } + pub(crate) fn copy<'ctx>( + &self, + c: &'ctx Context<'ctx>, + w: &mut NativeBatchWorkspace<'ctx>, + ranges: &[(u64, u64, usize)], + ) -> Result<()> { + w.validate_context(c)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + // Private callers derive each address and checked byte extent from actual + // initialized mapped/device owners; reject overflow and overlap prewrite. + for (src, dst, n) in ranges { + if *n == 0 || *src == 0 || *dst == 0 { + return Err(Error::InvalidSize); + } + let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + if *src < de && *dst < se { + return Err(Error::OutputAliasesInput); + } + } + let g = c.enter().map_err(|e| { + w.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let b = w.blas()?; + let op = (|| -> Result<()> { + c.driver.api.synchronize()?; + for (src, dst, n) in ranges { + // SAFETY: actual checked owner extents, real Context and retained stream; + // source/destination leases live through the final synchronize below. + let code = unsafe { (self.copy)(*dst, *src, *n, b.stream() as *mut c_void) }; + if code != 0 { + return Err(Error::Driver { operation: "cuMemcpyAsync", code }); + } + } + Ok(()) + })(); + let sync = b.synchronize(); + let pop = g.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + w.mark_failed(); + c.poison(); + c.retain_driver() + } + combine(combine(op, sync), pop) + } + /// `copy` for a caller that has already fenced every writer of the sources (a completed verifier commit event): + /// the same stream-ordered copies and drain, without the context-wide synchronize first. + pub(crate) fn copy_fenced<'ctx>( + &self, + c: &'ctx Context<'ctx>, + w: &mut NativeBatchWorkspace<'ctx>, + ranges: &[(u64, u64, usize)], + ) -> Result<()> { + w.validate_context(c)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + for (src, dst, n) in ranges { + if *n == 0 || *src == 0 || *dst == 0 { + return Err(Error::InvalidSize); + } + let se = src.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + let de = dst.checked_add(*n as u64).ok_or(Error::InvalidSize)?; + if *src < de && *dst < se { + return Err(Error::OutputAliasesInput); + } + } + let g = c.enter().map_err(|e| { + w.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let b = w.blas()?; + let op = (|| -> Result<()> { + for (src, dst, n) in ranges { + // SAFETY: as `copy`; the caller's fence replaces the context synchronize. + let code = unsafe { (self.copy)(*dst, *src, *n, b.stream() as *mut c_void) }; + if code != 0 { + return Err(Error::Driver { operation: "cuMemcpyAsync", code }); + } + } + Ok(()) + })(); + let sync = b.synchronize(); + let pop = g.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + w.mark_failed(); + c.poison(); + c.retain_driver() + } + combine(combine(op, sync), pop) + } +} +// SAFETY (Drop): `copy` is never called after drop; libcuda itself stays loaded (the driver holds its own reference), and +// every `Transfer::copy*` drains its stream before returning, so no enqueued copy outlives the dlclose. +impl Drop for Transfer { + fn drop(&mut self) { + // the side copy is waited for by `cancel` before a context goes away; here only the handles are released (errors ignored) + if let (Some(side), Some((s, x, y))) = (self.side.as_ref(), self.handles.get()) { + unsafe { + (side.stream_sync)(s as *mut c_void); + (side.event_destroy)(x as *mut c_void); + (side.event_destroy)(y as *mut c_void); + (side.stream_destroy)(s as *mut c_void); + } + } + if !self.library.is_null() { + unsafe { libc::dlclose(self.library) }; + self.library = std::ptr::null_mut(); + } + } +} diff --git a/crates/cuda-driver/src/qsa_resident_transport.rs b/crates/cuda-driver/src/qsa_resident_transport.rs index c00a42d7..1c6f955d 100644 --- a/crates/cuda-driver/src/qsa_resident_transport.rs +++ b/crates/cuda-driver/src/qsa_resident_transport.rs @@ -1,75 +1,320 @@ //! Original prompt KV staging uses actual cache-tail arena spans. Only the //! fixed module/status/identity table are owned here; no second full KV bank. use super::*; -pub struct OriginalQsaResidentTransport<'ctx>{context:&'ctx Context<'ctx>,table:Option>,status:Option>,module:Option,transfer:Option,failed:bool,prefix:Option<([u64;4],[u64;4],usize)>} -impl<'ctx> Context<'ctx>{pub fn original_qsa_resident_transport(&'ctx self)->Result>{OriginalQsaResidentTransport::new(self)}} -impl<'ctx> OriginalQsaResidentTransport<'ctx>{ - pub fn device_bytes()->usize{crate::serving_context::geometry().page_table_bytes()+4} - fn new(context:&'ctx Context<'ctx>)->Result{admit(context,Self::device_bytes())?; - let mut s=Self{context,table:None,status:None,module:None,transfer:None,failed:false,prefix:None};let r=(||->Result<()>{ - s.transfer=Some(crate::qsa_prompt_index::resident_transfer::Transfer::new()?); - let g=context.enter().map_err(|e|{context.poison();context.retain_driver();e})?;let load=Module::load(include_bytes!("qsa_prompt_kv.ptx"),&[c"leleka_qsa_kv_guard",c"leleka_qsa_kv_append",c"leleka_qsa_kv_scale_guard"]);let pop=g.finish(); - if pop.is_err(){context.poison();context.retain_driver()}s.module=Some(load?);pop?; - let mut table=context.allocate(crate::serving_context::geometry().page_table_bytes())?;table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p|p as i32))?)?;s.table=Some(table);s.status=Some(context.allocate(4)?);if context.memory_info()?.0usize{self.table.as_ref().map_or(0,DeviceBuffer::len)+self.status.as_ref().map_or(0,DeviceBuffer::len)} - pub fn is_failed(&self)->bool{self.failed||self.context.is_poisoned()} - pub(crate) fn validate(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.is_failed()||self.module.is_none(){return Err(Error::ContextPoisoned)}checked(c,self.table.as_ref().ok_or(Error::ContextPoisoned)?,crate::serving_context::geometry().page_table_bytes())?;checked(c,self.status.as_ref().ok_or(Error::ContextPoisoned)?,4)?;Ok(())} - pub(crate) fn table(&self)->Result{checked(self.context,self.table.as_ref().ok_or(Error::ContextPoisoned)?,crate::serving_context::geometry().page_table_bytes())} - pub(crate) fn status(&mut self)->Result<&mut DeviceBuffer<'ctx>>{self.status.as_mut().ok_or(Error::ContextPoisoned)} - pub(crate) fn flags(&self)->Result{let b=self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?;Ok(u32::from_le_bytes(b.try_into().map_err(|_|Error::InvalidSize)?))} - pub(crate) fn reject_span(&self,h:crate::ffi::BufferHandle,n:usize)->Result<()>{for b in self.table.iter().chain(self.status.iter()){if h.overlaps(n,b.handle.ok_or(Error::ContextPoisoned)?,b.len()){return Err(Error::OutputAliasesInput)}}Ok(())} - pub(crate) fn run(&mut self,w:&mut NativeBatchWorkspace<'ctx>,index:usize,grid:[u32;3],block:u32,mut a:Arguments)->Result<()>{self.validate(self.context)?;w.validate_context(self.context)?; - let c=self.context;let g=c.enter().map_err(|e|{self.failed=true;w.mark_failed();c.poison();c.retain_driver();e})?; - let op=c.driver.api.synchronize().and_then(|()|self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index,grid,block,0,w.blas()?.stream(),&mut a));let sync=w.blas()?.synchronize();let pop=g.finish(); - if op.is_err()||sync.is_err()||pop.is_err(){self.failed=true;w.mark_failed();c.poison();c.retain_driver()}if sync.is_err()||pop.is_err(){std::mem::forget(a)}combine(combine(op,sync),pop) - } +pub struct OriginalQsaResidentTransport<'ctx> { + context: &'ctx Context<'ctx>, + table: Option>, + status: Option>, + module: Option, + transfer: Option, + failed: bool, + prefix: Option<([u64; 4], [u64; 4], usize)>, +} +impl<'ctx> Context<'ctx> { + pub fn original_qsa_resident_transport(&'ctx self) -> Result> { + OriginalQsaResidentTransport::new(self) + } +} +impl<'ctx> OriginalQsaResidentTransport<'ctx> { + pub fn device_bytes() -> usize { + crate::serving_context::geometry().page_table_bytes() + 4 + } + fn new(context: &'ctx Context<'ctx>) -> Result { + admit(context, Self::device_bytes())?; + let mut s = + Self { context, table: None, status: None, module: None, transfer: None, failed: false, prefix: None }; + let r = (|| -> Result<()> { + s.transfer = Some(crate::qsa_prompt_index::resident_transfer::Transfer::new()?); + let g = context.enter().map_err(|e| { + context.poison(); + context.retain_driver(); + e + })?; + let load = Module::load( + include_bytes!("qsa_prompt_kv.ptx"), + &[c"leleka_qsa_kv_guard", c"leleka_qsa_kv_append", c"leleka_qsa_kv_scale_guard"], + ); + let pop = g.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver() + } + s.module = Some(load?); + pop?; + let mut table = context.allocate(crate::serving_context::geometry().page_table_bytes())?; + table.copy_from(&bytes_i32((0..crate::serving_context::geometry().pages()).map(|p| p as i32))?)?; + s.table = Some(table); + s.status = Some(context.allocate(4)?); + if context.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = r { + return combine(Err(e), s.close()); + } + Ok(s) + } + pub fn allocated_bytes(&self) -> usize { + self.table.as_ref().map_or(0, DeviceBuffer::len) + self.status.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub(crate) fn validate(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if self.is_failed() || self.module.is_none() { + return Err(Error::ContextPoisoned); + } + checked( + c, + self.table.as_ref().ok_or(Error::ContextPoisoned)?, + crate::serving_context::geometry().page_table_bytes(), + )?; + checked(c, self.status.as_ref().ok_or(Error::ContextPoisoned)?, 4)?; + Ok(()) + } + pub(crate) fn table(&self) -> Result { + checked( + self.context, + self.table.as_ref().ok_or(Error::ContextPoisoned)?, + crate::serving_context::geometry().page_table_bytes(), + ) + } + pub(crate) fn status(&mut self) -> Result<&mut DeviceBuffer<'ctx>> { + self.status.as_mut().ok_or(Error::ContextPoisoned) + } + pub(crate) fn flags(&self) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; + Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) + } + pub(crate) fn reject_span(&self, h: crate::ffi::BufferHandle, n: usize) -> Result<()> { + for b in self.table.iter().chain(self.status.iter()) { + if h.overlaps(n, b.handle.ok_or(Error::ContextPoisoned)?, b.len()) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + pub(crate) fn run( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + index: usize, + grid: [u32; 3], + block: u32, + mut a: Arguments, + ) -> Result<()> { + self.validate(self.context)?; + w.validate_context(self.context)?; + let c = self.context; + let g = c.enter().map_err(|e| { + self.failed = true; + w.mark_failed(); + c.poison(); + c.retain_driver(); + e + })?; + let op = c.driver.api.synchronize().and_then(|()| { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( + index, + grid, + block, + 0, + w.blas()?.stream(), + &mut a, + ) + }); + let sync = w.blas()?.synchronize(); + let pop = g.finish(); + if op.is_err() || sync.is_err() || pop.is_err() { + self.failed = true; + w.mark_failed(); + c.poison(); + c.retain_driver() + } + if sync.is_err() || pop.is_err() { + std::mem::forget(a) + } + combine(combine(op, sync), pop) + } - fn prefix_ranges(&self,w:&mut NativeBatchWorkspace<'ctx>,host:[u64;4],stage:[crate::ffi::BufferHandle;4],pages:usize)->Result<[(u64,u64,usize);4]>{ - let mut ranges=[(0,0,0);4];for i in 0..4{let n=pages*[2048,2048,64,64][i];stage[i].validate_projection_extent(n,1)?;self.reject_span(stage[i],n)?;w.reject_alias(stage[i],n)?;ranges[i]=(host[i],stage[i].qwen_address(),n);}Ok(ranges) - } - /// `LELEKA_PREFILL_QSA_PREFETCH` (docs/upstream-port-plan.md, 256k prefill gap): the prior-KV prefix copy of a QSA layer starts on a side - /// stream at the beginning of the layer, under its projections and indexer, instead of between the indexer and the attention. - /// `1` on, `0` off; unset: `QSA_PREFETCH_DEFAULT`. A per-arm override wins. -pub fn prefetch_enabled()->bool{ - match PREFETCH_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed){0=>return false,1=>return true,_=>{}} - static ON:std::sync::OnceLock=std::sync::OnceLock::new(); - *ON.get_or_init(||std::env::var("LELEKA_PREFILL_QSA_PREFETCH").map_or(QSA_PREFETCH_DEFAULT,|v|v!="0")) - } - /// Start the prefix copy of the layer that is about to run (its stage spans and host mirror are known before the indexer runs). The - /// layer's `copy_prefix` then only orders the compute stream after it. Falls back to nothing (the blocking copy runs later) when the - /// driver cannot overlap or the switch is off. - pub(crate) fn begin_prefix(&mut self,w:&mut NativeBatchWorkspace<'ctx>,host:[u64;4],stage:[crate::ffi::BufferHandle;4],pages:usize)->Result<()>{ - self.validate(self.context)?;if pages>crate::serving_context::geometry().pages(){return Err(Error::InvalidQwenShape)} - if let Some(t)=self.transfer.as_ref(){if t.is_pending(){t.cancel(self.context)?;}}self.prefix=None; - if pages==0||!Self::prefetch_enabled()||!self.transfer.as_ref().is_some_and(|t|t.can_overlap()){return Ok(())} - let ranges=self.prefix_ranges(w,host,stage,pages)?; - let result=self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.begin(self.context,w,&ranges); - if result.is_err(){self.failed=true}else{self.prefix=Some((host,[stage[0].qwen_address(),stage[1].qwen_address(),stage[2].qwen_address(),stage[3].qwen_address()],pages))}result - } - /// Abandon a started prefetch (host wait): nothing may reuse or free the stage under the copy. - pub fn cancel_prefix(&mut self)->Result<()>{self.prefix=None;match self.transfer.as_ref(){Some(t)=>t.cancel(self.context),None=>Ok(())}} - pub(crate) fn copy_prefix(&mut self,w:&mut NativeBatchWorkspace<'ctx>,host:[u64;4],stage:[crate::ffi::BufferHandle;4],pages:usize)->Result<()>{ - self.validate(self.context)?;if pages>crate::serving_context::geometry().pages(){return Err(Error::InvalidQwenShape)}if pages==0{return Ok(())} - let ranges=self.prefix_ranges(w,host,stage,pages)?; - // a prefix started at the layer's beginning for exactly these ranges: order the compute stream after it - if let Some((h,s,p))=self.prefix.take(){ - if h==host&&p==pages&&s==[stage[0].qwen_address(),stage[1].qwen_address(),stage[2].qwen_address(),stage[3].qwen_address()]{ - let result=self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.wait_pending(self.context,w);if result.is_err(){self.failed=true}return result; - } - if let Some(t)=self.transfer.as_ref(){t.cancel(self.context)?;} - } - let result=self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.copy(self.context,w,&ranges);if result.is_err(){self.failed=true}result - } - pub fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{self.failed=true;let mut r=Ok(());if let Some(t)=self.transfer.take(){if !self.context.is_poisoned(){let _=t.cancel(self.context);}if self.context.is_poisoned(){std::mem::forget(t);r=Err(Error::ContextPoisoned)}else{drop(t)}}if let Some(m)=self.module.take(){if self.context.is_poisoned(){std::mem::forget(m);r=Err(Error::ContextPoisoned)}else{match self.context.enter(){Ok(g)=>{let x=combine(m.close(),g.finish());if x.is_err(){self.context.poison();self.context.retain_driver()}r=combine(r,x)},Err(e)=>{self.context.poison();self.context.retain_driver();std::mem::forget(m);r=combine(r,Err(e))}}}} - for b in [self.status.take(),self.table.take()].into_iter().flatten(){if self.context.is_poisoned(){std::mem::forget(b);r=combine(r,Err(Error::ContextPoisoned))}else{r=combine(r,b.release())}}r - } + fn prefix_ranges( + &self, + w: &mut NativeBatchWorkspace<'ctx>, + host: [u64; 4], + stage: [crate::ffi::BufferHandle; 4], + pages: usize, + ) -> Result<[(u64, u64, usize); 4]> { + let mut ranges = [(0, 0, 0); 4]; + for i in 0..4 { + let n = pages * [2048, 2048, 64, 64][i]; + stage[i].validate_projection_extent(n, 1)?; + self.reject_span(stage[i], n)?; + w.reject_alias(stage[i], n)?; + ranges[i] = (host[i], stage[i].qwen_address(), n); + } + Ok(ranges) + } + /// `LELEKA_PREFILL_QSA_PREFETCH` (docs/upstream-port-plan.md, 256k prefill gap): the prior-KV prefix copy of a QSA layer starts on a side + /// stream at the beginning of the layer, under its projections and indexer, instead of between the indexer and the attention. + /// `1` on, `0` off; unset: `QSA_PREFETCH_DEFAULT`. A per-arm override wins. + pub fn prefetch_enabled() -> bool { + match PREFETCH_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return false, + 1 => return true, + _ => {} + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_PREFILL_QSA_PREFETCH").map_or(QSA_PREFETCH_DEFAULT, |v| v != "0")) + } + /// Start the prefix copy of the layer that is about to run (its stage spans and host mirror are known before the indexer runs). The + /// layer's `copy_prefix` then only orders the compute stream after it. Falls back to nothing (the blocking copy runs later) when the + /// driver cannot overlap or the switch is off. + pub(crate) fn begin_prefix( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + host: [u64; 4], + stage: [crate::ffi::BufferHandle; 4], + pages: usize, + ) -> Result<()> { + self.validate(self.context)?; + if pages > crate::serving_context::geometry().pages() { + return Err(Error::InvalidQwenShape); + } + if let Some(t) = self.transfer.as_ref() { + if t.is_pending() { + t.cancel(self.context)?; + } + } + self.prefix = None; + if pages == 0 || !Self::prefetch_enabled() || !self.transfer.as_ref().is_some_and(|t| t.can_overlap()) { + return Ok(()); + } + let ranges = self.prefix_ranges(w, host, stage, pages)?; + let result = self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.begin(self.context, w, &ranges); + if result.is_err() { + self.failed = true + } else { + self.prefix = Some(( + host, + [stage[0].qwen_address(), stage[1].qwen_address(), stage[2].qwen_address(), stage[3].qwen_address()], + pages, + )) + } + result + } + /// Abandon a started prefetch (host wait): nothing may reuse or free the stage under the copy. + pub fn cancel_prefix(&mut self) -> Result<()> { + self.prefix = None; + match self.transfer.as_ref() { + Some(t) => t.cancel(self.context), + None => Ok(()), + } + } + pub(crate) fn copy_prefix( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + host: [u64; 4], + stage: [crate::ffi::BufferHandle; 4], + pages: usize, + ) -> Result<()> { + self.validate(self.context)?; + if pages > crate::serving_context::geometry().pages() { + return Err(Error::InvalidQwenShape); + } + if pages == 0 { + return Ok(()); + } + let ranges = self.prefix_ranges(w, host, stage, pages)?; + // a prefix started at the layer's beginning for exactly these ranges: order the compute stream after it + if let Some((h, s, p)) = self.prefix.take() { + if h == host + && p == pages + && s == [ + stage[0].qwen_address(), + stage[1].qwen_address(), + stage[2].qwen_address(), + stage[3].qwen_address(), + ] + { + let result = self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.wait_pending(self.context, w); + if result.is_err() { + self.failed = true + } + return result; + } + if let Some(t) = self.transfer.as_ref() { + t.cancel(self.context)?; + } + } + let result = self.transfer.as_ref().ok_or(Error::ContextPoisoned)?.copy(self.context, w, &ranges); + if result.is_err() { + self.failed = true + } + result + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut r = Ok(()); + if let Some(t) = self.transfer.take() { + if !self.context.is_poisoned() { + let _ = t.cancel(self.context); + } + if self.context.is_poisoned() { + std::mem::forget(t); + r = Err(Error::ContextPoisoned) + } else { + drop(t) + } + } + if let Some(m) = self.module.take() { + if self.context.is_poisoned() { + std::mem::forget(m); + r = Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => { + let x = combine(m.close(), g.finish()); + if x.is_err() { + self.context.poison(); + self.context.retain_driver() + } + r = combine(r, x) + } + Err(e) => { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(m); + r = combine(r, Err(e)) + } + } + } + } + for b in [self.status.take(), self.table.take()].into_iter().flatten() { + if self.context.is_poisoned() { + std::mem::forget(b); + r = combine(r, Err(Error::ContextPoisoned)) + } else { + r = combine(r, b.release()) + } + } + r + } } /// Per-arm override of `LELEKA_PREFILL_QSA_PREFETCH` (-1: none, 0: off, 1: on). -static PREFETCH_OVERRIDE:std::sync::atomic::AtomicI8=std::sync::atomic::AtomicI8::new(-1); -pub fn set_qsa_prefetch_override(value:i8){PREFETCH_OVERRIDE.store(value,std::sync::atomic::Ordering::Relaxed);} +static PREFETCH_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); +pub fn set_qsa_prefetch_override(value: i8) { + PREFETCH_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed); +} /// Default of `LELEKA_PREFILL_QSA_PREFETCH` (flipped after its gates). -const QSA_PREFETCH_DEFAULT:bool=true; -impl Drop for OriginalQsaResidentTransport<'_>{fn drop(&mut self){let _=self.close_inner();}} +const QSA_PREFETCH_DEFAULT: bool = true; +impl Drop for OriginalQsaResidentTransport<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/cuda-driver/src/qsa_selected_kv.rs b/crates/cuda-driver/src/qsa_selected_kv.rs index 08b04725..aa51503a 100644 --- a/crates/cuda-driver/src/qsa_selected_kv.rs +++ b/crates/cuda-driver/src/qsa_selected_kv.rs @@ -14,8 +14,8 @@ const RESERVE: usize = 128 * 1024 * 1024; const PTX: &[u8] = concat!(include_str!("qsa_selected_kv.ptx"), "\0").as_bytes(); // Root replaces these ONLY after real offline NVCC output is pinned in a new derivative. const PTX_SHA: Option<[u8; 32]> = Some([ - 79, 42, 210, 4, 16, 155, 221, 151, 74, 124, 150, 93, 8, 217, 6, 74, 245, 39, 86, 177, 246, 252, - 21, 2, 127, 71, 125, 226, 253, 136, 63, 146, + 79, 42, 210, 4, 16, 155, 221, 151, 74, 124, 150, 93, 8, 217, 6, 74, 245, 39, 86, 177, 246, 252, 21, 2, 127, 71, + 125, 226, 253, 136, 63, 146, ]); const PTX_BYTES: Option = Some(3842); @@ -85,9 +85,7 @@ mod selected_kv_installed { } let driver = Driver::load().expect("actual CUDA library"); let device = driver.device(0).expect("actual device"); - let context = device - .create_context(256 * 1024 * 1024) - .expect("bounded actual context"); + let context = device.create_context(256 * 1024 * 1024).expect("bounded actual context"); let mut buffers = Vec::new(); let mut workspace = None; let mut differences = 0usize; @@ -95,13 +93,7 @@ mod selected_kv_installed { let mut guards = 0usize; let operation: Result<()> = (|| { let query: Vec = (0..6144) - .flat_map(|i| { - if i % 3 == 0 { - 0.125f32.to_le_bytes() - } else { - (-0.125f32).to_le_bytes() - } - }) + .flat_map(|i| if i % 3 == 0 { 0.125f32.to_le_bytes() } else { (-0.125f32).to_le_bytes() }) .collect(); buffers.push(upload(&context, &query)?); buffers.push(context.allocate(24576)?); @@ -136,21 +128,14 @@ mod selected_kv_installed { } else { 0 }; - keys[j * CELL..(j + 1) * CELL] - .copy_from_slice(&packed(&[slot as usize], old_seed)); - values[j * CELL..(j + 1) * CELL] - .copy_from_slice(&packed(&[slot as usize], old_seed + 7)); + keys[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed)); + values[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed + 7)); } let key = upload(&context, &keys)?; let value = upload(&context, &values)?; let (query_owner, output_owner) = buffers.split_at_mut(1); - let reference = context.qsa_attend( - &query_owner[0], - &key, - &value, - &mut output_owner[0], - selected.len() as u32, - ); + let reference = + context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], selected.len() as u32); let cleanup = combine(key.release(), value.release()); combine(reference, cleanup)?; let expected = read(&buffers[1], 24576)?; @@ -192,15 +177,9 @@ mod selected_kv_installed { guards += 1; { let previous = right[0].handle; - let alias = RestoreHandle { - buffer: &mut right[0], - previous, - }; + let alias = RestoreHandle { buffer: &mut right[0], previous }; alias.buffer.handle = left[0].handle; - if !matches!( - products.attend(&left[0], &mut *alias.buffer), - Err(Error::OutputAliasesInput) - ) { + if !matches!(products.attend(&left[0], &mut *alias.buffer), Err(Error::OutputAliasesInput)) { return Err(Error::InvalidDriverValue("QSA alias guard")); } guards += 1; @@ -230,13 +209,8 @@ mod selected_kv_installed { { return Err(Error::InvalidDriverValue("QSA full output finite")); } - differences += actual - .as_chunks::<4>() - .0 - .iter() - .zip(expected.as_chunks::<4>().0) - .filter(|(a, b)| a != b) - .count(); + differences += + actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); compared += 6144; drop(products); let generation = owner.generation; @@ -244,14 +218,10 @@ mod selected_kv_installed { for refused in [ owner.prepare(12, &[], &[], &[], &[0]).is_err(), owner.prepare(layer, &[], &[], &[], &[0, 0]).is_err(), - owner - .prepare(layer, &[0, 0], &vec![0; 2048], &vec![0; 2048], &[0]) - .is_err(), + owner.prepare(layer, &[0, 0], &vec![0; 2048], &vec![0; 2048], &[0]).is_err(), owner.prepare(layer, &[], &[], &[], &[2051]).is_err(), owner.prepare(layer, &[], &[], &[], &[18]).is_err(), - owner - .prepare(layer, &[0], &vec![0; 1023], &vec![0; 1023], &[0]) - .is_err(), + owner.prepare(layer, &[0], &vec![0; 1023], &vec![0; 1023], &[0]).is_err(), ] { if !refused { return Err(Error::InvalidDriverValue("QSA guard accepted")); @@ -260,17 +230,11 @@ mod selected_kv_installed { } let mut nonfinite = vec![0; 1024]; nonfinite[510..512].copy_from_slice(&0x7e00u16.to_le_bytes()); - if owner - .prepare(layer, &[0], &nonfinite, &vec![0; 1024], &[0]) - .is_ok() - { + if owner.prepare(layer, &[0], &nonfinite, &vec![0; 1024], &[0]).is_ok() { return Err(Error::InvalidDriverValue("QSA nonfinite accepted")); } guards += 1; - if owner.generation != generation - || context.allocated_bytes() != charged - || owner.is_failed() - { + if owner.generation != generation || context.allocated_bytes() != charged || owner.is_failed() { return Err(Error::InvalidDriverValue("QSA prewrite mutation")); } } @@ -286,8 +250,7 @@ mod selected_kv_installed { .iter() .flat_map(|&cell| { (0..512).flat_map(move |lane| { - let bits = (0x2000u16 + cell as u16 + seed) - | if lane % 2 == 0 { 0 } else { 0x8000 }; + let bits = (0x2000u16 + cell as u16 + seed) | if lane % 2 == 0 { 0 } else { 0x8000 }; bits.to_le_bytes() }) }) @@ -298,20 +261,14 @@ mod selected_kv_installed { let key = upload(&context, &keys)?; let value = upload(&context, &values)?; let (query_owner, output_owner) = buffers.split_at_mut(1); - let reference = - context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], 2051); + let reference = context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], 2051); let released = combine(key.release(), value.release()); combine(reference, released)?; let expected_output = read(&buffers[1], 24576)?; let owner = workspace.as_mut().ok_or(Error::ContextPoisoned)?; let generation = owner.generation; - let products = owner.prepare( - 11, - &misses, - &max_packed(&missing_ids, 3), - &max_packed(&missing_ids, 10), - &selected, - )?; + let products = + owner.prepare(11, &misses, &max_packed(&missing_ids, 3), &max_packed(&missing_ids, 10), &selected)?; if products.width() != 2051 || products.generation() != generation + 1 { return Err(Error::InvalidDriverValue("QSA max-width witness")); } @@ -355,9 +312,7 @@ mod selected_kv_installed { drop(products); Ok(()) })(); - let mut cleanup = workspace - .take() - .map_or(Ok(()), QsaSelectedKvWorkspace::close); + let mut cleanup = workspace.take().map_or(Ok(()), QsaSelectedKvWorkspace::close); drop(workspace); for buffer in buffers.drain(..) { cleanup = combine(cleanup, buffer.release()); @@ -381,8 +336,8 @@ mod selected_kv_installed { mod asset_fn; #[allow(unused_imports)] pub(crate) use asset_fn::asset; -mod impl_qsaselectedkvworkspace; mod impl_drop_for_qsaselectedkvworkspace; +mod impl_qsaselectedkvworkspace; #[allow(unused_imports)] use impl_drop_for_qsaselectedkvworkspace::owned_bytes; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/qsa_selected_kv/asset_fn.rs b/crates/cuda-driver/src/qsa_selected_kv/asset_fn.rs index badcb905..24cd8bb1 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/asset_fn.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/asset_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(crate) fn asset() -> Result<&'static [u8]> { let digest = PTX_SHA.ok_or(Error::UnsupportedQwenOperation)?; let bytes = PTX_BYTES.ok_or(Error::UnsupportedQwenOperation)?; diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs index 658b07fd..4217d838 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs @@ -55,11 +55,7 @@ impl QsaSelectedKvProducts<'_, '_> { return Err(error); } }; - let launch = w - .context - .driver - .api - .launch_qwen(function, Operation::QsaAttend, &mut args); + let launch = w.context.driver.api.launch_qwen(function, Operation::QsaAttend, &mut args); let sync = w.context.driver.api.synchronize(); let pop = guard.finish(); if launch.is_err() || sync.is_err() || pop.is_err() { @@ -74,15 +70,13 @@ impl QsaSelectedKvProducts<'_, '_> { } pub(super) fn owned_bytes(input: &[u8]) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(input.len()) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(input.len()).map_err(|_| Error::HostAllocation)?; v.extend_from_slice(input); Ok(v) } pub(super) fn slot_bytes(input: &[u32]) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(input.len() * 4) - .map_err(|_| Error::HostAllocation)?; + v.try_reserve_exact(input.len() * 4).map_err(|_| Error::HostAllocation)?; for n in input { v.extend_from_slice(&n.to_le_bytes()); } diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs index 74ddd05c..a4ba4e23 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs @@ -3,29 +3,22 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> QsaSelectedKvWorkspace<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } asset()?; // Pending asset refuses before allocation or module mutation. - let attention = - qwen_ffi::asset(Operation::QsaAttend).ok_or(Error::UnsupportedQwenOperation)?; + let attention = qwen_ffi::asset(Operation::QsaAttend).ok_or(Error::UnsupportedQwenOperation)?; attention.validate(Operation::QsaAttend)?; let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); } let mut initialized = Vec::new(); - initialized - .try_reserve_exact(LAYERS * CELLS) - .map_err(|_| Error::HostAllocation)?; + initialized.try_reserve_exact(LAYERS * CELLS).map_err(|_| Error::HostAllocation)?; initialized.resize(LAYERS * CELLS, false); let mut owner = Self { context, @@ -48,10 +41,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { let gather = context.driver.api.qsa_selected_function(transport, true)?; let original = context.driver.api.load_qwen_module(attention)?; owner.modules[1] = Some(original); - let attend = context - .driver - .api - .qwen_function(original, Operation::QsaAttend)?; + let attend = context.driver.api.qwen_function(original, Operation::QsaAttend)?; owner.functions = Some([scatter, gather, attend]); Ok(()) })(); @@ -76,8 +66,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { return Err(Error::ContextPoisoned); } let mut list = Vec::new(); - list.try_reserve_exact(8) - .map_err(|_| Error::HostAllocation)?; + list.try_reserve_exact(8).map_err(|_| Error::HostAllocation)?; for (i, buffer) in self.buffers.iter().enumerate() { let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; if !std::ptr::eq(self.context, buffer.context) { @@ -116,10 +105,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { { return Err(Error::InvalidQwenShape); } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let mut missing = [false; CELLS]; for &slot in miss_slots { if slot as usize >= CELLS || missing[slot as usize] { @@ -131,8 +117,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { for &slot in selected_slots { if slot as usize >= CELLS || selected[slot as usize] - || (!missing[slot as usize] - && !self.initialized[layer as usize * CELLS + slot as usize]) + || (!missing[slot as usize] && !self.initialized[layer as usize * CELLS + slot as usize]) { return Err(Error::InvalidQwenShape); } @@ -151,22 +136,11 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { return Err(Error::BudgetExceeded); } // All fallible staging allocation and closed ranges precede the first copy. - let stages = [ - owned_bytes(miss_k)?, - owned_bytes(miss_v)?, - slot_bytes(miss_slots)?, - slot_bytes(selected_slots)?, - ]; - let mut scatter = ffi::QsaSelectedArguments::new( - [h[0], h[1], h[4], h[5], h[6]], - layer, - miss_slots.len() as u32, - ); - let mut gather = ffi::QsaSelectedArguments::new( - [h[0], h[1], h[2], h[3], h[7]], - layer, - selected_slots.len() as u32, - ); + let stages = [owned_bytes(miss_k)?, owned_bytes(miss_v)?, slot_bytes(miss_slots)?, slot_bytes(selected_slots)?]; + let mut scatter = + ffi::QsaSelectedArguments::new([h[0], h[1], h[4], h[5], h[6]], layer, miss_slots.len() as u32); + let mut gather = + ffi::QsaSelectedArguments::new([h[0], h[1], h[2], h[3], h[7]], layer, selected_slots.len() as u32); let misses = if miss_slots.is_empty() { None } else { @@ -192,22 +166,16 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { } } if operation.is_ok() { - operation = self.context.driver.api.launch_qsa_selected( - functions[0], - miss_slots.len() as u32, - &mut scatter, - ); + operation = + self.context.driver.api.launch_qsa_selected(functions[0], miss_slots.len() as u32, &mut scatter); } } if operation.is_ok() { operation = self.context.driver.api.copy_from(selection, &stages[3]); } if operation.is_ok() { - operation = self.context.driver.api.launch_qsa_selected( - functions[1], - selected_slots.len() as u32, - &mut gather, - ); + operation = + self.context.driver.api.launch_qsa_selected(functions[1], selected_slots.len() as u32, &mut gather); } let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); @@ -223,11 +191,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { self.initialized[layer as usize * CELLS + slot as usize] = true; } self.generation = generation; - Ok(QsaSelectedKvProducts { - workspace: self, - width: selected_slots.len() as u32, - generation, - }) + Ok(QsaSelectedKvProducts { workspace: self, width: selected_slots.len() as u32, generation }) } pub fn close(mut self) -> Result<()> { @@ -257,9 +221,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { Err(Error::ContextPoisoned) } else { match self.context.enter() { - Ok(guard) => { - combine(self.context.driver.api.unload(module), guard.finish()) - } + Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), Err(e) => Err(e), } }; diff --git a/crates/cuda-driver/src/qsa_verification_commit.rs b/crates/cuda-driver/src/qsa_verification_commit.rs index 8cdb6365..49a3c44f 100644 --- a/crates/cuda-driver/src/qsa_verification_commit.rs +++ b/crates/cuda-driver/src/qsa_verification_commit.rs @@ -2,201 +2,69 @@ //! Owns those images; it never constructs an earlier checkpoint from final data. //! Child of qsa_resident_index. All graph aggregates retain this same Rc journal. use super::*; -use crate::original_verify::{OriginalVerifyBank,OriginalVerifyGdnJournal}; -use crate::original_verify::abi::{Arg,Command}; use crate::OriginalCapture; +use crate::original_verify::abi::{Arg, Command}; +use crate::original_verify::{OriginalVerifyBank, OriginalVerifyGdnJournal}; use std::cell::RefCell; /// Resolved Original analytic constants, and actual optional retained device /// tables. Process policy is fixed before capture by the genuine model adapter. -#[derive(Clone,Copy)] -pub struct OriginalVerifyRope<'a,'ctx>{pub theta_scale:f32,pub freq_scale:f32,pub corr_low:f32,pub corr_high:f32,pub ext_factor:f32,pub magnitude:f32,pub positions:Option<&'a DeviceBuffer<'ctx>>,pub angles:Option<(&'a DeviceBuffer<'ctx>,&'a DeviceBuffer<'ctx>,usize)>} -impl OriginalVerifyRope<'_, '_>{fn validate(&self,c:&Context<'_>,capacity:usize)->Result<()>{ - for v in [self.theta_scale,self.freq_scale,self.corr_low,self.corr_high,self.ext_factor,self.magnitude]{if !v.is_finite(){return Err(Error::InvalidQwenShape)}}if self.theta_scale<=0.0||self.freq_scale<=0.0||self.ext_factor<0.0||self.magnitude<=0.0{return Err(Error::InvalidQwenShape)} - if let Some(p)=self.positions{whole(c,p,capacity*3*4)?;}if let Some((cos,sin,n))=self.angles{if n==0||n>i32::MAX as usize{return Err(Error::InvalidSize)}let bytes=n.checked_mul(32*4).ok_or(Error::InvalidSize)?;whole(c,cos,bytes)?;whole(c,sin,bytes)?;if overlaps(cos,sin)?{return Err(Error::OutputAliasesInput)}}Ok(()) -}} -fn whole(c:&Context<'_>,b:&DeviceBuffer<'_>,bytes:usize)->Result{if !std::ptr::eq(c,b.context){return Err(Error::ContextMismatch)}if b.len()!=bytes{return Err(Error::ShapeMismatch{expected:bytes,actual:b.len()})}let h=b.handle.ok_or(Error::ContextPoisoned)?;h.validate_projection_extent(bytes,4)?;Ok(h.qwen_address())} -fn overlaps(a:&DeviceBuffer<'_>,b:&DeviceBuffer<'_>)->Result{Ok(a.handle.ok_or(Error::ContextPoisoned)?.overlaps(a.len(),b.handle.ok_or(Error::ContextPoisoned)?,b.len()))} +#[derive(Clone, Copy)] +pub struct OriginalVerifyRope<'a, 'ctx> { + pub theta_scale: f32, + pub freq_scale: f32, + pub corr_low: f32, + pub corr_high: f32, + pub ext_factor: f32, + pub magnitude: f32, + pub positions: Option<&'a DeviceBuffer<'ctx>>, + pub angles: Option<(&'a DeviceBuffer<'ctx>, &'a DeviceBuffer<'ctx>, usize)>, +} /// Addresses of one QSA layer's fixed owners (see `OriginalVerifyQsaJournal::window_addresses`). -pub(crate) struct OriginalVerifyQsaWindowAddresses{pub resident:[u64;4],pub table:u64,pub host:[u64;4],pub resolver:[u64;7],pub slots:usize,pub pooled:u64,pub pooled_bytes:usize,pub dead:u64,pub dead_bytes:usize} -struct Live{generation:u64,position:usize,rows:usize,armed:bool} +pub(crate) struct OriginalVerifyQsaWindowAddresses { + pub resident: [u64; 4], + pub table: u64, + pub host: [u64; 4], + pub resolver: [u64; 7], + pub slots: usize, + pub pooled: u64, + pub pooled_bytes: usize, + pub dead: u64, + pub dead_bytes: usize, +} +struct Live { + generation: u64, + position: usize, + rows: usize, + armed: bool, +} /// Actual source gamma references, table owners and index images stay alive /// through ALL graph captures/replays and accepted-prefix commits. /// The verifier retains both Original QSA state owners. The index image alone /// is insufficient: upstream `verify.cpp` appends the real K/V projections /// before the indexer and resolves attention from that same K/V prefix. -pub struct OriginalVerifyQsaJournal<'a,'ctx>{context:&'ctx Context<'ctx>,indices:[RefCell>;12],mapped:[RefCell>;12],gamma:[&'a DeviceBuffer<'ctx>;12],rope:OriginalVerifyRope<'a,'ctx>,live:RefCell,failed:Cell, - /// `set_window_snapshots`: the index state (12 x `WINDOW_STATE_BYTES`) and the PLE history image at the start of every window, for `discard_window`. - snapshots:Cell,snapshot:RefCell>,ple_snapshot:RefCell>} -impl<'a,'ctx> OriginalVerifyQsaJournal<'a,'ctx>{ - pub fn new(context:&'ctx Context<'ctx>,indices:[OriginalQsaResidentIndex<'ctx>;12],mapped:[OriginalQsaMappedJournal<'ctx>;12],gamma:[&'a DeviceBuffer<'ctx>;12],rope:OriginalVerifyRope<'a,'ctx>)->Result>{ - let end=indices[0].next_position();for(i,m)in indices.iter().zip(mapped.iter()){i.validate_context(context)?;m.validate_context(context)?;if i.in_flight||i.unpublished||i.end!=end||m.next_position()!=end{return Err(Error::InvalidQwenShape)}} - for g in gamma{whole(context,g,512)?;for i in &indices{for b in i.image.iter().flatten(){if overlaps(g,b)?{return Err(Error::OutputAliasesInput)}}}} - rope.validate(context,crate::serving_context::geometry().cells())?; - for i in &indices{for b in i.image.iter().flatten(){if let Some(p)=rope.positions{if overlaps(p,b)?{return Err(Error::OutputAliasesInput)}}if let Some((cos,sin,_))=rope.angles{if overlaps(cos,b)?||overlaps(sin,b)?{return Err(Error::OutputAliasesInput)}}}} - Ok(Rc::new(Self{context,indices:indices.map(RefCell::new),mapped:mapped.map(RefCell::new),gamma,rope,live:RefCell::new(Live{generation:0,position:end,rows:0,armed:false}),failed:Cell::new(false),snapshots:Cell::new(false),snapshot:RefCell::new(Vec::new()),ple_snapshot:RefCell::new(Vec::new())})) - } - pub fn validate_context(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.failed.get()||c.is_poisoned(){return Err(Error::ContextPoisoned)}for(i,m)in self.indices.iter().zip(self.mapped.iter()){let i=i.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let m=m.try_borrow().map_err(|_|Error::InvalidQwenShape)?;i.validate_context(c)?;m.validate_context(c)?;if i.next_position()!=m.next_position(){return Err(Error::InvalidQwenShape)}}Ok(())} - pub(crate) fn identity(&self)->usize{self as *const Self as usize} - /// Only driver siblings can bind actual image pointers into captured kernels. - /// The aggregate retains this actual owner after the short borrow ends. - pub(crate) fn with_image(&self,layer:usize,consume:impl FnOnce([&DeviceBuffer<'ctx>;4],&DeviceBuffer<'ctx>)->Result)->Result{self.validate_context(self.context)?;if layer>=12{return Err(Error::InvalidQwenShape)}let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?;consume([i.image[0].as_ref().ok_or(Error::ContextPoisoned)?,i.image[1].as_ref().ok_or(Error::ContextPoisoned)?,i.image[2].as_ref().ok_or(Error::ContextPoisoned)?,i.image[3].as_ref().ok_or(Error::ContextPoisoned)?],self.gamma[layer])} - pub(crate) fn with_committed_index(&self,layer:usize,consume:impl FnOnce(&mut OriginalQsaResidentIndex<'ctx>)->Result)->Result{self.validate_context(self.context)?;if layer>=12||self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?.armed{return Err(Error::InvalidQwenShape)}let mut i=self.indices[layer].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;if i.in_flight||i.unpublished{return Err(Error::InvalidQwenShape)}consume(&mut i)} - /// `with_committed_index(.., checkpoint)` of all twelve layers in one fenced batch (`checkpoint_fenced_all`): the - /// caller (the verifier) has waited its commit event, the only writer of these images. - pub(crate) fn checkpoint_committed_all(&self,ws:&mut NativeBatchWorkspace<'ctx>)->Result<[OriginalQsaIndexCheckpoint<'ctx>;12]>{ - self.validate_context(self.context)?;if self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?.armed{return Err(Error::InvalidQwenShape)} - let mut held=Vec::new();held.try_reserve_exact(12).map_err(|_|Error::HostAllocation)?; - for i in &self.indices{held.push(i.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?)} - let mut refs:Vec<&mut OriginalQsaResidentIndex<'ctx>>=held.iter_mut().map(|i|&mut **i).collect(); - let saved=OriginalQsaResidentIndex::checkpoint_fenced_all(&mut refs,ws)?; - saved.try_into().map_err(|_|Error::InvalidQwenShape) - } - /// Access to the genuine mapped K/V owner is restricted to the driver graph - /// bridge. A caller cannot mint a prefix from an index snapshot. - pub(crate) fn with_committed_mapped(&self,layer:usize,consume:impl FnOnce(&mut OriginalQsaMappedJournal<'ctx>)->Result)->Result{self.validate_context(self.context)?;if layer>=12||self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?.armed{return Err(Error::InvalidQwenShape)}let mut m=self.mapped[layer].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;consume(&mut m)} - /// The resolved Original RoPE constants and optional retained tables (read only). - pub(crate) fn rope(&self)->OriginalVerifyRope<'a,'ctx>{self.rope} - /// Fixed device addresses the captured window kernels of one QSA layer bind: the streamed INT8 KV - /// (resident pools, page table, host copy, resolver) and the index image's pooled keys and spare key. - /// Read only; the window recorder may call it while a window is armed because no state changes. - pub(crate) fn window_addresses(&self,layer:usize)->Result{ - self.validate_context(self.context)?;if layer>=12{return Err(Error::InvalidQwenShape)} - let (resident,table,host,resolver,slots)=self.mapped[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?.window_kv_addresses()?; - let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - let pooled=i.image[0].as_ref().ok_or(Error::ContextPoisoned)?;let dead=i.image[2].as_ref().ok_or(Error::ContextPoisoned)?; - let address=|b:&DeviceBuffer<'ctx>|->Result{Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address())}; - Ok(OriginalVerifyQsaWindowAddresses{resident,table,host,resolver,slots,pooled:address(pooled)?,pooled_bytes:pooled.len(),dead:address(dead)?,dead_bytes:dead.len()}) - } - pub fn allocated_bytes(&self)->usize{self.indices.iter().map(|i|i.borrow().allocated_bytes()).sum::()+self.mapped.iter().map(|m|m.borrow().allocated_bytes()).sum::()} - pub(crate) fn begin_window(&self,bank:&OriginalVerifyBank<'ctx>)->Result<()>{ - self.validate_context(self.context)?;bank.validate_context(self.context)?;let mut live=self.live.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;if live.armed{return Err(Error::InvalidQwenShape)} - let (generation,position,rows)=bank.staged_window()?;for(i,m)in self.indices.iter().zip(self.mapped.iter()){let i=i.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let m=m.try_borrow().map_err(|_|Error::InvalidQwenShape)?;if i.in_flight||i.unpublished||i.end!=position||m.next_position()!=position{return Err(Error::InvalidQwenShape)}} - // The NaN guard's undo (`discard_window`): the state a window disturbs, as it stands before this one. The device is idle here (the - // previous commit was waited), so these are plain synchronous reads; off, nothing is read. - if self.snapshots.get(){ - let n=OriginalQsaResidentIndex::WINDOW_STATE_BYTES;let mut snapshot=self.snapshot.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?; - snapshot.clear();snapshot.try_reserve_exact(12*n).map_err(|_|Error::HostAllocation)?;snapshot.resize(12*n,0); - for(layer,i)in self.indices.iter().enumerate(){let i=i.try_borrow().map_err(|_|Error::InvalidQwenShape)?;i.read_window_state(&mut snapshot[layer*n..(layer+1)*n])?;} - } - // All immutable borrows above are gone. This single-thread-affine owner - // has no escaping RefMut; the fixed pass performs no fallible allocation. - for i in &self.indices{let mut i=i.borrow_mut();i.in_flight=true;i.unpublished=true;}*live=Live{generation,position,rows,armed:true};Ok(()) - } - /// Recorded before the layer's first append; actual prior tail survives the - /// full provisional window and is restored by the accepted-prefix graph. - pub fn capture_tail_snapshot(&self,journal:&OriginalVerifyGdnJournal<'_, 'ctx>,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize)->Result<()>{ - self.validate_context(journal.context())?;if layer>=12{return Err(Error::InvalidQwenShape)}let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - journal.submit(capture,vec![Command::new("verify_copy_from_mapped_kernel",[1,1,1],[256,1,1],0,vec![Arg::Address(journal.address("tail_snap",layer*1536,1536)?),Arg::Address(i.h(1,0,1536)?.qwen_address()),Arg::I64(96)])?]) - } - /// EXACT Original commit: restore prewindow tail, append all maxT raw rows - /// using accepted positions or -1. No batched-prompt rounding substitution. - pub fn capture_commit_layer(&self,journal:&OriginalVerifyGdnJournal<'_, 'ctx>,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize)->Result<()>{ - self.validate_context(journal.context())?;if layer>=12{return Err(Error::InvalidQwenShape)}let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?;let t=journal.geometry().max_t; - journal.submit(capture,vec![Command::new("verify_copy_from_mapped_kernel",[1,1,1],[256,1,1],0,vec![Arg::Address(i.h(1,0,1536)?.qwen_address()),Arg::Address(journal.address("tail_snap",layer*1536,1536)?),Arg::I64(96)])?])?; - drop(i);self.capture_append(journal,capture,layer,0,t,true) - } - /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the twelve layers' `capture_commit_layer` (tail restore + all `max_t` row appends) in ONE launch (`draft_commit_qsa_layers`, - /// one block per layer, rows in order). Only the analytic RoPE variant (`verify_qsa_append_analytic`) is fused: with retained angle tables it returns `Ok(false)` and records nothing. - pub(crate) fn capture_commit_fused(&self,journal:&OriginalVerifyGdnJournal<'_, 'ctx>,capture:&mut OriginalCapture<'_, 'ctx>)->Result{ - self.validate_context(journal.context())?;let r=self.rope;if r.angles.is_some(){return Ok(false)} - let t=journal.geometry().max_t;if t==0||t>8{return Err(Error::InvalidQwenShape)} - let mut tail=[0u64;12];let mut dead=[0u64;12];let mut pooled=[0u64;12];let mut block_pos=[0u64;12];let mut gamma=[0u64;12]; - for layer in 0..12{ - let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?; - tail[layer]=i.h(1,0,1536)?.qwen_address();dead[layer]=i.h(2,0,512)?.qwen_address(); - pooled[layer]=i.h(0,0,i.image[0].as_ref().ok_or(Error::ContextPoisoned)?.len())?.qwen_address();block_pos[layer]=i.h(3,0,4)?.qwen_address(); - gamma[layer]=whole(self.context,self.gamma[layer],512)?; - } - let raw=journal.address("idx_raw_L",0,512)?;let snap=journal.address("tail_snap",0,1536)?;let commit=journal.address("commit",0,(t+2)*4)?; - // affine layout: the row append of (layer, row) binds idx_raw_L + (layer * t + row) * 512 and the tail snapshot of a layer is at + layer * 1536 (checked at the far end) - if journal.address("idx_raw_L",(11*t+t-1)*512,512)?!=raw+((11*t+t-1)*512)as u64||journal.address("tail_snap",11*1536,1536)?!=snap+(11*1536)as u64 - ||journal.address("commit",(2+t-1)*4,4)?!=commit+((2+t-1)*4)as u64{return Err(Error::InvalidQwenShape)} - let positions=r.positions.map(|b|whole(self.context,b,crate::serving_context::geometry().cells()*12)).transpose()?.unwrap_or(0); - let pack=|a:f32,b:f32|(a.to_bits()as u64)|((b.to_bits()as u64)<<32); - let mut words:Vec=Vec::with_capacity(5*12+7+4); - for v in [&tail,&dead,&pooled,&block_pos,&gamma]{words.extend_from_slice(v)} - words.extend_from_slice(&[raw,snap,commit,positions,t as u64,journal.geometry().max_cells as u64,0]); - words.extend_from_slice(&[pack(1e-6,r.theta_scale),pack(r.freq_scale,r.corr_low),pack(r.corr_high,r.ext_factor),pack(r.magnitude,0.0)]); - journal.submit_launches(capture,vec![crate::original_verify::kernels::Launch::new(&crate::original_verify::draft::DRAFT_COMMIT_QSA,crate::original_verify::draft::E_QSA,[12,1,1],[128,4,1],0, - vec![crate::original_verify::kernels::A::Words(words)])?])?; - Ok(true) - } - /// Original provisional index append, row by row on the SAME captured stream. - /// Caller records the tail snapshot before the first group's append. - pub fn capture_append_rows(&self,journal:&OriginalVerifyGdnJournal<'_, 'ctx>,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize,begin:usize,end:usize)->Result<()>{self.capture_append(journal,capture,layer,begin,end,false)} - fn capture_append(&self,journal:&OriginalVerifyGdnJournal<'_, 'ctx>,capture:&mut OriginalCapture<'_, 'ctx>,layer:usize,begin:usize,end:usize,commit:bool)->Result<()>{ - self.validate_context(journal.context())?;let t=journal.geometry().max_t;if layer>=12||begin>=end||end>t{return Err(Error::InvalidQwenShape)}let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?;let gamma=whole(self.context,self.gamma[layer],512)?; - let mut commands=Vec::new();commands.try_reserve_exact(end-begin).map_err(|_|Error::HostAllocation)?;let r=self.rope; - let (name,cos,sin,max_pos)=match r.angles{Some((c,s,n))=>("verify_qsa_append_table",whole(self.context,c,n*128)?,whole(self.context,s,n*128)?,n as i32),None=>("verify_qsa_append_analytic",0,0,0)}; - let positions=r.positions.map(|b|whole(self.context,b,crate::serving_context::geometry().cells()*12)).transpose()?.unwrap_or(0); - for row in begin..end{commands.push(Command::new(name,[1,1,1],[256,1,1],0,vec![Arg::Address(journal.address("idx_raw_L",(layer*t+row)*512,512)?),Arg::Address(if commit{journal.address("commit",(2+row)*4,4)?}else{journal.address("step",row*16,4)?}),Arg::I32(0),Arg::Address(gamma),Arg::F32(1e-6),Arg::Address(i.h(1,0,1536)?.qwen_address()),Arg::Address(i.h(2,0,512)?.qwen_address()),Arg::Address(i.h(0,0,i.image[0].as_ref().ok_or(Error::ContextPoisoned)?.len())?.qwen_address()),Arg::Address(i.h(3,0,4)?.qwen_address()),Arg::I32(journal.geometry().max_cells as i32),Arg::F32(r.theta_scale),Arg::F32(r.freq_scale),Arg::F32(r.corr_low),Arg::F32(r.corr_high),Arg::F32(r.ext_factor),Arg::F32(r.magnitude),Arg::Address(positions),Arg::Address(cos),Arg::Address(sin),Arg::I32(max_pos)])?);}journal.submit_qsa(capture,commands) - } - /// Publish the K/V half of a verifier window only from the append receipts - /// produced by the full resident QSA sequence. This is deliberately a - /// separate, consuming phase: an indexer graph cannot advance K/V coverage. - pub(crate) fn commit_mapped_prefixes(&self,bank:&OriginalVerifyBank<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>,appended:[OriginalQsaMappedAppend;12])->Result<()>{ - self.validate_context(self.context)?;workspace.validate_context(self.context)?; - let live=self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let(generation,position,rows)=bank.staged_window()?;let keep=bank.staged_keep()?; - if !live.armed||live.generation!=generation||live.position!=position||live.rows!=rows||keep==0||keep>rows{return Err(Error::InvalidQwenShape)} - for(m,a)in self.mapped.iter().zip(appended.iter()){let m=m.try_borrow().map_err(|_|Error::InvalidQwenShape)?;if a.first_position()!=position||a.rows()!=rows||a.final_prefix().next_position()!=position.checked_add(rows).ok_or(Error::InvalidSize)?{return Err(Error::InvalidQwenShape)}m.validate_prefix(a.final_prefix())?;} - drop(live); - for(m,a)in self.mapped.iter().zip(appended){let result=m.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.accept_prefix(workspace,&a,keep);if let Err(e)=result{self.failed.set(true);return Err(e)}} - Ok(()) - } - // Called only by the closed graph bridge after its actual commit receipt. - pub(crate) fn complete_commit(&self,bank:&OriginalVerifyBank<'ctx>)->Result<()>{self.validate_context(self.context)?;let mut live=self.live.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;let (generation,position,rows)=bank.staged_window()?;let keep=bank.staged_keep()?;if !live.armed||live.generation!=generation||live.position!=position||live.rows!=rows||keep==0||keep>rows{return Err(Error::InvalidQwenShape)}let end=position.checked_add(keep).ok_or(Error::InvalidSize)?; - for i in &self.indices{let i=i.try_borrow().map_err(|_|Error::InvalidQwenShape)?;if !i.in_flight||!i.unpublished{return Err(Error::InvalidQwenShape)}} - // The window graph appended the actual K/V (resident pool and host copy) before the index images are made visible; publish - // that K/V half on the host here, after the commit drain, and only then the index half. Do not publish an index-only - // verifier state: every journal must stand at `position` and every one is advanced together. - for m in &self.mapped{if m.try_borrow().map_err(|_|Error::InvalidQwenShape)?.next_position()!=position{return Err(Error::InvalidQwenShape)}} - for m in &self.mapped{m.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.publish_window_rows(position,keep)?;} - for i in &self.indices{let mut i=i.borrow_mut();i.coverage.end.set(i.coverage.end.get().min(position));i.coverage=Rc::new(Coverage{end:Cell::new(end)});i.end=end;i.in_flight=false;i.unpublished=false;}live.armed=false;Ok(()) - } - /// Switch on the per-window snapshots `discard_window` needs (the NaN guard, `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on`). They cost twelve small - /// device-to-host reads and one of the 360 KB PLE history at the start of every window, so they are off unless asked for. - pub fn set_window_snapshots(&self,on:bool){self.snapshots.set(on);} - /// The PLE history image as it stands when a window begins (called right after `begin_window`, device idle); nothing unless the snapshots are on. - pub(crate) fn snapshot_ple(&self,ple:&DeviceBuffer<'ctx>)->Result<()>{ - if !self.snapshots.get(){return Ok(())} - let mut bytes=self.ple_snapshot.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?; - bytes.clear();bytes.try_reserve_exact(ple.len()).map_err(|_|Error::HostAllocation)?;bytes.resize(ple.len(),0); - ple.copy_to_range(0,&mut bytes) - } - /// Undo the armed window that completed on the GPU and that nothing was committed for (the serve loop's NaN guard refused it and wants - /// the same rows run again). What a window disturbs in the index images and the accepted-prefix graph would not put back is the tail, - /// `dead`, the pooled row of the block in progress and the block position (a checkpoint's four pieces; the rows read the spare and the - /// tail from them, so the same rows staged again at the same position read different values if the window left its own), and the PLE - /// history, which every window row advances and only the commit graph sets from the kept row's snapshot (the first live attempt that - /// restored the index state alone got a rerun that differed from the refused window, deterministically, a different one each time): they - /// are written back from the snapshots taken when the window began. Each index then stands at `position` again, published, and the journal can arm - /// the next window. The K/V cells and pooled rows above the block in progress that the window wrote lie beyond every coverage, as after - /// a rejected suffix, and the rerun writes them again before it reads them. The device is idle (the window drained). An error leaves the - /// journal armed. - pub(crate) fn discard_window(&self,bank:&OriginalVerifyBank<'ctx>,ple:Option<&DeviceBuffer<'ctx>>)->Result<()>{ - self.validate_context(self.context)?;bank.validate_context(self.context)?; - let (generation,position,rows)=bank.staged_window()?; - let n=OriginalQsaResidentIndex::WINDOW_STATE_BYTES;let snapshot=self.snapshot.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - if !self.snapshots.get()||snapshot.len()!=12*n{return Err(Error::InvalidQwenShape)} - { - let live=self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - if !live.armed||live.generation!=generation||live.position!=position||live.rows!=rows{return Err(Error::InvalidQwenShape)} - for(i,m)in self.indices.iter().zip(self.mapped.iter()){ - let i=i.try_borrow().map_err(|_|Error::InvalidQwenShape)?;let m=m.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - if !i.in_flight||!i.unpublished||i.end!=position||m.next_position()!=position{return Err(Error::InvalidQwenShape)} - } - } - // the PLE history: the window advanced it row by row, and only the commit graph sets it (from the kept row's snapshot) - let ple_snapshot=self.ple_snapshot.try_borrow().map_err(|_|Error::InvalidQwenShape)?; - if let Some(ple)=ple{if ple_snapshot.len()!=ple.len(){return Err(Error::InvalidQwenShape)}} - for(layer,i)in self.indices.iter().enumerate(){i.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.write_window_state(&snapshot[layer*n..(layer+1)*n])?;} - if let Some(ple)=ple{ple.copy_from_range_shared(0,&ple_snapshot)?;} - let mut live=self.live.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?; - for i in &self.indices{let mut i=i.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;i.in_flight=false;i.unpublished=false;} - live.armed=false;Ok(()) - } - pub(crate) fn abandon_after_drain(&self){self.failed.set(true);for i in &self.indices{if let Ok(mut i)=i.try_borrow_mut(){i.in_flight=false;i.unpublished=true;}}} - /// The real group can be returned only after all captured graphs release it; - /// an abandoned image remains unpublished until genuine checkpoint restore. - pub fn into_owners(owner:Rc)->Result<([OriginalQsaResidentIndex<'ctx>;12],[OriginalQsaMappedJournal<'ctx>;12])>{match Rc::try_unwrap(owner){Ok(s)=>{if s.live.borrow().armed&&!s.failed.get(){return Err(Error::InvalidQwenShape)}Ok((s.indices.map(RefCell::into_inner),s.mapped.map(RefCell::into_inner)))},Err(_)=>Err(Error::InvalidQwenShape)}} +pub struct OriginalVerifyQsaJournal<'a, 'ctx> { + context: &'ctx Context<'ctx>, + indices: [RefCell>; 12], + mapped: [RefCell>; 12], + gamma: [&'a DeviceBuffer<'ctx>; 12], + rope: OriginalVerifyRope<'a, 'ctx>, + live: RefCell, + failed: Cell, + /// `set_window_snapshots`: the index state (12 x `WINDOW_STATE_BYTES`) and the PLE history image at the start of every window, for `discard_window`. + snapshots: Cell, + snapshot: RefCell>, + ple_snapshot: RefCell>, } + +#[path = "qsa_verification_commit/impl_originalverifyrope.rs"] +mod impl_originalverifyrope; +#[allow(unused_imports)] +use impl_originalverifyrope::overlaps; +#[allow(unused_imports)] +use impl_originalverifyrope::whole; +#[path = "qsa_verification_commit/impl_originalverifyqsajournal.rs"] +mod impl_originalverifyqsajournal; +#[path = "qsa_verification_commit/impl_originalverifyqsajournal_2.rs"] +mod impl_originalverifyqsajournal_2; +#[path = "qsa_verification_commit/impl_originalverifyqsajournal_3.rs"] +mod impl_originalverifyqsajournal_3; diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal.rs new file mode 100644 index 00000000..6c759ad6 --- /dev/null +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal.rs @@ -0,0 +1,252 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyQsaJournal. + +#[allow(unused_imports)] +use super::*; + +impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + indices: [OriginalQsaResidentIndex<'ctx>; 12], + mapped: [OriginalQsaMappedJournal<'ctx>; 12], + gamma: [&'a DeviceBuffer<'ctx>; 12], + rope: OriginalVerifyRope<'a, 'ctx>, + ) -> Result> { + let end = indices[0].next_position(); + for (i, m) in indices.iter().zip(mapped.iter()) { + i.validate_context(context)?; + m.validate_context(context)?; + if i.in_flight || i.unpublished || i.end != end || m.next_position() != end { + return Err(Error::InvalidQwenShape); + } + } + for g in gamma { + whole(context, g, 512)?; + for i in &indices { + for b in i.image.iter().flatten() { + if overlaps(g, b)? { + return Err(Error::OutputAliasesInput); + } + } + } + } + rope.validate(context, crate::serving_context::geometry().cells())?; + for i in &indices { + for b in i.image.iter().flatten() { + if let Some(p) = rope.positions { + if overlaps(p, b)? { + return Err(Error::OutputAliasesInput); + } + } + if let Some((cos, sin, _)) = rope.angles { + if overlaps(cos, b)? || overlaps(sin, b)? { + return Err(Error::OutputAliasesInput); + } + } + } + } + Ok(Rc::new(Self { + context, + indices: indices.map(RefCell::new), + mapped: mapped.map(RefCell::new), + gamma, + rope, + live: RefCell::new(Live { generation: 0, position: end, rows: 0, armed: false }), + failed: Cell::new(false), + snapshots: Cell::new(false), + snapshot: RefCell::new(Vec::new()), + ple_snapshot: RefCell::new(Vec::new()), + })) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if self.failed.get() || c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + for (i, m) in self.indices.iter().zip(self.mapped.iter()) { + let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + i.validate_context(c)?; + m.validate_context(c)?; + if i.next_position() != m.next_position() { + return Err(Error::InvalidQwenShape); + } + } + Ok(()) + } + pub(crate) fn identity(&self) -> usize { + self as *const Self as usize + } + /// Only driver siblings can bind actual image pointers into captured kernels. + /// The aggregate retains this actual owner after the short borrow ends. + pub(crate) fn with_image( + &self, + layer: usize, + consume: impl FnOnce([&DeviceBuffer<'ctx>; 4], &DeviceBuffer<'ctx>) -> Result, + ) -> Result { + self.validate_context(self.context)?; + if layer >= 12 { + return Err(Error::InvalidQwenShape); + } + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + consume( + [ + i.image[0].as_ref().ok_or(Error::ContextPoisoned)?, + i.image[1].as_ref().ok_or(Error::ContextPoisoned)?, + i.image[2].as_ref().ok_or(Error::ContextPoisoned)?, + i.image[3].as_ref().ok_or(Error::ContextPoisoned)?, + ], + self.gamma[layer], + ) + } + pub(crate) fn with_committed_index( + &self, + layer: usize, + consume: impl FnOnce(&mut OriginalQsaResidentIndex<'ctx>) -> Result, + ) -> Result { + self.validate_context(self.context)?; + if layer >= 12 || self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed { + return Err(Error::InvalidQwenShape); + } + let mut i = self.indices[layer].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + if i.in_flight || i.unpublished { + return Err(Error::InvalidQwenShape); + } + consume(&mut i) + } + /// `with_committed_index(.., checkpoint)` of all twelve layers in one fenced batch (`checkpoint_fenced_all`): the + /// caller (the verifier) has waited its commit event, the only writer of these images. + pub(crate) fn checkpoint_committed_all( + &self, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<[OriginalQsaIndexCheckpoint<'ctx>; 12]> { + self.validate_context(self.context)?; + if self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed { + return Err(Error::InvalidQwenShape); + } + let mut held = Vec::new(); + held.try_reserve_exact(12).map_err(|_| Error::HostAllocation)?; + for i in &self.indices { + held.push(i.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?) + } + let mut refs: Vec<&mut OriginalQsaResidentIndex<'ctx>> = held.iter_mut().map(|i| &mut **i).collect(); + let saved = OriginalQsaResidentIndex::checkpoint_fenced_all(&mut refs, ws)?; + saved.try_into().map_err(|_| Error::InvalidQwenShape) + } + /// Access to the genuine mapped K/V owner is restricted to the driver graph + /// bridge. A caller cannot mint a prefix from an index snapshot. + pub(crate) fn with_committed_mapped( + &self, + layer: usize, + consume: impl FnOnce(&mut OriginalQsaMappedJournal<'ctx>) -> Result, + ) -> Result { + self.validate_context(self.context)?; + if layer >= 12 || self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed { + return Err(Error::InvalidQwenShape); + } + let mut m = self.mapped[layer].try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + consume(&mut m) + } + /// The resolved Original RoPE constants and optional retained tables (read only). + pub(crate) fn rope(&self) -> OriginalVerifyRope<'a, 'ctx> { + self.rope + } + /// Fixed device addresses the captured window kernels of one QSA layer bind: the streamed INT8 KV + /// (resident pools, page table, host copy, resolver) and the index image's pooled keys and spare key. + /// Read only; the window recorder may call it while a window is armed because no state changes. + pub(crate) fn window_addresses(&self, layer: usize) -> Result { + self.validate_context(self.context)?; + if layer >= 12 { + return Err(Error::InvalidQwenShape); + } + let (resident, table, host, resolver, slots) = + self.mapped[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?.window_kv_addresses()?; + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let pooled = i.image[0].as_ref().ok_or(Error::ContextPoisoned)?; + let dead = i.image[2].as_ref().ok_or(Error::ContextPoisoned)?; + let address = + |b: &DeviceBuffer<'ctx>| -> Result { Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address()) }; + Ok(OriginalVerifyQsaWindowAddresses { + resident, + table, + host, + resolver, + slots, + pooled: address(pooled)?, + pooled_bytes: pooled.len(), + dead: address(dead)?, + dead_bytes: dead.len(), + }) + } + pub fn allocated_bytes(&self) -> usize { + self.indices.iter().map(|i| i.borrow().allocated_bytes()).sum::() + + self.mapped.iter().map(|m| m.borrow().allocated_bytes()).sum::() + } + pub(crate) fn begin_window(&self, bank: &OriginalVerifyBank<'ctx>) -> Result<()> { + self.validate_context(self.context)?; + bank.validate_context(self.context)?; + let mut live = self.live.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + if live.armed { + return Err(Error::InvalidQwenShape); + } + let (generation, position, rows) = bank.staged_window()?; + for (i, m) in self.indices.iter().zip(self.mapped.iter()) { + let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if i.in_flight || i.unpublished || i.end != position || m.next_position() != position { + return Err(Error::InvalidQwenShape); + } + } + // The NaN guard's undo (`discard_window`): the state a window disturbs, as it stands before this one. The device is idle here (the + // previous commit was waited), so these are plain synchronous reads; off, nothing is read. + if self.snapshots.get() { + let n = OriginalQsaResidentIndex::WINDOW_STATE_BYTES; + let mut snapshot = self.snapshot.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + snapshot.clear(); + snapshot.try_reserve_exact(12 * n).map_err(|_| Error::HostAllocation)?; + snapshot.resize(12 * n, 0); + for (layer, i) in self.indices.iter().enumerate() { + let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + i.read_window_state(&mut snapshot[layer * n..(layer + 1) * n])?; + } + } + // All immutable borrows above are gone. This single-thread-affine owner + // has no escaping RefMut; the fixed pass performs no fallible allocation. + for i in &self.indices { + let mut i = i.borrow_mut(); + i.in_flight = true; + i.unpublished = true; + } + *live = Live { generation, position, rows, armed: true }; + Ok(()) + } + /// Recorded before the layer's first append; actual prior tail survives the + /// full provisional window and is restored by the accepted-prefix graph. + pub fn capture_tail_snapshot( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + capture: &mut OriginalCapture<'_, 'ctx>, + layer: usize, + ) -> Result<()> { + self.validate_context(journal.context())?; + if layer >= 12 { + return Err(Error::InvalidQwenShape); + } + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + journal.submit( + capture, + vec![Command::new( + "verify_copy_from_mapped_kernel", + [1, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::Address(journal.address("tail_snap", layer * 1536, 1536)?), + Arg::Address(i.h(1, 0, 1536)?.qwen_address()), + Arg::I64(96), + ], + )?], + ) + } +} diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs new file mode 100644 index 00000000..9e66e855 --- /dev/null +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs @@ -0,0 +1,231 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyQsaJournal (2). + +#[allow(unused_imports)] +use super::*; + +impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { + /// EXACT Original commit: restore prewindow tail, append all maxT raw rows + /// using accepted positions or -1. No batched-prompt rounding substitution. + pub fn capture_commit_layer( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + capture: &mut OriginalCapture<'_, 'ctx>, + layer: usize, + ) -> Result<()> { + self.validate_context(journal.context())?; + if layer >= 12 { + return Err(Error::InvalidQwenShape); + } + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let t = journal.geometry().max_t; + journal.submit( + capture, + vec![Command::new( + "verify_copy_from_mapped_kernel", + [1, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::Address(i.h(1, 0, 1536)?.qwen_address()), + Arg::Address(journal.address("tail_snap", layer * 1536, 1536)?), + Arg::I64(96), + ], + )?], + )?; + drop(i); + self.capture_append(journal, capture, layer, 0, t, true) + } + /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the twelve layers' `capture_commit_layer` (tail restore + all `max_t` row appends) in ONE launch (`draft_commit_qsa_layers`, + /// one block per layer, rows in order). Only the analytic RoPE variant (`verify_qsa_append_analytic`) is fused: with retained angle tables it returns `Ok(false)` and records nothing. + pub(crate) fn capture_commit_fused( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + capture: &mut OriginalCapture<'_, 'ctx>, + ) -> Result { + self.validate_context(journal.context())?; + let r = self.rope; + if r.angles.is_some() { + return Ok(false); + } + let t = journal.geometry().max_t; + if t == 0 || t > 8 { + return Err(Error::InvalidQwenShape); + } + let mut tail = [0u64; 12]; + let mut dead = [0u64; 12]; + let mut pooled = [0u64; 12]; + let mut block_pos = [0u64; 12]; + let mut gamma = [0u64; 12]; + for layer in 0..12 { + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + tail[layer] = i.h(1, 0, 1536)?.qwen_address(); + dead[layer] = i.h(2, 0, 512)?.qwen_address(); + pooled[layer] = i.h(0, 0, i.image[0].as_ref().ok_or(Error::ContextPoisoned)?.len())?.qwen_address(); + block_pos[layer] = i.h(3, 0, 4)?.qwen_address(); + gamma[layer] = whole(self.context, self.gamma[layer], 512)?; + } + let raw = journal.address("idx_raw_L", 0, 512)?; + let snap = journal.address("tail_snap", 0, 1536)?; + let commit = journal.address("commit", 0, (t + 2) * 4)?; + // affine layout: the row append of (layer, row) binds idx_raw_L + (layer * t + row) * 512 and the tail snapshot of a layer is at + layer * 1536 (checked at the far end) + if journal.address("idx_raw_L", (11 * t + t - 1) * 512, 512)? != raw + ((11 * t + t - 1) * 512) as u64 + || journal.address("tail_snap", 11 * 1536, 1536)? != snap + (11 * 1536) as u64 + || journal.address("commit", (2 + t - 1) * 4, 4)? != commit + ((2 + t - 1) * 4) as u64 + { + return Err(Error::InvalidQwenShape); + } + let positions = r + .positions + .map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12)) + .transpose()? + .unwrap_or(0); + let pack = |a: f32, b: f32| (a.to_bits() as u64) | ((b.to_bits() as u64) << 32); + let mut words: Vec = Vec::with_capacity(5 * 12 + 7 + 4); + for v in [&tail, &dead, &pooled, &block_pos, &gamma] { + words.extend_from_slice(v) + } + words.extend_from_slice(&[raw, snap, commit, positions, t as u64, journal.geometry().max_cells as u64, 0]); + words.extend_from_slice(&[ + pack(1e-6, r.theta_scale), + pack(r.freq_scale, r.corr_low), + pack(r.corr_high, r.ext_factor), + pack(r.magnitude, 0.0), + ]); + journal.submit_launches( + capture, + vec![crate::original_verify::kernels::Launch::new( + &crate::original_verify::draft::DRAFT_COMMIT_QSA, + crate::original_verify::draft::E_QSA, + [12, 1, 1], + [128, 4, 1], + 0, + vec![crate::original_verify::kernels::A::Words(words)], + )?], + )?; + Ok(true) + } + /// Original provisional index append, row by row on the SAME captured stream. + /// Caller records the tail snapshot before the first group's append. + pub fn capture_append_rows( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + capture: &mut OriginalCapture<'_, 'ctx>, + layer: usize, + begin: usize, + end: usize, + ) -> Result<()> { + self.capture_append(journal, capture, layer, begin, end, false) + } + pub(super) fn capture_append( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + capture: &mut OriginalCapture<'_, 'ctx>, + layer: usize, + begin: usize, + end: usize, + commit: bool, + ) -> Result<()> { + self.validate_context(journal.context())?; + let t = journal.geometry().max_t; + if layer >= 12 || begin >= end || end > t { + return Err(Error::InvalidQwenShape); + } + let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let gamma = whole(self.context, self.gamma[layer], 512)?; + let mut commands = Vec::new(); + commands.try_reserve_exact(end - begin).map_err(|_| Error::HostAllocation)?; + let r = self.rope; + let (name, cos, sin, max_pos) = match r.angles { + Some((c, s, n)) => ( + "verify_qsa_append_table", + whole(self.context, c, n * 128)?, + whole(self.context, s, n * 128)?, + n as i32, + ), + None => ("verify_qsa_append_analytic", 0, 0, 0), + }; + let positions = r + .positions + .map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12)) + .transpose()? + .unwrap_or(0); + for row in begin..end { + commands.push(Command::new( + name, + [1, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::Address(journal.address("idx_raw_L", (layer * t + row) * 512, 512)?), + Arg::Address(if commit { + journal.address("commit", (2 + row) * 4, 4)? + } else { + journal.address("step", row * 16, 4)? + }), + Arg::I32(0), + Arg::Address(gamma), + Arg::F32(1e-6), + Arg::Address(i.h(1, 0, 1536)?.qwen_address()), + Arg::Address(i.h(2, 0, 512)?.qwen_address()), + Arg::Address(i.h(0, 0, i.image[0].as_ref().ok_or(Error::ContextPoisoned)?.len())?.qwen_address()), + Arg::Address(i.h(3, 0, 4)?.qwen_address()), + Arg::I32(journal.geometry().max_cells as i32), + Arg::F32(r.theta_scale), + Arg::F32(r.freq_scale), + Arg::F32(r.corr_low), + Arg::F32(r.corr_high), + Arg::F32(r.ext_factor), + Arg::F32(r.magnitude), + Arg::Address(positions), + Arg::Address(cos), + Arg::Address(sin), + Arg::I32(max_pos), + ], + )?); + } + journal.submit_qsa(capture, commands) + } + /// Publish the K/V half of a verifier window only from the append receipts + /// produced by the full resident QSA sequence. This is deliberately a + /// separate, consuming phase: an indexer graph cannot advance K/V coverage. + pub(crate) fn commit_mapped_prefixes( + &self, + bank: &OriginalVerifyBank<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + appended: [OriginalQsaMappedAppend; 12], + ) -> Result<()> { + self.validate_context(self.context)?; + workspace.validate_context(self.context)?; + let live = self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let (generation, position, rows) = bank.staged_window()?; + let keep = bank.staged_keep()?; + if !live.armed + || live.generation != generation + || live.position != position + || live.rows != rows + || keep == 0 + || keep > rows + { + return Err(Error::InvalidQwenShape); + } + for (m, a) in self.mapped.iter().zip(appended.iter()) { + let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if a.first_position() != position + || a.rows() != rows + || a.final_prefix().next_position() != position.checked_add(rows).ok_or(Error::InvalidSize)? + { + return Err(Error::InvalidQwenShape); + } + m.validate_prefix(a.final_prefix())?; + } + drop(live); + for (m, a) in self.mapped.iter().zip(appended) { + let result = m.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.accept_prefix(workspace, &a, keep); + if let Err(e) = result { + self.failed.set(true); + return Err(e); + } + } + Ok(()) + } +} diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs new file mode 100644 index 00000000..d69dc422 --- /dev/null +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs @@ -0,0 +1,151 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyQsaJournal (3). + +#[allow(unused_imports)] +use super::*; + +impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { + // Called only by the closed graph bridge after its actual commit receipt. + pub(crate) fn complete_commit(&self, bank: &OriginalVerifyBank<'ctx>) -> Result<()> { + self.validate_context(self.context)?; + let mut live = self.live.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + let (generation, position, rows) = bank.staged_window()?; + let keep = bank.staged_keep()?; + if !live.armed + || live.generation != generation + || live.position != position + || live.rows != rows + || keep == 0 + || keep > rows + { + return Err(Error::InvalidQwenShape); + } + let end = position.checked_add(keep).ok_or(Error::InvalidSize)?; + for i in &self.indices { + let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if !i.in_flight || !i.unpublished { + return Err(Error::InvalidQwenShape); + } + } + // The window graph appended the actual K/V (resident pool and host copy) before the index images are made visible; publish + // that K/V half on the host here, after the commit drain, and only then the index half. Do not publish an index-only + // verifier state: every journal must stand at `position` and every one is advanced together. + for m in &self.mapped { + if m.try_borrow().map_err(|_| Error::InvalidQwenShape)?.next_position() != position { + return Err(Error::InvalidQwenShape); + } + } + for m in &self.mapped { + m.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?.publish_window_rows(position, keep)?; + } + for i in &self.indices { + let mut i = i.borrow_mut(); + i.coverage.end.set(i.coverage.end.get().min(position)); + i.coverage = Rc::new(Coverage { end: Cell::new(end) }); + i.end = end; + i.in_flight = false; + i.unpublished = false; + } + live.armed = false; + Ok(()) + } + /// Switch on the per-window snapshots `discard_window` needs (the NaN guard, `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on`). They cost twelve small + /// device-to-host reads and one of the 360 KB PLE history at the start of every window, so they are off unless asked for. + pub fn set_window_snapshots(&self, on: bool) { + self.snapshots.set(on); + } + /// The PLE history image as it stands when a window begins (called right after `begin_window`, device idle); nothing unless the snapshots are on. + pub(crate) fn snapshot_ple(&self, ple: &DeviceBuffer<'ctx>) -> Result<()> { + if !self.snapshots.get() { + return Ok(()); + } + let mut bytes = self.ple_snapshot.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + bytes.clear(); + bytes.try_reserve_exact(ple.len()).map_err(|_| Error::HostAllocation)?; + bytes.resize(ple.len(), 0); + ple.copy_to_range(0, &mut bytes) + } + /// Undo the armed window that completed on the GPU and that nothing was committed for (the serve loop's NaN guard refused it and wants + /// the same rows run again). What a window disturbs in the index images and the accepted-prefix graph would not put back is the tail, + /// `dead`, the pooled row of the block in progress and the block position (a checkpoint's four pieces; the rows read the spare and the + /// tail from them, so the same rows staged again at the same position read different values if the window left its own), and the PLE + /// history, which every window row advances and only the commit graph sets from the kept row's snapshot (the first live attempt that + /// restored the index state alone got a rerun that differed from the refused window, deterministically, a different one each time): they + /// are written back from the snapshots taken when the window began. Each index then stands at `position` again, published, and the journal can arm + /// the next window. The K/V cells and pooled rows above the block in progress that the window wrote lie beyond every coverage, as after + /// a rejected suffix, and the rerun writes them again before it reads them. The device is idle (the window drained). An error leaves the + /// journal armed. + pub(crate) fn discard_window( + &self, + bank: &OriginalVerifyBank<'ctx>, + ple: Option<&DeviceBuffer<'ctx>>, + ) -> Result<()> { + self.validate_context(self.context)?; + bank.validate_context(self.context)?; + let (generation, position, rows) = bank.staged_window()?; + let n = OriginalQsaResidentIndex::WINDOW_STATE_BYTES; + let snapshot = self.snapshot.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if !self.snapshots.get() || snapshot.len() != 12 * n { + return Err(Error::InvalidQwenShape); + } + { + let live = self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if !live.armed || live.generation != generation || live.position != position || live.rows != rows { + return Err(Error::InvalidQwenShape); + } + for (i, m) in self.indices.iter().zip(self.mapped.iter()) { + let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if !i.in_flight || !i.unpublished || i.end != position || m.next_position() != position { + return Err(Error::InvalidQwenShape); + } + } + } + // the PLE history: the window advanced it row by row, and only the commit graph sets it (from the kept row's snapshot) + let ple_snapshot = self.ple_snapshot.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if let Some(ple) = ple { + if ple_snapshot.len() != ple.len() { + return Err(Error::InvalidQwenShape); + } + } + for (layer, i) in self.indices.iter().enumerate() { + i.try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .write_window_state(&snapshot[layer * n..(layer + 1) * n])?; + } + if let Some(ple) = ple { + ple.copy_from_range_shared(0, &ple_snapshot)?; + } + let mut live = self.live.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + for i in &self.indices { + let mut i = i.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?; + i.in_flight = false; + i.unpublished = false; + } + live.armed = false; + Ok(()) + } + pub(crate) fn abandon_after_drain(&self) { + self.failed.set(true); + for i in &self.indices { + if let Ok(mut i) = i.try_borrow_mut() { + i.in_flight = false; + i.unpublished = true; + } + } + } + /// The real group can be returned only after all captured graphs release it; + /// an abandoned image remains unpublished until genuine checkpoint restore. + pub fn into_owners( + owner: Rc, + ) -> Result<([OriginalQsaResidentIndex<'ctx>; 12], [OriginalQsaMappedJournal<'ctx>; 12])> { + match Rc::try_unwrap(owner) { + Ok(s) => { + if s.live.borrow().armed && !s.failed.get() { + return Err(Error::InvalidQwenShape); + } + Ok((s.indices.map(RefCell::into_inner), s.mapped.map(RefCell::into_inner))) + } + Err(_) => Err(Error::InvalidQwenShape), + } + } +} diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyrope.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyrope.rs new file mode 100644 index 00000000..6e4f0f9c --- /dev/null +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyrope.rs @@ -0,0 +1,46 @@ +//! Moved out of the parent module by STRA-338: impl OriginalVerifyRope, fn whole, fn overlaps. + +#[allow(unused_imports)] +use super::*; + +impl OriginalVerifyRope<'_, '_> { + pub(super) fn validate(&self, c: &Context<'_>, capacity: usize) -> Result<()> { + for v in [self.theta_scale, self.freq_scale, self.corr_low, self.corr_high, self.ext_factor, self.magnitude] { + if !v.is_finite() { + return Err(Error::InvalidQwenShape); + } + } + if self.theta_scale <= 0.0 || self.freq_scale <= 0.0 || self.ext_factor < 0.0 || self.magnitude <= 0.0 { + return Err(Error::InvalidQwenShape); + } + if let Some(p) = self.positions { + whole(c, p, capacity * 3 * 4)?; + } + if let Some((cos, sin, n)) = self.angles { + if n == 0 || n > i32::MAX as usize { + return Err(Error::InvalidSize); + } + let bytes = n.checked_mul(32 * 4).ok_or(Error::InvalidSize)?; + whole(c, cos, bytes)?; + whole(c, sin, bytes)?; + if overlaps(cos, sin)? { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } +} +pub(super) fn whole(c: &Context<'_>, b: &DeviceBuffer<'_>, bytes: usize) -> Result { + if !std::ptr::eq(c, b.context) { + return Err(Error::ContextMismatch); + } + if b.len() != bytes { + return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() }); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 4)?; + Ok(h.qwen_address()) +} +pub(super) fn overlaps(a: &DeviceBuffer<'_>, b: &DeviceBuffer<'_>) -> Result { + Ok(a.handle.ok_or(Error::ContextPoisoned)?.overlaps(a.len(), b.handle.ok_or(Error::ContextPoisoned)?, b.len())) +} diff --git a/crates/cuda-driver/src/qwen_dispatch.rs b/crates/cuda-driver/src/qwen_dispatch.rs index 7ae90737..fce93ff7 100644 --- a/crates/cuda-driver/src/qwen_dispatch.rs +++ b/crates/cuda-driver/src/qwen_dispatch.rs @@ -19,18 +19,9 @@ trait Backend { fn push(&self) -> Result<()>; fn restore(&self) -> Result<()>; fn load(&self, asset: &Asset) -> Result; - fn resolve( - &self, - module: ffi::ModuleHandle, - operation: Operation, - ) -> Result; + fn resolve(&self, module: ffi::ModuleHandle, operation: Operation) -> Result; fn unload(&self, module: ffi::ModuleHandle) -> Result<()>; - fn launch( - &self, - kernel: ffi::FunctionHandle, - operation: Operation, - arguments: &mut Arguments, - ) -> Result<()>; + fn launch(&self, kernel: ffi::FunctionHandle, operation: Operation, arguments: &mut Arguments) -> Result<()>; fn synchronize(&self) -> Result<()>; } struct Admission<'asset> { @@ -47,20 +38,10 @@ mod tests; #[path = "batch_gr_preview.rs"] pub(crate) mod batch_gr_preview; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64", - feature = "cuda-driver" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] mod queued_gr_installed; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64", - feature = "cuda-driver" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] mod gdn_products_installed; #[path = "qwen_shared_tail.rs"] @@ -105,26 +86,26 @@ pub(crate) mod gr_native_batch; mod impl_cache; #[allow(unused_imports)] -use impl_cache::restore; -#[allow(unused_imports)] -use impl_cache::registered; -#[allow(unused_imports)] use impl_cache::execute; #[allow(unused_imports)] use impl_cache::prepare_pair; +#[allow(unused_imports)] +use impl_cache::registered; +#[allow(unused_imports)] +use impl_cache::restore; mod prepare_gr_read_set_fn; +#[allow(unused_imports)] +use prepare_gr_read_set_fn::native_span; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] #[allow(unused_imports)] use prepare_gr_read_set_fn::prepare_gr_read_set; -#[allow(unused_imports)] -use prepare_gr_read_set_fn::unload; #[cfg(test)] #[allow(unused_imports)] use prepare_gr_read_set_fn::ranges; #[allow(unused_imports)] use prepare_gr_read_set_fn::ranges_layout; #[allow(unused_imports)] -use prepare_gr_read_set_fn::native_span; +use prepare_gr_read_set_fn::unload; mod admission_fn; #[allow(unused_imports)] use admission_fn::admission; diff --git a/crates/cuda-driver/src/qwen_dispatch/admission_fn.rs b/crates/cuda-driver/src/qwen_dispatch/admission_fn.rs index bb52e582..163eeea8 100644 --- a/crates/cuda-driver/src/qwen_dispatch/admission_fn.rs +++ b/crates/cuda-driver/src/qwen_dispatch/admission_fn.rs @@ -23,8 +23,7 @@ pub(super) fn admission<'asset>( asset.validate(request.operation)?; let layout = request.layout?; if buffers.len() != layout.count - || (request.operation.has_epsilon() - && (!request.epsilon.is_finite() || request.epsilon < 0.0)) + || (request.operation.has_epsilon() && (!request.epsilon.is_finite() || request.epsilon < 0.0)) { return Err(Error::InvalidQwenShape); } @@ -43,10 +42,7 @@ pub(super) fn admission<'asset>( } Ok((asset, layout, handles)) } -pub(super) fn owned_mtp_scratch<'a, 'd>( - context: &'a Context<'d>, - sizes: [usize; 4], -) -> Result<[DeviceBuffer<'a>; 4]> { +pub(super) fn owned_mtp_scratch<'a, 'd>(context: &'a Context<'d>, sizes: [usize; 4]) -> Result<[DeviceBuffer<'a>; 4]> { let mut owners: [Option>; 4] = std::array::from_fn(|_| None); for (i, size) in sizes.into_iter().enumerate() { match context.allocate(size) { diff --git a/crates/cuda-driver/src/qwen_dispatch/gdn_products_installed.rs b/crates/cuda-driver/src/qwen_dispatch/gdn_products_installed.rs index e67c3c2e..b24015ad 100644 --- a/crates/cuda-driver/src/qwen_dispatch/gdn_products_installed.rs +++ b/crates/cuda-driver/src/qwen_dispatch/gdn_products_installed.rs @@ -16,26 +16,16 @@ fn count_difference(expected: &[Vec; 2], actual: &[Vec; 2]) -> u64 { expected .iter() .zip(actual) - .map(|(x, y)| { - x.chunks_exact(4) - .zip(y.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count() as u64 - }) + .map(|(x, y)| x.chunks_exact(4).zip(y.chunks_exact(4)).filter(|(a, b)| a != b).count() as u64) .sum() } #[test] #[ignore = "Root-only new GDN whole-product transport boundary"] fn original_first_gdn_full_products_exact_and_whole_owner_guards() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GDN_PRODUCTS").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_PRODUCTS").as_deref(), Ok("yes")); let driver = Driver::load().expect("installed driver"); let device = driver.device(0).expect("device"); - let context = device - .create_context(24 * 1024 * 1024) - .expect("bounded context"); + let context = device.create_context(24 * 1024 * 1024).expect("bounded context"); let result: Result<(u64, u32)> = (|| { let mut inputs = [ context.allocate(3145728)?, @@ -114,9 +104,7 @@ fn original_first_gdn_full_products_exact_and_whole_owner_guards() { } let expected = read_pair(&outputs[0], &outputs[1])?; if expected.iter().any(|bytes| { - bytes.chunks_exact(4).any(|b| { - !f32::from_le_bytes(b.try_into().expect("four bytes")).is_finite() - }) + bytes.chunks_exact(4).any(|b| !f32::from_le_bytes(b.try_into().expect("four bytes")).is_finite()) }) { mismatches += 1; } @@ -127,12 +115,10 @@ fn original_first_gdn_full_products_exact_and_whole_owner_guards() { { let [_, _, next, output] = &mut outputs; context.gdn_step_from_products_f32( - &inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], next, - output, + &inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], next, output, )?; } - mismatches += - count_difference(&expected, &read_pair(&outputs[2], &outputs[3])?); + mismatches += count_difference(&expected, &read_pair(&outputs[2], &outputs[3])?); last_expected = Some(expected); last_qk = qk; last_h = h; @@ -153,25 +139,23 @@ fn original_first_gdn_full_products_exact_and_whole_owner_guards() { &inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], next, output, )?; } - mismatches += count_difference( - &last_expected.ok_or(Error::InvalidQwenShape)?, - &read_pair(&outputs[2], &outputs[3])?, - ); + mismatches += + count_difference(&last_expected.ok_or(Error::InvalidQwenShape)?, &read_pair(&outputs[2], &outputs[3])?); let before = read_pair(&outputs[2], &outputs[3])?; // New whole-owner admission must reject both full shape gaps // before writing either next-state or readout candidate. let bad = context.allocate(40956)?; let shape_operation: Result<()> = (|| { let [_, _, next, output] = &mut outputs; - if context.gdn_step_from_products_f32( - &inputs[0], &bad, &inputs[2], &inputs[3], &inputs[4], next, output, - ) != Err(Error::InvalidQwenShape) + if context + .gdn_step_from_products_f32(&inputs[0], &bad, &inputs[2], &inputs[3], &inputs[4], next, output) + != Err(Error::InvalidQwenShape) { mismatches += 1; } - if context.gdn_step_from_products_f32( - &inputs[0], &inputs[1], &bad, &inputs[3], &inputs[4], next, output, - ) != Err(Error::InvalidQwenShape) + if context + .gdn_step_from_products_f32(&inputs[0], &inputs[1], &bad, &inputs[3], &inputs[4], next, output) + != Err(Error::InvalidQwenShape) { mismatches += 1; } @@ -183,9 +167,9 @@ fn original_first_gdn_full_products_exact_and_whole_owner_guards() { let foreign = foreign_context.allocate(40960)?; let context_operation: Result<()> = (|| { let [_, _, next, output] = &mut outputs; - if context.gdn_step_from_products_f32( - &inputs[0], &foreign, &inputs[2], &inputs[3], &inputs[4], next, output, - ) != Err(Error::ContextMismatch) + if context + .gdn_step_from_products_f32(&inputs[0], &foreign, &inputs[2], &inputs[3], &inputs[4], next, output) + != Err(Error::ContextMismatch) { mismatches += 1; } @@ -204,15 +188,7 @@ fn original_first_gdn_full_products_exact_and_whole_owner_guards() { whole.outputs = 0b1100000; let alias = admission( &context, - &[ - &inputs[0], - &inputs[1], - &inputs[2], - &inputs[3], - &inputs[4], - &inputs[0], - &outputs[3], - ], + &[&inputs[0], &inputs[1], &inputs[2], &inputs[3], &inputs[4], &inputs[0], &outputs[3]], Admission { operation: Operation::GdnStep, layout: Ok(whole), diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs b/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs index 8f5b7a02..96654f59 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs @@ -5,9 +5,7 @@ use super::*; impl Cache { pub(in super::super) fn new() -> Self { - Self { - slots: std::array::from_fn(|_| Cell::new(None)), - } + Self { slots: std::array::from_fn(|_| Cell::new(None)) } } } impl Backend for Context<'_> { @@ -21,38 +19,21 @@ impl Backend for Context<'_> { std::mem::forget(Rc::clone(&self.driver.api)); } fn push(&self) -> Result<()> { - self.driver - .api - .push(self.handle.ok_or(Error::ContextPoisoned)?) + self.driver.api.push(self.handle.ok_or(Error::ContextPoisoned)?) } fn restore(&self) -> Result<()> { - self.driver.api.pop().and_then(|h| { - if Some(h) == self.handle { - Ok(()) - } else { - Err(Error::UnexpectedContext) - } - }) + self.driver.api.pop().and_then(|h| if Some(h) == self.handle { Ok(()) } else { Err(Error::UnexpectedContext) }) } fn load(&self, asset: &Asset) -> Result { self.driver.api.load_qwen_module(asset) } - fn resolve( - &self, - module: ffi::ModuleHandle, - operation: Operation, - ) -> Result { + fn resolve(&self, module: ffi::ModuleHandle, operation: Operation) -> Result { self.driver.api.qwen_function(module, operation) } fn unload(&self, module: ffi::ModuleHandle) -> Result<()> { self.driver.api.unload(module) } - fn launch( - &self, - kernel: ffi::FunctionHandle, - operation: Operation, - arguments: &mut Arguments, - ) -> Result<()> { + fn launch(&self, kernel: ffi::FunctionHandle, operation: Operation, arguments: &mut Arguments) -> Result<()> { self.driver.api.launch_qwen(kernel, operation, arguments) } fn synchronize(&self) -> Result<()> { @@ -92,12 +73,7 @@ pub(super) fn registered(backend: &B, cache: &Cache, asset: &Asset) } } } -pub(super) fn execute( - backend: &B, - cache: &Cache, - asset: &Asset, - mut arguments: Arguments, -) -> Result<()> { +pub(super) fn execute(backend: &B, cache: &Cache, asset: &Asset, mut arguments: Arguments) -> Result<()> { if backend.poisoned() { return Err(Error::ContextPoisoned); } diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs index 172a7464..38fe7258 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { /// Source-defined fixed 2560-value embedding RMS normalization. The /// producer validates finite semantic output after completed dispatch. @@ -19,12 +17,7 @@ impl Context<'_> { rs: &mut DeviceBuffer<'_>, injout: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpGrAttentionDown, - &[r, norm, down, inject, lo, rs, injout], - 0.0, - false, - ) + self.qwen_call(Operation::MtpGrAttentionDown, &[r, norm, down, inject, lo, rs, injout], 0.0, false) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. @@ -37,12 +30,7 @@ impl Context<'_> { rs: &DeviceBuffer<'_>, mixed: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpGrAttentionUp, - &[r, norm, up, lo, rs, mixed], - 0.0, - false, - ) + self.qwen_call(Operation::MtpGrAttentionUp, &[r, norm, up, lo, rs, mixed], 0.0, false) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. @@ -58,12 +46,7 @@ impl Context<'_> { rs: &mut DeviceBuffer<'_>, injout: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpGrMlpDown, - &[r, bo, inj, norm, down, inject, lo, rs, injout], - 0.0, - false, - ) + self.qwen_call(Operation::MtpGrMlpDown, &[r, bo, inj, norm, down, inject, lo, rs, injout], 0.0, false) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. @@ -79,12 +62,7 @@ impl Context<'_> { rout: &mut DeviceBuffer<'_>, mixed: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpGrMlpUp, - &[r, bo, inj, norm, up, lo, rs, rout, mixed], - 0.0, - false, - ) + self.qwen_call(Operation::MtpGrMlpUp, &[r, bo, inj, norm, up, lo, rs, rout, mixed], 0.0, false) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. @@ -116,12 +94,7 @@ impl Context<'_> { xscales: &DeviceBuffer<'_>, out: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpS2GateUp, - &[codes, halfscales, q, xscales, out], - 0.0, - false, - ) + self.qwen_call(Operation::MtpS2GateUp, &[codes, halfscales, q, xscales, out], 0.0, false) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. @@ -133,12 +106,7 @@ impl Context<'_> { xscales: &DeviceBuffer<'_>, out: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpS2Down, - &[codes, halfscales, q, xscales, out], - 0.0, - false, - ) + self.qwen_call(Operation::MtpS2Down, &[codes, halfscales, q, xscales, out], 0.0, false) } /// Original512-expert S2 bank; exactly640 gate then640 up results. @@ -188,20 +156,11 @@ impl Context<'_> { in_place: false, }, )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) + execute(self, &self.qwen_kernels, asset, Arguments::with_layout(operation, layout, handles, 0.0)) } #[allow(clippy::too_many_arguments)] // Fixed source ABI operands, not caller selected geometry. - pub fn mtp_swiglu_640( - &self, - gateup: &DeviceBuffer<'_>, - out: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn mtp_swiglu_640(&self, gateup: &DeviceBuffer<'_>, out: &mut DeviceBuffer<'_>) -> Result<()> { self.qwen_call(Operation::MtpS2Swiglu, &[gateup, out], 0.0, false) } pub fn mtp_embedding_norm_f32( @@ -210,12 +169,7 @@ impl Context<'_> { gamma: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpEmbeddingNorm, - &[input, gamma, output], - 0.0, - false, - ) + self.qwen_call(Operation::MtpEmbeddingNorm, &[input, gamma, output], 0.0, false) } /// Normalize all four hidden streams together over exactly 10240 values. pub fn mtp_hidden_norm_f32( @@ -224,12 +178,7 @@ impl Context<'_> { gamma: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpHiddenNorm, - &[input, gamma, output], - 0.0, - false, - ) + self.qwen_call(Operation::MtpHiddenNorm, &[input, gamma, output], 0.0, false) } /// Add the normalized embedding independently to each hidden stream. pub fn mtp_broadcast_f32( @@ -238,11 +187,6 @@ impl Context<'_> { embedding: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MtpBroadcast, - &[hidden, embedding, output], - 0.0, - false, - ) + self.qwen_call(Operation::MtpBroadcast, &[hidden, embedding, output], 0.0, false) } } diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs index e20c0f42..96346fb2 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { - /// Closed causal dense MTP attention, FP16 cell-major K/V in ascending /// window order. Position determines width; scratch and launch dimensions /// are internal. Completion is distinct from producer finite publication. @@ -20,22 +17,15 @@ impl Context<'_> { ) -> Result<()> { let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; - let chunk_asset = - qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; - let merge_asset = - qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; + let chunk_asset = qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; + let merge_asset = qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; chunk_asset.validate(Operation::MtpDenseChunk)?; merge_asset.validate(Operation::MtpDenseMerge)?; if self.poisoned() { return Err(Error::ContextPoisoned); } let inputs = [query, keys, values, &*output]; - let expected = [ - chunk_layout.bytes[0], - chunk_layout.bytes[1], - chunk_layout.bytes[2], - merge_layout.bytes[3], - ]; + let expected = [chunk_layout.bytes[0], chunk_layout.bytes[1], chunk_layout.bytes[2], merge_layout.bytes[3]]; for (i, buffer) in inputs.iter().enumerate() { if !std::ptr::eq(self, buffer.context) { return Err(Error::ContextMismatch); @@ -48,11 +38,7 @@ impl Context<'_> { .validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 }) .map_err(|_| Error::InvalidQwenShape)?; for other in inputs.iter().take(i) { - if handle.overlaps( - buffer.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { + if handle.overlaps(buffer.bytes, other.handle.ok_or(Error::ContextPoisoned)?, other.bytes) { return Err(Error::OutputAliasesInput); } } @@ -61,25 +47,13 @@ impl Context<'_> { .iter() .try_fold(256usize, |sum, size| sum.checked_add(*size)) .ok_or(Error::InvalidQwenShape)?; - if self - .allocated - .get() - .checked_add(scratch) - .is_none_or(|n| n > self.budget) - { + if self.allocated.get().checked_add(scratch).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } // Every allocation is retained by an owner through both synchronized // launches. Existing failed-free charges/poison policy remain active. - let [acc, max, sum, padding] = owned_mtp_scratch( - self, - [ - chunk_layout.bytes[3], - chunk_layout.bytes[4], - chunk_layout.bytes[5], - 256, - ], - )?; + let [acc, max, sum, padding] = + owned_mtp_scratch(self, [chunk_layout.bytes[3], chunk_layout.bytes[4], chunk_layout.bytes[5], 256])?; let result = (|| { let (chunk, cl, ch) = admission( self, @@ -139,10 +113,8 @@ impl Context<'_> { ) -> Result<()> { let chunk_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, position)?; let merge_layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseMerge, position)?; - let chunk_asset = - qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; - let merge_asset = - qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; + let chunk_asset = qwen_ffi::asset(Operation::MtpDenseChunk).ok_or(Error::UnsupportedQwenOperation)?; + let merge_asset = qwen_ffi::asset(Operation::MtpDenseMerge).ok_or(Error::UnsupportedQwenOperation)?; chunk_asset.validate(Operation::MtpDenseChunk)?; merge_asset.validate(Operation::MtpDenseMerge)?; if self.poisoned() { @@ -168,11 +140,7 @@ impl Context<'_> { let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; handle.validate_projection_extent(expected[i], if i < 3 { 16 } else { 4 })?; for other in inputs.iter().take(i) { - if handle.overlaps( - buffer.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { + if handle.overlaps(buffer.bytes, other.handle.ok_or(Error::ContextPoisoned)?, other.bytes) { return Err(Error::OutputAliasesInput); } } @@ -186,25 +154,13 @@ impl Context<'_> { .iter() .try_fold(256usize, |sum, size| sum.checked_add(*size)) .ok_or(Error::InvalidQwenShape)?; - if self - .allocated - .get() - .checked_add(scratch) - .is_none_or(|n| n > self.budget) - { + if self.allocated.get().checked_add(scratch).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } // Every allocation is retained by an owner through both synchronized // launches. Existing failed-free charges/poison policy remain active. - let [acc, max, sum, padding] = owned_mtp_scratch( - self, - [ - chunk_layout.bytes[3], - chunk_layout.bytes[4], - chunk_layout.bytes[5], - 256, - ], - )?; + let [acc, max, sum, padding] = + owned_mtp_scratch(self, [chunk_layout.bytes[3], chunk_layout.bytes[4], chunk_layout.bytes[5], 256])?; let result = (|| { let chunk = chunk_asset; let cl = chunk_layout; diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs index 96f17612..a8e8741e 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { - pub(in super::super) fn kar_ple_call( &self, operation: Operation, @@ -24,22 +21,12 @@ impl Context<'_> { in_place: false, }, )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) + execute(self, &self.qwen_kernels, asset, Arguments::with_layout(operation, layout, handles, 0.0)) } /// Fixed experimental PLE row-cache scatter. Missing qualification refuses /// before native mutation. Zero misses must skip this call. - pub fn kar_ple_scatter( - &self, - cache: &mut DeviceBuffer<'_>, - updates: &DeviceBuffer<'_>, - count: u32, - ) -> Result<()> { + pub fn kar_ple_scatter(&self, cache: &mut DeviceBuffer<'_>, updates: &DeviceBuffer<'_>, count: u32) -> Result<()> { self.kar_ple_call(Operation::KarPleScatter, &[cache, updates], count) } @@ -56,11 +43,7 @@ impl Context<'_> { return Err(Error::InvalidQwenShape); } let parts = u32::try_from(books.bytes / 8).map_err(|_| Error::InvalidQwenShape)?; - self.kar_ple_call( - Operation::KarPleDecode, - &[cache, slots, books, output], - parts, - ) + self.kar_ple_call(Operation::KarPleDecode, &[cache, slots, books, output], parts) } pub(in super::super) fn qsa_call( @@ -73,10 +56,7 @@ impl Context<'_> { // committed assets cannot rotate a scaled context, so a scaled serving context must never reach them. if matches!( operation, - Operation::QsaRopeQ - | Operation::QsaRopeK - | Operation::QsaRopeIndexQ - | Operation::QsaIndexAppend + Operation::QsaRopeQ | Operation::QsaRopeK | Operation::QsaRopeIndexQ | Operation::QsaIndexAppend ) && crate::serving_context::serving_context().rope_is_scaled() { return Err(Error::UnsupportedQwenOperation); @@ -92,12 +72,7 @@ impl Context<'_> { in_place: false, }, )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, 0.0), - ) + execute(self, &self.qwen_kernels, asset, Arguments::with_layout(operation, layout, handles, 0.0)) } /// Closed QSA split q gate; unqualified assets refuse before mutation. @@ -137,31 +112,16 @@ impl Context<'_> { gamma: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::QsaNormIndexQ, - &[input, gamma, output], - 0.0, - false, - ) + self.qwen_call(Operation::QsaNormIndexQ, &[input, gamma, output], 0.0, false) } /// Closed QSA rope q; unqualified assets refuse before mutation. - pub fn qsa_rope_q( - &self, - input: &DeviceBuffer<'_>, - position: u32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn qsa_rope_q(&self, input: &DeviceBuffer<'_>, position: u32, output: &mut DeviceBuffer<'_>) -> Result<()> { self.qsa_call(Operation::QsaRopeQ, &[input, output], position) } /// Closed QSA rope k; unqualified assets refuse before mutation. - pub fn qsa_rope_k( - &self, - input: &DeviceBuffer<'_>, - position: u32, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn qsa_rope_k(&self, input: &DeviceBuffer<'_>, position: u32, output: &mut DeviceBuffer<'_>) -> Result<()> { self.qsa_call(Operation::QsaRopeK, &[input, output], position) } @@ -184,11 +144,7 @@ impl Context<'_> { next: &mut DeviceBuffer<'_>, position: u32, ) -> Result<()> { - self.qsa_call( - Operation::QsaIndexAppend, - &[raw, gamma, prior, next], - position, - ) + self.qsa_call(Operation::QsaIndexAppend, &[raw, gamma, prior, next], position) } /// Closed QSA pack kv; unqualified assets refuse before mutation. @@ -199,12 +155,7 @@ impl Context<'_> { packed_key: &mut DeviceBuffer<'_>, packed_value: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::QsaPackKv, - &[key, value, packed_key, packed_value], - 0.0, - false, - ) + self.qwen_call(Operation::QsaPackKv, &[key, value, packed_key, packed_value], 0.0, false) } /// Closed QSA block scores; unqualified assets refuse before mutation. @@ -216,11 +167,7 @@ impl Context<'_> { scores: &mut DeviceBuffer<'_>, position: u32, ) -> Result<()> { - self.qsa_call( - Operation::QsaBlockScores, - &[pooled, dead, index_query, scores], - position, - ) + self.qsa_call(Operation::QsaBlockScores, &[pooled, dead, index_query, scores], position) } /// Score only the exact initialized prefix of a bounded pooled-key owner. diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs index 4182557f..986c8504 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_4.rs @@ -3,17 +3,9 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { - /// Closed QSA block topk; unqualified assets refuse before mutation. - pub fn qsa_block_topk( - &self, - scores: &DeviceBuffer<'_>, - ids: &mut DeviceBuffer<'_>, - position: u32, - ) -> Result<()> { + pub fn qsa_block_topk(&self, scores: &DeviceBuffer<'_>, ids: &mut DeviceBuffer<'_>, position: u32) -> Result<()> { self.qsa_call(Operation::QsaBlockTopk, &[scores, ids], position) } @@ -26,11 +18,7 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, width: u32, ) -> Result<()> { - self.qsa_call( - Operation::QsaAttend, - &[query, packed_key, packed_value, output], - width, - ) + self.qsa_call(Operation::QsaAttend, &[query, packed_key, packed_value, output], width) } /// Closed QSA gate f32; unqualified assets refuse before mutation. @@ -60,12 +48,7 @@ impl Context<'_> { weights: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MoeSharedScalar, - &[input, weights, output], - 0.0, - false, - ) + self.qwen_call(Operation::MoeSharedScalar, &[input, weights, output], 0.0, false) } /// Scale one shared 2560-value vector by its completed scalar gate. @@ -75,12 +58,7 @@ impl Context<'_> { scalar: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MoeSharedScale, - &[input, scalar, output], - 0.0, - false, - ) + self.qwen_call(Operation::MoeSharedScale, &[input, scalar, output], 0.0, false) } /// Original ordered DOUBLE reduction of ten routed outputs plus shared. @@ -92,12 +70,7 @@ impl Context<'_> { shared: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::MoeCombine, - &[parts, weights, shared, output], - 0.0, - false, - ) + self.qwen_call(Operation::MoeCombine, &[parts, weights, shared, output], 0.0, false) } /// Fixed PLE value projection: BF16-rounded activation, source double sum. @@ -107,12 +80,7 @@ impl Context<'_> { weights: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::PleValue, - &[embedding, weights, output], - 0.0, - false, - ) + self.qwen_call(Operation::PleValue, &[embedding, weights, output], 0.0, false) } /// Complete fixed PLE Value projection; forty CTAs preserve each serial row sum. @@ -122,12 +90,7 @@ impl Context<'_> { weights: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::PleValueFull, - &[embedding, weights, output], - 0.0, - false, - ) + self.qwen_call(Operation::PleValueFull, &[embedding, weights, output], 0.0, false) } /// Four PLE streams with the source's ordinary CUDA normalization profile. @@ -167,12 +130,7 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, next: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::PleConv, - &[prior, normalized, weights, output, next], - 0.0, - false, - ) + self.qwen_call(Operation::PleConv, &[prior, normalized, weights, output, next], 0.0, false) } pub fn ple_residual_f32( @@ -182,12 +140,7 @@ impl Context<'_> { convolution: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::PleResidual, - &[residual, gated, convolution, output], - 0.0, - false, - ) + self.qwen_call(Operation::PleResidual, &[residual, gated, convolution, output], 0.0, false) } /// Fixed decomposed GDN convolution over10240 channels and three prior taps. @@ -200,27 +153,13 @@ impl Context<'_> { raw: &mut DeviceBuffer<'_>, h: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::GdnConv, - &[history, input, weights, next_history, raw, h], - 0.0, - false, - ) + self.qwen_call(Operation::GdnConv, &[history, input, weights, next_history, raw, h], 0.0, false) } /// Normalizes32 Q/K rows. Only the first4096 F32 values are written. - pub fn gdn_qk_l2_f32( - &self, - h: &DeviceBuffer<'_>, - normalized: &mut DeviceBuffer<'_>, - epsilon: f32, - ) -> Result<()> { + pub fn gdn_qk_l2_f32(&self, h: &DeviceBuffer<'_>, normalized: &mut DeviceBuffer<'_>, epsilon: f32) -> Result<()> { self.qwen_call(Operation::GdnQk, &[h, normalized], epsilon, false) } - pub fn gdn_beta_sigmoid_f32( - &self, - beta: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn gdn_beta_sigmoid_f32(&self, beta: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>) -> Result<()> { self.qwen_call(Operation::GdnBeta, &[beta, output], 0.0, false) } pub fn gdn_gate_softplus_f32( @@ -245,11 +184,6 @@ impl Context<'_> { next_state: &mut DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::GdnStep, - &[state, q, k, v, gate, beta, next_state, output], - 0.0, - false, - ) + self.qwen_call(Operation::GdnStep, &[state, q, k, v, gate, beta, next_state, output], 0.0, false) } } diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs index 57f2eb01..70dc638b 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_5.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { /// The unchanged recurrence consumes fixed Q/K/V ranges of completed /// producer allocations. No general buffer view or range is exposed. @@ -41,19 +39,12 @@ impl Context<'_> { let q = owners[1].checked_subspan(40960, 0, 8192)?; let k = owners[1].checked_subspan(40960, 8192, 8192)?; let v = owners[2].checked_subspan(40960, 16384, 24576)?; - let handles = [ - owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0], - ]; + let handles = [owners[0], q, k, v, owners[3], owners[4], owners[5], owners[6], owners[0]]; ranges_layout(Operation::GdnStep, original, handles, original.bytes, false)?; // Same asset, eight-operand ABI, geometry and completed execution as // the original separate-input method. Runtime retains full finite // producer checks and authenticated row ownership before this call. - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(Operation::GdnStep, original, handles, 0.0), - ) + execute(self, &self.qwen_kernels, asset, Arguments::with_layout(Operation::GdnStep, original, handles, 0.0)) } pub fn gdn_out_norm_f32( &self, @@ -63,12 +54,7 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, epsilon: f32, ) -> Result<()> { - self.qwen_call( - Operation::GdnOutNorm, - &[input, z, gamma, output], - epsilon, - false, - ) + self.qwen_call(Operation::GdnOutNorm, &[input, z, gamma, output], epsilon, false) } /// One fixed512-expert/top10 router. Exact whole buffers are logits2048B, /// IDs40B and weights40B; each is aligned4 and owned by this Context. @@ -92,24 +78,21 @@ impl Context<'_> { output: &mut DeviceBuffer<'_>, shape: crate::Bf16ProjectionShape, ) -> Result<()> { - let (asset, layout, handles) = admission( - self, - &[weights, activation, output], - Admission { - operation: Operation::Bf16, - layout: qwen_ffi::bf16_layout(shape.rows, shape.columns), - asset: qwen_ffi::asset(Operation::Bf16), - epsilon: 0.0, - in_place: false, - }, - ) - .map_err(|error| { - if error == Error::InvalidQwenShape { - Error::InvalidBf16ProjectionShape - } else { - error - } - })?; + let (asset, layout, handles) = + admission( + self, + &[weights, activation, output], + Admission { + operation: Operation::Bf16, + layout: qwen_ffi::bf16_layout(shape.rows, shape.columns), + asset: qwen_ffi::asset(Operation::Bf16), + epsilon: 0.0, + in_place: false, + }, + ) + .map_err(|error| { + if error == Error::InvalidQwenShape { Error::InvalidBf16ProjectionShape } else { error } + })?; let arguments = Arguments::with_layout(Operation::Bf16, layout, handles, 0.0); execute(self, &self.qwen_kernels, asset, arguments) } @@ -131,12 +114,7 @@ impl Context<'_> { in_place, }, )?; - execute( - self, - &self.qwen_kernels, - asset, - Arguments::with_layout(operation, layout, handles, epsilon), - ) + execute(self, &self.qwen_kernels, asset, Arguments::with_layout(operation, layout, handles, epsilon)) } pub(in super::super::super) fn unload_qwen_kernels(&self) -> Result<()> { unload(self, &self.qwen_kernels) diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs index c7483580..1a4eb922 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_6.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { - /// Complete one fixed layer GR read using the original five kernels and /// original finite mask. Bit i denotes nonfinite values at stage i; the /// caller uses the first set bit before publishing a stage result. This @@ -93,34 +90,24 @@ impl Context<'_> { for (i, output) in outputs.iter().enumerate() { let handle = output.handle.ok_or(Error::ContextPoisoned)?; for input in inputs { - if handle.overlaps( - output.bytes, - input.handle.ok_or(Error::ContextPoisoned)?, - input.bytes, - ) { + if handle.overlaps(output.bytes, input.handle.ok_or(Error::ContextPoisoned)?, input.bytes) { return Err(Error::OutputAliasesInput); } } for prior in &outputs[..i] { - if handle.overlaps( - output.bytes, - prior.handle.ok_or(Error::ContextPoisoned)?, - prior.bytes, - ) { + if handle.overlaps(output.bytes, prior.handle.ok_or(Error::ContextPoisoned)?, prior.bytes) { return Err(Error::OutputAliasesInput); } } } - if self - .allocated - .get() - .checked_add(4) - .ok_or(Error::InvalidQwenShape)? - > self.budget - { + if self.allocated.get().checked_add(4).ok_or(Error::InvalidQwenShape)? > self.budget { return Err(Error::BudgetExceeded); } - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver")))] + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64", + feature = "cuda-driver" + )))] { return Err(Error::UnsupportedPlatform); } @@ -154,17 +141,10 @@ impl Context<'_> { if commands.is_err() { break; } - commands = self.driver.api.launch_qwen( - kernels[i].function, - assets[i].operation, - argument, - ); + commands = self.driver.api.launch_qwen(kernels[i].function, assets[i].operation, argument); } if commands.is_ok() { - commands = self - .driver - .api - .launch_gr_read_guard(kernels[5].function, &mut finite_arguments); + commands = self.driver.api.launch_gr_read_guard(kernels[5].function, &mut finite_arguments); } if commands.is_ok() { commands = self.driver.api.copy_to(status_handle, &mut readback); @@ -182,12 +162,7 @@ impl Context<'_> { return combine(combine(commands, sync), pop).map(|()| 0); } combine(combine(commands, sync), pop)?; - let mask = u32::from_le_bytes( - readback - .as_slice() - .try_into() - .map_err(|_| Error::InvalidQwenShape)?, - ); + let mask = u32::from_le_bytes(readback.as_slice().try_into().map_err(|_| Error::InvalidQwenShape)?); if mask & !31 != 0 { return Err(Error::InvalidDriverValue("GR finite witness")); } @@ -223,12 +198,7 @@ impl Context<'_> { activation: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::InjectProjection, - &[weights, activation, output], - 0.0, - false, - ) + self.qwen_call(Operation::InjectProjection, &[weights, activation, output], 0.0, false) } /// Weighted RMS over four streams of2560 F32 elements. Epsilon is finite /// and nonnegative (including -0.0), matching the native launch refusal. @@ -243,11 +213,7 @@ impl Context<'_> { self.qwen_call(Operation::Norm, &[residual, gamma, output], epsilon, false) } /// Fixed source-ordered division byHC=4 followed by SiLU on320 F32 values. - pub fn gr_down_silu_hc_f32( - &self, - down: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, - ) -> Result<()> { + pub fn gr_down_silu_hc_f32(&self, down: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>) -> Result<()> { self.qwen_call(Operation::DownSilu, &[down, output], 0.0, false) } } diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs index 46d3ff45..71ffaff9 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_context/impl_context_7.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl Context<'_> { /// Layer GR: separate products and ascending stream fused accumulation. /// xn/gates/products are F32[4,2560], mixed is F32[2560]. @@ -15,12 +13,7 @@ impl Context<'_> { products: &mut DeviceBuffer<'_>, mixed: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::LayerGate, - &[xn, gates, products, mixed], - 0.0, - false, - ) + self.qwen_call(Operation::LayerGate, &[xn, gates, products, mixed], 0.0, false) } /// Final GR: the qualified unfused product/add order, without injection. /// xn/gates/products are F32[4,2560], mixed is F32[2560]. @@ -31,12 +24,7 @@ impl Context<'_> { products: &mut DeviceBuffer<'_>, mixed: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::FinalGate, - &[xn, gates, products, mixed], - 0.0, - false, - ) + self.qwen_call(Operation::FinalGate, &[xn, gates, products, mixed], 0.0, false) } /// Inject shared block_out[2560] with four scalar inject values into a /// separate residual[4,2560] output. All values/storage are F32. @@ -47,12 +35,7 @@ impl Context<'_> { inject: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::InjectResidual, - &[residual, block_out, inject, output], - 0.0, - false, - ) + self.qwen_call(Operation::InjectResidual, &[residual, block_out, inject, output], 0.0, false) } /// Same-element in-place variant of the exact same fixed injection slot. /// The mutable buffer is both R and R_out; no partial alias is admitted. @@ -62,11 +45,6 @@ impl Context<'_> { block_out: &DeviceBuffer<'_>, inject: &DeviceBuffer<'_>, ) -> Result<()> { - self.qwen_call( - Operation::InjectResidual, - &[residual, block_out, inject, residual], - 0.0, - true, - ) + self.qwen_call(Operation::InjectResidual, &[residual, block_out, inject, residual], 0.0, true) } } diff --git a/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs b/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs index f76e6b1a..b96ad4af 100644 --- a/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs +++ b/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs @@ -11,11 +11,7 @@ pub(super) fn prepare_gr_read_set(context: &Context<'_>, assets: [&Asset; 5]) -> use crate::FixedOperation; let guard_slot = context.kernel_slot(FixedOperation::GrReadFinite); let mut kernels: [Option; 6] = std::array::from_fn(|i| { - if i < 5 { - context.qwen_kernels.slots[assets[i].operation as usize].get() - } else { - guard_slot.get() - } + if i < 5 { context.qwen_kernels.slots[assets[i].operation as usize].get() } else { guard_slot.get() } }); let mut pending = [None; 6]; context.push()?; @@ -27,10 +23,7 @@ pub(super) fn prepare_gr_read_set(context: &Context<'_>, assets: [&Asset; 5]) -> let module = if i < 5 { context.load(assets[i]) } else { - context - .driver - .api - .load_fixed_module(FixedOperation::GrReadFinite) + context.driver.api.load_fixed_module(FixedOperation::GrReadFinite) }; let module = match module { Ok(module) => module, @@ -42,10 +35,7 @@ pub(super) fn prepare_gr_read_set(context: &Context<'_>, assets: [&Asset; 5]) -> let function = if i < 5 { context.resolve(module, assets[i].operation) } else { - context - .driver - .api - .fixed_function(module, FixedOperation::GrReadFinite) + context.driver.api.fixed_function(module, FixedOperation::GrReadFinite) }; // Retain every loaded module before any later fallible operation. match function { @@ -154,21 +144,13 @@ pub(super) fn ranges_layout( || (operation != Operation::Bf16 && elements > i32::MAX as usize) || layout.grid == 0 || layout.grid > i32::MAX as u32 - || layout.shared_bytes - != if operation == Operation::QsaAttend { - 8332 - } else { - 0 - } + || layout.shared_bytes != if operation == Operation::QsaAttend { 8332 } else { 0 } || layout.grid_y == 0 || layout.grid_y > i32::MAX as u32 || layout.grid_z == 0 || layout.grid_z > i32::MAX as u32 || layout.block == 0 - || layout - .block - .checked_mul(layout.block_y) - .is_none_or(|threads| threads == 0 || threads > 1024) + || layout.block.checked_mul(layout.block_y).is_none_or(|threads| threads == 0 || threads > 1024) { return Err(Error::InvalidQwenShape); } @@ -182,25 +164,20 @@ pub(super) fn ranges_layout( if operation != Operation::Bf16 { native_span(bytes[i])?; } - handles[i] - .validate_projection_extent(bytes[i], layout.align[i]) - .map_err(|_| Error::InvalidQwenShape)?; + handles[i].validate_projection_extent(bytes[i], layout.align[i]).map_err(|_| Error::InvalidQwenShape)?; } if in_place && operation != Operation::InjectResidual { return Err(Error::OutputAliasesInput); } for i in 0..layout.count { for j in i + 1..layout.count { - if !matches!( - operation, - Operation::KarPleScatter | Operation::KarPleDecode - ) && layout.outputs & ((1 << i) | (1 << j)) == 0 + if !matches!(operation, Operation::KarPleScatter | Operation::KarPleDecode) + && layout.outputs & ((1 << i) | (1 << j)) == 0 { continue; } if handles[i].overlaps(bytes[i], handles[j], bytes[j]) { - if in_place && i == 0 && j == 3 && handles[0] == handles[3] && bytes[0] == bytes[3] - { + if in_place && i == 0 && j == 3 && handles[0] == handles[3] && bytes[0] == bytes[3] { continue; } return Err(Error::OutputAliasesInput); @@ -213,9 +190,5 @@ pub(super) fn native_span(bytes: usize) -> Result<()> { // Bound the greatest byte offset, not merely each dimension separately. // Current GR v1 arrays are smaller; future signed-address PTX cannot // silently inherit a weaker product-only admission rule. - if bytes == 0 || bytes - 1 > i32::MAX as usize { - Err(Error::InvalidQwenShape) - } else { - Ok(()) - } + if bytes == 0 || bytes - 1 > i32::MAX as usize { Err(Error::InvalidQwenShape) } else { Ok(()) } } diff --git a/crates/cuda-driver/src/qwen_dispatch/queued_gr_installed.rs b/crates/cuda-driver/src/qwen_dispatch/queued_gr_installed.rs index d8729c5d..d3f4418c 100644 --- a/crates/cuda-driver/src/qwen_dispatch/queued_gr_installed.rs +++ b/crates/cuda-driver/src/qwen_dispatch/queued_gr_installed.rs @@ -13,9 +13,7 @@ fn execute_read( let [residual, gamma, dw, uw] = inputs; let [xn, down, activated, gates, products, mixed] = outputs; if queued { - context.gr_read_chain_queued( - residual, gamma, dw, uw, epsilon, xn, down, activated, gates, products, mixed, - ) + context.gr_read_chain_queued(residual, gamma, dw, uw, epsilon, xn, down, activated, gates, products, mixed) } else { context.gr_norm_f32(residual, gamma, epsilon, xn)?; context.gr_down_projection_bf16_f32(dw, xn, down)?; @@ -38,11 +36,8 @@ fn read_outputs(outputs: &[DeviceBuffer<'_>; 6]) -> Result>> { fn residual_bytes(pattern: usize) -> Vec { (0..10240usize) .flat_map(|i| { - let x = if pattern == 0 { - if i % 2 == 0 { 0.0f32 } else { -0.0f32 } - } else { - ((i % 37) as f32 - 18.0) / 32.0 - }; + let x = + if pattern == 0 { if i % 2 == 0 { 0.0f32 } else { -0.0f32 } } else { ((i % 37) as f32 - 18.0) / 32.0 }; x.to_le_bytes() }) .collect() @@ -50,15 +45,10 @@ fn residual_bytes(pattern: usize) -> Vec { #[test] #[ignore = "Root-only new same-kernel queued GR completion boundary"] fn original_first_queued_gr_read_exact_and_status_reset() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_QUEUED_GR").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_QUEUED_GR").as_deref(), Ok("yes")); let driver = Driver::load().expect("installed driver"); let device = driver.device(0).expect("device"); - let context = device - .create_context(32 * 1024 * 1024) - .expect("bounded context"); + let context = device.create_context(32 * 1024 * 1024).expect("bounded context"); let result: Result<(u64, u32)> = (|| { let mut inputs = [ context.allocate(40960)?, @@ -76,20 +66,14 @@ fn original_first_queued_gr_read_exact_and_status_reset() { ]; let operation: Result<(u64, u32)> = (|| { inputs[1].copy_from( - &(0..10240usize) - .flat_map(|i| (1.0f32 + (i % 7) as f32 / 16.0).to_le_bytes()) - .collect::>(), + &(0..10240usize).flat_map(|i| (1.0f32 + (i % 7) as f32 / 16.0).to_le_bytes()).collect::>(), )?; // Sanitized exact BF16 powers and sign bits, independent of // candidate outputs. Original admitted kernels are the oracle. for (role, weight) in inputs[2..].iter_mut().enumerate() { let bytes: Vec<_> = (0..3276800usize) .flat_map(|i| { - let bits = if (i + role) % 3 == 0 { - 0x3b00u16 - } else { - 0xbb00u16 - }; + let bits = if (i + role) % 3 == 0 { 0x3b00u16 } else { 0xbb00u16 }; bits.to_le_bytes() }) .collect(); @@ -108,20 +92,14 @@ fn original_first_queued_gr_read_exact_and_status_reset() { mismatches += 1; } for (x, y) in expected.iter().zip(&actual) { - mismatches += x - .chunks_exact(4) - .zip(y.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count() as u64; + mismatches += x.chunks_exact(4).zip(y.chunks_exact(4)).filter(|(a, b)| a != b).count() as u64; } if pattern == 1 { reset_expected = Some(expected); } } let before = read_outputs(&outputs)?; - if execute_read(&context, &inputs, &mut outputs, true, -1.0) - != Err(Error::InvalidQwenShape) - { + if execute_read(&context, &inputs, &mut outputs, true, -1.0) != Err(Error::InvalidQwenShape) { mismatches += 1; } if read_outputs(&outputs)? != before { diff --git a/crates/cuda-driver/src/qwen_dispatch/tests.rs b/crates/cuda-driver/src/qwen_dispatch/tests.rs index 2a4f1393..f17a95a6 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests.rs @@ -3,12 +3,8 @@ use super::*; use std::cell::RefCell; -const MOE_OPERATIONS: [Operation; 4] = [ - Operation::MoeSwiglu, - Operation::MoeSharedScalar, - Operation::MoeSharedScale, - Operation::MoeCombine, -]; +const MOE_OPERATIONS: [Operation; 4] = + [Operation::MoeSwiglu, Operation::MoeSharedScalar, Operation::MoeSharedScale, Operation::MoeCombine]; #[derive(Default)] struct Mock { @@ -19,21 +15,11 @@ struct Mock { } impl Mock { fn fault(faults: &[&'static str]) -> Self { - Self { - faults: faults.to_vec(), - ..Self::default() - } + Self { faults: faults.to_vec(), ..Self::default() } } fn call(&self, operation: &'static str) -> Result<()> { self.trace.borrow_mut().push(operation); - if self.faults.contains(&operation) { - Err(Error::Driver { - operation, - code: 71, - }) - } else { - Ok(()) - } + if self.faults.contains(&operation) { Err(Error::Driver { operation, code: 71 }) } else { Ok(()) } } } impl Backend for Mock { @@ -54,26 +40,14 @@ impl Backend for Mock { } fn load(&self, _: &Asset) -> Result { self.call("load")?; - ffi::ModuleHandle::qwen_success(if self.faults.contains(&"null_module") { - 0 - } else { - 11 - }) + ffi::ModuleHandle::qwen_success(if self.faults.contains(&"null_module") { 0 } else { 11 }) } - fn resolve( - &self, - _: ffi::ModuleHandle, - operation: Operation, - ) -> Result { + fn resolve(&self, _: ffi::ModuleHandle, operation: Operation) -> Result { self.call("lookup")?; if operation == Operation::MtpDenseMerge && self.faults.contains(&"lookup_merge") { return Err(error("lookup_merge")); } - ffi::FunctionHandle::qwen_success(if self.faults.contains(&"null_function") { - 0 - } else { - 22 - }) + ffi::FunctionHandle::qwen_success(if self.faults.contains(&"null_function") { 0 } else { 22 }) } fn unload(&self, _: ffi::ModuleHandle) -> Result<()> { self.call("unload") @@ -88,11 +62,8 @@ impl Backend for Mock { fn arguments(op: Operation) -> Arguments { Arguments::new( op, - [ - 0x1000000, 0x2000000, 0x3000000, 0x4000000, 0x5000000, 0x6000000, 0x7000000, - 0x8000000, 0x9000000, - ] - .map(ffi::BufferHandle::synthetic), + [0x1000000, 0x2000000, 0x3000000, 0x4000000, 0x5000000, 0x6000000, 0x7000000, 0x8000000, 0x9000000] + .map(ffi::BufferHandle::synthetic), 1e-6, ) } @@ -100,25 +71,19 @@ fn ready(cache: &Cache) -> usize { cache.slots.iter().filter(|s| s.get().is_some()).count() } fn error(operation: &'static str) -> Error { - Error::Driver { - operation, - code: 71, - } + Error::Driver { operation, code: 71 } } fn nested(primary: Error, secondary: Error) -> Error { - Error::Multiple { - primary: Box::new(primary), - secondary: Box::new(secondary), - } + Error::Multiple { primary: Box::new(primary), secondary: Box::new(secondary) } } #[path = "tests/full_s2_bank_extent.rs"] mod full_s2_bank_extent; -#[path = "tests/qsa_new_slots_keep_atomic.rs"] -mod qsa_new_slots_keep_atomic; #[path = "tests/moe_new_preflight_requires_exact.rs"] mod moe_new_preflight_requires_exact; -#[path = "tests/qwen_attempted_launch_always_syncs.rs"] -mod qwen_attempted_launch_always_syncs; +#[path = "tests/qsa_new_slots_keep_atomic.rs"] +mod qsa_new_slots_keep_atomic; #[path = "tests/qwen_actual_owner_poison_missing.rs"] mod qwen_actual_owner_poison_missing; +#[path = "tests/qwen_attempted_launch_always_syncs.rs"] +mod qwen_attempted_launch_always_syncs; diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs b/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs index 95d52130..59b9f1a7 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs @@ -8,18 +8,13 @@ fn full_s2_bank_extent_and_output_refusals() { for operation in [Operation::MtpS2GateUpFull, Operation::MtpS2DownFull] { let layout = qwen_ffi::mtp_s2_full_layout(operation, 511).unwrap(); // Distinct synthetic ranges; no707MB host/device allocation. - let handles = std::array::from_fn(|i| { - ffi::BufferHandle::synthetic(0x1_0000_0000 * (i as u64 + 1)) - }); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x1_0000_0000 * (i as u64 + 1))); ranges_layout(operation, layout, handles, layout.bytes, false).unwrap(); for i in 0..layout.count { for difference in [-1i64, 1] { let mut bytes = layout.bytes; bytes[i] = (bytes[i] as i64 + difference) as usize; - assert_eq!( - ranges_layout(operation, layout, handles, bytes, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, handles, bytes, false), Err(Error::InvalidQwenShape)); } if i != 3 { let mut aliased = handles; @@ -31,10 +26,7 @@ fn full_s2_bank_extent_and_output_refusals() { } } // Full-bank slots are admitted only by their independent actual-GPU receipt. - qwen_ffi::asset(operation) - .expect("qualified full S2 asset") - .validate(operation) - .unwrap(); + qwen_ffi::asset(operation).expect("qualified full S2 asset").validate(operation).unwrap(); } } @@ -50,16 +42,12 @@ fn mtp_new_ninth_output_and_scale_extent_refuse() { Operation::MtpS2Swiglu, ] { let layout = operation.layout(); - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000)); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000)); ranges_layout(operation, layout, handles, layout.bytes, false).unwrap(); for i in 0..layout.count { let mut short = layout.bytes; short[i] -= 1; - assert_eq!( - ranges_layout(operation, layout, handles, short, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); if layout.outputs & (1 << i) != 0 { let mut aliased = handles; aliased[i] = handles[0]; @@ -78,12 +66,7 @@ fn kar_ple_qualified_receipt_corruption_refuses_before_mutation() { let qualified = qwen_ffi::asset(operation).unwrap(); qualified.validate(operation).unwrap(); for change in 0..4 { - let mut invalid = Asset { - operation, - ptx: qualified.ptx, - receipt: qualified.receipt, - pin: qualified.pin, - }; + let mut invalid = Asset { operation, ptx: qualified.ptx, receipt: qualified.receipt, pin: qualified.pin }; match change { 0 => invalid.receipt.source_sha256[0] ^= 1, 1 => invalid.receipt.oracle_sha256[0] ^= 1, @@ -92,10 +75,7 @@ fn kar_ple_qualified_receipt_corruption_refuses_before_mutation() { } let backend = Mock::default(); let cache = Cache::new(); - assert_eq!( - execute(&backend, &cache, &invalid, arguments(operation)), - Err(Error::UnsupportedQwenOperation) - ); + assert_eq!(execute(&backend, &cache, &invalid, arguments(operation)), Err(Error::UnsupportedQwenOperation)); assert!(backend.trace.borrow().is_empty()); assert_eq!(ready(&cache), 0); } @@ -104,24 +84,14 @@ fn kar_ple_qualified_receipt_corruption_refuses_before_mutation() { #[test] fn kar_ple_whole_spans_require_all_disjoint_allocations() { - for (operation, value) in [ - (Operation::KarPleScatter, 16), - (Operation::KarPleDecode, 65_535), - ] { + for (operation, value) in [(Operation::KarPleScatter, 16), (Operation::KarPleDecode, 65_535)] { let layout = qwen_ffi::kar_ple_layout(operation, value).unwrap(); - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, false), - Ok(()) - ); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); for i in 0..layout.count { let mut short = layout.bytes; short[i] -= 1; - assert_eq!( - ranges_layout(operation, layout, handles, short, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); if layout.align[i] > 1 { let mut misaligned = handles; misaligned[i] = ffi::BufferHandle::synthetic(handles[i].qwen_address() + 1); @@ -141,14 +111,8 @@ fn kar_ple_whole_spans_require_all_disjoint_allocations() { } let mut overflow = handles; overflow[0] = ffi::BufferHandle::synthetic(u64::MAX - 63); - assert_eq!( - ranges_layout(operation, layout, overflow, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, true), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges_layout(operation, layout, overflow, layout.bytes, false), Err(Error::InvalidQwenShape)); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, true), Err(Error::OutputAliasesInput)); } } @@ -161,10 +125,7 @@ fn kar_ple_whole_spans_require_all_disjoint_allocations() { fn kar_ple_qualified_public_calls_refuse_unsupported_platform_preserve_owner_and_cache() { use crate::{Driver, FixedPairKernels, ProjectionKernels}; use std::marker::PhantomData; - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let context = Context { driver: &driver, handle: Some(ffi::ContextHandle::synthetic(1)), @@ -177,9 +138,7 @@ fn kar_ple_qualified_public_calls_refuse_unsupported_platform_preserve_owner_and q5_k_kernel: Cell::>::new(None), q6_k_kernel: Cell::new(None), common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| { - Cell::>::new(None) - }), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), qwen_kernels: Cache::new(), }; let buffer = |address, bytes| DeviceBuffer { @@ -194,28 +153,13 @@ fn kar_ple_qualified_public_calls_refuse_unsupported_platform_preserve_owner_and let mut slots = buffer(0x30000000, 64); let mut books = buffer(0x40000000, 8); let mut out = buffer(0x50000000, 10_240); - assert_eq!( - context.kar_ple_scatter(&mut cache, &updates, 1), - Err(Error::UnsupportedPlatform) - ); - assert_eq!( - context.kar_ple_decode(&cache, &slots, &books, &mut out), - Err(Error::UnsupportedPlatform) - ); + assert_eq!(context.kar_ple_scatter(&mut cache, &updates, 1), Err(Error::UnsupportedPlatform)); + assert_eq!(context.kar_ple_decode(&cache, &slots, &books, &mut out), Err(Error::UnsupportedPlatform)); assert_eq!(context.allocated.get(), 67_119_176); assert!(!context.poisoned.get()); - assert!( - context - .qwen_kernels - .slots - .iter() - .all(|slot| slot.get().is_none()) - ); + assert!(context.qwen_kernels.slots.iter().all(|slot| slot.get().is_none())); context.poisoned.set(true); - assert_eq!( - context.kar_ple_scatter(&mut cache, &updates, 1), - Err(Error::ContextPoisoned) - ); + assert_eq!(context.kar_ple_scatter(&mut cache, &updates, 1), Err(Error::ContextPoisoned)); context.poisoned.set(false); // Synthetic buffers never own real device allocations. for b in [&mut cache, &mut updates, &mut slots, &mut books, &mut out] { @@ -226,25 +170,14 @@ fn kar_ple_qualified_public_calls_refuse_unsupported_platform_preserve_owner_and #[test] fn qsa_new_preflight_checks_whole_spans_aliases_and_fixed_shared_memory() { for operation in qwen_ffi::QSA_OPERATIONS { - let value = if operation == Operation::QsaAttend { - 2051 - } else { - crate::MAX_CONTEXT_CELLS as u32 - 1 - }; + let value = if operation == Operation::QsaAttend { 2051 } else { crate::MAX_CONTEXT_CELLS as u32 - 1 }; let layout = qwen_ffi::qsa_layout(operation, value).unwrap(); - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, false), - Ok(()) - ); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); for output in (0..layout.count).filter(|i| layout.outputs & (1 << i) != 0) { let mut short = layout.bytes; short[output] -= 1; - assert_eq!( - ranges_layout(operation, layout, handles, short, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); for input in 0..layout.count { if input == output { continue; @@ -259,23 +192,11 @@ fn qsa_new_preflight_checks_whole_spans_aliases_and_fixed_shared_memory() { } let mut wrapped = handles; wrapped[0] = ffi::BufferHandle::synthetic(u64::MAX - 3); - assert_eq!( - ranges_layout(operation, layout, wrapped, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, wrapped, layout.bytes, false), Err(Error::InvalidQwenShape)); let mut malformed = layout; malformed.shared_bytes = if layout.shared_bytes == 0 { 8332 } else { 0 }; - assert_eq!( - ranges_layout(operation, malformed, handles, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, true), - Err(Error::OutputAliasesInput) - ); - qwen_ffi::asset(operation) - .expect("qualified QSA component") - .validate(operation) - .unwrap(); + assert_eq!(ranges_layout(operation, malformed, handles, layout.bytes, false), Err(Error::InvalidQwenShape)); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, true), Err(Error::OutputAliasesInput)); + qwen_ffi::asset(operation).expect("qualified QSA component").validate(operation).unwrap(); } } diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs b/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs index 8005b27f..001c59a8 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs @@ -3,43 +3,29 @@ #[allow(unused_imports)] use super::*; - #[test] fn moe_new_preflight_requires_exact_disjoint_owner_spans() { - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))); for operation in MOE_OPERATIONS { let layout = operation.layout(); assert_eq!(ranges(operation, handles, layout.bytes, false), Ok(())); for index in 0..layout.count { let mut short = layout.bytes; short[index] -= 1; - assert_eq!( - ranges(operation, handles, short, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges(operation, handles, short, false), Err(Error::InvalidQwenShape)); for address in [handles[index].qwen_address() + 1, u64::MAX - 1] { let mut wrong = handles; wrong[index] = ffi::BufferHandle::synthetic(address); - assert_eq!( - ranges(operation, wrong, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges(operation, wrong, layout.bytes, false), Err(Error::InvalidQwenShape)); } } let output = layout.count - 1; for input in 0..output { let mut aliased = handles; aliased[output] = handles[input]; - assert_eq!( - ranges(operation, aliased, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(operation, aliased, layout.bytes, false), Err(Error::OutputAliasesInput)); } - assert_eq!( - ranges(operation, handles, layout.bytes, true), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(operation, handles, layout.bytes, true), Err(Error::OutputAliasesInput)); } } @@ -53,10 +39,7 @@ fn moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order() { execute(&backend, &cache, &asset, arguments(operation)).unwrap(); assert_eq!( *backend.trace.borrow(), - [ - "push", "load", "lookup", "launch", "sync", "restore", "push", "launch", - "sync", "restore" - ] + ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] ); assert_eq!(ready(&cache), 1); @@ -64,38 +47,23 @@ fn moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order() { let cache = Cache::new(); assert_eq!( execute(&backend, &cache, &asset, arguments(operation)), - Err(nested( - nested(error("lookup"), error("unload")), - error("restore") - )) + Err(nested(nested(error("lookup"), error("unload")), error("restore"))) ); assert_eq!(ready(&cache), 0); - assert_eq!( - *backend.trace.borrow(), - ["push", "load", "lookup", "unload", "restore"] - ); + assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); assert!(backend.poisoned()); let backend = Mock::fault(&["launch", "sync", "restore"]); let cache = Cache::new(); assert_eq!( execute(&backend, &cache, &asset, arguments(operation)), - Err(nested( - nested(error("launch"), error("sync")), - error("restore") - )) - ); - assert_eq!( - *backend.trace.borrow(), - ["push", "load", "lookup", "launch", "sync", "restore"] + Err(nested(nested(error("launch"), error("sync")), error("restore"))) ); + assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "launch", "sync", "restore"]); assert!(backend.poisoned()); assert!(backend.retained.get() > 0); let trace = backend.trace.borrow().clone(); - assert_eq!( - execute(&backend, &cache, &asset, arguments(operation)), - Err(Error::ContextPoisoned) - ); + assert_eq!(execute(&backend, &cache, &asset, arguments(operation)), Err(Error::ContextPoisoned)); assert_eq!(*backend.trace.borrow(), trace); } } @@ -104,37 +72,18 @@ fn moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order() { fn gdn_fixed_abi_keeps_recurrent_order_and_refuses_prior_output_alias() { let operation = Operation::GdnStep; let layout = operation.layout(); - assert_eq!( - layout.bytes, - [3145728, 8192, 8192, 24576, 192, 192, 3145728, 24576, 0] - ); - assert_eq!( - (layout.grid, layout.grid_z, layout.block, layout.block_y), - (48, 32, 32, 4) - ); + assert_eq!(layout.bytes, [3145728, 8192, 8192, 24576, 192, 192, 3145728, 24576, 0]); + assert_eq!((layout.grid, layout.grid_z, layout.block, layout.block_y), (48, 32, 32, 4)); assert_eq!((layout.count, layout.outputs), (8, 0b11000000)); - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, false), - Ok(()) - ); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); let mut aliased = handles; aliased[6] = handles[0]; - assert_eq!( - ranges_layout(operation, layout, aliased, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges_layout(operation, layout, aliased, layout.bytes, false), Err(Error::OutputAliasesInput)); let mut shortened = layout.bytes; shortened[7] -= 4; - assert_eq!( - ranges_layout(operation, layout, handles, shortened, false), - Err(Error::InvalidQwenShape) - ); - qwen_ffi::asset(operation) - .expect("separately admitted163 component") - .validate(operation) - .unwrap(); + assert_eq!(ranges_layout(operation, layout, handles, shortened, false), Err(Error::InvalidQwenShape)); + qwen_ffi::asset(operation).expect("separately admitted163 component").validate(operation).unwrap(); } #[test] fn qwen_fixed_slots_atomic_cache_and_no_quantizer() { @@ -147,35 +96,15 @@ fn qwen_fixed_slots_atomic_cache_and_no_quantizer() { } assert_eq!(ready(&cache), OPERATIONS.len()); let trace = backend.trace.borrow(); - assert_eq!( - trace.iter().filter(|&&x| x == "load").count(), - OPERATIONS.len() - ); - assert_eq!( - trace.iter().filter(|&&x| x == "lookup").count(), - OPERATIONS.len() - ); - assert_eq!( - trace.iter().filter(|&&x| x == "launch").count(), - 2 * OPERATIONS.len() - ); - assert_eq!( - trace.iter().filter(|&&x| x == "sync").count(), - 2 * OPERATIONS.len() - ); + assert_eq!(trace.iter().filter(|&&x| x == "load").count(), OPERATIONS.len()); + assert_eq!(trace.iter().filter(|&&x| x == "lookup").count(), OPERATIONS.len()); + assert_eq!(trace.iter().filter(|&&x| x == "launch").count(), 2 * OPERATIONS.len()); + assert_eq!(trace.iter().filter(|&&x| x == "sync").count(), 2 * OPERATIONS.len()); drop(trace); unload(&backend, &cache).unwrap(); unload(&backend, &cache).unwrap(); assert_eq!(ready(&cache), 0); - assert_eq!( - backend - .trace - .borrow() - .iter() - .filter(|&&x| x == "unload") - .count(), - OPERATIONS.len() - ); + assert_eq!(backend.trace.borrow().iter().filter(|&&x| x == "unload").count(), OPERATIONS.len()); } #[test] fn qwen_load_lookup_faults_never_publish_partial_slot() { @@ -189,10 +118,7 @@ fn qwen_load_lookup_faults_never_publish_partial_slot() { function: ffi::FunctionHandle::synthetic(100), })); let asset = qwen_ffi::mock_asset(op); - assert_eq!( - execute(&backend, &cache, &asset, arguments(op)), - Err(error(fault)) - ); + assert_eq!(execute(&backend, &cache, &asset, arguments(op)), Err(error(fault))); assert!(cache.slots[op as usize].get().is_none()); assert!(cache.slots[other].get().is_some()); let expected = match fault { @@ -209,16 +135,8 @@ fn qwen_load_lookup_faults_never_publish_partial_slot() { fn qwen_success_codes_with_null_handles_still_refuse_atomically() { for op in OPERATIONS { for (fault, label, expected_trace) in [ - ( - "null_module", - "cuModuleLoadData", - vec!["push", "load", "restore"], - ), - ( - "null_function", - "cuModuleGetFunction", - vec!["push", "load", "lookup", "unload", "restore"], - ), + ("null_module", "cuModuleLoadData", vec!["push", "load", "restore"]), + ("null_function", "cuModuleGetFunction", vec!["push", "load", "lookup", "unload", "restore"]), ] { let backend = Mock::fault(&[fault]); let cache = Cache::new(); @@ -239,19 +157,13 @@ fn qwen_partial_init_unload_and_restore_errors_are_ordered() { let asset = qwen_ffi::mock_asset(Operation::Down); assert_eq!( execute(&backend, &cache, &asset, arguments(Operation::Down)), - Err(nested( - nested(error("lookup"), error("unload")), - error("restore") - )) + Err(nested(nested(error("lookup"), error("unload")), error("restore"))) ); assert_eq!(ready(&cache), 0); assert!(backend.poison.get()); assert!(backend.retained.get() > 0); let trace = backend.trace.borrow().clone(); - assert_eq!( - execute(&backend, &cache, &asset, arguments(Operation::Down)), - Err(Error::ContextPoisoned) - ); + assert_eq!(execute(&backend, &cache, &asset, arguments(Operation::Down)), Err(Error::ContextPoisoned)); assert_eq!(*backend.trace.borrow(), trace); unload(&backend, &cache).unwrap(); assert_eq!(*backend.trace.borrow(), trace); diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs index e1874a59..8ef8bf67 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners() { for operation in qwen_ffi::QSA_OPERATIONS { @@ -14,10 +13,7 @@ fn qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners() { execute(&backend, &cache, &asset, arguments(operation)).unwrap(); assert_eq!( *backend.trace.borrow(), - [ - "push", "load", "lookup", "launch", "sync", "restore", "push", "launch", - "sync", "restore" - ] + ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] ); assert_eq!(ready(&cache), 1); let failed = Mock::fault(&["lookup", "unload"]); @@ -28,32 +24,18 @@ fn qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners() { ); assert_eq!(ready(&cache), 0); assert!(failed.poison.get()); - assert_eq!( - *failed.trace.borrow(), - ["push", "load", "lookup", "unload", "restore"] - ); + assert_eq!(*failed.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); let failed = Mock::fault(&["launch", "sync", "restore"]); let cache = Cache::new(); let drops = Rc::new(Cell::new(0)); assert_eq!( - execute( - &failed, - &cache, - &asset, - arguments(operation).observe_drop(Rc::clone(&drops)) - ), - Err(nested( - nested(error("launch"), error("sync")), - error("restore") - )) + execute(&failed, &cache, &asset, arguments(operation).observe_drop(Rc::clone(&drops))), + Err(nested(nested(error("launch"), error("sync")), error("restore"))) ); assert_eq!(drops.get(), 0); assert!(failed.poison.get()); let before = failed.trace.borrow().clone(); - assert_eq!( - execute(&failed, &cache, &asset, arguments(operation)), - Err(Error::ContextPoisoned) - ); + assert_eq!(execute(&failed, &cache, &asset, arguments(operation)), Err(Error::ContextPoisoned)); assert_eq!(*failed.trace.borrow(), before); unload(&failed, &cache).unwrap(); assert_eq!(*failed.trace.borrow(), before); @@ -67,28 +49,17 @@ fn qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation() { let asset = qwen_ffi::asset(operation).expect("thirteen qualified fixed entries"); asset.validate(operation).unwrap(); let original_bytes = asset.ptx; - let mut invalid = Asset { - operation, - ptx: original_bytes, - receipt: asset.receipt, - pin: asset.pin, - }; + let mut invalid = Asset { operation, ptx: original_bytes, receipt: asset.receipt, pin: asset.pin }; invalid.receipt.ptx_sha256[0] ^= 1; let backend = Mock::default(); let cache = Cache::new(); - assert_eq!( - execute(&backend, &cache, &invalid, arguments(operation)), - Err(Error::UnsupportedQwenOperation) - ); + assert_eq!(execute(&backend, &cache, &invalid, arguments(operation)), Err(Error::UnsupportedQwenOperation)); assert!(backend.trace.borrow().is_empty()); assert_eq!(ready(&cache), 0); invalid.receipt = asset.receipt; invalid.ptx = b"changed PTX\0"; - assert_eq!( - execute(&backend, &cache, &invalid, arguments(operation)), - Err(Error::UnsupportedQwenOperation) - ); + assert_eq!(execute(&backend, &cache, &invalid, arguments(operation)), Err(Error::UnsupportedQwenOperation)); assert!(backend.trace.borrow().is_empty()); assert_eq!(ready(&cache), 0); @@ -96,10 +67,7 @@ fn qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation() { // failure path and cannot publish a partly resolved kernel. let failed = Mock::fault(&["lookup"]); assert!(execute(&failed, &cache, asset, arguments(operation)).is_err()); - assert_eq!( - *failed.trace.borrow(), - ["push", "load", "lookup", "unload", "restore"] - ); + assert_eq!(*failed.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); assert_eq!(ready(&cache), 0); assert!(!failed.poison.get()); } @@ -114,10 +82,7 @@ fn qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation() { fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { use crate::{Driver, FixedPairKernels, ProjectionKernels}; use std::marker::PhantomData; - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let context = Context { driver: &driver, handle: Some(ffi::ContextHandle::synthetic(1)), @@ -130,9 +95,7 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { q5_k_kernel: Cell::>::new(None), q6_k_kernel: Cell::new(None), common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| { - Cell::>::new(None) - }), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), qwen_kernels: Cache::new(), }; for operation in MOE_OPERATIONS { @@ -148,18 +111,10 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { .collect(); let (inputs, outputs) = buffers.split_at_mut(layout.count - 1); let result = match operation { - Operation::MoeSwiglu => { - context.moe_swiglu_f32(&inputs[0], &inputs[1], &mut outputs[0]) - } - Operation::MoeSharedScalar => { - context.moe_shared_scalar_f32_bf16(&inputs[0], &inputs[1], &mut outputs[0]) - } - Operation::MoeSharedScale => { - context.moe_shared_scale_f32(&inputs[0], &inputs[1], &mut outputs[0]) - } - Operation::MoeCombine => { - context.moe_combine_f64(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0]) - } + Operation::MoeSwiglu => context.moe_swiglu_f32(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::MoeSharedScalar => context.moe_shared_scalar_f32_bf16(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::MoeSharedScale => context.moe_shared_scale_f32(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::MoeCombine => context.moe_combine_f64(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0]), _ => unreachable!("four frozen MoE methods"), }; assert_eq!(result, Err(Error::UnsupportedPlatform)); @@ -167,9 +122,7 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { assert_eq!(ready(&context.qwen_kernels), 0); assert!(!context.poisoned.get()); for (i, buffer) in buffers.iter_mut().enumerate() { - assert!( - buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))) - ); + assert!(buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))); assert_eq!(buffer.bytes, layout.bytes[i]); // Synthetic owners have no CUDA allocation to free. buffer.handle = None; @@ -186,10 +139,7 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { use crate::{Driver, FixedPairKernels, ProjectionKernels}; use std::marker::PhantomData; - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let make_context = || Context { driver: &driver, handle: Some(ffi::ContextHandle::synthetic(1)), @@ -202,9 +152,7 @@ fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { q5_k_kernel: Cell::>::new(None), q6_k_kernel: Cell::new(None), common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| { - Cell::>::new(None) - }), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), qwen_kernels: Cache::new(), }; let context = make_context(); @@ -228,14 +176,10 @@ fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { } Operation::QsaNormQ => context.qsa_norm_q(&inputs[0], &inputs[1], &mut outputs[0]), Operation::QsaNormK => context.qsa_norm_k(&inputs[0], &inputs[1], &mut outputs[0]), - Operation::QsaNormIndexQ => { - context.qsa_norm_index_q(&inputs[0], &inputs[1], &mut outputs[0]) - } + Operation::QsaNormIndexQ => context.qsa_norm_index_q(&inputs[0], &inputs[1], &mut outputs[0]), Operation::QsaRopeQ => context.qsa_rope_q(&inputs[0], 0, &mut outputs[0]), Operation::QsaRopeK => context.qsa_rope_k(&inputs[0], 0, &mut outputs[0]), - Operation::QsaRopeIndexQ => { - context.qsa_rope_index_q(&inputs[0], 0, &mut outputs[0]) - } + Operation::QsaRopeIndexQ => context.qsa_rope_index_q(&inputs[0], 0, &mut outputs[0]), Operation::QsaIndexAppend => { context.qsa_index_append(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0) } @@ -247,9 +191,7 @@ fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { context.qsa_block_scores(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0) } Operation::QsaBlockTopk => context.qsa_block_topk(&inputs[0], &mut outputs[0], 0), - Operation::QsaAttend => { - context.qsa_attend(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 1) - } + Operation::QsaAttend => context.qsa_attend(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 1), Operation::QsaGate => context.qsa_gate_f32(&inputs[0], &inputs[1], &mut outputs[0]), _ => unreachable!("exact thirteen QSA methods"), }; @@ -261,25 +203,17 @@ fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { _thread: PhantomData, borrowed: false, }; - assert_eq!( - context.qsa_call(operation, &[&foreign], 0), - Err(Error::ContextMismatch) - ); + assert_eq!(context.qsa_call(operation, &[&foreign], 0), Err(Error::ContextMismatch)); foreign.handle = None; context.poisoned.set(true); let refs: Vec<_> = buffers.iter().collect(); - assert_eq!( - context.qsa_call(operation, &refs, 0), - Err(Error::ContextPoisoned) - ); + assert_eq!(context.qsa_call(operation, &refs, 0), Err(Error::ContextPoisoned)); context.poisoned.set(false); assert_eq!(context.allocated.get(), 99); assert_eq!(ready(&context.qwen_kernels), 0); assert!(!context.poisoned.get()); for (i, buffer) in buffers.iter_mut().enumerate() { - assert!( - buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))) - ); + assert!(buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))); assert_eq!(buffer.bytes, layout.bytes[i]); // Synthetic owners have no CUDA allocation to free. buffer.handle = None; diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs index b03a6d54..2066dd15 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs @@ -12,10 +12,7 @@ use super::*; fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { use crate::{Driver, FixedPairKernels, ProjectionKernels}; use std::marker::PhantomData; - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let make_context = || Context { driver: &driver, handle: Some(ffi::ContextHandle::synthetic(1)), @@ -28,9 +25,7 @@ fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { q5_k_kernel: Cell::>::new(None), q6_k_kernel: Cell::new(None), common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| { - Cell::>::new(None) - }), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), qwen_kernels: Cache::new(), }; let context = make_context(); @@ -61,15 +56,9 @@ fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { }; let refs: Vec<_> = storage.iter().collect(); assert!(call(&refs, true, 1e-6).is_ok()); - assert!(matches!( - call(&refs, false, 1e-6), - Err(Error::UnsupportedQwenOperation) - )); + assert!(matches!(call(&refs, false, 1e-6), Err(Error::UnsupportedQwenOperation))); context.poisoned.set(true); - assert!(matches!( - call(&refs, true, 1e-6), - Err(Error::ContextPoisoned) - )); + assert!(matches!(call(&refs, true, 1e-6), Err(Error::ContextPoisoned))); context.poisoned.set(false); let foreign = DeviceBuffer { context: &other, @@ -80,22 +69,13 @@ fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { }; let mut foreign_refs = refs.clone(); foreign_refs[0] = &foreign; - assert!(matches!( - call(&foreign_refs, true, 1e-6), - Err(Error::ContextMismatch) - )); + assert!(matches!(call(&foreign_refs, true, 1e-6), Err(Error::ContextMismatch))); context.allocated.set(context.budget + 1); - assert!(matches!( - call(&refs, true, 1e-6), - Err(Error::BudgetExceeded) - )); + assert!(matches!(call(&refs, true, 1e-6), Err(Error::BudgetExceeded))); context.allocated.set(99); if op == Operation::Norm { for eps in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] { - assert!(matches!( - call(&refs, true, eps), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(call(&refs, true, eps), Err(Error::InvalidQwenShape))); } for eps in [0.0, -0.0, 1e-6] { assert!(call(&refs, true, eps).is_ok()); @@ -106,10 +86,7 @@ fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { drop(foreign_refs); drop(refs); storage[0].handle = None; - assert!(matches!( - call(&storage.iter().collect::>(), true, 1e-6), - Err(Error::ContextPoisoned) - )); + assert!(matches!(call(&storage.iter().collect::>(), true, 1e-6), Err(Error::ContextPoisoned))); context.poisoned.set(true); other.poisoned.set(true); let last = storage.pop().unwrap(); @@ -130,41 +107,25 @@ fn mtp_new_exact_dense_and_input_ranges_fail_closed() { Operation::MtpDenseChunk, Operation::MtpDenseMerge, ] { - let layout = if matches!( - operation, - Operation::MtpDenseChunk | Operation::MtpDenseMerge - ) { + let layout = if matches!(operation, Operation::MtpDenseChunk | Operation::MtpDenseMerge) { qwen_ffi::mtp_dense_layout(operation, 262143).unwrap() } else { operation.layout() }; - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); - assert_eq!( - ranges_layout(operation, layout, handles, layout.bytes, false), - Ok(()) - ); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); for i in 0..layout.count { let mut short = layout.bytes; short[i] -= 1; - assert_eq!( - ranges_layout(operation, layout, handles, short, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); let mut wrong = handles; wrong[i] = ffi::BufferHandle::synthetic(handles[i].qwen_address() + 1); - assert_eq!( - ranges_layout(operation, layout, wrong, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges_layout(operation, layout, wrong, layout.bytes, false), Err(Error::InvalidQwenShape)); } let first_output = layout.outputs.trailing_zeros() as usize; let mut overlap = handles; overlap[first_output] = handles[0]; - assert_eq!( - ranges_layout(operation, layout, overlap, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges_layout(operation, layout, overlap, layout.bytes, false), Err(Error::OutputAliasesInput)); } } @@ -177,10 +138,7 @@ fn mtp_new_exact_dense_and_input_ranges_fail_closed() { fn mtp_new_public_dense_preflight_preserves_owners_on_refusal() { use crate::{Driver, FixedPairKernels, ProjectionKernels}; use std::marker::PhantomData; - let driver = Driver { - api: Rc::new(ffi::Api), - version: 0, - }; + let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let context = Context { driver: &driver, handle: Some(ffi::ContextHandle::synthetic(1)), @@ -193,9 +151,7 @@ fn mtp_new_public_dense_preflight_preserves_owners_on_refusal() { q5_k_kernel: Cell::>::new(None), q6_k_kernel: Cell::new(None), common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| { - Cell::>::new(None) - }), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), qwen_kernels: Cache::new(), }; let layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, 0).unwrap(); @@ -243,11 +199,7 @@ fn mtp_new_public_dense_preflight_preserves_owners_on_refusal() { fn mtp_new_pair_second_lookup_and_restore_failures_publish_nothing() { let chunk = qwen_ffi::asset(Operation::MtpDenseChunk).unwrap(); let merge = qwen_ffi::asset(Operation::MtpDenseMerge).unwrap(); - for faults in [ - &["lookup_merge"][..], - &["lookup_merge", "unload"][..], - &["restore"][..], - ] { + for faults in [&["lookup_merge"][..], &["lookup_merge", "unload"][..], &["restore"][..]] { let backend = Mock::fault(faults); let cache = Cache::new(); assert!(prepare_pair(&backend, &cache, [chunk, merge]).is_err()); @@ -271,13 +223,5 @@ fn mtp_new_pair_second_lookup_and_restore_failures_publish_nothing() { prepare_pair(&backend, &cache, [chunk, merge]).unwrap(); assert_eq!(ready(&cache), 2); prepare_pair(&backend, &cache, [chunk, merge]).unwrap(); - assert_eq!( - backend - .trace - .borrow() - .iter() - .filter(|&&v| v == "load") - .count(), - 2 - ); + assert_eq!(backend.trace.borrow().iter().filter(|&&v| v == "load").count(), 2); } diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs index 4cca1bee..fd5513de 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs @@ -10,44 +10,20 @@ fn qwen_attempted_launch_always_syncs_and_uncertainty_never_retries() { let faults: Vec<_> = ["launch", "sync", "restore"] .into_iter() .enumerate() - .filter_map(|(i, label)| { - if mask & (1 << i) != 0 { - Some(label) - } else { - None - } - }) + .filter_map(|(i, label)| if mask & (1 << i) != 0 { Some(label) } else { None }) .collect(); let backend = Mock::fault(&faults); let cache = Cache::new(); let asset = qwen_ffi::mock_asset(op); - let expected = faults - .iter() - .map(|&label| error(label)) - .reduce(nested) - .map_or(Ok(()), Err); + let expected = faults.iter().map(|&label| error(label)).reduce(nested).map_or(Ok(()), Err); let drops = Rc::new(Cell::new(0)); - assert_eq!( - execute( - &backend, - &cache, - &asset, - arguments(op).observe_drop(Rc::clone(&drops)) - ), - expected - ); - assert_eq!( - *backend.trace.borrow(), - vec!["push", "load", "lookup", "launch", "sync", "restore"] - ); + assert_eq!(execute(&backend, &cache, &asset, arguments(op).observe_drop(Rc::clone(&drops))), expected); + assert_eq!(*backend.trace.borrow(), vec!["push", "load", "lookup", "launch", "sync", "restore"]); assert_eq!(backend.poison.get(), mask & 6 != 0); assert_eq!(drops.get(), usize::from(mask & 6 == 0)); if mask & 6 != 0 { assert!(backend.retained.get() > 0); - assert_eq!( - execute(&backend, &cache, &asset, arguments(op)), - Err(Error::ContextPoisoned) - ); + assert_eq!(execute(&backend, &cache, &asset, arguments(op)), Err(Error::ContextPoisoned)); unload(&backend, &cache).unwrap(); unload(&backend, &cache).unwrap(); assert_eq!(backend.trace.borrow().len(), 6); @@ -77,10 +53,7 @@ fn qwen_failed_teardown_consumes_once_and_retains_other_slots() { #[test] fn qwen_receipt_refusal_precedes_any_backend_mutation() { for op in OPERATIONS { - qwen_ffi::asset(op) - .expect("admitted component") - .validate(op) - .unwrap(); + qwen_ffi::asset(op).expect("admitted component").validate(op).unwrap(); for change in 0..9 { let mut asset = qwen_ffi::mock_asset(op); match change { @@ -96,11 +69,8 @@ fn qwen_receipt_refusal_precedes_any_backend_mutation() { } let backend = Mock::default(); let cache = Cache::new(); - let result = if change == 8 { - asset.validate(op) - } else { - execute(&backend, &cache, &asset, arguments(op)) - }; + let result = + if change == 8 { asset.validate(op) } else { execute(&backend, &cache, &asset, arguments(op)) }; assert_eq!(result, Err(Error::UnsupportedQwenOperation)); assert!(backend.trace.borrow().is_empty()); assert_eq!(ready(&cache), 0); @@ -116,17 +86,13 @@ fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { for op in OPERATIONS { // 256 MiB spacing keeps every synthetic range disjoint, including // the 64 MiB first buffer of KarPleScatter. - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); let bytes = op.layout().bytes; assert!(ranges(op, handles, bytes, false).is_ok()); for i in 0..op.layout().count { let mut wrong = bytes; wrong[i] = wrong[i].saturating_sub(1); - assert_eq!( - ranges(op, handles, wrong, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges(op, handles, wrong, false), Err(Error::InvalidQwenShape)); for address in [0, u64::MAX - 3, handles[i].qwen_address() + 1] { // A byte-aligned buffer (KAR PLE) has no misalignment case. if address == handles[i].qwen_address() + 1 && op.layout().align[i] == 1 { @@ -134,10 +100,7 @@ fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { } let mut wrong = handles; wrong[i] = ffi::BufferHandle::synthetic(address); - assert_eq!( - ranges(op, wrong, bytes, false), - Err(Error::InvalidQwenShape) - ); + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::InvalidQwenShape)); } } for i in 0..op.layout().count { @@ -147,18 +110,12 @@ fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { } let mut wrong = handles; wrong[j] = wrong[i]; - assert_eq!( - ranges(op, wrong, bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); // Offset by a step that keeps buffer j aligned. let step = 8.max(op.layout().align[j]); if (bytes[i].min(bytes[j]) as u64) > step { wrong[j] = ffi::BufferHandle::synthetic(wrong[i].qwen_address() + step); - assert_eq!( - ranges(op, wrong, bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); } } } @@ -167,15 +124,9 @@ fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { if op == Operation::InjectResidual { assert!(ranges(op, inplace, bytes, true).is_ok()); inplace[3] = ffi::BufferHandle::synthetic(inplace[0].qwen_address() + 4); - assert_eq!( - ranges(op, inplace, bytes, true), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(op, inplace, bytes, true), Err(Error::OutputAliasesInput)); } else { - assert_eq!( - ranges(op, handles, bytes, true), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges(op, handles, bytes, true), Err(Error::OutputAliasesInput)); } } } @@ -200,16 +151,7 @@ fn qwen_bf16_structural_geometry_and_wide_address_admission() { assert_eq!(layout.grid, 3); assert_eq!(layout.bytes, [6 * n, 4 * n, 12, 0, 0, 0, 0, 0, 0]); } - for (n, block) in [ - (64, 32), - (128, 64), - (192, 96), - (256, 128), - (320, 160), - (384, 192), - (448, 224), - (512, 256), - ] { + for (n, block) in [(64, 32), (128, 64), (192, 96), (256, 128), (320, 160), (384, 192), (448, 224), (512, 256)] { assert_eq!(qwen_ffi::bf16_layout(1, n).unwrap().block, block); } for (m, n) in [ @@ -222,36 +164,18 @@ fn qwen_bf16_structural_geometry_and_wide_address_admission() { (i32::MAX as usize + 1, 2), (1, i32::MAX as usize + 1), ] { - assert!(matches!( - qwen_ffi::bf16_layout(m, n), - Err(Error::InvalidBf16ProjectionShape) - )); + assert!(matches!(qwen_ffi::bf16_layout(m, n), Err(Error::InvalidBf16ProjectionShape))); } - let handles = [ - 0x1000000, 0x2000000, 0x3000000, 0x4000000, 0x5000000, 0x6000000, 0x7000000, 0x8000000, - 0, - ] - .map(ffi::BufferHandle::synthetic); + let handles = [0x1000000, 0x2000000, 0x3000000, 0x4000000, 0x5000000, 0x6000000, 0x7000000, 0x8000000, 0] + .map(ffi::BufferHandle::synthetic); let layout = qwen_ffi::bf16_layout(3, 66).unwrap(); let mut overlap = handles; overlap[2] = ffi::BufferHandle::synthetic(overlap[0].qwen_address() + 8); - assert_eq!( - ranges_layout(Operation::Bf16, layout, overlap, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); + assert_eq!(ranges_layout(Operation::Bf16, layout, overlap, layout.bytes, false), Err(Error::OutputAliasesInput)); let large = qwen_ffi::bf16_layout(1_048_577, 1024).unwrap(); assert!(large.bytes[0] > i32::MAX as usize); - let wide = [ - 0x100000000, - 0x300000000, - 0x400000000, - 0x500000000, - 0x600000000, - 0x700000000, - 0x800000000, - 0x900000000, - 0, - ] - .map(ffi::BufferHandle::synthetic); + let wide = + [0x100000000, 0x300000000, 0x400000000, 0x500000000, 0x600000000, 0x700000000, 0x800000000, 0x900000000, 0] + .map(ffi::BufferHandle::synthetic); assert!(ranges_layout(Operation::Bf16, large, wide, large.bytes, false).is_ok()); } diff --git a/crates/cuda-driver/src/qwen_ffi.rs b/crates/cuda-driver/src/qwen_ffi.rs index e78b425e..f03d6a42 100644 --- a/crates/cuda-driver/src/qwen_ffi.rs +++ b/crates/cuda-driver/src/qwen_ffi.rs @@ -195,8 +195,7 @@ struct PtxProof { ptx: &'static [u8], digest: [u8; 32], } -static PTX_PROOFS: [OnceLock; OPERATIONS.len()] = - [const { OnceLock::new() }; OPERATIONS.len()]; +static PTX_PROOFS: [OnceLock; OPERATIONS.len()] = [const { OnceLock::new() }; OPERATIONS.len()]; #[cfg(test)] #[path = "asset_validation_cache_tests.rs"] @@ -205,19 +204,16 @@ mod asset_validation_cache_tests; const ROUTE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x4b, 0xd2, 0xc9, 0xc4, 0xe1, 0x0b, 0x9a, 0xa0, 0xbc, 0xc2, 0xb1, 0xa8, 0x60, 0xf6, 0x7d, - 0xb0, 0x4f, 0x01, 0xd1, 0x7f, 0x59, 0xc9, 0x3b, 0xde, 0xa0, 0xae, 0x42, 0x67, 0x90, 0xd6, - 0x73, 0x73, + 0x4b, 0xd2, 0xc9, 0xc4, 0xe1, 0x0b, 0x9a, 0xa0, 0xbc, 0xc2, 0xb1, 0xa8, 0x60, 0xf6, 0x7d, 0xb0, 0x4f, 0x01, + 0xd1, 0x7f, 0x59, 0xc9, 0x3b, 0xde, 0xa0, 0xae, 0x42, 0x67, 0x90, 0xd6, 0x73, 0x73, ], ptx_sha256: [ - 0x48, 0x04, 0xcc, 0xad, 0xee, 0x77, 0xaa, 0xbd, 0xa8, 0x80, 0xfb, 0xc0, 0xa5, 0xb3, 0x4f, - 0x10, 0xe8, 0x58, 0x51, 0xc1, 0x69, 0xea, 0xa8, 0x96, 0xf3, 0x31, 0x4b, 0xed, 0x64, 0x78, - 0xe2, 0x25, + 0x48, 0x04, 0xcc, 0xad, 0xee, 0x77, 0xaa, 0xbd, 0xa8, 0x80, 0xfb, 0xc0, 0xa5, 0xb3, 0x4f, 0x10, 0xe8, 0x58, + 0x51, 0xc1, 0x69, 0xea, 0xa8, 0x96, 0xf3, 0x31, 0x4b, 0xed, 0x64, 0x78, 0xe2, 0x25, ], oracle_sha256: [ - 0x00, 0x6c, 0xde, 0x3f, 0xa5, 0xbc, 0xdb, 0x72, 0x1c, 0x8e, 0x8d, 0x8a, 0x7b, 0xdc, 0x10, - 0x94, 0xb1, 0xd2, 0xff, 0x09, 0xec, 0x7b, 0xdc, 0x9b, 0x3a, 0x18, 0x55, 0xe4, 0x94, 0xd8, - 0xd3, 0x9e, + 0x00, 0x6c, 0xde, 0x3f, 0xa5, 0xbc, 0xdb, 0x72, 0x1c, 0x8e, 0x8d, 0x8a, 0x7b, 0xdc, 0x10, 0x94, 0xb1, 0xd2, + 0xff, 0x09, 0xec, 0x7b, 0xdc, 0x9b, 0x3a, 0x18, 0x55, 0xe4, 0x94, 0xd8, 0xd3, 0x9e, ], compiler: "NVCC 12.8.93; CUDA 12.8.1; GCC 13.3", compiler_flags: "-ptx -O3 -std=c++17 -arch=compute_120; no --use_fast_math", @@ -236,19 +232,16 @@ const ROUTE_ASSET: Asset = Asset { const BF16_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xd2, 0xab, 0x43, 0xbd, 0x68, 0x1d, 0x2e, 0x63, 0x41, 0x72, 0xd8, 0xcc, 0x9b, 0xff, 0x87, - 0xfb, 0x82, 0xe8, 0x06, 0x7c, 0x8e, 0x23, 0x2f, 0xf7, 0x8b, 0xf9, 0x61, 0xb0, 0x0d, 0x6d, - 0x84, 0x53, + 0xd2, 0xab, 0x43, 0xbd, 0x68, 0x1d, 0x2e, 0x63, 0x41, 0x72, 0xd8, 0xcc, 0x9b, 0xff, 0x87, 0xfb, 0x82, 0xe8, + 0x06, 0x7c, 0x8e, 0x23, 0x2f, 0xf7, 0x8b, 0xf9, 0x61, 0xb0, 0x0d, 0x6d, 0x84, 0x53, ], ptx_sha256: [ - 0x04, 0x45, 0x43, 0xf6, 0x81, 0xbb, 0x23, 0xeb, 0x9c, 0xae, 0x60, 0x2b, 0x1a, 0x16, 0xaa, - 0x7b, 0x23, 0x86, 0xd6, 0xd5, 0xc3, 0xb1, 0x5c, 0xc4, 0x19, 0x87, 0x33, 0x8b, 0xd6, 0x13, - 0xb1, 0xc3, + 0x04, 0x45, 0x43, 0xf6, 0x81, 0xbb, 0x23, 0xeb, 0x9c, 0xae, 0x60, 0x2b, 0x1a, 0x16, 0xaa, 0x7b, 0x23, 0x86, + 0xd6, 0xd5, 0xc3, 0xb1, 0x5c, 0xc4, 0x19, 0x87, 0x33, 0x8b, 0xd6, 0x13, 0xb1, 0xc3, ], oracle_sha256: [ - 0x70, 0xb4, 0x47, 0x95, 0x52, 0x8f, 0xb7, 0x3d, 0x63, 0x6b, 0xe5, 0x91, 0x4d, 0x60, 0xf0, - 0xad, 0xaa, 0x84, 0x9a, 0x48, 0xcc, 0x38, 0xf3, 0x09, 0xd3, 0x27, 0xa2, 0x97, 0x6c, 0x3e, - 0xd3, 0xda, + 0x70, 0xb4, 0x47, 0x95, 0x52, 0x8f, 0xb7, 0x3d, 0x63, 0x6b, 0xe5, 0x91, 0x4d, 0x60, 0xf0, 0xad, 0xaa, 0x84, + 0x9a, 0x48, 0xcc, 0x38, 0xf3, 0x09, 0xd3, 0x27, 0xa2, 0x97, 0x6c, 0x3e, 0xd3, 0xda, ], compiler: "candidate manual PTX9.0, installed Driver595.91.07 JIT; unchanged original NVCC12.8.93/GCC13.3", compiler_flags: "candidate two ordered fma.rn.ftz, native adaptive/XOR order; original -O3 -arch=sm_120 --use_fast_math --ftz=true --fmad=true", @@ -287,19 +280,16 @@ const BF16_ASSETS: [Asset; 4] = [ const PLE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x91, 0x0a, 0xb4, 0x2d, 0x01, 0x70, 0xeb, 0xdd, 0xc9, 0xa5, 0xf2, 0xfb, 0xb3, 0x14, 0x66, - 0xf3, 0xd2, 0xcf, 0x0d, 0x5a, 0x25, 0x41, 0x03, 0xc1, 0xdb, 0xc6, 0x8e, 0xd0, 0xb4, 0x09, - 0x4e, 0x6d, + 0x91, 0x0a, 0xb4, 0x2d, 0x01, 0x70, 0xeb, 0xdd, 0xc9, 0xa5, 0xf2, 0xfb, 0xb3, 0x14, 0x66, 0xf3, 0xd2, 0xcf, + 0x0d, 0x5a, 0x25, 0x41, 0x03, 0xc1, 0xdb, 0xc6, 0x8e, 0xd0, 0xb4, 0x09, 0x4e, 0x6d, ], ptx_sha256: [ - 0xb1, 0x4c, 0x64, 0x24, 0xb3, 0x4a, 0x4f, 0xba, 0xc6, 0x8a, 0xe3, 0x33, 0xad, 0xf9, 0x77, - 0xe1, 0xa3, 0xff, 0x93, 0xe5, 0x0a, 0xe9, 0x97, 0x52, 0x8b, 0xb9, 0xa2, 0x33, 0xdf, 0xe7, - 0x04, 0x86, + 0xb1, 0x4c, 0x64, 0x24, 0xb3, 0x4a, 0x4f, 0xba, 0xc6, 0x8a, 0xe3, 0x33, 0xad, 0xf9, 0x77, 0xe1, 0xa3, 0xff, + 0x93, 0xe5, 0x0a, 0xe9, 0x97, 0x52, 0x8b, 0xb9, 0xa2, 0x33, 0xdf, 0xe7, 0x04, 0x86, ], oracle_sha256: [ - 0xaf, 0xcd, 0x6e, 0xfa, 0xc5, 0x91, 0xac, 0xf6, 0xc7, 0xff, 0x95, 0xd8, 0xc7, 0x56, 0xa7, - 0x82, 0xcf, 0xa6, 0xdb, 0xb4, 0x49, 0x01, 0x46, 0xf9, 0x24, 0xcb, 0x32, 0xa5, 0x5d, 0x9d, - 0x62, 0x62, + 0xaf, 0xcd, 0x6e, 0xfa, 0xc5, 0x91, 0xac, 0xf6, 0xc7, 0xff, 0x95, 0xd8, 0xc7, 0x56, 0xa7, 0x82, 0xcf, 0xa6, + 0xdb, 0xb4, 0x49, 0x01, 0x46, 0xf9, 0x24, 0xcb, 0x32, 0xa5, 0x5d, 0x9d, 0x62, 0x62, ], compiler: "NVCC 12.8.93; CUDA 12.8.1; installed Driver595.91.07; SM120", compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", @@ -319,14 +309,12 @@ const PLE_ASSETS: [Asset; 6] = [ // Fixed whole Value component admitted after independent original40-tile GPU comparison. const PLE_VALUE_FULL_RECEIPT: Receipt = Receipt { source_sha256: [ - 0x07, 0x11, 0x54, 0x62, 0x3f, 0xad, 0x20, 0x57, 0x19, 0x03, 0x3f, 0x77, 0xe2, 0xab, 0x70, - 0xf8, 0xbf, 0x24, 0xe7, 0x43, 0xf7, 0x9c, 0x7c, 0x23, 0x18, 0x7b, 0x10, 0xfb, 0x87, 0xa6, - 0x3c, 0xa1, + 0x07, 0x11, 0x54, 0x62, 0x3f, 0xad, 0x20, 0x57, 0x19, 0x03, 0x3f, 0x77, 0xe2, 0xab, 0x70, 0xf8, 0xbf, 0x24, + 0xe7, 0x43, 0xf7, 0x9c, 0x7c, 0x23, 0x18, 0x7b, 0x10, 0xfb, 0x87, 0xa6, 0x3c, 0xa1, ], ptx_sha256: [ - 0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, - 0xac, 0x6c, 0x15, 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, - 0x25, 0xd0, + 0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, 0xac, 0x6c, 0x15, + 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, 0x25, 0xd0, ], compiler: "NVCC 12.8.93; CUDA 12.8.1; GPU-hidden runc; pinned image520292dbb4f755fd360766059e62956e9379485d9e073bbd2f6e3c20c270ed66; SM120", compiler_flags: "-std=c++17 -O3 -ptx -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", @@ -345,19 +333,16 @@ const PLE_VALUE_FULL_ASSET: Asset = Asset { const GR_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xba, 0x67, 0x57, 0xed, 0x53, 0x6b, 0xcd, 0x76, 0xca, 0xb5, 0xf7, 0x0d, 0xda, 0xed, 0x7e, - 0xe8, 0xd6, 0x8e, 0x2c, 0x81, 0xf7, 0xab, 0x21, 0x42, 0xc8, 0x2f, 0x08, 0x90, 0x2a, 0xa9, - 0xad, 0xdd, + 0xba, 0x67, 0x57, 0xed, 0x53, 0x6b, 0xcd, 0x76, 0xca, 0xb5, 0xf7, 0x0d, 0xda, 0xed, 0x7e, 0xe8, 0xd6, 0x8e, + 0x2c, 0x81, 0xf7, 0xab, 0x21, 0x42, 0xc8, 0x2f, 0x08, 0x90, 0x2a, 0xa9, 0xad, 0xdd, ], ptx_sha256: [ - 0xde, 0xaa, 0x95, 0xe6, 0x1d, 0x25, 0xff, 0x87, 0xfd, 0x53, 0x1b, 0x62, 0xd5, 0xc2, 0x93, - 0x09, 0xb6, 0x9a, 0x37, 0x71, 0x18, 0x20, 0x4e, 0xef, 0xae, 0xe3, 0x10, 0xaf, 0x4e, 0xcf, - 0xfa, 0x8b, + 0xde, 0xaa, 0x95, 0xe6, 0x1d, 0x25, 0xff, 0x87, 0xfd, 0x53, 0x1b, 0x62, 0xd5, 0xc2, 0x93, 0x09, 0xb6, 0x9a, + 0x37, 0x71, 0x18, 0x20, 0x4e, 0xef, 0xae, 0xe3, 0x10, 0xaf, 0x4e, 0xcf, 0xfa, 0x8b, ], oracle_sha256: [ - 0x8c, 0x10, 0x27, 0x4e, 0x86, 0x93, 0xbf, 0x8c, 0x3d, 0xdc, 0x85, 0x07, 0x37, 0x31, 0x84, - 0x1d, 0x62, 0xa8, 0x46, 0x73, 0x08, 0xf5, 0xa2, 0x9e, 0xd3, 0xb0, 0x7e, 0x44, 0x1f, 0x63, - 0xca, 0x28, + 0x8c, 0x10, 0x27, 0x4e, 0x86, 0x93, 0xbf, 0x8c, 0x3d, 0xdc, 0x85, 0x07, 0x37, 0x31, 0x84, 0x1d, 0x62, 0xa8, + 0x46, 0x73, 0x08, 0xf5, 0xa2, 0x9e, 0xd3, 0xb0, 0x7e, 0x44, 0x1f, 0x63, 0xca, 0x28, ], compiler: "authored PTX9.0 norm RCP/FMA derivative; unchanged four NVCC12.8.93 postops", compiler_flags: "norm runtime cvt/rcp.approx.ftz/fma.rn.ftz matches actual d080 SASS DAG; postops byte unchanged", @@ -377,19 +362,16 @@ const GR_ASSETS: [Asset; 5] = [ const GDN_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x59, 0xd3, 0xc2, 0x82, 0xed, 0xbf, 0x84, 0xfa, 0xe7, 0x9e, 0xfa, 0x7e, 0xaf, 0x0c, 0xca, - 0xce, 0xba, 0x92, 0xed, 0x74, 0x39, 0x8d, 0xc3, 0x88, 0x3b, 0xd4, 0xb0, 0xea, 0x1d, 0xe7, - 0xb4, 0x29, + 0x59, 0xd3, 0xc2, 0x82, 0xed, 0xbf, 0x84, 0xfa, 0xe7, 0x9e, 0xfa, 0x7e, 0xaf, 0x0c, 0xca, 0xce, 0xba, 0x92, + 0xed, 0x74, 0x39, 0x8d, 0xc3, 0x88, 0x3b, 0xd4, 0xb0, 0xea, 0x1d, 0xe7, 0xb4, 0x29, ], ptx_sha256: [ - 0x7b, 0x2f, 0x20, 0x3c, 0xe1, 0xb1, 0xb4, 0xc7, 0xe6, 0x3b, 0xb5, 0x6a, 0x1f, 0x7c, 0x35, - 0x1a, 0x21, 0x3e, 0x1f, 0x5d, 0xf9, 0x71, 0x1a, 0xd2, 0xd8, 0xdb, 0x30, 0x47, 0xae, 0xad, - 0x9e, 0x25, + 0x7b, 0x2f, 0x20, 0x3c, 0xe1, 0xb1, 0xb4, 0xc7, 0xe6, 0x3b, 0xb5, 0x6a, 0x1f, 0x7c, 0x35, 0x1a, 0x21, 0x3e, + 0x1f, 0x5d, 0xf9, 0x71, 0x1a, 0xd2, 0xd8, 0xdb, 0x30, 0x47, 0xae, 0xad, 0x9e, 0x25, ], oracle_sha256: [ - 0xa9, 0x25, 0xa0, 0x93, 0x80, 0x6e, 0x2d, 0xca, 0xb1, 0xac, 0xf3, 0xe0, 0x64, 0xa7, 0x9a, - 0xdf, 0x78, 0xc4, 0xd1, 0x15, 0xc0, 0x6a, 0x86, 0xf9, 0xa6, 0xfd, 0x90, 0xf6, 0xd6, 0xda, - 0xee, 0x2c, + 0xa9, 0x25, 0xa0, 0x93, 0x80, 0x6e, 0x2d, 0xca, 0xb1, 0xac, 0xf3, 0xe0, 0x64, 0xa7, 0x9a, 0xdf, 0x78, 0xc4, + 0xd1, 0x15, 0xc0, 0x6a, 0x86, 0xf9, 0xa6, 0xfd, 0x90, 0xf6, 0xd6, 0xda, 0xee, 0x2c, ], compiler: "NVCC12.8.93 CUDA12.8.1; installed Driver595.91.07 JIT; SM120", compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --use_fast_math --fmad=true; nativeGDN=true fusedGDN=false", @@ -410,19 +392,16 @@ const GDN_ASSETS: [Asset; 6] = [ const MOE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xbd, 0xd9, 0xd3, 0x2a, 0xf7, 0xcf, 0x5b, 0x11, 0x7f, 0xa9, 0xb1, 0xff, 0xae, 0x08, 0x83, - 0xbb, 0xc9, 0xc1, 0xbc, 0x33, 0x2d, 0x8e, 0xe8, 0x7c, 0x88, 0x72, 0x34, 0xa4, 0x00, 0x02, - 0x07, 0xee, + 0xbd, 0xd9, 0xd3, 0x2a, 0xf7, 0xcf, 0x5b, 0x11, 0x7f, 0xa9, 0xb1, 0xff, 0xae, 0x08, 0x83, 0xbb, 0xc9, 0xc1, + 0xbc, 0x33, 0x2d, 0x8e, 0xe8, 0x7c, 0x88, 0x72, 0x34, 0xa4, 0x00, 0x02, 0x07, 0xee, ], ptx_sha256: [ - 0xeb, 0x25, 0xf4, 0x5f, 0x2b, 0xf1, 0xcd, 0x3b, 0xe5, 0x7e, 0x0b, 0x5f, 0x32, 0x6a, 0x63, - 0xf6, 0x66, 0x05, 0x9a, 0x58, 0x70, 0x6d, 0x7a, 0x2b, 0xd4, 0x70, 0x52, 0x6c, 0x22, 0xc0, - 0xf6, 0x7a, + 0xeb, 0x25, 0xf4, 0x5f, 0x2b, 0xf1, 0xcd, 0x3b, 0xe5, 0x7e, 0x0b, 0x5f, 0x32, 0x6a, 0x63, 0xf6, 0x66, 0x05, + 0x9a, 0x58, 0x70, 0x6d, 0x7a, 0x2b, 0xd4, 0x70, 0x52, 0x6c, 0x22, 0xc0, 0xf6, 0x7a, ], oracle_sha256: [ - 0xfb, 0x0a, 0xd5, 0x84, 0x81, 0xbc, 0xb8, 0x4b, 0x18, 0xa4, 0x37, 0xe6, 0x6b, 0x14, 0x56, - 0xd0, 0x26, 0x66, 0xf3, 0x97, 0x02, 0x17, 0xb1, 0x72, 0x9c, 0xa9, 0x7b, 0x2d, 0x84, 0xb2, - 0x99, 0x48, + 0xfb, 0x0a, 0xd5, 0x84, 0x81, 0xbc, 0xb8, 0x4b, 0x18, 0xa4, 0x37, 0xe6, 0x6b, 0x14, 0x56, 0xd0, 0x26, 0x66, + 0xf3, 0x97, 0x02, 0x17, 0xb1, 0x72, 0x9c, 0xa9, 0x7b, 0x2d, 0x84, 0xb2, 0x99, 0x48, ], compiler: "NVCC12.8.93 CUDA12.8.1; installed Driver595.91.07; SM120", compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --fmad=true --ftz=false; explicit native SwiGLU intrinsics; legacy shared/combine ordinary flags", @@ -441,19 +420,16 @@ const MOE_ASSETS: [Asset; 4] = [ const QSA_NATIVE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x35, 0xe3, 0x67, 0x29, 0x26, 0xfe, 0x27, 0xfe, 0xd1, 0x3f, 0x9e, 0x56, 0x01, 0x63, 0xd7, - 0xa4, 0xcf, 0x89, 0xe8, 0x27, 0xc6, 0x25, 0x6a, 0x3e, 0xde, 0x71, 0xf4, 0x87, 0xc7, 0xf8, - 0x5a, 0xb5, + 0x35, 0xe3, 0x67, 0x29, 0x26, 0xfe, 0x27, 0xfe, 0xd1, 0x3f, 0x9e, 0x56, 0x01, 0x63, 0xd7, 0xa4, 0xcf, 0x89, + 0xe8, 0x27, 0xc6, 0x25, 0x6a, 0x3e, 0xde, 0x71, 0xf4, 0x87, 0xc7, 0xf8, 0x5a, 0xb5, ], ptx_sha256: [ - 0xd6, 0x04, 0x89, 0xfb, 0x70, 0xce, 0x43, 0x70, 0x04, 0x7b, 0xf5, 0x4f, 0xae, 0x8d, 0xd4, - 0x6d, 0xfb, 0x53, 0xbb, 0x73, 0xb1, 0x61, 0x8c, 0x58, 0x94, 0x29, 0x32, 0xa7, 0x89, 0xd0, - 0x64, 0xc5, + 0xd6, 0x04, 0x89, 0xfb, 0x70, 0xce, 0x43, 0x70, 0x04, 0x7b, 0xf5, 0x4f, 0xae, 0x8d, 0xd4, 0x6d, 0xfb, 0x53, + 0xbb, 0x73, 0xb1, 0x61, 0x8c, 0x58, 0x94, 0x29, 0x32, 0xa7, 0x89, 0xd0, 0x64, 0xc5, ], oracle_sha256: [ - 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, - 0x96, 0x80, 0x6e, 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, - 0xeb, 0x79, + 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, 0x96, 0x80, 0x6e, + 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, 0xeb, 0x79, ], compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math", @@ -465,19 +441,16 @@ const QSA_NATIVE_RECEIPT: Receipt = Receipt { const QSA_SELECT_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x03, 0xdf, 0x9d, 0x4d, 0x42, 0xcf, 0x74, 0x2e, 0x4e, 0x06, 0x06, 0x8d, 0x30, 0xbf, 0xc3, - 0x0b, 0xf7, 0x30, 0x3f, 0xee, 0x18, 0x8f, 0xad, 0x45, 0x6b, 0x53, 0xa0, 0x78, 0x8c, 0x4f, - 0x1a, 0x7f, + 0x03, 0xdf, 0x9d, 0x4d, 0x42, 0xcf, 0x74, 0x2e, 0x4e, 0x06, 0x06, 0x8d, 0x30, 0xbf, 0xc3, 0x0b, 0xf7, 0x30, + 0x3f, 0xee, 0x18, 0x8f, 0xad, 0x45, 0x6b, 0x53, 0xa0, 0x78, 0x8c, 0x4f, 0x1a, 0x7f, ], ptx_sha256: [ - 0xe0, 0x94, 0xe1, 0x0f, 0x84, 0xcc, 0xa6, 0x12, 0xca, 0x28, 0x59, 0x6a, 0xa3, 0x94, 0xee, - 0x99, 0x9e, 0x33, 0xfe, 0x7b, 0xc8, 0x4b, 0x35, 0x9b, 0xfa, 0xb6, 0xda, 0x07, 0x30, 0xd4, - 0xa5, 0x19, + 0xe0, 0x94, 0xe1, 0x0f, 0x84, 0xcc, 0xa6, 0x12, 0xca, 0x28, 0x59, 0x6a, 0xa3, 0x94, 0xee, 0x99, 0x9e, 0x33, + 0xfe, 0x7b, 0xc8, 0x4b, 0x35, 0x9b, 0xfa, 0xb6, 0xda, 0x07, 0x30, 0xd4, 0xa5, 0x19, ], oracle_sha256: [ - 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, - 0x96, 0x80, 0x6e, 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, - 0xeb, 0x79, + 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, 0x96, 0x80, 0x6e, + 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, 0xeb, 0x79, ], compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false", @@ -489,19 +462,16 @@ const QSA_SELECT_RECEIPT: Receipt = Receipt { const QSA_ATTENTION_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x78, 0xab, 0x8d, 0x92, 0x40, 0x96, 0x38, 0x76, 0xe2, 0xa1, 0x57, 0x8f, 0x84, 0x58, 0x94, - 0xcd, 0x38, 0xaf, 0x14, 0x8a, 0x37, 0x24, 0x2a, 0x2d, 0xfc, 0x9a, 0x86, 0x68, 0xaf, 0xeb, - 0x1b, 0xc6, + 0x78, 0xab, 0x8d, 0x92, 0x40, 0x96, 0x38, 0x76, 0xe2, 0xa1, 0x57, 0x8f, 0x84, 0x58, 0x94, 0xcd, 0x38, 0xaf, + 0x14, 0x8a, 0x37, 0x24, 0x2a, 0x2d, 0xfc, 0x9a, 0x86, 0x68, 0xaf, 0xeb, 0x1b, 0xc6, ], ptx_sha256: [ - 0x91, 0x21, 0x9c, 0xfb, 0xc1, 0xa7, 0x7c, 0x4b, 0xb6, 0x66, 0x61, 0x06, 0x0a, 0xc9, 0x39, - 0xa5, 0x0d, 0xc4, 0xc4, 0xd7, 0xd4, 0xdb, 0x8d, 0x50, 0xbc, 0x59, 0xfb, 0xcd, 0x16, 0x75, - 0x62, 0xb2, + 0x91, 0x21, 0x9c, 0xfb, 0xc1, 0xa7, 0x7c, 0x4b, 0xb6, 0x66, 0x61, 0x06, 0x0a, 0xc9, 0x39, 0xa5, 0x0d, 0xc4, + 0xc4, 0xd7, 0xd4, 0xdb, 0x8d, 0x50, 0xbc, 0x59, 0xfb, 0xcd, 0x16, 0x75, 0x62, 0xb2, ], oracle_sha256: [ - 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, - 0x96, 0x80, 0x6e, 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, - 0xeb, 0x79, + 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, 0x96, 0x80, 0x6e, + 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, 0xeb, 0x79, ], compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false", @@ -513,19 +483,16 @@ const QSA_ATTENTION_RECEIPT: Receipt = Receipt { const QSA_GATE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x6b, 0x90, 0xb7, 0x48, 0xdf, 0x61, 0x0f, 0x26, 0xa4, 0x0b, 0x82, 0xeb, 0xba, 0xcd, 0xeb, - 0xd1, 0x5d, 0x35, 0x25, 0x2c, 0x3f, 0xeb, 0x76, 0xea, 0x1a, 0xaa, 0xd0, 0xed, 0x51, 0x9d, - 0xb2, 0x2a, + 0x6b, 0x90, 0xb7, 0x48, 0xdf, 0x61, 0x0f, 0x26, 0xa4, 0x0b, 0x82, 0xeb, 0xba, 0xcd, 0xeb, 0xd1, 0x5d, 0x35, + 0x25, 0x2c, 0x3f, 0xeb, 0x76, 0xea, 0x1a, 0xaa, 0xd0, 0xed, 0x51, 0x9d, 0xb2, 0x2a, ], ptx_sha256: [ - 0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, - 0x0f, 0xd4, 0x29, 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, - 0xe1, 0xf3, + 0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, 0x0f, 0xd4, 0x29, + 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, 0xe1, 0xf3, ], oracle_sha256: [ - 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, - 0x96, 0x80, 0x6e, 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, - 0xeb, 0x79, + 0x49, 0xde, 0xa1, 0xee, 0xc7, 0x2f, 0xd7, 0xb8, 0xe2, 0x97, 0x8a, 0x3a, 0xb1, 0xea, 0x03, 0x96, 0x80, 0x6e, + 0x02, 0x10, 0xf2, 0xa0, 0x22, 0x1a, 0xb4, 0x1e, 0x3e, 0x9b, 0x96, 0x0a, 0xeb, 0x79, ], compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math", @@ -554,19 +521,16 @@ const QSA_ASSETS: [Asset; 13] = [ const KAR_PLE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xea, 0x3a, 0xc1, 0xba, 0xd0, 0x64, 0xec, 0x57, 0x1b, 0x30, 0x63, 0xe9, 0x13, 0x4d, 0x7f, - 0xca, 0x14, 0x4c, 0x4e, 0x8e, 0x8d, 0x61, 0x59, 0x9f, 0x8b, 0x40, 0x0e, 0x1b, 0x90, 0x7d, - 0xec, 0xbb, + 0xea, 0x3a, 0xc1, 0xba, 0xd0, 0x64, 0xec, 0x57, 0x1b, 0x30, 0x63, 0xe9, 0x13, 0x4d, 0x7f, 0xca, 0x14, 0x4c, + 0x4e, 0x8e, 0x8d, 0x61, 0x59, 0x9f, 0x8b, 0x40, 0x0e, 0x1b, 0x90, 0x7d, 0xec, 0xbb, ], ptx_sha256: [ - 0x03, 0xc9, 0xf6, 0x63, 0x49, 0x5b, 0xea, 0xf1, 0xdd, 0x42, 0x02, 0x5f, 0x14, 0x80, 0x9b, - 0x7b, 0xfb, 0x8c, 0xd7, 0xad, 0x4c, 0x7f, 0xb5, 0x5e, 0x17, 0x3a, 0x79, 0xb1, 0xa9, 0x72, - 0x0c, 0x3b, + 0x03, 0xc9, 0xf6, 0x63, 0x49, 0x5b, 0xea, 0xf1, 0xdd, 0x42, 0x02, 0x5f, 0x14, 0x80, 0x9b, 0x7b, 0xfb, 0x8c, + 0xd7, 0xad, 0x4c, 0x7f, 0xb5, 0x5e, 0x17, 0x3a, 0x79, 0xb1, 0xa9, 0x72, 0x0c, 0x3b, ], oracle_sha256: [ - 0xc7, 0xb7, 0xc0, 0xf6, 0x71, 0x5b, 0x6e, 0x5c, 0x78, 0xce, 0x80, 0x73, 0x8b, 0xb6, 0x3e, - 0xb9, 0x52, 0x7a, 0x0c, 0x31, 0xb6, 0xdf, 0xb4, 0xfa, 0xd6, 0xc4, 0x92, 0x6f, 0xec, 0x14, - 0x66, 0x7f, + 0xc7, 0xb7, 0xc0, 0xf6, 0x71, 0x5b, 0x6e, 0x5c, 0x78, 0xce, 0x80, 0x73, 0x8b, 0xb6, 0x3e, 0xb9, 0x52, 0x7a, + 0x0c, 0x31, 0xb6, 0xdf, 0xb4, 0xfa, 0xd6, 0xc4, 0x92, 0x6f, 0xec, 0x14, 0x66, 0x7f, ], compiler: "NVCC12.8.93 NVVM20.0.0 CL-35583870; cached CUDA12.8.1", compiler_flags: "-ptx -O3 -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", @@ -592,19 +556,16 @@ const KAR_PLE_ASSETS: [Asset; 2] = [ const MTP_INPUT_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xcf, 0x3a, 0x6a, 0x8c, 0x5e, 0x6f, 0x96, 0x0f, 0x4f, 0xff, 0x08, 0x86, 0xc3, 0x2b, 0xb9, - 0xbd, 0xc5, 0x99, 0x3e, 0xcd, 0xec, 0x40, 0xec, 0x5a, 0x76, 0x66, 0xcb, 0xf0, 0x3f, 0x0e, - 0x85, 0xbe, + 0xcf, 0x3a, 0x6a, 0x8c, 0x5e, 0x6f, 0x96, 0x0f, 0x4f, 0xff, 0x08, 0x86, 0xc3, 0x2b, 0xb9, 0xbd, 0xc5, 0x99, + 0x3e, 0xcd, 0xec, 0x40, 0xec, 0x5a, 0x76, 0x66, 0xcb, 0xf0, 0x3f, 0x0e, 0x85, 0xbe, ], ptx_sha256: [ - 0xad, 0xa8, 0x7a, 0x1b, 0xd6, 0xff, 0x2f, 0x60, 0x13, 0xd2, 0xbd, 0x64, 0x1a, 0x37, 0x86, - 0xeb, 0x46, 0xb9, 0xc9, 0xfc, 0xf3, 0x58, 0x6c, 0x66, 0x60, 0x9c, 0x8e, 0xee, 0xa4, 0xb1, - 0x07, 0xe8, + 0xad, 0xa8, 0x7a, 0x1b, 0xd6, 0xff, 0x2f, 0x60, 0x13, 0xd2, 0xbd, 0x64, 0x1a, 0x37, 0x86, 0xeb, 0x46, 0xb9, + 0xc9, 0xfc, 0xf3, 0x58, 0x6c, 0x66, 0x60, 0x9c, 0x8e, 0xee, 0xa4, 0xb1, 0x07, 0xe8, ], oracle_sha256: [ - 0xa9, 0xf4, 0x7a, 0xa5, 0x83, 0xe6, 0x56, 0x75, 0x7e, 0x4b, 0x81, 0x83, 0x01, 0x43, 0xe0, - 0x5c, 0xac, 0x1a, 0x82, 0x66, 0xfb, 0x22, 0xce, 0xe0, 0x85, 0x66, 0x37, 0x32, 0xd5, 0xc6, - 0x94, 0x8a, + 0xa9, 0xf4, 0x7a, 0xa5, 0x83, 0xe6, 0x56, 0x75, 0x7e, 0x4b, 0x81, 0x83, 0x01, 0x43, 0xe0, 0x5c, 0xac, 0x1a, + 0x82, 0x66, 0xfb, 0x22, 0xce, 0xe0, 0x85, 0x66, 0x37, 0x32, 0xd5, 0xc6, 0x94, 0x8a, ], compiler: "NVCC12.8.93; installed Driver595.91.07 JIT on RTX5090", compiler_flags: "-std=c++17 -O3 -arch=sm_120 --use_fast_math --ftz=true --fmad=true", @@ -616,19 +577,16 @@ const MTP_INPUT_RECEIPT: Receipt = Receipt { const MTP_DENSE_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0xd5, 0xe9, 0x26, 0x37, 0xb6, 0x13, 0x88, 0x6f, 0xc4, 0x3c, 0xd4, 0x10, 0xbf, 0x05, 0xbb, - 0x93, 0x8e, 0xa1, 0x3b, 0xa4, 0x18, 0x5c, 0xb3, 0x85, 0x50, 0x76, 0x4b, 0x74, 0x0f, 0xaf, - 0xfc, 0xc3, + 0xd5, 0xe9, 0x26, 0x37, 0xb6, 0x13, 0x88, 0x6f, 0xc4, 0x3c, 0xd4, 0x10, 0xbf, 0x05, 0xbb, 0x93, 0x8e, 0xa1, + 0x3b, 0xa4, 0x18, 0x5c, 0xb3, 0x85, 0x50, 0x76, 0x4b, 0x74, 0x0f, 0xaf, 0xfc, 0xc3, ], ptx_sha256: [ - 0xe1, 0x1a, 0xc4, 0xde, 0x66, 0xc9, 0x9c, 0x31, 0xec, 0x95, 0x37, 0x27, 0xbd, 0xac, 0x91, - 0xca, 0xc9, 0x7d, 0x58, 0xd8, 0x2a, 0x3d, 0xcb, 0xe0, 0x6e, 0xf4, 0xc6, 0xe8, 0xdc, 0x2a, - 0x4c, 0x66, + 0xe1, 0x1a, 0xc4, 0xde, 0x66, 0xc9, 0x9c, 0x31, 0xec, 0x95, 0x37, 0x27, 0xbd, 0xac, 0x91, 0xca, 0xc9, 0x7d, + 0x58, 0xd8, 0x2a, 0x3d, 0xcb, 0xe0, 0x6e, 0xf4, 0xc6, 0xe8, 0xdc, 0x2a, 0x4c, 0x66, ], oracle_sha256: [ - 0x42, 0xa5, 0xbe, 0xe1, 0x17, 0xef, 0xdd, 0x03, 0xea, 0xe5, 0xc1, 0x10, 0x68, 0x4f, 0x4e, - 0x71, 0xfb, 0x29, 0x0f, 0xe5, 0x27, 0xdb, 0x26, 0x13, 0x86, 0xc4, 0x37, 0x5c, 0x3f, 0x4f, - 0xa5, 0xba, + 0x42, 0xa5, 0xbe, 0xe1, 0x17, 0xef, 0xdd, 0x03, 0xea, 0xe5, 0xc1, 0x10, 0x68, 0x4f, 0x4e, 0x71, 0xfb, 0x29, + 0x0f, 0xe5, 0x27, 0xdb, 0x26, 0x13, 0x86, 0xc4, 0x37, 0x5c, 0x3f, 0x4f, 0xa5, 0xba, ], compiler: "NVCC12.8.93; installed Driver595.91.07 JIT on RTX5090", compiler_flags: "-std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse; no --use_fast_math", @@ -674,19 +632,16 @@ const MTP_DENSE_ASSETS: [Asset; 2] = [ const MTP_GR_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x9a, 0x4e, 0x32, 0x27, 0x3c, 0xd7, 0xbf, 0x24, 0x47, 0x73, 0x44, 0x38, 0xa1, 0x9f, 0x2b, - 0xe9, 0x3a, 0xa3, 0x55, 0xd3, 0x8c, 0xd8, 0x55, 0x3e, 0x9e, 0xd5, 0xae, 0xb9, 0xdb, 0x32, - 0xf6, 0x90, + 0x9a, 0x4e, 0x32, 0x27, 0x3c, 0xd7, 0xbf, 0x24, 0x47, 0x73, 0x44, 0x38, 0xa1, 0x9f, 0x2b, 0xe9, 0x3a, 0xa3, + 0x55, 0xd3, 0x8c, 0xd8, 0x55, 0x3e, 0x9e, 0xd5, 0xae, 0xb9, 0xdb, 0x32, 0xf6, 0x90, ], ptx_sha256: [ - 0x7a, 0xba, 0x70, 0x01, 0x45, 0xb1, 0x9a, 0x09, 0x1d, 0x1c, 0xa2, 0x77, 0x44, 0x62, 0x01, - 0xff, 0x47, 0x69, 0xba, 0xa3, 0x66, 0xe7, 0xd5, 0xa0, 0x29, 0x4a, 0x91, 0xe7, 0x6b, 0xa6, - 0x09, 0xd4, + 0x7a, 0xba, 0x70, 0x01, 0x45, 0xb1, 0x9a, 0x09, 0x1d, 0x1c, 0xa2, 0x77, 0x44, 0x62, 0x01, 0xff, 0x47, 0x69, + 0xba, 0xa3, 0x66, 0xe7, 0xd5, 0xa0, 0x29, 0x4a, 0x91, 0xe7, 0x6b, 0xa6, 0x09, 0xd4, ], oracle_sha256: [ - 0x6a, 0x55, 0x47, 0xc0, 0xc5, 0x8e, 0x41, 0xe9, 0x64, 0x89, 0x8a, 0x6b, 0x70, 0xb9, 0xa6, - 0xcd, 0xa8, 0xc3, 0xc3, 0xbd, 0x34, 0x62, 0x87, 0x8e, 0xb7, 0x32, 0xe6, 0x15, 0x6d, 0xd1, - 0x48, 0x99, + 0x6a, 0x55, 0x47, 0xc0, 0xc5, 0x8e, 0x41, 0xe9, 0x64, 0x89, 0x8a, 0x6b, 0x70, 0xb9, 0xa6, 0xcd, 0xa8, 0xc3, + 0xc3, 0xbd, 0x34, 0x62, 0x87, 0x8e, 0xb7, 0x32, 0xe6, 0x15, 0x6d, 0xd1, 0x48, 0x99, ], compiler: "NVCC12.8.93/GCC13.3 CUDA12.8.1", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse nofastmath", @@ -698,19 +653,16 @@ const MTP_GR_RECEIPT: Receipt = Receipt { const MTP_S2_RECEIPT: Receipt = Receipt { version: 1, source_sha256: [ - 0x3f, 0x0d, 0x9e, 0xea, 0xe8, 0xe4, 0xa5, 0x35, 0x4b, 0xd0, 0x79, 0x01, 0xb0, 0x6a, 0x39, - 0xb4, 0x06, 0x19, 0x07, 0x26, 0x73, 0x0d, 0xba, 0x14, 0xe6, 0xf0, 0x0a, 0x08, 0x15, 0x09, - 0x1e, 0xd5, + 0x3f, 0x0d, 0x9e, 0xea, 0xe8, 0xe4, 0xa5, 0x35, 0x4b, 0xd0, 0x79, 0x01, 0xb0, 0x6a, 0x39, 0xb4, 0x06, 0x19, + 0x07, 0x26, 0x73, 0x0d, 0xba, 0x14, 0xe6, 0xf0, 0x0a, 0x08, 0x15, 0x09, 0x1e, 0xd5, ], ptx_sha256: [ - 0x0b, 0xf7, 0xb8, 0x12, 0x8c, 0x2d, 0x59, 0x0e, 0x36, 0xc8, 0xc5, 0x55, 0x97, 0xb4, 0xd0, - 0x2f, 0x3c, 0x50, 0x7e, 0x12, 0x0f, 0x3d, 0x09, 0x1c, 0xb3, 0x54, 0xea, 0xee, 0x9e, 0x09, - 0x74, 0xf7, + 0x0b, 0xf7, 0xb8, 0x12, 0x8c, 0x2d, 0x59, 0x0e, 0x36, 0xc8, 0xc5, 0x55, 0x97, 0xb4, 0xd0, 0x2f, 0x3c, 0x50, + 0x7e, 0x12, 0x0f, 0x3d, 0x09, 0x1c, 0xb3, 0x54, 0xea, 0xee, 0x9e, 0x09, 0x74, 0xf7, ], oracle_sha256: [ - 0x79, 0x01, 0xa0, 0x8d, 0xce, 0x54, 0xc9, 0x8e, 0xd4, 0x85, 0xd8, 0x9a, 0x52, 0x1d, 0x8a, - 0x42, 0x7b, 0xec, 0xa9, 0xbf, 0xae, 0x9d, 0x76, 0x12, 0xcf, 0x16, 0xc1, 0x61, 0x98, 0x9c, - 0x29, 0x17, + 0x79, 0x01, 0xa0, 0x8d, 0xce, 0x54, 0xc9, 0x8e, 0xd4, 0x85, 0xd8, 0x9a, 0x52, 0x1d, 0x8a, 0x42, 0x7b, 0xec, + 0xa9, 0xbf, 0xae, 0x9d, 0x76, 0x12, 0xcf, 0x16, 0xc1, 0x61, 0x98, 0x9c, 0x29, 0x17, ], compiler: "NVCC12.8.93/GCC13.3 CUDA12.8.1", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse nofastmath", @@ -778,14 +730,12 @@ const MTP_EXTENDED_ASSETS: [Asset; 9] = [ // Exact new full-bank geometry proof; existing tile assets retain their module. const MTP_S2_FULL_RECEIPT: Receipt = Receipt { source_sha256: [ - 0x63, 0x49, 0xa3, 0xc3, 0xe1, 0xb4, 0x6e, 0x1e, 0x89, 0x19, 0xaf, 0xfe, 0xb5, 0x60, 0xa7, - 0x0e, 0x23, 0x2a, 0x47, 0xe1, 0x51, 0xc9, 0x0c, 0xc1, 0x77, 0xde, 0xd2, 0x88, 0x84, 0xfb, - 0xfe, 0x12, + 0x63, 0x49, 0xa3, 0xc3, 0xe1, 0xb4, 0x6e, 0x1e, 0x89, 0x19, 0xaf, 0xfe, 0xb5, 0x60, 0xa7, 0x0e, 0x23, 0x2a, + 0x47, 0xe1, 0x51, 0xc9, 0x0c, 0xc1, 0x77, 0xde, 0xd2, 0x88, 0x84, 0xfb, 0xfe, 0x12, ], ptx_sha256: [ - 0x43, 0x81, 0x4a, 0x9c, 0x17, 0x9a, 0xba, 0xba, 0x8f, 0xe0, 0xa8, 0x0b, 0x88, 0xa3, 0x15, - 0xbc, 0x94, 0xc4, 0x38, 0xf3, 0x9b, 0x38, 0x42, 0xf4, 0xe4, 0x30, 0x1e, 0x96, 0xa0, 0x32, - 0xf7, 0x8d, + 0x43, 0x81, 0x4a, 0x9c, 0x17, 0x9a, 0xba, 0xba, 0x8f, 0xe0, 0xa8, 0x0b, 0x88, 0xa3, 0x15, 0xbc, 0x94, 0xc4, + 0x38, 0xf3, 0x9b, 0x38, 0x42, 0xf4, 0xe4, 0x30, 0x1e, 0x96, 0xa0, 0x32, 0xf7, 0x8d, ], qualification_receipt: "STRA-172 f05040fb-af66-4112-84bd-34d4cdcf9eae; independent frozen47d85033; actual log355b310041afd479dd82f96b73fc782e4fd0757e77106c68b544d6d86e98536a", comparison: "NEW full-vs40legacy-vsoriginal:115200 exact paired words,18finite/6late/4badIDs; oracle cubin38c0ca6fd0cdd9d9af39f657f407cfbd9df3919747c4e7cf260ed88079061621; helperdfa0f329d9fd40657fd14651866fa92b72d43feb1d4e71e0c877f29eebd10a17; ELFa50c4361380a1ae7f0fda14cf590068ecd565fb15ca0bd6c7b9239c61b0e51eb; corpus723d44b9a561198b59db508926d7897cfb807c308d7de33e3f9469eab7613dea; component-only,no fullmodel/performance claim", @@ -827,38 +777,38 @@ mod tests; mod impl_operation; mod mtp_s2_full_layout_fn; #[allow(unused_imports)] -pub(super) use mtp_s2_full_layout_fn::mtp_s2_full_layout; +pub(super) use mtp_s2_full_layout_fn::mtp_dense_layout; #[allow(unused_imports)] use mtp_s2_full_layout_fn::mtp_extended_layout; #[allow(unused_imports)] use mtp_s2_full_layout_fn::mtp_input_layout; #[allow(unused_imports)] -pub(super) use mtp_s2_full_layout_fn::mtp_dense_layout; +pub(super) use mtp_s2_full_layout_fn::mtp_s2_full_layout; mod qsa_layout_fn; #[allow(unused_imports)] -pub(super) use qsa_layout_fn::qsa_layout; -#[allow(unused_imports)] -use qsa_layout_fn::ple_layout; +use qsa_layout_fn::gdn_layout; #[allow(unused_imports)] use qsa_layout_fn::moe_layout; #[allow(unused_imports)] -use qsa_layout_fn::gdn_layout; -mod impl_operation_2; +use qsa_layout_fn::ple_layout; #[allow(unused_imports)] -pub(super) use impl_operation_2::kar_ple_layout; +pub(super) use qsa_layout_fn::qsa_layout; +mod impl_operation_2; #[allow(unused_imports)] pub(super) use impl_operation_2::bf16_layout; #[allow(unused_imports)] -use impl_operation_2::inspect_ptx; -#[allow(unused_imports)] -use impl_operation_2::ple_asset; +use impl_operation_2::gdn_asset; #[allow(unused_imports)] use impl_operation_2::gr_asset; #[allow(unused_imports)] -use impl_operation_2::gdn_asset; +use impl_operation_2::inspect_ptx; +#[allow(unused_imports)] +pub(super) use impl_operation_2::kar_ple_layout; #[allow(unused_imports)] use impl_operation_2::moe_asset; #[allow(unused_imports)] +use impl_operation_2::ple_asset; +#[allow(unused_imports)] use impl_operation_2::qsa_asset; mod asset_fn; #[allow(unused_imports)] @@ -866,11 +816,11 @@ pub(super) use asset_fn::asset; #[allow(unused_imports)] pub(crate) use asset_fn::sha256; mod mock_asset_fn; +#[allow(unused_imports)] +pub(super) use mock_asset_fn::gr_batch_preview_ptx; #[cfg(test)] #[allow(unused_imports)] pub(super) use mock_asset_fn::mock_asset; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] #[allow(unused_imports)] pub(crate) use mock_asset_fn::q6_batch_preview_ptx; -#[allow(unused_imports)] -pub(super) use mock_asset_fn::gr_batch_preview_ptx; diff --git a/crates/cuda-driver/src/qwen_ffi/asset_fn.rs b/crates/cuda-driver/src/qwen_ffi/asset_fn.rs index 4996eb0c..f4b79367 100644 --- a/crates/cuda-driver/src/qwen_ffi/asset_fn.rs +++ b/crates/cuda-driver/src/qwen_ffi/asset_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn asset(operation: Operation) -> Option<&'static Asset> { match operation { Operation::MtpS2GateUpFull => Some(&MTP_S2_FULL_ASSETS[0]), @@ -92,8 +91,7 @@ impl Arguments { // retagging occurs after these self-referential field addresses form. unsafe { for i in 0..layout.count { - let parameter = - i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i)); + let parameter = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i)); (*storage).parameters[parameter] = (&raw mut (*storage).addresses[i]).cast(); } if let Some((_, index)) = layout.integer { @@ -150,21 +148,17 @@ impl Drop for Arguments { pub(crate) fn sha256(bytes: &[u8]) -> [u8; 32] { const K: [u32; 64] = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, - 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, - 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, - 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, - 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, - 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, - 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, + 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, + 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, + 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ]; - let mut state: [u32; 8] = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, - 0x5be0cd19, - ]; + let mut state: [u32; 8] = + [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; let bit_length = (bytes.len() as u64).wrapping_mul(8).to_be_bytes(); let blocks = bytes.len() / 64 + if bytes.len() % 64 < 56 { 1 } else { 2 }; for block in 0..blocks { @@ -200,8 +194,8 @@ pub(crate) fn sha256(bytes: &[u8]) -> [u8; 32] { .wrapping_add((e & f) ^ (!e & g)) .wrapping_add(K[i]) .wrapping_add(w[i]); - let t2 = (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)) - .wrapping_add((a & b) ^ (a & c) ^ (b & c)); + let t2 = + (a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22)).wrapping_add((a & b) ^ (a & c) ^ (b & c)); h = g; g = f; f = e; diff --git a/crates/cuda-driver/src/qwen_ffi/impl_operation.rs b/crates/cuda-driver/src/qwen_ffi/impl_operation.rs index 4895c173..1fa9ac7d 100644 --- a/crates/cuda-driver/src/qwen_ffi/impl_operation.rs +++ b/crates/cuda-driver/src/qwen_ffi/impl_operation.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Operation { pub(in super::super) fn entry(self) -> &'static CStr { match self { @@ -81,8 +80,7 @@ impl Operation { return kar_ple_layout(self, 1).expect("fixed minimum KAR PLE geometry"); } if QSA_OPERATIONS.contains(&self) { - return qsa_layout(self, u32::from(self == Self::QsaAttend)) - .expect("fixed minimum QSA geometry"); + return qsa_layout(self, u32::from(self == Self::QsaAttend)).expect("fixed minimum QSA geometry"); } if let Some(layout) = moe_layout(self) { return layout; @@ -162,42 +160,17 @@ impl Operation { Self::Down | Self::Up | Self::InjectProjection => { unreachable!("checked fixed MMVF geometry above") } - Self::Norm => ( - [4 * HC * N, 4 * HC * N, 4 * HC * N, 0], - [4; 4], - 3, - 4, - HC, - N, - 1024, - ), + Self::Norm => ([4 * HC * N, 4 * HC * N, 4 * HC * N, 0], [4; 4], 3, 4, HC, N, 1024), Self::DownSilu => ([4 * H, 4 * H, 0, 0], [4; 4], 2, 2, H, 1, 256), - Self::LayerGate | Self::FinalGate => ( - [4 * HC * N, 4 * HC * N, 4 * HC * N, 4 * N], - [4; 4], - 4, - 12, - N, - HC, - 256, - ), - Self::InjectResidual => ( - [4 * HC * N, 4 * N, 4 * HC, 4 * HC * N], - [4; 4], - 4, - 8, - HC * N, - 1, - 256, - ), + Self::LayerGate | Self::FinalGate => { + ([4 * HC * N, 4 * HC * N, 4 * HC * N, 4 * N], [4; 4], 4, 12, N, HC, 256) + } + Self::InjectResidual => ([4 * HC * N, 4 * N, 4 * HC, 4 * HC * N], [4; 4], 4, 8, HC * N, 1, 256), Self::Bf16 => unreachable!("minimal checked geometry above"), Self::RouteTop10 => unreachable!("fixed router geometry above"), - Self::GdnConv - | Self::GdnQk - | Self::GdnBeta - | Self::GdnGate - | Self::GdnStep - | Self::GdnOutNorm => unreachable!("fixed GDN geometry above"), + Self::GdnConv | Self::GdnQk | Self::GdnBeta | Self::GdnGate | Self::GdnStep | Self::GdnOutNorm => { + unreachable!("fixed GDN geometry above") + } Self::PleValue | Self::PleValueFull | Self::PleNorm @@ -210,11 +183,7 @@ impl Operation { } }; let projection = matches!(self, Self::Down | Self::Up | Self::InjectProjection); - let grid = if projection || self == Self::Norm { - rows - } else { - rows.div_ceil(block) - }; + let grid = if projection || self == Self::Norm { rows } else { rows.div_ceil(block) }; let mut full_bytes = [0; 9]; full_bytes[..4].copy_from_slice(&bytes); let mut full_align = [1; 9]; diff --git a/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs b/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs index 73bae3b7..a8ef9bb8 100644 --- a/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs +++ b/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Operation { pub(in super::super) fn has_epsilon(self) -> bool { matches!(self, Self::Norm | Self::GdnQk | Self::GdnOutNorm) @@ -12,24 +11,12 @@ impl Operation { pub(in super::super) fn kar_ple_layout(operation: Operation, value: u32) -> Result { let (bytes, align, count, outputs, grid, block, parameter) = match operation { - Operation::KarPleScatter if (1..=16).contains(&value) => ( - [67_108_864, value as usize * 56, 0, 0, 0, 0, 0, 0, 0], - [1, 4, 1, 1, 1, 1, 1, 1, 0], - 2, - 1, - value, - 64, - 2, - ), - Operation::KarPleDecode if (1..=65_535).contains(&value) => ( - [67_108_864, 64, value as usize * 8, 10_240, 0, 0, 0, 0, 0], - [1, 4, 2, 4, 1, 1, 1, 1, 0], - 4, - 8, - 16, - 256, - 4, - ), + Operation::KarPleScatter if (1..=16).contains(&value) => { + ([67_108_864, value as usize * 56, 0, 0, 0, 0, 0, 0, 0], [1, 4, 1, 1, 1, 1, 1, 1, 0], 2, 1, value, 64, 2) + } + Operation::KarPleDecode if (1..=65_535).contains(&value) => { + ([67_108_864, 64, value as usize * 8, 10_240, 0, 0, 0, 0, 0], [1, 4, 2, 4, 1, 1, 1, 1, 0], 4, 8, 16, 256, 4) + } _ => return Err(Error::InvalidQwenShape), }; Ok(Layout { @@ -60,10 +47,7 @@ pub(in super::super) fn bf16_layout(rows: usize, columns: usize) -> Result Result Result<[u8; 32]> { - if ptx.len() < 2 - || ptx.last() != Some(&0) - || ptx[..ptx.len() - 1].contains(&0) - || !ptx.is_ascii() - { + if ptx.len() < 2 || ptx.last() != Some(&0) || ptx[..ptx.len() - 1].contains(&0) || !ptx.is_ascii() { return Err(Error::UnsupportedQwenOperation); } Ok(sha256(&ptx[..ptx.len() - 1])) @@ -121,11 +101,7 @@ impl Asset { || self.receipt.version != 1 || self.receipt.abi_version != 1 || self.receipt.topology - != if operation == Operation::RouteTop10 { - [512, 10, 1] - } else { - [N as u32, HC as u32, H as u32] - } + != if operation == Operation::RouteTop10 { [512, 10, 1] } else { [N as u32, HC as u32, H as u32] } || self.receipt.source_sha256 == [0; 32] || self.receipt.oracle_sha256 == [0; 32] || self.receipt.compiler.is_empty() @@ -139,11 +115,7 @@ impl Asset { // allocation do not inherit this proof. The static allocation cannot // change through safe Rust while retained by this immutable reference. if let Some(proof) = memo.get().filter(|proof| std::ptr::eq(proof.ptx, self.ptx)) { - return if proof.digest == self.receipt.ptx_sha256 { - Ok(()) - } else { - Err(Error::UnsupportedQwenOperation) - }; + return if proof.digest == self.receipt.ptx_sha256 { Ok(()) } else { Err(Error::UnsupportedQwenOperation) }; } let digest = inspect(self.ptx)?; if digest != self.receipt.ptx_sha256 { @@ -152,10 +124,7 @@ impl Asset { // A racing initializer may have retained another allocation. This // invocation still has its own complete successful validation, and a // later call uses the proof only if its exact allocation matches. - let _ = memo.set(PtxProof { - ptx: self.ptx, - digest, - }); + let _ = memo.set(PtxProof { ptx: self.ptx, digest }); Ok(()) } } @@ -201,32 +170,19 @@ pub(super) const fn qsa_asset(operation: Operation) -> Asset { | Operation::QsaRopeK | Operation::QsaRopeIndexQ | Operation::QsaIndexAppend - | Operation::QsaPackKv => ( - concat!(include_str!("../../assets/qwen_qsa_native.ptx"), "\0").as_bytes(), - QSA_NATIVE_RECEIPT, - ), - Operation::QsaBlockScores | Operation::QsaBlockTopk => ( - concat!(include_str!("../../assets/qwen_qsa_select.ptx"), "\0").as_bytes(), - QSA_SELECT_RECEIPT, - ), - Operation::QsaAttend => ( - concat!(include_str!("../../assets/qwen_qsa_attention.ptx"), "\0").as_bytes(), - QSA_ATTENTION_RECEIPT, - ), - Operation::QsaGate => ( - concat!( - include_str!("../../assets/qwen_qsa_attention_native.ptx"), - "\0" - ) - .as_bytes(), - QSA_GATE_RECEIPT, - ), + | Operation::QsaPackKv => { + (concat!(include_str!("../../assets/qwen_qsa_native.ptx"), "\0").as_bytes(), QSA_NATIVE_RECEIPT) + } + Operation::QsaBlockScores | Operation::QsaBlockTopk => { + (concat!(include_str!("../../assets/qwen_qsa_select.ptx"), "\0").as_bytes(), QSA_SELECT_RECEIPT) + } + Operation::QsaAttend => { + (concat!(include_str!("../../assets/qwen_qsa_attention.ptx"), "\0").as_bytes(), QSA_ATTENTION_RECEIPT) + } + Operation::QsaGate => { + (concat!(include_str!("../../assets/qwen_qsa_attention_native.ptx"), "\0").as_bytes(), QSA_GATE_RECEIPT) + } _ => panic!("not a fixed QSA operation"), }; - Asset { - operation, - ptx, - receipt, - pin: receipt, - } + Asset { operation, ptx, receipt, pin: receipt } } diff --git a/crates/cuda-driver/src/qwen_ffi/mock_asset_fn.rs b/crates/cuda-driver/src/qwen_ffi/mock_asset_fn.rs index 53bd918d..bdf802c7 100644 --- a/crates/cuda-driver/src/qwen_ffi/mock_asset_fn.rs +++ b/crates/cuda-driver/src/qwen_ffi/mock_asset_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(test)] pub(in super::super) fn mock_asset(operation: Operation) -> Asset { // CPU only: these bytes are never registered in the production map and @@ -19,26 +18,17 @@ pub(in super::super) fn mock_asset(operation: Operation) -> Asset { qualification_receipt: "private CPU mock; never production admission", comparison: "private control flow only; no numerical proof", abi_version: 1, - topology: if operation == Operation::RouteTop10 { - [512, 10, 1] - } else { - [N as u32, HC as u32, H as u32] - }, + topology: if operation == Operation::RouteTop10 { [512, 10, 1] } else { [N as u32, HC as u32, H as u32] }, }; - Asset { - operation, - ptx, - receipt, - pin: receipt, - } + Asset { operation, ptx, receipt, pin: receipt } } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64", feature = "cuda-driver"))] pub(crate) fn q6_batch_preview_ptx() -> Result<&'static [u8]> { const PTX: &[u8] = concat!(include_str!("../q6_batch_preview.ptx"), "\0").as_bytes(); const PIN: [u8; 32] = [ - 106, 77, 67, 228, 26, 69, 217, 159, 187, 170, 227, 145, 112, 56, 226, 129, 241, 29, 4, 55, - 14, 2, 89, 234, 112, 38, 129, 20, 66, 150, 222, 121, + 106, 77, 67, 228, 26, 69, 217, 159, 187, 170, 227, 145, 112, 56, 226, 129, 241, 29, 4, 55, 14, 2, 89, 234, 112, + 38, 129, 20, 66, 150, 222, 121, ]; if inspect_ptx(PTX)? != PIN { return Err(Error::UnsupportedQwenOperation); @@ -50,9 +40,8 @@ pub(crate) fn q6_batch_preview_ptx() -> Result<&'static [u8]> { pub(in super::super) fn gr_batch_preview_ptx() -> Result<&'static [u8]> { const PTX: &[u8] = concat!(include_str!("../gr_batch_preview.ptx"), "\0").as_bytes(); const PIN: [u8; 32] = [ - 0xc8, 0x56, 0xb6, 0xf5, 0x2d, 0x41, 0xd7, 0xe8, 0xf8, 0x8d, 0x7c, 0x63, 0xed, 0x68, 0x3b, - 0x94, 0x73, 0x10, 0x08, 0x87, 0x10, 0xf6, 0x62, 0xbc, 0xad, 0x0a, 0xfc, 0xed, 0x3e, 0xf6, - 0x5c, 0xac, + 0xc8, 0x56, 0xb6, 0xf5, 0x2d, 0x41, 0xd7, 0xe8, 0xf8, 0x8d, 0x7c, 0x63, 0xed, 0x68, 0x3b, 0x94, 0x73, 0x10, + 0x08, 0x87, 0x10, 0xf6, 0x62, 0xbc, 0xad, 0x0a, 0xfc, 0xed, 0x3e, 0xf6, 0x5c, 0xac, ]; if inspect_ptx(PTX)? != PIN { return Err(Error::UnsupportedQwenOperation); diff --git a/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs b/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs index 837c3993..46a3bf73 100644 --- a/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs +++ b/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn mtp_s2_full_layout(operation: Operation, expert: u32) -> Result { if expert >= 512 { return Err(Error::InvalidQwenShape); @@ -41,22 +40,12 @@ pub(in super::super) fn mtp_s2_full_layout(operation: Operation, expert: u32) -> pub(super) fn mtp_extended_layout(operation: Operation) -> Option { let (bytes, align, count, outputs, grid, block) = match operation { - Operation::MtpGrAttentionDown => ( - [40960, 40960, 6553600, 81920, 1280, 16, 16, 0, 0], - [16, 16, 16, 16, 16, 4, 4, 1, 1], - 7, - 112, - 41, - 256, - ), - Operation::MtpGrAttentionUp => ( - [40960, 40960, 6553600, 1280, 16, 10240, 0, 0, 0], - [16, 16, 16, 16, 4, 16, 1, 1, 1], - 6, - 32, - 80, - 256, - ), + Operation::MtpGrAttentionDown => { + ([40960, 40960, 6553600, 81920, 1280, 16, 16, 0, 0], [16, 16, 16, 16, 16, 4, 4, 1, 1], 7, 112, 41, 256) + } + Operation::MtpGrAttentionUp => { + ([40960, 40960, 6553600, 1280, 16, 10240, 0, 0, 0], [16, 16, 16, 16, 4, 16, 1, 1, 1], 6, 32, 80, 256) + } Operation::MtpGrMlpDown => ( [40960, 10240, 16, 40960, 6553600, 81920, 1280, 16, 16], [16, 16, 4, 16, 16, 16, 16, 4, 4], @@ -73,46 +62,13 @@ pub(super) fn mtp_extended_layout(operation: Operation) -> Option { 80, 256, ), - Operation::MtpQuant2560 => ( - [10240, 2720, 320, 0, 0, 0, 0, 0, 0], - [4, 4, 4, 1, 1, 1, 1, 1, 1], - 3, - 6, - 1, - 128, - ), - Operation::MtpQuant640 => ( - [2560, 680, 80, 0, 0, 0, 0, 0, 0], - [4, 4, 4, 1, 1, 1, 1, 1, 1], - 3, - 6, - 1, - 128, - ), - Operation::MtpS2GateUp => ( - [20480, 2560, 2720, 320, 128, 0, 0, 0, 0], - [8, 2, 4, 4, 4, 1, 1, 1, 1], - 5, - 16, - 1, - 256, - ), - Operation::MtpS2Down => ( - [10240, 1280, 680, 80, 256, 0, 0, 0, 0], - [8, 2, 4, 4, 4, 1, 1, 1, 1], - 5, - 16, - 1, - 256, - ), - Operation::MtpS2Swiglu => ( - [5120, 2560, 0, 0, 0, 0, 0, 0, 0], - [4, 4, 1, 1, 1, 1, 1, 1, 1], - 2, - 2, - 3, - 256, - ), + Operation::MtpQuant2560 => ([10240, 2720, 320, 0, 0, 0, 0, 0, 0], [4, 4, 4, 1, 1, 1, 1, 1, 1], 3, 6, 1, 128), + Operation::MtpQuant640 => ([2560, 680, 80, 0, 0, 0, 0, 0, 0], [4, 4, 4, 1, 1, 1, 1, 1, 1], 3, 6, 1, 128), + Operation::MtpS2GateUp => { + ([20480, 2560, 2720, 320, 128, 0, 0, 0, 0], [8, 2, 4, 4, 4, 1, 1, 1, 1], 5, 16, 1, 256) + } + Operation::MtpS2Down => ([10240, 1280, 680, 80, 256, 0, 0, 0, 0], [8, 2, 4, 4, 4, 1, 1, 1, 1], 5, 16, 1, 256), + Operation::MtpS2Swiglu => ([5120, 2560, 0, 0, 0, 0, 0, 0, 0], [4, 4, 1, 1, 1, 1, 1, 1, 1], 2, 2, 3, 256), _ => return None, }; Some(Layout { @@ -134,25 +90,9 @@ pub(super) fn mtp_extended_layout(operation: Operation) -> Option { } pub(super) fn mtp_input_layout(operation: Operation) -> Option { let (bytes, count, rows, columns, grid, block) = match operation { - Operation::MtpEmbeddingNorm => { - ([10240, 10240, 10240, 0, 0, 0, 0, 0, 0], 3, 1, 2560, 1, 1024) - } - Operation::MtpHiddenNorm => ( - [40960, 40960, 40960, 0, 0, 0, 0, 0, 0], - 3, - 1, - 10240, - 1, - 1024, - ), - Operation::MtpBroadcast => ( - [40960, 10240, 40960, 0, 0, 0, 0, 0, 0], - 3, - 10240, - 2560, - 40, - 256, - ), + Operation::MtpEmbeddingNorm => ([10240, 10240, 10240, 0, 0, 0, 0, 0, 0], 3, 1, 2560, 1, 1024), + Operation::MtpHiddenNorm => ([40960, 40960, 40960, 0, 0, 0, 0, 0, 0], 3, 1, 10240, 1, 1024), + Operation::MtpBroadcast => ([40960, 10240, 40960, 0, 0, 0, 0, 0, 0], 3, 10240, 2560, 40, 256), _ => return None, }; Some(Layout { @@ -185,17 +125,7 @@ pub(in super::super) fn mtp_dense_layout(operation: Operation, position: u32) -> let scalar = chunks as usize * 24 * 4; let (bytes, align, count, outputs, grid, grid_y, integer) = match operation { Operation::MtpDenseChunk => ( - [ - 24576, - width as usize * 1024, - width as usize * 1024, - acc, - scalar, - scalar, - 0, - 0, - 0, - ], + [24576, width as usize * 1024, width as usize * 1024, acc, scalar, scalar, 0, 0, 0], [16, 16, 16, 4, 4, 4, 1, 1, 0], 6, 56, @@ -203,15 +133,9 @@ pub(in super::super) fn mtp_dense_layout(operation: Operation, position: u32) -> 2, None, ), - Operation::MtpDenseMerge => ( - [acc, scalar, scalar, 24576, 0, 0, 0, 0, 0], - [4, 4, 4, 4, 1, 1, 1, 1, 0], - 4, - 8, - 24, - 1, - Some((chunks, 4)), - ), + Operation::MtpDenseMerge => { + ([acc, scalar, scalar, 24576, 0, 0, 0, 0, 0], [4, 4, 4, 4, 1, 1, 1, 1, 0], 4, 8, 24, 1, Some((chunks, 4))) + } _ => return Err(Error::InvalidQwenShape), }; Ok(Layout { diff --git a/crates/cuda-driver/src/qwen_ffi/qsa_layout_fn.rs b/crates/cuda-driver/src/qwen_ffi/qsa_layout_fn.rs index 9f862335..309b3851 100644 --- a/crates/cuda-driver/src/qwen_ffi/qsa_layout_fn.rs +++ b/crates/cuda-driver/src/qwen_ffi/qsa_layout_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Closed source-defined QSA extents. Position and selected width are the only /// semantic scalars; native index/launch calculations never come from callers. pub(in super::super) fn qsa_layout(operation: Operation, value: u32) -> Result { @@ -18,80 +17,22 @@ pub(in super::super) fn qsa_layout(operation: Operation, value: u32) -> Result ([49152, 24576, 24576, 0, 0, 0, 0, 0, 0], 3, 6, 24, 1, None), Operation::QsaNormQ => ([24576, 1024, 24576, 0, 0, 0, 0, 0, 0], 3, 4, 24, 1, None), Operation::QsaNormK => ([2048, 1024, 2048, 0, 0, 0, 0, 0, 0], 3, 4, 2, 1, None), Operation::QsaNormIndexQ => ([2048, 512, 2048, 0, 0, 0, 0, 0, 0], 3, 4, 4, 1, None), - Operation::QsaRopeQ => ( - [24576, 24576, 0, 0, 0, 0, 0, 0, 0], - 2, - 2, - 1, - 24, - Some((value, 1)), - ), - Operation::QsaRopeK => ( - [2048, 2048, 0, 0, 0, 0, 0, 0, 0], - 2, - 2, - 1, - 2, - Some((value, 1)), - ), - Operation::QsaRopeIndexQ => ( - [2048, 2048, 0, 0, 0, 0, 0, 0, 0], - 2, - 2, - 1, - 4, - Some((value, 1)), - ), - Operation::QsaIndexAppend => ( - [512, 512, 2048, 2560, 0, 0, 0, 0, 0], - 4, - 8, - 1, - 1, - Some((value, 4)), - ), + Operation::QsaRopeQ => ([24576, 24576, 0, 0, 0, 0, 0, 0, 0], 2, 2, 1, 24, Some((value, 1))), + Operation::QsaRopeK => ([2048, 2048, 0, 0, 0, 0, 0, 0, 0], 2, 2, 1, 2, Some((value, 1))), + Operation::QsaRopeIndexQ => ([2048, 2048, 0, 0, 0, 0, 0, 0, 0], 2, 2, 1, 4, Some((value, 1))), + Operation::QsaIndexAppend => ([512, 512, 2048, 2560, 0, 0, 0, 0, 0], 4, 8, 1, 1, Some((value, 4))), Operation::QsaPackKv => ([2048, 2048, 1024, 1024, 0, 0, 0, 0, 0], 4, 12, 2, 1, None), - Operation::QsaBlockScores => ( - [pooled, 512, 2048, scores, 0, 0, 0, 0, 0], - 4, - 8, - 256, - 1, - Some((value, 4)), - ), - Operation::QsaBlockTopk => ( - [scores, 8204, 0, 0, 0, 0, 0, 0, 0], - 2, - 2, - 1, - 1, - Some((value, 2)), - ), - Operation::QsaAttend => ( - [24576, packed, packed, 24576, 0, 0, 0, 0, 0], - 4, - 8, - 24, - 1, - Some((value, 4)), - ), + Operation::QsaBlockScores => ([pooled, 512, 2048, scores, 0, 0, 0, 0, 0], 4, 8, 256, 1, Some((value, 4))), + Operation::QsaBlockTopk => ([scores, 8204, 0, 0, 0, 0, 0, 0, 0], 2, 2, 1, 1, Some((value, 2))), + Operation::QsaAttend => ([24576, packed, packed, 24576, 0, 0, 0, 0, 0], 4, 8, 24, 1, Some((value, 4))), Operation::QsaGate => ([24576, 24576, 24576, 0, 0, 0, 0, 0, 0], 3, 4, 24, 1, None), _ => return Err(Error::InvalidQwenShape), }; @@ -121,11 +62,7 @@ pub(in super::super) fn qsa_layout(operation: Operation, value: u32) -> Result Option { pub(super) fn gdn_layout(operation: Operation) -> Option { let (bytes, count, outputs, grid, grid_z, block, block_y) = match operation { - Operation::GdnConv => ( - [122880, 40960, 163840, 122880, 40960, 40960, 0, 0, 0], - 6, - 0b111000, - 40, - 1, - 256, - 1, - ), + Operation::GdnConv => ([122880, 40960, 163840, 122880, 40960, 40960, 0, 0, 0], 6, 0b111000, 40, 1, 256, 1), Operation::GdnQk => ([40960, 40960, 0, 0, 0, 0, 0, 0, 0], 2, 0b10, 32, 1, 256, 1), Operation::GdnBeta => ([192, 192, 0, 0, 0, 0, 0, 0, 0], 2, 0b10, 1, 1, 256, 1), Operation::GdnGate => ([192, 192, 192, 192, 0, 0, 0, 0, 0], 4, 0b1000, 1, 1, 256, 1), - Operation::GdnStep => ( - [3145728, 8192, 8192, 24576, 192, 192, 3145728, 24576, 0], - 8, - 0b11000000, - 48, - 32, - 32, - 4, - ), - Operation::GdnOutNorm => ( - [24576, 24576, 512, 24576, 0, 0, 0, 0, 0], - 4, - 0b1000, - 48, - 1, - 256, - 1, - ), + Operation::GdnStep => ([3145728, 8192, 8192, 24576, 192, 192, 3145728, 24576, 0], 8, 0b11000000, 48, 32, 32, 4), + Operation::GdnOutNorm => ([24576, 24576, 512, 24576, 0, 0, 0, 0, 0], 4, 0b1000, 48, 1, 256, 1), _ => return None, }; Some(Layout { diff --git a/crates/cuda-driver/src/qwen_ffi/tests.rs b/crates/cuda-driver/src/qwen_ffi/tests.rs index f0449a64..0d966e6c 100644 --- a/crates/cuda-driver/src/qwen_ffi/tests.rs +++ b/crates/cuda-driver/src/qwen_ffi/tests.rs @@ -4,9 +4,9 @@ use super::*; #[path = "tests/full_s2_expert_scalar.rs"] mod full_s2_expert_scalar; -#[path = "tests/qsa_new_literal_abi_scalar.rs"] -mod qsa_new_literal_abi_scalar; #[path = "tests/moe_fixed_pointer_abi_extents.rs"] mod moe_fixed_pointer_abi_extents; #[path = "tests/mtp_new_qualified_assets.rs"] mod mtp_new_qualified_assets; +#[path = "tests/qsa_new_literal_abi_scalar.rs"] +mod qsa_new_literal_abi_scalar; 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 de1f88fa..5def0606 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 @@ -6,33 +6,15 @@ use super::*; #[test] fn full_s2_expert_scalar_and_fixed_bank_abi() { for (operation, q, scales, out, name) in [ - ( - Operation::MtpS2GateUpFull, - 2720, - 320, - 5120, - c"leleka_mtp_s2_gate_up_full", - ), - ( - Operation::MtpS2DownFull, - 680, - 80, - 10240, - c"leleka_mtp_s2_down_full", - ), + (Operation::MtpS2GateUpFull, 2720, 320, 5120, c"leleka_mtp_s2_gate_up_full"), + (Operation::MtpS2DownFull, 680, 80, 10240, c"leleka_mtp_s2_down_full"), ] { 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_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_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); @@ -50,10 +32,7 @@ fn full_s2_expert_scalar_and_fixed_bank_abi() { } } for expert in [512, u32::MAX] { - assert!(matches!( - mtp_s2_full_layout(operation, expert), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(mtp_s2_full_layout(operation, expert), Err(Error::InvalidQwenShape))); } } } @@ -71,8 +50,7 @@ fn mtp_new_nine_pointer_owner_and_scaled_packets() { asset.validate(operation).unwrap(); let layout = operation.layout(); assert_eq!(layout.count, count); - let handles = - std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000)); + let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic((i as u64 + 1) * 0x1000000)); let owner = Arguments::with_layout(operation, layout, handles, 0.0); let mut moved = std::hint::black_box(vec![owner]).pop().unwrap(); let table = moved.parameters(); @@ -84,59 +62,32 @@ fn mtp_new_nine_pointer_owner_and_scaled_packets() { assert!((*table.add(count)).is_null()); } } - assert_eq!( - &Operation::MtpQuant2560.layout().bytes[..3], - &[10240, 2720, 320] - ); - assert_eq!( - &Operation::MtpQuant640.layout().bytes[..3], - &[2560, 680, 80] - ); + assert_eq!(&Operation::MtpQuant2560.layout().bytes[..3], &[10240, 2720, 320]); + assert_eq!(&Operation::MtpQuant640.layout().bytes[..3], &[2560, 680, 80]); assert_eq!(Operation::MtpGrMlpDown.layout().outputs, 0b111000000); assert_eq!(Operation::MtpGrMlpUp.layout().outputs, 0b110000000); } #[test] fn gr_saturation_asset_requires_exact_independent_qualification_and_bytes() { - assert_eq!( - sha256(include_bytes!("../../offline_gr_kernel.cu")), - GR_RECEIPT.source_sha256 - ); - for operation in [ - Operation::Norm, - Operation::DownSilu, - Operation::LayerGate, - Operation::FinalGate, - Operation::InjectResidual, - ] { + assert_eq!(sha256(include_bytes!("../../offline_gr_kernel.cu")), GR_RECEIPT.source_sha256); + for operation in + [Operation::Norm, Operation::DownSilu, Operation::LayerGate, Operation::FinalGate, Operation::InjectResidual] + { let admitted = asset(operation).expect("independently reviewed GR asset"); assert_eq!(admitted.validate(operation), Ok(())); assert_eq!(admitted.receipt, GR_RECEIPT); let mut bad = GR_RECEIPT; bad.ptx_sha256[0] ^= 1; - let corrupted = Asset { - operation, - ptx: admitted.ptx, - receipt: bad, - pin: bad, - }; - assert_eq!( - corrupted.validate(operation), - Err(Error::UnsupportedQwenOperation) - ); + let corrupted = Asset { operation, ptx: admitted.ptx, receipt: bad, pin: bad }; + assert_eq!(corrupted.validate(operation), Err(Error::UnsupportedQwenOperation)); } } #[test] fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() { - assert_eq!( - sha256(include_bytes!("../../offline_kar_ple_kernel.cu")), - KAR_PLE_RECEIPT.source_sha256 - ); - assert_eq!( - sha256(include_bytes!("../../kar_ple_fixed.ptx")), - KAR_PLE_RECEIPT.ptx_sha256 - ); + assert_eq!(sha256(include_bytes!("../../offline_kar_ple_kernel.cu")), KAR_PLE_RECEIPT.source_sha256); + 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" @@ -145,28 +96,14 @@ fn kar_ple_qualified_receipt_matches_frozen_source_and_ptx() { let admitted = asset(op).unwrap(); assert_eq!(admitted.receipt, KAR_PLE_RECEIPT); admitted.validate(op).unwrap(); - assert!( - std::str::from_utf8(admitted.ptx) - .unwrap() - .contains(op.entry().to_str().unwrap()) - ); + assert!(std::str::from_utf8(admitted.ptx).unwrap().contains(op.entry().to_str().unwrap())); } } #[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::KarPleScatter, 16, c"leleka_kar_ple_scatter", vec![67_108_864, 896], vec![1, 4], 1, 16, 64, 2), ( Operation::KarPleDecode, 65_535, @@ -183,31 +120,12 @@ fn kar_ple_fixed_abi_and_boundary_refusals() { 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.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(); + 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 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 @@ -220,21 +138,12 @@ fn kar_ple_fixed_abi_and_boundary_refusals() { assert!((*table.add(scalar_index + 1)).is_null()); } } - for (op, maximum) in [ - (Operation::KarPleScatter, 16), - (Operation::KarPleDecode, 65_535), - ] { + for (op, maximum) in [(Operation::KarPleScatter, 16), (Operation::KarPleDecode, 65_535)] { assert!(kar_ple_layout(op, 1).is_ok()); assert!(kar_ple_layout(op, maximum).is_ok()); for invalid in [0, maximum + 1, u32::MAX] { - assert!(matches!( - kar_ple_layout(op, invalid), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(kar_ple_layout(op, invalid), Err(Error::InvalidQwenShape))); } } - assert!(matches!( - kar_ple_layout(Operation::Norm, 1), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(kar_ple_layout(Operation::Norm, 1), Err(Error::InvalidQwenShape))); } 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 0044c4fc..f0321532 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 @@ -3,64 +3,27 @@ #[allow(unused_imports)] use super::*; - #[test] fn moe_fixed_pointer_abi_extents_and_qualified_receipts() { // Literal expectations come from STRA-167 AD v1 / STRA-172 AD v8. for (operation, entry, bytes, align, count, outputs, grid) in [ - ( - Operation::MoeSwiglu, - c"leleka_moe_swiglu_f32", - [2560, 2560, 2560, 0], - [4, 4, 4, 4], - 3, - 4, - 3, - ), - ( - Operation::MoeSharedScalar, - c"leleka_moe_shared_gate_f32_bf16", - [10240, 5120, 4, 0], - [4, 2, 4, 4], - 3, - 4, - 1, - ), - ( - 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, - ), + (Operation::MoeSwiglu, c"leleka_moe_swiglu_f32", [2560, 2560, 2560, 0], [4, 4, 4, 4], 3, 4, 3), + (Operation::MoeSharedScalar, c"leleka_moe_shared_gate_f32_bf16", [10240, 5120, 4, 0], [4, 2, 4, 4], 3, 4, 1), + (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_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 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. @@ -76,20 +39,9 @@ fn moe_fixed_pointer_abi_extents_and_qualified_receipts() { #[test] fn qwen_hash_known_vectors_and_padding_boundaries() { - let hex = |bytes: &[u8]| { - sha256(bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::() - }; - assert_eq!( - hex(b""), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - assert_eq!( - hex(b"abc"), - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" - ); + let hex = |bytes: &[u8]| sha256(bytes).iter().map(|b| format!("{b:02x}")).collect::(); + assert_eq!(hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + assert_eq!(hex(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); assert_eq!( hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" @@ -110,11 +62,7 @@ fn qwen_raw_abi_remains_stable_after_moves() { // 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) - { + 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); } @@ -128,10 +76,7 @@ fn qwen_raw_abi_remains_stable_after_moves() { 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_eq!((*(*table.add(layout.count)).cast::()).to_bits(), 1e-6f32.to_bits()); } } } @@ -145,11 +90,7 @@ fn qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry() { assert_eq!((layout.grid, layout.block, layout.block_y), (1, 32, 8)); assert_eq!(layout.count, 3); assert!(!layout.projection); - let mut args = Arguments::new( - op, - [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic), - 0.0, - ); + let mut args = Arguments::new(op, [11, 22, 33, 44, 55, 66, 77, 88, 0].map(ffi::BufferHandle::synthetic), 0.0); let parameters = args.parameters(); // SAFETY: read the initialized private table while its owner is live. // The exact router ABI has no hidden scalar/status/count arguments. @@ -159,58 +100,19 @@ fn qwen_router_has_exact_three_pointer_abi_and_32_by_8_geometry() { } let admitted = asset(op).expect("independently qualified router component"); assert_eq!(admitted.validate(op), Ok(())); - assert_eq!( - admitted.receipt.qualification_receipt, - "STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388" - ); + assert_eq!(admitted.receipt.qualification_receipt, "STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388"); } #[test] fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() { // Expectations are the independently frozen STRA-161/172 contract. for (op, entry, bytes, outputs, grid) in [ - ( - Operation::PleValue, - c"leleka_ple_value_bf16_f32", - vec![10240, 327680, 256], - 4, - 1, - ), - ( - Operation::PleNorm, - c"leleka_ple_grouped_norm_f32", - vec![40960, 40960, 40960], - 4, - 4, - ), - ( - Operation::PleGate, - c"leleka_ple_signed_gate_f32", - vec![40960, 40960, 16], - 4, - 4, - ), - ( - Operation::PleBroadcast, - c"leleka_ple_broadcast_f32", - vec![10240, 16, 40960], - 4, - 40, - ), - ( - 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, - ), + (Operation::PleValue, c"leleka_ple_value_bf16_f32", vec![10240, 327680, 256], 4, 1), + (Operation::PleNorm, c"leleka_ple_grouped_norm_f32", vec![40960, 40960, 40960], 4, 4), + (Operation::PleGate, c"leleka_ple_signed_gate_f32", vec![40960, 40960, 16], 4, 4), + (Operation::PleBroadcast, c"leleka_ple_broadcast_f32", vec![10240, 16, 40960], 4, 40), + (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); @@ -218,26 +120,14 @@ fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() { 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_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 - }; + 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 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. @@ -248,19 +138,11 @@ fn qwen_ple_fixed_geometry_has_pointer_only_abi_and_exact_component_receipt() { } 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" - ); + 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, - }; + let corrupt = Asset { operation: op, ptx: admitted.ptx, receipt: bad, pin: bad }; assert_eq!(corrupt.validate(op), Err(Error::UnsupportedQwenOperation)); } } 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 07ca564c..f23565d5 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 @@ -16,38 +16,17 @@ fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() { 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, - }; + 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_eq!(forged.validate(operation), Err(Error::UnsupportedQwenOperation)); } - for (position, width, chunks) in [ - (0, 1, 1), - (63, 64, 1), - (64, 65, 2), - (32767, 32768, 512), - (262143, 32768, 512), - ] { + 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.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 - ) + (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); @@ -67,13 +46,7 @@ fn mtp_new_qualified_assets_and_fixed_dense_scalar_abi() { assert_eq!((merge.grid, merge.block, merge.outputs), (24, 256, 8)); } for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] { - assert_eq!( - mtp_dense_layout(Operation::MtpDenseChunk, position).err(), - Some(Error::InvalidQwenShape) - ); + assert_eq!(mtp_dense_layout(Operation::MtpDenseChunk, position).err(), Some(Error::InvalidQwenShape)); } - assert_eq!( - mtp_dense_layout(Operation::Norm, 0).err(), - Some(Error::InvalidQwenShape) - ); + assert_eq!(mtp_dense_layout(Operation::Norm, 0).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 ad701f85..0ee90032 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 @@ -7,136 +7,19 @@ use super::*; 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, - ), + (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); @@ -154,10 +37,7 @@ fn qsa_new_literal_abi_scalar_order_and_geometry() { (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(); + 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); @@ -221,18 +101,12 @@ 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))); } - for operation in QSA_OPERATIONS - .into_iter() - .filter(|op| *op != Operation::QsaAttend) - { + 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()); assert!(qsa_layout(operation, crate::MAX_CONTEXT_CELLS as u32 - 1).is_ok()); for position in [crate::MAX_CONTEXT_CELLS as u32, u32::MAX] { - assert!(matches!( - qsa_layout(operation, position), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(qsa_layout(operation, position), Err(Error::InvalidQwenShape))); } } for (width, extent) in [(1, 1024), (2051, 2100224)] { @@ -241,13 +115,7 @@ fn qsa_new_position_block_boundaries_and_attention_width_refusals() { assert_eq!(layout.integer, Some((width, 4))); } for width in [0, 2052, u32::MAX] { - assert!(matches!( - qsa_layout(Operation::QsaAttend, width), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(qsa_layout(Operation::QsaAttend, width), Err(Error::InvalidQwenShape))); } - assert!(matches!( - qsa_layout(Operation::Norm, 0), - Err(Error::InvalidQwenShape) - )); + assert!(matches!(qsa_layout(Operation::Norm, 0), Err(Error::InvalidQwenShape))); } diff --git a/crates/cuda-driver/src/qwen_shared_tail.rs b/crates/cuda-driver/src/qwen_shared_tail.rs index 2ba1abb1..2816daf3 100644 --- a/crates/cuda-driver/src/qwen_shared_tail.rs +++ b/crates/cuda-driver/src/qwen_shared_tail.rs @@ -20,12 +20,8 @@ const STAGES: [&str; 12] = [ "route-weights", "combined", ]; -const OPERATIONS: [Operation; 4] = [ - Operation::MoeSwiglu, - Operation::MoeSharedScalar, - Operation::MoeSharedScale, - Operation::MoeCombine, -]; +const OPERATIONS: [Operation; 4] = + [Operation::MoeSwiglu, Operation::MoeSharedScalar, Operation::MoeSharedScale, Operation::MoeCombine]; /// Actual existing shared Gate/Up descriptors, selected independently per role. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -113,19 +109,19 @@ enum Command { #[path = "qwen_shared_tail_gpu.rs"] mod shared_tail_gpu; -#[path = "qwen_shared_tail/impl_sharedgukind.rs"] -mod impl_sharedgukind; -#[path = "qwen_shared_tail/impl_sharedexpertworkspace.rs"] -mod impl_sharedexpertworkspace; #[path = "qwen_shared_tail/impl_drop_for_sharedexpertworkspace.rs"] mod impl_drop_for_sharedexpertworkspace; -#[allow(unused_imports)] -use impl_drop_for_sharedexpertworkspace::staging; -#[allow(unused_imports)] -use impl_drop_for_sharedexpertworkspace::status_spans; -#[allow(unused_imports)] -use impl_drop_for_sharedexpertworkspace::first_refusal; +#[path = "qwen_shared_tail/impl_sharedexpertworkspace.rs"] +mod impl_sharedexpertworkspace; +#[path = "qwen_shared_tail/impl_sharedgukind.rs"] +mod impl_sharedgukind; #[allow(unused_imports)] use impl_drop_for_sharedexpertworkspace::append_finite; #[allow(unused_imports)] use impl_drop_for_sharedexpertworkspace::append_projection; +#[allow(unused_imports)] +use impl_drop_for_sharedexpertworkspace::first_refusal; +#[allow(unused_imports)] +use impl_drop_for_sharedexpertworkspace::staging; +#[allow(unused_imports)] +use impl_drop_for_sharedexpertworkspace::status_spans; 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 126a13b3..5ec29fad 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 @@ -10,9 +10,7 @@ impl Drop for SharedExpertWorkspace<'_> { } pub(super) fn staging(bytes: usize) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(bytes) - .map_err(|_| Error::HostAllocation)?; + result.try_reserve_exact(bytes).map_err(|_| Error::HostAllocation)?; result.resize(bytes, 0); Ok(result) } @@ -48,11 +46,7 @@ pub(super) fn append_finite( status: ffi::BufferHandle, words: u32, ) { - commands.push(Command::Guard( - function, - words, - ffi::MmqResidentArguments::finite(source, status, 0, words, 0), - )); + commands.push(Command::Guard(function, words, ffi::MmqResidentArguments::finite(source, status, 0, words, 0))); } pub(super) fn append_projection( commands: &mut Vec, @@ -65,11 +59,7 @@ pub(super) fn append_projection( ) -> Result<()> { let (quant_grid, projection_grid, scratch_bytes) = match kernels.style { ProjectionStyle::Common(kind) => { - let shape = projection_shape(ProjectionSpec { - kind, - rows, - columns, - })?; + let shape = projection_shape(ProjectionSpec { kind, rows, columns })?; projection_ranges(kind, &shape, handles)?; (shape.quant_grid, shape.projection_grid, shape.scratch_bytes) } @@ -93,35 +83,17 @@ pub(super) fn append_projection( ProjectionStyle::Common(_) => commands.push(Command::Common( kernels.project, projection_grid, - ffi::ProjectionArguments::new( - handles[0], - scratch, - handles[2], - rows as u32, - columns as u32, - ), + ffi::ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), )), ProjectionStyle::Q5 => commands.push(Command::Q5( kernels.project, projection_grid, - ffi::Q5ProjectionArguments::new( - handles[0], - scratch, - handles[2], - rows as u32, - columns as u32, - ), + ffi::Q5ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), )), ProjectionStyle::Q6 => commands.push(Command::Q6( kernels.project, projection_grid, - ffi::Q6ProjectionArguments::new( - handles[0], - scratch, - handles[2], - rows as u32, - columns as u32, - ), + ffi::Q6ProjectionArguments::new(handles[0], scratch, handles[2], rows as u32, columns as u32), )), } Ok(()) diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs index 6608e86e..923083b1 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2.rs @@ -3,22 +3,16 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> SharedExpertWorkspace<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } for operation in OPERATIONS { - qwen_ffi::asset(operation) - .ok_or(Error::UnsupportedQwenOperation)? - .validate(operation)?; + qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?.validate(operation)?; } let required = TOTAL.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget) || context.memory_info()?.0 < required { return Err(Error::BudgetExceeded); @@ -40,11 +34,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let common = |format| -> Result { let kind = ProjectionKind::Dense(format); let (quant, project) = context.common_kernels(kind)?; - Ok(Pair { - quant, - project, - style: ProjectionStyle::Common(kind), - }) + Ok(Pair { quant, project, style: ProjectionStyle::Common(kind) }) }; let q4 = common(DenseFormat::Q4_K)?; let q5 = context.q5_kernels()?; @@ -52,23 +42,14 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let xs = common(DenseFormat::IQ4_XS)?; let gu = [ q4, - Pair { - quant: q5.quantize, - project: q5.project, - style: ProjectionStyle::Q5, - }, - Pair { - quant: q6.quantize, - project: q6.project, - style: ProjectionStyle::Q6, - }, + Pair { quant: q5.quantize, project: q5.project, style: ProjectionStyle::Q5 }, + Pair { quant: q6.quantize, project: q6.project, style: ProjectionStyle::Q6 }, xs, ]; let down = [common(DenseFormat::Q8_0)?, common(DenseFormat::IQ4_NL)?]; let mut qwen = [None; 4]; for (i, operation) in OPERATIONS.into_iter().enumerate() { - let asset = - qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; + let asset = qwen_ffi::asset(operation).ok_or(Error::UnsupportedQwenOperation)?; qwen[i] = Some(registered(context, &context.qwen_kernels, asset)?.function); } let module = context.driver.api.load_mmq_resident()?; @@ -77,12 +58,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { context.driver.api.mmq_resident_function(module, 0)?, context.driver.api.mmq_resident_function(module, 1)?, ]; - Ok(Kernels { - gu, - down, - qwen: qwen.map(|x| x.expect("four closed entries resolved")), - guard: finite, - }) + Ok(Kernels { gu, down, qwen: qwen.map(|x| x.expect("four closed entries resolved")), guard: finite }) })(); let pop = guard.finish(); if pop.is_err() { @@ -141,14 +117,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { packed: &DeviceBuffer<'_>, owned: [ffi::BufferHandle; 11], ) -> Result<[ffi::BufferHandle; 6]> { - let buffers = [ - activation, - weights.gate, - weights.up, - weights.down, - weights.scalar, - packed, - ]; + let buffers = [activation, weights.gate, weights.up, weights.down, weights.scalar, packed]; let sizes = [ 10240, weights.gu_kind[0].weight_bytes(), diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs index 03330c9c..043938ba 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_2_2.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> SharedExpertWorkspace<'ctx> { - /// Bounded completed queue, never a general asynchronous/operator API. /// Numeric flags are arbitrated in the original producer order after the final drain. pub fn compose<'lease>( @@ -17,10 +15,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { ) -> Result> { let handles = self.handles()?; let inputs = self.inputs(activation, &weights, packed, handles)?; - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; let kernels = self.kernels.as_ref().ok_or(Error::ContextPoisoned)?; let mut route = staging(40)?; for (value, out) in route_weights.iter().zip(route.as_chunks_mut::<4>().0) { @@ -30,19 +25,11 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { let mut scalar_staging = staging(4)?; let mut final_staging = staging(10240)?; let mut values = Vec::new(); - values - .try_reserve_exact(2560) - .map_err(|_| Error::HostAllocation)?; + values.try_reserve_exact(2560).map_err(|_| Error::HostAllocation)?; values.resize(2560, 0.0); let mut commands = Vec::new(); - commands - .try_reserve_exact(20) - .map_err(|_| Error::HostAllocation)?; - commands.push(Command::Guard( - kernels.guard[0], - 12, - ffi::MmqResidentArguments::zero(handles[9], 12), - )); + commands.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Guard(kernels.guard[0], 12, ffi::MmqResidentArguments::zero(handles[9], 12))); let statuses = status_spans(handles[9])?; append_projection( &mut commands, @@ -53,13 +40,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { 640, 2560, )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[0], - statuses[1], - 640, - ); + append_finite(&mut commands, kernels.guard[1], handles[0], statuses[1], 640); append_projection( &mut commands, kernels.gu[weights.gu_kind[1].index()], @@ -69,26 +50,14 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { 640, 2560, )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[1], - statuses[3], - 640, - ); + append_finite(&mut commands, kernels.guard[1], handles[1], statuses[3], 640); self.append_qwen( &mut commands, kernels.qwen[0], Operation::MoeSwiglu, &[self.buffer(0)?, self.buffer(1)?, self.buffer(2)?], )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[2], - statuses[4], - 640, - ); + append_finite(&mut commands, kernels.guard[1], handles[2], statuses[4], 640); append_projection( &mut commands, kernels.down[weights.down_kind.index()], @@ -98,13 +67,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { 2560, 640, )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[3], - statuses[6], - 2560, - ); + append_finite(&mut commands, kernels.guard[1], handles[3], statuses[6], 2560); self.append_qwen( &mut commands, kernels.qwen[1], @@ -118,40 +81,16 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { Operation::MoeSharedScale, &[self.buffer(3)?, self.buffer(4)?, self.buffer(5)?], )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[5], - statuses[8], - 2560, - ); - append_finite( - &mut commands, - kernels.guard[1], - inputs[5], - statuses[9], - 25600, - ); - append_finite( - &mut commands, - kernels.guard[1], - handles[10], - statuses[10], - 10, - ); + append_finite(&mut commands, kernels.guard[1], handles[5], statuses[8], 2560); + append_finite(&mut commands, kernels.guard[1], inputs[5], statuses[9], 25600); + append_finite(&mut commands, kernels.guard[1], handles[10], statuses[10], 10); self.append_qwen( &mut commands, kernels.qwen[3], Operation::MoeCombine, &[packed, self.buffer(10)?, self.buffer(5)?, self.buffer(6)?], )?; - append_finite( - &mut commands, - kernels.guard[1], - handles[6], - statuses[11], - 2560, - ); + append_finite(&mut commands, kernels.guard[1], handles[6], statuses[11], 2560); // All exact shapes/ranges/aliases/assets and owned staging precede the first write. let guard = match self.context.enter() { Ok(guard) => guard, @@ -170,25 +109,13 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { } // These are blocking cuMemcpyDtoH calls, in one final drain phase, not async DMA. if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[9], &mut status_staging); + operation = self.context.driver.api.copy_to(handles[9], &mut status_staging); } if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[4], &mut scalar_staging); + operation = self.context.driver.api.copy_to(handles[4], &mut scalar_staging); } if operation.is_ok() { - operation = self - .context - .driver - .api - .copy_to(handles[6], &mut final_staging); + operation = self.context.driver.api.copy_to(handles[6], &mut final_staging); } let sync = self.context.driver.api.synchronize(); let pop = guard.finish(); @@ -197,14 +124,7 @@ impl<'ctx> SharedExpertWorkspace<'ctx> { self.context.poisoned.set(true); } if sync.is_err() || pop.is_err() { - std::mem::forget(( - commands, - route, - status_staging, - scalar_staging, - final_staging, - values, - )); + std::mem::forget((commands, route, status_staging, scalar_staging, final_staging, values)); return combine(combine(operation, sync), pop).map(|()| unreachable!("failed drain")); } combine(combine(operation, sync), pop)?; diff --git a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs index b18315d2..ddbb3f32 100644 --- a/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs +++ b/crates/cuda-driver/src/qwen_shared_tail/impl_sharedexpertworkspace/impl_sharedexpertworkspace_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> SharedExpertWorkspace<'ctx> { pub(in super::super) fn append_qwen( &self, diff --git a/crates/cuda-driver/src/qwen_shared_tail_gpu.rs b/crates/cuda-driver/src/qwen_shared_tail_gpu.rs index feb75902..2d22c013 100644 --- a/crates/cuda-driver/src/qwen_shared_tail_gpu.rs +++ b/crates/cuda-driver/src/qwen_shared_tail_gpu.rs @@ -6,12 +6,7 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; const ENABLE: &str = "LELEKA_STRA172_RUN_SHARED_TAIL"; const PRODUCT_WORDS: usize = 9_601; -const GU: [SharedGuKind; 4] = [ - SharedGuKind::Q4K, - SharedGuKind::Q5K, - SharedGuKind::Q6K, - SharedGuKind::Iq4Xs, -]; +const GU: [SharedGuKind; 4] = [SharedGuKind::Q4K, SharedGuKind::Q5K, SharedGuKind::Q6K, SharedGuKind::Iq4Xs]; const DOWN: [SharedDownKind; 2] = [SharedDownKind::Q8_0, SharedDownKind::Iq4Nl]; #[derive(Default, Debug)] @@ -42,15 +37,11 @@ fn original_first_shared_tail_all_products_status_reset_and_cleanup() { let driver = Driver::load().expect("actual CUDA driver"); let device = driver.device(0).expect("device"); let foreign = device.create_context(1024 * 1024).expect("foreign context"); - let tiny = device - .create_context(TOTAL + RESERVE - 1) - .expect("budget refusal context"); + let tiny = device.create_context(TOTAL + RESERVE - 1).expect("budget refusal context"); let budget_refused = matches!(tiny.shared_expert_workspace(), Err(Error::BudgetExceeded)); let tiny_empty = tiny.allocated_bytes() == 0; let tiny_close = tiny.close(); - let context = device - .create_context(160 * 1024 * 1024) - .expect("bounded reserved context"); + let context = device.create_context(160 * 1024 * 1024).expect("bounded reserved context"); let result = catch_unwind(AssertUnwindSafe(|| run(&context, &foreign))); // All run-local owners, including the workspace and RAII alias guard, have // already closed or unwound. Attempt both context drains and destruction @@ -93,31 +84,31 @@ fn original_first_shared_tail_all_products_status_reset_and_cleanup() { #[path = "qwen_shared_tail_gpu/read_fn.rs"] mod read_fn; #[allow(unused_imports)] -use read_fn::read; +use read_fn::down_payload; #[allow(unused_imports)] use read_fn::f32_bytes; #[allow(unused_imports)] use read_fn::finite; #[allow(unused_imports)] +use read_fn::gu_payload; +#[allow(unused_imports)] use read_fn::input; #[allow(unused_imports)] +use read_fn::original_projection; +#[allow(unused_imports)] use read_fn::packet; #[allow(unused_imports)] +use read_fn::read; +#[allow(unused_imports)] use read_fn::scalar_weights; #[allow(unused_imports)] -use read_fn::gu_payload; -#[allow(unused_imports)] -use read_fn::down_payload; -#[allow(unused_imports)] use read_fn::weights; -#[allow(unused_imports)] -use read_fn::original_projection; #[path = "qwen_shared_tail_gpu/original_fn.rs"] mod original_fn; #[allow(unused_imports)] -use original_fn::original; -#[allow(unused_imports)] use original_fn::compare; +#[allow(unused_imports)] +use original_fn::original; #[path = "qwen_shared_tail_gpu/guard_probe_fn.rs"] mod guard_probe_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/qwen_shared_tail_gpu/guard_probe_fn.rs b/crates/cuda-driver/src/qwen_shared_tail_gpu/guard_probe_fn.rs index dc5b60cf..77912298 100644 --- a/crates/cuda-driver/src/qwen_shared_tail_gpu/guard_probe_fn.rs +++ b/crates/cuda-driver/src/qwen_shared_tail_gpu/guard_probe_fn.rs @@ -22,12 +22,7 @@ pub(super) fn guard_probe( )); let foreign_input = foreign.allocate(10240)?; report.guards += usize::from(matches!( - workspace.compose( - &foreign_input, - weights(inputs, gu, down), - &inputs[5], - &routes - ), + workspace.compose(&foreign_input, weights(inputs, gu, down), &inputs[5], &routes), Err(Error::ContextMismatch) )); let wrong_weights = weights(inputs, SharedGuKind::Q5K, down); @@ -62,12 +57,7 @@ pub(super) fn guard_probe( )); let short_packet = context.allocate(102396)?; report.guards += usize::from(matches!( - workspace.compose( - &inputs[0], - weights(inputs, gu, down), - &short_packet, - &routes - ), + workspace.compose(&inputs[0], weights(inputs, gu, down), &short_packet, &routes), Err(Error::InvalidQwenShape) )); let owned = workspace.buffer(6)?.handle.ok_or(Error::ContextPoisoned)?; @@ -87,8 +77,7 @@ pub(super) fn guard_probe( Err(Error::OutputAliasesInput) )); } - report.witness_errors += - usize::from(workspace.generation != generation || workspace.is_failed()); + report.witness_errors += usize::from(workspace.generation != generation || workspace.is_failed()); report.witness_errors += usize::from(read(workspace.buffer(6)?)? != before); Ok(()) } @@ -96,9 +85,7 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result, foreign: &Context<'_>) -> Result, foreign: &Context<'_>) -> Result inputs[1] - .copy_from_range(gu.weight_bytes() - 144, &0x7e00u16.to_le_bytes())?, - 3 => inputs[2] - .copy_from_range(gu.weight_bytes() - 144, &0x7c00u16.to_le_bytes())?, - 4 => inputs[3] - .copy_from_range(down.weight_bytes() - 18, &0x7c00u16.to_le_bytes())?, + 2 => inputs[1].copy_from_range(gu.weight_bytes() - 144, &0x7e00u16.to_le_bytes())?, + 3 => inputs[2].copy_from_range(gu.weight_bytes() - 144, &0x7c00u16.to_le_bytes())?, + 4 => inputs[3].copy_from_range(down.weight_bytes() - 18, &0x7c00u16.to_le_bytes())?, 5 => inputs[4].copy_from_range(5102, &0x7fc1u16.to_le_bytes())?, 6 => inputs[5].copy_from_range(102332, &f32::NAN.to_le_bytes())?, 7 => fault_routes[8] = f32::INFINITY, 8 => inputs[0].copy_from_range(2543 * 4, &f32::MAX.to_le_bytes())?, _ => { - inputs[5] - .copy_from(&f32_bytes(std::iter::repeat_n(f32::MAX, 25_600)))?; + inputs[5].copy_from(&f32_bytes(std::iter::repeat_n(f32::MAX, 25_600)))?; fault_routes = [1.0; 10]; } } @@ -182,17 +156,8 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result "route-weights", _ => "combined", }; - report.witness_errors += - usize::from(oracle.refusal.map(|x| x.1) != Some(expected_stage)); - compare( - &mut workspace, - &inputs, - gu, - down, - &fault_routes, - &oracle, - &mut report, - )?; + report.witness_errors += usize::from(oracle.refusal.map(|x| x.1) != Some(expected_stage)); + compare(&mut workspace, &inputs, gu, down, &fault_routes, &oracle, &mut report)?; report.faults += 1; // Recovery is a fresh whole overwrite, not host status repair. inputs[0].copy_from(&input(0))?; @@ -201,15 +166,7 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result (), Err(Error::InvalidQ8Activation) => { - return Ok(Oracle { - products, - refusal: Some((SharedTailRefusal::InvalidQ8Activation, $stage)), - }) + return Ok(Oracle { products, refusal: Some((SharedTailRefusal::InvalidQ8Activation, $stage)) }) } Err(error) => return Err(error), } @@ -35,23 +32,14 @@ pub(super) fn original( ($index:expr, $stage:expr) => { let bytes = read(&outputs[$index])?; if !finite(&bytes) { - return Ok(Oracle { - products, - refusal: Some((SharedTailRefusal::NonFinite, $stage)), - }); + return Ok(Oracle { products, refusal: Some((SharedTailRefusal::NonFinite, $stage)) }); } products.push(bytes); }; } - projection!( - original_projection(context, &inputs[1], &inputs[0], &mut outputs[0], gu), - "gate-quant" - ); + projection!(original_projection(context, &inputs[1], &inputs[0], &mut outputs[0], gu), "gate-quant"); product!(0, "gate"); - projection!( - original_projection(context, &inputs[2], &inputs[0], &mut outputs[1], gu), - "up-quant" - ); + projection!(original_projection(context, &inputs[2], &inputs[0], &mut outputs[1], gu), "up-quant"); product!(1, "up"); { let (prefix, suffix) = outputs.split_at_mut(2); @@ -82,10 +70,7 @@ pub(super) fn original( product!(4, "scalar"); let scalar = f32::from_le_bytes(products[4].as_chunks::<4>().0[0]); if !(0.0..=1.0).contains(&scalar) { - return Ok(Oracle { - products, - refusal: Some((SharedTailRefusal::InvalidScalar, "scalar")), - }); + return Ok(Oracle { products, refusal: Some((SharedTailRefusal::InvalidScalar, "scalar")) }); } { let (prefix, suffix) = outputs.split_at_mut(5); @@ -94,10 +79,7 @@ pub(super) fn original( product!(5, "scaled"); for (buffer, stage) in [(&inputs[5], "routed-parts"), (&route, "route-weights")] { if !finite(&read(buffer)?) { - return Ok(Oracle { - products, - refusal: Some((SharedTailRefusal::NonFinite, stage)), - }); + return Ok(Oracle { products, refusal: Some((SharedTailRefusal::NonFinite, stage)) }); } } { @@ -105,10 +87,7 @@ pub(super) fn original( context.moe_combine_f64(&inputs[5], &route, &prefix[5], &mut suffix[0])?; } product!(6, "combined"); - Ok(Oracle { - products, - refusal: None, - }) + Ok(Oracle { products, refusal: None }) } pub(super) fn compare( workspace: &mut SharedExpertWorkspace<'_>, @@ -120,34 +99,23 @@ pub(super) fn compare( report: &mut Report, ) -> Result<()> { let previous = workspace.generation; - let completion = - workspace.compose(&inputs[0], weights(inputs, gu, down), &inputs[5], routes)?; - let refusal = completion - .numerical_refusal() - .zip(completion.refusal_stage()); + let completion = workspace.compose(&inputs[0], weights(inputs, gu, down), &inputs[5], routes)?; + let refusal = completion.numerical_refusal().zip(completion.refusal_stage()); report.witness_errors += usize::from(refusal != oracle.refusal); report.witness_errors += usize::from(completion.generation != previous + 1); if oracle.refusal.is_none() { report.witness_errors += usize::from(completion.statuses != [0; 12]); - report.witness_errors += usize::from( - !completion.scalar.is_finite() || !(0.0..=1.0).contains(&completion.scalar), - ); + report.witness_errors += + usize::from(!completion.scalar.is_finite() || !(0.0..=1.0).contains(&completion.scalar)); for (index, expected) in oracle.products.iter().enumerate() { let actual = read(completion.workspace.buffer(index)?)?; report.words += expected.len() / 4; - report.differences += expected - .as_chunks::<4>() - .0 - .iter() - .zip(actual.as_chunks::<4>().0) - .filter(|(a, b)| a != b) - .count(); + report.differences += + expected.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); } - let final_values = completion - .into_final_values() - .map_err(|_| Error::InvalidDriverValue("unexpected shared-tail refusal"))?; - report.witness_errors += - usize::from(f32_bytes(final_values.iter().copied()) != oracle.products[6]); + let final_values = + completion.into_final_values().map_err(|_| Error::InvalidDriverValue("unexpected shared-tail refusal"))?; + report.witness_errors += usize::from(f32_bytes(final_values.iter().copied()) != oracle.products[6]); } else { report.witness_errors += usize::from(completion.into_final_values().is_ok()); } 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 a6a562ab..f5c34a0a 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 @@ -12,12 +12,7 @@ pub(super) fn f32_bytes(values: impl Iterator) -> Vec { values.flat_map(f32::to_le_bytes).collect() } pub(super) fn finite(bytes: &[u8]) -> bool { - bytes.as_chunks::<4>().1.is_empty() - && bytes - .as_chunks::<4>() - .0 - .iter() - .all(|b| f32::from_le_bytes(*b).is_finite()) + bytes.as_chunks::<4>().1.is_empty() && bytes.as_chunks::<4>().0.iter().all(|b| f32::from_le_bytes(*b).is_finite()) } pub(super) fn input(row: usize) -> Vec { f32_bytes((0..2560usize).map(|i| match row { @@ -134,24 +129,12 @@ pub(super) fn original_projection( gu: SharedGuKind, ) -> Result<()> { match gu { - SharedGuKind::Q5K => context.q5_k_q8_1( - weights, - activation, - output, - Q5KProjectionShape { - rows: 640, - columns: 2560, - }, - ), - SharedGuKind::Q6K => context.q6_k_q8_1( - weights, - activation, - output, - Q6KProjectionShape { - rows: 640, - columns: 2560, - }, - ), + SharedGuKind::Q5K => { + context.q5_k_q8_1(weights, activation, output, Q5KProjectionShape { rows: 640, columns: 2560 }) + } + SharedGuKind::Q6K => { + context.q6_k_q8_1(weights, activation, output, Q6KProjectionShape { rows: 640, columns: 2560 }) + } _ => context.project_q8_1( weights, activation, diff --git a/crates/cuda-driver/src/routed_columns_loan_gpu.rs b/crates/cuda-driver/src/routed_columns_loan_gpu.rs index e5c22ba9..56bfd5b8 100644 --- a/crates/cuda-driver/src/routed_columns_loan_gpu.rs +++ b/crates/cuda-driver/src/routed_columns_loan_gpu.rs @@ -3,68 +3,123 @@ use super::*; const ENABLE: &str = "LELEKA_STRA172_RUN_ROUTED_COLUMNS_LOAN"; #[derive(Default, Debug)] -struct Report { products: usize, words: usize, differences: usize, guards: usize, refusals: usize, witness_errors: usize } +struct Report { + products: usize, + words: usize, + differences: usize, + guards: usize, + refusals: usize, + witness_errors: usize, +} fn upload<'a>(context: &'a Context<'_>, bytes: &[u8]) -> Result> { let mut buffer = context.allocate(bytes.len())?; - match buffer.copy_from(bytes) { Ok(()) => Ok(buffer), Err(primary) => combine(Err(primary), buffer.release()) } + match buffer.copy_from(bytes) { + Ok(()) => Ok(buffer), + Err(primary) => combine(Err(primary), buffer.release()), + } } fn read(buffer: &DeviceBuffer<'_>) -> Result> { - let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes)?; Ok(bytes) + let mut bytes = vec![0; buffer.len()]; + buffer.copy_to(&mut bytes)?; + Ok(bytes) } fn raw(format: RoutedFormat, salt: usize) -> Vec { - let width = match format { RoutedFormat::IQ3_XXS => 98, RoutedFormat::IQ2_S => 82, RoutedFormat::IQ3_S => 110, RoutedFormat::IQ4_XS => 136, _ => unreachable!() }; + let width = match format { + RoutedFormat::IQ3_XXS => 98, + RoutedFormat::IQ2_S => 82, + RoutedFormat::IQ3_S => 110, + RoutedFormat::IQ4_XS => 136, + _ => unreachable!(), + }; let mut raw = vec![0; 640 * 10 * width]; for (row, bytes) in raw.chunks_exact_mut(10 * width).enumerate() { for (block, bytes) in bytes.chunks_exact_mut(width).enumerate() { - for (i, byte) in bytes.iter_mut().enumerate() { *byte = ((row * 17 + block * 29 + i * 37 + salt) & 255) as u8; } + for (i, byte) in bytes.iter_mut().enumerate() { + *byte = ((row * 17 + block * 29 + i * 37 + salt) & 255) as u8; + } bytes[..2].copy_from_slice(&0x1400u16.to_le_bytes()); } - } raw + } + raw } fn input(column: usize) -> Vec { - (0usize..2560).flat_map(|i| { - let value = if column.is_multiple_of(11) { f32::from_bits(if i.is_multiple_of(2) { 0x8000_0000 } else { 0 }) } - else { ((i * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 }; - value.to_le_bytes() - }).collect() + (0usize..2560) + .flat_map(|i| { + let value = if column.is_multiple_of(11) { + f32::from_bits(if i.is_multiple_of(2) { 0x8000_0000 } else { 0 }) + } else { + ((i * 13 + column * 7) % 43) as f32 / 16.0 - 1.25 + }; + value.to_le_bytes() + }) + .collect() } fn compare(old: &[u8], actual: &[u8], report: &mut Report) { - report.products += 1; report.witness_errors += usize::from(old.len() != actual.len()); - for (a,b) in old.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0) { - report.words += 1; report.differences += usize::from(a != b); + report.products += 1; + report.witness_errors += usize::from(old.len() != actual.len()); + for (a, b) in old.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0) { + report.words += 1; + report.differences += usize::from(a != b); report.witness_errors += usize::from(!f32::from_le_bytes(*a).is_finite()); } } fn refuse(result: Result<()>, expected: Error, report: &mut Report) -> Result<()> { report.guards += 1; - match result { Err(error) if error == expected => { report.refusals += 1; Ok(()) }, Ok(()) => { report.witness_errors += 1; Ok(()) }, Err(error) => Err(error) } + match result { + Err(error) if error == expected => { + report.refusals += 1; + Ok(()) + } + Ok(()) => { + report.witness_errors += 1; + Ok(()) + } + Err(error) => Err(error), + } } fn check_table(loan: &RoutedColumnsLoan<'_, '_, '_, '_>, report: &mut Report) -> Result<()> { let table = read(loan.workspace.table.as_ref().ok_or(Error::ContextPoisoned)?)?; report.witness_errors += usize::from(!loan.table_uploaded); for (word, owner) in table[..loan.columns.len() * 8].as_chunks::<8>().0.iter().zip(loan.columns) { let scratch = owner.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - report.witness_errors += usize::from(u64::from_le_bytes(*word) != scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address()); + report.witness_errors += + usize::from(u64::from_le_bytes(*word) != scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address()); } Ok(()) } fn case( - context: &Context<'_>, foreign: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, - finite: &mut RoutedStageFiniteGuard<'_>, format: RoutedFormat, total: usize, report: &mut Report, + context: &Context<'_>, + foreign: &Context<'_>, + workspace: &mut RoutedGroupWorkspace<'_>, + finite: &mut RoutedStageFiniteGuard<'_>, + format: RoutedFormat, + total: usize, + report: &mut Report, ) -> Result<()> { - let mut gate = None; let mut up = None; let mut foreign_weight = None; - let mut original = None; let mut output = None; let mut short = None; - let mut dual_gate = None; let mut dual_up = None; + let mut gate = None; + let mut up = None; + let mut foreign_weight = None; + let mut original = None; + let mut output = None; + let mut short = None; + let mut dual_gate = None; + let mut dual_up = None; let mut inputs = Vec::new(); let operation = (|| { - let gate_raw = raw(format, 11); let up_raw = raw(format, 79); - gate = Some(upload(context, &gate_raw)?); up = Some(upload(context, &up_raw)?); + let gate_raw = raw(format, 11); + let up_raw = raw(format, 79); + gate = Some(upload(context, &gate_raw)?); + up = Some(upload(context, &up_raw)?); foreign_weight = Some(upload(foreign, &gate_raw)?); - for i in 0..total { inputs.push(upload(context, &input(i))?); } - let prepared = inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>>()?; + for i in 0..total { + inputs.push(upload(context, &input(i))?); + } + let prepared = + inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>>()?; let operation = (|| { let mut refs: Vec<_> = prepared.iter().collect(); - original = Some(context.allocate(2560 * total)?); output = Some(context.allocate(2560 * total)?); + original = Some(context.allocate(2560 * total)?); + output = Some(context.allocate(2560 * total)?); short = Some(context.allocate(2560 * total - 4)?); let gate = gate.as_ref().ok_or(Error::ContextPoisoned)?; let up = up.as_ref().ok_or(Error::ContextPoisoned)?; @@ -83,13 +138,19 @@ fn case( report.witness_errors += usize::from(loan.table_uploaded); loan.project_gate_up(gate, output, format)?; report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Gate, total)?); - compare(&expected_gate, &read(output)?, report); check_table(&loan, report)?; + compare(&expected_gate, &read(output)?, report); + check_table(&loan, report)?; let saved = read(output)?; - refuse(loan.project_gate_up(foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, output, format), Error::ContextMismatch, report)?; + refuse( + loan.project_gate_up(foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, output, format), + Error::ContextMismatch, + report, + )?; report.witness_errors += usize::from(read(output)? != saved); loan.project_gate_up(up, output, format)?; report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Up, total)?); - compare(&expected_up, &read(output)?, report); check_table(&loan, report)?; + compare(&expected_up, &read(output)?, report); + check_table(&loan, report)?; drop(loan); report.witness_errors += usize::from(context.allocated_bytes() != allocated || workspace.is_failed()); if total == 64 { @@ -103,26 +164,35 @@ fn case( report.witness_errors += usize::from(fresh.table_uploaded); fresh.project_gate_up(gate, output, format)?; report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Gate, total)?); - compare(&expected_gate, &read(output)?, report); check_table(&fresh, report)?; + compare(&expected_gate, &read(output)?, report); + check_table(&fresh, report)?; fresh.project_gate_up(up, output, format)?; report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Up, total)?); compare(&expected_up, &read(output)?, report); drop(fresh); - let kind = match format { RoutedFormat::IQ3_XXS => Some(MmqFormat::Iq3XxsGateUp), RoutedFormat::IQ2_S => Some(MmqFormat::Iq2SGateUp), _ => None }; + let kind = match format { + RoutedFormat::IQ3_XXS => Some(MmqFormat::Iq3XxsGateUp), + RoutedFormat::IQ2_S => Some(MmqFormat::Iq2SGateUp), + _ => None, + }; if let Some(kind) = kind { dual_gate = Some(context.mmq_weights(kind, &gate_raw)?); dual_up = Some(context.mmq_weights(kind, &up_raw)?); let gate = dual_gate.as_ref().ok_or(Error::ContextPoisoned)?; let up = dual_up.as_ref().ok_or(Error::ContextPoisoned)?; - gate.native_gate_up_columns(&refs, original)?; let expected_gate = read(original)?; - up.native_gate_up_columns(&refs, original)?; let expected_up = read(original)?; + gate.native_gate_up_columns(&refs, original)?; + let expected_gate = read(original)?; + up.native_gate_up_columns(&refs, original)?; + let expected_up = read(original)?; let mut loan = workspace.begin_columns(&refs); gate.native_gate_up_columns_loan(&mut loan, output)?; - report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Gate, total)?); + report.witness_errors += + usize::from(!finite.check_stage(output, RoutedFiniteStage::Gate, total)?); compare(&expected_gate, &read(output)?, report); up.native_gate_up_columns_loan(&mut loan, output)?; report.witness_errors += usize::from(!finite.check_stage(output, RoutedFiniteStage::Up, total)?); - compare(&expected_up, &read(output)?, report); check_table(&loan, report)?; + compare(&expected_up, &read(output)?, report); + check_table(&loan, report)?; } } for refs in [Vec::new(), vec![&prepared[0]; 65]] { @@ -132,21 +202,34 @@ fn case( } Ok(()) })(); - let mut cleanup = Ok(()); for owner in prepared { cleanup = combine(cleanup, owner.close()); } + let mut cleanup = Ok(()); + for owner in prepared { + cleanup = combine(cleanup, owner.close()); + } combine(operation, cleanup) })(); let mut cleanup = Ok(()); - for buffer in gate.into_iter().chain(up).chain(foreign_weight).chain(original).chain(output).chain(short).chain(inputs) { + for buffer in + gate.into_iter().chain(up).chain(foreign_weight).chain(original).chain(output).chain(short).chain(inputs) + { cleanup = combine(cleanup, buffer.release()); } - for owner in dual_gate.into_iter().chain(dual_up) { cleanup = combine(cleanup, owner.close()); } + for owner in dual_gate.into_iter().chain(dual_up) { + cleanup = combine(cleanup, owner.close()); + } combine(operation, cleanup) } -fn mixed_pair(context: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, finite: &mut RoutedStageFiniteGuard<'_>, report: &mut Report) -> Result<()> { +fn mixed_pair( + context: &Context<'_>, + workspace: &mut RoutedGroupWorkspace<'_>, + finite: &mut RoutedStageFiniteGuard<'_>, + report: &mut Report, +) -> Result<()> { let input = upload(context, &input(3))?; let gate = upload(context, &raw(RoutedFormat::IQ3_S, 11))?; let up = upload(context, &raw(RoutedFormat::IQ4_XS, 79))?; - let mut original = context.allocate(2560)?; let mut output = context.allocate(2560)?; + let mut original = context.allocate(2560)?; + let mut output = context.allocate(2560)?; let operation = (|| { let owner = context.prepare_routed_gate_up_q8(&input)?; let operation = (|| { @@ -161,11 +244,15 @@ fn mixed_pair(context: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, f compare(&expected_gate, &read(&output)?, report); loan.project_gate_up(&up, &mut output, RoutedFormat::IQ4_XS)?; report.witness_errors += usize::from(!finite.check_stage(&output, RoutedFiniteStage::Up, 1)?); - compare(&expected_up, &read(&output)?, report); Ok(()) + compare(&expected_up, &read(&output)?, report); + Ok(()) })(); combine(operation, owner.close()) })(); - let mut cleanup = Ok(()); for buffer in [input, gate, up, original, output] { cleanup = combine(cleanup, buffer.release()); } + let mut cleanup = Ok(()); + for buffer in [input, gate, up, original, output] { + cleanup = combine(cleanup, buffer.release()); + } combine(operation, cleanup) } fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { @@ -177,28 +264,50 @@ fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { let workspace = workspace.as_mut().ok_or(Error::ContextPoisoned)?; let finite = finite.as_mut().ok_or(Error::ContextPoisoned)?; for format in [RoutedFormat::IQ3_XXS, RoutedFormat::IQ2_S, RoutedFormat::IQ3_S, RoutedFormat::IQ4_XS] { - for total in [1usize, 64] { case(context, foreign, workspace, finite, format, total, &mut report)?; } + for total in [1usize, 64] { + case(context, foreign, workspace, finite, format, total, &mut report)?; + } } mixed_pair(context, workspace, finite, &mut report)?; - report.witness_errors += usize::from(context.allocated_bytes() != ALLOCATED_BYTES + 4 || foreign.allocated_bytes() != 0); + report.witness_errors += + usize::from(context.allocated_bytes() != ALLOCATED_BYTES + 4 || foreign.allocated_bytes() != 0); Ok(report) })(); - let cleanup = combine(finite.take().map_or(Ok(()), RoutedStageFiniteGuard::close), workspace.take().map_or(Ok(()), RoutedGroupWorkspace::close)); - drop(finite); drop(workspace); combine(operation, cleanup) + let cleanup = combine( + finite.take().map_or(Ok(()), RoutedStageFiniteGuard::close), + workspace.take().map_or(Ok(()), RoutedGroupWorkspace::close), + ); + drop(finite); + drop(workspace); + combine(operation, cleanup) } #[test] #[ignore = "Root schedules only the changed borrowed-table component"] fn original_first_columns_loan_gate_up_fresh_order_guards_and_cleanup() { assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); - let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device"); + let driver = Driver::load().expect("driver"); + let device = driver.device(0).expect("device"); let context = device.create_context(16 * 1024 * 1024).expect("Context"); - let foreign = match device.create_context(16 * 1024 * 1024) { Ok(value) => value, Err(primary) => { let cleanup = context.close(); panic!("foreign {primary:?}; cleanup={cleanup:?}"); } }; + let foreign = match device.create_context(16 * 1024 * 1024) { + Ok(value) => value, + Err(primary) => { + let cleanup = context.close(); + panic!("foreign {primary:?}; cleanup={cleanup:?}"); + } + }; let operation = run(&context, &foreign); - let allocated = context.allocated_bytes(); let other = foreign.allocated_bytes(); let poisoned = context.is_poisoned() || foreign.is_poisoned(); + let allocated = context.allocated_bytes(); + let other = foreign.allocated_bytes(); + let poisoned = context.is_poisoned() || foreign.is_poisoned(); let cleanup = combine(context.close(), foreign.close()); let report = combine(operation, cleanup).expect("loan fixture plus all Context cleanup"); - assert_eq!(allocated, 0); assert_eq!(other, 0); assert!(!poisoned); - assert_eq!(report.products, 30); assert_eq!(report.words, 825600); - assert_eq!(report.differences, 0); assert_eq!(report.witness_errors, 0); assert_eq!(report.guards, report.refusals); + assert_eq!(allocated, 0); + assert_eq!(other, 0); + assert!(!poisoned); + assert_eq!(report.products, 30); + assert_eq!(report.words, 825600); + assert_eq!(report.differences, 0); + assert_eq!(report.witness_errors, 0); + assert_eq!(report.guards, report.refusals); eprintln!("ROUTED-COLUMNS-LOAN {report:?}; extra_device_bytes=0; cleanup=0; component_only=true"); } diff --git a/crates/cuda-driver/src/routed_group_workspace.rs b/crates/cuda-driver/src/routed_group_workspace.rs index 7c190b1b..0b927672 100644 --- a/crates/cuda-driver/src/routed_group_workspace.rs +++ b/crates/cuda-driver/src/routed_group_workspace.rs @@ -13,7 +13,12 @@ pub struct RoutedGroupWorkspace<'ctx> { failed: bool, } -#[cfg(all(test, feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[cfg(all( + test, + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +))] #[path = "routed_group_workspace_gpu.rs"] mod gpu; 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 dea9b85f..b3e8dc7b 100644 --- a/crates/cuda-driver/src/routed_group_workspace/impl_context.rs +++ b/crates/cuda-driver/src/routed_group_workspace/impl_context.rs @@ -11,9 +11,7 @@ impl<'ctx> Context<'ctx> { if self.allocated.get().checked_add(ALLOCATED_BYTES).is_none_or(|n| n > self.budget) { return Err(Error::BudgetExceeded); } - let mut owner = RoutedGroupWorkspace { - context: self, table: None, q8: None, status: None, failed: false, - }; + let mut owner = RoutedGroupWorkspace { context: self, table: None, q8: None, status: None, failed: false }; let operation = (|| { owner.table = Some(self.allocate(TABLE_BYTES)?); owner.q8 = Some(self.allocate(Q8_BYTES)?); @@ -29,20 +27,27 @@ impl<'ctx> Context<'ctx> { } impl RoutedGroupWorkspace<'_> { pub fn allocated_bytes(&self) -> usize { - [&self.table, &self.q8, &self.status].into_iter() - .filter_map(Option::as_ref).map(DeviceBuffer::len).sum() + [&self.table, &self.q8, &self.status].into_iter().filter_map(Option::as_ref).map(DeviceBuffer::len).sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() } - pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() } pub(super) fn validate(&self) -> Result<()> { if self.is_failed() || self.context.handle.is_none() { return Err(Error::ContextPoisoned); } let buffers = [self.table.as_ref(), self.q8.as_ref(), self.status.as_ref()]; let mut handles: [Option<(ffi::BufferHandle, usize)>; 3] = [None; 3]; - for (index, (buffer, (bytes, alignment))) in buffers.into_iter().zip([(TABLE_BYTES, 8), (Q8_BYTES, 4), (4, 4)]).enumerate() { + for (index, (buffer, (bytes, alignment))) in + buffers.into_iter().zip([(TABLE_BYTES, 8), (Q8_BYTES, 4), (4, 4)]).enumerate() + { let buffer = buffer.ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(buffer.context, self.context) { return Err(Error::ContextMismatch); } - if buffer.bytes != bytes { return Err(Error::InvalidProjectionShape); } + if !std::ptr::eq(buffer.context, self.context) { + return Err(Error::ContextMismatch); + } + if buffer.bytes != bytes { + return Err(Error::InvalidProjectionShape); + } let handle = buffer.handle.ok_or(Error::ContextPoisoned)?; handle.validate_projection_extent(bytes, alignment)?; if handles.iter().flatten().any(|&(prior, size)| handle.overlaps(bytes, prior, size)) { @@ -53,7 +58,9 @@ impl RoutedGroupWorkspace<'_> { Ok(()) } pub(super) fn disjoint(&self, source: &DeviceBuffer<'_>) -> Result<()> { - if !std::ptr::eq(source.context, self.context) { return Err(Error::ContextMismatch); } + if !std::ptr::eq(source.context, self.context) { + return Err(Error::ContextMismatch); + } let input = source.handle.ok_or(Error::ContextPoisoned)?; for buffer in [self.table.as_ref(), self.q8.as_ref(), self.status.as_ref()] { let buffer = buffer.ok_or(Error::ContextPoisoned)?; @@ -72,24 +79,35 @@ impl RoutedGroupWorkspace<'_> { } } pub fn project_gate_up_columns( - &mut self, weights: &DeviceBuffer<'_>, columns: &[&RoutedGateUpQ8<'_>], - output: &mut DeviceBuffer<'_>, format: RoutedFormat, + &mut self, + weights: &DeviceBuffer<'_>, + columns: &[&RoutedGateUpQ8<'_>], + output: &mut DeviceBuffer<'_>, + format: RoutedFormat, ) -> Result<()> { self.gate_up_weight(NativeWeights::Raw(weights), columns, output, format) } pub fn project_down_columns( - &mut self, weights: &DeviceBuffer<'_>, hidden: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, total: usize, format: RoutedFormat, + &mut self, + weights: &DeviceBuffer<'_>, + hidden: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + total: usize, + format: RoutedFormat, ) -> Result<()> { self.down_weight(NativeWeights::Raw(weights), hidden, output, total, format) } - pub fn close(mut self) -> Result<()> { self.release() } + pub fn close(mut self) -> Result<()> { + self.release() + } pub(super) fn release(&mut self) -> Result<()> { let mut result = Ok(()); for slot in [&mut self.status, &mut self.q8, &mut self.table] { if let Some(buffer) = slot.take() { let released = buffer.release(); - if released.is_err() { self.context.poisoned.set(true); } + if released.is_err() { + self.context.poisoned.set(true); + } result = combine(result, released); } } @@ -97,13 +115,18 @@ impl RoutedGroupWorkspace<'_> { } } impl Drop for RoutedGroupWorkspace<'_> { - fn drop(&mut self) { let _ = self.release(); } + fn drop(&mut self) { + let _ = self.release(); + } } impl RoutedGroupWorkspace<'_> { pub(in super::super) fn gate_up_weight( - &mut self, weight_owner: NativeWeights<'_, '_>, - columns: &[&RoutedGateUpQ8<'_>], output: &mut DeviceBuffer<'_>, format: RoutedFormat, + &mut self, + weight_owner: NativeWeights<'_, '_>, + columns: &[&RoutedGateUpQ8<'_>], + output: &mut DeviceBuffer<'_>, + format: RoutedFormat, ) -> Result<()> { self.validate()?; let context = self.context; @@ -123,17 +146,10 @@ impl RoutedGroupWorkspace<'_> { if !(1..=64).contains(&columns.len()) { return Err(Error::InvalidProjectionShape); } - let shape = projection_shape(ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - })?; + let shape = + projection_shape(ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })?; weight_owner.validate( - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - }, + ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 }, shape.weight_bytes, )?; if output.bytes != columns.len() * 2560 { @@ -144,10 +160,7 @@ impl RoutedGroupWorkspace<'_> { } let weight = weights.handle.ok_or(Error::ContextPoisoned)?; let out = output.handle.ok_or(Error::ContextPoisoned)?; - weight.validate_projection_extent( - shape.weight_bytes, - ProjectionKind::Routed(format).weight_alignment(), - )?; + weight.validate_projection_extent(shape.weight_bytes, ProjectionKind::Routed(format).weight_alignment())?; out.validate_projection_extent(output.bytes, 4)?; if out.overlaps(output.bytes, weight, weights.bytes) { return Err(Error::OutputAliasesInput); @@ -156,9 +169,7 @@ impl RoutedGroupWorkspace<'_> { self.disjoint(output)?; let table_handle = self.table.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; let mut pointers = Vec::new(); - pointers - .try_reserve_exact(columns.len() * 8) - .map_err(|_| Error::BudgetExceeded)?; + pointers.try_reserve_exact(columns.len() * 8).map_err(|_| Error::BudgetExceeded)?; for column in columns { let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; for buffer in [column.activation, scratch] { @@ -172,19 +183,10 @@ impl RoutedGroupWorkspace<'_> { return Err(Error::OutputAliasesInput); } } - if column.activation.bytes != 10240 - || scratch.bytes != 2880 - || context.common_quantizer.get().is_none() - { + if column.activation.bytes != 10240 || scratch.bytes != 2880 || context.common_quantizer.get().is_none() { return Err(Error::InvalidProjectionShape); } - pointers.extend_from_slice( - &scratch - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() - .to_le_bytes(), - ); + pointers.extend_from_slice(&scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address().to_le_bytes()); } let result = (|| { self.table.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(0, &pointers)?; 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 d2192de2..8918925a 100644 --- a/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs +++ b/crates/cuda-driver/src/routed_group_workspace/impl_routedgroupworkspace.rs @@ -3,11 +3,14 @@ #[allow(unused_imports)] use super::*; - impl RoutedGroupWorkspace<'_> { pub(in super::super) fn down_weight( - &mut self, weight_owner: NativeWeights<'_, '_>, hidden: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, total: usize, format: RoutedFormat, + &mut self, + weight_owner: NativeWeights<'_, '_>, + hidden: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + total: usize, + format: RoutedFormat, ) -> Result<()> { self.validate()?; let context = self.context; @@ -21,30 +24,16 @@ impl RoutedGroupWorkspace<'_> { RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2, _ => return Err(Error::UnsupportedProjection), }; - let shape = projection_shape(ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - })?; + let shape = + projection_shape(ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 })?; weight_owner.validate( - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 2560, - columns: 640, - }, + ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 2560, columns: 640 }, shape.weight_bytes, )?; - if !(1..=64).contains(&total) - || hidden.bytes != total * 2560 - || output.bytes != total * 10240 - { + if !(1..=64).contains(&total) || hidden.bytes != total * 2560 || output.bytes != total * 10240 { return Err(Error::InvalidProjectionShape); } - let handles = [ - weights.handle.unwrap(), - hidden.handle.unwrap(), - output.handle.unwrap(), - ]; + let handles = [weights.handle.unwrap(), hidden.handle.unwrap(), output.handle.unwrap()]; projection_ranges(ProjectionKind::Routed(format), &shape, handles)?; // projection_ranges checks one-column overlap; require full grouped extents. if handles[2].overlaps(output.bytes, handles[0], weights.bytes) @@ -58,11 +47,7 @@ impl RoutedGroupWorkspace<'_> { let flag = self.status.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; q8.validate_projection_extent(scratch_bytes, 4)?; flag.validate_projection_extent(4, 4)?; - for (h, n) in [ - (handles[0], weights.bytes), - (handles[1], hidden.bytes), - (handles[2], output.bytes), - ] { + for (h, n) in [(handles[0], weights.bytes), (handles[1], hidden.bytes), (handles[2], output.bytes)] { if q8.overlaps(scratch_bytes, h, n) || flag.overlaps(4, h, n) { return Err(Error::OutputAliasesInput); } @@ -80,8 +65,7 @@ impl RoutedGroupWorkspace<'_> { }; // 640 is a multiple of32: flattening columns preserves every Q8 // block, lane schedule, scale/sum and per-column original order. - let mut args = - ffi::Q8QuantizeArguments::new(handles[1], q8, flag, (640 * total) as u32); + let mut args = ffi::Q8QuantizeArguments::new(handles[1], q8, flag, (640 * total) as u32); let guard = context.enter()?; let launch = context.driver.api.launch_q8_quantize( quantizer.function, @@ -96,12 +80,7 @@ impl RoutedGroupWorkspace<'_> { } let mut args = ffi::ProjectionArguments::new(handles[0], q8, handles[2], 2560, 640); let guard = context.enter()?; - let launch = context.driver.api.launch_grouped_projection( - projector.function, - 640, - total as u32, - &mut args, - ); + let launch = context.driver.api.launch_grouped_projection(projector.function, 640, total as u32, &mut args); context.complete_launch(launch, args, guard) })(); self.record(&result); @@ -111,19 +90,25 @@ impl RoutedGroupWorkspace<'_> { impl<'ctx> RoutedGroupWorkspace<'ctx> { /// Inert minting: keep current role/weight/output admission inside projection. pub fn begin_columns<'ws, 'cols, 'activation>( - &'ws mut self, columns: &'cols [&'cols RoutedGateUpQ8<'activation>], + &'ws mut self, + columns: &'cols [&'cols RoutedGateUpQ8<'activation>], ) -> RoutedColumnsLoan<'ws, 'cols, 'activation, 'ctx> { RoutedColumnsLoan { workspace: self, columns, table_uploaded: false } } } impl RoutedColumnsLoan<'_, '_, '_, '_> { pub fn project_gate_up( - &mut self, weights: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, format: RoutedFormat, + &mut self, + weights: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + format: RoutedFormat, ) -> Result<()> { self.gate_up_weight(NativeWeights::Raw(weights), output, format) } pub(in super::super) fn gate_up_weight( - &mut self, weight_owner: NativeWeights<'_, '_>, output: &mut DeviceBuffer<'_>, + &mut self, + weight_owner: NativeWeights<'_, '_>, + output: &mut DeviceBuffer<'_>, format: RoutedFormat, ) -> Result<()> { let columns = self.columns; @@ -147,17 +132,10 @@ impl RoutedColumnsLoan<'_, '_, '_, '_> { if !(1..=64).contains(&columns.len()) { return Err(Error::InvalidProjectionShape); } - let shape = projection_shape(ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - })?; + let shape = + projection_shape(ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 })?; weight_owner.validate( - ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: 640, - columns: 2560, - }, + ProjectionSpec { kind: ProjectionKind::Routed(format), rows: 640, columns: 2560 }, shape.weight_bytes, )?; if output.bytes != columns.len() * 2560 { @@ -168,21 +146,18 @@ impl RoutedColumnsLoan<'_, '_, '_, '_> { } let weight = weights.handle.ok_or(Error::ContextPoisoned)?; let out = output.handle.ok_or(Error::ContextPoisoned)?; - weight.validate_projection_extent( - shape.weight_bytes, - ProjectionKind::Routed(format).weight_alignment(), - )?; + weight.validate_projection_extent(shape.weight_bytes, ProjectionKind::Routed(format).weight_alignment())?; out.validate_projection_extent(output.bytes, 4)?; if out.overlaps(output.bytes, weight, weights.bytes) { return Err(Error::OutputAliasesInput); } workspace.disjoint(weights)?; workspace.disjoint(output)?; - let table_handle = workspace.table.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; + let table_handle = + workspace.table.as_ref().ok_or(Error::ContextPoisoned)?.handle.ok_or(Error::ContextPoisoned)?; let mut pointers = Vec::new(); if !*uploaded { - pointers.try_reserve_exact(columns.len() * 8) - .map_err(|_| Error::BudgetExceeded)?; + pointers.try_reserve_exact(columns.len() * 8).map_err(|_| Error::BudgetExceeded)?; } for column in columns { let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; @@ -197,16 +172,11 @@ impl RoutedColumnsLoan<'_, '_, '_, '_> { return Err(Error::OutputAliasesInput); } } - if column.activation.bytes != 10240 - || scratch.bytes != 2880 - || context.common_quantizer.get().is_none() - { + if column.activation.bytes != 10240 || scratch.bytes != 2880 || context.common_quantizer.get().is_none() { return Err(Error::InvalidProjectionShape); } if !*uploaded { - pointers.extend_from_slice( - &scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address().to_le_bytes(), - ); + pointers.extend_from_slice(&scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address().to_le_bytes()); } } let result = (|| { diff --git a/crates/cuda-driver/src/routed_group_workspace_gpu.rs b/crates/cuda-driver/src/routed_group_workspace_gpu.rs index 0296bfc4..699e94a7 100644 --- a/crates/cuda-driver/src/routed_group_workspace_gpu.rs +++ b/crates/cuda-driver/src/routed_group_workspace_gpu.rs @@ -55,14 +55,16 @@ fn dual_format(format: RoutedFormat) -> Option { } } fn values(words: usize, column: usize, changed: bool) -> Vec { - (0usize..words).flat_map(|i| { - let value = if (column + usize::from(changed)).is_multiple_of(11) { - f32::from_bits(if i.is_multiple_of(2) { 0x8000_0000 } else { 0 }) - } else { - ((i * 13 + column * 7 + usize::from(changed) * 19) % 43) as f32 / 16.0 - 1.25 - }; - value.to_le_bytes() - }).collect() + (0usize..words) + .flat_map(|i| { + let value = if (column + usize::from(changed)).is_multiple_of(11) { + f32::from_bits(if i.is_multiple_of(2) { 0x8000_0000 } else { 0 }) + } else { + ((i * 13 + column * 7 + usize::from(changed) * 19) % 43) as f32 / 16.0 - 1.25 + }; + value.to_le_bytes() + }) + .collect() } fn compare(original: &[u8], actual: &[u8], report: &mut Report) { report.products += 1; @@ -80,13 +82,20 @@ fn refused(result: Result<()>, report: &mut Report) -> Result<()> { report.refusals += 1; Ok(()) } - Ok(()) => { report.witness_errors += 1; Ok(()) } + Ok(()) => { + report.witness_errors += 1; + Ok(()) + } Err(error) => Err(error), } } fn gu_case( - context: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, - format: RoutedFormat, total: usize, changed: bool, report: &mut Report, + context: &Context<'_>, + workspace: &mut RoutedGroupWorkspace<'_>, + format: RoutedFormat, + total: usize, + changed: bool, + report: &mut Report, ) -> Result<()> { let mut matrix = None; let mut dual = None; @@ -96,69 +105,86 @@ fn gu_case( let operation = (|| { let raw = weights(format); matrix = Some(upload(context, &raw)?); - if let Some(kind) = dual_format(format) { dual = Some(context.mmq_weights(kind, &raw)?); } - for column in 0..total { inputs.push(upload(context, &values(2560, column, changed))?); } - let prepared = inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)) - .collect::>>()?; + if let Some(kind) = dual_format(format) { + dual = Some(context.mmq_weights(kind, &raw)?); + } + for column in 0..total { + inputs.push(upload(context, &values(2560, column, changed))?); + } + let prepared = + inputs.iter().map(|input| context.prepare_routed_gate_up_q8(input)).collect::>>()?; let products = (|| { - let mut refs: Vec<_> = prepared.iter().collect(); - if changed { refs.reverse(); } - reference = Some(context.allocate(total * 2560)?); - output = Some(context.allocate(total * 2560)?); - let matrix = matrix.as_ref().ok_or(Error::ContextPoisoned)?; - let reference = reference.as_mut().ok_or(Error::ContextPoisoned)?; - let output = output.as_mut().ok_or(Error::ContextPoisoned)?; - // Unchanged original raw path completes and full output is read FIRST. - context.project_routed_gate_up_columns(matrix, &refs, reference, format)?; - let original = read(reference)?; - let allocated = context.allocated_bytes(); - workspace.table.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0xa5; TABLE_BYTES])?; - workspace.project_gate_up_columns(matrix, &refs, output, format)?; - compare(&original, &read(output)?, report); - let table = read(workspace.table.as_ref().ok_or(Error::ContextPoisoned)?)?; - report.witness_errors += usize::from(table[total * 8..].iter().any(|b| *b != 0xa5)); - for (pointer, owner) in table[..total * 8].as_chunks::<8>().0.iter().zip(&refs) { - let scratch = owner.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - report.witness_errors += usize::from(u64::from_le_bytes(*pointer) - != scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address()); - } - if let Some(dual) = dual.as_ref() { - dual.native_gate_up_columns(&refs, reference)?; + let mut refs: Vec<_> = prepared.iter().collect(); + if changed { + refs.reverse(); + } + reference = Some(context.allocate(total * 2560)?); + output = Some(context.allocate(total * 2560)?); + let matrix = matrix.as_ref().ok_or(Error::ContextPoisoned)?; + let reference = reference.as_mut().ok_or(Error::ContextPoisoned)?; + let output = output.as_mut().ok_or(Error::ContextPoisoned)?; + // Unchanged original raw path completes and full output is read FIRST. + context.project_routed_gate_up_columns(matrix, &refs, reference, format)?; let original = read(reference)?; - dual.native_gate_up_columns_in(workspace, &refs, output)?; + let allocated = context.allocated_bytes(); + workspace.table.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&[0xa5; TABLE_BYTES])?; + workspace.project_gate_up_columns(matrix, &refs, output, format)?; compare(&original, &read(output)?, report); - } - // The active pointer prefix must be completely overwritten on repeat. - refs.reverse(); - context.project_routed_gate_up_columns(matrix, &refs, reference, format)?; - let original = read(reference)?; - workspace.project_gate_up_columns(matrix, &refs, output, format)?; - compare(&original, &read(output)?, report); - report.resets += 1; - report.witness_errors += usize::from(context.allocated_bytes() != allocated || workspace.is_failed()); - let saved = read(output)?; - refused(workspace.project_gate_up_columns(matrix, &[], output, format), report)?; - let excess = vec![refs[0]; 65]; - refused(workspace.project_gate_up_columns(matrix, &excess, output, format), report)?; - refused(workspace.project_gate_up_columns(matrix, &refs, output, RoutedFormat::Q2_0), report)?; - report.witness_errors += usize::from(read(output)? != saved || workspace.is_failed()); - Ok(()) + let table = read(workspace.table.as_ref().ok_or(Error::ContextPoisoned)?)?; + report.witness_errors += usize::from(table[total * 8..].iter().any(|b| *b != 0xa5)); + for (pointer, owner) in table[..total * 8].as_chunks::<8>().0.iter().zip(&refs) { + let scratch = owner.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + report.witness_errors += usize::from( + u64::from_le_bytes(*pointer) != scratch.handle.ok_or(Error::ContextPoisoned)?.qwen_address(), + ); + } + if let Some(dual) = dual.as_ref() { + dual.native_gate_up_columns(&refs, reference)?; + let original = read(reference)?; + dual.native_gate_up_columns_in(workspace, &refs, output)?; + compare(&original, &read(output)?, report); + } + // The active pointer prefix must be completely overwritten on repeat. + refs.reverse(); + context.project_routed_gate_up_columns(matrix, &refs, reference, format)?; + let original = read(reference)?; + workspace.project_gate_up_columns(matrix, &refs, output, format)?; + compare(&original, &read(output)?, report); + report.resets += 1; + report.witness_errors += usize::from(context.allocated_bytes() != allocated || workspace.is_failed()); + let saved = read(output)?; + refused(workspace.project_gate_up_columns(matrix, &[], output, format), report)?; + let excess = vec![refs[0]; 65]; + refused(workspace.project_gate_up_columns(matrix, &excess, output, format), report)?; + refused(workspace.project_gate_up_columns(matrix, &refs, output, RoutedFormat::Q2_0), report)?; + report.witness_errors += usize::from(read(output)? != saved || workspace.is_failed()); + Ok(()) })(); let mut cleanup = Ok(()); - for owner in prepared { cleanup = combine(cleanup, owner.close()); } + for owner in prepared { + cleanup = combine(cleanup, owner.close()); + } combine(products, cleanup) })(); let mut cleanup = Ok(()); - for input in inputs { cleanup = combine(cleanup, input.release()); } + for input in inputs { + cleanup = combine(cleanup, input.release()); + } for buffer in reference.into_iter().chain(output).chain(matrix) { cleanup = combine(cleanup, buffer.release()); } - if let Some(owner) = dual { cleanup = combine(cleanup, owner.close()); } + if let Some(owner) = dual { + cleanup = combine(cleanup, owner.close()); + } combine(operation, cleanup) } fn down_case( - context: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, - format: RoutedFormat, total: usize, changed: bool, report: &mut Report, + context: &Context<'_>, + workspace: &mut RoutedGroupWorkspace<'_>, + format: RoutedFormat, + total: usize, + changed: bool, + report: &mut Report, ) -> Result<()> { let mut matrix = None; let mut dual = None; @@ -170,7 +196,9 @@ fn down_case( matrix = Some(upload(context, &raw)?); dual = Some(context.mmq_weights(dual_format(format).ok_or(Error::UnsupportedProjection)?, &raw)?); let mut valid = Vec::new(); - for column in 0..total { valid.extend_from_slice(&values(640, column, changed)); } + for column in 0..total { + valid.extend_from_slice(&values(640, column, changed)); + } hidden = Some(upload(context, &valid)?); reference = Some(context.allocate(total * 10240)?); output = Some(context.allocate(total * 10240)?); @@ -200,10 +228,15 @@ fn down_case( let old = context.project_routed_down_columns(matrix, hidden, reference, total, format); let new = workspace.project_down_columns(matrix, hidden, output, total, format); report.guards += 1; - report.refusals += usize::from(matches!(&old, Err(Error::InvalidQ8Activation)) - && matches!(&new, Err(Error::InvalidQ8Activation))); - if !matches!(&old, Err(Error::InvalidQ8Activation)) { old?; } - if !matches!(&new, Err(Error::InvalidQ8Activation)) { new?; } + report.refusals += usize::from( + matches!(&old, Err(Error::InvalidQ8Activation)) && matches!(&new, Err(Error::InvalidQ8Activation)), + ); + if !matches!(&old, Err(Error::InvalidQ8Activation)) { + old?; + } + if !matches!(&new, Err(Error::InvalidQ8Activation)) { + new?; + } report.witness_errors += usize::from(read(output)? != before || workspace.is_failed()); hidden.copy_from(&valid)?; context.project_routed_down_columns(matrix, hidden, reference, total, format)?; @@ -223,11 +256,15 @@ fn down_case( for buffer in reference.into_iter().chain(output).chain(hidden).chain(matrix) { cleanup = combine(cleanup, buffer.release()); } - if let Some(owner) = dual { cleanup = combine(cleanup, owner.close()); } + if let Some(owner) = dual { + cleanup = combine(cleanup, owner.close()); + } combine(operation, cleanup) } fn foreign_and_shape( - context: &Context<'_>, foreign: &Context<'_>, workspace: &mut RoutedGroupWorkspace<'_>, + context: &Context<'_>, + foreign: &Context<'_>, + workspace: &mut RoutedGroupWorkspace<'_>, report: &mut Report, ) -> Result<()> { let matrix = upload(context, &weights(RoutedFormat::IQ4_NL))?; @@ -238,7 +275,8 @@ fn foreign_and_shape( let local = upload(context, &values(640, 1, false))?; let shape = (|| { let mut short = context.allocate(10236)?; - let result = refused(workspace.project_down_columns(&matrix, &local, &mut short, 1, RoutedFormat::IQ4_NL), report); + let result = + refused(workspace.project_down_columns(&matrix, &local, &mut short, 1, RoutedFormat::IQ4_NL), report); combine(result, short.release()) })(); combine(shape, local.release())?; @@ -262,7 +300,8 @@ fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result { } } foreign_and_shape(context, foreign, owner, &mut report)?; - report.witness_errors += usize::from(context.allocated_bytes() != ALLOCATED_BYTES || foreign.allocated_bytes() != 0); + report.witness_errors += + usize::from(context.allocated_bytes() != ALLOCATED_BYTES || foreign.allocated_bytes() != 0); Ok(report) })(); let cleanup = workspace.take().map_or(Ok(()), RoutedGroupWorkspace::close); @@ -278,7 +317,10 @@ fn original_first_group_workspace_all_products_active_spans_reset_and_cleanup() let context = device.create_context(16 * 1024 * 1024).expect("bounded Context"); let foreign = match device.create_context(16 * 1024 * 1024) { Ok(value) => value, - Err(primary) => { let cleanup = context.close(); panic!("foreign: {primary:?}; cleanup={cleanup:?}"); } + Err(primary) => { + let cleanup = context.close(); + panic!("foreign: {primary:?}; cleanup={cleanup:?}"); + } }; let operation = (|| { let mut report = run(&context, &foreign)?; diff --git a/crates/cuda-driver/src/routed_resident_queue.rs b/crates/cuda-driver/src/routed_resident_queue.rs index 7c6ff255..65837b81 100644 --- a/crates/cuda-driver/src/routed_resident_queue.rs +++ b/crates/cuda-driver/src/routed_resident_queue.rs @@ -58,9 +58,9 @@ enum Command { #[path = "routed_resident_queue_gpu.rs"] mod gpu; +mod impl_drop_for_routedresidentqueue; mod impl_routedresidentcompletion; mod impl_routedresidentqueue; -mod impl_drop_for_routedresidentqueue; #[allow(unused_imports)] use impl_drop_for_routedresidentqueue::gu_operation; #[allow(unused_imports)] 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 9d63219b..f71a7686 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 @@ -19,17 +19,8 @@ pub(super) fn gu_operation(format: RoutedFormat, t: usize) -> Result return Err(Error::UnsupportedProjection), }) } -pub(super) fn scan( - f: ffi::FunctionHandle, - input: ffi::BufferHandle, - status: ffi::BufferHandle, - words: u32, -) -> Command { - Command::Finite( - f, - words, - ffi::MmqResidentArguments::finite(input, status, 0, words, 0), - ) +pub(super) fn scan(f: ffi::FunctionHandle, input: ffi::BufferHandle, status: ffi::BufferHandle, words: u32) -> Command { + Command::Finite(f, words, ffi::MmqResidentArguments::finite(input, status, 0, words, 0)) } impl Command { pub(super) fn launch(&mut self, context: &Context<'_>) -> Result<()> { diff --git a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs index f854b42d..aeb7c115 100644 --- a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs +++ b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentcompletion.rs @@ -28,11 +28,7 @@ impl<'ctx> Context<'ctx> { if self.is_poisoned() || self.handle.is_none() { return Err(Error::ContextPoisoned); } - if self - .allocated - .get() - .checked_add(CHARGE) - .is_none_or(|v| v > self.budget) + if self.allocated.get().checked_add(CHARGE).is_none_or(|v| v > self.budget) || self.memory_info()?.0 < CHARGE + RESERVE { return Err(Error::BudgetExceeded); diff --git a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs index fa362c0e..e2a16632 100644 --- a/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs +++ b/crates/cuda-driver/src/routed_resident_queue/impl_routedresidentqueue.rs @@ -5,11 +5,7 @@ use super::*; impl<'ctx> RoutedResidentQueue<'ctx> { pub fn allocated_bytes(&self) -> usize { - [&self.table, &self.q8, &self.status] - .into_iter() - .filter_map(Option::as_ref) - .map(DeviceBuffer::len) - .sum() + [&self.table, &self.q8, &self.status].into_iter().filter_map(Option::as_ref).map(DeviceBuffer::len).sum() } pub fn is_failed(&self) -> bool { self.failed || self.context.is_poisoned() @@ -19,13 +15,8 @@ impl<'ctx> RoutedResidentQueue<'ctx> { return Err(Error::ContextPoisoned); } let mut out: [Option; 3] = [None; 3]; - for (i, (buffer, size, align)) in [ - (&self.table, TABLE, 8), - (&self.q8, Q8, 4), - (&self.status, STATUS, 4), - ] - .into_iter() - .enumerate() + for (i, (buffer, size, align)) in + [(&self.table, TABLE, 8), (&self.q8, Q8, 4), (&self.status, STATUS, 4)].into_iter().enumerate() { let buffer = buffer.as_ref().ok_or(Error::ContextPoisoned)?; if !std::ptr::eq(buffer.context, self.context) { @@ -85,10 +76,7 @@ impl<'ctx> RoutedResidentQueue<'ctx> { if !(1..=64).contains(&t) { return Err(Error::InvalidProjectionShape); } - let ops = [ - gu_operation(weights.gu_formats[0], t)?, - gu_operation(weights.gu_formats[1], t)?, - ]; + let ops = [gu_operation(weights.gu_formats[0], t)?, gu_operation(weights.gu_formats[1], t)?]; let down_op = match weights.down_format { RoutedFormat::IQ4_NL => FixedOperation::GroupedDownIq4, RoutedFormat::Q2_0 => FixedOperation::GroupedDownQ2, @@ -104,17 +92,8 @@ impl<'ctx> RoutedResidentQueue<'ctx> { .enumerate() { let kind = ProjectionKind::Routed(format); - let shape = projection_shape(ProjectionSpec { - kind, - rows, - columns: cols, - })?; - wh[i] = Some(self.input( - buffer, - shape.weight_bytes, - kind.weight_alignment(), - internal, - )?); + let shape = projection_shape(ProjectionSpec { kind, rows, columns: cols })?; + wh[i] = Some(self.input(buffer, shape.weight_bytes, kind.weight_alignment(), internal)?); } let wh = wh.map(|h| h.expect("three whole checked weights")); let outputs = [ @@ -125,10 +104,7 @@ impl<'ctx> RoutedResidentQueue<'ctx> { ]; let output_sizes = [t * 2560, t * 2560, t * 2560, t * 10240]; for (i, &out) in outputs.iter().enumerate() { - for (&weight, bytes) in - wh.iter() - .zip([weights.gate.bytes, weights.up.bytes, weights.down.bytes]) - { + for (&weight, bytes) in wh.iter().zip([weights.gate.bytes, weights.up.bytes, weights.down.bytes]) { if out.overlaps(output_sizes[i], weight, bytes) { return Err(Error::OutputAliasesInput); } @@ -140,9 +116,7 @@ impl<'ctx> RoutedResidentQueue<'ctx> { } } let mut pointers = Vec::new(); - pointers - .try_reserve_exact(t * 8) - .map_err(|_| Error::HostAllocation)?; + pointers.try_reserve_exact(t * 8).map_err(|_| Error::HostAllocation)?; for column in columns { let scratch = column.scratch.as_ref().ok_or(Error::ContextPoisoned)?; let activation = self.input(column.activation, 10240, 4, internal)?; @@ -163,23 +137,16 @@ impl<'ctx> RoutedResidentQueue<'ctx> { table.validate_projection_extent(t * 8, 8)?; let q8 = internal[1].checked_subspan(Q8, 0, t * 720)?; q8.validate_projection_extent(t * 720, 4)?; - let flags: [ffi::BufferHandle; 5] = std::array::from_fn(|i| { - internal[2] - .checked_subspan(STATUS, i * 4, 4) - .expect("five fixed checked words") - }); + let flags: [ffi::BufferHandle; 5] = + std::array::from_fn(|i| internal[2].checked_subspan(STATUS, i * 4, 4).expect("five fixed checked words")); let finite = self.finite.ok_or(Error::ContextPoisoned)?; let guard = self.context.enter()?; let kernels = (|| { Ok([ self.context.fixed_kernel(ops[0])?.function, self.context.fixed_kernel(ops[1])?.function, - self.context - .fixed_kernel(FixedOperation::GroupedSwiglu)? - .function, - self.context - .fixed_kernel(FixedOperation::CommonQuantize)? - .function, + self.context.fixed_kernel(FixedOperation::GroupedSwiglu)?.function, + self.context.fixed_kernel(FixedOperation::CommonQuantize)?.function, self.context.fixed_kernel(down_op)?.function, ]) })(); @@ -190,14 +157,8 @@ impl<'ctx> RoutedResidentQueue<'ctx> { } let kernels = combine(kernels, pop)?; let mut commands = Vec::new(); - commands - .try_reserve_exact(10) - .map_err(|_| Error::HostAllocation)?; - commands.push(Command::Finite( - finite[0], - 5, - ffi::MmqResidentArguments::zero(internal[2], 5), - )); + commands.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Finite(finite[0], 5, ffi::MmqResidentArguments::zero(internal[2], 5))); commands.push(Command::Gu( kernels[0], t as u32, @@ -229,9 +190,7 @@ impl<'ctx> RoutedResidentQueue<'ctx> { commands.push(scan(finite[1], outputs[3], flags[4], (2560 * t) as u32)); // Ten commands include reset plus every original producer/finite scan. let mut staging = Vec::new(); - staging - .try_reserve_exact(STATUS) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(STATUS).map_err(|_| Error::HostAllocation)?; staging.resize(STATUS, 0); let guard = self.context.enter()?; let mut operation = self.context.driver.api.copy_from(table, &pointers); @@ -254,29 +213,19 @@ impl<'ctx> RoutedResidentQueue<'ctx> { // Real host ABI/staging owners and all device buffers remain retained // by poison; no receipt exists for unknown completion. std::mem::forget((commands, pointers, staging)); - return combine(combine(operation, sync), pop) - .map(|()| unreachable!("uncertain drain")); + return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain drain")); } combine(combine(operation, sync), pop)?; let mut result = [0; 5]; for (value, bytes) in result.iter_mut().zip(staging.as_chunks::<4>().0) { *value = u32::from_le_bytes(*bytes); } - if result - .iter() - .enumerate() - .any(|(i, &v)| if i == 3 { v > 3 } else { v > 1 }) - { + if result.iter().enumerate().any(|(i, &v)| if i == 3 { v > 3 } else { v > 1 }) { self.failed = true; self.context.poisoned.set(true); return Err(Error::InvalidDriverValue("routed resident numeric witness")); } - Ok(RoutedResidentCompletion { - owner: self, - hidden, - down, - flags: result, - }) + Ok(RoutedResidentCompletion { owner: self, hidden, down, flags: result }) } pub fn close(mut self) -> Result<()> { self.release() diff --git a/crates/cuda-driver/src/routed_resident_queue_gpu.rs b/crates/cuda-driver/src/routed_resident_queue_gpu.rs index 79f5fb48..3d0a9fa1 100644 --- a/crates/cuda-driver/src/routed_resident_queue_gpu.rs +++ b/crates/cuda-driver/src/routed_resident_queue_gpu.rs @@ -18,9 +18,7 @@ fn original_first_routed_resident_pipeline_all_products_refusals_reset_and_clean assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes")); let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device"); - let context = device - .create_context(16 * 1024 * 1024) - .expect("bounded Context"); + let context = device.create_context(16 * 1024 * 1024).expect("bounded Context"); let foreign = match device.create_context(16 * 1024 * 1024) { Ok(v) => v, Err(e) => { @@ -55,23 +53,23 @@ fn original_first_routed_resident_pipeline_all_products_refusals_reset_and_clean #[path = "routed_resident_queue_gpu/upload_fn.rs"] mod upload_fn; #[allow(unused_imports)] -use upload_fn::upload; -#[allow(unused_imports)] -use upload_fn::read; -#[allow(unused_imports)] -use upload_fn::weights; -#[allow(unused_imports)] use upload_fn::activation; #[allow(unused_imports)] -use upload_fn::view; +use upload_fn::compare; #[allow(unused_imports)] use upload_fn::finite; #[allow(unused_imports)] use upload_fn::original; #[allow(unused_imports)] -use upload_fn::compare; -#[allow(unused_imports)] use upload_fn::pair; +#[allow(unused_imports)] +use upload_fn::read; +#[allow(unused_imports)] +use upload_fn::upload; +#[allow(unused_imports)] +use upload_fn::view; +#[allow(unused_imports)] +use upload_fn::weights; #[path = "routed_resident_queue_gpu/case_fn.rs"] mod case_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/routed_resident_queue_gpu/case_fn.rs b/crates/cuda-driver/src/routed_resident_queue_gpu/case_fn.rs index 5c645943..bbedea1f 100644 --- a/crates/cuda-driver/src/routed_resident_queue_gpu/case_fn.rs +++ b/crates/cuda-driver/src/routed_resident_queue_gpu/case_fn.rs @@ -14,11 +14,7 @@ pub(super) fn case( faults: bool, report: &mut Report, ) -> Result<()> { - let mut matrices = [ - upload(context, &weights(gu))?, - upload(context, &weights(gu))?, - upload(context, &weights(d))?, - ]; + let mut matrices = [upload(context, &weights(gu))?, upload(context, &weights(gu))?, upload(context, &weights(d))?]; let mut buffers = [ context.allocate(t * 2560)?, context.allocate(t * 2560)?, @@ -34,25 +30,13 @@ pub(super) fn case( for (c, input) in inputs.iter_mut().enumerate() { input.copy_from(&activation(c + 1, changed))?; } - let prepared = inputs - .iter() - .map(|x| context.prepare_routed_gate_up_q8(x)) - .collect::>>()?; + let prepared = inputs.iter().map(|x| context.prepare_routed_gate_up_q8(x)).collect::>>()?; let step = (|| { let mut columns: Vec<_> = prepared.iter().collect(); if changed { columns.reverse(); } - let refusal = pair( - context, - queue, - &matrices, - gu, - d, - &columns, - &mut buffers, - report, - )?; + let refusal = pair(context, queue, &matrices, gu, d, &columns, &mut buffers, report)?; report.errors += usize::from(refusal.is_some()); let saved = buffers.iter().map(read).collect::>>()?; for count in [0usize, 65] { @@ -60,8 +44,7 @@ pub(super) fn case( let [g, u, h, o] = &mut buffers; let result = queue.compose(view(&matrices, gu, d), &bad, g, u, h, o); report.guards += 1; - report.errors += - usize::from(!matches!(&result, Err(Error::InvalidProjectionShape))); + report.errors += usize::from(!matches!(&result, Err(Error::InvalidProjectionShape))); drop(result); } let foreign_weight = upload(foreign, &weights(gu))?; @@ -114,21 +97,10 @@ pub(super) fn case( // All actual headers except the last remain their finite baseline. let at = valid.len() - width; matrices[role].copy_from_range(at, &bits.to_le_bytes())?; - let prepared = inputs - .iter() - .map(|x| context.prepare_routed_gate_up_q8(x)) - .collect::>>()?; + let prepared = + inputs.iter().map(|x| context.prepare_routed_gate_up_q8(x)).collect::>>()?; let columns: Vec<_> = prepared.iter().collect(); - let step = pair( - context, - queue, - &matrices, - gu, - d, - &columns, - &mut buffers, - report, - ); + let step = pair(context, queue, &matrices, gu, d, &columns, &mut buffers, report); let mut close = Ok(()); for item in prepared { close = combine(close, item.close()); @@ -156,48 +128,23 @@ pub(super) fn case( for input in &mut inputs { input.copy_from(&vec![1000f32.to_le_bytes(); 2560].concat())?; } - let prepared = inputs - .iter() - .map(|x| context.prepare_routed_gate_up_q8(x)) - .collect::>>()?; + let prepared = inputs.iter().map(|x| context.prepare_routed_gate_up_q8(x)).collect::>>()?; let columns: Vec<_> = prepared.iter().collect(); - let step = pair( - context, - queue, - &matrices, - gu, - d, - &columns, - &mut buffers, - report, - ); + let step = pair(context, queue, &matrices, gu, d, &columns, &mut buffers, report); let mut close = Ok(()); for item in prepared { close = combine(close, item.close()); } - report.errors += - usize::from(combine(step, close)? != Some(RoutedResidentRefusal::DownQuant)); + report.errors += usize::from(combine(step, close)? != Some(RoutedResidentRefusal::DownQuant)); report.faults += 1; matrices[0].copy_from(&weights(gu))?; matrices[1].copy_from(&weights(gu))?; for (c, input) in inputs.iter_mut().enumerate() { input.copy_from(&activation(c + 1, false))?; } - let prepared = inputs - .iter() - .map(|x| context.prepare_routed_gate_up_q8(x)) - .collect::>>()?; + let prepared = inputs.iter().map(|x| context.prepare_routed_gate_up_q8(x)).collect::>>()?; let columns: Vec<_> = prepared.iter().collect(); - let step = pair( - context, - queue, - &matrices, - gu, - d, - &columns, - &mut buffers, - report, - ); + let step = pair(context, queue, &matrices, gu, d, &columns, &mut buffers, report); let mut close = Ok(()); for item in prepared { close = combine(close, item.close()); diff --git a/crates/cuda-driver/src/routed_resident_queue_gpu/run_fn.rs b/crates/cuda-driver/src/routed_resident_queue_gpu/run_fn.rs index 94501a4a..f030963d 100644 --- a/crates/cuda-driver/src/routed_resident_queue_gpu/run_fn.rs +++ b/crates/cuda-driver/src/routed_resident_queue_gpu/run_fn.rs @@ -10,29 +10,14 @@ pub(super) fn run(context: &Context<'_>, foreign: &Context<'_>) -> Result Vec { } // Keep ordinary composed SwiGLU sums representable by native Q8_1 // HALF headers. Large finite/NaN refusal cases overwrite this below. - let scale = if matches!(format, RoutedFormat::IQ4_NL | RoutedFormat::Q2_0) { - 0x1400u16 - } else { - 0x0010u16 - }; + let scale = if matches!(format, RoutedFormat::IQ4_NL | RoutedFormat::Q2_0) { 0x1400u16 } else { 0x0010u16 }; bytes[..2].copy_from_slice(&scale.to_le_bytes()); } } @@ -68,11 +64,7 @@ pub(super) fn view<'a, 'ctx>( } } pub(super) fn finite(bytes: &[u8]) -> bool { - bytes - .as_chunks::<4>() - .0 - .iter() - .all(|v| f32::from_le_bytes(*v).is_finite()) + bytes.as_chunks::<4>().0.iter().all(|v| f32::from_le_bytes(*v).is_finite()) } pub(super) fn original( context: &Context<'_>, @@ -97,13 +89,7 @@ pub(super) fn original( if !finite(&products[2]) { return Ok((Some(RoutedResidentRefusal::Hidden), products)); } - match context.project_routed_down_columns( - weights.down, - hidden, - down, - columns.len(), - weights.down_format, - ) { + match context.project_routed_down_columns(weights.down, hidden, down, columns.len(), weights.down_format) { Ok(()) => {} Err(Error::InvalidQ8Activation) => { return Ok((Some(RoutedResidentRefusal::DownQuant), products)); @@ -111,20 +97,12 @@ pub(super) fn original( Err(e) => return Err(e), } products.push(read(down)?); - Ok(( - (!finite(&products[3])).then_some(RoutedResidentRefusal::Down), - products, - )) + Ok(((!finite(&products[3])).then_some(RoutedResidentRefusal::Down), products)) } pub(super) fn compare(original: &[u8], actual: &[u8], report: &mut Report) { report.products += 1; report.errors += usize::from(original.len() != actual.len()); - for (a, b) in original - .as_chunks::<4>() - .0 - .iter() - .zip(actual.as_chunks::<4>().0) - { + for (a, b) in original.as_chunks::<4>().0.iter().zip(actual.as_chunks::<4>().0) { report.words += 1; report.differences += usize::from(a != b); } @@ -152,10 +130,7 @@ pub(super) fn pair( report.errors += usize::from(completion.completed_down().is_some() != expected.is_none()); report.errors += usize::from( completion.completed_hidden().is_some() - != matches!( - expected, - None | Some(RoutedResidentRefusal::DownQuant | RoutedResidentRefusal::Down) - ), + != matches!(expected, None | Some(RoutedResidentRefusal::DownQuant | RoutedResidentRefusal::Down)), ); // Original finite-prefix products are meaningful even on refusal; later // speculative products are neither expected nor published. diff --git a/crates/cuda-driver/src/routed_stage_finite_guard.rs b/crates/cuda-driver/src/routed_stage_finite_guard.rs index c9450036..df9dfe5b 100644 --- a/crates/cuda-driver/src/routed_stage_finite_guard.rs +++ b/crates/cuda-driver/src/routed_stage_finite_guard.rs @@ -22,9 +22,7 @@ impl RoutedFiniteStage { Self::Gate | Self::Up | Self::Hidden => 640usize, Self::Down => 2560usize, }; - let words = width - .checked_mul(columns) - .ok_or(Error::InvalidProjectionShape)?; + let words = width.checked_mul(columns).ok_or(Error::InvalidProjectionShape)?; u32::try_from(words).map_err(|_| Error::InvalidProjectionShape) } } @@ -53,20 +51,10 @@ impl<'ctx> RoutedStageFiniteGuard<'ctx> { if context.is_poisoned() || context.handle.is_none() { return Err(Error::ContextPoisoned); } - if context - .allocated_bytes() - .checked_add(STATUS_BYTES) - .is_none_or(|n| n > context.budget) - { + if context.allocated_bytes().checked_add(STATUS_BYTES).is_none_or(|n| n > context.budget) { return Err(Error::BudgetExceeded); } - let mut owner = Self { - context, - status: None, - module: None, - functions: None, - failed: false, - }; + let mut owner = Self { context, status: None, module: None, functions: None, failed: false }; let result = (|| { owner.status = Some(context.allocate(STATUS_BYTES)?); let guard = context.enter()?; @@ -110,17 +98,13 @@ impl<'ctx> RoutedStageFiniteGuard<'ctx> { return Err(Error::ContextPoisoned); } let words = stage.words(columns)?; - let bytes = (words as usize) - .checked_mul(4) - .ok_or(Error::InvalidProjectionShape)?; + let bytes = (words as usize).checked_mul(4).ok_or(Error::InvalidProjectionShape)?; let functions = self.functions.ok_or(Error::ContextPoisoned)?; if self.module.is_none() { return Err(Error::ContextPoisoned); } let status_buffer = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(self.context, source_buffer.context) - || !std::ptr::eq(self.context, status_buffer.context) - { + if !std::ptr::eq(self.context, source_buffer.context) || !std::ptr::eq(self.context, status_buffer.context) { return Err(Error::ContextMismatch); } if source_buffer.bytes != bytes || status_buffer.bytes != STATUS_BYTES { @@ -137,22 +121,12 @@ impl<'ctx> RoutedStageFiniteGuard<'ctx> { let mut reset = ffi::MmqResidentArguments::zero(status, 1); let mut scan = ffi::MmqResidentArguments::finite(source, status, 0, words, 0); let mut staging = Vec::new(); - staging - .try_reserve_exact(STATUS_BYTES) - .map_err(|_| Error::HostAllocation)?; + staging.try_reserve_exact(STATUS_BYTES).map_err(|_| Error::HostAllocation)?; staging.resize(STATUS_BYTES, 0); let guard = self.context.enter()?; - let mut operation = - self.context - .driver - .api - .launch_mmq_resident(functions[0], 1, &mut reset); + let mut operation = self.context.driver.api.launch_mmq_resident(functions[0], 1, &mut reset); if operation.is_ok() { - operation = - self.context - .driver - .api - .launch_mmq_resident(functions[1], words, &mut scan); + operation = self.context.driver.api.launch_mmq_resident(functions[1], words, &mut scan); } if operation.is_ok() { operation = self.context.driver.api.copy_to(status, &mut staging); @@ -198,13 +172,10 @@ impl<'ctx> RoutedStageFiniteGuard<'ctx> { if status_result.is_err() { self.context.poisoned.set(true); } - let module_result = - self.module - .take() - .map_or(Ok(()), |module| match self.context.enter() { - Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), - Err(error) => Err(error), - }); + let module_result = self.module.take().map_or(Ok(()), |module| match self.context.enter() { + Ok(guard) => combine(self.context.driver.api.unload(module), guard.finish()), + Err(error) => Err(error), + }); if module_result.is_err() { self.context.poisoned.set(true); // Keep the driver ABI loaded while an uncertain module can exist. diff --git a/crates/cuda-driver/src/routed_stage_finite_guard_gpu.rs b/crates/cuda-driver/src/routed_stage_finite_guard_gpu.rs index bcc97297..f2324aee 100644 --- a/crates/cuda-driver/src/routed_stage_finite_guard_gpu.rs +++ b/crates/cuda-driver/src/routed_stage_finite_guard_gpu.rs @@ -2,12 +2,8 @@ use super::*; const ENABLE: &str = "LELEKA_STRA172_RUN_ROUTED_FINITE_GUARD"; -const STAGES: [RoutedFiniteStage; 4] = [ - RoutedFiniteStage::Gate, - RoutedFiniteStage::Up, - RoutedFiniteStage::Hidden, - RoutedFiniteStage::Down, -]; +const STAGES: [RoutedFiniteStage; 4] = + [RoutedFiniteStage::Gate, RoutedFiniteStage::Up, RoutedFiniteStage::Hidden, RoutedFiniteStage::Down]; #[derive(Default, Debug)] struct Report { @@ -54,20 +50,14 @@ fn compare( ) -> Result<()> { // The unchanged original full-D2H/is_finite check completes FIRST. let original = read(input)?; - let reference = original - .as_chunks::<4>() - .0 - .iter() - .all(|word| f32::from_le_bytes(*word).is_finite()); + let reference = original.as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_finite()); report.original_words += original.len() / 4; let actual = owner.check_stage(input, stage, columns)?; report.checks += 1; report.disagreements += usize::from(actual != reference); report.witness_errors += usize::from(owner.context.is_poisoned() || owner.failed); let status = read(owner.status.as_ref().ok_or(Error::ContextPoisoned)?)?; - report.witness_errors += usize::from( - u32::from_le_bytes(status.as_chunks::<4>().0[0]) != u32::from(!reference), - ); + report.witness_errors += usize::from(u32::from_le_bytes(status.as_chunks::<4>().0[0]) != u32::from(!reference)); let after = read(input)?; for (a, b) in original.as_chunks::<4>().0.iter().zip(after.as_chunks::<4>().0) { report.unchanged_words += 1; @@ -102,8 +92,7 @@ fn whole_stage( } } // A stale status must be reset even when no source word is invalid. - owner.status.as_mut().ok_or(Error::ContextPoisoned)? - .copy_from(&u32::MAX.to_le_bytes())?; + owner.status.as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&u32::MAX.to_le_bytes())?; compare(owner, &input, stage, columns, report)?; report.resets += 1; Ok(()) @@ -144,13 +133,10 @@ fn admission( refused(owner.check_stage(&input, RoutedFiniteStage::Down, 1), report)?; short = Some(context.allocate(2556)?); long = Some(context.allocate(2564)?); - refused(owner.check_stage(short.as_ref().ok_or(Error::ContextPoisoned)?, - RoutedFiniteStage::Gate, 1), report)?; - refused(owner.check_stage(long.as_ref().ok_or(Error::ContextPoisoned)?, - RoutedFiniteStage::Gate, 1), report)?; + refused(owner.check_stage(short.as_ref().ok_or(Error::ContextPoisoned)?, RoutedFiniteStage::Gate, 1), report)?; + refused(owner.check_stage(long.as_ref().ok_or(Error::ContextPoisoned)?, RoutedFiniteStage::Gate, 1), report)?; other = Some(foreign.allocate(2560)?); - refused(owner.check_stage(other.as_ref().ok_or(Error::ContextPoisoned)?, - RoutedFiniteStage::Gate, 1), report)?; + refused(owner.check_stage(other.as_ref().ok_or(Error::ContextPoisoned)?, RoutedFiniteStage::Gate, 1), report)?; // Every admission refusal leaves the actual owner usable and unpoisoned. compare(owner, &input, RoutedFiniteStage::Gate, 1, report) })(); @@ -225,6 +211,8 @@ fn original_first_complete_routed_finite_stages_reset_and_cleanup() { assert!(report.original_words > 4_000_000); assert_eq!(report.disagreements, 0); assert_eq!(report.witness_errors, 0); - eprintln!("ROUTED-FINITE checks={} words={} faults={} resets={} guards={} disagreements=0 allocated=0 context_closed=true", - report.checks, report.original_words, report.faults, report.resets, report.guards); + eprintln!( + "ROUTED-FINITE checks={} words={} faults={} resets={} guards={} disagreements=0 allocated=0 context_closed=true", + report.checks, report.original_words, report.faults, report.resets, report.guards + ); } diff --git a/crates/cuda-driver/src/s_gemv_legacy.rs b/crates/cuda-driver/src/s_gemv_legacy.rs index 62f193c3..e4cc50aa 100644 --- a/crates/cuda-driver/src/s_gemv_legacy.rs +++ b/crates/cuda-driver/src/s_gemv_legacy.rs @@ -118,53 +118,53 @@ mod tests; mod impl_default_for_sform; #[allow(unused_imports)] -use impl_default_for_sform::grid_for; +use impl_default_for_sform::bits_u8; #[allow(unused_imports)] use impl_default_for_sform::ceil_div; #[allow(unused_imports)] -use impl_default_for_sform::group_shift_of; -#[allow(unused_imports)] use impl_default_for_sform::check_tpr; #[allow(unused_imports)] -use impl_default_for_sform::bits_u8; +use impl_default_for_sform::grid_for; +#[allow(unused_imports)] +use impl_default_for_sform::group_shift_of; #[allow(unused_imports)] pub use impl_default_for_sform::plan_s_gemv; #[allow(unused_imports)] -pub use impl_default_for_sform::plan_s_gemv_split; -#[allow(unused_imports)] -use impl_default_for_sform::q8_form_ok; +pub use impl_default_for_sform::plan_s_gemv_q8_0_split; #[allow(unused_imports)] pub use impl_default_for_sform::plan_s_gemv_q8k; #[allow(unused_imports)] pub use impl_default_for_sform::plan_s_gemv_q8k_split; #[allow(unused_imports)] -pub use impl_default_for_sform::plan_s_gemv_q8_0_split; +pub use impl_default_for_sform::plan_s_gemv_split; #[allow(unused_imports)] pub use impl_default_for_sform::plan_s2_gemv; +#[allow(unused_imports)] +use impl_default_for_sform::q8_form_ok; mod plan_s2_gemv_quads_fn; #[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::plan_s2_gemv_quads; -#[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::plan_s2_gemv_q8; -#[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::plan_s2_gemv_fast; -#[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::f16_to_f32; -#[allow(unused_imports)] pub use plan_s2_gemv_quads_fn::code_at; #[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::pack_codes; -#[allow(unused_imports)] pub use plan_s2_gemv_quads_fn::decode; #[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::q8k_dequant; -#[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::q8_0_dequant; -#[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::reference_f64; +pub use plan_s2_gemv_quads_fn::f16_to_f32; #[allow(unused_imports)] pub use plan_s2_gemv_quads_fn::naive_f32; #[allow(unused_imports)] -pub use plan_s2_gemv_quads_fn::split_f32; +pub use plan_s2_gemv_quads_fn::pack_codes; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::plan_s2_gemv_fast; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::plan_s2_gemv_q8; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::plan_s2_gemv_quads; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::q8_0_dequant; #[allow(unused_imports)] pub use plan_s2_gemv_quads_fn::q8_split_f32; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::q8k_dequant; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::reference_f64; +#[allow(unused_imports)] +pub use plan_s2_gemv_quads_fn::split_f32; 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 cd0d67f6..f3b99a71 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 @@ -5,7 +5,14 @@ use super::*; impl Default for SForm { fn default() -> Self { - Self { code_bits: 2, code_bias: -1, group_elems: 64, codebook: Codebook::Affine, has_offset: false, act_kind: 0 } + Self { + code_bits: 2, + code_bias: -1, + group_elems: 64, + codebook: Codebook::Affine, + has_offset: false, + act_kind: 0, + } } } impl Kernel { @@ -56,14 +63,26 @@ impl Kernel { impl Error { pub fn message(&self) -> String { match self { - Self::NInNotGroupMultiple { who, n_in, group } => format!("{who}: n_in {n_in} is not a multiple of group_elems {group}"), + Self::NInNotGroupMultiple { who, n_in, group } => { + format!("{who}: n_in {n_in} is not a multiple of group_elems {group}") + } Self::OffsetMissing { who } => format!("{who}: form says has_offset but offset is null"), Self::UnsupportedCodeBits { who, bits } => format!("{who}: unsupported code_bits {bits}"), - Self::NoActivationContract { who, bits } => format!("{who}: code_bits {bits} has no activation contract for this kernel"), - Self::NInNotBlockMultiple { who, n_in, block } => format!("{who}: n_in {n_in} is not a multiple of {block}"), - Self::GroupNotPowerOfTwo { who, group } => format!("{who}: group_elems must be a power of two, got {group}"), - Self::GroupNotMultiple { who, group, multiple } => format!("{who}: group_elems {group} is not a multiple of {multiple}"), - Self::ThreadsPerRow { who, threads } => format!("{who}: threads_per_row must be a power of two in 1..1024, got {threads}"), + Self::NoActivationContract { who, bits } => { + format!("{who}: code_bits {bits} has no activation contract for this kernel") + } + Self::NInNotBlockMultiple { who, n_in, block } => { + format!("{who}: n_in {n_in} is not a multiple of {block}") + } + Self::GroupNotPowerOfTwo { who, group } => { + format!("{who}: group_elems must be a power of two, got {group}") + } + Self::GroupNotMultiple { who, group, multiple } => { + format!("{who}: group_elems {group} is not a multiple of {multiple}") + } + Self::ThreadsPerRow { who, threads } => { + format!("{who}: threads_per_row must be a power of two in 1..1024, got {threads}") + } Self::StagingLimit { n_in } => { format!("s2_gemv_fast: n_in {n_in} exceeds the {S2_FAST_MAX_SHARED_HALVES}-half shared staging limit") } @@ -86,7 +105,11 @@ pub(super) fn group_shift_of(group: i32) -> i32 { s } pub(super) fn check_tpr(who: &'static str, tpr: i32) -> Result<(), Error> { - if tpr < 1 || tpr > 1024 || (tpr & (tpr - 1)) != 0 { Err(Error::ThreadsPerRow { who, threads: tpr }) } else { Ok(()) } + if tpr < 1 || tpr > 1024 || (tpr & (tpr - 1)) != 0 { + Err(Error::ThreadsPerRow { who, threads: tpr }) + } else { + Ok(()) + } } pub(super) fn bits_u8(who: &'static str, bits: i32, allowed: &[i32], contract: bool) -> Result { if allowed.contains(&bits) { @@ -112,12 +135,22 @@ pub fn plan_s_gemv(n_in: i64, n_out: i64, form: &SForm, offset_present: bool) -> } let bits = bits_u8(WHO, form.code_bits, &[2, 4, 8], false)?; let grid = grid_for(WHO, ceil_div(n_out, 128))?; - Ok(Some(Plan { kernel: Kernel::SGemv(bits), launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, group_shift: 0 })) + Ok(Some(Plan { + kernel: Kernel::SGemv(bits), + launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, + group_shift: 0, + })) } /// `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, form: &SForm, threads_per_row: i32, offset_present: bool) -> Result, Error> { +pub fn plan_s_gemv_split( + n_in: i64, + n_out: i64, + form: &SForm, + threads_per_row: i32, + offset_present: bool, +) -> Result, Error> { const WHO: &str = "s_gemv_split"; if n_in <= 0 || n_out <= 0 { return Ok(None); @@ -139,7 +172,11 @@ pub fn plan_s_gemv_split(n_in: i64, n_out: i64, form: &SForm, threads_per_row: i let grid = grid_for(WHO, n_out)?; Ok(Some(Plan { kernel: Kernel::SGemvSplit(bits), - launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: threads_per_row as u32 * 4 }, + launch: Launch { + grid: [grid, 1, 1], + block: [threads_per_row as u32, 1, 1], + dynamic_shared: threads_per_row as u32 * 4, + }, group_shift: group_shift_of(form.group_elems), })) } @@ -163,7 +200,11 @@ pub fn plan_s_gemv_q8k(n_in: i64, n_out: i64, form: &SForm) -> Result Result Result, Error> { return Err(Error::NInNotBlockMultiple { who: WHO, n_in, block: S2_QK }); } let grid = grid_for(WHO, ceil_div(n_out, 128))?; - Ok(Some(Plan { kernel: Kernel::S2Gemv, launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, group_shift: 0 })) + Ok(Some(Plan { + kernel: Kernel::S2Gemv, + launch: Launch { grid: [grid, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }, + group_shift: 0, + })) } 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 1e134c02..5410e30e 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 @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `s2_gemv_quads`: one block per row; the Original only checks `n_in % 4`. pub fn plan_s2_gemv_quads(n_in: i64, n_out: i64, threads_per_row: i32) -> Result, Error> { const WHO: &str = "s2_gemv_quads"; @@ -17,7 +16,11 @@ pub fn plan_s2_gemv_quads(n_in: i64, n_out: i64, threads_per_row: i32) -> Result let grid = grid_for(WHO, n_out)?; Ok(Some(Plan { kernel: Kernel::S2GemvQuads, - launch: Launch { grid: [grid, 1, 1], block: [threads_per_row as u32, 1, 1], dynamic_shared: threads_per_row as u32 * 4 }, + launch: Launch { + grid: [grid, 1, 1], + block: [threads_per_row as u32, 1, 1], + dynamic_shared: threads_per_row as u32 * 4, + }, group_shift: 0, })) } @@ -35,7 +38,11 @@ pub fn plan_s2_gemv_q8(n_in: i64, n_out: i64, threads_per_row: i32) -> Result { let g = o * (self.n_in / self.form.group_elems as usize) + e / self.form.group_elems as usize; let d = self.scales[g]; let b = self.offset.map_or(0.0, |off| off[g]); - decode(code_at(self.row_codes(o), self.form.code_bits as u32, e), self.form.code_bias, self.form.codebook) * d + b + decode(code_at(self.row_codes(o), self.form.code_bits as u32, e), self.form.code_bias, self.form.codebook) * d + + b } } diff --git a/crates/cuda-driver/src/s_gemv_legacy/tests.rs b/crates/cuda-driver/src/s_gemv_legacy/tests.rs index 863e061c..39bb5f08 100644 --- a/crates/cuda-driver/src/s_gemv_legacy/tests.rs +++ b/crates/cuda-driver/src/s_gemv_legacy/tests.rs @@ -114,7 +114,8 @@ fn cuda_source_carries_the_codebook_and_every_entry() { // 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},")); + 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"); } // the s2_gemv_fast code table was generated: row b is [(b>>2k & 3) - 1 for k in 0..4] @@ -145,14 +146,20 @@ fn plan_s_gemv_geometry_and_refusals() { assert_eq!(p.launch, Launch { grid: [80, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); assert_eq!(plan_s_gemv(0, 5, &s4(), false), Ok(None)); assert_eq!(plan_s_gemv(2560, 0, &s4(), false), Ok(None)); - assert_eq!(plan_s_gemv(100, 8, &s4(), false), Err(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 })); + assert_eq!( + plan_s_gemv(100, 8, &s4(), false), + Err(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }) + ); let mut f = s4(); f.has_offset = true; assert_eq!(plan_s_gemv(64, 8, &f, false), Err(Error::OffsetMissing { who: "s_gemv" })); assert!(plan_s_gemv(64, 8, &f, true).is_ok()); f.code_bits = 3; assert_eq!(plan_s_gemv(64, 8, &f, true), Err(Error::UnsupportedCodeBits { who: "s_gemv", bits: 3 })); - assert_eq!(Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }.message(), "s_gemv: n_in 100 is not a multiple of group_elems 32"); + assert_eq!( + Error::NInNotGroupMultiple { who: "s_gemv", n_in: 100, group: 32 }.message(), + "s_gemv: n_in 100 is not a multiple of group_elems 32" + ); } #[test] @@ -163,31 +170,56 @@ fn plan_split_uses_a_row_per_block_and_shift_group() { assert_eq!(p.group_shift, 6); assert_eq!(p.launch, Launch { grid: [640, 1, 1], block: [64, 1, 1], dynamic_shared: 256 }); for t in [0, 3, 2048, -1] { - assert_eq!(plan_s_gemv_split(2560, 640, &f, t, false), Err(Error::ThreadsPerRow { who: "s_gemv_split", threads: t })); + assert_eq!( + plan_s_gemv_split(2560, 640, &f, t, false), + Err(Error::ThreadsPerRow { who: "s_gemv_split", threads: t }) + ); } let odd = SForm { group_elems: 48, ..f }; - assert_eq!(plan_s_gemv_split(2560, 8, &odd, 32, false), Err(Error::GroupNotPowerOfTwo { who: "s_gemv_split", group: 48 })); + assert_eq!( + plan_s_gemv_split(2560, 8, &odd, 32, false), + Err(Error::GroupNotPowerOfTwo { who: "s_gemv_split", group: 48 }) + ); let two = SForm { group_elems: 2, ..f }; - assert_eq!(plan_s_gemv_split(64, 8, &two, 32, false), Err(Error::GroupNotMultiple { who: "s_gemv_split", group: 2, multiple: 4 })); + assert_eq!( + plan_s_gemv_split(64, 8, &two, 32, false), + Err(Error::GroupNotMultiple { who: "s_gemv_split", group: 2, multiple: 4 }) + ); // stricter than the Original: n_in must be a group multiple assert!(plan_s_gemv_split(2562, 8, &f, 32, false).is_err()); } #[test] fn plan_q8_kernels_enforce_the_activation_contract() { - let f = SForm { code_bits: 4, code_bias: 0, group_elems: 32, codebook: Codebook::Iq4Nl, has_offset: false, act_kind: 1 }; + let f = SForm { + code_bits: 4, + code_bias: 0, + group_elems: 32, + codebook: Codebook::Iq4Nl, + 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 })); + 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 })); + 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_eq!( + plan_s_gemv_q8_0_split(640, 8, &g8), + Err(Error::GroupNotMultiple { who: "s_gemv_q8_0_split", group: 8, multiple: 16 }) + ); 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, .. }))); @@ -196,11 +228,17 @@ fn plan_q8_kernels_enforce_the_activation_contract() { #[test] fn plan_s2_kernels() { - assert_eq!(plan_s2_gemv(2560, 300).unwrap().unwrap().launch, Launch { grid: [3, 1, 1], block: [128, 1, 1], dynamic_shared: 0 }); + assert_eq!( + plan_s2_gemv(2560, 300).unwrap().unwrap().launch, + Launch { grid: [3, 1, 1], block: [128, 1, 1], dynamic_shared: 0 } + ); assert!(plan_s2_gemv(100, 8).is_err()); let q = plan_s2_gemv_quads(2560, 640, 32).unwrap().unwrap(); assert_eq!(q.launch, Launch { grid: [640, 1, 1], block: [32, 1, 1], dynamic_shared: 128 }); - assert_eq!(plan_s2_gemv_quads(6, 8, 32), Err(Error::NInNotBlockMultiple { who: "s2_gemv_quads", n_in: 6, block: 4 })); + assert_eq!( + plan_s2_gemv_quads(6, 8, 32), + Err(Error::NInNotBlockMultiple { who: "s2_gemv_quads", n_in: 6, block: 4 }) + ); assert!(plan_s2_gemv_quads(64, 8, 24).is_err()); assert_eq!(plan_s2_gemv_q8(640, 8, 64).unwrap().unwrap().launch.dynamic_shared, 256); assert!(plan_s2_gemv_q8(96, 8, 64).is_err()); diff --git a/crates/cuda-driver/src/sealed_ptx.rs b/crates/cuda-driver/src/sealed_ptx.rs index f613fb1c..01ecaeed 100644 --- a/crates/cuda-driver/src/sealed_ptx.rs +++ b/crates/cuda-driver/src/sealed_ptx.rs @@ -4,10 +4,7 @@ //! (All checked-in assets were compiled with nvcc 13.2.86 and sealed on 2026-10-15; `None` and the //! mismatch paths stay as the fail-closed guards and are exercised on synthetic corrupted copies.) -pub(crate) fn pinned( - ptx: &'static [u8], - pin: Option<(usize, [u8; 32])>, -) -> Option<&'static [u8]> { +pub(crate) fn pinned(ptx: &'static [u8], pin: Option<(usize, [u8; 32])>) -> Option<&'static [u8]> { let (len, digest) = pin?; if len < 2 || ptx.len() != len || ptx.last() != Some(&0) { return None; @@ -52,10 +49,8 @@ pub(crate) mod test_support { /// A copy whose body differs from `ptx` in exactly one byte (still ASCII, still no NUL, same length). pub(crate) fn one_byte_corrupted(ptx: &[u8]) -> &'static [u8] { let mut copy = ptx.to_vec(); - let at = copy[..copy.len() / 2 + 1] - .iter() - .rposition(|b| b.is_ascii_alphanumeric()) - .expect("an alphanumeric byte"); + let at = + copy[..copy.len() / 2 + 1].iter().rposition(|b| b.is_ascii_alphanumeric()).expect("an alphanumeric byte"); copy[at] ^= 1; assert!(copy[at].is_ascii() && copy[at] != 0 && copy[at] != ptx[at]); assert_eq!(copy.iter().zip(ptx).filter(|(a, b)| a != b).count(), 1); diff --git a/crates/cuda-driver/src/serving_context.rs b/crates/cuda-driver/src/serving_context.rs index 4cdcebb8..9156b927 100644 --- a/crates/cuda-driver/src/serving_context.rs +++ b/crates/cuda-driver/src/serving_context.rs @@ -32,11 +32,7 @@ pub struct ServingContext { impl ServingContext { /// The unconfigured default: `262144` cells and the identity RoPE. pub fn trained() -> Self { - Self { - geometry: QsaGeometry::TRAINED, - rope: RopeScaling::default(), - rope_args: RopeKernelArgs::default(), - } + Self { geometry: QsaGeometry::TRAINED, rope: RopeScaling::default(), rope_args: RopeKernelArgs::default() } } /// Whether any RoPE argument differs from the identity the committed PTX bakes. pub fn rope_is_scaled(&self) -> bool { @@ -51,36 +47,23 @@ static SERVING: OnceLock = OnceLock::new(); /// `rope_scaling_invalid`, and a context past the trained one requires an active scaling (the stock angles are /// out of spec there, `setup.py`). pub fn configure_serving_context(cells: usize, rope: &RopeScaling) -> Result<()> { - let geometry = QsaGeometry::new(cells) - .map_err(|_| Error::InvalidDriverValue("serving context cell count"))?; - rope.validate() - .map_err(|_| Error::InvalidDriverValue("serving context rope scaling"))?; + let geometry = QsaGeometry::new(cells).map_err(|_| Error::InvalidDriverValue("serving context cell count"))?; + rope.validate().map_err(|_| Error::InvalidDriverValue("serving context rope scaling"))?; if cells > TRAINED_CELLS && rope.kind == leleka_context::rope_scaling::RopeScalingType::None { - return Err(Error::InvalidDriverValue( - "contexts past the trained one need RoPE scaling", - )); + return Err(Error::InvalidDriverValue("contexts past the trained one need RoPE scaling")); } - let wanted = ServingContext { - geometry, - rope: *rope, - rope_args: rope.kernel_args(N_ROT), - }; + let wanted = ServingContext { geometry, rope: *rope, rope_args: rope.kernel_args(N_ROT) }; let got = SERVING.get_or_init(|| wanted); if *got == wanted { Ok(()) } else { - Err(Error::InvalidDriverValue( - "serving context already configured differently", - )) + Err(Error::InvalidDriverValue("serving context already configured differently")) } } /// The configured serving context, or the trained default when none was configured. pub fn serving_context() -> ServingContext { - SERVING - .get() - .copied() - .unwrap_or_else(ServingContext::trained) + SERVING.get().copied().unwrap_or_else(ServingContext::trained) } /// The geometry every context-linear size is derived from. @@ -101,31 +84,22 @@ static KV_RESIDENT: OnceLock = OnceLock::new(); /// must request the same count. Every owner sizes its pool from the value when it is created and launches /// with its own slot count, so an owner created before this call keeps the default window consistently. pub fn configure_kv_resident(cells: usize) -> Result<()> { - geometry() - .resident_pages_for(cells) - .map_err(|_| Error::InvalidDriverValue("resident KV window"))?; + geometry().resident_pages_for(cells).map_err(|_| Error::InvalidDriverValue("resident KV window"))?; if *KV_RESIDENT.get_or_init(|| cells) == cells { Ok(()) } else { - Err(Error::InvalidDriverValue( - "resident KV window already configured differently", - )) + Err(Error::InvalidDriverValue("resident KV window already configured differently")) } } /// The configured resident KV window in cells (the default 32768 when none was configured). pub fn kv_resident_cells() -> usize { - KV_RESIDENT - .get() - .copied() - .unwrap_or(KV_RESIDENT_DEFAULT_CELLS) + KV_RESIDENT.get().copied().unwrap_or(KV_RESIDENT_DEFAULT_CELLS) } /// Resident pages (VRAM slots) a new streamed QSA owner allocates. pub(crate) fn kv_resident_pages() -> Result { - geometry() - .resident_pages_for(kv_resident_cells()) - .map_err(|_| Error::InvalidDriverValue("resident KV window")) + geometry().resident_pages_for(kv_resident_cells()).map_err(|_| Error::InvalidDriverValue("resident KV window")) } #[cfg(test)] @@ -175,11 +149,7 @@ mod tests { assert!(configure_serving_context(524_288, &RopeScaling::default()).is_err()); assert!(configure_serving_context(3, &RopeScaling::default()).is_err()); assert!(configure_serving_context(0, &RopeScaling::default()).is_err()); - let bad = RopeScaling { - kind: RopeScalingType::YaRN, - factor: 0.5, - ..RopeScaling::default() - }; + let bad = RopeScaling { kind: RopeScalingType::YaRN, factor: 0.5, ..RopeScaling::default() }; assert!(configure_serving_context(524_288, &bad).is_err()); } } diff --git a/crates/cuda-driver/src/sm86_table.rs b/crates/cuda-driver/src/sm86_table.rs index 7f586c29..2b7adc3d 100644 --- a/crates/cuda-driver/src/sm86_table.rs +++ b/crates/cuda-driver/src/sm86_table.rs @@ -15,919 +15,1705 @@ pub(crate) struct Companion { pub(crate) static COMPANIONS: &[Companion] = &[ Companion { name: "ple_bf16_pack.ptx", - key: [0x01, 0x59, 0x28, 0xed, 0xe2, 0x02, 0x42, 0xc6, 0x31, 0x51, 0x30, 0x7b, 0xd5, 0x02, 0xbf, 0x98, 0xf4, 0xfb, 0x58, 0x0b, 0xad, 0x2b, 0x7d, 0x34, 0x72, 0xee, 0xbb, 0xa1, 0x12, 0x95, 0x30, 0xb3], + key: [ + 0x01, 0x59, 0x28, 0xed, 0xe2, 0x02, 0x42, 0xc6, 0x31, 0x51, 0x30, 0x7b, 0xd5, 0x02, 0xbf, 0x98, 0xf4, 0xfb, + 0x58, 0x0b, 0xad, 0x2b, 0x7d, 0x34, 0x72, 0xee, 0xbb, 0xa1, 0x12, 0x95, 0x30, 0xb3, + ], len: 8276, - sha: [0xb5, 0xe9, 0x9b, 0x53, 0x10, 0xcf, 0x1c, 0x92, 0x11, 0x67, 0x45, 0x06, 0x42, 0x6e, 0xe8, 0x99, 0x68, 0xd1, 0x4a, 0xb7, 0x71, 0x80, 0x55, 0x3d, 0x94, 0xd5, 0xbd, 0xb8, 0x8e, 0x3c, 0x9c, 0x09], + sha: [ + 0xb5, 0xe9, 0x9b, 0x53, 0x10, 0xcf, 0x1c, 0x92, 0x11, 0x67, 0x45, 0x06, 0x42, 0x6e, 0xe8, 0x99, 0x68, 0xd1, + 0x4a, 0xb7, 0x71, 0x80, 0x55, 0x3d, 0x94, 0xd5, 0xbd, 0xb8, 0x8e, 0x3c, 0x9c, 0x09, + ], ptx: concat!(include_str!("../ptx-sm86/ple_bf16_pack.ptx"), "\0").as_bytes(), }, Companion { name: "offline_native_dequant_f16.ptx", - key: [0x02, 0x0b, 0xc7, 0x97, 0xfc, 0x5a, 0x8f, 0x36, 0x23, 0x07, 0x54, 0x36, 0xb4, 0x4e, 0x02, 0x1a, 0x2e, 0x97, 0xff, 0xba, 0xaa, 0xbf, 0x54, 0xd2, 0x73, 0xea, 0xce, 0xc1, 0x31, 0x32, 0xeb, 0x2a], + key: [ + 0x02, 0x0b, 0xc7, 0x97, 0xfc, 0x5a, 0x8f, 0x36, 0x23, 0x07, 0x54, 0x36, 0xb4, 0x4e, 0x02, 0x1a, 0x2e, 0x97, + 0xff, 0xba, 0xaa, 0xbf, 0x54, 0xd2, 0x73, 0xea, 0xce, 0xc1, 0x31, 0x32, 0xeb, 0x2a, + ], len: 58080, - sha: [0x24, 0x31, 0xc2, 0x8a, 0x19, 0x52, 0x5c, 0x64, 0xb7, 0xf9, 0x75, 0x30, 0x6e, 0x01, 0x99, 0xce, 0x0f, 0x0d, 0x68, 0xf5, 0x5d, 0x22, 0x39, 0xe4, 0xb4, 0x72, 0x80, 0x9f, 0x1e, 0x17, 0x36, 0x70], + sha: [ + 0x24, 0x31, 0xc2, 0x8a, 0x19, 0x52, 0x5c, 0x64, 0xb7, 0xf9, 0x75, 0x30, 0x6e, 0x01, 0x99, 0xce, 0x0f, 0x0d, + 0x68, 0xf5, 0x5d, 0x22, 0x39, 0xe4, 0xb4, 0x72, 0x80, 0x9f, 0x1e, 0x17, 0x36, 0x70, + ], ptx: concat!(include_str!("../ptx-sm86/offline_native_dequant_f16.ptx"), "\0").as_bytes(), }, Companion { name: "kar_ple_fixed.ptx", - key: [0x03, 0xc9, 0xf6, 0x63, 0x49, 0x5b, 0xea, 0xf1, 0xdd, 0x42, 0x02, 0x5f, 0x14, 0x80, 0x9b, 0x7b, 0xfb, 0x8c, 0xd7, 0xad, 0x4c, 0x7f, 0xb5, 0x5e, 0x17, 0x3a, 0x79, 0xb1, 0xa9, 0x72, 0x0c, 0x3b], + key: [ + 0x03, 0xc9, 0xf6, 0x63, 0x49, 0x5b, 0xea, 0xf1, 0xdd, 0x42, 0x02, 0x5f, 0x14, 0x80, 0x9b, 0x7b, 0xfb, 0x8c, + 0xd7, 0xad, 0x4c, 0x7f, 0xb5, 0x5e, 0x17, 0x3a, 0x79, 0xb1, 0xa9, 0x72, 0x0c, 0x3b, + ], len: 5210, - sha: [0x76, 0xda, 0x12, 0x64, 0x39, 0xb0, 0x93, 0xf3, 0x9e, 0xda, 0x77, 0x14, 0x29, 0x9b, 0x6d, 0xf9, 0xc9, 0xa6, 0x0f, 0xaf, 0x43, 0xcb, 0x75, 0x8f, 0x49, 0xf3, 0x12, 0x42, 0x75, 0xce, 0xcf, 0x56], + sha: [ + 0x76, 0xda, 0x12, 0x64, 0x39, 0xb0, 0x93, 0xf3, 0x9e, 0xda, 0x77, 0x14, 0x29, 0x9b, 0x6d, 0xf9, 0xc9, 0xa6, + 0x0f, 0xaf, 0x43, 0xcb, 0x75, 0x8f, 0x49, 0xf3, 0x12, 0x42, 0x75, 0xce, 0xcf, 0x56, + ], ptx: concat!(include_str!("../ptx-sm86/kar_ple_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "bf16_f32_mmvf.ptx", - key: [0x04, 0x45, 0x43, 0xf6, 0x81, 0xbb, 0x23, 0xeb, 0x9c, 0xae, 0x60, 0x2b, 0x1a, 0x16, 0xaa, 0x7b, 0x23, 0x86, 0xd6, 0xd5, 0xc3, 0xb1, 0x5c, 0xc4, 0x19, 0x87, 0x33, 0x8b, 0xd6, 0x13, 0xb1, 0xc3], + key: [ + 0x04, 0x45, 0x43, 0xf6, 0x81, 0xbb, 0x23, 0xeb, 0x9c, 0xae, 0x60, 0x2b, 0x1a, 0x16, 0xaa, 0x7b, 0x23, 0x86, + 0xd6, 0xd5, 0xc3, 0xb1, 0x5c, 0xc4, 0x19, 0x87, 0x33, 0x8b, 0xd6, 0x13, 0xb1, 0xc3, + ], len: 5875, - sha: [0x54, 0xa3, 0x31, 0x46, 0x55, 0x8e, 0xf7, 0x6c, 0x81, 0x7f, 0xc8, 0xe5, 0x56, 0xf7, 0x09, 0x22, 0x8f, 0x90, 0xe2, 0xcc, 0xd6, 0x56, 0x5f, 0x57, 0xc4, 0xf8, 0xec, 0x46, 0x46, 0xe6, 0xc4, 0x42], + sha: [ + 0x54, 0xa3, 0x31, 0x46, 0x55, 0x8e, 0xf7, 0x6c, 0x81, 0x7f, 0xc8, 0xe5, 0x56, 0xf7, 0x09, 0x22, 0x8f, 0x90, + 0xe2, 0xcc, 0xd6, 0x56, 0x5f, 0x57, 0xc4, 0xf8, 0xec, 0x46, 0x46, 0xe6, 0xc4, 0x42, + ], ptx: concat!(include_str!("../ptx-sm86/bf16_f32_mmvf.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq4_xs_nc4.ptx", - key: [0x06, 0x11, 0xaa, 0x38, 0x6b, 0x2b, 0x36, 0x6e, 0x99, 0x42, 0xd5, 0x37, 0x17, 0x5b, 0xe5, 0xb1, 0xd9, 0x6e, 0x9c, 0x33, 0xbe, 0x5e, 0x12, 0x36, 0xc8, 0xb4, 0x6a, 0x83, 0x18, 0xf6, 0xb6, 0xc1], + key: [ + 0x06, 0x11, 0xaa, 0x38, 0x6b, 0x2b, 0x36, 0x6e, 0x99, 0x42, 0xd5, 0x37, 0x17, 0x5b, 0xe5, 0xb1, 0xd9, 0x6e, + 0x9c, 0x33, 0xbe, 0x5e, 0x12, 0x36, 0xc8, 0xb4, 0x6a, 0x83, 0x18, 0xf6, 0xb6, 0xc1, + ], len: 74210, - sha: [0x7c, 0xf9, 0x63, 0x32, 0x59, 0x2e, 0x39, 0x9b, 0x49, 0xe8, 0x4e, 0x53, 0x40, 0xff, 0xbb, 0xab, 0x26, 0xdb, 0x49, 0x25, 0x9a, 0x9b, 0x5e, 0x03, 0x04, 0x79, 0x4c, 0x1c, 0x0f, 0x54, 0x79, 0x41], + sha: [ + 0x7c, 0xf9, 0x63, 0x32, 0x59, 0x2e, 0x39, 0x9b, 0x49, 0xe8, 0x4e, 0x53, 0x40, 0xff, 0xbb, 0xab, 0x26, 0xdb, + 0x49, 0x25, 0x9a, 0x9b, 0x5e, 0x03, 0x04, 0x79, 0x4c, 0x1c, 0x0f, 0x54, 0x79, 0x41, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq4_xs_nc4.ptx"), "\0").as_bytes(), }, Companion { name: "q8_1_quantize.ptx", - key: [0x06, 0x40, 0x3c, 0x31, 0xe0, 0x94, 0x4b, 0x39, 0xc6, 0x8f, 0x3a, 0xf6, 0x37, 0xe3, 0x3d, 0xaa, 0x5f, 0x3d, 0x4c, 0x07, 0x26, 0x8f, 0x6b, 0xce, 0x15, 0x0c, 0x89, 0x1b, 0x9c, 0xf2, 0x33, 0xb0], + key: [ + 0x06, 0x40, 0x3c, 0x31, 0xe0, 0x94, 0x4b, 0x39, 0xc6, 0x8f, 0x3a, 0xf6, 0x37, 0xe3, 0x3d, 0xaa, 0x5f, 0x3d, + 0x4c, 0x07, 0x26, 0x8f, 0x6b, 0xce, 0x15, 0x0c, 0x89, 0x1b, 0x9c, 0xf2, 0x33, 0xb0, + ], len: 7200, - sha: [0xbb, 0x46, 0xb0, 0x53, 0xaf, 0x13, 0x94, 0xc4, 0x62, 0x17, 0x39, 0x3b, 0x4f, 0x7e, 0xff, 0xc1, 0xc9, 0x5f, 0xc4, 0x8a, 0xa5, 0x54, 0x68, 0x2a, 0xfb, 0xa5, 0xea, 0xeb, 0x0c, 0xd9, 0xc0, 0x6a], + sha: [ + 0xbb, 0x46, 0xb0, 0x53, 0xaf, 0x13, 0x94, 0xc4, 0x62, 0x17, 0x39, 0x3b, 0x4f, 0x7e, 0xff, 0xc1, 0xc9, 0x5f, + 0xc4, 0x8a, 0xa5, 0x54, 0x68, 0x2a, 0xfb, 0xa5, 0xea, 0xeb, 0x0c, 0xd9, 0xc0, 0x6a, + ], ptx: concat!(include_str!("../ptx-sm86/q8_1_quantize.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_gr_norm.ptx", - key: [0x06, 0xd6, 0x17, 0x7b, 0x48, 0x2c, 0xb6, 0x74, 0x13, 0xc6, 0x59, 0x6a, 0x02, 0x91, 0xb4, 0xda, 0xb1, 0x85, 0x03, 0x32, 0x16, 0x4a, 0x92, 0x12, 0xaf, 0xf6, 0x7b, 0x9e, 0xfd, 0xf2, 0x11, 0x20], + key: [ + 0x06, 0xd6, 0x17, 0x7b, 0x48, 0x2c, 0xb6, 0x74, 0x13, 0xc6, 0x59, 0x6a, 0x02, 0x91, 0xb4, 0xda, 0xb1, 0x85, + 0x03, 0x32, 0x16, 0x4a, 0x92, 0x12, 0xaf, 0xf6, 0x7b, 0x9e, 0xfd, 0xf2, 0x11, 0x20, + ], len: 29069, - sha: [0xaa, 0x51, 0x98, 0x13, 0x94, 0xa9, 0x4a, 0xe2, 0x22, 0xf4, 0x4c, 0x23, 0x9d, 0xff, 0x1e, 0xf2, 0x3c, 0xa7, 0xab, 0xda, 0x2a, 0xb0, 0x8f, 0x17, 0x95, 0x43, 0xd6, 0x2e, 0x71, 0x19, 0xd2, 0x1a], + sha: [ + 0xaa, 0x51, 0x98, 0x13, 0x94, 0xa9, 0x4a, 0xe2, 0x22, 0xf4, 0x4c, 0x23, 0x9d, 0xff, 0x1e, 0xf2, 0x3c, 0xa7, + 0xab, 0xda, 0x2a, 0xb0, 0x8f, 0x17, 0x95, 0x43, 0xd6, 0x2e, 0x71, 0x19, 0xd2, 0x1a, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_gr_norm.ptx"), "\0").as_bytes(), }, Companion { name: "offline_moe_prefill.ptx", - key: [0x07, 0x5e, 0xf4, 0x38, 0xcd, 0xb6, 0x21, 0x15, 0x05, 0x46, 0xdb, 0xef, 0xf8, 0xf5, 0xe6, 0xfd, 0xc4, 0xaa, 0xeb, 0xc2, 0xe7, 0xfa, 0x10, 0x99, 0xe6, 0xcc, 0x6e, 0xff, 0x3f, 0x5b, 0x6f, 0x34], + key: [ + 0x07, 0x5e, 0xf4, 0x38, 0xcd, 0xb6, 0x21, 0x15, 0x05, 0x46, 0xdb, 0xef, 0xf8, 0xf5, 0xe6, 0xfd, 0xc4, 0xaa, + 0xeb, 0xc2, 0xe7, 0xfa, 0x10, 0x99, 0xe6, 0xcc, 0x6e, 0xff, 0x3f, 0x5b, 0x6f, 0x34, + ], len: 71011, - sha: [0xe1, 0x5e, 0x02, 0x23, 0xec, 0x1d, 0x55, 0x5a, 0x3b, 0x89, 0xd7, 0xcb, 0xe3, 0xa6, 0xe9, 0xa0, 0xfe, 0x45, 0xb6, 0x5d, 0x39, 0x02, 0x90, 0x10, 0xd5, 0x19, 0xc7, 0x31, 0x32, 0x48, 0xcc, 0x7f], + sha: [ + 0xe1, 0x5e, 0x02, 0x23, 0xec, 0x1d, 0x55, 0x5a, 0x3b, 0x89, 0xd7, 0xcb, 0xe3, 0xa6, 0xe9, 0xa0, 0xfe, 0x45, + 0xb6, 0x5d, 0x39, 0x02, 0x90, 0x10, 0xd5, 0x19, 0xc7, 0x31, 0x32, 0x48, 0xcc, 0x7f, + ], ptx: concat!(include_str!("../ptx-sm86/offline_moe_prefill.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_down_iq4_nl.ptx", - key: [0x0b, 0x7b, 0xa2, 0xb0, 0x0b, 0x91, 0xb6, 0x64, 0x50, 0x51, 0x82, 0xbe, 0xf3, 0x2c, 0xac, 0xad, 0x06, 0x3f, 0x11, 0xee, 0x37, 0xed, 0x93, 0x13, 0x29, 0x64, 0x8d, 0x3e, 0xe4, 0xa0, 0x4d, 0x5a], + key: [ + 0x0b, 0x7b, 0xa2, 0xb0, 0x0b, 0x91, 0xb6, 0x64, 0x50, 0x51, 0x82, 0xbe, 0xf3, 0x2c, 0xac, 0xad, 0x06, 0x3f, + 0x11, 0xee, 0x37, 0xed, 0x93, 0x13, 0x29, 0x64, 0x8d, 0x3e, 0xe4, 0xa0, 0x4d, 0x5a, + ], len: 8620, - sha: [0x7d, 0xcf, 0xdb, 0x60, 0x83, 0x16, 0xcb, 0x28, 0xf0, 0x77, 0x6a, 0x10, 0xf8, 0x40, 0xb1, 0x98, 0x81, 0x43, 0x5c, 0x75, 0xb7, 0xf4, 0xf2, 0x2b, 0xa2, 0xc3, 0xfe, 0xf9, 0xe5, 0xbb, 0x89, 0xcb], + sha: [ + 0x7d, 0xcf, 0xdb, 0x60, 0x83, 0x16, 0xcb, 0x28, 0xf0, 0x77, 0x6a, 0x10, 0xf8, 0x40, 0xb1, 0x98, 0x81, 0x43, + 0x5c, 0x75, 0xb7, 0xf4, 0xf2, 0x2b, 0xa2, 0xc3, 0xfe, 0xf9, 0xe5, 0xbb, 0x89, 0xcb, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_down_iq4_nl.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_s2_fixed.ptx", - key: [0x0b, 0xf7, 0xb8, 0x12, 0x8c, 0x2d, 0x59, 0x0e, 0x36, 0xc8, 0xc5, 0x55, 0x97, 0xb4, 0xd0, 0x2f, 0x3c, 0x50, 0x7e, 0x12, 0x0f, 0x3d, 0x09, 0x1c, 0xb3, 0x54, 0xea, 0xee, 0x9e, 0x09, 0x74, 0xf7], + key: [ + 0x0b, 0xf7, 0xb8, 0x12, 0x8c, 0x2d, 0x59, 0x0e, 0x36, 0xc8, 0xc5, 0x55, 0x97, 0xb4, 0xd0, 0x2f, 0x3c, 0x50, + 0x7e, 0x12, 0x0f, 0x3d, 0x09, 0x1c, 0xb3, 0x54, 0xea, 0xee, 0x9e, 0x09, 0x74, 0xf7, + ], len: 103812, - sha: [0x97, 0xef, 0x26, 0x18, 0x0d, 0x6c, 0xa0, 0xa6, 0xc3, 0xb4, 0xe2, 0x8c, 0x55, 0x5b, 0xf4, 0x94, 0x12, 0x17, 0x5b, 0x7c, 0x65, 0x2d, 0x71, 0xa3, 0x1d, 0xc4, 0xee, 0x09, 0x7d, 0xc2, 0xc1, 0xb2], + sha: [ + 0x97, 0xef, 0x26, 0x18, 0x0d, 0x6c, 0xa0, 0xa6, 0xc3, 0xb4, 0xe2, 0x8c, 0x55, 0x5b, 0xf4, 0x94, 0x12, 0x17, + 0x5b, 0x7c, 0x65, 0x2d, 0x71, 0xa3, 0x1d, 0xc4, 0xee, 0x09, 0x7d, 0xc2, 0xc1, 0xb2, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_s2_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-adaptive-selected.ptx", - key: [0x0c, 0x7f, 0xa1, 0x08, 0x28, 0x02, 0x0b, 0x9e, 0xc8, 0x9b, 0x8b, 0x2f, 0xe5, 0x85, 0x50, 0x2c, 0x84, 0x89, 0xbe, 0x92, 0xf1, 0xf8, 0x25, 0x18, 0x7d, 0x4c, 0x6b, 0x90, 0xf1, 0x06, 0x49, 0x48], + key: [ + 0x0c, 0x7f, 0xa1, 0x08, 0x28, 0x02, 0x0b, 0x9e, 0xc8, 0x9b, 0x8b, 0x2f, 0xe5, 0x85, 0x50, 0x2c, 0x84, 0x89, + 0xbe, 0x92, 0xf1, 0xf8, 0x25, 0x18, 0x7d, 0x4c, 0x6b, 0x90, 0xf1, 0x06, 0x49, 0x48, + ], len: 3249625, - sha: [0x3f, 0x3c, 0xbc, 0x5f, 0x2d, 0x2d, 0xc8, 0x23, 0x83, 0xb1, 0x5a, 0x0d, 0xaf, 0xf0, 0x7f, 0xb6, 0x77, 0xcc, 0x4e, 0x45, 0xfb, 0x35, 0x73, 0x7d, 0xdc, 0x61, 0x41, 0x2f, 0xff, 0x3f, 0x79, 0x2c], + sha: [ + 0x3f, 0x3c, 0xbc, 0x5f, 0x2d, 0x2d, 0xc8, 0x23, 0x83, 0xb1, 0x5a, 0x0d, 0xaf, 0xf0, 0x7f, 0xb6, 0x77, 0xcc, + 0x4e, 0x45, 0xfb, 0x35, 0x73, 0x7d, 0xdc, 0x61, 0x41, 0x2f, 0xff, 0x3f, 0x79, 0x2c, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-adaptive-selected.ptx"), "\0").as_bytes(), }, Companion { name: "mapped_expert_copy.ptx", - key: [0x10, 0x51, 0x98, 0x85, 0xee, 0x9d, 0xab, 0xb6, 0x00, 0x10, 0x15, 0x4e, 0x2f, 0x80, 0x9b, 0x39, 0x73, 0x61, 0x86, 0xba, 0x1c, 0x0d, 0xac, 0x11, 0xa2, 0x40, 0x96, 0x5d, 0x05, 0x77, 0x62, 0x57], + key: [ + 0x10, 0x51, 0x98, 0x85, 0xee, 0x9d, 0xab, 0xb6, 0x00, 0x10, 0x15, 0x4e, 0x2f, 0x80, 0x9b, 0x39, 0x73, 0x61, + 0x86, 0xba, 0x1c, 0x0d, 0xac, 0x11, 0xa2, 0x40, 0x96, 0x5d, 0x05, 0x77, 0x62, 0x57, + ], len: 5620, - sha: [0x11, 0xda, 0x70, 0xf0, 0x16, 0x18, 0xa2, 0xa6, 0xf9, 0xd6, 0x59, 0xa6, 0xda, 0x03, 0xbb, 0x90, 0x48, 0x0d, 0x4c, 0xbd, 0x14, 0x1d, 0x3c, 0x36, 0x6c, 0xfe, 0x90, 0xc2, 0x65, 0x9d, 0x11, 0xb0], + sha: [ + 0x11, 0xda, 0x70, 0xf0, 0x16, 0x18, 0xa2, 0xa6, 0xf9, 0xd6, 0x59, 0xa6, 0xda, 0x03, 0xbb, 0x90, 0x48, 0x0d, + 0x4c, 0xbd, 0x14, 0x1d, 0x3c, 0x36, 0x6c, 0xfe, 0x90, 0xc2, 0x65, 0x9d, 0x11, 0xb0, + ], ptx: concat!(include_str!("../ptx-sm86/mapped_expert_copy.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify_window_qsa_gate.ptx", - key: [0x10, 0x80, 0x7c, 0x4c, 0x62, 0xd8, 0xbf, 0x4b, 0xe7, 0x5c, 0xfb, 0x1a, 0x50, 0x77, 0xfc, 0x3e, 0x00, 0xdc, 0x8f, 0x40, 0xea, 0x66, 0x9b, 0x22, 0xdc, 0xff, 0x7b, 0x78, 0x53, 0xab, 0x79, 0x49], + key: [ + 0x10, 0x80, 0x7c, 0x4c, 0x62, 0xd8, 0xbf, 0x4b, 0xe7, 0x5c, 0xfb, 0x1a, 0x50, 0x77, 0xfc, 0x3e, 0x00, 0xdc, + 0x8f, 0x40, 0xea, 0x66, 0x9b, 0x22, 0xdc, 0xff, 0x7b, 0x78, 0x53, 0xab, 0x79, 0x49, + ], len: 2232, - sha: [0x0c, 0x13, 0xa5, 0xf2, 0x95, 0x3f, 0x70, 0x7b, 0xb2, 0x87, 0xbc, 0x53, 0x25, 0x83, 0xf3, 0xfd, 0x69, 0xae, 0x8e, 0x80, 0xa7, 0x6e, 0x61, 0xdc, 0x88, 0x27, 0xe1, 0x3f, 0x00, 0x6b, 0x48, 0x49], + sha: [ + 0x0c, 0x13, 0xa5, 0xf2, 0x95, 0x3f, 0x70, 0x7b, 0xb2, 0x87, 0xbc, 0x53, 0x25, 0x83, 0xf3, 0xfd, 0x69, 0xae, + 0x8e, 0x80, 0xa7, 0x6e, 0x61, 0xdc, 0x88, 0x27, 0xe1, 0x3f, 0x00, 0x6b, 0x48, 0x49, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify_window_qsa_gate.ptx"), "\0").as_bytes(), }, Companion { name: "gr_native_batch.ptx", - key: [0x10, 0xa3, 0xe8, 0x36, 0xb9, 0x02, 0xe9, 0xa3, 0x87, 0x05, 0x5e, 0x98, 0x0c, 0x3e, 0xd0, 0x45, 0xe9, 0x0b, 0xdc, 0x25, 0x1e, 0xe1, 0xe6, 0xbe, 0x57, 0x66, 0x81, 0x61, 0x8f, 0x62, 0x1d, 0xb2], + key: [ + 0x10, 0xa3, 0xe8, 0x36, 0xb9, 0x02, 0xe9, 0xa3, 0x87, 0x05, 0x5e, 0x98, 0x0c, 0x3e, 0xd0, 0x45, 0xe9, 0x0b, + 0xdc, 0x25, 0x1e, 0xe1, 0xe6, 0xbe, 0x57, 0x66, 0x81, 0x61, 0x8f, 0x62, 0x1d, 0xb2, + ], len: 29664, - sha: [0xda, 0xec, 0x53, 0x68, 0x4c, 0x0c, 0xc3, 0x08, 0x8d, 0x46, 0xe9, 0x24, 0x14, 0x2d, 0xd3, 0x61, 0x32, 0xa5, 0x9f, 0xb7, 0x87, 0x16, 0x56, 0x94, 0xd1, 0x48, 0x27, 0xaf, 0xd3, 0x10, 0xd9, 0xc9], + sha: [ + 0xda, 0xec, 0x53, 0x68, 0x4c, 0x0c, 0xc3, 0x08, 0x8d, 0x46, 0xe9, 0x24, 0x14, 0x2d, 0xd3, 0x61, 0x32, 0xa5, + 0x9f, 0xb7, 0x87, 0x16, 0x56, 0x94, 0xd1, 0x48, 0x27, 0xaf, 0xd3, 0x10, 0xd9, 0xc9, + ], ptx: concat!(include_str!("../ptx-sm86/gr_native_batch.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_checks.ptx", - key: [0x16, 0xcb, 0x9f, 0x01, 0xe5, 0x4b, 0x05, 0x33, 0x43, 0x99, 0x37, 0xdd, 0x09, 0xae, 0xa4, 0xcc, 0xf9, 0x8d, 0xf7, 0x36, 0x76, 0xeb, 0x2b, 0x79, 0x62, 0x98, 0xac, 0x72, 0xe1, 0x27, 0xa5, 0x91], + key: [ + 0x16, 0xcb, 0x9f, 0x01, 0xe5, 0x4b, 0x05, 0x33, 0x43, 0x99, 0x37, 0xdd, 0x09, 0xae, 0xa4, 0xcc, 0xf9, 0x8d, + 0xf7, 0x36, 0x76, 0xeb, 0x2b, 0x79, 0x62, 0x98, 0xac, 0x72, 0xe1, 0x27, 0xa5, 0x91, + ], len: 115865, - sha: [0x70, 0x7a, 0xd0, 0xce, 0x70, 0xa3, 0x2b, 0x33, 0x34, 0x8b, 0x26, 0x48, 0xfd, 0xfe, 0x44, 0xaa, 0xe0, 0xd1, 0xfa, 0x1c, 0x43, 0x0a, 0x97, 0xe7, 0x39, 0x64, 0x2e, 0x4b, 0xc3, 0x38, 0x1e, 0x62], + sha: [ + 0x70, 0x7a, 0xd0, 0xce, 0x70, 0xa3, 0x2b, 0x33, 0x34, 0x8b, 0x26, 0x48, 0xfd, 0xfe, 0x44, 0xaa, 0xe0, 0xd1, + 0xfa, 0x1c, 0x43, 0x0a, 0x97, 0xe7, 0x39, 0x64, 0x2e, 0x4b, 0xc3, 0x38, 0x1e, 0x62, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_checks.ptx"), "\0").as_bytes(), }, Companion { name: "iq4_nl_q8_1.ptx", - key: [0x18, 0x9b, 0x02, 0xce, 0xe8, 0x18, 0x63, 0x79, 0xfb, 0x7b, 0x0b, 0xd0, 0x7a, 0x83, 0x1e, 0x1f, 0xb2, 0x76, 0x4d, 0x29, 0xa9, 0x8a, 0x17, 0xfd, 0x2b, 0x51, 0x6c, 0x54, 0x59, 0xf9, 0xd4, 0xce], + key: [ + 0x18, 0x9b, 0x02, 0xce, 0xe8, 0x18, 0x63, 0x79, 0xfb, 0x7b, 0x0b, 0xd0, 0x7a, 0x83, 0x1e, 0x1f, 0xb2, 0x76, + 0x4d, 0x29, 0xa9, 0x8a, 0x17, 0xfd, 0x2b, 0x51, 0x6c, 0x54, 0x59, 0xf9, 0xd4, 0xce, + ], len: 38554, - sha: [0xeb, 0x57, 0xbb, 0xff, 0x87, 0x55, 0x63, 0x75, 0xe2, 0xf9, 0x84, 0x95, 0x5b, 0x7d, 0x28, 0x9d, 0xf1, 0xfc, 0xab, 0xf8, 0xca, 0x20, 0x84, 0x88, 0xfa, 0x73, 0xbb, 0x3d, 0xc2, 0xe8, 0x11, 0x76], + sha: [ + 0xeb, 0x57, 0xbb, 0xff, 0x87, 0x55, 0x63, 0x75, 0xe2, 0xf9, 0x84, 0x95, 0x5b, 0x7d, 0x28, 0x9d, 0xf1, 0xfc, + 0xab, 0xf8, 0xca, 0x20, 0x84, 0x88, 0xfa, 0x73, 0xbb, 0x3d, 0xc2, 0xe8, 0x11, 0x76, + ], ptx: concat!(include_str!("../ptx-sm86/iq4_nl_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_cvec.ptx", - key: [0x19, 0x3a, 0xdd, 0x5c, 0xb4, 0x48, 0xf5, 0xe1, 0x93, 0xf2, 0x0f, 0xf2, 0x48, 0xca, 0x44, 0x59, 0xab, 0xb9, 0x62, 0xb4, 0x72, 0x66, 0x3c, 0x00, 0xd1, 0x89, 0x41, 0x31, 0x3b, 0xfa, 0x3e, 0xbc], + key: [ + 0x19, 0x3a, 0xdd, 0x5c, 0xb4, 0x48, 0xf5, 0xe1, 0x93, 0xf2, 0x0f, 0xf2, 0x48, 0xca, 0x44, 0x59, 0xab, 0xb9, + 0x62, 0xb4, 0x72, 0x66, 0x3c, 0x00, 0xd1, 0x89, 0x41, 0x31, 0x3b, 0xfa, 0x3e, 0xbc, + ], len: 28943, - sha: [0x09, 0x43, 0xc5, 0xc0, 0x4e, 0xf8, 0x63, 0x4b, 0x8e, 0xb6, 0x11, 0x33, 0x32, 0x9a, 0xd7, 0x30, 0xf6, 0xbc, 0x39, 0xdc, 0x4e, 0x55, 0xce, 0x9a, 0xc6, 0x25, 0x87, 0x1f, 0xa1, 0x62, 0x58, 0x78], + sha: [ + 0x09, 0x43, 0xc5, 0xc0, 0x4e, 0xf8, 0x63, 0x4b, 0x8e, 0xb6, 0x11, 0x33, 0x32, 0x9a, 0xd7, 0x30, 0xf6, 0xbc, + 0x39, 0xdc, 0x4e, 0x55, 0xce, 0x9a, 0xc6, 0x25, 0x87, 0x1f, 0xa1, 0x62, 0x58, 0x78, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_cvec.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_keyless.ptx", - key: [0x1a, 0xb8, 0xb8, 0x15, 0x6e, 0x8c, 0x82, 0x41, 0x31, 0xc0, 0x0c, 0xec, 0xda, 0x17, 0x7f, 0xe5, 0x7d, 0x74, 0xb2, 0x86, 0xa0, 0x2b, 0x7e, 0x5a, 0xfd, 0xfa, 0x39, 0xac, 0xad, 0xaa, 0x33, 0xe6], + key: [ + 0x1a, 0xb8, 0xb8, 0x15, 0x6e, 0x8c, 0x82, 0x41, 0x31, 0xc0, 0x0c, 0xec, 0xda, 0x17, 0x7f, 0xe5, 0x7d, 0x74, + 0xb2, 0x86, 0xa0, 0x2b, 0x7e, 0x5a, 0xfd, 0xfa, 0x39, 0xac, 0xad, 0xaa, 0x33, 0xe6, + ], len: 3760, - sha: [0x0a, 0x16, 0xc1, 0x19, 0x5e, 0x25, 0x74, 0x7c, 0xb0, 0x7b, 0x18, 0x34, 0xf7, 0xc4, 0x52, 0xb8, 0x91, 0x0c, 0x27, 0xac, 0x2b, 0x7d, 0x30, 0xb9, 0xf6, 0x68, 0x7d, 0x28, 0xcc, 0x76, 0xb8, 0xb9], + sha: [ + 0x0a, 0x16, 0xc1, 0x19, 0x5e, 0x25, 0x74, 0x7c, 0xb0, 0x7b, 0x18, 0x34, 0xf7, 0xc4, 0x52, 0xb8, 0x91, 0x0c, + 0x27, 0xac, 0x2b, 0x7d, 0x30, 0xb9, 0xf6, 0x68, 0x7d, 0x28, 0xcc, 0x76, 0xb8, 0xb9, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_keyless.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_attention.ptx", - key: [0x1c, 0x89, 0xe6, 0xcb, 0xc8, 0xbb, 0x52, 0xb4, 0x64, 0x96, 0xa1, 0xca, 0xe3, 0x14, 0x3a, 0x8a, 0xd6, 0xcb, 0x8e, 0x8d, 0xb7, 0x0f, 0x4e, 0x6d, 0x5a, 0x87, 0x4d, 0x59, 0xfd, 0xdd, 0x4a, 0x07], + key: [ + 0x1c, 0x89, 0xe6, 0xcb, 0xc8, 0xbb, 0x52, 0xb4, 0x64, 0x96, 0xa1, 0xca, 0xe3, 0x14, 0x3a, 0x8a, 0xd6, 0xcb, + 0x8e, 0x8d, 0xb7, 0x0f, 0x4e, 0x6d, 0x5a, 0x87, 0x4d, 0x59, 0xfd, 0xdd, 0x4a, 0x07, + ], len: 96184, - sha: [0xf3, 0x2c, 0x26, 0xe3, 0xdf, 0x42, 0xa4, 0xa2, 0xda, 0x00, 0xf2, 0xa9, 0x79, 0x1e, 0x1a, 0xb8, 0x98, 0x41, 0x61, 0xe8, 0x9e, 0x20, 0x3e, 0xdf, 0x88, 0x0a, 0xdc, 0xc8, 0x30, 0xe2, 0x43, 0x5c], + sha: [ + 0xf3, 0x2c, 0x26, 0xe3, 0xdf, 0x42, 0xa4, 0xa2, 0xda, 0x00, 0xf2, 0xa9, 0x79, 0x1e, 0x1a, 0xb8, 0x98, 0x41, + 0x61, 0xe8, 0x9e, 0x20, 0x3e, 0xdf, 0x88, 0x0a, 0xdc, 0xc8, 0x30, 0xe2, 0x43, 0x5c, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_attention.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_select.ptx", - key: [0x1e, 0x35, 0x51, 0x47, 0x44, 0x21, 0x62, 0x29, 0xb0, 0xcf, 0xfb, 0x4f, 0x45, 0xd2, 0xf1, 0x3f, 0x25, 0xcb, 0x95, 0xf3, 0x77, 0xa3, 0x0c, 0x1c, 0x01, 0x25, 0x43, 0xdb, 0xf5, 0x3a, 0x1c, 0x2d], + key: [ + 0x1e, 0x35, 0x51, 0x47, 0x44, 0x21, 0x62, 0x29, 0xb0, 0xcf, 0xfb, 0x4f, 0x45, 0xd2, 0xf1, 0x3f, 0x25, 0xcb, + 0x95, 0xf3, 0x77, 0xa3, 0x0c, 0x1c, 0x01, 0x25, 0x43, 0xdb, 0xf5, 0x3a, 0x1c, 0x2d, + ], len: 97179, - sha: [0x38, 0xef, 0x04, 0x0e, 0xff, 0x7b, 0x93, 0xe2, 0xaf, 0x2c, 0x15, 0x3f, 0xb1, 0xd9, 0x35, 0x24, 0xbd, 0xf1, 0x65, 0x42, 0x8a, 0xa2, 0xf8, 0xcf, 0xbd, 0xa5, 0x08, 0x3e, 0xc4, 0x07, 0x1d, 0xf3], + sha: [ + 0x38, 0xef, 0x04, 0x0e, 0xff, 0x7b, 0x93, 0xe2, 0xaf, 0x2c, 0x15, 0x3f, 0xb1, 0xd9, 0x35, 0x24, 0xbd, 0xf1, + 0x65, 0x42, 0x8a, 0xa2, 0xf8, 0xcf, 0xbd, 0xa5, 0x08, 0x3e, 0xc4, 0x07, 0x1d, 0xf3, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_select.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq2_s.ptx", - key: [0x1e, 0x5c, 0x05, 0x7c, 0xfb, 0x36, 0xd3, 0x51, 0xcc, 0xb2, 0xba, 0x54, 0x6c, 0xf2, 0x95, 0xd1, 0x3b, 0xfa, 0x00, 0x30, 0x65, 0xeb, 0x9b, 0x41, 0x5b, 0xf0, 0xc0, 0x11, 0x8b, 0xd4, 0x80, 0x4a], + key: [ + 0x1e, 0x5c, 0x05, 0x7c, 0xfb, 0x36, 0xd3, 0x51, 0xcc, 0xb2, 0xba, 0x54, 0x6c, 0xf2, 0x95, 0xd1, 0x3b, 0xfa, + 0x00, 0x30, 0x65, 0xeb, 0x9b, 0x41, 0x5b, 0xf0, 0xc0, 0x11, 0x8b, 0xd4, 0x80, 0x4a, + ], len: 42048, - sha: [0xe8, 0xcb, 0x46, 0x20, 0xf1, 0xe2, 0xcf, 0x38, 0xd5, 0x6b, 0x87, 0x55, 0x33, 0xc3, 0x9e, 0x27, 0x95, 0x94, 0x86, 0x2f, 0x77, 0x9e, 0x73, 0x1e, 0x50, 0x1d, 0xed, 0x50, 0xb2, 0xf8, 0xf5, 0x92], + sha: [ + 0xe8, 0xcb, 0x46, 0x20, 0xf1, 0xe2, 0xcf, 0x38, 0xd5, 0x6b, 0x87, 0x55, 0x33, 0xc3, 0x9e, 0x27, 0x95, 0x94, + 0x86, 0x2f, 0x77, 0x9e, 0x73, 0x1e, 0x50, 0x1d, 0xed, 0x50, 0xb2, 0xf8, 0xf5, 0x92, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq2_s.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_qsa_gate.ptx", - key: [0x21, 0xf1, 0xa0, 0x14, 0xbf, 0xa0, 0x59, 0x74, 0x3a, 0x7c, 0x9d, 0x55, 0x3a, 0x46, 0x15, 0xf5, 0x48, 0x82, 0x0b, 0xb4, 0xe7, 0xc4, 0x8f, 0x4e, 0xf1, 0xd7, 0x1f, 0x05, 0x07, 0x7b, 0x4b, 0x25], + key: [ + 0x21, 0xf1, 0xa0, 0x14, 0xbf, 0xa0, 0x59, 0x74, 0x3a, 0x7c, 0x9d, 0x55, 0x3a, 0x46, 0x15, 0xf5, 0x48, 0x82, + 0x0b, 0xb4, 0xe7, 0xc4, 0x8f, 0x4e, 0xf1, 0xd7, 0x1f, 0x05, 0x07, 0x7b, 0x4b, 0x25, + ], len: 26053, - sha: [0xb4, 0x22, 0x8c, 0x01, 0x5b, 0xb0, 0xb0, 0x62, 0x6d, 0x31, 0x40, 0x62, 0x77, 0x20, 0x94, 0x39, 0x0a, 0xd3, 0xba, 0xa6, 0x86, 0x64, 0xd7, 0x29, 0x9b, 0x2a, 0x17, 0x11, 0x80, 0xa4, 0x7c, 0x64], + sha: [ + 0xb4, 0x22, 0x8c, 0x01, 0x5b, 0xb0, 0xb0, 0x62, 0x6d, 0x31, 0x40, 0x62, 0x77, 0x20, 0x94, 0x39, 0x0a, 0xd3, + 0xba, 0xa6, 0x86, 0x64, 0xd7, 0x29, 0x9b, 0x2a, 0x17, 0x11, 0x80, 0xa4, 0x7c, 0x64, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_qsa_gate.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_combine.ptx", - key: [0x22, 0x53, 0xfe, 0x2d, 0x64, 0x13, 0x50, 0xf4, 0x44, 0x5a, 0x0a, 0x69, 0xc4, 0xa0, 0xfc, 0x22, 0xb8, 0x5c, 0x2f, 0xff, 0xca, 0x7c, 0xbd, 0x53, 0x6f, 0xfe, 0x5d, 0x29, 0x12, 0xf8, 0x1f, 0xb7], + key: [ + 0x22, 0x53, 0xfe, 0x2d, 0x64, 0x13, 0x50, 0xf4, 0x44, 0x5a, 0x0a, 0x69, 0xc4, 0xa0, 0xfc, 0x22, 0xb8, 0x5c, + 0x2f, 0xff, 0xca, 0x7c, 0xbd, 0x53, 0x6f, 0xfe, 0x5d, 0x29, 0x12, 0xf8, 0x1f, 0xb7, + ], len: 12958, - sha: [0x6e, 0x0f, 0xba, 0x41, 0xea, 0x8b, 0x0f, 0xe6, 0x0b, 0x1f, 0xc5, 0x1e, 0xb3, 0xe7, 0x0f, 0x5f, 0xc9, 0xb3, 0x51, 0x63, 0xce, 0xff, 0x1d, 0xb4, 0x36, 0xd6, 0x2e, 0xf6, 0x7e, 0x9a, 0xbd, 0xfe], + sha: [ + 0x6e, 0x0f, 0xba, 0x41, 0xea, 0x8b, 0x0f, 0xe6, 0x0b, 0x1f, 0xc5, 0x1e, 0xb3, 0xe7, 0x0f, 0x5f, 0xc9, 0xb3, + 0x51, 0x63, 0xce, 0xff, 0x1d, 0xb4, 0x36, 0xd6, 0x2e, 0xf6, 0x7e, 0x9a, 0xbd, 0xfe, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_combine.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_scalar_gr.ptx", - key: [0x24, 0x01, 0x60, 0x6b, 0x7e, 0xb4, 0x4a, 0xf8, 0x2a, 0x8b, 0x57, 0x48, 0x48, 0x6c, 0x72, 0xae, 0xc9, 0xc4, 0x7a, 0x4c, 0x7d, 0xb0, 0x6e, 0x5a, 0xbf, 0xd3, 0x7d, 0xb3, 0x75, 0x64, 0x88, 0x6d], + key: [ + 0x24, 0x01, 0x60, 0x6b, 0x7e, 0xb4, 0x4a, 0xf8, 0x2a, 0x8b, 0x57, 0x48, 0x48, 0x6c, 0x72, 0xae, 0xc9, 0xc4, + 0x7a, 0x4c, 0x7d, 0xb0, 0x6e, 0x5a, 0xbf, 0xd3, 0x7d, 0xb3, 0x75, 0x64, 0x88, 0x6d, + ], len: 387485, - sha: [0x89, 0xf9, 0xe9, 0x1d, 0xc7, 0xe3, 0x28, 0xa6, 0x7a, 0xd8, 0x7e, 0x02, 0xde, 0xae, 0x1c, 0x7a, 0x25, 0x56, 0xe7, 0x4d, 0x05, 0x98, 0x40, 0xd8, 0xe0, 0x94, 0x2d, 0x8e, 0x85, 0xe2, 0xe5, 0xcb], + sha: [ + 0x89, 0xf9, 0xe9, 0x1d, 0xc7, 0xe3, 0x28, 0xa6, 0x7a, 0xd8, 0x7e, 0x02, 0xde, 0xae, 0x1c, 0x7a, 0x25, 0x56, + 0xe7, 0x4d, 0x05, 0x98, 0x40, 0xd8, 0xe0, 0x94, 0x2d, 0x8e, 0x85, 0xe2, 0xe5, 0xcb, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_scalar_gr.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify_window_moe_experts.ptx", - key: [0x24, 0xd2, 0x8c, 0xcd, 0x9c, 0x3a, 0x5b, 0xbe, 0xdb, 0xeb, 0x93, 0x3b, 0x4f, 0xeb, 0x37, 0x6f, 0x84, 0x0a, 0x74, 0xe2, 0x1a, 0x44, 0x82, 0x17, 0x48, 0x8c, 0x06, 0xee, 0x23, 0x82, 0x11, 0x57], + key: [ + 0x24, 0xd2, 0x8c, 0xcd, 0x9c, 0x3a, 0x5b, 0xbe, 0xdb, 0xeb, 0x93, 0x3b, 0x4f, 0xeb, 0x37, 0x6f, 0x84, 0x0a, + 0x74, 0xe2, 0x1a, 0x44, 0x82, 0x17, 0x48, 0x8c, 0x06, 0xee, 0x23, 0x82, 0x11, 0x57, + ], len: 991906, - sha: [0xf6, 0xbe, 0xc9, 0xbb, 0x67, 0xe4, 0x5a, 0xa8, 0x40, 0x4f, 0xaa, 0xfd, 0x44, 0xdc, 0x30, 0xb7, 0x90, 0xbf, 0x29, 0x08, 0xf4, 0x5f, 0x0c, 0x7b, 0xb0, 0xef, 0x86, 0xa0, 0x4e, 0xad, 0x97, 0x23], + sha: [ + 0xf6, 0xbe, 0xc9, 0xbb, 0x67, 0xe4, 0x5a, 0xa8, 0x40, 0x4f, 0xaa, 0xfd, 0x44, 0xdc, 0x30, 0xb7, 0x90, 0xbf, + 0x29, 0x08, 0xf4, 0x5f, 0x0c, 0x7b, 0xb0, 0xef, 0x86, 0xa0, 0x4e, 0xad, 0x97, 0x23, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify_window_moe_experts.ptx"), "\0").as_bytes(), }, Companion { name: "q4_k_q8_1.ptx", - key: [0x29, 0x4f, 0x3a, 0xd5, 0xfd, 0xdd, 0xf7, 0x96, 0x94, 0x13, 0x46, 0xc9, 0x14, 0x4f, 0xc4, 0x9d, 0x4c, 0xff, 0x54, 0x78, 0xa8, 0x8d, 0xaa, 0xd6, 0xb8, 0x94, 0x1f, 0xbd, 0x4b, 0xb2, 0x40, 0xcb], + key: [ + 0x29, 0x4f, 0x3a, 0xd5, 0xfd, 0xdd, 0xf7, 0x96, 0x94, 0x13, 0x46, 0xc9, 0x14, 0x4f, 0xc4, 0x9d, 0x4c, 0xff, + 0x54, 0x78, 0xa8, 0x8d, 0xaa, 0xd6, 0xb8, 0x94, 0x1f, 0xbd, 0x4b, 0xb2, 0x40, 0xcb, + ], len: 28282, - sha: [0x7c, 0xb5, 0xfa, 0x63, 0x73, 0x59, 0x81, 0x41, 0x7d, 0x57, 0x45, 0x76, 0xcf, 0xd8, 0x7e, 0x86, 0x43, 0xcf, 0xea, 0xd8, 0x1b, 0x84, 0x75, 0x44, 0xf9, 0xf1, 0x4c, 0x09, 0x70, 0x2b, 0x3b, 0x60], + sha: [ + 0x7c, 0xb5, 0xfa, 0x63, 0x73, 0x59, 0x81, 0x41, 0x7d, 0x57, 0x45, 0x76, 0xcf, 0xd8, 0x7e, 0x86, 0x43, 0xcf, + 0xea, 0xd8, 0x1b, 0x84, 0x75, 0x44, 0xf9, 0xf1, 0x4c, 0x09, 0x70, 0x2b, 0x3b, 0x60, + ], ptx: concat!(include_str!("../ptx-sm86/q4_k_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-original-formats.ptx", - key: [0x29, 0xd9, 0x2d, 0xea, 0x14, 0x09, 0x95, 0x86, 0xc5, 0x7c, 0x97, 0x0a, 0x36, 0x46, 0xa7, 0x8e, 0x63, 0x1a, 0x49, 0x9a, 0x71, 0x57, 0xd5, 0x6a, 0xa0, 0xe2, 0x0a, 0xc1, 0xe0, 0xb4, 0x01, 0x36], + key: [ + 0x29, 0xd9, 0x2d, 0xea, 0x14, 0x09, 0x95, 0x86, 0xc5, 0x7c, 0x97, 0x0a, 0x36, 0x46, 0xa7, 0x8e, 0x63, 0x1a, + 0x49, 0x9a, 0x71, 0x57, 0xd5, 0x6a, 0xa0, 0xe2, 0x0a, 0xc1, 0xe0, 0xb4, 0x01, 0x36, + ], len: 2072448, - sha: [0xe0, 0x6d, 0xad, 0xbb, 0x57, 0xa9, 0xf0, 0xdc, 0x0b, 0x20, 0xd8, 0xb4, 0x7f, 0xdd, 0x62, 0xa4, 0xc8, 0x46, 0x75, 0xcc, 0xd4, 0x17, 0x0d, 0x42, 0x48, 0x95, 0x6c, 0x09, 0xb4, 0xfb, 0xd2, 0x1e], + sha: [ + 0xe0, 0x6d, 0xad, 0xbb, 0x57, 0xa9, 0xf0, 0xdc, 0x0b, 0x20, 0xd8, 0xb4, 0x7f, 0xdd, 0x62, 0xa4, 0xc8, 0x46, + 0x75, 0xcc, 0xd4, 0x17, 0x0d, 0x42, 0x48, 0x95, 0x6c, 0x09, 0xb4, 0xfb, 0xd2, 0x1e, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-original-formats.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_prefill_fixup.ptx", - key: [0x29, 0xfd, 0x3f, 0x75, 0x98, 0x64, 0x39, 0x75, 0x7c, 0x3a, 0x6e, 0xb1, 0x7d, 0x93, 0xe3, 0xed, 0x12, 0x4c, 0xc4, 0x18, 0x51, 0x97, 0xa2, 0xb4, 0x45, 0x84, 0x10, 0xd1, 0xe7, 0xf7, 0xec, 0x4b], + key: [ + 0x29, 0xfd, 0x3f, 0x75, 0x98, 0x64, 0x39, 0x75, 0x7c, 0x3a, 0x6e, 0xb1, 0x7d, 0x93, 0xe3, 0xed, 0x12, 0x4c, + 0xc4, 0x18, 0x51, 0x97, 0xa2, 0xb4, 0x45, 0x84, 0x10, 0xd1, 0xe7, 0xf7, 0xec, 0x4b, + ], len: 325813, - sha: [0x43, 0xa2, 0xa5, 0x24, 0x43, 0xcf, 0x7a, 0x2e, 0x2e, 0xe6, 0x58, 0xf5, 0x93, 0xb0, 0xfe, 0xb3, 0x93, 0x3d, 0xb7, 0x37, 0x93, 0x69, 0xef, 0x19, 0x15, 0xfe, 0x23, 0x99, 0x6a, 0xca, 0xda, 0x84], + sha: [ + 0x43, 0xa2, 0xa5, 0x24, 0x43, 0xcf, 0x7a, 0x2e, 0x2e, 0xe6, 0x58, 0xf5, 0x93, 0xb0, 0xfe, 0xb3, 0x93, 0x3d, + 0xb7, 0x37, 0x93, 0x69, 0xef, 0x19, 0x15, 0xfe, 0x23, 0x99, 0x6a, 0xca, 0xda, 0x84, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_prefill_fixup.ptx"), "\0").as_bytes(), }, Companion { name: "iq4_xs_q8_1.ptx", - key: [0x2c, 0x85, 0x3b, 0xad, 0xe2, 0xbb, 0x62, 0xb6, 0x71, 0x67, 0xb7, 0xcb, 0xe0, 0x03, 0x24, 0x61, 0x6c, 0x72, 0x87, 0xc6, 0x0a, 0xb5, 0xfb, 0x8a, 0x41, 0xd2, 0xb5, 0x69, 0x01, 0x97, 0xf1, 0xb4], + key: [ + 0x2c, 0x85, 0x3b, 0xad, 0xe2, 0xbb, 0x62, 0xb6, 0x71, 0x67, 0xb7, 0xcb, 0xe0, 0x03, 0x24, 0x61, 0x6c, 0x72, + 0x87, 0xc6, 0x0a, 0xb5, 0xfb, 0x8a, 0x41, 0xd2, 0xb5, 0x69, 0x01, 0x97, 0xf1, 0xb4, + ], len: 62854, - sha: [0x49, 0xbf, 0x1b, 0x11, 0x6a, 0xd9, 0xa8, 0x42, 0x7d, 0x7b, 0x64, 0x01, 0xae, 0x41, 0x4a, 0x2b, 0xd7, 0x81, 0x3c, 0x74, 0x4d, 0x96, 0x8a, 0x99, 0x26, 0xb9, 0xcc, 0x4a, 0x22, 0x3e, 0x96, 0xd6], + sha: [ + 0x49, 0xbf, 0x1b, 0x11, 0x6a, 0xd9, 0xa8, 0x42, 0x7d, 0x7b, 0x64, 0x01, 0xae, 0x41, 0x4a, 0x2b, 0xd7, 0x81, + 0x3c, 0x74, 0x4d, 0x96, 0x8a, 0x99, 0x26, 0xb9, 0xcc, 0x4a, 0x22, 0x3e, 0x96, 0xd6, + ], ptx: concat!(include_str!("../ptx-sm86/iq4_xs_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-fixup-selected.ptx", - key: [0x32, 0xa0, 0xc8, 0xc5, 0x45, 0x8b, 0xce, 0x5f, 0x2e, 0x07, 0xc7, 0x95, 0x7e, 0x39, 0xaa, 0x97, 0xbe, 0xac, 0x8d, 0x79, 0xbf, 0xad, 0x4a, 0x95, 0x4c, 0x91, 0xdc, 0xe3, 0x97, 0xa4, 0x79, 0x71], + key: [ + 0x32, 0xa0, 0xc8, 0xc5, 0x45, 0x8b, 0xce, 0x5f, 0x2e, 0x07, 0xc7, 0x95, 0x7e, 0x39, 0xaa, 0x97, 0xbe, 0xac, + 0x8d, 0x79, 0xbf, 0xad, 0x4a, 0x95, 0x4c, 0x91, 0xdc, 0xe3, 0x97, 0xa4, 0x79, 0x71, + ], len: 183342, - sha: [0xbd, 0x2a, 0x21, 0xaa, 0x98, 0x59, 0xc3, 0x1d, 0x70, 0x97, 0x9d, 0x89, 0x7c, 0xe7, 0xb7, 0x9c, 0xd4, 0x48, 0x3c, 0xde, 0xd8, 0x0a, 0x3b, 0x11, 0xbc, 0x24, 0x24, 0xdc, 0x13, 0xbc, 0x67, 0x0c], + sha: [ + 0xbd, 0x2a, 0x21, 0xaa, 0x98, 0x59, 0xc3, 0x1d, 0x70, 0x97, 0x9d, 0x89, 0x7c, 0xe7, 0xb7, 0x9c, 0xd4, 0x48, + 0x3c, 0xde, 0xd8, 0x0a, 0x3b, 0x11, 0xbc, 0x24, 0x24, 0xdc, 0x13, 0xbc, 0x67, 0x0c, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-fixup-selected.ptx"), "\0").as_bytes(), }, Companion { name: "q8_0_q8_1.ptx", - key: [0x34, 0x1a, 0xbb, 0xd0, 0x11, 0x39, 0x19, 0xd5, 0x73, 0x24, 0x1b, 0x1d, 0xc4, 0x78, 0x86, 0x51, 0x4e, 0xa7, 0xaa, 0x1d, 0x4d, 0x3f, 0x1a, 0x86, 0x70, 0x24, 0xe7, 0x66, 0x4b, 0x50, 0x1a, 0x0a], + key: [ + 0x34, 0x1a, 0xbb, 0xd0, 0x11, 0x39, 0x19, 0xd5, 0x73, 0x24, 0x1b, 0x1d, 0xc4, 0x78, 0x86, 0x51, 0x4e, 0xa7, + 0xaa, 0x1d, 0x4d, 0x3f, 0x1a, 0x86, 0x70, 0x24, 0xe7, 0x66, 0x4b, 0x50, 0x1a, 0x0a, + ], len: 21418, - sha: [0x5b, 0x7e, 0x7d, 0x2c, 0xd3, 0x17, 0xfd, 0x3b, 0x1a, 0x5b, 0xea, 0x40, 0x01, 0x32, 0xf0, 0x38, 0x6b, 0x06, 0x9c, 0xa7, 0xdb, 0x60, 0x97, 0x45, 0x93, 0xe9, 0x02, 0x27, 0x66, 0xb3, 0x95, 0xb2], + sha: [ + 0x5b, 0x7e, 0x7d, 0x2c, 0xd3, 0x17, 0xfd, 0x3b, 0x1a, 0x5b, 0xea, 0x40, 0x01, 0x32, 0xf0, 0x38, 0x6b, 0x06, + 0x9c, 0xa7, 0xdb, 0x60, 0x97, 0x45, 0x93, 0xe9, 0x02, 0x27, 0x66, 0xb3, 0x95, 0xb2, + ], ptx: concat!(include_str!("../ptx-sm86/q8_0_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "gr_prompt_device.ptx", - key: [0x39, 0xc4, 0xea, 0xcc, 0x21, 0x1f, 0xa4, 0x5f, 0xe3, 0x68, 0xee, 0x50, 0x2d, 0x3d, 0x3f, 0xf2, 0x12, 0x41, 0xe6, 0xfe, 0x24, 0xd5, 0xd1, 0x21, 0x1c, 0x6e, 0x18, 0xef, 0x0d, 0x37, 0x28, 0x70], + key: [ + 0x39, 0xc4, 0xea, 0xcc, 0x21, 0x1f, 0xa4, 0x5f, 0xe3, 0x68, 0xee, 0x50, 0x2d, 0x3d, 0x3f, 0xf2, 0x12, 0x41, + 0xe6, 0xfe, 0x24, 0xd5, 0xd1, 0x21, 0x1c, 0x6e, 0x18, 0xef, 0x0d, 0x37, 0x28, 0x70, + ], len: 46298, - sha: [0x1c, 0xcf, 0xf9, 0xa5, 0xce, 0x9f, 0x1a, 0xb7, 0x9c, 0xf8, 0xf5, 0xc8, 0x1d, 0xfd, 0x2a, 0x77, 0x5a, 0xd8, 0x38, 0x11, 0x5c, 0x09, 0x41, 0x4e, 0x0e, 0x1c, 0xdb, 0x3f, 0x34, 0x7f, 0x35, 0x6b], + sha: [ + 0x1c, 0xcf, 0xf9, 0xa5, 0xce, 0x9f, 0x1a, 0xb7, 0x9c, 0xf8, 0xf5, 0xc8, 0x1d, 0xfd, 0x2a, 0x77, 0x5a, 0xd8, + 0x38, 0x11, 0x5c, 0x09, 0x41, 0x4e, 0x0e, 0x1c, 0xdb, 0x3f, 0x34, 0x7f, 0x35, 0x6b, + ], ptx: concat!(include_str!("../ptx-sm86/gr_prompt_device.ptx"), "\0").as_bytes(), }, Companion { name: "s_gemv_legacy.ptx", - key: [0x3a, 0xb4, 0xd1, 0x2a, 0x5e, 0x97, 0xc4, 0xe2, 0xf4, 0x60, 0x2c, 0x6c, 0x87, 0x23, 0x72, 0xc5, 0xc0, 0x68, 0x5d, 0x8c, 0xf1, 0xa2, 0x02, 0x60, 0xaf, 0x6e, 0x0f, 0x52, 0x05, 0xac, 0x76, 0xd5], + key: [ + 0x3a, 0xb4, 0xd1, 0x2a, 0x5e, 0x97, 0xc4, 0xe2, 0xf4, 0x60, 0x2c, 0x6c, 0x87, 0x23, 0x72, 0xc5, 0xc0, 0x68, + 0x5d, 0x8c, 0xf1, 0xa2, 0x02, 0x60, 0xaf, 0x6e, 0x0f, 0x52, 0x05, 0xac, 0x76, 0xd5, + ], len: 303521, - sha: [0x97, 0x47, 0xc1, 0xbe, 0x0d, 0xb5, 0x20, 0x66, 0xf1, 0xef, 0xe8, 0xef, 0xa9, 0xad, 0xdf, 0x14, 0x23, 0xc5, 0xfd, 0x12, 0xe3, 0x17, 0x47, 0x99, 0xdf, 0x85, 0x3b, 0x0f, 0x71, 0x55, 0x76, 0x55], + sha: [ + 0x97, 0x47, 0xc1, 0xbe, 0x0d, 0xb5, 0x20, 0x66, 0xf1, 0xef, 0xe8, 0xef, 0xa9, 0xad, 0xdf, 0x14, 0x23, 0xc5, + 0xfd, 0x12, 0xe3, 0x17, 0x47, 0x99, 0xdf, 0x85, 0x3b, 0x0f, 0x71, 0x55, 0x76, 0x55, + ], ptx: concat!(include_str!("../ptx-sm86/s_gemv_legacy.ptx"), "\0").as_bytes(), }, Companion { name: "iq3_native_integer_mma.ptx", - key: [0x3b, 0xfb, 0x20, 0xc5, 0x31, 0xd0, 0xd5, 0x74, 0xcd, 0xd0, 0x12, 0xda, 0x9f, 0xd0, 0xca, 0xe0, 0x63, 0xf6, 0x16, 0xd1, 0xa0, 0x70, 0xe0, 0x20, 0x17, 0x99, 0xab, 0x11, 0xd7, 0x36, 0x8e, 0x63], + key: [ + 0x3b, 0xfb, 0x20, 0xc5, 0x31, 0xd0, 0xd5, 0x74, 0xcd, 0xd0, 0x12, 0xda, 0x9f, 0xd0, 0xca, 0xe0, 0x63, 0xf6, + 0x16, 0xd1, 0xa0, 0x70, 0xe0, 0x20, 0x17, 0x99, 0xab, 0x11, 0xd7, 0x36, 0x8e, 0x63, + ], len: 17927, - sha: [0x71, 0x0e, 0xda, 0x43, 0xa5, 0x42, 0x8c, 0x1f, 0xbe, 0xcc, 0xc6, 0x76, 0x82, 0x08, 0x93, 0x98, 0x0e, 0xa3, 0xcf, 0x1d, 0xf1, 0x22, 0x47, 0x17, 0xea, 0x95, 0x19, 0xb2, 0xe1, 0x39, 0xe3, 0x76], + sha: [ + 0x71, 0x0e, 0xda, 0x43, 0xa5, 0x42, 0x8c, 0x1f, 0xbe, 0xcc, 0xc6, 0x76, 0x82, 0x08, 0x93, 0x98, 0x0e, 0xa3, + 0xcf, 0x1d, 0xf1, 0x22, 0x47, 0x17, 0xea, 0x95, 0x19, 0xb2, 0xe1, 0x39, 0xe3, 0x76, + ], ptx: concat!(include_str!("../ptx-sm86/iq3_native_integer_mma.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_original_prefill_misc.ptx", - key: [0x3e, 0x57, 0x32, 0x6d, 0x0d, 0xd6, 0xae, 0xc8, 0x14, 0x7e, 0x6c, 0xf8, 0x37, 0xce, 0xca, 0x9d, 0x77, 0x9b, 0xa0, 0x6e, 0xa6, 0x7b, 0xf4, 0x31, 0x1b, 0x3c, 0xe0, 0xba, 0xa6, 0xd0, 0x4d, 0x69], + key: [ + 0x3e, 0x57, 0x32, 0x6d, 0x0d, 0xd6, 0xae, 0xc8, 0x14, 0x7e, 0x6c, 0xf8, 0x37, 0xce, 0xca, 0x9d, 0x77, 0x9b, + 0xa0, 0x6e, 0xa6, 0x7b, 0xf4, 0x31, 0x1b, 0x3c, 0xe0, 0xba, 0xa6, 0xd0, 0x4d, 0x69, + ], len: 5267, - sha: [0x7f, 0xb7, 0x4e, 0x54, 0xb7, 0xaf, 0x58, 0xdd, 0x65, 0x0d, 0x17, 0xaa, 0xa4, 0x0c, 0xa2, 0x31, 0x57, 0xd7, 0xb9, 0x88, 0x6b, 0xba, 0xf7, 0x0f, 0x8b, 0x71, 0x09, 0xc5, 0xa7, 0xa9, 0x74, 0xf2], + sha: [ + 0x7f, 0xb7, 0x4e, 0x54, 0xb7, 0xaf, 0x58, 0xdd, 0x65, 0x0d, 0x17, 0xaa, 0xa4, 0x0c, 0xa2, 0x31, 0x57, 0xd7, + 0xb9, 0x88, 0x6b, 0xba, 0xf7, 0x0f, 0x8b, 0x71, 0x09, 0xc5, 0xa7, 0xa9, 0x74, 0xf2, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_original_prefill_misc.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_prefill_mmq.ptx", - key: [0x3e, 0x67, 0x46, 0x7d, 0x41, 0x2d, 0xbf, 0x18, 0x12, 0x00, 0xd3, 0xca, 0x10, 0xf2, 0xb6, 0x69, 0x95, 0xaf, 0xe3, 0x16, 0xcb, 0xe4, 0x02, 0x60, 0xde, 0xa2, 0x1d, 0x97, 0x31, 0x8b, 0x61, 0xe1], + key: [ + 0x3e, 0x67, 0x46, 0x7d, 0x41, 0x2d, 0xbf, 0x18, 0x12, 0x00, 0xd3, 0xca, 0x10, 0xf2, 0xb6, 0x69, 0x95, 0xaf, + 0xe3, 0x16, 0xcb, 0xe4, 0x02, 0x60, 0xde, 0xa2, 0x1d, 0x97, 0x31, 0x8b, 0x61, 0xe1, + ], len: 1850087, - sha: [0x2f, 0xde, 0xe9, 0xf3, 0xc3, 0x06, 0x7e, 0x27, 0x64, 0x30, 0xc6, 0xb6, 0x15, 0x45, 0xb1, 0xf8, 0x59, 0x22, 0x60, 0xd4, 0x62, 0x64, 0x98, 0x89, 0xa8, 0xc9, 0x3b, 0xaa, 0xdf, 0x46, 0x92, 0xaa], + sha: [ + 0x2f, 0xde, 0xe9, 0xf3, 0xc3, 0x06, 0x7e, 0x27, 0x64, 0x30, 0xc6, 0xb6, 0x15, 0x45, 0xb1, 0xf8, 0x59, 0x22, + 0x60, 0xd4, 0x62, 0x64, 0x98, 0x89, 0xa8, 0xc9, 0x3b, 0xaa, 0xdf, 0x46, 0x92, 0xaa, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_prefill_mmq.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_attention.ptx", - key: [0x3f, 0xb2, 0x35, 0xca, 0x40, 0x5d, 0x24, 0xc3, 0xb8, 0xd0, 0xec, 0x46, 0x61, 0x1d, 0x9d, 0x64, 0x01, 0x03, 0xb7, 0x1a, 0x65, 0x85, 0x99, 0x23, 0x19, 0x4f, 0x02, 0xf0, 0x6b, 0x48, 0x2f, 0x6c], + key: [ + 0x3f, 0xb2, 0x35, 0xca, 0x40, 0x5d, 0x24, 0xc3, 0xb8, 0xd0, 0xec, 0x46, 0x61, 0x1d, 0x9d, 0x64, 0x01, 0x03, + 0xb7, 0x1a, 0x65, 0x85, 0x99, 0x23, 0x19, 0x4f, 0x02, 0xf0, 0x6b, 0x48, 0x2f, 0x6c, + ], len: 54452, - sha: [0xdc, 0x1a, 0xcb, 0x71, 0x2c, 0x99, 0x3b, 0x09, 0xaa, 0x87, 0x86, 0x72, 0x13, 0xd5, 0x23, 0xd8, 0x6d, 0x34, 0x2c, 0x91, 0xe7, 0x33, 0xf2, 0xdb, 0x80, 0x49, 0x7b, 0x85, 0xdc, 0xdd, 0x0b, 0x41], + sha: [ + 0xdc, 0x1a, 0xcb, 0x71, 0x2c, 0x99, 0x3b, 0x09, 0xaa, 0x87, 0x86, 0x72, 0x13, 0xd5, 0x23, 0xd8, 0x6d, 0x34, + 0x2c, 0x91, 0xe7, 0x33, 0xf2, 0xdb, 0x80, 0x49, 0x7b, 0x85, 0xdc, 0xdd, 0x0b, 0x41, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_attention.ptx"), "\0").as_bytes(), }, Companion { name: "ple_prompt_device.ptx", - key: [0x41, 0x2e, 0xd1, 0xdc, 0xcd, 0x1f, 0xc6, 0x2c, 0x5c, 0xf6, 0xc7, 0x50, 0xad, 0x8d, 0x2f, 0x45, 0x20, 0x5f, 0x6d, 0x19, 0xfa, 0xfc, 0x00, 0x23, 0xd6, 0x4a, 0x33, 0xd3, 0x12, 0x95, 0x09, 0x34], + key: [ + 0x41, 0x2e, 0xd1, 0xdc, 0xcd, 0x1f, 0xc6, 0x2c, 0x5c, 0xf6, 0xc7, 0x50, 0xad, 0x8d, 0x2f, 0x45, 0x20, 0x5f, + 0x6d, 0x19, 0xfa, 0xfc, 0x00, 0x23, 0xd6, 0x4a, 0x33, 0xd3, 0x12, 0x95, 0x09, 0x34, + ], len: 19418, - sha: [0xdb, 0x53, 0x73, 0x24, 0x8a, 0x30, 0x34, 0xea, 0x29, 0xc1, 0xd3, 0x65, 0xae, 0x26, 0x78, 0x5e, 0x4c, 0x46, 0x6f, 0x3d, 0xdc, 0x9b, 0x26, 0x48, 0x43, 0xca, 0x58, 0xaf, 0x47, 0xc9, 0xc2, 0x03], + sha: [ + 0xdb, 0x53, 0x73, 0x24, 0x8a, 0x30, 0x34, 0xea, 0x29, 0xc1, 0xd3, 0x65, 0xae, 0x26, 0x78, 0x5e, 0x4c, 0x46, + 0x6f, 0x3d, 0xdc, 0x9b, 0x26, 0x48, 0x43, 0xca, 0x58, 0xaf, 0x47, 0xc9, 0xc2, 0x03, + ], ptx: concat!(include_str!("../ptx-sm86/ple_prompt_device.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_s2_full_fixed.ptx", - key: [0x43, 0x81, 0x4a, 0x9c, 0x17, 0x9a, 0xba, 0xba, 0x8f, 0xe0, 0xa8, 0x0b, 0x88, 0xa3, 0x15, 0xbc, 0x94, 0xc4, 0x38, 0xf3, 0x9b, 0x38, 0x42, 0xf4, 0xe4, 0x30, 0x1e, 0x96, 0xa0, 0x32, 0xf7, 0x8d], + key: [ + 0x43, 0x81, 0x4a, 0x9c, 0x17, 0x9a, 0xba, 0xba, 0x8f, 0xe0, 0xa8, 0x0b, 0x88, 0xa3, 0x15, 0xbc, 0x94, 0xc4, + 0x38, 0xf3, 0x9b, 0x38, 0x42, 0xf4, 0xe4, 0x30, 0x1e, 0x96, 0xa0, 0x32, 0xf7, 0x8d, + ], len: 142044, - sha: [0x48, 0x41, 0xdf, 0x97, 0x8e, 0x70, 0x2a, 0xd9, 0x1a, 0xdf, 0xd6, 0xb1, 0x7f, 0xd3, 0x1e, 0x53, 0xa4, 0x12, 0x04, 0xf8, 0x0c, 0xbc, 0xa0, 0xdf, 0x2b, 0x6f, 0xad, 0xef, 0xf3, 0x5a, 0x3b, 0x78], + sha: [ + 0x48, 0x41, 0xdf, 0x97, 0x8e, 0x70, 0x2a, 0xd9, 0x1a, 0xdf, 0xd6, 0xb1, 0x7f, 0xd3, 0x1e, 0x53, 0xa4, 0x12, + 0x04, 0xf8, 0x0c, 0xbc, 0xa0, 0xdf, 0x2b, 0x6f, 0xad, 0xef, 0xf3, 0x5a, 0x3b, 0x78, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_s2_full_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_kv_q8.ptx", - key: [0x43, 0xc3, 0x08, 0x96, 0x08, 0x30, 0x83, 0x3e, 0x29, 0x32, 0x99, 0x07, 0xe2, 0x7b, 0xe5, 0x20, 0x3e, 0xf3, 0xbc, 0x89, 0xcc, 0x7d, 0x0a, 0x91, 0x76, 0x27, 0x0d, 0xc1, 0x87, 0x32, 0xd6, 0x00], + key: [ + 0x43, 0xc3, 0x08, 0x96, 0x08, 0x30, 0x83, 0x3e, 0x29, 0x32, 0x99, 0x07, 0xe2, 0x7b, 0xe5, 0x20, 0x3e, 0xf3, + 0xbc, 0x89, 0xcc, 0x7d, 0x0a, 0x91, 0x76, 0x27, 0x0d, 0xc1, 0x87, 0x32, 0xd6, 0x00, + ], len: 32973, - sha: [0x4b, 0xe6, 0xeb, 0xa3, 0xae, 0x08, 0xf2, 0x12, 0xeb, 0x89, 0x60, 0x7c, 0xea, 0x56, 0x63, 0x8c, 0x10, 0xfa, 0x12, 0xee, 0x40, 0x98, 0x5b, 0xeb, 0xee, 0x99, 0x75, 0x44, 0xae, 0xd7, 0xad, 0xc7], + sha: [ + 0x4b, 0xe6, 0xeb, 0xa3, 0xae, 0x08, 0xf2, 0x12, 0xeb, 0x89, 0x60, 0x7c, 0xea, 0x56, 0x63, 0x8c, 0x10, 0xfa, + 0x12, 0xee, 0x40, 0x98, 0x5b, 0xeb, 0xee, 0x99, 0x75, 0x44, 0xae, 0xd7, 0xad, 0xc7, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_kv_q8.ptx"), "\0").as_bytes(), }, Companion { name: "q6_k_q8_1.ptx", - key: [0x45, 0x40, 0xf6, 0x7f, 0x72, 0xe3, 0xb3, 0x5b, 0xf2, 0x1c, 0xfb, 0xde, 0x0b, 0xfd, 0xf7, 0x85, 0x1e, 0xbe, 0x90, 0xe4, 0x15, 0x40, 0x5c, 0x0c, 0x16, 0x16, 0x6d, 0x09, 0x33, 0xd5, 0x47, 0x97], + key: [ + 0x45, 0x40, 0xf6, 0x7f, 0x72, 0xe3, 0xb3, 0x5b, 0xf2, 0x1c, 0xfb, 0xde, 0x0b, 0xfd, 0xf7, 0x85, 0x1e, 0xbe, + 0x90, 0xe4, 0x15, 0x40, 0x5c, 0x0c, 0x16, 0x16, 0x6d, 0x09, 0x33, 0xd5, 0x47, 0x97, + ], len: 26986, - sha: [0x56, 0xb6, 0x06, 0xf4, 0x0b, 0x9a, 0xdd, 0xb9, 0x14, 0xed, 0x01, 0x83, 0x5e, 0x77, 0x87, 0x44, 0x22, 0xca, 0x26, 0xc5, 0xff, 0x32, 0x09, 0x94, 0x3d, 0x1d, 0xe1, 0x22, 0xfc, 0x79, 0x69, 0x58], + sha: [ + 0x56, 0xb6, 0x06, 0xf4, 0x0b, 0x9a, 0xdd, 0xb9, 0x14, 0xed, 0x01, 0x83, 0x5e, 0x77, 0x87, 0x44, 0x22, 0xca, + 0x26, 0xc5, 0xff, 0x32, 0x09, 0x94, 0x3d, 0x1d, 0xe1, 0x22, 0xfc, 0x79, 0x69, 0x58, + ], ptx: concat!(include_str!("../ptx-sm86/q6_k_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "moe_route_top10.ptx", - key: [0x48, 0x04, 0xcc, 0xad, 0xee, 0x77, 0xaa, 0xbd, 0xa8, 0x80, 0xfb, 0xc0, 0xa5, 0xb3, 0x4f, 0x10, 0xe8, 0x58, 0x51, 0xc1, 0x69, 0xea, 0xa8, 0x96, 0xf3, 0x31, 0x4b, 0xed, 0x64, 0x78, 0xe2, 0x25], + key: [ + 0x48, 0x04, 0xcc, 0xad, 0xee, 0x77, 0xaa, 0xbd, 0xa8, 0x80, 0xfb, 0xc0, 0xa5, 0xb3, 0x4f, 0x10, 0xe8, 0x58, + 0x51, 0xc1, 0x69, 0xea, 0xa8, 0x96, 0xf3, 0x31, 0x4b, 0xed, 0x64, 0x78, 0xe2, 0x25, + ], len: 61900, - sha: [0xe3, 0x29, 0x7c, 0x8c, 0x54, 0x4c, 0xe8, 0x40, 0x15, 0xb5, 0xba, 0x73, 0x45, 0x57, 0xd5, 0x1e, 0xd7, 0x77, 0xed, 0x40, 0x46, 0xf7, 0x4f, 0x09, 0x33, 0x1b, 0x63, 0x56, 0x9e, 0x01, 0xb5, 0x83], + sha: [ + 0xe3, 0x29, 0x7c, 0x8c, 0x54, 0x4c, 0xe8, 0x40, 0x15, 0xb5, 0xba, 0x73, 0x45, 0x57, 0xd5, 0x1e, 0xd7, 0x77, + 0xed, 0x40, 0x46, 0xf7, 0x4f, 0x09, 0x33, 0x1b, 0x63, 0x56, 0x9e, 0x01, 0xb5, 0x83, + ], ptx: concat!(include_str!("../ptx-sm86/moe_route_top10.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_postops.ptx", - key: [0x48, 0x6a, 0x73, 0xb0, 0x6b, 0x3a, 0x34, 0xf2, 0x98, 0xf5, 0x7e, 0x92, 0xc2, 0x0c, 0xc8, 0x39, 0x4d, 0xc5, 0x9d, 0x7b, 0xd8, 0x4b, 0x5c, 0xcc, 0xf8, 0xda, 0x53, 0xaa, 0x50, 0x81, 0xac, 0x9f], + key: [ + 0x48, 0x6a, 0x73, 0xb0, 0x6b, 0x3a, 0x34, 0xf2, 0x98, 0xf5, 0x7e, 0x92, 0xc2, 0x0c, 0xc8, 0x39, 0x4d, 0xc5, + 0x9d, 0x7b, 0xd8, 0x4b, 0x5c, 0xcc, 0xf8, 0xda, 0x53, 0xaa, 0x50, 0x81, 0xac, 0x9f, + ], len: 21830, - sha: [0x34, 0x00, 0x50, 0x40, 0x42, 0xb6, 0x9f, 0x98, 0x8b, 0x9a, 0x13, 0x3c, 0x2a, 0xea, 0xf8, 0x67, 0x69, 0xc7, 0xf3, 0x99, 0xfa, 0xaf, 0x94, 0xc6, 0x38, 0x7e, 0xbc, 0x6b, 0x46, 0xd3, 0x5d, 0xa9], + sha: [ + 0x34, 0x00, 0x50, 0x40, 0x42, 0xb6, 0x9f, 0x98, 0x8b, 0x9a, 0x13, 0x3c, 0x2a, 0xea, 0xf8, 0x67, 0x69, 0xc7, + 0xf3, 0x99, 0xfa, 0xaf, 0x94, 0xc6, 0x38, 0x7e, 0xbc, 0x6b, 0x46, 0xd3, 0x5d, 0xa9, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_postops.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_selected_kv.ptx", - key: [0x4f, 0x2a, 0xd2, 0x04, 0x10, 0x9b, 0xdd, 0x97, 0x4a, 0x7c, 0x96, 0x5d, 0x08, 0xd9, 0x06, 0x4a, 0xf5, 0x27, 0x56, 0xb1, 0xf6, 0xfc, 0x15, 0x02, 0x7f, 0x47, 0x7d, 0xe2, 0xfd, 0x88, 0x3f, 0x92], + key: [ + 0x4f, 0x2a, 0xd2, 0x04, 0x10, 0x9b, 0xdd, 0x97, 0x4a, 0x7c, 0x96, 0x5d, 0x08, 0xd9, 0x06, 0x4a, 0xf5, 0x27, + 0x56, 0xb1, 0xf6, 0xfc, 0x15, 0x02, 0x7f, 0x47, 0x7d, 0xe2, 0xfd, 0x88, 0x3f, 0x92, + ], len: 3842, - sha: [0x74, 0x02, 0x25, 0x5f, 0xdb, 0xe1, 0x21, 0xe0, 0x36, 0xaf, 0x74, 0x20, 0x3d, 0xb6, 0x0f, 0x61, 0xd9, 0xe2, 0xe4, 0xe1, 0x08, 0xbf, 0xbe, 0xdf, 0x17, 0xc4, 0xc3, 0x9f, 0xc0, 0x4e, 0xbf, 0x62], + sha: [ + 0x74, 0x02, 0x25, 0x5f, 0xdb, 0xe1, 0x21, 0xe0, 0x36, 0xaf, 0x74, 0x20, 0x3d, 0xb6, 0x0f, 0x61, 0xd9, 0xe2, + 0xe4, 0xe1, 0x08, 0xbf, 0xbe, 0xdf, 0x17, 0xc4, 0xc3, 0x9f, 0xc0, 0x4e, 0xbf, 0x62, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_selected_kv.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_kv_stream.ptx", - key: [0x4f, 0x71, 0xe7, 0x20, 0xe0, 0xca, 0x95, 0x0d, 0x32, 0x1b, 0xa3, 0xcb, 0xb2, 0x00, 0x82, 0xca, 0x47, 0x3e, 0x98, 0x39, 0xb7, 0x6d, 0x08, 0x89, 0x8e, 0x95, 0xb6, 0x62, 0x3b, 0xff, 0xfe, 0x50], + key: [ + 0x4f, 0x71, 0xe7, 0x20, 0xe0, 0xca, 0x95, 0x0d, 0x32, 0x1b, 0xa3, 0xcb, 0xb2, 0x00, 0x82, 0xca, 0x47, 0x3e, + 0x98, 0x39, 0xb7, 0x6d, 0x08, 0x89, 0x8e, 0x95, 0xb6, 0x62, 0x3b, 0xff, 0xfe, 0x50, + ], len: 34329, - sha: [0x9f, 0x99, 0x20, 0x44, 0x70, 0x2d, 0x0c, 0xa2, 0xf8, 0xcc, 0x0b, 0xfd, 0xfd, 0xb7, 0x55, 0x47, 0x59, 0x9f, 0x91, 0x26, 0x15, 0xff, 0xdb, 0x7c, 0xdb, 0x56, 0xcc, 0x06, 0x3c, 0xe8, 0xd6, 0xcf], + sha: [ + 0x9f, 0x99, 0x20, 0x44, 0x70, 0x2d, 0x0c, 0xa2, 0xf8, 0xcc, 0x0b, 0xfd, 0xfd, 0xb7, 0x55, 0x47, 0x59, 0x9f, + 0x91, 0x26, 0x15, 0xff, 0xdb, 0x7c, 0xdb, 0x56, 0xcc, 0x06, 0x3c, 0xe8, 0xd6, 0xcf, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_kv_stream.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_coupled.ptx", - key: [0x55, 0x47, 0x41, 0x61, 0x1c, 0xc0, 0x3e, 0x2c, 0x35, 0xb7, 0xab, 0x1d, 0xfc, 0xa9, 0xc6, 0xd6, 0xc0, 0x1b, 0x37, 0xc1, 0x7d, 0xd4, 0x91, 0x00, 0x0c, 0xcf, 0x0a, 0x23, 0xc3, 0xbb, 0xcb, 0xf9], + key: [ + 0x55, 0x47, 0x41, 0x61, 0x1c, 0xc0, 0x3e, 0x2c, 0x35, 0xb7, 0xab, 0x1d, 0xfc, 0xa9, 0xc6, 0xd6, 0xc0, 0x1b, + 0x37, 0xc1, 0x7d, 0xd4, 0x91, 0x00, 0x0c, 0xcf, 0x0a, 0x23, 0xc3, 0xbb, 0xcb, 0xf9, + ], len: 482063, - sha: [0xee, 0x6c, 0x57, 0x9d, 0x55, 0x15, 0x6e, 0x90, 0x3a, 0xf6, 0xc1, 0x8e, 0x6a, 0x47, 0x32, 0x95, 0x5f, 0xc1, 0x26, 0xd4, 0x8a, 0x02, 0x86, 0x04, 0xdb, 0x99, 0xa4, 0xcc, 0x2f, 0xcf, 0x4d, 0x80], + sha: [ + 0xee, 0x6c, 0x57, 0x9d, 0x55, 0x15, 0x6e, 0x90, 0x3a, 0xf6, 0xc1, 0x8e, 0x6a, 0x47, 0x32, 0x95, 0x5f, 0xc1, + 0x26, 0xd4, 0x8a, 0x02, 0x86, 0x04, 0xdb, 0x99, 0xa4, 0xcc, 0x2f, 0xcf, 0x4d, 0x80, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_coupled.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_qsa_attn.ptx", - key: [0x56, 0x23, 0xa5, 0xae, 0x9b, 0x2e, 0xbd, 0x2f, 0xa0, 0x10, 0xc3, 0x34, 0x36, 0x7f, 0xfc, 0x54, 0x87, 0x9a, 0xc6, 0xdf, 0x76, 0xae, 0xf0, 0x83, 0x81, 0xdb, 0xd3, 0x2b, 0x0f, 0x7e, 0xf3, 0x11], + key: [ + 0x56, 0x23, 0xa5, 0xae, 0x9b, 0x2e, 0xbd, 0x2f, 0xa0, 0x10, 0xc3, 0x34, 0x36, 0x7f, 0xfc, 0x54, 0x87, 0x9a, + 0xc6, 0xdf, 0x76, 0xae, 0xf0, 0x83, 0x81, 0xdb, 0xd3, 0x2b, 0x0f, 0x7e, 0xf3, 0x11, + ], len: 128247, - sha: [0x2d, 0xe6, 0x09, 0xa4, 0xbf, 0x6e, 0xb8, 0x80, 0xbe, 0x59, 0x4d, 0x47, 0xc0, 0x7f, 0xe4, 0x0a, 0x78, 0xd2, 0x5d, 0x70, 0xc7, 0x4e, 0xcd, 0xa7, 0x95, 0x82, 0xbd, 0x61, 0x21, 0x74, 0x99, 0xe2], + sha: [ + 0x2d, 0xe6, 0x09, 0xa4, 0xbf, 0x6e, 0xb8, 0x80, 0xbe, 0x59, 0x4d, 0x47, 0xc0, 0x7f, 0xe4, 0x0a, 0x78, 0xd2, + 0x5d, 0x70, 0xc7, 0x4e, 0xcd, 0xa7, 0x95, 0x82, 0xbd, 0x61, 0x21, 0x74, 0x99, 0xe2, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_qsa_attn.ptx"), "\0").as_bytes(), }, Companion { name: "device_poison.ptx", - key: [0x58, 0x7b, 0x09, 0x7a, 0x20, 0x1a, 0x67, 0x30, 0xe8, 0xfe, 0x55, 0x43, 0x29, 0x19, 0x87, 0xbb, 0xf8, 0x07, 0xda, 0x72, 0xda, 0x12, 0xb8, 0xe0, 0xa1, 0x69, 0xf9, 0xe5, 0xe8, 0xf6, 0xa6, 0x58], + key: [ + 0x58, 0x7b, 0x09, 0x7a, 0x20, 0x1a, 0x67, 0x30, 0xe8, 0xfe, 0x55, 0x43, 0x29, 0x19, 0x87, 0xbb, 0xf8, 0x07, + 0xda, 0x72, 0xda, 0x12, 0xb8, 0xe0, 0xa1, 0x69, 0xf9, 0xe5, 0xe8, 0xf6, 0xa6, 0x58, + ], len: 870, - sha: [0xab, 0x97, 0x01, 0x5f, 0xd4, 0x7e, 0x02, 0xe2, 0xbf, 0xde, 0x42, 0x49, 0x25, 0x62, 0xa5, 0x52, 0xef, 0x78, 0xb6, 0x0b, 0x99, 0xf0, 0xf1, 0xf3, 0xbb, 0x43, 0x5a, 0x3c, 0x0c, 0x82, 0x59, 0xa9], + sha: [ + 0xab, 0x97, 0x01, 0x5f, 0xd4, 0x7e, 0x02, 0xe2, 0xbf, 0xde, 0x42, 0x49, 0x25, 0x62, 0xa5, 0x52, 0xef, 0x78, + 0xb6, 0x0b, 0x99, 0xf0, 0xf1, 0xf3, 0xbb, 0x43, 0x5a, 0x3c, 0x0c, 0x82, 0x59, 0xa9, + ], ptx: concat!(include_str!("../ptx-sm86/device_poison.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq3_s.ptx", - key: [0x58, 0xd0, 0x68, 0xff, 0x3a, 0xcc, 0x42, 0x11, 0x61, 0x4f, 0x70, 0xab, 0x04, 0x70, 0x3a, 0x40, 0x85, 0x8e, 0x14, 0x8f, 0x9a, 0xef, 0x85, 0x03, 0xed, 0x66, 0xf7, 0x64, 0x0a, 0xe2, 0xe2, 0xaa], + key: [ + 0x58, 0xd0, 0x68, 0xff, 0x3a, 0xcc, 0x42, 0x11, 0x61, 0x4f, 0x70, 0xab, 0x04, 0x70, 0x3a, 0x40, 0x85, 0x8e, + 0x14, 0x8f, 0x9a, 0xef, 0x85, 0x03, 0xed, 0x66, 0xf7, 0x64, 0x0a, 0xe2, 0xe2, 0xaa, + ], len: 25114, - sha: [0x36, 0xc2, 0xf6, 0x8c, 0x0d, 0x3a, 0x3c, 0x52, 0x47, 0x87, 0xec, 0xf0, 0x3a, 0x1f, 0x33, 0xe2, 0xda, 0x93, 0x0a, 0x49, 0x17, 0x41, 0x9e, 0xa5, 0x89, 0x3c, 0xca, 0xa2, 0x8c, 0x33, 0xa8, 0x8c], + sha: [ + 0x36, 0xc2, 0xf6, 0x8c, 0x0d, 0x3a, 0x3c, 0x52, 0x47, 0x87, 0xec, 0xf0, 0x3a, 0x1f, 0x33, 0xe2, 0xda, 0x93, + 0x0a, 0x49, 0x17, 0x41, 0x9e, 0xa5, 0x89, 0x3c, 0xca, 0xa2, 0x8c, 0x33, 0xa8, 0x8c, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq3_s.ptx"), "\0").as_bytes(), }, Companion { name: "original_sampler.ptx", - key: [0x59, 0x1a, 0xa3, 0xdd, 0xa5, 0x2f, 0x41, 0xf0, 0xd1, 0x95, 0x41, 0x6c, 0xf0, 0x93, 0x96, 0x25, 0x68, 0xd2, 0xf8, 0x3d, 0x6f, 0x76, 0x2a, 0x96, 0x78, 0xbe, 0x61, 0x94, 0x6c, 0xec, 0xb7, 0x5b], + key: [ + 0x59, 0x1a, 0xa3, 0xdd, 0xa5, 0x2f, 0x41, 0xf0, 0xd1, 0x95, 0x41, 0x6c, 0xf0, 0x93, 0x96, 0x25, 0x68, 0xd2, + 0xf8, 0x3d, 0x6f, 0x76, 0x2a, 0x96, 0x78, 0xbe, 0x61, 0x94, 0x6c, 0xec, 0xb7, 0x5b, + ], len: 475837, - sha: [0x3c, 0xf7, 0xa3, 0x0f, 0x81, 0x6f, 0x9f, 0x27, 0xa2, 0x2f, 0xf8, 0x21, 0x11, 0x7e, 0x9b, 0xff, 0x7c, 0xbc, 0xc3, 0x19, 0x69, 0xac, 0x25, 0x5d, 0x32, 0xb4, 0x0d, 0xdd, 0x4d, 0xda, 0xdc, 0x40], + sha: [ + 0x3c, 0xf7, 0xa3, 0x0f, 0x81, 0x6f, 0x9f, 0x27, 0xa2, 0x2f, 0xf8, 0x21, 0x11, 0x7e, 0x9b, 0xff, 0x7c, 0xbc, + 0xc3, 0x19, 0x69, 0xac, 0x25, 0x5d, 0x32, 0xb4, 0x0d, 0xdd, 0x4d, 0xda, 0xdc, 0x40, + ], ptx: concat!(include_str!("../ptx-sm86/original_sampler.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-selected.ptx", - key: [0x5a, 0x56, 0xd8, 0xeb, 0x66, 0xf1, 0xf9, 0x8e, 0x3c, 0xb3, 0xab, 0x75, 0x18, 0x1e, 0x0f, 0x26, 0x3e, 0x4d, 0x51, 0xc4, 0xe7, 0x1e, 0x27, 0xab, 0x2b, 0xc9, 0x9a, 0x1a, 0x3b, 0x7c, 0x01, 0xcb], + key: [ + 0x5a, 0x56, 0xd8, 0xeb, 0x66, 0xf1, 0xf9, 0x8e, 0x3c, 0xb3, 0xab, 0x75, 0x18, 0x1e, 0x0f, 0x26, 0x3e, 0x4d, + 0x51, 0xc4, 0xe7, 0x1e, 0x27, 0xab, 0x2b, 0xc9, 0x9a, 0x1a, 0x3b, 0x7c, 0x01, 0xcb, + ], len: 955352, - sha: [0xc1, 0x5b, 0x58, 0x0a, 0x9f, 0xdc, 0x85, 0x67, 0x39, 0xfc, 0xa0, 0xa5, 0x68, 0x57, 0xfc, 0x7e, 0x7e, 0xc0, 0x1b, 0x4f, 0x1c, 0x99, 0x3f, 0xfb, 0x2e, 0xde, 0x04, 0x66, 0x01, 0x04, 0x86, 0x28], + sha: [ + 0xc1, 0x5b, 0x58, 0x0a, 0x9f, 0xdc, 0x85, 0x67, 0x39, 0xfc, 0xa0, 0xa5, 0x68, 0x57, 0xfc, 0x7e, 0x7e, 0xc0, + 0x1b, 0x4f, 0x1c, 0x99, 0x3f, 0xfb, 0x2e, 0xde, 0x04, 0x66, 0x01, 0x04, 0x86, 0x28, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-selected.ptx"), "\0").as_bytes(), }, Companion { name: "offline_gdn_prefill.ptx", - key: [0x5c, 0xc3, 0xa0, 0x28, 0x5d, 0xb9, 0x83, 0xce, 0xbe, 0x9e, 0x35, 0xfa, 0xc2, 0xd5, 0x3e, 0x57, 0x32, 0x68, 0xaf, 0x81, 0x7f, 0x13, 0x1b, 0x23, 0x40, 0xbd, 0x00, 0x3a, 0xe3, 0xe1, 0x64, 0xce], + key: [ + 0x5c, 0xc3, 0xa0, 0x28, 0x5d, 0xb9, 0x83, 0xce, 0xbe, 0x9e, 0x35, 0xfa, 0xc2, 0xd5, 0x3e, 0x57, 0x32, 0x68, + 0xaf, 0x81, 0x7f, 0x13, 0x1b, 0x23, 0x40, 0xbd, 0x00, 0x3a, 0xe3, 0xe1, 0x64, 0xce, + ], len: 52304, - sha: [0x12, 0x71, 0xac, 0x05, 0x6e, 0xa0, 0x13, 0x2b, 0xda, 0x7d, 0x11, 0x57, 0x0a, 0x29, 0x6d, 0x00, 0x81, 0x1d, 0x82, 0xe3, 0x90, 0x1d, 0x6c, 0x5d, 0x77, 0x14, 0x77, 0xf8, 0xd9, 0x60, 0x6c, 0x37], + sha: [ + 0x12, 0x71, 0xac, 0x05, 0x6e, 0xa0, 0x13, 0x2b, 0xda, 0x7d, 0x11, 0x57, 0x0a, 0x29, 0x6d, 0x00, 0x81, 0x1d, + 0x82, 0xe3, 0x90, 0x1d, 0x6c, 0x5d, 0x77, 0x14, 0x77, 0xf8, 0xd9, 0x60, 0x6c, 0x37, + ], ptx: concat!(include_str!("../ptx-sm86/offline_gdn_prefill.ptx"), "\0").as_bytes(), }, Companion { name: "ple_native_batch.ptx", - key: [0x5f, 0xa5, 0xc9, 0x30, 0xf4, 0x0c, 0xb4, 0x9d, 0x9e, 0x79, 0xa3, 0x5e, 0x19, 0x11, 0xc6, 0x85, 0x81, 0xf9, 0x2c, 0x09, 0x77, 0x50, 0xef, 0xf2, 0x8c, 0x24, 0x5e, 0x28, 0x70, 0x96, 0x4a, 0x40], + key: [ + 0x5f, 0xa5, 0xc9, 0x30, 0xf4, 0x0c, 0xb4, 0x9d, 0x9e, 0x79, 0xa3, 0x5e, 0x19, 0x11, 0xc6, 0x85, 0x81, 0xf9, + 0x2c, 0x09, 0x77, 0x50, 0xef, 0xf2, 0x8c, 0x24, 0x5e, 0x28, 0x70, 0x96, 0x4a, 0x40, + ], len: 19699, - sha: [0xf9, 0xa3, 0x97, 0x01, 0xe2, 0xcc, 0xf0, 0xf6, 0xf7, 0x2d, 0x5e, 0xce, 0x56, 0x6b, 0x78, 0x09, 0x33, 0xea, 0xdd, 0xe6, 0x89, 0xe7, 0xff, 0x50, 0x2a, 0xcf, 0x87, 0xdb, 0x63, 0xf5, 0xd8, 0x5f], + sha: [ + 0xf9, 0xa3, 0x97, 0x01, 0xe2, 0xcc, 0xf0, 0xf6, 0xf7, 0x2d, 0x5e, 0xce, 0x56, 0x6b, 0x78, 0x09, 0x33, 0xea, + 0xdd, 0xe6, 0x89, 0xe7, 0xff, 0x50, 0x2a, 0xcf, 0x87, 0xdb, 0x63, 0xf5, 0xd8, 0x5f, + ], ptx: concat!(include_str!("../ptx-sm86/ple_native_batch.ptx"), "\0").as_bytes(), }, Companion { name: "ple_value_full_fixed.ptx", - key: [0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, 0xac, 0x6c, 0x15, 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, 0x25, 0xd0], + key: [ + 0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, 0xac, 0x6c, 0x15, + 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, 0x25, 0xd0, + ], len: 5199, - sha: [0xbf, 0xcd, 0x7c, 0x88, 0x44, 0x62, 0xc1, 0xe1, 0xe2, 0x8e, 0x3f, 0x73, 0xc7, 0x25, 0x0f, 0xbb, 0xa5, 0x1b, 0xc0, 0xc9, 0x5f, 0x03, 0x7d, 0xba, 0x18, 0x4f, 0x32, 0x24, 0x75, 0x8f, 0xaa, 0x33], + sha: [ + 0xbf, 0xcd, 0x7c, 0x88, 0x44, 0x62, 0xc1, 0xe1, 0xe2, 0x8e, 0x3f, 0x73, 0xc7, 0x25, 0x0f, 0xbb, 0xa5, 0x1b, + 0xc0, 0xc9, 0x5f, 0x03, 0x7d, 0xba, 0x18, 0x4f, 0x32, 0x24, 0x75, 0x8f, 0xaa, 0x33, + ], ptx: concat!(include_str!("../ptx-sm86/ple_value_full_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "q5_k_q8_1.ptx", - key: [0x65, 0xcd, 0x98, 0x13, 0x8e, 0x2a, 0xd9, 0xd1, 0xc2, 0x71, 0x1f, 0xf7, 0xfc, 0x27, 0x28, 0x0f, 0x07, 0xf1, 0xa2, 0x24, 0xfc, 0xdd, 0x2a, 0xbe, 0xea, 0x9b, 0xed, 0xf9, 0xd9, 0xd3, 0xff, 0xfc], + key: [ + 0x65, 0xcd, 0x98, 0x13, 0x8e, 0x2a, 0xd9, 0xd1, 0xc2, 0x71, 0x1f, 0xf7, 0xfc, 0x27, 0x28, 0x0f, 0x07, 0xf1, + 0xa2, 0x24, 0xfc, 0xdd, 0x2a, 0xbe, 0xea, 0x9b, 0xed, 0xf9, 0xd9, 0xd3, 0xff, 0xfc, + ], len: 33608, - sha: [0x24, 0x64, 0xea, 0x04, 0x0f, 0xfa, 0x4d, 0xa2, 0x03, 0xe7, 0xde, 0xe9, 0x14, 0x5a, 0x1e, 0xa9, 0x88, 0xdb, 0x90, 0x2d, 0xff, 0xe7, 0xa1, 0x6d, 0x4f, 0x2c, 0xf1, 0x77, 0xcd, 0x7d, 0x32, 0xd6], + sha: [ + 0x24, 0x64, 0xea, 0x04, 0x0f, 0xfa, 0x4d, 0xa2, 0x03, 0xe7, 0xde, 0xe9, 0x14, 0x5a, 0x1e, 0xa9, 0x88, 0xdb, + 0x90, 0x2d, 0xff, 0xe7, 0xa1, 0x6d, 0x4f, 0x2c, 0xf1, 0x77, 0xcd, 0x7d, 0x32, 0xd6, + ], ptx: concat!(include_str!("../ptx-sm86/q5_k_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "native_head_iq.ptx", - key: [0x66, 0xd3, 0xe6, 0x22, 0xee, 0x4f, 0xb8, 0xb6, 0x71, 0x92, 0x8a, 0x73, 0xda, 0xe7, 0x03, 0x85, 0xe4, 0x41, 0x5d, 0xb4, 0x7a, 0xd5, 0x34, 0x2d, 0x5e, 0xb0, 0xd2, 0x50, 0x7b, 0xea, 0xb5, 0xe4], + key: [ + 0x66, 0xd3, 0xe6, 0x22, 0xee, 0x4f, 0xb8, 0xb6, 0x71, 0x92, 0x8a, 0x73, 0xda, 0xe7, 0x03, 0x85, 0xe4, 0x41, + 0x5d, 0xb4, 0x7a, 0xd5, 0x34, 0x2d, 0x5e, 0xb0, 0xd2, 0x50, 0x7b, 0xea, 0xb5, 0xe4, + ], len: 753628, - sha: [0x90, 0xda, 0x63, 0x69, 0xf0, 0x50, 0x9e, 0x6c, 0xa6, 0x41, 0xb0, 0xa4, 0x7d, 0xce, 0x03, 0x81, 0xe8, 0x8c, 0x27, 0xf0, 0x0e, 0xb4, 0x18, 0x19, 0x82, 0xd9, 0x42, 0x22, 0x16, 0x97, 0x2a, 0x2c], + sha: [ + 0x90, 0xda, 0x63, 0x69, 0xf0, 0x50, 0x9e, 0x6c, 0xa6, 0x41, 0xb0, 0xa4, 0x7d, 0xce, 0x03, 0x81, 0xe8, 0x8c, + 0x27, 0xf0, 0x0e, 0xb4, 0x18, 0x19, 0x82, 0xd9, 0x42, 0x22, 0x16, 0x97, 0x2a, 0x2c, + ], ptx: concat!(include_str!("../ptx-sm86/native_head_iq.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_device_gate.ptx", - key: [0x69, 0xf0, 0x3b, 0xe1, 0x7d, 0xb1, 0x7a, 0xba, 0x2f, 0x82, 0x8c, 0xf4, 0x37, 0x91, 0x0a, 0x4d, 0xb6, 0x63, 0x23, 0x97, 0x3d, 0xaa, 0x8b, 0x1a, 0x45, 0x9c, 0x24, 0x18, 0xf9, 0x11, 0x45, 0xd4], + key: [ + 0x69, 0xf0, 0x3b, 0xe1, 0x7d, 0xb1, 0x7a, 0xba, 0x2f, 0x82, 0x8c, 0xf4, 0x37, 0x91, 0x0a, 0x4d, 0xb6, 0x63, + 0x23, 0x97, 0x3d, 0xaa, 0x8b, 0x1a, 0x45, 0x9c, 0x24, 0x18, 0xf9, 0x11, 0x45, 0xd4, + ], len: 2382, - sha: [0x3b, 0xca, 0x8a, 0x59, 0x4f, 0x37, 0xdd, 0x80, 0xff, 0x12, 0xbd, 0x9b, 0x2c, 0x45, 0x4b, 0x76, 0x68, 0xf2, 0x26, 0x57, 0x1a, 0x2f, 0x2c, 0x5d, 0x33, 0x89, 0xd7, 0xa5, 0xa9, 0x81, 0xba, 0xa7], + sha: [ + 0x3b, 0xca, 0x8a, 0x59, 0x4f, 0x37, 0xdd, 0x80, 0xff, 0x12, 0xbd, 0x9b, 0x2c, 0x45, 0x4b, 0x76, 0x68, 0xf2, + 0x26, 0x57, 0x1a, 0x2f, 0x2c, 0x5d, 0x33, 0x89, 0xd7, 0xa5, 0xa9, 0x81, 0xba, 0xa7, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_device_gate.ptx"), "\0").as_bytes(), }, Companion { name: "q6_batch_preview.ptx", - key: [0x6a, 0x4d, 0x43, 0xe4, 0x1a, 0x45, 0xd9, 0x9f, 0xbb, 0xaa, 0xe3, 0x91, 0x70, 0x38, 0xe2, 0x81, 0xf1, 0x1d, 0x04, 0x37, 0x0e, 0x02, 0x59, 0xea, 0x70, 0x26, 0x81, 0x14, 0x42, 0x96, 0xde, 0x79], + key: [ + 0x6a, 0x4d, 0x43, 0xe4, 0x1a, 0x45, 0xd9, 0x9f, 0xbb, 0xaa, 0xe3, 0x91, 0x70, 0x38, 0xe2, 0x81, 0xf1, 0x1d, + 0x04, 0x37, 0x0e, 0x02, 0x59, 0xea, 0x70, 0x26, 0x81, 0x14, 0x42, 0x96, 0xde, 0x79, + ], len: 28112, - sha: [0xf5, 0x4e, 0xea, 0xa6, 0xeb, 0x53, 0xa4, 0xd5, 0x02, 0x34, 0x4f, 0x90, 0x8f, 0x97, 0x65, 0xaa, 0xdf, 0x44, 0x53, 0x77, 0xd4, 0x3a, 0x70, 0x53, 0x23, 0x59, 0xfe, 0xe2, 0x33, 0xa0, 0x06, 0x73], + sha: [ + 0xf5, 0x4e, 0xea, 0xa6, 0xeb, 0x53, 0xa4, 0xd5, 0x02, 0x34, 0x4f, 0x90, 0x8f, 0x97, 0x65, 0xaa, 0xdf, 0x44, + 0x53, 0x77, 0xd4, 0x3a, 0x70, 0x53, 0x23, 0x59, 0xfe, 0xe2, 0x33, 0xa0, 0x06, 0x73, + ], ptx: concat!(include_str!("../ptx-sm86/q6_batch_preview.ptx"), "\0").as_bytes(), }, Companion { name: "prefill_stage.ptx", - key: [0x6f, 0x8f, 0xb3, 0xbb, 0xd1, 0x11, 0x71, 0xc9, 0x39, 0x02, 0x97, 0xd5, 0xd2, 0xc9, 0xcb, 0x90, 0x76, 0xd4, 0xb6, 0x51, 0xf2, 0xa7, 0x04, 0x2b, 0xf1, 0x6f, 0x4c, 0xaf, 0x89, 0xa5, 0xb3, 0x84], + key: [ + 0x6f, 0x8f, 0xb3, 0xbb, 0xd1, 0x11, 0x71, 0xc9, 0x39, 0x02, 0x97, 0xd5, 0xd2, 0xc9, 0xcb, 0x90, 0x76, 0xd4, + 0xb6, 0x51, 0xf2, 0xa7, 0x04, 0x2b, 0xf1, 0x6f, 0x4c, 0xaf, 0x89, 0xa5, 0xb3, 0x84, + ], len: 161928, - sha: [0xd8, 0x1a, 0x87, 0x43, 0x7b, 0x72, 0x6b, 0xcf, 0x1a, 0x9d, 0xf0, 0xca, 0x6d, 0x5e, 0xbe, 0xdf, 0x5c, 0x06, 0xda, 0xce, 0xe6, 0x88, 0xbd, 0xc8, 0xfe, 0x91, 0x78, 0x91, 0xcc, 0x0c, 0xda, 0x4b], + sha: [ + 0xd8, 0x1a, 0x87, 0x43, 0x7b, 0x72, 0x6b, 0xcf, 0x1a, 0x9d, 0xf0, 0xca, 0x6d, 0x5e, 0xbe, 0xdf, 0x5c, 0x06, + 0xda, 0xce, 0xe6, 0x88, 0xbd, 0xc8, 0xfe, 0x91, 0x78, 0x91, 0xcc, 0x0c, 0xda, 0x4b, + ], ptx: concat!(include_str!("../ptx-sm86/prefill_stage.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify_window_pcie_fast.ptx", - key: [0x74, 0x07, 0x85, 0x9f, 0x8d, 0x88, 0x81, 0x66, 0x3f, 0x3a, 0x64, 0x6e, 0xbe, 0x28, 0x8c, 0x31, 0x13, 0x8c, 0xce, 0x32, 0x27, 0xc1, 0xc5, 0xd9, 0xe2, 0xe5, 0x92, 0x64, 0x8e, 0xd7, 0x7a, 0xea], + key: [ + 0x74, 0x07, 0x85, 0x9f, 0x8d, 0x88, 0x81, 0x66, 0x3f, 0x3a, 0x64, 0x6e, 0xbe, 0x28, 0x8c, 0x31, 0x13, 0x8c, + 0xce, 0x32, 0x27, 0xc1, 0xc5, 0xd9, 0xe2, 0xe5, 0x92, 0x64, 0x8e, 0xd7, 0x7a, 0xea, + ], len: 71051, - sha: [0x23, 0x48, 0x1b, 0x50, 0xaf, 0x2c, 0x50, 0x1b, 0x04, 0xed, 0xc1, 0xe9, 0xd4, 0xa3, 0x85, 0x35, 0xcf, 0x83, 0x88, 0x46, 0xaa, 0x57, 0xd4, 0x4f, 0x0b, 0xcf, 0x2c, 0x2d, 0xc7, 0xf3, 0xd1, 0xa3], + sha: [ + 0x23, 0x48, 0x1b, 0x50, 0xaf, 0x2c, 0x50, 0x1b, 0x04, 0xed, 0xc1, 0xe9, 0xd4, 0xa3, 0x85, 0x35, 0xcf, 0x83, + 0x88, 0x46, 0xaa, 0x57, 0xd4, 0x4f, 0x0b, 0xcf, 0x2c, 0x2d, 0xc7, 0xf3, 0xd1, 0xa3, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify_window_pcie_fast.ptx"), "\0").as_bytes(), }, Companion { name: "experimental_kv_q4.ptx", - key: [0x74, 0x66, 0x5b, 0x01, 0x6f, 0xde, 0x9d, 0xc4, 0xf5, 0x0a, 0x36, 0xe6, 0x2c, 0xbf, 0x2e, 0x57, 0x8c, 0x73, 0x5e, 0x48, 0xe3, 0xbe, 0x51, 0xb7, 0x07, 0x34, 0xe9, 0xe5, 0x39, 0x42, 0xcd, 0xe7], + key: [ + 0x74, 0x66, 0x5b, 0x01, 0x6f, 0xde, 0x9d, 0xc4, 0xf5, 0x0a, 0x36, 0xe6, 0x2c, 0xbf, 0x2e, 0x57, 0x8c, 0x73, + 0x5e, 0x48, 0xe3, 0xbe, 0x51, 0xb7, 0x07, 0x34, 0xe9, 0xe5, 0x39, 0x42, 0xcd, 0xe7, + ], len: 36319, - sha: [0x36, 0x1d, 0xb3, 0xe8, 0x47, 0x1e, 0x42, 0x77, 0x8a, 0x4b, 0x7d, 0x45, 0x9a, 0xf7, 0x28, 0x9a, 0xa8, 0xe8, 0x01, 0x7b, 0xb3, 0xa7, 0x45, 0x5e, 0x6a, 0xa2, 0xe0, 0x49, 0xb2, 0x2a, 0xd0, 0x93], + sha: [ + 0x36, 0x1d, 0xb3, 0xe8, 0x47, 0x1e, 0x42, 0x77, 0x8a, 0x4b, 0x7d, 0x45, 0x9a, 0xf7, 0x28, 0x9a, 0xa8, 0xe8, + 0x01, 0x7b, 0xb3, 0xa7, 0x45, 0x5e, 0x6a, 0xa2, 0xe0, 0x49, 0xb2, 0x2a, 0xd0, 0x93, + ], ptx: concat!(include_str!("../ptx-sm86/experimental_kv_q4.ptx"), "\0").as_bytes(), }, Companion { name: "qwen_qsa_attention_native.ptx", - key: [0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, 0x0f, 0xd4, 0x29, 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, 0xe1, 0xf3], + key: [ + 0x77, 0x72, 0xe4, 0xe7, 0x5d, 0x78, 0xa9, 0x91, 0x01, 0x44, 0xca, 0x10, 0x85, 0x51, 0x80, 0x0f, 0xd4, 0x29, + 0x69, 0x55, 0x78, 0x15, 0x40, 0xaf, 0xb6, 0x5f, 0x53, 0xd6, 0x12, 0xd7, 0xe1, 0xf3, + ], len: 3139, - sha: [0xda, 0xb3, 0xfd, 0x1c, 0xe3, 0xde, 0x7e, 0xfc, 0x94, 0x1e, 0xcb, 0x26, 0x84, 0x33, 0x6d, 0xea, 0x26, 0xe3, 0x61, 0xd6, 0xc5, 0x0a, 0xbd, 0x45, 0xdc, 0xf2, 0x0f, 0x2e, 0x1e, 0x8f, 0x86, 0xdd], + sha: [ + 0xda, 0xb3, 0xfd, 0x1c, 0xe3, 0xde, 0x7e, 0xfc, 0x94, 0x1e, 0xcb, 0x26, 0x84, 0x33, 0x6d, 0xea, 0x26, 0xe3, + 0x61, 0xd6, 0xc5, 0x0a, 0xbd, 0x45, 0xdc, 0xf2, 0x0f, 0x2e, 0x1e, 0x8f, 0x86, 0xdd, + ], ptx: concat!(include_str!("../ptx-sm86/qwen_qsa_attention_native.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq3_xxs.ptx", - key: [0x78, 0x82, 0x05, 0x48, 0x65, 0xe5, 0x55, 0x01, 0x0d, 0x4d, 0x60, 0xfc, 0x21, 0xf1, 0xae, 0xbb, 0x97, 0xb1, 0x0d, 0xc0, 0x6a, 0xf1, 0xaf, 0xe3, 0xd0, 0x9f, 0xce, 0x21, 0x96, 0xac, 0x37, 0x67], + key: [ + 0x78, 0x82, 0x05, 0x48, 0x65, 0xe5, 0x55, 0x01, 0x0d, 0x4d, 0x60, 0xfc, 0x21, 0xf1, 0xae, 0xbb, 0x97, 0xb1, + 0x0d, 0xc0, 0x6a, 0xf1, 0xaf, 0xe3, 0xd0, 0x9f, 0xce, 0x21, 0x96, 0xac, 0x37, 0x67, + ], len: 16161, - sha: [0xd7, 0x67, 0xad, 0x5a, 0x01, 0x05, 0x0a, 0x8e, 0xc6, 0x8b, 0x73, 0xc3, 0xb5, 0x30, 0x05, 0x09, 0x40, 0x2a, 0x5f, 0x25, 0x14, 0xd6, 0x72, 0xf1, 0x93, 0x01, 0x71, 0xa5, 0xef, 0x98, 0x65, 0xbc], + sha: [ + 0xd7, 0x67, 0xad, 0x5a, 0x01, 0x05, 0x0a, 0x8e, 0xc6, 0x8b, 0x73, 0xc3, 0xb5, 0x30, 0x05, 0x09, 0x40, 0x2a, + 0x5f, 0x25, 0x14, 0xd6, 0x72, 0xf1, 0x93, 0x01, 0x71, 0xa5, 0xef, 0x98, 0x65, 0xbc, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq3_xxs.ptx"), "\0").as_bytes(), }, Companion { name: "head_greedy.ptx", - key: [0x78, 0x9f, 0xb7, 0xfc, 0xd5, 0x56, 0x4d, 0xea, 0xac, 0x9e, 0xbd, 0x24, 0x79, 0x7d, 0x3a, 0x15, 0xcd, 0xbb, 0x7c, 0x45, 0xf3, 0x97, 0xa7, 0x72, 0x05, 0x7a, 0x6c, 0x5e, 0xd3, 0xf5, 0x2e, 0xb1], + key: [ + 0x78, 0x9f, 0xb7, 0xfc, 0xd5, 0x56, 0x4d, 0xea, 0xac, 0x9e, 0xbd, 0x24, 0x79, 0x7d, 0x3a, 0x15, 0xcd, 0xbb, + 0x7c, 0x45, 0xf3, 0x97, 0xa7, 0x72, 0x05, 0x7a, 0x6c, 0x5e, 0xd3, 0xf5, 0x2e, 0xb1, + ], len: 4291, - sha: [0x00, 0xa5, 0xe1, 0x17, 0x6c, 0xc8, 0x95, 0x28, 0x19, 0x41, 0x5f, 0x62, 0x2b, 0x88, 0x6e, 0xea, 0xc3, 0xd6, 0x7b, 0x1f, 0x2b, 0xd5, 0xa4, 0xf9, 0xc7, 0x2e, 0xde, 0x97, 0x85, 0xdf, 0xd8, 0x6e], + sha: [ + 0x00, 0xa5, 0xe1, 0x17, 0x6c, 0xc8, 0x95, 0x28, 0x19, 0x41, 0x5f, 0x62, 0x2b, 0x88, 0x6e, 0xea, 0xc3, 0xd6, + 0x7b, 0x1f, 0x2b, 0xd5, 0xa4, 0xf9, 0xc7, 0x2e, 0xde, 0x97, 0x85, 0xdf, 0xd8, 0x6e, + ], ptx: concat!(include_str!("../ptx-sm86/head_greedy.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_gr_fixed.ptx", - key: [0x7a, 0xba, 0x70, 0x01, 0x45, 0xb1, 0x9a, 0x09, 0x1d, 0x1c, 0xa2, 0x77, 0x44, 0x62, 0x01, 0xff, 0x47, 0x69, 0xba, 0xa3, 0x66, 0xe7, 0xd5, 0xa0, 0x29, 0x4a, 0x91, 0xe7, 0x6b, 0xa6, 0x09, 0xd4], + key: [ + 0x7a, 0xba, 0x70, 0x01, 0x45, 0xb1, 0x9a, 0x09, 0x1d, 0x1c, 0xa2, 0x77, 0x44, 0x62, 0x01, 0xff, 0x47, 0x69, + 0xba, 0xa3, 0x66, 0xe7, 0xd5, 0xa0, 0x29, 0x4a, 0x91, 0xe7, 0x6b, 0xa6, 0x09, 0xd4, + ], len: 103348, - sha: [0xcf, 0xa8, 0x85, 0xcd, 0x69, 0xf9, 0x51, 0xd3, 0x61, 0x67, 0x31, 0x9a, 0xb0, 0x5b, 0x5a, 0x6b, 0xbd, 0xce, 0x95, 0x98, 0xc9, 0x13, 0x3c, 0xd4, 0x30, 0x0d, 0x18, 0xa1, 0x92, 0x8f, 0x24, 0xdd], + sha: [ + 0xcf, 0xa8, 0x85, 0xcd, 0x69, 0xf9, 0x51, 0xd3, 0x61, 0x67, 0x31, 0x9a, 0xb0, 0x5b, 0x5a, 0x6b, 0xbd, 0xce, + 0x95, 0x98, 0xc9, 0x13, 0x3c, 0xd4, 0x30, 0x0d, 0x18, 0xa1, 0x92, 0x8f, 0x24, 0xdd, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_gr_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "gdn_fixed.ptx", - key: [0x7b, 0x2f, 0x20, 0x3c, 0xe1, 0xb1, 0xb4, 0xc7, 0xe6, 0x3b, 0xb5, 0x6a, 0x1f, 0x7c, 0x35, 0x1a, 0x21, 0x3e, 0x1f, 0x5d, 0xf9, 0x71, 0x1a, 0xd2, 0xd8, 0xdb, 0x30, 0x47, 0xae, 0xad, 0x9e, 0x25], + key: [ + 0x7b, 0x2f, 0x20, 0x3c, 0xe1, 0xb1, 0xb4, 0xc7, 0xe6, 0x3b, 0xb5, 0x6a, 0x1f, 0x7c, 0x35, 0x1a, 0x21, 0x3e, + 0x1f, 0x5d, 0xf9, 0x71, 0x1a, 0xd2, 0xd8, 0xdb, 0x30, 0x47, 0xae, 0xad, 0x9e, 0x25, + ], len: 35268, - sha: [0x09, 0x82, 0x29, 0x8e, 0xa9, 0xf8, 0xe4, 0xbf, 0xa7, 0x0e, 0xef, 0xb1, 0xde, 0xe0, 0xa4, 0x30, 0x73, 0x74, 0x38, 0x9b, 0x3d, 0x60, 0x4d, 0xf5, 0xea, 0x50, 0x7f, 0x35, 0xb5, 0x2f, 0xe4, 0x10], + sha: [ + 0x09, 0x82, 0x29, 0x8e, 0xa9, 0xf8, 0xe4, 0xbf, 0xa7, 0x0e, 0xef, 0xb1, 0xde, 0xe0, 0xa4, 0x30, 0x73, 0x74, + 0x38, 0x9b, 0x3d, 0x60, 0x4d, 0xf5, 0xea, 0x50, 0x7f, 0x35, 0xb5, 0x2f, 0xe4, 0x10, + ], ptx: concat!(include_str!("../ptx-sm86/gdn_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "offline_gdn_fused_t1.ptx", - key: [0x7b, 0xd0, 0x09, 0x09, 0x27, 0x3c, 0x41, 0x06, 0x55, 0xc3, 0xe1, 0x78, 0x1e, 0x58, 0xd2, 0x1a, 0xe1, 0x54, 0x18, 0x1f, 0xbd, 0x74, 0xc6, 0xb2, 0x11, 0x55, 0x74, 0x8c, 0x97, 0x03, 0x5d, 0xd3], + key: [ + 0x7b, 0xd0, 0x09, 0x09, 0x27, 0x3c, 0x41, 0x06, 0x55, 0xc3, 0xe1, 0x78, 0x1e, 0x58, 0xd2, 0x1a, 0xe1, 0x54, + 0x18, 0x1f, 0xbd, 0x74, 0xc6, 0xb2, 0x11, 0x55, 0x74, 0x8c, 0x97, 0x03, 0x5d, 0xd3, + ], len: 51663, - sha: [0x5d, 0x2d, 0xa8, 0x20, 0xdb, 0xc9, 0x31, 0x38, 0xe6, 0xa7, 0xce, 0x85, 0x92, 0xc7, 0x1e, 0xc3, 0xd6, 0xa2, 0xb1, 0x0d, 0x57, 0xd1, 0x89, 0xa2, 0xab, 0x50, 0x7d, 0xce, 0x5b, 0x20, 0xd0, 0x1c], + sha: [ + 0x5d, 0x2d, 0xa8, 0x20, 0xdb, 0xc9, 0x31, 0x38, 0xe6, 0xa7, 0xce, 0x85, 0x92, 0xc7, 0x1e, 0xc3, 0xd6, 0xa2, + 0xb1, 0x0d, 0x57, 0xd1, 0x89, 0xa2, 0xab, 0x50, 0x7d, 0xce, 0x5b, 0x20, 0xd0, 0x1c, + ], ptx: concat!(include_str!("../ptx-sm86/offline_gdn_fused_t1.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_native_decode.ptx", - key: [0x7c, 0x98, 0xe8, 0xf0, 0x08, 0x92, 0x14, 0x23, 0xe3, 0x05, 0x9f, 0x81, 0xf9, 0xf4, 0xe3, 0x17, 0xeb, 0x40, 0x7d, 0x15, 0xd6, 0xb9, 0x81, 0x5a, 0xe6, 0xda, 0xd7, 0x92, 0x08, 0x83, 0xb0, 0xda], + key: [ + 0x7c, 0x98, 0xe8, 0xf0, 0x08, 0x92, 0x14, 0x23, 0xe3, 0x05, 0x9f, 0x81, 0xf9, 0xf4, 0xe3, 0x17, 0xeb, 0x40, + 0x7d, 0x15, 0xd6, 0xb9, 0x81, 0x5a, 0xe6, 0xda, 0xd7, 0x92, 0x08, 0x83, 0xb0, 0xda, + ], len: 55720, - sha: [0xde, 0x1e, 0x3c, 0x7a, 0xe0, 0x3c, 0x7e, 0x7f, 0x57, 0x47, 0x2e, 0xbd, 0xe7, 0x58, 0x1f, 0xf0, 0x51, 0x62, 0xb5, 0x45, 0xb1, 0x00, 0x27, 0xf9, 0x6b, 0x2b, 0x36, 0xc4, 0x10, 0xd1, 0xa3, 0x65], + sha: [ + 0xde, 0x1e, 0x3c, 0x7a, 0xe0, 0x3c, 0x7e, 0x7f, 0x57, 0x47, 0x2e, 0xbd, 0xe7, 0x58, 0x1f, 0xf0, 0x51, 0x62, + 0xb5, 0x45, 0xb1, 0x00, 0x27, 0xf9, 0x6b, 0x2b, 0x36, 0xc4, 0x10, 0xd1, 0xa3, 0x65, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_native_decode.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_prefill_embedding.ptx", - key: [0x7e, 0x49, 0xc0, 0x3b, 0x93, 0x3c, 0xdf, 0x6a, 0x4a, 0x79, 0x37, 0x6f, 0xfa, 0x97, 0xf0, 0x61, 0x88, 0x7a, 0x54, 0x92, 0x46, 0x77, 0x43, 0xd0, 0x8e, 0x28, 0x5a, 0x13, 0x95, 0x58, 0x0f, 0xc8], + key: [ + 0x7e, 0x49, 0xc0, 0x3b, 0x93, 0x3c, 0xdf, 0x6a, 0x4a, 0x79, 0x37, 0x6f, 0xfa, 0x97, 0xf0, 0x61, 0x88, 0x7a, + 0x54, 0x92, 0x46, 0x77, 0x43, 0xd0, 0x8e, 0x28, 0x5a, 0x13, 0x95, 0x58, 0x0f, 0xc8, + ], len: 847405, - sha: [0x2c, 0xe1, 0xd3, 0xe9, 0xaa, 0x97, 0x2f, 0x1f, 0xd0, 0xc1, 0x34, 0x27, 0x21, 0x66, 0xd2, 0x72, 0x22, 0xe9, 0x3b, 0xae, 0x18, 0xda, 0x19, 0xfc, 0x11, 0x97, 0x41, 0x6f, 0x26, 0x4a, 0xe5, 0x54], + sha: [ + 0x2c, 0xe1, 0xd3, 0xe9, 0xaa, 0x97, 0x2f, 0x1f, 0xd0, 0xc1, 0x34, 0x27, 0x21, 0x66, 0xd2, 0x72, 0x22, 0xe9, + 0x3b, 0xae, 0x18, 0xda, 0x19, 0xfc, 0x11, 0x97, 0x41, 0x6f, 0x26, 0x4a, 0xe5, 0x54, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_prefill_embedding.ptx"), "\0").as_bytes(), }, Companion { name: "native_head_native.ptx", - key: [0x81, 0xa3, 0x99, 0x0c, 0x14, 0x3e, 0x45, 0x1d, 0xac, 0x79, 0x48, 0x62, 0xcf, 0x73, 0x3f, 0x5f, 0x41, 0x21, 0xf5, 0x2a, 0xa0, 0x70, 0x50, 0xc5, 0x6e, 0x06, 0x1c, 0x17, 0x63, 0xd1, 0x47, 0x9a], + key: [ + 0x81, 0xa3, 0x99, 0x0c, 0x14, 0x3e, 0x45, 0x1d, 0xac, 0x79, 0x48, 0x62, 0xcf, 0x73, 0x3f, 0x5f, 0x41, 0x21, + 0xf5, 0x2a, 0xa0, 0x70, 0x50, 0xc5, 0x6e, 0x06, 0x1c, 0x17, 0x63, 0xd1, 0x47, 0x9a, + ], len: 7398533, - sha: [0xe5, 0x44, 0x90, 0xc3, 0x6e, 0x5c, 0xd5, 0xbf, 0x1f, 0x3c, 0x77, 0xc1, 0xaa, 0xf0, 0xdb, 0x21, 0x1c, 0x06, 0x0d, 0x53, 0xfa, 0x93, 0x0a, 0x7a, 0xd0, 0xd4, 0xe9, 0xa5, 0x1c, 0xb9, 0x33, 0x89], + sha: [ + 0xe5, 0x44, 0x90, 0xc3, 0x6e, 0x5c, 0xd5, 0xbf, 0x1f, 0x3c, 0x77, 0xc1, 0xaa, 0xf0, 0xdb, 0x21, 0x1c, 0x06, + 0x0d, 0x53, 0xfa, 0x93, 0x0a, 0x7a, 0xd0, 0xd4, 0xe9, 0xa5, 0x1c, 0xb9, 0x33, 0x89, + ], ptx: concat!(include_str!("../ptx-sm86/native_head_native.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_session_native_rope.ptx", - key: [0x85, 0xb7, 0xef, 0x7c, 0xa5, 0x94, 0x3d, 0xbd, 0x71, 0x07, 0x10, 0x6b, 0x30, 0x29, 0xd5, 0x02, 0x7b, 0x46, 0x44, 0x14, 0x8d, 0x70, 0x05, 0xa4, 0x7d, 0xef, 0x7f, 0xa9, 0x01, 0xa3, 0xd7, 0x0a], + key: [ + 0x85, 0xb7, 0xef, 0x7c, 0xa5, 0x94, 0x3d, 0xbd, 0x71, 0x07, 0x10, 0x6b, 0x30, 0x29, 0xd5, 0x02, 0x7b, 0x46, + 0x44, 0x14, 0x8d, 0x70, 0x05, 0xa4, 0x7d, 0xef, 0x7f, 0xa9, 0x01, 0xa3, 0xd7, 0x0a, + ], len: 10518, - sha: [0x8e, 0x24, 0xc9, 0xe8, 0x0e, 0xe3, 0x11, 0xc7, 0x82, 0x77, 0x00, 0x77, 0x70, 0x3c, 0x7c, 0x11, 0x2a, 0x16, 0x3b, 0xb1, 0x12, 0x3c, 0x95, 0xb8, 0xc3, 0x12, 0x38, 0x0d, 0xf7, 0x14, 0x03, 0x25], + sha: [ + 0x8e, 0x24, 0xc9, 0xe8, 0x0e, 0xe3, 0x11, 0xc7, 0x82, 0x77, 0x00, 0x77, 0x70, 0x3c, 0x7c, 0x11, 0x2a, 0x16, + 0x3b, 0xb1, 0x12, 0x3c, 0x95, 0xb8, 0xc3, 0x12, 0x38, 0x0d, 0xf7, 0x14, 0x03, 0x25, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_session_native_rope.ptx"), "\0").as_bytes(), }, Companion { name: "native_head_sampler.ptx", - key: [0x86, 0x3d, 0xb1, 0x3d, 0xc6, 0x50, 0x23, 0x20, 0x6e, 0xb1, 0xa4, 0x5f, 0x29, 0xd4, 0xb9, 0x90, 0xa6, 0x59, 0x57, 0xba, 0x15, 0xd7, 0x83, 0xc2, 0x32, 0x9b, 0xbd, 0x88, 0xec, 0x61, 0x33, 0x3f], + key: [ + 0x86, 0x3d, 0xb1, 0x3d, 0xc6, 0x50, 0x23, 0x20, 0x6e, 0xb1, 0xa4, 0x5f, 0x29, 0xd4, 0xb9, 0x90, 0xa6, 0x59, + 0x57, 0xba, 0x15, 0xd7, 0x83, 0xc2, 0x32, 0x9b, 0xbd, 0x88, 0xec, 0x61, 0x33, 0x3f, + ], len: 497973, - sha: [0xe8, 0x64, 0x39, 0x00, 0x9f, 0x42, 0xe6, 0xbf, 0x64, 0xbf, 0xfa, 0xe8, 0x1c, 0xdc, 0x7e, 0xef, 0x69, 0x3f, 0xac, 0x9c, 0x09, 0x32, 0x80, 0x3f, 0xf0, 0x20, 0x8f, 0x85, 0x07, 0x1a, 0x86, 0x49], + sha: [ + 0xe8, 0x64, 0x39, 0x00, 0x9f, 0x42, 0xe6, 0xbf, 0x64, 0xbf, 0xfa, 0xe8, 0x1c, 0xdc, 0x7e, 0xef, 0x69, 0x3f, + 0xac, 0x9c, 0x09, 0x32, 0x80, 0x3f, 0xf0, 0x20, 0x8f, 0x85, 0x07, 0x1a, 0x86, 0x49, + ], ptx: concat!(include_str!("../ptx-sm86/native_head_sampler.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_resident_helpers.ptx", - key: [0x87, 0x0c, 0x6b, 0xc8, 0xa6, 0xec, 0x32, 0x0a, 0x05, 0x9c, 0x50, 0xbe, 0x9d, 0x5c, 0x96, 0x2f, 0xed, 0xec, 0x86, 0x63, 0x4d, 0x98, 0x8f, 0xc0, 0xe6, 0xb9, 0xd7, 0xed, 0xea, 0x11, 0x8d, 0x89], + key: [ + 0x87, 0x0c, 0x6b, 0xc8, 0xa6, 0xec, 0x32, 0x0a, 0x05, 0x9c, 0x50, 0xbe, 0x9d, 0x5c, 0x96, 0x2f, 0xed, 0xec, + 0x86, 0x63, 0x4d, 0x98, 0x8f, 0xc0, 0xe6, 0xb9, 0xd7, 0xed, 0xea, 0x11, 0x8d, 0x89, + ], len: 4045, - sha: [0x66, 0x8f, 0x35, 0x95, 0xce, 0x0d, 0xc7, 0x12, 0x77, 0x2b, 0x80, 0xbd, 0xa3, 0xb8, 0x5b, 0x5f, 0x05, 0xdd, 0x89, 0x23, 0x2a, 0x0a, 0x15, 0x00, 0x46, 0xff, 0x1f, 0xc4, 0xb1, 0x37, 0x90, 0x94], + sha: [ + 0x66, 0x8f, 0x35, 0x95, 0xce, 0x0d, 0xc7, 0x12, 0x77, 0x2b, 0x80, 0xbd, 0xa3, 0xb8, 0x5b, 0x5f, 0x05, 0xdd, + 0x89, 0x23, 0x2a, 0x0a, 0x15, 0x00, 0x46, 0xff, 0x1f, 0xc4, 0xb1, 0x37, 0x90, 0x94, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_resident_helpers.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_kv.ptx", - key: [0x87, 0xfd, 0x96, 0x69, 0xca, 0x28, 0x05, 0xe3, 0xaf, 0x3f, 0x97, 0x26, 0xb9, 0xd6, 0x92, 0x66, 0xda, 0xea, 0xc4, 0x17, 0x25, 0x31, 0x6a, 0x38, 0x23, 0x63, 0xc9, 0x56, 0xfd, 0x51, 0x04, 0x65], + key: [ + 0x87, 0xfd, 0x96, 0x69, 0xca, 0x28, 0x05, 0xe3, 0xaf, 0x3f, 0x97, 0x26, 0xb9, 0xd6, 0x92, 0x66, 0xda, 0xea, + 0xc4, 0x17, 0x25, 0x31, 0x6a, 0x38, 0x23, 0x63, 0xc9, 0x56, 0xfd, 0x51, 0x04, 0x65, + ], len: 12143, - sha: [0xad, 0xce, 0x0f, 0xc9, 0xb8, 0x5a, 0x2f, 0x60, 0x52, 0xcc, 0xd1, 0x13, 0x55, 0xf9, 0x11, 0x8b, 0x88, 0x63, 0x4e, 0x52, 0x31, 0x46, 0xe9, 0xfa, 0x8e, 0x1f, 0x86, 0xf0, 0xe8, 0xdb, 0x5b, 0x6c], + sha: [ + 0xad, 0xce, 0x0f, 0xc9, 0xb8, 0x5a, 0x2f, 0x60, 0x52, 0xcc, 0xd1, 0x13, 0x55, 0xf9, 0x11, 0x8b, 0x88, 0x63, + 0x4e, 0x52, 0x31, 0x46, 0xe9, 0xfa, 0x8e, 0x1f, 0x86, 0xf0, 0xe8, 0xdb, 0x5b, 0x6c, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_kv.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_gr_write.ptx", - key: [0x88, 0x1e, 0x38, 0xf0, 0xc9, 0x78, 0x6c, 0xed, 0x23, 0x8b, 0x7a, 0x00, 0x14, 0x8a, 0x2e, 0x16, 0xac, 0xff, 0x92, 0x7f, 0x7b, 0x8d, 0xe6, 0x6a, 0x1d, 0xd5, 0x83, 0xab, 0xf8, 0x1c, 0xf5, 0xb1], + key: [ + 0x88, 0x1e, 0x38, 0xf0, 0xc9, 0x78, 0x6c, 0xed, 0x23, 0x8b, 0x7a, 0x00, 0x14, 0x8a, 0x2e, 0x16, 0xac, 0xff, + 0x92, 0x7f, 0x7b, 0x8d, 0xe6, 0x6a, 0x1d, 0xd5, 0x83, 0xab, 0xf8, 0x1c, 0xf5, 0xb1, + ], len: 133910, - sha: [0x3b, 0xb1, 0x46, 0x0d, 0xe3, 0x5d, 0xa4, 0x42, 0x21, 0x7f, 0xf0, 0x35, 0x38, 0x7c, 0xaf, 0xc5, 0x33, 0x3a, 0x7d, 0x6b, 0x6c, 0x31, 0x16, 0xc5, 0x8a, 0xb3, 0x0a, 0xce, 0xd9, 0x62, 0x0c, 0xd1], + sha: [ + 0x3b, 0xb1, 0x46, 0x0d, 0xe3, 0x5d, 0xa4, 0x42, 0x21, 0x7f, 0xf0, 0x35, 0x38, 0x7c, 0xaf, 0xc5, 0x33, 0x3a, + 0x7d, 0x6b, 0x6c, 0x31, 0x16, 0xc5, 0x8a, 0xb3, 0x0a, 0xce, 0xd9, 0x62, 0x0c, 0xd1, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_gr_write.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_indexer.ptx", - key: [0x89, 0x15, 0x70, 0x0d, 0xd8, 0x1c, 0x99, 0x08, 0x3d, 0xe3, 0xcf, 0xf4, 0xed, 0x5d, 0x1a, 0x8b, 0x9a, 0x0c, 0x5d, 0xb1, 0x8c, 0x4d, 0x6d, 0xef, 0x9d, 0x49, 0xb3, 0xbb, 0xc8, 0xf2, 0x82, 0x30], + key: [ + 0x89, 0x15, 0x70, 0x0d, 0xd8, 0x1c, 0x99, 0x08, 0x3d, 0xe3, 0xcf, 0xf4, 0xed, 0x5d, 0x1a, 0x8b, 0x9a, 0x0c, + 0x5d, 0xb1, 0x8c, 0x4d, 0x6d, 0xef, 0x9d, 0x49, 0xb3, 0xbb, 0xc8, 0xf2, 0x82, 0x30, + ], len: 30560, - sha: [0x51, 0x62, 0x2e, 0x4f, 0x08, 0xa7, 0xe1, 0xfb, 0x52, 0x0f, 0xac, 0x0d, 0x0d, 0x8d, 0x2c, 0x3b, 0x61, 0xdc, 0xa1, 0x22, 0x70, 0x51, 0xaa, 0x14, 0xf6, 0xf7, 0x7d, 0xfc, 0x0a, 0xdf, 0x57, 0xad], + sha: [ + 0x51, 0x62, 0x2e, 0x4f, 0x08, 0xa7, 0xe1, 0xfb, 0x52, 0x0f, 0xac, 0x0d, 0x0d, 0x8d, 0x2c, 0x3b, 0x61, 0xdc, + 0xa1, 0x22, 0x70, 0x51, 0xaa, 0x14, 0xf6, 0xf7, 0x7d, 0xfc, 0x0a, 0xdf, 0x57, 0xad, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_indexer.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_resolver.ptx", - key: [0x8d, 0x3e, 0xcb, 0xae, 0xcb, 0xf2, 0x84, 0x45, 0xba, 0x64, 0x48, 0x5b, 0xdf, 0xf3, 0xd9, 0x1a, 0x21, 0xd8, 0x7b, 0x85, 0xd5, 0x93, 0x9a, 0x01, 0x52, 0xef, 0x2f, 0x24, 0x14, 0x48, 0x0e, 0x22], + key: [ + 0x8d, 0x3e, 0xcb, 0xae, 0xcb, 0xf2, 0x84, 0x45, 0xba, 0x64, 0x48, 0x5b, 0xdf, 0xf3, 0xd9, 0x1a, 0x21, 0xd8, + 0x7b, 0x85, 0xd5, 0x93, 0x9a, 0x01, 0x52, 0xef, 0x2f, 0x24, 0x14, 0x48, 0x0e, 0x22, + ], len: 23915, - sha: [0x32, 0xd9, 0x6c, 0xa6, 0xa7, 0x2f, 0x40, 0xed, 0xa2, 0x1d, 0x51, 0xd9, 0xf4, 0xd4, 0xd3, 0x77, 0xc3, 0x73, 0xc6, 0x37, 0x83, 0xcc, 0x42, 0x29, 0x10, 0x88, 0x3b, 0xb8, 0xd8, 0xd8, 0xb0, 0x8d], + sha: [ + 0x32, 0xd9, 0x6c, 0xa6, 0xa7, 0x2f, 0x40, 0xed, 0xa2, 0x1d, 0x51, 0xd9, 0xf4, 0xd4, 0xd3, 0x77, 0xc3, 0x73, + 0xc6, 0x37, 0x83, 0xcc, 0x42, 0x29, 0x10, 0x88, 0x3b, 0xb8, 0xd8, 0xd8, 0xb0, 0x8d, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_resolver.ptx"), "\0").as_bytes(), }, Companion { name: "q2_0_q8_1.ptx", - key: [0x8e, 0x81, 0xdb, 0xba, 0xa7, 0x6d, 0x85, 0x16, 0x47, 0x63, 0x39, 0xc1, 0x68, 0xf1, 0xd9, 0xc1, 0x72, 0x34, 0x1a, 0x78, 0xcc, 0xec, 0xda, 0x08, 0x71, 0x4a, 0x13, 0xa5, 0x68, 0x7e, 0x3b, 0x6e], + key: [ + 0x8e, 0x81, 0xdb, 0xba, 0xa7, 0x6d, 0x85, 0x16, 0x47, 0x63, 0x39, 0xc1, 0x68, 0xf1, 0xd9, 0xc1, 0x72, 0x34, + 0x1a, 0x78, 0xcc, 0xec, 0xda, 0x08, 0x71, 0x4a, 0x13, 0xa5, 0x68, 0x7e, 0x3b, 0x6e, + ], len: 18542, - sha: [0x8a, 0x25, 0x1c, 0x65, 0x02, 0x31, 0xac, 0x07, 0xa0, 0xce, 0xa8, 0xdd, 0xa2, 0x12, 0xbb, 0x84, 0xd1, 0xcf, 0x5c, 0xa3, 0x72, 0xf6, 0x30, 0xce, 0x03, 0x23, 0x81, 0xe0, 0x18, 0xce, 0x59, 0xf5], + sha: [ + 0x8a, 0x25, 0x1c, 0x65, 0x02, 0x31, 0xac, 0x07, 0xa0, 0xce, 0xa8, 0xdd, 0xa2, 0x12, 0xbb, 0x84, 0xd1, 0xcf, + 0x5c, 0xa3, 0x72, 0xf6, 0x30, 0xce, 0x03, 0x23, 0x81, 0xe0, 0x18, 0xce, 0x59, 0xf5, + ], ptx: concat!(include_str!("../ptx-sm86/q2_0_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_element.ptx", - key: [0x8f, 0xdf, 0xdf, 0x8e, 0xf6, 0x16, 0x69, 0x8c, 0x12, 0x30, 0x1f, 0x7d, 0xf4, 0x71, 0x6f, 0xc0, 0x22, 0xbf, 0x34, 0xb4, 0x19, 0x09, 0x9e, 0x4c, 0x97, 0x27, 0x29, 0x92, 0x0b, 0xd5, 0xf4, 0xa7], + key: [ + 0x8f, 0xdf, 0xdf, 0x8e, 0xf6, 0x16, 0x69, 0x8c, 0x12, 0x30, 0x1f, 0x7d, 0xf4, 0x71, 0x6f, 0xc0, 0x22, 0xbf, + 0x34, 0xb4, 0x19, 0x09, 0x9e, 0x4c, 0x97, 0x27, 0x29, 0x92, 0x0b, 0xd5, 0xf4, 0xa7, + ], len: 54956, - sha: [0xe3, 0xd7, 0x50, 0x63, 0x73, 0xa9, 0x30, 0x1c, 0x4d, 0x0e, 0xbd, 0x40, 0x13, 0x17, 0x2c, 0xce, 0x60, 0x91, 0xfc, 0xd5, 0x87, 0xb2, 0xad, 0xc3, 0x54, 0x1b, 0x6a, 0x55, 0xb9, 0xd5, 0xf1, 0xfd], + sha: [ + 0xe3, 0xd7, 0x50, 0x63, 0x73, 0xa9, 0x30, 0x1c, 0x4d, 0x0e, 0xbd, 0x40, 0x13, 0x17, 0x2c, 0xce, 0x60, 0x91, + 0xfc, 0xd5, 0x87, 0xb2, 0xad, 0xc3, 0x54, 0x1b, 0x6a, 0x55, 0xb9, 0xd5, 0xf1, 0xfd, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_element.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_prompt_attention_variants.ptx", - key: [0x90, 0x41, 0xe2, 0x50, 0xf6, 0xff, 0xca, 0x2f, 0x84, 0x9c, 0x20, 0x60, 0x5a, 0x3f, 0x75, 0x8c, 0x54, 0xf7, 0x85, 0x6e, 0x7c, 0xd0, 0x15, 0xc8, 0xa1, 0xda, 0x66, 0x25, 0x04, 0x8d, 0x6a, 0xac], + key: [ + 0x90, 0x41, 0xe2, 0x50, 0xf6, 0xff, 0xca, 0x2f, 0x84, 0x9c, 0x20, 0x60, 0x5a, 0x3f, 0x75, 0x8c, 0x54, 0xf7, + 0x85, 0x6e, 0x7c, 0xd0, 0x15, 0xc8, 0xa1, 0xda, 0x66, 0x25, 0x04, 0x8d, 0x6a, 0xac, + ], len: 216290, - sha: [0xa3, 0xe4, 0xd6, 0x97, 0x57, 0x88, 0xd1, 0x26, 0x72, 0xe3, 0x85, 0x5e, 0x5e, 0x9f, 0x16, 0x56, 0x0d, 0x3d, 0x82, 0x63, 0xb7, 0x52, 0x16, 0xaa, 0xf0, 0x89, 0x5c, 0x57, 0x98, 0x70, 0xbb, 0x7d], + sha: [ + 0xa3, 0xe4, 0xd6, 0x97, 0x57, 0x88, 0xd1, 0x26, 0x72, 0xe3, 0x85, 0x5e, 0x5e, 0x9f, 0x16, 0x56, 0x0d, 0x3d, + 0x82, 0x63, 0xb7, 0x52, 0x16, 0xaa, 0xf0, 0x89, 0x5c, 0x57, 0x98, 0x70, 0xbb, 0x7d, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_prompt_attention_variants.ptx"), "\0").as_bytes(), }, Companion { name: "qwen_qsa_attention.ptx", - key: [0x91, 0x21, 0x9c, 0xfb, 0xc1, 0xa7, 0x7c, 0x4b, 0xb6, 0x66, 0x61, 0x06, 0x0a, 0xc9, 0x39, 0xa5, 0x0d, 0xc4, 0xc4, 0xd7, 0xd4, 0xdb, 0x8d, 0x50, 0xbc, 0x59, 0xfb, 0xcd, 0x16, 0x75, 0x62, 0xb2], + key: [ + 0x91, 0x21, 0x9c, 0xfb, 0xc1, 0xa7, 0x7c, 0x4b, 0xb6, 0x66, 0x61, 0x06, 0x0a, 0xc9, 0x39, 0xa5, 0x0d, 0xc4, + 0xc4, 0xd7, 0xd4, 0xdb, 0x8d, 0x50, 0xbc, 0x59, 0xfb, 0xcd, 0x16, 0x75, 0x62, 0xb2, + ], len: 26737, - sha: [0xc1, 0x11, 0xc6, 0x12, 0x6a, 0x3a, 0x67, 0x5e, 0xc8, 0x87, 0x20, 0x88, 0x1d, 0x46, 0x99, 0xa6, 0xe7, 0x21, 0x84, 0xd2, 0xf4, 0x55, 0x87, 0x9a, 0xe0, 0x85, 0x5c, 0x56, 0xb8, 0x48, 0xbe, 0xa1], + sha: [ + 0xc1, 0x11, 0xc6, 0x12, 0x6a, 0x3a, 0x67, 0x5e, 0xc8, 0x87, 0x20, 0x88, 0x1d, 0x46, 0x99, 0xa6, 0xe7, 0x21, + 0x84, 0xd2, 0xf4, 0x55, 0x87, 0x9a, 0xe0, 0x85, 0x5c, 0x56, 0xb8, 0x48, 0xbe, 0xa1, + ], ptx: concat!(include_str!("../ptx-sm86/qwen_qsa_attention.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_down_q2_0.ptx", - key: [0x94, 0x7d, 0x08, 0xc4, 0x10, 0x9a, 0x19, 0x7a, 0xa1, 0xfa, 0xfc, 0xa4, 0xe8, 0xc9, 0x82, 0x3c, 0x91, 0xa8, 0xbd, 0xa0, 0x34, 0xb1, 0x62, 0x79, 0x2c, 0x83, 0x9a, 0x67, 0x97, 0x55, 0x19, 0xda], + key: [ + 0x94, 0x7d, 0x08, 0xc4, 0x10, 0x9a, 0x19, 0x7a, 0xa1, 0xfa, 0xfc, 0xa4, 0xe8, 0xc9, 0x82, 0x3c, 0x91, 0xa8, + 0xbd, 0xa0, 0x34, 0xb1, 0x62, 0x79, 0x2c, 0x83, 0x9a, 0x67, 0x97, 0x55, 0x19, 0xda, + ], len: 13458, - sha: [0xfc, 0x1a, 0xfa, 0x0b, 0x72, 0x43, 0x38, 0xd9, 0x31, 0x48, 0x1f, 0x41, 0x61, 0x6b, 0x8d, 0x25, 0x1f, 0x15, 0x0d, 0x06, 0x5d, 0x91, 0x15, 0x1a, 0x77, 0x12, 0xf9, 0xa9, 0x41, 0xce, 0x25, 0x4f], + sha: [ + 0xfc, 0x1a, 0xfa, 0x0b, 0x72, 0x43, 0x38, 0xd9, 0x31, 0x48, 0x1f, 0x41, 0x61, 0x6b, 0x8d, 0x25, 0x1f, 0x15, + 0x0d, 0x06, 0x5d, 0x91, 0x15, 0x1a, 0x77, 0x12, 0xf9, 0xa9, 0x41, 0xce, 0x25, 0x4f, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_down_q2_0.ptx"), "\0").as_bytes(), }, Companion { name: "iq3_s_q8_1.ptx", - key: [0x94, 0xf7, 0x98, 0xc0, 0x08, 0x13, 0xc2, 0xfb, 0x86, 0x0b, 0x4b, 0xf7, 0x7b, 0xe9, 0x22, 0x57, 0x67, 0xd4, 0x08, 0x95, 0x5e, 0x34, 0x21, 0x33, 0x0a, 0xc3, 0x4a, 0x4e, 0xbd, 0x43, 0x97, 0x8f], + key: [ + 0x94, 0xf7, 0x98, 0xc0, 0x08, 0x13, 0xc2, 0xfb, 0x86, 0x0b, 0x4b, 0xf7, 0x7b, 0xe9, 0x22, 0x57, 0x67, 0xd4, + 0x08, 0x95, 0x5e, 0x34, 0x21, 0x33, 0x0a, 0xc3, 0x4a, 0x4e, 0xbd, 0x43, 0x97, 0x8f, + ], len: 24712, - sha: [0xb1, 0x98, 0x60, 0x07, 0x0e, 0x69, 0xdc, 0xcd, 0x5e, 0x98, 0xd1, 0xe6, 0xbc, 0x7c, 0xdd, 0xcd, 0xa2, 0x92, 0x8e, 0xfb, 0xd3, 0xf0, 0xbd, 0x21, 0x56, 0x8f, 0xd1, 0xae, 0x7d, 0x4a, 0xe9, 0x27], + sha: [ + 0xb1, 0x98, 0x60, 0x07, 0x0e, 0x69, 0xdc, 0xcd, 0x5e, 0x98, 0xd1, 0xe6, 0xbc, 0x7c, 0xdd, 0xcd, 0xa2, 0x92, + 0x8e, 0xfb, 0xd3, 0xf0, 0xbd, 0x21, 0x56, 0x8f, 0xd1, 0xae, 0x7d, 0x4a, 0xe9, 0x27, + ], ptx: concat!(include_str!("../ptx-sm86/iq3_s_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_gr_post.ptx", - key: [0x9b, 0x47, 0x9c, 0x0f, 0x41, 0x2a, 0xe0, 0x07, 0x73, 0x81, 0x5c, 0x9a, 0x6d, 0x89, 0xd7, 0xf4, 0xc3, 0xf7, 0xa9, 0xf0, 0xf6, 0x91, 0x87, 0x6d, 0xe8, 0x05, 0xeb, 0x38, 0x17, 0x8d, 0x97, 0x90], + key: [ + 0x9b, 0x47, 0x9c, 0x0f, 0x41, 0x2a, 0xe0, 0x07, 0x73, 0x81, 0x5c, 0x9a, 0x6d, 0x89, 0xd7, 0xf4, 0xc3, 0xf7, + 0xa9, 0xf0, 0xf6, 0x91, 0x87, 0x6d, 0xe8, 0x05, 0xeb, 0x38, 0x17, 0x8d, 0x97, 0x90, + ], len: 35821, - sha: [0x77, 0x93, 0x32, 0x2e, 0x19, 0x00, 0x2f, 0xe8, 0x19, 0x97, 0xbc, 0xab, 0x03, 0xb9, 0xf4, 0xce, 0xd6, 0xce, 0x07, 0x62, 0xde, 0x88, 0x6b, 0xed, 0xe9, 0xbb, 0x11, 0xa9, 0xd3, 0x80, 0xf6, 0x4c], + sha: [ + 0x77, 0x93, 0x32, 0x2e, 0x19, 0x00, 0x2f, 0xe8, 0x19, 0x97, 0xbc, 0xab, 0x03, 0xb9, 0xf4, 0xce, 0xd6, 0xce, + 0x07, 0x62, 0xde, 0x88, 0x6b, 0xed, 0xe9, 0xbb, 0x11, 0xa9, 0xd3, 0x80, 0xf6, 0x4c, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_gr_post.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_native_batch.ptx", - key: [0x9b, 0xa6, 0x85, 0x23, 0xb6, 0x7a, 0x0e, 0x3b, 0x80, 0xfc, 0x16, 0x7b, 0x97, 0x30, 0x19, 0x63, 0xcf, 0x15, 0x98, 0x12, 0xcd, 0x15, 0x7f, 0x03, 0xc5, 0xa0, 0x2b, 0x69, 0xfd, 0xa2, 0x2f, 0xc7], + key: [ + 0x9b, 0xa6, 0x85, 0x23, 0xb6, 0x7a, 0x0e, 0x3b, 0x80, 0xfc, 0x16, 0x7b, 0x97, 0x30, 0x19, 0x63, 0xcf, 0x15, + 0x98, 0x12, 0xcd, 0x15, 0x7f, 0x03, 0xc5, 0xa0, 0x2b, 0x69, 0xfd, 0xa2, 0x2f, 0xc7, + ], len: 4566, - sha: [0xcb, 0xf1, 0x3c, 0x31, 0x7b, 0x78, 0x84, 0x54, 0x28, 0xc9, 0x86, 0xe9, 0xa9, 0xbf, 0xc0, 0x47, 0x53, 0x30, 0x29, 0x55, 0x51, 0x3a, 0x4a, 0xfd, 0x11, 0xf1, 0x39, 0xf2, 0x62, 0x22, 0xb6, 0xff], + sha: [ + 0xcb, 0xf1, 0x3c, 0x31, 0x7b, 0x78, 0x84, 0x54, 0x28, 0xc9, 0x86, 0xe9, 0xa9, 0xbf, 0xc0, 0x47, 0x53, 0x30, + 0x29, 0x55, 0x51, 0x3a, 0x4a, 0xfd, 0x11, 0xf1, 0x39, 0xf2, 0x62, 0x22, 0xb6, 0xff, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_native_batch.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_session_legacy_rope.ptx", - key: [0x9b, 0xba, 0x3b, 0x35, 0x85, 0x0c, 0xe3, 0x86, 0x9e, 0x32, 0xc5, 0x6c, 0x9d, 0xe6, 0x6a, 0x06, 0x52, 0x69, 0x11, 0x88, 0xf4, 0xc7, 0xff, 0x1d, 0xc4, 0xb1, 0xee, 0x9b, 0x2f, 0x9d, 0x0d, 0x9f], + key: [ + 0x9b, 0xba, 0x3b, 0x35, 0x85, 0x0c, 0xe3, 0x86, 0x9e, 0x32, 0xc5, 0x6c, 0x9d, 0xe6, 0x6a, 0x06, 0x52, 0x69, + 0x11, 0x88, 0xf4, 0xc7, 0xff, 0x1d, 0xc4, 0xb1, 0xee, 0x9b, 0x2f, 0x9d, 0x0d, 0x9f, + ], len: 12202, - sha: [0x25, 0x7e, 0x32, 0x1a, 0xbe, 0xa3, 0x30, 0x92, 0x6b, 0x29, 0x9a, 0x6a, 0x03, 0x03, 0x0d, 0x4c, 0xd2, 0xdf, 0x98, 0xe1, 0xf9, 0x7f, 0xfe, 0x07, 0x2d, 0xc1, 0x83, 0xc1, 0x1c, 0x5b, 0x9d, 0xe7], + sha: [ + 0x25, 0x7e, 0x32, 0x1a, 0xbe, 0xa3, 0x30, 0x92, 0x6b, 0x29, 0x9a, 0x6a, 0x03, 0x03, 0x0d, 0x4c, 0xd2, 0xdf, + 0x98, 0xe1, 0xf9, 0x7f, 0xfe, 0x07, 0x2d, 0xc1, 0x83, 0xc1, 0x1c, 0x5b, 0x9d, 0xe7, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_session_legacy_rope.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_qnorm.ptx", - key: [0xa0, 0xbc, 0xfe, 0xbd, 0x6b, 0xf4, 0x77, 0xcd, 0x3a, 0xd1, 0x36, 0x07, 0xe2, 0xf0, 0x1f, 0x3c, 0x0a, 0x9e, 0x4c, 0x70, 0x22, 0x87, 0x21, 0x36, 0x20, 0xd9, 0x1c, 0x89, 0xb9, 0x29, 0x8e, 0xb1], + key: [ + 0xa0, 0xbc, 0xfe, 0xbd, 0x6b, 0xf4, 0x77, 0xcd, 0x3a, 0xd1, 0x36, 0x07, 0xe2, 0xf0, 0x1f, 0x3c, 0x0a, 0x9e, + 0x4c, 0x70, 0x22, 0x87, 0x21, 0x36, 0x20, 0xd9, 0x1c, 0x89, 0xb9, 0x29, 0x8e, 0xb1, + ], len: 36079, - sha: [0x0f, 0x71, 0xc4, 0x60, 0xd4, 0x0a, 0x3e, 0xfb, 0xc4, 0x68, 0xba, 0xc3, 0x4b, 0xb9, 0x3f, 0x62, 0xa7, 0x17, 0x37, 0xd7, 0x28, 0x31, 0x92, 0x17, 0x5c, 0xff, 0x7e, 0x13, 0x32, 0x38, 0x20, 0x7f], + sha: [ + 0x0f, 0x71, 0xc4, 0x60, 0xd4, 0x0a, 0x3e, 0xfb, 0xc4, 0x68, 0xba, 0xc3, 0x4b, 0xb9, 0x3f, 0x62, 0xa7, 0x17, + 0x37, 0xd7, 0x28, 0x31, 0x92, 0x17, 0x5c, 0xff, 0x7e, 0x13, 0x32, 0x38, 0x20, 0x7f, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_qnorm.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_bf16.ptx", - key: [0xa1, 0x6d, 0xfc, 0xfc, 0x9a, 0x49, 0xcc, 0xab, 0x25, 0xd8, 0x03, 0x02, 0x93, 0xd5, 0x82, 0x6f, 0x8f, 0x75, 0xe2, 0x86, 0x8f, 0xae, 0x1b, 0x6c, 0x4c, 0xef, 0x70, 0x6b, 0x6d, 0xfc, 0x3d, 0x08], + key: [ + 0xa1, 0x6d, 0xfc, 0xfc, 0x9a, 0x49, 0xcc, 0xab, 0x25, 0xd8, 0x03, 0x02, 0x93, 0xd5, 0x82, 0x6f, 0x8f, 0x75, + 0xe2, 0x86, 0x8f, 0xae, 0x1b, 0x6c, 0x4c, 0xef, 0x70, 0x6b, 0x6d, 0xfc, 0x3d, 0x08, + ], len: 461120, - sha: [0x07, 0xf4, 0xde, 0x80, 0xcb, 0xb0, 0xdc, 0x7d, 0xc2, 0xb7, 0x5f, 0x75, 0x6e, 0x24, 0x1b, 0x30, 0x89, 0xd3, 0xcd, 0x97, 0xc7, 0x33, 0x6a, 0xe5, 0xf6, 0xbe, 0x0f, 0xa6, 0x42, 0x78, 0x3d, 0x81], + sha: [ + 0x07, 0xf4, 0xde, 0x80, 0xcb, 0xb0, 0xdc, 0x7d, 0xc2, 0xb7, 0x5f, 0x75, 0x6e, 0x24, 0x1b, 0x30, 0x89, 0xd3, + 0xcd, 0x97, 0xc7, 0x33, 0x6a, 0xe5, 0xf6, 0xbe, 0x0f, 0xa6, 0x42, 0x78, 0x3d, 0x81, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_bf16.ptx"), "\0").as_bytes(), }, Companion { name: "iq2_s_q8_1.ptx", - key: [0xa3, 0x1e, 0x65, 0x3d, 0xa8, 0xc2, 0x22, 0xe1, 0x67, 0x1c, 0xf2, 0x5e, 0xd1, 0x90, 0x17, 0xee, 0xb0, 0xb3, 0xef, 0x4d, 0x89, 0x0c, 0x01, 0x42, 0xb1, 0x81, 0xf3, 0xd5, 0xbc, 0xfc, 0xfb, 0x2c], + key: [ + 0xa3, 0x1e, 0x65, 0x3d, 0xa8, 0xc2, 0x22, 0xe1, 0x67, 0x1c, 0xf2, 0x5e, 0xd1, 0x90, 0x17, 0xee, 0xb0, 0xb3, + 0xef, 0x4d, 0x89, 0x0c, 0x01, 0x42, 0xb1, 0x81, 0xf3, 0xd5, 0xbc, 0xfc, 0xfb, 0x2c, + ], len: 46912, - sha: [0xc6, 0xca, 0xe7, 0xc0, 0x39, 0x61, 0x79, 0x04, 0x0b, 0x0c, 0x88, 0xf3, 0xce, 0xbd, 0x24, 0x70, 0xdf, 0x92, 0x69, 0xad, 0x5d, 0xc6, 0x6e, 0x9e, 0x22, 0x7f, 0x60, 0x0d, 0x1e, 0x79, 0xed, 0x9b], + sha: [ + 0xc6, 0xca, 0xe7, 0xc0, 0x39, 0x61, 0x79, 0x04, 0x0b, 0x0c, 0x88, 0xf3, 0xce, 0xbd, 0x24, 0x70, 0xdf, 0x92, + 0x69, 0xad, 0x5d, 0xc6, 0x6e, 0x9e, 0x22, 0x7f, 0x60, 0x0d, 0x1e, 0x79, 0xed, 0x9b, + ], ptx: concat!(include_str!("../ptx-sm86/iq2_s_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "chain_window.ptx", - key: [0xa3, 0xab, 0xdc, 0x41, 0x86, 0xb6, 0x6d, 0x51, 0xa8, 0x0c, 0x8e, 0xf5, 0x2f, 0x63, 0x6f, 0x18, 0x93, 0xa2, 0x13, 0x6b, 0x88, 0x7c, 0xd6, 0x54, 0x87, 0x86, 0xfe, 0xa2, 0x79, 0xef, 0x71, 0xba], + key: [ + 0xa3, 0xab, 0xdc, 0x41, 0x86, 0xb6, 0x6d, 0x51, 0xa8, 0x0c, 0x8e, 0xf5, 0x2f, 0x63, 0x6f, 0x18, 0x93, 0xa2, + 0x13, 0x6b, 0x88, 0x7c, 0xd6, 0x54, 0x87, 0x86, 0xfe, 0xa2, 0x79, 0xef, 0x71, 0xba, + ], len: 2336938, - sha: [0x36, 0x1e, 0x11, 0x00, 0xad, 0x58, 0xb9, 0xa2, 0x1b, 0xe3, 0xd9, 0x58, 0xef, 0x55, 0x59, 0xe7, 0x0b, 0x72, 0xf2, 0xd0, 0x4e, 0x15, 0xdb, 0x5e, 0x9d, 0xbc, 0x14, 0xd1, 0x21, 0xe0, 0xee, 0x43], + sha: [ + 0x36, 0x1e, 0x11, 0x00, 0xad, 0x58, 0xb9, 0xa2, 0x1b, 0xe3, 0xd9, 0x58, 0xef, 0x55, 0x59, 0xe7, 0x0b, 0x72, + 0xf2, 0xd0, 0x4e, 0x15, 0xdb, 0x5e, 0x9d, 0xbc, 0x14, 0xd1, 0x21, 0xe0, 0xee, 0x43, + ], ptx: concat!(include_str!("../ptx-sm86/chain_window.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_router_legacy.ptx", - key: [0xa5, 0x84, 0x12, 0x24, 0x97, 0x57, 0xcc, 0x35, 0x1e, 0xb8, 0x33, 0x2e, 0x80, 0x7e, 0x79, 0xf1, 0xb3, 0xda, 0x58, 0x65, 0x57, 0x4d, 0x0f, 0xb7, 0x17, 0x9e, 0xf5, 0x58, 0xdf, 0x70, 0xaf, 0x24], + key: [ + 0xa5, 0x84, 0x12, 0x24, 0x97, 0x57, 0xcc, 0x35, 0x1e, 0xb8, 0x33, 0x2e, 0x80, 0x7e, 0x79, 0xf1, 0xb3, 0xda, + 0x58, 0x65, 0x57, 0x4d, 0x0f, 0xb7, 0x17, 0x9e, 0xf5, 0x58, 0xdf, 0x70, 0xaf, 0x24, + ], len: 159038, - sha: [0xa9, 0x2b, 0xf0, 0xc3, 0xfc, 0x4c, 0xc5, 0x31, 0x2c, 0x14, 0xa5, 0x52, 0xf7, 0x24, 0x4d, 0x4a, 0x7e, 0x10, 0x26, 0xbb, 0x79, 0x32, 0xb0, 0x56, 0x1d, 0x73, 0x57, 0xd8, 0xec, 0x41, 0x72, 0x7f], + sha: [ + 0xa9, 0x2b, 0xf0, 0xc3, 0xfc, 0x4c, 0xc5, 0x31, 0x2c, 0x14, 0xa5, 0x52, 0xf7, 0x24, 0x4d, 0x4a, 0x7e, 0x10, + 0x26, 0xbb, 0x79, 0x32, 0xb0, 0x56, 0x1d, 0x73, 0x57, 0xd8, 0xec, 0x41, 0x72, 0x7f, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_router_legacy.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-original-formats-fixup.ptx", - key: [0xa6, 0x6a, 0x85, 0x6c, 0xe4, 0x97, 0x82, 0x20, 0xbb, 0xb0, 0x12, 0x57, 0xf3, 0x34, 0xe4, 0x48, 0x46, 0xce, 0xb3, 0x4d, 0x5d, 0xc3, 0x06, 0xdf, 0xbe, 0xba, 0x95, 0x65, 0x7e, 0x05, 0x0b, 0xf3], + key: [ + 0xa6, 0x6a, 0x85, 0x6c, 0xe4, 0x97, 0x82, 0x20, 0xbb, 0xb0, 0x12, 0x57, 0xf3, 0x34, 0xe4, 0x48, 0x46, 0xce, + 0xb3, 0x4d, 0x5d, 0xc3, 0x06, 0xdf, 0xbe, 0xba, 0x95, 0x65, 0x7e, 0x05, 0x0b, 0xf3, + ], len: 309892, - sha: [0xd2, 0x16, 0x69, 0x31, 0xf0, 0x54, 0x52, 0xde, 0x65, 0xed, 0x06, 0xd1, 0xb0, 0x60, 0xa9, 0x4c, 0x27, 0xa8, 0x68, 0x8e, 0xf5, 0x9b, 0x5f, 0xfc, 0x96, 0x08, 0x69, 0x64, 0x7a, 0x44, 0x84, 0x8b], + sha: [ + 0xd2, 0x16, 0x69, 0x31, 0xf0, 0x54, 0x52, 0xde, 0x65, 0xed, 0x06, 0xd1, 0xb0, 0x60, 0xa9, 0x4c, 0x27, 0xa8, + 0x68, 0x8e, 0xf5, 0x9b, 0x5f, 0xfc, 0x96, 0x08, 0x69, 0x64, 0x7a, 0x44, 0x84, 0x8b, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-original-formats-fixup.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_original_group_fixup.ptx", - key: [0xa8, 0xc7, 0x51, 0x91, 0xba, 0x8e, 0xf7, 0xa4, 0x57, 0x20, 0x82, 0x48, 0x50, 0xd6, 0x4c, 0xf4, 0x43, 0x45, 0x9b, 0x30, 0xbc, 0x53, 0x79, 0xab, 0x80, 0x7e, 0xb8, 0x3e, 0x26, 0x14, 0x88, 0x3f], + key: [ + 0xa8, 0xc7, 0x51, 0x91, 0xba, 0x8e, 0xf7, 0xa4, 0x57, 0x20, 0x82, 0x48, 0x50, 0xd6, 0x4c, 0xf4, 0x43, 0x45, + 0x9b, 0x30, 0xbc, 0x53, 0x79, 0xab, 0x80, 0x7e, 0xb8, 0x3e, 0x26, 0x14, 0x88, 0x3f, + ], len: 1455508, - sha: [0x18, 0xc9, 0x1c, 0x0f, 0x77, 0x48, 0x36, 0xd9, 0xcd, 0xc6, 0xee, 0x49, 0x8f, 0x3f, 0x3d, 0x66, 0x2b, 0x40, 0x07, 0x77, 0x39, 0x95, 0x29, 0xa4, 0x38, 0xf7, 0xae, 0x27, 0x67, 0x10, 0xf2, 0x04], + sha: [ + 0x18, 0xc9, 0x1c, 0x0f, 0x77, 0x48, 0x36, 0xd9, 0xcd, 0xc6, 0xee, 0x49, 0x8f, 0x3f, 0x3d, 0x66, 0x2b, 0x40, + 0x07, 0x77, 0x39, 0x95, 0x29, 0xa4, 0x38, 0xf7, 0xae, 0x27, 0x67, 0x10, 0xf2, 0x04, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_original_group_fixup.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_original_group_swiglu.ptx", - key: [0xa9, 0x13, 0x99, 0x36, 0x00, 0x87, 0x8c, 0xed, 0xd1, 0x28, 0xbe, 0xe0, 0xf7, 0x76, 0x89, 0x51, 0x19, 0xe5, 0x56, 0xe3, 0x3f, 0x2a, 0xd7, 0x0d, 0xad, 0xf0, 0x8e, 0x9e, 0x1a, 0x7e, 0xb9, 0xbd], + key: [ + 0xa9, 0x13, 0x99, 0x36, 0x00, 0x87, 0x8c, 0xed, 0xd1, 0x28, 0xbe, 0xe0, 0xf7, 0x76, 0x89, 0x51, 0x19, 0xe5, + 0x56, 0xe3, 0x3f, 0x2a, 0xd7, 0x0d, 0xad, 0xf0, 0x8e, 0x9e, 0x1a, 0x7e, 0xb9, 0xbd, + ], len: 6090, - sha: [0x7a, 0x34, 0x2b, 0xa9, 0x78, 0x1d, 0x0f, 0xdb, 0x63, 0x66, 0xc1, 0xb5, 0xbf, 0xd0, 0x65, 0xaa, 0x40, 0x05, 0xfd, 0x3f, 0x3d, 0x19, 0x5d, 0xaf, 0x0f, 0x2f, 0x0f, 0x64, 0x7d, 0x71, 0xe9, 0xec], + sha: [ + 0x7a, 0x34, 0x2b, 0xa9, 0x78, 0x1d, 0x0f, 0xdb, 0x63, 0x66, 0xc1, 0xb5, 0xbf, 0xd0, 0x65, 0xaa, 0x40, 0x05, + 0xfd, 0x3f, 0x3d, 0x19, 0x5d, 0xaf, 0x0f, 0x2f, 0x0f, 0x64, 0x7d, 0x71, 0xe9, 0xec, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_original_group_swiglu.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_fused_gr.ptx", - key: [0xac, 0x54, 0x00, 0xa7, 0x97, 0x2b, 0x3f, 0x24, 0x26, 0x48, 0xc2, 0xde, 0x71, 0xef, 0x4f, 0x17, 0x84, 0x66, 0xd3, 0x8b, 0x13, 0x92, 0xa8, 0x3a, 0x95, 0x91, 0xb3, 0xb2, 0x4e, 0x92, 0xc5, 0x9b], + key: [ + 0xac, 0x54, 0x00, 0xa7, 0x97, 0x2b, 0x3f, 0x24, 0x26, 0x48, 0xc2, 0xde, 0x71, 0xef, 0x4f, 0x17, 0x84, 0x66, + 0xd3, 0x8b, 0x13, 0x92, 0xa8, 0x3a, 0x95, 0x91, 0xb3, 0xb2, 0x4e, 0x92, 0xc5, 0x9b, + ], len: 422848, - sha: [0xe4, 0xc8, 0xcc, 0xbb, 0xfb, 0x68, 0x26, 0x7c, 0xa0, 0xba, 0xc4, 0xfd, 0xbd, 0x91, 0x04, 0x22, 0xa3, 0x16, 0x87, 0x0b, 0x0f, 0x79, 0x9c, 0x48, 0x52, 0x9c, 0x8a, 0x9d, 0xb9, 0xea, 0xa8, 0xe6], + sha: [ + 0xe4, 0xc8, 0xcc, 0xbb, 0xfb, 0x68, 0x26, 0x7c, 0xa0, 0xba, 0xc4, 0xfd, 0xbd, 0x91, 0x04, 0x22, 0xa3, 0x16, + 0x87, 0x0b, 0x0f, 0x79, 0x9c, 0x48, 0x52, 0x9c, 0x8a, 0x9d, 0xb9, 0xea, 0xa8, 0xe6, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_fused_gr.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_fixed.ptx", - key: [0xad, 0xa8, 0x7a, 0x1b, 0xd6, 0xff, 0x2f, 0x60, 0x13, 0xd2, 0xbd, 0x64, 0x1a, 0x37, 0x86, 0xeb, 0x46, 0xb9, 0xc9, 0xfc, 0xf3, 0x58, 0x6c, 0x66, 0x60, 0x9c, 0x8e, 0xee, 0xa4, 0xb1, 0x07, 0xe8], + key: [ + 0xad, 0xa8, 0x7a, 0x1b, 0xd6, 0xff, 0x2f, 0x60, 0x13, 0xd2, 0xbd, 0x64, 0x1a, 0x37, 0x86, 0xeb, 0x46, 0xb9, + 0xc9, 0xfc, 0xf3, 0x58, 0x6c, 0x66, 0x60, 0x9c, 0x8e, 0xee, 0xa4, 0xb1, 0x07, 0xe8, + ], len: 15190, - sha: [0x62, 0xd0, 0x43, 0x0e, 0x9e, 0xaf, 0x35, 0xd2, 0x1b, 0x95, 0xad, 0xc8, 0x18, 0xd5, 0x7b, 0xb8, 0x5e, 0xaf, 0x0a, 0x74, 0x66, 0x06, 0x87, 0x0d, 0xd5, 0xf1, 0xf2, 0xed, 0x25, 0xc1, 0xf7, 0x27], + sha: [ + 0x62, 0xd0, 0x43, 0x0e, 0x9e, 0xaf, 0x35, 0xd2, 0x1b, 0x95, 0xad, 0xc8, 0x18, 0xd5, 0x7b, 0xb8, 0x5e, 0xaf, + 0x0a, 0x74, 0x66, 0x06, 0x87, 0x0d, 0xd5, 0xf1, 0xf2, 0xed, 0x25, 0xc1, 0xf7, 0x27, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_head_sampler.ptx", - key: [0xb0, 0x48, 0xca, 0x90, 0xf9, 0x7e, 0x6e, 0x6f, 0x2c, 0x0d, 0x93, 0xe5, 0xc1, 0x24, 0xe5, 0xd4, 0xad, 0xbc, 0x7b, 0x34, 0x09, 0x74, 0xe4, 0x5a, 0x4f, 0x98, 0xdc, 0x15, 0xd0, 0xb1, 0xbc, 0x59], + key: [ + 0xb0, 0x48, 0xca, 0x90, 0xf9, 0x7e, 0x6e, 0x6f, 0x2c, 0x0d, 0x93, 0xe5, 0xc1, 0x24, 0xe5, 0xd4, 0xad, 0xbc, + 0x7b, 0x34, 0x09, 0x74, 0xe4, 0x5a, 0x4f, 0x98, 0xdc, 0x15, 0xd0, 0xb1, 0xbc, 0x59, + ], len: 504479, - sha: [0xa2, 0x45, 0xc8, 0x5c, 0x87, 0xbd, 0xf2, 0x03, 0x13, 0xbf, 0xf4, 0x22, 0x07, 0xbb, 0xd6, 0xfb, 0xa6, 0xda, 0x14, 0x8a, 0xd3, 0xa0, 0x89, 0x4d, 0x6a, 0x5e, 0xbf, 0xa3, 0x39, 0x8e, 0xca, 0xc7], + sha: [ + 0xa2, 0x45, 0xc8, 0x5c, 0x87, 0xbd, 0xf2, 0x03, 0x13, 0xbf, 0xf4, 0x22, 0x07, 0xbb, 0xd6, 0xfb, 0xa6, 0xda, + 0x14, 0x8a, 0xd3, 0xa0, 0x89, 0x4d, 0x6a, 0x5e, 0xbf, 0xa3, 0x39, 0x8e, 0xca, 0xc7, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_head_sampler.ptx"), "\0").as_bytes(), }, Companion { name: "ple_fixed.ptx", - key: [0xb1, 0x4c, 0x64, 0x24, 0xb3, 0x4a, 0x4f, 0xba, 0xc6, 0x8a, 0xe3, 0x33, 0xad, 0xf9, 0x77, 0xe1, 0xa3, 0xff, 0x93, 0xe5, 0x0a, 0xe9, 0x97, 0x52, 0x8b, 0xb9, 0xa2, 0x33, 0xdf, 0xe7, 0x04, 0x86], + key: [ + 0xb1, 0x4c, 0x64, 0x24, 0xb3, 0x4a, 0x4f, 0xba, 0xc6, 0x8a, 0xe3, 0x33, 0xad, 0xf9, 0x77, 0xe1, 0xa3, 0xff, + 0x93, 0xe5, 0x0a, 0xe9, 0x97, 0x52, 0x8b, 0xb9, 0xa2, 0x33, 0xdf, 0xe7, 0x04, 0x86, + ], len: 30868, - sha: [0x32, 0xbc, 0x7b, 0xc0, 0xcb, 0x88, 0x9b, 0x30, 0xaf, 0xc2, 0x02, 0x88, 0x51, 0x8b, 0x90, 0xa4, 0x13, 0x7a, 0x05, 0xb0, 0x5d, 0xaf, 0x3d, 0x4f, 0xee, 0xde, 0xcc, 0x02, 0xe5, 0x66, 0xce, 0x0a], + sha: [ + 0x32, 0xbc, 0x7b, 0xc0, 0xcb, 0x88, 0x9b, 0x30, 0xaf, 0xc2, 0x02, 0x88, 0x51, 0x8b, 0x90, 0xa4, 0x13, 0x7a, + 0x05, 0xb0, 0x5d, 0xaf, 0x3d, 0x4f, 0xee, 0xde, 0xcc, 0x02, 0xe5, 0x66, 0xce, 0x0a, + ], ptx: concat!(include_str!("../ptx-sm86/ple_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_shared.ptx", - key: [0xb3, 0x6f, 0x43, 0x26, 0x92, 0xe4, 0x3f, 0x79, 0x48, 0xa2, 0x53, 0x8c, 0x22, 0xca, 0xb5, 0x5e, 0xf6, 0x7c, 0x62, 0x5b, 0x8d, 0x44, 0x61, 0xc6, 0x7c, 0xa2, 0xa2, 0x75, 0x19, 0xb9, 0xe0, 0xf0], + key: [ + 0xb3, 0x6f, 0x43, 0x26, 0x92, 0xe4, 0x3f, 0x79, 0x48, 0xa2, 0x53, 0x8c, 0x22, 0xca, 0xb5, 0x5e, 0xf6, 0x7c, + 0x62, 0x5b, 0x8d, 0x44, 0x61, 0xc6, 0x7c, 0xa2, 0xa2, 0x75, 0x19, 0xb9, 0xe0, 0xf0, + ], len: 45827, - sha: [0xe9, 0x22, 0x49, 0x6b, 0x44, 0xdd, 0xb0, 0xde, 0x69, 0x00, 0xb5, 0xbe, 0xec, 0x4b, 0x35, 0x09, 0xf2, 0xfa, 0x7e, 0x2a, 0x17, 0x2c, 0x3f, 0xe1, 0x76, 0xc1, 0x6e, 0xdd, 0x10, 0x18, 0x52, 0x90], + sha: [ + 0xe9, 0x22, 0x49, 0x6b, 0x44, 0xdd, 0xb0, 0xde, 0x69, 0x00, 0xb5, 0xbe, 0xec, 0x4b, 0x35, 0x09, 0xf2, 0xfa, + 0x7e, 0x2a, 0x17, 0x2c, 0x3f, 0xe1, 0x76, 0xc1, 0x6e, 0xdd, 0x10, 0x18, 0x52, 0x90, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_shared.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_scalar_norm.ptx", - key: [0xbb, 0x78, 0x4f, 0xd8, 0xa5, 0x74, 0xeb, 0x38, 0xcc, 0x3f, 0xdb, 0x92, 0x64, 0xb6, 0x9b, 0x72, 0xcd, 0xf3, 0x40, 0x78, 0x85, 0x91, 0x88, 0x5c, 0x9b, 0x7f, 0x96, 0xa0, 0x5a, 0x6a, 0x81, 0x07], + key: [ + 0xbb, 0x78, 0x4f, 0xd8, 0xa5, 0x74, 0xeb, 0x38, 0xcc, 0x3f, 0xdb, 0x92, 0x64, 0xb6, 0x9b, 0x72, 0xcd, 0xf3, + 0x40, 0x78, 0x85, 0x91, 0x88, 0x5c, 0x9b, 0x7f, 0x96, 0xa0, 0x5a, 0x6a, 0x81, 0x07, + ], len: 16691, - sha: [0x56, 0xab, 0x10, 0x69, 0x20, 0x71, 0x2b, 0x92, 0x7c, 0xe8, 0x94, 0xb7, 0x22, 0x7d, 0x7c, 0xb4, 0x7c, 0x7a, 0xda, 0x9f, 0x07, 0x90, 0xc3, 0x65, 0x08, 0xf5, 0xc9, 0x8f, 0x74, 0x0d, 0x7c, 0xdc], + sha: [ + 0x56, 0xab, 0x10, 0x69, 0x20, 0x71, 0x2b, 0x92, 0x7c, 0xe8, 0x94, 0xb7, 0x22, 0x7d, 0x7c, 0xb4, 0x7c, 0x7a, + 0xda, 0x9f, 0x07, 0x90, 0xc3, 0x65, 0x08, 0xf5, 0xc9, 0x8f, 0x74, 0x0d, 0x7c, 0xdc, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_scalar_norm.ptx"), "\0").as_bytes(), }, Companion { name: "native_flash_attn.ptx", - key: [0xbe, 0x35, 0x3e, 0x61, 0x9a, 0x15, 0xa5, 0x66, 0xe5, 0x7b, 0xae, 0x12, 0xa0, 0xbf, 0x30, 0xcc, 0x17, 0x12, 0xa2, 0x81, 0xbc, 0xe6, 0x92, 0x8f, 0x3b, 0xb7, 0x6c, 0x14, 0xe5, 0x11, 0x4b, 0xba], + key: [ + 0xbe, 0x35, 0x3e, 0x61, 0x9a, 0x15, 0xa5, 0x66, 0xe5, 0x7b, 0xae, 0x12, 0xa0, 0xbf, 0x30, 0xcc, 0x17, 0x12, + 0xa2, 0x81, 0xbc, 0xe6, 0x92, 0x8f, 0x3b, 0xb7, 0x6c, 0x14, 0xe5, 0x11, 0x4b, 0xba, + ], len: 208590, - sha: [0x6e, 0xaf, 0xd5, 0x7d, 0x2f, 0xcf, 0x68, 0x71, 0xb8, 0x22, 0x4f, 0xe9, 0x48, 0x52, 0x59, 0xd1, 0xec, 0x75, 0x0f, 0xb1, 0x76, 0xa2, 0x68, 0x96, 0x6b, 0x1d, 0xe4, 0x3f, 0xfa, 0x75, 0x62, 0x97], + sha: [ + 0x6e, 0xaf, 0xd5, 0x7d, 0x2f, 0xcf, 0x68, 0x71, 0xb8, 0x22, 0x4f, 0xe9, 0x48, 0x52, 0x59, 0xd1, 0xec, 0x75, + 0x0f, 0xb1, 0x76, 0xa2, 0x68, 0x96, 0x6b, 0x1d, 0xe4, 0x3f, 0xfa, 0x75, 0x62, 0x97, + ], ptx: concat!(include_str!("../ptx-sm86/native_flash_attn.ptx"), "\0").as_bytes(), }, Companion { name: "quantize-d4-selected.ptx", - key: [0xbe, 0x3b, 0x9f, 0x55, 0xff, 0x60, 0x69, 0xde, 0x50, 0x52, 0xc8, 0x3e, 0xf2, 0x2d, 0xa8, 0xfe, 0x88, 0xcd, 0x65, 0xe3, 0xe4, 0xfb, 0x1b, 0x13, 0xa7, 0xf9, 0x3d, 0xd1, 0x4f, 0x69, 0x9c, 0x1b], + key: [ + 0xbe, 0x3b, 0x9f, 0x55, 0xff, 0x60, 0x69, 0xde, 0x50, 0x52, 0xc8, 0x3e, 0xf2, 0x2d, 0xa8, 0xfe, 0x88, 0xcd, + 0x65, 0xe3, 0xe4, 0xfb, 0x1b, 0x13, 0xa7, 0xf9, 0x3d, 0xd1, 0x4f, 0x69, 0x9c, 0x1b, + ], len: 102215, - sha: [0x15, 0xe3, 0xb0, 0xb1, 0x95, 0x03, 0x41, 0x3b, 0x7f, 0x7d, 0x97, 0x21, 0xaf, 0x05, 0x11, 0xbb, 0x5a, 0xb9, 0xf5, 0xe5, 0x9a, 0x7c, 0xf9, 0x16, 0x77, 0xa3, 0x13, 0xc2, 0x79, 0xc6, 0xa6, 0x9a], + sha: [ + 0x15, 0xe3, 0xb0, 0xb1, 0x95, 0x03, 0x41, 0x3b, 0x7f, 0x7d, 0x97, 0x21, 0xaf, 0x05, 0x11, 0xbb, 0x5a, 0xb9, + 0xf5, 0xe5, 0x9a, 0x7c, 0xf9, 0x16, 0x77, 0xa3, 0x13, 0xc2, 0x79, 0xc6, 0xa6, 0x9a, + ], ptx: concat!(include_str!("../ptx-sm86/quantize-d4-selected.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_router.ptx", - key: [0xbe, 0x6e, 0x3c, 0x91, 0xe4, 0xf6, 0x83, 0x14, 0x64, 0xf5, 0x99, 0x37, 0x87, 0xf0, 0xbf, 0xf9, 0x69, 0xbc, 0x5d, 0x28, 0x39, 0x5f, 0x24, 0x22, 0x6b, 0x88, 0x67, 0x6b, 0x30, 0x69, 0xa8, 0xcb], + key: [ + 0xbe, 0x6e, 0x3c, 0x91, 0xe4, 0xf6, 0x83, 0x14, 0x64, 0xf5, 0x99, 0x37, 0x87, 0xf0, 0xbf, 0xf9, 0x69, 0xbc, + 0x5d, 0x28, 0x39, 0x5f, 0x24, 0x22, 0x6b, 0x88, 0x67, 0x6b, 0x30, 0x69, 0xa8, 0xcb, + ], len: 107477, - sha: [0x17, 0xa9, 0x4f, 0xd3, 0xc2, 0xa1, 0xe2, 0x8c, 0x56, 0xbd, 0x85, 0x10, 0xba, 0xd4, 0xb1, 0xda, 0xa3, 0xdb, 0x39, 0xec, 0x01, 0x36, 0xdb, 0xc0, 0x33, 0x4a, 0x00, 0xfa, 0xad, 0xaf, 0x0c, 0x47], + sha: [ + 0x17, 0xa9, 0x4f, 0xd3, 0xc2, 0xa1, 0xe2, 0x8c, 0x56, 0xbd, 0x85, 0x10, 0xba, 0xd4, 0xb1, 0xda, 0xa3, 0xdb, + 0x39, 0xec, 0x01, 0x36, 0xdb, 0xc0, 0x33, 0x4a, 0x00, 0xfa, 0xad, 0xaf, 0x0c, 0x47, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_router.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq3_s_nc4.ptx", - key: [0xbe, 0x6e, 0xe9, 0x07, 0xc0, 0xb3, 0x70, 0xcb, 0x99, 0x89, 0x4a, 0x03, 0x41, 0x94, 0x66, 0xf1, 0xaa, 0x46, 0x5b, 0xa9, 0xb8, 0xe2, 0xe8, 0xcf, 0x60, 0x38, 0x87, 0xf5, 0x34, 0x45, 0x0d, 0x0c], + key: [ + 0xbe, 0x6e, 0xe9, 0x07, 0xc0, 0xb3, 0x70, 0xcb, 0x99, 0x89, 0x4a, 0x03, 0x41, 0x94, 0x66, 0xf1, 0xaa, 0x46, + 0x5b, 0xa9, 0xb8, 0xe2, 0xe8, 0xcf, 0x60, 0x38, 0x87, 0xf5, 0x34, 0x45, 0x0d, 0x0c, + ], len: 36382, - sha: [0x23, 0xb7, 0x02, 0xaa, 0xf1, 0x27, 0x8d, 0xd3, 0xd4, 0x36, 0x14, 0x2b, 0x9c, 0x27, 0x32, 0x19, 0x21, 0xf3, 0x6d, 0xda, 0x76, 0x06, 0xd1, 0xf7, 0x56, 0x97, 0x3e, 0x5d, 0xfc, 0xbd, 0x45, 0x37], + sha: [ + 0x23, 0xb7, 0x02, 0xaa, 0xf1, 0x27, 0x8d, 0xd3, 0xd4, 0x36, 0x14, 0x2b, 0x9c, 0x27, 0x32, 0x19, 0x21, 0xf3, + 0x6d, 0xda, 0x76, 0x06, 0xd1, 0xf7, 0x56, 0x97, 0x3e, 0x5d, 0xfc, 0xbd, 0x45, 0x37, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq3_s_nc4.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_verify.ptx", - key: [0xbe, 0xbb, 0xef, 0xc6, 0x5c, 0x2c, 0xc2, 0x1c, 0x54, 0x84, 0x71, 0xf6, 0x90, 0xce, 0x02, 0xc6, 0x73, 0x41, 0x8e, 0x8a, 0xc0, 0x66, 0xd4, 0x9f, 0x94, 0x8d, 0x0e, 0x6e, 0x35, 0xcf, 0xa2, 0x03], + key: [ + 0xbe, 0xbb, 0xef, 0xc6, 0x5c, 0x2c, 0xc2, 0x1c, 0x54, 0x84, 0x71, 0xf6, 0x90, 0xce, 0x02, 0xc6, 0x73, 0x41, + 0x8e, 0x8a, 0xc0, 0x66, 0xd4, 0x9f, 0x94, 0x8d, 0x0e, 0x6e, 0x35, 0xcf, 0xa2, 0x03, + ], len: 179130, - sha: [0x8e, 0x19, 0x61, 0xf3, 0x6f, 0x40, 0x9d, 0xea, 0x38, 0x60, 0x66, 0x6b, 0xc8, 0xd7, 0x67, 0x95, 0x1c, 0x50, 0xbb, 0xac, 0x96, 0x36, 0x6a, 0x9e, 0xc5, 0xd9, 0x9d, 0x87, 0xbe, 0xc4, 0xe9, 0x30], + sha: [ + 0x8e, 0x19, 0x61, 0xf3, 0x6f, 0x40, 0x9d, 0xea, 0x38, 0x60, 0x66, 0x6b, 0xc8, 0xd7, 0x67, 0x95, 0x1c, 0x50, + 0xbb, 0xac, 0x96, 0x36, 0x6a, 0x9e, 0xc5, 0xd9, 0x9d, 0x87, 0xbe, 0xc4, 0xe9, 0x30, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_verify.ptx"), "\0").as_bytes(), }, Companion { name: "gr_batch_preview.ptx", - key: [0xc8, 0x56, 0xb6, 0xf5, 0x2d, 0x41, 0xd7, 0xe8, 0xf8, 0x8d, 0x7c, 0x63, 0xed, 0x68, 0x3b, 0x94, 0x73, 0x10, 0x08, 0x87, 0x10, 0xf6, 0x62, 0xbc, 0xad, 0x0a, 0xfc, 0xed, 0x3e, 0xf6, 0x5c, 0xac], + key: [ + 0xc8, 0x56, 0xb6, 0xf5, 0x2d, 0x41, 0xd7, 0xe8, 0xf8, 0x8d, 0x7c, 0x63, 0xed, 0x68, 0x3b, 0x94, 0x73, 0x10, + 0x08, 0x87, 0x10, 0xf6, 0x62, 0xbc, 0xad, 0x0a, 0xfc, 0xed, 0x3e, 0xf6, 0x5c, 0xac, + ], len: 24666, - sha: [0x8b, 0x51, 0xd3, 0x67, 0x3b, 0xce, 0x01, 0x8b, 0x58, 0x7e, 0xa8, 0x1c, 0x5a, 0xb2, 0xe9, 0xd7, 0xdd, 0x4d, 0x75, 0xd0, 0x01, 0x4f, 0x6c, 0xfd, 0x4f, 0x7c, 0xf5, 0xfc, 0x17, 0xcd, 0x4c, 0xb3], + sha: [ + 0x8b, 0x51, 0xd3, 0x67, 0x3b, 0xce, 0x01, 0x8b, 0x58, 0x7e, 0xa8, 0x1c, 0x5a, 0xb2, 0xe9, 0xd7, 0xdd, 0x4d, + 0x75, 0xd0, 0x01, 0x4f, 0x6c, 0xfd, 0x4f, 0x7c, 0xf5, 0xfc, 0x17, 0xcd, 0x4c, 0xb3, + ], ptx: concat!(include_str!("../ptx-sm86/gr_batch_preview.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_iq4_xs.ptx", - key: [0xc8, 0x88, 0x0e, 0xf0, 0x8d, 0xcc, 0x6b, 0xfa, 0x4a, 0xcc, 0xc9, 0x89, 0x87, 0xc4, 0x5c, 0x64, 0x1e, 0x47, 0x2c, 0x52, 0x06, 0xad, 0x9d, 0x38, 0x9f, 0x5e, 0x94, 0x38, 0x5c, 0xd8, 0xc9, 0x84], + key: [ + 0xc8, 0x88, 0x0e, 0xf0, 0x8d, 0xcc, 0x6b, 0xfa, 0x4a, 0xcc, 0xc9, 0x89, 0x87, 0xc4, 0x5c, 0x64, 0x1e, 0x47, + 0x2c, 0x52, 0x06, 0xad, 0x9d, 0x38, 0x9f, 0x5e, 0x94, 0x38, 0x5c, 0xd8, 0xc9, 0x84, + ], len: 63256, - sha: [0x72, 0x2e, 0xff, 0xee, 0x93, 0x55, 0xd3, 0xe1, 0x39, 0x73, 0xd8, 0xec, 0x9e, 0x77, 0xde, 0x98, 0xfe, 0xc0, 0xfd, 0x4a, 0x97, 0xea, 0xfe, 0xbb, 0x55, 0x0c, 0xf9, 0xdd, 0xfd, 0x55, 0xc0, 0x2b], + sha: [ + 0x72, 0x2e, 0xff, 0xee, 0x93, 0x55, 0xd3, 0xe1, 0x39, 0x73, 0xd8, 0xec, 0x9e, 0x77, 0xde, 0x98, 0xfe, 0xc0, + 0xfd, 0x4a, 0x97, 0xea, 0xfe, 0xbb, 0x55, 0x0c, 0xf9, 0xdd, 0xfd, 0x55, 0xc0, 0x2b, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_iq4_xs.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify_window_pcie.ptx", - key: [0xcb, 0xeb, 0x32, 0x3f, 0x76, 0x47, 0x68, 0x2f, 0xee, 0x9e, 0xd3, 0xf1, 0x2f, 0xb7, 0xb7, 0xa5, 0xb3, 0xeb, 0x19, 0x2f, 0x21, 0x66, 0xc6, 0xec, 0x96, 0xb8, 0x1d, 0x55, 0xc3, 0xba, 0xb9, 0xd1], + key: [ + 0xcb, 0xeb, 0x32, 0x3f, 0x76, 0x47, 0x68, 0x2f, 0xee, 0x9e, 0xd3, 0xf1, 0x2f, 0xb7, 0xb7, 0xa5, 0xb3, 0xeb, + 0x19, 0x2f, 0x21, 0x66, 0xc6, 0xec, 0x96, 0xb8, 0x1d, 0x55, 0xc3, 0xba, 0xb9, 0xd1, + ], len: 7687, - sha: [0x98, 0x5b, 0xbf, 0xc8, 0x77, 0x91, 0xbd, 0x96, 0xa2, 0xcf, 0x61, 0x32, 0xce, 0x7e, 0x49, 0x9b, 0x90, 0xeb, 0xfe, 0x7a, 0x31, 0x0e, 0xe1, 0xc5, 0x78, 0x1c, 0x49, 0xaf, 0xd1, 0x96, 0x4f, 0x67], + sha: [ + 0x98, 0x5b, 0xbf, 0xc8, 0x77, 0x91, 0xbd, 0x96, 0xa2, 0xcf, 0x61, 0x32, 0xce, 0x7e, 0x49, 0x9b, 0x90, 0xeb, + 0xfe, 0x7a, 0x31, 0x0e, 0xe1, 0xc5, 0x78, 0x1c, 0x49, 0xaf, 0xd1, 0x96, 0x4f, 0x67, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify_window_pcie.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify.ptx", - key: [0xd0, 0xda, 0xda, 0x67, 0x15, 0xfb, 0x80, 0x8b, 0xb3, 0x28, 0x82, 0x91, 0xfd, 0x4a, 0x5c, 0x29, 0xe7, 0x8f, 0xd7, 0xfa, 0x6e, 0x70, 0xf2, 0xb9, 0x4d, 0x22, 0x0f, 0x86, 0x0b, 0xb4, 0x33, 0x53], + key: [ + 0xd0, 0xda, 0xda, 0x67, 0x15, 0xfb, 0x80, 0x8b, 0xb3, 0x28, 0x82, 0x91, 0xfd, 0x4a, 0x5c, 0x29, 0xe7, 0x8f, + 0xd7, 0xfa, 0x6e, 0x70, 0xf2, 0xb9, 0x4d, 0x22, 0x0f, 0x86, 0x0b, 0xb4, 0x33, 0x53, + ], len: 154200, - sha: [0xba, 0x92, 0xfe, 0x4e, 0x9b, 0x5a, 0xe0, 0x48, 0x86, 0x4a, 0x1c, 0xcb, 0xa8, 0x64, 0x50, 0x22, 0x4a, 0x07, 0x83, 0x67, 0x2c, 0x0c, 0x2b, 0x99, 0xe4, 0xec, 0x32, 0x02, 0xe1, 0x66, 0x03, 0x55], + sha: [ + 0xba, 0x92, 0xfe, 0x4e, 0x9b, 0x5a, 0xe0, 0x48, 0x86, 0x4a, 0x1c, 0xcb, 0xa8, 0x64, 0x50, 0x22, 0x4a, 0x07, + 0x83, 0x67, 0x2c, 0x0c, 0x2b, 0x99, 0xe4, 0xec, 0x32, 0x02, 0xe1, 0x66, 0x03, 0x55, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_quant80.ptx", - key: [0xd1, 0xae, 0x17, 0xce, 0xcc, 0x24, 0xe2, 0x4e, 0x0e, 0x1f, 0xc9, 0x5a, 0x73, 0x52, 0x79, 0x89, 0x71, 0x9b, 0x94, 0x5d, 0xfe, 0xed, 0x68, 0x9e, 0x80, 0x67, 0xa5, 0x8f, 0x10, 0x18, 0x11, 0x90], + key: [ + 0xd1, 0xae, 0x17, 0xce, 0xcc, 0x24, 0xe2, 0x4e, 0x0e, 0x1f, 0xc9, 0x5a, 0x73, 0x52, 0x79, 0x89, 0x71, 0x9b, + 0x94, 0x5d, 0xfe, 0xed, 0x68, 0x9e, 0x80, 0x67, 0xa5, 0x8f, 0x10, 0x18, 0x11, 0x90, + ], len: 96194, - sha: [0x33, 0x98, 0x0b, 0x2a, 0xd2, 0x18, 0xeb, 0x46, 0xb6, 0x4c, 0x3f, 0xf0, 0xf2, 0xe7, 0x3e, 0xba, 0x2d, 0xde, 0x43, 0xed, 0xa7, 0xbf, 0x12, 0x8c, 0x62, 0xc4, 0x08, 0xad, 0xe0, 0x2b, 0xbd, 0x83], + sha: [ + 0x33, 0x98, 0x0b, 0x2a, 0xd2, 0x18, 0xeb, 0x46, 0xb6, 0x4c, 0x3f, 0xf0, 0xf2, 0xe7, 0x3e, 0xba, 0x2d, 0xde, + 0x43, 0xed, 0xa7, 0xbf, 0x12, 0x8c, 0x62, 0xc4, 0x08, 0xad, 0xe0, 0x2b, 0xbd, 0x83, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_quant80.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_prefill_quant.ptx", - key: [0xd5, 0xa6, 0x7b, 0x91, 0xe2, 0xbd, 0x30, 0x8b, 0x6c, 0x5b, 0x3c, 0xf3, 0x80, 0xf4, 0xb1, 0x40, 0x00, 0x43, 0x28, 0xbd, 0x26, 0x4c, 0x98, 0x83, 0x70, 0xb7, 0x14, 0x37, 0xf9, 0x6b, 0x86, 0x4c], + key: [ + 0xd5, 0xa6, 0x7b, 0x91, 0xe2, 0xbd, 0x30, 0x8b, 0x6c, 0x5b, 0x3c, 0xf3, 0x80, 0xf4, 0xb1, 0x40, 0x00, 0x43, + 0x28, 0xbd, 0x26, 0x4c, 0x98, 0x83, 0x70, 0xb7, 0x14, 0x37, 0xf9, 0x6b, 0x86, 0x4c, + ], len: 217573, - sha: [0xcb, 0xa7, 0x20, 0xbb, 0x6b, 0xfb, 0x98, 0x41, 0xfa, 0xc5, 0x71, 0x6f, 0x84, 0x88, 0x6c, 0x94, 0x7f, 0x36, 0xf4, 0xf0, 0x21, 0x0d, 0xe9, 0x10, 0xd3, 0x99, 0x5c, 0x1d, 0x8e, 0x62, 0x0d, 0xd7], + sha: [ + 0xcb, 0xa7, 0x20, 0xbb, 0x6b, 0xfb, 0x98, 0x41, 0xfa, 0xc5, 0x71, 0x6f, 0x84, 0x88, 0x6c, 0x94, 0x7f, 0x36, + 0xf4, 0xf0, 0x21, 0x0d, 0xe9, 0x10, 0xd3, 0x99, 0x5c, 0x1d, 0x8e, 0x62, 0x0d, 0xd7, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_prefill_quant.ptx"), "\0").as_bytes(), }, Companion { name: "qwen_qsa_native.ptx", - key: [0xd6, 0x04, 0x89, 0xfb, 0x70, 0xce, 0x43, 0x70, 0x04, 0x7b, 0xf5, 0x4f, 0xae, 0x8d, 0xd4, 0x6d, 0xfb, 0x53, 0xbb, 0x73, 0xb1, 0x61, 0x8c, 0x58, 0x94, 0x29, 0x32, 0xa7, 0x89, 0xd0, 0x64, 0xc5], + key: [ + 0xd6, 0x04, 0x89, 0xfb, 0x70, 0xce, 0x43, 0x70, 0x04, 0x7b, 0xf5, 0x4f, 0xae, 0x8d, 0xd4, 0x6d, 0xfb, 0x53, + 0xbb, 0x73, 0xb1, 0x61, 0x8c, 0x58, 0x94, 0x29, 0x32, 0xa7, 0x89, 0xd0, 0x64, 0xc5, + ], len: 31598, - sha: [0x91, 0x8c, 0x74, 0x1a, 0xb3, 0xde, 0x0c, 0x8e, 0x3a, 0x4d, 0xb0, 0xf4, 0x54, 0xbc, 0xfc, 0x73, 0x9b, 0x9b, 0xad, 0xcd, 0x58, 0xdd, 0x04, 0x7c, 0xc5, 0xfd, 0x87, 0x2e, 0x99, 0xc0, 0x1e, 0xf0], + sha: [ + 0x91, 0x8c, 0x74, 0x1a, 0xb3, 0xde, 0x0c, 0x8e, 0x3a, 0x4d, 0xb0, 0xf4, 0x54, 0xbc, 0xfc, 0x73, 0x9b, 0x9b, + 0xad, 0xcd, 0x58, 0xdd, 0x04, 0x7c, 0xc5, 0xfd, 0x87, 0x2e, 0x99, 0xc0, 0x1e, 0xf0, + ], ptx: concat!(include_str!("../ptx-sm86/qwen_qsa_native.ptx"), "\0").as_bytes(), }, Companion { name: "gr_fixed.ptx", - key: [0xde, 0xaa, 0x95, 0xe6, 0x1d, 0x25, 0xff, 0x87, 0xfd, 0x53, 0x1b, 0x62, 0xd5, 0xc2, 0x93, 0x09, 0xb6, 0x9a, 0x37, 0x71, 0x18, 0x20, 0x4e, 0xef, 0xae, 0xe3, 0x10, 0xaf, 0x4e, 0xcf, 0xfa, 0x8b], + key: [ + 0xde, 0xaa, 0x95, 0xe6, 0x1d, 0x25, 0xff, 0x87, 0xfd, 0x53, 0x1b, 0x62, 0xd5, 0xc2, 0x93, 0x09, 0xb6, 0x9a, + 0x37, 0x71, 0x18, 0x20, 0x4e, 0xef, 0xae, 0xe3, 0x10, 0xaf, 0x4e, 0xcf, 0xfa, 0x8b, + ], len: 22704, - sha: [0x89, 0x18, 0x62, 0xf3, 0xd1, 0x04, 0x0d, 0x14, 0xbf, 0xd3, 0x8f, 0xf0, 0x0e, 0x19, 0xea, 0x42, 0xf4, 0xc6, 0x30, 0xdd, 0xcc, 0xfd, 0xa1, 0x69, 0x9f, 0xf5, 0xc6, 0x8f, 0xa1, 0x26, 0xd9, 0x66], + sha: [ + 0x89, 0x18, 0x62, 0xf3, 0xd1, 0x04, 0x0d, 0x14, 0xbf, 0xd3, 0x8f, 0xf0, 0x0e, 0x19, 0xea, 0x42, 0xf4, 0xc6, + 0x30, 0xdd, 0xcc, 0xfd, 0xa1, 0x69, 0x9f, 0xf5, 0xc6, 0x8f, 0xa1, 0x26, 0xd9, 0x66, + ], ptx: concat!(include_str!("../ptx-sm86/gr_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "qwen_qsa_select.ptx", - key: [0xe0, 0x94, 0xe1, 0x0f, 0x84, 0xcc, 0xa6, 0x12, 0xca, 0x28, 0x59, 0x6a, 0xa3, 0x94, 0xee, 0x99, 0x9e, 0x33, 0xfe, 0x7b, 0xc8, 0x4b, 0x35, 0x9b, 0xfa, 0xb6, 0xda, 0x07, 0x30, 0xd4, 0xa5, 0x19], + key: [ + 0xe0, 0x94, 0xe1, 0x0f, 0x84, 0xcc, 0xa6, 0x12, 0xca, 0x28, 0x59, 0x6a, 0xa3, 0x94, 0xee, 0x99, 0x9e, 0x33, + 0xfe, 0x7b, 0xc8, 0x4b, 0x35, 0x9b, 0xfa, 0xb6, 0xda, 0x07, 0x30, 0xd4, 0xa5, 0x19, + ], len: 41468, - sha: [0xe8, 0xad, 0xf4, 0x5c, 0x34, 0x90, 0x8f, 0xa7, 0xf1, 0x58, 0x3d, 0x1d, 0xa0, 0xc5, 0x83, 0x04, 0xfa, 0x02, 0x29, 0xbc, 0x2e, 0x37, 0x43, 0xc2, 0xaa, 0x30, 0x58, 0xf9, 0xe2, 0x6f, 0xf2, 0x7b], + sha: [ + 0xe8, 0xad, 0xf4, 0x5c, 0x34, 0x90, 0x8f, 0xa7, 0xf1, 0x58, 0x3d, 0x1d, 0xa0, 0xc5, 0x83, 0x04, 0xfa, 0x02, + 0x29, 0xbc, 0x2e, 0x37, 0x43, 0xc2, 0xaa, 0x30, 0x58, 0xf9, 0xe2, 0x6f, 0xf2, 0x7b, + ], ptx: concat!(include_str!("../ptx-sm86/qwen_qsa_select.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_kv.ptx", - key: [0xe0, 0xc1, 0xff, 0x10, 0xd3, 0xd4, 0xbc, 0xf8, 0xfd, 0x33, 0x69, 0x71, 0x30, 0x79, 0xb2, 0x32, 0xe6, 0x2c, 0xdb, 0x2c, 0x3a, 0x34, 0x5f, 0xae, 0xc4, 0x9d, 0x1e, 0x66, 0x76, 0x3f, 0x91, 0x1f], + key: [ + 0xe0, 0xc1, 0xff, 0x10, 0xd3, 0xd4, 0xbc, 0xf8, 0xfd, 0x33, 0x69, 0x71, 0x30, 0x79, 0xb2, 0x32, 0xe6, 0x2c, + 0xdb, 0x2c, 0x3a, 0x34, 0x5f, 0xae, 0xc4, 0x9d, 0x1e, 0x66, 0x76, 0x3f, 0x91, 0x1f, + ], len: 16734, - sha: [0xb9, 0x61, 0xa6, 0xbc, 0xaf, 0x30, 0x9b, 0xca, 0x67, 0xab, 0xf6, 0xc3, 0x7b, 0x8e, 0x30, 0x3b, 0x16, 0x5f, 0xcd, 0x8f, 0x51, 0xc6, 0x8f, 0x63, 0x11, 0xc5, 0xa0, 0xe1, 0x3f, 0x86, 0x1f, 0x8b], + sha: [ + 0xb9, 0x61, 0xa6, 0xbc, 0xaf, 0x30, 0x9b, 0xca, 0x67, 0xab, 0xf6, 0xc3, 0x7b, 0x8e, 0x30, 0x3b, 0x16, 0x5f, + 0xcd, 0x8f, 0x51, 0xc6, 0x8f, 0x63, 0x11, 0xc5, 0xa0, 0xe1, 0x3f, 0x86, 0x1f, 0x8b, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_kv.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_attention_fixed.ptx", - key: [0xe1, 0x1a, 0xc4, 0xde, 0x66, 0xc9, 0x9c, 0x31, 0xec, 0x95, 0x37, 0x27, 0xbd, 0xac, 0x91, 0xca, 0xc9, 0x7d, 0x58, 0xd8, 0x2a, 0x3d, 0xcb, 0xe0, 0x6e, 0xf4, 0xc6, 0xe8, 0xdc, 0x2a, 0x4c, 0x66], + key: [ + 0xe1, 0x1a, 0xc4, 0xde, 0x66, 0xc9, 0x9c, 0x31, 0xec, 0x95, 0x37, 0x27, 0xbd, 0xac, 0x91, 0xca, 0xc9, 0x7d, + 0x58, 0xd8, 0x2a, 0x3d, 0xcb, 0xe0, 0x6e, 0xf4, 0xc6, 0xe8, 0xdc, 0x2a, 0x4c, 0x66, + ], len: 75847, - sha: [0xa0, 0x5c, 0xff, 0x97, 0xbd, 0x7e, 0x4e, 0x0a, 0xc9, 0x24, 0xad, 0xb9, 0xf0, 0x1f, 0x7b, 0x6c, 0xa8, 0xe9, 0x67, 0x11, 0x3f, 0x84, 0xa1, 0x68, 0x7e, 0x09, 0x76, 0xb5, 0x64, 0x13, 0xa8, 0x37], + sha: [ + 0xa0, 0x5c, 0xff, 0x97, 0xbd, 0x7e, 0x4e, 0x0a, 0xc9, 0x24, 0xad, 0xb9, 0xf0, 0x1f, 0x7b, 0x6c, 0xa8, 0xe9, + 0x67, 0x11, 0x3f, 0x84, 0xa1, 0x68, 0x7e, 0x09, 0x76, 0xb5, 0x64, 0x13, 0xa8, 0x37, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_attention_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_head_iq.ptx", - key: [0xe5, 0x74, 0x52, 0xcc, 0xac, 0x77, 0x2a, 0x8a, 0x8a, 0x77, 0x25, 0x3b, 0xc6, 0xc9, 0x64, 0xeb, 0xb7, 0xbc, 0x61, 0xfd, 0xb2, 0xe9, 0x75, 0x27, 0xa9, 0x77, 0x5f, 0x8c, 0xcf, 0x3c, 0x3b, 0x9f], + key: [ + 0xe5, 0x74, 0x52, 0xcc, 0xac, 0x77, 0x2a, 0x8a, 0x8a, 0x77, 0x25, 0x3b, 0xc6, 0xc9, 0x64, 0xeb, 0xb7, 0xbc, + 0x61, 0xfd, 0xb2, 0xe9, 0x75, 0x27, 0xa9, 0x77, 0x5f, 0x8c, 0xcf, 0x3c, 0x3b, 0x9f, + ], len: 792488, - sha: [0xea, 0x98, 0x3e, 0x2b, 0x8f, 0xce, 0xae, 0xbb, 0xa0, 0xad, 0xdb, 0x29, 0x62, 0x84, 0xa1, 0xf2, 0xfa, 0x54, 0x6e, 0x26, 0x04, 0xfe, 0x8d, 0x6a, 0x10, 0x17, 0x02, 0x9a, 0xaf, 0x7e, 0x18, 0xae], + sha: [ + 0xea, 0x98, 0x3e, 0x2b, 0x8f, 0xce, 0xae, 0xbb, 0xa0, 0xad, 0xdb, 0x29, 0x62, 0x84, 0xa1, 0xf2, 0xfa, 0x54, + 0x6e, 0x26, 0x04, 0xfe, 0x8d, 0x6a, 0x10, 0x17, 0x02, 0x9a, 0xaf, 0x7e, 0x18, 0xae, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_head_iq.ptx"), "\0").as_bytes(), }, Companion { name: "mmq-adaptive-fixup.ptx", - key: [0xe8, 0x14, 0xd7, 0x50, 0x21, 0xa7, 0x3c, 0x38, 0x31, 0x02, 0x3d, 0x29, 0x81, 0x84, 0x72, 0x23, 0x2d, 0xb4, 0x47, 0x29, 0x21, 0x3d, 0xf1, 0x0d, 0x60, 0xc4, 0x78, 0x63, 0xaa, 0x47, 0x72, 0x78], + key: [ + 0xe8, 0x14, 0xd7, 0x50, 0x21, 0xa7, 0x3c, 0x38, 0x31, 0x02, 0x3d, 0x29, 0x81, 0x84, 0x72, 0x23, 0x2d, 0xb4, + 0x47, 0x29, 0x21, 0x3d, 0xf1, 0x0d, 0x60, 0xc4, 0x78, 0x63, 0xaa, 0x47, 0x72, 0x78, + ], len: 445570, - sha: [0xa5, 0x0b, 0x8a, 0x99, 0x40, 0x09, 0xa3, 0xc6, 0x0e, 0xd8, 0x29, 0xaa, 0x45, 0xf7, 0xb1, 0x71, 0x23, 0x40, 0x12, 0x95, 0xbd, 0xaa, 0x4e, 0x03, 0xe8, 0x71, 0xb4, 0x39, 0x3c, 0x2a, 0xf9, 0x1c], + sha: [ + 0xa5, 0x0b, 0x8a, 0x99, 0x40, 0x09, 0xa3, 0xc6, 0x0e, 0xd8, 0x29, 0xaa, 0x45, 0xf7, 0xb1, 0x71, 0x23, 0x40, + 0x12, 0x95, 0xbd, 0xaa, 0x4e, 0x03, 0xe8, 0x71, 0xb4, 0x39, 0x3c, 0x2a, 0xf9, 0x1c, + ], ptx: concat!(include_str!("../ptx-sm86/mmq-adaptive-fixup.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_original_group_mul.ptx", - key: [0xea, 0x0d, 0xb7, 0x85, 0x05, 0x28, 0x9e, 0x8e, 0x74, 0x3a, 0x55, 0x2e, 0xf2, 0x3d, 0xed, 0x98, 0xd6, 0x68, 0xa4, 0x89, 0xc6, 0x79, 0xa0, 0xe4, 0x48, 0x93, 0xb0, 0x00, 0x44, 0x5b, 0x48, 0xc7], + key: [ + 0xea, 0x0d, 0xb7, 0x85, 0x05, 0x28, 0x9e, 0x8e, 0x74, 0x3a, 0x55, 0x2e, 0xf2, 0x3d, 0xed, 0x98, 0xd6, 0x68, + 0xa4, 0x89, 0xc6, 0x79, 0xa0, 0xe4, 0x48, 0x93, 0xb0, 0x00, 0x44, 0x5b, 0x48, 0xc7, + ], len: 13083403, - sha: [0x8a, 0x80, 0x90, 0xb4, 0x00, 0xf4, 0x08, 0x8f, 0x3d, 0x45, 0x0a, 0x70, 0xca, 0x0f, 0x83, 0x60, 0x8f, 0xfe, 0x44, 0x73, 0xf4, 0x49, 0xd7, 0x9c, 0x69, 0xf8, 0x8c, 0x7c, 0x12, 0x2a, 0x26, 0x4a], + sha: [ + 0x8a, 0x80, 0x90, 0xb4, 0x00, 0xf4, 0x08, 0x8f, 0x3d, 0x45, 0x0a, 0x70, 0xca, 0x0f, 0x83, 0x60, 0x8f, 0xfe, + 0x44, 0x73, 0xf4, 0x49, 0xd7, 0x9c, 0x69, 0xf8, 0x8c, 0x7c, 0x12, 0x2a, 0x26, 0x4a, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_original_group_mul.ptx"), "\0").as_bytes(), }, Companion { name: "mmq_native_resident_d4.ptx", - key: [0xea, 0x33, 0xd3, 0xd1, 0xdb, 0xc3, 0xc6, 0x39, 0x81, 0x55, 0xef, 0xa1, 0x92, 0xb5, 0xbb, 0x4d, 0x5a, 0x25, 0xf7, 0x3f, 0x6e, 0x8a, 0xf6, 0x5f, 0x2d, 0xdc, 0x1b, 0x91, 0x95, 0xbb, 0x3e, 0xeb], + key: [ + 0xea, 0x33, 0xd3, 0xd1, 0xdb, 0xc3, 0xc6, 0x39, 0x81, 0x55, 0xef, 0xa1, 0x92, 0xb5, 0xbb, 0x4d, 0x5a, 0x25, + 0xf7, 0x3f, 0x6e, 0x8a, 0xf6, 0x5f, 0x2d, 0xdc, 0x1b, 0x91, 0x95, 0xbb, 0x3e, 0xeb, + ], len: 5199, - sha: [0x95, 0x4e, 0x26, 0x5c, 0x1d, 0x6a, 0x60, 0x53, 0x6c, 0x93, 0x6d, 0x3e, 0x01, 0x24, 0x02, 0x13, 0xc5, 0x0d, 0xf2, 0xae, 0xc8, 0x8c, 0x5f, 0x42, 0x88, 0xa5, 0xd5, 0xf6, 0xe3, 0xb7, 0xc1, 0x14], + sha: [ + 0x95, 0x4e, 0x26, 0x5c, 0x1d, 0x6a, 0x60, 0x53, 0x6c, 0x93, 0x6d, 0x3e, 0x01, 0x24, 0x02, 0x13, 0xc5, 0x0d, + 0xf2, 0xae, 0xc8, 0x8c, 0x5f, 0x42, 0x88, 0xa5, 0xd5, 0xf6, 0xe3, 0xb7, 0xc1, 0x14, + ], ptx: concat!(include_str!("../ptx-sm86/mmq_native_resident_d4.ptx"), "\0").as_bytes(), }, Companion { name: "moe_fixed.ptx", - key: [0xeb, 0x25, 0xf4, 0x5f, 0x2b, 0xf1, 0xcd, 0x3b, 0xe5, 0x7e, 0x0b, 0x5f, 0x32, 0x6a, 0x63, 0xf6, 0x66, 0x05, 0x9a, 0x58, 0x70, 0x6d, 0x7a, 0x2b, 0xd4, 0x70, 0x52, 0x6c, 0x22, 0xc0, 0xf6, 0x7a], + key: [ + 0xeb, 0x25, 0xf4, 0x5f, 0x2b, 0xf1, 0xcd, 0x3b, 0xe5, 0x7e, 0x0b, 0x5f, 0x32, 0x6a, 0x63, 0xf6, 0x66, 0x05, + 0x9a, 0x58, 0x70, 0x6d, 0x7a, 0x2b, 0xd4, 0x70, 0x52, 0x6c, 0x22, 0xc0, 0xf6, 0x7a, + ], len: 24983, - sha: [0x67, 0x25, 0x8f, 0xde, 0x60, 0xe2, 0xe5, 0xd0, 0xe5, 0x0b, 0xe8, 0xcb, 0xd6, 0x3b, 0x0d, 0xe4, 0x2e, 0x33, 0xf7, 0x22, 0xb1, 0x61, 0x40, 0xe1, 0xb0, 0x71, 0x85, 0x7b, 0x47, 0xaa, 0xa8, 0xbe], + sha: [ + 0x67, 0x25, 0x8f, 0xde, 0x60, 0xe2, 0xe5, 0xd0, 0xe5, 0x0b, 0xe8, 0xcb, 0xd6, 0x3b, 0x0d, 0xe4, 0x2e, 0x33, + 0xf7, 0x22, 0xb1, 0x61, 0x40, 0xe1, 0xb0, 0x71, 0x85, 0x7b, 0x47, 0xaa, 0xa8, 0xbe, + ], ptx: concat!(include_str!("../ptx-sm86/moe_fixed.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_late.ptx", - key: [0xeb, 0xc8, 0xbc, 0x0a, 0xac, 0x1b, 0xd4, 0xa7, 0x45, 0x40, 0xed, 0x24, 0x6c, 0x00, 0x96, 0x0d, 0x10, 0x15, 0x96, 0x30, 0x20, 0x11, 0x33, 0xe6, 0xd2, 0x1f, 0x30, 0x6e, 0xfe, 0xb1, 0xba, 0x2f], + key: [ + 0xeb, 0xc8, 0xbc, 0x0a, 0xac, 0x1b, 0xd4, 0xa7, 0x45, 0x40, 0xed, 0x24, 0x6c, 0x00, 0x96, 0x0d, 0x10, 0x15, + 0x96, 0x30, 0x20, 0x11, 0x33, 0xe6, 0xd2, 0x1f, 0x30, 0x6e, 0xfe, 0xb1, 0xba, 0x2f, + ], len: 213285, - sha: [0x11, 0x8d, 0x23, 0x00, 0xe6, 0x7d, 0x15, 0x42, 0x0b, 0x7e, 0xbd, 0xb4, 0xee, 0x82, 0x3d, 0x91, 0xbe, 0x58, 0x55, 0x62, 0x07, 0x23, 0x85, 0x3f, 0xe9, 0xda, 0x8d, 0xef, 0x8a, 0xe5, 0xe9, 0x8b], + sha: [ + 0x11, 0x8d, 0x23, 0x00, 0xe6, 0x7d, 0x15, 0x42, 0x0b, 0x7e, 0xbd, 0xb4, 0xee, 0x82, 0x3d, 0x91, 0xbe, 0x58, + 0x55, 0x62, 0x07, 0x23, 0x85, 0x3f, 0xe9, 0xda, 0x8d, 0xef, 0x8a, 0xe5, 0xe9, 0x8b, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_late.ptx"), "\0").as_bytes(), }, Companion { name: "kar_decode_levels.ptx", - key: [0xec, 0x69, 0x77, 0x87, 0xe0, 0x00, 0x53, 0x10, 0x00, 0x5e, 0xb1, 0x69, 0xa7, 0x58, 0x31, 0x5e, 0xb5, 0x50, 0x3a, 0xc7, 0x67, 0x1a, 0x38, 0x49, 0x5e, 0xea, 0xea, 0xf4, 0xfb, 0x2a, 0x8e, 0xc9], + key: [ + 0xec, 0x69, 0x77, 0x87, 0xe0, 0x00, 0x53, 0x10, 0x00, 0x5e, 0xb1, 0x69, 0xa7, 0x58, 0x31, 0x5e, 0xb5, 0x50, + 0x3a, 0xc7, 0x67, 0x1a, 0x38, 0x49, 0x5e, 0xea, 0xea, 0xf4, 0xfb, 0x2a, 0x8e, 0xc9, + ], len: 18428, - sha: [0xb9, 0x41, 0xaf, 0xb1, 0x17, 0xd7, 0x7a, 0x57, 0x32, 0xc1, 0x66, 0x6a, 0x25, 0x29, 0x1a, 0xb9, 0xbf, 0xd6, 0x17, 0x25, 0x28, 0xbd, 0x6b, 0x52, 0x7c, 0x37, 0x39, 0x7f, 0x24, 0xfd, 0x77, 0xc4], + sha: [ + 0xb9, 0x41, 0xaf, 0xb1, 0x17, 0xd7, 0x7a, 0x57, 0x32, 0xc1, 0x66, 0x6a, 0x25, 0x29, 0x1a, 0xb9, 0xbf, 0xd6, + 0x17, 0x25, 0x28, 0xbd, 0x6b, 0x52, 0x7c, 0x37, 0x39, 0x7f, 0x24, 0xfd, 0x77, 0xc4, + ], ptx: concat!(include_str!("../ptx-sm86/kar_decode_levels.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_prefill.ptx", - key: [0xf0, 0xa0, 0x67, 0x3d, 0x72, 0xe2, 0xaf, 0x9b, 0xaa, 0x48, 0x14, 0x64, 0xbd, 0x2f, 0x07, 0x04, 0x2a, 0x66, 0x98, 0xd4, 0x64, 0x13, 0xfe, 0x6a, 0x85, 0x4c, 0xc8, 0x30, 0x1d, 0xba, 0x67, 0x5a], + key: [ + 0xf0, 0xa0, 0x67, 0x3d, 0x72, 0xe2, 0xaf, 0x9b, 0xaa, 0x48, 0x14, 0x64, 0xbd, 0x2f, 0x07, 0x04, 0x2a, 0x66, + 0x98, 0xd4, 0x64, 0x13, 0xfe, 0x6a, 0x85, 0x4c, 0xc8, 0x30, 0x1d, 0xba, 0x67, 0x5a, + ], len: 68280, - sha: [0xc3, 0xba, 0x39, 0xe3, 0xc2, 0xbe, 0x4e, 0xfb, 0x0a, 0xca, 0x00, 0x19, 0xe2, 0xaa, 0xe7, 0x47, 0xff, 0x00, 0x1d, 0x13, 0x63, 0x10, 0x16, 0xe5, 0xcc, 0x9f, 0xef, 0x86, 0x7e, 0x9a, 0xc1, 0xaf], + sha: [ + 0xc3, 0xba, 0x39, 0xe3, 0xc2, 0xbe, 0x4e, 0xfb, 0x0a, 0xca, 0x00, 0x19, 0xe2, 0xaa, 0xe7, 0x47, 0xff, 0x00, + 0x1d, 0x13, 0x63, 0x10, 0x16, 0xe5, 0xcc, 0x9f, 0xef, 0x86, 0x7e, 0x9a, 0xc1, 0xaf, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_prefill.ptx"), "\0").as_bytes(), }, Companion { name: "original_verify_qsa.ptx", - key: [0xf5, 0x7b, 0x41, 0x82, 0xe2, 0x19, 0x2b, 0xe7, 0xf5, 0xd3, 0x19, 0xe7, 0xa5, 0xe0, 0x2f, 0xaa, 0x5f, 0xc2, 0x45, 0xc0, 0x61, 0x42, 0x6c, 0xd2, 0xbf, 0xc1, 0x39, 0xcf, 0x45, 0x3a, 0xdc, 0x05], + key: [ + 0xf5, 0x7b, 0x41, 0x82, 0xe2, 0x19, 0x2b, 0xe7, 0xf5, 0xd3, 0x19, 0xe7, 0xa5, 0xe0, 0x2f, 0xaa, 0x5f, 0xc2, + 0x45, 0xc0, 0x61, 0x42, 0x6c, 0xd2, 0xbf, 0xc1, 0x39, 0xcf, 0x45, 0x3a, 0xdc, 0x05, + ], len: 19585, - sha: [0x22, 0xd6, 0x9a, 0x56, 0xf3, 0x88, 0xc1, 0xb3, 0x83, 0xc7, 0xb1, 0x25, 0xeb, 0x11, 0xcb, 0x36, 0xb5, 0xb0, 0xe8, 0x02, 0x6e, 0x95, 0x7b, 0x87, 0xad, 0x06, 0xce, 0x07, 0xc8, 0x02, 0x52, 0x40], + sha: [ + 0x22, 0xd6, 0x9a, 0x56, 0xf3, 0x88, 0xc1, 0xb3, 0x83, 0xc7, 0xb1, 0x25, 0xeb, 0x11, 0xcb, 0x36, 0xb5, 0xb0, + 0xe8, 0x02, 0x6e, 0x95, 0x7b, 0x87, 0xad, 0x06, 0xce, 0x07, 0xc8, 0x02, 0x52, 0x40, + ], ptx: concat!(include_str!("../ptx-sm86/original_verify_qsa.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_head_native.ptx", - key: [0xf8, 0x20, 0x9e, 0x1c, 0x9f, 0xbf, 0x97, 0x8b, 0xc5, 0x7b, 0x60, 0xb0, 0xb5, 0xf6, 0xed, 0xca, 0xb1, 0x90, 0x5e, 0x49, 0xa4, 0xab, 0x3a, 0xa9, 0x82, 0x60, 0x4e, 0x3e, 0x68, 0x0f, 0xa4, 0x37], + key: [ + 0xf8, 0x20, 0x9e, 0x1c, 0x9f, 0xbf, 0x97, 0x8b, 0xc5, 0x7b, 0x60, 0xb0, 0xb5, 0xf6, 0xed, 0xca, 0xb1, 0x90, + 0x5e, 0x49, 0xa4, 0xab, 0x3a, 0xa9, 0x82, 0x60, 0x4e, 0x3e, 0x68, 0x0f, 0xa4, 0x37, + ], len: 7459176, - sha: [0x6b, 0x0a, 0x23, 0x33, 0x72, 0xb7, 0x51, 0x3f, 0x8c, 0x6e, 0xef, 0xd7, 0xaa, 0x7e, 0x66, 0x34, 0x99, 0xb7, 0xe2, 0x38, 0x6c, 0xd8, 0x7c, 0x82, 0x73, 0xde, 0x22, 0xd7, 0x26, 0xa9, 0x84, 0xe5], + sha: [ + 0x6b, 0x0a, 0x23, 0x33, 0x72, 0xb7, 0x51, 0x3f, 0x8c, 0x6e, 0xef, 0xd7, 0xaa, 0x7e, 0x66, 0x34, 0x99, 0xb7, + 0xe2, 0x38, 0x6c, 0xd8, 0x7c, 0x82, 0x73, 0xde, 0x22, 0xd7, 0x26, 0xa9, 0x84, 0xe5, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_head_native.ptx"), "\0").as_bytes(), }, Companion { name: "iq3_xxs_q8_1.ptx", - key: [0xf9, 0xc1, 0x08, 0x14, 0xf3, 0x7b, 0x75, 0xba, 0xbc, 0xae, 0xe1, 0x02, 0x8b, 0x4a, 0x13, 0x75, 0xe5, 0x30, 0x22, 0x0f, 0x86, 0x3a, 0xb3, 0x80, 0x1b, 0xeb, 0x8f, 0xcb, 0x5a, 0x19, 0x73, 0x3f], + key: [ + 0xf9, 0xc1, 0x08, 0x14, 0xf3, 0x7b, 0x75, 0xba, 0xbc, 0xae, 0xe1, 0x02, 0x8b, 0x4a, 0x13, 0x75, 0xe5, 0x30, + 0x22, 0x0f, 0x86, 0x3a, 0xb3, 0x80, 0x1b, 0xeb, 0x8f, 0xcb, 0x5a, 0x19, 0x73, 0x3f, + ], len: 15564, - sha: [0x94, 0x65, 0x5f, 0x22, 0x89, 0x15, 0xdd, 0x3d, 0x0a, 0xe5, 0xdc, 0x3a, 0xde, 0xde, 0xf8, 0xfc, 0xeb, 0x06, 0x98, 0x20, 0xae, 0x17, 0xe1, 0x5d, 0xb9, 0x49, 0x44, 0x42, 0x79, 0x48, 0xaf, 0xda], + sha: [ + 0x94, 0x65, 0x5f, 0x22, 0x89, 0x15, 0xdd, 0x3d, 0x0a, 0xe5, 0xdc, 0x3a, 0xde, 0xde, 0xf8, 0xfc, 0xeb, 0x06, + 0x98, 0x20, 0xae, 0x17, 0xe1, 0x5d, 0xb9, 0x49, 0x44, 0x42, 0x79, 0x48, 0xaf, 0xda, + ], ptx: concat!(include_str!("../ptx-sm86/iq3_xxs_q8_1.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_native_gate.ptx", - key: [0xf9, 0xf7, 0x78, 0x15, 0x44, 0xa4, 0xa0, 0xb0, 0xb2, 0xf0, 0x73, 0x3f, 0xe0, 0x0f, 0x36, 0xb8, 0x19, 0x49, 0x54, 0x33, 0x3b, 0x9b, 0xca, 0x99, 0x95, 0x91, 0x40, 0x45, 0xd8, 0x6b, 0xaf, 0x1e], + key: [ + 0xf9, 0xf7, 0x78, 0x15, 0x44, 0xa4, 0xa0, 0xb0, 0xb2, 0xf0, 0x73, 0x3f, 0xe0, 0x0f, 0x36, 0xb8, 0x19, 0x49, + 0x54, 0x33, 0x3b, 0x9b, 0xca, 0x99, 0x95, 0x91, 0x40, 0x45, 0xd8, 0x6b, 0xaf, 0x1e, + ], len: 1356, - sha: [0x20, 0x00, 0x36, 0x45, 0x64, 0x34, 0x00, 0x9b, 0x96, 0x1c, 0x37, 0x1d, 0xa8, 0xa1, 0x44, 0x0d, 0xb1, 0x5a, 0x7b, 0xe9, 0x53, 0x19, 0xa8, 0xc8, 0x15, 0xe1, 0xbf, 0xe8, 0x00, 0x95, 0xf2, 0x1c], + sha: [ + 0x20, 0x00, 0x36, 0x45, 0x64, 0x34, 0x00, 0x9b, 0x96, 0x1c, 0x37, 0x1d, 0xa8, 0xa1, 0x44, 0x0d, 0xb1, 0x5a, + 0x7b, 0xe9, 0x53, 0x19, 0xa8, 0xc8, 0x15, 0xe1, 0xbf, 0xe8, 0x00, 0x95, 0xf2, 0x1c, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_native_gate.ptx"), "\0").as_bytes(), }, Companion { name: "mtp_original_full_s2.ptx", - key: [0xfb, 0xb9, 0x17, 0xd5, 0x90, 0xea, 0x80, 0x33, 0x8a, 0x7b, 0xdf, 0x07, 0xb2, 0xca, 0x6d, 0x45, 0x8f, 0xa7, 0x27, 0x63, 0xba, 0x27, 0x9e, 0x57, 0x6b, 0xcc, 0x1e, 0xec, 0x88, 0x36, 0xfd, 0x55], + key: [ + 0xfb, 0xb9, 0x17, 0xd5, 0x90, 0xea, 0x80, 0x33, 0x8a, 0x7b, 0xdf, 0x07, 0xb2, 0xca, 0x6d, 0x45, 0x8f, 0xa7, + 0x27, 0x63, 0xba, 0x27, 0x9e, 0x57, 0x6b, 0xcc, 0x1e, 0xec, 0x88, 0x36, 0xfd, 0x55, + ], len: 408620, - sha: [0x84, 0xfc, 0xa0, 0x77, 0x1f, 0xef, 0x37, 0x13, 0x49, 0xc7, 0x2a, 0xdd, 0xaf, 0x76, 0x73, 0x8a, 0xe9, 0xb7, 0x55, 0x39, 0x89, 0xb5, 0xab, 0xf6, 0x60, 0x0a, 0x22, 0x35, 0x93, 0x95, 0xae, 0x83], + sha: [ + 0x84, 0xfc, 0xa0, 0x77, 0x1f, 0xef, 0x37, 0x13, 0x49, 0xc7, 0x2a, 0xdd, 0xaf, 0x76, 0x73, 0x8a, 0xe9, 0xb7, + 0x55, 0x39, 0x89, 0xb5, 0xab, 0xf6, 0x60, 0x0a, 0x22, 0x35, 0x93, 0x95, 0xae, 0x83, + ], ptx: concat!(include_str!("../ptx-sm86/mtp_original_full_s2.ptx"), "\0").as_bytes(), }, Companion { name: "qsa_decode_postops.ptx", - key: [0xfd, 0x76, 0xe6, 0xf8, 0x45, 0x57, 0xd7, 0xf2, 0xa6, 0x2a, 0xc5, 0x6e, 0x16, 0xd5, 0xe4, 0xf7, 0x88, 0x62, 0xe7, 0x56, 0xef, 0x98, 0x52, 0xb0, 0x4d, 0x59, 0x19, 0x99, 0x21, 0x3a, 0x51, 0x19], + key: [ + 0xfd, 0x76, 0xe6, 0xf8, 0x45, 0x57, 0xd7, 0xf2, 0xa6, 0x2a, 0xc5, 0x6e, 0x16, 0xd5, 0xe4, 0xf7, 0x88, 0x62, + 0xe7, 0x56, 0xef, 0x98, 0x52, 0xb0, 0x4d, 0x59, 0x19, 0x99, 0x21, 0x3a, 0x51, 0x19, + ], len: 12390, - sha: [0x5f, 0xf2, 0x93, 0x19, 0x01, 0x09, 0x9c, 0x2c, 0xfd, 0xb6, 0x03, 0x94, 0x56, 0x52, 0x2a, 0x1e, 0x1c, 0x26, 0xae, 0x32, 0xb6, 0x1f, 0xdf, 0x69, 0xfb, 0xee, 0xd9, 0xc2, 0xca, 0x02, 0xdd, 0x1e], + sha: [ + 0x5f, 0xf2, 0x93, 0x19, 0x01, 0x09, 0x9c, 0x2c, 0xfd, 0xb6, 0x03, 0x94, 0x56, 0x52, 0x2a, 0x1e, 0x1c, 0x26, + 0xae, 0x32, 0xb6, 0x1f, 0xdf, 0x69, 0xfb, 0xee, 0xd9, 0xc2, 0xca, 0x02, 0xdd, 0x1e, + ], ptx: concat!(include_str!("../ptx-sm86/qsa_decode_postops.ptx"), "\0").as_bytes(), }, Companion { name: "moe_group_swiglu.ptx", - key: [0xfe, 0x6f, 0xba, 0x86, 0x65, 0x4b, 0x64, 0x65, 0x1f, 0xee, 0xe8, 0x43, 0x91, 0xba, 0x77, 0xb2, 0xb0, 0xab, 0xff, 0x8b, 0x06, 0x23, 0xcd, 0xad, 0x41, 0x69, 0x76, 0x95, 0x44, 0x39, 0x7a, 0xea], + key: [ + 0xfe, 0x6f, 0xba, 0x86, 0x65, 0x4b, 0x64, 0x65, 0x1f, 0xee, 0xe8, 0x43, 0x91, 0xba, 0x77, 0xb2, 0xb0, 0xab, + 0xff, 0x8b, 0x06, 0x23, 0xcd, 0xad, 0x41, 0x69, 0x76, 0x95, 0x44, 0x39, 0x7a, 0xea, + ], len: 4684, - sha: [0xbe, 0x94, 0x9a, 0x3e, 0xf8, 0xc4, 0x3c, 0x2f, 0xa1, 0x1a, 0x73, 0x63, 0x7d, 0x2d, 0x2b, 0x9c, 0x8d, 0x83, 0xdf, 0x56, 0xc2, 0x78, 0x49, 0x21, 0xeb, 0x7b, 0xc2, 0xb4, 0xf0, 0xb5, 0x72, 0x26], + sha: [ + 0xbe, 0x94, 0x9a, 0x3e, 0xf8, 0xc4, 0x3c, 0x2f, 0xa1, 0x1a, 0x73, 0x63, 0x7d, 0x2d, 0x2b, 0x9c, 0x8d, 0x83, + 0xdf, 0x56, 0xc2, 0x78, 0x49, 0x21, 0xeb, 0x7b, 0xc2, 0xb4, 0xf0, 0xb5, 0x72, 0x26, + ], ptx: concat!(include_str!("../ptx-sm86/moe_group_swiglu.ptx"), "\0").as_bytes(), }, ]; diff --git a/crates/cuda-driver/src/tests.rs b/crates/cuda-driver/src/tests.rs index 6a55069b..865154b0 100644 --- a/crates/cuda-driver/src/tests.rs +++ b/crates/cuda-driver/src/tests.rs @@ -5,34 +5,18 @@ #[ignore = "Root-only original-first owned whole-buffer readback proof"] fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { let driver = super::Driver::load().unwrap(); - let context = driver - .device(0) - .unwrap() - .create_context(16 * 1024 * 1024) - .unwrap(); + let context = driver.device(0).unwrap().create_context(16 * 1024 * 1024).unwrap(); let mut exact_bytes = 0usize; let mut bounds = 0usize; // Full real recurrence state, convolution history and readout extents. 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 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) - }; + 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(); @@ -44,16 +28,8 @@ fn owned_readback_original_first_preserves_gdn_extents_and_raw_words() { // 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() - ); + 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] { @@ -109,10 +85,7 @@ fn sizes_and_error_composition() { assert_eq!(valid_size(1), Ok(())); assert_eq!( combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)), - Err(Error::Multiple { - primary: Box::new(Error::InvalidSize), - secondary: Box::new(Error::UnexpectedContext) - }) + Err(Error::Multiple { primary: Box::new(Error::InvalidSize), secondary: Box::new(Error::UnexpectedContext) }) ); } #[test] @@ -122,10 +95,7 @@ fn vector_count_geometry_boundaries() { } for n in [1u32, 127, 128, 129, 1025, u32::MAX] { let bytes = usize::try_from(u64::from(n) * 4).unwrap(); - assert_eq!( - vector_shape(bytes), - Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap())) - ); + assert_eq!(vector_shape(bytes), Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap()))); } assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err()); } @@ -154,10 +124,7 @@ fn matvec_shape_boundaries() { assert_eq!(shape.vector_bytes, u32::MAX as usize * 4); let largest_columns = (isize::MAX as usize / 4) / u32::MAX as usize; assert!(matvec_shape(u32::MAX as usize, largest_columns).is_ok()); - assert_eq!( - matvec_shape(u32::MAX as usize, largest_columns + 1), - Err(Error::InvalidMatvecShape) - ); + assert_eq!(matvec_shape(u32::MAX as usize, largest_columns + 1), Err(Error::InvalidMatvecShape)); // Element count is deliberately not restricted to u32. assert!(matvec_shape(65536, 65536).is_ok()); } @@ -166,36 +133,20 @@ fn matvec_allocation_identity_and_absent_handles() { let shape = matvec_shape(1, 1).unwrap(); let h = |v| Some(ffi::BufferHandle::synthetic(v)); for handles in [(h(4), h(8), h(4)), (h(4), h(8), h(8))] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::OutputAliasesInput) - )); + assert!(matches!(matvec_allocations(handles.0, handles.1, handles.2, &shape), Err(Error::OutputAliasesInput))); } for handles in [(None, h(8), h(12)), (h(4), None, h(12)), (h(4), h(8), None)] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::ContextPoisoned) - )); + assert!(matches!(matvec_allocations(handles.0, handles.1, handles.2, &shape), Err(Error::ContextPoisoned))); } - for handles in [ - (h(u64::MAX - 3), h(8), h(12)), - (h(4), h(u64::MAX - 3), h(12)), - (h(4), h(8), h(u64::MAX - 3)), - ] { - assert!(matches!( - matvec_allocations(handles.0, handles.1, handles.2, &shape), - Err(Error::InvalidMatvecShape) - )); + for handles in [(h(u64::MAX - 3), h(8), h(12)), (h(4), h(u64::MAX - 3), h(12)), (h(4), h(8), h(u64::MAX - 3))] { + assert!(matches!(matvec_allocations(handles.0, handles.1, handles.2, &shape), Err(Error::InvalidMatvecShape))); } 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 driver = Driver { api: Rc::new(ffi::Api), version: 0 }; let context = Context { driver: &driver, handle: None, @@ -225,20 +176,11 @@ fn matvec_private_admission_refuses_without_cuda() { window_modules: RefCell::new(Vec::new()), deferred_frees: RefCell::new(Vec::new()), }; - let make = |handle| DeviceBuffer { - context: &context, - handle, - bytes: 4, - _thread: PhantomData, - borrowed: false, - }; + 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))); let mut output = make(Some(ffi::BufferHandle::synthetic(12))); - assert_eq!( - context.matvec_f32(&matrix, &vector, &mut output, 1, 1), - Err(Error::ContextPoisoned) - ); + assert_eq!(context.matvec_f32(&matrix, &vector, &mut output, 1, 1), Err(Error::ContextPoisoned)); // No native context exists in this test. Pure allocation identity and // extent instruments supply the remaining impossible-safe-call cases. assert_eq!(context.allocated_bytes(), 12); diff --git a/crates/cuda-driver/src/vram_ledger.rs b/crates/cuda-driver/src/vram_ledger.rs index 6392c8d0..e7420771 100644 --- a/crates/cuda-driver/src/vram_ledger.rs +++ b/crates/cuda-driver/src/vram_ledger.rs @@ -17,11 +17,7 @@ const TOP_SITES: usize = 24; /// Bytes of device memory the driver is estimated to reserve for one allocation of `bytes`. pub fn driver_bytes(bytes: usize) -> usize { - if bytes > PACKED_BELOW { - bytes.div_ceil(GRANULE) * GRANULE - } else { - bytes.next_multiple_of(256) - } + if bytes > PACKED_BELOW { bytes.div_ceil(GRANULE) * GRANULE } else { bytes.next_multiple_of(256) } } #[derive(Default, Clone)] @@ -87,7 +83,8 @@ impl Ledger { let driver: usize = self.driver_estimate(); let reported_live: usize = self.sites.iter().map(|s| s.reported_live).sum(); let reported_driver: usize = self.sites.iter().map(|s| s.reported_driver).sum(); - let mut grown: Vec = (0..self.sites.len()).filter(|&i| self.sites[i].live != self.sites[i].reported_live).collect(); + let mut grown: Vec = + (0..self.sites.len()).filter(|&i| self.sites[i].live != self.sites[i].reported_live).collect(); grown.sort_by_key(|&i| std::cmp::Reverse(self.sites[i].live.abs_diff(self.sites[i].reported_live))); let mut text = format!( "leleka-vram-ledger [{label}]: live {:.1} MiB requested / {:.1} MiB driver-estimated in {} allocations; since the last report {:+.1} MiB requested / {:+.1} MiB driver-estimated (granularity waste in the delta {:+.1} MiB), {} sites changed", @@ -114,7 +111,10 @@ impl Ledger { )); } if grown.len() > TOP_SITES { - let rest: f64 = grown[TOP_SITES..].iter().map(|&i| self.sites[i].live as f64 - self.sites[i].reported_live as f64).sum(); + let rest: f64 = grown[TOP_SITES..] + .iter() + .map(|&i| self.sites[i].live as f64 - self.sites[i].reported_live as f64) + .sum(); text.push_str(&format!("\n {:+9.1} MiB req in {} more sites", rest / MIB, grown.len() - TOP_SITES)); } for s in &mut self.sites { @@ -138,13 +138,18 @@ pub(crate) fn site_key(trace: &str) -> String { } let symbol = symbol.trim(); let symbol = match symbol.rfind("::h") { - Some(at) if symbol.len() - at == 19 && symbol[at + 3..].bytes().all(|b| b.is_ascii_hexdigit()) => &symbol[..at], + Some(at) if symbol.len() - at == 19 && symbol[at + 3..].bytes().all(|b| b.is_ascii_hexdigit()) => { + &symbol[..at] + } _ => symbol, }; if !(symbol.starts_with("leleka_") || symbol.starts_with(" c.project_q8_1( - w, - x, - y, - ProjectionSpec { - rows, - columns, - kind, - }, - ), + Format::Common(kind, _, _) => c.project_q8_1(w, x, y, ProjectionSpec { rows, columns, kind }), Format::Q5 => c.q5_k_q8_1(w, x, y, Q5KProjectionShape { rows, columns }), Format::Q6 => c.q6_k_q8_1(w, x, y, Q6KProjectionShape { rows, columns }), Format::Bf16 => c.bf16_f32(w, x, y, Bf16ProjectionShape { rows, columns }), @@ -79,11 +66,8 @@ fn compare(c: &Context<'_>, format: Format, name: &str, rows: usize, columns: us } let activation: 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. - }; + 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(); @@ -105,13 +89,7 @@ fn compare(c: &Context<'_>, format: Format, name: &str, rows: usize, columns: us tile_output.release().unwrap(); tile.release().unwrap(); } - for (i, (a, b)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(legacy.as_chunks::<4>().0.iter()) - .enumerate() - { + 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"); @@ -127,9 +105,7 @@ fn compare(c: &Context<'_>, format: Format, name: &str, rows: usize, columns: us whole.release().unwrap(); x.release().unwrap(); assert_eq!(c.allocated_bytes(), 0); - println!( - "FULL_MATRIX PASS {name} rows={rows} columns={columns} zero={zero} exact_words={rows}" - ); + println!("FULL_MATRIX PASS {name} rows={rows} columns={columns} zero={zero} exact_words={rows}"); } #[test] @@ -139,76 +115,21 @@ fn complete_selected_matrices_match_legacy_64_row_bits() { let device = driver.device(0).unwrap(); let context = device.create_context(128 * 1024 * 1024).unwrap(); let cases = [ - ( - "routed-gu-iq3xxs", - Format::Common(K::Routed(R::IQ3_XXS), 256, 98), - 640, - 2560, - ), - ( - "routed-gu-iq3s", - Format::Common(K::Routed(R::IQ3_S), 256, 110), - 640, - 2560, - ), - ( - "routed-gu-iq2s", - Format::Common(K::Routed(R::IQ2_S), 256, 82), - 640, - 2560, - ), - ( - "routed-gu-iq4xs", - Format::Common(K::Routed(R::IQ4_XS), 256, 136), - 640, - 2560, - ), - ( - "routed-down-iq4nl", - Format::Common(K::Routed(R::IQ4_NL), 32, 18), - 2560, - 640, - ), - ( - "routed-down-q2", - Format::Common(K::Routed(R::Q2_0), 64, 18), - 2560, - 640, - ), - ( - "shared-gu-q4k", - Format::Common(K::Dense(D::Q4_K), 256, 144), - 640, - 2560, - ), + ("routed-gu-iq3xxs", Format::Common(K::Routed(R::IQ3_XXS), 256, 98), 640, 2560), + ("routed-gu-iq3s", Format::Common(K::Routed(R::IQ3_S), 256, 110), 640, 2560), + ("routed-gu-iq2s", Format::Common(K::Routed(R::IQ2_S), 256, 82), 640, 2560), + ("routed-gu-iq4xs", Format::Common(K::Routed(R::IQ4_XS), 256, 136), 640, 2560), + ("routed-down-iq4nl", Format::Common(K::Routed(R::IQ4_NL), 32, 18), 2560, 640), + ("routed-down-q2", Format::Common(K::Routed(R::Q2_0), 64, 18), 2560, 640), + ("shared-gu-q4k", Format::Common(K::Dense(D::Q4_K), 256, 144), 640, 2560), ("shared-gu-q5k", Format::Q5, 640, 2560), ("shared-gu-q6k", Format::Q6, 640, 2560), - ( - "shared-gu-iq4xs", - Format::Common(K::Dense(D::IQ4_XS), 256, 136), - 640, - 2560, - ), - ( - "shared-down-iq4nl", - Format::Common(K::Dense(D::IQ4_NL), 32, 18), - 2560, - 640, - ), - ( - "shared-down-q8", - Format::Common(K::Dense(D::Q8_0), 32, 34), - 2560, - 640, - ), + ("shared-gu-iq4xs", Format::Common(K::Dense(D::IQ4_XS), 256, 136), 640, 2560), + ("shared-down-iq4nl", Format::Common(K::Dense(D::IQ4_NL), 32, 18), 2560, 640), + ("shared-down-q8", Format::Common(K::Dense(D::Q8_0), 32, 34), 2560, 640), ("dense-q6-qsa-q", Format::Q6, 12288, 2560), ("dense-q5-gdn-qkv", Format::Q5, 10240, 2560), - ( - "dense-q4-qsa-out", - Format::Common(K::Dense(D::Q4_K), 256, 144), - 2560, - 6144, - ), + ("dense-q4-qsa-out", Format::Common(K::Dense(D::Q4_K), 256, 144), 2560, 6144), ("dense-bf16-gdn-z", Format::Bf16, 6144, 2560), ]; for (name, format, rows, columns) in cases { diff --git a/crates/cuda-driver/tests/gpu_driver.rs b/crates/cuda-driver/tests/gpu_driver.rs index 0a1946d8..7560e94d 100644 --- a/crates/cuda-driver/tests/gpu_driver.rs +++ b/crates/cuda-driver/tests/gpu_driver.rs @@ -1,8 +1,4 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use leleka_cuda_driver::{Context, Device, DeviceBuffer, Driver, Error}; @@ -54,11 +50,7 @@ fn rounded_add(a: f32, b: f32) -> f32 { fn oracle(case: &MatvecCase) -> Vec { case.matrix .chunks_exact(case.vector.len()) - .map(|row| { - row.iter() - .zip(&case.vector) - .fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b))) - }) + .map(|row| row.iter().zip(&case.vector).fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b)))) .collect() } @@ -103,9 +95,7 @@ fn finish(context: Context<'_>) { fn double_output(context: &Context<'_>, input: &DeviceBuffer<'_>, values: &[f32]) { let expected: Vec<_> = values.iter().map(|&v| rounded_add(v, v)).collect(); let mut output = upload(context, &vec![f32::NAN; values.len()]); - context - .vector_add_f32(input, input, &mut output) - .expect("interleaved add"); + context.vector_add_f32(input, input, &mut output).expect("interleaved add"); assert_output(&output, &expected); output.release().expect("interleaved output free"); println!("VECTOR PASS count={} interleaved=true", values.len()); @@ -128,11 +118,7 @@ fn execute_matvec(context: &Context<'_>, case: &MatvecCase, interleave: bool) { vector.release().expect("vector free"); output.release().expect("output free"); assert_eq!(context.allocated_bytes(), 0); - println!( - "MATVEC PASS rows={} columns={}", - expected.len(), - case.vector.len() - ); + println!("MATVEC PASS rows={} columns={}", expected.len(), case.vector.len()); } fn launch_matvec( @@ -142,24 +128,13 @@ fn launch_matvec( output: &mut DeviceBuffer<'_>, ) { context - .matvec_f32( - inputs[0], - inputs[1], - output, - case.matrix.len() / case.vector.len(), - case.vector.len(), - ) + .matvec_f32(inputs[0], inputs[1], output, case.matrix.len() / case.vector.len(), case.vector.len()) .expect("installed-driver matvec launch, sync and restoration"); } fn arithmetic(device: &Device<'_>) { assert_eq!(rounded_add(rounded_add(16777216.0, -16777216.0), 1.0), 1.0); - assert_eq!( - f32::from_bits(0x3f800001) - .mul_add(f32::from_bits(0x3f7ffffe), -1.0) - .to_bits(), - 0xa8800000 - ); + assert_eq!(f32::from_bits(0x3f800001).mul_add(f32::from_bits(0x3f7ffffe), -1.0).to_bits(), 0xa8800000); for (index, &(a, b, expected)) in ARITHMETIC.iter().enumerate() { let case = MatvecCase { matrix: a.iter().map(|&bits| f32::from_bits(bits)).collect(), @@ -178,9 +153,7 @@ fn rectangular_case(rows: usize, columns: usize, offset: f32) -> MatvecCase { matrix: (0..rows) .flat_map(|r| (0..columns).map(move |c| offset + r as f32 * 0.25 + c as f32 * 0.125)) .collect(), - vector: (0..columns) - .map(|c| (c as f32 + 1.0) * if c.is_multiple_of(2) { 0.5 } else { -0.5 }) - .collect(), + vector: (0..columns).map(|c| (c as f32 + 1.0) * if c.is_multiple_of(2) { 0.5 } else { -0.5 }).collect(), } } @@ -192,9 +165,7 @@ fn shapes(device: &Device<'_>) { finish(context); } } - let context = device - .create_context(65536) - .expect("larger partial block context"); + let context = device.create_context(65536).expect("larger partial block context"); execute_matvec(&context, &rectangular_case(1025, 7, 1.0), false); finish(context); } @@ -204,9 +175,7 @@ fn shared_input(device: &Device<'_>) { let input = upload(&context, &[1.0, -2.0, 3.0]); let mut output = upload(&context, &[f32::NAN]); assert_eq!(context.allocated_bytes(), 16, "shared input charged once"); - context - .matvec_f32(&input, &input, &mut output, 1, 3) - .expect("shared immutable input"); + context.matvec_f32(&input, &input, &mut output, 1, 3).expect("shared immutable input"); assert_output(&output, &[14.0]); assert_eq!(read(&input), bytes(&[1.0, -2.0, 3.0])); input.release().expect("shared input free"); @@ -219,14 +188,8 @@ fn foreign_refusal(first: &Context<'_>, second: &Context<'_>) { let matrix = upload(first, &[2.0]); let vector = upload(second, &[3.0]); let mut output = upload(second, &[-0.0]); - assert_eq!( - second.matvec_f32(&matrix, &vector, &mut output, 1, 1), - Err(Error::ContextMismatch) - ); - assert_eq!( - second.matvec_f32(&vector, &vector, &mut output, 0, 1), - Err(Error::InvalidMatvecShape) - ); + assert_eq!(second.matvec_f32(&matrix, &vector, &mut output, 1, 1), Err(Error::ContextMismatch)); + assert_eq!(second.matvec_f32(&vector, &vector, &mut output, 0, 1), Err(Error::InvalidMatvecShape)); assert_eq!(read(&output), bytes(&[-0.0]), "refusals preserve output"); assert_eq!(first.allocated_bytes(), 4); assert_eq!(second.allocated_bytes(), 8); @@ -237,12 +200,8 @@ fn foreign_refusal(first: &Context<'_>, second: &Context<'_>) { } fn two_contexts(device: &Device<'_>) { - let first = device - .create_context(65536) - .expect("first concurrent context"); - let second = device - .create_context(65536) - .expect("second concurrent context"); + let first = device.create_context(65536).expect("first concurrent context"); + let second = device.create_context(65536).expect("second concurrent context"); foreign_refusal(&first, &second); for _ in 0..2 { execute_matvec(&first, &rectangular_case(129, 3, 1.0), true); @@ -253,24 +212,16 @@ fn two_contexts(device: &Device<'_>) { } fn vector_case(device: &Device<'_>, count: usize) { - let pairs: Vec<_> = (0..count) - .map(|i| ADD_INPUTS[i % ADD_INPUTS.len()]) - .collect(); + let pairs: Vec<_> = (0..count).map(|i| ADD_INPUTS[i % ADD_INPUTS.len()]).collect(); let a: Vec<_> = pairs.iter().map(|&(a, _)| f32::from_bits(a)).collect(); let b: Vec<_> = pairs.iter().map(|&(_, b)| f32::from_bits(b)).collect(); let expected: Vec<_> = a.iter().zip(&b).map(|(&a, &b)| rounded_add(a, b)).collect(); - assert_eq!( - expected[0].to_bits(), - 0x80000000, - "negative-zero add reference" - ); + assert_eq!(expected[0].to_bits(), 0x80000000, "negative-zero add reference"); let context = device.create_context(count * 12).expect("vector context"); let input_a = upload(&context, &a); let input_b = upload(&context, &b); let mut output = upload(&context, &vec![f32::NAN; count]); - context - .vector_add_f32(&input_a, &input_b, &mut output) - .expect("installed-driver vector add"); + context.vector_add_f32(&input_a, &input_b, &mut output).expect("installed-driver vector add"); assert_output(&output, &expected); assert_eq!(read(&input_a), bytes(&a)); assert_eq!(read(&input_b), bytes(&b)); diff --git a/crates/cuda-driver/tests/mock_driver.rs b/crates/cuda-driver/tests/mock_driver.rs index 05d4df0d..5b7b473e 100644 --- a/crates/cuda-driver/tests/mock_driver.rs +++ b/crates/cuda-driver/tests/mock_driver.rs @@ -197,20 +197,11 @@ const VECTOR_POISON: &[&str] = &[ const VECTOR_ERRORS: &[(&str, &[&str])] = &[ ("vector_load", &["cuModuleLoadData"]), ("vector_lookup", &["cuModuleGetFunction"]), - ( - "vector_lookup_unload", - &["cuModuleGetFunction", "cuModuleUnload"], - ), + ("vector_lookup_unload", &["cuModuleGetFunction", "cuModuleUnload"]), ("vector_launch", &["cuLaunchKernel"]), ("vector_sync", &["cuCtxSynchronize"]), - ( - "vector_launch_sync", - &["cuLaunchKernel", "cuCtxSynchronize"], - ), - ( - "vector_launch_sync_pop", - &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"], - ), + ("vector_launch_sync", &["cuLaunchKernel", "cuCtxSynchronize"]), + ("vector_launch_sync_pop", &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"]), ("vector_pop", &["cuCtxPopCurrent_v2"]), ("vector_push", &["cuCtxPushCurrent_v2"]), ]; @@ -265,20 +256,11 @@ const MATVEC_POISON: &[&str] = &[ const MATVEC_ERRORS: &[(&str, &[&str])] = &[ ("matvec_load", &["cuModuleLoadData"]), ("matvec_lookup", &["cuModuleGetFunction"]), - ( - "matvec_lookup_unload", - &["cuModuleGetFunction", "cuModuleUnload"], - ), + ("matvec_lookup_unload", &["cuModuleGetFunction", "cuModuleUnload"]), ("matvec_launch", &["cuLaunchKernel"]), ("matvec_sync", &["cuCtxSynchronize"]), - ( - "matvec_launch_sync", - &["cuLaunchKernel", "cuCtxSynchronize"], - ), - ( - "matvec_launch_sync_pop", - &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"], - ), + ("matvec_launch_sync", &["cuLaunchKernel", "cuCtxSynchronize"]), + ("matvec_launch_sync_pop", &["cuLaunchKernel", "cuCtxSynchronize", "cuCtxPopCurrent_v2"]), ("matvec_pop", &["cuCtxPopCurrent_v2"]), ("matvec_push", &["cuCtxPushCurrent_v2"]), ]; @@ -300,9 +282,21 @@ mod isolated_cpu_elf_matrix; #[path = "mock_driver/trace_fn.rs"] mod trace_fn; #[allow(unused_imports)] -use trace_fn::trace; +use trace_fn::bootstrap_allocation_bounds; #[allow(unused_imports)] -use trace_fn::valid_context_trace; +use trace_fn::bootstrap_buffer_bounds; +#[allow(unused_imports)] +use trace_fn::bootstrap_buffer_path; +#[allow(unused_imports)] +use trace_fn::bootstrap_child; +#[allow(unused_imports)] +use trace_fn::bootstrap_create; +#[allow(unused_imports)] +use trace_fn::bootstrap_early_fault; +#[allow(unused_imports)] +use trace_fn::bootstrap_load_failure; +#[allow(unused_imports)] +use trace_fn::configure_faults; #[allow(unused_imports)] use trace_fn::cuda_errors; #[allow(unused_imports)] @@ -312,142 +306,130 @@ use trace_fn::scenario_command; #[allow(unused_imports)] use trace_fn::scenario_failure; #[allow(unused_imports)] -use trace_fn::configure_faults; +use trace_fn::trace; #[allow(unused_imports)] -use trace_fn::bootstrap_load_failure; -#[allow(unused_imports)] -use trace_fn::bootstrap_child; -#[allow(unused_imports)] -use trace_fn::bootstrap_create; -#[allow(unused_imports)] -use trace_fn::bootstrap_early_fault; -#[allow(unused_imports)] -use trace_fn::bootstrap_allocation_bounds; -#[allow(unused_imports)] -use trace_fn::bootstrap_buffer_path; -#[allow(unused_imports)] -use trace_fn::bootstrap_buffer_bounds; +use trace_fn::valid_context_trace; #[path = "mock_driver/bootstrap_copies_fn.rs"] mod bootstrap_copies_fn; #[allow(unused_imports)] +use bootstrap_copies_fn::bootstrap_close; +#[allow(unused_imports)] use bootstrap_copies_fn::bootstrap_copies; #[allow(unused_imports)] use bootstrap_copies_fn::bootstrap_copy_errors; #[allow(unused_imports)] -use bootstrap_copies_fn::bootstrap_htod_fault; -#[allow(unused_imports)] -use bootstrap_copies_fn::bootstrap_dtoh_fault; -#[allow(unused_imports)] -use bootstrap_copies_fn::bootstrap_release; -#[allow(unused_imports)] -use bootstrap_copies_fn::bootstrap_close; -#[allow(unused_imports)] use bootstrap_copies_fn::bootstrap_copy_trace; #[allow(unused_imports)] -use bootstrap_copies_fn::bootstrap_pending_trace; +use bootstrap_copies_fn::bootstrap_dtoh_fault; #[allow(unused_imports)] use bootstrap_copies_fn::bootstrap_failed_copy_sync; #[allow(unused_imports)] use bootstrap_copies_fn::bootstrap_final_trace; #[allow(unused_imports)] -use bootstrap_copies_fn::vector_count; +use bootstrap_copies_fn::bootstrap_htod_fault; #[allow(unused_imports)] -use bootstrap_copies_fn::vector_fixture; +use bootstrap_copies_fn::bootstrap_pending_trace; +#[allow(unused_imports)] +use bootstrap_copies_fn::bootstrap_release; #[allow(unused_imports)] use bootstrap_copies_fn::vector_call; #[allow(unused_imports)] use bootstrap_copies_fn::vector_child; +#[allow(unused_imports)] +use bootstrap_copies_fn::vector_count; +#[allow(unused_imports)] +use bootstrap_copies_fn::vector_fixture; #[path = "mock_driver/vector_bounds_fn.rs"] mod vector_bounds_fn; #[allow(unused_imports)] use vector_bounds_fn::vector_bounds; #[allow(unused_imports)] -use vector_bounds_fn::vector_error; -#[allow(unused_imports)] -use vector_bounds_fn::vector_poison_refusals; -#[allow(unused_imports)] -use vector_bounds_fn::vector_expected; -#[allow(unused_imports)] -use vector_bounds_fn::vector_success; -#[allow(unused_imports)] -use vector_bounds_fn::vector_second_context; +use vector_bounds_fn::vector_cache_trace; #[allow(unused_imports)] use vector_bounds_fn::vector_close; #[allow(unused_imports)] -use vector_bounds_fn::vector_trace; +use vector_bounds_fn::vector_error; #[allow(unused_imports)] -use vector_bounds_fn::vector_cache_trace; +use vector_bounds_fn::vector_expected; #[allow(unused_imports)] -use vector_bounds_fn::vector_successful_cache_trace; +use vector_bounds_fn::vector_fault_trace; #[allow(unused_imports)] use vector_bounds_fn::vector_launch_sync; #[allow(unused_imports)] -use vector_bounds_fn::vector_fault_trace; +use vector_bounds_fn::vector_poison_refusals; +#[allow(unused_imports)] +use vector_bounds_fn::vector_second_context; +#[allow(unused_imports)] +use vector_bounds_fn::vector_success; +#[allow(unused_imports)] +use vector_bounds_fn::vector_successful_cache_trace; +#[allow(unused_imports)] +use vector_bounds_fn::vector_trace; #[path = "mock_driver/vector_module_context_trace_fn.rs"] mod vector_module_context_trace_fn; #[allow(unused_imports)] -use vector_module_context_trace_fn::vector_module_context_trace; -#[allow(unused_imports)] -use vector_module_context_trace_fn::f32_bytes; -#[allow(unused_imports)] -use vector_module_context_trace_fn::rounded_product; -#[allow(unused_imports)] -use vector_module_context_trace_fn::rounded_add; -#[allow(unused_imports)] -use vector_module_context_trace_fn::matvec_oracle; +use vector_module_context_trace_fn::check_arithmetic_fixture; #[allow(unused_imports)] use vector_module_context_trace_fn::check_f32_output; #[allow(unused_imports)] +use vector_module_context_trace_fn::check_matvec_dimensions; +#[allow(unused_imports)] +use vector_module_context_trace_fn::check_matvec_foreign; +#[allow(unused_imports)] +use vector_module_context_trace_fn::f32_bytes; +#[allow(unused_imports)] use vector_module_context_trace_fn::matvec_arithmetic; #[allow(unused_imports)] -use vector_module_context_trace_fn::check_arithmetic_fixture; -#[allow(unused_imports)] -use vector_module_context_trace_fn::matvec_rows; -#[allow(unused_imports)] -use vector_module_context_trace_fn::matvec_fixture; +use vector_module_context_trace_fn::matvec_bounds; #[allow(unused_imports)] use vector_module_context_trace_fn::matvec_call; #[allow(unused_imports)] use vector_module_context_trace_fn::matvec_child; #[allow(unused_imports)] -use vector_module_context_trace_fn::matvec_bounds; +use vector_module_context_trace_fn::matvec_fixture; #[allow(unused_imports)] -use vector_module_context_trace_fn::check_matvec_dimensions; +use vector_module_context_trace_fn::matvec_oracle; #[allow(unused_imports)] -use vector_module_context_trace_fn::check_matvec_foreign; +use vector_module_context_trace_fn::matvec_rows; +#[allow(unused_imports)] +use vector_module_context_trace_fn::rounded_add; +#[allow(unused_imports)] +use vector_module_context_trace_fn::rounded_product; +#[allow(unused_imports)] +use vector_module_context_trace_fn::vector_module_context_trace; #[path = "mock_driver/check_matvec_lengths_fn.rs"] mod check_matvec_lengths_fn; #[allow(unused_imports)] -use check_matvec_lengths_fn::check_matvec_lengths; -#[allow(unused_imports)] use check_matvec_lengths_fn::check_matvec_bad_length; #[allow(unused_imports)] -use check_matvec_lengths_fn::check_matvec_error; -#[allow(unused_imports)] -use check_matvec_lengths_fn::matvec_poison_refusals; -#[allow(unused_imports)] -use check_matvec_lengths_fn::release_poisoned_fixture; -#[allow(unused_imports)] -use check_matvec_lengths_fn::check_poison_trace; -#[allow(unused_imports)] -use check_matvec_lengths_fn::matvec_success; -#[allow(unused_imports)] -use check_matvec_lengths_fn::matvec_interleave; -#[allow(unused_imports)] -use check_matvec_lengths_fn::matvec_second_context; +use check_matvec_lengths_fn::check_matvec_cache_trace; #[allow(unused_imports)] use check_matvec_lengths_fn::check_matvec_close; #[allow(unused_imports)] +use check_matvec_lengths_fn::check_matvec_error; +#[allow(unused_imports)] +use check_matvec_lengths_fn::check_matvec_lengths; +#[allow(unused_imports)] use check_matvec_lengths_fn::check_matvec_trace; #[allow(unused_imports)] -use check_matvec_lengths_fn::check_matvec_cache_trace; +use check_matvec_lengths_fn::check_poison_trace; +#[allow(unused_imports)] +use check_matvec_lengths_fn::matvec_interleave; +#[allow(unused_imports)] +use check_matvec_lengths_fn::matvec_poison_refusals; +#[allow(unused_imports)] +use check_matvec_lengths_fn::matvec_second_context; +#[allow(unused_imports)] +use check_matvec_lengths_fn::matvec_success; +#[allow(unused_imports)] +use check_matvec_lengths_fn::release_poisoned_fixture; #[path = "mock_driver/matvec_launch_count_fn.rs"] mod matvec_launch_count_fn; #[allow(unused_imports)] -use matvec_launch_count_fn::matvec_launch_count; -#[allow(unused_imports)] -use matvec_launch_count_fn::check_matvec_geometry; +use matvec_launch_count_fn::check_launch_sync; #[allow(unused_imports)] use matvec_launch_count_fn::check_matvec_both_cleanup; #[allow(unused_imports)] -use matvec_launch_count_fn::check_launch_sync; +use matvec_launch_count_fn::check_matvec_geometry; +#[allow(unused_imports)] +use matvec_launch_count_fn::matvec_launch_count; 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 d07e87eb..be327967 100644 --- a/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/bootstrap_copies_fn.rs @@ -89,10 +89,7 @@ pub(super) fn bootstrap_release( } pub(super) fn bootstrap_close(context: leleka_cuda_driver::Context<'_>, case: &str) { if case == "destroy" { - assert_eq!( - cuda_errors(&context.close().unwrap_err()), - vec![("cuCtxDestroy_v2", 700)] - ); + assert_eq!(cuda_errors(&context.close().unwrap_err()), vec![("cuCtxDestroy_v2", 700)]); } else if COPY_POISON.contains(&case) { drop(context); } else { @@ -106,64 +103,33 @@ pub(super) fn bootstrap_copy_trace(case: &str, rows: &[Row], output: [u8; 8]) { pub(super) fn bootstrap_pending_trace(case: &str, rows: &[Row], output: [u8; 8]) { if case == "sync_htod" { assert!( - rows.iter() - .any(|r| r.stage == "pending_htod" && r.code == 0 && r.bytes == 644), + rows.iter().any(|r| r.stage == "pending_htod" && r.code == 0 && r.bytes == 644), "delayed source retained original owned bytes after caller input changed" ); } if case == "sync_dtoh" { - assert!( - rows.iter() - .any(|r| r.stage == "pending_dtoh" && r.bytes == 8) - ); - assert_eq!( - output, [0x99; 8], - "completion after failed sync targets retained staging, never caller output" - ); + assert!(rows.iter().any(|r| r.stage == "pending_dtoh" && r.bytes == 8)); + assert_eq!(output, [0x99; 8], "completion after failed sync targets retained staging, never caller output"); } } pub(super) fn bootstrap_failed_copy_sync(case: &str, rows: &[Row]) { if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case) { - let copy = if case.starts_with("htod") { - "htod" - } else { - "dtoh" - }; - let index = rows - .iter() - .position(|r| r.stage == copy && r.code == 700) - .unwrap(); - assert_eq!( - rows[index + 1].stage, - "sync", - "sync must be attempted after copy failure" - ); - assert_eq!( - rows[index + 1].code, - if case.ends_with("_sync") { 700 } else { 0 } - ); + let copy = if case.starts_with("htod") { "htod" } else { "dtoh" }; + let index = rows.iter().position(|r| r.stage == copy && r.code == 700).unwrap(); + assert_eq!(rows[index + 1].stage, "sync", "sync must be attempted after copy failure"); + assert_eq!(rows[index + 1].code, if case.ends_with("_sync") { 700 } else { 0 }); } } pub(super) fn bootstrap_final_trace(case: &str, rows: &[Row]) { valid_context_trace(rows); - assert!( - rows.iter().any(|r| r.stage == "destroy"), - "owned context cleanup attempted" - ); - assert!( - !rows.iter().any(|r| r.stage == "unsafe_pending_free"), - "pending copy device freed early" - ); + assert!(rows.iter().any(|r| r.stage == "destroy"), "owned context cleanup attempted"); + assert!(!rows.iter().any(|r| r.stage == "unsafe_pending_free"), "pending copy device freed early"); for r in rows.iter().filter(|r| r.stage == "alloc" && r.code == 0) { assert_eq!(r.bytes, 8); assert_eq!(r.charged, 8); } if case != "destroy" { - let r = rows - .iter() - .rev() - .find(|r| r.stage == "destroy" && r.code == 0) - .unwrap(); + let r = rows.iter().rev().find(|r| r.stage == "destroy" && r.code == 0).unwrap(); assert_eq!(r.live, 0); assert_eq!(r.charged, 0); assert_eq!(r.current, 0x11); @@ -172,45 +138,20 @@ pub(super) fn bootstrap_final_trace(case: &str, rows: &[Row]) { pub(super) fn vector_count(case: &str) -> usize { case.strip_prefix("vector_").unwrap().parse().unwrap_or(129) } -pub(super) fn vector_fixture<'a>( - context: &'a leleka_cuda_driver::Context<'a>, - case: &'a str, -) -> VectorFixture<'a> { +pub(super) fn vector_fixture<'a>(context: &'a leleka_cuda_driver::Context<'a>, case: &'a str) -> VectorFixture<'a> { let count = vector_count(case); let bytes = count * 4; let mut a = context.allocate(bytes).unwrap(); let mut b = context.allocate(bytes).unwrap(); let out = context.allocate(bytes).unwrap(); - let av: Vec<_> = (0..count) - .map(|i| (i as i32 % 31 - 15) as f32 * 0.5) - .collect(); - let bv: Vec<_> = (0..count) - .map(|i| (i as i32 % 23 - 11) as f32 * 0.25) - .collect(); + let av: Vec<_> = (0..count).map(|i| (i as i32 % 31 - 15) as f32 * 0.5).collect(); + let bv: Vec<_> = (0..count).map(|i| (i as i32 % 23 - 11) as f32 * 0.25).collect(); a.copy_from(&f32_bytes(&av)).unwrap(); b.copy_from(&f32_bytes(&bv)).unwrap(); - VectorFixture { - context, - case, - a, - b, - out, - av, - bv, - count, - bytes, - } + VectorFixture { context, case, a, b, out, av, bv, count, bytes } } pub(super) fn vector_call(f: &mut VectorFixture<'_>) -> leleka_cuda_driver::Result<()> { - f.context.vector_add_f32( - &f.a, - if f.case == "vector_same_input" { - &f.a - } else { - &f.b - }, - &mut f.out, - ) + f.context.vector_add_f32(&f.a, if f.case == "vector_same_input" { &f.a } else { &f.b }, &mut f.out) } pub(super) fn vector_child(case: &str) { let driver = Driver::load().unwrap(); 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 a4837b26..3dc6317e 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 @@ -16,15 +16,9 @@ pub(super) fn check_matvec_bad_length(f: &mut MatvecFixture<'_>, slot: usize, by let before = trace().len(); let charged = f.context.allocated_bytes(); let error = match slot { - 0 => f - .context - .matvec_f32(&bad, &f.b, &mut f.out, f.rows, f.columns), - 1 => f - .context - .matvec_f32(&f.a, &bad, &mut f.out, f.rows, f.columns), - _ => f - .context - .matvec_f32(&f.a, &f.b, &mut bad, f.rows, f.columns), + 0 => f.context.matvec_f32(&bad, &f.b, &mut f.out, f.rows, f.columns), + 1 => f.context.matvec_f32(&f.a, &bad, &mut f.out, f.rows, f.columns), + _ => f.context.matvec_f32(&f.a, &f.b, &mut bad, f.rows, f.columns), }; assert_eq!(error, Err(leleka_cuda_driver::Error::InvalidMatvecShape)); assert_eq!(trace().len(), before); @@ -32,15 +26,8 @@ pub(super) fn check_matvec_bad_length(f: &mut MatvecFixture<'_>, slot: usize, by } pub(super) fn check_matvec_error(case: &str, error: leleka_cuda_driver::Error) { use leleka_cuda_driver::Error; - let expected = MATVEC_ERRORS - .iter() - .find(|r| r.0 == case) - .map(|r| r.1) - .unwrap_or(&[]); - assert_eq!( - cuda_errors(&error), - expected.iter().map(|&s| (s, 700)).collect::>() - ); + let expected = MATVEC_ERRORS.iter().find(|r| r.0 == case).map(|r| r.1).unwrap_or(&[]); + assert_eq!(cuda_errors(&error), expected.iter().map(|&s| (s, 700)).collect::>()); match case { "matvec_null_load" => assert_eq!(error, Error::InvalidDriverValue("cuModuleLoadData")), "matvec_null_function" => { @@ -54,19 +41,10 @@ pub(super) fn matvec_poison_refusals(f: &mut MatvecFixture<'_>) { use leleka_cuda_driver::Error; let before = trace().len(); assert_eq!(matvec_call(f), Err(Error::ContextPoisoned)); - assert_eq!( - f.context.vector_add_f32(&f.a, &f.b, &mut f.out), - Err(Error::ContextPoisoned) - ); + assert_eq!(f.context.vector_add_f32(&f.a, &f.b, &mut f.out), Err(Error::ContextPoisoned)); assert!(matches!(f.context.allocate(4), Err(Error::ContextPoisoned))); - assert_eq!( - f.a.copy_from(&f32_bytes(&f.matrix)), - Err(Error::ContextPoisoned) - ); - assert_eq!( - f.b.copy_to(&mut vec![0; f.columns * 4]), - Err(Error::ContextPoisoned) - ); + assert_eq!(f.a.copy_from(&f32_bytes(&f.matrix)), Err(Error::ContextPoisoned)); + assert_eq!(f.b.copy_to(&mut vec![0; f.columns * 4]), Err(Error::ContextPoisoned)); assert_eq!(f.context.synchronize(), Err(Error::ContextPoisoned)); assert_eq!(trace().len(), before); } @@ -83,15 +61,9 @@ pub(super) fn release_poisoned_fixture(f: MatvecFixture<'_>) { pub(super) fn check_poison_trace(case: &str) { let rows = trace(); assert!(!rows.iter().any(|r| r.stage == "free")); - assert_eq!( - rows.iter().filter(|r| r.stage == "unload").count(), - usize::from(case == "matvec_lookup_unload") - ); + assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), usize::from(case == "matvec_lookup_unload")); if case.contains("sync") { - assert!( - rows.iter() - .any(|r| r.stage == "pending_matvec" && r.bytes == 3) - ); + assert!(rows.iter().any(|r| r.stage == "pending_matvec" && r.bytes == 3)); } check_launch_sync(&rows); } @@ -102,14 +74,7 @@ pub(super) fn matvec_success(device: &leleka_cuda_driver::Device<'_>, f: &mut Ma if f.case.contains("interleave") || f.case.starts_with("matvec_both_") { matvec_interleave(f); } - let expected = matvec_oracle( - &f.matrix, - if f.case == "matvec_same_input" { - &f.matrix - } else { - &f.vector - }, - ); + let expected = matvec_oracle(&f.matrix, if f.case == "matvec_same_input" { &f.matrix } else { &f.vector }); let mut actual = vec![0; f.rows * 4]; f.out.copy_to(&mut actual).unwrap(); check_f32_output(&actual, &expected); @@ -125,30 +90,20 @@ pub(super) fn matvec_success(device: &leleka_cuda_driver::Device<'_>, f: &mut Ma } pub(super) fn matvec_interleave(f: &mut MatvecFixture<'_>) { let mut add_out = f.context.allocate(f.rows * 4).unwrap(); - f.context - .vector_add_f32(&f.out, &f.out, &mut add_out) - .unwrap(); + f.context.vector_add_f32(&f.out, &f.out, &mut add_out).unwrap(); matvec_call(f).unwrap(); if f.case == "matvec_interleave_reverse" { - f.context - .vector_add_f32(&f.out, &f.out, &mut add_out) - .unwrap(); + f.context.vector_add_f32(&f.out, &f.out, &mut add_out).unwrap(); } } -pub(super) fn matvec_second_context( - device: &leleka_cuda_driver::Device<'_>, - f: &MatvecFixture<'_>, - expected: &[f32], -) { +pub(super) fn matvec_second_context(device: &leleka_cuda_driver::Device<'_>, f: &MatvecFixture<'_>, expected: &[f32]) { let second = device.create_context(65536).unwrap(); let mut x = second.allocate(f.a.len()).unwrap(); let mut y = second.allocate(f.b.len()).unwrap(); let mut z = second.allocate(f.out.len()).unwrap(); x.copy_from(&f32_bytes(&f.matrix)).unwrap(); y.copy_from(&f32_bytes(&f.vector)).unwrap(); - second - .matvec_f32(&x, &y, &mut z, f.rows, f.columns) - .unwrap(); + second.matvec_f32(&x, &y, &mut z, f.rows, f.columns).unwrap(); let mut actual = vec![0; f.rows * 4]; z.copy_to(&mut actual).unwrap(); check_f32_output(&actual, expected); @@ -198,41 +153,21 @@ pub(super) fn check_matvec_trace(case: &str, dimensions: (usize, usize)) { assert_eq!(order, ["unload_add", "unload_matvec"]); } if !["matvec_close_destroy", "matvec_unload_destroy"].contains(&case) { - let last = rows - .iter() - .rev() - .find(|r| r.stage == "destroy" && r.code == 0) - .unwrap(); + let last = rows.iter().rev().find(|r| r.stage == "destroy" && r.code == 0).unwrap(); assert_eq!(last.current, 0x11); assert_eq!(last.live, 0); assert_eq!(last.charged, 0); } } pub(super) fn check_matvec_cache_trace(case: &str, (m, n): (usize, usize), rows: &[Row]) { - let modules = if case == "matvec_contexts" - || case.contains("interleave") - || case.starts_with("matvec_both_") - { + let modules = if case == "matvec_contexts" || case.contains("interleave") || case.starts_with("matvec_both_") { 2 } else { 1 }; - assert_eq!( - rows.iter() - .filter(|r| r.stage == "load" && r.code == 0) - .count(), - modules - ); - assert_eq!( - rows.iter() - .filter(|r| r.stage == "lookup" && r.code == 0) - .count(), - modules - ); + assert_eq!(rows.iter().filter(|r| r.stage == "load" && r.code == 0).count(), modules); + assert_eq!(rows.iter().filter(|r| r.stage == "lookup" && r.code == 0).count(), modules); check_matvec_geometry((m, n), rows); let launches = matvec_launch_count(case); - assert_eq!( - rows.iter().filter(|r| r.stage == "launch").count(), - launches - ); + assert_eq!(rows.iter().filter(|r| r.stage == "launch").count(), launches); } diff --git a/crates/cuda-driver/tests/mock_driver/isolated_cpu_elf_matrix.rs b/crates/cuda-driver/tests/mock_driver/isolated_cpu_elf_matrix.rs index b9324052..006c6324 100644 --- a/crates/cuda-driver/tests/mock_driver/isolated_cpu_elf_matrix.rs +++ b/crates/cuda-driver/tests/mock_driver/isolated_cpu_elf_matrix.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] #[ignore = "requires isolated CPU-only fake libcuda harness"] fn isolated_cpu_elf_matrix() { 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 da8a6416..a4175310 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 @@ -15,29 +15,14 @@ pub(super) fn matvec_launch_count(case: &str) -> usize { } } pub(super) fn check_matvec_geometry((m, n): (usize, usize), rows: &[Row]) { - assert!( - rows.iter() - .filter(|r| r.stage == "matvec_rows") - .all(|r| r.bytes == m) - ); - assert!( - rows.iter() - .filter(|r| r.stage == "matvec_columns") - .all(|r| r.bytes == n) - ); - assert!( - rows.iter() - .filter(|r| r.stage == "geometry") - .all(|r| r.bytes == m.div_ceil(128)) - ); + assert!(rows.iter().filter(|r| r.stage == "matvec_rows").all(|r| r.bytes == m)); + assert!(rows.iter().filter(|r| r.stage == "matvec_columns").all(|r| r.bytes == n)); + assert!(rows.iter().filter(|r| r.stage == "geometry").all(|r| r.bytes == m.div_ceil(128))); } pub(super) fn check_matvec_both_cleanup(case: &str, rows: &[Row]) { assert_eq!(rows.iter().filter(|r| r.stage == "module_add").count(), 1); - assert_eq!( - rows.iter().filter(|r| r.stage == "module_matvec").count(), - 1 - ); + assert_eq!(rows.iter().filter(|r| r.stage == "module_matvec").count(), 1); let attempts = rows.iter().filter(|r| r.stage == "unload").count(); let expected = if case.ends_with("matvec") { if case.contains("push") { 1 } else { 2 } @@ -46,27 +31,17 @@ pub(super) fn check_matvec_both_cleanup(case: &str, rows: &[Row]) { } else { 1 }; - assert_eq!( - attempts, expected, - "fault suppresses unsafe later slot unload" - ); + assert_eq!(attempts, expected, "fault suppresses unsafe later slot unload"); } pub(super) fn check_launch_sync(rows: &[Row]) { - assert!(!rows.iter().any(|r| { - [ - "unsafe_pending_free", - "unsafe_pending_unload", - "stack_arguments", - ] - .contains(&r.stage.as_str()) - })); + assert!( + !rows.iter().any(|r| { + ["unsafe_pending_free", "unsafe_pending_unload", "stack_arguments"].contains(&r.stage.as_str()) + }) + ); for (i, _) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") { assert_eq!( - rows[i + 1..] - .iter() - .take_while(|r| r.stage != "pop") - .filter(|r| r.stage == "sync") - .count(), + rows[i + 1..].iter().take_while(|r| r.stage != "pop").filter(|r| r.stage == "sync").count(), 1, "exactly one mandatory sync after each attempt" ); diff --git a/crates/cuda-driver/tests/mock_driver/trace_fn.rs b/crates/cuda-driver/tests/mock_driver/trace_fn.rs index 3a51496a..c998d31b 100644 --- a/crates/cuda-driver/tests/mock_driver/trace_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/trace_fn.rs @@ -74,11 +74,7 @@ pub(super) fn scenario_command(root: &std::path::Path, scenario: &str) -> Comman if scenario.starts_with("vector_") || scenario.starts_with("matvec_") { command.env("MOCK_CUDA_VECTOR", "1"); } - let library = if scenario.starts_with("missing") { - scenario - } else { - "complete" - }; + let library = if scenario.starts_with("missing") { scenario } else { "complete" }; command.env("LD_LIBRARY_PATH", root.join(library)); command } @@ -89,15 +85,7 @@ pub(super) fn scenario_failure(scenario: &str) -> Option<&str> { if scenario.starts_with("matvec_") || scenario.starts_with("vector_") { return None; } - if [ - "success", - "bounds", - "missing", - "wrong_pop", - "operation_wrong_pop", - ] - .contains(&scenario) - { + if ["success", "bounds", "missing", "wrong_pop", "operation_wrong_pop"].contains(&scenario) { return None; } Some(scenario) @@ -117,9 +105,7 @@ pub(super) fn configure_faults(command: &mut Command, scenario: &str) { } } pub(super) fn bootstrap_load_failure(case: &str) { - let error = Driver::load() - .err() - .expect("missing ABI/init/version must fail"); + let error = Driver::load().err().expect("missing ABI/init/version must fail"); if case.starts_with("missing") { let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2"); assert!(matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol)); @@ -176,10 +162,7 @@ pub(super) fn bootstrap_create(device: &leleka_cuda_driver::Device<'_>, case: &s if case == "create" { assert!(!rows.iter().any(|row| row.stage == "destroy")); } else { - assert!( - rows.iter() - .any(|row| row.stage == "destroy" && row.code == 0) - ); + assert!(rows.iter().any(|row| row.stage == "destroy" && row.code == 0)); } true } @@ -231,9 +214,5 @@ pub(super) fn bootstrap_buffer_bounds( let mut short = [0x99; 7]; assert!(buffer.copy_to(&mut short).is_err()); assert_eq!(short, [0x99; 7]); - assert_eq!( - trace().len(), - before, - "bounds reject before driver mutation" - ); + assert_eq!(trace().len(), before, "bounds reject before driver mutation"); } 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 7f06165e..658b51eb 100644 --- a/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs +++ b/crates/cuda-driver/tests/mock_driver/vector_bounds_fn.rs @@ -11,10 +11,7 @@ pub(super) fn vector_bounds(device: &leleka_cuda_driver::Device<'_>, f: &mut Vec let odd = f.context.allocate(3).unwrap(); let mut odd_out = f.context.allocate(3).unwrap(); let before = trace().len(); - assert!(matches!( - f.context.vector_add_f32(&foreign_input, &f.b, &mut f.out), - Err(Error::ContextMismatch) - )); + assert!(matches!(f.context.vector_add_f32(&foreign_input, &f.b, &mut f.out), Err(Error::ContextMismatch))); assert!(f.context.vector_add_f32(&f.a, &short, &mut f.out).is_err()); assert!(f.context.vector_add_f32(&odd, &odd, &mut odd_out).is_err()); assert_eq!(trace().len(), before, "validation before ABI mutation"); @@ -23,26 +20,13 @@ pub(super) fn vector_bounds(device: &leleka_cuda_driver::Device<'_>, f: &mut Vec } pub(super) fn vector_error(case: &str, error: leleka_cuda_driver::Error) { use leleka_cuda_driver::Error; - let expected = VECTOR_ERRORS - .iter() - .find(|r| r.0 == case) - .map(|r| r.1) - .unwrap_or(&[]); - assert_eq!( - cuda_errors(&error), - expected.iter().map(|&s| (s, 700)).collect::>() - ); + let expected = VECTOR_ERRORS.iter().find(|r| r.0 == case).map(|r| r.1).unwrap_or(&[]); + assert_eq!(cuda_errors(&error), expected.iter().map(|&s| (s, 700)).collect::>()); if case == "vector_null_load" { - assert!(matches!( - error, - Error::InvalidDriverValue("cuModuleLoadData") - )); + assert!(matches!(error, Error::InvalidDriverValue("cuModuleLoadData"))); } if case == "vector_null_function" { - assert!(matches!( - error, - Error::InvalidDriverValue("cuModuleGetFunction") - )); + assert!(matches!(error, Error::InvalidDriverValue("cuModuleGetFunction"))); } if case == "vector_wrong_pop" { assert_eq!(error, Error::UnexpectedContext); @@ -52,10 +36,7 @@ pub(super) fn vector_poison_refusals(f: &mut VectorFixture<'_>) { use leleka_cuda_driver::Error; let before = trace().len(); assert!(vector_call(f).is_err()); - assert_eq!( - f.context.matvec_f32(&f.a, &f.b, &mut f.out, 1, f.count), - Err(Error::ContextPoisoned) - ); + assert_eq!(f.context.matvec_f32(&f.a, &f.b, &mut f.out, 1, f.count), Err(Error::ContextPoisoned)); assert!(f.context.allocate(4).is_err()); assert!(f.a.copy_from(&f32_bytes(&f.av)).is_err()); assert!(f.context.synchronize().is_err()); @@ -64,14 +45,7 @@ pub(super) fn vector_poison_refusals(f: &mut VectorFixture<'_>) { std::hint::black_box(churn); } pub(super) fn vector_expected(f: &VectorFixture<'_>) -> Vec { - f.av.iter() - .zip(if f.case == "vector_same_input" { - &f.av - } else { - &f.bv - }) - .map(|(a, b)| (a + b).to_bits()) - .collect() + f.av.iter().zip(if f.case == "vector_same_input" { &f.av } else { &f.bv }).map(|(a, b)| (a + b).to_bits()).collect() } pub(super) fn vector_success(device: &leleka_cuda_driver::Device<'_>, f: &mut VectorFixture<'_>) { if f.case == "vector_cache" { @@ -79,17 +53,8 @@ pub(super) fn vector_success(device: &leleka_cuda_driver::Device<'_>, f: &mut Ve } let mut output = vec![0; f.bytes]; f.out.copy_to(&mut output).unwrap(); - let actual: Vec<_> = output - .as_chunks::<4>() - .0 - .iter() - .map(|v| u32::from_ne_bytes(*v)) - .collect(); - assert_eq!( - actual, - vector_expected(f), - "independent exact finite f32 reference" - ); + let actual: Vec<_> = output.as_chunks::<4>().0.iter().map(|v| u32::from_ne_bytes(*v)).collect(); + assert_eq!(actual, vector_expected(f), "independent exact finite f32 reference"); let mut unchanged = vec![0; f.bytes]; f.a.copy_to(&mut unchanged).unwrap(); assert_eq!(unchanged, f32_bytes(&f.av)); @@ -99,11 +64,7 @@ pub(super) fn vector_success(device: &leleka_cuda_driver::Device<'_>, f: &mut Ve vector_second_context(device, f, &mut output); } } -pub(super) fn vector_second_context( - device: &leleka_cuda_driver::Device<'_>, - f: &VectorFixture<'_>, - output: &mut [u8], -) { +pub(super) fn vector_second_context(device: &leleka_cuda_driver::Device<'_>, f: &VectorFixture<'_>, output: &mut [u8]) { let second = device.create_context(f.bytes * 3).unwrap(); let mut x = second.allocate(f.bytes).unwrap(); let mut y = second.allocate(f.bytes).unwrap(); @@ -112,16 +73,7 @@ pub(super) fn vector_second_context( y.copy_from(&f32_bytes(&f.bv)).unwrap(); second.vector_add_f32(&x, &y, &mut z).unwrap(); z.copy_to(output).unwrap(); - assert_eq!( - output, - f32_bytes( - &f.av - .iter() - .zip(&f.bv) - .map(|(a, b)| a + b) - .collect::>() - ) - ); + assert_eq!(output, f32_bytes(&f.av.iter().zip(&f.bv).map(|(a, b)| a + b).collect::>())); drop((x, y, z)); second.close().unwrap(); } @@ -139,24 +91,17 @@ pub(super) fn vector_close(case: &str, closed: leleka_cuda_driver::Result<()>) { } } pub(super) fn vector_trace(case: &str, count: usize, rows: &[Row]) { - assert!(!rows.iter().any(|r| { - [ - "unsafe_pending_free", - "unsafe_pending_unload", - "stack_arguments", - ] - .contains(&r.stage.as_str()) - })); + assert!( + !rows.iter().any(|r| { + ["unsafe_pending_free", "unsafe_pending_unload", "stack_arguments"].contains(&r.stage.as_str()) + }) + ); vector_cache_trace(case, count, rows); vector_launch_sync(rows); vector_fault_trace(case, count, rows); vector_module_context_trace(rows); if case != "vector_close_destroy" { - let last = rows - .iter() - .rev() - .find(|r| r.stage == "destroy" && r.code == 0) - .unwrap(); + let last = rows.iter().rev().find(|r| r.stage == "destroy" && r.code == 0).unwrap(); assert_eq!(last.current, 0x11); assert_eq!(last.live, 0); assert_eq!(last.charged, 0); @@ -165,75 +110,34 @@ pub(super) fn vector_trace(case: &str, count: usize, rows: &[Row]) { pub(super) fn vector_cache_trace(case: &str, count: usize, rows: &[Row]) { let modules = if case == "vector_contexts" { 2 } else { 1 }; if !["vector_load", "vector_null_load", "vector_push"].contains(&case) { - assert_eq!( - rows.iter() - .filter(|r| r.stage == "load" && r.code == 0) - .count(), - modules - ); + assert_eq!(rows.iter().filter(|r| r.stage == "load" && r.code == 0).count(), modules); } if !VECTOR_EXECUTION_FAILURES.contains(&case) { vector_successful_cache_trace(case, count, rows, modules); } } pub(super) fn vector_successful_cache_trace(case: &str, count: usize, rows: &[Row], modules: usize) { - assert_eq!( - rows.iter() - .filter(|r| r.stage == "lookup" && r.code == 0) - .count(), - modules - ); - let launches = if ["vector_cache", "vector_contexts"].contains(&case) { - 2 - } else { - 1 - }; - assert_eq!( - rows.iter().filter(|r| r.stage == "launch").count(), - launches - ); - assert!( - rows.iter() - .filter(|r| r.stage == "geometry") - .all(|r| r.bytes == count.div_ceil(128)) - ); - assert!( - rows.iter() - .filter(|r| r.stage == "arguments") - .all(|r| r.bytes == count) - ); + assert_eq!(rows.iter().filter(|r| r.stage == "lookup" && r.code == 0).count(), modules); + let launches = if ["vector_cache", "vector_contexts"].contains(&case) { 2 } else { 1 }; + assert_eq!(rows.iter().filter(|r| r.stage == "launch").count(), launches); + assert!(rows.iter().filter(|r| r.stage == "geometry").all(|r| r.bytes == count.div_ceil(128))); + assert!(rows.iter().filter(|r| r.stage == "arguments").all(|r| r.bytes == count)); } pub(super) fn vector_launch_sync(rows: &[Row]) { for (i, row) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") { assert!( - rows[i + 1..] - .iter() - .take_while(|r| r.stage != "pop") - .any(|r| r.stage == "sync"), + rows[i + 1..].iter().take_while(|r| r.stage != "pop").any(|r| r.stage == "sync"), "mandatory sync after any launch attempt" ); assert!([0, 700].contains(&row.code)); } } pub(super) fn vector_fault_trace(case: &str, count: usize, rows: &[Row]) { - if [ - "vector_sync", - "vector_launch_sync", - "vector_launch_sync_pop", - ] - .contains(&case) - { + if ["vector_sync", "vector_launch_sync", "vector_launch_sync_pop"].contains(&case) { assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), 0); - assert!( - rows.iter() - .any(|r| r.stage == "pending_launch" && r.bytes == count) - ); + assert!(rows.iter().any(|r| r.stage == "pending_launch" && r.bytes == count)); } if ["vector_unload", "vector_lookup_unload"].contains(&case) { - assert_eq!( - rows.iter().filter(|r| r.stage == "unload").count(), - 1, - "failed handle consumed once" - ); + assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), 1, "failed handle consumed once"); } } 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 db62bbfa..cec2c2ff 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 @@ -29,11 +29,7 @@ pub(super) fn rounded_add(a: f32, b: f32) -> f32 { pub(super) fn matvec_oracle(matrix: &[f32], vector: &[f32]) -> Vec { matrix .chunks_exact(vector.len()) - .map(|row| { - row.iter() - .zip(vector) - .fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b))) - }) + .map(|row| row.iter().zip(vector).fold(0.0f32, |s, (&a, &b)| rounded_add(s, rounded_product(a, b)))) .collect() } pub(super) fn check_f32_output(bytes: &[u8], expected: &[f32]) { @@ -56,29 +52,13 @@ pub(super) fn matvec_arithmetic() { let device = driver.device(0).unwrap(); // These expected bits are recorded independently of mock/wrapper/PTX. assert_eq!(rounded_add(rounded_add(16777216.0, -16777216.0), 1.0), 1.0); - assert_ne!( - f32::from_bits(0x3f800001) - .mul_add(f32::from_bits(0x3f7ffffe), -1.0) - .to_bits(), - 0 - ); + assert_ne!(f32::from_bits(0x3f800001).mul_add(f32::from_bits(0x3f7ffffe), -1.0).to_bits(), 0); for &(a, b, bits) in ARITHMETIC_FIXTURES { check_arithmetic_fixture(&device, a, b, bits); } - assert_eq!( - trace() - .iter() - .filter(|r| r.stage == "pending_matvec") - .count(), - 13 - ); + assert_eq!(trace().iter().filter(|r| r.stage == "pending_matvec").count(), 13); } -pub(super) fn check_arithmetic_fixture( - device: &leleka_cuda_driver::Device<'_>, - a: &[u32], - b: &[u32], - bits: u32, -) { +pub(super) fn check_arithmetic_fixture(device: &leleka_cuda_driver::Device<'_>, a: &[u32], b: &[u32], bits: u32) { let matrix: Vec<_> = a.iter().map(|&v| f32::from_bits(v)).collect(); let vector: Vec<_> = b.iter().map(|&v| f32::from_bits(v)).collect(); let expected = matvec_oracle(&matrix, &vector); @@ -94,9 +74,7 @@ pub(super) fn check_arithmetic_fixture( let mut out = context.allocate(4).unwrap(); a.copy_from(&f32_bytes(&matrix)).unwrap(); b.copy_from(&f32_bytes(&vector)).unwrap(); - context - .matvec_f32(&a, &b, &mut out, 1, vector.len()) - .unwrap(); + context.matvec_f32(&a, &b, &mut out, 1, vector.len()).unwrap(); let mut bytes = [0u8; 4]; out.copy_to(&mut bytes).unwrap(); check_f32_output(&bytes, &expected); @@ -104,51 +82,22 @@ pub(super) fn check_arithmetic_fixture( context.close().unwrap(); } pub(super) fn matvec_rows(case: &str) -> usize { - if case == "matvec_same_input" { - 1 - } else { - case.strip_prefix("matvec_").unwrap().parse().unwrap_or(129) - } + if case == "matvec_same_input" { 1 } else { case.strip_prefix("matvec_").unwrap().parse().unwrap_or(129) } } -pub(super) fn matvec_fixture<'a>( - context: &'a leleka_cuda_driver::Context<'a>, - case: &'a str, -) -> MatvecFixture<'a> { +pub(super) fn matvec_fixture<'a>(context: &'a leleka_cuda_driver::Context<'a>, case: &'a str) -> MatvecFixture<'a> { let rows = matvec_rows(case); let columns = if case == "matvec_n1" { 1 } else { 3 }; - let matrix: Vec<_> = (0..rows * columns) - .map(|i| (i as i32 % 37 - 18) as f32 * 0.25) - .collect(); + let matrix: Vec<_> = (0..rows * columns).map(|i| (i as i32 % 37 - 18) as f32 * 0.25).collect(); let vector: Vec<_> = (0..columns).map(|i| (i as f32 + 1.0) * 0.5).collect(); let mut a = context.allocate(rows * columns * 4).unwrap(); let mut b = context.allocate(columns * 4).unwrap(); let out = context.allocate(rows * 4).unwrap(); a.copy_from(&f32_bytes(&matrix)).unwrap(); b.copy_from(&f32_bytes(&vector)).unwrap(); - MatvecFixture { - context, - case, - a, - b, - out, - matrix, - vector, - rows, - columns, - } + MatvecFixture { context, case, a, b, out, matrix, vector, rows, columns } } pub(super) fn matvec_call(f: &mut MatvecFixture<'_>) -> leleka_cuda_driver::Result<()> { - f.context.matvec_f32( - &f.a, - if f.case == "matvec_same_input" { - &f.a - } else { - &f.b - }, - &mut f.out, - f.rows, - f.columns, - ) + f.context.matvec_f32(&f.a, if f.case == "matvec_same_input" { &f.a } else { &f.b }, &mut f.out, f.rows, f.columns) } pub(super) fn matvec_child(case: &str) { let driver = Driver::load().unwrap(); @@ -212,21 +161,9 @@ pub(super) fn check_matvec_foreign(device: &leleka_cuda_driver::Device<'_>, f: & let b = foreign.allocate(f.b.len()).unwrap(); let mut out = foreign.allocate(f.out.len()).unwrap(); let before = trace().len(); - assert_eq!( - f.context - .matvec_f32(&a, &f.b, &mut f.out, f.rows, f.columns), - Err(Error::ContextMismatch) - ); - assert_eq!( - f.context - .matvec_f32(&f.a, &b, &mut f.out, f.rows, f.columns), - Err(Error::ContextMismatch) - ); - assert_eq!( - f.context - .matvec_f32(&f.a, &f.b, &mut out, f.rows, f.columns), - Err(Error::ContextMismatch) - ); + assert_eq!(f.context.matvec_f32(&a, &f.b, &mut f.out, f.rows, f.columns), Err(Error::ContextMismatch)); + assert_eq!(f.context.matvec_f32(&f.a, &b, &mut f.out, f.rows, f.columns), Err(Error::ContextMismatch)); + assert_eq!(f.context.matvec_f32(&f.a, &f.b, &mut out, f.rows, f.columns), Err(Error::ContextMismatch)); assert_eq!(trace().len(), before); drop((a, b, out)); foreign.close().unwrap(); diff --git a/crates/cuda-driver/tests/original_arena_probe.rs b/crates/cuda-driver/tests/original_arena_probe.rs index f00fb490..e7966008 100644 --- a/crates/cuda-driver/tests/original_arena_probe.rs +++ b/crates/cuda-driver/tests/original_arena_probe.rs @@ -9,11 +9,21 @@ fn arena_probe() { let device = driver.device(0).expect("device 0"); let context = device.create_context(budget << 30).expect("context"); eprintln!("PROBE context ok budget={budget}GiB"); - let mut workspace = context.native_integer_iq3_mmq_original_formats_workspace().map_err(|e| { eprintln!("PROBE workspace err: {e:?}"); e }).expect("workspace"); + let mut workspace = context + .native_integer_iq3_mmq_original_formats_workspace() + .map_err(|e| { + eprintln!("PROBE workspace err: {e:?}"); + e + }) + .expect("workspace"); eprintln!("PROBE workspace ok"); match workspace.enable_original_expert_group_arena(capacity) { Ok(()) => eprintln!("PROBE arena ok capacity={capacity}"), - Err(e) => { eprintln!("PROBE arena ERR: {e:?}"); let _ = workspace.close(); panic!("arena failed: {e:?}"); } + Err(e) => { + eprintln!("PROBE arena ERR: {e:?}"); + let _ = workspace.close(); + panic!("arena failed: {e:?}"); + } } let _ = workspace.close(); } diff --git a/crates/cuda-driver/tests/original_executor_probe.rs b/crates/cuda-driver/tests/original_executor_probe.rs index 45b2a72e..f43e66ed 100644 --- a/crates/cuda-driver/tests/original_executor_probe.rs +++ b/crates/cuda-driver/tests/original_executor_probe.rs @@ -1,6 +1,19 @@ //! Temporary model-free probe (bring-up debugging): create each device object OriginalPromptExecutor::new builds. use leleka_cuda_driver::*; -macro_rules! step { ($name:expr, $e:expr) => {{ match $e { Ok(v) => { eprintln!("PROBE2 {} ok", $name); Some(v) } Err(e) => { eprintln!("PROBE2 {} ERR: {e:?}", $name); None } } }}; } +macro_rules! step { + ($name:expr, $e:expr) => {{ + match $e { + Ok(v) => { + eprintln!("PROBE2 {} ok", $name); + Some(v) + } + Err(e) => { + eprintln!("PROBE2 {} ERR: {e:?}", $name); + None + } + } + }}; +} #[test] #[ignore = "GPU bring-up probe; no model"] fn executor_probe() { @@ -9,13 +22,23 @@ fn executor_probe() { let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device 0"); let context = device.create_context(24usize << 30).expect("context"); - let _a = step!("original_prompt_device", context.original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly)); - let _b = step!("original_gdn_prompt_device", context.original_gdn_prompt_device(capacity, GrNativeProfile::HighOnly)); - let _c = step!("original_qsa_resident_prompt_device", context.original_qsa_resident_prompt_device(capacity, QsaNativePacking::HighOnly)); + let _a = step!( + "original_prompt_device", + context.original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly) + ); + let _b = + step!("original_gdn_prompt_device", context.original_gdn_prompt_device(capacity, GrNativeProfile::HighOnly)); + let _c = step!( + "original_qsa_resident_prompt_device", + context.original_qsa_resident_prompt_device(capacity, QsaNativePacking::HighOnly) + ); let _d = step!("original_qsa_resident_transport", context.original_qsa_resident_transport()); let _e = step!("original_qsa_resident_attention", context.original_qsa_resident_attention(capacity)); let _f = step!("original_mtp_prefill", context.original_mtp_prefill()); let _g = step!("original_mtp_scalar_prefill", context.original_mtp_scalar_prefill(max_t, capacity)); let _h = step!("original_qsa_resident_index", context.original_qsa_resident_index()); - let _i = step!("qsa_prompt_kv.into_original_mapped_journal", context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal())); + let _i = step!( + "qsa_prompt_kv.into_original_mapped_journal", + context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal()) + ); } diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe.rs b/crates/cuda-driver/tests/original_serve_preflight_probe.rs index 13d6e7b9..8222b835 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe.rs @@ -55,19 +55,19 @@ mod preflight_00_sealed_asset_report; #[path = "original_serve_preflight_probe/env_usize_fn.rs"] mod env_usize_fn; #[allow(unused_imports)] -use env_usize_fn::env_usize; -#[allow(unused_imports)] use env_usize_fn::budget; #[allow(unused_imports)] +use env_usize_fn::embed_row_bytes; +#[allow(unused_imports)] +use env_usize_fn::env_list; +#[allow(unused_imports)] +use env_usize_fn::env_usize; +#[allow(unused_imports)] use env_usize_fn::geometry; #[allow(unused_imports)] use env_usize_fn::layout_options; #[allow(unused_imports)] -use env_usize_fn::embed_row_bytes; -#[allow(unused_imports)] use env_usize_fn::synthetic_mtp; -#[allow(unused_imports)] -use env_usize_fn::env_list; #[path = "original_serve_preflight_probe/synthetic_verifier_fn.rs"] mod synthetic_verifier_fn; #[allow(unused_imports)] 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 900cfea9..dce65f62 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 @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn env_usize(name: &str, default: usize) -> usize { std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default) } @@ -104,25 +103,54 @@ pub(super) fn synthetic_mtp<'ctx>( 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 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 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))?; + let prefix = step!( + "OriginalMtpRetainedPrefix::from_scalar", + OriginalMtpRetainedPrefix::from_scalar(Rc::new(scalar)).map(Rc::new) + )?; // ---- 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, + 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 { @@ -138,8 +166,19 @@ pub(super) fn synthetic_mtp<'ctx>( 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) + OriginalMtpRetainedFullWeights::retain( + context, + prefix, + full_roles, + experts, + head, + head_kind, + vocab, + vocab, + None, + NativeHeadDispatch::default() + ) + .map(Rc::new) )?; // ---- plan + meter exactly as OriginalMtpFullOwner::assemble does @@ -154,7 +193,8 @@ pub(super) fn synthetic_mtp<'ctx>( 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 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!( @@ -162,18 +202,21 @@ pub(super) fn synthetic_mtp<'ctx>( 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 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 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()) + 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(); @@ -184,5 +227,9 @@ pub(super) fn synthetic_mtp<'ctx>( } pub(super) fn env_list(name: &str, default: &str) -> Vec { - std::env::var(name).unwrap_or_else(|_| default.to_owned()).split(',').filter_map(|s| s.trim().parse().ok()).collect() + std::env::var(name) + .unwrap_or_else(|_| default.to_owned()) + .split(',') + .filter_map(|s| s.trim().parse().ok()) + .collect() } 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 2da54781..8c62c959 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 @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Which gating assets the build itself reports as unsealed (no GPU needed beyond the process). #[test] #[ignore = "GPU bring-up probe; no model"] @@ -17,7 +16,11 @@ fn preflight_00_sealed_asset_report() { } eprintln!("PREFLIGHT asset {:?} {} sealed={}", a.kind, a.name, a.sealed); } - eprintln!("PREFLIGHT assets total={} unsealed={unsealed} window_unsealed={:?}", status.len(), unsealed_window_assets()); + eprintln!( + "PREFLIGHT assets total={} unsealed={unsealed} window_unsealed={:?}", + status.len(), + unsealed_window_assets() + ); eprintln!("PREFLIGHT UNBOUND_PRODUCERS={UNBOUND_PRODUCERS:?}"); let serving = serving_context(); eprintln!("PREFLIGHT serving_cells={}", serving.geometry.cells()); @@ -33,7 +36,10 @@ fn preflight_01_device_limits() { let context = device.create_context(budget()).expect("context"); let (free, total) = context.memory_info().expect("memory_info"); eprintln!("PREFLIGHT context ok budget={}GiB free={}MiB total={}MiB", budget() >> 30, free >> 20, total >> 20); - let bank = step!("original_verify_bank(geometry)", context.original_verify_bank(geometry(8, env_usize("PROBE_CELLS", 262_144), 2_329_600))); + let bank = step!( + "original_verify_bank(geometry)", + context.original_verify_bank(geometry(8, env_usize("PROBE_CELLS", 262_144), 2_329_600)) + ); drop(bank); } @@ -50,7 +56,8 @@ fn preflight_10_lazy_constructors() { let vocab = env_usize("PROBE_VOCAB", 248_320); 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)); + let _b = + step!("original_gpu_stream(BlockingCapture)", context.original_gpu_stream(OriginalStreamKind::BlockingCapture)); let _c = step!("original_gpu_stream(NonBlocking)", context.original_gpu_stream(OriginalStreamKind::NonBlocking)); let _d = step!("original_gpu_event(Completion)", context.original_gpu_event(OriginalEventKind::Completion)); let _e = step!("original_gpu_event(Timing)", context.original_gpu_event(OriginalEventKind::Timing)); @@ -76,11 +83,21 @@ fn preflight_10_lazy_constructors() { 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)); let streams = vec![0.0f32; capacity * 10240]; - let _a1 = step!("gr_native_prompt_batch(capacity)", context.gr_native_prompt_batch(capacity, &streams, GrNativeProfile::HighOnly)); + let _a1 = step!( + "gr_native_prompt_batch(capacity)", + context.gr_native_prompt_batch(capacity, &streams, GrNativeProfile::HighOnly) + ); let _a2 = step!("gdn_prefill_batch_for_prompt(capacity)", context.gdn_prefill_batch_for_prompt(capacity)); - let _a3 = step!("ple_batch_queue_for_prompt(capacity)", context.ple_batch_queue_for_prompt(PleBf16Mode::HighOnly, capacity)); - let _a4 = step!("qsa_native_batch_workspace_for_prompt(capacity)", context.qsa_native_batch_workspace_for_prompt(QsaNativePacking::HighOnly, capacity)); - let _a5 = step!("qsa_prompt_index_workspace_for_capacity", context.qsa_prompt_index_workspace_for_capacity(capacity)); + let _a3 = step!( + "ple_batch_queue_for_prompt(capacity)", + context.ple_batch_queue_for_prompt(PleBf16Mode::HighOnly, capacity) + ); + let _a4 = step!( + "qsa_native_batch_workspace_for_prompt(capacity)", + context.qsa_native_batch_workspace_for_prompt(QsaNativePacking::HighOnly, capacity) + ); + let _a5 = + step!("qsa_prompt_index_workspace_for_capacity", context.qsa_prompt_index_workspace_for_capacity(capacity)); let _a6 = step!("qsa_prompt_attention_for_capacity", context.qsa_prompt_attention_for_capacity(capacity)); let _a7 = step!("qsa_prompt_kv", context.qsa_prompt_kv()); let _a8 = step!("original_qsa_resident_scalar_index", context.original_qsa_resident_scalar_index()); @@ -111,7 +128,11 @@ fn preflight_20_prefill_arena() { } let arena = step!("original_prefill_arena(layout)", context.original_prefill_arena(options)); if let Some(arena) = &arena { - eprintln!("PREFLIGHT arena physically_owned={}MiB capacity={}", arena.physically_owned_bytes() >> 20, arena.capacity()); + eprintln!( + "PREFLIGHT arena physically_owned={}MiB capacity={}", + arena.physically_owned_bytes() >> 20, + arena.capacity() + ); } eprintln!("PREFLIGHT context allocated={}MiB", context.allocated_bytes() >> 20); } @@ -160,7 +181,8 @@ fn preflight_40_synthetic_verifier_record_all() { 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 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(';') { diff --git a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs index 5c4dad9b..9bff0808 100644 --- a/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs +++ b/crates/cuda-driver/tests/original_serve_preflight_probe/synthetic_verifier_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// One synthetic verifier assembly: the window graphs T=1..=max_t and the commit graph are RECORDED /// (`OriginalVerifier::record_all`) over uninitialised correctly sized weights of the given ggml kinds. This is /// `original_serve_verifier::assemble` without the model: every sealed window module is loaded and every launch is @@ -31,14 +30,26 @@ pub(super) fn synthetic_verifier<'ctx>( // ---- head rows and embedding rows let head_bytes = need!("head bytes", size(head_kind, 2560, vocab)); - let head = need!("original_native_head", context.original_native_head(head_kind, 2560, vocab, &vec![0u8; head_bytes], NativeHeadDispatch::default())); + let head = need!( + "original_native_head", + context.original_native_head(head_kind, 2560, vocab, &vec![0u8; head_bytes], NativeHeadDispatch::default()) + ); let embed_bytes = need!("embed bytes", size(embed_kind, 2560, vocab)); - let embed = need!("original_native_embed", context.original_native_embed(embed_kind, 2560, vocab, &vec![0u8; embed_bytes])); + let embed = + need!("original_native_embed", context.original_native_embed(embed_kind, 2560, vocab, &vec![0u8; embed_bytes])); // ---- the MTP drafter over the same head allocation (the serve stack lends `OriginalNativeOutput::mtp_head`) let mut mtp = if std::env::var("PROBE_DRAFT").map_or(true, |v| v != "0") { let head_weights = need!("head.retain_weights", head.retain_weights()); - synthetic_mtp(context, Some(head_weights), head_kind, vocab, env_usize("PROBE_MTP_MAX_T", 6), env_usize("PROBE_CAPACITY", 1024), false) + synthetic_mtp( + context, + Some(head_weights), + head_kind, + vocab, + env_usize("PROBE_MTP_MAX_T", 6), + env_usize("PROBE_CAPACITY", 1024), + false, + ) } else { None }; @@ -49,7 +60,8 @@ pub(super) fn synthetic_verifier<'ctx>( need!($name, context.allocate($bytes)) }; } - let mats: Vec<(usize, usize)> = vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)]; + let mats: Vec<(usize, usize)> = + vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)]; let mut proj_bufs = Vec::new(); for (i, (&(n_in, n_out), &k)) in mats.iter().zip(proj).enumerate() { let bytes = need!("projection bytes", size(k, n_in, n_out)); @@ -136,7 +148,10 @@ pub(super) fn synthetic_verifier<'ctx>( let mut batch_ws = need!("native_batch_workspace", context.native_batch_workspace()); for _ in 0..12 { indices.push(need!("original_qsa_resident_index", context.original_qsa_resident_index())); - let mut journal = need!("qsa_prompt_kv.into_original_mapped_journal", context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal())); + let mut journal = need!( + "qsa_prompt_kv.into_original_mapped_journal", + context.qsa_prompt_kv().and_then(|k| k.into_original_mapped_journal()) + ); // the prompt path initialises the streamed-KV resolver lazily (append_resident_arena); a prompt of ONE token // never runs it, so the serve assembly calls `ensure_resolver` (epoch-preserving) before the capture. if std::env::var_os("PROBE_SKIP_RESOLVER_RESET").is_none() { @@ -157,15 +172,24 @@ pub(super) fn synthetic_verifier<'ctx>( angles: None, }; let gamma: [&DeviceBuffer<'ctx>; 12] = std::array::from_fn(|i| &gamma_bufs[i]); - let qsa_journal = need!("OriginalVerifyQsaJournal::new", OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope)); + let qsa_journal = need!( + "OriginalVerifyQsaJournal::new", + OriginalVerifyQsaJournal::new(context, indices, mapped, gamma, rope) + ); let states = vec![0.0f32; 128 * 48 * 128]; let histories = vec![0.0f32; 10240 * 3]; let mut canonical = need!( "original_verify_canonical_gdn", - context.original_verify_canonical_gdn(std::array::from_fn(|_| states.as_slice()), std::array::from_fn(|_| histories.as_slice())) + context.original_verify_canonical_gdn( + std::array::from_fn(|_| states.as_slice()), + std::array::from_fn(|_| histories.as_slice()) + ) ); let before_verifier = context.allocated_bytes(); - let mut verifier = need!("OriginalVerifier::new", OriginalVerifier::>::new(context, g)); + let mut verifier = need!( + "OriginalVerifier::new", + OriginalVerifier::>::new(context, g) + ); eprintln!( "PREFLIGHT verifier bank device={}MiB mapped_host={}MiB (context allocated {}MiB -> {}MiB)", context.allocated_bytes().saturating_sub(before_verifier) >> 20, @@ -178,15 +202,28 @@ pub(super) fn synthetic_verifier<'ctx>( let mut windows = Vec::new(); for t in 1..=max_t + 1 { let window_t = if t <= max_t { t } else { max_t }; - let gdn_weights: [OriginalVerifyGdnWeights<'_, 'ctx>; 36] = - std::array::from_fn(|_| OriginalVerifyGdnWeights { conv: &conv, alpha: &alpha, beta: &beta, dt: &dt, a: &a, norm: &norm }); + let gdn_weights: [OriginalVerifyGdnWeights<'_, 'ctx>; 36] = std::array::from_fn(|_| { + OriginalVerifyGdnWeights { conv: &conv, alpha: &alpha, beta: &beta, dt: &dt, a: &a, norm: &norm } + }); let bank = need!("verifier.bank()", verifier.bank()); - let journal = need!(format!("gdn_journal(t={window_t})"), bank.gdn_journal(&mut canonical, gdn_weights, Some(&ple_history))); + let journal = need!( + format!("gdn_journal(t={window_t})"), + bank.gdn_journal(&mut canonical, gdn_weights, Some(&ple_history)) + ); let head_rows = need!(format!("head.rows({window_t})"), head.rows(window_t)); - let resources = need!(format!("OriginalVerifyResources::new(t={window_t})"), OriginalVerifyResources::new(context, journal, Rc::clone(&qsa_journal), head_rows)); + let resources = need!( + format!("OriginalVerifyResources::new(t={window_t})"), + OriginalVerifyResources::new(context, journal, Rc::clone(&qsa_journal), head_rows) + ); let embed_rows = need!(format!("embed.rows({window_t})"), embed.rows(window_t)); - let w = need!(format!("OriginalVerifyWindowResources::new(t={window_t})"), OriginalVerifyWindowResources::new(context, resources, embed_rows, layout.clone(), window_t)); - let w = need!("with_projections", OriginalVerifyProjBinding::new(context, &g, gdn_proj(), qsa_proj()).and_then(|p| w.with_projections(p))); + let w = need!( + format!("OriginalVerifyWindowResources::new(t={window_t})"), + OriginalVerifyWindowResources::new(context, resources, embed_rows, layout.clone(), window_t) + ); + let w = need!( + "with_projections", + OriginalVerifyProjBinding::new(context, &g, gdn_proj(), qsa_proj()).and_then(|p| w.with_projections(p)) + ); let layers: Vec<_> = (0..48).map(|_| HcLayerBuffers { attention: half(), ffn: half() }).collect(); let output = HcOutputBuffers { norm: &hc_norm, down: &hc_down, up: &hc_up }; let ple = PleBuffers { @@ -199,15 +236,20 @@ pub(super) fn synthetic_verifier<'ctx>( scratch: &ple_scratch, history: &ple_history, }; - let w = need!("with_gr", OriginalVerifyGrBinding::new(context, layers, output, Some(ple)).and_then(|b| w.with_gr(b))); - let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] = std::array::from_fn(|i| OriginalVerifyQsaLayerWeights { - attn_q_norm: &qsa_bufs[i][0], - attn_k_norm: &qsa_bufs[i][1], - index_q_norm: &qsa_bufs[i][2], - index_k_proj: &qsa_bufs[i][3], - index_q_proj: &qsa_bufs[i][4], - }); - let w = need!("with_qsa", OriginalVerifyQsaBinding::new(context, g, qsa_layers).and_then(|b| w.with_qsa(b))); + let w = need!( + "with_gr", + OriginalVerifyGrBinding::new(context, layers, output, Some(ple)).and_then(|b| w.with_gr(b)) + ); + let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] = + std::array::from_fn(|i| OriginalVerifyQsaLayerWeights { + attn_q_norm: &qsa_bufs[i][0], + attn_k_norm: &qsa_bufs[i][1], + index_q_norm: &qsa_bufs[i][2], + index_k_proj: &qsa_bufs[i][3], + index_q_proj: &qsa_bufs[i][4], + }); + let w = + need!("with_qsa", OriginalVerifyQsaBinding::new(context, g, qsa_layers).and_then(|b| w.with_qsa(b))); let moe_layers: Vec<_> = (0..48) .map(|_| OriginalVerifyMoeLayerWeights { router: &router, @@ -220,7 +262,10 @@ pub(super) fn synthetic_verifier<'ctx>( down_shexp_type: shared[2], }) .collect(); - let w = need!("with_moe", OriginalVerifyMoeBinding::new(context, &g, moe_layers, formats.clone()).and_then(|b| w.with_moe(b))); + let w = need!( + "with_moe", + OriginalVerifyMoeBinding::new(context, &g, moe_layers, formats.clone()).and_then(|b| w.with_moe(b)) + ); windows.push(Some(w)); } let commit = windows.pop().flatten().expect("commit aggregate"); @@ -293,7 +338,13 @@ pub(super) fn synthetic_verifier<'ctx>( }); let mut selection = None; let mut completed = None; - match step!(format!("verifier.run(t={t}, position={position}, sampler={sampled:?}) in {:?}, {groups_seen} pool groups", started.elapsed()), result) { + match step!( + format!( + "verifier.run(t={t}, position={position}, sampler={sampled:?}) in {:?}, {groups_seen} pool groups", + started.elapsed() + ), + result + ) { Some(window) => { eprintln!("PREFLIGHT window t={t} sampled ids {:?}", window.selection.ids()); completed = step!("verifier.completed_window", verifier.completed_window()); @@ -303,16 +354,29 @@ pub(super) fn synthetic_verifier<'ctx>( } // alternate the synchronous and the asynchronous (event) commit; the next run / read joins the event let async_commit = t == 2; - if step!(format!("verifier.commit(keep={keep}, async={async_commit})"), verifier.commit(keep, async_commit)).is_none() { + if step!( + format!("verifier.commit(keep={keep}, async={async_commit})"), + verifier.commit(keep, async_commit) + ) + .is_none() + { break; } // the reads `OriginalServeHost::publish_committed` / `settle_state` make after a commit let _ = step!("verifier.accepted_tokens", verifier.accepted_tokens().map(|a| a.len())); - last_checkpoint = step!("with_committed_qsa(0).checkpoint", verifier.with_committed_qsa(0, |index| index.checkpoint(&mut publish_ws))); + last_checkpoint = step!( + "with_committed_qsa(0).checkpoint", + verifier.with_committed_qsa(0, |index| index.checkpoint(&mut publish_ws)) + ); last_prefix = step!("qsa_journal.committed_mapped_prefix(0)", qsa_journal.committed_mapped_prefix(0)); - let _ = step!("with_committed_gdn(0)", verifier.with_committed_gdn(0, |values, history| Ok((values.len(), history.len())))); + let _ = step!( + "with_committed_gdn(0)", + verifier.with_committed_gdn(0, |values, history| Ok((values.len(), history.len()))) + ); if draft_after { - if let (Some((ring, actor)), Some(selection), Some(done)) = (mtp.as_mut(), selection.take(), completed.take()) { + if let (Some((ring, actor)), Some(selection), Some(done)) = + (mtp.as_mut(), selection.take(), completed.take()) + { // `OriginalServeHost::draft_committed`: the MTP drafter over the completed window (first call records its graphs) actor.set_prompt_len(1); actor.set_max_drafts(3); @@ -329,17 +393,29 @@ pub(super) fn synthetic_verifier<'ctx>( coupled_j: None, }; // the draft session restores a stored checkpoint and uses that very snapshot as `prior` - let prior = match (ring_prior.take(), reset_snapshot.take()) { - (Some(speculative), _) => Some(speculative), - (None, Some(restored)) => Some(restored), - (None, None) => step!("ring.empty_snapshot", ring.empty_snapshot()), - }; - if let Some(prior) = prior { + let prior = match (ring_prior.take(), reset_snapshot.take()) { + (Some(speculative), _) => Some(speculative), + (None, Some(restored)) => Some(restored), + (None, None) => step!("ring.empty_snapshot", ring.empty_snapshot()), + }; + if let Some(prior) = prior { let started = std::time::Instant::now(); - eprintln!("PREFLIGHT draft: window t={t} position={position} accepted_row={} ring_prior_end={}", keep - 1, prior.next_position()); - let drafted = actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &policy); - if let Some(d) = step!(format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), drafted) { - eprintln!("PREFLIGHT drafted ids {:?}, ring snapshot end {}", d.ids(), d.final_snapshot().next_position()); + eprintln!( + "PREFLIGHT draft: window t={t} position={position} accepted_row={} ring_prior_end={}", + keep - 1, + prior.next_position() + ); + let drafted = + actor.draft_from_verifier(ring, &prior, done, selection, keep - 1, 0.0, &policy); + if let Some(d) = step!( + format!("actor.draft_from_verifier(t={t}, a={}) in {:?}", keep - 1, started.elapsed()), + drafted + ) { + eprintln!( + "PREFLIGHT drafted ids {:?}, ring snapshot end {}", + d.ids(), + d.final_snapshot().next_position() + ); ring_prior = Some(d.final_snapshot().clone()); } let _ = step!("actor.idle", actor.idle()); @@ -352,14 +428,18 @@ pub(super) fn synthetic_verifier<'ctx>( // `disassemble`: closing the verifier must succeed after a request that drafted, or the stack is marked broken if std::env::var_os("PROBE_NO_RELEASE").is_none() { if let Some((_, actor)) = mtp.as_mut() { - let _ = step!(format!("actor.release_verifier_bindings (request {request})"), actor.release_verifier_bindings()); + let _ = step!( + format!("actor.release_verifier_bindings (request {request})"), + actor.release_verifier_bindings() + ); } } let _ = step!(format!("verifier.close (request {request})"), verifier.close()); // `recover` + `adopt_qsa_owners`: the journal gives the twelve owners back and each is rolled back to the session's witness - if let Some((mut indices, mut mapped)) = - step!(format!("OriginalVerifyQsaJournal::into_owners (request {request})"), OriginalVerifyQsaJournal::into_owners(qsa_journal)) - { + if let Some((mut indices, mut mapped)) = step!( + format!("OriginalVerifyQsaJournal::into_owners (request {request})"), + OriginalVerifyQsaJournal::into_owners(qsa_journal) + ) { if let (Some(cp), Some(prefix)) = (last_checkpoint.take(), last_prefix.take()) { let mut ws = need!("native_batch_workspace (adopt)", context.native_batch_workspace()); let _ = step!("owner index.restore(checkpoint)", indices[0].restore(&mut ws, &cp)); diff --git a/crates/cuda-driver/tests/ple_key_bulk_gpu.rs b/crates/cuda-driver/tests/ple_key_bulk_gpu.rs index 7711a122..cbc4a0ff 100644 --- a/crates/cuda-driver/tests/ple_key_bulk_gpu.rs +++ b/crates/cuda-driver/tests/ple_key_bulk_gpu.rs @@ -1,10 +1,6 @@ //! Closed PLE Key full projection against unchanged 64-row projection calls. //! Geometry/transport equality only; no serving-state, model-quality or speed claim. -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use leleka_cuda_driver::{Bf16ProjectionShape, Context, DeviceBuffer, Driver}; const ROWS: usize = 10240; @@ -46,11 +42,7 @@ fn activation(zero: bool) -> Vec { (0..COLUMNS) .flat_map(|column| { let value = if zero { - if column.is_multiple_of(2) { - -0.0f32 - } else { - 0.0 - } + if column.is_multiple_of(2) { -0.0f32 } else { 0.0 } } else { ((column % 31) as f32 - 15.) / 8. }; @@ -66,17 +58,7 @@ fn project( output: &mut DeviceBuffer<'_>, rows: usize, ) { - context - .bf16_f32( - weights, - input, - output, - Bf16ProjectionShape { - rows, - columns: COLUMNS, - }, - ) - .unwrap(); + context.bf16_f32(weights, input, output, Bf16ProjectionShape { rows, columns: COLUMNS }).unwrap(); } fn word(bytes: &[u8]) -> u32 { @@ -93,15 +75,9 @@ fn compare(context: &Context<'_>, whole: &DeviceBuffer<'_>, encoded: &[u8], zero let actual = read(&output, OUTPUT_BYTES); let mut legacy = Vec::with_capacity(OUTPUT_BYTES); for first in (0..ROWS).step_by(TILE_ROWS) { - let tile = upload( - context, - &encoded[first * STRIDE..(first + TILE_ROWS) * STRIDE], - ); + let tile = upload(context, &encoded[first * STRIDE..(first + TILE_ROWS) * STRIDE]); let mut tile_output = upload(context, &[0x5a; TILE_ROWS * 4]); - assert_eq!( - context.allocated_bytes(), - initial + TILE_BYTES + TILE_ROWS * 4 - ); + assert_eq!(context.allocated_bytes(), initial + TILE_BYTES + TILE_ROWS * 4); project(context, &tile, &x, &mut tile_output, TILE_ROWS); legacy.extend_from_slice(&read(&tile_output, TILE_ROWS * 4)); tile_output.release().unwrap(); @@ -110,12 +86,7 @@ fn compare(context: &Context<'_>, whole: &DeviceBuffer<'_>, encoded: &[u8], zero } assert_eq!(actual.len(), OUTPUT_BYTES); assert_eq!(legacy.len(), OUTPUT_BYTES); - for (row, (actual, reference)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(legacy.as_chunks::<4>().0.iter()) - .enumerate() + for (row, (actual, reference)) in actual.as_chunks::<4>().0.iter().zip(legacy.as_chunks::<4>().0.iter()).enumerate() { let actual = word(actual); let reference = word(reference); @@ -149,17 +120,8 @@ fn late_nonfinite(context: &Context<'_>, whole: &mut DeviceBuffer<'_>, encoded: let mut tile_output = upload(context, &[0x5a; TILE_ROWS * 4]); project(context, &tile, &x, &mut tile_output, TILE_ROWS); let legacy = read(&tile_output, TILE_ROWS * 4); - assert_eq!( - context.allocated_bytes(), - initial + TILE_BYTES + TILE_ROWS * 4 - ); - assert!( - actual[..OUTPUT_BYTES - 4] - .as_chunks::<4>() - .0 - .iter() - .all(|bytes| f32::from_bits(word(bytes)).is_finite()) - ); + assert_eq!(context.allocated_bytes(), initial + TILE_BYTES + TILE_ROWS * 4); + assert!(actual[..OUTPUT_BYTES - 4].as_chunks::<4>().0.iter().all(|bytes| f32::from_bits(word(bytes)).is_finite())); assert!(f32::from_bits(word(&actual[OUTPUT_BYTES - 4..])).is_nan()); for (actual, reference) in actual[OUTPUT_BYTES - TILE_ROWS * 4..OUTPUT_BYTES - 4] .as_chunks::<4>() @@ -171,13 +133,7 @@ fn late_nonfinite(context: &Context<'_>, whole: &mut DeviceBuffer<'_>, encoded: assert_eq!(word(actual), word(reference)); } assert!(f32::from_bits(word(&legacy[TILE_ROWS * 4 - 4..])).is_nan()); - assert!( - !actual - .as_chunks::<4>() - .0 - .iter() - .all(|bytes| f32::from_bits(word(bytes)).is_finite()) - ); + assert!(!actual.as_chunks::<4>().0.iter().all(|bytes| f32::from_bits(word(bytes)).is_finite())); assert_eq!(read(&x, INPUT_BYTES), input); assert_eq!(read(whole, WEIGHT_BYTES), encoded); tile_output.release().unwrap(); diff --git a/crates/cuda-driver/tests/prepared_routed_gate_up_gpu.rs b/crates/cuda-driver/tests/prepared_routed_gate_up_gpu.rs index 0f2c811b..ac04cad9 100644 --- a/crates/cuda-driver/tests/prepared_routed_gate_up_gpu.rs +++ b/crates/cuda-driver/tests/prepared_routed_gate_up_gpu.rs @@ -1,13 +1,7 @@ //! Changed per-step Q8 ownership against the admitted, unchanged projection path. //! Exact transport/math equality only; no model-quality or throughput claim. -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -use leleka_cuda_driver::{ - Context, DeviceBuffer, Driver, Error, ProjectionKind, ProjectionSpec, RoutedFormat, -}; +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Error, ProjectionKind, ProjectionSpec, RoutedFormat}; const ROWS: usize = 640; const COLUMNS: usize = 2560; @@ -30,11 +24,8 @@ fn read(buffer: &DeviceBuffer<'_>, bytes: usize) -> Vec { fn activation(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. - }; + 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() @@ -65,11 +56,7 @@ fn pair(context: &Context<'_>, format: RoutedFormat, block_bytes: usize, zero: b let up = upload(context, &up_bytes); let mut output = upload(context, &[0xa5; OUTPUT_BYTES]); let initial = context.allocated_bytes(); - let spec = ProjectionSpec { - kind: ProjectionKind::Routed(format), - rows: ROWS, - columns: COLUMNS, - }; + let spec = ProjectionSpec { kind: ProjectionKind::Routed(format), rows: ROWS, columns: COLUMNS }; // Reference is obtained first from the old public path, never from the // prepared implementation or a host reimplementation of quantization. let mut reference = Vec::with_capacity(2); @@ -82,18 +69,12 @@ fn pair(context: &Context<'_>, format: RoutedFormat, block_bytes: usize, zero: b assert_eq!(context.allocated_bytes(), initial + PREPARED_BYTES); for (matrix, expected) in [&gate, &up].into_iter().zip(&reference) { output.copy_from(&[0x5a; OUTPUT_BYTES]).unwrap(); - context - .project_routed_gate_up_prepared(matrix, &prepared, &mut output, format) - .unwrap(); + context.project_routed_gate_up_prepared(matrix, &prepared, &mut output, format).unwrap(); assert_eq!(context.allocated_bytes(), initial + PREPARED_BYTES); let actual = read(&output, OUTPUT_BYTES); assert_eq!(actual.len(), OUTPUT_BYTES); - for (row, (actual, expected)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(expected.as_chunks::<4>().0.iter()) - .enumerate() + for (row, (actual, expected)) in + actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0.iter()).enumerate() { let actual = u32::from_le_bytes(*actual); let expected = u32::from_le_bytes(*expected); @@ -136,30 +117,21 @@ fn refusals(context: &Context<'_>, foreign: &Context<'_>, tiny: &Context<'_>) { let source = vec![0; bytes]; let x = upload(context, &source); let initial = context.allocated_bytes(); - assert!(matches!( - context.prepare_routed_gate_up_q8(&x), - Err(Error::InvalidProjectionShape) - )); + assert!(matches!(context.prepare_routed_gate_up_q8(&x), Err(Error::InvalidProjectionShape))); assert_eq!(context.allocated_bytes(), initial); assert_eq!(read(&x, bytes), source); x.release().unwrap(); } let input = activation(false); let foreign_x = upload(foreign, &input); - assert!(matches!( - context.prepare_routed_gate_up_q8(&foreign_x), - Err(Error::ContextMismatch) - )); + assert!(matches!(context.prepare_routed_gate_up_q8(&foreign_x), Err(Error::ContextMismatch))); assert_eq!(context.allocated_bytes(), 0); assert_eq!(foreign.allocated_bytes(), INPUT_BYTES); assert_eq!(read(&foreign_x, INPUT_BYTES), input); foreign_x.release().unwrap(); // 10240+2880+4=13124: this context is exactly one byte short. let tiny_x = upload(tiny, &input); - assert!(matches!( - tiny.prepare_routed_gate_up_q8(&tiny_x), - Err(Error::BudgetExceeded) - )); + assert!(matches!(tiny.prepare_routed_gate_up_q8(&tiny_x), Err(Error::BudgetExceeded))); assert_eq!(tiny.allocated_bytes(), INPUT_BYTES); assert_eq!(read(&tiny_x, INPUT_BYTES), input); tiny_x.release().unwrap(); @@ -171,10 +143,7 @@ fn refusals(context: &Context<'_>, foreign: &Context<'_>, tiny: &Context<'_>) { malformed[INPUT_BYTES - 4..].copy_from_slice(&bits.to_le_bytes()); let bad = upload(context, &malformed); let initial = context.allocated_bytes(); - assert!(matches!( - context.prepare_routed_gate_up_q8(&bad), - Err(Error::InvalidQ8Activation) - )); + assert!(matches!(context.prepare_routed_gate_up_q8(&bad), Err(Error::InvalidQ8Activation))); assert_eq!(context.allocated_bytes(), initial); assert_eq!(read(&bad, INPUT_BYTES), malformed); bad.release().unwrap(); @@ -192,77 +161,37 @@ fn refusals(context: &Context<'_>, foreign: &Context<'_>, tiny: &Context<'_>) { assert_eq!(context.allocated_bytes(), initial + PREPARED_BYTES); for bytes in [627196, 627204] { let wrong = upload(context, &vec![0; bytes]); - refuses_without_output_change( - context, - &mut out, - OUTPUT_BYTES, - Error::InvalidProjectionShape, - |out| { - context.project_routed_gate_up_prepared( - &wrong, - &prepared, - out, - RoutedFormat::IQ3_XXS, - ) - }, - ); + refuses_without_output_change(context, &mut out, OUTPUT_BYTES, Error::InvalidProjectionShape, |out| { + context.project_routed_gate_up_prepared(&wrong, &prepared, out, RoutedFormat::IQ3_XXS) + }); wrong.release().unwrap(); } for bytes in [2556, 2564] { let mut wrong = upload(context, &vec![0; bytes]); - refuses_without_output_change( - context, - &mut wrong, - bytes, - Error::InvalidProjectionShape, - |out| { - context.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS) - }, - ); + refuses_without_output_change(context, &mut wrong, bytes, Error::InvalidProjectionShape, |out| { + context.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS) + }); wrong.release().unwrap(); } - refuses_without_output_change( - context, - &mut out, - OUTPUT_BYTES, - Error::ContextMismatch, - |out| foreign.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS), - ); + refuses_without_output_change(context, &mut out, OUTPUT_BYTES, Error::ContextMismatch, |out| { + foreign.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS) + }); let foreign_w = upload(foreign, &encoded); - refuses_without_output_change( - context, - &mut out, - OUTPUT_BYTES, - Error::ContextMismatch, - |out| { - context.project_routed_gate_up_prepared( - &foreign_w, - &prepared, - out, - RoutedFormat::IQ3_XXS, - ) - }, - ); + refuses_without_output_change(context, &mut out, OUTPUT_BYTES, Error::ContextMismatch, |out| { + context.project_routed_gate_up_prepared(&foreign_w, &prepared, out, RoutedFormat::IQ3_XXS) + }); foreign_w.release().unwrap(); let mut foreign_out = upload(foreign, &[0xa5; OUTPUT_BYTES]); let initial = context.allocated_bytes(); - refuses_without_output_change( - foreign, - &mut foreign_out, - OUTPUT_BYTES, - Error::ContextMismatch, - |out| context.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS), - ); + refuses_without_output_change(foreign, &mut foreign_out, OUTPUT_BYTES, Error::ContextMismatch, |out| { + context.project_routed_gate_up_prepared(&w, &prepared, out, RoutedFormat::IQ3_XXS) + }); assert_eq!(context.allocated_bytes(), initial); foreign_out.release().unwrap(); for format in [RoutedFormat::IQ4_NL, RoutedFormat::Q2_0] { - refuses_without_output_change( - context, - &mut out, - OUTPUT_BYTES, - Error::UnsupportedProjection, - |out| context.project_routed_gate_up_prepared(&w, &prepared, out, format), - ); + refuses_without_output_change(context, &mut out, OUTPUT_BYTES, Error::UnsupportedProjection, |out| { + context.project_routed_gate_up_prepared(&w, &prepared, out, format) + }); } assert_eq!(read(&x, INPUT_BYTES), input); assert_eq!(read(&w, encoded.len()), encoded); diff --git a/crates/cuda-driver/tests/projection_family_gpu.rs b/crates/cuda-driver/tests/projection_family_gpu.rs index c9ba0507..44060c23 100644 --- a/crates/cuda-driver/tests/projection_family_gpu.rs +++ b/crates/cuda-driver/tests/projection_family_gpu.rs @@ -1,11 +1,6 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use leleka_cuda_driver::{ - Context, DenseFormat as D, DeviceBuffer, Driver, Error, ProjectionKind as K, ProjectionSpec, - RoutedFormat as R, + Context, DenseFormat as D, DeviceBuffer, Driver, Error, ProjectionKind as K, ProjectionSpec, RoutedFormat as R, }; use std::{fs, path::PathBuf, process::Command}; const MODES: [K; 10] = [ @@ -20,18 +15,8 @@ const MODES: [K; 10] = [ K::Routed(R::IQ4_XS), K::Routed(R::Q2_0), ]; -const BLOCK: [(usize, usize); 10] = [ - (32, 34), - (256, 144), - (256, 98), - (256, 110), - (256, 82), - (32, 18), - (32, 18), - (256, 136), - (256, 136), - (64, 18), -]; +const BLOCK: [(usize, usize); 10] = + [(32, 34), (256, 144), (256, 98), (256, 110), (256, 82), (32, 18), (32, 18), (256, 136), (256, 136), (64, 18)]; fn upload<'a>(c: &'a Context<'_>, bytes: &[u8]) -> DeviceBuffer<'a> { let mut b = c.allocate(bytes.len()).unwrap(); b.copy_from(bytes).unwrap(); @@ -115,42 +100,22 @@ fn case(c: &Context<'_>, paths: &OraclePaths, mode: usize, m: usize, n: usize, p .unwrap(); fs::write(root.join(format!("{stem}.stdout")), &out.stdout).unwrap(); fs::write(root.join(format!("{stem}.stderr")), &out.stderr).unwrap(); - assert!( - out.status.success(), - "native {stem}: {}", - String::from_utf8_lossy(&out.stderr) - ); + assert!(out.status.success(), "native {stem}: {}", String::from_utf8_lossy(&out.stderr)); let reference = fs::read(&result).unwrap(); let qb = n / 32 * 36; assert_eq!(reference.len(), 20 + 2 * qb + 4 * m); - for (i, h) in [0x31464f51, mode as u32, m as u32, n as u32, 0] - .into_iter() - .enumerate() - { + for (i, h) in [0x31464f51, mode as u32, m as u32, n as u32, 0].into_iter().enumerate() { assert_eq!(&reference[i * 4..i * 4 + 4], &h.to_le_bytes()); } - assert_eq!( - &reference[20..20 + qb], - &reference[20 + qb..20 + 2 * qb], - "independent native/candidate Q8 bytes" - ); + assert_eq!(&reference[20..20 + qb], &reference[20 + qb..20 + 2 * qb], "independent native/candidate Q8 bytes"); let weights = upload(c, &w); let activation = upload(c, &x); let mut output = upload(c, &vec![99; 4 * m]); let before = c.allocated_bytes(); let mut y = vec![0; 4 * m]; for _ in 0..2 { - c.project_q8_1( - &weights, - &activation, - &mut output, - ProjectionSpec { - kind: MODES[mode], - rows: m, - columns: n, - }, - ) - .unwrap(); + c.project_q8_1(&weights, &activation, &mut output, ProjectionSpec { kind: MODES[mode], rows: m, columns: n }) + .unwrap(); assert_eq!(c.allocated_bytes(), before); output.copy_to(&mut y).unwrap(); exact_result(&y, &reference[20 + 2 * qb..]); @@ -195,11 +160,7 @@ fn numeric_refusals(c: &Context<'_>, mode: usize) { &weights, &activation, &mut output, - ProjectionSpec { - kind: MODES[mode], - rows: 1, - columns: 256 - } + ProjectionSpec { kind: MODES[mode], rows: 1, columns: 256 } ), Err(Error::InvalidQ8Activation) ); @@ -239,18 +200,10 @@ fn installed_driver_public_family_parity() { assert!(i < 10); } let d = Driver::load().unwrap(); - let c = d - .device(0) - .unwrap() - .create_context(128 * 1024 * 1024) - .unwrap(); + let c = d.device(0).unwrap().create_context(128 * 1024 * 1024).unwrap(); for mode in selected { let block = BLOCK[mode].0; - let widths = if mode == 2 { - vec![256, 512, 768, 1024, 1280, 2560] - } else { - vec![block, 256, 512] - }; + let widths = if mode == 2 { vec![256, 512, 768, 1024, 1280, 2560] } else { vec![block, 256, 512] }; for m in [1, 3, 4, 5] { for &n in &widths { for p in [0, 1] { diff --git a/crates/cuda-driver/tests/projection_family_mock.rs b/crates/cuda-driver/tests/projection_family_mock.rs index c27cd338..6763c243 100644 --- a/crates/cuda-driver/tests/projection_family_mock.rs +++ b/crates/cuda-driver/tests/projection_family_mock.rs @@ -1,11 +1,5 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -use leleka_cuda_driver::{ - DenseFormat as D, Driver, Error, ProjectionKind as K, ProjectionSpec, RoutedFormat as R, -}; +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +use leleka_cuda_driver::{DenseFormat as D, Driver, Error, ProjectionKind as K, ProjectionSpec, RoutedFormat as R}; use std::{fs, path::PathBuf, process::Command}; const KINDS: [K; 10] = [ K::Dense(D::Q8_0), diff --git a/crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs b/crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs index 4151de63..fdee6c23 100644 --- a/crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs +++ b/crates/cuda-driver/tests/projection_family_mock/common_protocol_matrix.rs @@ -6,10 +6,7 @@ use super::*; #[test] #[ignore = "isolated GPU-hidden Linux CPU ELF only"] fn common_protocol_matrix() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let root = PathBuf::from(std::env::var("LELEKA_FAMILY_ROOT").unwrap()); assert!(root.is_absolute()); let unit = std::env::var("LELEKA_FAMILY_UNIT_ELF").unwrap(); @@ -20,58 +17,26 @@ fn common_protocol_matrix() { for status in [1u32, 2, 3, 0x80000000] { cases.push((format!("status{status}"), 640, "", "", status, false, false)); } - for fault in [ - "load", - "lookup:1", - "lookup:1,unload:1", - "htod:2", - "dtoh:1", - "free:1", - "free:2", - ] { + for fault in ["load", "lookup:1", "lookup:1,unload:1", "htod:2", "dtoh:1", "free:1", "free:2"] { cases.push((fault.replace(':', "-"), 640, fault, "", 0, true, false)); } - for fault in [ - "quant_launch", - "quant_sync", - "quant_restore", - "quant_launch,quant_sync,quant_restore", - ] { + for fault in ["quant_launch", "quant_sync", "quant_restore", "quant_launch,quant_sync,quant_restore"] { cases.push((fault.replace(',', "-"), 640, "", fault, 0, true, false)); } for fault in ["unload:1", "destroy:1"] { - cases.push(( - format!("close-{}", fault.replace(':', "-")), - 640, - fault, - "", - 0, - false, - true, - )); + cases.push((format!("close-{}", fault.replace(':', "-")), 640, fault, "", 0, false, true)); } for (name, n, base, family, status, failure, close_failure) in cases { let trace = root.join(format!("{name}.trace")); let out = Command::new(&unit) - .args([ - "--exact", - "family_tests::family_quantizer_transport_child", - "--ignored", - "--nocapture", - ]) + .args(["--exact", "family_tests::family_quantizer_transport_child", "--ignored", "--nocapture"]) .env("MOCK_CUDA_TRACE", &trace) .env("LELEKA_FAMILY_N", n.to_string()) .env("MOCK_CUDA_FAIL", base) .env("MOCK_CUDA_FAMILY_FAIL", family) .env("MOCK_FAMILY_STATUS", status.to_string()) - .env( - "LELEKA_FAMILY_EXPECT_FAILURE", - if failure { "1" } else { "0" }, - ) - .env( - "LELEKA_FAMILY_CLOSE_FAILURE", - if close_failure { "1" } else { "0" }, - ) + .env("LELEKA_FAMILY_EXPECT_FAILURE", if failure { "1" } else { "0" }) + .env("LELEKA_FAMILY_CLOSE_FAILURE", if close_failure { "1" } else { "0" }) .output() .unwrap(); fs::write(root.join(format!("{name}.stdout")), &out.stdout).unwrap(); @@ -121,16 +86,7 @@ fn common_protocol_matrix() { let charged = context.allocated_bytes(); for kind in KINDS { assert_eq!( - context.project_q8_1( - &w, - &x, - &mut y, - ProjectionSpec { - kind, - rows: 0, - columns: usize::MAX - } - ), + context.project_q8_1(&w, &x, &mut y, ProjectionSpec { kind, rows: 0, columns: usize::MAX }), if (q8_enabled && kind == KINDS[0]) || (q4k_enabled && kind == KINDS[1]) || (iq3_enabled && kind == KINDS[2]) @@ -154,16 +110,7 @@ fn common_protocol_matrix() { let foreign = driver.device(0).unwrap().create_context(64).unwrap(); let z = foreign.allocate(4).unwrap(); assert_eq!( - context.project_q8_1( - &w, - &z, - &mut y, - ProjectionSpec { - kind: KINDS[0], - rows: 1, - columns: 32 - } - ), + context.project_q8_1(&w, &z, &mut y, ProjectionSpec { kind: KINDS[0], rows: 1, columns: 32 }), Err(Error::ContextMismatch) ); // Release the completed admission/refusal fixtures before allocating the @@ -229,12 +176,7 @@ fn common_protocol_matrix() { let stem = format!("public-mode{mode}-{}", name.replace([':', ','], "-")); let child_trace = root.join(format!("{stem}.trace")); let out = Command::new(¤t) - .args([ - "--exact", - "family_public_q8_child", - "--ignored", - "--nocapture", - ]) + .args(["--exact", "family_public_q8_child", "--ignored", "--nocapture"]) .env("LELEKA_FAMILY_PUBLIC_MODE", mode.to_string()) .env("LELEKA_FAMILY_PUBLIC_CASE", &name) .env("MOCK_CUDA_TRACE", &child_trace) @@ -307,16 +249,7 @@ fn common_protocol_matrix() { (&q8_weights, &short_activation, 0, 32), ] { context - .project_q8_1( - weights, - activation, - &mut output, - ProjectionSpec { - kind: KINDS[mode], - rows: 1, - columns, - }, - ) + .project_q8_1(weights, activation, &mut output, ProjectionSpec { kind: KINDS[mode], rows: 1, columns }) .unwrap_or_else(|error| panic!("mixed public mode {mode}: {error:?}")); assert_eq!(context.allocated_bytes(), charged); let mut bytes = [0; 4]; @@ -335,65 +268,18 @@ fn common_protocol_matrix() { "module_family_iq4xs ", "module_family_q2 ", ] { - assert_eq!( - mixed.lines().filter(|line| line.starts_with(label)).count(), - 1 - ); + assert_eq!(mixed.lines().filter(|line| line.starts_with(label)).count(), 1); } - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_projection_complete ")) - .count(), - 2 - ); - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_q4k_projection_complete ")) - .count(), - 1 - ); - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_iq3xxs_projection_complete ")) - .count(), - 1 - ); - for label in [ - "family_iq3s_projection_complete ", - "family_iq2s_projection_complete ", - ] { - assert_eq!( - mixed.lines().filter(|line| line.starts_with(label)).count(), - 1 - ); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_projection_complete ")).count(), 2); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_q4k_projection_complete ")).count(), 1); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_iq3xxs_projection_complete ")).count(), 1); + for label in ["family_iq3s_projection_complete ", "family_iq2s_projection_complete "] { + assert_eq!(mixed.lines().filter(|line| line.starts_with(label)).count(), 1); } - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_iq4nl_projection_complete ")) - .count(), - 2 - ); - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_iq4xs_projection_complete ")) - .count(), - 2 - ); - assert_eq!( - mixed - .lines() - .filter(|line| line.starts_with("family_q2_projection_complete ")) - .count(), - 1 - ); - println!( - "FAMILY_MIXED_CACHE PASS q8-q4k-iq3xxs-iq3s-iq2s-iq4nl-iq4xs-q2-q8 shared_quantizer=true" - ); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_iq4nl_projection_complete ")).count(), 2); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_iq4xs_projection_complete ")).count(), 2); + assert_eq!(mixed.lines().filter(|line| line.starts_with("family_q2_projection_complete ")).count(), 1); + println!("FAMILY_MIXED_CACHE PASS q8-q4k-iq3xxs-iq3s-iq2s-iq4nl-iq4xs-q2-q8 shared_quantizer=true"); drop(output); drop(wide_activation); drop(q2_activation); diff --git a/crates/cuda-driver/tests/projection_family_mock/family_public_q8_child.rs b/crates/cuda-driver/tests/projection_family_mock/family_public_q8_child.rs index a2164dd7..7e2ad9ec 100644 --- a/crates/cuda-driver/tests/projection_family_mock/family_public_q8_child.rs +++ b/crates/cuda-driver/tests/projection_family_mock/family_public_q8_child.rs @@ -3,29 +3,16 @@ #[allow(unused_imports)] use super::*; - #[test] #[ignore = "requires frozen integrated assets; CPU transport only"] fn family_public_q8_child() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); - assert_eq!( - std::env::var("LELEKA_FAMILY_Q8_ENABLED").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); + assert_eq!(std::env::var("LELEKA_FAMILY_Q8_ENABLED").as_deref(), Ok("1")); let case = std::env::var("LELEKA_FAMILY_PUBLIC_CASE").unwrap(); - let mode: usize = std::env::var("LELEKA_FAMILY_PUBLIC_MODE") - .unwrap_or_else(|_| "0".into()) - .parse() - .unwrap(); + let mode: usize = std::env::var("LELEKA_FAMILY_PUBLIC_MODE").unwrap_or_else(|_| "0".into()).parse().unwrap(); assert!(mode <= 9); if mode == 9 { - assert_eq!( - std::env::var("LELEKA_FAMILY_Q2_ENABLED").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_FAMILY_Q2_ENABLED").as_deref(), Ok("1")); } let columns = match mode { 0 => 640, @@ -118,11 +105,7 @@ fn family_public_q8_child() { 8192 }) .unwrap(); - let wbytes = if case == "size" { - valid_weight_bytes - 2 - } else { - valid_weight_bytes - }; + let wbytes = if case == "size" { valid_weight_bytes - 2 } else { valid_weight_bytes }; let mut weights = context.allocate(wbytes).unwrap(); weights.copy_from(&vec![3; wbytes]).unwrap(); let mut activation = context.allocate(columns * 4).unwrap(); @@ -136,20 +119,9 @@ fn family_public_q8_child() { &weights, &activation, &mut output, - ProjectionSpec { - kind: KINDS[mode], - rows: 5, - columns: if case == "shape" { - columns + 1 - } else { - columns - }, - }, + ProjectionSpec { kind: KINDS[mode], rows: 5, columns: if case == "shape" { columns + 1 } else { columns } }, ); - let status = std::env::var("MOCK_FAMILY_STATUS") - .unwrap_or_else(|_| "0".into()) - .parse::() - .unwrap(); + let status = std::env::var("MOCK_FAMILY_STATUS").unwrap_or_else(|_| "0".into()).parse::().unwrap(); let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default(); let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default(); let operation_failure = matches!(case.as_str(), "budget" | "size" | "shape") @@ -158,22 +130,14 @@ fn family_public_q8_child() { || (!base.is_empty() && !matches!(base.as_str(), "unload:1" | "unload:2" | "destroy:1")); assert_eq!(result.is_err(), operation_failure, "{case}: {result:?}"); if matches!(case.as_str(), "budget" | "size" | "shape") { - assert_eq!( - result, - Err(if case == "budget" { - Error::BudgetExceeded - } else { - Error::InvalidProjectionShape - }) - ); + assert_eq!(result, Err(if case == "budget" { Error::BudgetExceeded } else { Error::InvalidProjectionShape })); assert_eq!(fs::read(&trace).unwrap(), before_trace); assert_eq!(context.allocated_bytes(), before); } else if status != 0 { assert_eq!(result, Err(Error::InvalidQ8Activation)); } let rows = fs::read_to_string(&trace).unwrap(); - let poisoned = - family.contains("sync") || family.contains("restore") || base == "lookup:2,unload:1"; + let poisoned = family.contains("sync") || family.contains("restore") || base == "lookup:2,unload:1"; let expected_charge = if poisoned { before + scratch_bytes + 4 } else if base == "free:1" { @@ -188,48 +152,27 @@ fn family_public_q8_child() { let mut y = [0; 20]; output.copy_to(&mut y).unwrap(); if !operation_failure { - let expected: Vec = (0..5) - .flat_map(|r| (17f32 + r as f32).to_le_bytes()) - .collect(); + let expected: Vec = (0..5).flat_map(|r| (17f32 + r as f32).to_le_bytes()).collect(); assert_eq!(y.as_slice(), expected); context .project_q8_1( &weights, &activation, &mut output, - ProjectionSpec { - kind: KINDS[mode], - rows: 5, - columns, - }, + ProjectionSpec { kind: KINDS[mode], rows: 5, columns }, ) .unwrap(); output.copy_to(&mut y).unwrap(); assert_eq!(y.as_slice(), expected); let rows = fs::read_to_string(&trace).unwrap(); - assert_eq!( - rows.lines() - .filter(|l| l.starts_with("module_family_quantizer ")) - .count(), - 1 - ); - assert_eq!( - rows.lines().filter(|l| l.starts_with(module_label)).count(), - 1 - ); + assert_eq!(rows.lines().filter(|l| l.starts_with("module_family_quantizer ")).count(), 1); + assert_eq!(rows.lines().filter(|l| l.starts_with(module_label)).count(), 1); } else if matches!(base.as_str(), "free:1" | "free:2") { // Both scratch frees follow a successfully synchronized projection. // A cleanup error retains its budget but does not undo computed output. - let expected: Vec = (0..5) - .flat_map(|r| (17f32 + r as f32).to_le_bytes()) - .collect(); + let expected: Vec = (0..5).flat_map(|r| (17f32 + r as f32).to_le_bytes()).collect(); assert_eq!(y.as_slice(), expected); - assert_eq!( - rows.lines() - .filter(|l| l.starts_with(completion_label)) - .count(), - 1 - ); + assert_eq!(rows.lines().filter(|l| l.starts_with(completion_label)).count(), 1); } else if !family.contains("projection") { assert_eq!(y, [99; 20]); assert!(!rows.lines().any(|l| l.starts_with(launch_label))); @@ -247,35 +190,13 @@ fn family_public_q8_child() { } if case == "recover" { context - .project_q8_1( - &weights, - &activation, - &mut output, - ProjectionSpec { - kind: KINDS[mode], - rows: 5, - columns, - }, - ) + .project_q8_1(&weights, &activation, &mut output, ProjectionSpec { kind: KINDS[mode], rows: 5, columns }) .unwrap(); let rows = fs::read_to_string(&trace).unwrap(); - assert_eq!( - rows.lines() - .filter(|l| l.starts_with("module_family_quantizer ")) - .count(), - 1 - ); - assert_eq!( - rows.lines().filter(|l| l.starts_with(module_label)).count(), - 2 - ); + assert_eq!(rows.lines().filter(|l| l.starts_with("module_family_quantizer ")).count(), 1); + assert_eq!(rows.lines().filter(|l| l.starts_with(module_label)).count(), 2); assert_eq!(rows.lines().filter(|l| l.starts_with("unload ")).count(), 1); - assert_eq!( - rows.lines() - .filter(|l| l.starts_with(completion_label)) - .count(), - 1 - ); + assert_eq!(rows.lines().filter(|l| l.starts_with(completion_label)).count(), 1); assert_eq!(context.allocated_bytes(), before); } drop(weights); diff --git a/crates/cuda-driver/tests/projection_family_oracle.rs b/crates/cuda-driver/tests/projection_family_oracle.rs index e6d6e302..391a8539 100644 --- a/crates/cuda-driver/tests/projection_family_oracle.rs +++ b/crates/cuda-driver/tests/projection_family_oracle.rs @@ -1,26 +1,11 @@ //! Independent geometry expectations frozen from native layouts, not candidate output. //! Numeric acceptance is the separately executed pinned native GPU oracle. #[allow(dead_code)] -pub const LAYOUTS: [(usize, usize); 8] = [ - (32, 34), - (256, 144), - (256, 98), - (256, 110), - (256, 82), - (32, 18), - (256, 136), - (64, 18), -]; +pub const LAYOUTS: [(usize, usize); 8] = + [(32, 34), (256, 144), (256, 98), (256, 110), (256, 82), (32, 18), (256, 136), (64, 18)]; #[allow(dead_code)] -pub const TAILS: [(usize, usize, usize); 7] = [ - (32, 36, 1), - (64, 72, 1), - (96, 108, 1), - (224, 252, 1), - (256, 288, 1), - (288, 324, 2), - (640, 720, 3), -]; +pub const TAILS: [(usize, usize, usize); 7] = + [(32, 36, 1), (64, 72, 1), (96, 108, 1), (224, 252, 1), (256, 288, 1), (288, 324, 2), (640, 720, 3)]; #[test] fn frozen_tail_expectations_are_whole_warps() { for (n, bytes, blocks) in TAILS { diff --git a/crates/cuda-driver/tests/q5_gpu.rs b/crates/cuda-driver/tests/q5_gpu.rs index dfa37760..ea867def 100644 --- a/crates/cuda-driver/tests/q5_gpu.rs +++ b/crates/cuda-driver/tests/q5_gpu.rs @@ -1,8 +1,4 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "q5_oracle.rs"] mod oracle; use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Error, Q5KProjectionShape}; @@ -23,13 +19,7 @@ fn read(b: &DeviceBuffer<'_>) -> Vec { } fn compare_output(actual: &[u8], expected: &[u8]) { assert_eq!(actual.len(), expected.len()); - for (i, (a, b)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(expected.as_chunks::<4>().0.iter()) - .enumerate() - { + for (i, (a, b)) in actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0.iter()).enumerate() { let a = u32::from_le_bytes(*a); let b = u32::from_le_bytes(*b); if f32::from_bits(b).is_nan() { @@ -39,15 +29,7 @@ fn compare_output(actual: &[u8], expected: &[u8]) { } } } -fn run_case( - ctx: &Context<'_>, - root: &Path, - native: &Path, - ptx: &Path, - rows: usize, - columns: usize, - pattern: usize, -) { +fn run_case(ctx: &Context<'_>, root: &Path, native: &Path, ptx: &Path, rows: usize, columns: usize, pattern: usize) { let w = oracle::weights(rows, columns, pattern); let x = oracle::activation(columns, pattern); let xb = oracle::f32bytes(&x); @@ -71,31 +53,17 @@ fn run_case( .unwrap(); fs::write(root.join(format!("{stem}.stdout")), &output.stdout).unwrap(); fs::write(root.join(format!("{stem}.stderr")), &output.stderr).unwrap(); - assert!( - output.status.success(), - "native {stem}: {}", - String::from_utf8_lossy(&output.stderr) - ); + assert!(output.status.success(), "native {stem}: {}", String::from_utf8_lossy(&output.stderr)); let expected = fs::read(&result).unwrap(); let qb = columns / 32 * 36; assert_eq!(expected.len(), 16 + 2 * qb + rows * 4); - assert_eq!( - u32::from_le_bytes(expected[0..4].try_into().unwrap()), - 0x35314f51 - ); + assert_eq!(u32::from_le_bytes(expected[0..4].try_into().unwrap()), 0x35314f51); assert_eq!(&expected[4..8], &(rows as u32).to_le_bytes()); assert_eq!(&expected[8..12], &(columns as u32).to_le_bytes()); - assert_eq!( - &expected[12..16], - &0u32.to_le_bytes(), - "native-math activation admission" - ); + assert_eq!(&expected[12..16], &0u32.to_le_bytes(), "native-math activation admission"); let nativeq = &expected[16..16 + qb]; let candidateq = &expected[16 + qb..16 + 2 * qb]; - assert_eq!( - candidateq, nativeq, - "all independently quantized Q8 bytes {stem}" - ); + assert_eq!(candidateq, nativeq, "all independently quantized Q8 bytes {stem}"); if pattern == 1 { for block in nativeq.as_chunks::<36>().0.iter() { assert_eq!(&block[..4], &[0, 0x3c, 0, 0]); @@ -112,11 +80,7 @@ fn run_case( } if pattern == 7 { for word in expected[16 + 2 * qb..].as_chunks::<4>().0.iter() { - assert_eq!( - f32::from_le_bytes(*word), - 959104.0 * (columns / 256) as f32, - "independent hand projection" - ); + assert_eq!(f32::from_le_bytes(*word), 959104.0 * (columns / 256) as f32, "independent hand projection"); } } let dw = upload(ctx, &w); @@ -124,8 +88,7 @@ fn run_case( let sentinel = vec![0xa5; rows * 4]; let mut dy = upload(ctx, &sentinel); let charged = ctx.allocated_bytes(); - ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns }) - .expect("safe resident public projection"); + ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns }).expect("safe resident public projection"); let actual = read(&dy); compare_output(&actual, &expected[16 + 2 * qb..]); assert_eq!(read(&dw), w, "compressed weights immutable"); @@ -133,17 +96,14 @@ fn run_case( assert_eq!(ctx.allocated_bytes(), charged, "healthy temporary cleanup"); // Repeat proves the public cache path and stable ownership, against the SAME // frozen native result, not a first candidate run used as a baseline. - ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns }) - .unwrap(); + ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows, columns }).unwrap(); compare_output(&read(&dy), &expected[16 + 2 * qb..]); fs::write(root.join(format!("{stem}.actual")), &actual).unwrap(); dw.release().unwrap(); dx.release().unwrap(); dy.release().unwrap(); assert_eq!(ctx.allocated_bytes(), 0); - println!( - "Q5_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0" - ); + println!("Q5_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0"); } #[test] #[ignore = "requires installed NVIDIA GPU, pinned independent native fixture and explicit private evidence root"] @@ -169,9 +129,7 @@ fn installed_driver_q5_native_parity() { run_case(&ctx, &root, &native, &ptx, 3, 256, pattern); } ctx.close().unwrap(); - println!( - "Q5_PARITY_SUMMARY cases=29 public_launches=58 q8_exact=true outputs_exact=true context_close=ok" - ); + println!("Q5_PARITY_SUMMARY cases=29 public_launches=58 q8_exact=true outputs_exact=true context_close=ok"); } #[test] #[ignore = "requires installed NVIDIA driver, explicit opt-in"] @@ -203,15 +161,7 @@ fn installed_driver_q5_numeric_refusals() { let dx = upload(&ctx, &xb); let charged = ctx.allocated_bytes(); assert_eq!( - ctx.q5_k_q8_1( - &dw, - &dx, - &mut dy, - Q5KProjectionShape { - rows: 1, - columns: 256 - } - ), + ctx.q5_k_q8_1(&dw, &dx, &mut dy, Q5KProjectionShape { rows: 1, columns: 256 }), Err(Error::InvalidQ8Activation), "{name}" ); @@ -249,10 +199,7 @@ fn installed_driver_q5_real_tensor_component() { assert_eq!(&data[8..12], &(n as u32).to_le_bytes()); // Synthetic activation must equal our independent deterministic input, // rather than a captured request or an arbitrary external fixture. - assert_eq!( - &data[12 + wb..], - oracle::f32bytes(&oracle::activation(n, 0)) - ); + assert_eq!(&data[12 + wb..], oracle::f32bytes(&oracle::activation(n, 0))); let result = root.join("real-qwen-q5.native"); let out = Command::new("timeout") .args(["--signal=TERM", "--kill-after=5", "30"]) @@ -264,20 +211,12 @@ fn installed_driver_q5_real_tensor_component() { .unwrap(); fs::write(root.join("real-qwen-q5.stdout"), &out.stdout).unwrap(); fs::write(root.join("real-qwen-q5.stderr"), &out.stderr).unwrap(); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let expected = fs::read(result).unwrap(); assert_eq!(expected.len(), 16 + 2 * qb + m * 4); assert_eq!(&expected[..4], &0x35314f51u32.to_le_bytes()); assert_eq!(&expected[12..16], &0u32.to_le_bytes()); - assert_eq!( - &expected[16..16 + qb], - &expected[16 + qb..16 + 2 * qb], - "separate fresh Q8 bytes" - ); + assert_eq!(&expected[16..16 + qb], &expected[16 + qb..16 + 2 * qb], "separate fresh Q8 bytes"); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let ctx = device.create_context(8 << 20).unwrap(); @@ -286,16 +225,7 @@ fn installed_driver_q5_real_tensor_component() { let mut y = upload(&ctx, &vec![0xa5; m * 4]); let resident = ctx.allocated_bytes(); for _ in 0..2 { - ctx.q5_k_q8_1( - &w, - &x, - &mut y, - Q5KProjectionShape { - rows: m, - columns: n, - }, - ) - .unwrap(); + ctx.q5_k_q8_1(&w, &x, &mut y, Q5KProjectionShape { rows: m, columns: n }).unwrap(); compare_output(&read(&y), &expected[16 + 2 * qb..]); assert_eq!(ctx.allocated_bytes(), resident); } diff --git a/crates/cuda-driver/tests/q5_mock.rs b/crates/cuda-driver/tests/q5_mock.rs index 49c021d2..028a1361 100644 --- a/crates/cuda-driver/tests/q5_mock.rs +++ b/crates/cuda-driver/tests/q5_mock.rs @@ -1,8 +1,4 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use leleka_cuda_driver::{Driver, Error, Q5KProjectionShape}; use std::{fs, path::PathBuf, process::Command}; #[derive(Debug)] @@ -73,10 +69,7 @@ const CASES: &[&str] = &[ #[test] #[ignore = "isolated CPU ELF protocol fixture only, no GPU arithmetic claim"] fn isolated_q5_protocol_matrix() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let root = PathBuf::from(std::env::var("LELEKA_CUDA_Q5_MOCK_ROOT").unwrap()); assert!(root.is_absolute()); for case in CASES { @@ -123,10 +116,7 @@ fn isolated_q5_protocol_matrix() { #[test] #[ignore = "only invoked by isolated_q5_protocol_matrix"] fn q5_fixture_child() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let case = std::env::var("LELEKA_Q5_CASE").unwrap(); assert!(CASES.contains(&case.as_str())); let (m, n) = match case.as_str() { @@ -140,9 +130,7 @@ fn q5_fixture_child() { let resident = wb + xb + ob; let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); - let ctx = device - .create_context(if case == "budget" { resident } else { 16384 }) - .unwrap(); + let ctx = device.create_context(if case == "budget" { resident } else { 16384 }).unwrap(); let mut w = ctx.allocate(wb).unwrap(); w.copy_from(&vec![0; wb]).unwrap(); let mut x = ctx.allocate(xb).unwrap(); @@ -161,51 +149,20 @@ fn q5_fixture_child() { let sentinel = vec![0xa5; ob]; y.copy_from(&sentinel).unwrap(); let before = trace().len(); - let shape = Q5KProjectionShape { - rows: m, - columns: n, - }; + let shape = Q5KProjectionShape { rows: m, columns: n }; if case == "bounds" { for shape in [ - Q5KProjectionShape { - rows: 0, - columns: 256, - }, - Q5KProjectionShape { - rows: 1, - columns: 0, - }, - Q5KProjectionShape { - rows: 1, - columns: 255, - }, - Q5KProjectionShape { - rows: 1, - columns: 257, - }, - Q5KProjectionShape { - rows: usize::MAX, - columns: 256, - }, - Q5KProjectionShape { - rows: 1, - columns: usize::MAX, - }, - Q5KProjectionShape { - rows: i32::MAX as usize + 1, - columns: 256, - }, + Q5KProjectionShape { rows: 0, columns: 256 }, + Q5KProjectionShape { rows: 1, columns: 0 }, + Q5KProjectionShape { rows: 1, columns: 255 }, + Q5KProjectionShape { rows: 1, columns: 257 }, + Q5KProjectionShape { rows: usize::MAX, columns: 256 }, + Q5KProjectionShape { rows: 1, columns: usize::MAX }, + Q5KProjectionShape { rows: i32::MAX as usize + 1, columns: 256 }, ] { - assert_eq!( - ctx.q5_k_q8_1(&w, &x, &mut y, shape), - Err(Error::InvalidQ5KProjectionShape) - ); + assert_eq!(ctx.q5_k_q8_1(&w, &x, &mut y, shape), Err(Error::InvalidQ5KProjectionShape)); } - assert_eq!( - trace().len(), - before, - "structural admission before native mutation" - ); + assert_eq!(trace().len(), before, "structural admission before native mutation"); } else if case == "sizes" { for which in 0..3 { let mut short = ctx @@ -231,10 +188,7 @@ fn q5_fixture_child() { let other = device.create_context(2048).unwrap(); let otherx = other.allocate(xb).unwrap(); let mark = trace().len(); - assert_eq!( - ctx.q5_k_q8_1(&w, &otherx, &mut y, shape), - Err(Error::ContextMismatch) - ); + assert_eq!(ctx.q5_k_q8_1(&w, &otherx, &mut y, shape), Err(Error::ContextMismatch)); assert_eq!(trace().len(), mark); otherx.release().unwrap(); other.close().unwrap(); @@ -276,10 +230,7 @@ fn q5_fixture_child() { } "quant_sync" | "projection_sync" | "quant_restore" | "projection_restore" => { assert!(driver_codes(&result.unwrap_err()).contains(&700)); - assert!( - ctx.allocated_bytes() > resident, - "uncertain scratch stays charged" - ); + assert!(ctx.allocated_bytes() > resident, "uncertain scratch stays charged"); let mark = trace().len(); assert_eq!(ctx.synchronize(), Err(Error::ContextPoisoned)); assert_eq!(trace().len(), mark); @@ -292,13 +243,7 @@ fn q5_fixture_child() { } } } - let poisoned = [ - "quant_sync", - "projection_sync", - "quant_restore", - "projection_restore", - ] - .contains(&case.as_str()); + let poisoned = ["quant_sync", "projection_sync", "quant_restore", "projection_restore"].contains(&case.as_str()); if !poisoned { if [ "bounds", @@ -338,10 +283,7 @@ fn q5_fixture_child() { close.unwrap(); } let rows = trace(); - assert_eq!( - count(&rows, "destroy"), - if case == "context" { 2 } else { 1 } - ); + assert_eq!(count(&rows, "destroy"), if case == "context" { 2 } else { 1 }); assert_eq!(count(&rows, "unsafe_q5_pending_free"), 0); assert_eq!(count(&rows, "unsafe_pending_unload"), 0); if !poisoned { diff --git a/crates/cuda-driver/tests/q5_oracle.rs b/crates/cuda-driver/tests/q5_oracle.rs index 1ea0a6b7..794f592a 100644 --- a/crates/cuda-driver/tests/q5_oracle.rs +++ b/crates/cuda-driver/tests/q5_oracle.rs @@ -145,16 +145,7 @@ fn packed_layout_independent_hand_oracle() { assert_eq!(half(0x0001).to_bits(), 0x33800000); assert_eq!(half(0x8000).to_bits(), 0x80000000); let mut scales = [0u8; 12]; - let pairs = [ - (0, 63), - (1, 32), - (15, 16), - (16, 15), - (31, 1), - (32, 0), - (48, 48), - (63, 63), - ]; + let pairs = [(0, 63), (1, 32), (15, 16), (16, 15), (31, 1), (32, 0), (48, 48), (63, 63)]; for (g, (s, m)) in pairs.into_iter().enumerate() { pack_scale_min(&mut scales, g, s, m); } diff --git a/crates/cuda-driver/tests/q6_gpu.rs b/crates/cuda-driver/tests/q6_gpu.rs index aafb3057..9af75234 100644 --- a/crates/cuda-driver/tests/q6_gpu.rs +++ b/crates/cuda-driver/tests/q6_gpu.rs @@ -1,8 +1,4 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] #[path = "q6_oracle.rs"] mod oracle; use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Error, Q6KProjectionShape}; @@ -23,13 +19,7 @@ fn read(b: &DeviceBuffer<'_>) -> Vec { } fn compare_output(actual: &[u8], expected: &[u8]) { assert_eq!(actual.len(), expected.len()); - for (i, (a, b)) in actual - .as_chunks::<4>() - .0 - .iter() - .zip(expected.as_chunks::<4>().0.iter()) - .enumerate() - { + for (i, (a, b)) in actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0.iter()).enumerate() { let a = u32::from_le_bytes(*a); let b = u32::from_le_bytes(*b); if f32::from_bits(b).is_nan() { @@ -39,15 +29,7 @@ fn compare_output(actual: &[u8], expected: &[u8]) { } } } -fn run_case( - ctx: &Context<'_>, - root: &Path, - native: &Path, - ptx: &Path, - rows: usize, - columns: usize, - pattern: usize, -) { +fn run_case(ctx: &Context<'_>, root: &Path, native: &Path, ptx: &Path, rows: usize, columns: usize, pattern: usize) { let w = oracle::weights(rows, columns, pattern); let x = oracle::activation(columns, pattern); let xb = oracle::f32bytes(&x); @@ -71,31 +53,17 @@ fn run_case( .unwrap(); fs::write(root.join(format!("{stem}.stdout")), &output.stdout).unwrap(); fs::write(root.join(format!("{stem}.stderr")), &output.stderr).unwrap(); - assert!( - output.status.success(), - "native {stem}: {}", - String::from_utf8_lossy(&output.stderr) - ); + assert!(output.status.success(), "native {stem}: {}", String::from_utf8_lossy(&output.stderr)); let expected = fs::read(&result).unwrap(); let qb = columns / 32 * 36; assert_eq!(expected.len(), 16 + 2 * qb + rows * 4); - assert_eq!( - u32::from_le_bytes(expected[0..4].try_into().unwrap()), - 0x36314f51 - ); + assert_eq!(u32::from_le_bytes(expected[0..4].try_into().unwrap()), 0x36314f51); assert_eq!(&expected[4..8], &(rows as u32).to_le_bytes()); assert_eq!(&expected[8..12], &(columns as u32).to_le_bytes()); - assert_eq!( - &expected[12..16], - &0u32.to_le_bytes(), - "native-math activation admission" - ); + assert_eq!(&expected[12..16], &0u32.to_le_bytes(), "native-math activation admission"); let nativeq = &expected[16..16 + qb]; let candidateq = &expected[16 + qb..16 + 2 * qb]; - assert_eq!( - candidateq, nativeq, - "all independently quantized Q8 bytes {stem}" - ); + assert_eq!(candidateq, nativeq, "all independently quantized Q8 bytes {stem}"); if pattern == 1 { for block in nativeq.as_chunks::<36>().0.iter() { assert_eq!(&block[..4], &[0, 0x3c, 0, 0]); @@ -112,47 +80,27 @@ fn run_case( } if pattern == 7 { for word in expected[16 + 2 * qb..].as_chunks::<4>().0.iter() { - assert_eq!( - f32::from_le_bytes(*word), - 65024.0 * (columns / 256) as f32, - "independent hand projection" - ); + assert_eq!(f32::from_le_bytes(*word), 65024.0 * (columns / 256) as f32, "independent hand projection"); } } if pattern == 8 { - for (row, word) in expected[16 + 2 * qb..] - .as_chunks::<4>() - .0 - .iter() - .enumerate() - { + for (row, word) in expected[16 + 2 * qb..].as_chunks::<4>().0.iter().enumerate() { assert_eq!( u32::from_le_bytes(*word), - if row.is_multiple_of(2) { - f32::INFINITY.to_bits() - } else { - f32::NEG_INFINITY.to_bits() - }, + if row.is_multiple_of(2) { f32::INFINITY.to_bits() } else { f32::NEG_INFINITY.to_bits() }, "independent signed infinity case" ); } } if pattern == 9 { - assert!( - expected[16 + 2 * qb..] - .as_chunks::<4>() - .0 - .iter() - .all(|word| f32::from_le_bytes(*word).is_nan()) - ); + assert!(expected[16 + 2 * qb..].as_chunks::<4>().0.iter().all(|word| f32::from_le_bytes(*word).is_nan())); } let dw = upload(ctx, &w); let dx = upload(ctx, &xb); let sentinel = vec![0xa5; rows * 4]; let mut dy = upload(ctx, &sentinel); let charged = ctx.allocated_bytes(); - ctx.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows, columns }) - .expect("safe resident public projection"); + ctx.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows, columns }).expect("safe resident public projection"); let actual = read(&dy); compare_output(&actual, &expected[16 + 2 * qb..]); assert_eq!(read(&dw), w, "compressed weights immutable"); @@ -160,17 +108,14 @@ fn run_case( assert_eq!(ctx.allocated_bytes(), charged, "healthy temporary cleanup"); // Repeat proves the public cache path and stable ownership, against the SAME // frozen native result, not a first candidate run used as a baseline. - ctx.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows, columns }) - .unwrap(); + ctx.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows, columns }).unwrap(); compare_output(&read(&dy), &expected[16 + 2 * qb..]); fs::write(root.join(format!("{stem}.actual")), &actual).unwrap(); dw.release().unwrap(); dx.release().unwrap(); dy.release().unwrap(); assert_eq!(ctx.allocated_bytes(), 0); - println!( - "Q6_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0" - ); + println!("Q6_NATIVE PASS {stem} q8_bytes={qb} outputs={rows} exactbits=true repeat=true cleanup=0"); } #[test] #[ignore = "requires installed NVIDIA GPU, pinned independent native fixture and explicit private evidence root"] @@ -199,9 +144,7 @@ fn installed_driver_q6_native_parity() { run_case(&ctx, &root, &native, &ptx, 3, 512, pattern); } ctx.close().unwrap(); - println!( - "Q6_PARITY_SUMMARY cases=36 public_launches=72 q8_exact=true outputs_exact=true context_close=ok" - ); + println!("Q6_PARITY_SUMMARY cases=36 public_launches=72 q8_exact=true outputs_exact=true context_close=ok"); } #[test] #[ignore = "requires installed NVIDIA driver, explicit opt-in"] @@ -233,15 +176,7 @@ fn installed_driver_q6_numeric_refusals() { let dx = upload(&ctx, &xb); let charged = ctx.allocated_bytes(); assert_eq!( - ctx.q6_k_q8_1( - &dw, - &dx, - &mut dy, - Q6KProjectionShape { - rows: 1, - columns: 256 - } - ), + ctx.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows: 1, columns: 256 }), Err(Error::InvalidQ8Activation), "{name}" ); @@ -279,10 +214,7 @@ fn installed_driver_q6_real_tensor_component() { assert_eq!(&data[8..12], &(n as u32).to_le_bytes()); // Synthetic activation must equal our independent deterministic input, // rather than a captured request or an arbitrary external fixture. - assert_eq!( - &data[12 + wb..], - oracle::f32bytes(&oracle::activation(n, 0)) - ); + assert_eq!(&data[12 + wb..], oracle::f32bytes(&oracle::activation(n, 0))); let result = root.join("real-qwen-q6.native"); let out = Command::new("timeout") .args(["--signal=TERM", "--kill-after=5", "30"]) @@ -294,20 +226,12 @@ fn installed_driver_q6_real_tensor_component() { .unwrap(); fs::write(root.join("real-qwen-q6.stdout"), &out.stdout).unwrap(); fs::write(root.join("real-qwen-q6.stderr"), &out.stderr).unwrap(); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); let expected = fs::read(result).unwrap(); assert_eq!(expected.len(), 16 + 2 * qb + m * 4); assert_eq!(&expected[..4], &0x36314f51u32.to_le_bytes()); assert_eq!(&expected[12..16], &0u32.to_le_bytes()); - assert_eq!( - &expected[16..16 + qb], - &expected[16 + qb..16 + 2 * qb], - "separate fresh Q8 bytes" - ); + assert_eq!(&expected[16..16 + qb], &expected[16 + qb..16 + 2 * qb], "separate fresh Q8 bytes"); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let ctx = device.create_context(32 << 20).unwrap(); @@ -316,16 +240,7 @@ fn installed_driver_q6_real_tensor_component() { let mut y = upload(&ctx, &vec![0xa5; m * 4]); let resident = ctx.allocated_bytes(); for _ in 0..2 { - ctx.q6_k_q8_1( - &w, - &x, - &mut y, - Q6KProjectionShape { - rows: m, - columns: n, - }, - ) - .unwrap(); + ctx.q6_k_q8_1(&w, &x, &mut y, Q6KProjectionShape { rows: m, columns: n }).unwrap(); compare_output(&read(&y), &expected[16 + 2 * qb..]); assert_eq!(ctx.allocated_bytes(), resident); } diff --git a/crates/cuda-driver/tests/q6_mock.rs b/crates/cuda-driver/tests/q6_mock.rs index 0e7db52b..934cff74 100644 --- a/crates/cuda-driver/tests/q6_mock.rs +++ b/crates/cuda-driver/tests/q6_mock.rs @@ -1,8 +1,4 @@ -#![cfg(all( - feature = "cuda-driver", - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#![cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] use leleka_cuda_driver::{Driver, Error, Q5KProjectionShape, Q6KProjectionShape}; use std::{fs, path::PathBuf, process::Command}; #[derive(Debug)] diff --git a/crates/cuda-driver/tests/q6_mock/isolated_q6_protocol_matrix.rs b/crates/cuda-driver/tests/q6_mock/isolated_q6_protocol_matrix.rs index 2c5709f8..b60fd1f5 100644 --- a/crates/cuda-driver/tests/q6_mock/isolated_q6_protocol_matrix.rs +++ b/crates/cuda-driver/tests/q6_mock/isolated_q6_protocol_matrix.rs @@ -6,10 +6,7 @@ use super::*; #[test] #[ignore = "isolated CPU ELF protocol fixture only, no GPU arithmetic claim"] fn isolated_q6_protocol_matrix() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let root = PathBuf::from(std::env::var("LELEKA_CUDA_Q6_MOCK_ROOT").unwrap()); assert!(root.is_absolute()); for case in CASES { diff --git a/crates/cuda-driver/tests/q6_mock/q6_fixture_child.rs b/crates/cuda-driver/tests/q6_mock/q6_fixture_child.rs index 1d343f59..b6ee7b6a 100644 --- a/crates/cuda-driver/tests/q6_mock/q6_fixture_child.rs +++ b/crates/cuda-driver/tests/q6_mock/q6_fixture_child.rs @@ -6,10 +6,7 @@ use super::*; #[test] #[ignore = "only invoked by isolated_q6_protocol_matrix"] fn q6_fixture_child() { - assert_eq!( - std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), - Ok("1") - ); + assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(), Ok("1")); let case = std::env::var("LELEKA_Q6_CASE").unwrap(); assert!(CASES.contains(&case.as_str())); let (m, n) = match case.as_str() { @@ -23,9 +20,7 @@ fn q6_fixture_child() { let resident = wb + xb + ob; let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); - let ctx = device - .create_context(if case == "budget" { resident } else { 16384 }) - .unwrap(); + let ctx = device.create_context(if case == "budget" { resident } else { 16384 }).unwrap(); let mut w = ctx.allocate(wb).unwrap(); w.copy_from(&vec![0; wb]).unwrap(); let mut x = ctx.allocate(xb).unwrap(); @@ -44,34 +39,13 @@ fn q6_fixture_child() { let sentinel = vec![0xa5; ob]; y.copy_from(&sentinel).unwrap(); let before = trace().len(); - let shape = Q6KProjectionShape { - rows: m, - columns: n, - }; + let shape = Q6KProjectionShape { rows: m, columns: n }; if case == "cache_partition" { let mut q5w = ctx.allocate(176).unwrap(); q5w.copy_from(&[0; 176]).unwrap(); - ctx.q5_k_q8_1( - &q5w, - &x, - &mut y, - Q5KProjectionShape { - rows: m, - columns: n, - }, - ) - .unwrap(); + ctx.q5_k_q8_1(&q5w, &x, &mut y, Q5KProjectionShape { rows: m, columns: n }).unwrap(); ctx.q6_k_q8_1(&w, &x, &mut y, shape).unwrap(); - ctx.q5_k_q8_1( - &q5w, - &x, - &mut y, - Q5KProjectionShape { - rows: m, - columns: n, - }, - ) - .unwrap(); + ctx.q5_k_q8_1(&q5w, &x, &mut y, Q5KProjectionShape { rows: m, columns: n }).unwrap(); ctx.q6_k_q8_1(&w, &x, &mut y, shape).unwrap(); let rows = trace(); assert_eq!(count(&rows, "module_q5"), 1); @@ -82,45 +56,17 @@ fn q6_fixture_child() { assert_eq!(ctx.allocated_bytes(), resident); } else if case == "bounds" { for shape in [ - Q6KProjectionShape { - rows: 0, - columns: 256, - }, - Q6KProjectionShape { - rows: 1, - columns: 0, - }, - Q6KProjectionShape { - rows: 1, - columns: 255, - }, - Q6KProjectionShape { - rows: 1, - columns: 257, - }, - Q6KProjectionShape { - rows: usize::MAX, - columns: 256, - }, - Q6KProjectionShape { - rows: 1, - columns: usize::MAX, - }, - Q6KProjectionShape { - rows: i32::MAX as usize + 1, - columns: 256, - }, + Q6KProjectionShape { rows: 0, columns: 256 }, + Q6KProjectionShape { rows: 1, columns: 0 }, + Q6KProjectionShape { rows: 1, columns: 255 }, + Q6KProjectionShape { rows: 1, columns: 257 }, + Q6KProjectionShape { rows: usize::MAX, columns: 256 }, + Q6KProjectionShape { rows: 1, columns: usize::MAX }, + Q6KProjectionShape { rows: i32::MAX as usize + 1, columns: 256 }, ] { - assert_eq!( - ctx.q6_k_q8_1(&w, &x, &mut y, shape), - Err(Error::InvalidQ6KProjectionShape) - ); + assert_eq!(ctx.q6_k_q8_1(&w, &x, &mut y, shape), Err(Error::InvalidQ6KProjectionShape)); } - assert_eq!( - trace().len(), - before, - "structural admission before native mutation" - ); + assert_eq!(trace().len(), before, "structural admission before native mutation"); } else if case == "sizes" { for which in 0..3 { let mut short = ctx @@ -146,20 +92,9 @@ fn q6_fixture_child() { let other = device.create_context(1024).unwrap(); let otherx = other.allocate(xb).unwrap(); let mark = trace().len(); + assert_eq!(ctx.q6_k_q8_1(&w, &otherx, &mut y, shape), Err(Error::ContextMismatch)); assert_eq!( - ctx.q6_k_q8_1(&w, &otherx, &mut y, shape), - Err(Error::ContextMismatch) - ); - assert_eq!( - ctx.q6_k_q8_1( - &w, - &otherx, - &mut y, - Q6KProjectionShape { - rows: 0, - columns: 0 - } - ), + ctx.q6_k_q8_1(&w, &otherx, &mut y, Q6KProjectionShape { rows: 0, columns: 0 }), Err(Error::ContextMismatch) ); assert_eq!(trace().len(), mark); @@ -201,29 +136,17 @@ fn q6_fixture_child() { assert!(matches!(result, Err(Error::InvalidDriverValue(_)))); assert_eq!(count(&trace(), "q6_projection_launch"), 0); } - "quant_sync" | "projection_sync" | "quant_restore" | "projection_restore" - | "quant_all_fail" => { + "quant_sync" | "projection_sync" | "quant_restore" | "projection_restore" | "quant_all_fail" => { let codes = driver_codes(&result.unwrap_err()); if case == "quant_all_fail" { assert_eq!(codes, [700, 700, 700]); } else { assert!(codes.contains(&700)); } - assert!( - ctx.allocated_bytes() > resident, - "uncertain scratch stays charged" - ); + assert!(ctx.allocated_bytes() > resident, "uncertain scratch stays charged"); let mark = trace().len(); assert_eq!( - ctx.q6_k_q8_1( - &w, - &x, - &mut y, - Q6KProjectionShape { - rows: 0, - columns: 0 - } - ), + ctx.q6_k_q8_1(&w, &x, &mut y, Q6KProjectionShape { rows: 0, columns: 0 }), Err(Error::ContextPoisoned) ); assert_eq!(ctx.synchronize(), Err(Error::ContextPoisoned)); @@ -236,11 +159,7 @@ fn q6_fixture_child() { } assert_eq!( count(&trace(), "q6_projection_launch"), - if case == "projection_launch" || case == "free" { - 1 - } else { - 0 - } + if case == "projection_launch" || case == "free" { 1 } else { 0 } ); if case != "free" && case != "unload" { assert_eq!(ctx.allocated_bytes(), resident); @@ -248,14 +167,8 @@ fn q6_fixture_child() { } } } - let poisoned = [ - "quant_sync", - "quant_all_fail", - "projection_sync", - "quant_restore", - "projection_restore", - ] - .contains(&case.as_str()); + let poisoned = ["quant_sync", "quant_all_fail", "projection_sync", "quant_restore", "projection_restore"] + .contains(&case.as_str()); if !poisoned { if [ "bounds", @@ -294,11 +207,7 @@ fn q6_fixture_child() { drop(y); } if case == "quant_all_fail" { - let failed = trace() - .into_iter() - .filter(|r| r.code == 700) - .map(|r| r.stage) - .collect::>(); + let failed = trace().into_iter().filter(|r| r.code == 700).map(|r| r.stage).collect::>(); assert_eq!(failed, ["launch", "sync", "pop"]); } let close = ctx.close(); @@ -308,10 +217,7 @@ fn q6_fixture_child() { close.unwrap(); } let rows = trace(); - assert_eq!( - count(&rows, "destroy"), - if case == "context" { 2 } else { 1 } - ); + assert_eq!(count(&rows, "destroy"), if case == "context" { 2 } else { 1 }); assert_eq!(count(&rows, "unsafe_q6_pending_free"), 0); assert_eq!(count(&rows, "unsafe_pending_unload"), 0); if !poisoned { diff --git a/crates/cuda-driver/tests/q6_oracle.rs b/crates/cuda-driver/tests/q6_oracle.rs index a130dbbe..a2a55bb9 100644 --- a/crates/cuda-driver/tests/q6_oracle.rs +++ b/crates/cuda-driver/tests/q6_oracle.rs @@ -23,8 +23,7 @@ pub fn code(block: &[u8], i: usize) -> i8 { let half = i / 128; let quarter = i % 128 / 32; let lane = i % 32; - let low = - (block[half * 64 + (quarter % 2) * 32 + lane] >> (if quarter < 2 { 0 } else { 4 })) & 15; + let low = (block[half * 64 + (quarter % 2) * 32 + lane] >> (if quarter < 2 { 0 } else { 4 })) & 15; let high = (block[128 + half * 32 + lane] >> (quarter * 2)) & 3; ((low | (high << 4)) as i16 - 32) as i8 } @@ -56,22 +55,14 @@ pub fn weights(rows: usize, columns: usize, pattern: usize) -> Vec { b[192 + g] = scales[(g + row + k) % 8] as u8; } for i in 0..256 { - pack_code( - &mut b, - i, - ((i * 7 + row * 11 + k * 17 + pattern * 5) % 64) as i8 - 32, - ); + pack_code(&mut b, i, ((i * 7 + row * 11 + k * 17 + pattern * 5) % 64) as i8 - 32); } match pattern { 7 | 8 => { b.fill(0); b[208..210].copy_from_slice( &(if pattern == 8 { - if row.is_multiple_of(2) { - 0x7c00u16 - } else { - 0xfc00u16 - } + if row.is_multiple_of(2) { 0x7c00u16 } else { 0xfc00u16 } } else { 0x3c00u16 }) diff --git a/crates/engine-core/rustfmt.toml b/crates/engine-core/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/engine-core/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/engine-core/src/conversation/binding.rs b/crates/engine-core/src/conversation/binding.rs index 39617c97..c245d141 100644 --- a/crates/engine-core/src/conversation/binding.rs +++ b/crates/engine-core/src/conversation/binding.rs @@ -8,8 +8,8 @@ use super::cache::{ConversationCheckpoint, ConversationKvReuse, SavedConversatio use super::manager::SessionEngine; use super::model::{ConvError, ConvResult, ModelGeometry, QsaDesc, SessionSpec, StateMemory}; use super::snapshot::{ - ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, - snapshot_save, snapshot_validate, + ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, snapshot_save, + snapshot_validate, }; use super::state::{checkpoint_restore, checkpoint_save}; @@ -57,15 +57,7 @@ impl SessionEngine for DeviceEngine<'_, D> { reuse: ConversationKvReuse, reused_bytes: &mut usize, ) -> ConvResult { - snapshot_save( - view, - self.session, - self.geometry, - self.draft, - self.device, - reuse, - Some(reused_bytes), - ) + snapshot_save(view, self.session, self.geometry, self.draft, self.device, reuse, Some(reused_bytes)) } fn snapshot_validate(&mut self, image: &SavedConversation) -> ConvResult<()> { @@ -85,21 +77,15 @@ impl SessionEngine for DeviceEngine<'_, D> { } fn synchronize(&mut self) -> ConvResult<()> { - self.device - .synchronize() - .map_err(|message| device_error("conversation snapshot synchronize", message)) + self.device.synchronize().map_err(|message| device_error("conversation snapshot synchronize", message)) } fn zero_session(&mut self) -> ConvResult<()> { - self.device - .zero_session() - .map_err(|message| device_error("zeroing the session", message)) + self.device.zero_session().map_err(|message| device_error("zeroing the session", message)) } fn restore_draft(&mut self, resume: usize) -> ConvResult<()> { - self.device - .restore_draft(resume) - .map_err(|message| device_error("restoring the draft ring", message)) + self.device.restore_draft(resume).map_err(|message| device_error("restoring the draft ring", message)) } fn set_steering(&mut self, enabled: bool) { diff --git a/crates/engine-core/src/conversation/buffer.rs b/crates/engine-core/src/conversation/buffer.rs index 192b8d30..a8e5548c 100644 --- a/crates/engine-core/src/conversation/buffer.rs +++ b/crates/engine-core/src/conversation/buffer.rs @@ -59,8 +59,7 @@ impl ConversationBuffer { /// Allocated bytes: directory capacity plus every segment's capacity. pub fn bytes(&self) -> usize { - self.segments.capacity() * SEGMENT_STRUCT_BYTES - + self.segments.iter().map(Vec::capacity).sum::() + self.segments.capacity() * SEGMENT_STRUCT_BYTES + self.segments.iter().map(Vec::capacity).sum::() } /// Peak allocation while growing to `n` bytes, including the old directory @@ -71,10 +70,7 @@ impl ConversationBuffer { if n <= self.size { return total; } - let spare = self - .segments - .last() - .map_or(0, |segment| segment.capacity() - segment.len()); + let spare = self.segments.last().map_or(0, |segment| segment.capacity() - segment.len()); let extra = n - self.size - (n - self.size).min(spare); let full = extra / SEGMENT_BYTES; let tail = extra % SEGMENT_BYTES; @@ -82,11 +78,7 @@ impl ConversationBuffer { return usize::MAX; } if tail != 0 { - let previous = if full != 0 { - SEGMENT_BYTES - } else { - self.segments.last().map_or(0, Vec::capacity) - }; + let previous = if full != 0 { SEGMENT_BYTES } else { self.segments.last().map_or(0, Vec::capacity) }; if !add(&mut total, segment_capacity(tail, previous, self.size != 0)) { return usize::MAX; } @@ -96,8 +88,7 @@ impl ConversationBuffer { return usize::MAX; } if count > self.segments.capacity() - && (count > usize::MAX / SEGMENT_STRUCT_BYTES - || !add(&mut total, count * SEGMENT_STRUCT_BYTES)) + && (count > usize::MAX / SEGMENT_STRUCT_BYTES || !add(&mut total, count * SEGMENT_STRUCT_BYTES)) { return usize::MAX; } @@ -109,14 +100,10 @@ impl ConversationBuffer { pub fn resize(&mut self, n: usize, value: u8) -> Result<(), TryReserveError> { if n > self.size { let growing = self.size != 0; - let spare = self - .segments - .last() - .map_or(0, |segment| segment.capacity() - segment.len()); + let spare = self.segments.last().map_or(0, |segment| segment.capacity() - segment.len()); let extend = (n - self.size).min(spare); let extra = n - self.size - extend; - let directory = - extra / SEGMENT_BYTES + usize::from(!extra.is_multiple_of(SEGMENT_BYTES)); + let directory = extra / SEGMENT_BYTES + usize::from(!extra.is_multiple_of(SEGMENT_BYTES)); self.segments.try_reserve_exact(directory)?; if extend != 0 { let back = self.segments.last_mut().expect("spare implies a segment"); @@ -161,12 +148,7 @@ impl ConversationBuffer { /// `f(chunk, absolute_offset)` over `[offset, offset + count)`; `false` /// aborts a transfer immediately. Out-of-range requests return `false` /// without calling `f`. - pub fn visit( - &self, - offset: usize, - count: usize, - mut f: impl FnMut(&[u8], usize) -> bool, - ) -> bool { + pub fn visit(&self, offset: usize, count: usize, mut f: impl FnMut(&[u8], usize) -> bool) -> bool { if offset > self.size || count > self.size - offset { return false; } @@ -190,12 +172,7 @@ impl ConversationBuffer { } /// Mutable twin of [`visit`](Self::visit). - pub fn visit_mut( - &mut self, - offset: usize, - count: usize, - mut f: impl FnMut(&mut [u8], usize) -> bool, - ) -> bool { + pub fn visit_mut(&mut self, offset: usize, count: usize, mut f: impl FnMut(&mut [u8], usize) -> bool) -> bool { if offset > self.size || count > self.size - offset { return false; } @@ -279,46 +256,23 @@ mod tests { let first = SEGMENT_BYTES + 17; let peak = bytes.allocation_peak(first); bytes.resize(first, 7).unwrap(); - assert!( - bytes.bytes() <= peak, - "segmented payload and directory fit admitted bytes" - ); + assert!(bytes.bytes() <= peak, "segmented payload and directory fit admitted bytes"); let original = bytes.first_address(); let grown_peak = bytes.allocation_peak(first + 99); bytes.resize(first + 99, 9).unwrap(); - assert_eq!( - bytes.first_address(), - original, - "appending preserves existing payload addresses" - ); - assert!( - bytes.bytes() <= grown_peak, - "growth including transient directory fits admission" - ); + assert_eq!(bytes.first_address(), original, "appending preserves existing payload addresses"); + assert!(bytes.bytes() <= grown_peak, "growth including transient directory fits admission"); let mut tail = vec![0u8; 116]; - assert!( - bytes.read(&mut tail, SEGMENT_BYTES), - "read spans segment boundaries" - ); + assert!(bytes.read(&mut tail, SEGMENT_BYTES), "read spans segment boundaries"); assert!(tail[..17].iter().all(|&v| v == 7) && tail[17..].iter().all(|&v| v == 9)); let copy = bytes.clone(); bytes.resize(SEGMENT_BYTES + 10, 0).unwrap(); bytes.resize(first, 7).unwrap(); bytes.resize(first + 99, 9).unwrap(); - assert_eq!( - bytes, copy, - "equality ignores differing segmentation after rewind and regrowth" - ); + assert_eq!(bytes, copy, "equality ignores differing segmentation after rewind and regrowth"); let mut two = [0u8; 2]; - assert!( - !bytes.read(&mut two, bytes.size() - 1), - "range check rejects a truncated payload" - ); - assert_eq!( - bytes.allocation_peak(usize::MAX), - usize::MAX, - "allocation estimate rejects overflow" - ); + assert!(!bytes.read(&mut two, bytes.size() - 1), "range check rejects a truncated payload"); + assert_eq!(bytes.allocation_peak(usize::MAX), usize::MAX, "allocation estimate rejects overflow"); } #[test] @@ -327,20 +281,14 @@ mod tests { for n in 1..=4096usize { let peak = bytes.allocation_peak(n * 17); bytes.resize(n * 17, 7).unwrap(); - assert!( - bytes.bytes() <= peak, - "small append stays within the predicted allocation peak" - ); + assert!(bytes.bytes() <= peak, "small append stays within the predicted allocation peak"); } let mut segments = 0; bytes.visit(0, bytes.size(), |_, _| { segments += 1; true }); - assert!( - segments <= 4, - "thousands of small turns do not create thousands of restore transfers" - ); + assert!(segments <= 4, "thousands of small turns do not create thousands of restore transfers"); } #[test] @@ -357,10 +305,7 @@ mod tests { big.pop_back().unwrap(); assert_eq!(big.size(), SEGMENT_BYTES - 1); big.resize(0, 0).unwrap(); - assert_eq!( - (big.segment_count(), big.size(), big.bytes()), - (0, 0, big.segments.capacity() * 24) - ); + assert_eq!((big.segment_count(), big.size(), big.bytes()), (0, 0, big.segments.capacity() * 24)); assert!(ConversationBuffer::new().pop_back().is_ok()); } diff --git a/crates/engine-core/src/conversation/cache.rs b/crates/engine-core/src/conversation/cache.rs index 5cb26994..b5658daa 100644 --- a/crates/engine-core/src/conversation/cache.rs +++ b/crates/engine-core/src/conversation/cache.rs @@ -121,7 +121,7 @@ mod tests; mod impl_conversationcheckpoint; #[allow(unused_imports)] -pub use impl_conversationcheckpoint::prefix_len; -#[allow(unused_imports)] pub use impl_conversationcheckpoint::conversation_prefix; +#[allow(unused_imports)] +pub use impl_conversationcheckpoint::prefix_len; mod impl_conversationcache; diff --git a/crates/engine-core/src/conversation/cache/impl_conversationcache.rs b/crates/engine-core/src/conversation/cache/impl_conversationcache.rs index 85f15d4a..791ebb01 100644 --- a/crates/engine-core/src/conversation/cache/impl_conversationcache.rs +++ b/crates/engine-core/src/conversation/cache/impl_conversationcache.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl ConversationCache { pub fn new(budget: usize, slots: usize) -> Self { Self { @@ -51,17 +50,8 @@ impl ConversationCache { /// make itself fit. pub fn retain(&mut self, kv: Vec, tokens: i64) { self.reuse = ConversationKvReuse::default(); - let candidate = ConversationKvReuse { - kv, - captured_tokens: tokens, - unchanged_tokens: tokens, - }; - if self.enabled() - && self - .budget - .checked_sub(self.bytes) - .is_some_and(|room| candidate.bytes() <= room) - { + let candidate = ConversationKvReuse { kv, captured_tokens: tokens, unchanged_tokens: tokens }; + if self.enabled() && self.budget.checked_sub(self.bytes).is_some_and(|room| candidate.bytes() <= room) { self.reuse = candidate; } } @@ -103,20 +93,12 @@ impl ConversationCache { } let n = prefix_len(entry.live_ids(), entry.live_images(), prompt, images); if n > best.tokens { - best = Match { - index, - tokens: n, - live: true, - }; + best = Match { index, tokens: n, live: true }; } for key in entry.checkpoint_keys() { let n = prefix_len(key.ids, key.imgs, prompt, images); if n > best.tokens { - best = Match { - index, - tokens: n, - live: false, - }; + best = Match { index, tokens: n, live: false }; } } } @@ -166,10 +148,7 @@ impl ConversationCache { cvec: bool, ) -> usize { let held = |c: &CheckpointKey<'_>| { - (c.ids == ids && c.imgs == images) - || checkpoints - .iter() - .any(|k| k.ids == c.ids && k.imgs == c.imgs) + (c.ids == ids && c.imgs == images) || checkpoints.iter().any(|k| k.ids == c.ids && k.imgs == c.imgs) }; let mut dropped = 0; let mut i = 0; @@ -181,8 +160,7 @@ impl ConversationCache { deepest = Some(key); } } - let superseded = - entry.cvec() == cvec && deepest.is_some_and(|d| !d.ids.is_empty() && held(&d)); + let superseded = entry.cvec() == cvec && deepest.is_some_and(|d| !d.ids.is_empty() && held(&d)); if superseded { if let Some(entry) = self.entries.remove(i) { self.bytes -= entry.bytes(); diff --git a/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs b/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs index b6fb9627..02717c26 100644 --- a/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs +++ b/crates/engine-core/src/conversation/cache/impl_conversationcheckpoint.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl ConversationCheckpoint { pub fn bytes(&self) -> usize { let mut n = self.ids.capacity() * size_of::() @@ -23,11 +22,7 @@ impl ConversationCheckpoint { impl ConversationKv { pub fn bytes(&self) -> usize { - self.k.bytes() - + self.v.bytes() - + self.k_scale.bytes() - + self.v_scale.bytes() - + self.pooled.bytes() + self.k.bytes() + self.v.bytes() + self.k_scale.bytes() + self.v_scale.bytes() + self.pooled.bytes() } pub fn buffers(&self) -> [&ConversationBuffer; 5] { @@ -35,13 +30,7 @@ impl ConversationKv { } pub fn buffers_mut(&mut self) -> [&mut ConversationBuffer; 5] { - [ - &mut self.k, - &mut self.v, - &mut self.k_scale, - &mut self.v_scale, - &mut self.pooled, - ] + [&mut self.k, &mut self.v, &mut self.k_scale, &mut self.v_scale, &mut self.pooled] } } @@ -92,13 +81,7 @@ impl ParkedConversation for SavedConversation { &self.live.imgs } fn checkpoint_keys(&self) -> Vec> { - self.checkpoints - .iter() - .map(|c| CheckpointKey { - ids: &c.ids, - imgs: &c.imgs, - }) - .collect() + self.checkpoints.iter().map(|c| CheckpointKey { ids: &c.ids, imgs: &c.imgs }).collect() } fn cvec(&self) -> bool { self.cvec @@ -112,12 +95,7 @@ impl ParkedConversation for SavedConversation { /// The last prompt token always starts the next verify window, so a point at /// least as long as the prompt never matches. Images wholly inside the point /// must match one for one; images past it are irrelevant. -pub fn prefix_len( - ids: &[i32], - imgs: &[ConversationImageKey], - prompt: &[T], - images: &[ConversationImageKey], -) -> i64 +pub fn prefix_len(ids: &[i32], imgs: &[ConversationImageKey], prompt: &[T], images: &[ConversationImageKey]) -> i64 where T: Copy, i64: From, @@ -125,10 +103,7 @@ where let n = ids.len(); if n == 0 || n >= prompt.len() - || !ids - .iter() - .zip(prompt) - .all(|(&id, &token)| >::from(id) == >::from(token)) + || !ids.iter().zip(prompt).all(|(&id, &token)| >::from(id) == >::from(token)) { return 0; } @@ -153,11 +128,7 @@ where } /// [`prefix_len`] over a [`ConversationCheckpoint`] (`conversation_prefix`). -pub fn conversation_prefix( - checkpoint: &ConversationCheckpoint, - prompt: &[T], - images: &[ConversationImageKey], -) -> i64 +pub fn conversation_prefix(checkpoint: &ConversationCheckpoint, prompt: &[T], images: &[ConversationImageKey]) -> i64 where T: Copy, i64: From, diff --git a/crates/engine-core/src/conversation/cache/tests.rs b/crates/engine-core/src/conversation/cache/tests.rs index c3cd0b0a..01d2282b 100644 --- a/crates/engine-core/src/conversation/cache/tests.rs +++ b/crates/engine-core/src/conversation/cache/tests.rs @@ -13,10 +13,7 @@ fn image_mode(ids: &[i32], cvec: bool) -> SavedConversation { s } fn cp(ids: &[i32]) -> ConversationCheckpoint { - ConversationCheckpoint { - ids: ids.to_vec(), - ..Default::default() - } + ConversationCheckpoint { ids: ids.to_vec(), ..Default::default() } } fn with(prefix: &[i32], more: &[i32]) -> Vec { let mut v = prefix.to_vec(); diff --git a/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs b/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs index 1e879af0..73f6dc1a 100644 --- a/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs +++ b/crates/engine-core/src/conversation/cache/tests/retained_buffers_count_against_bytes.rs @@ -3,17 +3,13 @@ #[allow(unused_imports)] use super::*; - #[test] fn retained_buffers_count_against_bytes_but_not_slots() { let layers = exact_kv_layers(); let retained = layers.capacity() * size_of::() + layers[0].bytes(); let parked = image(&[1, 2, 3]).bytes(); let mut cache = ConversationCache::new(retained + parked, 4); - assert!( - cache.put(image(&[1, 2, 3]), 0).is_ok(), - "park before retaining active storage" - ); + assert!(cache.put(image(&[1, 2, 3]), 0).is_ok(), "park before retaining active storage"); cache.retain(layers, 16); assert!( cache.bytes() == retained + parked && cache.size() == 1, @@ -22,20 +18,10 @@ fn retained_buffers_count_against_bytes_but_not_slots() { cache.limit_reuse(9); cache.limit_reuse(12); let reuse = cache.take_reuse(); - assert_eq!( - reuse.unchanged_tokens, 9, - "a later continuation cannot undo a rewind's dirty boundary" - ); - assert_eq!( - cache.bytes(), - parked, - "taking retained buffers releases their budget accounting" - ); + assert_eq!(reuse.unchanged_tokens, 9, "a later continuation cannot undo a rewind's dirty boundary"); + assert_eq!(cache.bytes(), parked, "taking retained buffers releases their budget accounting"); cache.retain(reuse.kv, 16); - assert!( - !cache.can_fit(parked, 0), - "retained storage is counted when checking a capture without eviction" - ); + assert!(!cache.can_fit(parked, 0), "retained storage is counted when checking a capture without eviction"); assert!( cache.retained_bytes() == retained && cache.size() == 1 && cache.evictions() == 0, "optional reuse admission does not evict or release anything" @@ -44,10 +30,7 @@ fn retained_buffers_count_against_bytes_but_not_slots() { !cache.can_fit(usize::MAX, 0) && !cache.can_fit(1, usize::MAX), "non-mutating reservation rejects overflow" ); - assert!( - cache.make_room(parked, 0), - "reservation can discard optional active buffers" - ); + assert!(cache.make_room(parked, 0), "reservation can discard optional active buffers"); assert!( cache.retained_bytes() == 0 && cache.size() == 1 && cache.evictions() == 0, "pressure drops retained storage before evicting parked conversations" @@ -62,29 +45,12 @@ fn a_b_a_recovery_and_slot_eviction() { let m = cache.best(&A, &[], true); assert!(m.tokens == 3 && m.live, "A/B/A: recover A"); let restored = cache.take(m.index).unwrap(); - assert_eq!( - restored.live.ids, - vec![1, 2, 3], - "taking selected A preserves identity" - ); - assert!( - cache.size() == 1 && cache.best(&B, &[], true).tokens == 3, - "B remains parked" - ); - assert_eq!( - cache.bytes(), - image(&[9, 8, 7]).bytes(), - "byte accounting after take" - ); + assert_eq!(restored.live.ids, vec![1, 2, 3], "taking selected A preserves identity"); + assert!(cache.size() == 1 && cache.best(&B, &[], true).tokens == 3, "B remains parked"); + assert_eq!(cache.bytes(), image(&[9, 8, 7]).bytes(), "byte accounting after take"); assert!(cache.put(restored, 0).is_ok(), "park returned A as newest"); - assert!( - cache.put(image(&[5, 6]), 0).is_ok(), - "evict oldest by slot limit" - ); - assert!( - cache.best(&B, &[], true).tokens == 0 && cache.best(&A, &[], true).tokens == 3, - "B evicted before A" - ); + assert!(cache.put(image(&[5, 6]), 0).is_ok(), "evict oldest by slot limit"); + assert!(cache.best(&B, &[], true).tokens == 0 && cache.best(&A, &[], true).tokens == 3, "B evicted before A"); assert_eq!(cache.evictions(), 1, "eviction counter"); } @@ -95,68 +61,26 @@ fn checkpoints_steering_and_boundary_rules() { let mut cache = ConversationCache::new(4096, 4); cache.put(s, 0).unwrap(); let m = cache.best(&[1i64, 2, 9, 4], &[], true); - assert!( - m.tokens == 2 && !m.live, - "edited suffix falls back to parked checkpoint" - ); - assert_eq!( - cache.best(&A, &[], true).tokens, - 3, - "live prefix beats shorter checkpoint" - ); - assert_eq!( - cache.best(&A, &[], false).tokens, - 0, - "steering mode is isolated" - ); - assert_eq!( - cache.best(&[1i64, 2], &[], true).tokens, - 0, - "equal-length checkpoint cannot consume last token" - ); - assert_eq!( - cache.best(&[1i64], &[], true).tokens, - 0, - "short prompt cannot match" - ); - assert_eq!( - cache.best::(&[], &[], true).tokens, - 0, - "empty prompt cannot match" - ); + assert!(m.tokens == 2 && !m.live, "edited suffix falls back to parked checkpoint"); + assert_eq!(cache.best(&A, &[], true).tokens, 3, "live prefix beats shorter checkpoint"); + assert_eq!(cache.best(&A, &[], false).tokens, 0, "steering mode is isolated"); + assert_eq!(cache.best(&[1i64, 2], &[], true).tokens, 0, "equal-length checkpoint cannot consume last token"); + assert_eq!(cache.best(&[1i64], &[], true).tokens, 0, "short prompt cannot match"); + assert_eq!(cache.best::(&[], &[], true).tokens, 0, "empty prompt cannot match"); cache.put(image(&[1, 2, 3]), 0).unwrap(); - assert_eq!( - cache.best(&A, &[], true).index, - 1, - "ties prefer most recently parked" - ); + assert_eq!(cache.best(&A, &[], true).index, 1, "ties prefer most recently parked"); } #[test] fn image_identity_is_part_of_the_prefix() { let mut s = image(&[1, 2, 3]); - s.live.imgs = vec![ConversationImageKey { - start: 1, - hash: 123, - }]; + s.live.imgs = vec![ConversationImageKey { start: 1, hash: 123 }]; let mut cache = ConversationCache::new(1024, 3); cache.put(s, 0).unwrap(); let key = |start, hash| ConversationImageKey { start, hash }; - assert_eq!( - cache.best(&A, &[key(1, 123)], true).tokens, - 3, - "same image can resume" - ); - assert_eq!( - cache.best(&A, &[key(1, 124)], true).tokens, - 0, - "different image pixels invalidate same pad tokens" - ); - assert_eq!( - cache.best(&A, &[], true).tokens, - 0, - "missing image invalidates prefix" - ); + assert_eq!(cache.best(&A, &[key(1, 123)], true).tokens, 3, "same image can resume"); + assert_eq!(cache.best(&A, &[key(1, 124)], true).tokens, 0, "different image pixels invalidate same pad tokens"); + assert_eq!(cache.best(&A, &[], true).tokens, 0, "missing image invalidates prefix"); assert_eq!( cache.best(&A, &[key(1, 123), key(2, 45)], true).tokens, 0, @@ -175,47 +99,20 @@ fn in_flight_image_is_counted_during_an_exchange() { let mut cache = ConversationCache::new(one * 2, 8); cache.put(image(&[1, 2, 3]), 0).unwrap(); cache.put(image(&[9, 8, 7]), 0).unwrap(); - assert_eq!( - cache.bytes(), - one * 2, - "budget holds two exact-sized images" - ); + assert_eq!(cache.bytes(), one * 2, "budget holds two exact-sized images"); let held = cache.take(cache.best(&A, &[], true).index).unwrap(); - assert!( - cache.make_room(one, held.bytes()), - "count in-flight image when reserving outgoing snapshot" - ); - assert_eq!( - cache.size(), - 0, - "in-flight reservation evicts otherwise fitting B" - ); - assert!( - cache.put(image(&[5, 6, 7]), held.bytes()).is_ok(), - "insert with in-flight accounting" - ); - assert!( - cache.bytes() + held.bytes() <= one * 2, - "exchange obeys byte budget" - ); - assert!( - !cache.make_room(one + 1, one), - "oversized exchange rejected" - ); - assert_eq!( - cache.size(), - 1, - "oversized snapshot does not evict useful entries" - ); + assert!(cache.make_room(one, held.bytes()), "count in-flight image when reserving outgoing snapshot"); + assert_eq!(cache.size(), 0, "in-flight reservation evicts otherwise fitting B"); + assert!(cache.put(image(&[5, 6, 7]), held.bytes()).is_ok(), "insert with in-flight accounting"); + assert!(cache.bytes() + held.bytes() <= one * 2, "exchange obeys byte budget"); + assert!(!cache.make_room(one + 1, one), "oversized exchange rejected"); + assert_eq!(cache.size(), 1, "oversized snapshot does not evict useful entries"); let mut huge = image(&[1]); huge.live.gdn = vec![0; one * 3]; let back = cache.put(huge, 0).unwrap_err(); assert_eq!(back.live.ids, vec![1], "a refused image is handed back"); assert_eq!(cache.size(), 1, "oversized put leaves cache unchanged"); - assert!( - !cache.make_room(0, one * 2 + 1), - "held larger than budget cannot underflow" - ); + assert!(!cache.make_room(0, one * 2 + 1), "held larger than budget cannot underflow"); } /// Upstream 41cf05a0 `940011da`: a full cache dropped the new snapshot instead of evicting for it. Full by slots or by bytes, the @@ -270,21 +167,11 @@ fn superseded_copies_of_one_conversation_do_not_push_out_another() { assert!(cache.size() <= 2, "one parked copy of SUB at a time"); history = with(&history, &[30, turn]); } - assert!( - cache.evictions() == 0 && cache.superseded() == 8, - "8 superseded copies dropped, nothing evicted" - ); - let prompt: Vec = with(&with(&root, &[10, 11, 12]), &[13, 14, 15]) - .into_iter() - .map(i64::from) - .collect(); + assert!(cache.evictions() == 0 && cache.superseded() == 8, "8 superseded copies dropped, nothing evicted"); + let prompt: Vec = with(&with(&root, &[10, 11, 12]), &[13, 14, 15]).into_iter().map(i64::from).collect(); let m = cache.best(&prompt, &[], true); assert!(m.tokens == 9 && m.live, "MAIN still restores in full"); let prompt: Vec = with(&history, &[40]); let s = cache.best(&prompt, &[], true); - assert_eq!( - s.tokens, - history.len() as i64 - 2, - "SUB resumes from its last turn boundary" - ); + assert_eq!(s.tokens, history.len() as i64 - 2, "SUB resumes from its last turn boundary"); } diff --git a/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs b/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs index 293aff58..7c1b8314 100644 --- a/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs +++ b/crates/engine-core/src/conversation/cache/tests/what_is_not_superseded.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn what_is_not_superseded() { let mut cache = ConversationCache::new(1 << 20, 8); @@ -19,14 +18,8 @@ fn what_is_not_superseded() { cache.put(branch, 0).unwrap(); let mut incoming = image(&[1, 2, 3, 4, 60, 80, 81]); incoming.checkpoints = vec![cp(&[1, 2, 3, 4]), cp(&[1, 2, 3, 4, 60])]; - assert!( - cache.put(incoming, 0).is_ok(), - "park a conversation sharing roots with all of them" - ); - assert!( - cache.size() == 5 && cache.superseded() == 0, - "none of them is superseded" - ); + assert!(cache.put(incoming, 0).is_ok(), "park a conversation sharing roots with all of them"); + assert!(cache.size() == 5 && cache.superseded() == 0, "none of them is superseded"); let mut same_state = image(&[1, 2, 3, 4, 60, 70]); // live equal to the branch's deepest point same_state.checkpoints = vec![cp(&[1, 2, 3, 4])]; assert!( @@ -46,27 +39,13 @@ fn what_is_not_superseded() { fn disabled_caches_store_nothing() { let disabled = ConversationCache::::new(0, 4); let no_slots = ConversationCache::::new(1024, 0); - assert!( - !disabled.enabled() && !no_slots.enabled(), - "both disable switches" - ); + assert!(!disabled.enabled() && !no_slots.enabled(), "both disable switches"); let (mut disabled, mut no_slots) = (disabled, no_slots); - assert!( - disabled.put(image(&[1, 2, 3]), 0).is_err() - && no_slots.put(image(&[1, 2, 3]), 0).is_err() - ); - assert_eq!( - disabled.best(&A, &[], true).tokens, - 0, - "disabled cache has no matches" - ); + assert!(disabled.put(image(&[1, 2, 3]), 0).is_err() && no_slots.put(image(&[1, 2, 3]), 0).is_err()); + assert_eq!(disabled.best(&A, &[], true).tokens, 0, "disabled cache has no matches"); assert!(!disabled.make_room(0, 0) && !disabled.can_fit(0, 0)); disabled.retain(exact_kv_layers(), 4); - assert_eq!( - disabled.retained_bytes(), - 0, - "a disabled cache retains nothing" - ); + assert_eq!(disabled.retained_bytes(), 0, "a disabled cache retains nothing"); } #[test] @@ -77,11 +56,7 @@ fn take_out_of_range_is_none_and_prefix_len_is_generic_over_token_types() { assert!(cache.take(1).is_none()); assert_eq!(cache.best(&[1u32, 2, 3, 4], &[], true).tokens, 3); assert_eq!(cache.best(&[1i32, 2, 3, 4], &[], true).tokens, 3); - assert_eq!( - cache.best(&[1i64, 2, 4, 4], &[], true).tokens, - 0, - "diverging token" - ); + assert_eq!(cache.best(&[1i64, 2, 4, 4], &[], true).tokens, 0, "diverging token"); assert_eq!(B.len(), 4); } diff --git a/crates/engine-core/src/conversation/golden_cache.rs b/crates/engine-core/src/conversation/golden_cache.rs index e25ae89e..8f0d7896 100644 --- a/crates/engine-core/src/conversation/golden_cache.rs +++ b/crates/engine-core/src/conversation/golden_cache.rs @@ -5,8 +5,7 @@ use super::buffer::ConversationBuffer; use super::cache::{ - CheckpointKey, ConversationCache, ConversationCheckpoint, ConversationImageKey, ConversationKv, - SavedConversation, + CheckpointKey, ConversationCache, ConversationCheckpoint, ConversationImageKey, ConversationKv, SavedConversation, }; use super::memory::{mem_available, memory_admit}; use super::retention::eviction_victim; @@ -16,12 +15,10 @@ fn golden() -> Value { serde_json::from_str(include_str!("golden/cache_golden.json")).expect("golden fixture parses") } fn u(v: &Value) -> u64 { - v.as_u64() - .unwrap_or_else(|| panic!("expected unsigned, got {v}")) + v.as_u64().unwrap_or_else(|| panic!("expected unsigned, got {v}")) } fn i(v: &Value) -> i64 { - v.as_i64() - .unwrap_or_else(|| panic!("expected signed, got {v}")) + v.as_i64().unwrap_or_else(|| panic!("expected signed, got {v}")) } fn exact(items: impl ExactSizeIterator) -> Vec { let mut v = Vec::with_capacity(items.len()); @@ -32,27 +29,15 @@ fn ids(v: &Value) -> Vec { exact(v.as_array().unwrap().iter().map(|x| i(x) as i32)) } fn imgs(v: &Value) -> Vec { - exact(v.as_array().unwrap().iter().map(|p| ConversationImageKey { - start: i(&p[0]), - hash: u(&p[1]), - })) + exact(v.as_array().unwrap().iter().map(|p| ConversationImageKey { start: i(&p[0]), hash: u(&p[1]) })) } #[test] fn struct_sizes_match_the_compiled_original() { let g = golden(); - assert_eq!( - u(&g["sizes"]["checkpoint"]) as usize, - std::mem::size_of::() - ); - assert_eq!( - u(&g["sizes"]["kv"]) as usize, - std::mem::size_of::() - ); - assert_eq!( - u(&g["sizes"]["image_key"]) as usize, - std::mem::size_of::() - ); + assert_eq!(u(&g["sizes"]["checkpoint"]) as usize, std::mem::size_of::()); + assert_eq!(u(&g["sizes"]["kv"]) as usize, std::mem::size_of::()); + assert_eq!(u(&g["sizes"]["image_key"]) as usize, std::mem::size_of::()); } #[test] @@ -73,36 +58,15 @@ fn buffer_traces_match_bytes_peaks_segments_and_content() { probe[0] ); } - assert_eq!( - buf.allocation_peak(n) as u64, - u(&state["peak"]), - "case {c} step {step}: peak" - ); + assert_eq!(buf.allocation_peak(n) as u64, u(&state["peak"]), "case {c} step {step}: peak"); buf.resize(n, value).unwrap(); - assert_eq!( - buf.size() as u64, - u(&state["size"]), - "case {c} step {step}: size" - ); - assert_eq!( - buf.bytes() as u64, - u(&state["bytes"]), - "case {c} step {step}: bytes" - ); - assert_eq!( - buf.segment_count() as u64, - u(&state["segments"]), - "case {c} step {step}: segments" - ); + assert_eq!(buf.size() as u64, u(&state["size"]), "case {c} step {step}: size"); + assert_eq!(buf.bytes() as u64, u(&state["bytes"]), "case {c} step {step}: bytes"); + assert_eq!(buf.segment_count() as u64, u(&state["segments"]), "case {c} step {step}: segments"); for at in state["bytes_at"].as_array().unwrap() { let mut byte = [0u8]; assert!(buf.read(&mut byte, u(&at[0]) as usize)); - assert_eq!( - byte[0] as u64, - u(&at[1]), - "case {c} step {step}: byte at {}", - at[0] - ); + assert_eq!(byte[0] as u64, u(&at[1]), "case {c} step {step}: byte at {}", at[0]); } } } @@ -113,11 +77,7 @@ fn eviction_victims_match() { let g = golden(); for case in g["eviction"].as_array().unwrap() { let stamps: Vec = case["stamps"].as_array().unwrap().iter().map(u).collect(); - assert_eq!( - eviction_victim(&stamps, i(&case["cap"])) as u64, - u(&case["victim"]), - "{case}" - ); + assert_eq!(eviction_victim(&stamps, i(&case["cap"])) as u64, u(&case["victim"]), "{case}"); } } @@ -163,27 +123,19 @@ fn build(spec: &Value) -> SavedConversation { fn cache_traces_match_every_observable() { let g = golden(); for (t, trace) in g["cache_traces"].as_array().unwrap().iter().enumerate() { - let mut cache = ConversationCache::::new( - u(&trace["budget"]) as usize, - u(&trace["slots"]) as usize, - ); + let mut cache = + ConversationCache::::new(u(&trace["budget"]) as usize, u(&trace["slots"]) as usize); for (step, entry) in trace["ops"].as_array().unwrap().iter().enumerate() { let (call, res, state) = (&entry["call"], &entry["res"], &entry["state"]); let ctx = format!("trace {t} step {step}: {call}"); match call["op"].as_str().unwrap() { "put" => { - let ok = cache - .put(build(&call["spec"]), u(&call["held"]) as usize) - .is_ok(); + let ok = cache.put(build(&call["spec"]), u(&call["held"]) as usize).is_ok(); assert_eq!(ok, res["ok"].as_bool().unwrap(), "{ctx}"); } "best" => { let prompt = ids(&call["prompt"]); - let m = cache.best( - &prompt, - &imgs(&call["imgs"]), - call["cvec"].as_bool().unwrap(), - ); + let m = cache.best(&prompt, &imgs(&call["imgs"]), call["cvec"].as_bool().unwrap()); assert_eq!(m.index as u64, u(&res["index"]), "{ctx}"); assert_eq!(m.tokens, i(&res["tokens"]), "{ctx}"); assert_eq!(m.live, res["live"].as_bool().unwrap(), "{ctx}"); @@ -200,18 +152,9 @@ fn cache_traces_match_every_observable() { } } "room" => { - let (incoming, held) = - (u(&call["incoming"]) as usize, u(&call["held"]) as usize); - assert_eq!( - cache.can_fit(incoming, held), - res["fit"].as_bool().unwrap(), - "{ctx}" - ); - assert_eq!( - cache.make_room(incoming, held), - res["ok"].as_bool().unwrap(), - "{ctx}" - ); + let (incoming, held) = (u(&call["incoming"]) as usize, u(&call["held"]) as usize); + assert_eq!(cache.can_fit(incoming, held), res["fit"].as_bool().unwrap(), "{ctx}"); + assert_eq!(cache.make_room(incoming, held), res["ok"].as_bool().unwrap(), "{ctx}"); } "retain" => { let sizes = call["sizes"].as_array().unwrap(); @@ -238,21 +181,9 @@ fn cache_traces_match_every_observable() { } assert_eq!(cache.bytes() as u64, u(&state["bytes"]), "{ctx}: bytes"); assert_eq!(cache.size() as u64, u(&state["size"]), "{ctx}: size"); - assert_eq!( - cache.evictions() as u64, - u(&state["evictions"]), - "{ctx}: evictions" - ); - assert_eq!( - cache.superseded() as u64, - u(&state["superseded"]), - "{ctx}: superseded" - ); - assert_eq!( - cache.retained_bytes() as u64, - u(&state["retained"]), - "{ctx}: retained" - ); + assert_eq!(cache.evictions() as u64, u(&state["evictions"]), "{ctx}: evictions"); + assert_eq!(cache.superseded() as u64, u(&state["superseded"]), "{ctx}: superseded"); + assert_eq!(cache.retained_bytes() as u64, u(&state["retained"]), "{ctx}: retained"); } } } @@ -260,8 +191,5 @@ fn cache_traces_match_every_observable() { // Keep the key type exercised by the public API from this module as well. #[allow(dead_code)] fn _keys(c: &ConversationCheckpoint) -> CheckpointKey<'_> { - CheckpointKey { - ids: &c.ids, - imgs: &c.imgs, - } + CheckpointKey { ids: &c.ids, imgs: &c.imgs } } diff --git a/crates/engine-core/src/conversation/golden_manager.rs b/crates/engine-core/src/conversation/golden_manager.rs index 2c3f3d17..afd57ff5 100644 --- a/crates/engine-core/src/conversation/golden_manager.rs +++ b/crates/engine-core/src/conversation/golden_manager.rs @@ -6,9 +6,7 @@ //! checkpoint re-read check. Every request's resume decision and the complete //! cache/chain state after it must match. -use super::cache::{ - ConversationCheckpoint, ConversationImageKey, ConversationKvReuse, SavedConversation, -}; +use super::cache::{ConversationCheckpoint, ConversationImageKey, ConversationKvReuse, SavedConversation}; use super::manager::{ConversationManager, ConversationOptions, SessionEngine}; use super::model::{ConvError, ConvResult}; use super::snapshot::{ConversationView, RestoreOutcome}; @@ -37,11 +35,7 @@ impl SessionEngine for Synthetic { fn snapshot_bytes(&mut self, view: &ConversationView<'_>) -> ConvResult { Ok(image_of(view).bytes()) } - fn snapshot_capture_bytes( - &mut self, - _: &ConversationKvReuse, - view: &ConversationView<'_>, - ) -> ConvResult { + fn snapshot_capture_bytes(&mut self, _: &ConversationKvReuse, view: &ConversationView<'_>) -> ConvResult { Ok(image_of(view).bytes()) } fn snapshot_save( @@ -53,11 +47,7 @@ impl SessionEngine for Synthetic { Ok(image_of(view)) } fn snapshot_validate(&mut self, _: &SavedConversation) -> ConvResult<()> { - if self.validate_fails { - Err(ConvError("injected".into())) - } else { - Ok(()) - } + if self.validate_fails { Err(ConvError("injected".into())) } else { Ok(()) } } fn snapshot_restore(&mut self, _: &SavedConversation) -> RestoreOutcome { RestoreOutcome::Restored @@ -87,10 +77,7 @@ impl SessionEngine for Synthetic { fn runs(v: &Value) -> Vec { let mut out = Vec::new(); for run in v.as_array().unwrap() { - let (start, len) = ( - run[0].as_i64().unwrap() as i32, - run[1].as_i64().unwrap() as i32, - ); + let (start, len) = (run[0].as_i64().unwrap() as i32, run[1].as_i64().unwrap() as i32); out.extend((0..len).map(|i| start + i)); } out @@ -100,10 +87,7 @@ fn imgs(v: &Value) -> Vec { v.as_array() .unwrap() .iter() - .map(|p| ConversationImageKey { - start: p[0].as_i64().unwrap(), - hash: p[1].as_u64().unwrap(), - }) + .map(|p| ConversationImageKey { start: p[0].as_i64().unwrap(), hash: p[1].as_u64().unwrap() }) .collect() } @@ -142,16 +126,8 @@ fn manager_decisions_match_the_generate_cpp_policy() { let start = mgr .begin_request(&mut engine, &ids, &images, req["cvec"].as_bool().unwrap()) .unwrap_or_else(|e| panic!("{ctx}: {e}")); - assert_eq!( - start.resume as i64, - want["resume"].as_i64().unwrap(), - "{ctx}: resume" - ); - assert_eq!( - start.from_live, - want["from_live"].as_bool().unwrap(), - "{ctx}: from_live" - ); + assert_eq!(start.resume as i64, want["resume"].as_i64().unwrap(), "{ctx}: resume"); + assert_eq!(start.from_live, want["from_live"].as_bool().unwrap(), "{ctx}: from_live"); let restored = start.restored.map(|(tokens, live)| (tokens as i64, live)); let expected_restored = match &want["restored"] { Value::Null => None, @@ -163,21 +139,10 @@ fn manager_decisions_match_the_generate_cpp_policy() { want["reread_to"].as_i64().unwrap(), "{ctx}: reread_to" ); - assert_eq!( - start.read_from as i64, - want["read_from"].as_i64().unwrap(), - "{ctx}: read_from" - ); + assert_eq!(start.read_from as i64, want["read_from"].as_i64().unwrap(), "{ctx}: read_from"); let prompt: Vec = ids.iter().map(|&i| i as u32).collect(); - let plan = PromptPlan::new( - &prompt, - start.resume, - start.reread_to, - None, - plan_options, - 256, - ) - .unwrap_or_else(|e| panic!("{ctx}: {e:?}")); + let plan = PromptPlan::new(&prompt, start.resume, start.reread_to, None, plan_options, 256) + .unwrap_or_else(|e| panic!("{ctx}: {e:?}")); let stop_after = req["stop_after"].as_i64().unwrap(); let mut cancelled = false; for (actions, action) in plan.enumerate() { @@ -188,70 +153,33 @@ fn manager_decisions_match_the_generate_cpp_policy() { cancelled = true; break; } - mgr.after_prompt_action(&mut engine, &ids, &images, &action) - .unwrap_or_else(|e| panic!("{ctx}: {e}")); + mgr.after_prompt_action(&mut engine, &ids, &images, &action).unwrap_or_else(|e| panic!("{ctx}: {e}")); } let generated = req["gen"].as_i64().unwrap() as usize; - let consumed_len = if cancelled { - 0 - } else { - ids.len() + generated - 1 - }; + let consumed_len = if cancelled { 0 } else { ids.len() + generated - 1 }; if !cancelled { let mut consumed = ids.clone(); - consumed - .extend((0..generated as i32 - 1).map(|i| 200000 + ids.len() as i32 * 10 + i)); + consumed.extend((0..generated as i32 - 1).map(|i| 200000 + ids.len() as i32 * 10 + i)); mgr.finish_request(consumed, &images, false); } else { mgr.finish_request(Vec::new(), &images, true); } - assert_eq!( - consumed_len as i64, - want["consumed"].as_i64().unwrap(), - "{ctx}: consumed" - ); - parks += mgr - .take_events() - .iter() - .filter(|e| e.starts_with("conversation cache: parked ")) - .count(); + assert_eq!(consumed_len as i64, want["consumed"].as_i64().unwrap(), "{ctx}: consumed"); + parks += mgr.take_events().iter().filter(|e| e.starts_with("conversation cache: parked ")).count(); // The state after the request. let state = &want["state"]; - assert_eq!( - mgr.live().len() as i64, - state["live"].as_i64().unwrap(), - "{ctx}: live length" - ); - assert_eq!( - mgr.live_ok(), - state["live_ok"].as_bool().unwrap(), - "{ctx}: live_ok" - ); - assert_eq!( - mgr.cvec_cached(), - state["cvec"].as_bool().unwrap(), - "{ctx}: cvec" - ); - let chain: Vec<(i64, u64)> = mgr - .checkpoints() - .iter() - .map(|c| (c.ids.len() as i64, c.used)) - .collect(); + assert_eq!(mgr.live().len() as i64, state["live"].as_i64().unwrap(), "{ctx}: live length"); + assert_eq!(mgr.live_ok(), state["live_ok"].as_bool().unwrap(), "{ctx}: live_ok"); + assert_eq!(mgr.cvec_cached(), state["cvec"].as_bool().unwrap(), "{ctx}: cvec"); + let chain: Vec<(i64, u64)> = mgr.checkpoints().iter().map(|c| (c.ids.len() as i64, c.used)).collect(); let expected: Vec<(i64, u64)> = state["checks"] .as_array() .unwrap() .iter() .map(|p| (p[0].as_i64().unwrap(), p[1].as_u64().unwrap())) .collect(); - assert_eq!( - chain, expected, - "{ctx}: checkpoint chain (length, LRU stamp)" - ); - assert_eq!( - mgr.check_clock(), - state["clock"].as_u64().unwrap(), - "{ctx}: LRU clock" - ); + assert_eq!(chain, expected, "{ctx}: checkpoint chain (length, LRU stamp)"); + assert_eq!(mgr.check_clock(), state["clock"].as_u64().unwrap(), "{ctx}: LRU clock"); assert_eq!( mgr.next_periodic_checkpoint(), state["pp_next"].as_i64().unwrap(), @@ -259,36 +187,12 @@ fn manager_decisions_match_the_generate_cpp_policy() { ); let cache = mgr.cache(); let c = &state["cache"]; - assert_eq!( - cache.size() as u64, - c["size"].as_u64().unwrap(), - "{ctx}: cache size" - ); - assert_eq!( - cache.bytes() as u64, - c["bytes"].as_u64().unwrap(), - "{ctx}: cache bytes" - ); - assert_eq!( - cache.evictions() as u64, - c["evictions"].as_u64().unwrap(), - "{ctx}: evictions" - ); - assert_eq!( - cache.superseded() as u64, - c["superseded"].as_u64().unwrap(), - "{ctx}: superseded" - ); - assert_eq!( - cache.retained_bytes() as u64, - c["retained"].as_u64().unwrap(), - "{ctx}: retained" - ); - assert_eq!( - parks as u64, - state["parks"].as_u64().unwrap(), - "{ctx}: parked images" - ); + assert_eq!(cache.size() as u64, c["size"].as_u64().unwrap(), "{ctx}: cache size"); + assert_eq!(cache.bytes() as u64, c["bytes"].as_u64().unwrap(), "{ctx}: cache bytes"); + assert_eq!(cache.evictions() as u64, c["evictions"].as_u64().unwrap(), "{ctx}: evictions"); + assert_eq!(cache.superseded() as u64, c["superseded"].as_u64().unwrap(), "{ctx}: superseded"); + assert_eq!(cache.retained_bytes() as u64, c["retained"].as_u64().unwrap(), "{ctx}: retained"); + assert_eq!(parks as u64, state["parks"].as_u64().unwrap(), "{ctx}: parked images"); let path = if restored.is_some() { 0 } else if start.resume == 0 { @@ -302,8 +206,5 @@ fn manager_decisions_match_the_generate_cpp_policy() { totals[4] += usize::from(cancelled); } } - assert!( - totals.iter().all(|&n| n >= 20), - "the traces cover every path: {totals:?}" - ); + assert!(totals.iter().all(|&n| n >= 20), "the traces cover every path: {totals:?}"); } diff --git a/crates/engine-core/src/conversation/kv.rs b/crates/engine-core/src/conversation/kv.rs index 7bb77fb5..5c9401fa 100644 --- a/crates/engine-core/src/conversation/kv.rs +++ b/crates/engine-core/src/conversation/kv.rs @@ -9,8 +9,8 @@ use super::cache::ConversationKv; use super::checked::{add, product}; use super::model::{ - ConvError, ConvResult, IDX_BLOCK, KV_HYBRID, KV_ROTATED, KvLayer, KvPool, ModelGeometry, - PAGE_SIZE, Q4_0_BLOCK_BYTES, QsaDesc, StateMemory, StateRegion, fail, + ConvError, ConvResult, IDX_BLOCK, KV_HYBRID, KV_ROTATED, KvLayer, KvPool, ModelGeometry, PAGE_SIZE, + Q4_0_BLOCK_BYTES, QsaDesc, StateMemory, StateRegion, fail, }; #[derive(Clone, Copy, Debug)] @@ -35,28 +35,28 @@ struct Verifier<'a> { mod impl_layout; #[allow(unused_imports)] +pub use impl_layout::kv_bytes; +#[allow(unused_imports)] +pub use impl_layout::kv_capture_bytes; +#[allow(unused_imports)] use impl_layout::kv_q4_bytes_per_head; #[allow(unused_imports)] -use impl_layout::valid_extent; -#[allow(unused_imports)] use impl_layout::layout; #[allow(unused_imports)] -use impl_layout::valid; -#[allow(unused_imports)] use impl_layout::region; #[allow(unused_imports)] use impl_layout::transfer_err; #[allow(unused_imports)] -pub use impl_layout::kv_capture_bytes; +use impl_layout::valid; #[allow(unused_imports)] -pub use impl_layout::kv_bytes; +use impl_layout::valid_extent; mod kv_save_fn; #[allow(unused_imports)] +pub use kv_save_fn::kv_restore; +#[allow(unused_imports)] pub use kv_save_fn::kv_save; #[allow(unused_imports)] pub use kv_save_fn::kv_validate; -#[allow(unused_imports)] -pub use kv_save_fn::kv_restore; mod kv_verify_fn; #[allow(unused_imports)] pub use kv_verify_fn::kv_verify; diff --git a/crates/engine-core/src/conversation/kv/impl_layout.rs b/crates/engine-core/src/conversation/kv/impl_layout.rs index ffdb9280..6b82d2ee 100644 --- a/crates/engine-core/src/conversation/kv/impl_layout.rs +++ b/crates/engine-core/src/conversation/kv/impl_layout.rs @@ -3,17 +3,10 @@ #[allow(unused_imports)] use super::*; - impl Layout { /// Byte sizes in `ConversationKv` buffer order. pub(super) fn sizes(&self) -> [usize; 5] { - [ - self.data, - self.value_data, - self.scales, - self.value_scales, - self.pooled, - ] + [self.data, self.value_data, self.scales, self.value_scales, self.pooled] } } @@ -44,36 +37,17 @@ pub(super) fn layout(st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> return fail("invalid K/V geometry"); } let cells = ((upto + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE; - let per = if st.kv_q4 { - kv_q4_bytes_per_head(g.head_dim) - } else { - g.head_dim as u64 * if int8_keys { 1 } else { 2 } - }; + let per = + if st.kv_q4 { kv_q4_bytes_per_head(g.head_dim) } else { g.head_dim as u64 * if int8_keys { 1 } else { 2 } }; // Include the moving spare row, not only completed blocks. The checkpoint // restore reconstructs that row when rewinding to an earlier prefix. - let pooled = if index && upto > 0 { - upto / IDX_BLOCK + 1 - } else { - 0 - }; + let pooled = if index && upto > 0 { upto / IDX_BLOCK + 1 } else { 0 }; // Format 3 identifies snapshot K8V4 only; rotated INT8 K/V is another // format too (+16): its bytes mean nothing to a state that does not rotate. - let rotated = if st.kv_rot && !st.kv_q4 && !st.kv_hybrid { - KV_ROTATED - } else { - 0 - }; - let base = if st.kv_hybrid { - KV_HYBRID - } else { - st.kv_format().expect("non-hybrid has a format") - }; + let rotated = if st.kv_rot && !st.kv_q4 && !st.kv_hybrid { KV_ROTATED } else { 0 }; + let base = if st.kv_hybrid { KV_HYBRID } else { st.kv_format().expect("non-hybrid has a format") }; let overflow = || ConvError("conversation snapshot: K/V byte count overflow".into()); - let scale_unit = if int8_keys && !st.kv_q4 { - (g.head_dim / 64) as u64 * 2 - } else { - 0 - }; + let scale_unit = if int8_keys && !st.kv_q4 { (g.head_dim / 64) as u64 * 2 } else { 0 }; let data = product(&[cells as u64, g.n_head_kv as u64, per]).ok_or_else(overflow)?; let scales = product(&[cells as u64, g.n_head_kv as u64, scale_unit]).ok_or_else(overflow)?; let pooled_bytes = product(&[pooled as u64, g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; @@ -93,12 +67,8 @@ pub(super) fn layout(st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> l.scales = 0; } if st.kv_hybrid { - l.value_data = product(&[ - cells as u64, - g.n_head_kv as u64, - kv_q4_bytes_per_head(g.head_dim), - ]) - .ok_or_else(|| ConvError("conversation snapshot: hybrid V byte count overflow".into()))?; + l.value_data = product(&[cells as u64, g.n_head_kv as u64, kv_q4_bytes_per_head(g.head_dim)]) + .ok_or_else(|| ConvError("conversation snapshot: hybrid V byte count overflow".into()))?; l.value_scales = 0; } Ok(l) @@ -141,11 +111,7 @@ pub(super) fn valid(st: &QsaDesc, l: &Layout, upto: i64) -> ConvResult<()> { } pub(super) fn region(layer: KvLayer, pool: KvPool, resident: bool) -> StateRegion { - StateRegion::Kv { - layer, - pool, - resident, - } + StateRegion::Kv { layer, pool, resident } } pub(super) fn transfer_err(message: String) -> ConvError { diff --git a/crates/engine-core/src/conversation/kv/kv_save_fn.rs b/crates/engine-core/src/conversation/kv/kv_save_fn.rs index 6c9f3653..e0e08a33 100644 --- a/crates/engine-core/src/conversation/kv/kv_save_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_save_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Capture layer `layer` into `image`. A nonzero `unchanged_tokens` is valid /// only for storage retained from an image actually restored into this /// session, bounded by every subsequent rewrite: equal token IDs alone do not @@ -40,11 +39,7 @@ pub fn kv_save( // Recopy the partial page and the indexer's moving spare row. Completed // pages/rows strictly before the first rewritten token remain identical. let keep = if i == 4 { - if index { - (unchanged_tokens / IDX_BLOCK) as usize * g.idx_key_dim as usize * 4 - } else { - 0 - } + if index { (unchanged_tokens / IDX_BLOCK) as usize * g.idx_key_dim as usize * 4 } else { 0 } } else if l.cells != 0 { (sizes[i] / l.cells as usize) * whole_cells as usize } else { @@ -53,18 +48,14 @@ pub fn kv_save( if keep > buffer.size() { return fail("missing reusable prefix"); } - buffer - .resize(sizes[i], 0) - .map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; + buffer.resize(sizes[i], 0).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; let mut error = None; let ok = buffer.visit_mut(keep, sizes[i] - keep, |chunk, at| { if chunk.is_empty() { return true; } if !present[i] { - error = Some(ConvError( - "conversation snapshot: missing state buffer".into(), - )); + error = Some(ConvError("conversation snapshot: missing state buffer".into())); return false; } match mem.read(region(layer, pool, false), at, chunk) { @@ -76,9 +67,7 @@ pub fn kv_save( } }); if !ok { - return Err( - error.unwrap_or_else(|| ConvError("conversation snapshot: capture failed".into())) - ); + return Err(error.unwrap_or_else(|| ConvError("conversation snapshot: capture failed".into()))); } reused += keep; } @@ -89,13 +78,7 @@ pub fn kv_save( } /// Structural validation of an image against a target: no device calls. -pub fn kv_validate( - image: &ConversationKv, - st: &QsaDesc, - g: &ModelGeometry, - upto: i64, - index: bool, -) -> ConvResult<()> { +pub fn kv_validate(image: &ConversationKv, st: &QsaDesc, g: &ModelGeometry, upto: i64, index: bool) -> ConvResult<()> { let l = layout(st, g, upto, index)?; valid(st, &l, upto)?; if image.format != l.format @@ -137,26 +120,18 @@ pub fn kv_restore( kv_validate(image, st, g, upto, index)?; for (buffer, pool) in image.buffers().into_iter().zip(KvPool::ALL) { let mut error = None; - let ok = buffer.visit(0, buffer.size(), |chunk, at| { - match mem.write(region(layer, pool, false), at, chunk) { - Ok(()) => true, - Err(message) => { - error = Some(transfer_err(message)); - false - } + let ok = buffer.visit(0, buffer.size(), |chunk, at| match mem.write(region(layer, pool, false), at, chunk) { + Ok(()) => true, + Err(message) => { + error = Some(transfer_err(message)); + false } }); if !ok { - return Err( - error.unwrap_or_else(|| ConvError("conversation snapshot: restore failed".into())) - ); + return Err(error.unwrap_or_else(|| ConvError("conversation snapshot: restore failed".into()))); } } - let residency = |message: String| { - ConvError(format!( - "conversation snapshot residency restore: {message}" - )) - }; + let residency = |message: String| ConvError(format!("conversation snapshot residency restore: {message}")); // VRAM slots still contain the outgoing conversation. Resolve must refill // them from the restored authoritative pools before any attention reads. if st.kv_mode == 1 { @@ -164,11 +139,8 @@ pub fn kv_restore( } if st.kv_mode == 2 && upto > 0 { let end = (upto + PAGE_SIZE - 1) / PAGE_SIZE; - let format = st - .kv_format() - .ok_or_else(|| ConvError("conversation snapshot: hybrid ring".into()))?; - mem.restore_ring(layer, format, (end - st.n_slots).max(0), end, st.n_slots) - .map_err(residency)?; + let format = st.kv_format().ok_or_else(|| ConvError("conversation snapshot: hybrid ring".into()))?; + mem.restore_ring(layer, format, (end - st.n_slots).max(0), end, st.n_slots).map_err(residency)?; } Ok(()) } @@ -176,13 +148,7 @@ pub fn kv_restore( impl Verifier<'_> { /// Compare device bytes at `base + ..` with `expected`, chunked through a /// 64 KiB workspace; optionally fold them into the fingerprint. - pub(super) fn compare( - &mut self, - loc: StateRegion, - base: usize, - expected: &[u8], - include_hash: bool, - ) -> bool { + pub(super) fn compare(&mut self, loc: StateRegion, base: usize, expected: &[u8], include_hash: bool) -> bool { let mut offset = 0; while offset < expected.len() { let n = self.buffer.len().min(expected.len() - offset); @@ -191,9 +157,7 @@ impl Verifier<'_> { return false; } if self.buffer[..n] != expected[offset..offset + n] { - self.error = Some(ConvError( - "conversation snapshot: restored K/V bytes differ".into(), - )); + self.error = Some(ConvError("conversation snapshot: restored K/V bytes differ".into())); return false; } if include_hash { @@ -208,8 +172,6 @@ impl Verifier<'_> { } pub(super) fn failure(&mut self) -> ConvError { - self.error - .take() - .unwrap_or_else(|| ConvError("conversation snapshot: restored K/V bytes differ".into())) + self.error.take().unwrap_or_else(|| ConvError("conversation snapshot: restored K/V bytes differ".into())) } } diff --git a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs index d68c5937..12ac19cc 100644 --- a/crates/engine-core/src/conversation/kv/kv_verify_fn.rs +++ b/crates/engine-core/src/conversation/kv/kv_verify_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Diagnostic read-back after a synchronised restore: compares the /// authoritative bytes (and the resident draft-ring pages), fingerprinting the /// authoritative payload only (FNV-1a 64). Never changes model state. @@ -17,16 +16,9 @@ pub fn kv_verify( mem: &mut dyn StateMemory, ) -> ConvResult { kv_validate(image, st, g, upto, index)?; - let mut v = Verifier { - mem, - buffer: vec![0; 65536], - hash: 1469598103934665603, - error: None, - }; + let mut v = Verifier { mem, buffer: vec![0; 65536], hash: 1469598103934665603, error: None }; for (saved, pool) in image.buffers().into_iter().zip(KvPool::ALL) { - if !saved.visit(0, saved.size(), |chunk, at| { - v.compare(region(layer, pool, false), at, chunk, true) - }) { + if !saved.visit(0, saved.size(), |chunk, at| v.compare(region(layer, pool, false), at, chunk, true)) { return Err(v.failure()); } } diff --git a/crates/engine-core/src/conversation/manager.rs b/crates/engine-core/src/conversation/manager.rs index afe6fb6f..73d90b77 100644 --- a/crates/engine-core/src/conversation/manager.rs +++ b/crates/engine-core/src/conversation/manager.rs @@ -21,8 +21,8 @@ //! against a synthetic engine in the differential test vs the C++ original. use super::cache::{ - CheckpointKey, ConversationCache, ConversationCheckpoint, ConversationImageKey, - ConversationKvReuse, SavedConversation, + CheckpointKey, ConversationCache, ConversationCheckpoint, ConversationImageKey, ConversationKvReuse, + SavedConversation, }; use super::memory::memory_admit; use super::model::{ConvError, ConvResult}; @@ -33,11 +33,8 @@ use crate::prompt::{PromptAction, PromptPath}; /// Everything the policy needs from the device side. pub trait SessionEngine { fn snapshot_bytes(&mut self, view: &ConversationView<'_>) -> ConvResult; - fn snapshot_capture_bytes( - &mut self, - reuse: &ConversationKvReuse, - view: &ConversationView<'_>, - ) -> ConvResult; + fn snapshot_capture_bytes(&mut self, reuse: &ConversationKvReuse, view: &ConversationView<'_>) + -> ConvResult; /// Capture the live session. `reuse` is consumed, including on failure. fn snapshot_save( &mut self, @@ -119,7 +116,7 @@ mod impl_default_for_conversationoptions; #[allow(unused_imports)] pub use impl_default_for_conversationoptions::images_below; #[allow(unused_imports)] -pub use impl_default_for_conversationoptions::starts_with; -#[allow(unused_imports)] use impl_default_for_conversationoptions::is_allocation; +#[allow(unused_imports)] +pub use impl_default_for_conversationoptions::starts_with; mod impl_conversationmanager; diff --git a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs index 158570ae..e45b0bd8 100644 --- a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs +++ b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2.rs @@ -3,15 +3,9 @@ #[allow(unused_imports)] use super::*; - - impl ConversationManager { pub fn new(options: ConversationOptions) -> Self { - let budget = if options.prompt_cache > 0 { - options.conversation_cache_bytes - } else { - 0 - }; + let budget = if options.prompt_cache > 0 { options.conversation_cache_bytes } else { 0 }; let cache = ConversationCache::new(budget, options.conversation_cache_slots); Self { options, @@ -87,8 +81,7 @@ impl ConversationManager { let fresh_estimate = match engine.snapshot_bytes(&view) { Ok(n) => n, Err(e) => { - self.events - .push(format!("conversation cache: skip parking ({e})")); + self.events.push(format!("conversation cache: skip parking ({e})")); return Ok(()); } }; @@ -108,17 +101,9 @@ impl ConversationManager { // size and a capped figure would under-evict and overfill the budget. // #342: before make_room evicts oldest-first, the copies of this // conversation a turn back go. - let keys: Vec> = self - .checks - .iter() - .map(|c| CheckpointKey { - ids: &c.ids, - imgs: &c.imgs, - }) - .collect(); - let dropped = - self.cache - .drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached); + let keys: Vec> = + self.checks.iter().map(|c| CheckpointKey { ids: &c.ids, imgs: &c.imgs }).collect(); + let dropped = self.cache.drop_superseded(&self.live, &self.live_imgs, &keys, self.cvec_cached); if dropped != 0 { self.events.push(format!( "conversation cache: dropped {dropped} superseded cop{} of this conversation; parked={}", @@ -149,8 +134,7 @@ impl ConversationManager { Err(e) if is_allocation(&e) => { // The active state has not been touched: continue with normal // prompt processing rather than killing a serving process. - self.events - .push("conversation cache: allocation failed; skip parking".into()); + self.events.push("conversation cache: allocation failed; skip parking".into()); return Ok(()); } Err(e) => return Err(e), diff --git a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs index 8c59202a..41eb4166 100644 --- a/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs +++ b/crates/engine-core/src/conversation/manager/impl_conversationmanager/impl_conversationmanager_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl ConversationManager { - /// Decide where `ids` starts reading and put the device in that state: /// continue the live session, restore a checkpoint, restore a parked /// conversation (parking the outgoing one first), or start empty. Any @@ -34,19 +31,13 @@ impl ConversationManager { } } let parked = self.cache.best(ids, req_imgs, want_cvec); - let mut incoming = if parked.tokens as usize > resume { - self.cache.take(parked.index) - } else { - None - }; + let mut incoming = if parked.tokens as usize > resume { self.cache.take(parked.index) } else { None }; // Reject the entire image before parking/overwriting the outgoing // state. Invalid entries can safely fall back to the existing prefix. if let Some(image) = &incoming && let Err(e) = engine.snapshot_validate(image) { - self.events.push(format!( - "conversation cache: discard invalid snapshot ({e})" - )); + self.events.push(format!("conversation cache: discard invalid snapshot ({e})")); incoming = None; } // Preserve the outgoing branch before any checkpoint rewind, reset or @@ -73,8 +64,7 @@ impl ConversationManager { from_live = parked.live; restored = Some((resume, from_live)); if self.options.incremental_capture { - self.cache - .retain(std::mem::take(&mut image.kv), self.live.len() as i64); + self.cache.retain(std::mem::take(&mut image.kv), self.live.len() as i64); } self.events.push(format!( "conversation cache: restored {resume} tokens ({}); parked={} bytes={}", @@ -92,8 +82,7 @@ impl ConversationManager { // This request rewrites every cell from `resume` on, so a checkpoint // past it (or not on this prompt's path) no longer has its cells; the // ones kept are prefixes of both the old tokens and the new. - self.checks - .retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs)); + self.checks.retain(|c| c.ids.len() <= resume && starts_with(&c.ids, &c.imgs, ids, req_imgs)); self.live_ok = false; // until this request has finished, the session is in between let mut reread_to = None; if resume == 0 { @@ -101,9 +90,7 @@ impl ConversationManager { self.checks.clear(); } else if !from_live { let Some(index) = self.checks.iter().rposition(|k| k.ids.len() == resume) else { - return Err(ConvError( - "restoring a conversation checkpoint failed".into(), - )); + return Err(ConvError("restoring a conversation checkpoint failed".into())); }; self.check_clock += 1; self.checks[index].used = self.check_clock; @@ -113,15 +100,11 @@ impl ConversationManager { // fixed the answer must match the restored one token for token. engine.zero_session()?; reread_to = Some(resume); - self.events.push(format!( - "STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring" - )); + self.events.push(format!("STRATA_CKPT_REREAD: reading {resume} tokens again instead of restoring")); } else { let c = &self.checks[index]; if !c.stage_parts.is_empty() || engine.checkpoint_restore(c).is_err() { - return Err(ConvError( - "restoring a conversation checkpoint failed".into(), - )); + return Err(ConvError("restoring a conversation checkpoint failed".into())); } } } @@ -133,18 +116,9 @@ impl ConversationManager { } let read_from = if reread_to.is_some() { 0 } else { resume }; self.cache.limit_reuse(read_from as i64); - self.pp_next_check = if reread_to.is_some() { - i64::MAX - } else { - resume as i64 + self.options.prompt_cache_every - }; - Ok(RequestStart { - resume, - from_live, - restored, - reread_to, - read_from, - }) + self.pp_next_check = + if reread_to.is_some() { i64::MAX } else { resume as i64 + self.options.prompt_cache_every }; + Ok(RequestStart { resume, from_live, restored, reread_to, read_from }) } /// A checkpoint of the state after `ids[..position]`. `Ok` also when @@ -161,9 +135,7 @@ impl ConversationManager { return Ok(()); } if position > ids.len() { - return Err(ConvError( - "conversation checkpoint beyond the prompt".into(), - )); + return Err(ConvError("conversation checkpoint beyond the prompt".into())); } if let Some(existing) = self.checks.iter_mut().find(|c| c.ids.len() == position) { self.check_clock += 1; @@ -232,12 +204,7 @@ impl ConversationManager { /// prompt read so far, then every committed token. A request stopped /// while reading the prompt leaves the session between two chunks, with /// nothing to continue from (the checkpoints taken meanwhile are good). - pub fn finish_request( - &mut self, - consumed: Vec, - req_imgs: &[ConversationImageKey], - cancelled: bool, - ) { + pub fn finish_request(&mut self, consumed: Vec, req_imgs: &[ConversationImageKey], cancelled: bool) { if !cancelled { self.live_imgs = images_below(req_imgs, consumed.len()); self.live = consumed; diff --git a/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs b/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs index e323a7de..78c6f440 100644 --- a/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs +++ b/crates/engine-core/src/conversation/manager/impl_default_for_conversationoptions.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Default for ConversationOptions { fn default() -> Self { Self { @@ -20,10 +19,7 @@ impl Default for ConversationOptions { /// Prompt positions of the pictures below `limit` (`imgs_below`). pub fn images_below(all: &[ConversationImageKey], limit: usize) -> Vec { - all.iter() - .filter(|key| key.start < limit as i64) - .copied() - .collect() + all.iter().filter(|key| key.start < limit as i64).copied().collect() } /// The saved point `pre` (tokens and pictures) is exactly the start of diff --git a/crates/engine-core/src/conversation/manager_tests.rs b/crates/engine-core/src/conversation/manager_tests.rs index 09a3c8af..25182e05 100644 --- a/crates/engine-core/src/conversation/manager_tests.rs +++ b/crates/engine-core/src/conversation/manager_tests.rs @@ -12,9 +12,7 @@ use super::binding::{DeviceEngine, SessionDevice}; use super::cache::ConversationImageKey; use super::manager::{ConversationManager, ConversationOptions, RequestStart}; -use super::model::{ - IdxKind, KvLayer, KvPool, ModelGeometry, SessionShape, SessionSpec, StateMemory, StateRegion, -}; +use super::model::{IdxKind, KvLayer, KvPool, ModelGeometry, SessionShape, SessionSpec, StateMemory, StateRegion}; use super::snapshot_tests::{Fixture, kv_region}; use super::state::state_sizes; use super::testing::HostMemory; @@ -53,10 +51,10 @@ struct Run { /// Deterministic xorshift for the property test. struct Rng(u64); -#[path = "manager_tests/continuing_chat_reuses.rs"] -mod continuing_chat_reuses; #[path = "manager_tests/byte_budget_and_slot.rs"] mod byte_budget_and_slot; +#[path = "manager_tests/continuing_chat_reuses.rs"] +mod continuing_chat_reuses; #[path = "manager_tests/random_conversation_traffic_always_resum.rs"] mod random_conversation_traffic_always_resum; @@ -64,19 +62,19 @@ mod hash_fn; #[allow(unused_imports)] use hash_fn::hash; #[allow(unused_imports)] +use hash_fn::idx; +#[allow(unused_imports)] use hash_fn::pat; #[allow(unused_imports)] use hash_fn::pattern; -#[allow(unused_imports)] -use hash_fn::idx; mod impl_sessiondevice_for_simdevice; #[allow(unused_imports)] -use impl_sessiondevice_for_simdevice::options; -#[allow(unused_imports)] -use impl_sessiondevice_for_simdevice::world; -#[allow(unused_imports)] -use impl_sessiondevice_for_simdevice::prompt_options; -#[allow(unused_imports)] use impl_sessiondevice_for_simdevice::chat; #[allow(unused_imports)] use impl_sessiondevice_for_simdevice::gen_tokens; +#[allow(unused_imports)] +use impl_sessiondevice_for_simdevice::options; +#[allow(unused_imports)] +use impl_sessiondevice_for_simdevice::prompt_options; +#[allow(unused_imports)] +use impl_sessiondevice_for_simdevice::world; diff --git a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs index 5795e416..84a5edbe 100644 --- a/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs +++ b/crates/engine-core/src/conversation/manager_tests/byte_budget_and_slot.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn the_byte_budget_and_slot_limit_evict_oldest_first() { let mut o = options(); @@ -13,15 +12,7 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { for salt in 1..=4 { runs.push(( salt, - w.request( - &chat(salt, 16 + salt as usize, &[9]), - &[], - true, - &gen_tokens(salt, 4), - None, - 8, - ) - .unwrap(), + w.request(&chat(salt, 16 + salt as usize, &[9]), &[], true, &gen_tokens(salt, 4), None, 8).unwrap(), )); } // 4 chats: the live one is chat 4; parked are the two most recent others. @@ -31,9 +22,7 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { // chat 1 (evicted) comes back: nothing to restore let mut again = runs[0].1.consumed.clone(); again.extend([TURN, 5]); - let r = w - .request(&again, &[], true, &gen_tokens(9, 3), None, 8) - .unwrap(); + let r = w.request(&again, &[], true, &gen_tokens(9, 3), None, 8).unwrap(); assert_eq!(r.start.restored, None); assert_eq!(r.start.resume, 0); } @@ -41,28 +30,18 @@ fn the_byte_budget_and_slot_limit_evict_oldest_first() { #[test] fn an_incompatible_parked_image_is_discarded_and_the_request_falls_back() { let mut w = world(options(), false); - let ra = w - .request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); + let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 1); // The runtime geometry changes under the parked image. w.g.n_expert = 256; let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2]); - let r = w - .request(&a2, &[], true, &gen_tokens(3, 4), None, 8) - .unwrap(); + let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 8).unwrap(); assert_eq!(r.start.restored, None, "invalid image never restores"); assert_eq!(r.start.resume, 0); let events = w.mgr.take_events(); - assert!( - events - .iter() - .any(|e| e.contains("discard invalid snapshot")), - "{events:?}" - ); + assert!(events.iter().any(|e| e.contains("discard invalid snapshot")), "{events:?}"); } #[test] @@ -70,29 +49,17 @@ fn a_failed_restore_transfer_is_fatal_to_the_request() { // Measure the device copies `begin_request` performs for A/B/A, then fail the last one. let scenario = |fail_last: Option| { let mut w = world(options(), false); - let ra = w - .request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); + let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2]); w.dev.mem.reset_counters(); if let Some(n) = fail_last { w.dev.mem.fail_copy = n; } - let mut engine = DeviceEngine { - device: &mut w.dev, - geometry: &w.g, - session: &w.ss, - draft: &w.draft, - }; + let mut engine = DeviceEngine { device: &mut w.dev, geometry: &w.g, session: &w.ss, draft: &w.draft }; let result = w.mgr.begin_request(&mut engine, &a2, &[], true); - ( - result.map(|s| s.resume), - w.dev.mem.copy_calls, - ra.consumed.len(), - ) + (result.map(|s| s.resume), w.dev.mem.copy_calls, ra.consumed.len()) }; let (ok, copies, expected) = scenario(None); assert_eq!(ok.unwrap(), expected, "sanity: A is restored whole"); @@ -108,25 +75,16 @@ fn a_failed_restore_transfer_is_fatal_to_the_request() { fn switching_steering_invalidates_checkpoints_and_isolates_parked_images() { let mut w = world(options(), false); let p = chat(1, 20, &[10, 10]); - let r1 = w - .request(&p, &[], true, &gen_tokens(1, 6), None, 64) - .unwrap(); + let r1 = w.request(&p, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); assert!(!w.mgr.checkpoints().is_empty()); let mut same = r1.consumed.clone(); same.extend([TURN, 3, 4]); - let r2 = w - .request(&same, &[], false, &gen_tokens(2, 4), None, 64) - .unwrap(); - assert_eq!( - r2.start.resume, 0, - "a different steering mode never reuses the session" - ); + let r2 = w.request(&same, &[], false, &gen_tokens(2, 4), None, 64).unwrap(); + assert_eq!(r2.start.resume, 0, "a different steering mode never reuses the session"); assert!(!w.mgr.cvec_cached()); assert_eq!(w.dev.steering.last(), Some(&false)); // The old (steered) conversation was parked with its own steering mode. - let r3 = w - .request(&same, &[], true, &gen_tokens(3, 4), None, 64) - .unwrap(); + let r3 = w.request(&same, &[], true, &gen_tokens(3, 4), None, 64).unwrap(); assert_eq!(r3.start.restored.map(|(t, _)| t), Some(r1.consumed.len())); assert_eq!(w.dev.steering.last(), Some(&true)); } @@ -135,26 +93,13 @@ fn switching_steering_invalidates_checkpoints_and_isolates_parked_images() { fn a_cancelled_prompt_keeps_its_checkpoints_but_not_a_live_session() { let mut w = world(options(), false); let p = chat(1, 100, &[30]); - let cancelled = w - .request(&p, &[], true, &gen_tokens(1, 4), Some(1), 8) - .unwrap(); + let cancelled = w.request(&p, &[], true, &gen_tokens(1, 4), Some(1), 8).unwrap(); assert!(cancelled.consumed.is_empty()); - assert!( - !w.mgr.live_ok(), - "the session is between two chunks: nothing to continue from" - ); - assert!( - w.mgr.checkpoints().iter().any(|c| c.ids.len() > 8), - "checkpoints taken while reading survive" - ); + assert!(!w.mgr.live_ok(), "the session is between two chunks: nothing to continue from"); + assert!(w.mgr.checkpoints().iter().any(|c| c.ids.len() > 8), "checkpoints taken while reading survive"); let kept = w.mgr.checkpoints().last().unwrap().ids.len(); - let r = w - .request(&p, &[], true, &gen_tokens(2, 4), None, 8) - .unwrap(); - assert_eq!( - r.start.resume, kept, - "a retry mounts the deepest surviving checkpoint" - ); + let r = w.request(&p, &[], true, &gen_tokens(2, 4), None, 8).unwrap(); + assert_eq!(r.start.resume, kept, "a retry mounts the deepest surviving checkpoint"); assert!(!r.start.from_live); } @@ -167,8 +112,7 @@ fn periodic_checkpoints_follow_the_chunk_stride() { // No turn tokens inside: only periodic checkpoints can appear. let mut p = vec![TURN]; p.extend(1..=120); - w.request(&p, &[], true, &gen_tokens(1, 3), None, 1 << 20) - .unwrap(); + w.request(&p, &[], true, &gen_tokens(1, 3), None, 1 << 20).unwrap(); let lens: Vec = w.mgr.checkpoints().iter().map(|c| c.ids.len()).collect(); assert!(!lens.is_empty()); assert!(lens.iter().all(|&l| l < p.len())); @@ -180,14 +124,11 @@ fn the_reread_check_zeroes_and_reads_a_checkpoint_again() { o.reread_checkpoints = true; let mut w = world(o, false); let p1 = chat(5, 16, &[10, 12]); - w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64) - .unwrap(); + w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); let mut p2 = p1[..turn_at].to_vec(); p2.extend([TURN, 9, 9, 9, 9]); - let r = w - .request(&p2, &[], true, &gen_tokens(2, 3), None, 64) - .unwrap(); + let r = w.request(&p2, &[], true, &gen_tokens(2, 3), None, 64).unwrap(); assert_eq!(r.start.reread_to, Some(turn_at)); assert_eq!(r.start.read_from, 0); } @@ -197,41 +138,26 @@ fn pictures_are_part_of_the_resume_identity() { let mut w = world(options(), false); let mut p = chat(1, 20, &[10]); let img = ConversationImageKey { start: 3, hash: 99 }; - let r1 = w - .request(&p, &[img], true, &gen_tokens(1, 4), None, 64) - .unwrap(); + let r1 = w.request(&p, &[img], true, &gen_tokens(1, 4), None, 64).unwrap(); p = r1.consumed.clone(); p.extend([TURN, 4]); - let same = w - .request(&p, &[img], true, &gen_tokens(2, 3), None, 64) - .unwrap(); + let same = w.request(&p, &[img], true, &gen_tokens(2, 3), None, 64).unwrap(); assert!(same.start.from_live && same.start.resume > 0); - let other = ConversationImageKey { - start: 3, - hash: 100, - }; + let other = ConversationImageKey { start: 3, hash: 100 }; let mut p2 = same.consumed.clone(); p2.extend([TURN, 5]); - let changed = w - .request(&p2, &[other], true, &gen_tokens(3, 3), None, 64) - .unwrap(); - assert_eq!( - changed.start.resume, 0, - "same pad tokens, different pixels: nothing is reused" - ); + let changed = w.request(&p2, &[other], true, &gen_tokens(3, 3), None, 64).unwrap(); + assert_eq!(changed.start.resume, 0, "same pad tokens, different pixels: nothing is reused"); } #[test] fn the_ple_history_window_is_restored_with_the_checkpoint() { let mut w = world(options(), true); let p1 = chat(6, 16, &[10, 12]); - w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64) - .unwrap(); + w.request(&p1, &[], true, &gen_tokens(1, 4), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); let mut p2 = p1[..turn_at].to_vec(); p2.extend([TURN, 1, 2, 3, 4]); - let r = w - .request(&p2, &[], true, &gen_tokens(2, 3), None, 64) - .unwrap(); + let r = w.request(&p2, &[], true, &gen_tokens(2, 3), None, 64).unwrap(); assert_eq!(r.start.resume, turn_at); } diff --git a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs index dca08b3f..37d7b641 100644 --- a/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs +++ b/crates/engine-core/src/conversation/manager_tests/continuing_chat_reuses.rs @@ -3,78 +3,49 @@ #[allow(unused_imports)] use super::*; - #[test] fn a_continuing_chat_reuses_the_live_session_without_a_copy() { let mut w = world(options(), false); let p1 = chat(1, 20, &[10]); - let r1 = w - .request(&p1, &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); + let r1 = w.request(&p1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); assert_eq!((r1.start.resume, r1.start.from_live), (0, false)); // Next request: the history as the client re-renders it, plus a new turn. let mut p2 = r1.consumed.clone(); p2.push(TURN); p2.extend([7, 8, 9]); - let r2 = w - .request(&p2, &[], true, &gen_tokens(2, 5), None, 8) - .unwrap(); + let r2 = w.request(&p2, &[], true, &gen_tokens(2, 5), None, 8).unwrap(); assert!(r2.start.from_live, "continues the live session"); assert_eq!(r2.start.resume, r1.consumed.len()); assert!(r2.start.restored.is_none()); - assert_eq!( - w.dev.draft_restores, - vec![r1.consumed.len()], - "the drafter ring is re-synchronised on a resume" - ); - assert_eq!( - w.dev.zeroed, 1, - "only the first request started from an empty sequence" - ); + assert_eq!(w.dev.draft_restores, vec![r1.consumed.len()], "the drafter ring is re-synchronised on a resume"); + assert_eq!(w.dev.zeroed, 1, "only the first request started from an empty sequence"); } #[test] fn an_identical_prompt_still_reads_its_last_token() { let mut w = world(options(), false); let p = chat(2, 12, &[8]); - let first = w - .request(&p, &[], true, &gen_tokens(1, 1), None, 8) - .unwrap(); + let first = w.request(&p, &[], true, &gen_tokens(1, 1), None, 8).unwrap(); // gen of one token commits nothing: the session holds exactly the prompt. assert_eq!(first.consumed, p); - let second = w - .request(&p, &[], true, &gen_tokens(2, 3), None, 8) - .unwrap(); - assert!( - second.start.resume < p.len(), - "the last token always starts the first verify window" - ); + let second = w.request(&p, &[], true, &gen_tokens(2, 3), None, 8).unwrap(); + assert!(second.start.resume < p.len(), "the last token always starts the first verify window"); } #[test] fn a_rewritten_tail_resumes_from_the_turn_boundary_checkpoint() { let mut w = world(options(), false); let p1 = chat(3, 16, &[10, 12]); - let r1 = w - .request(&p1, &[], true, &gen_tokens(1, 6), None, 64) - .unwrap(); + let r1 = w.request(&p1, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); let turn_at = p1.iter().rposition(|&t| t == TURN).unwrap(); - assert!( - w.mgr.checkpoints().iter().any(|c| c.ids.len() == turn_at), - "checkpoint at the last turn boundary" - ); + assert!(w.mgr.checkpoints().iter().any(|c| c.ids.len() == turn_at), "checkpoint at the last turn boundary"); // The client re-renders the last turn differently (e.g. dropped thinking). let mut p2 = p1[..turn_at].to_vec(); p2.push(TURN); p2.extend([42, 43, 44, 45, 46]); - let r2 = w - .request(&p2, &[], true, &gen_tokens(2, 4), None, 64) - .unwrap(); + let r2 = w.request(&p2, &[], true, &gen_tokens(2, 4), None, 64).unwrap(); assert!(!r2.start.from_live); - assert_eq!( - r2.start.resume, turn_at, - "restored the checkpoint at the turn boundary" - ); + assert_eq!(r2.start.resume, turn_at, "restored the checkpoint at the turn boundary"); assert!(r1.consumed.len() > turn_at); } @@ -90,36 +61,22 @@ fn the_shared_root_is_pinned_while_other_checkpoints_rotate() { // Every chat shares the system prompt (same salt for it) via a common prefix. let mut shared = chat(1, system, &[]); shared.extend_from_slice(&ids[1 + system..]); - w.request(&shared, &[], true, &gen_tokens(1, 4), None, 8) - .unwrap(); + w.request(&shared, &[], true, &gen_tokens(1, 4), None, 8).unwrap(); let checks = w.mgr.checkpoints(); assert!(checks.len() <= 3, "chain capacity honoured"); let root = checks.first().expect("a checkpoint exists"); let expected_root = shared.iter().skip(1).position(|&t| t == TURN).unwrap() + 1; - assert_eq!( - root.ids.len(), - expected_root, - "chat {chat_no}: the chain root is the end of the system prompt" - ); + assert_eq!(root.ids.len(), expected_root, "chat {chat_no}: the chain root is the end of the system prompt"); root_len.get_or_insert(root.ids.len()); for pair in checks.windows(2) { - assert!( - pair[1].ids.starts_with(&pair[0].ids), - "the chain is a prefix chain" - ); + assert!(pair[1].ids.starts_with(&pair[0].ids), "the chain is a prefix chain"); } } // A brand-new chat sharing only the system prompt mounts through the root. let mut fresh = chat(1, system, &[]); fresh.extend([TURN, 5, 6, 7, 8, 9, 10]); - let r = w - .request(&fresh, &[], true, &gen_tokens(3, 3), None, 8) - .unwrap(); - assert_eq!( - r.start.resume, - root_len.unwrap(), - "new chats read only what follows the pinned root" - ); + let r = w.request(&fresh, &[], true, &gen_tokens(3, 3), None, 8).unwrap(); + assert_eq!(r.start.resume, root_len.unwrap(), "new chats read only what follows the pinned root"); assert!(!r.start.from_live); } @@ -127,46 +84,29 @@ fn the_shared_root_is_pinned_while_other_checkpoints_rotate() { fn switching_between_conversations_parks_and_restores_exactly() { let mut w = world(options(), false); let a1 = chat(1, 20, &[10]); - let ra = w - .request(&a1, &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); + let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 8).unwrap(); let b1 = chat(2, 18, &[14]); - let rb = w - .request(&b1, &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); + let rb = w.request(&b1, &[], true, &gen_tokens(2, 6), None, 8).unwrap(); assert!(rb.start.restored.is_none() && rb.start.resume == 0); assert_eq!(w.mgr.cache().size(), 1, "A was parked when B took over"); let events = w.mgr.take_events(); assert!( - events - .iter() - .any(|e| e.contains("parked") && e.contains(&format!("{} tokens", ra.consumed.len()))), + events.iter().any(|e| e.contains("parked") && e.contains(&format!("{} tokens", ra.consumed.len()))), "{events:?}" ); // Back to A: its next turn. let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1, 2, 3, 4]); - let r = w - .request(&a2, &[], true, &gen_tokens(3, 4), None, 8) - .unwrap(); - assert_eq!( - r.start.restored.map(|(tokens, _)| tokens), - Some(ra.consumed.len()), - "A restored from RAM" - ); + let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 8).unwrap(); + assert_eq!(r.start.restored.map(|(tokens, _)| tokens), Some(ra.consumed.len()), "A restored from RAM"); assert_eq!(r.start.resume, ra.consumed.len()); assert!(r.start.from_live); assert_eq!(w.mgr.cache().size(), 1, "B is parked now"); // And B again. let mut b2 = rb.consumed.clone(); b2.extend([TURN, 9, 9, 9]); - let r = w - .request(&b2, &[], true, &gen_tokens(4, 4), None, 8) - .unwrap(); - assert_eq!( - r.start.restored.map(|(tokens, _)| tokens), - Some(rb.consumed.len()) - ); + let r = w.request(&b2, &[], true, &gen_tokens(4, 4), None, 8).unwrap(); + assert_eq!(r.start.restored.map(|(tokens, _)| tokens), Some(rb.consumed.len())); } #[test] @@ -193,7 +133,8 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { assert_eq!(rc.start.resume, 0); assert_eq!(w.mgr.cache().retained_bytes(), 0, "C never inherits A's retained K/V"); let events = w.mgr.take_events(); - let parked_a = events.iter().filter(|e| e.contains("parked ") && e.contains(&format!("{} tokens", r.consumed.len()))).count(); + let parked_a = + events.iter().filter(|e| e.contains("parked ") && e.contains(&format!("{} tokens", r.consumed.len()))).count(); assert_eq!(parked_a, 1, "{events:?}"); // every conversation comes back with exactly its own cells (the harness asserts the device state after each begin_request) for (conv, tag) in [(r.consumed.clone(), 5), (rb.consumed.clone(), 6), (rc.consumed.clone(), 7)] { @@ -208,23 +149,14 @@ fn a_restored_conversations_retained_kv_never_serves_another_conversation() { fn a_parked_conversation_restores_through_its_checkpoint_when_the_tail_was_rewritten() { let mut w = world(options(), false); let a1 = chat(1, 20, &[10, 10]); - let ra = w - .request(&a1, &[], true, &gen_tokens(1, 6), None, 64) - .unwrap(); + let ra = w.request(&a1, &[], true, &gen_tokens(1, 6), None, 64).unwrap(); let turn_at = a1.iter().rposition(|&t| t == TURN).unwrap(); let b1 = chat(2, 18, &[14]); - w.request(&b1, &[], true, &gen_tokens(2, 6), None, 64) - .unwrap(); + w.request(&b1, &[], true, &gen_tokens(2, 6), None, 64).unwrap(); let mut a2 = a1[..turn_at].to_vec(); a2.extend([TURN, 77, 78, 79, 80]); - let r = w - .request(&a2, &[], true, &gen_tokens(3, 4), None, 64) - .unwrap(); - assert_eq!( - r.start.restored, - Some((turn_at, false)), - "restored the parked image, mounted its checkpoint" - ); + let r = w.request(&a2, &[], true, &gen_tokens(3, 4), None, 64).unwrap(); + assert_eq!(r.start.restored, Some((turn_at, false)), "restored the parked image, mounted its checkpoint"); assert_eq!(r.start.resume, turn_at); assert!(ra.consumed.len() > turn_at); } @@ -234,22 +166,13 @@ fn parking_is_off_by_default_and_the_live_session_is_simply_replaced() { let mut off = options(); off.conversation_cache_bytes = 0; let mut w = world(off, false); - let ra = w - .request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); + let ra = w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 0); let mut a2 = ra.consumed.clone(); a2.extend([TURN, 1]); - let r = w - .request(&a2, &[], true, &gen_tokens(3, 3), None, 8) - .unwrap(); - assert_eq!( - (r.start.resume, r.start.restored), - (0, None), - "A is gone and is read again" - ); + let r = w.request(&a2, &[], true, &gen_tokens(3, 3), None, 8).unwrap(); + assert_eq!((r.start.resume, r.start.restored), (0, None), "A is gone and is read again"); } #[test] @@ -259,28 +182,17 @@ fn physical_memory_admission_gates_parking() { o.conversation_cache_min_free_bytes = 128 << 20; let mut w = world(o, false); w.dev.available = available; - w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); - assert_eq!( - w.mgr.cache().size(), - 0, - "unknown or short RAM never parks ({available:?})" - ); + w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); + assert_eq!(w.mgr.cache().size(), 0, "unknown or short RAM never parks ({available:?})"); let events = w.mgr.take_events(); - assert!( - events.iter().any(|e| e.contains("physical RAM admission")), - "{events:?}" - ); + assert!(events.iter().any(|e| e.contains("physical RAM admission")), "{events:?}"); } let mut o = options(); o.conversation_cache_min_free_bytes = 128 << 20; let mut w = world(o, false); w.dev.available = Some(10 * GIB); - w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8) - .unwrap(); - w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8) - .unwrap(); + w.request(&chat(1, 20, &[10]), &[], true, &gen_tokens(1, 6), None, 8).unwrap(); + w.request(&chat(2, 18, &[14]), &[], true, &gen_tokens(2, 6), None, 8).unwrap(); assert_eq!(w.mgr.cache().size(), 1); } diff --git a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs index 0239e928..927f2d39 100644 --- a/crates/engine-core/src/conversation/manager_tests/hash_fn.rs +++ b/crates/engine-core/src/conversation/manager_tests/hash_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn hash(ids: &[i32]) -> u64 { let mut h: u64 = 1469598103934665603; for id in ids { @@ -16,10 +15,7 @@ pub(super) fn hash(ids: &[i32]) -> u64 { } pub(super) fn pat(seed: u64, tag: u64, j: usize) -> u8 { - let mixed = seed - .wrapping_mul(0x9E37_79B9_7F4A_7C15) - .rotate_left((tag % 63) as u32 + 1) - ^ tag.wrapping_mul(0xA5); + let mixed = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left((tag % 63) as u32 + 1) ^ tag.wrapping_mul(0xA5); (mixed >> ((j % 8) * 8)) as u8 ^ (j / 8) as u8 ^ tag as u8 } @@ -45,18 +41,14 @@ impl SimDevice { for (i, pool) in [KvPool::K, KvPool::V].into_iter().enumerate() { let at = (c / PAGE) * PAGE * per + (c % PAGE) * per; // one KV head let tag = 10 + 2 * i as u64 + if layer == KvLayer::Draft { 100 } else { 0 }; - self.mem.get_mut(kv_region(layer, pool, false))[at..at + per] - .copy_from_slice(&pattern(seed, tag, per)); + self.mem.get_mut(kv_region(layer, pool, false))[at..at + per].copy_from_slice(&pattern(seed, tag, per)); } } pub(super) fn mirror_ring(&mut self, pages: std::ops::Range) { for pool in [KvPool::K, KvPool::V] { let block = PAGE * self.per(); - let host = self - .mem - .get(kv_region(KvLayer::Draft, pool, false)) - .to_vec(); + let host = self.mem.get(kv_region(KvLayer::Draft, pool, false)).to_vec(); let ring = self.mem.get_mut(kv_region(KvLayer::Draft, pool, true)); for page in pages.clone() { let to = (page % SLOTS) * block; @@ -75,36 +67,22 @@ impl SimDevice { let dead = pattern(hash(&ids[..1]), 4, row); for r in from / 4..to / 4 { let at = r * row; - self.mem - .get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + row] + self.mem.get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + row] .copy_from_slice(&pattern(hash(&ids[..(r + 1) * 4]), 5, row)); } let p = &ids[..to]; let seed = hash(p); let z = state_sizes(&self.g).unwrap(); - self.mem - .get_mut(StateRegion::Gdn) - .copy_from_slice(&pattern(seed, 1, z.gdn)); + self.mem.get_mut(StateRegion::Gdn).copy_from_slice(&pattern(seed, 1, z.gdn)); if self.ple { - self.mem - .get_mut(StateRegion::PleHist) - .copy_from_slice(&pattern(seed, 2, z.ple)); + self.mem.get_mut(StateRegion::PleHist).copy_from_slice(&pattern(seed, 2, z.ple)); } - self.mem - .get_mut(idx(IdxKind::Tail)) - .copy_from_slice(&pattern(seed, 3, z.tail)); + self.mem.get_mut(idx(IdxKind::Tail)).copy_from_slice(&pattern(seed, 3, z.tail)); self.mem.get_mut(idx(IdxKind::Dead)).copy_from_slice(&dead); - self.mem - .get_mut(idx(IdxKind::BlockPos)) - .copy_from_slice(&((to / 4) as i32).to_le_bytes()); + self.mem.get_mut(idx(IdxKind::BlockPos)).copy_from_slice(&((to / 4) as i32).to_le_bytes()); let spare = (to / 4) * row; - self.mem - .get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[spare..spare + row] - .copy_from_slice(&dead); - self.mem.ple_prev = [ - if to >= 2 { ids[to - 2] } else { -1 }, - if to >= 1 { ids[to - 1] } else { -1 }, - ]; + self.mem.get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[spare..spare + row].copy_from_slice(&dead); + self.mem.ple_prev = [if to >= 2 { ids[to - 2] } else { -1 }, if to >= 1 { ids[to - 1] } else { -1 }]; self.mirror_ring(from / PAGE..to.div_ceil(PAGE)); } @@ -114,57 +92,23 @@ impl SimDevice { let row = self.row_bytes(); let per = self.per(); if l == 0 { - for region in [ - StateRegion::Gdn, - idx(IdxKind::Tail), - idx(IdxKind::Dead), - idx(IdxKind::BlockPos), - ] { - assert!( - self.mem.get(region).iter().all(|&b| b == 0), - "{ctx}: {region:?} not zero" - ); + for region in [StateRegion::Gdn, idx(IdxKind::Tail), idx(IdxKind::Dead), idx(IdxKind::BlockPos)] { + assert!(self.mem.get(region).iter().all(|&b| b == 0), "{ctx}: {region:?} not zero"); } assert_eq!(self.mem.ple_prev, [-1, -1], "{ctx}"); return; } let seed = hash(&ids[..l]); - assert_eq!( - self.mem.get(StateRegion::Gdn), - &pattern(seed, 1, z.gdn)[..], - "{ctx}: gdn" - ); + assert_eq!(self.mem.get(StateRegion::Gdn), &pattern(seed, 1, z.gdn)[..], "{ctx}: gdn"); if self.ple { - assert_eq!( - self.mem.get(StateRegion::PleHist), - &pattern(seed, 2, z.ple)[..], - "{ctx}: ple" - ); + assert_eq!(self.mem.get(StateRegion::PleHist), &pattern(seed, 2, z.ple)[..], "{ctx}: ple"); } - assert_eq!( - self.mem.get(idx(IdxKind::Tail)), - &pattern(seed, 3, z.tail)[..], - "{ctx}: tail" - ); + assert_eq!(self.mem.get(idx(IdxKind::Tail)), &pattern(seed, 3, z.tail)[..], "{ctx}: tail"); let dead = pattern(hash(&ids[..1]), 4, row); - assert_eq!( - self.mem.get(idx(IdxKind::Dead)), - &dead[..], - "{ctx}: dead key" - ); - assert_eq!( - self.mem.get(idx(IdxKind::BlockPos)), - &((l / 4) as i32).to_le_bytes(), - "{ctx}: block_pos" - ); - assert_eq!( - self.mem.ple_prev, - [if l >= 2 { ids[l - 2] } else { -1 }, ids[l - 1]], - "{ctx}: ple window" - ); - let pooled = self - .mem - .get(kv_region(KvLayer::Main(0), KvPool::Pooled, false)); + assert_eq!(self.mem.get(idx(IdxKind::Dead)), &dead[..], "{ctx}: dead key"); + assert_eq!(self.mem.get(idx(IdxKind::BlockPos)), &((l / 4) as i32).to_le_bytes(), "{ctx}: block_pos"); + assert_eq!(self.mem.ple_prev, [if l >= 2 { ids[l - 2] } else { -1 }, ids[l - 1]], "{ctx}: ple window"); + let pooled = self.mem.get(kv_region(KvLayer::Main(0), KvPool::Pooled, false)); for r in 0..l / 4 { assert_eq!( &pooled[r * row..(r + 1) * row], @@ -172,11 +116,7 @@ impl SimDevice { "{ctx}: pooled row {r}" ); } - assert_eq!( - &pooled[(l / 4) * row..(l / 4 + 1) * row], - &dead[..], - "{ctx}: spare row" - ); + assert_eq!(&pooled[(l / 4) * row..(l / 4 + 1) * row], &dead[..], "{ctx}: spare row"); for layer in [KvLayer::Main(0), KvLayer::Draft] { for (i, pool) in [KvPool::K, KvPool::V].into_iter().enumerate() { let tag = 10 + 2 * i as u64 + if layer == KvLayer::Draft { 100 } else { 0 }; @@ -227,14 +167,7 @@ impl StateMemory for SimDevice { fn reset_streaming_residency(&mut self, layer: KvLayer) -> Result<(), String> { self.mem.reset_streaming_residency(layer) } - fn restore_ring( - &mut self, - layer: KvLayer, - format: i32, - b0: i64, - b1: i64, - slots: i64, - ) -> Result<(), String> { + fn restore_ring(&mut self, layer: KvLayer, format: i32, b0: i64, b1: i64, slots: i64) -> Result<(), String> { self.mem.restore_ring(layer, format, b0, b1, slots) } } diff --git a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs index a8530337..cf601378 100644 --- a/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs +++ b/crates/engine-core/src/conversation/manager_tests/impl_sessiondevice_for_simdevice.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl SessionDevice for SimDevice { fn zero_session(&mut self) -> Result<(), String> { self.zeroed += 1; @@ -57,11 +56,7 @@ pub(super) fn world(options: ConversationOptions, ple: bool) -> World { let z = state_sizes(&g).unwrap(); mem.put(StateRegion::Gdn, vec![0; z.gdn]); mem.put(StateRegion::PleHist, vec![0; if ple { z.ple } else { 0 }]); - for (kind, n) in [ - (IdxKind::Tail, z.tail), - (IdxKind::Dead, z.dead), - (IdxKind::BlockPos, z.block_pos), - ] { + for (kind, n) in [(IdxKind::Tail, z.tail), (IdxKind::Dead, z.dead), (IdxKind::BlockPos, z.block_pos)] { mem.put(idx(kind), vec![0; n]); } let mut st = main.st.clone(); @@ -89,20 +84,11 @@ pub(super) fn world(options: ConversationOptions, ple: bool) -> World { draft_restores: Vec::new(), steering: Vec::new(), }; - World { - dev, - ss, - draft: draft.st.clone(), - g, - mgr: ConversationManager::new(options), - } + World { dev, ss, draft: draft.st.clone(), g, mgr: ConversationManager::new(options) } } pub(super) fn prompt_options(root_min: usize) -> PromptOptions { - PromptOptions { - root_min, - ..PromptOptions::original_mode17(262144) - } + PromptOptions { root_min, ..PromptOptions::original_mode17(262144) } } /// A chat: `<|im_start|> system... ` then `turns` user/assistant turns, each @@ -130,33 +116,14 @@ impl World { stop_after: Option, root_min: usize, ) -> Result { - let mut engine = DeviceEngine { - device: &mut self.dev, - geometry: &self.g, - session: &self.ss, - draft: &self.draft, - }; - let start = self - .mgr - .begin_request(&mut engine, ids, imgs, cvec) - .map_err(|e| e.0)?; - let resume = if start.reread_to.is_some() { - 0 - } else { - start.resume - }; - self.dev - .assert_prefix_state(ids, resume, "state after begin_request"); + let mut engine = + DeviceEngine { device: &mut self.dev, geometry: &self.g, session: &self.ss, draft: &self.draft }; + let start = self.mgr.begin_request(&mut engine, ids, imgs, cvec).map_err(|e| e.0)?; + let resume = if start.reread_to.is_some() { 0 } else { start.resume }; + self.dev.assert_prefix_state(ids, resume, "state after begin_request"); let prompt: Vec = ids.iter().map(|&i| i as u32).collect(); - let plan = PromptPlan::new( - &prompt, - start.resume, - start.reread_to, - None, - prompt_options(root_min), - 256, - ) - .map_err(|e| format!("{e:?}"))?; + let plan = PromptPlan::new(&prompt, start.resume, start.reread_to, None, prompt_options(root_min), 256) + .map_err(|e| format!("{e:?}"))?; let mut at = start.read_from; for (done_actions, action) in plan.enumerate() { if action.path == PromptPath::FinalSeed { @@ -164,31 +131,20 @@ impl World { } if stop_after == Some(done_actions) { self.mgr.finish_request(Vec::new(), imgs, true); - return Ok(Run { - start, - consumed: Vec::new(), - }); + return Ok(Run { start, consumed: Vec::new() }); } assert_eq!(action.first, at, "plan is contiguous"); - self.dev - .read(ids, action.first, action.first + action.count); + self.dev.read(ids, action.first, action.first + action.count); at += action.count; - let mut engine = DeviceEngine { - device: &mut self.dev, - geometry: &self.g, - session: &self.ss, - draft: &self.draft, - }; - self.mgr - .after_prompt_action(&mut engine, ids, imgs, &action) - .map_err(|e| e.0)?; + let mut engine = + DeviceEngine { device: &mut self.dev, geometry: &self.g, session: &self.ss, draft: &self.draft }; + self.mgr.after_prompt_action(&mut engine, ids, imgs, &action).map_err(|e| e.0)?; } // The last prompt token and the committed generated tokens read through verify windows. let mut consumed = ids.to_vec(); consumed.extend_from_slice(&gen_tokens[..gen_tokens.len().saturating_sub(1)]); self.dev.read(&consumed, at, consumed.len()); - self.dev - .assert_prefix_state(&consumed, consumed.len(), "state after the request"); + self.dev.assert_prefix_state(&consumed, consumed.len(), "state after the request"); self.mgr.finish_request(consumed.clone(), imgs, false); Ok(Run { start, consumed }) } diff --git a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs index 61caa4a1..c1e109ab 100644 --- a/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs +++ b/crates/engine-core/src/conversation/manager_tests/random_conversation_traffic_always_resum.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { // How the resumes were reached, so the trace is known to cover every path. @@ -13,17 +12,9 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ seed.wrapping_mul(0xD1B5_4A32_D192_ED03)); let mut o = options(); o.prompt_cache = 2 + rng.below(4) as i64; - o.prompt_cache_every = if rng.below(3) == 0 { - 8 + rng.below(30) as i64 - } else { - 1_000_000 - }; + o.prompt_cache_every = if rng.below(3) == 0 { 8 + rng.below(30) as i64 } else { 1_000_000 }; o.conversation_cache_slots = 1 + rng.below(4) as usize; - o.conversation_cache_bytes = if rng.below(5) == 0 { - 0 - } else { - (200 + rng.below(600)) as usize * 1024 - }; + o.conversation_cache_bytes = if rng.below(5) == 0 { 0 } else { (200 + rng.below(600)) as usize * 1024 }; o.reread_checkpoints = rng.below(7) == 0; let mut w = world(o, rng.below(4) == 0); // A few conversations that share (or not) a system prompt, each a list of turns. @@ -33,11 +24,7 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { let pick = rng.below(4); let ids: Vec = if convs.is_empty() || pick == 0 { let shared = rng.below(2) == 0; - let mut c = chat( - if shared { 1 } else { 2 + rng.below(3) as i32 }, - 14 + rng.below(8) as usize, - &[], - ); + let mut c = chat(if shared { 1 } else { 2 + rng.below(3) as i32 }, 14 + rng.below(8) as usize, &[]); c.extend([TURN]); c.extend((0..(3 + rng.below(12)) as i32).map(|i| 300 + i + rng.below(3) as i32)); c @@ -54,9 +41,7 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { 1 => { let cut = 1 + rng.below(base.len() as u64 - 1) as usize; let mut c = base[..cut].to_vec(); - c.extend( - (0..(2 + rng.below(8)) as i32).map(|i| 800 + i + rng.below(2) as i32), - ); + c.extend((0..(2 + rng.below(8)) as i32).map(|i| 800 + i + rng.below(2) as i32)); c } _ => base, @@ -69,9 +54,7 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { let stop = (rng.below(8) == 0).then(|| rng.below(3) as usize); let generated = gen_tokens(step, 1 + rng.below(8) as usize); let ctx = format!("seed {seed} step {step}"); - let run = w - .request(&ids, &[], cvec, &generated, stop, 8) - .unwrap_or_else(|e| panic!("{ctx}: {e}")); + let run = w.request(&ids, &[], cvec, &generated, stop, 8).unwrap_or_else(|e| panic!("{ctx}: {e}")); let s = &run.start; let path = match (s.restored, s.resume, s.from_live) { (Some((_, true)), _, _) => 2, @@ -81,12 +64,7 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { (None, _, false) => 1, }; paths[path] += 1; - parks += w - .mgr - .take_events() - .iter() - .filter(|e| e.contains("parked ")) - .count(); + parks += w.mgr.take_events().iter().filter(|e| e.contains("parked ")).count(); if run.consumed.is_empty() { assert!(!w.mgr.live_ok(), "{ctx}"); } else { @@ -96,32 +74,17 @@ fn random_conversation_traffic_always_resumes_into_the_exact_prefix_state() { } // Invariants of the chain and the cache. let checks = w.mgr.checkpoints(); - assert!( - checks.len() as i64 <= w.mgr.options().prompt_cache, - "{ctx}: chain capacity" - ); + assert!(checks.len() as i64 <= w.mgr.options().prompt_cache, "{ctx}: chain capacity"); let mut previous = 0; for c in checks { - assert!( - c.ids.len() > previous || previous == 0, - "{ctx}: chain strictly deepens" - ); + assert!(c.ids.len() > previous || previous == 0, "{ctx}: chain strictly deepens"); previous = c.ids.len(); } - assert!( - w.mgr.cache().bytes() <= w.mgr.cache().budget() || w.mgr.cache().budget() == 0, - "{ctx}: budget" - ); - assert!( - w.mgr.cache().size() <= w.mgr.cache().slots().max(1), - "{ctx}: slots" - ); + assert!(w.mgr.cache().bytes() <= w.mgr.cache().budget() || w.mgr.cache().budget() == 0, "{ctx}: budget"); + assert!(w.mgr.cache().size() <= w.mgr.cache().slots().max(1), "{ctx}: slots"); } assert!(live_requests > 10, "the trace exercised real requests"); } - assert!( - paths.iter().all(|&n| n >= 5), - "every resume path was exercised: {paths:?}" - ); + assert!(paths.iter().all(|&n| n >= 5), "every resume path was exercised: {paths:?}"); assert!(parks >= 20, "parking was exercised: {parks}"); } diff --git a/crates/engine-core/src/conversation/model.rs b/crates/engine-core/src/conversation/model.rs index 59b96d96..ad3cdb2f 100644 --- a/crates/engine-core/src/conversation/model.rs +++ b/crates/engine-core/src/conversation/model.rs @@ -107,11 +107,7 @@ impl ModelGeometry { /// Full-attention layer count; 0 for a non-positive interval (such a /// geometry is rejected by the sizing functions before this matters). pub fn n_qsa_layers(&self) -> i64 { - if self.qsa_interval > 0 { - self.n_layers / self.qsa_interval - } else { - 0 - } + if self.qsa_interval > 0 { self.n_layers / self.qsa_interval } else { 0 } } pub fn n_gdn_layers(&self) -> i64 { @@ -286,13 +282,7 @@ pub enum KvPool { } impl KvPool { - pub const ALL: [KvPool; 5] = [ - KvPool::K, - KvPool::V, - KvPool::KScale, - KvPool::VScale, - KvPool::Pooled, - ]; + pub const ALL: [KvPool; 5] = [KvPool::K, KvPool::V, KvPool::KScale, KvPool::VScale, KvPool::Pooled]; } /// Per-owned-layer indexer running state. @@ -314,11 +304,7 @@ pub enum StateRegion { Idx { layer: usize, kind: IdxKind }, /// A K/V payload; `resident` selects the VRAM slots over the /// authoritative copy (they differ only for streamed layers). - Kv { - layer: KvLayer, - pool: KvPool, - resident: bool, - }, + Kv { layer: KvLayer, pool: KvPool, resident: bool }, } /// Conversation errors carry the original's message text. diff --git a/crates/engine-core/src/conversation/snapshot.rs b/crates/engine-core/src/conversation/snapshot.rs index 13f03c7e..a9c37360 100644 --- a/crates/engine-core/src/conversation/snapshot.rs +++ b/crates/engine-core/src/conversation/snapshot.rs @@ -7,17 +7,13 @@ //! from that session. use super::cache::{ - ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, - SavedConversation, + ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, SavedConversation, }; use super::checked::{add, product}; use super::kv::{kv_bytes, kv_capture_bytes, kv_restore, kv_save, kv_validate}; -use super::model::{ - ConvError, ConvResult, KvLayer, ModelGeometry, QsaDesc, SessionSpec, StateMemory, fail, -}; +use super::model::{ConvError, ConvResult, KvLayer, ModelGeometry, QsaDesc, SessionSpec, StateMemory, fail}; use super::state::{ - StateSizes, checkpoint_restore, checkpoint_save, checkpoint_targets, checkpoint_validate, - image_keys, session_sizes, + StateSizes, checkpoint_restore, checkpoint_save, checkpoint_targets, checkpoint_validate, image_keys, session_sizes, }; use std::mem::size_of; @@ -41,16 +37,9 @@ pub enum RestoreOutcome { TransferFailed(String), } -fn view_validate( - view: &ConversationView<'_>, - ss: &SessionSpec, - g: &ModelGeometry, -) -> ConvResult<()> { +fn view_validate(view: &ConversationView<'_>, ss: &SessionSpec, g: &ModelGeometry) -> ConvResult<()> { checkpoint_targets(ss, g, view.ids.len())?; - if view.ids.is_empty() - || !image_keys(view.images, view.ids.len()) - || view.ids.iter().any(|&id| id < 0) - { + if view.ids.is_empty() || !image_keys(view.images, view.ids.len()) || view.ids.iter().any(|&id| id < 0) { return fail("invalid live token/image metadata"); } for c in view.checkpoints { @@ -82,32 +71,20 @@ fn view_validate( fn metadata_bytes(c: &ConversationCheckpoint, total: &mut usize) -> bool { let (Some(ids), Some(images)) = ( product(&[c.ids.len() as u64, size_of::() as u64]), - product(&[ - c.imgs.len() as u64, - size_of::() as u64, - ]), + product(&[c.imgs.len() as u64, size_of::() as u64]), ) else { return false; }; - [ - ids, - images, - c.gdn.len(), - c.ple.len(), - c.tails.len(), - c.dead.len(), - c.block_pos.len(), - ] - .into_iter() - .all(|n| add(total, n)) + [ids, images, c.gdn.len(), c.ple.len(), c.tails.len(), c.dead.len(), c.block_pos.len()] + .into_iter() + .all(|n| add(total, n)) } fn layer_state<'a>(ss: &'a SessionSpec, draft: &'a QsaDesc, i: usize) -> ConvResult<&'a QsaDesc> { if i == ss.owned_qsa() { Ok(draft) } else { - ss.owned(i) - .ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into())) + ss.owned(i).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into())) } } @@ -121,36 +98,18 @@ pub fn snapshot_bytes( view_validate(view, ss, g)?; let z: StateSizes = session_sizes(g, ss)?; let qsa = ss.owned_qsa() as u64; - let overflow = - || ConvError("conversation snapshot: snapshot metadata byte count overflow".into()); + let overflow = || ConvError("conversation snapshot: snapshot metadata byte count overflow".into()); let ids = product(&[view.ids.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; - let images = product(&[ - view.images.len() as u64, - size_of::() as u64, - ]) - .ok_or_else(overflow)?; - let checkpoints = product(&[ - view.checkpoints.len() as u64, - size_of::() as u64, - ]) - .ok_or_else(overflow)?; + let images = product(&[view.images.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; + let checkpoints = + product(&[view.checkpoints.len() as u64, size_of::() as u64]).ok_or_else(overflow)?; let layers = product(&[qsa + 1, size_of::() as u64]).ok_or_else(overflow)?; let tails = product(&[qsa, z.tail as u64]).ok_or_else(overflow)?; let dead = product(&[qsa, z.dead as u64]).ok_or_else(overflow)?; let positions = product(&[qsa, z.block_pos as u64]).ok_or_else(overflow)?; let mut bytes = 0usize; let ple = if ss.shape.has_ple_hist { z.ple } else { 0 }; - for n in [ - ids, - images, - checkpoints, - layers, - tails, - dead, - positions, - z.gdn, - ple, - ] { + for n in [ids, images, checkpoints, layers, tails, dead, positions, z.gdn, ple] { if !add(&mut bytes, n) { return fail("snapshot byte count overflow"); } @@ -204,11 +163,8 @@ pub fn snapshot_capture_bytes( return fail("retained K/V allocation overflow"); } } - let directory = product(&[ - (reuse.kv.capacity() - layers) as u64, - size_of::() as u64, - ]) - .ok_or_else(|| ConvError("conversation snapshot: retained K/V directory overflow".into()))?; + let directory = product(&[(reuse.kv.capacity() - layers) as u64, size_of::() as u64]) + .ok_or_else(|| ConvError("conversation snapshot: retained K/V directory overflow".into()))?; if !add(&mut bytes, directory) { return fail("retained K/V directory overflow"); } @@ -216,8 +172,7 @@ pub fn snapshot_capture_bytes( } fn synchronize(mem: &mut dyn StateMemory) -> ConvResult<()> { - mem.synchronize() - .map_err(|message| ConvError(format!("conversation snapshot synchronize: {message}"))) + mem.synchronize().map_err(|message| ConvError(format!("conversation snapshot synchronize: {message}"))) } /// `conversation_snapshot_save`: capture the live session into a new image. @@ -246,37 +201,18 @@ pub fn snapshot_save( captured.live.ids = view.ids.to_vec(); captured.live.imgs = view.images.to_vec(); captured.checkpoints = view.checkpoints.to_vec(); - let unchanged = if reuse.kv.is_empty() { - 0 - } else { - reuse.unchanged_tokens - }; + let unchanged = if reuse.kv.is_empty() { 0 } else { reuse.unchanged_tokens }; captured.kv = reuse.kv; let layers = ss.owned_qsa(); let missing = (layers + 1).saturating_sub(captured.kv.len()); - captured - .kv - .try_reserve_exact(missing) - .map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; + captured.kv.try_reserve_exact(missing).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; captured.kv.resize_with(layers + 1, ConversationKv::default); checkpoint_save(&mut captured.live, ss, g, mem)?; let upto = view.ids.len() as i64; let mut reused = 0usize; for j in 0..layers { - let st = ss - .owned(j) - .ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; - kv_save( - &mut captured.kv[j], - KvLayer::Main(j), - st, - g, - upto, - true, - unchanged, - mem, - Some(&mut reused), - )?; + let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; + kv_save(&mut captured.kv[j], KvLayer::Main(j), st, g, upto, true, unchanged, mem, Some(&mut reused))?; } // The draft's final cell may not have been computed when the output cap was // reached. Refresh that page even when the main prefix continued unchanged. @@ -329,9 +265,7 @@ pub fn snapshot_validate( } let upto = image.live.ids.len() as i64; for j in 0..layers { - let st = ss - .owned(j) - .ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; + let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; kv_validate(&image.kv[j], st, g, upto, true)?; } kv_validate(&image.kv[layers], draft, g, upto, false) @@ -355,20 +289,10 @@ pub fn snapshot_restore( let upto = image.live.ids.len() as i64; let restore = |mem: &mut dyn StateMemory| -> ConvResult<()> { for j in 0..ss.owned_qsa() { - let st = ss - .owned(j) - .ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; + let st = ss.owned(j).ok_or_else(|| ConvError("conversation snapshot: missing QSA state".into()))?; kv_restore(&image.kv[j], KvLayer::Main(j), st, g, upto, true, mem)?; } - kv_restore( - &image.kv[ss.owned_qsa()], - KvLayer::Draft, - draft, - g, - upto, - false, - mem, - )?; + kv_restore(&image.kv[ss.owned_qsa()], KvLayer::Draft, draft, g, upto, false, mem)?; checkpoint_restore(&image.live, ss, g, mem) }; match restore(mem) { diff --git a/crates/engine-core/src/conversation/snapshot_tests.rs b/crates/engine-core/src/conversation/snapshot_tests.rs index 7e8ab088..4a370516 100644 --- a/crates/engine-core/src/conversation/snapshot_tests.rs +++ b/crates/engine-core/src/conversation/snapshot_tests.rs @@ -4,21 +4,18 @@ //! fault injection (failed first/later copy, failed pre/post synchronize). use super::cache::{ - ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, - SavedConversation, + ConversationCheckpoint, ConversationImageKey, ConversationKv, ConversationKvReuse, SavedConversation, }; use super::kv::{kv_bytes, kv_restore, kv_save, kv_verify}; use super::model::{ - IDX_BLOCK, IdxKind, KV_F16, KV_INT8, KV_Q4, KV_VALUE_INT8, KvLayer, KvPool, ModelGeometry, - QsaDesc, SessionShape, SessionSpec, StateRegion, StreamMap, + IDX_BLOCK, IdxKind, KV_F16, KV_INT8, KV_Q4, KV_VALUE_INT8, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, + SessionSpec, StateRegion, StreamMap, }; use super::snapshot::{ - ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, - snapshot_save, snapshot_validate, -}; -use super::state::{ - checkpoint_restore, checkpoint_save, checkpoint_validate, session_sizes, state_sizes, + ConversationView, RestoreOutcome, snapshot_bytes, snapshot_capture_bytes, snapshot_restore, snapshot_save, + snapshot_validate, }; +use super::state::{checkpoint_restore, checkpoint_save, checkpoint_validate, session_sizes, state_sizes}; use super::testing::HostMemory; pub(super) const HYBRID: i32 = 3; @@ -54,12 +51,12 @@ mod layer_snapshots_are_byte_exact; mod kv_region_fn; #[allow(unused_imports)] +use kv_region_fn::equal; +#[allow(unused_imports)] pub(super) use kv_region_fn::kv_region; #[allow(unused_imports)] use kv_region_fn::mk_view; #[allow(unused_imports)] -use kv_region_fn::equal; -#[allow(unused_imports)] use kv_region_fn::q4_per_head; mod kv_level_fn; #[allow(unused_imports)] @@ -67,20 +64,20 @@ use kv_level_fn::kv_level; mod full_session_fn; #[allow(unused_imports)] use full_session_fn::full_session; -mod impl_pools; mod fixture_fn; +mod impl_pools; #[allow(unused_imports)] use fixture_fn::fixture; mod golden_state_fn; #[allow(unused_imports)] -use golden_state_fn::golden_state; +use golden_state_fn::assert_checkpoint; +#[allow(unused_imports)] +use golden_state_fn::assert_image; +#[allow(unused_imports)] +use golden_state_fn::assert_kv; #[allow(unused_imports)] use golden_state_fn::fnv; #[allow(unused_imports)] use golden_state_fn::fnv_buf; #[allow(unused_imports)] -use golden_state_fn::assert_kv; -#[allow(unused_imports)] -use golden_state_fn::assert_checkpoint; -#[allow(unused_imports)] -use golden_state_fn::assert_image; +use golden_state_fn::golden_state; diff --git a/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs index e9146faf..ec98b2b5 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/fixture_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { let g = ModelGeometry { n_layers: if zero_qsa { 3 } else { 8 }, @@ -17,17 +16,10 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { ..ModelGeometry::default() }; let z = state_sizes(&g).expect("checked canonical/pruned/zero-QSA sizing"); - let (first, last, draft) = ( - Pools::new(&g, format), - Pools::new(&g, format), - Pools::new(&g, format), - ); + let (first, last, draft) = (Pools::new(&g, format), Pools::new(&g, format), Pools::new(&g, format)); let mut mem = HostMemory::new(); mem.put(StateRegion::Gdn, vec![0xa5; z.gdn]); - mem.put( - StateRegion::PleHist, - vec![0xa5; if ple { z.ple } else { 0 }], - ); + mem.put(StateRegion::PleHist, vec![0xa5; if ple { z.ple } else { 0 }]); first.register(&mut mem, KvLayer::Main(0), Some(0)); last.register(&mut mem, KvLayer::Main(1), Some(1)); draft.register(&mut mem, KvLayer::Draft, None); @@ -41,11 +33,7 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { has_ple_hist: ple, ..Default::default() }, - qsa: if zero_qsa { - Vec::new() - } else { - vec![first.st.clone(), last.st.clone()] - }, + qsa: if zero_qsa { Vec::new() } else { vec![first.st.clone(), last.st.clone()] }, }; let n_qsa = g.n_qsa_layers() as usize; let checkpoint = |tokens: usize| { @@ -74,64 +62,36 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { image.kv.push(last.image(&g, true)); } image.kv.push(draft.image(&g, false)); - snapshot_validate(&image, &ss, &g, &draft.st) - .expect("complete image validates without a device"); + snapshot_validate(&image, &ss, &g, &draft.st).expect("complete image validates without a device"); let view = ConversationView { ids: &image.live.ids, images: &image.live.imgs, checkpoints: &image.checkpoints, cvec: true, }; - let estimate = - snapshot_bytes(&view, &ss, &g, &draft.st).expect("capture estimate works without a device"); - assert_eq!( - estimate, - image.bytes(), - "estimate covers checkpoint/indexer/spare payloads" - ); + let estimate = snapshot_bytes(&view, &ss, &g, &draft.st).expect("capture estimate works without a device"); + assert_eq!(estimate, image.bytes(), "estimate covers checkpoint/indexer/spare payloads"); let snapshot_regions = |mem: &HostMemory| -> Vec<(StateRegion, Vec)> { let mut all: Vec<_> = mem.regions.iter().map(|(k, v)| (*k, v.clone())).collect(); all.sort_by_key(|(k, _)| format!("{k:?}")); all }; let pristine = snapshot_regions(&mem); - let unchanged = - |mem: &HostMemory| snapshot_regions(mem) == pristine && mem.ple_prev == [-1, -1]; + let unchanged = |mem: &HostMemory| snapshot_regions(mem) == pristine && mem.ple_prev == [-1, -1]; let reject = |mem: &mut HostMemory, mutate: &dyn Fn(&mut SavedConversation), label: &str| { let mut bad = image.clone(); mutate(&mut bad); - assert!( - matches!( - snapshot_restore(&bad, &ss, &g, &draft.st, mem), - RestoreOutcome::Invalid(_) - ), - "{label}" - ); - assert!( - unchanged(mem), - "invalid restore did not touch any layer or running-state buffer ({label})" - ); - assert_eq!( - mem.copy_calls + mem.sync_calls, - 0, - "invalid restore performs no device calls ({label})" - ); + assert!(matches!(snapshot_restore(&bad, &ss, &g, &draft.st, mem), RestoreOutcome::Invalid(_)), "{label}"); + assert!(unchanged(mem), "invalid restore did not touch any layer or running-state buffer ({label})"); + assert_eq!(mem.copy_calls + mem.sync_calls, 0, "invalid restore performs no device calls ({label})"); }; reject( &mut mem, &|s| s.kv.last_mut().unwrap().k.pop_back().unwrap(), "late draft corruption rejected before first layer write", ); - reject( - &mut mem, - &|s| s.geometry[16] = 128, - "different expert geometry rejected", - ); - reject( - &mut mem, - &|s| s.live.stage_parts.push(Default::default()), - "layer-split live state rejected before writes", - ); + reject(&mut mem, &|s| s.geometry[16] = 128, "different expert geometry rejected"); + reject(&mut mem, &|s| s.live.stage_parts.push(Default::default()), "layer-split live state rejected before writes"); reject( &mut mem, &|s| s.checkpoints[0].stage_parts.push(Default::default()), @@ -158,42 +118,14 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { }, "bad retained checkpoint rejected", ); - reject( - &mut mem, - &|s| s.checkpoints.last_mut().unwrap().ids[0] = 99, - "foreign checkpoint prefix rejected", - ); - reject( - &mut mem, - &|s| s.checkpoints.last_mut().unwrap().imgs[0].hash += 1, - "foreign checkpoint image rejected", - ); - reject( - &mut mem, - &|s| s.live.imgs[0].start = -1, - "negative image position rejected", - ); - reject( - &mut mem, - &|s| s.live.ids[0] = -1, - "negative live token rejected", - ); - reject( - &mut mem, - &|s| s.live.ple.push(0), - "PLE size/enabled mismatch rejected", - ); - reject( - &mut mem, - &|s| s.live.tails.push(0), - "tail size/zero-QSA mismatch rejected", - ); + reject(&mut mem, &|s| s.checkpoints.last_mut().unwrap().ids[0] = 99, "foreign checkpoint prefix rejected"); + reject(&mut mem, &|s| s.checkpoints.last_mut().unwrap().imgs[0].hash += 1, "foreign checkpoint image rejected"); + reject(&mut mem, &|s| s.live.imgs[0].start = -1, "negative image position rejected"); + reject(&mut mem, &|s| s.live.ids[0] = -1, "negative live token rejected"); + reject(&mut mem, &|s| s.live.ple.push(0), "PLE size/enabled mismatch rejected"); + reject(&mut mem, &|s| s.live.tails.push(0), "tail size/zero-QSA mismatch rejected"); if !zero_qsa { - reject( - &mut mem, - &|s| s.kv[1].pooled.pop_back().unwrap(), - "late indexer spare row corruption rejected", - ); + reject(&mut mem, &|s| s.kv[1].pooled.pop_back().unwrap(), "late indexer spare row corruption rejected"); reject( &mut mem, &|s| { @@ -210,15 +142,8 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { ); let mut without = ss.clone(); without.qsa.clear(); - assert!( - snapshot_validate(&image, &without, &g, &draft.st).is_err(), - "missing QSA targets rejected" - ); - reject( - &mut mem, - &|s| s.layer_lo = 4, - "snapshot from another layer range rejected", - ); + assert!(snapshot_validate(&image, &without, &g, &draft.st).is_err(), "missing QSA targets rejected"); + reject(&mut mem, &|s| s.layer_lo = 4, "snapshot from another layer range rejected"); // #216's carve: a split stage owning layers [4, 8) holds GDN rows 3..5 and QSA ordinal 1 only. let mut stage = ss.clone(); stage.shape.layer_lo = 4; @@ -226,61 +151,27 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { stage.shape.qsa_ord0 = 1; stage.shape.qsa_alloc = 1; let zs = session_sizes(&g, &stage).unwrap(); - assert!( - zs.gdn == z.gdn / 6 * 3 && zs.tail == z.tail, - "carved session sizes cover the owned rows only" - ); - assert!( - checkpoint_validate(&image.live, &stage, &g).is_err(), - "whole-model checkpoint rejected by a carve" - ); + assert!(zs.gdn == z.gdn / 6 * 3 && zs.tail == z.tail, "carved session sizes cover the owned rows only"); + assert!(checkpoint_validate(&image.live, &stage, &g).is_err(), "whole-model checkpoint rejected by a carve"); let mut part = image.live.clone(); part.gdn.resize(zs.gdn, 0); part.tails.resize(zs.tail, 0); part.dead.resize(zs.dead, 0); part.block_pos.resize(zs.block_pos, 0); checkpoint_validate(&part, &stage, &g).expect("carve-sized checkpoint validates"); - assert!( - snapshot_validate(&image, &stage, &g, &draft.st).is_err(), - "whole-model snapshot rejected by a carve" - ); + assert!(snapshot_validate(&image, &stage, &g, &draft.st).is_err(), "whole-model snapshot rejected by a carve"); stage.shape.qsa_alloc = 2; - assert!( - session_sizes(&g, &stage).is_err(), - "carve past the last QSA ordinal rejected" - ); + assert!(session_sizes(&g, &stage).is_err(), "carve past the last QSA ordinal rejected"); stage.shape.qsa_alloc = 1; stage.shape.gdn_alloc = 7; - assert!( - session_sizes(&g, &stage).is_err(), - "carve past the GDN rows rejected" - ); + assert!(session_sizes(&g, &stage).is_err(), "carve past the GDN rows rejected"); } - let bad = ModelGeometry { - ssm_state_size: i64::MAX, - ..g - }; - assert!( - state_sizes(&bad).is_err(), - "running-state arithmetic overflow rejected" - ); - let bad = ModelGeometry { - qsa_interval: 0, - ..g - }; - assert!( - state_sizes(&bad).is_err(), - "zero layer interval rejected before division" - ); - let bad = ModelGeometry { - n_head_kv: i64::MAX, - ..g - }; - assert_eq!( - kv_bytes(&draft.st, &bad, 9, false), - 0, - "KV byte overflow rejected" - ); + let bad = ModelGeometry { ssm_state_size: i64::MAX, ..g }; + assert!(state_sizes(&bad).is_err(), "running-state arithmetic overflow rejected"); + let bad = ModelGeometry { qsa_interval: 0, ..g }; + assert!(state_sizes(&bad).is_err(), "zero layer interval rejected before division"); + let bad = ModelGeometry { n_head_kv: i64::MAX, ..g }; + assert_eq!(kv_bytes(&draft.st, &bad, 9, false), 0, "KV byte overflow rejected"); // Fault injection through the host transfer backend. let reset = |mem: &mut HostMemory| { @@ -294,52 +185,31 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { reset(&mut mem); mem.fail_sync = 1; assert!( - matches!( - snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::TransferFailed(_) - ), + matches!(snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), RestoreOutcome::TransferFailed(_)), "pre-transfer synchronization failure is fatal" ); - assert!( - mem.copy_calls == 0 && unchanged(&mem), - "pre-sync failure did not mutate state" - ); + assert!(mem.copy_calls == 0 && unchanged(&mem), "pre-sync failure did not mutate state"); reset(&mut mem); mem.fail_copy = 1; assert!( - matches!( - snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::TransferFailed(_) - ), + matches!(snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), RestoreOutcome::TransferFailed(_)), "first transfer failure is fatal" ); assert!(unchanged(&mem), "first-copy failure did not mutate state"); reset(&mut mem); mem.fail_copy = 2; assert!( - matches!( - snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::TransferFailed(_) - ), + matches!(snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), RestoreOutcome::TransferFailed(_)), "partial transfer failure is fatal, not an invalid-image fallback" ); - assert!( - !unchanged(&mem), - "fault fixture genuinely produced partial state" - ); + assert!(!unchanged(&mem), "fault fixture genuinely produced partial state"); reset(&mut mem); mem.fail_sync = 2; assert!( - matches!( - snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::TransferFailed(_) - ), + matches!(snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), RestoreOutcome::TransferFailed(_)), "post-transfer synchronization failure is fatal" ); - assert!( - mem.copy_calls > 0 && !unchanged(&mem), - "post-sync failure occurred after state writes" - ); + assert!(mem.copy_calls > 0 && !unchanged(&mem), "post-sync failure occurred after state writes"); reset(&mut mem); assert_eq!( snapshot_restore(&image, &ss, &g, &draft.st, &mut mem), @@ -348,48 +218,18 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { ); assert_eq!(mem.get(StateRegion::Gdn), &image.live.gdn[..]); assert_eq!(mem.get(StateRegion::PleHist), &image.live.ple[..]); - assert_eq!( - mem.ple_prev, - [8, 9], - "successful restore publishes correct running state and PLE window" - ); - kv_verify( - image.kv.last().unwrap(), - KvLayer::Draft, - &draft.st, - &g, - 9, - false, - &mut mem, - ) - .expect("read-back verifies complete draft payload"); + assert_eq!(mem.ple_prev, [8, 9], "successful restore publishes correct running state and PLE window"); + kv_verify(image.kv.last().unwrap(), KvLayer::Draft, &draft.st, &g, 9, false, &mut mem) + .expect("read-back verifies complete draft payload"); mem.get_mut(kv_region(KvLayer::Draft, KvPool::K, false))[0] ^= 1; assert!( - kv_verify( - image.kv.last().unwrap(), - KvLayer::Draft, - &draft.st, - &g, - 9, - false, - &mut mem - ) - .is_err(), + kv_verify(image.kv.last().unwrap(), KvLayer::Draft, &draft.st, &g, 9, false, &mut mem).is_err(), "read-back detects corrupted draft byte" ); mem.get_mut(kv_region(KvLayer::Draft, KvPool::K, false))[0] ^= 1; mem.fail_copy = mem.copy_calls + 1; assert!( - kv_verify( - image.kv.last().unwrap(), - KvLayer::Draft, - &draft.st, - &g, - 9, - false, - &mut mem - ) - .is_err(), + kv_verify(image.kv.last().unwrap(), KvLayer::Draft, &draft.st, &g, 9, false, &mut mem).is_err(), "read-back transfer failure is not a successful fingerprint" ); reset(&mut mem); @@ -400,36 +240,16 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { checkpoints: &image.checkpoints, cvec: true, }; - let full = snapshot_save( - &live_view, - &ss, - &g, - &draft.st, - &mut mem, - Default::default(), - None, - ) - .expect("full capture through host transfer backend"); + let full = snapshot_save(&live_view, &ss, &g, &draft.st, &mut mem, Default::default(), None) + .expect("full capture through host transfer backend"); let full_copies = mem.copied_bytes; - let reuse = ConversationKvReuse { - kv: full.kv.clone(), - captured_tokens: 9, - unchanged_tokens: 9, - }; + let reuse = ConversationKvReuse { kv: full.kv.clone(), captured_tokens: 9, unchanged_tokens: 9 }; let peak = snapshot_capture_bytes(&reuse, &live_view, &ss, &g, &draft.st) .expect("incremental capture admission without transfers"); mem.copied_bytes = 0; let mut reused = 0; - let incremental = snapshot_save( - &live_view, - &ss, - &g, - &draft.st, - &mut mem, - reuse, - Some(&mut reused), - ) - .expect("incremental capture through host backend"); + let incremental = snapshot_save(&live_view, &ss, &g, &draft.st, &mut mem, reuse, Some(&mut reused)) + .expect("incremental capture through host backend"); assert!( reused > 0 && mem.copied_bytes + reused == full_copies, "reused byte count measures transfers actually omitted" @@ -439,16 +259,9 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { "running state refreshed within admitted allocation" ); for i in 0..full.kv.len() { - assert!( - equal(&incremental.kv[i], &full.kv[i]), - "incremental and full capture agree across every payload" - ); + assert!(equal(&incremental.kv[i], &full.kv[i]), "incremental and full capture agree across every payload"); } - let mut malformed = ConversationKvReuse { - kv: full.kv.clone(), - captured_tokens: 9, - unchanged_tokens: 9, - }; + let mut malformed = ConversationKvReuse { kv: full.kv.clone(), captured_tokens: 9, unchanged_tokens: 9 }; malformed.kv.last_mut().unwrap().k.pop_back().unwrap(); mem.copy_calls = 0; mem.sync_calls = 0; @@ -456,15 +269,8 @@ pub(super) fn fixture(format: i32, experts: i64, zero_qsa: bool, ple: bool) { snapshot_capture_bytes(&malformed, &live_view, &ss, &g, &draft.st).is_err(), "malformed retained draft rejected before admission" ); - assert!( - mem.copy_calls == 0 && mem.sync_calls == 0, - "invalid retained storage performs no device calls" - ); - let reuse = ConversationKvReuse { - kv: full.kv.clone(), - captured_tokens: 9, - unchanged_tokens: 9, - }; + assert!(mem.copy_calls == 0 && mem.sync_calls == 0, "invalid retained storage performs no device calls"); + let reuse = ConversationKvReuse { kv: full.kv.clone(), captured_tokens: 9, unchanged_tokens: 9 }; mem.fail_copy = mem.copy_calls + 1; assert!( snapshot_save(&live_view, &ss, &g, &draft.st, &mut mem, reuse, None).is_err(), diff --git a/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs index 31f4d5fd..0e21a6b3 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/full_session_fn.rs @@ -3,16 +3,11 @@ #[allow(unused_imports)] use super::*; - /// `full_session` of conversation_snapshot_test.cpp. pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { let mut mem = HostMemory::new(); let main = Fixture::new(&mut mem, KvLayer::Main(0), fmt, mode); - let draft_fmt = if fmt == HYBRID || fmt == KV_VALUE_INT8 { - KV_INT8 - } else { - fmt - }; + let draft_fmt = if fmt == HYBRID || fmt == KV_VALUE_INT8 { KV_INT8 } else { fmt }; let draft = Fixture::new(&mut mem, KvLayer::Draft, draft_fmt, 2); let mut g = main.g; g.n_layers = 4; @@ -27,27 +22,9 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { main_st.idx_tail = true; main_st.idx_dead = true; main_st.idx_block_pos = true; - mem.put( - StateRegion::Idx { - layer: 0, - kind: IdxKind::Tail, - }, - vec![0; sizes.tail], - ); - mem.put( - StateRegion::Idx { - layer: 0, - kind: IdxKind::Dead, - }, - vec![0; sizes.dead], - ); - mem.put( - StateRegion::Idx { - layer: 0, - kind: IdxKind::BlockPos, - }, - vec![0; sizes.block_pos], - ); + mem.put(StateRegion::Idx { layer: 0, kind: IdxKind::Tail }, vec![0; sizes.tail]); + mem.put(StateRegion::Idx { layer: 0, kind: IdxKind::Dead }, vec![0; sizes.dead]); + mem.put(StateRegion::Idx { layer: 0, kind: IdxKind::BlockPos }, vec![0; sizes.block_pos]); let ss = SessionSpec { shape: SessionShape { max_cells: 96, @@ -64,15 +41,9 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { let images: Vec = Vec::new(); let spare = |mem: &mut HostMemory, ids_len: usize| { // A real indexer maintains its spare pooled row as a copy of idx_dead. - let dead = mem - .get(StateRegion::Idx { - layer: 0, - kind: IdxKind::Dead, - }) - .to_vec(); + let dead = mem.get(StateRegion::Idx { layer: 0, kind: IdxKind::Dead }).to_vec(); let at = (ids_len / 4) * g.idx_key_dim as usize * 4; - mem.get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + dead.len()] - .copy_from_slice(&dead); + mem.get_mut(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + dead.len()].copy_from_slice(&dead); }; let fill = |mem: &mut HostMemory, salt: u8, ids_len: usize| { main.fill(mem, salt); @@ -80,62 +51,32 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { for region in [ StateRegion::Gdn, StateRegion::PleHist, - StateRegion::Idx { - layer: 0, - kind: IdxKind::Tail, - }, - StateRegion::Idx { - layer: 0, - kind: IdxKind::Dead, - }, - StateRegion::Idx { - layer: 0, - kind: IdxKind::BlockPos, - }, + StateRegion::Idx { layer: 0, kind: IdxKind::Tail }, + StateRegion::Idx { layer: 0, kind: IdxKind::Dead }, + StateRegion::Idx { layer: 0, kind: IdxKind::BlockPos }, ] { mem.get_mut(region).fill(salt); } spare(mem, ids_len); }; fill(&mut mem, 13, ids.len()); - let mut checkpoint = ConversationCheckpoint { - ids: ids[..3].to_vec(), - ..Default::default() - }; + let mut checkpoint = ConversationCheckpoint { ids: ids[..3].to_vec(), ..Default::default() }; checkpoint_save(&mut checkpoint, &ss, &g, &mut mem).expect("save complete running checkpoint"); checkpoint.used = 17; let checkpoints = vec![checkpoint]; let save = |mem: &mut HostMemory, ids: &[i32]| { - snapshot_save( - &mk_view(ids, &images, &checkpoints), - &ss, - &g, - &draft.st, - mem, - Default::default(), - None, - ) + snapshot_save(&mk_view(ids, &images, &checkpoints), &ss, &g, &draft.st, mem, Default::default(), None) }; - let estimate = - snapshot_bytes(&mk_view(&ids, &images, &checkpoints), &ss, &g, &draft.st).unwrap(); + let estimate = snapshot_bytes(&mk_view(&ids, &images, &checkpoints), &ss, &g, &draft.st).unwrap(); let a = save(&mut mem, &ids).expect("capture complete A"); - assert_eq!( - a.checkpoints[0].used, 17, - "upstream checkpoint LRU stamp survives capture" - ); + assert_eq!(a.checkpoints[0].used, 17, "upstream checkpoint LRU stamp survives capture"); fill(&mut mem, 177, ids.len()); let b = save(&mut mem, &ids).expect("capture complete B"); - assert_ne!( - a.live.dead, b.live.dead, - "different opening-state spare keys in regression fixture" - ); + assert_ne!(a.live.dead, b.live.dead, "different opening-state spare keys in regression fixture"); let mut bad = a.clone(); bad.kv.last_mut().unwrap().k.pop_back().unwrap(); assert!( - matches!( - snapshot_restore(&bad, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::Invalid(_) - ), + matches!(snapshot_restore(&bad, &ss, &g, &draft.st, &mut mem), RestoreOutcome::Invalid(_)), "reject invalid late draft before any main-layer write" ); let restored = save(&mut mem, &ids).expect("capture B after refused restore"); @@ -146,11 +87,7 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { && equal(&restored.kv[1], &b.kv[1]), "refusal preserves all tested state" ); - assert_eq!( - snapshot_restore(&a, &ss, &g, &draft.st, &mut mem), - RestoreOutcome::Restored, - "restore complete A" - ); + assert_eq!(snapshot_restore(&a, &ss, &g, &draft.st, &mut mem), RestoreOutcome::Restored, "restore complete A"); let restored = save(&mut mem, &ids).expect("capture restored A"); assert!( restored.live.gdn == a.live.gdn @@ -163,24 +100,14 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { "whole-session A/B/A exactness including spare key" ); assert_eq!(mem.ple_prev, [64, 65], "PLE token window reconstructed"); - let observation = Observation { - estimate, - a: a.clone(), - b: b.clone(), - restored, - ple_prev: mem.ple_prev, - }; + let observation = Observation { estimate, a: a.clone(), b: b.clone(), restored, ple_prev: mem.ple_prev }; for dirty in [65i64, 3, 0] { assert_eq!( snapshot_restore(&a, &ss, &g, &draft.st, &mut mem), RestoreOutcome::Restored, "restore growth fixture base" ); - let reuse = ConversationKvReuse { - kv: a.kv.clone(), - captured_tokens: 65, - unchanged_tokens: dirty, - }; + let reuse = ConversationKvReuse { kv: a.kv.clone(), captured_tokens: 65, unchanged_tokens: dirty }; let original = reuse.kv[0].v.first_address(); main.fill_after(&mut mem, 91, dirty); draft.fill_after(&mut mem, 91, (dirty - 1).max(0)); @@ -191,14 +118,8 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { } spare(&mut mem, ids.len()); let fresh = save(&mut mem, &ids).expect("full capture reference after growth or rewind"); - let peak = snapshot_capture_bytes( - &reuse, - &mk_view(&ids, &images, &checkpoints), - &ss, - &g, - &draft.st, - ) - .expect("admit incremental capture peak"); + let peak = snapshot_capture_bytes(&reuse, &mk_view(&ids, &images, &checkpoints), &ss, &g, &draft.st) + .expect("admit incremental capture peak"); let mut reused = 0usize; let incremental = snapshot_save( &mk_view(&ids, &images, &checkpoints), @@ -210,10 +131,7 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { Some(&mut reused), ) .expect("capture with retained pages"); - assert!( - incremental.bytes() <= peak, - "incremental allocation stays within admitted bound" - ); + assert!(incremental.bytes() <= peak, "incremental allocation stays within admitted bound"); assert!( incremental.live.gdn == fresh.live.gdn && incremental.live.ple == fresh.live.ple @@ -222,41 +140,20 @@ pub(super) fn full_session(fmt: i32, mode: i32, experts: i64) -> Observation { && equal(&incremental.kv[1], &fresh.kv[1]), "incremental capture equals full capture after growth or rewind" ); - assert_eq!( - dirty >= 4, - reused > 0, - "only complete unchanged pages or rows are retained" - ); - assert_eq!( - incremental.kv[0].v.first_address(), - original, - "growth never reallocates the retained payload" - ); + assert_eq!(dirty >= 4, reused > 0, "only complete unchanged pages or rows are retained"); + assert_eq!(incremental.kv[0].v.first_address(), original, "growth never reallocates the retained payload"); assert_eq!( snapshot_restore(&incremental, &ss, &g, &draft.st, &mut mem), RestoreOutcome::Restored, "restore segmented incremental snapshot" ); - kv_verify( - incremental.kv.last().unwrap(), - KvLayer::Draft, - &draft.st, - &g, - 70, - false, - &mut mem, - ) - .expect("incremental draft authoritative and ring read-back"); + kv_verify(incremental.kv.last().unwrap(), KvLayer::Draft, &draft.st, &g, 70, false, &mut mem) + .expect("incremental draft authoritative and ring read-back"); ids.truncate(65); } - checkpoint_restore(&a.checkpoints[0], &ss, &g, &mut mem) - .expect("restore early running checkpoint"); - let spare_row = - mem.get(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[..sizes.dead].to_vec(); - assert_eq!( - spare_row, a.checkpoints[0].dead, - "checkpoint rebuilds spare row over a later completed block" - ); + checkpoint_restore(&a.checkpoints[0], &ss, &g, &mut mem).expect("restore early running checkpoint"); + let spare_row = mem.get(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[..sizes.dead].to_vec(); + assert_eq!(spare_row, a.checkpoints[0].dead, "checkpoint rebuilds spare row over a later completed block"); assert_eq!(mem.ple_prev, [2, 3], "checkpoint PLE token window"); observation } diff --git a/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs index b7d72304..f0cb2f4a 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/golden_state_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // --------------------------------------------------------------------------------------------------------------- // Differential tests against the ORIGINAL C++ (golden/gen_state_golden.cpp). @@ -30,75 +29,30 @@ pub(super) fn assert_kv(json: &serde_json::Value, k: &ConversationKv, ctx: &str) let n = |key: &str| json[key].as_i64().unwrap(); assert_eq!(i64::from(k.format), n("format"), "{ctx}: format"); assert_eq!( - [ - k.cells, - k.heads, - k.head_dim, - k.page_size, - k.pooled_rows, - k.idx_dim - ], - [ - n("cells"), - n("heads"), - n("head_dim"), - n("page_size"), - n("pooled_rows"), - n("idx_dim") - ], + [k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim], + [n("cells"), n("heads"), n("head_dim"), n("page_size"), n("pooled_rows"), n("idx_dim")], "{ctx}: geometry fields" ); assert_eq!(k.bytes() as i64, n("bytes"), "{ctx}: bytes"); - let sizes: Vec = json["sizes"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_i64().unwrap()) - .collect(); + let sizes: Vec = json["sizes"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); let got: Vec = k.buffers().iter().map(|b| b.size() as i64).collect(); assert_eq!(got, sizes, "{ctx}: payload sizes"); - let hashes: Vec<&str> = json["hash"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_str().unwrap()) - .collect(); + let hashes: Vec<&str> = json["hash"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); let got: Vec = k.buffers().into_iter().map(fnv_buf).collect(); assert_eq!(got, hashes, "{ctx}: payload hashes"); } pub(super) fn assert_checkpoint(json: &serde_json::Value, c: &ConversationCheckpoint, ctx: &str) { - assert_eq!( - c.ids.len() as u64, - json["ids"].as_u64().unwrap(), - "{ctx}: ids" - ); + assert_eq!(c.ids.len() as u64, json["ids"].as_u64().unwrap(), "{ctx}: ids"); assert_eq!(c.used, json["used"].as_u64().unwrap(), "{ctx}: used"); - assert_eq!( - c.bytes() as u64, - json["bytes"].as_u64().unwrap(), - "{ctx}: bytes" - ); + assert_eq!(c.bytes() as u64, json["bytes"].as_u64().unwrap(), "{ctx}: bytes"); let got = [&c.gdn, &c.ple, &c.tails, &c.dead, &c.block_pos].map(|v| fnv(v.iter().copied())); - let want: Vec<&str> = json["hash"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_str().unwrap()) - .collect(); + let want: Vec<&str> = json["hash"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); assert_eq!(got.to_vec(), want, "{ctx}: running-state hashes"); } pub(super) fn assert_image(json: &serde_json::Value, s: &SavedConversation, ctx: &str) { - assert_eq!( - s.bytes() as u64, - json["bytes"].as_u64().unwrap(), - "{ctx}: image bytes" - ); + assert_eq!(s.bytes() as u64, json["bytes"].as_u64().unwrap(), "{ctx}: image bytes"); assert_checkpoint(&json["live"], &s.live, &format!("{ctx} live")); - assert_checkpoint( - &json["checkpoint"], - &s.checkpoints[0], - &format!("{ctx} checkpoint"), - ); + assert_checkpoint(&json["checkpoint"], &s.checkpoints[0], &format!("{ctx} checkpoint")); let kv = json["kv"].as_array().unwrap(); assert_eq!(kv.len(), s.kv.len(), "{ctx}: layer count"); for (i, (j, k)) in kv.iter().zip(&s.kv).enumerate() { diff --git a/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs b/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs index 6fd668ca..7671460e 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/impl_pools.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Pools { pub(super) fn new(g: &ModelGeometry, format: i32) -> Self { let mut st = QsaDesc { @@ -15,17 +14,9 @@ impl Pools { kv_q4: format == 2, ..Default::default() }; - let per = if format == 2 { - q4_per_head(g) - } else { - g.head_dim as usize * if format == 1 { 1 } else { 2 } - }; + let per = if format == 2 { q4_per_head(g) } else { g.head_dim as usize * if format == 1 { 1 } else { 2 } }; let mut data = vec![vec![0xa5u8; 96 * g.n_head_kv as usize * per]; 2]; - let scale = if format == 1 { - 96 * g.n_head_kv as usize * (g.head_dim as usize / 64) * 2 - } else { - 0 - }; + let scale = if format == 1 { 96 * g.n_head_kv as usize * (g.head_dim as usize / 64) * 2 } else { 0 }; data.push(vec![0xa5; scale]); data.push(vec![0xa5; scale]); data.push(vec![0xa5; 26 * g.idx_key_dim as usize * 4]); @@ -57,27 +48,9 @@ impl Pools { mem.put(kv_region(layer, pool, false), self.data[i].clone()); } if let Some(j) = main_index { - mem.put( - StateRegion::Idx { - layer: j, - kind: IdxKind::Tail, - }, - self.data[5].clone(), - ); - mem.put( - StateRegion::Idx { - layer: j, - kind: IdxKind::Dead, - }, - self.data[6].clone(), - ); - mem.put( - StateRegion::Idx { - layer: j, - kind: IdxKind::BlockPos, - }, - self.data[7].clone(), - ); + mem.put(StateRegion::Idx { layer: j, kind: IdxKind::Tail }, self.data[5].clone()); + mem.put(StateRegion::Idx { layer: j, kind: IdxKind::Dead }, self.data[6].clone()); + mem.put(StateRegion::Idx { layer: j, kind: IdxKind::BlockPos }, self.data[7].clone()); } } @@ -96,9 +69,7 @@ impl Pools { k.v.resize(self.data[0].len() / 8, 13).unwrap(); k.k_scale.resize(self.data[2].len() / 8, 13).unwrap(); k.v_scale.resize(self.data[2].len() / 8, 13).unwrap(); - k.pooled - .resize(k.pooled_rows as usize * g.idx_key_dim as usize * 4, 13) - .unwrap(); + k.pooled.resize(k.pooled_rows as usize * g.idx_key_dim as usize * 4, 13).unwrap(); k } } diff --git a/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs index ecb66f57..08801851 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/kv_level_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn kv_level(fmt: i32, mode: i32) { let mut mem = HostMemory::new(); let mut f = Fixture::new(&mut mem, KvLayer::Main(0), fmt, mode); @@ -11,11 +10,7 @@ pub(super) fn kv_level(fmt: i32, mode: i32) { if fmt == HYBRID { for unsupported in [1, 2] { f.st.kv_mode = unsupported; - assert_eq!( - kv_bytes(&f.st, &f.g, 9, true), - 0, - "hybrid streaming/ring rejected without block-mover abort" - ); + assert_eq!(kv_bytes(&f.st, &f.g, 9, true), 0, "hybrid streaming/ring rejected without block-mover abort"); let mut invalid = ConversationKv::default(); assert!( kv_save(&mut invalid, layer, &f.st, &f.g, 9, true, 0, &mut mem, None).is_err(), @@ -29,29 +24,14 @@ pub(super) fn kv_level(fmt: i32, mode: i32) { let mut invalid = ConversationKv::default(); let index = index_for(mode); assert!( - kv_save( - &mut invalid, - layer, - &f.st, - &f.g, - bad, - index, - 0, - &mut mem, - None - ) - .is_err(), + kv_save(&mut invalid, layer, &f.st, &f.g, bad, index, 0, &mut mem, None).is_err(), "reject invalid save extent before allocation" ); assert!( kv_restore(&invalid, layer, &f.st, &f.g, bad, index, &mut mem).is_err(), "reject invalid restore extent before copying" ); - assert_eq!( - kv_bytes(&f.st, &f.g, bad, index), - 0, - "invalid extent cannot overflow byte estimate" - ); + assert_eq!(kv_bytes(&f.st, &f.g, bad, index), 0, "invalid extent cannot overflow byte estimate"); } for upto in [0i64, 1, 3, 4, 5, 63, 64, 65, 96] { let index = index_for(mode); @@ -70,40 +50,19 @@ pub(super) fn kv_level(fmt: i32, mode: i32) { "reject K+V snapshot in V-only state" ); } - assert_eq!( - a.bytes(), - kv_bytes(&f.st, &f.g, upto, index), - "size estimate equals snapshot payload" - ); + assert_eq!(a.bytes(), kv_bytes(&f.st, &f.g, upto, index), "size estimate equals snapshot payload"); f.fill(&mut mem, 177); let mut b = ConversationKv::default(); kv_save(&mut b, layer, &f.st, &f.g, upto, index, 0, &mut mem, None).expect("save B"); assert!(upto == 0 || !equal(&a, &b), "fixture changes state"); kv_restore(&a, layer, &f.st, &f.g, upto, index, &mut mem).expect("restore A over B"); let mut restored = ConversationKv::default(); - kv_save( - &mut restored, - layer, - &f.st, - &f.g, - upto, - index, - 0, - &mut mem, - None, - ) - .expect("read back restored A"); - assert!( - equal(&a, &restored), - "A/B/A byte-exact K/V and indexer state" - ); + kv_save(&mut restored, layer, &f.st, &f.g, upto, index, 0, &mut mem, None).expect("read back restored A"); + assert!(equal(&a, &restored), "A/B/A byte-exact K/V and indexer state"); kv_verify(&a, layer, &f.st, &f.g, upto, index, &mut mem) .expect("verify restored authoritative and resident bytes without rewriting them"); if mode == 1 { - assert!( - mem.page_tables[&layer].iter().all(|&x| x == -1), - "stale VRAM pages invalidated" - ); + assert!(mem.page_tables[&layer].iter().all(|&x| x == -1), "stale VRAM pages invalidated"); } if mode == 2 && upto > 0 { let b1 = (upto + 3) / 4; @@ -116,45 +75,24 @@ pub(super) fn kv_level(fmt: i32, mode: i32) { 512 }; let code_block = 4 * f.g.n_head_kv as usize * per; - let (pool, buffer) = if fmt == KV_VALUE_INT8 { - (KvPool::V, &a.v) - } else { - (KvPool::K, &a.k) - }; + let (pool, buffer) = if fmt == KV_VALUE_INT8 { (KvPool::V, &a.v) } else { (KvPool::K, &a.k) }; for page in b0..b1 { let at = (page % f.st.n_slots) as usize * code_block; let got = mem.get(kv_region(layer, pool, true))[at..at + code_block].to_vec(); let mut expected = vec![0u8; code_block]; - assert!( - buffer.read(&mut expected, page as usize * code_block), - "read segmented expected draft page" - ); + assert!(buffer.read(&mut expected, page as usize * code_block), "read segmented expected draft page"); assert_eq!(got, expected, "draft ring contains restored pages"); } } let mut bad = a.clone(); bad.head_dim += 1; - assert!( - kv_restore(&bad, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), - "reject incompatible geometry" - ); + assert!(kv_restore(&bad, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), "reject incompatible geometry"); if fmt == KV_INT8 { // #293: INT8 K/V saved through the Hadamard rotation never restores // into a state without it, nor the reverse. f.st.kv_rot = true; let mut rotated = ConversationKv::default(); - kv_save( - &mut rotated, - layer, - &f.st, - &f.g, - upto, - index, - 0, - &mut mem, - None, - ) - .expect("save rotated INT8"); + kv_save(&mut rotated, layer, &f.st, &f.g, upto, index, 0, &mut mem, None).expect("save rotated INT8"); assert!( kv_restore(&a, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), "unrotated image into a rotated state rejected" @@ -164,16 +102,12 @@ pub(super) fn kv_level(fmt: i32, mode: i32) { kv_restore(&rotated, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), "rotated image into an unrotated state rejected" ); - kv_restore(&a, layer, &f.st, &f.g, upto, index, &mut mem) - .expect("unrotated image still restores"); + kv_restore(&a, layer, &f.st, &f.g, upto, index, &mut mem).expect("unrotated image still restores"); } if !a.k.is_empty() { bad = a.clone(); bad.k.pop_back().unwrap(); - assert!( - kv_restore(&bad, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), - "reject malformed payload" - ); + assert!(kv_restore(&bad, layer, &f.st, &f.g, upto, index, &mut mem).is_err(), "reject malformed payload"); } } } diff --git a/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs b/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs index 67c3e676..f521cd51 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/kv_region_fn.rs @@ -3,13 +3,8 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn kv_region(layer: KvLayer, pool: KvPool, resident: bool) -> StateRegion { - StateRegion::Kv { - layer, - pool, - resident, - } + StateRegion::Kv { layer, pool, resident } } pub(super) fn mk_view<'a>( @@ -17,20 +12,11 @@ pub(super) fn mk_view<'a>( images: &'a [ConversationImageKey], checkpoints: &'a [ConversationCheckpoint], ) -> ConversationView<'a> { - ConversationView { - ids, - images, - checkpoints, - cvec: true, - } + ConversationView { ids, images, checkpoints, cvec: true } } pub(super) fn equal(a: &ConversationKv, b: &ConversationKv) -> bool { - a.k == b.k - && a.v == b.v - && a.k_scale == b.k_scale - && a.v_scale == b.v_scale - && a.pooled == b.pooled + a.k == b.k && a.v == b.v && a.k_scale == b.k_scale && a.v_scale == b.v_scale && a.pooled == b.pooled } pub(super) fn q4_per_head(g: &ModelGeometry) -> usize { @@ -72,11 +58,7 @@ impl Fixture { let slot_rows = st.n_slots as usize * 4 * g.n_head_kv as usize; let scale = rows * (g.head_dim as usize / 64) * 2; let pooled = st.idx_pooled_rows as usize * g.idx_key_dim as usize * 4; - let scales = if fmt == KV_INT8 || fmt == KV_VALUE_INT8 { - scale - } else { - 0 - }; + let scales = if fmt == KV_INT8 || fmt == KV_VALUE_INT8 { scale } else { 0 }; let mut sizes = [rows * per, rows * per, scales, scales, pooled]; if st.without_key { sizes[0] = 0; @@ -90,13 +72,7 @@ impl Fixture { }; let host = mode != 0; if fmt == HYBRID { - sizes = [ - rows * per, - rows * q4_per_head(&g), - rows * (g.head_dim as usize / 64) * 2, - 0, - pooled, - ]; + sizes = [rows * per, rows * q4_per_head(&g), rows * (g.head_dim as usize / 64) * 2, 0, pooled]; st.k_q = alloc(mem, KvPool::K, false, sizes[0]); st.v_q4 = alloc(mem, KvPool::V, false, sizes[1]); st.k_scale = alloc(mem, KvPool::KScale, false, sizes[2]); @@ -137,21 +113,12 @@ impl Fixture { st.idx_pooled = alloc(mem, KvPool::Pooled, false, sizes[4]); st.page_table = true; if mode == 1 { - st.map = StreamMap { - n_blocks: st.n_pages, - n_slots: st.n_slots, - complete: true, - }; + st.map = StreamMap { n_blocks: st.n_pages, n_slots: st.n_slots, complete: true }; mem.page_tables.insert(layer, vec![5; st.n_pages as usize]); } else if mode == 2 { mem.ring_pages.insert(layer, st.n_pages as usize); } - Self { - g, - st, - layer, - sizes, - } + Self { g, st, layer, sizes } } pub(in super::super) fn source(&self, i: usize) -> StateRegion { @@ -165,10 +132,7 @@ impl Fixture { } let data = mem.get_mut(self.source(i)); for (j, byte) in data.iter_mut().enumerate() { - *byte = salt - .wrapping_add((i * 31) as u8) - .wrapping_add((j * 7) as u8) - .wrapping_add((j / 257) as u8); + *byte = salt.wrapping_add((i * 31) as u8).wrapping_add((j * 7) as u8).wrapping_add((j / 257) as u8); } } } diff --git a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs index f1bdee3f..39b34537 100644 --- a/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs +++ b/crates/engine-core/src/conversation/snapshot_tests/layer_snapshots_are_byte_exact.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn layer_snapshots_are_byte_exact_across_formats_and_residency_modes() { for fmt in [KV_F16, KV_INT8, KV_Q4, HYBRID, KV_VALUE_INT8] { @@ -56,25 +55,12 @@ fn checkpoint_save_restore_round_trips_through_host_memory() { let z = state_sizes(&g).unwrap(); let mut mem = HostMemory::new(); mem.put(StateRegion::Gdn, (0..z.gdn).map(|i| i as u8).collect()); - mem.put( - StateRegion::PleHist, - (0..z.ple).map(|i| (i * 3) as u8).collect(), - ); - for (kind, n) in [ - (IdxKind::Tail, z.tail), - (IdxKind::Dead, z.dead), - (IdxKind::BlockPos, z.block_pos), - ] { - mem.put( - StateRegion::Idx { layer: 0, kind }, - (0..n).map(|i| (i * 5 + 1) as u8).collect(), - ); + mem.put(StateRegion::PleHist, (0..z.ple).map(|i| (i * 3) as u8).collect()); + for (kind, n) in [(IdxKind::Tail, z.tail), (IdxKind::Dead, z.dead), (IdxKind::BlockPos, z.block_pos)] { + mem.put(StateRegion::Idx { layer: 0, kind }, (0..n).map(|i| (i * 5 + 1) as u8).collect()); } let pooled = Pools::new(&g, 0); - mem.put( - kv_region(KvLayer::Main(0), KvPool::Pooled, false), - vec![0; 26 * g.idx_key_dim as usize * 4], - ); + mem.put(kv_region(KvLayer::Main(0), KvPool::Pooled, false), vec![0; 26 * g.idx_key_dim as usize * 4]); let mut st = pooled.st.clone(); st.idx_pooled_rows = 26; let ss = SessionSpec { @@ -89,10 +75,7 @@ fn checkpoint_save_restore_round_trips_through_host_memory() { }, qsa: vec![st], }; - let mut c = ConversationCheckpoint { - ids: vec![5, 6, 7, 8, 9], - ..Default::default() - }; + let mut c = ConversationCheckpoint { ids: vec![5, 6, 7, 8, 9], ..Default::default() }; checkpoint_save(&mut c, &ss, &g, &mut mem).unwrap(); assert_eq!(c.gdn.len(), z.gdn); let original: Vec<_> = mem.regions.iter().map(|(k, v)| (*k, v.clone())).collect(); @@ -109,21 +92,13 @@ fn checkpoint_save_restore_round_trips_through_host_memory() { assert_eq!(mem.ple_prev, [8, 9]); let row = 5 / IDX_BLOCK as usize; let at = row * g.idx_key_dim as usize * 4; - assert_eq!( - &mem.get(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + z.dead], - &c.dead[..] - ); + assert_eq!(&mem.get(kv_region(KvLayer::Main(0), KvPool::Pooled, false))[at..at + z.dead], &c.dead[..]); } #[test] fn golden_geometry_and_carve_sizes_match_the_original() { for case in golden_state()["state_cases"].as_array().unwrap() { - let key: Vec = case["geometry"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_i64().unwrap()) - .collect(); + let key: Vec = case["geometry"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); let g = ModelGeometry { n_embd: key[0], n_layers: key[1], @@ -145,19 +120,10 @@ fn golden_geometry_and_carve_sizes_match_the_original() { n_ff: key[17], }; assert_eq!(g.key().to_vec(), key); - let sizes = |z: super::super::state::StateSizes| { - [z.gdn, z.ple, z.tail, z.dead, z.block_pos] - .map(|v| v as u64) - .to_vec() - }; - let want = |name: &str| -> Vec { - case[name] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_u64().unwrap()) - .collect() - }; + let sizes = + |z: super::super::state::StateSizes| [z.gdn, z.ple, z.tail, z.dead, z.block_pos].map(|v| v as u64).to_vec(); + let want = + |name: &str| -> Vec { case[name].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() }; let whole = state_sizes(&g); assert_eq!(whole.is_ok(), case["whole_ok"].as_bool().unwrap(), "{case}"); if let Ok(z) = whole { @@ -173,11 +139,7 @@ fn golden_geometry_and_carve_sizes_match_the_original() { qsa: Vec::new(), }; let session = session_sizes(&g, &spec); - assert_eq!( - session.is_ok(), - case["session_ok"].as_bool().unwrap(), - "{case}" - ); + assert_eq!(session.is_ok(), case["session_ok"].as_bool().unwrap(), "{case}"); if let Ok(z) = session { assert_eq!(sizes(z), want("session"), "{case}"); } @@ -197,10 +159,7 @@ fn golden_layer_layouts_and_payload_hashes_match_the_original() { case["rot"].as_i64().unwrap(), ); let upto = case["upto"].as_i64().unwrap(); - if cached - .as_ref() - .is_none_or(|c| (c.0, c.1, c.2) != (fmt, mode, rot)) - { + if cached.as_ref().is_none_or(|c| (c.0, c.1, c.2) != (fmt, mode, rot)) { let mut mem = HostMemory::new(); let mut f = Fixture::new(&mut mem, KvLayer::Main(0), fmt, mode); f.st.kv_rot = rot != 0; @@ -210,18 +169,10 @@ fn golden_layer_layouts_and_payload_hashes_match_the_original() { let (_, _, _, mem, f) = cached.as_mut().unwrap(); let index = mode != 2; let ctx = format!("fmt {fmt} mode {mode} rot {rot} upto {upto}"); - assert_eq!( - kv_bytes(&f.st, &f.g, upto, index) as u64, - case["bytes"].as_u64().unwrap(), - "{ctx}: kv_bytes" - ); + assert_eq!(kv_bytes(&f.st, &f.g, upto, index) as u64, case["bytes"].as_u64().unwrap(), "{ctx}: kv_bytes"); let mut image = ConversationKv::default(); let saved = kv_save(&mut image, f.layer, &f.st, &f.g, upto, index, 0, mem, None); - assert_eq!( - saved.is_ok(), - case["ok"].as_bool().unwrap(), - "{ctx}: save outcome" - ); + assert_eq!(saved.is_ok(), case["ok"].as_bool().unwrap(), "{ctx}: save outcome"); if saved.is_ok() { assert_kv(&case["image"], &image, &ctx); } @@ -239,29 +190,12 @@ fn golden_whole_session_snapshots_match_the_original() { ); let ctx = format!("fmt {fmt} mode {mode} experts {experts}"); let seen = full_session(fmt, mode, experts); - assert_eq!( - seen.estimate as u64, - case["estimate"].as_u64().unwrap(), - "{ctx}: snapshot_bytes" - ); + assert_eq!(seen.estimate as u64, case["estimate"].as_u64().unwrap(), "{ctx}: snapshot_bytes"); assert_image(&case["a"], &seen.a, &format!("{ctx} A")); assert_image(&case["b"], &seen.b, &format!("{ctx} B")); assert!(case["restored_ok"].as_bool().unwrap()); - assert_image( - &case["restored"], - &seen.restored, - &format!("{ctx} restored"), - ); - let ple: Vec = case["ple_prev"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_i64().unwrap()) - .collect(); - assert_eq!( - seen.ple_prev.map(i64::from).to_vec(), - ple, - "{ctx}: ple_prev" - ); + assert_image(&case["restored"], &seen.restored, &format!("{ctx} restored")); + let ple: Vec = case["ple_prev"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + assert_eq!(seen.ple_prev.map(i64::from).to_vec(), ple, "{ctx}: ple_prev"); } } diff --git a/crates/engine-core/src/conversation/state.rs b/crates/engine-core/src/conversation/state.rs index 07f5fd0e..d4d22a28 100644 --- a/crates/engine-core/src/conversation/state.rs +++ b/crates/engine-core/src/conversation/state.rs @@ -8,8 +8,8 @@ use super::cache::{ConversationCheckpoint, ConversationImageKey}; use super::checked::{add, product}; use super::model::{ - ConvError, ConvResult, IDX_BLOCK, IdxKind, KvLayer, KvPool, ModelGeometry, NG_HC_DIM, NG_HIST, - SessionSpec, StateMemory, StateRegion, fail, + ConvError, ConvResult, IDX_BLOCK, IdxKind, KvLayer, KvPool, ModelGeometry, NG_HC_DIM, NG_HIST, SessionSpec, + StateMemory, StateRegion, fail, }; /// Byte sizes of one session's running state (`ConversationStateSizes`). @@ -32,14 +32,9 @@ pub fn state_sizes(g: &ModelGeometry) -> ConvResult { } } let overflow = || ConvError("conversation snapshot: running-state byte count overflow".into()); - let recurrence = product(&[ - g.ssm_state_size as u64, - g.ssm_v_heads as u64, - g.ssm_state_size as u64, - ]) - .ok_or_else(overflow)?; - let convolution = - product(&[g.ssm_conv_channels as u64, (g.ssm_d_conv - 1) as u64]).ok_or_else(overflow)?; + let recurrence = + product(&[g.ssm_state_size as u64, g.ssm_v_heads as u64, g.ssm_state_size as u64]).ok_or_else(overflow)?; + let convolution = product(&[g.ssm_conv_channels as u64, (g.ssm_d_conv - 1) as u64]).ok_or_else(overflow)?; let mut recurrence = recurrence; if !add(&mut recurrence, convolution) { return Err(overflow()); @@ -48,13 +43,7 @@ pub fn state_sizes(g: &ModelGeometry) -> ConvResult { let ple = product(&[NG_HIST, NG_HC_DIM, 4]).ok_or_else(overflow)?; let tail = product(&[(IDX_BLOCK - 1) as u64, g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; let dead = product(&[g.idx_key_dim as u64, 4]).ok_or_else(overflow)?; - let z = StateSizes { - gdn, - ple, - tail, - dead, - block_pos: 4, - }; + let z = StateSizes { gdn, ple, tail, dead, block_pos: 4 }; for part in [z.tail, z.dead, z.block_pos] { if product(&[g.n_qsa_layers() as u64, part as u64]).is_none() { return fail("indexer byte count overflow"); @@ -81,11 +70,7 @@ pub fn session_sizes(g: &ModelGeometry, ss: &SessionSpec) -> ConvResult 0 { - z.gdn / n_gdn as usize * s.gdn_alloc as usize - } else { - 0 - }; + z.gdn = if n_gdn > 0 { z.gdn / n_gdn as usize * s.gdn_alloc as usize } else { 0 }; Ok(z) } @@ -103,15 +88,10 @@ pub fn image_keys(images: &[ConversationImageKey], tokens: usize) -> bool { /// `checkpoint_targets`: the session can hold `tokens` and owns every buffer a /// checkpoint reads or writes. -pub fn checkpoint_targets( - ss: &SessionSpec, - g: &ModelGeometry, - tokens: usize, -) -> ConvResult { +pub fn checkpoint_targets(ss: &SessionSpec, g: &ModelGeometry, tokens: usize) -> ConvResult { let z = session_sizes(g, ss)?; let s = &ss.shape; - let invalid = - || ConvError("conversation snapshot: invalid session running-state targets".into()); + let invalid = || ConvError("conversation snapshot: invalid session running-state targets".into()); if s.max_cells < 0 || tokens as u64 > s.max_cells as u64 || (z.gdn != 0 && !s.has_gdn_state) @@ -120,8 +100,7 @@ pub fn checkpoint_targets( return Err(invalid()); } for j in 0..ss.owned_qsa() { - let bad = - || ConvError("conversation snapshot: invalid indexer running-state target".into()); + let bad = || ConvError("conversation snapshot: invalid indexer running-state target".into()); let st = ss.owned(j).ok_or_else(bad)?; let block = IDX_BLOCK as u64; let pooled_bytes = product(&[tokens as u64 / block + 1, g.idx_key_dim as u64, 4]); @@ -144,25 +123,18 @@ pub fn checkpoint_targets( /// cache charges capacity), reporting allocation failure instead of aborting. pub fn exact_zeroed(n: usize) -> ConvResult> { let mut v = Vec::new(); - v.try_reserve_exact(n) - .map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; + v.try_reserve_exact(n).map_err(|_| ConvError("conversation snapshot: allocation failed".into()))?; v.resize(n, 0); Ok(v) } fn copy_error(message: String) -> ConvError { - ConvError(format!( - "conversation snapshot running-state copy: {message}" - )) + ConvError(format!("conversation snapshot running-state copy: {message}")) } /// Validate a checkpoint's payload sizes against the session that would /// restore it. No device access. -pub fn checkpoint_validate( - c: &ConversationCheckpoint, - ss: &SessionSpec, - g: &ModelGeometry, -) -> ConvResult<()> { +pub fn checkpoint_validate(c: &ConversationCheckpoint, ss: &SessionSpec, g: &ModelGeometry) -> ConvResult<()> { let z = checkpoint_targets(ss, g, c.ids.len())?; let layers = ss.owned_qsa(); let times = |n: usize| layers.checked_mul(n); @@ -185,12 +157,7 @@ fn read_into(mem: &mut dyn StateMemory, region: StateRegion, dst: &mut [u8]) -> mem.read(region, 0, dst).map_err(copy_error) } -fn write_from( - mem: &mut dyn StateMemory, - region: StateRegion, - offset: usize, - src: &[u8], -) -> ConvResult<()> { +fn write_from(mem: &mut dyn StateMemory, region: StateRegion, offset: usize, src: &[u8]) -> ConvResult<()> { if src.is_empty() { return Ok(()); } @@ -217,21 +184,9 @@ pub fn checkpoint_save( read_into(mem, StateRegion::PleHist, &mut c.ple)?; for j in 0..layers { let idx = |kind| StateRegion::Idx { layer: j, kind }; - read_into( - mem, - idx(IdxKind::Tail), - &mut c.tails[j * z.tail..(j + 1) * z.tail], - )?; - read_into( - mem, - idx(IdxKind::Dead), - &mut c.dead[j * z.dead..(j + 1) * z.dead], - )?; - read_into( - mem, - idx(IdxKind::BlockPos), - &mut c.block_pos[j * z.block_pos..(j + 1) * z.block_pos], - )?; + read_into(mem, idx(IdxKind::Tail), &mut c.tails[j * z.tail..(j + 1) * z.tail])?; + read_into(mem, idx(IdxKind::Dead), &mut c.dead[j * z.dead..(j + 1) * z.dead])?; + read_into(mem, idx(IdxKind::BlockPos), &mut c.block_pos[j * z.block_pos..(j + 1) * z.block_pos])?; } Ok(()) } @@ -249,38 +204,14 @@ pub fn checkpoint_restore( write_from(mem, StateRegion::PleHist, 0, &c.ple)?; for j in 0..ss.owned_qsa() { let idx = |kind| StateRegion::Idx { layer: j, kind }; - write_from( - mem, - idx(IdxKind::Tail), - 0, - &c.tails[j * z.tail..(j + 1) * z.tail], - )?; - write_from( - mem, - idx(IdxKind::Dead), - 0, - &c.dead[j * z.dead..(j + 1) * z.dead], - )?; - write_from( - mem, - idx(IdxKind::BlockPos), - 0, - &c.block_pos[j * z.block_pos..(j + 1) * z.block_pos], - )?; + write_from(mem, idx(IdxKind::Tail), 0, &c.tails[j * z.tail..(j + 1) * z.tail])?; + write_from(mem, idx(IdxKind::Dead), 0, &c.dead[j * z.dead..(j + 1) * z.dead])?; + write_from(mem, idx(IdxKind::BlockPos), 0, &c.block_pos[j * z.block_pos..(j + 1) * z.block_pos])?; if !c.ids.is_empty() { // The spare (moving) pooled row is reconstructed from the dead key. let row = c.ids.len() / IDX_BLOCK as usize; - let region = StateRegion::Kv { - layer: KvLayer::Main(j), - pool: KvPool::Pooled, - resident: false, - }; - write_from( - mem, - region, - row * g.idx_key_dim as usize * 4, - &c.dead[j * z.dead..(j + 1) * z.dead], - )?; + let region = StateRegion::Kv { layer: KvLayer::Main(j), pool: KvPool::Pooled, resident: false }; + write_from(mem, region, row * g.idx_key_dim as usize * 4, &c.dead[j * z.dead..(j + 1) * z.dead])?; } } let tokens = c.ids.len(); @@ -288,6 +219,5 @@ pub fn checkpoint_restore( if tokens >= 2 { c.ids[tokens - 2] } else { -1 }, if tokens >= 1 { c.ids[tokens - 1] } else { -1 }, ]); - mem.synchronize() - .map_err(|message| ConvError(format!("conversation snapshot synchronize: {message}"))) + mem.synchronize().map_err(|message| ConvError(format!("conversation snapshot synchronize: {message}"))) } diff --git a/crates/engine-core/src/conversation/testing.rs b/crates/engine-core/src/conversation/testing.rs index b7f6b51d..26d031fd 100644 --- a/crates/engine-core/src/conversation/testing.rs +++ b/crates/engine-core/src/conversation/testing.rs @@ -26,10 +26,7 @@ pub struct HostMemory { impl HostMemory { pub fn new() -> Self { - Self { - ple_prev: [-1, -1], - ..Self::default() - } + Self { ple_prev: [-1, -1], ..Self::default() } } pub fn put(&mut self, region: StateRegion, bytes: Vec) { @@ -39,15 +36,9 @@ impl HostMemory { /// Pooled indexer rows have one storage regardless of residency. fn key(region: StateRegion) -> StateRegion { match region { - StateRegion::Kv { - layer, - pool: super::model::KvPool::Pooled, - .. - } => StateRegion::Kv { - layer, - pool: super::model::KvPool::Pooled, - resident: false, - }, + StateRegion::Kv { layer, pool: super::model::KvPool::Pooled, .. } => { + StateRegion::Kv { layer, pool: super::model::KvPool::Pooled, resident: false } + } other => other, } } @@ -57,9 +48,7 @@ impl HostMemory { } pub fn get_mut(&mut self, region: StateRegion) -> &mut Vec { - self.regions - .get_mut(&Self::key(region)) - .expect("region exists") + self.regions.get_mut(&Self::key(region)).expect("region exists") } pub fn reset_counters(&mut self) { @@ -82,37 +71,21 @@ impl HostMemory { impl StateMemory for HostMemory { fn synchronize(&mut self) -> Result<(), String> { self.sync_calls += 1; - if self.sync_calls == self.fail_sync { - Err("unknown error".into()) - } else { - Ok(()) - } + if self.sync_calls == self.fail_sync { Err("unknown error".into()) } else { Ok(()) } } fn read(&mut self, region: StateRegion, offset: usize, dst: &mut [u8]) -> Result<(), String> { self.account(dst.len())?; - let source = self - .regions - .get(&Self::key(region)) - .ok_or("no such region")?; - let end = offset - .checked_add(dst.len()) - .filter(|&e| e <= source.len()) - .ok_or("read out of range")?; + let source = self.regions.get(&Self::key(region)).ok_or("no such region")?; + let end = offset.checked_add(dst.len()).filter(|&e| e <= source.len()).ok_or("read out of range")?; dst.copy_from_slice(&source[offset..end]); Ok(()) } fn write(&mut self, region: StateRegion, offset: usize, src: &[u8]) -> Result<(), String> { self.account(src.len())?; - let target = self - .regions - .get_mut(&Self::key(region)) - .ok_or("no such region")?; - let end = offset - .checked_add(src.len()) - .filter(|&e| e <= target.len()) - .ok_or("write out of range")?; + let target = self.regions.get_mut(&Self::key(region)).ok_or("no such region")?; + let end = offset.checked_add(src.len()).filter(|&e| e <= target.len()).ok_or("write out of range")?; target[offset..end].copy_from_slice(src); Ok(()) } @@ -122,11 +95,7 @@ impl StateMemory for HostMemory { } fn reset_streaming_residency(&mut self, layer: KvLayer) -> Result<(), String> { - self.page_tables - .entry(layer) - .or_default() - .iter_mut() - .for_each(|slot| *slot = -1); + self.page_tables.entry(layer).or_default().iter_mut().for_each(|slot| *slot = -1); Ok(()) } @@ -145,16 +114,8 @@ impl StateMemory for HostMemory { super::model::KvPool::KScale, super::model::KvPool::VScale, ] { - let host = StateRegion::Kv { - layer, - pool, - resident: false, - }; - let slots = StateRegion::Kv { - layer, - pool, - resident: true, - }; + let host = StateRegion::Kv { layer, pool, resident: false }; + let slots = StateRegion::Kv { layer, pool, resident: true }; let Some(source) = self.regions.get(&host).cloned() else { continue; }; diff --git a/crates/engine-core/src/memory.rs b/crates/engine-core/src/memory.rs index da4f8be7..f24d1ec3 100644 --- a/crates/engine-core/src/memory.rs +++ b/crates/engine-core/src/memory.rs @@ -11,9 +11,7 @@ const KEY: &[u8] = b"MemAvailable:"; fn fields(line: &[u8]) -> Vec<&[u8]> { // The C++ stream extraction splits on the C-locale isspace set. - line.split(|b| matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')) - .filter(|field| !field.is_empty()) - .collect() + line.split(|b| matches!(b, b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r')).filter(|field| !field.is_empty()).collect() } fn parse_kb(value: &[u8]) -> Option { diff --git a/crates/engine-core/src/prefix_cache/budget.rs b/crates/engine-core/src/prefix_cache/budget.rs index e666ea0c..01fe45e4 100644 --- a/crates/engine-core/src/prefix_cache/budget.rs +++ b/crates/engine-core/src/prefix_cache/budget.rs @@ -29,23 +29,11 @@ impl AutoBudget { /// sealed KAR memfd, the resident expert source and the pinned K/V leave only ~14 GiB available when the stack opens, /// so a generous floor would switch the cache off exactly where it is wanted.) pub const fn server(mem_available: Option) -> Self { - Self { - mem_available, - floor: 4 * GIB, - percent: 75, - cap: 96 * GIB, - min_useful: GIB, - } + Self { mem_available, floor: 4 * GIB, percent: 75, cap: 96 * GIB, min_useful: GIB } } /// The laptop profile: the same shares, never more than 24 GiB. pub const fn laptop(mem_available: Option) -> Self { - Self { - mem_available, - floor: 4 * GIB, - percent: 75, - cap: 24 * GIB, - min_useful: GIB, - } + Self { mem_available, floor: 4 * GIB, percent: 75, cap: 24 * GIB, min_useful: GIB } } /// Budget in bytes; `0` = the cache is off. pub fn bytes(&self) -> u64 { @@ -89,37 +77,20 @@ mod tests { let b = AutoBudget::server(Some(14 * GIB)).bytes(); assert_eq!(b, 10 * GIB * 75 / 100); // the same server with a mapped expert source: much more is available - assert_eq!( - AutoBudget::server(Some(67 * GIB)).bytes(), - 63 * GIB * 75 / 100 / MIB * MIB - ); + assert_eq!(AutoBudget::server(Some(67 * GIB)).bytes(), 63 * GIB * 75 / 100 / MIB * MIB); // plenty of memory: capped assert_eq!(AutoBudget::server(Some(1000 * GIB)).bytes(), 96 * GIB); // the laptop profile: 31 GiB available in WSL - assert_eq!( - AutoBudget::laptop(Some(31 * GIB)).bytes(), - 27 * GIB * 75 / 100 / MIB * MIB - ); - assert_eq!( - AutoBudget::laptop(Some(60 * GIB)).bytes(), - 24 * GIB, - "the laptop ceiling" - ); - assert_eq!( - AutoBudget::laptop(Some(10 * GIB)).bytes(), - 6 * GIB * 75 / 100 / MIB * MIB - ); + assert_eq!(AutoBudget::laptop(Some(31 * GIB)).bytes(), 27 * GIB * 75 / 100 / MIB * MIB); + assert_eq!(AutoBudget::laptop(Some(60 * GIB)).bytes(), 24 * GIB, "the laptop ceiling"); + assert_eq!(AutoBudget::laptop(Some(10 * GIB)).bytes(), 6 * GIB * 75 / 100 / MIB * MIB); } #[test] fn auto_is_off_when_nothing_useful_fits_or_telemetry_is_missing() { assert_eq!(AutoBudget::server(None).bytes(), 0); assert_eq!(AutoBudget::server(Some(4 * GIB)).bytes(), 0); - assert_eq!( - AutoBudget::server(Some(5 * GIB)).bytes(), - 0, - "750 MiB is below the useful minimum" - ); + assert_eq!(AutoBudget::server(Some(5 * GIB)).bytes(), 0, "750 MiB is below the useful minimum"); assert_eq!(AutoBudget::laptop(Some(3 * GIB)).bytes(), 0); assert!(AutoBudget::server(Some(6 * GIB)).bytes() >= GIB); } diff --git a/crates/engine-core/src/prefix_cache/hash.rs b/crates/engine-core/src/prefix_cache/hash.rs index a5e77958..1215afbe 100644 --- a/crates/engine-core/src/prefix_cache/hash.rs +++ b/crates/engine-core/src/prefix_cache/hash.rs @@ -79,10 +79,7 @@ mod tests { fn the_function_is_pinned() { // These values are the protocol: a router computes them independently. let tokens: Vec = (0..8).collect(); - assert_eq!( - chain(&tokens, 4), - vec![0x9e7feaf140c714d6, 0xcd122713bf23558d] - ); + assert_eq!(chain(&tokens, 4), vec![0x9e7feaf140c714d6, 0xcd122713bf23558d]); } #[test] diff --git a/crates/engine-core/src/prefix_cache/store/decayed_fn.rs b/crates/engine-core/src/prefix_cache/store/decayed_fn.rs index 1d376dee..618601eb 100644 --- a/crates/engine-core/src/prefix_cache/store/decayed_fn.rs +++ b/crates/engine-core/src/prefix_cache/store/decayed_fn.rs @@ -4,9 +4,5 @@ use super::*; pub(super) fn decayed(value: f64, age: u64, half_life: f64) -> f64 { - if value == 0.0 { - 0.0 - } else { - value * 0.5f64.powf(age as f64 / half_life) - } + if value == 0.0 { 0.0 } else { value * 0.5f64.powf(age as f64 / half_life) } } diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs index 25d5fc56..3f274d69 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2.rs @@ -112,11 +112,7 @@ impl PrefixStore { pub fn tail_of(&self, key: u64) -> Option<(&B, usize, usize)> { let node = self.nodes.get(&key)?; let tail = node.tail.as_ref()?; - Some(( - &tail.payload, - node.path.len() * self.cfg.block_tokens, - tail.tokens.len(), - )) + Some((&tail.payload, node.path.len() * self.cfg.block_tokens, tail.tokens.len())) } /// The payloads of the node's blocks from block `from_block` on, with their block indices. pub fn blocks_from(&self, key: u64, from_block: usize) -> Option> { @@ -146,10 +142,7 @@ impl PrefixStore { } prev = h; if self.nodes.contains_key(&h) { - best = Some(Match { - key: h, - tokens: end, - }); + best = Some(Match { key: h, tokens: end }); } // request-end checkpoints that extend this block (the longest whose tokens are the prompt's next ones) if let Some(keys) = self.tails.get(&h) { @@ -162,10 +155,7 @@ impl PrefixStore { && best.is_none_or(|b| upto > b.tokens) && tokens.get(end..upto).is_some_and(|t| t == &*tail.tokens) { - best = Some(Match { - key: *key, - tokens: upto, - }); + best = Some(Match { key: *key, tokens: upto }); } } } @@ -176,10 +166,7 @@ impl PrefixStore { /// The deepest node among `chain` (chain values of a prompt's blocks, from [`super::hash::chain`]): the tokens /// of a cached prefix of that prompt, 0 when none. Hash-only (the router's query): it cannot see collisions. pub fn prefix_match(&self, chain: &[u64]) -> usize { - chain - .iter() - .rposition(|h| self.nodes.contains_key(h)) - .map_or(0, |j| (j + 1) * self.cfg.block_tokens) + chain.iter().rposition(|h| self.nodes.contains_key(h)).map_or(0, |j| (j + 1) * self.cfg.block_tokens) } /// Every node as `(key, tokens)`, deepest first. @@ -219,9 +206,7 @@ impl PrefixStore { return false; } let at = node.path.len() - 1; - self.nodes - .values() - .any(|other| other.path.len() > node.path.len() && other.path[at] == key) + self.nodes.values().any(|other| other.path.len() > node.path.len() && other.path[at] == key) } /// A request resumed from `m`. A hit on a branch point counts as evidence of sharing, a hit on a frontier as @@ -233,11 +218,7 @@ impl PrefixStore { /// `record_hit` with the sharing verdict given by the caller. pub fn record_hit_as(&mut self, m: &Match, shared: bool) { - let weight = if shared { - self.cfg.policy.shared_weight - } else { - self.cfg.policy.continuation_weight - }; + let weight = if shared { self.cfg.policy.shared_weight } else { self.cfg.policy.continuation_weight }; let clock = self.clock; let half_life = self.cfg.policy.half_life; if let Some(node) = self.nodes.get_mut(&m.key) { diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs index 48121698..863db5be 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_2_2.rs @@ -7,11 +7,7 @@ impl PrefixStore { /// Value of every node not in `removed`: expected tokens saved per byte its eviction frees. A node's saving is /// measured against its nearest SURVIVING ancestor, so thinning a chain makes what is left worth more. /// `protect`: blocks that stay whatever happens (the path of an entry being admitted). - pub(in super::super) fn scores( - &self, - removed: &HashSet, - protect: &HashSet, - ) -> Vec { + pub(in super::super) fn scores(&self, removed: &HashSet, protect: &HashSet) -> Vec { let g = self.cfg.block_tokens; let mut cover: HashMap = HashMap::new(); for key in removed { @@ -29,11 +25,7 @@ impl PrefixStore { } let mut depth = 0; // a tail node's nearest ancestor may be the grid node at the end of its own path - let upto = if node.tail.is_some() { - node.path.len() - } else { - node.path.len() - 1 - }; + let upto = if node.tail.is_some() { node.path.len() } else { node.path.len() - 1 }; for i in (0..upto).rev() { let h = node.path[i]; if self.nodes.contains_key(&h) && !removed.contains(&h) { @@ -52,23 +44,13 @@ impl PrefixStore { let mut freed = node.bytes; for h in node.path.iter() { let block = &self.blocks[h]; - if block - .refs - .saturating_sub(cover.get(h).copied().unwrap_or(0)) - == 1 - && !protect.contains(h) - { + if block.refs.saturating_sub(cover.get(h).copied().unwrap_or(0)) == 1 && !protect.contains(h) { freed += block.bytes; } } let marginal = (self.tokens_of(node) - anc) as f64; let p = self.probability(node, children.get(key).copied().unwrap_or(0)); - out.push(Scored { - key: *key, - score: p * marginal / freed.max(1) as f64, - value: p * marginal, - freed, - }); + out.push(Scored { key: *key, score: p * marginal / freed.max(1) as f64, value: p * marginal, freed }); } out } @@ -76,30 +58,15 @@ impl PrefixStore { /// Decide whether a node for `tokens` (a whole number of blocks) is worth its bytes, making room if so. /// `est_state` / `est_block`: the sizes the payloads are expected to have. Evictions made here are final even if /// the caller then fails to build the payloads. - pub fn consider( - &mut self, - tokens: &[i32], - frontier: bool, - est_state: usize, - est_block: usize, - ) -> Consider { + pub fn consider(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { let g = self.cfg.block_tokens; - assert!( - !tokens.is_empty() && tokens.len() % g == 0, - "a node covers whole blocks" - ); + assert!(!tokens.is_empty() && tokens.len() % g == 0, "a node covers whole blocks"); self.consider_at(tokens, frontier, est_state, est_block) } /// `consider` for a checkpoint at the END OF A REQUEST: `tokens` is a whole number of blocks (at least one) plus a tail of /// 1..block_tokens tokens. The tail's cells are charged as the same share of a block. - pub fn consider_tail( - &mut self, - tokens: &[i32], - frontier: bool, - est_state: usize, - est_block: usize, - ) -> Consider { + pub fn consider_tail(&mut self, tokens: &[i32], frontier: bool, est_state: usize, est_block: usize) -> Consider { let g = self.cfg.block_tokens; assert!( tokens.len() > g && tokens.len() % g != 0, @@ -134,20 +101,14 @@ impl PrefixStore { path.push(h); prev = h; } - let key = if tail_len == 0 { - prev - } else { - chain_step(prev, &tokens[tokens.len() - tail_len..]) - }; + let key = if tail_len == 0 { prev } else { chain_step(prev, &tokens[tokens.len() - tail_len..]) }; if let Some(node) = self.nodes.get_mut(&key) { node.touched = self.clock; node.last_used_ms = self.now_ms; self.stats.already_cached += 1; return Consider::Exists; } - let need = est_state - + missing.len() * est_block - + (est_block as u128 * tail_len as u128 / g as u128) as usize; + let need = est_state + missing.len() * est_block + (est_block as u128 * tail_len as u128 / g as u128) as usize; if need > self.cfg.budget_bytes { self.stats.rejected += 1; return Consider::Rejected(Reject::TooLarge); @@ -185,13 +146,7 @@ impl PrefixStore { for key in removed { self.evict_keeping(key, &protect); } - Consider::Admit(Candidate { - key, - path, - tail_len, - missing, - frontier, - }) + Consider::Admit(Candidate { key, path, tail_len, missing, frontier }) } /// Expected tokens saved by a node at the end of `path` (against its nearest surviving ancestor). @@ -203,21 +158,13 @@ impl PrefixStore { removed: &HashSet, ) -> f64 { let g = self.cfg.block_tokens; - let upto = if tail_len > 0 { - path.len() - } else { - path.len() - 1 - }; + let upto = if tail_len > 0 { path.len() } else { path.len() - 1 }; let anc = (0..upto) .rev() .find(|&i| self.nodes.contains_key(&path[i]) && !removed.contains(&path[i])) .map_or(0, |i| (i + 1) * g); let marginal = (path.len() * g + tail_len - anc) as f64; - let p = if frontier { - self.cfg.policy.frontier_prior - } else { - self.cfg.policy.interior_prior - }; + let p = if frontier { self.cfg.policy.frontier_prior } else { self.cfg.policy.interior_prior }; p * marginal } @@ -280,14 +227,8 @@ impl PrefixStore { let g = self.cfg.block_tokens; if tokens.len() != candidate.path.len() * g + candidate.tail_len || blocks.len() != candidate.missing.len() - || blocks - .iter() - .zip(&candidate.missing) - .any(|((j, _), m)| j != m) - || candidate - .missing - .iter() - .any(|j| self.blocks.contains_key(&candidate.path[*j])) + || blocks.iter().zip(&candidate.missing).any(|((j, _), m)| j != m) + || candidate.missing.iter().any(|j| self.blocks.contains_key(&candidate.path[*j])) || self.nodes.contains_key(&candidate.key) { return Err(Reject::Mismatch); @@ -297,12 +238,7 @@ impl PrefixStore { self.block_bytes += bytes; self.blocks.insert( candidate.path[j], - Block { - tokens: tokens[j * g..(j + 1) * g].into(), - payload, - bytes, - refs: 0, - }, + Block { tokens: tokens[j * g..(j + 1) * g].into(), payload, bytes, refs: 0 }, ); } for h in &candidate.path { @@ -313,22 +249,13 @@ impl PrefixStore { None => return Err(Reject::Mismatch), } } - let superseded = if candidate.tail_len > 0 { - self.superseded_tails(&candidate.path, tokens, keep_end) - } else { - Vec::new() - }; - let tail = tail.map(|payload| Tail { - tokens: tokens[tokens.len() - candidate.tail_len..].into(), - payload, - }); + let superseded = + if candidate.tail_len > 0 { self.superseded_tails(&candidate.path, tokens, keep_end) } else { Vec::new() }; + let tail = tail.map(|payload| Tail { tokens: tokens[tokens.len() - candidate.tail_len..].into(), payload }); let bytes = state.byte_size() + tail.as_ref().map_or(0, |t| t.payload.byte_size()); self.node_bytes += bytes; if tail.is_some() { - self.tails - .entry(*candidate.path.last().expect("a tail extends a block")) - .or_default() - .push(candidate.key); + self.tails.entry(*candidate.path.last().expect("a tail extends a block")).or_default().push(candidate.key); } self.nodes.insert( candidate.key, @@ -355,12 +282,7 @@ impl PrefixStore { } /// Tail nodes whose tokens are a strict prefix of `tokens` (the history this tail node continues). - pub(in super::super) fn superseded_tails( - &self, - path: &[u64], - tokens: &[i32], - keep_end: Option, - ) -> Vec { + pub(in super::super) fn superseded_tails(&self, path: &[u64], tokens: &[i32], keep_end: Option) -> Vec { let g = self.cfg.block_tokens; let mut out = Vec::new(); for (j, parent) in path.iter().enumerate() { @@ -370,8 +292,7 @@ impl PrefixStore { continue; }; let end = start + tail.tokens.len(); - if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens - { + if end < tokens.len() && Some(end) != keep_end && tokens[start..end] == *tail.tokens { out.push(*key); } } diff --git a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs index d3759861..c013ce2f 100644 --- a/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs +++ b/crates/engine-core/src/prefix_cache/store/impl_prefixstore/impl_prefixstore_3.rs @@ -103,20 +103,10 @@ impl PrefixStore { } let mut block_bytes = 0; for (h, b) in &self.blocks { - assert_eq!( - refs.get(h).copied().unwrap_or(0), - b.refs, - "refcount of a block" - ); - assert!( - b.refs > 0 || self.orphans.contains(h), - "an unreferenced block is kept" - ); + assert_eq!(refs.get(h).copied().unwrap_or(0), b.refs, "refcount of a block"); + assert!(b.refs > 0 || self.orphans.contains(h), "an unreferenced block is kept"); block_bytes += b.bytes; } - assert_eq!( - (node_bytes, block_bytes), - (self.node_bytes, self.block_bytes) - ); + assert_eq!((node_bytes, block_bytes), (self.node_bytes, self.block_bytes)); } } diff --git a/crates/engine-core/src/prefix_cache/store/tests.rs b/crates/engine-core/src/prefix_cache/store/tests.rs index bd5b9d04..095917c5 100644 --- a/crates/engine-core/src/prefix_cache/store/tests.rs +++ b/crates/engine-core/src/prefix_cache/store/tests.rs @@ -15,7 +15,12 @@ const STATE: usize = 100; const BLOCK: usize = 30; fn store(budget: usize) -> PrefixStore { - PrefixStore::new(StoreConfig { block_tokens: G, budget_bytes: budget, max_nodes: 64, policy: PolicyParams::default() }) + PrefixStore::new(StoreConfig { + block_tokens: G, + budget_bytes: budget, + max_nodes: 64, + policy: PolicyParams::default(), + }) } fn tokens(session: i32, shared_blocks: usize, blocks: usize) -> Vec { // `shared_blocks` identical leading blocks, then blocks private to `session` @@ -70,7 +75,7 @@ fn put_tail_keeping(s: &mut PrefixStore, t: &[i32], len: usize const MINUTE: u64 = 60_000; -#[path = "tests/request_resumes_from.rs"] -mod request_resumes_from; #[path = "tests/hit_by_another_session.rs"] mod hit_by_another_session; +#[path = "tests/request_resumes_from.rs"] +mod request_resumes_from; diff --git a/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs b/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs index e76f41ea..74a91ce1 100644 --- a/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs +++ b/crates/engine-core/src/prefix_cache/store/tests/hit_by_another_session.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn a_hit_by_another_session_makes_a_shared_root_outlive_private_leaves() { // budget for the shared root chain + 3 private frontier leaves @@ -171,7 +170,11 @@ fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_ policy: PolicyParams::default(), }); let token = |session: i32, i: usize| -> i32 { - if i < 4 * BLOCK_TOKENS { (i as i32 * 31) % 247_000 + 1 } else { ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 } + if i < 4 * BLOCK_TOKENS { + (i as i32 * 31) % 247_000 + 1 + } else { + ((i64::from(session) * 1_000_003 + i as i64 * 7919) % 247_000 + 1) as i32 + } }; let sessions = 12; let mut lengths = vec![8_192usize; sessions]; @@ -216,9 +219,17 @@ fn twelve_sessions_growing_to_180k_tokens_stay_inside_the_budget_and_the_lookup_ "scale: {} requests, longest prompt {longest}; reuse {:.1}%; lookup mean {:.0} us max {:.0} us; policy per request mean {:.0} us max {:.0} us; nodes {} blocks {} bytes {} MiB of {}; admitted {} rejected {} evicted {}", match_us.len(), 100.0 * reused as f64 / prompt_total as f64, - mean(&match_us), max(&match_us), mean(&policy_us), max(&policy_us), - s.node_count(), s.block_count(), s.bytes() >> 20, s.config().budget_bytes >> 20, - s.stats().admitted, s.stats().rejected, s.stats().evicted + mean(&match_us), + max(&match_us), + mean(&policy_us), + max(&policy_us), + s.node_count(), + s.block_count(), + s.bytes() >> 20, + s.config().budget_bytes >> 20, + s.stats().admitted, + s.stats().rejected, + s.stats().evicted ); assert!(longest >= 170_000); // the cache is smaller than the sum of the histories (12 x ~90k tokens on average = 15 GB of blocks alone): it must have chosen diff --git a/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs b/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs index 485474a8..a367603e 100644 --- a/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs +++ b/crates/engine-core/src/prefix_cache/store/tests/request_resumes_from.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn a_request_resumes_from_the_deepest_node_of_any_session() { let mut s = store(10_000); @@ -116,7 +115,11 @@ fn a_checkpoint_between_two_grid_points_is_matched_exactly_and_supersedes_the_on put(&mut s, &a, 4, true); assert_eq!(put_tail(&mut s, &a, 4 * G + 3), Consider::Exists); assert_eq!(s.longest_match(&a, a.len()).unwrap().tokens, 4 * G + 3); - assert_eq!(s.longest_match(&a, 4 * G + 2).unwrap().tokens, 4 * G, "the older tails are gone, the grid nodes remain"); + assert_eq!( + s.longest_match(&a, 4 * G + 2).unwrap().tokens, + 4 * G, + "the older tails are gone, the grid nodes remain" + ); // summaries and router queries only know grid nodes assert!(s.heads().iter().all(|h| h.1 % G == 0)); assert_eq!(s.heads_by_value().len(), s.heads().len()); @@ -181,7 +184,12 @@ fn a_session_is_kept_for_the_retention_time_and_dropped_after_it() { #[test] fn retention_zero_never_expires() { - let mut s = PrefixStore::::new(StoreConfig { block_tokens: G, budget_bytes: 100_000, max_nodes: 64, policy: PolicyParams { retention_ms: 0, ..PolicyParams::default() } }); + let mut s = PrefixStore::::new(StoreConfig { + block_tokens: G, + budget_bytes: 100_000, + max_nodes: 64, + policy: PolicyParams { retention_ms: 0, ..PolicyParams::default() }, + }); let a = tokens(1, 0, 2); put(&mut s, &a, 2, true); s.set_now(1_000_000 * MINUTE); diff --git a/crates/engine-core/src/prefix_cache/summary.rs b/crates/engine-core/src/prefix_cache/summary.rs index 52e40617..f3deaaeb 100644 --- a/crates/engine-core/src/prefix_cache/summary.rs +++ b/crates/engine-core/src/prefix_cache/summary.rs @@ -75,21 +75,11 @@ pub fn hex(h: u64) -> String { } impl PrefixSummary { - pub fn build( - store: &PrefixStore, - namespace: u64, - max_heads: usize, - ) -> Self { + pub fn build(store: &PrefixStore, namespace: u64, max_heads: usize) -> Self { let all = store.heads_by_value(); let truncated = all.len() > max_heads; - let heads = all - .into_iter() - .take(max_heads) - .map(|(h, tokens)| Head { - h: hex(h), - tokens: tokens as u32, - }) - .collect(); + let heads = + all.into_iter().take(max_heads).map(|(h, tokens)| Head { h: hex(h), tokens: tokens as u32 }).collect(); Self { version: SUMMARY_VERSION, chain_version: CHAIN_VERSION, @@ -108,16 +98,8 @@ impl PrefixSummary { /// Tokens of the longest cached prefix of a prompt whose chain values (one per full block) are `chain`; /// 0 when none of its heads is here. pub fn match_tokens(&self, chain: &[u64]) -> u32 { - let known: HashMap<&str, u32> = self - .heads - .iter() - .map(|h| (h.h.as_str(), h.tokens)) - .collect(); - chain - .iter() - .rev() - .find_map(|h| known.get(hex(*h).as_str()).copied()) - .unwrap_or(0) + let known: HashMap<&str, u32> = self.heads.iter().map(|h| (h.h.as_str(), h.tokens)).collect(); + chain.iter().rev().find_map(|h| known.get(hex(*h).as_str()).copied()).unwrap_or(0) } } @@ -152,9 +134,7 @@ mod tests { }); let tokens: Vec = (0..48).collect(); for k in [2usize, 6] { - let Consider::Admit(c) = s.consider(&tokens[..k * 8], true, 10, 5) else { - panic!() - }; + let Consider::Admit(c) = s.consider(&tokens[..k * 8], true, 10, 5) else { panic!() }; let blocks = c.missing.iter().map(|j| (*j, P(5))).collect(); s.commit(c, &tokens[..k * 8], P(10), blocks).unwrap(); } @@ -165,25 +145,13 @@ mod tests { fn a_router_matches_a_prompt_against_the_heads_with_the_same_chain() { let (store, tokens) = filled(); let summary = PrefixSummary::build(&store, 0xabc, 64); - assert_eq!( - ( - summary.version, - summary.block_tokens, - summary.nodes, - summary.blocks - ), - (1, 8, 2, 6) - ); + assert_eq!((summary.version, summary.block_tokens, summary.nodes, summary.blocks), (1, 8, 2, 6)); assert_eq!(summary.namespace, "0000000000000abc"); assert!(!summary.truncated); // the router hashes its own prompt: it shares 3 blocks, then diverges let mut prompt = tokens.clone(); prompt[30] = -5; - assert_eq!( - summary.match_tokens(&chain(&prompt, 8)), - 16, - "the node at 2 blocks is the deepest prefix" - ); + assert_eq!(summary.match_tokens(&chain(&prompt, 8)), 16, "the node at 2 blocks is the deepest prefix"); assert_eq!(summary.match_tokens(&chain(&tokens, 8)), 48); assert_eq!(summary.match_tokens(&chain(&tokens[..40], 8)), 16); assert_eq!(summary.match_tokens(&chain(&[9; 64], 8)), 0); @@ -201,18 +169,8 @@ mod tests { let text = serde_json::to_string(&summary).unwrap(); let back: PrefixSummary = serde_json::from_str(&text).unwrap(); assert_eq!(back, summary); - assert!( - text.contains("\"namespace\":\"0000000000000007\""), - "{text}" - ); - let m = PrefixMatch { - namespace: summary.namespace.clone(), - block_tokens: 8, - cached_tokens: 48, - }; - assert_eq!( - serde_json::from_str::(&serde_json::to_string(&m).unwrap()).unwrap(), - m - ); + assert!(text.contains("\"namespace\":\"0000000000000007\""), "{text}"); + let m = PrefixMatch { namespace: summary.namespace.clone(), block_tokens: 8, cached_tokens: 48 }; + assert_eq!(serde_json::from_str::(&serde_json::to_string(&m).unwrap()).unwrap(), m); } } diff --git a/crates/engine-core/src/prompt.rs b/crates/engine-core/src/prompt.rs index defd9fea..1b9eb5d4 100644 --- a/crates/engine-core/src/prompt.rs +++ b/crates/engine-core/src/prompt.rs @@ -27,7 +27,9 @@ pub struct PromptOptions { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PromptPath { - Batched { capacity: usize }, + Batched { + capacity: usize, + }, Verify, /// Original first decode window: the actual last prompt token alone. FinalSeed, @@ -89,227 +91,27 @@ pub struct DriveSummary { } #[derive(Debug, Eq, PartialEq)] pub enum DriveError { - Cancelled { at: usize }, + Cancelled { + at: usize, + }, /// The plan skipped or repeated positions, or a batched action exceeds the admitted capacity. Contract(&'static str), Runner(E), } #[cfg(test)] -mod tests { - use super::*; - - // Independent literal Original control flow FIRST; no session/device proof. - fn original(tokens: &[u32], resume: usize, reread: Option, pictures: Option<&[bool]>, o: PromptOptions, cap: usize) -> Vec { - let n = tokens.len(); - let mut turn = None; - if o.prompt_cache { - for i in (resume + 1..n).rev() { - if Some(tokens[i]) == o.turn_token { turn = Some(i); break; } - } - } - let from = if reread.is_some() { 0 } else { resume }; - let mut root = None; - if o.prompt_cache && o.root_min > 0 && from == 0 { - for i in 1..turn.unwrap_or(0) { - if Some(tokens[i]) == o.turn_token { - if i >= o.root_min { root = Some(i); } - break; - } - } - } - let mut actions = Vec::new(); - let mut at = from; - for to in [reread.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), n - 1] { - if to <= at { continue; } - let windows = !o.force_batched && to - at <= o.short_read - && !pictures.is_some_and(|p| p[at..to].iter().any(|v| *v)); - let capacity = ((to - at + 255) / 256 * 256).min(cap); - while at < to { - let count = (if windows { o.verify_width } else { capacity }).min(to - at); - let first = at; - at += count; - actions.push(PromptAction { first, count, - path: if windows { PromptPath::Verify } else { PromptPath::Batched { capacity } }, - checkpoint_after: at == to && (Some(to) == turn || Some(to) == root) }); - } - } - actions.push(PromptAction { first: n - 1, count: 1, path: PromptPath::FinalSeed, checkpoint_after: false }); - actions - } - #[test] - fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { - let o = PromptOptions::original_mode17(262144); - // Sanitized IDs reproduce only known turn-boundary positions; no model - // payload, tokenizer output or expected greedy output is embedded. - let mut frame = vec![17; 202]; - for i in [0, 17, 195] { frame[i] = 248045; } - let baseline = original(&frame, 0, None, None, o, 8192); - let candidate: Vec<_> = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap().collect(); - assert_eq!(baseline, candidate); - assert_eq!(candidate.iter().map(|a| (a.first, a.count, a.path)).collect::>(), vec![ - (0,195,PromptPath::Batched {capacity:256}), (195,4,PromptPath::Verify), - (199,2,PromptPath::Verify), (201,1,PromptPath::FinalSeed)]); - for n in [1, 64, 65, 256, 8193, 16386] { - let mut tokens = vec![7; n]; - if n > 70 { tokens[n - 7] = 248045; } - for resume in [0, n.saturating_sub(8)] { - for reread in [None, (resume > 0).then_some(resume)] { - for cache in [false,true] { - for forced in [false,true] { - let options = PromptOptions { prompt_cache:cache, force_batched:forced, root_min:64, ..o }; - let baseline = original(&tokens,resume,reread,None,options,8192); - let candidate:Vec<_> = PromptPlan::new(&tokens,resume,reread,None,options,8192).unwrap().collect(); - assert_eq!(baseline,candidate); - assert_eq!(candidate.last().unwrap().first,n-1); - assert!(candidate.iter().all(|a|a.count>0 && a.first+a.count<=n)); - } - } - } - } - } - let mut pictures = vec![false;202]; pictures[199]=true; - let baseline = original(&frame,0,None,Some(&pictures),o,8192); - assert_eq!(baseline,PromptPlan::new(&frame,0,None,Some(&pictures),o,8192).unwrap().collect::>()); - let mut visited=Vec::new(); - assert_eq!(choose_auto_capacity(262144,8192,1000,85,|cap| { visited.push(cap); Ok(if cap>=4096 {900}else{600}) }).unwrap(),Some(3072)); - assert_eq!(visited,vec![8192,6144,4096,3072]); - assert_eq!(request_capacity(195,8192),Ok(256)); - assert_eq!(request_capacity(8193,8192),Ok(8192)); - assert_eq!(request_capacity(usize::MAX,8192),Ok(8192)); - for options in [PromptOptions {root_min:1,..o}, PromptOptions {short_read:0,..o}] { - let baseline=original(&frame,0,None,None,options,8192); - assert_eq!(baseline,PromptPlan::new(&frame,0,None,None,options,8192).unwrap().collect::>()); - } - assert!(PromptPlan::new(&frame,202,None,None,o,8192).is_err()); - assert!(PromptPlan::new(&frame,0,Some(1),None,o,8192).is_err()); - assert!(PromptPlan::new(&frame,0,None,Some(&pictures[..201]),o,8192).is_err()); - assert!(PromptPlan::new(&frame,0,None,None,o,0).is_err()); - assert!(choose_auto_capacity(262144,8192,128,85,|_|Ok(1)).unwrap().is_none()); - } - - struct Recorder { - log: Vec<(&'static str, usize, usize)>, - stop_after: Option, - fail_on: Option<&'static str>, - } - impl PromptRunner for Recorder { - type Error = &'static str; - fn cancelled(&mut self) -> bool { self.stop_after.is_some_and(|n| self.log.len() >= n) } - fn batched(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { - if self.fail_on == Some("batched") { return Err("batched failed"); } - self.log.push(("batched", a.first, a.count)); Ok(()) - } - fn verify_window(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { self.log.push(("verify", a.first, a.count)); Ok(()) } - fn final_seed(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { self.log.push(("seed", a.first, a.count)); Ok(()) } - fn checkpoint(&mut self, end: usize) -> core::result::Result<(), Self::Error> { self.log.push(("checkpoint", end, 0)); Ok(()) } - } - - #[test] - fn drive_executes_a_plan_in_order_with_checkpoints_and_the_final_seed() { - let o = PromptOptions::original_mode17(262144); - let mut frame = vec![17; 202]; - for i in [0, 17, 195] { frame[i] = 248045; } - let plan = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap(); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - let s = drive(plan, 8192, &mut r).unwrap(); - assert_eq!(r.log, vec![("batched", 0, 195), ("checkpoint", 195, 0), ("verify", 195, 4), ("verify", 199, 2), ("seed", 201, 1)]); - assert_eq!((s.batched_chunks, s.batched_rows, s.verify_windows, s.verify_rows, s.checkpoints, s.final_seed, s.first, s.end), - (1, 195, 2, 6, 1, true, 0, 202)); - // a long segment is cut into admitted-capacity chunks - let long = vec![7; 20000]; - let plan = PromptPlan::new(&long, 0, None, None, o, 8192).unwrap(); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - let s = drive(plan, 8192, &mut r).unwrap(); - assert_eq!(r.log.iter().map(|e| (e.0, e.2)).collect::>(), vec![("batched", 8192), ("batched", 8192), ("batched", 3615), ("seed", 1)]); - assert_eq!((s.batched_rows, s.end), (19999, 20000)); - // resume from a cached prefix: positions start there and stay contiguous - let plan = PromptPlan::new(&long, 12000, None, None, o, 8192).unwrap(); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - let s = drive(plan, 8192, &mut r).unwrap(); - assert_eq!(s.first, 12000); - assert_eq!(r.log.first().map(|e| e.1), Some(12000)); - } - - #[test] - fn drive_stops_on_cancel_runner_error_and_contract_violations() { - let o = PromptOptions::original_mode17(262144); - let tokens = vec![7; 20000]; - let mut r = Recorder { log: vec![], stop_after: Some(1), fail_on: None }; - assert_eq!(drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), Err(DriveError::Cancelled { at: 8192 })); - assert_eq!(r.log.len(), 1); - let mut r = Recorder { log: vec![], stop_after: None, fail_on: Some("batched") }; - assert_eq!(drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), Err(DriveError::Runner("batched failed"))); - // an executor built for a smaller capacity than the plan was admitted with - let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; - assert_eq!(drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 4096, &mut r), - Err(DriveError::Contract("batched chunk exceeds the admitted capacity"))); - assert!(r.log.is_empty()); - } -} +#[path = "prompt/tests.rs"] +mod tests; #[cfg(test)] -mod grid_tests { - use super::*; - - fn cuts(tokens: &[u32], resume: usize, o: PromptOptions, capacity: usize) -> Vec<(usize, usize)> { - PromptPlan::new(tokens, resume, None, None, o, capacity) - .unwrap() - .filter(|a| a.path != PromptPath::FinalSeed) - .map(|a| (a.first, a.count)) - .collect() - } - - #[test] - fn a_grid_puts_every_chunk_end_but_the_last_on_a_multiple_and_a_resume_on_the_grid_reads_the_same_chunks() { - let o = PromptOptions { grid: 512, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(262144) }; - let mut tokens = vec![7u32; 5000]; - // turn tokens must not add cuts (the prefix cache has no turn/root cuts) - tokens[300] = 248_045; - tokens[3000] = 248_045; - for capacity in [512, 1024, 2048, 8192] { - let full = cuts(&tokens, 0, o, capacity); - let (last, rest) = full.split_last().unwrap(); - assert!(rest.iter().all(|(first, count)| (first + count) % 512 == 0), "{capacity}: {full:?}"); - assert_eq!(last.0 + last.1, 4999); - assert!(full.iter().all(|(_, count)| *count <= capacity.min(512))); - // contiguous - assert!(full.windows(2).all(|w| w[0].0 + w[0].1 == w[1].0)); - // resuming on any grid point reads exactly the remaining chunks of the full read - for resume in [512usize, 1024, 2560, 4608] { - let read = cuts(&tokens, resume, o, capacity); - let expected: Vec<_> = full.iter().copied().filter(|(first, _)| *first >= resume).collect(); - assert_eq!(read, expected, "capacity {capacity} resume {resume}"); - } - } - // a prompt that ends inside a block has a short last chunk, and a short prompt a single one - assert_eq!(cuts(&tokens[..700], 0, o, 2048), vec![(0, 512), (512, 187)]); - assert_eq!(cuts(&tokens[..100], 0, o, 2048), vec![(0, 99)]); - } - - #[test] - fn a_grid_must_be_a_multiple_of_256_within_the_admitted_capacity() { - let tokens = vec![1u32; 3000]; - for (grid, capacity, ok) in [(0, 1024, true), (256, 1024, true), (1024, 1024, true), (2048, 1024, false), (300, 2048, false), (512, 256, false)] { - let o = PromptOptions { grid, force_batched: true, ..PromptOptions::original_mode17(262144) }; - assert_eq!(PromptPlan::new(&tokens, 0, None, None, o, capacity).is_ok(), ok, "grid {grid} capacity {capacity}"); - } - } - - #[test] - fn grid_zero_is_the_originals_plan() { - let o = PromptOptions { force_batched: true, ..PromptOptions::original_mode17(262144) }; - let tokens = vec![3u32; 5000]; - assert_eq!(cuts(&tokens, 0, o, 2048), vec![(0, 2048), (2048, 2048), (4096, 903)]); - assert_eq!(cuts(&tokens, 1000, o, 2048), vec![(1000, 2048), (3048, 1951)]); - } -} +#[path = "prompt/grid_tests.rs"] +mod grid_tests; #[path = "prompt/impl_promptoptions.rs"] mod impl_promptoptions; #[allow(unused_imports)] -pub use impl_promptoptions::request_capacity; -#[allow(unused_imports)] pub use impl_promptoptions::choose_auto_capacity; #[allow(unused_imports)] pub use impl_promptoptions::drive; +#[allow(unused_imports)] +pub use impl_promptoptions::request_capacity; diff --git a/crates/engine-core/src/prompt/grid_tests.rs b/crates/engine-core/src/prompt/grid_tests.rs new file mode 100644 index 00000000..a1436a6b --- /dev/null +++ b/crates/engine-core/src/prompt/grid_tests.rs @@ -0,0 +1,69 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +fn cuts(tokens: &[u32], resume: usize, o: PromptOptions, capacity: usize) -> Vec<(usize, usize)> { + PromptPlan::new(tokens, resume, None, None, o, capacity) + .unwrap() + .filter(|a| a.path != PromptPath::FinalSeed) + .map(|a| (a.first, a.count)) + .collect() +} + +#[test] +fn a_grid_puts_every_chunk_end_but_the_last_on_a_multiple_and_a_resume_on_the_grid_reads_the_same_chunks() { + let o = PromptOptions { + grid: 512, + prompt_cache: false, + turn_token: None, + root_min: 0, + force_batched: true, + ..PromptOptions::original_mode17(262144) + }; + let mut tokens = vec![7u32; 5000]; + // turn tokens must not add cuts (the prefix cache has no turn/root cuts) + tokens[300] = 248_045; + tokens[3000] = 248_045; + for capacity in [512, 1024, 2048, 8192] { + let full = cuts(&tokens, 0, o, capacity); + let (last, rest) = full.split_last().unwrap(); + assert!(rest.iter().all(|(first, count)| (first + count) % 512 == 0), "{capacity}: {full:?}"); + assert_eq!(last.0 + last.1, 4999); + assert!(full.iter().all(|(_, count)| *count <= capacity.min(512))); + // contiguous + assert!(full.windows(2).all(|w| w[0].0 + w[0].1 == w[1].0)); + // resuming on any grid point reads exactly the remaining chunks of the full read + for resume in [512usize, 1024, 2560, 4608] { + let read = cuts(&tokens, resume, o, capacity); + let expected: Vec<_> = full.iter().copied().filter(|(first, _)| *first >= resume).collect(); + assert_eq!(read, expected, "capacity {capacity} resume {resume}"); + } + } + // a prompt that ends inside a block has a short last chunk, and a short prompt a single one + assert_eq!(cuts(&tokens[..700], 0, o, 2048), vec![(0, 512), (512, 187)]); + assert_eq!(cuts(&tokens[..100], 0, o, 2048), vec![(0, 99)]); +} + +#[test] +fn a_grid_must_be_a_multiple_of_256_within_the_admitted_capacity() { + let tokens = vec![1u32; 3000]; + for (grid, capacity, ok) in [ + (0, 1024, true), + (256, 1024, true), + (1024, 1024, true), + (2048, 1024, false), + (300, 2048, false), + (512, 256, false), + ] { + let o = PromptOptions { grid, force_batched: true, ..PromptOptions::original_mode17(262144) }; + assert_eq!(PromptPlan::new(&tokens, 0, None, None, o, capacity).is_ok(), ok, "grid {grid} capacity {capacity}"); + } +} + +#[test] +fn grid_zero_is_the_originals_plan() { + let o = PromptOptions { force_batched: true, ..PromptOptions::original_mode17(262144) }; + let tokens = vec![3u32; 5000]; + assert_eq!(cuts(&tokens, 0, o, 2048), vec![(0, 2048), (2048, 2048), (4096, 903)]); + assert_eq!(cuts(&tokens, 1000, o, 2048), vec![(1000, 2048), (3048, 1951)]); +} diff --git a/crates/engine-core/src/prompt/impl_promptoptions.rs b/crates/engine-core/src/prompt/impl_promptoptions.rs index 5ed570f3..fd254dab 100644 --- a/crates/engine-core/src/prompt/impl_promptoptions.rs +++ b/crates/engine-core/src/prompt/impl_promptoptions.rs @@ -90,8 +90,7 @@ impl<'a> PromptPlan<'a> { || resume >= prompt.len() || prompt.iter().any(|id| *id >= 248320) || ![8192, 16384, 32768].contains(&options.auto_max) - || ![256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768] - .contains(&admitted_capacity) + || ![256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768].contains(&admitted_capacity) || admitted_capacity > options.auto_max || !(1..=4).contains(&options.verify_width) || embedding_rows.is_some_and(|rows| rows.len() != prompt.len()) @@ -103,9 +102,7 @@ impl<'a> PromptPlan<'a> { let last = prompt.len() - 1; let read_from = if reread_to.is_some() { 0 } else { resume }; let turn = if options.prompt_cache { - options.turn_token.and_then(|id| { - (resume + 1..prompt.len()).rev().find(|index| prompt[*index] == id) - }) + options.turn_token.and_then(|id| (resume + 1..prompt.len()).rev().find(|index| prompt[*index] == id)) } else { None }; @@ -113,36 +110,47 @@ impl<'a> PromptPlan<'a> { options.turn_token.and_then(|id| { // FIRST boundary only; a later boundary cannot substitute for // an undersized original system root. - (1..turn.unwrap_or(0)).find(|index| prompt[*index] == id) - .filter(|index| *index >= options.root_min) + (1..turn.unwrap_or(0)).find(|index| prompt[*index] == id).filter(|index| *index >= options.root_min) }) } else { None }; Ok(Self { - prompt, embedding_rows, options, admitted_capacity, + prompt, + embedding_rows, + options, + admitted_capacity, boundaries: [reread_to.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), last], - turn, root, segment: 0, position: read_from, end: read_from, - path: None, seed_done: false, + turn, + root, + segment: 0, + position: read_from, + end: read_from, + path: None, + seed_done: false, }) } - pub fn prompt(&self) -> &'a [u32] { self.prompt } + pub fn prompt(&self) -> &'a [u32] { + self.prompt + } pub(super) fn next_segment(&mut self) { while self.segment < self.boundaries.len() { let end = self.boundaries[self.segment]; self.segment += 1; - if end <= self.position { continue; } + if end <= self.position { + continue; + } let len = end - self.position; - let has_picture = self.embedding_rows.is_some_and(|rows| { - rows[self.position..end].iter().any(|present| *present) - }); + let has_picture = + self.embedding_rows.is_some_and(|rows| rows[self.position..end].iter().any(|present| *present)); let windows = !self.options.force_batched && len <= self.options.short_read && !has_picture; self.end = end; - self.path = Some(if windows { PromptPath::Verify } else { + self.path = Some(if windows { + PromptPath::Verify + } else { // Input bounds make request_capacity overflow impossible here. PromptPath::Batched { - capacity: request_capacity(len, self.admitted_capacity) - .expect("bounded admitted prompt capacity"), + capacity: request_capacity(len, self.admitted_capacity).expect("bounded admitted prompt capacity"), } }); return; @@ -153,7 +161,9 @@ impl<'a> PromptPlan<'a> { impl Iterator for PromptPlan<'_> { type Item = PromptAction; fn next(&mut self) -> Option { - if self.position == self.end { self.next_segment(); } + if self.position == self.end { + self.next_segment(); + } if let Some(path) = self.path { let width = match path { PromptPath::Batched { capacity } => capacity, @@ -167,16 +177,22 @@ impl Iterator for PromptPlan<'_> { let first = self.position; self.position += count; return Some(PromptAction { - first, count, path, + first, + count, + path, checkpoint_after: self.position == self.end && (Some(self.end) == self.turn || Some(self.end) == self.root), }); } - if self.seed_done { return None; } + if self.seed_done { + return None; + } self.seed_done = true; Some(PromptAction { - first: self.prompt.len() - 1, count: 1, - path: PromptPath::FinalSeed, checkpoint_after: false, + first: self.prompt.len() - 1, + count: 1, + path: PromptPath::FinalSeed, + checkpoint_after: false, }) } } diff --git a/crates/engine-core/src/prompt/tests.rs b/crates/engine-core/src/prompt/tests.rs new file mode 100644 index 00000000..02465ae3 --- /dev/null +++ b/crates/engine-core/src/prompt/tests.rs @@ -0,0 +1,228 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +// Independent literal Original control flow FIRST; no session/device proof. +fn original( + tokens: &[u32], + resume: usize, + reread: Option, + pictures: Option<&[bool]>, + o: PromptOptions, + cap: usize, +) -> Vec { + let n = tokens.len(); + let mut turn = None; + if o.prompt_cache { + for i in (resume + 1..n).rev() { + if Some(tokens[i]) == o.turn_token { + turn = Some(i); + break; + } + } + } + let from = if reread.is_some() { 0 } else { resume }; + let mut root = None; + if o.prompt_cache && o.root_min > 0 && from == 0 { + for i in 1..turn.unwrap_or(0) { + if Some(tokens[i]) == o.turn_token { + if i >= o.root_min { + root = Some(i); + } + break; + } + } + } + let mut actions = Vec::new(); + let mut at = from; + for to in [reread.unwrap_or(0), root.unwrap_or(0), turn.unwrap_or(0), n - 1] { + if to <= at { + continue; + } + let windows = + !o.force_batched && to - at <= o.short_read && !pictures.is_some_and(|p| p[at..to].iter().any(|v| *v)); + let capacity = ((to - at + 255) / 256 * 256).min(cap); + while at < to { + let count = (if windows { o.verify_width } else { capacity }).min(to - at); + let first = at; + at += count; + actions.push(PromptAction { + first, + count, + path: if windows { PromptPath::Verify } else { PromptPath::Batched { capacity } }, + checkpoint_after: at == to && (Some(to) == turn || Some(to) == root), + }); + } + } + actions.push(PromptAction { first: n - 1, count: 1, path: PromptPath::FinalSeed, checkpoint_after: false }); + actions +} +#[test] +fn original_first_prompt_boundaries_windows_capacity_and_final_seed() { + let o = PromptOptions::original_mode17(262144); + // Sanitized IDs reproduce only known turn-boundary positions; no model + // payload, tokenizer output or expected greedy output is embedded. + let mut frame = vec![17; 202]; + for i in [0, 17, 195] { + frame[i] = 248045; + } + let baseline = original(&frame, 0, None, None, o, 8192); + let candidate: Vec<_> = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap().collect(); + assert_eq!(baseline, candidate); + assert_eq!( + candidate.iter().map(|a| (a.first, a.count, a.path)).collect::>(), + vec![ + (0, 195, PromptPath::Batched { capacity: 256 }), + (195, 4, PromptPath::Verify), + (199, 2, PromptPath::Verify), + (201, 1, PromptPath::FinalSeed) + ] + ); + for n in [1, 64, 65, 256, 8193, 16386] { + let mut tokens = vec![7; n]; + if n > 70 { + tokens[n - 7] = 248045; + } + for resume in [0, n.saturating_sub(8)] { + for reread in [None, (resume > 0).then_some(resume)] { + for cache in [false, true] { + for forced in [false, true] { + let options = PromptOptions { prompt_cache: cache, force_batched: forced, root_min: 64, ..o }; + let baseline = original(&tokens, resume, reread, None, options, 8192); + let candidate: Vec<_> = + PromptPlan::new(&tokens, resume, reread, None, options, 8192).unwrap().collect(); + assert_eq!(baseline, candidate); + assert_eq!(candidate.last().unwrap().first, n - 1); + assert!(candidate.iter().all(|a| a.count > 0 && a.first + a.count <= n)); + } + } + } + } + } + let mut pictures = vec![false; 202]; + pictures[199] = true; + let baseline = original(&frame, 0, None, Some(&pictures), o, 8192); + assert_eq!(baseline, PromptPlan::new(&frame, 0, None, Some(&pictures), o, 8192).unwrap().collect::>()); + let mut visited = Vec::new(); + assert_eq!( + choose_auto_capacity(262144, 8192, 1000, 85, |cap| { + visited.push(cap); + Ok(if cap >= 4096 { 900 } else { 600 }) + }) + .unwrap(), + Some(3072) + ); + assert_eq!(visited, vec![8192, 6144, 4096, 3072]); + assert_eq!(request_capacity(195, 8192), Ok(256)); + assert_eq!(request_capacity(8193, 8192), Ok(8192)); + assert_eq!(request_capacity(usize::MAX, 8192), Ok(8192)); + for options in [PromptOptions { root_min: 1, ..o }, PromptOptions { short_read: 0, ..o }] { + let baseline = original(&frame, 0, None, None, options, 8192); + assert_eq!(baseline, PromptPlan::new(&frame, 0, None, None, options, 8192).unwrap().collect::>()); + } + assert!(PromptPlan::new(&frame, 202, None, None, o, 8192).is_err()); + assert!(PromptPlan::new(&frame, 0, Some(1), None, o, 8192).is_err()); + assert!(PromptPlan::new(&frame, 0, None, Some(&pictures[..201]), o, 8192).is_err()); + assert!(PromptPlan::new(&frame, 0, None, None, o, 0).is_err()); + assert!(choose_auto_capacity(262144, 8192, 128, 85, |_| Ok(1)).unwrap().is_none()); +} + +struct Recorder { + log: Vec<(&'static str, usize, usize)>, + stop_after: Option, + fail_on: Option<&'static str>, +} +impl PromptRunner for Recorder { + type Error = &'static str; + fn cancelled(&mut self) -> bool { + self.stop_after.is_some_and(|n| self.log.len() >= n) + } + fn batched(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { + if self.fail_on == Some("batched") { + return Err("batched failed"); + } + self.log.push(("batched", a.first, a.count)); + Ok(()) + } + fn verify_window(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { + self.log.push(("verify", a.first, a.count)); + Ok(()) + } + fn final_seed(&mut self, a: &PromptAction) -> core::result::Result<(), Self::Error> { + self.log.push(("seed", a.first, a.count)); + Ok(()) + } + fn checkpoint(&mut self, end: usize) -> core::result::Result<(), Self::Error> { + self.log.push(("checkpoint", end, 0)); + Ok(()) + } +} + +#[test] +fn drive_executes_a_plan_in_order_with_checkpoints_and_the_final_seed() { + let o = PromptOptions::original_mode17(262144); + let mut frame = vec![17; 202]; + for i in [0, 17, 195] { + frame[i] = 248045; + } + let plan = PromptPlan::new(&frame, 0, None, None, o, 8192).unwrap(); + let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; + let s = drive(plan, 8192, &mut r).unwrap(); + assert_eq!( + r.log, + vec![("batched", 0, 195), ("checkpoint", 195, 0), ("verify", 195, 4), ("verify", 199, 2), ("seed", 201, 1)] + ); + assert_eq!( + ( + s.batched_chunks, + s.batched_rows, + s.verify_windows, + s.verify_rows, + s.checkpoints, + s.final_seed, + s.first, + s.end + ), + (1, 195, 2, 6, 1, true, 0, 202) + ); + // a long segment is cut into admitted-capacity chunks + let long = vec![7; 20000]; + let plan = PromptPlan::new(&long, 0, None, None, o, 8192).unwrap(); + let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; + let s = drive(plan, 8192, &mut r).unwrap(); + assert_eq!( + r.log.iter().map(|e| (e.0, e.2)).collect::>(), + vec![("batched", 8192), ("batched", 8192), ("batched", 3615), ("seed", 1)] + ); + assert_eq!((s.batched_rows, s.end), (19999, 20000)); + // resume from a cached prefix: positions start there and stay contiguous + let plan = PromptPlan::new(&long, 12000, None, None, o, 8192).unwrap(); + let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; + let s = drive(plan, 8192, &mut r).unwrap(); + assert_eq!(s.first, 12000); + assert_eq!(r.log.first().map(|e| e.1), Some(12000)); +} + +#[test] +fn drive_stops_on_cancel_runner_error_and_contract_violations() { + let o = PromptOptions::original_mode17(262144); + let tokens = vec![7; 20000]; + let mut r = Recorder { log: vec![], stop_after: Some(1), fail_on: None }; + assert_eq!( + drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), + Err(DriveError::Cancelled { at: 8192 }) + ); + assert_eq!(r.log.len(), 1); + let mut r = Recorder { log: vec![], stop_after: None, fail_on: Some("batched") }; + assert_eq!( + drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 8192, &mut r), + Err(DriveError::Runner("batched failed")) + ); + // an executor built for a smaller capacity than the plan was admitted with + let mut r = Recorder { log: vec![], stop_after: None, fail_on: None }; + assert_eq!( + drive(PromptPlan::new(&tokens, 0, None, None, o, 8192).unwrap(), 4096, &mut r), + Err(DriveError::Contract("batched chunk exceeds the admitted capacity")) + ); + assert!(r.log.is_empty()); +} diff --git a/crates/engine-core/src/request.rs b/crates/engine-core/src/request.rs index de75e7f0..6be0822d 100644 --- a/crates/engine-core/src/request.rs +++ b/crates/engine-core/src/request.rs @@ -15,11 +15,7 @@ pub const ENDOFTEXT_TOKEN: i32 = 248_044; /// The stop set of a request on the Original serve path: generate.cpp's `eos_ids` ({248044, 248046}) plus the model's own EOS id. pub fn original_stop_tokens(eos: u32) -> Vec { let eos = eos as i32; - if eos == ENDOFTEXT_TOKEN { - vec![eos] - } else { - vec![eos, ENDOFTEXT_TOKEN] - } + if eos == ENDOFTEXT_TOKEN { vec![eos] } else { vec![eos, ENDOFTEXT_TOKEN] } } /// Cells a request keeps free beyond `n + max_new`: the last verify window may overshoot by up to this. @@ -45,11 +41,8 @@ pub fn admit(prompt: &[i32], eos: &[i32], max_new: usize, spec_min_p: f32, max_c if prompt.iter().chain(eos).any(|&t| !(0..248_320).contains(&t)) { return Err(Admission::BadToken); } - let needed = prompt - .len() - .checked_add(max_new) - .and_then(|n| n.checked_add(CONTEXT_SLACK)) - .ok_or(Admission::Context)?; + let needed = + prompt.len().checked_add(max_new).and_then(|n| n.checked_add(CONTEXT_SLACK)).ok_or(Admission::Context)?; if i64::try_from(needed).map_or(true, |needed| needed > max_context) { return Err(Admission::Context); } diff --git a/crates/engine-core/src/spec/adaptive.rs b/crates/engine-core/src/spec/adaptive.rs index c00ed3f1..ac3f6c1b 100644 --- a/crates/engine-core/src/spec/adaptive.rs +++ b/crates/engine-core/src/spec/adaptive.rs @@ -179,11 +179,11 @@ mod tests; mod impl_adaptiveconfig; #[allow(unused_imports)] -use impl_adaptiveconfig::p_bucket; +use impl_adaptiveconfig::logit; #[allow(unused_imports)] use impl_adaptiveconfig::m_bucket; #[allow(unused_imports)] -use impl_adaptiveconfig::logit; +use impl_adaptiveconfig::p_bucket; #[allow(unused_imports)] use impl_adaptiveconfig::sigmoid; mod impl_adaptivepolicy; diff --git a/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs b/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs index ce5fd759..88ef347b 100644 --- a/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs +++ b/crates/engine-core/src/spec/adaptive/impl_adaptiveconfig.rs @@ -65,7 +65,17 @@ pub(super) fn p_bucket(p: f32) -> usize { (1..P_BUCKETS).find(|&b| p < P_EDGES[b]).map_or(P_BUCKETS - 1, |b| b - 1) } pub(super) fn m_bucket(n: usize) -> usize { - if n < 6 { 0 } else if n < 12 { 1 } else if n < 24 { 2 } else if n < 48 { 3 } else { 4 } + if n < 6 { + 0 + } else if n < 12 { + 1 + } else if n < 24 { + 2 + } else if n < 48 { + 3 + } else { + 4 + } } pub(super) fn logit(p: f64) -> f64 { let p = p.clamp(1e-4, 1.0 - 1e-4); diff --git a/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs b/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs index 18405717..9c1d97cb 100644 --- a/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs +++ b/crates/engine-core/src/spec/adaptive/impl_adaptivepolicy.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl AdaptivePolicy { pub fn new(cfg: AdaptiveConfig) -> Self { Self { @@ -40,7 +39,8 @@ impl AdaptivePolicy { /// A new request: the content changes, so the fast biases restart (the cell statistics and the costs persist). /// `min_p`: the request's chain floor, the policy's upper bound (0 = none given: the default bound). pub fn begin_request(&mut self, min_p: f32) { - self.cfg.min_p_hi = if min_p > 0.0 && min_p.is_finite() { min_p.max(self.cfg.min_p_lo) } else { self.hi_default }; + self.cfg.min_p_hi = + if min_p > 0.0 && min_p.is_finite() { min_p.max(self.cfg.min_p_lo) } else { self.hi_default }; self.bias_mtp = 0.0; self.bias_suf = [0.0; 2]; self.last = None; @@ -176,7 +176,9 @@ impl AdaptivePolicy { if self.cost_n[c.t] >= 3.0 && stale < 48 { continue; } - if pick.is_none_or(|p| self.cost_n[c.t] < self.cost_n[p.t] || (self.cost_n[c.t] == self.cost_n[p.t] && c.rate > p.rate)) { + if pick.is_none_or(|p| { + self.cost_n[c.t] < self.cost_n[p.t] || (self.cost_n[c.t] == self.cost_n[p.t] && c.rate > p.rate) + }) { pick = Some(*c); } } @@ -191,7 +193,16 @@ impl AdaptivePolicy { for (d, &p) in offer.mtp_probs.iter().take(MAX_T).enumerate() { probs[d] = p; } - Choice { origin: best.origin, t: best.t, expected: best.expected, rate: best.rate, explored, probs, matched: offer.suffix_match, agrees: offer.suffix_agrees } + Choice { + origin: best.origin, + t: best.t, + expected: best.expected, + rate: best.rate, + explored, + probs, + matched: offer.suffix_match, + agrees: offer.suffix_agrees, + } } // ---- learning --------------------------------------------------------------------------------------------- @@ -216,7 +227,11 @@ impl AdaptivePolicy { Origin::Suffix => { let (cl, m) = (c.agrees as usize ^ 1, m_bucket(c.matched)); let predicted = self.suffix_row_rate(j, c.matched, c.agrees); - if j == 1 { self.suf_first[cl][m].add(hit, decay) } else { self.suf_cont[cl][m].add(hit, decay) } + if j == 1 { + self.suf_first[cl][m].add(hit, decay) + } else { + self.suf_cont[cl][m].add(hit, decay) + } self.bias_suf[cl] = (self.bias_suf[cl] + eta * ((hit as u8 as f64) - predicted)).clamp(-2.5, 2.5); } } @@ -256,7 +271,12 @@ impl AdaptivePolicy { for v in f.iter_mut() { *v *= 0.97; } - f[0] += 1.0; f[1] += x; f[2] += x * x; f[3] += y; f[4] += x * y; f[5] += y / (1.0 + PRIOR_SLOPE * x); + f[0] += 1.0; + f[1] += x; + f[2] += x * x; + f[3] += y; + f[4] += x * y; + f[5] += y / (1.0 + PRIOR_SLOPE * x); } self.drafts_ewma += 0.1 * (drafts_after as f64 - self.drafts_ewma); self.hold_t = (c.t as f64).max(self.hold_t * 0.92); @@ -295,7 +315,8 @@ impl AdaptivePolicy { } else { 0.04 }; - (rate * (self.cfg.row_q * self.row_slope_ms() + self.cfg.draft_step_ms) / self.survive_ewma.max(0.2)).clamp(0.0, 0.99) + (rate * (self.cfg.row_q * self.row_slope_ms() + self.cfg.draft_step_ms) / self.survive_ewma.max(0.2)) + .clamp(0.0, 0.99) } /// How deep the next MTP chain should go and the draft probability below which it stops. A chain step costs @@ -304,11 +325,14 @@ impl AdaptivePolicy { pub fn draft_plan(&self) -> DraftPlan { let max_drafts = ((self.hold_t.ceil() as usize).max(2)).min(self.cfg.max_drafts.max(1)); let a_req = self.bar(); - let rates: [f64; P_BUCKETS] = std::array::from_fn(|b| sigmoid(logit(self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + self.bias_mtp)); + let rates: [f64; P_BUCKETS] = + std::array::from_fn(|b| sigmoid(logit(self.mtp_bucket[b].rate(P_PRIOR[b], N0_BUCKET)) + self.bias_mtp)); let mut min_p = self.cfg.min_p_hi; if self.cfg.smooth_floor { // the smallest p at which the calibrated acceptance (linear between the bucket centres) reaches the bar - let centre = |b: usize| -> f64 { if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 } }; + let centre = |b: usize| -> f64 { + if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 } + }; let mut found = None; for b in 0..P_BUCKETS { if rates[b] >= a_req { diff --git a/crates/engine-core/src/spec/adaptive/impl_specstats.rs b/crates/engine-core/src/spec/adaptive/impl_specstats.rs index 52d50e4f..0d795365 100644 --- a/crates/engine-core/src/spec/adaptive/impl_specstats.rs +++ b/crates/engine-core/src/spec/adaptive/impl_specstats.rs @@ -19,13 +19,25 @@ impl SpecStats { pub fn line(&self) -> String { let hist = |h: &[u64]| h.iter().map(|n| n.to_string()).collect::>().join(","); let mean_ms: Vec = (0..=MAX_T) - .map(|t| if self.by_t[t] > 0 { format!("{:.1}", self.ms_by_t[t] / self.by_t[t] as f64) } else { "-".into() }) + .map( + |t| if self.by_t[t] > 0 { format!("{:.1}", self.ms_by_t[t] / self.by_t[t] as f64) } else { "-".into() }, + ) .collect(); format!( "rounds={} tokens={} tok_per_round={:.3} lookup_rounds={} explored={} accepted={}/{} round_ms={:.2} T_hist[0..={}]={} acc_hist={} ms_by_T={} healed={}", - self.rounds, self.tokens, - self.tokens as f64 / self.rounds.max(1) as f64, self.lookup_rounds, self.explored, self.accepted, self.offered, - self.total_ms / self.rounds.max(1) as f64, MAX_T, hist(&self.by_t), hist(&self.acc_hist), mean_ms.join(","), self.healed + self.rounds, + self.tokens, + self.tokens as f64 / self.rounds.max(1) as f64, + self.lookup_rounds, + self.explored, + self.accepted, + self.offered, + self.total_ms / self.rounds.max(1) as f64, + MAX_T, + hist(&self.by_t), + hist(&self.acc_hist), + mean_ms.join(","), + self.healed ) } } diff --git a/crates/engine-core/src/spec/adaptive/tests.rs b/crates/engine-core/src/spec/adaptive/tests.rs index 8a206bb2..8c913d4e 100644 --- a/crates/engine-core/src/spec/adaptive/tests.rs +++ b/crates/engine-core/src/spec/adaptive/tests.rs @@ -23,31 +23,67 @@ struct World { suffix_len: usize, suffix_match: usize, } -const CODE_CHEAP: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; -const CODE_COSTLY: World = World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; -const PROSE_CHEAP: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; -const PROSE_COSTLY: World = World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; -const REPEAT: World = World { p_lo: 0.5, p_hi: 1.0, calib: 0.9, base: 30.0, slope: 3.0, suffix_q: 0.995, suffix_len: 7, suffix_match: 40 }; +const CODE_CHEAP: World = + World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const CODE_COSTLY: World = + World { p_lo: 0.6, p_hi: 1.0, calib: 0.97, base: 30.0, slope: 11.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const PROSE_CHEAP: World = + World { p_lo: 0.15, p_hi: 0.9, calib: 0.85, base: 30.0, slope: 2.0, suffix_q: 0.0, suffix_len: 0, suffix_match: 0 }; +const PROSE_COSTLY: World = World { + p_lo: 0.15, + p_hi: 0.9, + calib: 0.85, + base: 30.0, + slope: 11.0, + suffix_q: 0.0, + suffix_len: 0, + suffix_match: 0, +}; +const REPEAT: World = World { + p_lo: 0.5, + p_hi: 1.0, + calib: 0.9, + base: 30.0, + slope: 3.0, + suffix_q: 0.995, + suffix_len: 7, + suffix_match: 40, +}; /// One policy-driven (`fixed == None`) or fixed-width round; returns (tokens, ms, t). -fn play(world: &World, rng: &mut Rng, policy: Option<&mut AdaptivePolicy>, fixed: Option) -> (usize, f64, usize) { +fn play( + world: &World, + rng: &mut Rng, + policy: Option<&mut AdaptivePolicy>, + fixed: Option, +) -> (usize, f64, usize) { let max_t = 8; - let probs: Vec = (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect(); + let probs: Vec = + (0..max_t - 1).map(|_| (world.p_lo + (world.p_hi - world.p_lo) * rng.next()) as f32).collect(); let hits = |rng: &mut Rng, q: f64, n: usize| -> usize { let mut a = 0; - while a < n && rng.next() < q { a += 1; } + while a < n && rng.next() < q { + a += 1; + } a }; let accept_mtp = |rng: &mut Rng, rows: usize| -> usize { let mut a = 0; - while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { a += 1; } + while a < rows && rng.next() < (probs[a] as f64 * world.calib).min(0.999) { + a += 1; + } a }; let noise = 1.0 + 0.04 * (rng.next() - 0.5); let cost = |t: usize| (world.base + world.slope * (t - 1) as f64) * noise; match (policy, fixed) { (Some(pol), _) => { - let offer = Offer { mtp_probs: &probs, suffix_k: world.suffix_len, suffix_match: world.suffix_match, suffix_agrees: true }; + let offer = Offer { + mtp_probs: &probs, + suffix_k: world.suffix_len, + suffix_match: world.suffix_match, + suffix_agrees: true, + }; let c = pol.choose(&offer); let a = match c.origin { Origin::Mtp => accept_mtp(rng, c.t - 1), @@ -73,7 +109,8 @@ fn fixed_rate(world: &World, t: usize) -> f64 { let (mut tok, mut ms) = (0usize, 0.0); for _ in 0..4000 { let (a, m, _) = play(world, &mut rng, None, Some(t)); - tok += a; ms += m; + tok += a; + ms += m; } tok as f64 / ms } @@ -90,8 +127,12 @@ fn adaptive_run(world_seq: &[(World, usize)], cfg: AdaptiveConfig) -> (f64, Vec< let mut tail = 0usize; for i in 0..*n { let (a, m, t) = play(w, &mut rng, Some(&mut pol), None); - tok += a; ms += m; sum_t += t; - if i >= *n / 2 { tail += t; } + tok += a; + ms += m; + sum_t += t; + if i >= *n / 2 { + tail += t; + } } let _ = sum_t; mean_t.push(tail as f64 / (*n - *n / 2) as f64); @@ -102,177 +143,6 @@ fn cfg() -> AdaptiveConfig { AdaptiveConfig::new(8, 7) } -#[test] -fn stationary_regimes_reach_the_best_fixed_width() { - for w in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { - let (bt, best) = best_fixed(&w); - let (rate, _) = adaptive_run(&[(w, 4000)], cfg()); - assert!(rate >= 0.97 * best, "adaptive {rate:.5} vs best fixed t={bt} {best:.5}"); - for t in [3usize, 4, 6] { - assert!(rate >= 0.99 * fixed_rate(&w, t), "adaptive {rate:.5} vs fixed {t}"); - } - } -} - -#[test] -fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() { - let (_, cheap) = adaptive_run(&[(CODE_CHEAP, 1500)], cfg()); - let (_, costly) = adaptive_run(&[(CODE_COSTLY, 1500)], cfg()); - assert!(cheap[0] > costly[0] + 1.5, "cheap {:.2} costly {:.2}", cheap[0], costly[0]); - assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]); -} - -#[test] -fn it_follows_a_change_of_content_and_of_cost() { - let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)]; - let (rate, tail) = adaptive_run(&seq, cfg()); - assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}"); - // against the oracle that knows each segment's best fixed width - let (mut tok, mut ms) = (0.0, 0.0); - for (w, n) in seq { - let (_, r) = best_fixed(&w); - tok += r * n as f64 * 1.0; - ms += n as f64; - } - let _ = (tok, ms); - let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() / seq.iter().map(|(_, n)| *n as f64).sum::(); - assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}"); - // and it beats every single fixed width over the whole sequence - let whole = |t: usize| -> f64 { - let mut rng = Rng(3); - let (mut tk, mut m) = (0usize, 0.0); - for (w, n) in seq { - for _ in 0..n { - let (a, c, _) = play(&w, &mut rng, None, Some(t)); - tk += a; m += c; - } - } - tk as f64 / m - }; - for t in 1..=8 { - assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t)); - } -} - -#[test] -fn reaction_to_a_switch_takes_tens_of_rounds_not_hundreds() { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(5); - for _ in 0..600 { play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); } - let mut ts = Vec::new(); - for _ in 0..120 { ts.push(play(&CODE_CHEAP, &mut rng, Some(&mut pol), None).2); } - let late: f64 = ts[60..].iter().sum::() as f64 / 60.0; - assert!(late >= 5.5, "width 60..120 rounds after the cost dropped: {late:.2}"); -} - -#[test] -fn exploration_costs_little_and_is_the_only_way_to_learn_unseen_widths() { - let mut off = cfg(); - off.explore_period = 0; - let (on_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], cfg()); - let (off_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], off); - assert!(on_rate >= 0.97 * off_rate, "on {on_rate:.5} off {off_rate:.5}"); - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(9); - let mut explored = 0; - for _ in 0..400 { - let before = pol.since_explore; - let _ = before; - let probs = [0.9f32; 7]; - let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 0, suffix_match: 0, suffix_agrees: false }); - explored += c.explored as usize; - pol.observe(&c, 3.min(c.t - 1), 40.0 + 2.0 * c.t as f64 + rng.next(), 3); - } - assert!(explored >= 4 && explored <= 60, "explored {explored} of 400"); -} - -#[test] -fn a_long_repeated_suffix_opens_the_widest_window() { - let (rate, tail) = adaptive_run(&[(REPEAT, 600)], cfg()); - assert!(tail[0] >= 7.5, "mean width {:.2}", tail[0]); - assert!(rate > fixed_rate(&REPEAT, 4) * 1.3, "rate {rate:.5} vs fixed-4 {:.5}", fixed_rate(&REPEAT, 4)); -} - -#[test] -fn a_suffix_that_keeps_missing_is_dropped() { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(21); - let probs = [0.9f32, 0.9, 0.9, 0.9, 0.8, 0.8, 0.7]; - let mut suffix_late = 0; - for i in 0..600 { - // a stale short match that never continues, MTP is right 85 % of the time - let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 5, suffix_match: 4, suffix_agrees: false }); - let a = match c.origin { - Origin::Suffix => 0, - Origin::Mtp => { let mut a = 0; while a < c.t - 1 && rng.next() < 0.85 { a += 1; } a } - }; - if i >= 300 && c.origin == Origin::Suffix && c.t > 1 { suffix_late += 1; } - pol.observe(&c, a, 40.0 + 3.0 * c.t as f64, 3); - } - assert!(suffix_late <= 20, "{suffix_late} late suffix rounds"); -} - -#[test] -fn unmeasured_widths_are_interpolated_from_the_measured_ones() { - let mut pol = AdaptivePolicy::new(cfg()); - for i in 0..200 { - let t = [2usize, 4, 6][i % 3]; - let c = Choice { origin: Origin::Mtp, t, expected: 2.0, rate: 0.04, explored: false, probs: [0.8; MAX_T], matched: 0, agrees: false }; - pol.observe(&c, 1, 30.0 + 5.0 * (t - 1) as f64 + 0.45 * 3.0, 3); - } - for t in [1usize, 3, 5, 7, 8] { - let want = 30.0 + 5.0 * (t - 1) as f64; - let got = pol.window_ms(t); - assert!((got - want).abs() <= 0.1 * want, "t={t}: {got:.1} vs {want:.1}"); - } - assert!((pol.row_slope_ms() - 5.0).abs() < 1.0); -} - -#[test] -fn the_calibration_follows_the_drafter() { - // a drafter that is right half as often as it claims: its 0.9 drafts must be believed less than 0.9 - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(2); - for _ in 0..800 { - let c = Choice { origin: Origin::Mtp, t: 4, expected: 2.0, rate: 0.04, explored: false, probs: [0.92; MAX_T], matched: 0, agrees: false }; - let mut a = 0; - while a < 3 && rng.next() < 0.45 { a += 1; } - pol.observe(&c, a, 40.0, 3); - } - let r = pol.mtp_rate(1, 0.92); - assert!((r - 0.45).abs() < 0.1, "calibrated rate {r:.3}"); - assert!(pol.mtp_rate(1, 0.6) < 0.8); -} - -#[test] -fn the_draft_plan_stays_inside_its_bounds_and_follows_the_cost() { - let mut cheap = AdaptivePolicy::new(cfg()); - let mut costly = AdaptivePolicy::new(cfg()); - let mut rng = Rng(4); - for _ in 0..500 { - play(&CODE_CHEAP, &mut rng, Some(&mut cheap), None); - play(&CODE_COSTLY, &mut rng, Some(&mut costly), None); - } - let (a, b) = (cheap.draft_plan(), costly.draft_plan()); - for p in [a, b] { - assert!((1..=7).contains(&p.max_drafts) && (0.10..=0.90).contains(&p.min_p), "{p:?}"); - } - assert!(a.max_drafts > b.max_drafts, "{a:?} {b:?}"); - assert!(a.min_p <= b.min_p, "{a:?} {b:?}"); -} - -#[test] -fn replay_arm_options_set_the_named_constants_and_refuse_the_unknown() { - let mut c = cfg(); - assert!(c.set_option("step", "0.3") && c.set_option("explore", "0") && c.set_option("margin", "0.05") && c.set_option("min_p_lo", "0.2")); - assert!(c.set_option("alpha", "0.2") && c.set_option("decay", "0.99") && c.set_option("bias", "0.1")); - assert_eq!((c.draft_step_ms, c.explore_period, c.margin, c.min_p_lo), (0.3, 0, 0.05, 0.2)); - assert_eq!((c.cost_alpha, c.decay, c.bias_rate), (0.2, 0.99, 0.1)); - let before = c; - assert!(!c.set_option("nope", "1") && !c.set_option("step", "fast")); - assert_eq!(c, before); -} - /// The earlier rule, kept as the reference: the floor is the lower edge of the first bucket whose calibrated acceptance clears the bar. fn legacy_plan(pol: &AdaptivePolicy) -> DraftPlan { let max_drafts = ((pol.hold_t.ceil() as usize).max(2)).min(pol.cfg.max_drafts.max(1)); @@ -289,110 +159,7 @@ fn legacy_plan(pol: &AdaptivePolicy) -> DraftPlan { DraftPlan { max_drafts, min_p: min_p.clamp(pol.cfg.min_p_lo, pol.cfg.min_p_hi) } } -#[test] -fn the_default_draft_plan_is_the_earlier_rule_and_the_new_options_only_lower_or_smooth_the_floor() { - let mut rng = Rng(8); - for world in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { - let mut pol = AdaptivePolicy::new(cfg()); - let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); - cheaper.row_q = 0.5; - smooth.smooth_floor = true; - measured.measured_rate = true; - let (mut pc, mut ps, mut pm) = (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); - for i in 0..600 { - let mut r2 = Rng(i + 3); - play(&world, &mut rng, Some(&mut pol), None); - play(&world, &mut r2, Some(&mut pc), None); - let mut r3 = Rng(i + 3); - play(&world, &mut r3, Some(&mut ps), None); - let mut r4 = Rng(i + 3); - play(&world, &mut r4, Some(&mut pm), None); - assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); - let l = legacy_plan(&pc); - assert!(pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, "row_q 0.5 raised the floor at round {i}"); - let sp = ps.draft_plan().min_p; - assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); - let pl = pm.draft_plan(); - assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); - } - } -} - -#[test] -fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { - let new = AdaptiveConfig::new(8, 7); - assert_eq!(new.min_p_hi, FLOOR_CEILING); - let legacy = new.with_policy(Some("legacy")); - assert_eq!(legacy.min_p_hi, 0.90); - // everything but the ceiling is the earlier policy's, field by field - let earlier = AdaptiveConfig { - max_t: 8, max_drafts: 7, margin: 0.02, explore_period: 32, min_p_lo: 0.10, min_p_hi: 0.90, draft_step_ms: 0.45, - cost_alpha: 0.12, decay: 0.995, bias_rate: 0.06, row_q: 1.0, smooth_floor: false, measured_rate: false, - }; - assert_eq!(legacy, earlier); - assert_eq!(new.with_policy(Some("v1")), earlier); - assert_eq!(new.with_policy(None), new); - assert_eq!(new.with_policy(Some("current")), new); - // a request that names a ceiling keeps it in both policies; one that does not gets the policy's - for (cfg, want) in [(new, FLOOR_CEILING), (legacy, 0.90)] { - let mut pol = AdaptivePolicy::new(cfg); - pol.begin_request(0.0); - assert_eq!(pol.cfg.min_p_hi, want); - pol.begin_request(0.7); - assert_eq!(pol.cfg.min_p_hi, 0.7); - pol.begin_request(0.0); - assert_eq!(pol.cfg.min_p_hi, want); - } - // the chain floor the plan asks for never exceeds the ceiling of the policy - let mut pol = AdaptivePolicy::new(new); - pol.begin_request(0.0); - let mut rng = Rng(5); - for _ in 0..600 { - play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); - assert!(pol.draft_plan().min_p <= FLOOR_CEILING + 1e-6); - } -} - -#[test] -fn the_smooth_floor_moves_continuously_with_the_bar() { - // synthetic, calibrated tables: the floor must not jump by a bucket for a small change of the bar - let mut pol = AdaptivePolicy::new({ let mut c = cfg(); c.smooth_floor = true; c }); - for b in 0..P_BUCKETS { - let centre = if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 }; - for _ in 0..400 { - pol.mtp_bucket[b].add(false, 1.0); - } - pol.mtp_bucket[b].ok = 400.0 * centre; - } - let mut last: Option = None; - for step in 0..30 { - pol.rate_ewma = 0.10 + 0.002 * step as f64; - pol.survive_ewma = 0.5; - let p = pol.draft_plan().min_p; - if let Some(l) = last { - assert!((p - l).abs() < 0.08, "floor jumped from {l} to {p} at step {step}"); - assert!(p >= l - 1e-6, "floor fell while the bar rose"); - } - last = Some(p); - } -} - -#[test] -fn a_trace_is_reproducible() { - let run = || { - let mut pol = AdaptivePolicy::new(cfg()); - let mut rng = Rng(1); - (0..300).map(|_| play(&PROSE_CHEAP, &mut rng, Some(&mut pol), None).2).collect::>() - }; - assert_eq!(run(), run()); -} - -#[test] -fn stats_line_reports_the_histograms() { - let mut s = SpecStats::default(); - s.record(4, 3, false, false, 50.0); - s.record(6, 0, true, true, 60.0); - let l = s.line(); - assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}"); - assert!(l.contains("accepted=3/8"), "{l}"); -} +#[path = "tests/default_ceiling.rs"] +mod default_ceiling; +#[path = "tests/stationary_regimes_reach_the_best.rs"] +mod stationary_regimes_reach_the_best; diff --git a/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs new file mode 100644 index 00000000..2b1fbb9c --- /dev/null +++ b/crates/engine-core/src/spec/adaptive/tests/default_ceiling.rs @@ -0,0 +1,98 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly, the_smooth_floor_moves_continuously_with_the_bar, a_trace_is_reproducible, stats_line_reports_the_histograms. + +#[allow(unused_imports)] +use super::*; + +#[test] +fn the_default_ceiling_is_the_new_one_and_the_legacy_switch_restores_the_old_policy_exactly() { + let new = AdaptiveConfig::new(8, 7); + assert_eq!(new.min_p_hi, FLOOR_CEILING); + let legacy = new.with_policy(Some("legacy")); + assert_eq!(legacy.min_p_hi, 0.90); + // everything but the ceiling is the earlier policy's, field by field + let earlier = AdaptiveConfig { + max_t: 8, + max_drafts: 7, + margin: 0.02, + explore_period: 32, + min_p_lo: 0.10, + min_p_hi: 0.90, + draft_step_ms: 0.45, + cost_alpha: 0.12, + decay: 0.995, + bias_rate: 0.06, + row_q: 1.0, + smooth_floor: false, + measured_rate: false, + }; + assert_eq!(legacy, earlier); + assert_eq!(new.with_policy(Some("v1")), earlier); + assert_eq!(new.with_policy(None), new); + assert_eq!(new.with_policy(Some("current")), new); + // a request that names a ceiling keeps it in both policies; one that does not gets the policy's + for (cfg, want) in [(new, FLOOR_CEILING), (legacy, 0.90)] { + let mut pol = AdaptivePolicy::new(cfg); + pol.begin_request(0.0); + assert_eq!(pol.cfg.min_p_hi, want); + pol.begin_request(0.7); + assert_eq!(pol.cfg.min_p_hi, 0.7); + pol.begin_request(0.0); + assert_eq!(pol.cfg.min_p_hi, want); + } + // the chain floor the plan asks for never exceeds the ceiling of the policy + let mut pol = AdaptivePolicy::new(new); + pol.begin_request(0.0); + let mut rng = Rng(5); + for _ in 0..600 { + play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); + assert!(pol.draft_plan().min_p <= FLOOR_CEILING + 1e-6); + } +} + +#[test] +fn the_smooth_floor_moves_continuously_with_the_bar() { + // synthetic, calibrated tables: the floor must not jump by a bucket for a small change of the bar + let mut pol = AdaptivePolicy::new({ + let mut c = cfg(); + c.smooth_floor = true; + c + }); + for b in 0..P_BUCKETS { + let centre = if b + 1 < P_BUCKETS { 0.5 * (P_EDGES[b] + P_EDGES[b + 1]) as f64 } else { 0.975 }; + for _ in 0..400 { + pol.mtp_bucket[b].add(false, 1.0); + } + pol.mtp_bucket[b].ok = 400.0 * centre; + } + let mut last: Option = None; + for step in 0..30 { + pol.rate_ewma = 0.10 + 0.002 * step as f64; + pol.survive_ewma = 0.5; + let p = pol.draft_plan().min_p; + if let Some(l) = last { + assert!((p - l).abs() < 0.08, "floor jumped from {l} to {p} at step {step}"); + assert!(p >= l - 1e-6, "floor fell while the bar rose"); + } + last = Some(p); + } +} + +#[test] +fn a_trace_is_reproducible() { + let run = || { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(1); + (0..300).map(|_| play(&PROSE_CHEAP, &mut rng, Some(&mut pol), None).2).collect::>() + }; + assert_eq!(run(), run()); +} + +#[test] +fn stats_line_reports_the_histograms() { + let mut s = SpecStats::default(); + s.record(4, 3, false, false, 50.0); + s.record(6, 0, true, true, 60.0); + let l = s.line(); + assert!(l.contains("rounds=2 tokens=5 tok_per_round=2.500") && l.contains("lookup_rounds=1 explored=1"), "{l}"); + assert!(l.contains("accepted=3/8"), "{l}"); +} diff --git a/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs b/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs new file mode 100644 index 00000000..52625861 --- /dev/null +++ b/crates/engine-core/src/spec/adaptive/tests/stationary_regimes_reach_the_best.rs @@ -0,0 +1,247 @@ +//! Tests of tests by topic (moved out of the test file by STRA-338): stationary_regimes_reach_the_best_fixed_width, it_widens_when_rows_are_cheap_and_narrows_when_they_are_not, it_follows_a_change_of_content_and_of_cost, reaction_to_a_switch_takes_tens_of_rounds_not_hundreds .... + +#[allow(unused_imports)] +use super::*; + +#[test] +fn stationary_regimes_reach_the_best_fixed_width() { + for w in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { + let (bt, best) = best_fixed(&w); + let (rate, _) = adaptive_run(&[(w, 4000)], cfg()); + assert!(rate >= 0.97 * best, "adaptive {rate:.5} vs best fixed t={bt} {best:.5}"); + for t in [3usize, 4, 6] { + assert!(rate >= 0.99 * fixed_rate(&w, t), "adaptive {rate:.5} vs fixed {t}"); + } + } +} + +#[test] +fn it_widens_when_rows_are_cheap_and_narrows_when_they_are_not() { + let (_, cheap) = adaptive_run(&[(CODE_CHEAP, 1500)], cfg()); + let (_, costly) = adaptive_run(&[(CODE_COSTLY, 1500)], cfg()); + assert!(cheap[0] > costly[0] + 1.5, "cheap {:.2} costly {:.2}", cheap[0], costly[0]); + assert!(cheap[0] >= 6.0, "cheap windows are wide: {:.2}", cheap[0]); +} + +#[test] +fn it_follows_a_change_of_content_and_of_cost() { + let seq = [(CODE_CHEAP, 800), (PROSE_COSTLY, 800), (CODE_CHEAP, 800), (CODE_COSTLY, 800)]; + let (rate, tail) = adaptive_run(&seq, cfg()); + assert!(tail[0] > tail[1] + 2.0 && tail[2] > tail[1] + 2.0 && tail[2] > tail[3] + 1.5, "{tail:?}"); + // against the oracle that knows each segment's best fixed width + let (mut tok, mut ms) = (0.0, 0.0); + for (w, n) in seq { + let (_, r) = best_fixed(&w); + tok += r * n as f64 * 1.0; + ms += n as f64; + } + let _ = (tok, ms); + let oracle: f64 = seq.iter().map(|(w, n)| best_fixed(w).1 * *n as f64).sum::() + / seq.iter().map(|(_, n)| *n as f64).sum::(); + assert!(rate >= 0.93 * oracle, "adaptive {rate:.5} vs per-segment oracle {oracle:.5}"); + // and it beats every single fixed width over the whole sequence + let whole = |t: usize| -> f64 { + let mut rng = Rng(3); + let (mut tk, mut m) = (0usize, 0.0); + for (w, n) in seq { + for _ in 0..n { + let (a, c, _) = play(&w, &mut rng, None, Some(t)); + tk += a; + m += c; + } + } + tk as f64 / m + }; + for t in 1..=8 { + assert!(rate >= whole(t) * 0.995, "fixed {t}: {:.5} vs adaptive {rate:.5}", whole(t)); + } +} + +#[test] +fn reaction_to_a_switch_takes_tens_of_rounds_not_hundreds() { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(5); + for _ in 0..600 { + play(&CODE_COSTLY, &mut rng, Some(&mut pol), None); + } + let mut ts = Vec::new(); + for _ in 0..120 { + ts.push(play(&CODE_CHEAP, &mut rng, Some(&mut pol), None).2); + } + let late: f64 = ts[60..].iter().sum::() as f64 / 60.0; + assert!(late >= 5.5, "width 60..120 rounds after the cost dropped: {late:.2}"); +} + +#[test] +fn exploration_costs_little_and_is_the_only_way_to_learn_unseen_widths() { + let mut off = cfg(); + off.explore_period = 0; + let (on_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], cfg()); + let (off_rate, _) = adaptive_run(&[(CODE_CHEAP, 3000)], off); + assert!(on_rate >= 0.97 * off_rate, "on {on_rate:.5} off {off_rate:.5}"); + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(9); + let mut explored = 0; + for _ in 0..400 { + let before = pol.since_explore; + let _ = before; + let probs = [0.9f32; 7]; + let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 0, suffix_match: 0, suffix_agrees: false }); + explored += c.explored as usize; + pol.observe(&c, 3.min(c.t - 1), 40.0 + 2.0 * c.t as f64 + rng.next(), 3); + } + assert!(explored >= 4 && explored <= 60, "explored {explored} of 400"); +} + +#[test] +fn a_long_repeated_suffix_opens_the_widest_window() { + let (rate, tail) = adaptive_run(&[(REPEAT, 600)], cfg()); + assert!(tail[0] >= 7.5, "mean width {:.2}", tail[0]); + assert!(rate > fixed_rate(&REPEAT, 4) * 1.3, "rate {rate:.5} vs fixed-4 {:.5}", fixed_rate(&REPEAT, 4)); +} + +#[test] +fn a_suffix_that_keeps_missing_is_dropped() { + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(21); + let probs = [0.9f32, 0.9, 0.9, 0.9, 0.8, 0.8, 0.7]; + let mut suffix_late = 0; + for i in 0..600 { + // a stale short match that never continues, MTP is right 85 % of the time + let c = pol.choose(&Offer { mtp_probs: &probs, suffix_k: 5, suffix_match: 4, suffix_agrees: false }); + let a = match c.origin { + Origin::Suffix => 0, + Origin::Mtp => { + let mut a = 0; + while a < c.t - 1 && rng.next() < 0.85 { + a += 1; + } + a + } + }; + if i >= 300 && c.origin == Origin::Suffix && c.t > 1 { + suffix_late += 1; + } + pol.observe(&c, a, 40.0 + 3.0 * c.t as f64, 3); + } + assert!(suffix_late <= 20, "{suffix_late} late suffix rounds"); +} + +#[test] +fn unmeasured_widths_are_interpolated_from_the_measured_ones() { + let mut pol = AdaptivePolicy::new(cfg()); + for i in 0..200 { + let t = [2usize, 4, 6][i % 3]; + let c = Choice { + origin: Origin::Mtp, + t, + expected: 2.0, + rate: 0.04, + explored: false, + probs: [0.8; MAX_T], + matched: 0, + agrees: false, + }; + pol.observe(&c, 1, 30.0 + 5.0 * (t - 1) as f64 + 0.45 * 3.0, 3); + } + for t in [1usize, 3, 5, 7, 8] { + let want = 30.0 + 5.0 * (t - 1) as f64; + let got = pol.window_ms(t); + assert!((got - want).abs() <= 0.1 * want, "t={t}: {got:.1} vs {want:.1}"); + } + assert!((pol.row_slope_ms() - 5.0).abs() < 1.0); +} + +#[test] +fn the_calibration_follows_the_drafter() { + // a drafter that is right half as often as it claims: its 0.9 drafts must be believed less than 0.9 + let mut pol = AdaptivePolicy::new(cfg()); + let mut rng = Rng(2); + for _ in 0..800 { + let c = Choice { + origin: Origin::Mtp, + t: 4, + expected: 2.0, + rate: 0.04, + explored: false, + probs: [0.92; MAX_T], + matched: 0, + agrees: false, + }; + let mut a = 0; + while a < 3 && rng.next() < 0.45 { + a += 1; + } + pol.observe(&c, a, 40.0, 3); + } + let r = pol.mtp_rate(1, 0.92); + assert!((r - 0.45).abs() < 0.1, "calibrated rate {r:.3}"); + assert!(pol.mtp_rate(1, 0.6) < 0.8); +} + +#[test] +fn the_draft_plan_stays_inside_its_bounds_and_follows_the_cost() { + let mut cheap = AdaptivePolicy::new(cfg()); + let mut costly = AdaptivePolicy::new(cfg()); + let mut rng = Rng(4); + for _ in 0..500 { + play(&CODE_CHEAP, &mut rng, Some(&mut cheap), None); + play(&CODE_COSTLY, &mut rng, Some(&mut costly), None); + } + let (a, b) = (cheap.draft_plan(), costly.draft_plan()); + for p in [a, b] { + assert!((1..=7).contains(&p.max_drafts) && (0.10..=0.90).contains(&p.min_p), "{p:?}"); + } + assert!(a.max_drafts > b.max_drafts, "{a:?} {b:?}"); + assert!(a.min_p <= b.min_p, "{a:?} {b:?}"); +} + +#[test] +fn replay_arm_options_set_the_named_constants_and_refuse_the_unknown() { + let mut c = cfg(); + assert!( + c.set_option("step", "0.3") + && c.set_option("explore", "0") + && c.set_option("margin", "0.05") + && c.set_option("min_p_lo", "0.2") + ); + assert!(c.set_option("alpha", "0.2") && c.set_option("decay", "0.99") && c.set_option("bias", "0.1")); + assert_eq!((c.draft_step_ms, c.explore_period, c.margin, c.min_p_lo), (0.3, 0, 0.05, 0.2)); + assert_eq!((c.cost_alpha, c.decay, c.bias_rate), (0.2, 0.99, 0.1)); + let before = c; + assert!(!c.set_option("nope", "1") && !c.set_option("step", "fast")); + assert_eq!(c, before); +} + +#[test] +fn the_default_draft_plan_is_the_earlier_rule_and_the_new_options_only_lower_or_smooth_the_floor() { + let mut rng = Rng(8); + for world in [CODE_CHEAP, CODE_COSTLY, PROSE_CHEAP, PROSE_COSTLY] { + let mut pol = AdaptivePolicy::new(cfg()); + let (mut cheaper, mut smooth, mut measured) = (cfg(), cfg(), cfg()); + cheaper.row_q = 0.5; + smooth.smooth_floor = true; + measured.measured_rate = true; + let (mut pc, mut ps, mut pm) = + (AdaptivePolicy::new(cheaper), AdaptivePolicy::new(smooth), AdaptivePolicy::new(measured)); + for i in 0..600 { + let mut r2 = Rng(i + 3); + play(&world, &mut rng, Some(&mut pol), None); + play(&world, &mut r2, Some(&mut pc), None); + let mut r3 = Rng(i + 3); + play(&world, &mut r3, Some(&mut ps), None); + let mut r4 = Rng(i + 3); + play(&world, &mut r4, Some(&mut pm), None); + assert_eq!(pol.draft_plan(), legacy_plan(&pol), "round {i}"); + let l = legacy_plan(&pc); + assert!( + pc.draft_plan().min_p <= l.min_p + 1e-6 && pc.draft_plan().max_drafts == l.max_drafts, + "row_q 0.5 raised the floor at round {i}" + ); + let sp = ps.draft_plan().min_p; + assert!((0.10..=0.90).contains(&sp), "smooth floor {sp} out of bounds at round {i}"); + let pl = pm.draft_plan(); + assert!((0.10..=0.90).contains(&pl.min_p) && (1..=7).contains(&pl.max_drafts), "{pl:?}"); + } + } +} diff --git a/crates/engine-core/src/spec/policy.rs b/crates/engine-core/src/spec/policy.rs index a80e8081..f02684ef 100644 --- a/crates/engine-core/src/spec/policy.rs +++ b/crates/engine-core/src/spec/policy.rs @@ -7,63 +7,113 @@ const SHAPE: [f64; 9] = [0.0, 1.0, 1.35, 1.7, 2.05, 2.45, 2.85, 3.25, 3.6]; const PRIOR_Q: [f64; 4] = [0.75, 0.88, 0.93, 0.96]; #[derive(Clone, Copy, Debug, PartialEq)] -pub struct Pick { pub lookup: bool, pub t: usize } +pub struct Pick { + pub lookup: bool, + pub t: usize, +} #[derive(Clone)] pub struct DraftPolicy { - max_t: usize, margin: f64, - cost: [f64; 9], cost_n: [f64; 9], - mtp_tok: [f64; 9], mtp_n: [f64; 9], - ok: [f64; 4], bad: [f64; 4], + max_t: usize, + margin: f64, + cost: [f64; 9], + cost_n: [f64; 9], + mtp_tok: [f64; 9], + mtp_n: [f64; 9], + ok: [f64; 4], + bad: [f64; 4], } impl DraftPolicy { pub fn new(max_t: usize, margin: f64) -> Result { - if !(1..=MAX_T).contains(&max_t) || !margin.is_finite() { return Err(Error::InvalidDimension); } - Ok(Self { max_t, margin, cost: [0.0;9], cost_n: [0.0;9], mtp_tok: [0.0;9], mtp_n: [0.0;9], ok: [0.0;4], bad: [0.0;4] }) + if !(1..=MAX_T).contains(&max_t) || !margin.is_finite() { + return Err(Error::InvalidDimension); + } + Ok(Self { + max_t, + margin, + cost: [0.0; 9], + cost_n: [0.0; 9], + mtp_tok: [0.0; 9], + mtp_n: [0.0; 9], + ok: [0.0; 4], + bad: [0.0; 4], + }) + } + fn bucket(n: usize) -> usize { + if n < 6 { + 0 + } else if n < 12 { + 1 + } else if n < 24 { + 2 + } else { + 3 + } } - fn bucket(n: usize) -> usize { if n<6 {0} else if n<12 {1} else if n<24 {2} else {3} } pub fn lookup_rate(&self, n: usize) -> f64 { - let b=Self::bucket(n); (self.ok[b]+4.0*PRIOR_Q[b])/(self.ok[b]+self.bad[b]+4.0) + let b = Self::bucket(n); + (self.ok[b] + 4.0 * PRIOR_Q[b]) / (self.ok[b] + self.bad[b] + 4.0) } pub fn cost_ms(&self, t: usize) -> f64 { - let t=t.clamp(1,MAX_T); - if self.cost_n[t]>0.0 { return self.cost[t]; } - let (mut num,mut den)=(0.0,0.0); - for u in 1..=MAX_T { if self.cost_n[u]>0.0 { - let w=self.cost_n[u].min(20.0); num+=w*self.cost[u]*SHAPE[t]/SHAPE[u]; den+=w; - }} - if den>0.0 {num/den} else {SHAPE[t]} + let t = t.clamp(1, MAX_T); + if self.cost_n[t] > 0.0 { + return self.cost[t]; + } + let (mut num, mut den) = (0.0, 0.0); + for u in 1..=MAX_T { + if self.cost_n[u] > 0.0 { + let w = self.cost_n[u].min(20.0); + num += w * self.cost[u] * SHAPE[t] / SHAPE[u]; + den += w; + } + } + if den > 0.0 { num / den } else { SHAPE[t] } } - fn mtp_tokens(&self,t:usize)->f64 { - if self.mtp_n[t]>0.0 {self.mtp_tok[t]} else {1.0+0.7*(t as f64-1.0)} + fn mtp_tokens(&self, t: usize) -> f64 { + if self.mtp_n[t] > 0.0 { self.mtp_tok[t] } else { 1.0 + 0.7 * (t as f64 - 1.0) } } - pub fn choose(&self,t_mtp:usize,lookup_k:usize,matched:usize)->Pick { - let mut p=Pick { lookup:false,t:t_mtp.clamp(1,self.max_t) }; - if lookup_k==0 { return p; } - let base=self.mtp_tokens(p.t)/self.cost_ms(p.t); - let q=self.lookup_rate(matched); - let (mut e,mut qi,mut best,mut best_t)=(1.0,1.0,0.0,0); - for k in 1..=lookup_k.min(self.max_t-1) { - qi*=q; e+=qi; let r=e/self.cost_ms(k+1); - if r>best {best=r;best_t=k+1;} + pub fn choose(&self, t_mtp: usize, lookup_k: usize, matched: usize) -> Pick { + let mut p = Pick { lookup: false, t: t_mtp.clamp(1, self.max_t) }; + if lookup_k == 0 { + return p; + } + let base = self.mtp_tokens(p.t) / self.cost_ms(p.t); + let q = self.lookup_rate(matched); + let (mut e, mut qi, mut best, mut best_t) = (1.0, 1.0, 0.0, 0); + for k in 1..=lookup_k.min(self.max_t - 1) { + qi *= q; + e += qi; + let r = e / self.cost_ms(k + 1); + if r > best { + best = r; + best_t = k + 1; + } + } + if best_t > 0 && best > base * (1.0 + self.margin) { + return Pick { lookup: true, t: best_t }; + } + let t_full = lookup_k.min(self.max_t - 1) + 1; + if t_full > p.t && self.cost_n[t_full] < 3.0 && q >= 0.85 { + p.lookup = true; + p.t = t_full; } - if best_t>0 && best>base*(1.0+self.margin) { return Pick {lookup:true,t:best_t}; } - let t_full=lookup_k.min(self.max_t-1)+1; - if t_full>p.t && self.cost_n[t_full]<3.0 && q>=0.85 {p.lookup=true;p.t=t_full;} p } - pub fn observe(&mut self,lookup:bool,t:usize,accepted:usize,matched:usize,round_ms:f64)->Result<()> { - if !(1..=MAX_T).contains(&t) || accepted>=t || !round_ms.is_finite() {return Err(Error::InvalidDimension);} - if round_ms>0.0 { - self.cost[t]=if self.cost_n[t]>0.0 {(1.0-0.1)*self.cost[t]+0.1*round_ms} else {round_ms}; - self.cost_n[t]+=1.0; + pub fn observe(&mut self, lookup: bool, t: usize, accepted: usize, matched: usize, round_ms: f64) -> Result<()> { + if !(1..=MAX_T).contains(&t) || accepted >= t || !round_ms.is_finite() { + return Err(Error::InvalidDimension); + } + if round_ms > 0.0 { + self.cost[t] = if self.cost_n[t] > 0.0 { (1.0 - 0.1) * self.cost[t] + 0.1 * round_ms } else { round_ms }; + self.cost_n[t] += 1.0; } if lookup { - let b=Self::bucket(matched); self.ok[b]=0.97*self.ok[b]+accepted as f64; - self.bad[b]=0.97*self.bad[b]+if accepted0.0 {(1.0-0.05)*self.mtp_tok[t]+0.05*got} else {got}; - self.mtp_n[t]+=1.0; + let got = accepted as f64 + 1.0; + self.mtp_tok[t] = if self.mtp_n[t] > 0.0 { (1.0 - 0.05) * self.mtp_tok[t] + 0.05 * got } else { got }; + self.mtp_n[t] += 1.0; } Ok(()) } @@ -71,58 +121,131 @@ impl DraftPolicy { #[derive(Clone)] pub struct CostModel { - pub dense_ms:f64, pub dense_ratio:[f64;9], - pub cpu_all_miss_ms:f64, pub hit_rate:f64, pub distinct_ratio:[f64;9], - pub extra_use_cost:f64, pub sync_ms:f64, pub mtp_draft_ms:f64, pub lookup_draft_ms:f64, + pub dense_ms: f64, + pub dense_ratio: [f64; 9], + pub cpu_all_miss_ms: f64, + pub hit_rate: f64, + pub distinct_ratio: [f64; 9], + pub extra_use_cost: f64, + pub sync_ms: f64, + pub mtp_draft_ms: f64, + pub lookup_draft_ms: f64, } impl Default for CostModel { - fn default()->Self {Self {dense_ms:11.0,dense_ratio:[1.0,1.05,1.3,1.45,1.85,2.2,2.6,3.0,3.3], - cpu_all_miss_ms:15.8,hit_rate:0.55,distinct_ratio:[1.0,1.70,2.31,2.88,3.40,3.89,4.35,4.80,5.2], - extra_use_cost:0.25,sync_ms:2.4,mtp_draft_ms:1.2,lookup_draft_ms:0.01}} + fn default() -> Self { + Self { + dense_ms: 11.0, + dense_ratio: [1.0, 1.05, 1.3, 1.45, 1.85, 2.2, 2.6, 3.0, 3.3], + cpu_all_miss_ms: 15.8, + hit_rate: 0.55, + distinct_ratio: [1.0, 1.70, 2.31, 2.88, 3.40, 3.89, 4.35, 4.80, 5.2], + extra_use_cost: 0.25, + sync_ms: 2.4, + mtp_draft_ms: 1.2, + lookup_draft_ms: 0.01, + } + } } impl CostModel { - pub fn step_ms(&self,k:usize,mtp:bool)->f64 { - let n=k.saturating_add(1).clamp(1,9); - let dense=self.dense_ms*self.dense_ratio[n-1]; let u=self.distinct_ratio[n-1]; - let uses=n as f64/u; - let cpu=(1.0-self.hit_rate)*self.cpu_all_miss_ms*u*(1.0+self.extra_use_cost*(uses-1.0)); - let draft=k as f64*if mtp {self.mtp_draft_ms} else {self.lookup_draft_ms}; - dense+cpu+self.sync_ms+draft + pub fn step_ms(&self, k: usize, mtp: bool) -> f64 { + let n = k.saturating_add(1).clamp(1, 9); + let dense = self.dense_ms * self.dense_ratio[n - 1]; + let u = self.distinct_ratio[n - 1]; + let uses = n as f64 / u; + let cpu = (1.0 - self.hit_rate) * self.cpu_all_miss_ms * u * (1.0 + self.extra_use_cost * (uses - 1.0)); + let draft = k as f64 * if mtp { self.mtp_draft_ms } else { self.lookup_draft_ms }; + dense + cpu + self.sync_ms + draft } } -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub enum Source { None, Lookup, Mtp } -#[derive(Clone,Copy,Debug,PartialEq)] -pub struct Choice {pub source:Source,pub k:usize,pub expected_tokens:f64,pub tokens_per_ms:f64} -pub struct CostController { cost:CostModel,min_gain:f64,ema:f64,mtp_p:[f64;8],lookup_q:[f64;4] } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Source { + None, + Lookup, + Mtp, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Choice { + pub source: Source, + pub k: usize, + pub expected_tokens: f64, + pub tokens_per_ms: f64, +} +pub struct CostController { + cost: CostModel, + min_gain: f64, + ema: f64, + mtp_p: [f64; 8], + lookup_q: [f64; 4], +} impl CostController { - pub fn new(cost:CostModel,min_gain:f64,ema:f64)->Self {Self{cost,min_gain,ema,mtp_p:[0.86;8],lookup_q:[0.35,0.6,0.8,0.92]}} - fn bucket(n:usize)->usize {if n>=16 {3} else if n>=8 {2} else if n>=5 {1} else {0}} - fn expected(p:&[f64],k:usize,same:bool)->f64 { - let(mut e,mut run)=(1.0,1.0); for i in 0..k {run*=p[if same {0} else {i}];e+=run;}e + pub fn new(cost: CostModel, min_gain: f64, ema: f64) -> Self { + Self { cost, min_gain, ema, mtp_p: [0.86; 8], lookup_q: [0.35, 0.6, 0.8, 0.92] } } - pub fn choose(&self,lookup_available:usize,lookup_match:usize,mtp_ready:bool)->Choice { - let baseline=1.0/self.cost.step_ms(0,false); - let mut best=Choice{source:Source::None,k:0,expected_tokens:1.0,tokens_per_ms:baseline}; - let mut consider=|source,k,e| {let rate=e/self.cost.step_ms(k,source==Source::Mtp); - if rate>best.tokens_per_ms {best=Choice{source,k,expected_tokens:e,tokens_per_ms:rate};}}; - let q=self.lookup_q[Self::bucket(lookup_match)]; - for k in 1..=lookup_available.min(8) {consider(Source::Lookup,k,Self::expected(&[q],k,true));} - if mtp_ready {for k in 1..=8 {consider(Source::Mtp,k,Self::expected(&self.mtp_p,k,false));}} - if best.source!=Source::None && best.tokens_per_ms usize { + if n >= 16 { + 3 + } else if n >= 8 { + 2 + } else if n >= 5 { + 1 + } else { + 0 + } } - pub fn observe(&mut self,c:Choice,accepted:usize,matched:usize)->Result<()> { - if c.source==Source::None || c.k==0 {return Ok(());} - if c.k>8 {return Err(Error::InvalidDimension);} - let a=accepted.min(c.k); - for i in 0..c.k.min(a+1) { - let hit=if i f64 { + let (mut e, mut run) = (1.0, 1.0); + for i in 0..k { + run *= p[if same { 0 } else { i }]; + e += run; + } + e + } + pub fn choose(&self, lookup_available: usize, lookup_match: usize, mtp_ready: bool) -> Choice { + let baseline = 1.0 / self.cost.step_ms(0, false); + let mut best = Choice { source: Source::None, k: 0, expected_tokens: 1.0, tokens_per_ms: baseline }; + let mut consider = |source, k, e| { + let rate = e / self.cost.step_ms(k, source == Source::Mtp); + if rate > best.tokens_per_ms { + best = Choice { source, k, expected_tokens: e, tokens_per_ms: rate }; + } + }; + let q = self.lookup_q[Self::bucket(lookup_match)]; + for k in 1..=lookup_available.min(8) { + consider(Source::Lookup, k, Self::expected(&[q], k, true)); + } + if mtp_ready { + for k in 1..=8 { + consider(Source::Mtp, k, Self::expected(&self.mtp_p, k, false)); + } + } + if best.source != Source::None && best.tokens_per_ms < baseline * (1.0 + self.min_gain) { + Choice { source: Source::None, k: 0, expected_tokens: 1.0, tokens_per_ms: baseline } + } else { + best + } + } + pub fn observe(&mut self, c: Choice, accepted: usize, matched: usize) -> Result<()> { + if c.source == Source::None || c.k == 0 { + return Ok(()); + } + if c.k > 8 { + return Err(Error::InvalidDimension); + } + let a = accepted.min(c.k); + for i in 0..c.k.min(a + 1) { + let hit = if i < a { 1.0 } else { 0.0 }; + if c.source == Source::Mtp { + self.mtp_p[i] += self.ema * (hit - self.mtp_p[i]); + } else { + let b = Self::bucket(matched); + self.lookup_q[b] += self.ema * (hit - self.lookup_q[b]); + } + } + if c.source == Source::Mtp && a == c.k && c.k < 8 { + for i in c.k..8 { + self.mtp_p[i] += self.ema * (self.mtp_p[c.k - 1] - self.mtp_p[i]); + } } - if c.source==Source::Mtp && a==c.k && c.k<8 {for i in c.k..8 {self.mtp_p[i]+=self.ema*(self.mtp_p[c.k-1]-self.mtp_p[i]);}} Ok(()) } } diff --git a/crates/engine-fake/rustfmt.toml b/crates/engine-fake/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/engine-fake/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/engine-qwen35-cuda/build.rs b/crates/engine-qwen35-cuda/build.rs index 10204d8a..769e8d8d 100644 --- a/crates/engine-qwen35-cuda/build.rs +++ b/crates/engine-qwen35-cuda/build.rs @@ -37,7 +37,11 @@ fn main() { println!("cargo:rerun-if-changed=../../desktop-core/src"); println!("cargo:rerun-if-changed=../../Cargo.lock"); - let commit = std::env::var("LELEKA_BUILD_COMMIT").ok().filter(|v| !v.is_empty()).or_else(|| git(&["rev-parse", "HEAD"])).unwrap_or_else(|| "unknown".to_owned()); + let commit = std::env::var("LELEKA_BUILD_COMMIT") + .ok() + .filter(|v| !v.is_empty()) + .or_else(|| git(&["rev-parse", "HEAD"])) + .unwrap_or_else(|| "unknown".to_owned()); let dirty = match std::env::var("LELEKA_BUILD_DIRTY").ok().filter(|v| !v.is_empty()) { Some(value) => match value.as_str() { "0" | "1" => value, @@ -50,7 +54,9 @@ fn main() { }, }; let mut features: Vec = std::env::vars() - .filter_map(|(key, _)| key.strip_prefix("CARGO_FEATURE_").map(|name| name.to_ascii_lowercase().replace('_', "-"))) + .filter_map(|(key, _)| { + key.strip_prefix("CARGO_FEATURE_").map(|name| name.to_ascii_lowercase().replace('_', "-")) + }) .collect(); features.sort(); let features = if features.is_empty() { "-".to_owned() } else { features.join(",") }; diff --git a/crates/engine-qwen35-cuda/rustfmt.toml b/crates/engine-qwen35-cuda/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/engine-qwen35-cuda/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/engine-qwen35-cuda/src/backend.rs b/crates/engine-qwen35-cuda/src/backend.rs index 6924e5ab..6704fc7e 100644 --- a/crates/engine-qwen35-cuda/src/backend.rs +++ b/crates/engine-qwen35-cuda/src/backend.rs @@ -5,13 +5,10 @@ pub(crate) use leleka_engine_core::prompt as original_prompt; mod original_serve; use crate::experimental::{self as experimental_modes, ExperimentalConfig}; use crate::model_binding::kar_expert_source::KarExpertSource; -pub use crate::model_binding::kar_expert_source::{ - KarArchiveRef, KarExpertLevels, KarExpertSourceConfig, -}; +pub use crate::model_binding::kar_expert_source::{KarArchiveRef, KarExpertLevels, KarExpertSourceConfig}; pub use crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive; pub use original_serve::{ - ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, - PrefixTail, + ExpertSource, OriginalServeChoice, OriginalServeMode, OriginalServeOptions, PrefixCacheOptions, PrefixTail, }; #[path = "backend_measurement.rs"] mod measurement; @@ -30,18 +27,16 @@ use crate::{ }, }; use leleka_backend_api::{ - BACKEND_API_VERSION, Backend, BackendCapabilities, BackendError, BackendIdentity, - ContractError, ErrorCode, FinishReason, GenerationEvent, GenerationRequest, GenerationSink, - GenerationStream, GenerationTerminal, InferenceMode, LOAD_CONFIG_VERSION, LoadedModel, - ModelDescriptor, RecentIds, RuntimeConfig, SupportedModelTuple, Usage, + BACKEND_API_VERSION, Backend, BackendCapabilities, BackendError, BackendIdentity, ContractError, ErrorCode, + FinishReason, GenerationEvent, GenerationRequest, GenerationSink, GenerationStream, GenerationTerminal, + InferenceMode, LOAD_CONFIG_VERSION, LoadedModel, ModelDescriptor, RecentIds, RuntimeConfig, SupportedModelTuple, + Usage, }; use leleka_cuda_driver::Driver; -use leleka_obs::time::{Clock, SystemClock}; use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; +use leleka_obs::time::{Clock, SystemClock}; use leleka_tokenizer::Tokenizer; -pub use measurement::{ - CacheCounts, EvaluationMeasurement, EvaluationObserver, MeasurementFailure, WindowWitness, -}; +pub use measurement::{CacheCounts, EvaluationMeasurement, EvaluationObserver, MeasurementFailure, WindowWitness}; use sha2::{Digest, Sha256}; use std::{ path::PathBuf, @@ -130,106 +125,50 @@ mod tests; #[path = "gpu_proofs/backend_measurement_sdet.rs"] mod backend_measurement_sdet; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/combined_prefix_numeric.rs"] mod combined_prefix_numeric; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/combined_prefix_numeric_sdet.rs"] mod combined_prefix_numeric_sdet; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_arms.rs"] mod original_serve_arms; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_laptop.rs"] mod original_serve_laptop; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_memory_smoke.rs"] mod original_serve_memory_smoke; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_prefix_smoke.rs"] mod original_serve_prefix_smoke; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "backend_original_serve_replay.rs"] mod original_serve_replay; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_smoke.rs"] mod original_serve_smoke; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/backend_original_serve_ttft.rs"] mod original_serve_ttft; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/singleload_proof.rs"] mod singleload_proof; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/resident_mmq_model_proof.rs"] mod resident_mmq_model_proof; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/native_resident_mmq_model_proof.rs"] mod native_resident_mmq_model_proof; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/layer0_native_mmq_proof.rs"] mod layer0_native_mmq_proof; -#[cfg(all( - test, - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gpu_proofs/combined_changed_boundary_proof.rs"] mod combined_changed_boundary_proof; @@ -254,21 +193,11 @@ mod streamed_spill_policy_tests { #[test] fn streamed_spill_identity_is_distinct_and_binds_actual_mode_and_profile() { let old = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); - let new = - streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); + let new = streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); assert_ne!(old, new); - assert_ne!( - new, - streamed_spill_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA) - ); - assert_ne!( - new, - streamed_spill_execution_digest("sanitized-bound-mode", "different-profile") - ); - assert_eq!( - new, - streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA) - ); + assert_ne!(new, streamed_spill_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA)); + assert_ne!(new, streamed_spill_execution_digest("sanitized-bound-mode", "different-profile")); + assert_eq!(new, streamed_spill_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA)); assert_ne!(STREAMED_SPILL_EXECUTION, QUEUED_OWNERS_EXECUTION); } } @@ -279,18 +208,9 @@ mod retained_scratch_policy_tests { #[test] fn retained_scratch_identity_distinctly_binds_bound_mode_profile_and_eager_owners() { let new = retained_scratch_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA); - assert_ne!( - new, - streamed_spill_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA) - ); - assert_ne!( - new, - retained_scratch_execution_digest("other", RANKED_EXPERT_PROFILE_SHA) - ); + assert_ne!(new, streamed_spill_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA)); + assert_ne!(new, retained_scratch_execution_digest("other", RANKED_EXPERT_PROFILE_SHA)); assert_ne!(new, retained_scratch_execution_digest("sanitized", "other")); - assert_eq!( - new, - retained_scratch_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA) - ); + assert_eq!(new, retained_scratch_execution_digest("sanitized", RANKED_EXPERT_PROFILE_SHA)); } } diff --git a/crates/engine-qwen35-cuda/src/backend/clock_tests.rs b/crates/engine-qwen35-cuda/src/backend/clock_tests.rs index 013d57f6..88112362 100644 --- a/crates/engine-qwen35-cuda/src/backend/clock_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/clock_tests.rs @@ -7,11 +7,7 @@ use leleka_obs::time::ManualClock; fn completed() -> GenerationTerminal { GenerationTerminal::Completed { reason: FinishReason::Stop, - usage: Usage { - input_tokens: 1, - output_tokens: 1, - reused_input_tokens: 0, - }, + usage: Usage { input_tokens: 1, output_tokens: 1, reused_input_tokens: 0 }, } } @@ -27,10 +23,7 @@ fn a_terminal_with_room_is_published_after_one_clock_read() { assert!(emit_terminal(&sink, completed(), &clock).is_ok()); // the clock moved once for the publication and once for the reading below assert_eq!(clock.now() - before, Duration::from_secs(20)); - assert!(matches!( - stream.recv(), - Ok(Some(GenerationEvent::Terminal(_))) - )); + assert!(matches!(stream.recv(), Ok(Some(GenerationEvent::Terminal(_))))); } #[test] @@ -40,15 +33,11 @@ fn a_terminal_that_meets_a_full_queue_gives_up_when_the_clock_passes_the_backpre // 10 s per reading: the start (0), then 10 s and 20 s are inside the 30 s limit, 30 s is not let clock = ManualClock::ticking(BACKPRESSURE_TIMEOUT / 3); let result = emit_terminal(&sink, completed(), &clock); - assert!( - matches!(result, Err(ContractError::GenerationBackpressure)), - "{result:?}" - ); + assert!(matches!(result, Err(ContractError::GenerationBackpressure)), "{result:?}"); } #[test] -fn a_terminal_waits_while_the_clock_stands_inside_the_limit_and_goes_through_when_the_reader_frees_a_slot() - { +fn a_terminal_waits_while_the_clock_stands_inside_the_limit_and_goes_through_when_the_reader_frees_a_slot() { let (sink, mut stream) = GenerationSink::bounded_channel(1).unwrap(); sink.try_emit(filler()).unwrap(); let clock = ManualClock::new(); @@ -71,10 +60,7 @@ fn an_event_that_meets_a_full_queue_gives_up_at_the_backpressure_limit_but_a_can sink.try_emit(filler()).unwrap(); let clock = ManualClock::ticking(BACKPRESSURE_TIMEOUT / 3); let result = emit_event(&sink, &|| false, &clock, filler()); - assert!( - matches!(result, Err(GenerationFailure::Backend(_))), - "the limit is a backend refusal" - ); + assert!(matches!(result, Err(GenerationFailure::Backend(_))), "the limit is a backend refusal"); let rounds = std::cell::Cell::new(0); let cancel_on_second = || { rounds.set(rounds.get() + 1); @@ -83,11 +69,7 @@ fn an_event_that_meets_a_full_queue_gives_up_at_the_backpressure_limit_but_a_can let slow = ManualClock::new(); let result = emit_event(&sink, &cancel_on_second, &slow, filler()); assert!(matches!(result, Err(GenerationFailure::Cancelled))); - assert_eq!( - rounds.get(), - 2, - "one wait of 5 ms on a clock that never reaches the limit, then the cancel" - ); + assert_eq!(rounds.get(), 2, "one wait of 5 ms on a clock that never reaches the limit, then the cancel"); } fn finished_request(clock: &ManualClock, prefill_ms: u64, decode_ms: u64) -> EvaluationMeasurement { @@ -107,9 +89,7 @@ fn finished_request(clock: &ManualClock, prefill_ms: u64, decode_ms: u64) -> Eva dense_source_bytes: 0, dense_upload_bytes: 0, }; - record - .finish(counts, counts, true, true, true, Some((3, 1, 0))) - .expect("complete record") + record.finish(counts, counts, true, true, true, Some((3, 1, 0))).expect("complete record") } #[test] @@ -125,10 +105,7 @@ fn two_recorders_on_one_clock_do_not_see_each_others_start() { let clock = ManualClock::new(); clock.advance_ms(5000); let measured = finished_request(&clock, 7, 11); - assert_eq!( - (measured.prefill, measured.decode), - (Duration::from_millis(7), Duration::from_millis(11)) - ); + assert_eq!((measured.prefill, measured.decode), (Duration::from_millis(7), Duration::from_millis(11))); } #[test] diff --git a/crates/engine-qwen35-cuda/src/backend/config.rs b/crates/engine-qwen35-cuda/src/backend/config.rs index 66715df7..b51c2578 100644 --- a/crates/engine-qwen35-cuda/src/backend/config.rs +++ b/crates/engine-qwen35-cuda/src/backend/config.rs @@ -1,17 +1,13 @@ //! Pinned model identity, resource limits and the operator-facing configuration types of the CUDA owner. use super::*; -pub(super) const SHARD0: &str = - "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; -pub(super) const SHARD1: &str = - "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; +pub(super) const SHARD0: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; +pub(super) const SHARD1: &str = "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; // SHA256(raw32 shard0 digest || raw32 shard1 digest), independently computed. -pub(super) const MODEL_DIGEST: &str = - "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; +pub(super) const MODEL_DIGEST: &str = "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; // SHA256 of the newline-terminated profile declaration documented below. // leleka-native-v1\nmodel=\nqsa=fp16\nmtp=none\ngreedy=ordered-finite-logits\n -pub(super) const MODE_DIGEST: &str = - "sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5"; +pub(super) const MODE_DIGEST: &str = "sha256:82b774f9c0daaf4290ae96b079224efea7da49dae74770cb32db3da69e4e3eb5"; pub(super) const KAR_PROFILE: &str = "qwen-iq3-s-l2-v4-ple"; pub(super) const NATIVE_MTP_PROFILE: &str = "qwen4exp-native-mtp-v1"; pub(super) const KAR_MTP_PROFILE: &str = "qwen4exp-kar-ple-mtp-v1"; @@ -86,20 +82,12 @@ pub(super) struct PolicyFlags { } impl PolicyFlags { pub(super) fn of(optimized: Option<&OptimizedBackendConfig>) -> Self { - use OptimizedOwnerPolicy::{ - AdaptiveSlots, Original, ResidentOwners, RetainedScratch, StreamedSpill, - }; + use OptimizedOwnerPolicy::{AdaptiveSlots, Original, ResidentOwners, RetainedScratch, StreamedSpill}; let policy = optimized.map(|options| options.policy); - let one_of = - |set: &[OptimizedOwnerPolicy]| policy.is_some_and(|policy| set.contains(&policy)); + let one_of = |set: &[OptimizedOwnerPolicy]| policy.is_some_and(|policy| set.contains(&policy)); Self { queued_owners: policy.is_some_and(|policy| policy != Original), - streamed_spill: one_of(&[ - StreamedSpill, - RetainedScratch, - ResidentOwners, - AdaptiveSlots, - ]), + streamed_spill: one_of(&[StreamedSpill, RetainedScratch, ResidentOwners, AdaptiveSlots]), retained_scratch: one_of(&[RetainedScratch, ResidentOwners, AdaptiveSlots]), resident_owners: one_of(&[ResidentOwners, AdaptiveSlots]), adaptive_slots: one_of(&[AdaptiveSlots]), @@ -116,14 +104,15 @@ pub(super) const OPTIMIZED_EXECUTION: &str = "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-v1"; pub(super) const QUEUED_OWNERS_EXECUTION: &str = "experimental-iq3-integer-window256-mtp-selected-qsa-router-shared-tail-indexed-lru-pinned-profile-queued-input-compact-head-gr-batch-v1"; pub(super) const ADAPTIVE_SLOTS_EXECUTION: &str = "experimental-iq3-window256-mtp-strata-adapt4-96-shared192-cpu-miss-event-refill-gdn-journal-incremental-prompt-gpu-seed-singleton-original-group16-v6"; -pub(super) const RESIDENT_OWNERS_EXECUTION: &str = "experimental-iq3-window256-mtp-learned-main-shared192-gdn-device-journal-incremental-capture-original-v2"; +pub(super) const RESIDENT_OWNERS_EXECUTION: &str = + "experimental-iq3-window256-mtp-learned-main-shared192-gdn-device-journal-incremental-capture-original-v2"; pub(super) const RETAINED_SCRATCH_EXECUTION: &str = "experimental-iq3-window256-mtp-streamed-spill-retained-gdn-qk-qsa-attention-v1"; -pub(super) const STREAMED_SPILL_EXECUTION: &str = "experimental-iq3-window256-mtp-queued-input-compact-head-gr-batch-digest-capture-spill-floor-1gib-v1"; +pub(super) const STREAMED_SPILL_EXECUTION: &str = + "experimental-iq3-window256-mtp-queued-input-compact-head-gr-batch-digest-capture-spill-floor-1gib-v1"; pub(super) const ORIGINAL_SERVE_EXECUTION: &str = "experimental-original-mode17-verified-window-batched-prefill-mtp-cpu-expert-tier-v1"; -pub(super) const RANKED_EXPERT_PROFILE_SHA: &str = - "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; +pub(super) const RANKED_EXPERT_PROFILE_SHA: &str = "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf"; pub(super) const RANKED_EXPERT_PROFILE_BYTES: usize = 196632; /// Provenance only: this descriptor does not attest a successful load. @@ -148,8 +137,7 @@ pub(super) enum EvaluationExecution { impl EvaluationExecution { pub(super) fn prefill_tile_cap(self) -> usize { match self { - Self::ExperimentalWindowed256RetainedGr - | Self::ExperimentalNativeIntegerIq3Windowed256RetainedGr => 256, + Self::ExperimentalWindowed256RetainedGr | Self::ExperimentalNativeIntegerIq3Windowed256RetainedGr => 256, _ => 64, } } diff --git a/crates/engine-qwen35-cuda/src/backend/digests.rs b/crates/engine-qwen35-cuda/src/backend/digests.rs index 3485e6d6..50fbe81d 100644 --- a/crates/engine-qwen35-cuda/src/backend/digests.rs +++ b/crates/engine-qwen35-cuda/src/backend/digests.rs @@ -31,32 +31,20 @@ pub(super) fn selected_bound_mode( if requires_kar(mode) != matches!(base, InferenceMode::ExperimentalKarPle { .. }) { return Err(invalid("MTP input provider mismatch")); } - let pins = binding - .mtp_pack_identity() - .map_err(|_| invalid("MTP pack identity absent"))?; - Ok(( - mode.clone(), - mtp_mode_digest(&base_digest, profile_id, pins), - )) + let pins = binding.mtp_pack_identity().map_err(|_| invalid("MTP pack identity absent"))?; + Ok((mode.clone(), mtp_mode_digest(&base_digest, profile_id, pins))) } _ => Ok((base, base_digest)), } } -pub(super) fn optimized_execution_digest( - bound_digest: &str, - ranked_profile: Option<&str>, -) -> String { +pub(super) fn optimized_execution_digest(bound_digest: &str, ranked_profile: Option<&str>) -> String { lines_digest([ "leleka-optimized-execution-v2", "bounded-resident-raw-expert-source-52gib-headroom8gib-v1", "complete-routed-gpu-finite-guard-v1", bound_digest, OPTIMIZED_EXECUTION, - if ranked_profile.is_some() { - "ranked-pinned-prefix-bounded-spill-v1" - } else { - "original-matrix-lru-index-v1" - }, + if ranked_profile.is_some() { "ranked-pinned-prefix-bounded-spill-v1" } else { "original-matrix-lru-index-v1" }, ranked_profile.unwrap_or("none"), ]) } @@ -113,10 +101,7 @@ pub(super) fn resident_owners_execution_digest(bound_digest: &str, ranked_profil "incremental-capacity52g-pretouch-future-plus8g-full-sha-index-before-publication", ]) } -pub(super) fn retained_scratch_execution_digest( - bound_digest: &str, - ranked_profile: &str, -) -> String { +pub(super) fn retained_scratch_execution_digest(bound_digest: &str, ranked_profile: &str) -> String { lines_digest([ "leleka-retained-gdn-qk-qsa-scratch-v1", streamed_spill_execution_digest(bound_digest, ranked_profile).as_str(), @@ -162,24 +147,13 @@ pub(super) fn kar_expert_mode_digest(bound_digest: &str, identity: &[u8; 32]) -> hex_digest(digest) } pub(super) fn execution_mode_digest(bound_digest: &str) -> String { - lines_digest([ - "leleka-execution-v1", - bound_digest, - INTEGER_WINDOWED_EXECUTION, - ]) + lines_digest(["leleka-execution-v1", bound_digest, INTEGER_WINDOWED_EXECUTION]) } pub(super) fn mtp_mode_digest(base: &str, profile: &str, pins: [&str; 3]) -> String { lines_digest( - [ - "leleka-mtp-v1", - base, - profile, - "depth=4", - "attention=fp16-dense", - "experts=s2-greedy", - ] - .into_iter() - .chain(pins), + ["leleka-mtp-v1", base, profile, "depth=4", "attention=fp16-dense", "experts=s2-greedy"] + .into_iter() + .chain(pins), ) } @@ -189,9 +163,7 @@ pub(super) fn bound_mode(binding: &ModelBinding) -> (InferenceMode, String) { match binding.kar_ple_binding() { None => (InferenceMode::Native, MODE_DIGEST.into()), Some(provider) => ( - InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }, + InferenceMode::ExperimentalKarPle { profile_id: KAR_PROFILE.into() }, kar_mode_digest(provider.archive_digest(), provider.profile_digest()), ), } diff --git a/crates/engine-qwen35-cuda/src/backend/errors.rs b/crates/engine-qwen35-cuda/src/backend/errors.rs index b0c4217c..4cba36df 100644 --- a/crates/engine-qwen35-cuda/src/backend/errors.rs +++ b/crates/engine-qwen35-cuda/src/backend/errors.rs @@ -2,28 +2,16 @@ use super::*; pub(super) fn error(code: ErrorCode, message: &'static str) -> BackendError { - BackendError { - code, - message: message.into(), - retryable: false, - } + BackendError { code, message: message.into(), retryable: false } } pub(super) fn invalid(message: &'static str) -> BackendError { error(ErrorCode::InvalidRequest, message) } pub(super) fn invalid_dynamic(message: String) -> BackendError { - BackendError { - code: ErrorCode::InvalidRequest, - message, - retryable: false, - } + BackendError { code: ErrorCode::InvalidRequest, message, retryable: false } } pub(super) fn unsupported_dynamic(message: String) -> BackendError { - BackendError { - code: ErrorCode::UnsupportedModel, - message, - retryable: false, - } + BackendError { code: ErrorCode::UnsupportedModel, message, retryable: false } } pub(super) fn unsupported(message: &'static str) -> BackendError { error(ErrorCode::UnsupportedModel, message) diff --git a/crates/engine-qwen35-cuda/src/backend/generate.rs b/crates/engine-qwen35-cuda/src/backend/generate.rs index 8aff0474..7ff213c6 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate.rs @@ -38,24 +38,16 @@ impl Generation<'_, '_, '_, C> { } } pub(super) fn cancelled(&self) -> bool { - self.cancel.load(Ordering::Acquire) - || self.shared.shutdown.load(Ordering::Acquire) - || self.sink.is_closed() + self.cancel.load(Ordering::Acquire) || self.shared.shutdown.load(Ordering::Acquire) || self.sink.is_closed() } pub(super) fn step(&mut self, token: u32, position: usize) -> Result { if self.cancelled() { return Err(GenerationFailure::Cancelled); } - let vocabulary = - Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?; + let vocabulary = Dimension::new(248_320).map_err(|_| invalid("native vocabulary invalid"))?; - let token = TokenId::new(u64::from(token), vocabulary) - .map_err(|_| invalid("native token invalid"))?; - let position = native_position( - self.binding.input_constants(), - self.context_tokens, - position, - )?; + let token = TokenId::new(u64::from(token), vocabulary).map_err(|_| invalid("native token invalid"))?; + let position = native_position(self.binding.input_constants(), self.context_tokens, position)?; let forwarded = QwenForward::step_cached( self.binding, token, @@ -79,16 +71,13 @@ impl Generation<'_, '_, '_, C> { // owners for explicit unload, but withdraw serving readiness. self.shared.ready.store(false, Ordering::Release); match failure { - crate::qwen_forward::contract::Error::InputAllocation => { - exhausted("native step allocation failed") - } + crate::qwen_forward::contract::Error::InputAllocation => exhausted("native step allocation failed"), crate::qwen_forward::contract::Error::Unsupported(_) => { unsupported("native forward operator unavailable") } - crate::qwen_forward::contract::Error::NonFinite => error( - ErrorCode::Internal, - "native forward produced invalid values", - ), + crate::qwen_forward::contract::Error::NonFinite => { + error(ErrorCode::Internal, "native forward produced invalid values") + } _ => unavailable("native forward failed"), } })?; @@ -97,10 +86,7 @@ impl Generation<'_, '_, '_, C> { } Ok(token.get()) } - pub(super) fn mtp_error( - &self, - failure: crate::qwen_forward::contract::Error, - ) -> GenerationFailure { + pub(super) fn mtp_error(&self, failure: crate::qwen_forward::contract::Error) -> GenerationFailure { use crate::qwen_forward::contract::Error; #[cfg(test)] eprintln!("PUBLIC MTP contract failure={failure:?}"); @@ -113,24 +99,13 @@ impl Generation<'_, '_, '_, C> { }; GenerationFailure::Backend(error) } - pub(super) fn target_step( - &mut self, - token: u32, - position: usize, - ) -> Result { + pub(super) fn target_step(&mut self, token: u32, position: usize) -> Result { if self.cancelled() { return Err(GenerationFailure::Cancelled); } - let token = TokenId::new( - u64::from(token), - Dimension::new(248320).map_err(|e| self.mtp_error(e))?, - ) - .map_err(|e| self.mtp_error(e))?; - let position = native_position( - self.binding.input_constants(), - self.context_tokens, - position, - )?; + let token = TokenId::new(u64::from(token), Dimension::new(248320).map_err(|e| self.mtp_error(e))?) + .map_err(|e| self.mtp_error(e))?; + let position = native_position(self.binding.input_constants(), self.context_tokens, position)?; let result = QwenForward::step_for_mtp_cached( self.binding, token, @@ -148,10 +123,7 @@ impl Generation<'_, '_, '_, C> { Ok(product) } pub(super) fn prefill_tile_cap(&self) -> usize { - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] // The selected native prompt admits its actual simultaneous index, // INT8 KV and FFN owners under the unchanged request host ceiling. if self.moe_cache.uses_strata_adaptive_experts() { @@ -178,13 +150,9 @@ impl Generation<'_, '_, '_, C> { } let vocabulary = Dimension::new(248320).map_err(|e| self.mtp_error(e))?; let mut typed = Vec::new(); - typed - .try_reserve_exact(tokens.len()) - .map_err(|_| exhausted("prefill tile allocation failed"))?; + typed.try_reserve_exact(tokens.len()).map_err(|_| exhausted("prefill tile allocation failed"))?; for (offset, &token) in tokens.iter().enumerate() { - let actual = position - .checked_add(offset) - .ok_or_else(|| exhausted("MTP context exhausted"))?; + let actual = position.checked_add(offset).ok_or_else(|| exhausted("MTP context exhausted"))?; let _ = native_position(self.binding.input_constants(), self.context_tokens, actual)?; typed.push(TokenId::new(u64::from(token), vocabulary).map_err(|e| self.mtp_error(e))?); } @@ -214,13 +182,9 @@ impl Generation<'_, '_, '_, C> { } EvaluationExecution::ExperimentalResidentMmq | EvaluationExecution::ExperimentalNativeResidentMmq - | EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => { - QwenForward::prefill_chunk_mmq_joint - } + | EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => QwenForward::prefill_chunk_mmq_joint, }; - let host_remaining = draft - .prefill_host_remaining(512 * 1024 * 1024) - .map_err(|e| self.mtp_error(e))?; + let host_remaining = draft.prefill_host_remaining(512 * 1024 * 1024).map_err(|e| self.mtp_error(e))?; let result = forward( self.binding, &typed, @@ -235,9 +199,9 @@ impl Generation<'_, '_, '_, C> { stopped, ); let product = match result { - Err(crate::qwen_forward::contract::Error::Unsupported( - crate::qwen_forward::contract::Stage::Executor, - )) if stopped() => { + Err(crate::qwen_forward::contract::Error::Unsupported(crate::qwen_forward::contract::Stage::Executor)) + if stopped() => + { if self.clock.since(started) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } @@ -283,19 +247,12 @@ pub(super) fn generate( run.observe(|r| r.token(next)); if next == run.eos { utf8.finish()?; - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count + 1, - reused_input_tokens: 0, - }; + let usage = Usage { input_tokens: prompt.len() as u64, output_tokens: count + 1, reused_input_tokens: 0 }; run.emit(GenerationEvent::Usage(usage.clone()))?; run.observe(|r| r.decoded()); return Ok((FinishReason::Stop, usage)); } - let bytes = run - .tokenizer - .decode_bytes(&[next]) - .map_err(|_| unavailable("native token decoding failed"))?; + let bytes = run.tokenizer.decode_bytes(&[next]).map_err(|_| unavailable("native token decoding failed"))?; if let Some(text) = utf8.push(&bytes)? { run.emit(GenerationEvent::TextDelta { text })?; } @@ -305,11 +262,7 @@ pub(super) fn generate( } } utf8.finish_length(|text| run.emit(GenerationEvent::TextDelta { text }))?; - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count, - reused_input_tokens: 0, - }; + let usage = Usage { input_tokens: prompt.len() as u64, output_tokens: count, reused_input_tokens: 0 }; run.emit(GenerationEvent::Usage(usage.clone()))?; run.observe(|r| r.decoded()); Ok((FinishReason::Length, usage)) diff --git a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs index 5b5a873b..eefaa077 100644 --- a/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs +++ b/crates/engine-qwen35-cuda/src/backend/generate_mtp.rs @@ -30,9 +30,7 @@ pub(super) fn generate_mtp_resume( (old.decoder, Some(old.product), reused, old.tokens) } None => ( - if run.execution - == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { + if run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { MtpDecoder::new_kv_prefill(run.binding, run.session, prompt) } else { MtpDecoder::new(run.binding) @@ -63,30 +61,20 @@ pub(super) fn generate_mtp_resume( return Err(GenerationFailure::Cancelled); } let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?; - decoder - .warm_retained(run.binding, run.session, product, next, run.moe_cache) - .map_err(|e| run.mtp_error(e))?; + decoder.warm_retained(run.binding, run.session, product, next, run.moe_cache).map_err(|e| run.mtp_error(e))?; } // Each tile preserves the genuine last-known-next edge. A final tile // obtains its actual head product; no intermediate greedy IDs are minted. - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts(); - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let adaptive_prefill = false; let mut position = reused; while position < prompt.len() { if run.clock.since(start) > GENERATION_TIMEOUT { return Err(unavailable("generation deadline exceeded").into()); } - let mut end = position - .saturating_add(run.prefill_tile_cap()) - .min(prompt.len()); + let mut end = position.saturating_add(run.prefill_tile_cap()).min(prompt.len()); // Keep the last known-next edge and final head in one joint tile. // A completed fresh KV warmer cannot admit a second final tile. if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 { @@ -108,12 +96,8 @@ pub(super) fn generate_mtp_resume( position = end; } let mut product = latest.ok_or_else(|| invalid("empty MTP prompt"))?; - if reused == 0 - && run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { - decoder - .finish_kv_prefill(run.binding, run.session, &product, &committed) - .map_err(|e| run.mtp_error(e))?; + if reused == 0 && run.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { + decoder.finish_kv_prefill(run.binding, run.session, &product, &committed).map_err(|e| run.mtp_error(e))?; } run.observe(|r| r.prefilled()); let mut utf8 = Utf8Pending::default(); @@ -128,9 +112,7 @@ pub(super) fn generate_mtp_resume( if count == u64::from(max) { break FinishReason::Length; } - let authoritative = product - .predicted(run.session) - .map_err(|e| run.mtp_error(e))?; + let authoritative = product.predicted(run.session).map_err(|e| run.mtp_error(e))?; if authoritative == eos { run.observe(|r| r.token(eos.get())); count += 1; @@ -152,13 +134,9 @@ pub(super) fn generate_mtp_resume( } // Bound the target advances by the operator's context, independently // of the verified model's larger Position dimension. - let position = prompt - .len() - .checked_add(count as usize) - .ok_or_else(|| exhausted("MTP context exhausted"))?; + let position = prompt.len().checked_add(count as usize).ok_or_else(|| exhausted("MTP context exhausted"))?; let _ = native_position(run.binding.input_constants(), run.context_tokens, position)?; - let remaining = - (max as usize - count as usize - 1).min(run.context_tokens as usize - position); + let remaining = (max as usize - count as usize - 1).min(run.context_tokens as usize - position); let spec = MtpWindowSpec::new(4, remaining, Some(eos)).map_err(|e| run.mtp_error(e))?; let cancel = run.cancel; let shared = run.shared; @@ -215,10 +193,8 @@ pub(super) fn generate_mtp_resume( for token in tokens { run.observe(|r| r.token(token.get())); committed.push(token.get()); - let bytes = run - .tokenizer - .decode_bytes(&[token.get()]) - .map_err(|_| unavailable("MTP token decoding failed"))?; + let bytes = + run.tokenizer.decode_bytes(&[token.get()]).map_err(|_| unavailable("MTP token decoding failed"))?; if let Some(text) = utf8.push(&bytes)? { run.emit(GenerationEvent::TextDelta { text })?; } @@ -239,23 +215,13 @@ pub(super) fn generate_mtp_resume( } else { utf8.finish()?; } - let usage = Usage { - input_tokens: prompt.len() as u64, - output_tokens: count, - reused_input_tokens: reused as u64, - }; + let usage = Usage { input_tokens: prompt.len() as u64, output_tokens: count, reused_input_tokens: reused as u64 }; run.emit(GenerationEvent::Usage(usage.clone()))?; - decoder - .validate_resume(run.binding, run.session, &product, &committed) - .map_err(|e| run.mtp_error(e))?; + decoder.validate_resume(run.binding, run.session, &product, &committed).map_err(|e| run.mtp_error(e))?; if run.cancelled() { return Err(GenerationFailure::Cancelled); } run.observe(|r| r.decoded()); - *publish = Some(MtpContinuation { - decoder, - product, - tokens: committed, - }); + *publish = Some(MtpContinuation { decoder, product, tokens: committed }); Ok((reason, usage)) } diff --git a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs index d8620b62..0307c0ac 100644 --- a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests.rs @@ -8,9 +8,7 @@ use super::*; use crate::qwen_forward::original_serve_engine::{ServeOutcome, ServeStop}; use crate::qwen_forward::original_serve_request::{ServeDevice, ServeError, ServeRequest}; -use crate::qwen_forward::original_serve_stack::lifecycle_fake::{ - FakeDevice, FakeStack, Script, greedy_continuation, -}; +use crate::qwen_forward::original_serve_stack::lifecycle_fake::{FakeDevice, FakeStack, Script, greedy_continuation}; use leleka_obs::time::ManualClock; mod ends; @@ -21,9 +19,7 @@ const NO_EOS: i32 = 200; const HOUR_MS: u64 = 3_600_000; fn prompt_of(n: usize, seed: usize) -> Vec { - (0..n) - .map(|i| 33 + ((i * 13 + 5 + 40 * seed) % 90) as i32) - .collect() + (0..n).map(|i| 33 + ((i * 13 + 5 + 40 * seed) % 90) as i32).collect() } fn prompt(n: usize) -> Vec { @@ -101,20 +97,10 @@ impl Rig { let cancel = Arc::new(AtomicBool::new(false)); dev.watch_cancel(Arc::clone(&cancel)); let stack = FakeStack::new(dev.clone(), clock.clone(), prefix); - let shared = Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }; + let shared = + Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }; let tokenizer = tokenizer(); - Self { - dev, - stack, - clock, - tokenizer, - cancel, - shared, - } + Self { dev, stack, clock, tokenizer, cancel, shared } } /// One request through the production `generate`, with the events the client would see. @@ -125,11 +111,7 @@ impl Rig { let terminal = GenerationEvent::Terminal(GenerationTerminal::Cancelled); sink.try_emit(terminal).unwrap(); let (text, usage_events) = drain(&mut stream); - Run { - ended: ended(result), - text, - usage_events, - } + Run { ended: ended(result), text, usage_events } } fn generate( @@ -139,18 +121,9 @@ impl Rig { request: &GenerationRequest, eos: i32, ) -> Result<(FinishReason, Usage), GenerationFailure> { - let Self { - stack, - tokenizer, - cancel, - shared, - clock, - .. - } = self; + let Self { stack, tokenizer, cancel, shared, clock, .. } = self; let generate = original_serve::runner::generate; - generate( - stack, tokenizer, sink, cancel, shared, eos as u32, ids, request, 0.0, &*clock, - ) + generate(stack, tokenizer, sink, cancel, shared, eos as u32, ids, request, 0.0, &*clock) } /// One request straight through `run_request`, for the outcome `generate` does not return. @@ -161,9 +134,7 @@ impl Rig { fn position_of(&self, line: &str) -> usize { let all = self.dev.lines(""); - all.iter() - .position(|l| l == line) - .unwrap_or_else(|| panic!("{line} missing in {all:?}")) + all.iter().position(|l| l == line).unwrap_or_else(|| panic!("{line} missing in {all:?}")) } /// The device log lines that start with `prefix`, in order. @@ -218,27 +189,13 @@ fn a_request_runs_resume_prefill_rounds_and_finish_in_order_and_ends_on_the_leng fn the_length_limit_ends_the_request_at_exactly_that_many_tokens_whatever_the_acceptance() { for accept in [vec![], vec![0], vec![1, 2]] { for max_new in [1u32, 2, 5, 13] { - let mut rig = Rig::new( - Script { - accept: accept.clone(), - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { accept: accept.clone(), ..Script::default() }, false); let p = prompt(300); let run = rig.run(&p, max_new, NO_EOS); let (reason, usage) = done(&run); assert_eq!(*reason, FinishReason::Length, "{accept:?} {max_new}"); - assert_eq!( - usage.output_tokens, - u64::from(max_new), - "{accept:?} {max_new}" - ); - assert_eq!( - run.text, - expect(&p, max_new as usize), - "{accept:?} {max_new}" - ); + assert_eq!(usage.output_tokens, u64::from(max_new), "{accept:?} {max_new}"); + assert_eq!(run.text, expect(&p, max_new as usize), "{accept:?} {max_new}"); } } } @@ -248,45 +205,24 @@ fn an_eos_inside_a_round_ends_the_request_counts_as_an_output_token_and_carries_ let p = prompt(300); let eos = greedy_continuation(*p.last().unwrap(), 5)[4]; for accept in [vec![], vec![0]] { - let mut rig = Rig::new( - Script { - accept: accept.clone(), - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { accept: accept.clone(), ..Script::default() }, false); let run = rig.run(&p, 50, eos); let (reason, usage) = done(&run); assert_eq!(*reason, FinishReason::Stop, "{accept:?}"); - assert_eq!( - usage.output_tokens, 5, - "four tokens of text and the eos {accept:?}" - ); + assert_eq!(usage.output_tokens, 5, "four tokens of text and the eos {accept:?}"); assert_eq!(run.text, expect(&p, 4), "{accept:?}"); } } #[test] fn partial_acceptance_commits_the_accepted_rows_of_each_round_and_never_changes_the_text() { - let mut rig = Rig::new( - Script { - accept: vec![2, 0, 1, 3], - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { accept: vec![2, 0, 1, 3], ..Script::default() }, false); let p = prompt(300); let run = rig.run(&p, 40, NO_EOS); assert_eq!(run.text, expect(&p, 40)); let keeps = rig.log("commit keep="); // the first window is the last prompt token alone; each later one is drafted by the call before it - let first = [ - "commit keep=1", - "commit keep=3", - "commit keep=1", - "commit keep=2", - "commit keep=4", - ]; + let first = ["commit keep=1", "commit keep=3", "commit keep=1", "commit keep=2", "commit keep=4"]; assert_eq!(keeps[..5], first); let windows = rig.log("run t="); assert_eq!(windows[..3], ["run t=1", "run t=4", "run t=4"]); @@ -295,30 +231,14 @@ fn partial_acceptance_commits_the_accepted_rows_of_each_round_and_never_changes_ #[test] fn the_prefill_and_decode_durations_follow_the_clock_and_count_the_rounds() { - let mut rig = Rig::new( - Script { - chunk_ms: 7, - round_ms: 3, - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { chunk_ms: 7, round_ms: 3, ..Script::default() }, false); let outcome = rig.serve(&prompt(1500), 12).unwrap(); let (prefill_ms, decode_ms) = rig.stack.last_timing(); assert_eq!(outcome.stop, ServeStop::Length); assert_eq!(outcome.rounds, rig.log("run t=").len()); - assert_eq!( - outcome.rounds, 4, - "1 + 4 + 4 + 4 rows cover 12 tokens in four rounds" - ); - assert!( - (prefill_ms - 14.0).abs() < 1e-6, - "two chunks of 7 ms: {prefill_ms}" - ); - assert!( - (decode_ms - 12.0).abs() < 1e-6, - "four rounds of 3 ms: {decode_ms}" - ); + assert_eq!(outcome.rounds, 4, "1 + 4 + 4 + 4 rows cover 12 tokens in four rounds"); + assert!((prefill_ms - 14.0).abs() < 1e-6, "two chunks of 7 ms: {prefill_ms}"); + assert!((decode_ms - 12.0).abs() < 1e-6, "four rounds of 3 ms: {decode_ms}"); } #[test] diff --git a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/ends.rs b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/ends.rs index 0f268599..5631f6dd 100644 --- a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/ends.rs +++ b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/ends.rs @@ -6,96 +6,47 @@ const DEADLINE: &str = "generation deadline exceeded"; #[test] fn a_client_cancel_in_the_middle_of_the_decode_ends_cancelled_and_the_next_request_is_served() { - let mut rig = Rig::new( - Script { - cancel_in_round: Some(1), - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { cancel_in_round: Some(1), ..Script::default() }, false); let p = prompt(300); let run = rig.run(&p, 40, NO_EOS); assert_eq!(run.ended, Ended::Cancelled); - assert!( - run.usage_events.is_empty(), - "a cancelled request reports no usage" - ); + assert!(run.usage_events.is_empty(), "a cancelled request reports no usage"); assert!(expect(&p, 40).starts_with(&run.text)); - assert_eq!( - rig.log("run t=").len(), - 2, - "the round that saw the flag was the last" - ); + assert_eq!(rig.log("run t=").len(), 2, "the round that saw the flag was the last"); assert_eq!(rig.last_line(), "finish completed=true"); rig.cancel.store(false, Ordering::Release); assert_eq!(rig.run(&p, 6, NO_EOS).text, expect(&p, 6)); - assert_eq!( - rig.log("reset").len(), - 1, - "the second request resets what the first left behind" - ); + assert_eq!(rig.log("reset").len(), 1, "the second request resets what the first left behind"); } #[test] fn the_deadline_expiring_between_rounds_fails_the_request_as_unavailable() { - let mut rig = Rig::new( - Script { - round_ms: 13 * HOUR_MS, - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { round_ms: 13 * HOUR_MS, ..Script::default() }, false); let p = prompt(300); let run = rig.run(&p, 40, NO_EOS); assert_eq!(run.ended, failed(ErrorCode::BackendUnavailable, DEADLINE)); assert!(expect(&p, 40).starts_with(&run.text)); assert!(run.usage_events.is_empty()); - assert_eq!( - rig.log("run t=").len(), - 2, - "13 h is inside the 24 h limit, 26 h is not" - ); + assert_eq!(rig.log("run t=").len(), 2, "13 h is inside the 24 h limit, 26 h is not"); } #[test] fn the_deadline_expiring_between_prompt_chunks_stops_the_prefill_before_the_next_chunk() { - let mut rig = Rig::new( - Script { - chunk_ms: 25 * HOUR_MS, - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { chunk_ms: 25 * HOUR_MS, ..Script::default() }, false); let run = rig.run(&prompt(1500), 10, NO_EOS); assert_eq!(run.ended, failed(ErrorCode::BackendUnavailable, DEADLINE)); assert_eq!(rig.log("chunk").len(), 1); - assert!( - rig.log("run t=").is_empty(), - "no decode after a prefill that timed out" - ); + assert!(rig.log("run t=").is_empty(), "no decode after a prefill that timed out"); assert_eq!(rig.last_line(), "finish completed=true"); } #[test] fn a_device_error_in_the_prefill_fails_the_request_and_the_next_one_starts_from_a_reset() { - let mut rig = Rig::new( - Script { - fail_chunk: Some(1), - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { fail_chunk: Some(1), ..Script::default() }, false); let p = prompt(1500); let run = rig.run(&p, 10, NO_EOS); - assert_eq!( - run.ended, - failed(ErrorCode::BackendUnavailable, SERVE_FAILED) - ); - assert_eq!( - rig.log("chunk").len(), - 2, - "the first chunk read, the second failed" - ); + assert_eq!(run.ended, failed(ErrorCode::BackendUnavailable, SERVE_FAILED)); + assert_eq!(rig.log("chunk").len(), 2, "the first chunk read, the second failed"); assert!(rig.log("run t=").is_empty()); assert_eq!(rig.last_line(), "finish completed=false"); assert_eq!(rig.run(&p, 10, NO_EOS).text, expect(&p, 10)); @@ -104,26 +55,11 @@ fn a_device_error_in_the_prefill_fails_the_request_and_the_next_one_starts_from_ #[test] fn a_device_error_in_a_round_restores_both_checkpoints_and_the_next_request_is_served() { - let mut rig = Rig::new( - Script { - fail_round: Some(1), - ..Script::default() - }, - false, - ); + let mut rig = Rig::new(Script { fail_round: Some(1), ..Script::default() }, false); let p = prompt(300); let run = rig.run(&p, 40, NO_EOS); - assert_eq!( - run.ended, - failed(ErrorCode::BackendUnavailable, SERVE_FAILED) - ); - assert_eq!( - ( - rig.log("restore-target").len(), - rig.log("restore-draft").len() - ), - (1, 1) - ); + assert_eq!(run.ended, failed(ErrorCode::BackendUnavailable, SERVE_FAILED)); + assert_eq!((rig.log("restore-target").len(), rig.log("restore-draft").len()), (1, 1)); assert!(expect(&p, 40).starts_with(&run.text)); assert_eq!(rig.run(&p, 6, NO_EOS).text, expect(&p, 6)); } diff --git a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/prefix.rs b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/prefix.rs index 08d7c582..b5aee1e9 100644 --- a/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/prefix.rs +++ b/crates/engine-qwen35-cuda/src/backend/lifecycle_tests/prefix.rs @@ -4,19 +4,8 @@ use super::*; /// A cache that holds one session (700 tokens), then another: the buffer no longer holds the first one. fn rig_after_two_sessions() -> Rig { - let mut rig = Rig::new( - Script { - chunk_ms: 5, - ..Script::default() - }, - true, - ); - assert_eq!( - done(&rig.run(&prompt(700), 4, NO_EOS)) - .1 - .reused_input_tokens, - 0 - ); + let mut rig = Rig::new(Script { chunk_ms: 5, ..Script::default() }, true); + assert_eq!(done(&rig.run(&prompt(700), 4, NO_EOS)).1.reused_input_tokens, 0); rig.run(&prompt_of(700, 1), 4, NO_EOS); rig } @@ -27,15 +16,9 @@ fn a_prefix_hit_resumes_from_the_deepest_grid_point_and_reports_the_reuse() { let (second, chunks_before) = (prompt(800), rig.log("chunk").len()); let run = rig.run(&second, 8, NO_EOS); let (_, usage) = done(&run); - assert_eq!( - usage.reused_input_tokens, 512, - "the deepest checkpoint below the 799 tokens that are read" - ); + assert_eq!(usage.reused_input_tokens, 512, "the deepest checkpoint below the 799 tokens that are read"); assert_eq!(rig.stack.prefix_hits(), 1); - assert_eq!( - rig.log("chunk")[chunks_before..], - ["chunk first=512 count=256", "chunk first=768 count=31"] - ); + assert_eq!(rig.log("chunk")[chunks_before..], ["chunk first=512 count=256", "chunk first=768 count=31"]); assert_eq!(run.text, expect(&second, 8)); } @@ -44,18 +27,10 @@ fn a_hit_after_another_session_writes_the_cells_back_and_ends_in_the_full_reads_ let mut rig = rig_after_two_sessions(); let second = prompt(800); rig.run(&second, 8, NO_EOS); - assert_eq!( - rig.log("import"), - ["import 512 blocks=2"], - "the buffer held the other session's cells" - ); + assert_eq!(rig.log("import"), ["import 512 blocks=2"], "the buffer held the other session's cells"); let mut fresh = Rig::new(Script::default(), false); fresh.run(&second, 8, NO_EOS); - assert_eq!( - rig.dev.digest(), - fresh.dev.digest(), - "the resumed read ends in exactly the full read's state" - ); + assert_eq!(rig.dev.digest(), fresh.dev.digest(), "the resumed read ends in exactly the full read's state"); } #[test] @@ -65,27 +40,11 @@ fn a_cancelled_request_keeps_the_prefix_checkpoints_and_a_failed_one_drops_them( let kept = rig.stack.prefix_nodes(); assert!(kept > 0); rig.dev.state().script.cancel_in_round = Some(0); - assert_eq!( - rig.run(&prompt_of(700, 2), 4, NO_EOS).ended, - Ended::Cancelled - ); - assert!( - rig.stack.prefix_nodes() >= kept, - "a cancelled request is completed: its checkpoints stay" - ); + assert_eq!(rig.run(&prompt_of(700, 2), 4, NO_EOS).ended, Ended::Cancelled); + assert!(rig.stack.prefix_nodes() >= kept, "a cancelled request is completed: its checkpoints stay"); rig.cancel.store(false, Ordering::Release); rig.dev.state().script.fail_chunk = Some(1); let run = rig.run(&prompt_of(1500, 1), 4, NO_EOS); - assert_eq!( - run.ended, - failed( - ErrorCode::BackendUnavailable, - "Original serve request failed" - ) - ); - assert_eq!( - rig.stack.prefix_nodes(), - 0, - "owners in an unknown state: nothing the cache holds can be trusted" - ); + assert_eq!(run.ended, failed(ErrorCode::BackendUnavailable, "Original serve request failed")); + assert_eq!(rig.stack.prefix_nodes(), 0, "owners in an unknown state: nothing the cache holds can be trusted"); } diff --git a/crates/engine-qwen35-cuda/src/backend/load.rs b/crates/engine-qwen35-cuda/src/backend/load.rs index b36dcdf9..73805c92 100644 --- a/crates/engine-qwen35-cuda/src/backend/load.rs +++ b/crates/engine-qwen35-cuda/src/backend/load.rs @@ -55,8 +55,7 @@ fn serve_native<'d>( let mut weights = load_weights(env, &bound.binding, context.as_ref(), bound.flags, ranked)?; // Exercise only structural session initialization; no synthetic inference // or repeated model/GPU qualification is performed during load. - let initial_session = - QwenSession::for_binding_on_shared_device(&bound.binding, Rc::clone(context)); + let initial_session = QwenSession::for_binding_on_shared_device(&bound.binding, Rc::clone(context)); drop(initial_session); let loaded = build_loaded(env, identity, requested)?; check_not_cancelled(env.shared)?; @@ -67,12 +66,7 @@ fn serve_native<'d>( let mut conversations = new_conversations(); let mut serving = Serving::new(env, bound, context, &loaded, &mut weights); serve_commands(&mut serving, &mut conversations, &mut unload_reply)?; - Ok(Some(close_weights( - env.shared, - conversations, - weights, - unload_reply, - ))) + Ok(Some(close_weights(env.shared, conversations, weights, unload_reply))) } /// Publish the handle; `false` (and not ready again) when the requester is gone. diff --git a/crates/engine-qwen35-cuda/src/backend/load_admit.rs b/crates/engine-qwen35-cuda/src/backend/load_admit.rs index e17c3d46..b4c71e1c 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_admit.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_admit.rs @@ -29,29 +29,16 @@ pub(super) fn kar_mtp_requested(requested: &RuntimeConfig) -> bool { // prefills prompt tiles and verifies draft windows through chunked/grouped // MoE paths that read the GGUF experts, so combining them would build the // KV cache from one expert set and decode from another. Refuse, not mix. -fn refuse_kar_experts_with_mtp( - config: &NativeBackendConfig, - requested: &RuntimeConfig, -) -> Result<(), BackendError> { - if config.kar_expert_source.is_some() - && matches!( - requested.inference_mode, - InferenceMode::ExperimentalMtp { .. } - ) - { - return Err(load_failure( - LoadPhase::Selection, - unsupported("KAR expert source does not support the MTP flow"), - )); +fn refuse_kar_experts_with_mtp(config: &NativeBackendConfig, requested: &RuntimeConfig) -> Result<(), BackendError> { + if config.kar_expert_source.is_some() && matches!(requested.inference_mode, InferenceMode::ExperimentalMtp { .. }) { + return Err(load_failure(LoadPhase::Selection, unsupported("KAR expert source does not support the MTP flow"))); } Ok(()) } // Experimental modes: validate the combination with the Original's selection rules and refuse cheaply, // before any model byte is read, while nothing in the forward pass consumes them. -fn plan_experimental( - config: &NativeBackendConfig, -) -> Result, BackendError> { +fn plan_experimental(config: &NativeBackendConfig) -> Result, BackendError> { experimental_modes::plan(&config.experimental) .and_then(|plan| experimental_modes::ensure_consumed(&plan).map(|()| plan)) .map_err(|e| load_failure(LoadPhase::Config, experimental_error(e))) @@ -118,11 +105,7 @@ fn log_original_refusal(env: &LoadEnv<'_>, requested: &RuntimeConfig, has_plan: } /// The evaluation executions each demand an explicit KAR PLE MTP Load (and, for most, an observer). -fn check_execution_gates( - env: &LoadEnv<'_>, - requested: &RuntimeConfig, - gguf_ple: bool, -) -> Result<(), BackendError> { +fn check_execution_gates(env: &LoadEnv<'_>, requested: &RuntimeConfig, gguf_ple: bool) -> Result<(), BackendError> { let kar_mtp = kar_mtp_requested(requested); match execution_gate_message(env.execution, kar_mtp, env.observer.is_some(), gguf_ple) { Some(message) => Err(load_failure(LoadPhase::Selection, invalid(message))), @@ -145,9 +128,7 @@ pub(super) fn execution_gate_message( { Some("resident MMQ evaluation requires explicit KAR PLE MTP Load") } - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - if !gguf_ple && !kar_mtp => - { + EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr if !gguf_ple && !kar_mtp => { Some("IQ3 windowed256 retained GR experiment requires explicit KAR PLE MTP Load") } EvaluationExecution::ExperimentalWindowed256RetainedGr if !kar_mtp || !observed => { @@ -157,25 +138,14 @@ pub(super) fn execution_gate_message( } } -fn validate_selection( - config: &NativeBackendConfig, - requested: &RuntimeConfig, -) -> Result<(), BackendError> { +fn validate_selection(config: &NativeBackendConfig, requested: &RuntimeConfig) -> Result<(), BackendError> { let kar_present = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(); - validate_kar_selection(requested, kar_present) - .map_err(|e| load_failure(LoadPhase::Selection, e))?; - validate_mtp_selection(requested, config.mtp_source.is_some()) - .map_err(|e| load_failure(LoadPhase::Selection, e)) + validate_kar_selection(requested, kar_present).map_err(|e| load_failure(LoadPhase::Selection, e))?; + validate_mtp_selection(requested, config.mtp_source.is_some()).map_err(|e| load_failure(LoadPhase::Selection, e)) } -fn check_memory_ceiling( - config: &NativeBackendConfig, - requested: &RuntimeConfig, -) -> Result<(), BackendError> { - if requested - .gpu_memory_limit_bytes - .is_some_and(|limit| limit < config.gpu_budget_bytes) - { +fn check_memory_ceiling(config: &NativeBackendConfig, requested: &RuntimeConfig) -> Result<(), BackendError> { + if requested.gpu_memory_limit_bytes.is_some_and(|limit| limit < config.gpu_budget_bytes) { return Err(load_failure( LoadPhase::Config, exhausted("requested memory ceiling is below native owner budget"), @@ -185,57 +155,38 @@ fn check_memory_ceiling( } /// What the memory governor hands back at startup (`docs/memory-safety.md`); nothing off the CUDA platforms. -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) type Governed = Option<&'static leleka_memory::Governor>; -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) type Governed = (); // The memory budget, before a single model byte is read: refuse with numbers when the fixed footprint does not fit, // otherwise size the caches from what is left and keep the sealed KAR memfd resident (`docs/memory-safety.md`). -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn start_governor(env: &LoadEnv<'_>) -> Result { let Some(options) = env.original else { return Ok(None); }; let fail = |e| load_failure(LoadPhase::Config, e); - let governor = - crate::memory_governor::startup(&governor_args(env.config, options), env.settings) - .map_err(fail)?; + let governor = crate::memory_governor::startup(&governor_args(env.config, options), env.settings).map_err(fail)?; if let Some(archive) = env.config.kar_ple_inherited.as_ref() { crate::memory_governor::guard_archive(governor, archive).map_err(fail)?; } Ok(Some(governor)) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) fn start_governor(_: &LoadEnv<'_>) -> Result { Ok(()) } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn governor_args( config: &NativeBackendConfig, options: &original_serve::OriginalServeOptions, ) -> crate::memory_governor::StartArgs { let inherited = config.kar_ple_inherited.as_ref(); crate::memory_governor::StartArgs { - kv_resident: options - .kv_resident - .unwrap_or(leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS), + kv_resident: options.kv_resident.unwrap_or(leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS), gpu_budget_bytes: config.gpu_budget_bytes, kar_file_backed: inherited.map(InheritedKarArchive::file_backed), kar_sparse_bytes: inherited diff --git a/crates/engine-qwen35-cuda/src/backend/load_bind.rs b/crates/engine-qwen35-cuda/src/backend/load_bind.rs index f01872ce..138d5e95 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_bind.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_bind.rs @@ -24,14 +24,7 @@ pub(super) fn bind_model( bound.ranked_profile = read_profile(env.optimized)?; let digest = policy_digest(env.optimized, flags, digest)?; adopt_bank(env, &mut bound.binding, capture, flags)?; - Ok(( - bound, - Identity { - model, - mode, - digest, - }, - )) + Ok((bound, Identity { model, mode, digest })) } /// Verify the sources, bind the artifact to the selected providers and admit the KAR expert source. @@ -45,13 +38,7 @@ fn bind_providers( check_mtp_context(env.config, requested)?; let selected = bind_selected(env.config, requested, parts.artifact, opened.kar)?; let binding = admit_kar_experts(env, selected)?; - let bound = Bound { - binding, - tokenizer: parts.tokenizer, - eos: parts.eos, - ranked_profile: None, - flags, - }; + let bound = Bound { binding, tokenizer: parts.tokenizer, eos: parts.eos, ranked_profile: None, flags }; Ok((bound, opened.capture)) } @@ -83,23 +70,18 @@ fn admit_expert_bank( capture: Option, flags: PolicyFlags, ) -> Result<(), BackendError> { - let mapped = env - .original - .is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped); + let mapped = env.original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Mapped); let adopted = if flags.streamed_spill { - binding.adopt_resident_expert_capture(capture.ok_or_else(|| { - load_failure( - LoadPhase::SelectedBinding, - invalid("streamed expert capture absent"), - ) - })?) + binding.adopt_resident_expert_capture( + capture + .ok_or_else(|| load_failure(LoadPhase::SelectedBinding, invalid("streamed expert capture absent")))?, + ) } else if mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() }; - adopted - .map_err(|error| load_failure(LoadPhase::SelectedBinding, expert_bank_refusal(error)))?; + adopted.map_err(|error| load_failure(LoadPhase::SelectedBinding, expert_bank_refusal(error)))?; Ok(()) } @@ -113,14 +95,8 @@ fn expert_bank_refusal(error: InputBindingError) -> BackendError { #[cfg(any(target_os = "linux", target_os = "windows"))] fn drop_shard_page_cache(env: &LoadEnv<'_>) { - if env - .original - .is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) - { - crate::memory_governor::drop_file_cache(&[ - env.config.shard0.as_path(), - env.config.shard1.as_path(), - ]); + if env.original.is_some_and(|options| options.expert_source == original_serve::ExpertSource::Resident) { + crate::memory_governor::drop_file_cache(&[env.config.shard0.as_path(), env.config.shard1.as_path()]); } } #[cfg(not(any(target_os = "linux", target_os = "windows")))] diff --git a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs index a14b8ba7..0a3ec13a 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_cuda.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_cuda.rs @@ -3,8 +3,7 @@ use super::*; use leleka_cuda_driver::Context; pub(super) fn open_driver() -> Result { - Driver::load() - .map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable"))) + Driver::load().map_err(|_| load_failure(LoadPhase::Driver, unavailable("CUDA driver unavailable"))) } pub(super) fn open_context<'d>( @@ -17,12 +16,7 @@ pub(super) fn open_context<'d>( let context = Rc::new( device .create_context(config.gpu_budget_bytes as usize) - .map_err(|_| { - load_failure( - LoadPhase::Context, - exhausted("native CUDA context unavailable"), - ) - })?, + .map_err(|_| load_failure(LoadPhase::Context, exhausted("native CUDA context unavailable")))?, ); crate::load_clock::lap("cuda_driver_and_context"); Ok(context) @@ -41,27 +35,21 @@ pub(super) fn open_checked_context<'d>( if binding.kar_expert_source().is_some() { // Fail at Load, not at the first token, if the KAR level-decode PTX is // unpinned or does not load on this device. - probe_kar_level_decode(context.as_ref()) - .map_err(|e| load_failure(LoadPhase::Context, e))?; + probe_kar_level_decode(context.as_ref()).map_err(|e| load_failure(LoadPhase::Context, e))?; } Ok(context) } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn check_vram(governed: Governed, context: &Context<'_>, budget: u64) -> Result<(), BackendError> { match governed { - Some(g) => crate::memory_governor::check_vram(g, context, budget) - .map_err(|e| load_failure(LoadPhase::Context, e)), + Some(g) => { + crate::memory_governor::check_vram(g, context, budget).map_err(|e| load_failure(LoadPhase::Context, e)) + } None => Ok(()), } } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] fn check_vram(_: Governed, _: &Context<'_>, _: u64) -> Result<(), BackendError> { Ok(()) } @@ -73,17 +61,15 @@ pub(super) fn probe_experimental_plan( plan: Option<&experimental_modes::Plan>, ) -> Result<(), BackendError> { match plan { - Some(plan) => probe_experimental(context, &env.config.experimental, plan) - .map_err(|e| load_failure(LoadPhase::Context, e)), + Some(plan) => { + probe_experimental(context, &env.config.experimental, plan).map_err(|e| load_failure(LoadPhase::Context, e)) + } None => Ok(()), } } /// Hand the bound model and the context to the Original serve stack, which serves until Unload. -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn launch_original<'d>( env: &LoadEnv<'_>, options: &original_serve::OriginalServeOptions, @@ -109,10 +95,7 @@ pub(super) fn launch_original<'d>( gpu_ordinal: env.config.gpu_device_ordinal, }) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) fn launch_original( _: &LoadEnv<'_>, _: &original_serve::OriginalServeOptions, @@ -121,8 +104,5 @@ pub(super) fn launch_original( _: Bound, _: Rc>, ) -> Result<(), BackendError> { - Err(load_failure( - LoadPhase::Selection, - unsupported("Original serve CUDA owners require Linux x86_64"), - )) + Err(load_failure(LoadPhase::Selection, unsupported("Original serve CUDA owners require Linux x86_64"))) } diff --git a/crates/engine-qwen35-cuda/src/backend/load_identity.rs b/crates/engine-qwen35-cuda/src/backend/load_identity.rs index 002a99ee..bdb4e0d4 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_identity.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_identity.rs @@ -20,9 +20,7 @@ pub(super) fn effective_identity( } fn fold_mode_digest(env: &LoadEnv<'_>, binding: &ModelBinding, digest: String) -> String { - let digest = if env.execution - == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { + let digest = if env.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { execution_mode_digest(&digest) } else { digest @@ -34,28 +32,19 @@ fn fold_mode_digest(env: &LoadEnv<'_>, binding: &ModelBinding, digest: String) - }; // An experimental mode changes model outputs, so it changes the mode (all-off leaves the digest alone). let digest = experimental_modes::mode_digest(&digest, &env.config.experimental); - if env.original.is_some() { - original_serve_execution_digest(&digest) - } else { - digest - } + if env.original.is_some() { original_serve_execution_digest(&digest) } else { digest } } pub(super) fn check_not_cancelled(shared: &Shared) -> Result<(), BackendError> { if shared.shutdown.load(Ordering::Acquire) { - return Err(load_failure( - LoadPhase::Cancellation, - unavailable("native load cancelled"), - )); + return Err(load_failure(LoadPhase::Cancellation, unavailable("native load cancelled"))); } Ok(()) } // Only a bounded, pinned metadata file is read here. Complete source SHA // admission precedes Driver/Context allocation and cannot change on RPCs. -pub(super) fn read_profile( - optimized: Option<&OptimizedBackendConfig>, -) -> Result>, BackendError> { +pub(super) fn read_profile(optimized: Option<&OptimizedBackendConfig>) -> Result>, BackendError> { optimized .and_then(|options| options.ranked_profile.as_ref()) .map(read_ranked_expert_profile) @@ -74,17 +63,10 @@ pub(super) fn policy_digest( }; let profile = options.ranked_profile.as_ref(); if !flags.queued_owners { - return Ok(optimized_execution_digest( - &digest, - profile.map(|source| source.sha256.as_str()), - )); + return Ok(optimized_execution_digest(&digest, profile.map(|source| source.sha256.as_str()))); } - let source = profile.ok_or_else(|| { - load_failure( - LoadPhase::Selection, - invalid("queued owners require ranked profile"), - ) - })?; + let source = + profile.ok_or_else(|| load_failure(LoadPhase::Selection, invalid("queued owners require ranked profile")))?; Ok(queued_family_digest(flags, &digest, &source.sha256)) } @@ -109,12 +91,7 @@ pub(super) fn build_loaded( requested: &RuntimeConfig, ) -> Result { let loaded = LoadedModel { - handle: format!( - "native-{}-{}-{}", - std::process::id(), - env.instance, - env.serial - ), + handle: format!("native-{}-{}-{}", std::process::id(), env.instance, env.serial), descriptor: identity.model, load_config_version: LOAD_CONFIG_VERSION, effective_mode: identity.mode, @@ -122,11 +99,6 @@ pub(super) fn build_loaded( }; loaded .validate_for_load(&loaded.descriptor, requested) - .map_err(|_| { - load_failure( - LoadPhase::Identity, - unavailable("native load identity failed"), - ) - })?; + .map_err(|_| load_failure(LoadPhase::Identity, unavailable("native load identity failed")))?; Ok(loaded) } diff --git a/crates/engine-qwen35-cuda/src/backend/load_moe.rs b/crates/engine-qwen35-cuda/src/backend/load_moe.rs index b8b2331f..61153a33 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_moe.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_moe.rs @@ -23,27 +23,17 @@ pub(super) fn load_moe<'c>( if let Some(dense) = optimized_dense.take() { let _ = dense.close(); } - load_forward_failure( - LoadPhase::MoeWeightCache, - e, - exhausted("MoE/MTP weight cache initialization failed"), - ) + load_forward_failure(LoadPhase::MoeWeightCache, e, exhausted("MoE/MTP weight cache initialization failed")) }) } -fn plain_moe<'c>( - execution: EvaluationExecution, - binding: &ModelBinding, - context: &'c Context<'_>, -) -> Cache<'c> { +fn plain_moe<'c>(execution: EvaluationExecution, binding: &ModelBinding, context: &'c Context<'_>) -> Cache<'c> { match execution { EvaluationExecution::Native | EvaluationExecution::ExperimentalWindowed256RetainedGr => { MoeWeightCache::new(binding, context) } EvaluationExecution::ExperimentalResidentMmq => MoeWeightCache::new_mmq(binding, context), - EvaluationExecution::ExperimentalNativeResidentMmq => { - MoeWeightCache::new_native_mmq(binding, context) - } + EvaluationExecution::ExperimentalNativeResidentMmq => MoeWeightCache::new_native_mmq(binding, context), EvaluationExecution::ExperimentalNativeIntegerIq3Mmq => { MoeWeightCache::new_native_integer_iq3_mmq(binding, context) } @@ -53,10 +43,7 @@ fn plain_moe<'c>( } } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn optimized_moe<'c>( binding: &ModelBinding, context: &'c Context<'_>, @@ -77,19 +64,12 @@ fn optimized_moe<'c>( ) } Some(bytes) => { - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile( - binding, context, bytes, - ) + MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile(binding, context, bytes) } - None => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru( - binding, context, - ), + None => MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context), }) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] fn optimized_moe<'c>( _: &ModelBinding, _: &'c Context<'_>, @@ -97,7 +77,5 @@ fn optimized_moe<'c>( ranked_profile: Option<&[u8]>, ) -> Result, BackendError> { let _ = &ranked_profile; - Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )) + Err(unsupported("optimized CUDA execution requires Linux x86_64")) } diff --git a/crates/engine-qwen35-cuda/src/backend/load_moe_gates.rs b/crates/engine-qwen35-cuda/src/backend/load_moe_gates.rs index fe2292b3..4bf1fdea 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_moe_gates.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_moe_gates.rs @@ -2,9 +2,7 @@ //! only when its witness shows the state a fresh load must have; otherwise it is closed and refused. use super::*; use crate::qwen_forward::contract::Error as ForwardError; -use crate::qwen_forward::moe_weight_cache::{ - AdaptiveWitness, LearnedMainWitness, SharedPermanentWitness, -}; +use crate::qwen_forward::moe_weight_cache::{AdaptiveWitness, LearnedMainWitness, SharedPermanentWitness}; use leleka_cuda_driver::Context; type Cache<'c> = Result, ForwardError>; @@ -15,14 +13,8 @@ fn close_refused<'c>(cache: MoeWeightCache<'c>, error: ForwardError) -> Cache<'c Err(error) } -pub(super) fn adaptive_moe<'c>( - binding: &ModelBinding, - context: &'c Context<'_>, - bytes: &[u8], -) -> Cache<'c> { - let cache = MoeWeightCache::new_native_strata_adaptive_shared_permanent_mapped( - binding, context, bytes, - )?; +pub(super) fn adaptive_moe<'c>(binding: &ModelBinding, context: &'c Context<'_>, bytes: &[u8]) -> Cache<'c> { + let cache = MoeWeightCache::new_native_strata_adaptive_shared_permanent_mapped(binding, context, bytes)?; match cache.strata_adaptive_witness(binding) { Ok(witness) if adaptive_fresh(&witness) => Ok(cache), Ok(_) => close_refused(cache, ForwardError::IdentityMismatch), @@ -48,11 +40,7 @@ fn adaptive_idle(w: &AdaptiveWitness) -> bool { && w.completed_swap_upload_bytes == 0 } -pub(super) fn learned_main_moe<'c>( - binding: &ModelBinding, - context: &'c Context<'_>, - bytes: &[u8], -) -> Cache<'c> { +pub(super) fn learned_main_moe<'c>(binding: &ModelBinding, context: &'c Context<'_>, bytes: &[u8]) -> Cache<'c> { let cache = MoeWeightCache:: new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( binding, context, bytes, @@ -67,16 +55,12 @@ pub(super) fn learned_main_moe<'c>( } } -fn learned_main_check( - cache: &MoeWeightCache<'_>, - w: &LearnedMainWitness, -) -> Result<(), ForwardError> { +fn learned_main_check(cache: &MoeWeightCache<'_>, w: &LearnedMainWitness) -> Result<(), ForwardError> { let s = cache.shared_permanent_witness()?; if learned_shared_mismatch(w, &s) || learned_main_mismatch(w) { return Err(ForwardError::IdentityMismatch); } - let demand = - u64::try_from(w.routed_matrices + w.shared_matrices).map_err(|_| ForwardError::Overflow)?; + let demand = u64::try_from(w.routed_matrices + w.shared_matrices).map_err(|_| ForwardError::Overflow)?; if w.age < demand || learned_traffic_mismatch(&s) { return Err(ForwardError::IdentityMismatch); } @@ -95,31 +79,20 @@ fn learned_main_mismatch(w: &LearnedMainWitness) -> bool { || w.routed_bytes.checked_add(w.shared_bytes) != Some(w.main_bytes) || w.main_bytes > (24usize << 30) || w.metadata_bytes > (16usize << 20) - || w.routed_matrices - .checked_add(w.shared_matrices) - .is_none_or(|n| n > w.main_slot_limit) + || w.routed_matrices.checked_add(w.shared_matrices).is_none_or(|n| n > w.main_slot_limit) || w.historical_prefix == 0 || w.historical_routed_preload_bytes != w.routed_bytes } fn learned_traffic_mismatch(s: &SharedPermanentWitness) -> bool { - s.roles != s.preload_roles - || s.request_roles != [Default::default(); 7] - || !s.successful_bytes_reconcile + s.roles != s.preload_roles || s.request_roles != [Default::default(); 7] || !s.successful_bytes_reconcile } /// Hits, fills, source-read, upload and eviction bytes summed over the seven roles. fn role_totals(s: &SharedPermanentWitness) -> Result<[u64; 5], ForwardError> { s.roles.iter().try_fold([0u64; 5], |mut totals, c| { - for (i, value) in [ - c.hits, - c.fills, - c.source_read_bytes, - c.upload_bytes, - c.eviction_bytes, - ] - .into_iter() - .enumerate() + for (i, value) in + [c.hits, c.fills, c.source_read_bytes, c.upload_bytes, c.eviction_bytes].into_iter().enumerate() { totals[i] = totals[i].checked_add(value).ok_or(ForwardError::Overflow)?; } diff --git a/crates/engine-qwen35-cuda/src/backend/load_sources.rs b/crates/engine-qwen35-cuda/src/backend/load_sources.rs index d1adf878..27431728 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_sources.rs @@ -24,49 +24,29 @@ pub(super) fn open_sources( ) -> Result { let parallel_sources = !flags.resident_owners && !flags.streamed_spill; let archive_wanted = kar_mtp_requested(requested); - let mut prefetched = - parallel_sources.then(|| verify_sources_parallel(env.config, archive_wanted, &env.clock)); - let (shard0, capture) = - open_shard0(env.config, prefetched.as_mut(), flags).map_err(shard0_refusal)?; + let mut prefetched = parallel_sources.then(|| verify_sources_parallel(env.config, archive_wanted, &env.clock)); + let (shard0, capture) = open_shard0(env.config, prefetched.as_mut(), flags).map_err(shard0_refusal)?; crate::load_clock::lap("shard0_result"); let shard1 = open_shard1(env.config, prefetched.as_mut()).map_err(shard1_refusal)?; crate::load_clock::lap("shard1_result"); let kar = prefetched.and_then(|sources| sources.kar); - Ok(Opened { - shard0, - shard1, - capture, - kar, - }) + Ok(Opened { shard0, shard1, capture, kar }) } fn shard0_refusal(_: ()) -> BackendError { - load_failure( - LoadPhase::Shard0, - invalid("pinned shard 0 verification failed"), - ) + load_failure(LoadPhase::Shard0, invalid("pinned shard 0 verification failed")) } fn shard1_refusal(_: ()) -> BackendError { - load_failure( - LoadPhase::Shard1, - invalid("pinned shard 1 verification failed"), - ) + load_failure(LoadPhase::Shard1, invalid("pinned shard 1 verification failed")) } /// The owned KAR file the capture observes (never KAR admission), when an inherited archive is configured. fn capture_observation(config: &NativeBackendConfig) -> Option<&std::fs::File> { - config - .kar_ple_inherited - .as_ref() - .map(InheritedKarArchive::expert_capture_observation) + config.kar_ple_inherited.as_ref().map(InheritedKarArchive::expert_capture_observation) } -fn open_shard0( - config: &NativeBackendConfig, - prefetched: Option<&mut VerifiedSources>, - flags: PolicyFlags, -) -> Shard0 { +fn open_shard0(config: &NativeBackendConfig, prefetched: Option<&mut VerifiedSources>, flags: PolicyFlags) -> Shard0 { if let Some(sources) = prefetched { let shard0 = std::mem::replace(&mut sources.shard0, Err(String::new())); return shard0.map(|shard| (shard, None)).map_err(|_| ()); @@ -77,9 +57,7 @@ fn open_shard0( if flags.streamed_spill { return captured_shard0(config, false); } - VerifiedGgufFile::open(&config.shard0, SHARD0) - .map(|shard| (shard, None)) - .map_err(|_| ()) + VerifiedGgufFile::open(&config.shard0, SHARD0).map(|shard| (shard, None)).map_err(|_| ()) } // Borrow metadata only from the operator's actual owned sealed archive. @@ -92,15 +70,10 @@ fn captured_shard0(config: &NativeBackendConfig, incremental: bool) -> Shard0 { } else { Qwen4ExpArtifact::open_shard0_with_expert_capture(path, SHARD0, observation) }; - opened - .map(|(shard, capture)| (shard, Some(capture))) - .map_err(|_| ()) + opened.map(|(shard, capture)| (shard, Some(capture))).map_err(|_| ()) } -fn open_shard1( - config: &NativeBackendConfig, - prefetched: Option<&mut VerifiedSources>, -) -> Result { +fn open_shard1(config: &NativeBackendConfig, prefetched: Option<&mut VerifiedSources>) -> Result { match prefetched { Some(sources) => std::mem::replace(&mut sources.shard1, Err(String::new())).map_err(|_| ()), None => VerifiedGgufFile::open(&config.shard1, SHARD1).map_err(|_| ()), @@ -114,19 +87,12 @@ pub(super) struct Parts { pub(super) eos: u32, } -pub(super) fn bind_artifact( - shard0: VerifiedGgufFile, - shard1: VerifiedGgufFile, -) -> Result { +pub(super) fn bind_artifact(shard0: VerifiedGgufFile, shard1: VerifiedGgufFile) -> Result { let artifact = Qwen4ExpArtifact::bind(shard0, shard1) .map_err(|_| load_failure(LoadPhase::Artifact, invalid("pinned model binding failed")))?; let (tokenizer, eos) = tokenizer_of(&artifact)?; crate::load_clock::lap("artifact_bind_and_tokenizer"); - Ok(Parts { - artifact, - tokenizer, - eos, - }) + Ok(Parts { artifact, tokenizer, eos }) } fn tokenizer_of(artifact: &Qwen4ExpArtifact) -> Result<(Tokenizer, u32), BackendError> { @@ -138,12 +104,7 @@ fn tokenizer_of(artifact: &Qwen4ExpArtifact) -> Result<(Tokenizer, u32), Backend metadata.merges.clone(), metadata.token_types.clone(), ) - .map_err(|_| { - load_failure( - LoadPhase::Tokenizer, - invalid("verified tokenizer construction failed"), - ) - })?; + .map_err(|_| load_failure(LoadPhase::Tokenizer, invalid("verified tokenizer construction failed")))?; let eos = *metadata .special_ids .get("tokenizer.ggml.eos_token_id") @@ -153,14 +114,9 @@ fn tokenizer_of(artifact: &Qwen4ExpArtifact) -> Result<(Tokenizer, u32), Backend // The Original-literal MTP drafter bank (mapped host image, page table, ring) is frozen at the trained // 262144-cell geometry (`MTP_ORIGINAL_MAX_CELLS`); it is refused, not resized, past it. -pub(super) fn check_mtp_context( - config: &NativeBackendConfig, - requested: &RuntimeConfig, -) -> Result<(), BackendError> { - if matches!( - requested.inference_mode, - InferenceMode::ExperimentalMtp { .. } - ) && u64::from(config.context_tokens) > leleka_context::rope_scaling::TRAINED_CONTEXT +pub(super) fn check_mtp_context(config: &NativeBackendConfig, requested: &RuntimeConfig) -> Result<(), BackendError> { + if matches!(requested.inference_mode, InferenceMode::ExperimentalMtp { .. }) + && u64::from(config.context_tokens) > leleka_context::rope_scaling::TRAINED_CONTEXT { return Err(load_failure( LoadPhase::EffectiveMode, @@ -181,9 +137,7 @@ pub(super) fn bind_selected( let bound = match &requested.inference_mode { InferenceMode::Native => ModelBinding::from_artifact(artifact), InferenceMode::ExperimentalKarPle { .. } => bind_kar_ple(config, artifact)?, - InferenceMode::ExperimentalMtp { profile_id } => { - bind_mtp(config, profile_id, artifact, kar)? - } + InferenceMode::ExperimentalMtp { profile_id } => bind_mtp(config, profile_id, artifact, kar)?, _ => return Err(unsupported("experimental mode is not supported")), }; let binding = bound.map_err(selected_binding_failure)?; @@ -191,22 +145,13 @@ pub(super) fn bind_selected( Ok(binding) } -fn bind_kar_ple( - config: &NativeBackendConfig, - artifact: Qwen4ExpArtifact, -) -> Result { +fn bind_kar_ple(config: &NativeBackendConfig, artifact: Qwen4ExpArtifact) -> Result { if let Some(source) = config.kar_ple_inherited.as_ref() { - return Ok(ModelBinding::from_artifact_with_inherited_kar_ple( - artifact, source, - )); + return Ok(ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source)); } - let (source, staging) = config - .kar_ple_source - .as_ref() - .ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - Ok(ModelBinding::from_artifact_with_pinned_kar_ple( - artifact, source, staging, - )) + let (source, staging) = + config.kar_ple_source.as_ref().ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; + Ok(ModelBinding::from_artifact_with_pinned_kar_ple(artifact, source, staging)) } fn bind_mtp( @@ -215,14 +160,9 @@ fn bind_mtp( artifact: Qwen4ExpArtifact, kar: Option, ) -> Result { - let (source, staging) = config - .mtp_source - .as_ref() - .ok_or_else(|| unsupported("MTP operator source is absent"))?; + let (source, staging) = config.mtp_source.as_ref().ok_or_else(|| unsupported("MTP operator source is absent"))?; if profile_id != KAR_MTP_PROFILE { - return Ok(ModelBinding::from_artifact_with_pinned_mtp( - artifact, source, staging, - )); + return Ok(ModelBinding::from_artifact_with_pinned_mtp(artifact, source, staging)); } bind_kar_mtp(config, artifact, kar, (source.as_path(), staging.as_path())) } @@ -234,24 +174,11 @@ fn bind_kar_mtp( (source, staging): (&Path, &Path), ) -> Result { if let Some(inherited) = config.kar_ple_inherited.as_ref() { - return Ok(bind_inherited_kar_mtp( - artifact, - inherited, - kar, - (source, staging), - )); + return Ok(bind_inherited_kar_mtp(artifact, inherited, kar, (source, staging))); } - let (kar_source, kar_staging) = config - .kar_ple_source - .as_ref() - .ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; - Ok(ModelBinding::from_artifact_with_pinned_kar_mtp( - artifact, - kar_source, - kar_staging, - source, - staging, - )) + let (kar_source, kar_staging) = + config.kar_ple_source.as_ref().ok_or_else(|| unsupported("KAR PLE operator source is absent"))?; + Ok(ModelBinding::from_artifact_with_pinned_kar_mtp(artifact, kar_source, kar_staging, source, staging)) } /// The archive verified at the same time as the shards when it was, otherwise verified by the binding itself. @@ -265,18 +192,13 @@ fn bind_inherited_kar_mtp( Some(verified) => verified.and_then(|verified| { ModelBinding::from_artifact_with_verified_kar_mtp(artifact, verified, source, staging) }), - None => { - ModelBinding::from_artifact_with_inherited_kar_mtp(artifact, inherited, source, staging) - } + None => ModelBinding::from_artifact_with_inherited_kar_mtp(artifact, inherited, source, staging), } } // Routed experts from a pinned KAR archive: verified whole (SHA-256 and // every payload CRC), mapped completely, and bound before publication. -pub(super) fn admit_kar_experts( - env: &LoadEnv<'_>, - binding: ModelBinding, -) -> Result { +pub(super) fn admit_kar_experts(env: &LoadEnv<'_>, binding: ModelBinding) -> Result { let Some(kar_config) = env.config.kar_expert_source.as_ref() else { return Ok(binding); }; @@ -287,17 +209,11 @@ pub(super) fn admit_kar_experts( )); } let source = KarExpertSource::open(kar_config).map_err(kar_expert_admission_failure)?; - binding - .with_kar_expert_source(source) - .map_err(selected_binding_failure) + binding.with_kar_expert_source(source).map_err(selected_binding_failure) } fn kar_expert_admission_failure(error: impl std::fmt::Debug) -> BackendError { use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={:?} class={error:?}", - LoadPhase::SelectedBinding - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-load phase={:?} class={error:?}", LoadPhase::SelectedBinding); invalid("KAR expert source admission failed") } diff --git a/crates/engine-qwen35-cuda/src/backend/load_tests.rs b/crates/engine-qwen35-cuda/src/backend/load_tests.rs index f7dbc114..4f752f27 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_tests.rs @@ -8,25 +8,14 @@ use crate::qwen_forward::moe_weight_cache::WeightCacheCounters; /// adaptive slots. fn former_flags(policy: OptimizedOwnerPolicy) -> [bool; 5] { use OptimizedOwnerPolicy::*; - let config = OptimizedBackendConfig { - ranked_profile: None, - policy, - }; + let config = OptimizedBackendConfig { ranked_profile: None, policy }; let optimized = Some(&config); [ optimized.is_some_and(|options| options.policy != Original), optimized.is_some_and(|options| { - matches!( - options.policy, - StreamedSpill | RetainedScratch | ResidentOwners | AdaptiveSlots - ) - }), - optimized.is_some_and(|options| { - matches!( - options.policy, - RetainedScratch | ResidentOwners | AdaptiveSlots - ) + matches!(options.policy, StreamedSpill | RetainedScratch | ResidentOwners | AdaptiveSlots) }), + optimized.is_some_and(|options| matches!(options.policy, RetainedScratch | ResidentOwners | AdaptiveSlots)), optimized.is_some_and(|options| matches!(options.policy, ResidentOwners | AdaptiveSlots)), optimized.is_some_and(|options| options.policy == AdaptiveSlots), ] @@ -35,26 +24,10 @@ fn former_flags(policy: OptimizedOwnerPolicy) -> [bool; 5] { #[test] fn policy_flags_match_the_expressions_of_the_former_serve_load() { use OptimizedOwnerPolicy::*; - for policy in [ - Original, - QueuedOwners, - StreamedSpill, - RetainedScratch, - ResidentOwners, - AdaptiveSlots, - ] { - let config = OptimizedBackendConfig { - ranked_profile: None, - policy, - }; + for policy in [Original, QueuedOwners, StreamedSpill, RetainedScratch, ResidentOwners, AdaptiveSlots] { + let config = OptimizedBackendConfig { ranked_profile: None, policy }; let f = PolicyFlags::of(Some(&config)); - let flags = [ - f.queued_owners, - f.streamed_spill, - f.retained_scratch, - f.resident_owners, - f.adaptive_slots, - ]; + let flags = [f.queued_owners, f.streamed_spill, f.retained_scratch, f.resident_owners, f.adaptive_slots]; assert_eq!(flags, former_flags(policy)); } let none = PolicyFlags::of(None); @@ -63,17 +36,10 @@ fn policy_flags_match_the_expressions_of_the_former_serve_load() { } /// The three sequential checks of the former `serve_load`, with the booleans they were made of. -fn former_gate( - execution: EvaluationExecution, - kar_mtp: bool, - observed: bool, - gguf_ple: bool, -) -> Option<&'static str> { +fn former_gate(execution: EvaluationExecution, kar_mtp: bool, observed: bool, gguf_ple: bool) -> Option<&'static str> { use EvaluationExecution::*; - let resident_mmq = matches!( - execution, - ExperimentalResidentMmq | ExperimentalNativeResidentMmq | ExperimentalNativeIntegerIq3Mmq - ); + let resident_mmq = + matches!(execution, ExperimentalResidentMmq | ExperimentalNativeResidentMmq | ExperimentalNativeIntegerIq3Mmq); if resident_mmq && (!kar_mtp || !observed) { return Some("resident MMQ evaluation requires explicit KAR PLE MTP Load"); } @@ -109,41 +75,18 @@ fn execution_gates_match_the_former_sequential_checks() { } } -fn moe( - hits: u64, - misses: u64, - read_bytes: u64, - upload_bytes: u64, - eviction_bytes: u64, -) -> WeightCacheCounters { - WeightCacheCounters { - hits, - misses, - read_bytes, - upload_bytes, - eviction_bytes, - } +fn moe(hits: u64, misses: u64, read_bytes: u64, upload_bytes: u64, eviction_bytes: u64) -> WeightCacheCounters { + WeightCacheCounters { hits, misses, read_bytes, upload_bytes, eviction_bytes } } fn dense(hits: u64, read_bytes: u64, upload_bytes: u64) -> DenseCacheCounters { - DenseCacheCounters { - hits, - read_bytes, - upload_bytes, - matrices: 9, - } + DenseCacheCounters { hits, read_bytes, upload_bytes, matrices: 9 } } #[test] fn generation_cache_line_keeps_its_text() { - let before = Counters { - moe: moe(1, 2, 3, 100, 4), - dense: dense(5, 6, 7), - }; - let after = Counters { - moe: moe(11, 5, 30, 250, 9), - dense: dense(8, 6, 70), - }; + let before = Counters { moe: moe(1, 2, 3, 100, 4), dense: dense(5, 6, 7) }; + let after = Counters { moe: moe(11, 5, 30, 250, 9), dense: dense(8, 6, 70) }; assert_eq!( generation_cache_line(before, after, (40, 12345), "completed"), "leleka-weight-cache phase=generation outcome=completed hits=10 misses=3 source_bytes=27 \ @@ -154,14 +97,8 @@ fn generation_cache_line_keeps_its_text() { #[test] fn generation_cache_line_reads_a_counter_that_went_down_as_zero() { - let before = Counters { - moe: moe(1, 2, 3, 100, 4), - dense: dense(5, 6, 7), - }; - let after = Counters { - moe: moe(11, 5, 30, 250, 9), - dense: dense(8, 6, 70), - }; + let before = Counters { moe: moe(1, 2, 3, 100, 4), dense: dense(5, 6, 7) }; + let after = Counters { moe: moe(11, 5, 30, 250, 9), dense: dense(8, 6, 70) }; assert_eq!( generation_cache_line(after, before, (400, 1), "failed"), "leleka-weight-cache phase=generation outcome=failed hits=0 misses=0 source_bytes=0 \ diff --git a/crates/engine-qwen35-cuda/src/backend/load_weights.rs b/crates/engine-qwen35-cuda/src/backend/load_weights.rs index 7debb413..6a6cafb9 100644 --- a/crates/engine-qwen35-cuda/src/backend/load_weights.rs +++ b/crates/engine-qwen35-cuda/src/backend/load_weights.rs @@ -28,25 +28,12 @@ pub(super) fn load_weights<'c, 'd>( let output = load_output(binding, context, flags.queued_owners)?; let kar_cache = load_kar_cache(binding, context)?; let mut optimized_dense = load_optimized_dense(env, binding, context, flags)?; - let moe_cache = load_moe( - env, - binding, - context, - flags, - ranked_profile, - &mut optimized_dense, - )?; + let moe_cache = load_moe(env, binding, context, flags, ranked_profile, &mut optimized_dense)?; let mtp_resident_bytes = mtp_resident_bytes(&moe_cache)?; let dense_cache = staged_or_plain_dense(binding, context, &mut optimized_dense)?; // The optional staging owner is empty after take; end its Context borrow. drop(optimized_dense); - Ok(Weights { - dense_cache, - moe_cache, - kar_cache, - output, - mtp_resident_bytes, - }) + Ok(Weights { dense_cache, moe_cache, kar_cache, output, mtp_resident_bytes }) } fn load_output<'c, 'd>( @@ -54,34 +41,21 @@ fn load_output<'c, 'd>( context: &'c Context<'d>, queued_owners: bool, ) -> Result, BackendError> { - let stage = if queued_owners { - load_compact_output(binding, context)? - } else { - OutputStage::load(binding, context) - }; + let stage = + if queued_owners { load_compact_output(binding, context)? } else { OutputStage::load(binding, context) }; stage.map_err(|e| { - load_forward_failure( - LoadPhase::OutputHead, - e, - exhausted("native output head initialization failed"), - ) + load_forward_failure(LoadPhase::OutputHead, e, exhausted("native output head initialization failed")) }) } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn load_compact_output<'c, 'd>( binding: &ModelBinding, context: &'c Context<'d>, ) -> Result>, BackendError> { Ok(OutputStage::load_compact(binding, context)) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] fn load_compact_output<'c, 'd>( _: &ModelBinding, _: &'c Context<'d>, @@ -97,13 +71,7 @@ fn load_kar_cache<'c>( .kar_ple_binding() .map(|provider| KarPleCache::new(context, provider)) .transpose() - .map_err(|e| { - load_forward_failure( - LoadPhase::KarCache, - e, - exhausted("KAR PLE cache initialization failed"), - ) - }) + .map_err(|e| load_forward_failure(LoadPhase::KarCache, e, exhausted("KAR PLE cache initialization failed"))) } fn staged_or_plain_dense<'c>( @@ -122,18 +90,11 @@ fn load_plain_dense<'c>( context: &'c Context<'_>, ) -> Result, BackendError> { DenseWeightCache::new(binding, context).map_err(|e| { - load_forward_failure( - LoadPhase::DenseWeightCache, - e, - exhausted("dense weight cache initialization failed"), - ) + load_forward_failure(LoadPhase::DenseWeightCache, e, exhausted("dense weight cache initialization failed")) }) } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn load_optimized_dense<'c>( env: &LoadEnv<'_>, binding: &ModelBinding, @@ -144,9 +105,7 @@ fn load_optimized_dense<'c>( return Ok(None); } let built = if flags.resident_owners { - DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal( - binding, context, - ) + DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(binding, context) } else if flags.retained_scratch { DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention(binding, context) } else if flags.queued_owners { @@ -155,17 +114,10 @@ fn load_optimized_dense<'c>( DenseWeightCache::new_qsa_selected_router(binding, context) }; built.map(Some).map_err(|e| { - load_forward_failure( - LoadPhase::DenseWeightCache, - e, - exhausted("optimized dense initialization failed"), - ) + load_forward_failure(LoadPhase::DenseWeightCache, e, exhausted("optimized dense initialization failed")) }) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] fn load_optimized_dense<'c>( _: &LoadEnv<'_>, _: &ModelBinding, @@ -178,22 +130,11 @@ fn load_optimized_dense<'c>( /// Resident MTP bytes: the upload of the cache build minus the ranked-profile preload. fn mtp_resident_bytes(moe_cache: &MoeWeightCache<'_>) -> Result { let initial_cache_upload_bytes = moe_cache.counters().upload_bytes; - #[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - ))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let profile_preload_bytes = moe_cache.profile_preload_upload_bytes(); - #[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )))] + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let profile_preload_bytes = 0; initial_cache_upload_bytes .checked_sub(profile_preload_bytes) - .ok_or_else(|| { - load_failure( - LoadPhase::MoeWeightCache, - invalid("cache preload accounting mismatch"), - ) - }) + .ok_or_else(|| load_failure(LoadPhase::MoeWeightCache, invalid("cache preload accounting mismatch"))) } diff --git a/crates/engine-qwen35-cuda/src/backend/owner.rs b/crates/engine-qwen35-cuda/src/backend/owner.rs index 6b90a078..f45798ba 100644 --- a/crates/engine-qwen35-cuda/src/backend/owner.rs +++ b/crates/engine-qwen35-cuda/src/backend/owner.rs @@ -27,20 +27,13 @@ pub(super) enum LoadPhase { pub(super) fn load_failure(phase: LoadPhase, error: BackendError) -> BackendError { use std::io::Write; // BackendError.message is deliberately excluded from operator diagnostics. - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={:?}", - error.code - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-load phase={phase:?} class={:?}", error.code); error } pub(super) fn selected_binding_failure(error: InputBindingError) -> BackendError { use std::io::Write; let phase = LoadPhase::SelectedBinding; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={error:?}" - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-load phase={phase:?} class={error:?}"); invalid("selected input binding failed") } pub(super) fn load_forward_failure( @@ -49,10 +42,7 @@ pub(super) fn load_forward_failure( result: BackendError, ) -> BackendError { use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-load phase={phase:?} class={error:?}" - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-load phase={phase:?} class={error:?}"); result } @@ -74,14 +64,7 @@ impl<'a> OwnerCtx<'a> { observer: Option<&'a EvaluationObserver>, selection: &'a OwnerExecution, ) -> Self { - Self { - config, - rx, - shared, - instance, - observer, - selection, - } + Self { config, rx, shared, instance, observer, selection } } fn run(&self) { let mut serial = 0_u64; @@ -103,13 +86,7 @@ impl<'a> OwnerCtx<'a> { } } } - fn load( - &self, - serial: u64, - model: ModelDescriptor, - requested: RuntimeConfig, - reply: Reply, - ) { + fn load(&self, serial: u64, model: ModelDescriptor, requested: RuntimeConfig, reply: Reply) { let env = LoadEnv { config: self.config, rx: self.rx, @@ -154,13 +131,5 @@ pub(super) fn owner( observer: Option, selection: OwnerExecution, ) { - OwnerCtx::new( - &config, - &rx, - shared, - instance, - observer.as_ref(), - &selection, - ) - .run(); + OwnerCtx::new(&config, &rx, shared, instance, observer.as_ref(), &selection).run(); } diff --git a/crates/engine-qwen35-cuda/src/backend/probes.rs b/crates/engine-qwen35-cuda/src/backend/probes.rs index 5e7bafb1..662978cf 100644 --- a/crates/engine-qwen35-cuda/src/backend/probes.rs +++ b/crates/engine-qwen35-cuda/src/backend/probes.rs @@ -7,10 +7,7 @@ pub(super) fn experimental_error(error: experimental_modes::ExperimentalError) - experimental_modes::ExperimentalError::Unsupported(message) => unsupported(message), } } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(super) fn probe_experimental( context: &leleka_cuda_driver::Context<'_>, config: &ExperimentalConfig, @@ -30,10 +27,7 @@ pub(super) fn probe_experimental( } Ok(()) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] pub(super) fn probe_experimental( _: &leleka_cuda_driver::Context<'_>, _: &ExperimentalConfig, @@ -41,28 +35,16 @@ pub(super) fn probe_experimental( ) -> Result<(), BackendError> { Err(unsupported("experimental modes require Linux CUDA")) } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -))] -pub(super) fn probe_kar_level_decode( - context: &leleka_cuda_driver::Context<'_>, -) -> Result<(), BackendError> { - leleka_cuda_driver::kar_decode_levels_gpu::KarDecodeLevels::open(context) - .map(|_| ()) - .map_err(|error| match error { - leleka_cuda_driver::kar_decode_levels::KarDecodeError::Unpinned => { - unsupported("KAR level-decode PTX is not pinned") - } - _ => unavailable("KAR level-decode program failed to load"), - }) +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +pub(super) fn probe_kar_level_decode(context: &leleka_cuda_driver::Context<'_>) -> Result<(), BackendError> { + leleka_cuda_driver::kar_decode_levels_gpu::KarDecodeLevels::open(context).map(|_| ()).map_err(|error| match error { + leleka_cuda_driver::kar_decode_levels::KarDecodeError::Unpinned => { + unsupported("KAR level-decode PTX is not pinned") + } + _ => unavailable("KAR level-decode program failed to load"), + }) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_pointer_width = "64" -)))] -pub(super) fn probe_kar_level_decode( - _: &leleka_cuda_driver::Context<'_>, -) -> Result<(), BackendError> { +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +pub(super) fn probe_kar_level_decode(_: &leleka_cuda_driver::Context<'_>) -> Result<(), BackendError> { Err(unsupported("KAR expert source requires Linux CUDA")) } diff --git a/crates/engine-qwen35-cuda/src/backend/profile_tests.rs b/crates/engine-qwen35-cuda/src/backend/profile_tests.rs index 0e2693b5..e942643a 100644 --- a/crates/engine-qwen35-cuda/src/backend/profile_tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/profile_tests.rs @@ -5,10 +5,7 @@ use super::*; use leleka_model_format::weight_source::MemWeightSource; fn hex(bytes: &[u8]) -> String { - Sha256::digest(bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect() + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() } fn refusal(error: BackendError) -> String { @@ -17,9 +14,7 @@ fn refusal(error: BackendError) -> String { } fn patterned() -> Vec { - (0..RANKED_EXPERT_PROFILE_BYTES) - .map(|i| (i % 251) as u8) - .collect() + (0..RANKED_EXPERT_PROFILE_BYTES).map(|i| (i % 251) as u8).collect() } #[test] @@ -51,18 +46,12 @@ fn a_profile_with_one_changed_byte_is_a_digest_mismatch() { fn temp_profile(tag: &str, bytes: &[u8]) -> RankedExpertProfileSource { let path = std::env::temp_dir().join(format!("ranked-profile-{tag}-{}", std::process::id())); std::fs::write(&path, bytes).unwrap(); - RankedExpertProfileSource { - path, - sha256: RANKED_EXPERT_PROFILE_SHA.to_string(), - } + RankedExpertProfileSource { path, sha256: RANKED_EXPERT_PROFILE_SHA.to_string() } } #[test] fn the_file_adapter_refuses_in_the_order_of_the_former_read() { - let unknown = RankedExpertProfileSource { - path: "missing".into(), - sha256: "00".repeat(32), - }; + let unknown = RankedExpertProfileSource { path: "missing".into(), sha256: "00".repeat(32) }; let message = refusal(read_ranked_expert_profile(&unknown).unwrap_err()); assert_eq!(message, "unrecognized ranked expert profile"); let missing = RankedExpertProfileSource { diff --git a/crates/engine-qwen35-cuda/src/backend/proxy.rs b/crates/engine-qwen35-cuda/src/backend/proxy.rs index 767863fc..d26b2d40 100644 --- a/crates/engine-qwen35-cuda/src/backend/proxy.rs +++ b/crates/engine-qwen35-cuda/src/backend/proxy.rs @@ -30,12 +30,7 @@ pub(super) struct Proxy { pub(super) type Reply = SyncSender>; pub(super) enum Command { Load(ModelDescriptor, RuntimeConfig, Reply), - Generate( - LoadedModel, - GenerationRequest, - Arc, - Reply, - ), + Generate(LoadedModel, GenerationRequest, Arc, Reply), Unload(LoadedModel, Reply<()>), /// New inference settings as a JSON document (`serve_tuning.rs`); the reply is the effective settings. Reconfigure(String, Reply), @@ -45,13 +40,7 @@ impl Proxy { if self.shared.shutdown.load(Ordering::Acquire) { return Err(unavailable("native owner stopped")); } - if self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))? - .is_some() - { + if self.shared.active.lock().map_err(|_| unavailable("native owner state unavailable"))?.is_some() { return Err(exhausted("native generation is active")); } Ok(()) @@ -62,10 +51,7 @@ impl Proxy { mpsc::TrySendError::Disconnected(_) => unavailable("native owner stopped"), }) } - pub(super) fn wait( - &self, - reply: Receiver>, - ) -> Result { + pub(super) fn wait(&self, reply: Receiver>) -> Result { self.wait_with_timeout(reply, REPLY_TIMEOUT) } pub(super) fn wait_with_timeout( @@ -102,9 +88,7 @@ impl Backend for Proxy { QUEUED_OWNERS_EXECUTION.into() } else if self.optimized_execution { OPTIMIZED_EXECUTION.into() - } else if self.execution - == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr - { + } else if self.execution == EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr { INTEGER_WINDOWED_EXECUTION.into() } else { "0.1.0-fp16-qsa-explicit-modes".into() @@ -113,9 +97,7 @@ impl Backend for Proxy { } } fn capabilities(&self) -> BackendCapabilities { - let models = if self.shared.ready.load(Ordering::Acquire) - && !self.shared.shutdown.load(Ordering::Acquire) - { + let models = if self.shared.ready.load(Ordering::Acquire) && !self.shared.shutdown.load(Ordering::Acquire) { vec![SupportedModelTuple { family: "qwen4exp".into(), architecture: "qwen4exp".into(), @@ -132,9 +114,7 @@ impl Backend for Proxy { } } fn prefix_cache_summary(&self) -> Option { - if !self.shared.ready.load(Ordering::Acquire) - || self.shared.shutdown.load(Ordering::Acquire) - { + if !self.shared.ready.load(Ordering::Acquire) || self.shared.shutdown.load(Ordering::Acquire) { return None; } original_serve::published_prefix_summary() @@ -151,11 +131,7 @@ impl Backend for Proxy { } leleka_memory::telemetry::published_telemetry() } - fn load( - &mut self, - model: ModelDescriptor, - config: RuntimeConfig, - ) -> Result { + fn load(&mut self, model: ModelDescriptor, config: RuntimeConfig) -> Result { validate_load(&model, &config)?; validate_kar_selection(&config, self.kar_configured)?; validate_mtp_selection(&config, self.mtp_configured)?; @@ -189,14 +165,8 @@ impl Backend for Proxy { return Err(invalid("generation request was already accepted")); } let cancel = Arc::new(AtomicBool::new(false)); - *self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))? = Some(Active { - id: request.request_id.clone(), - cancel: Arc::clone(&cancel), - }); + *self.shared.active.lock().map_err(|_| unavailable("native owner state unavailable"))? = + Some(Active { id: request.request_id.clone(), cancel: Arc::clone(&cancel) }); let id = request.request_id.clone(); let (tx, rx) = mpsc::sync_channel(1); if let Err(error) = self.send(Command::Generate(model.clone(), request, cancel, tx)) { @@ -212,11 +182,7 @@ impl Backend for Proxy { result } fn cancel(&mut self, request_id: &str) -> Result<(), BackendError> { - let active = self - .shared - .active - .lock() - .map_err(|_| unavailable("native owner state unavailable"))?; + let active = self.shared.active.lock().map_err(|_| unavailable("native owner state unavailable"))?; match active.as_ref() { Some(active) if active.id == request_id => { active.cancel.store(true, Ordering::Release); @@ -227,9 +193,7 @@ impl Backend for Proxy { } fn reconfigure(&mut self, settings_json: &str) -> Result { if !self.original_serve { - return Err(unsupported( - "only the Original serve path can be reconfigured at run time", - )); + return Err(unsupported("only the Original serve path can be reconfigured at run time")); } self.idle()?; if !self.shared.ready.load(Ordering::Acquire) { diff --git a/crates/engine-qwen35-cuda/src/backend/request.rs b/crates/engine-qwen35-cuda/src/backend/request.rs index fe5ab2da..65e63c2d 100644 --- a/crates/engine-qwen35-cuda/src/backend/request.rs +++ b/crates/engine-qwen35-cuda/src/backend/request.rs @@ -6,30 +6,24 @@ pub(super) fn request_sampler( entropy: u64, ) -> Result, leleka_sampler_ref::SamplingError> { let s = &request.sampling; - let raw = - leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint { - temperature_milli: request.temperature_milli, - top_p_micro: s.top_p_micro, - top_k: s.top_k, - min_p_micro: s.min_p_micro, - repetition_penalty_micro: s.repetition_penalty_micro, - frequency_penalty_micro: s.frequency_penalty_micro, - presence_penalty_micro: s.presence_penalty_micro, - penalty_last_n: s.penalty_last_n, - seed: s.seed, - }); + let raw = leleka_sampler_ref::RequestSampling::from_fixed_point(&leleka_sampler_ref::FixedPoint { + temperature_milli: request.temperature_milli, + top_p_micro: s.top_p_micro, + top_k: s.top_k, + min_p_micro: s.min_p_micro, + repetition_penalty_micro: s.repetition_penalty_micro, + frequency_penalty_micro: s.frequency_penalty_micro, + presence_penalty_micro: s.presence_penalty_micro, + penalty_last_n: s.penalty_last_n, + seed: s.seed, + }); let params = leleka_sampler_ref::SamplingParams::resolve(&raw)?; - Ok(params - .needs_sampler() - .then(|| params.to_sampler_params(entropy))) + Ok(params.needs_sampler().then(|| params.to_sampler_params(entropy))) } /// The steady-clock tick the Original takes as the seed of a request without one. pub(super) fn clock_seed() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(1, |d| d.as_nanos() as u64) - .max(1) + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_nanos() as u64).max(1) } pub(super) fn prepare_prompt( tokenizer: &Tokenizer, @@ -39,14 +33,9 @@ pub(super) fn prepare_prompt( validate_request(request)?; // The prompt may carry marks (`LiteralMarks`) for control-token text that was inside a message: that text is encoded as // ordinary text, the template's own literals as special tokens. A prompt without marks encodes as before. - let tokens = tokenizer - .encode_marked(&request.prompt) - .map_err(|_| invalid("prompt tokenization failed"))?; + let tokens = tokenizer.encode_marked(&request.prompt).map_err(|_| invalid("prompt tokenization failed"))?; if tokens.is_empty() - || tokens - .len() - .checked_add(request.max_output_tokens as usize) - .is_none_or(|total| total > context as usize) + || tokens.len().checked_add(request.max_output_tokens as usize).is_none_or(|total| total > context as usize) { return Err(exhausted("prompt and output exceed configured context")); } @@ -68,7 +57,6 @@ pub(super) fn native_position( if value >= u64::from(configured) { return Err(exhausted("native configured context exhausted")); } - let bound = Dimension::new(u64::from(model_context)) - .map_err(|_| invalid("verified native context invalid"))?; + let bound = Dimension::new(u64::from(model_context)).map_err(|_| invalid("verified native context invalid"))?; Position::new(value, bound).map_err(|_| exhausted("native model context exhausted")) } diff --git a/crates/engine-qwen35-cuda/src/backend/serve_close.rs b/crates/engine-qwen35-cuda/src/backend/serve_close.rs index 39f119b0..5f162090 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_close.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_close.rs @@ -19,21 +19,12 @@ pub(super) fn close_weights( conversations.clear(); drop(conversations); log_final_counters(&weights); - let Weights { - dense_cache, - moe_cache, - kar_cache, - output, - .. - } = weights; + let Weights { dense_cache, moe_cache, kar_cache, output, .. } = weights; let moe_closed = moe_cache.close(); let dense_closed = dense_cache.close(); drop(kar_cache); drop(output); - Closed { - caches_failed: moe_closed.is_err() || dense_closed.is_err(), - unload_reply, - } + Closed { caches_failed: moe_closed.is_err() || dense_closed.is_err(), unload_reply } } fn log_final_counters(weights: &Weights<'_, '_>) { @@ -57,22 +48,13 @@ fn log_final_counters(weights: &Weights<'_, '_>) { } /// Close the context once nothing borrows it, mark the owner shut down on a failure and answer Unload. -pub(super) fn close_context( - shared: &Shared, - context: Rc>, - closed: Closed, -) -> Result<(), BackendError> { +pub(super) fn close_context(shared: &Shared, context: Rc>, closed: Closed) -> Result<(), BackendError> { let context_closed = Rc::try_unwrap(context) .map_err(|_| unavailable("native context still borrowed"))? .close() .map_err(|_| unavailable("native context cleanup failed")); - let result = context_closed.and_then(|()| { - if closed.caches_failed { - Err(unavailable("weight cache cleanup failed")) - } else { - Ok(()) - } - }); + let result = context_closed + .and_then(|()| if closed.caches_failed { Err(unavailable("weight cache cleanup failed")) } else { Ok(()) }); if result.is_err() { shared.shutdown.store(true, Ordering::Release); } diff --git a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs index 16d08aa8..ffeb8c7a 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_generate.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_generate.rs @@ -17,12 +17,7 @@ impl Job { cancel: Arc, reply: Reply, ) -> Self { - Self { - candidate, - request, - cancel, - reply, - } + Self { candidate, request, cancel, reply } } } @@ -56,13 +51,7 @@ impl<'c> Exchange<'c> { sv.env.clock, )) }); - Self { - measured, - resume, - session, - pending_prefix: None, - before, - } + Self { measured, resume, session, pending_prefix: None, before } } } @@ -100,8 +89,8 @@ fn admit<'c>( return Ok(None); } }; - let (sink, stream) = GenerationSink::bounded_channel(QUEUE) - .map_err(|_| unavailable("generation queue unavailable"))?; + let (sink, stream) = + GenerationSink::bounded_channel(QUEUE).map_err(|_| unavailable("generation queue unavailable"))?; if job.reply.send(Ok(stream)).is_err() { conversations.clear(); return Ok(None); @@ -117,11 +106,7 @@ fn prompt_for(sv: &Serving<'_, '_, '_>, job: &Job) -> Result, BackendEr if !sv.env.shared.ready.load(Ordering::Acquire) { return Err(unavailable("native model is not ready")); } - prepare_prompt( - &sv.bound.tokenizer, - &job.request, - sv.env.config.context_tokens, - ) + prepare_prompt(&sv.bound.tokenizer, &job.request, sv.env.config.context_tokens) } fn start_session<'c>( @@ -132,8 +117,7 @@ fn start_session<'c>( match take_resumable(sv, conversations, prompt) { Some(entry) => (entry.session, Some(entry.continuation)), None => { - let fresh = - QwenSession::for_binding_on_shared_device(&sv.bound.binding, Rc::clone(sv.context)); + let fresh = QwenSession::for_binding_on_shared_device(&sv.bound.binding, Rc::clone(sv.context)); (fresh, None) } } @@ -151,9 +135,7 @@ fn take_resumable<'c>( ) -> Option> { let (loaded, binding, shared) = (sv.loaded, &sv.bound.binding, sv.env.shared); conversations - .take_for(prompt, |entry| { - resumable(entry, loaded, binding, shared, prompt) - }) + .take_for(prompt, |entry| resumable(entry, loaded, binding, shared, prompt)) .map(|resumed| resumed.session) } @@ -168,10 +150,7 @@ fn resumable( return false; } let resume = &entry.continuation; - match resume - .decoder - .validate_resume(binding, &entry.session, &resume.product, &resume.tokens) - { + match resume.decoder.validate_resume(binding, &entry.session, &resume.product, &resume.tokens) { Ok(()) => true, Err(crate::qwen_forward::contract::Error::CudaExecution) => { // Dropping a poisoned session cannot mint a fresh @@ -217,12 +196,5 @@ fn publish_prefix<'c>( ) { let committed = continuation.tokens.clone(); let loaded = sv.loaded.clone(); - conversations.publish( - &committed, - PrefixSession { - loaded, - session, - continuation, - }, - ); + conversations.publish(&committed, PrefixSession { loaded, session, continuation }); } diff --git a/crates/engine-qwen35-cuda/src/backend/serve_loop.rs b/crates/engine-qwen35-cuda/src/backend/serve_loop.rs index 5cc61a09..ba94b40f 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_loop.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_loop.rs @@ -21,13 +21,7 @@ impl<'a, 'c, 'd> Serving<'a, 'c, 'd> { loaded: &'a LoadedModel, weights: &'a mut Weights<'c, 'd>, ) -> Self { - Self { - env, - bound, - context, - loaded, - weights, - } + Self { env, bound, context, loaded, weights } } } @@ -42,16 +36,14 @@ enum Flow { // the Original's best-prefix / slot / byte-budget policy. Disabled (the // default) this is exactly the former single resident prefix. pub(super) fn new_conversations<'c>() -> Conversations<'c> { - ResidentConversations::>::new( - ResidentPolicy::from_environment().unwrap_or_else(|reason| { - use std::io::Write; - let _ = writeln!( - std::io::stderr().lock(), - "leleka-conversation configuration-rejected reason={reason}; parking disabled" - ); - ResidentPolicy::disabled() - }), - ) + ResidentConversations::>::new(ResidentPolicy::from_environment().unwrap_or_else(|reason| { + use std::io::Write; + let _ = writeln!( + std::io::stderr().lock(), + "leleka-conversation configuration-rejected reason={reason}; parking disabled" + ); + ResidentPolicy::disabled() + })) } pub(super) fn serve_commands<'c>( @@ -87,11 +79,7 @@ fn dispatch<'c>( return Ok(unload(sv.loaded, candidate, reply, unload_reply)); } Command::Generate(candidate, request, cancel, reply) => { - handle_generate( - sv, - conversations, - Job::new(candidate, request, cancel, reply), - )?; + handle_generate(sv, conversations, Job::new(candidate, request, cancel, reply))?; } } Ok(Flow::Continue) @@ -99,15 +87,11 @@ fn dispatch<'c>( fn refuse_load(conversations: &mut Conversations<'_>, reply: Reply) { conversations.clear(); - let _ = reply.send(Err(exhausted( - "unload the existing model before another load", - ))); + let _ = reply.send(Err(exhausted("unload the existing model before another load"))); } fn refuse_reconfigure(reply: Reply) { - let _ = reply.send(Err(unsupported( - "this backend cannot be reconfigured at run time", - ))); + let _ = reply.send(Err(unsupported("this backend cannot be reconfigured at run time"))); } /// The loop ends when the handle is the loaded one; its reply is kept until the model is closed. diff --git a/crates/engine-qwen35-cuda/src/backend/serve_report.rs b/crates/engine-qwen35-cuda/src/backend/serve_report.rs index c66e4755..0fc43bd9 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_report.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_report.rs @@ -11,10 +11,7 @@ pub(super) struct Counters { } impl Counters { pub(super) fn of(weights: &Weights<'_, '_>) -> Self { - Self { - moe: weights.moe_cache.counters(), - dense: weights.dense_cache.counters(), - } + Self { moe: weights.moe_cache.counters(), dense: weights.dense_cache.counters() } } pub(super) fn counts(self) -> CacheCounts { let (m, d) = (self.moe, self.dense); @@ -41,12 +38,7 @@ pub(super) fn log_generation_cache(sv: &Serving<'_, '_, '_>, before: Counters, o Err(GenerationFailure::Backend(_)) => "failed", }; let allocated = sv.context.allocated_bytes(); - let line = generation_cache_line( - before, - after, - (sv.weights.mtp_resident_bytes, allocated), - label, - ); + let line = generation_cache_line(before, after, (sv.weights.mtp_resident_bytes, allocated), label); let _ = writeln!(std::io::stderr().lock(), "{line}"); } @@ -60,11 +52,8 @@ pub(super) fn generation_cache_line( let [dense_hits, dense_source, dense_upload] = dense_deltas(before.dense, after.dense); // Resident main bytes are successful uploads less successful // LRU frees; eager MTP/dense weights are never eviction victims. - let main_resident = after - .moe - .upload_bytes - .saturating_sub(mtp_resident_bytes) - .saturating_sub(after.moe.eviction_bytes); + let main_resident = + after.moe.upload_bytes.saturating_sub(mtp_resident_bytes).saturating_sub(after.moe.eviction_bytes); let resident_dense = after.dense.upload_bytes; format!( "leleka-weight-cache phase=generation outcome={outcome} hits={hits} misses={misses} \ @@ -108,11 +97,7 @@ pub(super) fn verdict(outcome: &Outcome) -> Verdict { // Length truncation is not admitted as a reusable public result. stopped: matches!(outcome, Ok((FinishReason::Stop, _))), usage: match outcome { - Ok((_, usage)) => Some(( - usage.input_tokens, - usage.output_tokens, - usage.reused_input_tokens, - )), + Ok((_, usage)) => Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)), Err(_) => None, }, } @@ -122,39 +107,23 @@ pub(super) fn terminal_of(outcome: Outcome) -> GenerationTerminal { match outcome { Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage }, Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled, - Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed { - code: error.code, - message: error.message, - retryable: false, - }, + Err(GenerationFailure::Backend(error)) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } } } -pub(super) fn deliver_measurement( - sv: &Serving<'_, '_, '_>, - x: &mut Exchange<'_>, - verdict: &Verdict, - published: bool, -) { +pub(super) fn deliver_measurement(sv: &Serving<'_, '_, '_>, x: &mut Exchange<'_>, verdict: &Verdict, published: bool) { let (Some(observer), Some(measured)) = (sv.env.observer, x.measured.take()) else { return; }; let after = Counters::of(sv.weights).counts(); - let record = measured.into_inner().finish( - x.before.counts(), - after, - verdict.ok, - verdict.stopped, - published, - verdict.usage, - ); + let record = + measured.into_inner().finish(x.before.counts(), after, verdict.ok, verdict.stopped, published, verdict.usage); if !measurement::notify(observer, record) { use std::io::Write; // Fixed delivery status only; no request, IDs, paths or data. - let _ = writeln!( - std::io::stderr().lock(), - "leleka-evaluation observation-delivery=failed" - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-evaluation observation-delivery=failed"); } } diff --git a/crates/engine-qwen35-cuda/src/backend/serve_run.rs b/crates/engine-qwen35-cuda/src/backend/serve_run.rs index 0969568d..5b432cc8 100644 --- a/crates/engine-qwen35-cuda/src/backend/serve_run.rs +++ b/crates/engine-qwen35-cuda/src/backend/serve_run.rs @@ -2,8 +2,7 @@ use super::*; use std::cell::RefCell; -pub(super) type Sampler = - Result, leleka_sampler_ref::SamplingError>; +pub(super) type Sampler = Result, leleka_sampler_ref::SamplingError>; pub(super) type Outcome = Result<(FinishReason, Usage), GenerationFailure>; pub(super) fn run_generation<'c>( @@ -15,20 +14,11 @@ pub(super) fn run_generation<'c>( let run = build_run(sv, job, admitted, (&mut x.session, x.measured.as_ref())); let sampler = request_sampler(&job.request, clock_seed()); let max = job.request.max_output_tokens; - choose_generation( - run, - sampler, - (&admitted.prompt, max), - &mut x.resume, - &mut x.pending_prefix, - ) + choose_generation(run, sampler, (&admitted.prompt, max), &mut x.resume, &mut x.pending_prefix) } /// The session of the exchange and the recorder that observes it, when there is one. -type RunParts<'a, 'c> = ( - &'a mut QwenSession<'c>, - Option<&'a RefCell>, -); +type RunParts<'a, 'c> = (&'a mut QwenSession<'c>, Option<&'a RefCell>); pub(super) fn build_run<'a, 'c, 'd>( sv: &'a mut Serving<'_, 'c, 'd>, @@ -51,10 +41,7 @@ pub(super) fn build_run<'a, 'c, 'd>( shared: sv.env.shared, context_tokens: sv.env.config.context_tokens, eos: sv.bound.eos, - mtp: matches!( - sv.loaded.effective_mode, - InferenceMode::ExperimentalMtp { .. } - ), + mtp: matches!(sv.loaded.effective_mode, InferenceMode::ExperimentalMtp { .. }), clock: sv.env.clock, } } @@ -67,14 +54,10 @@ pub(super) fn choose_generation( pending_prefix: &mut Option, ) -> Outcome { if !run.shared.ready.load(Ordering::Acquire) { - Err(GenerationFailure::Backend(unavailable( - "resident prefix unavailable", - ))) + Err(GenerationFailure::Backend(unavailable("resident prefix unavailable"))) } else if matches!(sampler, Err(_) | Ok(Some(_))) && run.mtp { // Sampled drafting/verification (coupled draft sampling) is not wired. - Err(GenerationFailure::Backend(unsupported( - "sampling is unavailable with MTP", - ))) + Err(GenerationFailure::Backend(unsupported("sampling is unavailable with MTP"))) } else if run.mtp { generate_mtp_resume(run, prompt, max, resume.take(), pending_prefix) } else { @@ -82,18 +65,11 @@ pub(super) fn choose_generation( } } -pub(super) fn generate_single( - run: Generation<'_, '_, '_>, - sampler: Sampler, - prompt: &[u32], - max: u32, -) -> Outcome { +pub(super) fn generate_single(run: Generation<'_, '_, '_>, sampler: Sampler, prompt: &[u32], max: u32) -> Outcome { match sampler { Ok(None) => generate(run, prompt, max), Ok(Some(params)) => generate_sampled(run, params, prompt, max), - Err(_) => Err(GenerationFailure::Backend(invalid( - "unsupported generation request", - ))), + Err(_) => Err(GenerationFailure::Backend(invalid("unsupported generation request"))), } } @@ -104,16 +80,14 @@ pub(super) fn generate_sampled( max: u32, ) -> Outcome { let output = run.output; - let armed = crate::qwen_forward::step_sampler::StepSampler::new(params, prompt) - .and_then(|plan| output.arm_sampler(plan)); + let armed = + crate::qwen_forward::step_sampler::StepSampler::new(params, prompt).and_then(|plan| output.arm_sampler(plan)); match armed { Ok(()) => { let result = generate(run, prompt, max); output.disarm_sampler(); result } - Err(_) => Err(GenerationFailure::Backend(unavailable( - "sampling setup failed", - ))), + Err(_) => Err(GenerationFailure::Backend(unavailable("sampling setup failed"))), } } diff --git a/crates/engine-qwen35-cuda/src/backend/sources.rs b/crates/engine-qwen35-cuda/src/backend/sources.rs index af92ceb2..41057256 100644 --- a/crates/engine-qwen35-cuda/src/backend/sources.rs +++ b/crates/engine-qwen35-cuda/src/backend/sources.rs @@ -1,8 +1,6 @@ //! Verification of the pinned sources (shards, KAR archive, ranked profile) at load time. use super::*; -use leleka_model_format::weight_source::{ - BackingKind, FileWeightSource, WeightError, WeightSource, -}; +use leleka_model_format::weight_source::{BackingKind, FileWeightSource, WeightError, WeightSource}; /// What the three source verifications returned. Errors are reduced to text because the verifying threads hand /// them over; the callers map each to the same fixed refusal as before. @@ -13,8 +11,7 @@ pub(super) struct VerifiedSources { pub(super) kar: Option, } -pub(super) type InputResultKar = - Result; +pub(super) type InputResultKar = Result; /// Verify shard 0, shard 1 and the inherited KAR archive at the same time. They are independent files; the /// SHA-256 of each is sequential, so the wall time is the slowest one instead of their sum. Each verification @@ -33,29 +30,20 @@ pub(super) fn verify_sources_parallel( crate::load_clock::span("shard1_sha256_and_index", started); result }); - let kar = config - .kar_ple_inherited - .as_ref() - .filter(|_| want_kar) - .map(|archive| { - scope.spawn(move || { - let started = clock.now(); - let result = - crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive( - archive, - ); - crate::load_clock::span("kar_inspect_verify", started); - result - }) - }); + let kar = config.kar_ple_inherited.as_ref().filter(|_| want_kar).map(|archive| { + scope.spawn(move || { + let started = clock.now(); + let result = crate::model_binding::qwen4exp_kar_ple::load_pinned_inherited_archive(archive); + crate::load_clock::span("kar_inspect_verify", started); + result + }) + }); let started = clock.now(); let shard0 = VerifiedGgufFile::open(&config.shard0, SHARD0).map_err(|e| e.to_string()); crate::load_clock::span("shard0_sha256_and_index", started); VerifiedSources { shard0, - shard1: shard1 - .join() - .unwrap_or_else(|_| Err("verification thread failed".into())), + shard1: shard1.join().unwrap_or_else(|_| Err("verification thread failed".into())), kar: kar.map(|handle| handle.join().unwrap_or(Err(InputBindingError::Busy))), } }); @@ -69,12 +57,8 @@ pub(super) fn verify_sources_parallel( pub fn verify_sources_only(config: NativeBackendConfig) -> Result<(), BackendError> { crate::load_clock::begin(); let sources = verify_sources_parallel(&config, true, &SystemClock); - sources - .shard0 - .map_err(|_| invalid("pinned shard 0 verification failed"))?; - sources - .shard1 - .map_err(|_| invalid("pinned shard 1 verification failed"))?; + sources.shard0.map_err(|_| invalid("pinned shard 0 verification failed"))?; + sources.shard1.map_err(|_| invalid("pinned shard 1 verification failed"))?; if let Some(kar) = sources.kar { kar.map_err(|_| invalid("pinned KAR archive verification failed"))?; } @@ -91,23 +75,20 @@ pub fn set_archive_attested() { /// Operator switch of `leleka-inference --verify-stamps DIR [--verify-rehash]`: a file that matched its pinned /// digest before and is unchanged (device, inode, size, mtime, ctime) is not hashed again. Set once, before Load. pub fn set_verify_stamps(directory: PathBuf, rehash: bool) -> bool { - leleka_model_format::verify_stamp::set_global( - leleka_model_format::verify_stamp::VerifyStamps::new(directory, rehash), - ) + leleka_model_format::verify_stamp::set_global(leleka_model_format::verify_stamp::VerifyStamps::new( + directory, rehash, + )) } const PROFILE_UNAVAILABLE: &str = "ranked expert profile unavailable"; /// The pinned ranked expert profile: opened once through the `WeightSource` port, read into the one profile buffer /// the caller keeps, and accepted only when its length and digest match. -pub(super) fn read_ranked_expert_profile( - source: &RankedExpertProfileSource, -) -> Result, BackendError> { +pub(super) fn read_ranked_expert_profile(source: &RankedExpertProfileSource) -> Result, BackendError> { if source.sha256 != RANKED_EXPERT_PROFILE_SHA { return Err(invalid("unrecognized ranked expert profile")); } let file = std::fs::File::open(&source.path).map_err(|_| invalid(PROFILE_UNAVAILABLE))?; - let weights = FileWeightSource::unverified(&file, BackingKind::File) - .map_err(|_| invalid(PROFILE_UNAVAILABLE))?; + let weights = FileWeightSource::unverified(&file, BackingKind::File).map_err(|_| invalid(PROFILE_UNAVAILABLE))?; check_profile_domain(read_pinned_profile(&weights, &source.sha256)?) } @@ -137,14 +118,9 @@ pub(super) fn read_pinned_profile( /// Read the whole profile into `bytes`. A file that ended early or grew after the length check does not hold the /// pinned bytes: it is the digest refusal, as when the profile was read to its end. -fn fill_profile( - weights: &S, - bytes: &mut [u8], -) -> Result<(), BackendError> { +fn fill_profile(weights: &S, bytes: &mut [u8]) -> Result<(), BackendError> { let read_failed = || invalid("ranked expert profile read failed"); - let region = weights - .region(0..bytes.len() as u64) - .map_err(|_| read_failed())?; + let region = weights.region(0..bytes.len() as u64).map_err(|_| read_failed())?; match region.read_at(0, bytes) { Ok(()) => {} Err(WeightError::Io(std::io::ErrorKind::UnexpectedEof)) => { @@ -163,22 +139,14 @@ fn profile_digest_mismatch() -> BackendError { invalid("ranked expert profile digest mismatch") } -#[cfg(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] fn check_profile_domain(bytes: Vec) -> Result, BackendError> { crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&bytes) .map_err(|_| invalid("ranked expert profile domain mismatch"))?; Ok(bytes) } -#[cfg(not(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" -)))] +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] fn check_profile_domain(_: Vec) -> Result, BackendError> { - Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )) + Err(unsupported("optimized CUDA execution requires Linux x86_64")) } diff --git a/crates/engine-qwen35-cuda/src/backend/spawn.rs b/crates/engine-qwen35-cuda/src/backend/spawn.rs index 57b78d0a..cfc18a60 100644 --- a/crates/engine-qwen35-cuda/src/backend/spawn.rs +++ b/crates/engine-qwen35-cuda/src/backend/spawn.rs @@ -10,18 +10,10 @@ pub fn spawn_backend(config: NativeBackendConfig) -> Result, Ba pub fn spawn_backend_experimental_native_integer_iq3_windowed256_retained_gr( config: NativeBackendConfig, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 windowed256 retained GR experiment requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("IQ3 windowed256 retained GR experiment requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - None, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - ) + spawn_backend_inner(config, None, EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr) } /// Explicit public evaluation only. Normal serving has no observer and never /// exposes token IDs; this does not change the RPC or backend protocol. @@ -38,18 +30,10 @@ pub fn spawn_backend_observed_resident_mmq( config: NativeBackendConfig, observer: EvaluationObserver, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "resident MMQ evaluation requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("resident MMQ evaluation requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalResidentMmq, - ) + spawn_backend_inner(config, Some(observer), EvaluationExecution::ExperimentalResidentMmq) } /// Explicit evaluation-only native-certified activation policy. This retains /// original MMQ tensor kernels and does not certify model quality or speed. @@ -57,18 +41,10 @@ pub fn spawn_backend_observed_native_resident_mmq( config: NativeBackendConfig, observer: EvaluationObserver, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "native-certified resident MMQ evaluation requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("native-certified resident MMQ evaluation requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeResidentMmq, - ) + spawn_backend_inner(config, Some(observer), EvaluationExecution::ExperimentalNativeResidentMmq) } /// Explicit operator evaluation candidate only: IQ3 GU integer MMA with native /// integer truncation/order. Ineligible GU layers use actual native execution. @@ -78,18 +54,10 @@ pub fn spawn_backend_observed_native_integer_iq3_mmq( config: NativeBackendConfig, observer: EvaluationObserver, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 integer MMA evaluation requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("IQ3 integer MMA evaluation requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeIntegerIq3Mmq, - ) + spawn_backend_inner(config, Some(observer), EvaluationExecution::ExperimentalNativeIntegerIq3Mmq) } /// Explicit private evaluation: real outer256 with bounded64 kernels and /// retained GR transport. Native MoE arithmetic and normal serving are kept. @@ -98,18 +66,10 @@ pub fn spawn_backend_observed_windowed256_retained_gr( config: NativeBackendConfig, observer: EvaluationObserver, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "windowed256 retained GR evaluation requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("windowed256 retained GR evaluation requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalWindowed256RetainedGr, - ) + spawn_backend_inner(config, Some(observer), EvaluationExecution::ExperimentalWindowed256RetainedGr) } /// Explicit private evaluation composition: outer256 retained GR transport, /// IQ3-only native-order integer GU, and native whole-layer fallback for other GU. @@ -119,33 +79,17 @@ pub fn spawn_backend_observed_native_integer_iq3_windowed256_retained_gr( config: NativeBackendConfig, observer: EvaluationObserver, ) -> Result, BackendError> { - if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) - || config.mtp_source.is_none() - { - return Err(invalid( - "IQ3 windowed256 retained GR evaluation requires KAR PLE and MTP sources", - )); + if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() { + return Err(invalid("IQ3 windowed256 retained GR evaluation requires KAR PLE and MTP sources")); } - spawn_backend_inner( - config, - Some(observer), - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - ) + spawn_backend_inner(config, Some(observer), EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr) } pub(super) fn spawn_backend_inner( config: NativeBackendConfig, observer: Option, execution: EvaluationExecution, ) -> Result, BackendError> { - spawn_backend_configured( - config, - observer, - OwnerExecution { - original: None, - kind: execution, - optimized: None, - }, - ) + spawn_backend_configured(config, observer, OwnerExecution { original: None, kind: execution, optimized: None }) } pub(super) fn spawn_backend_configured( config: NativeBackendConfig, @@ -154,10 +98,8 @@ pub(super) fn spawn_backend_configured( ) -> Result, BackendError> { let execution = selection.kind; let optimized_execution = selection.optimized.is_some(); - let queued_owners = selection - .optimized - .as_ref() - .is_some_and(|options| options.policy != OptimizedOwnerPolicy::Original); + let queued_owners = + selection.optimized.as_ref().is_some_and(|options| options.policy != OptimizedOwnerPolicy::Original); let streamed_spill = selection.optimized.as_ref().is_some_and(|options| { matches!( options.policy, @@ -175,15 +117,10 @@ pub(super) fn spawn_backend_configured( | OptimizedOwnerPolicy::AdaptiveSlots ) }); - let adaptive_slots = selection - .optimized - .as_ref() - .is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots); + let adaptive_slots = + selection.optimized.as_ref().is_some_and(|options| options.policy == OptimizedOwnerPolicy::AdaptiveSlots); let resident_owners = selection.optimized.as_ref().is_some_and(|options| { - matches!( - options.policy, - OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots - ) + matches!(options.policy, OptimizedOwnerPolicy::ResidentOwners | OptimizedOwnerPolicy::AdaptiveSlots) }); let original_serve = selection.original.is_some(); if config.context_tokens == 0 @@ -196,29 +133,21 @@ pub(super) fn spawn_backend_configured( return Err(invalid("invalid native resource configuration")); } // The serving context (cells, RoPE scaling) is fixed once per process before any CUDA owner exists. - crate::serving::admit_context_tokens(config.context_tokens, config.gpu_budget_bytes).map_err( - |e| BackendError { - code: ErrorCode::InvalidRequest, - message: format!("native context not servable: {e}"), - retryable: false, - }, - )?; + crate::serving::admit_context_tokens(config.context_tokens, config.gpu_budget_bytes).map_err(|e| BackendError { + code: ErrorCode::InvalidRequest, + message: format!("native context not servable: {e}"), + retryable: false, + })?; let (tx, rx) = mpsc::sync_channel(QUEUE); - let shared = Arc::new(Shared { - ready: AtomicBool::new(false), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }); + let shared = + Arc::new(Shared { ready: AtomicBool::new(false), shutdown: AtomicBool::new(false), active: Mutex::new(None) }); let kar_configured = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(); let mtp_configured = config.mtp_source.is_some(); let kar_experts_configured = config.kar_expert_source.is_some(); // The Native handle a KAR-expert Load will publish: the base Native digest // mixed with the source identity (pure function of the operator config). let kar_expert_native_digest = config.kar_expert_source.as_ref().map(|source| { - kar_expert_mode_digest( - MODE_DIGEST, - &crate::model_binding::kar_expert_source::config_identity_digest(source), - ) + kar_expert_mode_digest(MODE_DIGEST, &crate::model_binding::kar_expert_source::config_identity_digest(source)) }); let worker_shared = Arc::clone(&shared); let instance = INSTANCE.fetch_add(1, Ordering::Relaxed); diff --git a/crates/engine-qwen35-cuda/src/backend/spawn_optimized.rs b/crates/engine-qwen35-cuda/src/backend/spawn_optimized.rs index 7c96c42b..7af205ec 100644 --- a/crates/engine-qwen35-cuda/src/backend/spawn_optimized.rs +++ b/crates/engine-qwen35-cuda/src/backend/spawn_optimized.rs @@ -7,19 +7,14 @@ pub fn spawn_backend_experimental_optimized_windowed256( config: NativeBackendConfig, ranked_profile: Option, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "optimized CUDA execution requires Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("optimized CUDA execution requires Linux x86_64")); } if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) || config.mtp_source.is_none() - || ranked_profile.as_ref().is_some_and(|source| { - source.path.as_os_str().is_empty() || source.sha256 != RANKED_EXPERT_PROFILE_SHA - }) + || ranked_profile + .as_ref() + .is_some_and(|source| source.path.as_os_str().is_empty() || source.sha256 != RANKED_EXPERT_PROFILE_SHA) { return Err(invalid("invalid optimized KAR PLE MTP profile selection")); } @@ -29,10 +24,7 @@ pub fn spawn_backend_experimental_optimized_windowed256( OwnerExecution { original: None, kind: EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, - optimized: Some(OptimizedBackendConfig { - ranked_profile, - policy: OptimizedOwnerPolicy::Original, - }), + optimized: Some(OptimizedBackendConfig { ranked_profile, policy: OptimizedOwnerPolicy::Original }), }, ) } @@ -43,10 +35,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_queued_owners( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { return Err(unsupported("queued CUDA owners require Linux x86_64")); } if (config.kar_ple_source.is_none() && config.kar_ple_inherited.is_none()) @@ -54,9 +43,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_queued_owners( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "invalid queued-owner KAR PLE MTP profile selection", - )); + return Err(invalid("invalid queued-owner KAR PLE MTP profile selection")); } spawn_backend_configured( config, @@ -77,13 +64,8 @@ pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "streamed spill CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); } if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() @@ -91,9 +73,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_streamed_spill( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "streamed spill requires inherited sealed KAR, MTP and pinned profile", - )); + return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); } spawn_backend_configured( config, @@ -113,13 +93,8 @@ pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "streamed spill CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); } if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() @@ -127,9 +102,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_retained_scratch( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "streamed spill requires inherited sealed KAR, MTP and pinned profile", - )); + return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); } spawn_backend_configured( config, @@ -149,13 +122,8 @@ pub fn spawn_backend_experimental_optimized_windowed256_resident_owners( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "streamed spill CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); } if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() @@ -163,9 +131,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_resident_owners( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "streamed spill requires inherited sealed KAR, MTP and pinned profile", - )); + return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); } spawn_backend_configured( config, @@ -185,13 +151,8 @@ pub fn spawn_backend_experimental_optimized_windowed256_adaptive_slots( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "streamed spill CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); } if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() @@ -199,9 +160,7 @@ pub fn spawn_backend_experimental_optimized_windowed256_adaptive_slots( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "streamed spill requires inherited sealed KAR, MTP and pinned profile", - )); + return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); } spawn_backend_configured( config, @@ -226,13 +185,8 @@ pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots( if !crate::settings::process().serve.public_evaluation { return Err(invalid("explicit public evaluation required")); } - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "streamed spill CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("streamed spill CUDA owners require Linux x86_64")); } if config.kar_ple_inherited.is_none() || config.kar_ple_source.is_some() @@ -240,9 +194,7 @@ pub fn spawn_backend_observed_experimental_optimized_windowed256_adaptive_slots( || ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { - return Err(invalid( - "streamed spill requires inherited sealed KAR, MTP and pinned profile", - )); + return Err(invalid("streamed spill requires inherited sealed KAR, MTP and pinned profile")); } spawn_backend_configured( config, diff --git a/crates/engine-qwen35-cuda/src/backend/spawn_original.rs b/crates/engine-qwen35-cuda/src/backend/spawn_original.rs index 27674153..97189931 100644 --- a/crates/engine-qwen35-cuda/src/backend/spawn_original.rs +++ b/crates/engine-qwen35-cuda/src/backend/spawn_original.rs @@ -19,11 +19,7 @@ pub fn original_serve_choice( context_tokens: config.context_tokens, }; // The probe is only consulted when the mode could select the Original path. - let unsealed = if mode == OriginalServeMode::Preview { - Vec::new() - } else { - original_serve::current_unsealed() - }; + let unsealed = if mode == OriginalServeMode::Preview { Vec::new() } else { original_serve::current_unsealed() }; original_serve::choose(mode, &facts, &unsealed) } /// The Original-literal mode17 serve backend: the generate.cpp serve loop (`OriginalSpecController` over @@ -36,13 +32,8 @@ pub fn spawn_backend_original_serve( config: NativeBackendConfig, options: OriginalServeOptions, ) -> Result, BackendError> { - if !cfg!(all( - any(target_os = "linux", target_os = "windows"), - target_arch = "x86_64" - )) { - return Err(unsupported( - "Original serve CUDA owners require Linux x86_64", - )); + if !cfg!(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")) { + return Err(unsupported("Original serve CUDA owners require Linux x86_64")); } options.validate()?; match original_serve_choice(options.mode, &config)? { @@ -70,18 +61,11 @@ pub fn spawn_backend_experimental_original_serve( config: NativeBackendConfig, ranked_profile: RankedExpertProfileSource, ) -> Result, BackendError> { - if ranked_profile.path.as_os_str().is_empty() - || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA - { - return Err(invalid( - "Original serve requires the pinned ranked profile selection", - )); + if ranked_profile.path.as_os_str().is_empty() || ranked_profile.sha256 != RANKED_EXPERT_PROFILE_SHA { + return Err(invalid("Original serve requires the pinned ranked profile selection")); } spawn_backend_original_serve( config, - OriginalServeOptions { - mode: OriginalServeMode::Original, - ..OriginalServeOptions::default() - }, + OriginalServeOptions { mode: OriginalServeMode::Original, ..OriginalServeOptions::default() }, ) } diff --git a/crates/engine-qwen35-cuda/src/backend/tests.rs b/crates/engine-qwen35-cuda/src/backend/tests.rs index 1d594b8f..0f35a839 100644 --- a/crates/engine-qwen35-cuda/src/backend/tests.rs +++ b/crates/engine-qwen35-cuda/src/backend/tests.rs @@ -20,23 +20,13 @@ fn queued_owner_identity_is_distinct_and_binds_profile_and_actual_bound_mode() { use std::fmt::Write; let _ = write!(expected_old, "{byte:02x}"); } - let original = - optimized_execution_digest("sanitized-bound-mode", Some(RANKED_EXPERT_PROFILE_SHA)); + let original = optimized_execution_digest("sanitized-bound-mode", Some(RANKED_EXPERT_PROFILE_SHA)); assert_eq!(original, expected_old); let queued = queued_owners_execution_digest("sanitized-bound-mode", RANKED_EXPERT_PROFILE_SHA); assert_ne!(queued, original); - assert_ne!( - queued, - optimized_execution_digest("sanitized-bound-mode", None) - ); - assert_ne!( - queued, - queued_owners_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA) - ); - assert_ne!( - queued, - queued_owners_execution_digest("sanitized-bound-mode", "different-profile") - ); + assert_ne!(queued, optimized_execution_digest("sanitized-bound-mode", None)); + assert_ne!(queued, queued_owners_execution_digest("different-bound-mode", RANKED_EXPERT_PROFILE_SHA)); + assert_ne!(queued, queued_owners_execution_digest("sanitized-bound-mode", "different-profile")); assert_ne!(QUEUED_OWNERS_EXECUTION, OPTIMIZED_EXECUTION); } @@ -65,21 +55,14 @@ fn explicit_kar_selection_requires_source_and_binds_actual_digests() { requested.allow_experimental = true; assert!(validate_load(&model, &requested).is_ok()); assert!(validate_kar_selection(&requested, false).is_ok()); - requested.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }; + requested.inference_mode = InferenceMode::ExperimentalKarPle { profile_id: KAR_PROFILE.into() }; assert!(validate_load(&model, &requested).is_ok()); - assert_eq!( - validate_kar_selection(&requested, false).unwrap_err().code, - ErrorCode::UnsupportedModel - ); + assert_eq!(validate_kar_selection(&requested, false).unwrap_err().code, ErrorCode::UnsupportedModel); assert!(validate_kar_selection(&requested, true).is_ok()); requested.allow_experimental = false; assert!(validate_load(&model, &requested).is_err()); requested.allow_experimental = true; - requested.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: "wrong".into(), - }; + requested.inference_mode = InferenceMode::ExperimentalKarPle { profile_id: "wrong".into() }; assert!(validate_load(&model, &requested).is_err()); let digest = kar_mode_digest(&[1; 32], &[2; 32]); assert_ne!(digest, MODE_DIGEST); @@ -89,9 +72,7 @@ fn explicit_kar_selection_requires_source_and_binds_actual_digests() { handle: "synthetic-kar".into(), descriptor: model, load_config_version: LOAD_CONFIG_VERSION, - effective_mode: InferenceMode::ExperimentalKarPle { - profile_id: KAR_PROFILE.into(), - }, + effective_mode: InferenceMode::ExperimentalKarPle { profile_id: KAR_PROFILE.into() }, mode_identity_digest: digest, }; assert!(validate_handle(&loaded, None).is_ok()); @@ -107,15 +88,9 @@ fn configured_context_admission_preserves_verified_position_identity() { for value in [0, 127] { let position = native_position(&constants, 128, value).unwrap(); assert_eq!(position, Position::new(value as u64, model_bound).unwrap()); - assert_ne!( - position, - Position::new(value as u64, configured_bound).unwrap() - ); + assert_ne!(position, Position::new(value as u64, configured_bound).unwrap()); } - assert_eq!( - native_position(&constants, 128, 128).unwrap_err().code, - ErrorCode::ResourceExhausted - ); + assert_eq!(native_position(&constants, 128, 128).unwrap_err().code, ErrorCode::ResourceExhausted); assert!(native_position(&constants, 0, 0).is_err()); assert!(native_position(&constants, constants.context_length() + 1, 0).is_err()); } @@ -128,13 +103,8 @@ fn fixed_identity_and_native_refusal_precede_artifact_access() { let mut config = native_config(); config.allow_experimental = true; assert!(validate_load(&model, &config).is_ok()); - config.inference_mode = InferenceMode::ExperimentalKarPle { - profile_id: "synthetic".into(), - }; - assert_eq!( - validate_load(&model, &config).unwrap_err().code, - ErrorCode::UnsupportedModel - ); + config.inference_mode = InferenceMode::ExperimentalKarPle { profile_id: "synthetic".into() }; + assert_eq!(validate_load(&model, &config).unwrap_err().code, ErrorCode::UnsupportedModel); let mut loaded = LoadedModel { handle: "synthetic-handle".into(), descriptor: model.clone(), @@ -151,23 +121,11 @@ fn fixed_identity_and_native_refusal_precede_artifact_access() { loaded.mode_identity_digest = kar_native.clone(); assert!(validate_handle(&loaded, Some(&kar_native)).is_ok()); assert!(validate_handle(&loaded, None).is_err()); - assert!( - validate_handle( - &loaded, - Some(&kar_expert_mode_digest(MODE_DIGEST, &[8; 32])) - ) - .is_err() - ); + assert!(validate_handle(&loaded, Some(&kar_expert_mode_digest(MODE_DIGEST, &[8; 32]))).is_err()); loaded.mode_identity_digest = MODE_DIGEST.into(); // The cold KAR archive hash needs the long budget even in Native mode. - assert_eq!( - load_reply_timeout(&InferenceMode::Native, false), - REPLY_TIMEOUT - ); - assert_eq!( - load_reply_timeout(&InferenceMode::Native, true), - KAR_LOAD_REPLY_TIMEOUT - ); + assert_eq!(load_reply_timeout(&InferenceMode::Native, false), REPLY_TIMEOUT); + assert_eq!(load_reply_timeout(&InferenceMode::Native, true), KAR_LOAD_REPLY_TIMEOUT); loaded.handle = "x".repeat(129); assert!(validate_handle(&loaded, None).is_err()); let mut wrong = model; @@ -248,11 +206,7 @@ fn utf8_length_replaces_incomplete_unicode_suffix_once() { original.extend_from_slice(suffix); assert_eq!(deltas.concat(), String::from_utf8_lossy(&original)); assert!(pending.finish().is_ok()); - assert!( - pending - .finish_length(|_| panic!("completed suffix emitted twice")) - .is_ok() - ); + assert!(pending.finish_length(|_| panic!("completed suffix emitted twice")).is_ok()); } } #[test] @@ -261,11 +215,7 @@ fn utf8_length_preserves_completed_split_unicode() { let first = pending.push(&[b'a', 0xf0]).unwrap().unwrap(); assert_eq!(pending.push(&[0x9f, 0x98]).unwrap(), None); let last = pending.push(&[0x80]).unwrap().unwrap(); - assert!( - pending - .finish_length(|_| panic!("complete Unicode emitted a replacement")) - .is_ok() - ); + assert!(pending.finish_length(|_| panic!("complete Unicode emitted a replacement")).is_ok()); assert_eq!(first + &last, "a😀"); assert!(pending.finish().is_ok()); } @@ -282,11 +232,7 @@ fn utf8_stop_keeps_incomplete_unicode_refusal() { fn utf8_interior_invalid_remains_refused_at_push() { let mut pending = Utf8Pending::default(); assert!(pending.push(&[b'a', 0xff, b'b']).is_err()); - assert!( - pending - .finish_length(|_| panic!("invalid interior bytes emitted a replacement")) - .is_err() - ); + assert!(pending.finish_length(|_| panic!("invalid interior bytes emitted a replacement")).is_err()); } #[test] fn utf8_frame_bound_refuses_before_growth() { @@ -301,10 +247,7 @@ fn cancel_is_independent_of_full_control_queue() { let shared = Arc::new(Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), - active: Mutex::new(Some(Active { - id: "synthetic-1".into(), - cancel: Arc::clone(&cancel), - })), + active: Mutex::new(Some(Active { id: "synthetic-1".into(), cancel: Arc::clone(&cancel) })), }); let mut proxy = Proxy { tx, @@ -324,13 +267,7 @@ fn cancel_is_independent_of_full_control_queue() { original_serve: false, }; let (reply, _) = mpsc::sync_channel(1); - proxy - .send(Command::Load( - pinned_model_descriptor(), - native_config(), - reply, - )) - .unwrap(); + proxy.send(Command::Load(pinned_model_descriptor(), native_config(), reply)).unwrap(); proxy.cancel("synthetic-1").unwrap(); assert!(cancel.load(Ordering::Acquire)); assert!(proxy.cancel("unknown").is_err()); @@ -338,8 +275,7 @@ fn cancel_is_independent_of_full_control_queue() { } #[test] fn prompt_context_admission_is_before_forward() { - let tokenizer = - Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap(); + let tokenizer = Tokenizer::from_vocabulary("gpt2", "qwen35", vec!["x".into()], vec![], None).unwrap(); assert_eq!(prepare_prompt(&tokenizer, &request(), 2).unwrap(), vec![0]); assert!(prepare_prompt(&tokenizer, &request(), 1).is_err()); let mut r = request(); @@ -354,8 +290,7 @@ fn marked_control_token_text_is_encoded_as_text_and_the_templates_own_literals_s tokens.push("".into()); let mut types = vec![1u32; 256]; types.extend([4, 4]); - let tokenizer = - Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, vec![], Some(types)).unwrap(); + let tokenizer = Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, vec![], Some(types)).unwrap(); let mut r = request(); r.max_output_tokens = 1; // The template's own `` and a quoted `` in the message. @@ -366,8 +301,5 @@ fn marked_control_token_text_is_encoded_as_text_and_the_templates_own_literals_s assert_eq!(tokenizer.decode(&ids).unwrap(), "\na"); // A prompt without marks is encoded as before. r.prompt = "\na".into(); - assert_eq!( - prepare_prompt(&tokenizer, &r, 100).unwrap(), - tokenizer.encode(&r.prompt, true).unwrap() - ); + assert_eq!(prepare_prompt(&tokenizer, &r, 100).unwrap(), tokenizer.encode(&r.prompt, true).unwrap()); } diff --git a/crates/engine-qwen35-cuda/src/backend/utf8.rs b/crates/engine-qwen35-cuda/src/backend/utf8.rs index b7875643..3ff1bbda 100644 --- a/crates/engine-qwen35-cuda/src/backend/utf8.rs +++ b/crates/engine-qwen35-cuda/src/backend/utf8.rs @@ -5,17 +5,10 @@ use super::*; pub(super) struct Utf8Pending(pub(super) Vec); impl Utf8Pending { pub(super) fn push(&mut self, bytes: &[u8]) -> Result, BackendError> { - if self - .0 - .len() - .checked_add(bytes.len()) - .is_none_or(|len| len > FRAME_LIMIT) - { + if self.0.len().checked_add(bytes.len()).is_none_or(|len| len > FRAME_LIMIT) { return Err(exhausted("decoded token exceeds output frame limit")); } - self.0 - .try_reserve(bytes.len()) - .map_err(|_| exhausted("token decoding allocation failed"))?; + self.0.try_reserve(bytes.len()).map_err(|_| exhausted("token decoding allocation failed"))?; self.0.extend_from_slice(bytes); let valid = match std::str::from_utf8(&self.0) { Ok(_) => self.0.len(), @@ -25,9 +18,8 @@ impl Utf8Pending { if valid == 0 { return Ok(None); } - let text = std::str::from_utf8(&self.0[..valid]) - .map_err(|_| unavailable("native UTF8 prefix invalid"))? - .to_owned(); + let text = + std::str::from_utf8(&self.0[..valid]).map_err(|_| unavailable("native UTF8 prefix invalid"))?.to_owned(); self.0.drain(..valid); Ok(Some(text)) } @@ -49,11 +41,7 @@ impl Utf8Pending { Ok(()) } pub(super) fn finish(&self) -> Result<(), BackendError> { - if self.0.is_empty() { - Ok(()) - } else { - Err(unavailable("generation ended with incomplete UTF8")) - } + if self.0.is_empty() { Ok(()) } else { Err(unavailable("generation ended with incomplete UTF8")) } } } pub(super) fn emit_terminal( @@ -64,9 +52,7 @@ pub(super) fn emit_terminal( let start = clock.now(); loop { match sink.try_emit(GenerationEvent::Terminal(terminal.clone())) { - Err(ContractError::GenerationBackpressure) - if clock.since(start) < BACKPRESSURE_TIMEOUT => - { + Err(ContractError::GenerationBackpressure) if clock.since(start) < BACKPRESSURE_TIMEOUT => { thread::sleep(Duration::from_millis(5)) } result => return result, @@ -89,9 +75,7 @@ pub(super) fn emit_event( } match sink.try_emit(event.clone()) { Ok(()) => return Ok(()), - Err(ContractError::GenerationBackpressure) - if clock.since(start) < BACKPRESSURE_TIMEOUT => - { + Err(ContractError::GenerationBackpressure) if clock.since(start) < BACKPRESSURE_TIMEOUT => { thread::sleep(Duration::from_millis(5)) } Err(ContractError::GenerationClosed) => return Err(GenerationFailure::Cancelled), diff --git a/crates/engine-qwen35-cuda/src/backend/validate.rs b/crates/engine-qwen35-cuda/src/backend/validate.rs index a82c026d..c1268f1c 100644 --- a/crates/engine-qwen35-cuda/src/backend/validate.rs +++ b/crates/engine-qwen35-cuda/src/backend/validate.rs @@ -1,13 +1,8 @@ //! Admission checks of loads, handles and generation requests. use super::*; -pub(super) fn validate_load( - model: &ModelDescriptor, - config: &RuntimeConfig, -) -> Result<(), BackendError> { - config - .validate() - .map_err(|_| invalid("invalid load configuration"))?; +pub(super) fn validate_load(model: &ModelDescriptor, config: &RuntimeConfig) -> Result<(), BackendError> { + config.validate().map_err(|_| invalid("invalid load configuration"))?; if model != &pinned_model_descriptor() { return Err(unsupported("unsupported pinned model identity")); } @@ -21,19 +16,13 @@ pub(super) fn validate_load( Ok(()) } pub(super) fn load_reply_timeout(mode: &InferenceMode, kar_experts_configured: bool) -> Duration { - if requires_kar(mode) - || kar_experts_configured - || matches!(mode, InferenceMode::ExperimentalMtp { .. }) - { + if requires_kar(mode) || kar_experts_configured || matches!(mode, InferenceMode::ExperimentalMtp { .. }) { KAR_LOAD_REPLY_TIMEOUT } else { REPLY_TIMEOUT } } -pub(super) fn validate_kar_selection( - config: &RuntimeConfig, - source_present: bool, -) -> Result<(), BackendError> { +pub(super) fn validate_kar_selection(config: &RuntimeConfig, source_present: bool) -> Result<(), BackendError> { if requires_kar(&config.inference_mode) && !source_present { return Err(unsupported("KAR PLE operator source is absent")); } @@ -44,19 +33,13 @@ pub(super) fn requires_kar(mode: &InferenceMode) -> bool { matches!(mode, InferenceMode::ExperimentalKarPle { .. }) || matches!(mode, InferenceMode::ExperimentalMtp { profile_id } if profile_id == KAR_MTP_PROFILE) } -pub(super) fn validate_mtp_selection( - config: &RuntimeConfig, - present: bool, -) -> Result<(), BackendError> { +pub(super) fn validate_mtp_selection(config: &RuntimeConfig, present: bool) -> Result<(), BackendError> { if matches!(config.inference_mode, InferenceMode::ExperimentalMtp { .. }) && !present { return Err(unsupported("MTP operator source is absent")); } Ok(()) } -pub(super) fn validate_handle( - model: &LoadedModel, - kar_expert_native_digest: Option<&str>, -) -> Result<(), BackendError> { +pub(super) fn validate_handle(model: &LoadedModel, kar_expert_native_digest: Option<&str>) -> Result<(), BackendError> { if model.handle.is_empty() || model.handle.len() > 128 || model.handle.chars().any(char::is_control) @@ -65,32 +48,18 @@ pub(super) fn validate_handle( || !match &model.effective_mode { // With a KAR expert source the Native handle carries the source // identity; it must equal the digest this owner would publish. - InferenceMode::Native => { - model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST) - } + InferenceMode::Native => model.mode_identity_digest == kar_expert_native_digest.unwrap_or(MODE_DIGEST), InferenceMode::ExperimentalKarPle { profile_id } => { profile_id == KAR_PROFILE - && model - .mode_identity_digest - .strip_prefix("sha256:") - .is_some_and(|hex| { - hex.len() == 64 - && hex - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - }) + && model.mode_identity_digest.strip_prefix("sha256:").is_some_and(|hex| { + hex.len() == 64 && hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) } InferenceMode::ExperimentalMtp { profile_id } => { (profile_id == NATIVE_MTP_PROFILE || profile_id == KAR_MTP_PROFILE) - && model - .mode_identity_digest - .strip_prefix("sha256:") - .is_some_and(|hex| { - hex.len() == 64 - && hex - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) - }) + && model.mode_identity_digest.strip_prefix("sha256:").is_some_and(|hex| { + hex.len() == 64 && hex.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + }) } _ => false, } diff --git a/crates/engine-qwen35-cuda/src/backend_measurement.rs b/crates/engine-qwen35-cuda/src/backend_measurement.rs index 60f886f2..d61c4cd1 100644 --- a/crates/engine-qwen35-cuda/src/backend_measurement.rs +++ b/crates/engine-qwen35-cuda/src/backend_measurement.rs @@ -105,11 +105,7 @@ impl Recorder { (&self.output, self.windows.len(), self.prefill.is_some()) } pub(super) fn retained(&mut self, n: usize) { - if n > self.input.len() { - self.failed = Some(MeasurementFailure::Bounds) - } else { - self.retained = n - } + if n > self.input.len() { self.failed = Some(MeasurementFailure::Bounds) } else { self.retained = n } } pub(super) fn prefilled(&mut self) { if self.prefill.replace(self.clock.since(self.start)).is_some() { @@ -151,9 +147,7 @@ impl Recorder { }); } pub(super) fn decoded(&mut self) { - self.decode = self - .prefill - .and_then(|p| self.clock.since(self.start).checked_sub(p)); + self.decode = self.prefill.and_then(|p| self.clock.since(self.start).checked_sub(p)); } pub(super) fn finish( self, @@ -169,13 +163,7 @@ impl Recorder { } let prefill = self.prefill.ok_or(MeasurementFailure::Incomplete)?; let decode = self.decode.ok_or(MeasurementFailure::Incomplete)?; - if usage - != Some(( - self.input.len() as u64, - self.output.len() as u64, - self.retained as u64, - )) - { + if usage != Some((self.input.len() as u64, self.output.len() as u64, self.retained as u64)) { return Err(MeasurementFailure::Incomplete); } let a = [ @@ -216,13 +204,7 @@ impl Recorder { }) } } -pub(super) fn notify( - observer: &EvaluationObserver, - result: Result, -) -> bool { +pub(super) fn notify(observer: &EvaluationObserver, result: Result) -> bool { // Callback failure cannot unwind or replace the actor's actual terminal. - matches!( - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observer(result))), - Ok(Ok(())) - ) + matches!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observer(result))), Ok(Ok(()))) } diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve.rs b/crates/engine-qwen35-cuda/src/backend_original_serve.rs index 12acde87..f0e4ead3 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve.rs @@ -120,7 +120,7 @@ pub(super) struct ConfigFacts { } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(super) use runner::{run, Run}; +pub(super) use runner::{Run, run}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "backend_original_serve/runner.rs"] @@ -133,10 +133,6 @@ mod tests; #[path = "backend_original_serve/impl_originalservemode.rs"] mod impl_originalservemode; #[allow(unused_imports)] -pub(super) use impl_originalservemode::published_prefix_summary; -#[allow(unused_imports)] -use impl_originalservemode::ineligible; -#[allow(unused_imports)] pub(super) use impl_originalservemode::choose; #[allow(unused_imports)] pub(super) use impl_originalservemode::context_fits; @@ -146,3 +142,7 @@ pub(super) use impl_originalservemode::current_unsealed; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] #[allow(unused_imports)] pub(super) use impl_originalservemode::current_unsealed; +#[allow(unused_imports)] +use impl_originalservemode::ineligible; +#[allow(unused_imports)] +pub(super) use impl_originalservemode::published_prefix_summary; diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/impl_originalservemode.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/impl_originalservemode.rs index 7dce1c16..bff4b6f7 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/impl_originalservemode.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/impl_originalservemode.rs @@ -79,17 +79,26 @@ impl OriginalServeOptions { self.validate().map_err(|error| error.message) } pub(in super::super) fn validate(&self) -> Result<(), BackendError> { - let capacity_ok = self.prefill_capacity.is_none_or(|c| [256, 512, 1024, 2048, 3072, 4096, 6144, 8192].contains(&c)); + let capacity_ok = + self.prefill_capacity.is_none_or(|c| [256, 512, 1024, 2048, 3072, 4096, 6144, 8192].contains(&c)); let directory_ok = self.mtp_rt_directory.as_ref().is_none_or(|d| !d.as_os_str().is_empty()); let cache_ok = self.prompt_cache <= 64 && self.turn_token.is_none_or(|t| t < 248_320); let prefix_ok = self.prefix_cache.as_ref().is_none_or(|p| p.block_tokens % 256 == 0 && p.block_tokens <= 8192); - if !capacity_ok || !directory_ok || !cache_ok || !prefix_ok || !self.spec_min_p.is_finite() || !(0.0..=1.0).contains(&self.spec_min_p) { + if !capacity_ok + || !directory_ok + || !cache_ok + || !prefix_ok + || !self.spec_min_p.is_finite() + || !(0.0..=1.0).contains(&self.spec_min_p) + { return Err(super::super::invalid("invalid Original serve options")); } Ok(()) } /// The stack's conversation-cache configuration, `None` when `--prompt-cache 0`. - pub(in super::super) fn conversation(&self) -> Option { + pub(in super::super) fn conversation( + &self, + ) -> Option { (self.prompt_cache > 0).then(|| crate::qwen_forward::original_serve_stack::ConversationConfig { prompt_cache: self.prompt_cache, prompt_cache_every: self.prompt_cache_every, diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs index 36f3074f..4364a435 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner.rs @@ -1,12 +1,12 @@ //! Moved out of the parent file by STRA-338 (same module path as before). use super::super::{ - emit_event, emit_terminal, exhausted, invalid, load_failure, prepare_prompt, request_sampler, clock_seed, unavailable, - ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GenerationEvent, - GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, Reply, Shared, - Tokenizer, Usage, Utf8Pending, GENERATION_TIMEOUT, QUEUE, + ActiveGuard, BackendError, Command, ErrorCode, FinishReason, GENERATION_TIMEOUT, GenerationEvent, + GenerationFailure, GenerationSink, GenerationTerminal, LoadPhase, LoadedModel, ModelBinding, QUEUE, Reply, Shared, + Tokenizer, Usage, Utf8Pending, clock_seed, emit_event, emit_terminal, exhausted, invalid, load_failure, + prepare_prompt, request_sampler, unavailable, }; -use super::{context_fits, OriginalServeOptions, PrefixTail, PREFIX_SUMMARY}; +use super::{OriginalServeOptions, PREFIX_SUMMARY, PrefixTail, context_fits}; type GpuProbe = Box Option + Send + Sync>; use crate::qwen_forward::{ @@ -17,7 +17,6 @@ use crate::qwen_forward::{ original_serve_verifier::ServeFailure, }; use leleka_backend_api::GenerationRequest; -use {crate::idle_sweep::IdleSweep, leleka_obs::time::{Clock, SystemClock}}; use std::{ path::PathBuf, rc::Rc, @@ -28,6 +27,10 @@ use std::{ thread, time::Duration, }; +use { + crate::idle_sweep::IdleSweep, + leleka_obs::time::{Clock, SystemClock}, +}; /// Everything the Original owner loop needs from `serve_load` once the context exists. pub(in super::super) struct Run<'a, 'd> { @@ -73,7 +76,8 @@ mod capture_tests { }; capture_request(&dir, &[1, 2, 3], &[7, 8], &request, 2, 1); capture_request(&dir, &[1, 2, 3, 7, 8, 9], &[5], &request, 1, 4); - let names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + let names: Vec = + std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); let first = names.iter().filter(|n| n.starts_with("req-")).min().cloned().unwrap(); let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join(&first)).unwrap()).unwrap(); assert_eq!(doc["prompt_ids"], serde_json::json!([1, 2, 3])); @@ -90,9 +94,13 @@ mod capture_tests { #[path = "runner/gpu_probe_fn.rs"] mod gpu_probe_fn; #[allow(unused_imports)] +use gpu_probe_fn::admission_error; +#[allow(unused_imports)] +use gpu_probe_fn::capture_request; +#[allow(unused_imports)] use gpu_probe_fn::gpu_probe; #[allow(unused_imports)] -use gpu_probe_fn::stack_config; +use gpu_probe_fn::log_request_end; #[allow(unused_imports)] use gpu_probe_fn::meta_facts; #[allow(unused_imports)] @@ -100,11 +108,7 @@ use gpu_probe_fn::open_error; #[allow(unused_imports)] use gpu_probe_fn::publish_prefix_summary; #[allow(unused_imports)] -use gpu_probe_fn::admission_error; -#[allow(unused_imports)] -use gpu_probe_fn::log_request_end; -#[allow(unused_imports)] -use gpu_probe_fn::capture_request; +use gpu_probe_fn::stack_config; #[path = "runner/generate_fn.rs"] mod generate_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs index 19100148..bcd569e9 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/generate_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// One request over the stack; the caller owns the stream/terminal bookkeeping. #[allow(clippy::too_many_arguments)] pub(in super::super::super) fn generate( @@ -46,9 +45,8 @@ pub(in super::super::super) fn generate( // the authoritative EOS (<|im_end|> or <|endoftext|>) counts as an output token and carries no text return Ok(()); } - let bytes = tokenizer - .decode_bytes(&[token as u32]) - .map_err(|_| unavailable("native token decoding failed"))?; + let bytes = + tokenizer.decode_bytes(&[token as u32]).map_err(|_| unavailable("native token decoding failed"))?; if let Some(text) = utf8.push(&bytes)? { emit_event(sink, &cancelled, clock, GenerationEvent::TextDelta { text })?; } @@ -103,7 +101,14 @@ pub(in super::super::super) fn generate( } }; if let Some(directory) = crate::settings::process().serve.capture_dir.as_ref() { - capture_request(std::path::Path::new(directory), prompt, &generated_ids, request, outcome.rounds as u64, stack.reused_tokens() as u64); + capture_request( + std::path::Path::new(directory), + prompt, + &generated_ids, + request, + outcome.rounds as u64, + stack.reused_tokens() as u64, + ); } let reason = match outcome.stop { ServeStop::Eos => FinishReason::Stop, @@ -120,7 +125,13 @@ pub(in super::super::super) fn generate( reused_input_tokens: stack.reused_tokens() as u64, }; let (prompt_ms, decode_ms) = stack.last_timing(); - leleka_memory::telemetry::request_finished(usage.input_tokens, usage.reused_input_tokens, usage.output_tokens, prompt_ms, decode_ms); + leleka_memory::telemetry::request_finished( + usage.input_tokens, + usage.reused_input_tokens, + usage.output_tokens, + prompt_ms, + decode_ms, + ); let tier_stats = stack.expert_tier_stats(); let tier = tier_stats.map(|s| leleka_memory::telemetry::TierCounters { groups: s.groups, @@ -132,7 +143,15 @@ pub(in super::super::super) fn generate( }); leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier); emit_event(sink, &cancelled, clock, GenerationEvent::Usage(usage.clone()))?; - log_request_end(&request.request_id, &usage, prompt_ms, decode_ms, outcome.produced as u64, outcome.rounds as u64, tier); + log_request_end( + &request.request_id, + &usage, + prompt_ms, + decode_ms, + outcome.produced as u64, + outcome.rounds as u64, + tier, + ); if leleka_obs::settings().legacy { // the exact lines scripts/e2e/analyze_session.py parses leleka_obs::legacy_line(&format!( diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs index 3ef63824..f701b221 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/gpu_probe_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The telemetry sampler's view of the GPU: NVML when `libnvidia-ml` loads, otherwise polling `nvidia-smi` (WSL2, containers /// without the management library), otherwise nothing (the document then has no `gpu` block). pub(super) fn gpu_probe(ordinal: u32) -> Option { @@ -68,13 +67,22 @@ pub(super) fn stack_config(options: &OriginalServeOptions, context_tokens: u32) config.prefix = Some(prefix_config); } // The VRAM expert tier (off unless LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS / _EXPERT_PROFILE select it). - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .map_err(|_| load_failure(LoadPhase::OriginalStack, invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting")))?; + config.expert_tier = + crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment().map_err(|_| { + load_failure( + LoadPhase::OriginalStack, + invalid("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"), + ) + })?; Ok(config) } /// The effective tuning of a stack configuration as plain values for the start-up report (`serve_meta`); reads nothing else. -pub(super) fn meta_facts(config: &StackConfig, options: &OriginalServeOptions, context_tokens: u32) -> crate::serve_meta::ConfigFacts { +pub(super) fn meta_facts( + config: &StackConfig, + options: &OriginalServeOptions, + context_tokens: u32, +) -> crate::serve_meta::ConfigFacts { use crate::qwen_forward::original_serve_stack::{PrefixBudget, TailMode}; let prefix = config.prefix.as_ref().filter(|p| !matches!(p.budget, PrefixBudget::Off)); let slots = config.expert_tier.effective_slots(); @@ -173,7 +181,14 @@ pub(super) fn log_request_end( /// `LELEKA_CAPTURE_DIR`: keep the prompt ids and the generated ids of every completed request for offline replay /// (`original_serve_replay_smoke`). PRIVATE data (the prompt is the user's conversation): never in Git. One /// `req-NNNNNN.json` per request plus `prompts.ids` / `generated.ids`, one comma-separated line per request. -pub(super) fn capture_request(dir: &std::path::Path, prompt: &[u32], generated: &[i32], request: &GenerationRequest, rounds: u64, reused: u64) { +pub(super) fn capture_request( + dir: &std::path::Path, + prompt: &[u32], + generated: &[i32], + request: &GenerationRequest, + rounds: u64, + reused: u64, +) { use std::io::Write; static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); let index = NEXT.fetch_add(1, Ordering::Relaxed); diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs index 68999926..77497788 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/runner/run_fn.rs @@ -3,11 +3,24 @@ #[allow(unused_imports)] use super::*; - /// Open the stack, answer the load, then serve commands until unload/shutdown. Returns the unload reply /// target, as `serve_load` does after its loop. pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError> { - let Run { context_tokens, rx, shared, binding, context, tokenizer, eos, loaded, reply, options, model_files, clock, gpu_ordinal } = args; + let Run { + context_tokens, + rx, + shared, + binding, + context, + tokenizer, + eos, + loaded, + reply, + options, + model_files, + clock, + gpu_ordinal, + } = args; // the settings can change at run time (`Command::Reconfigure`): this thread owns the current copy let mut options = options.clone(); let mut context_tokens = context_tokens; @@ -21,11 +34,12 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError &crate::serve_meta::ModelInfo::recorded(&loaded.descriptor.artifact_digest, &model_files), &meta_facts(&config, &options, context_tokens), )); - let stack = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve open: {}", failure.describe()); - load_failure(LoadPhase::OriginalStack, open_error(&failure)) - })?; + let stack = + OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve open: {}", failure.describe()); + load_failure(LoadPhase::OriginalStack, open_error(&failure)) + })?; crate::serve_meta::emit(&[crate::serve_meta::cache_line(&match stack.prefix_summary(0) { Some(summary) => crate::serve_meta::CacheFacts { prefix_on: true, @@ -34,7 +48,13 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError prefix_used_bytes: summary.used_bytes, prefix_budget_bytes: summary.budget_bytes, }, - None => crate::serve_meta::CacheFacts { prefix_on: false, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 0 }, + None => crate::serve_meta::CacheFacts { + prefix_on: false, + prefix_entries: 0, + prefix_blocks: 0, + prefix_used_bytes: 0, + prefix_budget_bytes: 0, + }, })]); publish_prefix_summary(&stack, shared); crate::load_clock::lap("serve_stack_open_total"); @@ -84,7 +104,11 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError let expired = owner.prefix_expire_idle(); if expired > 0 { use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", owner.prefix_metrics().unwrap_or_default()); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve prefix retention: expired {expired} idle checkpoint(s); {}", + owner.prefix_metrics().unwrap_or_default() + ); publish_prefix_summary(owner, shared); } } @@ -96,10 +120,13 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError } Ok(Command::Reconfigure(text, reply)) => { let outcome = (|| -> Result { - let tuning = crate::serve_tuning::Tuning::parse(&text).map_err(super::super::super::invalid_dynamic)?; + let tuning = + crate::serve_tuning::Tuning::parse(&text).map_err(super::super::super::invalid_dynamic)?; let mut next_options = options.clone(); let mut next_context = context_tokens; - let changed = tuning.apply(&mut next_options, &mut next_context).map_err(super::super::super::invalid_dynamic)?; + let changed = tuning + .apply(&mut next_options, &mut next_context) + .map_err(super::super::super::invalid_dynamic)?; if changed.is_empty() || stack.is_none() { return Ok(crate::serve_tuning::describe(&options, context_tokens, workers, None).to_string()); } @@ -108,7 +135,9 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError // what is free now. Refuse up front on a starved host instead of leaving the engine without a stack (live native run 2026-10-25). if let Some(governor) = leleka_memory::Governor::global() { let need = governor.policy().soft_floor.saturating_add(RECONFIGURE_HEADROOM_BYTES); - if let Some(available) = governor.probe().effective_available().filter(|available| *available < need) { + if let Some(available) = + governor.probe().effective_available().filter(|available| *available < need) + { return Err(BackendError { code: ErrorCode::ResourceExhausted, message: format!( @@ -121,7 +150,10 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError }); } } - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure: {changed:?}; reopening the serve stack"); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve reconfigure: {changed:?}; reopening the serve stack" + ); let started = clock.now(); shared.ready.store(false, Ordering::Release); if let Some(old) = stack.take() { @@ -130,10 +162,13 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError return Err(unavailable("Original serve stack cleanup failed during reconfigure")); } } - let open = |options: &OriginalServeOptions, tokens: u32| -> Result<(OriginalServeStack<'_, '_>, i32), BackendError> { + let open = |options: &OriginalServeOptions, + tokens: u32| + -> Result<(OriginalServeStack<'_, '_>, i32), BackendError> { let config = stack_config(options, tokens)?; let workers = config.cpu_workers; - let opened = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config).map_err(|failure| open_error(&failure))?; + let opened = OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) + .map_err(|failure| open_error(&failure))?; Ok((opened, workers)) }; match open(&next_options, next_context) { @@ -145,7 +180,11 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError workers = w; } Err(failure) => { - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure failed: {}; reopening with the previous settings", failure.message); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve reconfigure failed: {}; reopening with the previous settings", + failure.message + ); match open(&options, context_tokens) { Ok((again, w)) => { publish_prefix_summary(&again, shared); @@ -157,17 +196,25 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError shared.shutdown.store(true, Ordering::Release); // No stack is left and none can be built here: end the process a moment after the reply goes out so that the // supervisor starts a fresh engine instead of keeping a half-dead one. - let _ = writeln!(std::io::stderr().lock(), "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine"); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine" + ); thread::spawn(|| { thread::sleep(Duration::from_secs(2)); std::process::exit(70); }); - return Err(unavailable("reconfigure failed and the previous settings could not be restored")); + return Err(unavailable( + "reconfigure failed and the previous settings could not be restored", + )); } } return Err(BackendError { code: ErrorCode::InvalidRequest, - message: format!("reconfigure refused: {}; the previous settings are back", failure.message), + message: format!( + "reconfigure refused: {}; the previous settings are back", + failure.message + ), retryable: false, }); } @@ -176,7 +223,11 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError leleka_memory::telemetry::set_context_max(u64::from(context_tokens)); let effective = crate::serve_tuning::describe(&options, context_tokens, workers, None); leleka_memory::telemetry::set_settings(effective.clone()); - let _ = writeln!(std::io::stderr().lock(), "leleka-serve reconfigure done in {:.1} s", clock.since(started).as_secs_f64()); + let _ = writeln!( + std::io::stderr().lock(), + "leleka-serve reconfigure done in {:.1} s", + clock.since(started).as_secs_f64() + ); Ok(effective.to_string()) })(); let _ = reply.send(outcome); @@ -221,14 +272,17 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError if let leleka_memory::Admission::Refuse(refusal) = governor.admit(&shape) { let _ = reply.send(Err(BackendError { code: ErrorCode::ResourceExhausted, - message: format!("{}: retry_after={}: {}", refusal.code, refusal.retry_after_secs, refusal.message), + message: format!( + "{}: retry_after={}: {}", + refusal.code, refusal.retry_after_secs, refusal.message + ), retryable: refusal.status == 503, })); continue; } } - let (sink, stream) = GenerationSink::bounded_channel(QUEUE) - .map_err(|_| unavailable("generation queue unavailable"))?; + let (sink, stream) = + GenerationSink::bounded_channel(QUEUE).map_err(|_| unavailable("generation queue unavailable"))?; if reply.send(Ok(stream)).is_err() { continue; } @@ -244,15 +298,24 @@ pub(in super::super::super) fn run(args: Run<'_, '_>) -> Result<(), BackendError ); continue; }; - let result = generate(owner, &tokenizer, &sink, &cancel, shared, eos, &prompt, &request, options.spec_min_p, &clock); + let result = generate( + owner, + &tokenizer, + &sink, + &cancel, + shared, + eos, + &prompt, + &request, + options.spec_min_p, + &clock, + ); let terminal = match result { Ok((reason, usage)) => GenerationTerminal::Completed { reason, usage }, Err(GenerationFailure::Cancelled) => GenerationTerminal::Cancelled, - Err(GenerationFailure::Backend(error)) => GenerationTerminal::Failed { - code: error.code, - message: error.message, - retryable: false, - }, + Err(GenerationFailure::Backend(error)) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } }; let _ = emit_terminal(&sink, terminal, &clock); publish_prefix_summary(owner, shared); diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs b/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs index be353281..c39842c5 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve/tests.rs @@ -3,7 +3,15 @@ use super::*; fn facts() -> ConfigFacts { - ConfigFacts { kar_inherited: true, kar_staged: false, mtp: true, kar_expert: false, gguf_ple: false, experimental: false, context_tokens: 32768 } + ConfigFacts { + kar_inherited: true, + kar_staged: false, + mtp: true, + kar_expert: false, + gguf_ple: false, + experimental: false, + context_tokens: 32768, + } } #[test] @@ -18,7 +26,9 @@ fn modes_parse_and_print_symmetrically() { #[test] fn auto_takes_the_original_path_only_when_everything_is_sealed_and_fed() { assert_eq!(choose(OriginalServeMode::Auto, &facts(), &[]).unwrap(), OriginalServeChoice::Original); - let OriginalServeChoice::Preview { reason } = choose(OriginalServeMode::Auto, &facts(), &["router", "head"]).unwrap() else { + let OriginalServeChoice::Preview { reason } = + choose(OriginalServeMode::Auto, &facts(), &["router", "head"]).unwrap() + else { panic!("an unsealed build must stay on the preview path"); }; assert!(reason.contains("router") && reason.contains("head"), "{reason}"); @@ -43,7 +53,10 @@ fn auto_takes_the_original_path_only_when_everything_is_sealed_and_fed() { ConfigFacts { context_tokens: 0, ..facts() }, ConfigFacts { context_tokens: 262_145, ..facts() }, ] { - assert!(matches!(choose(OriginalServeMode::Auto, &broken, &[]).unwrap(), OriginalServeChoice::Preview { .. }), "{broken:?}"); + assert!( + matches!(choose(OriginalServeMode::Auto, &broken, &[]).unwrap(), OriginalServeChoice::Preview { .. }), + "{broken:?}" + ); } } @@ -84,11 +97,17 @@ fn options_validation_bounds_the_chunk_and_the_floor() { fn the_conversation_cache_is_on_by_default_and_maps_the_original_flags() { let defaults = OriginalServeOptions::default(); assert_eq!(defaults.conversation().map(|c| c.prompt_cache), Some(6), "--prompt-cache 6 by default"); - assert!(OriginalServeOptions { prompt_cache: 0, ..Default::default() }.conversation().is_none(), "--prompt-cache 0 turns it off"); + assert!( + OriginalServeOptions { prompt_cache: 0, ..Default::default() }.conversation().is_none(), + "--prompt-cache 0 turns it off" + ); let on = OriginalServeOptions { prompt_cache: 6, prompt_cache_every: 0, turn_token: None, ..Default::default() }; assert!(on.validate().is_ok()); let config = on.conversation().expect("--prompt-cache 6 turns the cache on"); - assert_eq!((config.prompt_cache, config.prompt_cache_every, config.prompt_cache_root, config.turn_token), (6, 0, 2048, None)); + assert_eq!( + (config.prompt_cache, config.prompt_cache_every, config.prompt_cache_root, config.turn_token), + (6, 0, 2048, None) + ); assert!(OriginalServeOptions { prompt_cache: 65, ..Default::default() }.validate().is_err()); assert!(OriginalServeOptions { turn_token: Some(248_320), ..Default::default() }.validate().is_err()); } diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs index 25e4ace2..ae51b9cc 100644 --- a/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay.rs @@ -26,17 +26,13 @@ //! (the user's conversation) and stay out of Git. //! //! Run (inside a holder job): ` --ignored --nocapture original_serve_replay_smoke`. +use super::super::qwen_forward::original_serve_stack::dbg_el; use super::*; use crate::qwen_forward::{ original_serve_request::ServeRequest, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, }; use std::env; -use super::super::qwen_forward::original_serve_stack::dbg_el; - -fn required_path(name: &str) -> PathBuf { - env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned input {name}")) -} #[test] #[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; replay of captured agent traffic"] @@ -50,32 +46,52 @@ fn original_serve_replay_smoke() { let mut files: Vec = std::fs::read_dir(&dir) .expect("capture directory unreadable") .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json"))) + .filter(|p| { + p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json")) + }) .collect(); files.sort(); - let files: Vec = files.into_iter().skip(number("LELEKA_REPLAY_FIRST", 0)).take(number("LELEKA_REPLAY_COUNT", usize::MAX)).collect(); + let files: Vec = files + .into_iter() + .skip(number("LELEKA_REPLAY_FIRST", 0)) + .take(number("LELEKA_REPLAY_COUNT", usize::MAX)) + .collect(); assert!(!files.is_empty(), "no captured requests selected"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); // LELEKA_REPLAY_GGUF_PLE=1 (quality / speed study of `kar_source: none`, docs/experiments/kar-off-ab-5090.md): no KAR archive at all, the per-layer // n-gram (PLE) rows are read from the GGUF shard by the native reader (the binding of the `qwen4exp-native-mtp-v1` load). Unset: the inherited KAR descriptor, as always. let gguf_ple = env::var("LELEKA_REPLAY_GGUF_PLE").is_ok_and(|v| v == "1"); let mut binding = if gguf_ple { - ModelBinding::from_artifact_with_pinned_mtp(artifact, &required_path("LELEKA_STRA169_MTP_PACK"), &required_path("LELEKA_STRA169_MTP_STAGING")) - .expect("pinned GGUF-PLE+MTP binding failed") + ModelBinding::from_artifact_with_pinned_mtp( + artifact, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("pinned GGUF-PLE+MTP binding failed") } else { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); // LELEKA_KAR_SPARSE_EXTENTS_SHA256=<64 hex>: the descriptor is a sparse memfd (`leleka seal-exec --sparse-ple`, docs/kar-sparse-memfd.md); it is verified against the // pinned digest of its extents instead of the archive's SHA-256. Unset: the full archive, as always. let inherited = match env::var("LELEKA_KAR_SPARSE_EXTENTS_SHA256") { Ok(text) => { assert_eq!(text.len(), 64, "LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be 64 hex digits"); - let digest: [u8; 32] = std::array::from_fn(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).expect("LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be hex")); - InheritedKarArchive::open_sparse(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"), digest).expect("sparse inherited KAR admission failed") + let digest: [u8; 32] = std::array::from_fn(|i| { + u8::from_str_radix(&text[2 * i..2 * i + 2], 16) + .expect("LELEKA_KAR_SPARSE_EXTENTS_SHA256 must be hex") + }); + InheritedKarArchive::open_sparse(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE"), digest) + .expect("sparse inherited KAR admission failed") } - Err(_) => InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"), + Err(_) => InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"), }; ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, @@ -91,7 +107,11 @@ fn original_serve_replay_smoke() { } let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30).expect("bounded Context unavailable")); + let context = Rc::new( + device + .create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30) + .expect("bounded Context unavailable"), + ); // arms: `label=mode,...` with mode conv (the conversation cache) | off | prompt | reply (the prefix cache with that tail mode); each arm is a // fresh stack over the same loaded model. Default: one arm, the tail mode of `LELEKA_REPLAY_PREFIX_TAIL`. let arms: Vec<(String, String)> = match env::var("LELEKA_REPLAY_ARMS") { @@ -102,201 +122,351 @@ fn original_serve_replay_smoke() { (label.to_owned(), mode.to_owned()) }) .collect(), - Err(_) => vec![("replay".to_owned(), env::var("LELEKA_REPLAY_PREFIX_TAIL").unwrap_or_else(|_| "off".to_owned()))], + Err(_) => { + vec![("replay".to_owned(), env::var("LELEKA_REPLAY_PREFIX_TAIL").unwrap_or_else(|_| "off".to_owned()))] + } }; // LELEKA_REPLAY_FORCE=1: every request decodes along its RECORDED tokens (teacher forcing, `quality_force`), so all arms // read the same path and, with LELEKA_TRACE_LOGPROBS=16 and LELEKA_BRINGUP_TRACE, print the top-16 rows that // `scripts/quality/q_tail_gate.py` compares (the arm index plays the corpus pass). let force = env::var_os("LELEKA_REPLAY_FORCE").is_some(); for (arm_index, (label, arm)) in arms.iter().enumerate() { - // the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, grid = chunk) or `reply@8192/2048` - let mut down_override: i8 = -1; - let (mut sm120_attn, mut sm120_gu, mut sm120_side): (i8, i8, i8) = (-1, -1, -1); - let mut tail_flag: Option = None; - let (mut gdn_flag, mut topk_flag, mut cluster_flag, mut nostore_flag, mut sized_flag, mut qpf_flag, mut gpool_flag, mut mspan_flag): (i8, i8, i8, i8, i8, i8, i8, i8) = (-1, -1, -1, -1, -1, -1, -1, -1); - let (arm_mode, arm_capacity, arm_block, arm_tiers): (String, usize, usize, Option) = match arm.split_once('@') { - Some((mode, shape)) => { - // flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: the stack's), `w8` (the previous - // 8-row x all-tokens hyper-connection down projection of the chain kernels instead of the tiled one) - let (shape, flags) = shape.split_once('!').map_or((shape, ""), |(s, f)| (s, f)); - let tiers = if flags.split('!').any(|f| f == "notiers") { Some(false) } else if flags.split('!').any(|f| f == "tiers") { Some(true) } else { None }; - down_override = if flags.split('!').any(|f| f == "w8") { 0 } else { -1 }; - // `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = off); without it the environment decides - tail_flag = flags.split('!').find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::().expect("arm flag !tailN")); - // docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the three-value-heads kernel, the two-barrier kernel, - // the sealed Original one), `wide` / `fast` (the prompt top-k), `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster) - let has = |name: &str| flags.split('!').any(|f| f == name); - gdn_flag = if has("kh") { 1 } else if has("rec") { 2 } else if has("orig") { 0 } else { -1 }; - topk_flag = if has("wide") { 1 } else if has("fast") { 0 } else { -1 }; - cluster_flag = if has("cluster") { 1 } else if has("nocluster") { 0 } else { -1 }; - nostore_flag = if has("nostore") { 1 } else if has("store") { 0 } else { -1 }; - sized_flag = if has("sized") { 1 } else if has("uniform") { 0 } else { -1 }; - qpf_flag = if has("qpf") { 1 } else if has("noqpf") { 0 } else { -1 }; - gpool_flag = if has("gpool") { 1 } else if has("nogpool") { 0 } else { -1 }; - mspan_flag = if has("mspan") { 1 } else if has("nomspan") { 0 } else { -1 }; - // claude/decode-sm120-switches: `attn` / `noattn` (ATTN_DAILY decode attention), `gus` / `nogus` (GU_SWIGLU fused expert gate/up); without a flag the environment and the card decide - sm120_attn = if has("attn") { 1 } else if has("noattn") { 0 } else { -1 }; - sm120_gu = if has("gus") { 1 } else if has("nogus") { 0 } else { -1 }; - sm120_side = if has("side") { 1 } else if has("noside") { 0 } else { -1 }; - let (cap, block) = shape.split_once('/').unwrap_or((shape, "0")); - (mode.to_owned(), cap.parse::().expect("arm chunk: mode@CAP[/BLOCK]"), block.parse::().expect("arm grid: mode@CAP[/BLOCK]"), tiers) - } - None => (arm.clone(), number("LELEKA_REPLAY_CAPACITY", 2048), 0, None), - }; - let arm = &arm_mode; - leleka_cuda_driver::set_chain_down_override(down_override); - leleka_cuda_driver::set_sm120_overrides(sm120_attn, sm120_gu, sm120_side); - leleka_cuda_driver::set_prefill_gdn_override(gdn_flag); - leleka_cuda_driver::set_qsa_topk_override(topk_flag); - leleka_cuda_driver::set_qsa_cluster_override(cluster_flag); - leleka_cuda_driver::set_prefill_gdn_nostore_override(nostore_flag); - crate::qwen_forward::original_cache_startup::set_sized_override(sized_flag); - leleka_cuda_driver::set_qsa_prefetch_override(qpf_flag); - crate::qwen_forward::gdn::set_pool_override(gpool_flag); - crate::qwen_forward::moe_weight_cache::set_span_cache_override(mspan_flag); - crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail_flag); - eprintln!("REPLAY-ARM start label={label} mode={arm} capacity={arm_capacity} block={arm_block} tiers={}", arm_tiers.map_or("default", |on| if on { "on" } else { "off" })); - let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); - config.capacity = arm_capacity; - if let Some(on) = arm_tiers { - config.loan_tiers = on; - } - // the Original's draft vocabulary (the MTP pack directory); unset = the full head, as the daemon did without --mtp-rt-dir - config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() - .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - if let (Ok(mib), true) = (env::var("LELEKA_REPLAY_PREFIX_MIB"), arm != "conv") { - config.prefix = Some(PrefixConfig { - tail: match Ok::<&str, ()>(arm.as_str()) { - Ok("prompt") => crate::qwen_forward::original_serve_stack::TailMode::Prompt, - Ok("reply") => crate::qwen_forward::original_serve_stack::TailMode::Reply, - Ok("off") | Err(_) => crate::qwen_forward::original_serve_stack::TailMode::Off, - Ok(other) => panic!("replay arm mode: conv | off | prompt | reply, not {other}"), - }, - budget: if mib == "auto" { PrefixBudget::Auto } else { PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) }, - block_tokens: arm_block, - ..PrefixConfig::auto() - }); - } - let min_p: f32 = env::var("LELEKA_REPLAY_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_REPLAY_SPEC_MIN_P")).unwrap_or(0.0); - eprintln!( - "REPLAY config: {} requests from {:?}, capacity {}, spec_min_p {min_p}, prefix cache {}, tier {:?}", - files.len(), dir, config.capacity, config.prefix.is_some(), config.expert_tier - ); - let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { - Ok(stack) => stack, - Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), - }; - let spec_arms = stack.spec_arms(); - let reps = number("LELEKA_REPLAY_REPS", 1).max(1); - let force = env::var("LELEKA_REPLAY_FORCE").is_ok_and(|v| v == "1"); - // (label, arm) of every pass: a warm-up with arm 0, then reps x arms rotated per repetition - let mut passes: Vec<(String, Option)> = Vec::new(); - if spec_arms.is_empty() { - passes.extend((0..reps).map(|r| (format!("p{r}"), None))); - } else { - passes.push(("warm".to_owned(), Some(spec_arms[0].clone()))); - for r in 0..reps { - for q in 0..spec_arms.len() { - passes.push((format!("r{r}"), Some(spec_arms[(q + r) % spec_arms.len()].clone()))); - } - } - } - for (pass_no, (pass_label, arm)) in passes.iter().enumerate() { - if let Some(arm) = arm { - assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}"); - // `+tailN` in an arm label (`adaptive@0+tail7`): the experimental route tail skip of this pass (docs/upstream-port-plan.md 3.1); without it the environment decides - if spec_arms.iter().any(|a| a.contains("+tail")) { - let tail = arm.split('+').skip(1).find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::().expect("arm flag +tailN")); - crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail); - } - } - let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = (0usize, 0f64, 0usize, 0usize, 0f64); - for (n, file) in files.iter().enumerate() { - let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON"); - let ids = |key: &str| -> Vec { doc[key].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect() }; - let (prompt, recorded) = (ids("prompt_ids"), ids("generated_ids")); - let max_new = recorded.len().clamp(1, doc["max_new"].as_u64().unwrap_or(4096) as usize).min(number("LELEKA_REPLAY_MAX_NEW", usize::MAX)); - let greedy = doc["temperature_milli"].as_u64() == Some(0) - && doc["repetition_penalty_micro"].as_u64().is_none_or(|v| v == 1_000_000 || v == 0); - if !greedy { - eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily"); - } - crate::qwen_forward::quality_force::set(force.then(|| prompt.iter().copied().chain(recorded.iter().copied()).collect())); - if force { - eprintln!("DBG corpus {n} pass={arm_index} begin forced=true"); - } - let started = std::time::Instant::now(); - let mut first: Option = None; - let mut out: Vec = Vec::new(); - let served = stack.serve( - &ServeRequest::new(prompt.clone(), max_new, None, 7, stack.spec_arm_min_p().unwrap_or(min_p), vec![eos as i32]), - &mut |round| { - if first.is_none() { - first = Some(started.elapsed()); + // the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, grid = chunk) or `reply@8192/2048` + let mut down_override: i8 = -1; + let (mut sm120_attn, mut sm120_gu, mut sm120_side): (i8, i8, i8) = (-1, -1, -1); + let mut tail_flag: Option = None; + let ( + mut gdn_flag, + mut topk_flag, + mut cluster_flag, + mut nostore_flag, + mut sized_flag, + mut qpf_flag, + mut gpool_flag, + mut mspan_flag, + ): (i8, i8, i8, i8, i8, i8, i8, i8) = (-1, -1, -1, -1, -1, -1, -1, -1); + let (arm_mode, arm_capacity, arm_block, arm_tiers): (String, usize, usize, Option) = + match arm.split_once('@') { + Some((mode, shape)) => { + // flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: the stack's), `w8` (the previous + // 8-row x all-tokens hyper-connection down projection of the chain kernels instead of the tiled one) + let (shape, flags) = shape.split_once('!').map_or((shape, ""), |(s, f)| (s, f)); + let tiers = if flags.split('!').any(|f| f == "notiers") { + Some(false) + } else if flags.split('!').any(|f| f == "tiers") { + Some(true) + } else { + None + }; + down_override = if flags.split('!').any(|f| f == "w8") { 0 } else { -1 }; + // `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = off); without it the environment decides + tail_flag = flags + .split('!') + .find_map(|f| f.strip_prefix("tail")) + .map(|n| n.parse::().expect("arm flag !tailN")); + // docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the three-value-heads kernel, the two-barrier kernel, + // the sealed Original one), `wide` / `fast` (the prompt top-k), `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster) + let has = |name: &str| flags.split('!').any(|f| f == name); + gdn_flag = if has("kh") { + 1 + } else if has("rec") { + 2 + } else if has("orig") { + 0 + } else { + -1 + }; + topk_flag = if has("wide") { + 1 + } else if has("fast") { + 0 + } else { + -1 + }; + cluster_flag = if has("cluster") { + 1 + } else if has("nocluster") { + 0 + } else { + -1 + }; + nostore_flag = if has("nostore") { + 1 + } else if has("store") { + 0 + } else { + -1 + }; + sized_flag = if has("sized") { + 1 + } else if has("uniform") { + 0 + } else { + -1 + }; + qpf_flag = if has("qpf") { + 1 + } else if has("noqpf") { + 0 + } else { + -1 + }; + gpool_flag = if has("gpool") { + 1 + } else if has("nogpool") { + 0 + } else { + -1 + }; + mspan_flag = if has("mspan") { + 1 + } else if has("nomspan") { + 0 + } else { + -1 + }; + // claude/decode-sm120-switches: `attn` / `noattn` (ATTN_DAILY decode attention), `gus` / `nogus` (GU_SWIGLU fused expert gate/up); without a flag the environment and the card decide + sm120_attn = if has("attn") { + 1 + } else if has("noattn") { + 0 + } else { + -1 + }; + sm120_gu = if has("gus") { + 1 + } else if has("nogus") { + 0 + } else { + -1 + }; + sm120_side = if has("side") { + 1 + } else if has("noside") { + 0 + } else { + -1 + }; + let (cap, block) = shape.split_once('/').unwrap_or((shape, "0")); + ( + mode.to_owned(), + cap.parse::().expect("arm chunk: mode@CAP[/BLOCK]"), + block.parse::().expect("arm grid: mode@CAP[/BLOCK]"), + tiers, + ) } - out.extend_from_slice(round); - Ok(()) - }, - &mut || false, + None => (arm.clone(), number("LELEKA_REPLAY_CAPACITY", 2048), 0, None), + }; + let arm = &arm_mode; + leleka_cuda_driver::set_chain_down_override(down_override); + leleka_cuda_driver::set_sm120_overrides(sm120_attn, sm120_gu, sm120_side); + leleka_cuda_driver::set_prefill_gdn_override(gdn_flag); + leleka_cuda_driver::set_qsa_topk_override(topk_flag); + leleka_cuda_driver::set_qsa_cluster_override(cluster_flag); + leleka_cuda_driver::set_prefill_gdn_nostore_override(nostore_flag); + crate::qwen_forward::original_cache_startup::set_sized_override(sized_flag); + leleka_cuda_driver::set_qsa_prefetch_override(qpf_flag); + crate::qwen_forward::gdn::set_pool_override(gpool_flag); + crate::qwen_forward::moe_weight_cache::set_span_cache_override(mspan_flag); + crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail_flag); + eprintln!( + "REPLAY-ARM start label={label} mode={arm} capacity={arm_capacity} block={arm_block} tiers={}", + arm_tiers.map_or("default", |on| if on { "on" } else { "off" }) ); - let total = started.elapsed(); - if force { - crate::qwen_forward::quality_force::set(None); + let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); + config.capacity = arm_capacity; + if let Some(on) = arm_tiers { + config.loan_tiers = on; } - match served { - Ok(outcome) => { - let ttft = first.unwrap_or(total); - let decode = (total - ttft).as_secs_f64() * 1e3; - let agree = out.iter().zip(&recorded).take_while(|(a, b)| a == b).count(); - if let Some(path) = env::var_os("LELEKA_REPLAY_OUT") { - use std::io::Write; - let line = format!("REPLAY-OUT arm={label} #{n} {}\n", out.iter().map(|t| t.to_string()).collect::>().join(",")); - let _ = std::fs::OpenOptions::new().create(true).append(true).open(path).and_then(|mut f| f.write_all(line.as_bytes())); - } - let reused = stack.reused_tokens(); - let (p_ms, d_ms) = stack.last_timing(); - let m = stack.ttft_marks(); - eprintln!( - "REPLAY-MARKS #{n} prompt={} reprefill={} ttft_ms={:.1} resumed={:.1} prefilled={:.1} assembled={:.1} first_round={:.1} (stages: resume {:.1}, prefill {:.1}, assemble {:.1}, first round {:.1})", - prompt.len(), prompt.len().saturating_sub(reused), ttft.as_secs_f64() * 1e3, m[0], m[1], m[2], m[3], m[0], m[1] - m[0], m[2] - m[1], m[3] - m[2] - ); - eprintln!( - "REPLAY #{n} pass={pass_no} {pass_label} arm={} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}", - stack.spec_arm(), - file.file_name().and_then(|f| f.to_str()).unwrap_or("?"), - prompt.len(), - prompt.len().saturating_sub(reused), - ttft.as_secs_f64() * 1e3, - out.len(), - outcome.rounds, - out.len() as f64 / outcome.rounds.max(1) as f64, - if decode > 0.0 { out.len().saturating_sub(1) as f64 * 1e3 / decode } else { 0.0 }, - recorded.len() - ); - tokens += out.len().saturating_sub(1); - decode_ms += decode; - rounds_total += outcome.rounds; - prefill_tokens += prompt.len().saturating_sub(reused); - prefill_ms += ttft.as_secs_f64() * 1e3; - if let Some(stats) = stack.expert_tier_stats() { - eprintln!("REPLAY #{n} {}", stats.describe()); + // the Original's draft vocabulary (the MTP pack directory); unset = the full head, as the daemon did without --mtp-rt-dir + config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + if let (Ok(mib), true) = (env::var("LELEKA_REPLAY_PREFIX_MIB"), arm != "conv") { + config.prefix = Some(PrefixConfig { + tail: match Ok::<&str, ()>(arm.as_str()) { + Ok("prompt") => crate::qwen_forward::original_serve_stack::TailMode::Prompt, + Ok("reply") => crate::qwen_forward::original_serve_stack::TailMode::Reply, + Ok("off") | Err(_) => crate::qwen_forward::original_serve_stack::TailMode::Off, + Ok(other) => panic!("replay arm mode: conv | off | prompt | reply, not {other}"), + }, + budget: if mib == "auto" { + PrefixBudget::Auto + } else { + PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) + }, + block_tokens: arm_block, + ..PrefixConfig::auto() + }); + } + let min_p: f32 = env::var("LELEKA_REPLAY_SPEC_MIN_P") + .ok() + .map(|v| v.parse().expect("LELEKA_REPLAY_SPEC_MIN_P")) + .unwrap_or(0.0); + eprintln!( + "REPLAY config: {} requests from {:?}, capacity {}, spec_min_p {min_p}, prefix cache {}, tier {:?}", + files.len(), + dir, + config.capacity, + config.prefix.is_some(), + config.expert_tier + ); + let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + let spec_arms = stack.spec_arms(); + let reps = number("LELEKA_REPLAY_REPS", 1).max(1); + let force = env::var("LELEKA_REPLAY_FORCE").is_ok_and(|v| v == "1"); + // (label, arm) of every pass: a warm-up with arm 0, then reps x arms rotated per repetition + let mut passes: Vec<(String, Option)> = Vec::new(); + if spec_arms.is_empty() { + passes.extend((0..reps).map(|r| (format!("p{r}"), None))); + } else { + passes.push(("warm".to_owned(), Some(spec_arms[0].clone()))); + for r in 0..reps { + for q in 0..spec_arms.len() { + passes.push((format!("r{r}"), Some(spec_arms[(q + r) % spec_arms.len()].clone()))); } } - Err(e) => eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()), } - } - crate::qwen_forward::quality_force::set(None); - eprintln!( - "REPLAY PASS {pass_no} {pass_label} arm={} requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}", - stack.spec_arm(), - files.len(), - if decode_ms > 0.0 { tokens as f64 * 1e3 / decode_ms } else { 0.0 }, - decode_ms / 1e3, - prefill_ms / 1e3 - ); - } - stack.close().expect("stack cleanup failed"); + for (pass_no, (pass_label, arm)) in passes.iter().enumerate() { + if let Some(arm) = arm { + assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}"); + // `+tailN` in an arm label (`adaptive@0+tail7`): the experimental route tail skip of this pass (docs/upstream-port-plan.md 3.1); without it the environment decides + if spec_arms.iter().any(|a| a.contains("+tail")) { + let tail = arm + .split('+') + .skip(1) + .find_map(|f| f.strip_prefix("tail")) + .map(|n| n.parse::().expect("arm flag +tailN")); + crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail); + } + } + let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = + (0usize, 0f64, 0usize, 0usize, 0f64); + for (n, file) in files.iter().enumerate() { + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")) + .expect("capture is not JSON"); + let ids = |key: &str| -> Vec { + doc[key].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect() + }; + let (prompt, recorded) = (ids("prompt_ids"), ids("generated_ids")); + let max_new = recorded + .len() + .clamp(1, doc["max_new"].as_u64().unwrap_or(4096) as usize) + .min(number("LELEKA_REPLAY_MAX_NEW", usize::MAX)); + let greedy = doc["temperature_milli"].as_u64() == Some(0) + && doc["repetition_penalty_micro"].as_u64().is_none_or(|v| v == 1_000_000 || v == 0); + if !greedy { + eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily"); + } + crate::qwen_forward::quality_force::set( + force.then(|| prompt.iter().copied().chain(recorded.iter().copied()).collect()), + ); + if force { + eprintln!("DBG corpus {n} pass={arm_index} begin forced=true"); + } + let started = std::time::Instant::now(); + let mut first: Option = None; + let mut out: Vec = Vec::new(); + let served = stack.serve( + &ServeRequest::new( + prompt.clone(), + max_new, + None, + 7, + stack.spec_arm_min_p().unwrap_or(min_p), + vec![eos as i32], + ), + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); + let total = started.elapsed(); + if force { + crate::qwen_forward::quality_force::set(None); + } + match served { + Ok(outcome) => { + let ttft = first.unwrap_or(total); + let decode = (total - ttft).as_secs_f64() * 1e3; + let agree = out.iter().zip(&recorded).take_while(|(a, b)| a == b).count(); + if let Some(path) = env::var_os("LELEKA_REPLAY_OUT") { + use std::io::Write; + let line = format!( + "REPLAY-OUT arm={label} #{n} {}\n", + out.iter().map(|t| t.to_string()).collect::>().join(",") + ); + let _ = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .and_then(|mut f| f.write_all(line.as_bytes())); + } + let reused = stack.reused_tokens(); + let (p_ms, d_ms) = stack.last_timing(); + let m = stack.ttft_marks(); + eprintln!( + "REPLAY-MARKS #{n} prompt={} reprefill={} ttft_ms={:.1} resumed={:.1} prefilled={:.1} assembled={:.1} first_round={:.1} (stages: resume {:.1}, prefill {:.1}, assemble {:.1}, first round {:.1})", + prompt.len(), + prompt.len().saturating_sub(reused), + ttft.as_secs_f64() * 1e3, + m[0], + m[1], + m[2], + m[3], + m[0], + m[1] - m[0], + m[2] - m[1], + m[3] - m[2] + ); + eprintln!( + "REPLAY #{n} pass={pass_no} {pass_label} arm={} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}", + stack.spec_arm(), + file.file_name().and_then(|f| f.to_str()).unwrap_or("?"), + prompt.len(), + prompt.len().saturating_sub(reused), + ttft.as_secs_f64() * 1e3, + out.len(), + outcome.rounds, + out.len() as f64 / outcome.rounds.max(1) as f64, + if decode > 0.0 { out.len().saturating_sub(1) as f64 * 1e3 / decode } else { 0.0 }, + recorded.len() + ); + tokens += out.len().saturating_sub(1); + decode_ms += decode; + rounds_total += outcome.rounds; + prefill_tokens += prompt.len().saturating_sub(reused); + prefill_ms += ttft.as_secs_f64() * 1e3; + if let Some(stats) = stack.expert_tier_stats() { + eprintln!("REPLAY #{n} {}", stats.describe()); + } + } + Err(e) => eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()), + } + } + crate::qwen_forward::quality_force::set(None); + eprintln!( + "REPLAY PASS {pass_no} {pass_label} arm={} requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}", + stack.spec_arm(), + files.len(), + if decode_ms > 0.0 { tokens as f64 * 1e3 / decode_ms } else { 0.0 }, + decode_ms / 1e3, + prefill_ms / 1e3 + ); + } + stack.close().expect("stack cleanup failed"); } Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); } + +#[path = "backend_original_serve_replay/required_path_fn.rs"] +mod required_path_fn; +#[allow(unused_imports)] +use required_path_fn::required_path; diff --git a/crates/engine-qwen35-cuda/src/backend_original_serve_replay/required_path_fn.rs b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/required_path_fn.rs new file mode 100644 index 00000000..2b038d62 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/backend_original_serve_replay/required_path_fn.rs @@ -0,0 +1,8 @@ +//! Moved out of the parent module by STRA-338: fn required_path. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn required_path(name: &str) -> PathBuf { + env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned input {name}")) +} diff --git a/crates/engine-qwen35-cuda/src/conversation/memory.rs b/crates/engine-qwen35-cuda/src/conversation/memory.rs index c237a7e1..1a87b9a3 100644 --- a/crates/engine-qwen35-cuda/src/conversation/memory.rs +++ b/crates/engine-qwen35-cuda/src/conversation/memory.rs @@ -73,10 +73,7 @@ mod tests { #[test] fn only_mem_available_is_counted() { - assert_eq!( - parse("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n"), - Some(12345 * 1024) - ); + assert_eq!(parse("MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n"), Some(12345 * 1024)); assert_eq!(parse("MemAvailable: 0 kB"), Some(0)); assert_eq!(parse("MemAvailable:\t7\tkB\r\n"), Some(7 * 1024)); // A different key sharing the prefix is not MemAvailable. @@ -98,35 +95,14 @@ mod tests { #[test] fn admission_arithmetic_cannot_wrap() { - assert!( - !memory_admit(None, 0, 0), - "unknown fails closed even with zero floor" - ); - assert!( - memory_admit(Some(100), 40, 60), - "exact allocation plus floor fits" - ); - assert!( - !memory_admit(Some(99), 40, 60), - "one byte below required memory rejected" - ); - assert!( - !memory_admit(Some(59), 0, 60), - "floor subtraction cannot underflow" - ); + assert!(!memory_admit(None, 0, 0), "unknown fails closed even with zero floor"); + assert!(memory_admit(Some(100), 40, 60), "exact allocation plus floor fits"); + assert!(!memory_admit(Some(99), 40, 60), "one byte below required memory rejected"); + assert!(!memory_admit(Some(59), 0, 60), "floor subtraction cannot underflow"); assert!(memory_admit(Some(60), 0, 60), "post-capture floor check"); - assert!( - !memory_admit(Some(100), u64::MAX, 1), - "allocation arithmetic cannot overflow" - ); - assert!( - memory_admit(Some(u64::MAX), u64::MAX, 0), - "maximal exact bound" - ); - assert!( - !memory_admit(Some(u64::MAX), u64::MAX, 1), - "maximal sum overflow rejected" - ); + assert!(!memory_admit(Some(100), u64::MAX, 1), "allocation arithmetic cannot overflow"); + assert!(memory_admit(Some(u64::MAX), u64::MAX, 0), "maximal exact bound"); + assert!(!memory_admit(Some(u64::MAX), u64::MAX, 1), "maximal sum overflow rejected"); } #[test] diff --git a/crates/engine-qwen35-cuda/src/conversation/mod.rs b/crates/engine-qwen35-cuda/src/conversation/mod.rs index 7f2c4ba1..d87df263 100644 --- a/crates/engine-qwen35-cuda/src/conversation/mod.rs +++ b/crates/engine-qwen35-cuda/src/conversation/mod.rs @@ -4,9 +4,11 @@ //! The pure policy modules live in `leleka-engine-core::conversation` and are re-exported here under their old paths; //! the CUDA-owner bindings live next to the session owners. -pub use leleka_engine_core::conversation::{binding, buffer, cache, checked, kv, manager, model, retention, snapshot, state}; #[cfg(test)] pub(crate) use leleka_engine_core::conversation::testing; +pub use leleka_engine_core::conversation::{ + binding, buffer, cache, checked, kv, manager, model, retention, snapshot, state, +}; pub mod memory; #[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] diff --git a/crates/engine-qwen35-cuda/src/conversation/original.rs b/crates/engine-qwen35-cuda/src/conversation/original.rs index ff90a893..6f772a49 100644 --- a/crates/engine-qwen35-cuda/src/conversation/original.rs +++ b/crates/engine-qwen35-cuda/src/conversation/original.rs @@ -8,12 +8,12 @@ use super::binding::SessionDevice; use super::model::{ - HostPools, IdxKind, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, SessionSpec, - StateMemory, StateRegion, StreamMap, + HostPools, IdxKind, KvLayer, KvPool, ModelGeometry, QsaDesc, SessionShape, SessionSpec, StateMemory, StateRegion, + StreamMap, }; use leleka_cuda_driver::{ - OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, - OriginalSessionBytes, OriginalSessionControl, OriginalSessionFacts, + OriginalIdxKind, OriginalKvLayer, OriginalKvPool, OriginalQsaFacts, OriginalRegion, OriginalSessionBytes, + OriginalSessionControl, OriginalSessionFacts, }; fn layer(l: KvLayer) -> OriginalKvLayer { @@ -45,15 +45,9 @@ fn region(r: StateRegion) -> OriginalRegion { IdxKind::BlockPos => OriginalIdxKind::BlockPos, }, }, - StateRegion::Kv { - layer: l, - pool: p, - resident, - } => OriginalRegion::Kv { - layer: layer(l), - pool: pool(p), - resident, - }, + StateRegion::Kv { layer: l, pool: p, resident } => { + OriginalRegion::Kv { layer: layer(l), pool: pool(p), resident } + } } } @@ -123,16 +117,9 @@ pub fn qsa_desc(q: &OriginalQsaFacts, max_cells: usize) -> QsaDesc { map: StreamMap { n_blocks: q.pages as i64, n_slots: q.slots as i64, - complete: [ - "slot_block", - "slot_stamp", - "slot_ref", - "miss_block", - "miss_slot", - "ctl", - ] - .iter() - .all(|name| q.has(name)), + complete: ["slot_block", "slot_stamp", "slot_ref", "miss_block", "miss_slot", "ctl"] + .iter() + .all(|name| q.has(name)), }, idx_pooled_rows: q.pooled_rows as i64, idx_tail: q.has("idx_tail"), @@ -195,17 +182,8 @@ impl StateMemory for OriginalDevice { } } - fn restore_ring( - &mut self, - l: KvLayer, - format: i32, - begin: i64, - end: i64, - slots: i64, - ) -> Result<(), String> { - self.session - .restore_ring(layer(l), format, begin, end, slots) - .map_err(text) + fn restore_ring(&mut self, l: KvLayer, format: i32, begin: i64, end: i64, slots: i64) -> Result<(), String> { + self.session.restore_ring(layer(l), format, begin, end, slots).map_err(text) } } @@ -302,25 +280,14 @@ mod tests { fn the_original_session_facts_are_a_valid_snapshot_target() { let f = facts(false); let g = model_geometry(&f); - assert_eq!( - g, - ModelGeometry::default(), - "the pinned geometry round-trips through the layout facts" - ); + assert_eq!(g, ModelGeometry::default(), "the pinned geometry round-trips through the layout facts"); let spec = session_spec(&f); // The compiled C++ sizes (golden/state_golden.json, "original whole model"). let z = session_sizes(&g, &spec).unwrap(); - assert_eq!( - (z.gdn, z.ple, z.tail, z.dead, z.block_pos), - (117_669_888, 368_640, 1536, 512, 4) - ); + assert_eq!((z.gdn, z.ple, z.tail, z.dead, z.block_pos), (117_669_888, 368_640, 1536, 512, 4)); assert_eq!(z, state_sizes(&g).unwrap()); - checkpoint_targets(&spec, &g, 100) - .expect("a session with every running-state buffer takes checkpoints"); - assert!( - checkpoint_targets(&spec, &g, 5000).is_err(), - "more tokens than cells" - ); + checkpoint_targets(&spec, &g, 100).expect("a session with every running-state buffer takes checkpoints"); + assert!(checkpoint_targets(&spec, &g, 5000).is_err(), "more tokens than cells"); } #[test] @@ -345,11 +312,7 @@ mod tests { f.qsa.truncate(1); f.gdn_state_bytes = 117_669_888 / 12; let spec = session_spec(&f); - assert_eq!( - spec.qsa.len(), - 2, - "one placeholder below the first owned ordinal" - ); + assert_eq!(spec.qsa.len(), 2, "one placeholder below the first owned ordinal"); assert!(spec.owned(0).is_some() && spec.owned(1).is_none()); let g = model_geometry(&f); assert_eq!(session_sizes(&g, &spec).unwrap().gdn, 117_669_888 / 36 * 3); diff --git a/crates/engine-qwen35-cuda/src/conversation/resident.rs b/crates/engine-qwen35-cuda/src/conversation/resident.rs index 432f4635..77a1336c 100644 --- a/crates/engine-qwen35-cuda/src/conversation/resident.rs +++ b/crates/engine-qwen35-cuda/src/conversation/resident.rs @@ -42,12 +42,7 @@ pub struct ResidentPolicy { impl ResidentPolicy { /// Parking off: exactly one live continuation, as before. pub const fn disabled() -> Self { - Self { - budget_bytes: 0, - slots: 4, - fixed_bytes: 118_038_528, - bytes_per_token: 24_576, - } + Self { budget_bytes: 0, slots: 4, fixed_bytes: 118_038_528, bytes_per_token: 24_576 } } pub fn enabled(&self) -> bool { @@ -56,8 +51,7 @@ impl ResidentPolicy { /// Accounted bytes of a session that committed `tokens` tokens. pub fn estimate(&self, tokens: usize) -> usize { - self.fixed_bytes - .saturating_add(tokens.saturating_mul(self.bytes_per_token)) + self.fixed_bytes.saturating_add(tokens.saturating_mul(self.bytes_per_token)) } /// Strict parse of the operator knobs (`LELEKA_CONVERSATION_CACHE_MIB`, @@ -68,9 +62,7 @@ impl ResidentPolicy { if text.is_empty() || text.len() > 12 || !text.bytes().all(|b| b.is_ascii_digit()) { return Err("invalid conversation cache setting"); } - let value: u64 = text - .parse() - .map_err(|_| "invalid conversation cache setting")?; + let value: u64 = text.parse().map_err(|_| "invalid conversation cache setting")?; if value > max { return Err("conversation cache setting out of range"); } @@ -78,8 +70,8 @@ impl ResidentPolicy { } let mut policy = Self::disabled(); if let Some(text) = mib { - policy.budget_bytes = usize::try_from(number(text, 1 << 22)? << 20) - .map_err(|_| "conversation cache too large")?; + policy.budget_bytes = + usize::try_from(number(text, 1 << 22)? << 20).map_err(|_| "conversation cache too large")?; } if let Some(text) = slots { policy.slots = number(text, 64)? as usize; @@ -96,15 +88,9 @@ impl ResidentPolicy { pub(crate) fn from_source(env: &impl EnvSource) -> Result { let read = |name: &str| match env.get_os(name) { None => Ok(None), - Some(value) => value - .into_string() - .map(Some) - .map_err(|_| "invalid conversation cache setting"), + Some(value) => value.into_string().map(Some).map_err(|_| "invalid conversation cache setting"), }; - let (mib, slots) = ( - read("LELEKA_CONVERSATION_CACHE_MIB")?, - read("LELEKA_CONVERSATION_CACHE_SLOTS")?, - ); + let (mib, slots) = (read("LELEKA_CONVERSATION_CACHE_MIB")?, read("LELEKA_CONVERSATION_CACHE_SLOTS")?); Self::from_values(mib.as_deref(), slots.as_deref()) } } @@ -163,12 +149,7 @@ fn as_ids(tokens: &[u32]) -> Option> { impl ResidentConversations { pub fn new(policy: ResidentPolicy) -> Self { let cache = ConversationCache::new(policy.budget_bytes, policy.slots); - Self { - policy, - live: None, - cache, - events: Vec::new(), - } + Self { policy, live: None, cache, events: Vec::new() } } pub fn policy(&self) -> ResidentPolicy { @@ -203,10 +184,8 @@ impl ResidentConversations { // No checkpoint chain here, so nothing is superseded: the explicit // reservation is `make_room`'s oldest-first eviction. if !self.cache.make_room(live.bytes, held) { - self.events.push(format!( - "conversation cache: skip parking ({} MiB exceeds available budget)", - live.bytes >> 20 - )); + self.events + .push(format!("conversation cache: skip parking ({} MiB exceeds available budget)", live.bytes >> 20)); return; } let tokens = live.ids.len(); @@ -229,24 +208,17 @@ impl ResidentConversations { /// candidate it rejects is dropped. The live candidate may reuse a prompt /// equal to its committed tokens; parked candidates keep the Original's /// rule that the last prompt token always starts the next window. - pub fn take_for( - &mut self, - prompt: &[u32], - mut usable: impl FnMut(&S) -> bool, - ) -> Option> { + pub fn take_for(&mut self, prompt: &[u32], mut usable: impl FnMut(&S) -> bool) -> Option> { let Some(ids) = as_ids(prompt) else { self.live = None; return None; }; // Strict equality of every committed token; length may equal the prompt. - let live_ok = self.live.as_ref().is_some_and(|l| { - !l.ids.is_empty() && l.ids.len() <= ids.len() && ids[..l.ids.len()] == l.ids[..] - }); - let mut live_len = if live_ok { - self.live.as_ref().map_or(0, |l| l.ids.len()) - } else { - 0 - }; + let live_ok = self + .live + .as_ref() + .is_some_and(|l| !l.ids.is_empty() && l.ids.len() <= ids.len() && ids[..l.ids.len()] == l.ids[..]); + let mut live_len = if live_ok { self.live.as_ref().map_or(0, |l| l.ids.len()) } else { 0 }; if live_ok && let Some(l) = &self.live && !usable(&l.session) @@ -255,16 +227,11 @@ impl ResidentConversations { live_len = 0; } let best = self.cache.best(prompt, &[], true); - let mut incoming = if best.tokens as usize > live_len { - self.cache.take(best.index) - } else { - None - }; + let mut incoming = if best.tokens as usize > live_len { self.cache.take(best.index) } else { None }; if let Some(p) = &incoming && !usable(&p.session) { - self.events - .push("conversation cache: discard unusable parked session".into()); + self.events.push("conversation cache: discard unusable parked session".into()); incoming = None; } let swap = incoming.is_some() || live_len == 0; @@ -279,19 +246,11 @@ impl ResidentConversations { self.cache.size(), self.cache.bytes() )); - return Some(Resumed { - tokens: p.ids.len(), - session: p.session, - source: ResumeSource::Parked, - }); + return Some(Resumed { tokens: p.ids.len(), session: p.session, source: ResumeSource::Parked }); } if live_len > 0 { let l = self.live.take()?; - return Some(Resumed { - tokens: l.ids.len(), - session: l.session, - source: ResumeSource::Live, - }); + return Some(Resumed { tokens: l.ids.len(), session: l.session, source: ResumeSource::Live }); } None } @@ -301,11 +260,7 @@ impl ResidentConversations { match as_ids(committed) { Some(ids) if !ids.is_empty() => { let bytes = self.policy.estimate(ids.len()); - self.live = Some(ParkedResident { - ids, - bytes, - session, - }); + self.live = Some(ParkedResident { ids, bytes, session }); } _ => self.live = None, } diff --git a/crates/engine-qwen35-cuda/src/conversation/resident/tests.rs b/crates/engine-qwen35-cuda/src/conversation/resident/tests.rs index 4937f122..5856f848 100644 --- a/crates/engine-qwen35-cuda/src/conversation/resident/tests.rs +++ b/crates/engine-qwen35-cuda/src/conversation/resident/tests.rs @@ -3,12 +3,7 @@ use super::*; fn policy(budget_gib: usize, slots: usize) -> ResidentPolicy { - ResidentPolicy { - budget_bytes: budget_gib << 30, - slots, - fixed_bytes: 100 << 20, - bytes_per_token: 20_000, - } + ResidentPolicy { budget_bytes: budget_gib << 30, slots, fixed_bytes: 100 << 20, bytes_per_token: 20_000 } } fn toks(salt: u32, n: u32) -> Vec { (0..n).map(|i| salt * 1000 + i).collect() @@ -21,10 +16,7 @@ fn disabled_policy_keeps_exactly_the_old_single_continuation() { let mut p = toks(1, 10); p.push(7); let r = store.take_for(&p, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens, r.source), - ("a", 10, ResumeSource::Live) - ); + assert_eq!((r.session, r.tokens, r.source), ("a", 10, ResumeSource::Live)); store.publish(&toks(1, 12), "a2"); // Another conversation replaces it; nothing is parked. assert!(store.take_for(&toks(2, 9), |_| true).is_none()); @@ -36,11 +28,7 @@ fn disabled_policy_keeps_exactly_the_old_single_continuation() { fn an_identical_prompt_may_reuse_the_live_session_but_not_a_parked_one() { let mut store = ResidentConversations::::new(policy(8, 4)); store.publish(&toks(1, 10), 1); - assert_eq!( - store.take_for(&toks(1, 10), |_| true).unwrap().tokens, - 10, - "live: equal length allowed" - ); + assert_eq!(store.take_for(&toks(1, 10), |_| true).unwrap().tokens, 10, "live: equal length allowed"); store.publish(&toks(1, 10), 1); assert!(store.take_for(&toks(2, 5), |_| true).is_none()); // parks 1 assert_eq!(store.parked(), 1); @@ -62,10 +50,7 @@ fn a_b_a_swaps_through_the_cache_and_prefers_the_longest_prefix() { let mut a = toks(1, 20); a.push(5); let r = store.take_for(&a, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens, r.source), - ("A", 20, ResumeSource::Parked) - ); + assert_eq!((r.session, r.tokens, r.source), ("A", 20, ResumeSource::Parked)); assert_eq!(store.parked(), 1, "B was parked in exchange"); store.publish(&a, "A2"); // A branch of A that diverges after 12 tokens finds nothing reusable @@ -75,10 +60,7 @@ fn a_b_a_swaps_through_the_cache_and_prefers_the_longest_prefix() { assert!(store.take_for(&branch, |_| true).is_none()); assert_eq!(store.parked(), 2, "A2 is parked rather than lost"); let events = store.take_events(); - assert!( - events.iter().any(|e| e.contains("restored 20 tokens")), - "{events:?}" - ); + assert!(events.iter().any(|e| e.contains("restored 20 tokens")), "{events:?}"); } #[test] @@ -94,11 +76,7 @@ fn the_longest_parked_prefix_wins_and_ties_go_to_the_newest() { let mut request = toks(1, 14); request.push(0); let r = store.take_for(&request, |_| true).unwrap(); - assert_eq!( - (r.session, r.tokens), - ("long-dup", 14), - "equal length: the most recently parked" - ); + assert_eq!((r.session, r.tokens), ("long-dup", 14), "equal length: the most recently parked"); } #[test] @@ -118,18 +96,12 @@ fn slots_and_bytes_bound_the_parked_set_oldest_first() { assert_eq!(hit, expect, "conversation {salt}"); } // A budget smaller than one session parks nothing. - let mut tiny = ResidentConversations::::new(ResidentPolicy { - budget_bytes: 1 << 20, - ..policy(8, 4) - }); + let mut tiny = ResidentConversations::::new(ResidentPolicy { budget_bytes: 1 << 20, ..policy(8, 4) }); tiny.publish(&toks(1, 10), 1); assert!(tiny.take_for(&toks(2, 3), |_| true).is_none()); assert_eq!(tiny.parked(), 0); let events = tiny.take_events(); - assert!( - events.iter().any(|e| e.contains("skip parking")), - "{events:?}" - ); + assert!(events.iter().any(|e| e.contains("skip parking")), "{events:?}"); } #[test] @@ -160,10 +132,7 @@ fn publishing_nothing_or_unrepresentable_tokens_leaves_no_live_session() { assert!(!store.has_live()); store.publish(&[1, 2], 1); assert!(store.take_for(&[u32::MAX], |_| true).is_none()); - assert!( - !store.has_live(), - "an unrepresentable prompt invalidates the live session" - ); + assert!(!store.has_live(), "an unrepresentable prompt invalidates the live session"); store.publish(&[1, 2], 1); store.clear(); assert!(!store.has_live() && store.parked() == 0); @@ -173,48 +142,21 @@ fn publishing_nothing_or_unrepresentable_tokens_leaves_no_live_session() { fn operator_settings_are_parsed_strictly() { let p = ResidentPolicy::from_values(Some("2048"), Some("3")).unwrap(); assert_eq!((p.budget_bytes, p.slots), (2048 << 20, 3)); - assert_eq!( - ResidentPolicy::from_values(None, None).unwrap(), - ResidentPolicy::disabled() - ); + assert_eq!(ResidentPolicy::from_values(None, None).unwrap(), ResidentPolicy::disabled()); assert!(!ResidentPolicy::disabled().enabled()); - for bad in [ - "", - "-1", - "+1", - " 1", - "1 ", - "1e3", - "0x10", - "99999999999999999999", - "٣", - ] { - assert!( - ResidentPolicy::from_values(Some(bad), None).is_err(), - "{bad:?}" - ); - assert!( - ResidentPolicy::from_values(None, Some(bad)).is_err(), - "{bad:?}" - ); + for bad in ["", "-1", "+1", " 1", "1 ", "1e3", "0x10", "99999999999999999999", "٣"] { + assert!(ResidentPolicy::from_values(Some(bad), None).is_err(), "{bad:?}"); + assert!(ResidentPolicy::from_values(None, Some(bad)).is_err(), "{bad:?}"); } assert!(ResidentPolicy::from_values(None, Some("65")).is_err()); assert!(ResidentPolicy::from_values(Some("4194305"), None).is_err()); - assert_eq!( - ResidentPolicy::from_values(Some("0"), Some("0")) - .unwrap() - .budget_bytes, - 0 - ); + assert_eq!(ResidentPolicy::from_values(Some("0"), Some("0")).unwrap().budget_bytes, 0); } #[test] fn the_accounting_estimate_saturates() { let p = ResidentPolicy::disabled(); assert_eq!(p.estimate(0), p.fixed_bytes); - assert_eq!( - p.estimate(100_000), - p.fixed_bytes + 100_000 * p.bytes_per_token - ); + assert_eq!(p.estimate(100_000), p.fixed_bytes + 100_000 * p.bytes_per_token); assert_eq!(p.estimate(usize::MAX), usize::MAX); } diff --git a/crates/engine-qwen35-cuda/src/experimental.rs b/crates/engine-qwen35-cuda/src/experimental.rs index cb87c82e..92774afa 100644 --- a/crates/engine-qwen35-cuda/src/experimental.rs +++ b/crates/engine-qwen35-cuda/src/experimental.rs @@ -68,9 +68,7 @@ fn selection_error(e: KvSelectionError) -> ExperimentalError { "keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps" } KvSelectionError::NegativeResident => "--kv-resident must be >= 0", - KvSelectionError::K8V4NotStreamable => { - "--kv k8v4 does not support --kv-resident streaming (yet)" - } + KvSelectionError::K8V4NotStreamable => "--kv k8v4 does not support --kv-resident streaming (yet)", }) } @@ -95,9 +93,7 @@ pub fn plan(config: &ExperimentalConfig) -> Result, ExperimentalErr on(Mode::ControlVectors), ); if q4 && k8 { - return Err(ExperimentalError::Invalid( - "kv-q4_0 and kv-k8v4 are exclusive", - )); + return Err(ExperimentalError::Invalid("kv-q4_0 and kv-k8v4 are exclusive")); } if rot && (q4 || k8) { return Err(ExperimentalError::Invalid( @@ -170,18 +166,12 @@ pub fn plan(config: &ExperimentalConfig) -> Result, ExperimentalErr if cvec { need(Program::Cvec); } - Ok(Some(Plan { - format, - programs, - streamed, - control_vectors: cvec, - })) + Ok(Some(Plan { format, programs, streamed, control_vectors: cvec })) } /// Pool bytes of one QSA layer for `pages` pages in the plan's format (`kv_pool_bytes` of `layer.cpp`). pub fn pool_bytes(plan: &Plan, pages: u64) -> Option { - plan.format - .map(|f| kv_pool_bytes(f, &QsaShapes::real(), pages)) + plan.format.map(|f| kv_pool_bytes(f, &QsaShapes::real(), pages)) } /// The execution-mode digest with the experimental identity mixed in: an experimental mode changes model @@ -230,20 +220,14 @@ pub fn load_control_vector_tables( .read_to_end(&mut bytes) .map_err(|_| ExperimentalError::Invalid("control-vector file cannot be read"))?; if bytes.len() as u64 > MAX_CONTROL_VECTOR_FILE_BYTES { - return Err(ExperimentalError::Invalid( - "control-vector file is too large", - )); + return Err(ExperimentalError::Invalid("control-vector file is too large")); } files.push((path.display().to_string(), bytes, *scale)); } - load_control_vectors(&files, n_layers, n_embd, hc, &config.control_vector_options).map_err( - |e| match e { - CvecError::UnsupportedEmbd => { - ExperimentalError::Unsupported("control vector: unsupported n_embd") - } - _ => ExperimentalError::Invalid("control-vector file or options rejected"), - }, - ) + load_control_vectors(&files, n_layers, n_embd, hc, &config.control_vector_options).map_err(|e| match e { + CvecError::UnsupportedEmbd => ExperimentalError::Unsupported("control vector: unsupported n_embd"), + _ => ExperimentalError::Invalid("control-vector file or options rejected"), + }) } /// Whether the forward pass applies the experimental cell formats and the control-vector hook. Until it does, diff --git a/crates/engine-qwen35-cuda/src/experimental/tests.rs b/crates/engine-qwen35-cuda/src/experimental/tests.rs index 3d730642..2dac1700 100644 --- a/crates/engine-qwen35-cuda/src/experimental/tests.rs +++ b/crates/engine-qwen35-cuda/src/experimental/tests.rs @@ -7,11 +7,7 @@ fn cfg(modes: &[Mode], resident: i64) -> ExperimentalConfig { for m in modes { opt_in = opt_in.with(*m); } - ExperimentalConfig { - opt_in, - kv_resident: resident, - ..Default::default() - } + ExperimentalConfig { opt_in, kv_resident: resident, ..Default::default() } } #[test] @@ -22,20 +18,8 @@ fn default_is_off_and_changes_nothing() { assert_eq!(mode_digest("sha256:abc", &c), "sha256:abc"); assert_eq!(ensure_consumed(&None), Ok(())); // stray values without their mode are refused, not ignored - assert!( - plan(&ExperimentalConfig { - kv_resident: 8, - ..Default::default() - }) - .is_err() - ); - assert!( - plan(&ExperimentalConfig { - control_vectors: vec![("a".into(), 1.0)], - ..Default::default() - }) - .is_err() - ); + assert!(plan(&ExperimentalConfig { kv_resident: 8, ..Default::default() }).is_err()); + assert!(plan(&ExperimentalConfig { control_vectors: vec![("a".into(), 1.0)], ..Default::default() }).is_err()); } #[test] @@ -50,76 +34,29 @@ fn each_mode_selects_the_originals_format_and_programs() { assert_eq!(p.format, Some(KvFormat::Int8Rotated)); let p = plan(&cfg(&[Mode::KeylessVOnly], 0)).unwrap().unwrap(); assert_eq!(p.format, Some(KvFormat::Int8Keyless)); - assert_eq!( - p.programs, - [Program::Keyless, Program::KvQ8, Program::QsaAttn] - ); - let p = plan(&cfg(&[Mode::KvQ40, Mode::KvStreamed], 20_480)) - .unwrap() - .unwrap(); + assert_eq!(p.programs, [Program::Keyless, Program::KvQ8, Program::QsaAttn]); + let p = plan(&cfg(&[Mode::KvQ40, Mode::KvStreamed], 20_480)).unwrap().unwrap(); assert!(p.streamed); - assert_eq!( - p.programs, - [Program::KvQ4, Program::QsaAttn, Program::KvStream] - ); + assert_eq!(p.programs, [Program::KvQ4, Program::QsaAttn, Program::KvStream]); let mut c = cfg(&[Mode::ControlVectors], 0); c.control_vectors.push(("v.gguf".into(), 1.0)); let p = plan(&c).unwrap().unwrap(); - assert_eq!( - (p.format, p.programs.as_slice()), - (None, &[Program::Cvec][..]) - ); + assert_eq!((p.format, p.programs.as_slice()), (None, &[Program::Cvec][..])); } #[test] fn exclusions_follow_the_originals_selection_rules() { let bad = |modes: &[Mode], resident| plan(&cfg(modes, resident)).unwrap_err(); - assert!( - bad(&[Mode::KvQ40, Mode::KvK8V4], 0) - .to_string() - .contains("exclusive") - ); - assert!( - bad(&[Mode::KvRotatedInt8, Mode::KvQ40], 0) - .to_string() - .contains("exclusive") - ); - assert!( - bad(&[Mode::KeylessVOnly, Mode::KvQ40], 0) - .to_string() - .contains("keyless requires INT8") - ); - assert!( - bad(&[Mode::KeylessVOnly, Mode::KvRotatedInt8], 0) - .to_string() - .contains("keyless requires INT8") - ); - assert!( - bad(&[Mode::KvK8V4, Mode::KvStreamed], 4096) - .to_string() - .contains("k8v4 does not support") - ); - assert!( - bad(&[Mode::KvStreamed], 0) - .to_string() - .contains("kv-streamed needs") - ); - assert!( - bad(&[Mode::KvQ40], 4096) - .to_string() - .contains("kv-streamed needs") - ); - assert!( - bad(&[Mode::ControlVectors], 0) - .to_string() - .contains("control-vectors needs") - ); + assert!(bad(&[Mode::KvQ40, Mode::KvK8V4], 0).to_string().contains("exclusive")); + assert!(bad(&[Mode::KvRotatedInt8, Mode::KvQ40], 0).to_string().contains("exclusive")); + assert!(bad(&[Mode::KeylessVOnly, Mode::KvQ40], 0).to_string().contains("keyless requires INT8")); + assert!(bad(&[Mode::KeylessVOnly, Mode::KvRotatedInt8], 0).to_string().contains("keyless requires INT8")); + assert!(bad(&[Mode::KvK8V4, Mode::KvStreamed], 4096).to_string().contains("k8v4 does not support")); + assert!(bad(&[Mode::KvStreamed], 0).to_string().contains("kv-streamed needs")); + assert!(bad(&[Mode::KvQ40], 4096).to_string().contains("kv-streamed needs")); + assert!(bad(&[Mode::ControlVectors], 0).to_string().contains("control-vectors needs")); // keyless streams (the Original's V-only stream format) - assert!( - plan(&cfg(&[Mode::KeylessVOnly, Mode::KvStreamed], 20_480)) - .unwrap() - .is_some() - ); + assert!(plan(&cfg(&[Mode::KeylessVOnly, Mode::KvStreamed], 20_480)).unwrap().is_some()); } #[test] @@ -154,22 +91,16 @@ fn digest_binds_modes_values_and_files() { #[test] fn an_enabled_mode_is_refused_until_the_forward_pass_consumes_it() { let p = plan(&cfg(&[Mode::KvQ40], 0)).unwrap(); - assert!(matches!( - ensure_consumed(&p), - Err(ExperimentalError::Unsupported(_)) - )); + assert!(matches!(ensure_consumed(&p), Err(ExperimentalError::Unsupported(_)))); } #[test] fn control_vector_files_are_validated_at_load() { let mut c = cfg(&[Mode::ControlVectors], 0); - c.control_vectors - .push((PathBuf::from("/nonexistent/leleka-cvec.gguf"), 1.0)); + c.control_vectors.push((PathBuf::from("/nonexistent/leleka-cvec.gguf"), 1.0)); assert_eq!( load_control_vector_tables(&c, 6, 40, 4), - Err(ExperimentalError::Invalid( - "control-vector file cannot be opened" - )) + Err(ExperimentalError::Invalid("control-vector file cannot be opened")) ); // a real (tiny, invalid) file is rejected by the Original's GGUF checks let dir = std::env::temp_dir().join(format!("leleka-cvec-{}", std::process::id())); @@ -179,9 +110,7 @@ fn control_vector_files_are_validated_at_load() { c.control_vectors[0].0 = path; assert_eq!( load_control_vector_tables(&c, 6, 40, 4), - Err(ExperimentalError::Invalid( - "control-vector file or options rejected" - )) + Err(ExperimentalError::Invalid("control-vector file or options rejected")) ); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_measurement_sdet.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_measurement_sdet.rs index 5aa8e9a0..f2cefee6 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_measurement_sdet.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_measurement_sdet.rs @@ -83,9 +83,7 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() { bounds.push(unverified_drafts); for record in bounds { assert_eq!( - record - .finish(counts([0; 8]), counts([0; 8]), true, false, true, None) - .err(), + record.finish(counts([0; 8]), counts([0; 8]), true, false, true, None).err(), Some(MeasurementFailure::Bounds) ); } @@ -94,9 +92,7 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() { // usage; failures never become a successful measurement by default. for usage in [None, Some((2, 1, 0)), Some((3, 2, 0)), Some((3, 1, 1))] { assert_eq!( - finished_one() - .finish(counts([0; 8]), counts([0; 8]), true, false, true, usage) - .err(), + finished_one().finish(counts([0; 8]), counts([0; 8]), true, false, true, usage).err(), Some(MeasurementFailure::Incomplete) ); } @@ -108,16 +104,7 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() { twice_prefilled.prefilled(); for record in [missing, no_decode, twice_prefilled] { assert_eq!( - record - .finish( - counts([0; 8]), - counts([0; 8]), - false, - false, - false, - Some((3, 1, 0)), - ) - .err(), + record.finish(counts([0; 8]), counts([0; 8]), false, false, false, Some((3, 1, 0)),).err(), Some(MeasurementFailure::Incomplete) ); } @@ -125,29 +112,13 @@ fn measurement_framed_eos_bounds_usage_rewind_and_callback_isolation() { let mut rewound = [10; 8]; rewound[field] = 9; assert_eq!( - finished_one() - .finish( - counts([10; 8]), - counts(rewound), - true, - false, - true, - Some((3, 1, 0)), - ) - .err(), + finished_one().finish(counts([10; 8]), counts(rewound), true, false, true, Some((3, 1, 0)),).err(), Some(MeasurementFailure::CounterRewind) ); } let unpublished = finished_one() - .finish( - counts([0; 8]), - counts([0; 8]), - false, - false, - false, - Some((3, 1, 0)), - ) + .finish(counts([0; 8]), counts([0; 8]), false, false, false, Some((3, 1, 0))) .expect("flags describe outcome, never invent completion"); assert!(!unpublished.completed && !unpublished.stopped && !unpublished.terminal_published); diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_arms.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_arms.rs index 5b81ca44..a640d436 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_arms.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_arms.rs @@ -7,10 +7,7 @@ //! first-request state (`reset_expert_tier`: starting profile set, empty adaptive counts, fresh controller), so a request //! never sees the placement an earlier request adapted; the arms of one prompt run back to back, the order reversed on //! alternate prompts (ABBA drift balance). -use crate::qwen_forward::{ - original_serve_request::ServeRequest, - original_serve_stack::OriginalServeStack, -}; +use crate::qwen_forward::{original_serve_request::ServeRequest, original_serve_stack::OriginalServeStack}; #[derive(Clone, Debug)] pub(super) struct ArmSpec { @@ -28,15 +25,21 @@ pub(super) fn parse_arms(text: &str) -> Vec { .map(str::trim) .filter(|s| !s.is_empty()) .map(|label| { - let mut arm = ArmSpec { label: label.to_owned(), adapt_every: 0, seed_swaps: 0, keep: 0.0, usage: 0.0, decay: 1.0 }; + let mut arm = + ArmSpec { label: label.to_owned(), adapt_every: 0, seed_swaps: 0, keep: 0.0, usage: 0.0, decay: 1.0 }; for token in label.split('+') { let (name, value) = token.split_once('=').map_or((token, None), |(n, v)| (n, Some(v))); - let num = |v: Option<&str>| v.map(|v| v.parse::().unwrap_or_else(|_| panic!("arm {label}: bad number in {token}"))); + let num = |v: Option<&str>| { + v.map(|v| v.parse::().unwrap_or_else(|_| panic!("arm {label}: bad number in {token}"))) + }; match name { "static" => arm.adapt_every = 0, "adaptive" => arm.adapt_every = 4, "every" => arm.adapt_every = num(value).expect("every=N") as u32, - "seed" => arm.seed_swaps = num(value).map_or(crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS, |n| n as usize), + "seed" => { + arm.seed_swaps = num(value) + .map_or(crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS, |n| n as usize) + } "keep" => arm.keep = num(value).expect("keep=F") as f32, "usage" => arm.usage = num(value).expect("usage=F") as f32, "id" => {} @@ -95,15 +98,20 @@ pub(super) fn serve_arm( let started = std::time::Instant::now(); let mut first: Option = None; let mut out = Vec::new(); - let served = stack.serve(request, &mut |round| { - if first.is_none() { - first = Some(started.elapsed()); - } - out.extend_from_slice(round); - Ok(()) - }, &mut || false); + let served = stack.serve( + request, + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); let total = started.elapsed(); - let outcome = served.unwrap_or_else(|e| panic!("arm {} {tag} failed: {e:?} health={:?}", arm.label, stack.health())); + let outcome = + served.unwrap_or_else(|e| panic!("arm {} {tag} failed: {e:?} health={:?}", arm.label, stack.health())); let ttft = first.unwrap_or(total); let decode_s = (total - ttft).as_secs_f64(); let decode_tps = if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 }; @@ -129,7 +137,11 @@ pub(super) fn serve_arm( rate(&marks, marks.len(), 1), stats.map_or(0, |s| s.adaptations), ); - eprintln!("DBG arm-output {} {tag}: {}", arm.label, out.iter().map(|t| t.to_string()).collect::>().join(" ")); + eprintln!( + "DBG arm-output {} {tag}: {}", + arm.label, + out.iter().map(|t| t.to_string()).collect::>().join(" ") + ); ArmRun { tokens: out } } @@ -142,7 +154,10 @@ mod tests { let arms = parse_arms("static, static+seed ,adaptive+seed=512+keep=1.5+usage=0.25,every=8"); assert_eq!(arms.len(), 4); assert_eq!((arms[0].adapt_every, arms[0].seed_swaps), (0, 0)); - assert_eq!((arms[1].adapt_every, arms[1].seed_swaps), (0, crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS)); + assert_eq!( + (arms[1].adapt_every, arms[1].seed_swaps), + (0, crate::qwen_forward::original_serve_seed::DEFAULT_SEED_SWAPS) + ); assert_eq!((arms[2].adapt_every, arms[2].seed_swaps, arms[2].keep, arms[2].usage), (4, 512, 1.5, 0.25)); assert_eq!(arms[3].adapt_every, 8); assert_eq!(arms_for(&arms, 0)[0].label, "static"); diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_laptop.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_laptop.rs index 196397cb..1f5c87c7 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_laptop.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_laptop.rs @@ -69,16 +69,22 @@ fn elapsed(start: std::time::Instant) -> f64 { fn original_serve_laptop_bench() { assert!(env::var("LELEKA_LAPTOP_BENCH").is_ok_and(|v| v == "yes"), "explicit laptop bench opt-in required"); let start = std::time::Instant::now(); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); eprintln!("LAPTOP load: shards verified in {:.1} s; {}", elapsed(start), memory_line()); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") { - Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"), + Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) + .expect("read-only KAR admission failed"), None => { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("LELEKA_LAPTOP_KAR_FILE or LELEKA_STRA169_KAR_FD").parse().expect("invalid descriptor"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("LELEKA_LAPTOP_KAR_FILE or LELEKA_STRA169_KAR_FD") + .parse() + .expect("invalid descriptor"); InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") } }; @@ -89,14 +95,25 @@ fn original_serve_laptop_bench() { &required_path("LELEKA_STRA169_MTP_STAGING"), ) .expect("actual pinned KAR+MTP binding failed"); - eprintln!("LAPTOP load: KAR ({}) + MTP bound at {:.1} s; {}", if inherited.file_backed() { "read-only file" } else { "sealed memfd" }, elapsed(start), memory_line()); + eprintln!( + "LAPTOP load: KAR ({}) + MTP bound at {:.1} s; {}", + if inherited.file_backed() { "read-only file" } else { "sealed memfd" }, + elapsed(start), + memory_line() + ); let experts = env::var("LELEKA_LAPTOP_EXPERTS").unwrap_or_else(|_| "mapped".to_owned()); let report = match experts.as_str() { "mapped" => binding.load_mapped_expert_source().expect("mapped expert source load failed"), "resident" => binding.load_resident_expert_source().expect("resident expert source load failed"), other => panic!("LELEKA_LAPTOP_EXPERTS must be mapped or resident, not {other}"), }; - eprintln!("LAPTOP load: experts {experts} ({} bytes, file_mapped={}) at {:.1} s; {}", report.source_bytes, report.file_mapped, elapsed(start), memory_line()); + eprintln!( + "LAPTOP load: experts {experts} ({} bytes, file_mapped={}) at {:.1} s; {}", + report.source_bytes, + report.file_mapped, + elapsed(start), + memory_line() + ); // Experimental: a process geometry of N cells instead of the trained 262144 (the Original sizes its KV by // --max-context). Unscaled RoPE; must precede the first CUDA context user. @@ -128,10 +145,17 @@ fn original_serve_laptop_bench() { "auto" => PrefixBudget::Auto, other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_LAPTOP_PREFIX_MIB: auto or MiB") << 20), }; - config.prefix = Some(PrefixConfig { budget, block_tokens: number("LELEKA_LAPTOP_PREFIX_BLOCK", 0), laptop: true, ..PrefixConfig::auto() }); + config.prefix = Some(PrefixConfig { + budget, + block_tokens: number("LELEKA_LAPTOP_PREFIX_BLOCK", 0), + laptop: true, + ..PrefixConfig::auto() + }); } - eprintln!("LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}", - config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier); + eprintln!( + "LAPTOP config: capacity {} cpu_workers {} max_context {} kv_resident {} budget {budget_gib} GiB tier {:?}", + config.capacity, config.cpu_workers, config.max_context, config.kv_resident, config.expert_tier + ); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), @@ -147,7 +171,8 @@ fn original_serve_laptop_bench() { let max_new = number("LELEKA_LAPTOP_MAX_NEW", 128); let repeat = number("LELEKA_LAPTOP_REPEAT", 2).max(1); // setup.py's `--spec-min-p 0.5` (the draft-probability floor; greedy output does not depend on it) - let spec_min_p: f32 = env::var("LELEKA_LAPTOP_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SPEC_MIN_P")).unwrap_or(0.5); + let spec_min_p: f32 = + env::var("LELEKA_LAPTOP_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SPEC_MIN_P")).unwrap_or(0.5); // LELEKA_LAPTOP_ARMS (see backend_original_serve_arms.rs): first-request A/B of the expert tier's policies; every // prompt of LELEKA_LAPTOP_ORDER (default: file order) once per arm from a first-request tier state, `repeat` times. if let Ok(arms) = env::var("LELEKA_LAPTOP_ARMS") { @@ -158,8 +183,21 @@ fn original_serve_laptop_bench() { for rep in 0..repeat { for (k, &index) in order.iter().enumerate() { for arm in super::original_serve_arms::arms_for(&arms, k + rep) { - let request = ServeRequest::new(prompts[index].clone(), max_new, None, 7, spec_min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)); - super::original_serve_arms::serve_arm(&mut stack, &arm, &request, &format!("p{} rep{rep}", index + 1), &format!("prompt={}", prompts[index].len())); + let request = ServeRequest::new( + prompts[index].clone(), + max_new, + None, + 7, + spec_min_p, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ); + super::original_serve_arms::serve_arm( + &mut stack, + &arm, + &request, + &format!("p{} rep{rep}", index + 1), + &format!("prompt={}", prompts[index].len()), + ); } } } @@ -171,7 +209,8 @@ fn original_serve_laptop_bench() { .map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_LAPTOP_SEQUENCE: indices")).collect()) .unwrap_or_else(|_| (0..prompts.len()).collect()); assert!(sequence.iter().all(|&i| i < prompts.len()), "LELEKA_LAPTOP_SEQUENCE index out of range"); - let soak_s: f64 = env::var("LELEKA_LAPTOP_SOAK_S").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SOAK_S")).unwrap_or(0.0); + let soak_s: f64 = + env::var("LELEKA_LAPTOP_SOAK_S").ok().map(|v| v.parse().expect("LELEKA_LAPTOP_SOAK_S")).unwrap_or(0.0); let skip_failed = env::var("LELEKA_LAPTOP_SKIP_FAILED").is_ok_and(|v| v == "1"); let served_from = std::time::Instant::now(); let mut done_requests = 0usize; @@ -184,17 +223,28 @@ fn original_serve_laptop_bench() { break 'passes; } let ids = &prompts[index]; - let request = ServeRequest::new(ids.clone(), max_new, None, 7, spec_min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)); + let request = ServeRequest::new( + ids.clone(), + max_new, + None, + 7, + spec_min_p, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ); let mut out = Vec::new(); let begun = std::time::Instant::now(); let mut first = None; - let served = stack.serve(&request, &mut |round| { - if first.is_none() { - first = Some(begun.elapsed()); - } - out.extend_from_slice(round); - Ok(()) - }, &mut || false); + let served = stack.serve( + &request, + &mut |round| { + if first.is_none() { + first = Some(begun.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); let total = begun.elapsed().as_secs_f64() * 1e3; let ttft = first.map_or(total, |d| d.as_secs_f64() * 1e3); let (prompt_ms, decode_ms) = stack.last_timing(); @@ -203,24 +253,44 @@ fn original_serve_laptop_bench() { done_requests += 1; let prefill = if prompt_ms > 0.0 { ids.len() as f64 * 1e3 / prompt_ms } else { 0.0 }; let decode = if decode_ms > 0.0 { out.len() as f64 * 1e3 / decode_ms } else { 0.0 }; - eprintln!("LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2} t={:.1}; {}", - index + 1, ids.len(), out.len(), outcome.rounds, served_from.elapsed().as_secs_f64(), memory_line()); + eprintln!( + "LAPTOP request p{} pass={pass} prompt={} produced={} rounds={} ttft_ms={ttft:.1} prompt_ms={prompt_ms:.1} decode_ms={decode_ms:.1} total_ms={total:.1} prefill_tok_s={prefill:.1} decode_tok_s={decode:.2} t={:.1}; {}", + index + 1, + ids.len(), + out.len(), + outcome.rounds, + served_from.elapsed().as_secs_f64(), + memory_line() + ); if let Some(stats) = stack.expert_tier_stats() { eprintln!("LAPTOP tier p{} pass={pass}: {}", index + 1, stats.describe()); } if pass == 0 { - eprintln!("LAPTOP output p{}: {}", index + 1, out.iter().map(|t| t.to_string()).collect::>().join(",")); + eprintln!( + "LAPTOP output p{}: {}", + index + 1, + out.iter().map(|t| t.to_string()).collect::>().join(",") + ); } } Err(e) if skip_failed => { - eprintln!("LAPTOP failed p{} pass={pass} after {done_requests} requests: {e:?} health={:?}; {}", index + 1, stack.health(), memory_line()); + eprintln!( + "LAPTOP failed p{} pass={pass} after {done_requests} requests: {e:?} health={:?}; {}", + index + 1, + stack.health(), + memory_line() + ); break 'passes; } Err(e) => panic!("request p{} pass {pass} failed: {e:?} health={:?}", index + 1, stack.health()), } } } - eprintln!("LAPTOP done: {done_requests} requests in {:.1} s; {}", served_from.elapsed().as_secs_f64(), memory_line()); + eprintln!( + "LAPTOP done: {done_requests} requests in {:.1} s; {}", + served_from.elapsed().as_secs_f64(), + memory_line() + ); stack.close().expect("stack cleanup failed"); Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs index cfb11143..cad923db 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_memory_smoke.rs @@ -38,7 +38,11 @@ fn text(name: &str, default: &str) -> String { env::var(name).unwrap_or_else(|_| default.to_owned()) } fn list(name: &str, default: &str) -> Vec { - text(name, default).split(',').filter(|s| !s.trim().is_empty()).map(|t| t.trim().parse().unwrap_or_else(|_| panic!("{name} must be counts"))).collect() + text(name, default) + .split(',') + .filter(|s| !s.trim().is_empty()) + .map(|t| t.trim().parse().unwrap_or_else(|_| panic!("{name} must be counts"))) + .collect() } struct Rng(u64); @@ -77,7 +81,14 @@ fn filler(tokenizer: &Tokenizer, rng: &mut Rng, kind: u8, tokens: usize) -> Vec< /// While set, a request does not stop at EOS (the reader scenario measures a fixed number of decoded tokens). static NO_STOP: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); -fn serve_one(stack: &mut OriginalServeStack<'_, '_>, prompt: &[u32], max_new: usize, eos: u32, cancel_probes: Option, cancel_rounds: Option) -> Result<(Vec, f64, f64, usize), ServeError> { +fn serve_one( + stack: &mut OriginalServeStack<'_, '_>, + prompt: &[u32], + max_new: usize, + eos: u32, + cancel_probes: Option, + cancel_rounds: Option, +) -> Result<(Vec, f64, f64, usize), ServeError> { let stops = if NO_STOP.load(std::sync::atomic::Ordering::Relaxed) { Vec::new() } else { vec![eos as i32] }; let request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, 0.0, stops); let rounds = std::cell::Cell::new(0usize); @@ -110,7 +121,11 @@ fn census(context: &leleka_cuda_driver::Context<'_>) -> Census { /// Abort (never go on) when the host is short of memory: the operator's rule for this server. fn guard(floor_gib: u64, what: &str) { if let Some(avail) = crate::conversation::memory::available_memory() { - assert!(avail >= floor_gib << 30, "ABORT {what}: MemAvailable {} MiB is below the {floor_gib} GiB guard", avail >> 20); + assert!( + avail >= floor_gib << 30, + "ABORT {what}: MemAvailable {} MiB is below the {floor_gib} GiB guard", + avail >> 20 + ); } } @@ -138,18 +153,30 @@ fn original_serve_memory_smoke() { let prefix_wish = text("LELEKA_MEM_PREFIX_MIB", "4096"); guard(abort_gib, "before the load"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary(&metadata.model, &metadata.pre, metadata.tokens.clone(), metadata.merges.clone(), metadata.token_types.clone()) - .expect("verified tokenizer construction failed"); + let tokenizer = Tokenizer::from_vocabulary( + &metadata.model, + &metadata.pre, + metadata.tokens.clone(), + metadata.merges.clone(), + metadata.token_types.clone(), + ) + .expect("verified tokenizer construction failed"); let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); let inherited = match env::var_os("LELEKA_MEM_KAR_FILE") { - Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"), + Some(path) => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) + .expect("read-only KAR admission failed"), None => { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") } }; @@ -160,17 +187,21 @@ fn original_serve_memory_smoke() { "0" | "off" => None, mib => Some(Some(mib.parse::().expect("LELEKA_MEM_PREFIX_MIB: auto or MiB") << 20)), }; - let governor = crate::memory_governor::startup(&crate::memory_governor::StartArgs { - kv_resident: resident, - gpu_budget_bytes: (budget_gib as u64) << 30, - kar_file_backed: Some(inherited.file_backed()), - kar_sparse_bytes: None, - expert_source_mapped: experts_mapped, - prefix: prefix_arg, - prompt_cache: 6, - }, crate::settings::process()) + let governor = crate::memory_governor::startup( + &crate::memory_governor::StartArgs { + kv_resident: resident, + gpu_budget_bytes: (budget_gib as u64) << 30, + kar_file_backed: Some(inherited.file_backed()), + kar_sparse_bytes: None, + expert_source_mapped: experts_mapped, + prefix: prefix_arg, + prompt_cache: 6, + }, + crate::settings::process(), + ) .unwrap_or_else(|e| panic!("memory plan refused: {}", e.message)); - crate::memory_governor::guard_archive(governor, &inherited).unwrap_or_else(|e| panic!("memory guard refused: {}", e.message)); + crate::memory_governor::guard_archive(governor, &inherited) + .unwrap_or_else(|e| panic!("memory guard refused: {}", e.message)); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -179,7 +210,8 @@ fn original_serve_memory_smoke() { ) .expect("actual pinned KAR+MTP binding failed"); let bank_stage = crate::memory_governor::begin("expert bank (resident copy or mappings)", None); - let bank = if experts_mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() }.expect("expert source load failed"); + let bank = if experts_mapped { binding.load_mapped_expert_source() } else { binding.load_resident_expert_source() } + .expect("expert source load failed"); crate::memory_governor::end(bank_stage, None); crate::memory_governor::account( "expert_bank", @@ -190,13 +222,17 @@ fn original_serve_memory_smoke() { bank.charged_bytes, ); if !experts_mapped { - crate::memory_governor::drop_file_cache(&[&required_path("LELEKA_STRA169_IQ3S_SHARD0"), &required_path("LELEKA_STRA169_IQ3S_SHARD1")]); + crate::memory_governor::drop_file_cache(&[ + &required_path("LELEKA_STRA169_IQ3S_SHARD0"), + &required_path("LELEKA_STRA169_IQ3S_SHARD1"), + ]); } guard(abort_gib, "after the expert bank"); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - crate::memory_governor::check_vram(governor, context.as_ref(), (budget_gib as u64) << 30).unwrap_or_else(|e| panic!("vram refused: {}", e.message)); + crate::memory_governor::check_vram(governor, context.as_ref(), (budget_gib as u64) << 30) + .unwrap_or_else(|e| panic!("vram refused: {}", e.message)); let mut config = StackConfig::new(max_context as i64); config.capacity = capacity; @@ -211,11 +247,13 @@ fn original_serve_memory_smoke() { None => PrefixBudget::Auto, Some(bytes) => PrefixBudget::Bytes(bytes), }; - config.prefix = Some(PrefixConfig { budget, block_tokens: 0, laptop: experts_mapped, ..PrefixConfig::auto() }); + config.prefix = + Some(PrefixConfig { budget, block_tokens: 0, laptop: experts_mapped, ..PrefixConfig::auto() }); } None => {} } - config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment().expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), @@ -273,8 +311,18 @@ fn original_serve_memory_smoke() { if i % 4 == 0 { eprintln!("MEM-FILL i={i} {line}"); } - let used = line.split("used_mib=").nth(1).and_then(|s| s.split_whitespace().next()).and_then(|s| s.parse::().ok()).unwrap_or(0); - let budget = line.split("budget_mib=").nth(1).and_then(|s| s.split_whitespace().next()).and_then(|s| s.parse::().ok()).unwrap_or(u64::MAX); + let used = line + .split("used_mib=") + .nth(1) + .and_then(|s| s.split_whitespace().next()) + .and_then(|s| s.parse::().ok()) + .unwrap_or(0); + let budget = line + .split("budget_mib=") + .nth(1) + .and_then(|s| s.split_whitespace().next()) + .and_then(|s| s.parse::().ok()) + .unwrap_or(u64::MAX); if used * 100 >= budget * 97 { eprintln!("MEM-FILL full at i={i}: {line}"); break; @@ -316,14 +364,20 @@ fn original_serve_memory_smoke() { "overlong" => { // a request that cannot fit the pinned K/V image: refused up front, nothing allocated let prompt = vec![1u32; max_context + 16]; - let shape = RequestShape { prompt_tokens: prompt.len() as u64, max_new_tokens: 16, max_context: max_context as u64 }; + let shape = RequestShape { + prompt_tokens: prompt.len() as u64, + max_new_tokens: 16, + max_context: max_context as u64, + }; match governor.admit(&shape) { Admission::Refuse(r) if r.status == 400 => refused += 1, other => failed.push(format!("overlong {i} not refused with 400: {other:?}")), } match serve_one(&mut stack, &prompt, 16, eos, None, None) { Err(ServeError::Refused(_)) => {} - other => failed.push(format!("overlong {i} reached the engine: {:?}", other.map(|o| o.0.len()))), + other => { + failed.push(format!("overlong {i} reached the engine: {:?}", other.map(|o| o.0.len()))) + } } } "big" => { @@ -351,7 +405,11 @@ fn original_serve_memory_smoke() { next.extend(filler(&tokenizer, &mut rng, 1, 1500)); } let result = if kind == "cancel" { - let r = if i % 2 == 0 { serve_one(&mut stack, &next, 32, eos, Some(3), None) } else { serve_one(&mut stack, &next, 64, eos, None, Some(1)) }; + let r = if i % 2 == 0 { + serve_one(&mut stack, &next, 32, eos, Some(3), None) + } else { + serve_one(&mut stack, &next, 64, eos, None, Some(1)) + }; match r { Err(ServeError::Cancelled) => { cancelled += 1; @@ -406,8 +464,14 @@ fn original_serve_memory_smoke() { let ballast_mib = number("LELEKA_MEM_BALLAST_MIB", 3584); assert!(a0 >= abort_gib << 30, "start with more than the guard"); governor.set_floors(a0 - soft_below, a0 - hard_below).expect("floors"); - eprintln!("MEM-SHED start available_mib={} soft_mib={} hard_mib={}", a0 >> 20, (a0 - soft_below) >> 20, (a0 - hard_below) >> 20); - let shape = |n: usize| RequestShape { prompt_tokens: n as u64, max_new_tokens: 8, max_context: max_context as u64 }; + eprintln!( + "MEM-SHED start available_mib={} soft_mib={} hard_mib={}", + a0 >> 20, + (a0 - soft_below) >> 20, + (a0 - hard_below) >> 20 + ); + let shape = + |n: usize| RequestShape { prompt_tokens: n as u64, max_new_tokens: 8, max_context: max_context as u64 }; // 1. grow the prefix cache until the soft floor is crossed (or the budget is full) let mut max_used = 0usize; let mut shed_seen = false; @@ -424,7 +488,12 @@ fn original_serve_memory_smoke() { let used = stack.prefix_bytes(); max_used = max_used.max(used); let level = governor.level(); - eprintln!("MEM-SHED grow i={i} level={} prefix_used_mib={} available_mib={}", level.as_str(), used >> 20, crate::conversation::memory::available_memory().unwrap_or(0) >> 20); + eprintln!( + "MEM-SHED grow i={i} level={} prefix_used_mib={} available_mib={}", + level.as_str(), + used >> 20, + crate::conversation::memory::available_memory().unwrap_or(0) >> 20 + ); guard(abort_gib, "growing the prefix cache"); if level != Level::Normal { shed_seen = true; @@ -432,7 +501,10 @@ fn original_serve_memory_smoke() { } } if !shed_seen { - eprintln!("MEM-SHED the prefix cache reached its budget ({} MiB) without crossing the soft floor", max_used >> 20); + eprintln!( + "MEM-SHED the prefix cache reached its budget ({} MiB) without crossing the soft floor", + max_used >> 20 + ); failed.push("shed level never reached by cache growth".into()); } // the next request applies the directive: the cache evicts before it starts @@ -444,10 +516,12 @@ fn original_serve_memory_smoke() { failed.push("shedding must still admit requests".into()); } let used_before = stack.prefix_bytes(); - let (avail_before, rss_before) = (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); + let (avail_before, rss_before) = + (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); let _ = serve_one(&mut stack, &prompt, 4, eos, None, None); let used_after = stack.prefix_bytes(); - let (avail_after, rss_after) = (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); + let (avail_after, rss_after) = + (crate::conversation::memory::available_memory().unwrap_or(0), census(context.as_ref()).rss); eprintln!( "MEM-SHED evicted: prefix {} MiB -> {} MiB (level {}); MemAvailable {} -> {} MiB, RSS {} -> {} MiB", used_before >> 20, @@ -474,9 +548,16 @@ fn original_serve_memory_smoke() { governor.sample_now(); guard(abort_gib, "ballast"); } - eprintln!("MEM-SHED ballast {} MiB level={} available_mib={}", ballast.len() >> 20, governor.level().as_str(), crate::conversation::memory::available_memory().unwrap_or(0) >> 20); + eprintln!( + "MEM-SHED ballast {} MiB level={} available_mib={}", + ballast.len() >> 20, + governor.level().as_str(), + crate::conversation::memory::available_memory().unwrap_or(0) >> 20 + ); match governor.admit(&shape(prompt.len())) { - Admission::Refuse(r) if r.status == 503 && r.code == "memory_pressure" => eprintln!("MEM-SHED refused: {} retry_after={}s", r.message, r.retry_after_secs), + Admission::Refuse(r) if r.status == 503 && r.code == "memory_pressure" => { + eprintln!("MEM-SHED refused: {} retry_after={}s", r.message, r.retry_after_secs) + } other => failed.push(format!("no 503 at the hard floor: {other:?}")), } let _ = serve_one(&mut stack, &prompt, 4, eos, None, None); @@ -507,7 +588,12 @@ fn original_serve_memory_smoke() { } let r = serve_one(&mut stack, &prompt, 4, eos, None, None); let restored = stack.prefix_budget_bytes(); - eprintln!("MEM-SHED after recovery: served={} prefix_budget_mib={} prefix_used_mib={}", r.is_ok(), restored >> 20, stack.prefix_bytes() >> 20); + eprintln!( + "MEM-SHED after recovery: served={} prefix_budget_mib={} prefix_used_mib={}", + r.is_ok(), + restored >> 20, + stack.prefix_bytes() >> 20 + ); if r.is_err() || restored < (1 << 30) { failed.push("the prefix budget was not restored".into()); } @@ -525,7 +611,9 @@ fn original_serve_memory_smoke() { let big = list("LELEKA_MEM_BIG", "100000,180000"); let big_every = number("LELEKA_MEM_BIG_EVERY", 120); let tsv_path = env::var_os("LELEKA_MEM_LEAK_TSV").map(PathBuf::from); - let mut tsv = String::from("t_s\treq\trss\trss_anon\trss_file\trss_shmem\tswap\tavail\tcached\tshmem_sys\tactive_file\tinactive_file\tvram_used\tvram_acct\tprefix_store\tmalloc_arena\tmalloc_in_use\tmalloc_free\tmalloc_mmapped\tthreads\tfds\n"); + let mut tsv = String::from( + "t_s\treq\trss\trss_anon\trss_file\trss_shmem\tswap\tavail\tcached\tshmem_sys\tactive_file\tinactive_file\tvram_used\tvram_acct\tprefix_store\tmalloc_arena\tmalloc_in_use\tmalloc_free\tmalloc_mmapped\tthreads\tfds\n", + ); let mut sessions: Vec> = (0..sessions_n) .map(|s| { let mut p = system.clone(); @@ -536,7 +624,8 @@ fn original_serve_memory_smoke() { .collect(); let started = std::time::Instant::now(); let mut next_sample = 0u64; - let (mut req, mut served, mut cancelled, mut refused, mut bigs, mut fresh) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); + let (mut req, mut served, mut cancelled, mut refused, mut bigs, mut fresh) = + (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); // req, rss, anon, file, shmem, swap, vram, vram_acct, prefix, malloc_in_use, malloc_free, avail let mut series: Vec<[f64; 12]> = Vec::new(); while started.elapsed().as_secs() < seconds { @@ -556,7 +645,11 @@ fn original_serve_memory_smoke() { match kind { "overlong" => { let prompt_len = max_context + 16; - let shape = RequestShape { prompt_tokens: prompt_len as u64, max_new_tokens: 16, max_context: max_context as u64 }; + let shape = RequestShape { + prompt_tokens: prompt_len as u64, + max_new_tokens: 16, + max_context: max_context as u64, + }; match governor.admit(&shape) { Admission::Refuse(r) if r.status == 400 => refused += 1, other => failed.push(format!("overlong {req} not refused with 400: {other:?}")), @@ -578,8 +671,15 @@ fn original_serve_memory_smoke() { // an unshared session: its own task text, 8k..30k tokens, never seen again fresh += 1; let size = 8000 + (rng.next() as usize % 22_000); - let mut prompt = tok(&format!("<|im_start|>system\nIndependent agent {req}.<|im_end|>\n<|im_start|>user\nUnshared task {req}.\n")); - prompt.extend(filler(&tokenizer, &mut rng, (req % 2) as u8, size.min(max_context.saturating_sub(2000)))); + let mut prompt = tok(&format!( + "<|im_start|>system\nIndependent agent {req}.<|im_end|>\n<|im_start|>user\nUnshared task {req}.\n" + )); + prompt.extend(filler( + &tokenizer, + &mut rng, + (req % 2) as u8, + size.min(max_context.saturating_sub(2000)), + )); prompt.extend(tok("<|im_end|>\n<|im_start|>assistant\n")); match serve_one(&mut stack, &prompt, 12, eos, None, None) { Ok(_) => served += 1, @@ -598,7 +698,11 @@ fn original_serve_memory_smoke() { next.extend(filler(&tokenizer, &mut rng, 1, 1500)); } let result = if kind == "cancel" { - let r = if req % 2 == 0 { serve_one(&mut stack, &next, 32, eos, Some(3), None) } else { serve_one(&mut stack, &next, 64, eos, None, Some(1)) }; + let r = if req % 2 == 0 { + serve_one(&mut stack, &next, 32, eos, Some(3), None) + } else { + serve_one(&mut stack, &next, 64, eos, None, Some(1)) + }; match r { Err(ServeError::Cancelled) => { cancelled += 1; @@ -694,7 +798,19 @@ fn original_serve_memory_smoke() { // slope after the warm-up, in MiB per 1000 requests, for every series let skip = (series.len() as f64 * warm_frac) as usize; let tail = &series[skip.min(series.len())..]; - let names = ["rss", "rss_anon", "rss_file", "rss_shmem", "swap", "vram_used", "vram_accounted", "prefix_store", "malloc_in_use", "malloc_free", "mem_available"]; + let names = [ + "rss", + "rss_anon", + "rss_file", + "rss_shmem", + "swap", + "vram_used", + "vram_accounted", + "prefix_store", + "malloc_in_use", + "malloc_free", + "mem_available", + ]; eprintln!( "MEM-LEAK-FIT requests={req} samples={} used_for_fit={} (after {:.0}% warm-up); slope in MiB per 1000 requests with its 95% interval (OLS) and the Theil-Sen slope", series.len(), @@ -719,7 +835,9 @@ fn original_serve_memory_smoke() { None => eprintln!("MEM-LEAK-FIT {name}: too few samples"), } } - eprintln!("MEM-LEAK-RESULT requests={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs}"); + eprintln!( + "MEM-LEAK-RESULT requests={req} served={served} cancelled={cancelled} refused={refused} fresh={fresh} big={bigs}" + ); print_report("leak-end"); } "reader" => { @@ -739,7 +857,10 @@ fn original_serve_memory_smoke() { (f.pswpin.unwrap_or(0), f.pswpout.unwrap_or(0)) }; NO_STOP.store(true, std::sync::atomic::Ordering::Relaxed); - let mut phase = |label: &str, stack: &mut OriginalServeStack<'_, '_>, rates: &mut Vec, until: &dyn Fn() -> bool| { + let mut phase = |label: &str, + stack: &mut OriginalServeStack<'_, '_>, + rates: &mut Vec, + until: &dyn Fn() -> bool| { for i in 0..usize::MAX { if i >= n && until() { break; @@ -781,7 +902,9 @@ fn original_serve_memory_smoke() { use std::io::Read; let mut file = std::fs::File::open(path).expect("reader file"); let mut buf = vec![0u8; 16 << 20]; - while !stop.load(std::sync::atomic::Ordering::Relaxed) && read_bytes.load(std::sync::atomic::Ordering::Relaxed) < gib << 30 { + while !stop.load(std::sync::atomic::Ordering::Relaxed) + && read_bytes.load(std::sync::atomic::Ordering::Relaxed) < gib << 30 + { match file.read(&mut buf) { Ok(0) | Err(_) => break, Ok(k) => { @@ -793,14 +916,26 @@ fn original_serve_memory_smoke() { }; // B lasts until the reader has streamed its volume (or finished): a request every ~1-2 s, minutes of page-cache churn let (rb, st) = (read_bytes.clone(), stop.clone()); - phase("B-reader", &mut stack, &mut b, &move || rb.load(std::sync::atomic::Ordering::Relaxed) >= gib << 30 || st.load(std::sync::atomic::Ordering::Relaxed)); + phase("B-reader", &mut stack, &mut b, &move || { + rb.load(std::sync::atomic::Ordering::Relaxed) >= gib << 30 + || st.load(std::sync::atomic::Ordering::Relaxed) + }); stop.store(true, std::sync::atomic::Ordering::Relaxed); reader.join().expect("reader thread"); - eprintln!("MEM-READER the reader streamed {} GiB through the page cache", read_bytes.load(std::sync::atomic::Ordering::Relaxed) >> 30); + eprintln!( + "MEM-READER the reader streamed {} GiB through the page cache", + read_bytes.load(std::sync::atomic::Ordering::Relaxed) >> 30 + ); phase("C-after", &mut stack, &mut c, &|| true); NO_STOP.store(false, std::sync::atomic::Ordering::Relaxed); let mean = |v: &[f64]| v.iter().sum::() / v.len().max(1) as f64; - eprintln!("MEM-READER decode tok/s mean: A {:.2} B {:.2} C {:.2} (B/A {:.3})", mean(&a), mean(&b), mean(&c), mean(&b) / mean(&a).max(1e-9)); + eprintln!( + "MEM-READER decode tok/s mean: A {:.2} B {:.2} C {:.2} (B/A {:.3})", + mean(&a), + mean(&b), + mean(&c), + mean(&b) / mean(&a).max(1e-9) + ); print_report("reader-end"); } other => panic!("LELEKA_MEM_SCENARIO: inventory | soak | shed | reader | leak, not {other}"), @@ -820,13 +955,20 @@ fn original_serve_memory_smoke() { #[ignore = "needs the holder's inherited sealed KAR descriptor (LELEKA_STRA169_KAR_FD)"] fn memory_archive_guard_probe() { assert!(env::var("LELEKA_MEM_SMOKE").is_ok_and(|v| v == "yes"), "explicit memory smoke opt-in required"); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); let inherited = InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed"); let governor = crate::memory_governor::install(false, crate::settings::process()).expect("governor"); let started = std::time::Instant::now(); let report = crate::memory_governor::guard_archive(governor, &inherited); - eprintln!("PROBE guard result: {:?} in {:.1} s", report.as_ref().map(|_| "ok").map_err(|e| e.message.clone()), started.elapsed().as_secs_f64()); + eprintln!( + "PROBE guard result: {:?} in {:.1} s", + report.as_ref().map(|_| "ok").map_err(|e| e.message.clone()), + started.elapsed().as_secs_f64() + ); let secs = number("LELEKA_MEM_PROBE_SECS", 60); let mut last_in = None; for t in 0..secs { diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs index 061883b0..37906aa7 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_prefix_smoke.rs @@ -31,11 +31,11 @@ //! //! Run: `cargo test -p leleka-engine-qwen35-cuda -- --ignored --exact backend::original_serve_prefix_smoke::original_serve_prefix_cache_smoke`. use super::*; +use crate::qwen_forward::original_serve_stack::dbg_el; use crate::qwen_forward::{ original_serve_request::{ServeError, ServeRequest}, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, }; -use crate::qwen_forward::original_serve_stack::dbg_el; use std::env; fn required_path(name: &str) -> PathBuf { @@ -119,7 +119,8 @@ fn serve_one( cancel_probes: Option, cancel_rounds: Option, ) -> Result { - let request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, 0.0, vec![eos as i32]); + let request = + ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, 0.0, vec![eos as i32]); let started = std::time::Instant::now(); let first = std::cell::Cell::new(None::); let rounds = std::cell::Cell::new(0usize); @@ -164,16 +165,20 @@ fn original_serve_prefix_cache_smoke() { let mode = text("LELEKA_PFX_MODE", "prefix"); let scenario = text("LELEKA_PFX_SCENARIO", "grid"); let verify = text("LELEKA_PFX_VERIFY", "none"); - let (shared_n, sessions_n, turns_n) = (number("LELEKA_PFX_SHARED", 8000), number("LELEKA_PFX_SESSIONS", 3), number("LELEKA_PFX_TURNS", 3)); - let (start_n, grow_n, end_n) = (number("LELEKA_PFX_START", 2000), number("LELEKA_PFX_GROW", 2500), number("LELEKA_PFX_END", 40_000)); + let (shared_n, sessions_n, turns_n) = + (number("LELEKA_PFX_SHARED", 8000), number("LELEKA_PFX_SESSIONS", 3), number("LELEKA_PFX_TURNS", 3)); + let (start_n, grow_n, end_n) = + (number("LELEKA_PFX_START", 2000), number("LELEKA_PFX_GROW", 2500), number("LELEKA_PFX_END", 40_000)); let max_new = number("LELEKA_PFX_MAX_NEW", 16); let capacity = number("LELEKA_PFX_CAPACITY", 2048); let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 262_144); let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); let laptop = env::var("LELEKA_PFX_LAPTOP").is_ok_and(|v| v == "yes"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( @@ -187,9 +192,13 @@ fn original_serve_prefix_cache_smoke() { let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); let provenance = required_path("LELEKA_STRA169_KAR_PROVENANCE"); let inherited = match env::var_os("LELEKA_LAPTOP_KAR_FILE") { - Some(path) if laptop => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance).expect("read-only KAR admission failed"), + Some(path) if laptop => InheritedKarArchive::open_read_only_file(std::path::Path::new(&path), provenance) + .expect("read-only KAR admission failed"), _ => { - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); InheritedKarArchive::open(fd, provenance).expect("inherited KAR admission failed") } }; @@ -219,7 +228,10 @@ fn original_serve_prefix_cache_smoke() { let mut rng = Rng(0x5eed_1234_abcd_0001); let tok = |s: &str, special: bool| tokenizer.encode(s, special).expect("tokenization failed"); let t0 = std::time::Instant::now(); - let mut system = tok("<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search. Repository notes follow.\n", true); + let mut system = tok( + "<|im_start|>system\nYou are a coding agent. Tools: shell, apply_patch, read_file, search. Repository notes follow.\n", + true, + ); system.extend(filler(&tokenizer, &mut rng, 0, shared_n.saturating_sub(system.len() + 4))); system.extend(tok("<|im_end|>\n", true)); let mut sessions: Vec = Vec::new(); @@ -281,7 +293,12 @@ fn original_serve_prefix_cache_smoke() { "auto" => PrefixBudget::Auto, other => PrefixBudget::Bytes(other.parse::().expect("LELEKA_PFX_MIB: auto or MiB") << 20), }; - config.prefix = Some(PrefixConfig { budget, block_tokens: number("LELEKA_PFX_BLOCK", 0), laptop, ..PrefixConfig::auto() }); + config.prefix = Some(PrefixConfig { + budget, + block_tokens: number("LELEKA_PFX_BLOCK", 0), + laptop, + ..PrefixConfig::auto() + }); } "legacy" => {} "off" => config.conversation = None, @@ -289,7 +306,10 @@ fn original_serve_prefix_cache_smoke() { } config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); - eprintln!("PFX stack: capacity={capacity} kv_resident={resident} max_context={max_context} expert tier {:?}", config.expert_tier); + eprintln!( + "PFX stack: capacity={capacity} kv_resident={resident} max_context={max_context} expert tier {:?}", + config.expert_tier + ); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), @@ -364,9 +384,11 @@ fn original_serve_prefix_cache_smoke() { failed.push(format!("verify req {i}")); // localise: where the ids first differ, and whether each arm is repeatable on its own let at = served.tokens.iter().zip(&full.tokens).position(|(a, b)| a != b); - let cached_again = serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat cached read failed"); + let cached_again = + serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat cached read failed"); stack.prefix_bypass(true); - let full_again = serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat full read failed"); + let full_again = + serve_one(&mut stack, &prompt, max_new, eos, None, None).expect("repeat full read failed"); stack.prefix_bypass(false); eprintln!( "PFX-VERIFY-DIAG req={i} first_difference_at={at:?} cached_repeat_equal_cached={} (reused {}) full_repeat_equal_full={} cached_repeat_equal_full={}", @@ -393,9 +415,20 @@ fn original_serve_prefix_cache_smoke() { // ---- the pool protocol on the live cache ---- if let Some(summary) = stack.prefix_summary(512) { let json = serde_json::to_string(&summary).expect("summary json"); - eprintln!("PFX-POOL summary: namespace={} nodes={} blocks={} heads={} json_bytes={} truncated={}", summary.namespace, summary.nodes, summary.blocks, summary.heads.len(), json.len(), summary.truncated); + eprintln!( + "PFX-POOL summary: namespace={} nodes={} blocks={} heads={} json_bytes={} truncated={}", + summary.namespace, + summary.nodes, + summary.blocks, + summary.heads.len(), + json.len(), + summary.truncated + ); for s in 0..sessions_n { - let chain = crate::prefix_cache::chain(&sessions[s].prompt.iter().map(|&t| t as i32).collect::>(), summary.block_tokens as usize); + let chain = crate::prefix_cache::chain( + &sessions[s].prompt.iter().map(|&t| t as i32).collect::>(), + summary.block_tokens as usize, + ); let started = std::time::Instant::now(); let from_summary = summary.match_tokens(&chain); let query = stack.prefix_match(&chain).map_or(0, |m| m.cached_tokens); @@ -413,7 +446,10 @@ fn original_serve_prefix_cache_smoke() { if env::var("LELEKA_PFX_CANCEL").is_ok_and(|v| v == "yes") && mode == "prefix" { let s = 0usize; let mut next = sessions[s].prompt.clone(); - next.extend(tok("shell {\"cmd\": \"ls\"}<|im_end|>\n<|im_start|>user\n\n", true)); + next.extend(tok( + "shell {\"cmd\": \"ls\"}<|im_end|>\n<|im_start|>user\n\n", + true, + )); next.extend(filler(&tokenizer, &mut rng, 1, 3 * capacity.min(2048))); next.extend(tok("\n<|im_end|>\n<|im_start|>assistant\n", true)); let cancelled_prefill = serve_one(&mut stack, &next, max_new, eos, Some(3), None); @@ -433,7 +469,8 @@ fn original_serve_prefix_cache_smoke() { } // a switch to another session right after a cancelled request let other = sessions[1 % sessions_n].prompt.clone(); - let switched = serve_one(&mut stack, &other, max_new, eos, None, None).expect("switch after cancellation failed"); + let switched = + serve_one(&mut stack, &other, max_new, eos, None, None).expect("switch after cancellation failed"); eprintln!("PFX-CANCEL switch reused={} out={}", switched.reused, ids(&switched.tokens)); } if let Some(line) = stack.prefix_metrics() { diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs index a3167f30..7053abe3 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_smoke.rs @@ -24,13 +24,13 @@ //! Run: `cargo test -p leleka-engine-qwen35-cuda --features cuda-driver -- --ignored original_serve_smoke`. //! While the verifier window producers listed in `UNBOUND_PRODUCERS` are unbound the stack refuses to open //! with the first missing producer's name; that refusal is the expected result of this smoke until they land. +use super::super::qwen_forward::original_serve_stack::dbg_el; use super::*; use crate::qwen_forward::{ original_serve_request::{ServeError, ServeRequest}, original_serve_stack::{OriginalServeStack, StackConfig}, }; use std::env; -use super::super::qwen_forward::original_serve_stack::dbg_el; const PROMPT: &str = "The capital of France is Paris. The capital of Germany is Berlin. The capital of Italy is"; @@ -38,14 +38,28 @@ fn required_path(name: &str) -> PathBuf { env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned smoke input {name}")) } -fn request(prompt: &[u32], max_new: usize, sampler: Option<&leleka_sampler_ref::SamplerParams>, eos: u32) -> ServeRequest { - ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, sampler, 7, 0.0, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)) +fn request( + prompt: &[u32], + max_new: usize, + sampler: Option<&leleka_sampler_ref::SamplerParams>, + eos: u32, +) -> ServeRequest { + ServeRequest::new( + prompt.iter().map(|&t| t as i32).collect(), + max_new, + sampler, + 7, + 0.0, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ) } fn report_timing(stack: &OriginalServeStack<'_, '_>, label: &str, produced: usize) { let (prompt_ms, decode_ms) = stack.last_timing(); let rate = if decode_ms > 0.0 { produced as f64 * 1e3 / decode_ms } else { 0.0 }; - eprintln!("DBG timing {label}: prompt {prompt_ms:.1} ms, decode {decode_ms:.1} ms, produced {produced}, decode {rate:.2} tok/s"); + eprintln!( + "DBG timing {label}: prompt {prompt_ms:.1} ms, decode {decode_ms:.1} ms, produced {produced}, decode {rate:.2} tok/s" + ); if let Some(stats) = stack.expert_tier_stats() { eprintln!("DBG timing {label}: {}", stats.describe()); } @@ -59,9 +73,14 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), "explicit Original serve smoke opt-in required" ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( @@ -73,7 +92,8 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { ) .expect("verified tokenizer construction failed"); let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -84,12 +104,14 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { eprintln!("DBG[{:.0}s] smoke: binding ready, loading resident expert source", dbg_el()); let resident = binding.load_resident_expert_source().expect("resident expert source load failed"); eprintln!("DBG[{:.0}s] smoke: resident expert source loaded: {resident:?}", dbg_el()); - let budget_gib: usize = env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); + let budget_gib: usize = + env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); - let mut config = StackConfig::new(env::var("LELEKA_SMOKE_MAX_CONTEXT").ok().and_then(|v| v.parse().ok()).unwrap_or(4096)); + let mut config = + StackConfig::new(env::var("LELEKA_SMOKE_MAX_CONTEXT").ok().and_then(|v| v.parse().ok()).unwrap_or(4096)); config.capacity = env::var("LELEKA_ORIGINAL_SERVE_CAPACITY").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); if let Some(cells) = env::var("LELEKA_ORIGINAL_SERVE_KV_RESIDENT").ok().and_then(|v| v.parse().ok()) { @@ -108,16 +130,23 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { let same = |label: &str, a: &[i32], b: &[i32]| { if tier_on { let first = a.iter().zip(b).position(|(x, y)| x != y); - eprintln!("DBG smoke: {label}: {} (expert tier on: residency changes between requests)", match first { - None if a.len() == b.len() => "identical".to_owned(), - None => format!("lengths {} vs {}", a.len(), b.len()), - Some(i) => format!("first difference at token {i}"), - }); + eprintln!( + "DBG smoke: {label}: {} (expert tier on: residency changes between requests)", + match first { + None if a.len() == b.len() => "identical".to_owned(), + None => format!("lengths {} vs {}", a.len(), b.len()), + Some(i) => format!("first difference at token {i}"), + } + ); } else { assert_eq!(a, b, "{label}"); } }; - eprintln!("DBG[{:.0}s] smoke: opening serve stack (budget {budget_gib} GiB, capacity {})", dbg_el(), config.capacity); + eprintln!( + "DBG[{:.0}s] smoke: opening serve stack (budget {budget_gib} GiB, capacity {})", + dbg_el(), + config.capacity + ); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), @@ -134,10 +163,14 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { for _ in 0..2 { let mut tokens = Vec::new(); let outcome = stack - .serve(&request(&prompt, 24, None, eos), &mut |round| { - tokens.extend_from_slice(round); - Ok(()) - }, &mut || false) + .serve( + &request(&prompt, 24, None, eos), + &mut |round| { + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) .unwrap_or_else(|e| panic!("greedy request failed: {e:?}")); assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); assert_eq!(outcome.produced, tokens.len()); @@ -167,28 +200,40 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { }; let mut sampled = Vec::new(); stack - .serve(&request(&prompt, 16, Some(&sampler), eos), &mut |round| { - sampled.extend_from_slice(round); - Ok(()) - }, &mut || false) + .serve( + &request(&prompt, 16, Some(&sampler), eos), + &mut |round| { + sampled.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) .unwrap_or_else(|e| panic!("sampled request failed: {e:?}")); eprintln!("DBG[{:.0}s] smoke: sampled tokens ({}): {:?}", dbg_el(), sampled.len(), sampled); assert!(!sampled.is_empty()); // 3. cancellation after the first committed round returns Cancelled and leaves the stack usable let emitted = std::cell::Cell::new(0usize); - let cancelled = stack.serve(&request(&prompt, 64, None, eos), &mut |round| { - emitted.set(emitted.get() + round.len()); - Ok(()) - }, &mut || emitted.get() > 0); + let cancelled = stack.serve( + &request(&prompt, 64, None, eos), + &mut |round| { + emitted.set(emitted.get() + round.len()); + Ok(()) + }, + &mut || emitted.get() > 0, + ); assert_eq!(cancelled.err(), Some(ServeError::Cancelled)); assert_eq!(stack.health(), None); let mut after = Vec::new(); stack - .serve(&request(&prompt, 24, None, eos), &mut |round| { - after.extend_from_slice(round); - Ok(()) - }, &mut || false) + .serve( + &request(&prompt, 24, None, eos), + &mut |round| { + after.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) .unwrap_or_else(|e| panic!("request after a cancellation failed: {e:?}")); same("a cancelled request must not disturb the next one", &after, &runs[0]); @@ -226,11 +271,28 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { for (k, &index) in order.iter().enumerate() { let ids = &prompts[index]; if rep == 0 { - eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::>().join(",")); + eprintln!( + "DBG corpus {index} prompt_ids ({}): {}", + ids.len(), + ids.iter().map(|t| t.to_string()).collect::>().join(",") + ); } for arm in super::original_serve_arms::arms_for(&arms, k + rep) { - let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, None, 7, min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)); - super::original_serve_arms::serve_arm(&mut stack, &arm, &corpus_request, &format!("p{index} rep{rep}"), &format!("prompt={}", ids.len())); + let corpus_request = ServeRequest::new( + ids.iter().map(|&t| t as i32).collect(), + max_new, + None, + 7, + min_p, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ); + super::original_serve_arms::serve_arm( + &mut stack, + &arm, + &corpus_request, + &format!("p{index} rep{rep}"), + &format!("prompt={}", ids.len()), + ); } } } @@ -260,7 +322,11 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { line.to_owned() }; let ids = tokenizer.encode(&turn, true).expect("corpus tokenization failed"); - eprintln!("DBG corpus {index} prompt_ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::>().join(",")); + eprintln!( + "DBG corpus {index} prompt_ids ({}): {}", + ids.len(), + ids.iter().map(|t| t.to_string()).collect::>().join(",") + ); // LELEKA_SMOKE_FORCE_DIR=dir (quality gate, docs/quality-gate.md): `dir/c.truth` is the comma-separated // token list of this prompt followed by the tokens another engine produced for it. The first // LELEKA_SMOKE_FORCE_PASSES (default 1) passes of this prompt decode along that text (teacher forcing: the @@ -269,14 +335,17 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { let truth: Option> = env::var_os("LELEKA_SMOKE_FORCE_DIR").and_then(|dir| { let file = std::path::Path::new(&dir).join(format!("c{index}.truth")); let text = std::fs::read_to_string(&file).ok()?; - let sequence: Vec = text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect(); + let sequence: Vec = + text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect(); assert!( sequence.len() > ids.len() && sequence[..ids.len()].iter().zip(&ids).all(|(a, &b)| *a == b as i32), - "{}: the forced sequence must start with the tokenized prompt and extend it", file.display() + "{}: the forced sequence must start with the tokenized prompt and extend it", + file.display() ); Some(sequence) }); - let forced_passes: usize = env::var("LELEKA_SMOKE_FORCE_PASSES").ok().and_then(|v| v.parse().ok()).unwrap_or(1); + let forced_passes: usize = + env::var("LELEKA_SMOKE_FORCE_PASSES").ok().and_then(|v| v.parse().ok()).unwrap_or(1); for pass in 0..repeat { if !spec_arms.is_empty() { assert!(stack.select_spec_arm(&spec_arms[(pass + index) % spec_arms.len()])); @@ -286,40 +355,89 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { eprintln!("DBG corpus {index} pass={pass} begin forced={}", forced.is_some()); let max_new = forced.map_or(max_new, |t| t.len() - ids.len()); let mut out = Vec::new(); - let min_p: f32 = stack.spec_arm_min_p().unwrap_or_else(|| env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0)); + let min_p: f32 = stack + .spec_arm_min_p() + .unwrap_or_else(|| env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0)); // LELEKA_SMOKE_SAMPLED=1: the corpus is served with the sampling head and a penalty window (an agent-style // request: temperature 0.7, top-k 20, top-p 0.95, repeat penalty 1.1 over 64, fixed seed) instead of greedy. let sampled = env::var("LELEKA_SMOKE_SAMPLED").is_ok_and(|v| v == "1"); let sampler = leleka_sampler_ref::SamplerParams { - top_k: 20, top_p: 0.95, min_p: 0.0, temperature: 0.7, min_keep: 1, penalty_last_n: 64, penalty_repeat: 1.1, - penalty_freq: 0.0, penalty_present: 0.0, seed: 1234, counter: 0, greedy: false, + top_k: 20, + top_p: 0.95, + min_p: 0.0, + temperature: 0.7, + min_keep: 1, + penalty_last_n: 64, + penalty_repeat: 1.1, + penalty_freq: 0.0, + penalty_present: 0.0, + seed: 1234, + counter: 0, + greedy: false, }; - let corpus_request = ServeRequest::new(ids.iter().map(|&t| t as i32).collect(), max_new, sampled.then_some(&sampler), 7, min_p, crate::qwen_forward::original_serve_request::original_stop_tokens(eos)); + let corpus_request = ServeRequest::new( + ids.iter().map(|&t| t as i32).collect(), + max_new, + sampled.then_some(&sampler), + 7, + min_p, + crate::qwen_forward::original_serve_request::original_stop_tokens(eos), + ); let started = std::time::Instant::now(); let mut first: Option = None; - let served = stack.serve(&corpus_request, &mut |round| { - if first.is_none() { first = Some(started.elapsed()); } - out.extend_from_slice(round); - Ok(()) - }, &mut || false); + let served = stack.serve( + &corpus_request, + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); let total = started.elapsed(); crate::qwen_forward::quality_force::set(None); if let (Some(t), Ok(_)) = (forced, &served) { - eprintln!("DBG corpus {index} pass={pass} forced: produced {} of {} forced tokens, stopped as forced: {}", out.len(), t.len() - ids.len(), - out.iter().zip(&t[ids.len()..]).all(|(a, b)| a == b)); + eprintln!( + "DBG corpus {index} pass={pass} forced: produced {} of {} forced tokens, stopped as forced: {}", + out.len(), + t.len() - ids.len(), + out.iter().zip(&t[ids.len()..]).all(|(a, b)| a == b) + ); } match served { Ok(outcome) => { if pass == 0 && spec_arms.is_empty() { - eprintln!("DBG corpus {index} output ({} tokens, rounds {}): {}", out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::>().join(" ")); + eprintln!( + "DBG corpus {index} output ({} tokens, rounds {}): {}", + out.len(), + outcome.rounds, + out.iter().map(|t| t.to_string()).collect::>().join(" ") + ); } else { - eprintln!("DBG corpus {index} output pass={pass} arm={} ({} tokens, rounds {}): {}", stack.spec_arm(), out.len(), outcome.rounds, out.iter().map(|t| t.to_string()).collect::>().join(" ")); + eprintln!( + "DBG corpus {index} output pass={pass} arm={} ({} tokens, rounds {}): {}", + stack.spec_arm(), + out.len(), + outcome.rounds, + out.iter().map(|t| t.to_string()).collect::>().join(" ") + ); } let ttft = first.unwrap_or(total); let decode_s = (total - ttft).as_secs_f64(); - let decode_tps = if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 }; - eprintln!("DBG corpus {index} timing pass={pass} arm={} prompt={} produced={} rounds={} ttft_ms={:.1} total_ms={:.1} decode_tok_s={:.2}", - stack.spec_arm(), ids.len(), out.len(), outcome.rounds, ttft.as_secs_f64() * 1e3, total.as_secs_f64() * 1e3, decode_tps); + let decode_tps = + if out.len() > 1 && decode_s > 0.0 { (out.len() - 1) as f64 / decode_s } else { 0.0 }; + eprintln!( + "DBG corpus {index} timing pass={pass} arm={} prompt={} produced={} rounds={} ttft_ms={:.1} total_ms={:.1} decode_tok_s={:.2}", + stack.spec_arm(), + ids.len(), + out.len(), + outcome.rounds, + ttft.as_secs_f64() * 1e3, + total.as_secs_f64() * 1e3, + decode_tps + ); report_timing(&stack, &format!("corpus {index} pass {pass}"), out.len()); } Err(e) => eprintln!("DBG corpus {index} pass={pass} FAILED {e:?} health={:?}", stack.health()), @@ -330,8 +448,20 @@ fn original_serve_smoke_prompt_decode_mtp_verify_commit_reset_cancel_sample() { // 4. a short prompt (<= 64 tokens) takes the scalar draft-KV path of the Original; report instead of asserting eprintln!("DBG[{:.0}s] smoke: short-prompt request ({} tokens)", dbg_el(), short_prompt.len()); let mut short_out = Vec::new(); - match stack.serve(&request(&short_prompt, 16, None, eos), &mut |round| { short_out.extend_from_slice(round); Ok(()) }, &mut || false) { - Ok(outcome) => eprintln!("DBG[{:.0}s] smoke: short prompt ok produced={} tokens={:?}", dbg_el(), outcome.produced, short_out), + match stack.serve( + &request(&short_prompt, 16, None, eos), + &mut |round| { + short_out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) { + Ok(outcome) => eprintln!( + "DBG[{:.0}s] smoke: short prompt ok produced={} tokens={:?}", + dbg_el(), + outcome.produced, + short_out + ), Err(e) => eprintln!("DBG[{:.0}s] smoke: short prompt FAILED {e:?} health={:?}", dbg_el(), stack.health()), } stack.close().expect("stack cleanup failed"); @@ -370,16 +500,26 @@ fn original_serve_long_context_streamed_kv_smoke() { }; // one prompt length, or a comma-separated list served in order on the same stack let targets: Vec = env::var("LELEKA_ORIGINAL_SERVE_LONG_TOKENS") - .map(|v| v.split(',').map(|t| t.trim().parse().expect("LELEKA_ORIGINAL_SERVE_LONG_TOKENS must be counts")).collect()) + .map(|v| { + v.split(',').map(|t| t.trim().parse().expect("LELEKA_ORIGINAL_SERVE_LONG_TOKENS must be counts")).collect() + }) .unwrap_or_else(|_| vec![40_000]); let target = targets.iter().copied().max().expect("at least one prompt length"); let resident = number("LELEKA_ORIGINAL_SERVE_KV_RESIDENT", 20_480); let max_context = number("LELEKA_ORIGINAL_SERVE_MAX_CONTEXT", 65_536); let max_new = number("LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW", 32); - assert!(targets.iter().all(|&t| t >= 64) && target + max_new + 8 <= max_context, "the prompt and the answer must fit the ceiling"); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + assert!( + targets.iter().all(|&t| t >= 64) && target + max_new + 8 <= max_context, + "the prompt and the answer must fit the ceiling" + ); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( @@ -391,7 +531,8 @@ fn original_serve_long_context_streamed_kv_smoke() { ) .expect("verified tokenizer construction failed"); let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -477,116 +618,155 @@ fn original_serve_long_context_streamed_kv_smoke() { Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), }; for prompt in &prompts { - let prompt = prompt.as_slice(); - eprintln!("long-smoke prompt tokens={} kv-resident={resident} max-context={max_context}", prompt.len()); - // LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt.ids` (comma-separated) for the Original's - // `--tokens-file`, so both engines read the identical token sequence - if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") { - let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len())); - let text = prompt.iter().map(|t| t.to_string()).collect::>().join(","); - std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); - eprintln!("long-smoke prompt ids -> {}", path.display()); - } - // LELEKA_ORIGINAL_SERVE_LONG_ARMS (see backend_original_serve_arms.rs): the prompt once per arm from a first-request - // tier state, the order reversed on odd passes (`repeat` passes); replaces the plain passes below. - if let Ok(arms) = env::var("LELEKA_ORIGINAL_SERVE_LONG_ARMS") { - let arms = super::original_serve_arms::parse_arms(&arms); - for pass in 0..repeat { - for arm in super::original_serve_arms::arms_for(&arms, pass) { - super::original_serve_arms::serve_arm(&mut stack, &arm, &request(prompt, max_new, None, eos), &format!("long pass{pass}"), &format!("prompt={}", prompt.len())); + let prompt = prompt.as_slice(); + eprintln!("long-smoke prompt tokens={} kv-resident={resident} max-context={max_context}", prompt.len()); + // LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR: write the prompt as `prompt.ids` (comma-separated) for the Original's + // `--tokens-file`, so both engines read the identical token sequence + if let Some(dir) = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_IDS_DIR") { + let path = PathBuf::from(dir).join(format!("prompt{}.ids", prompt.len())); + let text = prompt.iter().map(|t| t.to_string()).collect::>().join(","); + std::fs::write(&path, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + eprintln!("long-smoke prompt ids -> {}", path.display()); + } + // LELEKA_ORIGINAL_SERVE_LONG_ARMS (see backend_original_serve_arms.rs): the prompt once per arm from a first-request + // tier state, the order reversed on odd passes (`repeat` passes); replaces the plain passes below. + if let Ok(arms) = env::var("LELEKA_ORIGINAL_SERVE_LONG_ARMS") { + let arms = super::original_serve_arms::parse_arms(&arms); + for pass in 0..repeat { + for arm in super::original_serve_arms::arms_for(&arms, pass) { + super::original_serve_arms::serve_arm( + &mut stack, + &arm, + &request(prompt, max_new, None, eos), + &format!("long pass{pass}"), + &format!("prompt={}", prompt.len()), + ); + } } + continue; } - continue; - } - // LELEKA_SPEC_ARMS: pass p of the prompt is served by arm p % arms (the window policy A/B inside one load); - // LELEKA_SMOKE_MIN_P: the request's draft floor (default 0). - let spec_arms = stack.spec_arms(); - let spec_min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0); - // LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer.ids` (comma-separated) holds the tokens - // another engine answered to the N-token prompt; the request then decodes along that text (teacher forcing, see - // `quality_force`) for exactly that many tokens, with the port's own logits and `LELEKA_TRACE_LOGPROBS` rows. - let forced_answer: Option> = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR").and_then(|dir| { - let text = std::fs::read_to_string(PathBuf::from(dir).join(format!("answer{}.ids", prompt.len()))).ok()?; - Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect()) - }); - let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len()); - // LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process) - let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ") - .map(|v| v.split(',').filter_map(|t| { - let mut parts = t.trim().splitn(2, ':'); - Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0))) - }).collect()).unwrap_or_default(); - // LELEKA_QSA_LATE_SEQ=1,0,0,1: the QSA late-selection kernels per pass (paired A/B inside one process) - let late_seq: Vec = env::var("LELEKA_QSA_LATE_SEQ") - .map(|v| v.split(',').filter_map(|t| t.trim().parse().ok()).collect()).unwrap_or_default(); - for pass in 0..repeat { - if !late_seq.is_empty() { - let v = late_seq[pass % late_seq.len()]; - leleka_cuda_driver::set_qsa_late_override(v); - eprintln!("long-smoke pass={pass} qsa_late={v}"); + // LELEKA_SPEC_ARMS: pass p of the prompt is served by arm p % arms (the window policy A/B inside one load); + // LELEKA_SMOKE_MIN_P: the request's draft floor (default 0). + let spec_arms = stack.spec_arms(); + let spec_min_p: f32 = env::var("LELEKA_SMOKE_MIN_P").ok().and_then(|v| v.parse().ok()).unwrap_or(0.0); + // LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR (quality gate, docs/quality-gate.md): `answer.ids` (comma-separated) holds the tokens + // another engine answered to the N-token prompt; the request then decodes along that text (teacher forcing, see + // `quality_force`) for exactly that many tokens, with the port's own logits and `LELEKA_TRACE_LOGPROBS` rows. + let forced_answer: Option> = env::var_os("LELEKA_ORIGINAL_SERVE_LONG_FORCE_DIR").and_then(|dir| { + let text = std::fs::read_to_string(PathBuf::from(dir).join(format!("answer{}.ids", prompt.len()))).ok()?; + Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect()) + }); + let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len()); + // LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process) + let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ") + .map(|v| { + v.split(',') + .filter_map(|t| { + let mut parts = t.trim().splitn(2, ':'); + Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0))) + }) + .collect() + }) + .unwrap_or_default(); + // LELEKA_QSA_LATE_SEQ=1,0,0,1: the QSA late-selection kernels per pass (paired A/B inside one process) + let late_seq: Vec = env::var("LELEKA_QSA_LATE_SEQ") + .map(|v| v.split(',').filter_map(|t| t.trim().parse().ok()).collect()) + .unwrap_or_default(); + for pass in 0..repeat { + if !late_seq.is_empty() { + let v = late_seq[pass % late_seq.len()]; + leleka_cuda_driver::set_qsa_late_override(v); + eprintln!("long-smoke pass={pass} qsa_late={v}"); + } + crate::qwen_forward::quality_force::set( + forced_answer + .as_ref() + .map(|answer| prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect()), + ); + if !stream_seq.is_empty() { + let (v, depth) = stream_seq[pass % stream_seq.len()]; + leleka_cuda_driver::compute_drain::set_issue_depth(depth); + // bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight + crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE + .store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed); + leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0); + eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}"); + } + if !spec_arms.is_empty() { + assert!(stack.select_spec_arm(&spec_arms[pass % spec_arms.len()])); + } + let started = std::time::Instant::now(); + let mut tokens = Vec::new(); + let long_request = ServeRequest::new( + prompt.iter().map(|&t| t as i32).collect(), + max_new, + None, + 7, + spec_min_p, + vec![eos as i32], + ); + let outcome = stack + .serve( + &long_request, + &mut |round| { + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) + .unwrap_or_else(|e| panic!("long-context request failed: {e:?} health={:?}", stack.health())); + crate::qwen_forward::quality_force::set(None); + assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); + assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); + assert_eq!(stack.health(), None); + let (prompt_ms, decode_ms) = stack.last_timing(); + eprintln!( + "long-smoke prefill pass={pass} arm={} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} decode_ms={decode_ms:.1}", + stack.spec_arm(), + prompt.len(), + (prompt.len() - 1) as f64 / (prompt_ms / 1e3).max(1e-9) + ); + let ids: Vec = tokens.iter().map(|&t| t as u32).collect(); + let text = tokenizer.decode(&ids).unwrap_or_default(); + eprintln!( + "long-smoke output ids ({}): {}", + ids.len(), + ids.iter().map(|t| t.to_string()).collect::>().join(",") + ); + eprintln!( + "long-smoke result pass={pass} prompt={} resident={resident} produced={} rounds={} wall_s={:.1} needle_found={} text={text:?}", + prompt.len(), + outcome.produced, + outcome.rounds, + started.elapsed().as_secs_f64(), + text.contains("4817") + ); } - crate::qwen_forward::quality_force::set(forced_answer.as_ref().map(|answer| { - prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect() - })); - if !stream_seq.is_empty() { - let (v, depth) = stream_seq[pass % stream_seq.len()]; - leleka_cuda_driver::compute_drain::set_issue_depth(depth); - // bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight - crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE.store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed); - leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0); - eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}"); - } - if !spec_arms.is_empty() { - assert!(stack.select_spec_arm(&spec_arms[pass % spec_arms.len()])); - } - let started = std::time::Instant::now(); - let mut tokens = Vec::new(); - let long_request = ServeRequest::new(prompt.iter().map(|&t| t as i32).collect(), max_new, None, 7, spec_min_p, vec![eos as i32]); - let outcome = stack - .serve(&long_request, &mut |round| { - tokens.extend_from_slice(round); - Ok(()) - }, &mut || false) - .unwrap_or_else(|e| panic!("long-context request failed: {e:?} health={:?}", stack.health())); - crate::qwen_forward::quality_force::set(None); - assert!(outcome.rounds >= 1 && !tokens.is_empty(), "no committed round"); - assert!(tokens.iter().all(|&t| (0..248_320).contains(&t))); - assert_eq!(stack.health(), None); - let (prompt_ms, decode_ms) = stack.last_timing(); - eprintln!( - "long-smoke prefill pass={pass} arm={} prompt={} prompt_ms={prompt_ms:.1} prefill_tok_s={:.1} decode_ms={decode_ms:.1}", - stack.spec_arm(), - prompt.len(), - (prompt.len() - 1) as f64 / (prompt_ms / 1e3).max(1e-9) - ); - let ids: Vec = tokens.iter().map(|&t| t as u32).collect(); - let text = tokenizer.decode(&ids).unwrap_or_default(); - eprintln!("long-smoke output ids ({}): {}", ids.len(), ids.iter().map(|t| t.to_string()).collect::>().join(",")); - eprintln!( - "long-smoke result pass={pass} prompt={} resident={resident} produced={} rounds={} wall_s={:.1} needle_found={} text={text:?}", - prompt.len(), - outcome.produced, - outcome.rounds, - started.elapsed().as_secs_f64(), - text.contains("4817") - ); - } } stack.close().expect("stack cleanup failed"); Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); } /// One greedy request; returns (tokens, time to the first committed round in ms, total ms, reused tokens). -fn timed(stack: &mut OriginalServeStack<'_, '_>, prompt: &[u32], max_new: usize, eos: u32) -> (Vec, f64, f64, usize) { +fn timed( + stack: &mut OriginalServeStack<'_, '_>, + prompt: &[u32], + max_new: usize, + eos: u32, +) -> (Vec, f64, f64, usize) { let started = std::time::Instant::now(); let mut first: Option = None; let mut tokens = Vec::new(); let outcome = stack - .serve(&request(prompt, max_new, None, eos), &mut |round| { - first.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1e3); - tokens.extend_from_slice(round); - Ok(()) - }, &mut || false) + .serve( + &request(prompt, max_new, None, eos), + &mut |round| { + first.get_or_insert_with(|| started.elapsed().as_secs_f64() * 1e3); + tokens.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ) .unwrap_or_else(|e| { eprintln!("CONV FAILED n={} error={e:?} health={:?}", prompt.len(), stack.health()); panic!("conversation smoke request failed: {e:?}") @@ -611,9 +791,14 @@ fn original_serve_conversation_smoke_resume_matches_a_full_read() { env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), "explicit Original serve smoke opt-in required" ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( @@ -625,7 +810,8 @@ fn original_serve_conversation_smoke_resume_matches_a_full_read() { ) .expect("verified tokenizer construction failed"); let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -634,7 +820,8 @@ fn original_serve_conversation_smoke_resume_matches_a_full_read() { ) .expect("actual pinned KAR+MTP binding failed"); binding.load_resident_expert_source().expect("resident expert source load failed"); - let budget_gib: usize = env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); + let budget_gib: usize = + env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); @@ -672,9 +859,15 @@ fn original_serve_conversation_smoke_resume_matches_a_full_read() { let next_turn = "<|im_end|>\n<|im_start|>user\nAnd the capital of Spain?<|im_end|>\n<|im_start|>assistant\n"; second.extend(tokenizer.encode(next_turn, true).expect("second turn")); let (cached, ttft_b, total_b, reused_b) = timed(&mut stack, &second, max_new, eos); - eprintln!("CONV B(cache) n={} reused={reused_b} ttft={ttft_b:.1}ms total={total_b:.1}ms out={cached:?}", second.len()); + eprintln!( + "CONV B(cache) n={} reused={reused_b} ttft={ttft_b:.1}ms total={total_b:.1}ms out={cached:?}", + second.len() + ); if cache { - assert!(reused_b > 0 || env::var_os("STRATA_CKPT_REREAD").is_some(), "the second turn must resume from a checkpoint"); + assert!( + reused_b > 0 || env::var_os("STRATA_CKPT_REREAD").is_some(), + "the second turn must resume from a checkpoint" + ); } else { assert_eq!(reused_b, 0, "nothing is reused with the cache off"); } @@ -683,7 +876,10 @@ fn original_serve_conversation_smoke_resume_matches_a_full_read() { // 3. the same second request read from the empty prompt stack.forget_conversation(); let (full, ttft_f, total_f, reused_f) = timed(&mut stack, &second, max_new, eos); - eprintln!("CONV B(full) n={} reused={reused_f} ttft={ttft_f:.1}ms total={total_f:.1}ms out={full:?}", second.len()); + eprintln!( + "CONV B(full) n={} reused={reused_f} ttft={ttft_f:.1}ms total={total_f:.1}ms out={full:?}", + second.len() + ); assert_eq!(reused_f, 0); eprintln!("CONV greedy equal: {} ttft cache/full: {ttft_b:.1}/{ttft_f:.1} ms", cached == full); @@ -742,7 +938,12 @@ fn serve_once( ); result.map(|outcome| { assert_eq!(outcome.produced, tokens.len()); - Served { tokens, ttft: first.get().unwrap_or(f64::NAN), reused: stack.reused_tokens(), resume: stack.resume_point() } + Served { + tokens, + ttft: first.get().unwrap_or(f64::NAN), + reused: stack.reused_tokens(), + resume: stack.resume_point(), + } }) } @@ -755,9 +956,14 @@ fn with_stack( env::var("LELEKA_ORIGINAL_SERVE_SMOKE").is_ok_and(|value| value == "yes"), "explicit Original serve smoke opt-in required" ); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( @@ -769,7 +975,8 @@ fn with_stack( ) .expect("verified tokenizer construction failed"); let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -778,7 +985,8 @@ fn with_stack( ) .expect("actual pinned KAR+MTP binding failed"); binding.load_resident_expert_source().expect("resident expert source load failed"); - let budget_gib: usize = env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); + let budget_gib: usize = + env::var("LELEKA_ORIGINAL_SERVE_BUDGET_GIB").ok().and_then(|v| v.parse().ok()).unwrap_or(28); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); let context = Rc::new(device.create_context(budget_gib << 30).expect("bounded Context unavailable")); @@ -804,8 +1012,11 @@ fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option, every: u use crate::backend::original_prompt::{PromptOptions, PromptPath, PromptPlan}; let options = PromptOptions { short_read: 64, force_batched: true, ..PromptOptions::original_mode17(16_384) }; let options = if cache { - crate::qwen_forward::original_serve_stack::ConversationConfig { prompt_cache_every: every, ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() } - .plan_options(options) + crate::qwen_forward::original_serve_stack::ConversationConfig { + prompt_cache_every: every, + ..crate::qwen_forward::original_serve_stack::ConversationConfig::original() + } + .plan_options(options) } else { PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..options } }; @@ -818,7 +1029,8 @@ fn same_chunks(prompt: &[u32], resume: usize, reread_to: Option, every: u let full = cuts(0, None); let read = cuts(resume, reread_to); let from = read.first().map_or(prompt.len(), |a| a.0); - full.iter().filter(|a| a.0 >= from).copied().collect::>() == read && full.iter().all(|a| a.0 >= from || a.0 + a.1 <= from) + full.iter().filter(|a| a.0 >= from).copied().collect::>() == read + && full.iter().all(|a| a.0 >= from || a.0 + a.1 <= from) } fn ids(tokens: &[i32]) -> String { @@ -852,8 +1064,12 @@ fn original_serve_conversation_coverage_smoke() { }); let max_new: usize = env::var("LELEKA_CONVERSATION_MAX_NEW").ok().and_then(|v| v.parse().ok()).unwrap_or(48); let repeat: usize = env::var("LELEKA_CONVERSATION_SYSTEM_REPEAT").ok().and_then(|v| v.parse().ok()).unwrap_or(250); - let cancel_probes: usize = env::var("LELEKA_CONVERSATION_CANCEL_PROBES").ok().and_then(|v| v.parse().ok()).unwrap_or(4); - eprintln!("CONV cache={} reread={reread} every={every} max_new={max_new} repeat={repeat}", if cache { "on" } else { "off" }); + let cancel_probes: usize = + env::var("LELEKA_CONVERSATION_CANCEL_PROBES").ok().and_then(|v| v.parse().ok()).unwrap_or(4); + eprintln!( + "CONV cache={} reread={reread} every={every} max_new={max_new} repeat={repeat}", + if cache { "on" } else { "off" } + ); let mut failed: Vec<&'static str> = Vec::new(); with_stack(conversation, |stack, tokenizer, eos| { let mut check = |name: &'static str, ok: bool| { @@ -876,7 +1092,13 @@ fn original_serve_conversation_coverage_smoke() { let greedy = |stack: &mut OriginalServeStack<'_, '_>, prompt: &[u32], what: &str| -> Served { let served = serve_once(stack, prompt, max_new, None, eos, None, None) .unwrap_or_else(|e| panic!("CONV {what} failed: {e:?} health={:?}", stack.health())); - eprintln!("CONV {what} n={} reused={} ttft={:.1}ms out={}", prompt.len(), served.reused, served.ttft, ids(&served.tokens)); + eprintln!( + "CONV {what} n={} reused={} ttft={:.1}ms out={}", + prompt.len(), + served.reused, + served.ttft, + ids(&served.tokens) + ); served }; let system = format!("{PROMPT} ").repeat(repeat); @@ -903,11 +1125,25 @@ fn original_serve_conversation_coverage_smoke() { } stack.forget_conversation(); let p_full = greedy(stack, &p, "P(full)"); - if same_chunks(&p, p_cached.resume, (reread && p_cached.resume > 0).then_some(p_cached.resume), every, cache) { strict += usize::from(p_cached.resume > 0); check("periodic_equal", p_cached.tokens == p_full.tokens); } else { eprintln!("CONV-INFO periodic_equal: different prefill chunks than the full read (equal={})", p_cached.tokens == p_full.tokens); } + if same_chunks(&p, p_cached.resume, (reread && p_cached.resume > 0).then_some(p_cached.resume), every, cache) { + strict += usize::from(p_cached.resume > 0); + check("periodic_equal", p_cached.tokens == p_full.tokens); + } else { + eprintln!( + "CONV-INFO periodic_equal: different prefill chunks than the full read (equal={})", + p_cached.tokens == p_full.tokens + ); + } // 3. fallback: the follow-up edits the earlier user turn (it does NOT extend the previous prompt) - let reply = tokenizer.decode(&p_full.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos).collect::>()).unwrap_or_default(); - let follow = encode(&chat(&edited, &[("Name three other European capitals.", reply.as_str())], "And the capital of Spain?")); + let reply = tokenizer + .decode(&p_full.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos).collect::>()) + .unwrap_or_default(); + let follow = encode(&chat( + &edited, + &[("Name three other European capitals.", reply.as_str())], + "And the capital of Spain?", + )); let f_cached = greedy(stack, &follow, "F(root fallback)"); if resumes { // the edited user turn starts right after the root (the first turn boundary past the system prompt) @@ -915,7 +1151,21 @@ fn original_serve_conversation_coverage_smoke() { } stack.forget_conversation(); let f_full = greedy(stack, &follow, "F(full)"); - if same_chunks(&follow, f_cached.resume, (reread && f_cached.resume > 0).then_some(f_cached.resume), every, cache) { strict += usize::from(f_cached.resume > 0); check("fallback_equal", f_cached.tokens == f_full.tokens); } else { eprintln!("CONV-INFO fallback_equal: different prefill chunks than the full read (equal={})", f_cached.tokens == f_full.tokens); } + if same_chunks( + &follow, + f_cached.resume, + (reread && f_cached.resume > 0).then_some(f_cached.resume), + every, + cache, + ) { + strict += usize::from(f_cached.resume > 0); + check("fallback_equal", f_cached.tokens == f_full.tokens); + } else { + eprintln!( + "CONV-INFO fallback_equal: different prefill chunks than the full read (equal={})", + f_cached.tokens == f_full.tokens + ); + } let unrelated = encode(&chat("You are a terse assistant.", &[], "What is the capital of Poland?")); let u = greedy(stack, &unrelated, "U(unrelated)"); check("unrelated_empty", u.reused == 0); @@ -938,15 +1188,25 @@ fn original_serve_conversation_coverage_smoke() { let mut q = unrelated.clone(); q.extend(u.tokens.iter().map(|&t| t as u32).filter(|&t| t != eos)); q.extend(encode("<|im_end|>\n<|im_start|>user\nAnd of Hungary?<|im_end|>\n<|im_start|>assistant\n")); - let s_cached = serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled resumed request failed"); + let s_cached = + serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled resumed request failed"); eprintln!("CONV S(sampled cache) n={} reused={} out={}", q.len(), s_cached.reused, ids(&s_cached.tokens)); if resumes { check("sampled_resume", s_cached.reused > 0); } stack.forget_conversation(); - let s_full = serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled full request failed"); + let s_full = + serve_once(stack, &q, max_new, Some(&sampler), eos, None, None).expect("sampled full request failed"); eprintln!("CONV S(sampled full) n={} reused={} out={}", q.len(), s_full.reused, ids(&s_full.tokens)); - if same_chunks(&q, s_cached.resume, (reread && s_cached.resume > 0).then_some(s_cached.resume), every, cache) { strict += usize::from(s_cached.resume > 0); check("sampled_equal", s_cached.tokens == s_full.tokens); } else { eprintln!("CONV-INFO sampled_equal: different prefill chunks than the full read (equal={})", s_cached.tokens == s_full.tokens); } + if same_chunks(&q, s_cached.resume, (reread && s_cached.resume > 0).then_some(s_cached.resume), every, cache) { + strict += usize::from(s_cached.resume > 0); + check("sampled_equal", s_cached.tokens == s_full.tokens); + } else { + eprintln!( + "CONV-INFO sampled_equal: different prefill chunks than the full read (equal={})", + s_cached.tokens == s_full.tokens + ); + } // 5. cancel in the decode phase after the first committed round, then the next request let mut q2 = q.clone(); @@ -958,7 +1218,15 @@ fn original_serve_conversation_coverage_smoke() { let after = greedy(stack, &q2, "Q2(after decode cancel)"); stack.forget_conversation(); let q2_full = greedy(stack, &q2, "Q2(full)"); - if same_chunks(&q2, after.resume, (reread && after.resume > 0).then_some(after.resume), every, cache) { strict += usize::from(after.resume > 0); check("cancel_decode_equal", after.tokens == q2_full.tokens); } else { eprintln!("CONV-INFO cancel_decode_equal: different prefill chunks than the full read (equal={})", after.tokens == q2_full.tokens); } + if same_chunks(&q2, after.resume, (reread && after.resume > 0).then_some(after.resume), every, cache) { + strict += usize::from(after.resume > 0); + check("cancel_decode_equal", after.tokens == q2_full.tokens); + } else { + eprintln!( + "CONV-INFO cancel_decode_equal: different prefill chunks than the full read (equal={})", + after.tokens == q2_full.tokens + ); + } // 6. cancel during the prefill of the long prompt, then the same prompt again stack.forget_conversation(); diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_ttft.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_ttft.rs index 93d86a63..320c3a89 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_ttft.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/backend_original_serve_ttft.rs @@ -9,13 +9,13 @@ //! //! Inputs: those of the replay (`LELEKA_ORIGINAL_SERVE_REPLAY=yes`, model, expert tier, `LELEKA_REPLAY_CAPACITY`, //! `LELEKA_REPLAY_PREFIX_MIB`, `LELEKA_ORIGINAL_SERVE_RT_DIR`), `LELEKA_SWEEP_MAX_NEW` (4). +use super::super::qwen_forward::original_serve_stack::dbg_el; use super::*; use crate::qwen_forward::{ original_serve_request::ServeRequest, original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, }; use std::env; -use super::super::qwen_forward::original_serve_stack::dbg_el; fn required_path(name: &str) -> PathBuf { env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned input {name}")) @@ -33,14 +33,18 @@ fn original_serve_ttft_sweep() { let mut files: Vec = std::fs::read_dir(&dir) .expect("capture directory unreadable") .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json"))) + .filter(|p| { + p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json")) + }) .collect(); files.sort(); let want = number("LELEKA_SWEEP_CONTEXT", 52_000); let mut base: Option> = None; for file in &files { - let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON"); - let prompt: Vec = doc["prompt_ids"].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect(); + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON"); + let prompt: Vec = + doc["prompt_ids"].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect(); if prompt.len() >= want { base = Some(prompt); break; @@ -53,12 +57,18 @@ fn original_serve_ttft_sweep() { let max_new = number("LELEKA_SWEEP_MAX_NEW", 4); let reps = number("LELEKA_SWEEP_REPS", 3); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); - let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); - let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") + .expect("missing inherited sealed archive descriptor") + .parse() + .expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) + .expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) + .expect("pinned shard1 verification failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); - let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("inherited KAR admission failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -69,7 +79,11 @@ fn original_serve_ttft_sweep() { binding.load_resident_expert_source().expect("resident expert source load failed"); let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device 0 unavailable"); - let context = Rc::new(device.create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30).expect("bounded Context unavailable")); + let context = Rc::new( + device + .create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30) + .expect("bounded Context unavailable"), + ); let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); config.capacity = number("LELEKA_REPLAY_CAPACITY", 2048); config.rt_directory = env::var_os("LELEKA_ORIGINAL_SERVE_RT_DIR").map(PathBuf::from); @@ -77,11 +91,19 @@ fn original_serve_ttft_sweep() { .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); let mib = env::var("LELEKA_REPLAY_PREFIX_MIB").unwrap_or_else(|_| "auto".into()); config.prefix = Some(PrefixConfig { - budget: if mib == "auto" { PrefixBudget::Auto } else { PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) }, + budget: if mib == "auto" { + PrefixBudget::Auto + } else { + PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) + }, ..PrefixConfig::auto() }); let capacity = config.capacity; - eprintln!("SWEEP config: base prompt {} tokens, capacity {capacity}, ks {ks:?}, reps {reps}, tier {:?}", base.len(), config.expert_tier); + eprintln!( + "SWEEP config: base prompt {} tokens, capacity {capacity}, ks {ks:?}, reps {reps}, tier {:?}", + base.len(), + config.expert_tier + ); let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { Ok(stack) => stack, Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs index 118ef9c4..6ae40de5 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_changed_boundary_proof.rs @@ -6,9 +6,7 @@ use std::{ }; const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned MMQ proof path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path") } // New root-only phase: fresh real target owner; no repeated capture/prefix phases. #[test] @@ -27,8 +25,7 @@ fn pinned_single_load_layer0_and_window_boundaries() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -40,20 +37,10 @@ fn pinned_single_load_layer0_and_window_boundaries() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); let execution = EvaluationExecution::ExperimentalNativeResidentMmq; let mut moe = match execution { EvaluationExecution::ExperimentalNativeResidentMmq => { @@ -62,13 +49,10 @@ fn pinned_single_load_layer0_and_window_boundaries() { _ => panic!("native-certified activation policy required"), } .expect("actual native-certified MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical_layer0 = catch_unwind(AssertUnwindSafe(|| { let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - let report = QwenForward::test_layer0_pair_on_loaded( - &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, - ); + let report = QwenForward::test_layer0_pair_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); drop(chunk); report })); @@ -76,8 +60,7 @@ fn pinned_single_load_layer0_and_window_boundaries() { // binding/context/cache. No second source load or CUDA context is created. let numerical_window = if matches!(&numerical_layer0, Ok(Ok(_))) { Some(catch_unwind(AssertUnwindSafe(|| { - let mut chunk = - QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); + let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let report = QwenForward::test_window_boundaries_on_loaded( &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, ); @@ -115,18 +98,12 @@ fn pinned_single_load_layer0_and_window_boundaries() { Ok(report) => report.expect("changed window proof refused"), Err(primary) => resume_unwind(primary), }; - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); report .write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR")) .expect("exclusive bounded layer0 diagnostic write failed"); diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs index 3cd8af65..01f9a1e9 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric.rs @@ -31,44 +31,22 @@ fn observe( output: &OutputStage<'_, '_>, continuation: &MtpContinuation, ) -> ObservedPrefix { - assert!( - continuation.tokens == COMPLETE, - "actual target committed IDs differ" - ); - let target = session - .test_reset_replay_snapshot(binding) - .expect("actual complete target state observation refused"); - assert!( - target.has_prefix(5, [1, 0]), - "target position/predecessors differ" - ); + assert!(continuation.tokens == COMPLETE, "actual target committed IDs differ"); + let target = session.test_reset_replay_snapshot(binding).expect("actual complete target state observation refused"); + assert!(target.has_prefix(5, [1, 0]), "target position/predecessors differ"); let draft = continuation .decoder - .test_prefix_snapshot( - binding, - session, - &continuation.product, - &continuation.tokens, - ) + .test_prefix_snapshot(binding, session, &continuation.product, &continuation.tokens) .expect("actual complete draft state observation refused"); - assert!( - draft.has_prefix(4, 0), - "draft known-next edge metadata differs" - ); + assert!(draft.has_prefix(4, 0), "draft known-next edge metadata differs"); let residual = continuation .product .test_prefix_residual(binding, session) .expect("actual current residual observation refused"); - let greedy = continuation - .product - .predicted(session) - .expect("actual greedy origin refused") - .get(); + let greedy = continuation.product.predicted(session).expect("actual greedy origin refused").get(); // Executor captures ONLY the target's actual full finite logits. Draft // mtp_greedy never writes this observation; no reconstructed logits. - let logits = output - .test_reset_replay_take_logits() - .expect("actual complete target logits observation missing"); + let logits = output.test_reset_replay_take_logits().expect("actual complete target logits observation missing"); assert_eq!(residual.len(), 10240); assert_eq!(logits.len(), 248320); let charge = target @@ -77,17 +55,8 @@ fn observe( .and_then(|n| n.checked_add(residual.len().checked_mul(4)?)) .and_then(|n| n.checked_add(logits.len().checked_mul(4)?)) .expect("observation charge overflow"); - assert!( - charge <= SNAPSHOT_BOUND, - "observation exceeds declared host bound" - ); - ObservedPrefix { - target, - draft, - residual, - logits, - greedy, - } + assert!(charge <= SNAPSHOT_BOUND, "observation exceeds declared host bound"); + ObservedPrefix { target, draft, residual, logits, greedy } } struct Inputs<'a, 'ctx, 'driver> { @@ -105,8 +74,8 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { fn reference(&mut self, session: &mut QwenSession<'ctx>) -> MtpContinuation { let (sink, stream) = GenerationSink::bounded_channel(16).expect("reference queue refused"); let mut run = Generation { - measurement: None, - execution: EvaluationExecution::Native, + measurement: None, + execution: EvaluationExecution::Native, binding: self.binding, output: self.output, kar_cache: Some(&mut *self.kar), @@ -119,7 +88,8 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { shared: &self.shared, context_tokens: 128, eos: self.eos, - mtp: true, clock: SystemClock, + mtp: true, + clock: SystemClock, }; let vocabulary = Dimension::new(248320).expect("reference vocabulary refused"); let mut decoder = MtpDecoder::new(self.binding).expect("reference draft refused"); @@ -130,17 +100,9 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { Err(_) => panic!("reference full target step failed"), }; if let Some(&next) = COMPLETE.get(position + 1) { - let next = TokenId::new(u64::from(next), vocabulary) - .expect("reference known-next refused"); + let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused"); decoder - .warm( - self.binding, - run.session, - &product, - next, - self.output, - run.moe_cache, - ) + .warm(self.binding, run.session, &product, next, self.output, run.moe_cache) .expect("reference actual full draft step failed"); } latest = Some(product); @@ -150,11 +112,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { decoder .validate_resume(self.binding, run.session, &product, &COMPLETE) .expect("reference actual complete source validation refused"); - MtpContinuation { - decoder, - product, - tokens: COMPLETE.to_vec(), - } + MtpContinuation { decoder, product, tokens: COMPLETE.to_vec() } } fn advance( @@ -164,8 +122,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { prior: Option, expected_reuse: u64, ) -> MtpContinuation { - let (sink, stream) = - GenerationSink::bounded_channel(16).expect("numeric observation queue refused"); + let (sink, stream) = GenerationSink::bounded_channel(16).expect("numeric observation queue refused"); let mut pending = None; let result = generate_mtp_resume( Generation { @@ -183,7 +140,8 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { shared: &self.shared, context_tokens: 128, eos: self.eos, - mtp: true, clock: SystemClock, + mtp: true, + clock: SystemClock, }, prompt, 1, @@ -199,10 +157,7 @@ impl<'a, 'ctx, 'driver> Inputs<'a, 'ctx, 'driver> { // No consumer closes transport while the genuine generator publishes. drop(stream); let continuation = pending.expect("fully validated mathematical continuation missing"); - assert!( - continuation.tokens == prompt, - "emitted unconsumed prediction entered prefix key" - ); + assert!(continuation.tokens == prompt, "emitted unconsumed prediction entered prefix key"); continuation } } @@ -223,11 +178,7 @@ pub(super) fn check_on_loaded<'ctx, 'driver>( resumed_session: &mut QwenSession<'ctx>, fresh_session: &mut QwenSession<'ctx>, ) { - assert!( - SNAPSHOT_BOUND - .checked_mul(4) - .is_some_and(|n| n <= HOST_LIMIT) - ); + assert!(SNAPSHOT_BOUND.checked_mul(4).is_some_and(|n| n <= HOST_LIMIT)); assert_eq!(binding.layer_count(), 48); assert!(binding.kar_ple_binding().is_some()); assert!(binding.mtp_weights().is_ok()); @@ -246,21 +197,14 @@ pub(super) fn check_on_loaded<'ctx, 'driver>( moe, dense, tokenizer, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, cancel: AtomicBool::new(false), eos, }; - output - .test_reset_replay_record(true) - .expect("actual logit observation refused"); + output.test_reset_replay_record(true).expect("actual logit observation refused"); crate::qwen_forward::qsa_index::combined_qsa_observer::reset_counts(); - let fresh = crate::qwen_forward::qsa_index::combined_qsa_observer::without_residency(|| { - inputs.reference(fresh_session) - }); + let fresh = + crate::qwen_forward::qsa_index::combined_qsa_observer::without_residency(|| inputs.reference(fresh_session)); let expected = observe(binding, fresh_session, output, &fresh); assert_eq!( crate::qwen_forward::qsa_index::combined_qsa_observer::counts(), @@ -268,10 +212,7 @@ pub(super) fn check_on_loaded<'ctx, 'driver>( "reference did not execute all original nonresident QSA selections" ); assert!( - fresh - .decoder - .validate_resume(binding, resumed_session, &fresh.product, &fresh.tokens) - .is_err(), + fresh.decoder.validate_resume(binding, resumed_session, &fresh.product, &fresh.tokens).is_err(), "reference source must refuse rival session" ); let prefix = inputs.advance(resumed_session, &PREFIX, None, 0); @@ -283,55 +224,20 @@ pub(super) fn check_on_loaded<'ctx, 'driver>( "candidate did not execute all resident QSA selections" ); let (reload, append, reuse) = crate::qwen_forward::qsa_index::combined_qsa_observer::actions(); - assert_eq!( - reload, 12, - "candidate must reload exactly one actual fresh state per QSA layer" - ); - assert_eq!( - append + reuse, - 48, - "candidate incremental QSA action coverage differs" - ); + assert_eq!(reload, 12, "candidate must reload exactly one actual fresh state per QSA layer"); + assert_eq!(append + reuse, 48, "candidate incremental QSA action coverage differs"); + assert!(append >= 12, "candidate never published completed pooled block row"); + assert!(resumed.decoder.validate_resume(binding, resumed_session, &resumed.product, &resumed.tokens).is_ok()); assert!( - append >= 12, - "candidate never published completed pooled block row" - ); - assert!( - resumed - .decoder - .validate_resume(binding, resumed_session, &resumed.product, &resumed.tokens) - .is_ok() - ); - assert!( - resumed - .decoder - .validate_resume(binding, fresh_session, &resumed.product, &resumed.tokens) - .is_err(), + resumed.decoder.validate_resume(binding, fresh_session, &resumed.product, &resumed.tokens).is_err(), "retained source must refuse rival session" ); - assert!( - expected.target.numeric_eq(&actual.target), - "complete target numerical state differs" - ); - assert!( - expected.draft.numeric_eq(&actual.draft), - "complete active draft numerical state differs" - ); - assert!( - expected.residual == actual.residual, - "current target residual bits differ" - ); - assert!( - expected.logits == actual.logits, - "full actual target logits bits differ" - ); - assert_eq!( - expected.greedy, actual.greedy, - "actual current greedy differs" - ); - output - .test_reset_replay_record(false) - .expect("actual logit observation cleanup refused"); + assert!(expected.target.numeric_eq(&actual.target), "complete target numerical state differs"); + assert!(expected.draft.numeric_eq(&actual.draft), "complete active draft numerical state differs"); + assert!(expected.residual == actual.residual, "current target residual bits differ"); + assert!(expected.logits == actual.logits, "full actual target logits bits differ"); + assert_eq!(expected.greedy, actual.greedy, "actual current greedy differs"); + output.test_reset_replay_record(false).expect("actual logit observation cleanup refused"); eprintln!( "combined numeric PASS reference=full_head_nonresident_FIRST candidate=resident_headfree3+2_vs_5 reused=3 target_layers=48 gdn=36 qsa=12 draft_cells=4 logits=248320 exact_bits=true" ); diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric_sdet.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric_sdet.rs index 2e959450..ca9a67bf 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric_sdet.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/combined_prefix_numeric_sdet.rs @@ -9,9 +9,7 @@ use std::{ const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned prefix test path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path") } #[test] @@ -30,8 +28,7 @@ fn pinned_combined_kar_mtp_retained_three_plus_two_matches_full_reference_five() .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( &metadata.model, @@ -41,10 +38,7 @@ fn pinned_combined_kar_mtp_retained_three_plus_two_matches_full_reference_five() metadata.token_types.clone(), ) .expect("verified prefix tokenizer construction failed"); - let eos = *metadata - .special_ids - .get("tokenizer.ggml.eos_token_id") - .expect("verified prefix EOS absent"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified prefix EOS absent"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -56,24 +50,12 @@ fn pinned_combined_kar_mtp_retained_three_plus_two_matches_full_reference_five() .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); - let mut moe = MoeWeightCache::new(&binding, context.as_ref()) - .expect("actual MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); + let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let mut resumed = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let mut fresh = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let numerical = catch_unwind(AssertUnwindSafe(|| { @@ -115,9 +97,6 @@ fn pinned_combined_kar_mtp_retained_three_plus_two_matches_full_reference_five() assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); eprintln!("prefix proof teardown PASS allocated_bytes=0 context_closed=true"); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_frames.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_frames.rs index 4a83408a..5de37534 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_frames.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_frames.rs @@ -20,8 +20,8 @@ fn seal_json(root: &std::path::Path, name: &str, value: &Value, uid: u32) -> (Pa // Original create_new0600/write/newline/sync_data and shared16MiB budget. save(root, name, value); let file = root.join(name); - let mut opened = OpenOptions::new().read(true).custom_flags(0x20000 | 0x800) - .open(&file).expect("new public frame unavailable"); + let mut opened = + OpenOptions::new().read(true).custom_flags(0x20000 | 0x800).open(&file).expect("new public frame unavailable"); let metadata = opened.metadata().unwrap(); assert!(metadata.is_file() && metadata.uid() == uid); assert_eq!(metadata.len(), expected.len() as u64); @@ -62,12 +62,29 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) { let instructions = format!("{prefix} Use only the public document. Preserve the requested word order."); let prompt = public_renderer::render( &[ - public_renderer::Message { role: public_renderer::Role::System, content: &instructions, reasoning: None, parts: None }, - public_renderer::Message { role: public_renderer::Role::User, content: document, reasoning: None, parts: None }, - ], public_renderer::Effort::None, - ).expect("actual public renderer refused frame variant"); - let req = GenerationRequest { request_id: CASE_IDS[index + 1].into(), prompt, - max_output_tokens: CAP, temperature_milli: 0, sampling: Default::default() }; + public_renderer::Message { + role: public_renderer::Role::System, + content: &instructions, + reasoning: None, + parts: None, + }, + public_renderer::Message { + role: public_renderer::Role::User, + content: document, + reasoning: None, + parts: None, + }, + ], + public_renderer::Effort::None, + ) + .expect("actual public renderer refused frame variant"); + let req = GenerationRequest { + request_id: CASE_IDS[index + 1].into(), + prompt, + max_output_tokens: CAP, + temperature_milli: 0, + sampling: Default::default(), + }; let ids = prepare_prompt(inputs.tokenizer, &req, 262144) .expect("actual admitted tokenizer refused public frame variant"); requests.push((req, ids)); @@ -94,7 +111,9 @@ pub(super) fn prepare(inputs: &Inputs<'_, '_, '_>) -> (PathBuf, String) { let mut raw = Vec::new(); raw.try_reserve_exact(ids.len().checked_mul(4).expect("public IDs byte extent overflow")) .expect("public IDs allocation refused"); - for id in ids { raw.extend_from_slice(&id.to_le_bytes()); } + for id in ids { + raw.extend_from_slice(&id.to_le_bytes()); + } let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::>().join(",")); assert!(wire.len() <= 32768); entries.push(json!({"ordinal":index,"case_id":CASE_IDS[index],"frame_file":file, diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_runtime.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_runtime.rs index d4785b4e..44954b3e 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_runtime.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/fivecase_runtime.rs @@ -22,8 +22,8 @@ fn pinned_json(file: &std::path::Path, digest: &str, uid: u32) -> Value { assert!(file.is_absolute()); assert_eq!(digest.len(), 64); assert!(digest.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); - let mut f = OpenOptions::new().read(true).custom_flags(0x20000 | 0x800) - .open(file).expect("sealed public file unavailable"); + let mut f = + OpenOptions::new().read(true).custom_flags(0x20000 | 0x800).open(file).expect("sealed public file unavailable"); let metadata = f.metadata().unwrap(); assert!(metadata.is_file() && metadata.uid() == uid); assert!(metadata.len() <= 65536); @@ -61,9 +61,7 @@ impl FiveCaseReport { assert!(offered > 0 && accepted > 0, "actual five-case MTP was not exercised"); } pub(super) fn json_after_teardown(&self) -> Value { - let cases: Vec<_> = self.arms.iter().enumerate().map(|(i, arm)| { - arm.json(PHASES[i], self.policy) - }).collect(); + let cases: Vec<_> = self.arms.iter().enumerate().map(|(i, arm)| arm.json(PHASES[i], self.policy)).collect(); json!({"schema":1,"admission":self.admission,"cases":cases, "boundary_error":self.boundary_error,"one_loaded_owner":true, "fresh_target_draft_each_case":true,"retained_prefix_tokens":0, @@ -74,15 +72,21 @@ impl FiveCaseReport { } } fn completed_boundary(arm: &Arm) -> bool { - arm.measurement.completed && arm.measurement.terminal_published - && !arm.measurement.stopped && matches!(arm.reason, FinishReason::Length) + arm.measurement.completed + && arm.measurement.terminal_published + && !arm.measurement.stopped + && matches!(arm.reason, FinishReason::Length) && arm.measurement.retained_prefix_tokens == 0 && arm.usage.reused_input_tokens == 0 && arm.usage.input_tokens == u64::try_from(arm.measurement.input_token_ids.len()).unwrap() - && arm.usage.output_tokens == u64::from(CAP) && arm.measurement.output_token_ids.len() == CAP as usize + && arm.usage.output_tokens == u64::from(CAP) + && arm.measurement.output_token_ids.len() == CAP as usize } fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec { - fields(manifest, &["schema", "case_count", "baseline_frame_sha256", "model_digest", "renderer_source_sha256", "cases"]); + fields( + manifest, + &["schema", "case_count", "baseline_frame_sha256", "model_digest", "renderer_source_sha256", "cases"], + ); assert_eq!(number(manifest, "schema"), 1); assert_eq!(number(manifest, "case_count"), CASE_COUNT as u64); assert_eq!(text(manifest, "baseline_frame_sha256"), BASE_FRAME_SHA); @@ -94,11 +98,35 @@ fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec { let mut cases: Vec = Vec::new(); let uid = std::fs::metadata(path("LELEKA_STRA169_PAIR_OUTPUT")).unwrap().uid(); for (i, entry) in entries.iter().enumerate() { - fields(entry, &["ordinal", "case_id", "frame_file", "frame_sha256", "framed_count", "input_ids_sha256", "wire_sha256", "wire_bytes"]); + fields( + entry, + &[ + "ordinal", + "case_id", + "frame_file", + "frame_sha256", + "framed_count", + "input_ids_sha256", + "wire_sha256", + "wire_bytes", + ], + ); assert_eq!(number(entry, "ordinal"), i as u64); assert_eq!(text(entry, "case_id"), PHASES[i]); let frame = pinned_json(std::path::Path::new(text(entry, "frame_file")), text(entry, "frame_sha256"), uid); - fields(&frame, &["renderer_source_sha256", "framed_prompt", "framed_prompt_sha256", "input_token_ids", "framed_count", "model_digest", "max_output_tokens", "temperature_milli"]); + fields( + &frame, + &[ + "renderer_source_sha256", + "framed_prompt", + "framed_prompt_sha256", + "input_token_ids", + "framed_count", + "model_digest", + "max_output_tokens", + "temperature_milli", + ], + ); assert_eq!(text(&frame, "renderer_source_sha256"), renderer); assert_eq!(text(&frame, "model_digest"), MODEL_DIGEST); assert_eq!(number(&frame, "max_output_tokens"), u64::from(CAP)); @@ -113,15 +141,26 @@ fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec { assert_eq!(ids.len(), usize::try_from(count).unwrap()); assert!(ids.iter().all(|id| *id < 248320)); let mut raw = Vec::new(); - for id in &ids { raw.extend_from_slice(&id.to_le_bytes()); } + for id in &ids { + raw.extend_from_slice(&id.to_le_bytes()); + } assert_eq!(sha(&raw), text(entry, "input_ids_sha256")); let wire = format!("GEN 32 {}\n", ids.iter().map(u32::to_string).collect::>().join(",")); assert!(wire.len() <= 32768); assert_eq!(wire.len() as u64, number(entry, "wire_bytes")); assert_eq!(sha(wire.as_bytes()), text(entry, "wire_sha256")); - let request = GenerationRequest { request_id: PHASES[i].into(), prompt: prompt.to_owned(), max_output_tokens: CAP, temperature_milli: 0, sampling: Default::default() }; + let request = GenerationRequest { + request_id: PHASES[i].into(), + prompt: prompt.to_owned(), + max_output_tokens: CAP, + temperature_milli: 0, + sampling: Default::default(), + }; // Actual admitted tokenizer, never trust supplied count/IDs as a producer. - assert_eq!(prepare_prompt(tokenizer, &request, 262144).expect("genuine public frame tokenization refused"), ids); + assert_eq!( + prepare_prompt(tokenizer, &request, 262144).expect("genuine public frame tokenization refused"), + ids + ); assert!(cases.iter().all(|old| old.ids != ids && old.request.prompt != request.prompt)); cases.push(Case { request, ids, admission: entry.clone() }); } @@ -131,7 +170,12 @@ fn admit(tokenizer: &Tokenizer, manifest: &Value) -> Vec { pub(super) fn run_on_loaded(inputs: &mut Inputs<'_, '_, '_>, file: &std::path::Path, digest: &str) -> FiveCaseReport { run_on_loaded_with_policy(inputs, file, digest, POLICY) } -pub(super) fn run_on_loaded_with_policy(inputs: &mut Inputs<'_, '_, '_>, file: &std::path::Path, digest: &str, policy: &'static str) -> FiveCaseReport { +pub(super) fn run_on_loaded_with_policy( + inputs: &mut Inputs<'_, '_, '_>, + file: &std::path::Path, + digest: &str, + policy: &'static str, +) -> FiveCaseReport { assert_eq!(env::var("LELEKA_STRA169_RUN_FIVE_PUBLIC_CASES").as_deref(), Ok("yes")); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); let uid = root.metadata().unwrap().uid(); @@ -143,14 +187,25 @@ pub(super) fn run_on_loaded_with_policy(inputs: &mut Inputs<'_, '_, '_>, file: & save(&root, "FIVE-CASE-ADMISSION.json", &admission); let mut report = FiveCaseReport { arms: Vec::new(), admission, boundary_error: None, policy }; for (i, case) in cases.iter().enumerate() { - let arm = inputs.arm(&case.request, &case.ids, - EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, PHASES[i]); + let arm = inputs.arm( + &case.request, + &case.ids, + EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr, + PHASES[i], + ); // Original arm has drained/joined the consumer and dropped pending draft // and actual target session. Preserve this completed record BEFORE next arm. - save(&root, &format!("CASE-{}.json", i + 1), &json!({"admission":case.admission,"actual":arm.json(PHASES[i], policy)})); + save( + &root, + &format!("CASE-{}.json", i + 1), + &json!({"admission":case.admission,"actual":arm.json(PHASES[i], policy)}), + ); let valid = completed_boundary(&arm); report.arms.push(arm); - if !valid { report.boundary_error = Some("completed_length_usage_prefix"); break; } + if !valid { + report.boundary_error = Some("completed_length_usage_prefix"); + break; + } } report } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/layer0_native_mmq_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/layer0_native_mmq_proof.rs index 651b8176..815368c6 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/layer0_native_mmq_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/layer0_native_mmq_proof.rs @@ -6,9 +6,7 @@ use std::{ }; const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned MMQ proof path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path") } // New root-only phase: fresh real target owner; no repeated capture/prefix phases. #[test] @@ -27,8 +25,7 @@ fn pinned_single_load_layer0_native_first_mmq_diagnostic() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -40,20 +37,10 @@ fn pinned_single_load_layer0_native_first_mmq_diagnostic() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); let execution = EvaluationExecution::ExperimentalNativeResidentMmq; let mut moe = match execution { EvaluationExecution::ExperimentalNativeResidentMmq => { @@ -62,13 +49,10 @@ fn pinned_single_load_layer0_native_first_mmq_diagnostic() { _ => panic!("native-certified activation policy required"), } .expect("actual native-certified MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical = catch_unwind(AssertUnwindSafe(|| { let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - let report = QwenForward::test_layer0_pair_on_loaded( - &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, - ); + let report = QwenForward::test_layer0_pair_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); drop(chunk); report })); @@ -94,18 +78,12 @@ fn pinned_single_load_layer0_native_first_mmq_diagnostic() { Ok(report) => report, Err(primary) => resume_unwind(primary), }; - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); let report = report.expect("same-source layer0 diagnostic refused"); report .write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR")) diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/long_public_preflight/long_public_request.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/long_public_preflight/long_public_request.rs index 075514cc..a75759ff 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/long_public_preflight/long_public_request.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/long_public_preflight/long_public_request.rs @@ -17,26 +17,21 @@ const ARTIFACT_CAP: usize = 16 * 1024 * 1024; const CONTEXT: usize = 262144; const OUTPUT: usize = 128; const MODEL: &str = "sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; -const INSTRUCTIONS: &str = "Use only the public document. Return only the six-digit code for PUBLIC-LONG-17, without explanation."; +const INSTRUCTIONS: &str = + "Use only the public document. Return only the six-digit code for PUBLIC-LONG-17, without explanation."; const PREFIX: &str = "PUBLIC deterministic retrieval fixture; no private agent data.\nPUBLIC-LONG-17 code: 314159\nThe following public filler has no other code:\n"; -const SUFFIX: &str = "\nEnd of public filler. What is the six-digit code for PUBLIC-LONG-17? Reply only with that code."; +const SUFFIX: &str = + "\nEnd of public filler. What is the six-digit code for PUBLIC-LONG-17? Reply only with that code."; fn refused(message: &'static str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } fn digest(bytes: &[u8]) -> String { - Sha256::digest(bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() + Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() } fn encoded(tokenizer: &Tokenizer, repeats: usize) -> io::Result<(String, String, Vec)> { let body_bytes = PREFIX .len() - .checked_add( - repeats - .checked_mul(2) - .ok_or_else(|| refused("repeat overflow"))?, - ) + .checked_add(repeats.checked_mul(2).ok_or_else(|| refused("repeat overflow"))?) .and_then(|n| n.checked_add(SUFFIX.len())) .ok_or_else(|| refused("body overflow"))?; if body_bytes > BYTE_CAP { @@ -70,9 +65,7 @@ fn encoded(tokenizer: &Tokenizer, repeats: usize) -> io::Result<(String, String, return Err(refused("framed prompt exceeds byte cap")); } // Exactly the runtime parse-special choice; no padding/truncation/relabelled IDs. - let ids = tokenizer - .encode(&prompt, true) - .map_err(|_| refused("actual tokenizer refused public frame"))?; + let ids = tokenizer.encode(&prompt, true).map_err(|_| refused("actual tokenizer refused public frame"))?; if ids.is_empty() { return Err(refused("empty public frame")); } @@ -81,9 +74,7 @@ fn encoded(tokenizer: &Tokenizer, repeats: usize) -> io::Result<(String, String, fn request_for_band(tokenizer: &Tokenizer, lower: usize) -> io::Result<(String, String, Vec)> { // Search is bounded and every count is from the complete real frame. The // bracket must remain monotone for this filler or we refuse, never invent IDs. - let upper = lower - .checked_add(255) - .ok_or_else(|| refused("band overflow"))?; + let upper = lower.checked_add(255).ok_or_else(|| refused("band overflow"))?; let mut lo = 0usize; let mut hi = 480000usize; // <=960KB filler; renderer overhead separately checked. let mut lo_count = encoded(tokenizer, lo)?.2.len(); @@ -115,9 +106,7 @@ fn request_for_band(tokenizer: &Tokenizer, lower: usize) -> io::Result<(String, hi_count = count; } } - Err(refused( - "exact public count band unavailable within bounded search", - )) + Err(refused("exact public count band unavailable within bounded search")) } struct Artifact { name: String, @@ -143,9 +132,7 @@ pub(crate) fn produce_on_bound_tokenizer( } if !output.is_absolute() || output.exists() - || output - .parent() - .is_none_or(|p| p.canonicalize().ok().as_deref() != Some(p)) + || output.parent().is_none_or(|p| p.canonicalize().ok().as_deref() != Some(p)) { return Err(refused("fresh canonical-parent output required")); } @@ -155,15 +142,10 @@ pub(crate) fn produce_on_bound_tokenizer( let (body, prompt, ids) = request_for_band(tokenizer, lower)?; let request = json!({"model":"pinned-native-model","instructions":INSTRUCTIONS,"input":body,"tools":[],"max_output_tokens":OUTPUT,"temperature":0,"stream":true,"store":false}); let request_bytes = json_bytes(&request)?; - if request_bytes.len() > BYTE_CAP || prompt.len() > BYTE_CAP || ids.len() + OUTPUT > CONTEXT - { + if request_bytes.len() > BYTE_CAP || prompt.len() > BYTE_CAP || ids.len() + OUTPUT > CONTEXT { return Err(refused("actual request/prompt/context cap")); } - let mut binary = Vec::with_capacity( - ids.len() - .checked_mul(4) - .ok_or_else(|| refused("ID extent overflow"))?, - ); + let mut binary = Vec::with_capacity(ids.len().checked_mul(4).ok_or_else(|| refused("ID extent overflow"))?); for id in &ids { binary.extend_from_slice(&id.to_le_bytes()); } @@ -171,32 +153,19 @@ pub(crate) fn produce_on_bound_tokenizer( let prompt_name = format!("{lower}.prompt.utf8"); let ids_name = format!("{lower}.ids.u32le"); frames.push(json!({"target_band":[lower,lower+255],"framed_count":ids.len(),"max_output_tokens":OUTPUT,"context_tokens":CONTEXT,"request_file":request_name,"request_bytes":request_bytes.len(),"request_sha256":digest(&request_bytes),"prompt_file":prompt_name,"prompt_bytes":prompt.len(),"prompt_sha256":digest(prompt.as_bytes()),"ids_file":ids_name,"ids_bytes":binary.len(),"ids_sha256":digest(&binary),"ids_encoding":"u32-le","expected_answer":"314159","numeric_prefix":"fresh; retained reuse not claimed"})); - artifacts.push(Artifact { - name: request_name, - bytes: request_bytes, - }); - artifacts.push(Artifact { - name: prompt_name, - bytes: prompt.into_bytes(), - }); - artifacts.push(Artifact { - name: ids_name, - bytes: binary, - }); + artifacts.push(Artifact { name: request_name, bytes: request_bytes }); + artifacts.push(Artifact { name: prompt_name, bytes: prompt.into_bytes() }); + artifacts.push(Artifact { name: ids_name, bytes: binary }); } let frame = json!({"schema":"public-long-preflight-v1","model_digest":bound_model_digest,"renderer_source_sha256":digest(include_bytes!("../../../../../crates/gateway-text/src/prompt.rs")),"tokenizer_implementation_source_sha256":"e675d8cbcccc071ff1ae69574e6042dc33b6b71e26bb756f7c65ae527dfcd38b","tokenizer_provenance":"caller must supply the actual already-bound pinned model tokenizer","parse_special":true,"effort":"none","public_fixture":true,"frames":frames,"aggregate_cap_bytes":ARTIFACT_CAP,"request_cap_bytes":BYTE_CAP,"prompt_cap_bytes":BYTE_CAP,"inference_executed":false,"KV_artifacts":false,"MTP_exercised":false,"quality_or_speed_claim":false}); let frame_bytes = json_bytes(&frame)?; if frame_bytes.len() > 65536 { return Err(refused("shared frame summary cap")); } - artifacts.push(Artifact { - name: "FRAME.json".into(), - bytes: frame_bytes, - }); - let total = artifacts.iter().try_fold(0usize, |n, a| { - n.checked_add(a.bytes.len()) - .ok_or_else(|| refused("artifact total overflow")) - })?; + artifacts.push(Artifact { name: "FRAME.json".into(), bytes: frame_bytes }); + let total = artifacts + .iter() + .try_fold(0usize, |n, a| n.checked_add(a.bytes.len()).ok_or_else(|| refused("artifact total overflow")))?; if total > ARTIFACT_CAP || total > remaining_artifact_bytes { return Err(refused("aggregate artifacts cap")); } @@ -208,11 +177,7 @@ pub(crate) fn produce_on_bound_tokenizer( use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(output, std::fs::Permissions::from_mode(0o700))?; for artifact in artifacts { - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(output.join(artifact.name))?; + let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(output.join(artifact.name))?; file.write_all(&artifact.bytes)?; file.sync_data()?; } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_adaptive_candidate_only.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_adaptive_candidate_only.rs index b8a70c21..e69bf7eb 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_adaptive_candidate_only.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_adaptive_candidate_only.rs @@ -5,18 +5,12 @@ use super::*; #[test] #[ignore = "ROOT five public requests on one admitted owner; paired Original required"] fn pinned_five_public_cases_strata_adaptive_slots() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); let baseline = baseline(); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -29,22 +23,19 @@ fn pinned_five_public_cases_strata_adaptive_slots() { let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); let shard0_started = Instant::now(); let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental( - &path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0, observed_kar.as_ref(), - ).expect("pinned shard0 failed"); + &path("LELEKA_STRA169_IQ3S_SHARD0"), + SHARD0, + observed_kar.as_ref(), + ) + .expect("pinned shard0 failed"); let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); assert_eq!(ids, baseline.input_ids); @@ -60,8 +51,8 @@ fn pinned_five_public_cases_strata_adaptive_slots() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -77,13 +68,8 @@ fn pinned_five_public_cases_strata_adaptive_slots() { assert!(profile_file.metadata().unwrap().is_file()); assert_eq!(profile_file.metadata().unwrap().len(), 196_632); let mut profile_bytes = Vec::new(); - profile_bytes - .try_reserve_exact(196_632) - .expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file) - .take(196_633) - .read_to_end(&mut profile_bytes) - .unwrap(); + profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); + Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); assert_eq!(profile_bytes.len(), 196_632); crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) .expect("pure pinned profile admission failed before Driver"); @@ -107,14 +93,12 @@ fn pinned_five_public_cases_strata_adaptive_slots() { let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(&binding, context.as_ref()).unwrap(); + let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(&binding, context.as_ref()) + .unwrap(); let preload_started = Instant::now(); - let mut moe = MoeWeightCache::new_native_strata_adaptive_shared_permanent( - &binding, - context.as_ref(), - &profile_bytes, - ) - .unwrap(); + let mut moe = + MoeWeightCache::new_native_strata_adaptive_shared_permanent(&binding, context.as_ref(), &profile_bytes) + .unwrap(); let preload_ns = preload_started.elapsed().as_nanos(); drop(profile_file); drop(profile_bytes); @@ -130,17 +114,16 @@ fn pinned_five_public_cases_strata_adaptive_slots() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; - crate::qwen_forward::owner_wall_profile::arm() - .expect("actual owner wall profile admission failed"); + crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - fivecase_runtime::run_on_loaded_with_policy(&mut inputs, &case_manifest, &case_manifest_sha, "strata-adaptive-4-96-native-resident-CPU-miss-event-shared192-gdn-journal-incremental-capture") - + fivecase_runtime::run_on_loaded_with_policy( + &mut inputs, + &case_manifest, + &case_manifest_sha, + "strata-adaptive-4-96-native-resident-CPU-miss-event-shared192-gdn-journal-incremental-capture", + ) })); let disabled = crate::qwen_forward::oracle_capture::disable(&output); let shared_tail_rows = moe.test_shared_tail_witness(); @@ -160,7 +143,8 @@ fn pinned_five_public_cases_strata_adaptive_slots() { "physical_layout":"three-whole-raw-Gate-Up-Down-owners-per-slot", "native_ephemeral_pcie_share_ported":false,"normal_defaults_changed":false })); - let role_names = ["routed_gate", "routed_up", "routed_down", "shared_gate", "shared_up", "shared_down", "shared_scalar"]; + let role_names = + ["routed_gate", "routed_up", "routed_down", "shared_gate", "shared_up", "shared_down", "shared_scalar"]; let shared_json = shared_witness.as_ref().ok().map(|w| json!({ "descriptors":w.descriptors,"bytes":w.bytes, "roles":w.roles.iter().enumerate().map(|(i,c)| json!({"role":role_names[i], @@ -203,10 +187,15 @@ fn pinned_five_public_cases_strata_adaptive_slots() { let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples.iter().map(|sample| json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - })).collect::>() + samples + .iter() + .map(|sample| { + json!({ + "label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns + }) + }) + .collect::>() }); save( &root, @@ -251,15 +240,24 @@ fn pinned_five_public_cases_strata_adaptive_slots() { assert_eq!(allocated, 0); assert!(matches!(closed, Some(Ok(())))); assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - assert!(adaptive_witness.as_ref().is_ok_and(|w| w.initial_slots > 0 - && w.resident_slots <= w.initial_slots && w.pending_swaps <= 96 - && w.verified_windows > 0 && w.routed_occurrences > 0 - && w.resident_occurrences.checked_add(w.cpu_occurrences) == Some(w.routed_occurrences) - && w.preload_upload_bytes > 0 && w.raw_slot_bytes <= 24 * 1024 * 1024 * 1024), - "actual adaptive slot/cadence/occurrence witness invalid"); - assert!(shared_witness.as_ref().is_ok_and(|w| w.descriptors == 192 - && w.roles[3..].iter().all(|role| role.evictions == 0 && role.eviction_bytes == 0)), - "actual adaptive shared permanent role witness missing"); + assert!( + adaptive_witness.as_ref().is_ok_and(|w| w.initial_slots > 0 + && w.resident_slots <= w.initial_slots + && w.pending_swaps <= 96 + && w.verified_windows > 0 + && w.routed_occurrences > 0 + && w.resident_occurrences.checked_add(w.cpu_occurrences) == Some(w.routed_occurrences) + && w.preload_upload_bytes > 0 + && w.raw_slot_bytes <= 24 * 1024 * 1024 * 1024), + "actual adaptive slot/cadence/occurrence witness invalid" + ); + assert!( + shared_witness + .as_ref() + .is_ok_and(|w| w.descriptors == 192 + && w.roles[3..].iter().all(|role| role.evictions == 0 && role.eviction_bytes == 0)), + "actual adaptive shared permanent role witness missing" + ); // Quality assertions follow every attempted teardown and preserve a primary // generation panic/error. There is no Native call or historical timing ratio. assert!(resident_queue_completions > 0, "actual completed resident queue+packet handoff did not execute"); @@ -268,15 +266,12 @@ fn pinned_five_public_cases_strata_adaptive_slots() { assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); + assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); assert!( - shared_tail_rows > 0, - "actual queued target shared tail was not executed" + retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), + "actual retained scratch owner rows absent" ); - assert!( - router_rows.as_ref().is_ok_and(|rows| *rows > 1), - "actual router scratch was not reused" - ); - assert!(retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), "actual retained scratch owner rows absent"); candidate.assert_after_teardown(); let first = &five_json["cases"][0]; assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); @@ -284,14 +279,18 @@ fn pinned_five_public_cases_strata_adaptive_slots() { && first["text"].as_str() == Some(baseline.text.as_str()) && first["finish_reason"] == json!("Length") && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save(&root, "QUALITY.json", &json!({"case1_retained_native_parity":parity, + save( + &root, + "QUALITY.json", + &json!({"case1_retained_native_parity":parity, "quality_against_original17":null,"requires_matching_original_five":true, "changed_owner_policy":"incremental-capture-strata-adaptive-4-96-CPU-miss-event-shared192-gdn-journal-qk40960-qsa108544", "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false})); + "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), + ); assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs index a2696ca7..66992a32 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_candidate_only.rs @@ -18,9 +18,7 @@ static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::Atomi fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { ARTIFACT_BYTES .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { - current - .checked_add(bytes) - .filter(|next| *next <= ARTIFACT_CAP) + current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP) }) .map(|_| ()) .map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded")) @@ -28,26 +26,16 @@ fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; const CAP: u32 = 32; fn path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing ROOT-owned public pair path") + env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path") } fn sha(bytes: &[u8]) -> String { - Sha256::digest(bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() + Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() } fn save(root: &std::path::Path, name: &str, value: &Value) { let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed"); assert!(bytes.len() <= 1024 * 1024); - reserve_artifacts( - bytes - .len() - .checked_add(1) - .expect("JSON newline extent overflow"), - ) - .expect("whole public pair serialized budget exceeded"); + reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow")) + .expect("whole public pair serialized budget exceeded"); let mut f = OpenOptions::new() .write(true) .create_new(true) @@ -83,9 +71,7 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { "PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n", ); for index in 0..lines { - document.push_str(&format!( - "Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n" - )); + document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n")); } document.push_str("Return this public sequence once, without explanation: amber birch cedar delta elm fern grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc amber birch cedar delta elm fern."); let prompt = public_renderer::render( @@ -110,10 +96,10 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { request_id: "public-paired-owner-generation".into(), prompt, max_output_tokens: CAP, - temperature_milli: 0, sampling: Default::default(), + temperature_milli: 0, + sampling: Default::default(), }; - let ids = prepare_prompt(tokenizer, &req, 262144) - .expect("actual pinned tokenizer refused public frame"); + let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame"); if (193..=256).contains(&ids.len()) { let canonical = json!({"model":"pinned-native-model","instructions":instructions,"input":document,"tools":[],"max_output_tokens":CAP,"temperature":0,"stream":true,"store":false}); return (req, ids, canonical); @@ -169,11 +155,9 @@ impl Inputs<'_, '_, '_> { ); // Fresh genuine target state and fresh actual decoder. No position reset, // invented prefix, checkpoint reuse or cached-token count substitution. - let mut session = - QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); + let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); let cancel = AtomicBool::new(false); - let (sink, mut stream) = - GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); + let (sink, mut stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); let drain = thread::spawn(move || { let mut text = String::new(); let mut usage = None; @@ -202,8 +186,7 @@ impl Inputs<'_, '_, '_> { (text, usage, terminal, first_text_at) }); let before = cache(self.moe.counters(), self.dense.counters()); - let recorder = - std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); + let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); let mut pending = None; let request_started = Instant::now(); let result = generate_mtp_resume( @@ -222,7 +205,8 @@ impl Inputs<'_, '_, '_> { shared: &self.shared, context_tokens: 262144, eos: self.eos, - mtp: true, clock: SystemClock, + mtp: true, + clock: SystemClock, }, ids, req.max_output_tokens, @@ -234,11 +218,9 @@ impl Inputs<'_, '_, '_> { Err(failure) => { let terminal = match failure { GenerationFailure::Cancelled => GenerationTerminal::Cancelled, - GenerationFailure::Backend(error) => GenerationTerminal::Failed { - code: error.code, - message: error.message, - retryable: false, - }, + GenerationFailure::Backend(error) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } }; let diagnostic = format!("{terminal:?}"); let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); @@ -258,14 +240,10 @@ impl Inputs<'_, '_, '_> { panic!("actual public pair generation failed; bounded failure artifact retained"); } }; - let terminal = GenerationTerminal::Completed { - reason: reason.clone(), - usage: usage.clone(), - }; + let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); - let (text, seen_usage, seen_terminal, first_text_at) = - drain.join().expect("actual pair consumer failed"); + let (text, seen_usage, seen_terminal, first_text_at) = drain.join().expect("actual pair consumer failed"); let request_wall = request_started.elapsed(); let first_text = first_text_at.map(|at| at.duration_since(request_started)); assert!(published && seen_terminal.as_ref() == Some(&terminal)); @@ -283,23 +261,12 @@ impl Inputs<'_, '_, '_> { true, matches!(reason, FinishReason::Stop), published, - Some(( - usage.input_tokens, - usage.output_tokens, - usage.reused_input_tokens, - )), + Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)), ) .expect("actual owner measurement refused"); assert_eq!(measured.input_token_ids, ids); assert_eq!(measured.retained_prefix_tokens, 0); - Arm { - measurement: measured, - text, - usage, - reason, - request_wall, - first_text, - } + Arm { measurement: measured, text, usage, reason, request_wall, first_text } } } fn metadata() -> Value { @@ -310,15 +277,11 @@ fn metadata() -> Value { .expect("ROOT public measurement metadata required"); assert!(f.metadata().unwrap().is_file()); let mut b = Vec::new(); - std::io::Read::by_ref(&mut f) - .take(16385) - .read_to_end(&mut b) - .unwrap(); + std::io::Read::by_ref(&mut f).take(16385).read_to_end(&mut b).unwrap(); assert!(b.len() <= 16384); assert_eq!( sha(&b), - env::var("LELEKA_STRA169_PAIR_METADATA_SHA") - .expect("ROOT exact public metadata digest required") + env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required") ); let value: Value = serde_json::from_slice(&b).unwrap(); let o = value.as_object().expect("public metadata object required"); @@ -332,10 +295,7 @@ fn metadata() -> Value { "clocks", "context_tokens", ] { - assert!( - o.get(key).is_some_and(|v| !v.is_null()), - "actual hardware/profile metadata required" - ); + assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required"); } assert!(o.keys().all(|k| { [ @@ -377,27 +337,18 @@ fn baseline() -> Baseline { .expect("sealed retained Native baseline required"); assert!(f.metadata().unwrap().is_file()); let mut bytes = Vec::new(); - std::io::Read::by_ref(&mut f) - .take(65537) - .read_to_end(&mut bytes) - .unwrap(); + std::io::Read::by_ref(&mut f).take(65537).read_to_end(&mut bytes).unwrap(); assert!(bytes.len() <= 65536); assert_eq!(sha(&bytes), BASELINE_SHA); let v: Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(v["phase"], json!("warm")); - assert_eq!( - v["execution_policy"], - json!("native64-same-dual-cache-retained-mtp-kv") - ); + assert_eq!(v["execution_policy"], json!("native64-same-dual-cache-retained-mtp-kv")); assert_eq!(v["completed"], json!(true)); assert_eq!(v["terminal_published"], json!(true)); assert_eq!(v["stopped"], json!(false)); assert_eq!(v["finish_reason"], json!("Length")); assert_eq!(v["retained_prefix_tokens"], json!(0)); - assert_eq!( - v["usage"], - json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}) - ); + assert_eq!(v["usage"], json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0})); let input_ids = token_ids(&v["input_token_ids"]); let output_ids = token_ids(&v["output_token_ids"]); assert_eq!(input_ids.len(), 202); @@ -426,11 +377,7 @@ fn baseline() -> Baseline { assert_eq!(active, output_ids[..31]); assert_eq!(offered, 31); assert_eq!(accepted, 23); - Baseline { - input_ids, - output_ids, - text, - } + Baseline { input_ids, output_ids, text } } fn checked_candidate_window_prefix(windows: &[WindowWitness], output_ids: &[u32]) -> (usize, usize) { assert!(!output_ids.is_empty()); @@ -462,15 +409,21 @@ fn checked_candidate_window_prefix(windows: &[WindowWitness], output_ids: &[u32] (offered, accepted) } fn candidate_windows(candidate: &Arm) -> (usize, usize) { - let counts = checked_candidate_window_prefix(&candidate.measurement.windows, &candidate.measurement.output_token_ids); + let counts = + checked_candidate_window_prefix(&candidate.measurement.windows, &candidate.measurement.output_token_ids); assert_eq!(counts.0, candidate.offered()); counts } #[test] fn cap_final_zero_draft_anchor_is_only_last_verified_prefix_before_final_public_token() { fn window(steps: usize, ids: [u32; 4], count: usize) -> WindowWitness { - WindowWitness { draft_steps: steps, verified_ids: ids, verified_count: count, - authoritative_eos: false, accepted_non_eos_drafts: count - 1 } + WindowWitness { + draft_steps: steps, + verified_ids: ids, + verified_count: count, + authoritative_eos: false, + accepted_non_eos_drafts: count - 1, + } } let prefix = window(2, [10, 11, 12, 999], 3); let last = window(0, [13, 998, 997, 996], 1); @@ -478,28 +431,27 @@ fn cap_final_zero_draft_anchor_is_only_last_verified_prefix_before_final_public_ assert_eq!(checked_candidate_window_prefix(&[prefix.clone(), last.clone()], &outputs), (2, 2)); let original = window(3, [10, 11, 12, 13], 4); assert_eq!(checked_candidate_window_prefix(&[original], &outputs), (3, 3)); - for bad in [vec![last.clone(), prefix.clone()], vec![prefix.clone(), last.clone(), last.clone()], + for bad in [ + vec![last.clone(), prefix.clone()], + vec![prefix.clone(), last.clone(), last.clone()], vec![prefix.clone(), window(0, [13, 14, 0, 0], 2)], - vec![prefix.clone(), window(0, [999, 0, 0, 0], 1)]] { + vec![prefix.clone(), window(0, [999, 0, 0, 0], 1)], + ] { assert!(catch_unwind(AssertUnwindSafe(|| checked_candidate_window_prefix(&bad, &outputs))).is_err()); } - assert!(catch_unwind(AssertUnwindSafe(|| checked_candidate_window_prefix(&[prefix, last], &outputs[..4]))).is_err()); + assert!( + catch_unwind(AssertUnwindSafe(|| checked_candidate_window_prefix(&[prefix, last], &outputs[..4]))).is_err() + ); } #[test] #[ignore = "ROOT candidate-only changed owner proof; retained Native is not replayed"] fn pinned_new_slowpaths_match_completed_public_output() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); let baseline = baseline(); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -512,22 +464,19 @@ fn pinned_new_slowpaths_match_completed_public_output() { let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); let shard0_started = Instant::now(); let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0, observed_kar.as_ref(), - ).expect("pinned shard0 failed"); + &path("LELEKA_STRA169_IQ3S_SHARD0"), + SHARD0, + observed_kar.as_ref(), + ) + .expect("pinned shard0 failed"); let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); assert_eq!(ids, baseline.input_ids); @@ -543,8 +492,8 @@ fn pinned_new_slowpaths_match_completed_public_output() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -560,13 +509,8 @@ fn pinned_new_slowpaths_match_completed_public_output() { assert!(profile_file.metadata().unwrap().is_file()); assert_eq!(profile_file.metadata().unwrap().len(), 196_632); let mut profile_bytes = Vec::new(); - profile_bytes - .try_reserve_exact(196_632) - .expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file) - .take(196_633) - .read_to_end(&mut profile_bytes) - .unwrap(); + profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); + Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); assert_eq!(profile_bytes.len(), 196_632); crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) .expect("pure pinned profile admission failed before Driver"); @@ -605,18 +549,10 @@ fn pinned_new_slowpaths_match_completed_public_output() { // The unchanged, previously qualified GDN helper is not repeated. let mut direct_down_report = None; let candidate = catch_unwind(AssertUnwindSafe(|| { - let mut proof_session = - QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); + let mut proof_session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); direct_down_report = Some( - QwenForward::test_direct_down_on_loaded( - &binding, - &context, - &mut proof_session, - &mut kar, - &mut moe, - &dense, - ) - .expect("actual original-first direct Down packet proof failed"), + QwenForward::test_direct_down_on_loaded(&binding, &context, &mut proof_session, &mut kar, &mut moe, &dense) + .expect("actual original-first direct Down packet proof failed"), ); drop(proof_session); let mut inputs = Inputs { @@ -628,14 +564,9 @@ fn pinned_new_slowpaths_match_completed_public_output() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; - crate::qwen_forward::owner_wall_profile::arm() - .expect("actual owner wall profile admission failed"); + crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); inputs.arm( &req, &ids, @@ -685,10 +616,15 @@ fn pinned_new_slowpaths_match_completed_public_output() { let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples.iter().map(|sample| json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - })).collect::>() + samples + .iter() + .map(|sample| { + json!({ + "label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns + }) + }) + .collect::>() }); save( &root, @@ -727,25 +663,14 @@ fn pinned_new_slowpaths_match_completed_public_output() { if let Err(secondary) = cleanup_artifact { resume_unwind(secondary); } - save( - &root, - "CANDIDATE.json", - &candidate.json( - "candidate-only", - "integer-gu-native-down-retained-gr256-kv-only", - ), - ); + save(&root, "CANDIDATE.json", &candidate.json("candidate-only", "integer-gu-native-down-retained-gr256-kv-only")); assert!(disabled.is_ok() && moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok()); assert_eq!(allocated, 0); assert!(matches!(closed, Some(Ok(())))); assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - direct_down_report - .expect("loaded direct Down report missing") - .assert_after_teardown(); + direct_down_report.expect("loaded direct Down report missing").assert_after_teardown(); assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 - && w.pinned_hits > 0 - && w.metadata_bytes <= 16 * 1024 * 1024), + profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), "actual bounded pinned profile owner/hit witness missing" ); // Quality assertions follow every attempted teardown and preserve a primary @@ -753,14 +678,8 @@ fn pinned_new_slowpaths_match_completed_public_output() { assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!( - shared_tail_rows > 0, - "actual queued target shared tail was not executed" - ); - assert!( - router_rows.as_ref().is_ok_and(|rows| *rows > 1), - "actual router scratch was not reused" - ); + assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); assert!( lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, "actual indexed lookup/update/removal path was not exercised" @@ -783,14 +702,8 @@ fn pinned_new_slowpaths_match_completed_public_output() { ); assert!(candidate.measurement.completed && candidate.measurement.terminal_published); assert_eq!(candidate.measurement.retained_prefix_tokens, 0); - assert!( - offered > 0 && accepted > 0, - "actual candidate must offer and accept MTP drafts" - ); - assert!( - parity, - "candidate differs from retained actual Native output/finish/Usage" - ); + assert!(offered > 0 && accepted > 0, "actual candidate must offer and accept MTP drafts"); + assert!(parity, "candidate differs from retained actual Native output/finish/Usage"); eprintln!( "PUBLIC candidate-only framed={} output={} offered={offered} accepted={accepted} parity=true allocated=0 historical_speed_ratio=null", ids.len(), @@ -823,18 +736,12 @@ impl Inputs<'_, '_, '_> { #[test] #[ignore = "ROOT five public requests on one admitted owner; paired Original required"] fn pinned_five_public_cases_one_loaded_owner() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); let baseline = baseline(); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -847,22 +754,19 @@ fn pinned_five_public_cases_one_loaded_owner() { let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); let shard0_started = Instant::now(); let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0, observed_kar.as_ref(), - ).expect("pinned shard0 failed"); + &path("LELEKA_STRA169_IQ3S_SHARD0"), + SHARD0, + observed_kar.as_ref(), + ) + .expect("pinned shard0 failed"); let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); assert_eq!(ids, baseline.input_ids); @@ -878,8 +782,8 @@ fn pinned_five_public_cases_one_loaded_owner() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -895,13 +799,8 @@ fn pinned_five_public_cases_one_loaded_owner() { assert!(profile_file.metadata().unwrap().is_file()); assert_eq!(profile_file.metadata().unwrap().len(), 196_632); let mut profile_bytes = Vec::new(); - profile_bytes - .try_reserve_exact(196_632) - .expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file) - .take(196_633) - .read_to_end(&mut profile_bytes) - .unwrap(); + profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); + Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); assert_eq!(profile_bytes.len(), 196_632); crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) .expect("pure pinned profile admission failed before Driver"); @@ -948,17 +847,11 @@ fn pinned_five_public_cases_one_loaded_owner() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; - crate::qwen_forward::owner_wall_profile::arm() - .expect("actual owner wall profile admission failed"); + crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); inputs.arm_five_public_cases(&case_manifest, &case_manifest_sha) - })); let disabled = crate::qwen_forward::oracle_capture::disable(&output); let shared_tail_rows = moe.test_shared_tail_witness(); @@ -1002,10 +895,15 @@ fn pinned_five_public_cases_one_loaded_owner() { let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples.iter().map(|sample| json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - })).collect::>() + samples + .iter() + .map(|sample| { + json!({ + "label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns + }) + }) + .collect::>() }); save( &root, @@ -1051,9 +949,7 @@ fn pinned_five_public_cases_one_loaded_owner() { assert!(matches!(closed, Some(Ok(())))); assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 - && w.pinned_hits > 0 - && w.metadata_bytes <= 16 * 1024 * 1024), + profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), "actual bounded pinned profile owner/hit witness missing" ); // Quality assertions follow every attempted teardown and preserve a primary @@ -1061,14 +957,8 @@ fn pinned_five_public_cases_one_loaded_owner() { assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!( - shared_tail_rows > 0, - "actual queued target shared tail was not executed" - ); - assert!( - router_rows.as_ref().is_ok_and(|rows| *rows > 1), - "actual router scratch was not reused" - ); + assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); assert!( lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, "actual indexed lookup/update/removal path was not exercised" @@ -1084,14 +974,18 @@ fn pinned_five_public_cases_one_loaded_owner() { && first["text"].as_str() == Some(baseline.text.as_str()) && first["finish_reason"] == json!("Length") && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save(&root, "QUALITY.json", &json!({"case1_retained_native_parity":parity, + save( + &root, + "QUALITY.json", + &json!({"case1_retained_native_parity":parity, "quality_against_original17":null,"requires_matching_original_five":true, "changed_owner_policy":"digest-capture-queued-input-compact-head-GR-batch-1GiB-reusable-spill-floor", "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false})); + "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), + ); assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); } @@ -1099,18 +993,12 @@ fn pinned_five_public_cases_one_loaded_owner() { #[test] #[ignore = "ROOT five public requests on one admitted owner; paired Original required"] fn pinned_five_public_cases_retained_qk_qsa_owner() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); let baseline = baseline(); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -1123,22 +1011,19 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); let shard0_started = Instant::now(); let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture( - &path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0, observed_kar.as_ref(), - ).expect("pinned shard0 failed"); + &path("LELEKA_STRA169_IQ3S_SHARD0"), + SHARD0, + observed_kar.as_ref(), + ) + .expect("pinned shard0 failed"); let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); assert_eq!(ids, baseline.input_ids); @@ -1154,8 +1039,8 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -1171,13 +1056,8 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { assert!(profile_file.metadata().unwrap().is_file()); assert_eq!(profile_file.metadata().unwrap().len(), 196_632); let mut profile_bytes = Vec::new(); - profile_bytes - .try_reserve_exact(196_632) - .expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file) - .take(196_633) - .read_to_end(&mut profile_bytes) - .unwrap(); + profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); + Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); assert_eq!(profile_bytes.len(), 196_632); crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) .expect("pure pinned profile admission failed before Driver"); @@ -1224,17 +1104,16 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; - crate::qwen_forward::owner_wall_profile::arm() - .expect("actual owner wall profile admission failed"); + crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - fivecase_runtime::run_on_loaded_with_policy(&mut inputs, &case_manifest, &case_manifest_sha, "integer-gr256-streamed-spill-retained-qk40960-qsa108544") - + fivecase_runtime::run_on_loaded_with_policy( + &mut inputs, + &case_manifest, + &case_manifest_sha, + "integer-gr256-streamed-spill-retained-qk40960-qsa108544", + ) })); let disabled = crate::qwen_forward::oracle_capture::disable(&output); let shared_tail_rows = moe.test_shared_tail_witness(); @@ -1279,10 +1158,15 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples.iter().map(|sample| json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - })).collect::>() + samples + .iter() + .map(|sample| { + json!({ + "label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns + }) + }) + .collect::>() }); save( &root, @@ -1328,9 +1212,7 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { assert!(matches!(closed, Some(Ok(())))); assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); assert!( - profile_witness.is_ok_and(|w| w.prefix > 0 - && w.pinned_hits > 0 - && w.metadata_bytes <= 16 * 1024 * 1024), + profile_witness.is_ok_and(|w| w.prefix > 0 && w.pinned_hits > 0 && w.metadata_bytes <= 16 * 1024 * 1024), "actual bounded pinned profile owner/hit witness missing" ); // Quality assertions follow every attempted teardown and preserve a primary @@ -1338,14 +1220,8 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!( - shared_tail_rows > 0, - "actual queued target shared tail was not executed" - ); - assert!( - router_rows.as_ref().is_ok_and(|rows| *rows > 1), - "actual router scratch was not reused" - ); + assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); assert!( lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, "actual indexed lookup/update/removal path was not exercised" @@ -1354,7 +1230,10 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), "bounded actual index metadata charge missing" ); - assert!(retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), "actual retained scratch owner rows absent"); + assert!( + retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), + "actual retained scratch owner rows absent" + ); candidate.assert_after_teardown(); let first = &five_json["cases"][0]; assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); @@ -1362,14 +1241,18 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { && first["text"].as_str() == Some(baseline.text.as_str()) && first["finish_reason"] == json!("Length") && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save(&root, "QUALITY.json", &json!({"case1_retained_native_parity":parity, + save( + &root, + "QUALITY.json", + &json!({"case1_retained_native_parity":parity, "quality_against_original17":null,"requires_matching_original_five":true, "changed_owner_policy":"digest-capture-queued-input-compact-head-GR-batch-1GiB-spill-retained-qk40960-qsa108544", "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false})); + "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), + ); assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); } @@ -1377,18 +1260,12 @@ fn pinned_five_public_cases_retained_qk_qsa_owner() { #[test] #[ignore = "ROOT five public requests on one admitted owner; paired Original required"] fn pinned_five_public_cases_resident_owners() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_CANDIDATE_ONLY").as_deref(), Ok("yes")); let baseline = baseline(); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); @@ -1401,22 +1278,19 @@ fn pinned_five_public_cases_resident_owners() { let observed_kar = std::fs::File::open(format!("/proc/self/fd/{fd}")).ok(); let shard0_started = Instant::now(); let (shard0, expert_capture) = Qwen4ExpArtifact::open_shard0_with_expert_capture_incremental( - &path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0, observed_kar.as_ref(), - ).expect("pinned shard0 failed"); + &path("LELEKA_STRA169_IQ3S_SHARD0"), + SHARD0, + observed_kar.as_ref(), + ) + .expect("pinned shard0 failed"); let shard0_digest_capture_ns = shard0_started.elapsed().as_nanos(); drop(observed_kar); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); assert_eq!(ids, baseline.input_ids); @@ -1432,8 +1306,8 @@ fn pinned_five_public_cases_resident_owners() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -1449,13 +1323,8 @@ fn pinned_five_public_cases_resident_owners() { assert!(profile_file.metadata().unwrap().is_file()); assert_eq!(profile_file.metadata().unwrap().len(), 196_632); let mut profile_bytes = Vec::new(); - profile_bytes - .try_reserve_exact(196_632) - .expect("bounded profile allocation failed"); - Read::by_ref(&mut profile_file) - .take(196_633) - .read_to_end(&mut profile_bytes) - .unwrap(); + profile_bytes.try_reserve_exact(196_632).expect("bounded profile allocation failed"); + Read::by_ref(&mut profile_file).take(196_633).read_to_end(&mut profile_bytes).unwrap(); assert_eq!(profile_bytes.len(), 196_632); crate::qwen_forward::moe_weight_cache::validate_ranked_profile(&profile_bytes) .expect("pure pinned profile admission failed before Driver"); @@ -1479,7 +1348,8 @@ fn pinned_five_public_cases_resident_owners() { let output = OutputStage::load_compact(&binding, context.as_ref()).unwrap(); let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); // Profile admission observes all eager Dense/QSA/router and MTP owners. - let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(&binding, context.as_ref()).unwrap(); + let dense = DenseWeightCache::new_qsa_selected_router_gr_batch_qk_attention_mtp_journal(&binding, context.as_ref()) + .unwrap(); let preload_started = Instant::now(); let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( &binding, @@ -1502,17 +1372,16 @@ fn pinned_five_public_cases_resident_owners() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; - crate::qwen_forward::owner_wall_profile::arm() - .expect("actual owner wall profile admission failed"); + crate::qwen_forward::owner_wall_profile::arm().expect("actual owner wall profile admission failed"); let (case_manifest, case_manifest_sha) = inputs.prepare_five_public_frames(); - fivecase_runtime::run_on_loaded_with_policy(&mut inputs, &case_manifest, &case_manifest_sha, "integer-gr256-resident-owners-learned-main-shared192-gdn-journal-incremental-capture") - + fivecase_runtime::run_on_loaded_with_policy( + &mut inputs, + &case_manifest, + &case_manifest_sha, + "integer-gr256-resident-owners-learned-main-shared192-gdn-journal-incremental-capture", + ) })); let disabled = crate::qwen_forward::oracle_capture::disable(&output); let shared_tail_rows = moe.test_shared_tail_witness(); @@ -1520,14 +1389,16 @@ fn pinned_five_public_cases_resident_owners() { let lru_metadata_bytes = moe.test_lru_metadata_bytes(); let profile_witness = moe.learned_main_witness(&binding); let shared_witness = moe.shared_permanent_witness(); - let profile_json = profile_witness.as_ref().ok().map(|w| json!({ - "policy":"learned-main-lru-shared192", "routed_matrices":w.routed_matrices, - "routed_bytes":w.routed_bytes,"shared_matrices":w.shared_matrices,"shared_bytes":w.shared_bytes, - "main_bytes":w.main_bytes,"main_slot_limit":w.main_slot_limit,"metadata_bytes":w.metadata_bytes, - "historical_prefix":w.historical_prefix,"historical_routed_preload_bytes":w.historical_routed_preload_bytes, - "age":w.age,"preload_ns":preload_ns,"normal_defaults_changed":false, - "shared_witness_valid":shared_witness.is_ok() - })); + let profile_json = profile_witness.as_ref().ok().map(|w| { + json!({ + "policy":"learned-main-lru-shared192", "routed_matrices":w.routed_matrices, + "routed_bytes":w.routed_bytes,"shared_matrices":w.shared_matrices,"shared_bytes":w.shared_bytes, + "main_bytes":w.main_bytes,"main_slot_limit":w.main_slot_limit,"metadata_bytes":w.metadata_bytes, + "historical_prefix":w.historical_prefix,"historical_routed_preload_bytes":w.historical_routed_preload_bytes, + "age":w.age,"preload_ns":preload_ns,"normal_defaults_changed":false, + "shared_witness_valid":shared_witness.is_ok() + }) + }); let mtp_input_completions = moe.test_mtp_input_completions(); let moe_closed = moe.close(); let router_rows = dense.test_router_witness(); @@ -1552,10 +1423,15 @@ fn pinned_five_public_cases_resident_owners() { let owner_wall_profile = crate::qwen_forward::owner_wall_profile::drain(); let cleanup_artifact = catch_unwind(AssertUnwindSafe(|| { let profile_rows = owner_wall_profile.as_ref().ok().map(|samples| { - samples.iter().map(|sample| json!({ - "label":sample.label,"attempted_scope_count":sample.count, - "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns - })).collect::>() + samples + .iter() + .map(|sample| { + json!({ + "label":sample.label,"attempted_scope_count":sample.count, + "inclusive_owner_wall_ns":sample.total_ns,"max_scope_ns":sample.max_ns + }) + }) + .collect::>() }); save( &root, @@ -1600,22 +1476,19 @@ fn pinned_five_public_cases_resident_owners() { assert_eq!(allocated, 0); assert!(matches!(closed, Some(Ok(())))); assert!(owner_wall_profile.is_ok(), "actual owner wall profile drain failed"); - assert!(profile_witness.is_ok_and(|w| w.routed_matrices > 0 && w.shared_matrices == 192 - && w.metadata_bytes <= 16 * 1024 * 1024), "actual learned main owner witness missing"); + assert!( + profile_witness + .is_ok_and(|w| w.routed_matrices > 0 && w.shared_matrices == 192 && w.metadata_bytes <= 16 * 1024 * 1024), + "actual learned main owner witness missing" + ); assert!(shared_witness.is_ok(), "actual shared owner role witness missing"); // Quality assertions follow every attempted teardown and preserve a primary // generation panic/error. There is no Native call or historical timing ratio. assert!(gr_batch_completions > 0, "actual retained GR batch injection did not complete"); assert!(compact_head_completions > 0, "actual compact full-vocabulary head did not complete"); assert!(mtp_input_completions > 0, "actual completed MTP input queue was not executed"); - assert!( - shared_tail_rows > 0, - "actual queued target shared tail was not executed" - ); - assert!( - router_rows.as_ref().is_ok_and(|rows| *rows > 1), - "actual router scratch was not reused" - ); + assert!(shared_tail_rows > 0, "actual queued target shared tail was not executed"); + assert!(router_rows.as_ref().is_ok_and(|rows| *rows > 1), "actual router scratch was not reused"); assert!( lru_witness.0 > 0 && lru_witness.1 > 0 && lru_witness.2 > 0, "actual indexed lookup/update/removal path was not exercised" @@ -1624,7 +1497,10 @@ fn pinned_five_public_cases_resident_owners() { lru_metadata_bytes.is_ok_and(|bytes| bytes > 0 && bytes <= 16 * 1024 * 1024), "bounded actual index metadata charge missing" ); - assert!(retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), "actual retained scratch owner rows absent"); + assert!( + retained_scratch_witness.is_ok_and(|(bytes, rows)| bytes == 149504 && rows > 1), + "actual retained scratch owner rows absent" + ); candidate.assert_after_teardown(); let first = &five_json["cases"][0]; assert_eq!(token_ids(&first["input_token_ids"]), baseline.input_ids); @@ -1632,14 +1508,18 @@ fn pinned_five_public_cases_resident_owners() { && first["text"].as_str() == Some(baseline.text.as_str()) && first["finish_reason"] == json!("Length") && first["usage"] == json!({"input_tokens":202,"output_tokens":32,"reused_input_tokens":0}); - save(&root, "QUALITY.json", &json!({"case1_retained_native_parity":parity, + save( + &root, + "QUALITY.json", + &json!({"case1_retained_native_parity":parity, "quality_against_original17":null,"requires_matching_original_five":true, "changed_owner_policy":"incremental-capture-learned-main-shared192-gdn-journal-qk40960-qsa108544", "spill_floor_bytes":1073741824u64,"actual_cuda_driver_version":driver_version, "model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"hardware":hardware, "allocated":allocated,"cleanup_complete":true,"same_request_case1":true, "cache_state":"no replayed helper; actual per-case before/after counters; same loaded owners but fresh target/draft each request", - "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false})); + "GateC":false,"GateD":false,"performance_acceptance":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false}), + ); assert!(parity, "case1 differs from retained actual Native IDs/text/Length/Usage"); eprintln!("PUBLIC five cases completed allocated=0 case1_native_parity=true paired_original_pending=true"); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs index 6cdc4737..4aa34697 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_down_public_pair.rs @@ -19,9 +19,7 @@ static ARTIFACT_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::Atomi fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { ARTIFACT_BYTES .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { - current - .checked_add(bytes) - .filter(|next| *next <= ARTIFACT_CAP) + current.checked_add(bytes).filter(|next| *next <= ARTIFACT_CAP) }) .map(|_| ()) .map_err(|_| std::io::Error::other("whole public pair artifact cap exceeded")) @@ -29,26 +27,16 @@ fn reserve_artifacts(bytes: usize) -> std::io::Result<()> { const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; const CAP: u32 = 32; fn path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing ROOT-owned public pair path") + env::var_os(name).map(PathBuf::from).expect("missing ROOT-owned public pair path") } fn sha(bytes: &[u8]) -> String { - Sha256::digest(bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() + Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect() } fn save(root: &std::path::Path, name: &str, value: &Value) { let bytes = serde_json::to_vec(value).expect("public pair JSON encoding failed"); assert!(bytes.len() <= 1024 * 1024); - reserve_artifacts( - bytes - .len() - .checked_add(1) - .expect("JSON newline extent overflow"), - ) - .expect("whole public pair serialized budget exceeded"); + reserve_artifacts(bytes.len().checked_add(1).expect("JSON newline extent overflow")) + .expect("whole public pair serialized budget exceeded"); let mut f = OpenOptions::new() .write(true) .create_new(true) @@ -84,9 +72,7 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { "PUBLIC deterministic evaluation document; no private agent content.\nTicket LV-17 is READY.\n", ); for index in 0..lines { - document.push_str(&format!( - "Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n" - )); + document.push_str(&format!("Record {index}: LV-17 has priority 3; status READY; owner PUBLIC.\n")); } document.push_str("Return this public sequence once, without explanation: amber birch cedar delta elm fern grove hazel iris jade kelp lake moss north oak pine quartz reed sage thyme umber vale willow xenon yew zinc amber birch cedar delta elm fern."); let prompt = public_renderer::render( @@ -111,10 +97,10 @@ fn request(tokenizer: &Tokenizer) -> (GenerationRequest, Vec, Value) { request_id: "public-paired-owner-generation".into(), prompt, max_output_tokens: CAP, - temperature_milli: 0, sampling: Default::default(), + temperature_milli: 0, + sampling: Default::default(), }; - let ids = prepare_prompt(tokenizer, &req, 262144) - .expect("actual pinned tokenizer refused public frame"); + let ids = prepare_prompt(tokenizer, &req, 262144).expect("actual pinned tokenizer refused public frame"); if (193..=256).contains(&ids.len()) { let canonical = json!({"model":"pinned-native-model","instructions":instructions,"input":document,"tools":[],"max_output_tokens":CAP,"temperature":0,"stream":true,"store":false}); return (req, ids, canonical); @@ -168,11 +154,9 @@ impl Inputs<'_, '_, '_> { ); // Fresh genuine target state and fresh actual decoder. No position reset, // invented prefix, checkpoint reuse or cached-token count substitution. - let mut session = - QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); + let mut session = QwenSession::for_binding_on_shared_device(self.binding, Rc::clone(self.context)); let cancel = AtomicBool::new(false); - let (sink, mut stream) = - GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); + let (sink, mut stream) = GenerationSink::bounded_channel(QUEUE).expect("actual pair channel refused"); let drain = thread::spawn(move || { let mut text = String::new(); let mut usage = None; @@ -197,8 +181,7 @@ impl Inputs<'_, '_, '_> { (text, usage, terminal) }); let before = cache(self.moe.counters(), self.dense.counters()); - let recorder = - std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); + let recorder = std::cell::RefCell::new(measurement::Recorder::new(ids, req.max_output_tokens)); let mut pending = None; let result = generate_mtp_resume( Generation { @@ -216,7 +199,8 @@ impl Inputs<'_, '_, '_> { shared: &self.shared, context_tokens: 262144, eos: self.eos, - mtp: true, clock: SystemClock, + mtp: true, + clock: SystemClock, }, ids, req.max_output_tokens, @@ -228,11 +212,9 @@ impl Inputs<'_, '_, '_> { Err(failure) => { let terminal = match failure { GenerationFailure::Cancelled => GenerationTerminal::Cancelled, - GenerationFailure::Backend(error) => GenerationTerminal::Failed { - code: error.code, - message: error.message, - retryable: false, - }, + GenerationFailure::Backend(error) => { + GenerationTerminal::Failed { code: error.code, message: error.message, retryable: false } + } }; let diagnostic = format!("{terminal:?}"); let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); @@ -251,10 +233,7 @@ impl Inputs<'_, '_, '_> { panic!("actual public pair generation failed; bounded failure artifact retained"); } }; - let terminal = GenerationTerminal::Completed { - reason: reason.clone(), - usage: usage.clone(), - }; + let terminal = GenerationTerminal::Completed { reason: reason.clone(), usage: usage.clone() }; let published = emit_terminal(&sink, terminal.clone(), &SystemClock).is_ok(); drop(sink); let (text, seen_usage, seen_terminal) = drain.join().expect("actual pair consumer failed"); @@ -270,21 +249,12 @@ impl Inputs<'_, '_, '_> { true, matches!(reason, FinishReason::Stop), published, - Some(( - usage.input_tokens, - usage.output_tokens, - usage.reused_input_tokens, - )), + Some((usage.input_tokens, usage.output_tokens, usage.reused_input_tokens)), ) .expect("actual owner measurement refused"); assert_eq!(measured.input_token_ids, ids); assert_eq!(measured.retained_prefix_tokens, 0); - Arm { - measurement: measured, - text, - usage, - reason, - } + Arm { measurement: measured, text, usage, reason } } } fn metadata() -> Value { @@ -295,15 +265,11 @@ fn metadata() -> Value { .expect("ROOT public measurement metadata required"); assert!(f.metadata().unwrap().is_file()); let mut b = Vec::new(); - std::io::Read::by_ref(&mut f) - .take(16385) - .read_to_end(&mut b) - .unwrap(); + std::io::Read::by_ref(&mut f).take(16385).read_to_end(&mut b).unwrap(); assert!(b.len() <= 16384); assert_eq!( sha(&b), - env::var("LELEKA_STRA169_PAIR_METADATA_SHA") - .expect("ROOT exact public metadata digest required") + env::var("LELEKA_STRA169_PAIR_METADATA_SHA").expect("ROOT exact public metadata digest required") ); let value: Value = serde_json::from_slice(&b).unwrap(); let o = value.as_object().expect("public metadata object required"); @@ -317,10 +283,7 @@ fn metadata() -> Value { "clocks", "context_tokens", ] { - assert!( - o.get(key).is_some_and(|v| !v.is_null()), - "actual hardware/profile metadata required" - ); + assert!(o.get(key).is_some_and(|v| !v.is_null()), "actual hardware/profile metadata required"); } assert!(o.keys().all(|k| { [ @@ -341,36 +304,23 @@ fn metadata() -> Value { #[test] #[ignore = "ROOT one-load public paired owner generation; no serving overlap"] fn pinned_single_load_public_native_vs_native_down_outer256_pair() { - assert_eq!( - env::var("LELEKA_STRA169_RUN_PUBLIC_NATIVE_DOWN_PAIR").as_deref(), - Ok("yes") - ); + assert_eq!(env::var("LELEKA_STRA169_RUN_PUBLIC_NATIVE_DOWN_PAIR").as_deref(), Ok("yes")); let hardware = metadata(); let root = path("LELEKA_STRA169_PAIR_OUTPUT"); assert!(root.is_absolute() && !root.exists()); - assert_eq!( - root.parent().unwrap().canonicalize().unwrap(), - root.parent().unwrap() - ); + assert_eq!(root.parent().unwrap().canonicalize().unwrap(), root.parent().unwrap()); std::fs::create_dir(&root).unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap(); let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").unwrap().parse().unwrap(); assert!((3..=1048576).contains(&fd)); - let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0) - .expect("pinned shard0 failed"); - let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) - .expect("pinned shard1 failed"); + let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 failed"); + let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 failed"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact failed"); let m = artifact.tokenizer(); - let tokenizer = Tokenizer::from_vocabulary( - &m.model, - &m.pre, - m.tokens.clone(), - m.merges.clone(), - m.token_types.clone(), - ) - .expect("actual pinned tokenizer failed"); + let tokenizer = + Tokenizer::from_vocabulary(&m.model, &m.pre, m.tokens.clone(), m.merges.clone(), m.token_types.clone()) + .expect("actual pinned tokenizer failed"); let eos = *m.special_ids.get("tokenizer.ggml.eos_token_id").unwrap(); let (req, ids, canonical) = request(&tokenizer); save(&root, "PUBLIC-REQUEST.json", &canonical); @@ -379,8 +329,8 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { "FRAME.json", &json!({"renderer_source_sha256":sha(include_bytes!("../../../../crates/gateway-text/src/prompt.rs")),"framed_prompt":req.prompt,"framed_prompt_sha256":sha(req.prompt.as_bytes()),"input_token_ids":ids,"framed_count":ids.len(),"model_digest":MODEL_DIGEST,"max_output_tokens":CAP,"temperature_milli":0}), ); - let inherited = InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("inherited sealed KAR failed"); + let inherited = + InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited sealed KAR failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( artifact, &inherited, @@ -401,18 +351,14 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { reserve_artifacts, ) .expect("actual public long preflight refused before CUDA initialization"); - eprintln!( - "PUBLIC long preflight serialized_bytes={long_bytes}; whole package cap={ARTIFACT_CAP}" - ); + eprintln!("PUBLIC long preflight serialized_bytes={long_bytes}; whole package cap={ARTIFACT_CAP}"); let driver = Driver::load().expect("actual CUDA driver failed"); let driver_version = driver.version(); let device = driver.device(0).unwrap(); let context = Rc::new(device.create_context(DEVICE_BUDGET).unwrap()); let output = OutputStage::load(&binding, context.as_ref()).unwrap(); let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); - let mut moe = - MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv(&binding, context.as_ref()) - .unwrap(); + let mut moe = MoeWeightCache::new_native_integer_iq3_mmq_retained_mtp_kv(&binding, context.as_ref()).unwrap(); let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap(); let pair = catch_unwind(AssertUnwindSafe(|| { let mut inputs = Inputs { @@ -424,20 +370,12 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { tokenizer: &tokenizer, context: &context, eos, - shared: Shared { - ready: AtomicBool::new(true), - shutdown: AtomicBool::new(false), - active: Mutex::new(None), - }, + shared: Shared { ready: AtomicBool::new(true), shutdown: AtomicBool::new(false), active: Mutex::new(None) }, }; // Warm exact PUBLIC traffic once per policy; fresh numeric state every // arm. Actual misses/uploads are still recorded, never called fully hot. let warm_a = inputs.arm(&req, &ids, EvaluationExecution::Native, "warm-native64"); - save( - &root, - "WARM-NATIVE64.json", - &warm_a.json("warm", "native64-same-dual-cache-retained-mtp-kv"), - ); + save(&root, "WARM-NATIVE64.json", &warm_a.json("warm", "native64-same-dual-cache-retained-mtp-kv")); let warm_b = inputs.arm( &req, &ids, @@ -447,17 +385,10 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { save( &root, "WARM-NATIVE-DOWN256.json", - &warm_b.json( - "warm", - "integer-gu-native-down-retained-gr256-retained-mtp-kv", - ), + &warm_b.json("warm", "integer-gu-native-down-retained-gr256-retained-mtp-kv"), ); let a = inputs.arm(&req, &ids, EvaluationExecution::Native, "measured-native64"); - save( - &root, - "MEASURED-NATIVE64.json", - &a.json("measured", "native64-same-dual-cache-retained-mtp-kv"), - ); + save(&root, "MEASURED-NATIVE64.json", &a.json("measured", "native64-same-dual-cache-retained-mtp-kv")); let b = inputs.arm( &req, &ids, @@ -467,10 +398,7 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { save( &root, "MEASURED-NATIVE-DOWN256.json", - &b.json( - "measured", - "integer-gu-native-down-retained-gr256-retained-mtp-kv", - ), + &b.json("measured", "integer-gu-native-down-retained-gr256-retained-mtp-kv"), ); (warm_a, warm_b, a, b) })); @@ -527,10 +455,7 @@ fn pinned_single_load_public_native_vs_native_down_outer256_pair() { "PAIR.json", &json!({"scope":"actual public framed owner prefill/decode; excludes HTTP/daemon/tool-task and model load","model_digest":MODEL_DIGEST,"profile":KAR_MTP_PROFILE,"device_budget_bytes":DEVICE_BUDGET,"context_tokens":262144,"hardware":hardware,"actual_cuda_driver_version":driver_version,"framed_tokens":ids.len(),"output_cap":CAP,"measured_order":["Native64","IntegerGU-nativeDown-retainedGR256"],"cache_state":"same loaded model/shared actual native-integer dual weight owner, retained MTP KV ring and counters; real MMQ transient reservation before packets; prewarmed PUBLIC request once each; fresh numeric target+draft each arm; not assumed all expert hits","greedy_output_ids_equal":parity,"actual_mtp_offered":{"baseline":a.offered(),"candidate":b.offered()},"actual_mtp_exercised":mtp,"natural_early_eos_or_no_draft_scope":!mtp,"baseline_prefill_ns":u64::try_from(a.measurement.prefill.as_nanos()).unwrap(),"candidate_prefill_ns":u64::try_from(b.measurement.prefill.as_nanos()).unwrap(),"baseline_decode_ns":u64::try_from(a.measurement.decode.as_nanos()).unwrap(),"candidate_decode_ns":u64::try_from(b.measurement.decode.as_nanos()).unwrap(),"single_descriptive_pair":true,"owner_prefill_ratio_if_equal_work":if parity && !b.measurement.prefill.is_zero() {Some(a.measurement.prefill.as_secs_f64()/b.measurement.prefill.as_secs_f64())}else{None},"owner_decode_ratio_if_equal_work":if parity && !b.measurement.decode.is_zero() {Some(a.measurement.decode.as_secs_f64()/b.measurement.decode.as_secs_f64())}else{None},"same_actual_device_context":true,"retained_mtp_kv_factory":true,"mmq_transient_reservation":true,"GateC":false,"GateD":false,"HTTP_endagent_speed_claim":false,"longcontext_170K":false,"allocated":0,"cleanup_complete":true}), ); - assert!( - parity, - "actual PUBLIC output token/text/finish/Usage parity failed; no equal-work speed claim" - ); + assert!(parity, "actual PUBLIC output token/text/finish/Usage parity failed; no equal-work speed claim"); eprintln!( "PUBLIC native64/nativeDown-retainedGR256 owner pair recorded framed={} output={} actual_mtp={} allocated=0 GateC=false GateD=false HTTP=false longcontext=false", ids.len(), diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs index 76c6ff05..df8b1146 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/native_resident_mmq_model_proof.rs @@ -6,9 +6,7 @@ use std::{ }; const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned MMQ proof path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path") } // New root-only phase: fresh real target owner; no repeated capture/prefix phases. #[test] @@ -27,8 +25,7 @@ fn pinned_single_load_native_resident_mmq_model_numeric() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -40,20 +37,10 @@ fn pinned_single_load_native_resident_mmq_model_numeric() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); let execution = EvaluationExecution::ExperimentalNativeResidentMmq; let mut moe = match execution { EvaluationExecution::ExperimentalNativeResidentMmq => { @@ -62,13 +49,10 @@ fn pinned_single_load_native_resident_mmq_model_numeric() { _ => panic!("native-certified activation policy required"), } .expect("actual native-certified MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical = catch_unwind(AssertUnwindSafe(|| { let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - let report = QwenForward::test_native_mmq_on_loaded( - &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, - ); + let report = QwenForward::test_native_mmq_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); drop(chunk); report })); @@ -94,32 +78,18 @@ fn pinned_single_load_native_resident_mmq_model_numeric() { Ok(report) => report, Err(primary) => resume_unwind(primary), }; - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); // No GPU/cache/session owners remain when diagnosis and strict quality // assertions run. Tensor exactness remains reported, as in the frozen gate. - for (phase, head) in [ - ("final", &report.final_head), - ("continuation", &report.continuation_head), - ] { + for (phase, head) in [("final", &report.final_head), ("continuation", &report.continuation_head)] { eprintln!( "native-resident MMQ observation phase={} fullhead_words={} different={} max_abs={} native_greedy={} candidate_greedy={} allocated_bytes=0 GateC=false speed_claim=false", - phase, - head.words, - head.different, - head.max_abs, - head.baseline_greedy, - head.candidate_greedy + phase, head.words, head.different, head.max_abs, head.baseline_greedy, head.candidate_greedy ); } eprintln!( diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs index 39c18e3b..b8e1a9e1 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/resident_mmq_model_proof.rs @@ -6,9 +6,7 @@ use std::{ }; const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned MMQ proof path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned MMQ proof path") } // New root-only phase: fresh real target owner; no repeated capture/prefix phases. #[test] @@ -27,8 +25,7 @@ fn pinned_single_load_resident_mmq_model_numeric() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -40,24 +37,12 @@ fn pinned_single_load_resident_mmq_model_numeric() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); - let mut moe = MoeWeightCache::new_mmq(&binding, context.as_ref()) - .expect("actual MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); + let mut moe = MoeWeightCache::new_mmq(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical = catch_unwind(AssertUnwindSafe(|| { let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); QwenForward::test_mmq_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); @@ -84,17 +69,11 @@ fn pinned_single_load_resident_mmq_model_numeric() { if let Err(primary) = numerical { resume_unwind(primary); } - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); eprintln!("resident MMQ model proof teardown PASS allocated_bytes=0 context_closed=true"); } diff --git a/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs b/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs index 6bf1e5e7..0b1363c1 100644 --- a/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs +++ b/crates/engine-qwen35-cuda/src/gpu_proofs/singleload_proof.rs @@ -10,9 +10,7 @@ use std::{ const DEVICE_BUDGET: usize = 28 * 1024 * 1024 * 1024; fn required_path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing operator-owned prefix test path") + env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path") } #[test] @@ -31,8 +29,7 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let metadata = artifact.tokenizer(); let tokenizer = Tokenizer::from_vocabulary( &metadata.model, @@ -42,10 +39,7 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() { metadata.token_types.clone(), ) .expect("verified prefix tokenizer construction failed"); - let eos = *metadata - .special_ids - .get("tokenizer.ggml.eos_token_id") - .expect("verified prefix EOS absent"); + let eos = *metadata.special_ids.get("tokenizer.ggml.eos_token_id").expect("verified prefix EOS absent"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -57,24 +51,12 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); - let mut moe = MoeWeightCache::new(&binding, context.as_ref()) - .expect("actual MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); + let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical = catch_unwind(AssertUnwindSafe(|| { let mut captured = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let capture = crate::qwen_forward::oracle_capture::check_on_loaded( @@ -108,9 +90,7 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() { drop(resumed); drop(fresh); let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - QwenForward::test_chunk_on_loaded( - &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, - ); + QwenForward::test_chunk_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); drop(chunk); })); // Attempt teardown even after a numerical assertion: no new device work, @@ -134,18 +114,12 @@ fn pinned_single_load_capture_two_combined_reuse_and_chunk_numeric() { if let Err(primary) = numerical { resume_unwind(primary); } - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); eprintln!("singleload proof teardown PASS allocated_bytes=0 context_closed=true"); } @@ -166,8 +140,7 @@ fn pinned_single_load_grouped_certified_chunk_numeric() { .expect("pinned prefix shard0 verification failed"); let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1) .expect("pinned prefix shard1 verification failed"); - let artifact = - Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned prefix artifact binding failed"); let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")) .expect("pinned inherited sealed KAR admission failed"); let binding = ModelBinding::from_artifact_with_inherited_kar_mtp( @@ -179,29 +152,15 @@ fn pinned_single_load_grouped_certified_chunk_numeric() { .expect("actual pinned KAR+MTP binding failed"); let driver = Driver::load().expect("prefix CUDA driver load failed"); let device = driver.device(0).expect("prefix CUDA device0 unavailable"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("bounded prefix Context unavailable"), - ); - let output = OutputStage::load(&binding, context.as_ref()) - .expect("resident prefix output head unavailable"); - let mut kar = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("actual KAR binding absent"), - ) - .expect("actual KAR device cache unavailable"); - let mut moe = MoeWeightCache::new(&binding, context.as_ref()) - .expect("actual MoE/MTP device cache unavailable"); - let dense = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actual dense device cache unavailable"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident prefix output head unavailable"); + let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("actual KAR binding absent")) + .expect("actual KAR device cache unavailable"); + let mut moe = MoeWeightCache::new(&binding, context.as_ref()).expect("actual MoE/MTP device cache unavailable"); + let dense = DenseWeightCache::new(&binding, context.as_ref()).expect("actual dense device cache unavailable"); let numerical = catch_unwind(AssertUnwindSafe(|| { let mut chunk = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - QwenForward::test_chunk_on_loaded( - &binding, &mut chunk, &output, &mut kar, &mut moe, &dense, - ); + QwenForward::test_chunk_on_loaded(&binding, &mut chunk, &output, &mut kar, &mut moe, &dense); drop(chunk); })); // Attempt teardown even after a numerical assertion: no new device work, @@ -225,17 +184,11 @@ fn pinned_single_load_grouped_certified_chunk_numeric() { if let Err(primary) = numerical { resume_unwind(primary); } - assert!( - observation_disabled.is_ok(), - "final capture observation cleanup failed" - ); + assert!(observation_disabled.is_ok(), "final capture observation cleanup failed"); assert!(moe_closed.is_ok(), "prefix MoE/MTP teardown failed"); assert!(dense_closed.is_ok(), "prefix dense teardown failed"); assert!(synchronized.is_ok(), "prefix final synchronization failed"); assert_eq!(allocated, 0, "prefix proof retained owned device buffers"); - assert!( - matches!(closed, Some(Ok(()))), - "prefix Context teardown failed" - ); + assert!(matches!(closed, Some(Ok(()))), "prefix Context teardown failed"); eprintln!("grouped certified chunk proof teardown PASS allocated_bytes=0 context_closed=true"); } diff --git a/crates/engine-qwen35-cuda/src/idle_sweep.rs b/crates/engine-qwen35-cuda/src/idle_sweep.rs index 5ed65086..96bf8834 100644 --- a/crates/engine-qwen35-cuda/src/idle_sweep.rs +++ b/crates/engine-qwen35-cuda/src/idle_sweep.rs @@ -16,10 +16,7 @@ pub(crate) struct IdleSweep { impl IdleSweep { /// A sweep that is first due `every` after `clock`'s present reading. pub(crate) fn new(every: Duration, clock: &impl Clock) -> Self { - Self { - every, - last: clock.now(), - } + Self { every, last: clock.now() } } /// True when `every` has passed since the last due sweep (or since `new`); the next period then starts now. diff --git a/crates/engine-qwen35-cuda/src/lib.rs b/crates/engine-qwen35-cuda/src/lib.rs index 026f79eb..8f83eb6b 100644 --- a/crates/engine-qwen35-cuda/src/lib.rs +++ b/crates/engine-qwen35-cuda/src/lib.rs @@ -1,6 +1,5 @@ //! Independent Qwen runtime. CUDA state stays inside its dedicated owner thread. - /// Bring-up tracing: `LELEKA_BRINGUP_TRACE` set (any value) enables the `DBG`/`PROBE` diagnostics on stderr. /// Off by default so production serving prints nothing extra. pub(crate) fn bringup_trace_enabled() -> bool { @@ -19,23 +18,23 @@ macro_rules! bringup_trace { } pub(crate) use bringup_trace; +pub mod backend; pub(crate) mod idle_sweep; pub(crate) mod load_clock; pub(crate) mod settings; -pub mod backend; pub use leleka_context::{context_policy, memory_plan, rope_scaling}; pub mod conversation; pub use leleka_engine_core::prefix_cache; -pub mod serve_tuning; +pub mod experimental; +pub(crate) mod memory_governor; #[cfg_attr(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")), allow(dead_code))] pub(crate) mod serve_meta; -pub(crate) mod memory_governor; -pub mod experimental; +pub mod serve_tuning; pub use backend::spawn_backend_observed_native_integer_iq3_windowed256_retained_gr; pub use backend::spawn_backend_observed_native_resident_mmq; pub use backend::spawn_backend_observed_windowed256_retained_gr; -pub mod serving; pub(crate) mod model_binding; pub(crate) mod qwen_forward; +pub mod serving; diff --git a/crates/engine-qwen35-cuda/src/memory_governor.rs b/crates/engine-qwen35-cuda/src/memory_governor.rs index da8b06b0..949b673d 100644 --- a/crates/engine-qwen35-cuda/src/memory_governor.rs +++ b/crates/engine-qwen35-cuda/src/memory_governor.rs @@ -5,12 +5,13 @@ //! The decisions live in `leleka-memory` (pure, tested on fixtures); this file only gathers the facts and applies the answers. //! See `docs/memory-safety.md`. +use crate::settings::{EnvSource, Settings}; use leleka_backend_api::BackendError; use leleka_memory::ledger::{DeviceSample, OpenStage}; use leleka_memory::{ - CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, RealProc, SamplerGuard, Space, VramFacts, When, + CacheWish, Entry, FixedItem, Governor, GovernorConfig, HostFacts, KarForm, PlanInput, RealProc, SamplerGuard, + Space, VramFacts, When, }; -use crate::settings::{EnvSource, Settings}; use std::sync::Mutex; /// Bytes of a conversation checkpoint (the GDN/PLE images, the draft ring and the index tails): 118 MB measured by the @@ -65,8 +66,11 @@ pub(crate) fn install(laptop: bool, settings: &Settings) -> Result<&'static Gove } let facts = HostFacts::probe(&RealProc); let total = facts.effective_total().unwrap_or(0); - let cfg = GovernorConfig::from_env(total, laptop, &|k| settings.env().get(k)) - .map_err(|e| BackendError { code: leleka_backend_api::ErrorCode::InvalidRequest, message: e, retryable: false })?; + let cfg = GovernorConfig::from_env(total, laptop, &|k| settings.env().get(k)).map_err(|e| BackendError { + code: leleka_backend_api::ErrorCode::InvalidRequest, + message: e, + retryable: false, + })?; let g = Governor::real(cfg).install(); let mut sampler = SAMPLER.lock().unwrap_or_else(|p| p.into_inner()); if sampler.is_none() { @@ -93,15 +97,25 @@ pub(crate) fn startup(args: &StartArgs, settings: &Settings) -> Result<&'static let total = g.probe().effective_total().unwrap_or(0); // `LELEKA_MAPPED_WORKING_SET_GIB`: the hot part the plan should expect to stay resident when the desktop competes for RAM (the workstation // preset on Windows sets it; the OS still decides what is really resident, this is the accounting of the start check and the cache budgets). - let reserve = settings - .serve - .mapped_working_set_gib - .map_or_else(|| mapped_working_set(total, RESIDENT_BANK_BYTES), |gib| ((gib * (1u64 << 30) as f64) as u64).min(RESIDENT_BANK_BYTES)); + let reserve = settings.serve.mapped_working_set_gib.map_or_else( + || mapped_working_set(total, RESIDENT_BANK_BYTES), + |gib| ((gib * (1u64 << 30) as f64) as u64).min(RESIDENT_BANK_BYTES), + ); MAPPED_WORKING_SET.store(reserve, std::sync::atomic::Ordering::Release); - fixed.push(FixedItem::new("expert_bank_working_set", reserve, Space::HostMapped, "min(MemTotal / 2, bank): the hot part of the file-mapped bank, reclaimable but constantly touched")); + fixed.push(FixedItem::new( + "expert_bank_working_set", + reserve, + Space::HostMapped, + "min(MemTotal / 2, bank): the hot part of the file-mapped bank, reclaimable but constantly touched", + )); } else { MAPPED_WORKING_SET.store(0, std::sync::atomic::Ordering::Release); - fixed.push(FixedItem::new("expert_bank_resident", RESIDENT_BANK_BYTES, Space::HostPinned, "routed experts of shard 0 as a RAM copy (--expert-source resident)")); + fixed.push(FixedItem::new( + "expert_bank_resident", + RESIDENT_BANK_BYTES, + Space::HostPinned, + "routed experts of shard 0 as a RAM copy (--expert-source resident)", + )); } fixed.push(FixedItem::new( "rings_staging_pool_checkpoints", @@ -111,7 +125,9 @@ pub(crate) fn startup(args: &StartArgs, settings: &Settings) -> Result<&'static )); let kar = match args.kar_file_backed { Some(true) => KarForm::File { bytes: crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES }, - _ => KarForm::MemfdInherited { bytes: args.kar_sparse_bytes.unwrap_or(crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES) }, + _ => KarForm::MemfdInherited { + bytes: args.kar_sparse_bytes.unwrap_or(crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES), + }, }; let host = g.probe(); let resident_complement = settings @@ -142,7 +158,10 @@ pub(crate) fn startup(args: &StartArgs, settings: &Settings) -> Result<&'static /// Lock the sealed memfd (when the limits allow) and keep the residency guard on it; a no-op for the file-backed archive. #[cfg(all(target_os = "linux", target_arch = "x86_64"))] -pub(crate) fn guard_archive(g: &Governor, archive: &crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive) -> Result<(), BackendError> { +pub(crate) fn guard_archive( + g: &Governor, + archive: &crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive, +) -> Result<(), BackendError> { use std::os::fd::AsFd; if archive.file_backed() { return Ok(()); @@ -150,9 +169,13 @@ pub(crate) fn guard_archive(g: &Governor, archive: &crate::model_binding::qwen4e // A sparse memfd (`--kar-sparse-extents-sha256`) holds only the extents the serve path reads: lock, heal and count those, never a hole // (locking a hole allocates zero pages for it). let extents = archive.sparse_extents(); - g.guard_archive_extents(archive.archive_handle().as_fd(), crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES, extents.as_deref()) - .map(|_| ()) - .map_err(|r| refusal_error(r.to_string()))?; + g.guard_archive_extents( + archive.archive_handle().as_fd(), + crate::model_binding::qwen4exp_kar_ple::PINNED_ARCHIVE_BYTES, + extents.as_deref(), + ) + .map(|_| ()) + .map_err(|r| refusal_error(r.to_string()))?; let (bytes, what) = match &extents { Some(spans) => ( leleka_memory::lock::spans_bytes(spans), @@ -178,7 +201,11 @@ pub(crate) fn device_sample(context: &leleka_cuda_driver::Context<'_>) -> Option } /// Check the device once it exists: refuse (with numbers) only against a measured footprint, otherwise note. -pub(crate) fn check_vram(g: &Governor, context: &leleka_cuda_driver::Context<'_>, budget: u64) -> Result<(), BackendError> { +pub(crate) fn check_vram( + g: &Governor, + context: &leleka_cuda_driver::Context<'_>, + budget: u64, +) -> Result<(), BackendError> { match context.memory_info() { Ok((free, total)) => g .check_vram(VramFacts { free: free as u64, total: total as u64 }, budget, None) @@ -239,16 +266,22 @@ pub(crate) fn report() -> Option { } /// The `auto` prefix budget at stack open, or the explicit one clamped to what the host has now. -pub(crate) fn resolve_prefix_budget(budget: crate::qwen_forward::original_serve_stack::PrefixBudget, available: Option, complement_pending: u64) -> Option { +pub(crate) fn resolve_prefix_budget( + budget: crate::qwen_forward::original_serve_stack::PrefixBudget, + available: Option, + complement_pending: u64, +) -> Option { use crate::qwen_forward::original_serve_stack::PrefixBudget as View; let g = Governor::global()?; let policy = g.policy(); - let complement_pending = complement_pending.saturating_add(MAPPED_WORKING_SET.load(std::sync::atomic::Ordering::Acquire)); + let complement_pending = + complement_pending.saturating_add(MAPPED_WORKING_SET.load(std::sync::atomic::Ordering::Acquire)); let bytes = match budget { View::Off => 0, View::Auto => leleka_memory::plan::auto_prefix_budget(available, &policy, complement_pending), View::Bytes(wish) => { - let (granted, elastic) = leleka_memory::plan::explicit_prefix_budget(wish, available, &policy, complement_pending); + let (granted, elastic) = + leleka_memory::plan::explicit_prefix_budget(wish, available, &policy, complement_pending); if granted < wish { g.log(&format!( "note: prefix cache clamped from {} MiB to {} MiB: only {} MiB are elastic above the {} MiB soft floor", @@ -308,7 +341,10 @@ pub(crate) fn drop_file_cache(paths: &[&std::path::Path]) { /// Windows has no sealed memfd: the archive is always file-backed (`InheritedKarArchive::open_read_only_file`), so there /// is nothing to lock or guard. #[cfg(target_os = "windows")] -pub(crate) fn guard_archive(_g: &Governor, _archive: &crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive) -> Result<(), BackendError> { +pub(crate) fn guard_archive( + _g: &Governor, + _archive: &crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive, +) -> Result<(), BackendError> { Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/model_binding/kar_expert_source.rs b/crates/engine-qwen35-cuda/src/model_binding/kar_expert_source.rs index 5452b954..005ae7e0 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/kar_expert_source.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/kar_expert_source.rs @@ -22,8 +22,7 @@ #![allow(dead_code)] use super::kar_levels::{ - ArchiveSlot, ArchiveView, ClassLevels, GpuRows, KarLevelSelector, KarLevelsError, LevelPolicy, - ScratchBytes, + ArchiveSlot, ArchiveView, ClassLevels, GpuRows, KarLevelSelector, KarLevelsError, LevelPolicy, ScratchBytes, }; use leleka_cuda_driver::Context; use leleka_model_format::kar::KarInspection; @@ -100,9 +99,7 @@ impl KarExpertSource { .and_then(|base| Ok((base, ClassLevels::uniform(config.levels.overlay)?))) .map_err(KarSourceError::Level)?; if config.scratch_budget_bytes == 0 { - return Err(KarSourceError::Config( - "KAR scratch budget must be positive", - )); + return Err(KarSourceError::Config("KAR scratch budget must be positive")); } let (base, base_view) = open_archive(&config.base)?; let (overlay, overlay_view) = match &config.overlay { @@ -112,14 +109,8 @@ impl KarExpertSource { } None => (None, None), }; - let selector = KarLevelSelector::new( - base_view, - overlay_view, - LevelPolicy { - base: levels.0, - overlay: levels.1, - }, - )?; + let selector = + KarLevelSelector::new(base_view, overlay_view, LevelPolicy { base: levels.0, overlay: levels.1 })?; let source = Self { selector, base, @@ -133,9 +124,7 @@ impl KarExpertSource { /// 48 layers x gate/up/down, exact shapes, plannable first and last expert. fn validate_map(&self) -> Result<()> { - Ok(self - .selector - .validate_expert_map(LAYERS, EXPERTS, HIDDEN, FF)?) + Ok(self.selector.validate_expert_map(LAYERS, EXPERTS, HIDDEN, FF)?) } /// Identity of this source: archive pins, overlay presence and levels. @@ -165,9 +154,9 @@ impl KarExpertSource { match rows.window.slot { ArchiveSlot::Base => stage_window(&self.base, &rows.window.plan), ArchiveSlot::Overlay => stage_window( - self.overlay.as_ref().ok_or(KarSourceError::Layout( - "overlay-served record without an overlay archive", - ))?, + self.overlay + .as_ref() + .ok_or(KarSourceError::Layout("overlay-served record without an overlay archive"))?, &rows.window.plan, ), } @@ -176,11 +165,7 @@ impl KarExpertSource { /// Admission against the operator budget and the context's remaining /// device budget; performed before any allocation or launch. - pub(crate) fn admit_scratch( - &self, - rows: &[GpuRows; 3], - available_device: u64, - ) -> Result { + pub(crate) fn admit_scratch(&self, rows: &[GpuRows; 3], available_device: u64) -> Result { let scratch = expert_scratch(rows); if scratch.aligned > self.scratch_budget || scratch.aligned > available_device { return Err(KarSourceError::Budget); @@ -200,15 +185,9 @@ impl KarExpertSource { return Err(KarSourceError::NonFinite); } let rows = self.plan_expert(layer, expert)?; - let available = context - .budget_bytes() - .saturating_sub(context.allocated_bytes()) as u64; + let available = context.budget_bytes().saturating_sub(context.allocated_bytes()) as u64; self.admit_scratch(&rows, available)?; - let packets = [ - self.stage(&rows[0])?, - self.stage(&rows[1])?, - self.stage(&rows[2])?, - ]; + let packets = [self.stage(&rows[0])?, self.stage(&rows[1])?, self.stage(&rows[2])?]; run_device(context, &rows, &packets, input) } } @@ -220,9 +199,7 @@ fn open_archive(reference: &KarArchiveRef) -> Result<(KarInspection, ArchiveView } let mut inspection = KarInspection::inspect(file).map_err(|_| KarSourceError::Open)?; // Full SHA-256 pin + every payload CRC on the retained descriptor. - inspection - .verify_archive(&reference.sha256) - .map_err(|_| KarSourceError::Verify)?; + inspection.verify_archive(&reference.sha256).map_err(|_| KarSourceError::Verify)?; let view = ArchiveView::from_inspection(&inspection, reference.sha256) .map_err(|_| KarSourceError::Layout("KAR nested record directory is invalid"))?; Ok((inspection, view)) @@ -244,26 +221,16 @@ pub(crate) fn config_identity_digest(config: &KarExpertSourceConfig) -> [u8; 32] } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] -fn run_device( - context: &Context<'_>, - rows: &[GpuRows; 3], - packets: &[Vec; 3], - input: &[f32], -) -> Result> { +fn run_device(context: &Context<'_>, rows: &[GpuRows; 3], packets: &[Vec; 3], input: &[f32]) -> Result> { use super::kar_levels::{driver_geometry, driver_shape}; use leleka_cuda_driver::kar_decode_levels::KarDecodeError; use leleka_cuda_driver::kar_decode_levels_gpu::{KarDecodeLevels, KarMatrix}; let matrix = |i: usize| -> Result> { // The driver derives the launch geometry independently; any // disagreement with the planner is drift and must never launch. - let geometry = driver_geometry(&rows[i].window.plan).ok_or(KarSourceError::Layout( - "planner and driver geometry disagree", - ))?; - Ok(KarMatrix { - geometry, - shape: driver_shape(&rows[i]), - packet: &packets[i], - }) + let geometry = driver_geometry(&rows[i].window.plan) + .ok_or(KarSourceError::Layout("planner and driver geometry disagree"))?; + Ok(KarMatrix { geometry, shape: driver_shape(&rows[i]), packet: &packets[i] }) }; let map = |error: KarDecodeError| match error { KarDecodeError::Unpinned => KarSourceError::Unsupported, @@ -271,26 +238,16 @@ fn run_device( KarDecodeError::DeviceStatus(_) => KarSourceError::Device("device status"), KarDecodeError::Invalid(reason) => KarSourceError::Device(reason), KarDecodeError::Driver(leleka_cuda_driver::Error::BudgetExceeded) - | KarDecodeError::Driver(leleka_cuda_driver::Error::HostAllocation) => { - KarSourceError::Budget - } + | KarDecodeError::Driver(leleka_cuda_driver::Error::HostAllocation) => KarSourceError::Budget, KarDecodeError::Driver(_) => KarSourceError::Device("driver"), }; let (gate, up, down) = (matrix(0)?, matrix(1)?, matrix(2)?); let program = KarDecodeLevels::open(context).map_err(map)?; - program - .expert_mlp_to_host(&gate, &up, &down, input) - .map(Vec::into_boxed_slice) - .map_err(map) + program.expert_mlp_to_host(&gate, &up, &down, input).map(Vec::into_boxed_slice).map_err(map) } #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] -fn run_device( - _: &Context<'_>, - _: &[GpuRows; 3], - _: &[Vec; 3], - _: &[f32], -) -> Result> { +fn run_device(_: &Context<'_>, _: &[GpuRows; 3], _: &[Vec; 3], _: &[f32]) -> Result> { Err(KarSourceError::Unsupported) } @@ -300,18 +257,10 @@ mod tests { fn config(overlay: bool, base_level: u8, overlay_level: u8) -> KarExpertSourceConfig { KarExpertSourceConfig { - base: KarArchiveRef { - path: PathBuf::from("/nonexistent/base.kar"), - sha256: [1; 32], - }, - overlay: overlay.then(|| KarArchiveRef { - path: PathBuf::from("/nonexistent/overlay.kar"), - sha256: [2; 32], - }), - levels: KarExpertLevels { - base: base_level, - overlay: overlay_level, - }, + base: KarArchiveRef { path: PathBuf::from("/nonexistent/base.kar"), sha256: [1; 32] }, + overlay: overlay + .then(|| KarArchiveRef { path: PathBuf::from("/nonexistent/overlay.kar"), sha256: [2; 32] }), + levels: KarExpertLevels { base: base_level, overlay: overlay_level }, scratch_budget_bytes: 1 << 20, } } @@ -321,33 +270,22 @@ mod tests { let base = config_identity_digest(&config(false, 2, 3)); assert_ne!(base, config_identity_digest(&config(true, 2, 3))); assert_ne!(base, config_identity_digest(&config(false, 3, 3))); - assert_ne!( - config_identity_digest(&config(true, 2, 3)), - config_identity_digest(&config(true, 2, 4)) - ); + assert_ne!(config_identity_digest(&config(true, 2, 3)), config_identity_digest(&config(true, 2, 4))); assert_eq!(base, config_identity_digest(&config(false, 2, 3))); } #[test] fn open_fails_closed_before_touching_files_on_bad_policy_or_budget() { for bad in [(1u8, 3u8), (2, 6), (0, 0), (9, 2)] { - assert!(matches!( - KarExpertSource::open(&config(false, bad.0, bad.1)), - Err(KarSourceError::Level(_)) - )); + assert!(matches!(KarExpertSource::open(&config(false, bad.0, bad.1)), Err(KarSourceError::Level(_)))); } let mut zero = config(false, 2, 3); zero.scratch_budget_bytes = 0; assert_eq!( KarExpertSource::open(&zero).err(), - Some(KarSourceError::Config( - "KAR scratch budget must be positive" - )) + Some(KarSourceError::Config("KAR scratch budget must be positive")) ); // A missing archive is an Open failure, never a panic or partial source. - assert_eq!( - KarExpertSource::open(&config(false, 2, 3)).err(), - Some(KarSourceError::Open) - ); + assert_eq!(KarExpertSource::open(&config(false, 2, 3)).err(), Some(KarSourceError::Open)); } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/kar_levels.rs b/crates/engine-qwen35-cuda/src/model_binding/kar_levels.rs index b4eee20d..c394976b 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/kar_levels.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/kar_levels.rs @@ -6,8 +6,8 @@ #![allow(dead_code, unused_imports)] pub(crate) use leleka_model_format::kar_levels::{ - ArchiveSlot, ArchiveView, ClassLevels, GpuRows, GpuWindow, KarLevelSelector, KarLevelsError, - LevelPolicy, ScratchBudget, ScratchBytes, Selection, TensorClass, + ArchiveSlot, ArchiveView, ClassLevels, GpuRows, GpuWindow, KarLevelSelector, KarLevelsError, LevelPolicy, + ScratchBudget, ScratchBytes, Selection, TensorClass, }; use leleka_cuda_driver::kar_decode_levels::{DecodeGeometry, MultiplyGeometry}; @@ -16,13 +16,7 @@ use leleka_model_format::kar_kernel_model::WindowPlan; /// The driver-side geometry for a planned window, or `None` if the driver's /// own derivation disagrees with the planner (planner/driver drift). pub(crate) fn driver_geometry(plan: &WindowPlan) -> Option { - let g = DecodeGeometry::for_window( - u32::from(plan.level), - plan.group, - plan.start, - u64::from(plan.count), - ) - .ok()?; + let g = DecodeGeometry::for_window(u32::from(plan.level), plan.group, plan.start, u64::from(plan.count)).ok()?; let p = &plan.params; let same = g.level == p.level && g.group == p.group @@ -39,11 +33,7 @@ pub(crate) fn driver_geometry(plan: &WindowPlan) -> Option { } pub(crate) fn driver_shape(rows: &GpuRows) -> MultiplyGeometry { - MultiplyGeometry { - columns: rows.shape.columns, - rows: rows.shape.rows, - tokens: rows.shape.tokens, - } + MultiplyGeometry { columns: rows.shape.columns, rows: rows.shape.rows, tokens: rows.shape.tokens } } #[cfg(test)] @@ -102,10 +92,7 @@ mod tests { let start = next() % n; let count = 1 + next() % (n - start); let plan = plan_window(&r, level, start, count).unwrap(); - assert!( - driver_geometry(&plan).is_some(), - "L{level} g{group} {start}+{count}" - ); + assert!(driver_geometry(&plan).is_some(), "L{level} g{group} {start}+{count}"); } } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn.rs index 63b337cb..a9c33198 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn.rs @@ -2,8 +2,8 @@ // Original core/layer.cpp46 RMS_EPS, not a nearby rounded metadata value. const NATIVE_EPSILON: f32 = 1.0e-6; use super::{ - BindingIdentity, BoundLayerKind, InputBindingError as E, InputResult, LayerRole, ModelBinding, - Qwen4ExpArtifact, TensorRole, + BindingIdentity, BoundLayerKind, InputBindingError as E, InputResult, LayerRole, ModelBinding, Qwen4ExpArtifact, + TensorRole, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum GdnMatrixRole { @@ -43,9 +43,7 @@ pub(crate) struct GdnWeights { impl GdnWeights { pub(crate) fn source_bytes(&self, role: GdnMatrixRole) -> InputResult { let m = self.matrices[index(role)]; - super::decode::row_bytes(m.kind, m.columns)? - .checked_mul(m.rows) - .ok_or(E::Geometry) + super::decode::row_bytes(m.kind, m.columns)?.checked_mul(m.rows).ok_or(E::Geometry) } pub(crate) fn layer(&self) -> u32 { self.layer @@ -154,10 +152,7 @@ impl ModelBinding { return Err(E::Metadata); } let layer8 = u8::try_from(layer).map_err(|_| E::Range)?; - let role = |role| TensorRole::Layer { - layer: layer8, - role, - }; + let role = |role| TensorRole::Layer { layer: layer8, role }; let definitions = [ (LayerRole::AttnQkv, 2560, 10240), (LayerRole::AttnGate, 2560, 6144), @@ -165,29 +160,12 @@ impl ModelBinding { (LayerRole::SsmBeta, 2560, 48), (LayerRole::SsmOut, 6144, 2560), ]; - let mut matrices = [Matrix { - role: role(LayerRole::AttnQkv), - kind: 0, - columns: 0, - rows: 0, - }; 5]; + let mut matrices = [Matrix { role: role(LayerRole::AttnQkv), kind: 0, columns: 0, rows: 0 }; 5]; for (i, (r, c, n)) in definitions.into_iter().enumerate() { let r = role(r); let d = artifact.tensor(r).map_err(|_| E::Geometry)?; - descriptor( - d.kind(), - d.dimensions(), - d.byte_length(), - c, - n, - i == 2 || i == 3, - )?; - matrices[i] = Matrix { - role: r, - kind: d.kind(), - columns: c, - rows: n, - }; + descriptor(d.kind(), d.dimensions(), d.byte_length(), c, n, i == 2 || i == 3)?; + matrices[i] = Matrix { role: r, kind: d.kind(), columns: c, rows: n }; } // Whole small-weight set admitted before allocation/read. for (r, shape, count) in [ @@ -205,16 +183,7 @@ impl ModelBinding { let a = read_f32(&mut artifact, role(LayerRole::SsmA), 48, 1)?; let dt = read_f32(&mut artifact, role(LayerRole::SsmDtBias), 48, 1)?; let norm = read_f32(&mut artifact, role(LayerRole::SsmNorm), 128, 1)?; - Ok(GdnWeights { - binding: self.identity(), - layer, - matrices, - conv, - a, - dt, - norm, - epsilon, - }) + Ok(GdnWeights { binding: self.identity(), layer, matrices, conv, a, dt, norm, epsilon }) } pub(crate) fn gdn_matrix_block( &self, @@ -244,25 +213,15 @@ impl ModelBinding { matches!(role, GdnMatrixRole::Alpha | GdnMatrixRole::Beta), )?; let row_size = super::decode::row_bytes(m.kind, m.columns)?; - let output_row = if m.kind == 0 { - m.columns.checked_mul(2).ok_or(E::Geometry)? - } else { - row_size - }; + let output_row = if m.kind == 0 { m.columns.checked_mul(2).ok_or(E::Geometry)? } else { row_size }; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(output_row.checked_mul(count).ok_or(E::Geometry)?) - .map_err(|_| E::Allocation)?; + bytes.try_reserve_exact(output_row.checked_mul(count).ok_or(E::Geometry)?).map_err(|_| E::Allocation)?; let mut packed = Vec::new(); let limit = row_size.checked_mul(count).ok_or(E::Geometry)?; packed.try_reserve_exact(limit).map_err(|_| E::Allocation)?; artifact .stream_rows(m.role, first as u64, count as u64, |chunk| { - if packed - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if packed.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } packed.extend_from_slice(chunk); @@ -305,29 +264,15 @@ fn exact_bf16(bits: u32) -> InputResult { } Ok((bits >> 16) as u16) } -fn read_f32( - artifact: &mut Qwen4ExpArtifact, - role: TensorRole, - columns: usize, - rows: usize, -) -> InputResult> { +fn read_f32(artifact: &mut Qwen4ExpArtifact, role: TensorRole, columns: usize, rows: usize) -> InputResult> { let mut values = Vec::new(); - values - .try_reserve_exact(columns.checked_mul(rows).ok_or(E::Geometry)?) - .map_err(|_| E::Allocation)?; - let limit = columns - .checked_mul(rows) - .and_then(|n| n.checked_mul(4)) - .ok_or(E::Geometry)?; + values.try_reserve_exact(columns.checked_mul(rows).ok_or(E::Geometry)?).map_err(|_| E::Allocation)?; + let limit = columns.checked_mul(rows).and_then(|n| n.checked_mul(4)).ok_or(E::Geometry)?; let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; artifact .stream_rows(role, 0, rows as u64, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -346,21 +291,12 @@ fn read_f32( } Ok(values.into_boxed_slice()) } -fn read_row( - artifact: &mut Qwen4ExpArtifact, - role: TensorRole, - row: u64, - limit: usize, -) -> InputResult> { +fn read_row(artifact: &mut Qwen4ExpArtifact, role: TensorRole, row: u64, limit: usize) -> InputResult> { let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; artifact .stream_row(role, row, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|end| end > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|end| end > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn/tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn/tests.rs index 374d087b..2ce3564a 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn/tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gdn/tests.rs @@ -5,10 +5,7 @@ use super::*; fn epsilon_is_exact_original_layer_operand() { assert_eq!(NATIVE_EPSILON.to_bits(), 0x358637bd); let admitted_nearby_metadata = 1.0e-6_f64 + 5.0e-13; - assert_ne!( - (admitted_nearby_metadata as f32).to_bits(), - NATIVE_EPSILON.to_bits() - ); + assert_ne!((admitted_nearby_metadata as f32).to_bits(), NATIVE_EPSILON.to_bits()); } #[test] fn closed_projection_kinds_and_exact_containers() { @@ -27,18 +24,9 @@ fn closed_projection_kinds_and_exact_containers() { } #[test] fn fixed_shapes_and_bounded_rows_before_read() { - assert_eq!( - descriptor(30, &[2560, 10240], 52428800, 2560, 10240, false), - Ok(()) - ); - assert_eq!( - descriptor(30, &[10240, 2560], 52428800, 2560, 10240, false), - Err(E::Geometry) - ); - assert_eq!( - descriptor(13, &[2560, 48], 84480, 2560, 48, true), - Err(E::UnsupportedKind) - ); + assert_eq!(descriptor(30, &[2560, 10240], 52428800, 2560, 10240, false), Ok(())); + assert_eq!(descriptor(30, &[10240, 2560], 52428800, 2560, 10240, false), Err(E::Geometry)); + assert_eq!(descriptor(13, &[2560, 48], 84480, 2560, 48, true), Err(E::UnsupportedKind)); for (first, count) in [(0, 0), (0, 65), (usize::MAX, 1), (10239, 2)] { assert_eq!(block_range(first, count, 10240), Err(E::Range)); } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr.rs index 07211d8c..c0967578 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr.rs @@ -1,8 +1,5 @@ //! Finite GR weight access from the retained verified artifact. -use super::{ - BindingIdentity, GlobalRole, InputBindingError, InputResult, LayerRole, ModelBinding, - TensorRole, -}; +use super::{BindingIdentity, GlobalRole, InputBindingError, InputResult, LayerRole, ModelBinding, TensorRole}; const WIDTH: usize = 4 * 2560; const HIDDEN: usize = 320; @@ -47,23 +44,11 @@ impl GrWeights { impl ModelBinding { pub(crate) fn gr_weights(&self, role: GrRole) -> InputResult { let roles = role_set(role, self.layer_count())?; - let mut artifact = self - .artifact - .try_borrow_mut() - .map_err(|_| InputBindingError::Busy)?; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?; // Admit the whole set before allocation or the first row read. for (tensor_role, columns, rows, norm) in roles.iter().flatten().copied() { - let tensor = artifact - .tensor(tensor_role) - .map_err(|_| InputBindingError::Geometry)?; - validate_descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - columns, - rows, - norm, - )?; + let tensor = artifact.tensor(tensor_role).map_err(|_| InputBindingError::Geometry)?; + validate_descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), columns, rows, norm)?; } let metadata_epsilon = artifact.topology().rms_epsilon(); if !metadata_epsilon.is_finite() || metadata_epsilon < 0.0 { @@ -72,8 +57,7 @@ impl ModelBinding { let norm_role = roles[0].ok_or(InputBindingError::Geometry)?.0; let norm_bytes = read_row(&mut artifact, norm_role, 0, WIDTH * 4)?; let mut norm = Vec::new(); - norm.try_reserve_exact(WIDTH) - .map_err(|_| InputBindingError::Allocation)?; + norm.try_reserve_exact(WIDTH).map_err(|_| InputBindingError::Allocation)?; for chunk in norm_bytes.as_chunks::<4>().0 { let value = f32::from_bits(u32::from_le_bytes(*chunk)); if !value.is_finite() { @@ -85,10 +69,7 @@ impl ModelBinding { let down = read_bf16(&mut artifact, roles[1].ok_or(InputBindingError::Geometry)?)?; let up = read_bf16(&mut artifact, roles[2].ok_or(InputBindingError::Geometry)?)?; let inject = if roles[3].is_some() { - Some(read_bf16( - &mut artifact, - roles[3].ok_or(InputBindingError::Geometry)?, - )?) + Some(read_bf16(&mut artifact, roles[3].ok_or(InputBindingError::Geometry)?)?) } else { None }; @@ -108,44 +89,27 @@ impl ModelBinding { impl ModelBinding { pub(crate) fn gr_source_bytes(&self, role: GrRole) -> InputResult<[usize; 4]> { let roles = role_set(role, self.layer_count())?; - let artifact = self - .artifact - .try_borrow() - .map_err(|_| InputBindingError::Busy)?; + let artifact = self.artifact.try_borrow().map_err(|_| InputBindingError::Busy)?; let mut bytes = [0; 4]; for (i, role) in roles.into_iter().enumerate() { if let Some((role, _, _, _)) = role { - bytes[i] = usize::try_from( - artifact - .tensor(role) - .map_err(|_| InputBindingError::Geometry)? - .byte_length(), - ) - .map_err(|_| InputBindingError::Geometry)?; + bytes[i] = + usize::try_from(artifact.tensor(role).map_err(|_| InputBindingError::Geometry)?.byte_length()) + .map_err(|_| InputBindingError::Geometry)?; } } Ok(bytes) } pub(crate) fn validate_dense_sources(&self) -> InputResult<()> { - let mut artifact = self - .artifact - .try_borrow_mut() - .map_err(|_| InputBindingError::Busy)?; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?; // Descriptors remain immutable inside this binding. Check each retained // source once rather than stat the same shard for every matrix. let mut checked = [false; 2]; let mut validate = |role| -> InputResult<()> { - let shard = usize::from( - artifact - .tensor(role) - .map_err(|_| InputBindingError::Geometry)? - .shard(), - ); + let shard = usize::from(artifact.tensor(role).map_err(|_| InputBindingError::Geometry)?.shard()); let done = checked.get_mut(shard).ok_or(InputBindingError::Geometry)?; if !*done { - artifact - .validate_tensor_source(role) - .map_err(|_| InputBindingError::Read)?; + artifact.validate_tensor_source(role).map_err(|_| InputBindingError::Read)?; *done = true; } Ok(()) @@ -191,11 +155,7 @@ impl ModelBinding { validate(TensorRole::Layer { layer: l, role })?; } } - for role in [ - GlobalRole::OutputHcNorm, - GlobalRole::OutputHcDown, - GlobalRole::OutputHcUp, - ] { + for role in [GlobalRole::OutputHcNorm, GlobalRole::OutputHcDown, GlobalRole::OutputHcUp] { validate(TensorRole::Global(role))?; } Ok(()) @@ -218,37 +178,15 @@ fn role_set(role: GrRole, layer_count: u32) -> InputResult<[Option InputResult { } Ok((bits >> 16) as u16) } -fn read_bf16( - artifact: &mut super::Qwen4ExpArtifact, - descriptor: RoleDescriptor, -) -> InputResult> { +fn read_bf16(artifact: &mut super::Qwen4ExpArtifact, descriptor: RoleDescriptor) -> InputResult> { let (role, columns, rows, _) = descriptor; - let kind = artifact - .tensor(role) - .map_err(|_| InputBindingError::Geometry)? - .kind(); - let row_bytes = columns - .checked_mul(if kind == 30 { 2 } else { 4 }) - .ok_or(InputBindingError::Geometry)?; + let kind = artifact.tensor(role).map_err(|_| InputBindingError::Geometry)?.kind(); + let row_bytes = columns.checked_mul(if kind == 30 { 2 } else { 4 }).ok_or(InputBindingError::Geometry)?; let mut values = Vec::new(); values - .try_reserve_exact( - columns - .checked_mul(rows) - .ok_or(InputBindingError::Geometry)?, - ) + .try_reserve_exact(columns.checked_mul(rows).ok_or(InputBindingError::Geometry)?) .map_err(|_| InputBindingError::Allocation)?; - let limit = row_bytes - .checked_mul(rows) - .ok_or(InputBindingError::Geometry)?; + let limit = row_bytes.checked_mul(rows).ok_or(InputBindingError::Geometry)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(limit) - .map_err(|_| InputBindingError::Allocation)?; + bytes.try_reserve_exact(limit).map_err(|_| InputBindingError::Allocation)?; artifact .stream_rows(role, 0, rows as u64, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -355,23 +269,12 @@ fn read_bf16( Ok(values.into_boxed_slice()) } -fn read_row( - artifact: &mut super::Qwen4ExpArtifact, - role: TensorRole, - row: u64, - limit: usize, -) -> InputResult> { +fn read_row(artifact: &mut super::Qwen4ExpArtifact, role: TensorRole, row: u64, limit: usize) -> InputResult> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(limit) - .map_err(|_| InputBindingError::Allocation)?; + bytes.try_reserve_exact(limit).map_err(|_| InputBindingError::Allocation)?; artifact .stream_row(role, row, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|end| end > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|end| end > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr/tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr/tests.rs index f42bb7ba..b5e47ba8 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr/tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_gr/tests.rs @@ -6,10 +6,7 @@ fn gr_binding_accepts_only_exact_finite_bf16_containers() { for bits in [0, 0x80000000, 0x3f800000, 0x00010000, 0x7f7f0000] { assert_eq!(u32::from(exact_bf16(bits).unwrap()) << 16, bits); } - assert_eq!( - exact_bf16(0x3f800001), - Err(InputBindingError::UnsupportedKind) - ); + assert_eq!(exact_bf16(0x3f800001), Err(InputBindingError::UnsupportedKind)); for bits in [0x7f800000, 0xff800000, 0x7fc00000] { assert_eq!(exact_bf16(bits), Err(InputBindingError::NonFinite)); } @@ -17,28 +14,10 @@ fn gr_binding_accepts_only_exact_finite_bf16_containers() { #[test] fn gr_binding_freezes_role_shapes_and_final_has_no_injection() { assert!(role_set(GrRole::Final, 48).unwrap()[3].is_none()); - assert_eq!( - role_set(GrRole::Attention(48), 48), - Err(InputBindingError::Range) - ); - assert_eq!( - validate_descriptor(30, &[10240, 320], 6553600, 10240, 320, false), - Ok(()) - ); - assert_eq!( - validate_descriptor(0, &[10240, 320], 13107200, 10240, 320, false), - Ok(()) - ); - assert_eq!( - validate_descriptor(30, &[320, 10240], 6553600, 10240, 320, false), - Err(InputBindingError::Geometry) - ); - assert_eq!( - validate_descriptor(0, &[10240], 40960, 10240, 1, true), - Ok(()) - ); - assert_eq!( - validate_descriptor(30, &[10240], 20480, 10240, 1, true), - Err(InputBindingError::UnsupportedKind) - ); + assert_eq!(role_set(GrRole::Attention(48), 48), Err(InputBindingError::Range)); + assert_eq!(validate_descriptor(30, &[10240, 320], 6553600, 10240, 320, false), Ok(())); + assert_eq!(validate_descriptor(0, &[10240, 320], 13107200, 10240, 320, false), Ok(())); + assert_eq!(validate_descriptor(30, &[320, 10240], 6553600, 10240, 320, false), Err(InputBindingError::Geometry)); + assert_eq!(validate_descriptor(0, &[10240], 40960, 10240, 1, true), Ok(())); + assert_eq!(validate_descriptor(30, &[10240], 20480, 10240, 1, true), Err(InputBindingError::UnsupportedKind)); } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_inherited_kar_gpu.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_inherited_kar_gpu.rs index 1aaee67c..dbd8e6dc 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_inherited_kar_gpu.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_inherited_kar_gpu.rs @@ -15,8 +15,8 @@ use std::{ const PAYLOAD: [u8; 8] = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]; // Independent offline SHA-256 of the literal bytes above, never candidate-derived. const PAYLOAD_SHA: [u8; 32] = [ - 0xae, 0xb7, 0x5d, 0x15, 0x14, 0xcb, 0xdb, 0x00, 0x1a, 0xf6, 0x5f, 0x88, 0x26, 0x55, 0x3d, 0xf8, - 0xfe, 0x6b, 0x2e, 0x11, 0xc6, 0x7f, 0xf3, 0xa5, 0x44, 0x35, 0xea, 0x40, 0x08, 0x94, 0xd7, 0xea, + 0xae, 0xb7, 0x5d, 0x15, 0x14, 0xcb, 0xdb, 0x00, 0x1a, 0xf6, 0x5f, 0x88, 0x26, 0x55, 0x3d, 0xf8, 0xfe, 0x6b, 0x2e, + 0x11, 0xc6, 0x7f, 0xf3, 0xa5, 0x44, 0x35, 0xea, 0x40, 0x08, 0x94, 0xd7, 0xea, ]; static NEXT: AtomicU64 = AtomicU64::new(1); @@ -24,13 +24,8 @@ fn required() -> SealFlags { SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL } fn memfd(bytes: &[u8], seals: SealFlags) -> File { - let mut file = File::from( - memfd_create( - "leleka-inherited-sdet", - MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, - ) - .unwrap(), - ); + let mut file = + File::from(memfd_create("leleka-inherited-sdet", MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING).unwrap()); file.write_all(bytes).unwrap(); if !seals.is_empty() { fcntl_add_seals(&file, seals).unwrap(); @@ -54,13 +49,7 @@ impl OwnFixture { )); DirBuilder::new().mode(0o700).create(&directory).unwrap(); let path = directory.join("literal.bin"); - let mut file = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .mode(0o600) - .open(&path) - .unwrap(); + let mut file = OpenOptions::new().read(true).write(true).create_new(true).mode(0o600).open(&path).unwrap(); file.write_all(&PAYLOAD).unwrap(); drop(file); Self { directory, path } @@ -102,56 +91,30 @@ fn inherited_real_memfd_requires_irreversible_seals_and_independent_owned_handle assert_eq!(reader.metadata().unwrap().nlink(), 0); let unsealed = memfd(&PAYLOAD, SealFlags::empty()); - assert_eq!( - open_sealed_archive_fd(descriptor(&unsealed), 8).err(), - Some(InputBindingError::Metadata) - ); + assert_eq!(open_sealed_archive_fd(descriptor(&unsealed), 8).err(), Some(InputBindingError::Metadata)); drop(unsealed); - for omitted in [ - SealFlags::WRITE, - SealFlags::GROW, - SealFlags::SHRINK, - SealFlags::SEAL, - ] { + for omitted in [SealFlags::WRITE, SealFlags::GROW, SealFlags::SHRINK, SealFlags::SEAL] { let partial = memfd(&PAYLOAD, required() & !omitted); - assert_eq!( - open_sealed_archive_fd(descriptor(&partial), 8).err(), - Some(InputBindingError::Metadata) - ); + assert_eq!(open_sealed_archive_fd(descriptor(&partial), 8).err(), Some(InputBindingError::Metadata)); drop(partial); } for bytes in [&PAYLOAD[..7], &[0u8; 9][..]] { let wrong = memfd(bytes, required()); - assert_eq!( - open_sealed_archive_fd(descriptor(&wrong), 8).err(), - Some(InputBindingError::Range) - ); + assert_eq!(open_sealed_archive_fd(descriptor(&wrong), 8).err(), Some(InputBindingError::Range)); drop(wrong); } let regular = File::open(&fixture.path).unwrap(); assert_eq!(regular.metadata().unwrap().nlink(), 1); - assert_eq!( - open_sealed_archive_fd(descriptor(®ular), 8).err(), - Some(InputBindingError::Range) - ); + assert_eq!(open_sealed_archive_fd(descriptor(®ular), 8).err(), Some(InputBindingError::Range)); let directory = File::open(&fixture.directory).unwrap(); - assert_eq!( - open_sealed_archive_fd(descriptor(&directory), 8).err(), - Some(InputBindingError::Range) - ); + assert_eq!(open_sealed_archive_fd(descriptor(&directory), 8).err(), Some(InputBindingError::Range)); drop(directory); let closed = memfd(&PAYLOAD, required()); let closed_fd = descriptor(&closed); drop(closed); - assert_eq!( - open_sealed_archive_fd(closed_fd, 8).err(), - Some(InputBindingError::Read) - ); + assert_eq!(open_sealed_archive_fd(closed_fd, 8).err(), Some(InputBindingError::Read)); for fd in [0, u32::MAX] { - assert_eq!( - open_sealed_archive_fd(fd, 8).err(), - Some(InputBindingError::Range) - ); + assert_eq!(open_sealed_archive_fd(fd, 8).err(), Some(InputBindingError::Range)); } // Public admission never uses the tiny override. It cannot return a loader @@ -169,14 +132,8 @@ fn inherited_real_memfd_requires_irreversible_seals_and_independent_owned_handle assert_eq!(regular.stream_position().unwrap(), 3); let mut corrupt = PAYLOAD_SHA; corrupt[31] ^= 1; - assert_eq!( - verify_open_provenance(®ular, corrupt), - Err(InputBindingError::Metadata) - ); - assert_eq!( - verify_open_provenance(®ular, PROVENANCE_DIGEST), - Err(InputBindingError::Metadata) - ); + assert_eq!(verify_open_provenance(®ular, corrupt), Err(InputBindingError::Metadata)); + assert_eq!(verify_open_provenance(®ular, PROVENANCE_DIGEST), Err(InputBindingError::Metadata)); assert_eq!(regular.stream_position().unwrap(), 3); drop(regular); drop(reader); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input.rs index f663fd41..05a413a4 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input.rs @@ -41,8 +41,7 @@ mod qsa; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) use moe_expert::MoeRoutedSourceScope; pub(crate) use moe_expert::{ - MoeExpertBlock, MoeExpertSelection, MoeExpertWeights, MoeMatrixKind, MoeMatrixRole, - MoeWeightDescriptor, + MoeExpertBlock, MoeExpertSelection, MoeExpertWeights, MoeMatrixKind, MoeMatrixRole, MoeWeightDescriptor, }; pub(crate) use qsa::{QsaMatrixKind, QsaMatrixRole, QsaWeights}; @@ -135,14 +134,14 @@ mod tests { #[path = "qwen4exp_resident_expert_source.rs"] mod resident_expert_source; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="qwen4exp_original_file_source.rs"] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "qwen4exp_original_file_source.rs"] mod original_file_expert_source; -#[cfg(all(any(target_os="linux",target_os="windows"),target_pointer_width="64"))] -#[path="qwen4exp_native_head.rs"] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +#[path = "qwen4exp_native_head.rs"] mod native_output; -#[cfg(all(any(target_os="linux",target_os="windows"),target_pointer_width="64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) use native_output::NativeOutputRole; mod impl_fmt_display_for; @@ -151,8 +150,8 @@ mod impl_modelbinding; use impl_modelbinding::bind_expert_counts; mod validate_ple_descriptor_fn; #[allow(unused_imports)] -use validate_ple_descriptor_fn::validate_ple_descriptor; +use validate_ple_descriptor_fn::bind_layer; #[allow(unused_imports)] use validate_ple_descriptor_fn::bind_layers; #[allow(unused_imports)] -use validate_ple_descriptor_fn::bind_layer; +use validate_ple_descriptor_fn::validate_ple_descriptor; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_fmt_display_for.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_fmt_display_for.rs index 0dc9775e..2d8b04e7 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_fmt_display_for.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_fmt_display_for.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl fmt::Display for InputBindingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Qwen input binding rejected: {self:?}") @@ -30,18 +29,9 @@ impl InputConstants { return Err(InputBindingError::Metadata); } let constants = Self { - offsets: t - .ple_head_offsets() - .try_into() - .map_err(|_| InputBindingError::Metadata)?, - vocabularies: t - .ple_head_vocab_sizes() - .try_into() - .map_err(|_| InputBindingError::Metadata)?, - multipliers: t - .ple_layer_multipliers() - .try_into() - .map_err(|_| InputBindingError::Metadata)?, + offsets: t.ple_head_offsets().try_into().map_err(|_| InputBindingError::Metadata)?, + vocabularies: t.ple_head_vocab_sizes().try_into().map_err(|_| InputBindingError::Metadata)?, + multipliers: t.ple_layer_multipliers().try_into().map_err(|_| InputBindingError::Metadata)?, eos: t.ple_eos_token_id(), context_length: t.context_length(), }; @@ -53,11 +43,7 @@ impl InputConstants { return Err(InputBindingError::Metadata); } for (&offset, &vocabulary) in self.offsets.iter().zip(&self.vocabularies) { - if vocabulary == 0 - || offset - .checked_add(vocabulary) - .is_none_or(|end| end > PLE_ROWS) - { + if vocabulary == 0 || offset.checked_add(vocabulary).is_none_or(|end| end > PLE_ROWS) { return Err(InputBindingError::Metadata); } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_modelbinding.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_modelbinding.rs index 0e30342c..24de8586 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_modelbinding.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/impl_modelbinding.rs @@ -9,9 +9,8 @@ impl ModelBinding { } pub(crate) fn from_artifact(artifact: Qwen4ExpArtifact) -> InputResult { let constants = InputConstants::from_artifact(&artifact)?; - let embedding = artifact - .tensor(TensorRole::Global(GlobalRole::TokenEmbedding)) - .map_err(|_| InputBindingError::Geometry)?; + let embedding = + artifact.tensor(TensorRole::Global(GlobalRole::TokenEmbedding)).map_err(|_| InputBindingError::Geometry)?; if embedding.shard() != 0 || embedding.dimensions() != [2560, 248_320] { return Err(InputBindingError::Geometry); } @@ -42,10 +41,7 @@ impl ModelBinding { kar: leleka_model_format::kar::VerifiedKarPleArtifact, ) -> InputResult { let mut binding = Self::from_artifact(artifact)?; - binding.kar_ple = Some(super::super::qwen4exp_kar_ple::KarPleBinding::new( - &binding.identity, - kar, - )?); + binding.kar_ple = Some(super::super::qwen4exp_kar_ple::KarPleBinding::new(&binding.identity, kar)?); Ok(binding) } /// Select the KAR routed-expert weight source before publishing the @@ -187,25 +183,30 @@ impl ModelBinding { if token >= VOCABULARY { return Err(InputBindingError::Range); } - let bytes = self.read_row( - GlobalRole::TokenEmbedding, - u64::from(token), - self.embedding_bytes, - )?; + let bytes = self.read_row(GlobalRole::TokenEmbedding, u64::from(token), self.embedding_bytes)?; decode::row(self.embedding_kind, &bytes, EMBEDDING_VALUES) } - pub(crate) fn native_embedding_layout(&self)->InputResult<(u32,usize,usize,usize)>{ - let artifact=self.artifact.try_borrow().map_err(|_|InputBindingError::Busy)?; - let tensor=artifact.tensor(TensorRole::Global(GlobalRole::TokenEmbedding)).map_err(|_|InputBindingError::Geometry)?; - let total=self.embedding_bytes.checked_mul(VOCABULARY as usize).ok_or(InputBindingError::Geometry)?; - if tensor.shard()!=0||tensor.kind()!=self.embedding_kind||tensor.dimensions()!=[2560,248320] - ||tensor.byte_length()!=total as u64{return Err(InputBindingError::Geometry);} - Ok((self.embedding_kind,self.embedding_bytes,VOCABULARY as usize,total)) + pub(crate) fn native_embedding_layout(&self) -> InputResult<(u32, usize, usize, usize)> { + let artifact = self.artifact.try_borrow().map_err(|_| InputBindingError::Busy)?; + let tensor = + artifact.tensor(TensorRole::Global(GlobalRole::TokenEmbedding)).map_err(|_| InputBindingError::Geometry)?; + let total = self.embedding_bytes.checked_mul(VOCABULARY as usize).ok_or(InputBindingError::Geometry)?; + if tensor.shard() != 0 + || tensor.kind() != self.embedding_kind + || tensor.dimensions() != [2560, 248320] + || tensor.byte_length() != total as u64 + { + return Err(InputBindingError::Geometry); + } + Ok((self.embedding_kind, self.embedding_bytes, VOCABULARY as usize, total)) } - pub(crate) fn stream_native_embedding(&self,consume:impl FnMut(&[u8])->std::io::Result<()>)->InputResult<()> { + pub(crate) fn stream_native_embedding(&self, consume: impl FnMut(&[u8]) -> std::io::Result<()>) -> InputResult<()> { self.native_embedding_layout()?; - self.artifact.try_borrow_mut().map_err(|_|InputBindingError::Busy)? - .stream_token_embedding(consume).map_err(|_|InputBindingError::Read) + self.artifact + .try_borrow_mut() + .map_err(|_| InputBindingError::Busy)? + .stream_token_embedding(consume) + .map_err(|_| InputBindingError::Read) } pub(crate) fn ple_row(&self, row: u64) -> InputResult> { if row >= PLE_ROWS { @@ -216,18 +217,12 @@ impl ModelBinding { } pub(super) fn read_row(&self, role: GlobalRole, row: u64, byte_count: usize) -> InputResult> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(byte_count) - .map_err(|_| InputBindingError::Allocation)?; + bytes.try_reserve_exact(byte_count).map_err(|_| InputBindingError::Allocation)?; self.artifact .try_borrow_mut() .map_err(|_| InputBindingError::Busy)? .stream_row(TensorRole::Global(role), row, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|end| end > byte_count) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|end| end > byte_count) { return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); } bytes.extend_from_slice(chunk); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor_fn.rs index 69f1d220..daa37bc4 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input/validate_ple_descriptor_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn validate_ple_descriptor(artifact: &Qwen4ExpArtifact) -> InputResult<()> { let ple = artifact .tensor(TensorRole::Global(GlobalRole::PerLayerTokenEmbedding)) @@ -11,11 +10,7 @@ pub(super) fn validate_ple_descriptor(artifact: &Qwen4ExpArtifact) -> InputResul if ple.shard() != 1 || ple.kind() != 20 || ple.dimensions() != [160, PLE_ROWS] { return Err(InputBindingError::Geometry); } - if ple.byte_length() - != PLE_ROWS - .checked_mul(90) - .ok_or(InputBindingError::Geometry)? - { + if ple.byte_length() != PLE_ROWS.checked_mul(90).ok_or(InputBindingError::Geometry)? { return Err(InputBindingError::Geometry); } Ok(()) @@ -26,13 +21,12 @@ impl InputConstants { pub(crate) fn test_fixture() -> Self { Self { offsets: [ - 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, - 160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, - 300001275, + 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, 160000374, 180000455, + 200000548, 220000655, 240000802, 260000955, 280001114, 300001275, ], vocabularies: [ - 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, - 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171, + 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, 20000081, 20000093, + 20000107, 20000147, 20000153, 20000159, 20000161, 20000171, ], multipliers: [23703573157769, 20109073645365, 8052911324071], eos: 248044, @@ -48,9 +42,7 @@ pub(super) fn bind_layers(artifact: &Qwen4ExpArtifact) -> InputResult InputResult InputResult { let qsa = (index + 1).is_multiple_of(interval); - let (required, forbidden) = if qsa { - (LayerRole::AttnQ, LayerRole::AttnQkv) - } else { - (LayerRole::AttnQkv, LayerRole::AttnQ) - }; - let role = |role| TensorRole::Layer { - layer: index as u8, - role, - }; - artifact - .tensor(role(required)) - .map_err(|_| InputBindingError::Geometry)?; + let (required, forbidden) = + if qsa { (LayerRole::AttnQ, LayerRole::AttnQkv) } else { (LayerRole::AttnQkv, LayerRole::AttnQ) }; + let role = |role| TensorRole::Layer { layer: index as u8, role }; + artifact.tensor(role(required)).map_err(|_| InputBindingError::Geometry)?; if artifact.tensor(role(forbidden)).is_ok() { return Err(InputBindingError::Geometry); } - Ok(BoundLayer { - index, - kind: if qsa { - BoundLayerKind::Qsa - } else { - BoundLayerKind::Gdn - }, - }) + Ok(BoundLayer { index, kind: if qsa { BoundLayerKind::Qsa } else { BoundLayerKind::Gdn } }) } #[cfg(test)] diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input_decode.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input_decode.rs index cb5aa23d..d2b8a89f 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input_decode.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_input_decode.rs @@ -20,18 +20,14 @@ pub(super) fn row_bytes(kind: u32, values: usize) -> InputResult { if values == 0 || !values.is_multiple_of(elements) { return Err(InputBindingError::Geometry); } - (values / elements) - .checked_mul(bytes) - .ok_or(InputBindingError::Geometry) + (values / elements).checked_mul(bytes).ok_or(InputBindingError::Geometry) } pub(super) fn row(kind: u32, bytes: &[u8], values: usize) -> InputResult> { if bytes.len() != row_bytes(kind, values)? { return Err(InputBindingError::Geometry); } let mut output = Vec::new(); - output - .try_reserve_exact(values) - .map_err(|_| InputBindingError::Allocation)?; + output.try_reserve_exact(values).map_err(|_| InputBindingError::Allocation)?; output.resize(values, 0.0); match kind { 0 | 1 | 30 => scalar(kind, bytes, &mut output), @@ -50,11 +46,7 @@ fn scalar(kind: u32, bytes: &[u8], output: &mut [f32]) { } else { for (value, encoded) in output.iter_mut().zip(bytes.as_chunks::<2>().0) { let bits = u16::from_le_bytes(*encoded); - *value = if kind == 1 { - quant::f16_bits_to_f32(bits) - } else { - f32::from_bits(u32::from(bits) << 16) - }; + *value = if kind == 1 { quant::f16_bits_to_f32(bits) } else { f32::from_bits(u32::from(bits) << 16) }; } } } @@ -84,47 +76,26 @@ mod tests { fn iq4_nl_five_block_rows_match_independent_head_order_bits() { for case in reference::DECODE_CASES { let actual = row(20, &case.encoded, 160).unwrap(); - assert_eq!( - actual.iter().map(|v| v.to_bits()).collect::>(), - case.expected_words, - "{}", - case.name - ); + assert_eq!(actual.iter().map(|v| v.to_bits()).collect::>(), case.expected_words, "{}", case.name); } } #[test] fn scalar_binary_formats_preserve_exact_finite_bits() { for (kind, bytes) in [(1, 0xbc00u16), (30, 0xbf80u16)] { - assert_eq!( - row(kind, &bytes.to_le_bytes(), 1).unwrap()[0].to_bits(), - (-1.0f32).to_bits() - ); + assert_eq!(row(kind, &bytes.to_le_bytes(), 1).unwrap()[0].to_bits(), (-1.0f32).to_bits()); } let input = [-0.0f32, 1.5]; let bytes: Vec<_> = input.iter().flat_map(|v| v.to_le_bytes()).collect(); - assert_eq!( - row(0, &bytes, 2) - .unwrap() - .iter() - .map(|v| v.to_bits()) - .collect::>(), - input.map(f32::to_bits) - ); + assert_eq!(row(0, &bytes, 2).unwrap().iter().map(|v| v.to_bits()).collect::>(), input.map(f32::to_bits)); } #[test] fn invalid_sizes_kinds_and_nonfinite_payloads_are_not_published() { - assert_eq!( - row_bytes(999, 2560), - Err(InputBindingError::UnsupportedKind) - ); + assert_eq!(row_bytes(999, 2560), Err(InputBindingError::UnsupportedKind)); for values in [0, 159, 161, usize::MAX] { assert!(row_bytes(20, values).is_err()); } assert_eq!(row(20, &[0; 89], 160), Err(InputBindingError::Geometry)); - assert_eq!( - row(0, &f32::NAN.to_le_bytes(), 1), - Err(InputBindingError::NonFinite) - ); + assert_eq!(row(0, &f32::NAN.to_le_bytes(), 1), Err(InputBindingError::NonFinite)); let mut iq = [0; 90]; iq[..2].copy_from_slice(&0x7c00u16.to_le_bytes()); assert_eq!(row(20, &iq, 160), Err(InputBindingError::NonFinite)); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs index 53d7ca2d..c8cbbf85 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple.rs @@ -80,38 +80,38 @@ enum LoadPhase { const NATIVE_DIGESTS: [[u8; 32]; 2] = [ [ - 76, 30, 178, 206, 180, 145, 94, 17, 146, 244, 243, 134, 2, 24, 151, 189, 229, 106, 151, - 244, 10, 11, 183, 139, 184, 100, 101, 224, 247, 210, 172, 163, + 76, 30, 178, 206, 180, 145, 94, 17, 146, 244, 243, 134, 2, 24, 151, 189, 229, 106, 151, 244, 10, 11, 183, 139, + 184, 100, 101, 224, 247, 210, 172, 163, ], [ - 49, 107, 70, 243, 162, 219, 214, 140, 144, 15, 67, 19, 106, 185, 68, 159, 157, 204, 55, 37, - 223, 216, 199, 148, 132, 124, 32, 75, 193, 97, 225, 19, + 49, 107, 70, 243, 162, 219, 214, 140, 144, 15, 67, 19, 106, 185, 68, 159, 157, 204, 55, 37, 223, 216, 199, 148, + 132, 124, 32, 75, 193, 97, 225, 19, ], ]; const ARCHIVE_DIGEST: [u8; 32] = [ - 0x53, 0x6d, 0x61, 0x2c, 0xa6, 0x0e, 0xab, 0x46, 0x0c, 0xb9, 0x78, 0xf5, 0x17, 0x48, 0xfc, 0x6f, - 0xa4, 0xe9, 0xd6, 0x11, 0xd4, 0x60, 0x1e, 0x77, 0x78, 0x84, 0xe8, 0xb5, 0x13, 0x85, 0xaf, 0xa5, + 0x53, 0x6d, 0x61, 0x2c, 0xa6, 0x0e, 0xab, 0x46, 0x0c, 0xb9, 0x78, 0xf5, 0x17, 0x48, 0xfc, 0x6f, 0xa4, 0xe9, 0xd6, + 0x11, 0xd4, 0x60, 0x1e, 0x77, 0x78, 0x84, 0xe8, 0xb5, 0x13, 0x85, 0xaf, 0xa5, ]; const PROVENANCE_DIGEST: [u8; 32] = [ - 0x3e, 0xdc, 0xeb, 0x51, 0x2c, 0x38, 0x6e, 0xa4, 0x55, 0x2a, 0x3e, 0x5d, 0x3d, 0x49, 0xfb, 0xd8, - 0x41, 0xf7, 0xbd, 0x1b, 0x31, 0x4a, 0xeb, 0xa8, 0xb2, 0xa8, 0x7a, 0xc8, 0x11, 0xa8, 0xa6, 0xb5, + 0x3e, 0xdc, 0xeb, 0x51, 0x2c, 0x38, 0x6e, 0xa4, 0x55, 0x2a, 0x3e, 0x5d, 0x3d, 0x49, 0xfb, 0xd8, 0x41, 0xf7, 0xbd, + 0x1b, 0x31, 0x4a, 0xeb, 0xa8, 0xb2, 0xa8, 0x7a, 0xc8, 0x11, 0xa8, 0xa6, 0xb5, ]; const VIRTUAL_F32_DIGEST: [u8; 32] = [ - 0xc8, 0x9b, 0xfc, 0xea, 0x7b, 0x1c, 0x97, 0x9a, 0xd2, 0xe9, 0xe6, 0x4c, 0x59, 0xfc, 0xc3, 0xc0, - 0x3f, 0xc4, 0x14, 0xb3, 0x45, 0xc5, 0xf4, 0x7f, 0x02, 0x7c, 0xe0, 0xba, 0x99, 0x01, 0x54, 0x79, + 0xc8, 0x9b, 0xfc, 0xea, 0x7b, 0x1c, 0x97, 0x9a, 0xd2, 0xe9, 0xe6, 0x4c, 0x59, 0xfc, 0xc3, 0xc0, 0x3f, 0xc4, 0x14, + 0xb3, 0x45, 0xc5, 0xf4, 0x7f, 0x02, 0x7c, 0xe0, 0xba, 0x99, 0x01, 0x54, 0x79, ]; const PART0_F32_DIGEST: [u8; 32] = [ - 0x94, 0xf8, 0x3e, 0x0c, 0x08, 0x1f, 0xd9, 0x2a, 0x82, 0x4c, 0xb7, 0x4a, 0x0d, 0x67, 0xc6, 0xfc, - 0x22, 0x61, 0xaf, 0x10, 0x1d, 0xee, 0x25, 0x1a, 0x41, 0x1a, 0x6b, 0xb5, 0xf0, 0x66, 0x46, 0x81, + 0x94, 0xf8, 0x3e, 0x0c, 0x08, 0x1f, 0xd9, 0x2a, 0x82, 0x4c, 0xb7, 0x4a, 0x0d, 0x67, 0xc6, 0xfc, 0x22, 0x61, 0xaf, + 0x10, 0x1d, 0xee, 0x25, 0x1a, 0x41, 0x1a, 0x6b, 0xb5, 0xf0, 0x66, 0x46, 0x81, ]; const PART1_F32_DIGEST: [u8; 32] = [ - 0x06, 0x62, 0x37, 0x54, 0xd1, 0x37, 0x3d, 0xd5, 0x0f, 0x21, 0xec, 0x99, 0x38, 0x0f, 0xb3, 0xe7, - 0x82, 0x3e, 0xb3, 0xc9, 0x99, 0x37, 0x00, 0xee, 0x07, 0x19, 0x65, 0x24, 0x2d, 0xc7, 0xeb, 0x15, + 0x06, 0x62, 0x37, 0x54, 0xd1, 0x37, 0x3d, 0xd5, 0x0f, 0x21, 0xec, 0x99, 0x38, 0x0f, 0xb3, 0xe7, 0x82, 0x3e, 0xb3, + 0xc9, 0x99, 0x37, 0x00, 0xee, 0x07, 0x19, 0x65, 0x24, 0x2d, 0xc7, 0xeb, 0x15, ]; #[cfg(test)] @@ -123,13 +123,13 @@ mod private_copy; mod impl_inheritedkararchive; #[cfg(target_os = "linux")] #[allow(unused_imports)] -use impl_inheritedkararchive::open_sealed_archive_fd; +use impl_inheritedkararchive::check_read_only_archive; #[cfg(target_os = "linux")] #[allow(unused_imports)] use impl_inheritedkararchive::open_read_only_archive; #[cfg(target_os = "linux")] #[allow(unused_imports)] -use impl_inheritedkararchive::check_read_only_archive; +use impl_inheritedkararchive::open_sealed_archive_fd; #[cfg(target_os = "linux")] #[allow(unused_imports)] use impl_inheritedkararchive::reopen_read_only_archive; @@ -137,17 +137,6 @@ use impl_inheritedkararchive::reopen_read_only_archive; #[allow(unused_imports)] use impl_inheritedkararchive::verify_open_provenance; mod load_pinned_inherited_archive_fn; -#[cfg(target_os = "linux")] -#[allow(unused_imports)] -pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; -#[allow(unused_imports)] -use load_pinned_inherited_archive_fn::log_startup_read; -#[cfg(target_os = "windows")] -#[allow(unused_imports)] -pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; -#[cfg(not(any(target_os = "linux", target_os = "windows")))] -#[allow(unused_imports)] -pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; #[allow(unused_imports)] use load_pinned_inherited_archive_fn::error; #[allow(unused_imports)] @@ -158,19 +147,30 @@ use load_pinned_inherited_archive_fn::input_failure; use load_pinned_inherited_archive_fn::kar_diagnostic; #[allow(unused_imports)] use load_pinned_inherited_archive_fn::kar_failure; -mod pinned_profile_fn; +#[cfg(target_os = "linux")] #[allow(unused_imports)] -pub(crate) use pinned_profile_fn::pinned_profile; +pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; +#[cfg(target_os = "windows")] +#[allow(unused_imports)] +pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; +#[cfg(not(any(target_os = "linux", target_os = "windows")))] +#[allow(unused_imports)] +pub(crate) use load_pinned_inherited_archive_fn::load_pinned_inherited_archive; +#[allow(unused_imports)] +use load_pinned_inherited_archive_fn::log_startup_read; +mod pinned_profile_fn; +#[cfg(target_os = "linux")] +#[allow(unused_imports)] +pub(crate) use pinned_profile_fn::load_pinned_archive; +#[cfg(not(target_os = "linux"))] +#[allow(unused_imports)] +pub(crate) use pinned_profile_fn::load_pinned_archive; #[allow(unused_imports)] use pinned_profile_fn::pinned_parts; #[allow(unused_imports)] +pub(crate) use pinned_profile_fn::pinned_profile; +#[allow(unused_imports)] use pinned_profile_fn::pinned_profile_spec; #[cfg(target_os = "linux")] #[allow(unused_imports)] -pub(crate) use pinned_profile_fn::load_pinned_archive; -#[cfg(target_os = "linux")] -#[allow(unused_imports)] use pinned_profile_fn::verify_pinned_provenance; -#[cfg(not(target_os = "linux"))] -#[allow(unused_imports)] -pub(crate) use pinned_profile_fn::load_pinned_archive; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive.rs index 515167aa..61a529a0 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive.rs @@ -2,9 +2,7 @@ #[allow(unused_imports)] use super::*; -use leleka_model_format::weight_source::{ - BackingKind, FileWeightSource, Verification, WeightIdentity, -}; +use leleka_model_format::weight_source::{BackingKind, FileWeightSource, Verification, WeightIdentity}; #[cfg(test)] mod weight_source_tests; @@ -18,12 +16,7 @@ impl InheritedKarArchive { .map_err(|_| "inherited KAR provenance is not a regular file")?; verify_open_provenance(&provenance, PROVENANCE_DIGEST) .map_err(|_| "inherited KAR provenance verification failed")?; - Ok(Self { - archive, - provenance, - file_backed: false, - sparse: None, - }) + Ok(Self { archive, provenance, file_backed: false, sparse: None }) } /// `open` for a memfd that holds only the extents the serve path reads (`memfd_extents: ple_only`; **experimental**, off by @@ -70,32 +63,20 @@ impl InheritedKarArchive { pub fn open_read_only_file(archive: &Path, provenance: PathBuf) -> Result { let archive = open_read_only_archive(archive, PINNED_ARCHIVE_BYTES) .map_err(|_| "KAR archive file is not the pinned read-only archive")?; - let provenance = private_copy::open_regular(&provenance, None) - .map_err(|_| "KAR provenance is not a regular file")?; - verify_open_provenance(&provenance, PROVENANCE_DIGEST) - .map_err(|_| "KAR provenance verification failed")?; - Ok(Self { - archive, - provenance, - file_backed: true, - sparse: None, - }) + let provenance = + private_copy::open_regular(&provenance, None).map_err(|_| "KAR provenance is not a regular file")?; + verify_open_provenance(&provenance, PROVENANCE_DIGEST).map_err(|_| "KAR provenance verification failed")?; + Ok(Self { archive, provenance, file_backed: true, sparse: None }) } #[cfg(target_os = "windows")] pub fn open_read_only_file(archive: &Path, provenance: PathBuf) -> Result { let archive = win_archive::open_read_only_archive(archive, PINNED_ARCHIVE_BYTES) .map_err(|_| "KAR archive file is not the pinned read-only archive")?; - let provenance = win_archive::open_regular(&provenance) - .map_err(|_| "KAR provenance is not a regular file")?; + let provenance = win_archive::open_regular(&provenance).map_err(|_| "KAR provenance is not a regular file")?; win_archive::verify_open_provenance(&provenance, PROVENANCE_DIGEST) .map_err(|_| "KAR provenance verification failed")?; - Ok(Self { - archive, - provenance, - file_backed: true, - sparse: None, - }) + Ok(Self { archive, provenance, file_backed: true, sparse: None }) } #[cfg(not(any(target_os = "linux", target_os = "windows")))] @@ -108,21 +89,10 @@ impl InheritedKarArchive { /// so the identity says `Unverified`; the digest is the pinned one, or the pinned digest of the extents when the /// memfd is sparse. pub(crate) fn weight_source(&self) -> FileWeightSource<&File> { - let sha256 = self - .sparse - .as_ref() - .map_or(ARCHIVE_DIGEST, |sparse| sparse.extents_sha256); - let backing = if self.file_backed { - BackingKind::File - } else { - BackingKind::SealedMemfd - }; - let identity = WeightIdentity { - sha256, - bytes: PINNED_ARCHIVE_BYTES, - verification: Verification::Unverified, - backing, - }; + let sha256 = self.sparse.as_ref().map_or(ARCHIVE_DIGEST, |sparse| sparse.extents_sha256); + let backing = if self.file_backed { BackingKind::File } else { BackingKind::SealedMemfd }; + let identity = + WeightIdentity { sha256, bytes: PINNED_ARCHIVE_BYTES, verification: Verification::Unverified, backing }; FileWeightSource::new(&self.archive, identity) } @@ -164,10 +134,7 @@ pub(super) fn open_sealed_archive_fd(fd: u32, expected_bytes: u64) -> InputResul | rustix::fs::SealFlags::GROW | rustix::fs::SealFlags::SHRINK | rustix::fs::SealFlags::SEAL; - if !rustix::fs::fcntl_get_seals(&file) - .map_err(|_| InputBindingError::Read)? - .contains(required) - { + if !rustix::fs::fcntl_get_seals(&file).map_err(|_| InputBindingError::Read)?.contains(required) { return Err(InputBindingError::Metadata); } Ok(file) @@ -236,18 +203,13 @@ pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> let mut buffer = [0u8; 64 * 1024]; let mut offset = 0u64; while offset < length { - let count = usize::try_from((length - offset).min(buffer.len() as u64)) - .map_err(|_| InputBindingError::Range)?; - file.read_exact_at(&mut buffer[..count], offset) - .map_err(private_copy::provenance_error)?; + let count = + usize::try_from((length - offset).min(buffer.len() as u64)).map_err(|_| InputBindingError::Range)?; + file.read_exact_at(&mut buffer[..count], offset).map_err(private_copy::provenance_error)?; digest.update(&buffer[..count]); offset += count as u64; } - if file - .metadata() - .map_err(private_copy::provenance_error)? - .len() - != length + if file.metadata().map_err(private_copy::provenance_error)?.len() != length || digest.finalize().as_slice() != expected_digest { return Err(InputBindingError::Metadata); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive/weight_source_tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive/weight_source_tests.rs index bd6718de..016ddd32 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive/weight_source_tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/impl_inheritedkararchive/weight_source_tests.rs @@ -8,10 +8,7 @@ fn archive_over(path: &Path, bytes: &[u8], sparse: Option<[u8; 32]>) -> Inherite archive: File::open(path).unwrap(), provenance: File::open(path).unwrap(), file_backed: sparse.is_none(), - sparse: sparse.map(|extents_sha256| SparseArchive { - extents_sha256, - extents: Vec::new(), - }), + sparse: sparse.map(|extents_sha256| SparseArchive { extents_sha256, extents: Vec::new() }), } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive_fn.rs index f44e22e9..9ff29736 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/load_pinned_inherited_archive_fn.rs @@ -3,11 +3,8 @@ #[allow(unused_imports)] use super::*; - #[cfg(target_os = "linux")] -pub(crate) fn load_pinned_inherited_archive( - source: &InheritedKarArchive, -) -> InputResult { +pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> InputResult { use std::os::fd::AsRawFd; let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; let reader = if source.file_backed { @@ -15,13 +12,12 @@ pub(crate) fn load_pinned_inherited_archive( .map_err(|e| input_failure(LoadPhase::Source, e))? } else { let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?; - open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES) - .map_err(|e| input_failure(LoadPhase::Source, e))? + open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES).map_err(|e| input_failure(LoadPhase::Source, e))? }; verify_open_provenance(&source.provenance, PROVENANCE_DIGEST) .map_err(|e| input_failure(LoadPhase::Provenance, e))?; - let inspection = leleka_model_format::kar::KarInspection::inspect(reader) - .map_err(|e| kar_failure(LoadPhase::Inspect, e))?; + let inspection = + leleka_model_format::kar::KarInspection::inspect(reader).map_err(|e| kar_failure(LoadPhase::Inspect, e))?; // Only an independently owned, detached, fully sealed inode reaches this boundary. let Some(sparse) = source.sparse.as_ref() else { let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) @@ -31,8 +27,9 @@ pub(crate) fn load_pinned_inherited_archive( }; // A sparse memfd: the digest of its extents, not the archive's SHA-256. The extents the governor locks must be exactly the // ones the verifier hashed and the row reader reads. - let artifact = VerifiedKarPleArtifact::verify_sparse(inspection.into_owner_controlled(), profile, &sparse.extents_sha256) - .map_err(|e| kar_failure(LoadPhase::Verify, e))?; + let artifact = + VerifiedKarPleArtifact::verify_sparse(inspection.into_owner_controlled(), profile, &sparse.extents_sha256) + .map_err(|e| kar_failure(LoadPhase::Verify, e))?; if artifact.serve_extents() != sparse.extents.as_slice() { return Err(input_failure(LoadPhase::Verify, InputBindingError::Metadata)); } @@ -59,9 +56,7 @@ pub(super) fn log_startup_read(source: &InheritedKarArchive, artifact: &Verified /// Windows: only the file-backed form exists (`open_read_only_file`); the archive is shared read-only while open. #[cfg(target_os = "windows")] -pub(crate) fn load_pinned_inherited_archive( - source: &InheritedKarArchive, -) -> InputResult { +pub(crate) fn load_pinned_inherited_archive(source: &InheritedKarArchive) -> InputResult { let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; if !source.file_backed { return Err(input_failure(LoadPhase::Source, InputBindingError::UnsupportedKind)); @@ -70,8 +65,8 @@ pub(crate) fn load_pinned_inherited_archive( .map_err(|e| input_failure(LoadPhase::Source, e))?; win_archive::verify_open_provenance(&source.provenance, PROVENANCE_DIGEST) .map_err(|e| input_failure(LoadPhase::Provenance, e))?; - let inspection = leleka_model_format::kar::KarInspection::inspect(reader) - .map_err(|e| kar_failure(LoadPhase::Inspect, e))?; + let inspection = + leleka_model_format::kar::KarInspection::inspect(reader).map_err(|e| kar_failure(LoadPhase::Inspect, e))?; let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) .map_err(|e| kar_failure(LoadPhase::Verify, e))?; log_startup_read(source, &artifact); @@ -79,9 +74,7 @@ pub(crate) fn load_pinned_inherited_archive( } #[cfg(not(any(target_os = "linux", target_os = "windows")))] -pub(crate) fn load_pinned_inherited_archive( - _source: &InheritedKarArchive, -) -> InputResult { +pub(crate) fn load_pinned_inherited_archive(_source: &InheritedKarArchive) -> InputResult { Err(InputBindingError::UnsupportedKind) } impl KarRowPacket { @@ -95,29 +88,18 @@ impl KarRowPacket { impl KarRowReader { pub(crate) fn read_rows(&self, rows: &[u64], max_threads: usize) -> InputResult> { let packets = self.reader.read_rows(rows, max_threads).map_err(error)?; - Ok(packets - .into_iter() - .map(|p| KarRowPacket { - payload: *p.payload(), - partition: p.partition(), - }) - .collect()) + Ok(packets.into_iter().map(|p| KarRowPacket { payload: *p.payload(), partition: p.partition() }).collect()) } } impl KarPleBinding { - pub(crate) fn new( - identity: &BindingIdentity, - archive: VerifiedKarPleArtifact, - ) -> InputResult { + pub(crate) fn new(identity: &BindingIdentity, archive: VerifiedKarPleArtifact) -> InputResult { // These are the same immutable source pins as Qwen4ExpArtifact. A label is insufficient. const NATIVE: [[u8; 32]; 2] = NATIVE_DIGESTS; if archive.row_count() != PLE_ROWS || archive.native_shard_sha256() != &NATIVE { return Err(InputBindingError::Metadata); } let mut books = Vec::new(); - books - .try_reserve_exact(archive.partition_books().len()) - .map_err(|_| InputBindingError::Allocation)?; + books.try_reserve_exact(archive.partition_books().len()).map_err(|_| InputBindingError::Allocation)?; books.extend_from_slice(archive.partition_books()); if books.is_empty() || books.len() > 65535 { return Err(InputBindingError::Geometry); @@ -146,42 +128,20 @@ impl KarPleBinding { &self.books } pub(crate) fn read_rows(&self, rows: &[u64; 16]) -> InputResult<[KarRowPacket; 16]> { - let packets = self - .archive - .try_borrow_mut() - .map_err(|_| InputBindingError::Busy)? - .read_rows(rows) - .map_err(error)?; - Ok(packets.map(|p| KarRowPacket { - payload: *p.payload(), - partition: p.partition(), - })) + let packets = + self.archive.try_borrow_mut().map_err(|_| InputBindingError::Busy)?.read_rows(rows).map_err(error)?; + Ok(packets.map(|p| KarRowPacket { payload: *p.payload(), partition: p.partition() })) } /// An owned reader of the same rows for another thread (the prefill's read-ahead of the next chunk's rows). pub(crate) fn row_reader(&self) -> InputResult { - let reader = self - .archive - .try_borrow() - .map_err(|_| InputBindingError::Busy)? - .row_reader() - .map_err(error)?; + let reader = self.archive.try_borrow().map_err(|_| InputBindingError::Busy)?.row_reader().map_err(error)?; Ok(KarRowReader { reader }) } /// `read_rows` for any number of rows (the batched prefill's cache misses). pub(crate) fn read_rows_batch(&self, rows: &[u64]) -> InputResult> { - let packets = self - .archive - .try_borrow() - .map_err(|_| InputBindingError::Busy)? - .read_rows_batch(rows) - .map_err(error)?; - Ok(packets - .into_iter() - .map(|p| KarRowPacket { - payload: *p.payload(), - partition: p.partition(), - }) - .collect()) + let packets = + self.archive.try_borrow().map_err(|_| InputBindingError::Busy)?.read_rows_batch(rows).map_err(error)?; + Ok(packets.into_iter().map(|p| KarRowPacket { payload: *p.payload(), partition: p.partition() }).collect()) } } pub(super) fn error(error: KarError) -> InputBindingError { @@ -189,9 +149,7 @@ pub(super) fn error(error: KarError) -> InputBindingError { KarError::Allocation => InputBindingError::Allocation, KarError::Io(_) => InputBindingError::Read, KarError::Range(_) => InputBindingError::Range, - KarError::Format(_) | KarError::Integrity(_) | KarError::Profile(_) => { - InputBindingError::Metadata - } + KarError::Format(_) | KarError::Integrity(_) | KarError::Profile(_) => InputBindingError::Metadata, } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_fn.rs index b14d440c..f46f06ef 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Candidate expectations from independently verified v4 conversion receipts /// d51353be and 0d8a4a52. Construction reads no archive and grants no serving /// capability: retained immutable-source verification remains mandatory. @@ -13,9 +12,7 @@ pub(crate) fn pinned_profile() -> InputResult { pub(super) fn pinned_parts() -> InputResult> { let mut parts = Vec::new(); - parts - .try_reserve_exact(2) - .map_err(|_| InputBindingError::Allocation)?; + parts.try_reserve_exact(2).map_err(|_| InputBindingError::Allocation)?; parts.push(KarPlePartProvenance { name: "per_layer_token_embd.weight#strata-part-001-of-002".into(), row_base: 0, @@ -48,18 +45,15 @@ pub(super) fn pinned_profile_spec() -> InputResult { /// Freeze a fresh private inode before inspection; never admit the shared source /// inode as owner-controlled. Only the Linux provisioning path is supported. #[cfg(target_os = "linux")] -pub(crate) fn load_pinned_archive( - source: &Path, - owner_root: &Path, -) -> InputResult { +pub(crate) fn load_pinned_archive(source: &Path, owner_root: &Path) -> InputResult { let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?; - let mut source_file = private_copy::open_regular(source, Some(55_295_529_472)) - .map_err(|e| input_failure(LoadPhase::Source, e))?; + let mut source_file = + private_copy::open_regular(source, Some(55_295_529_472)).map_err(|e| input_failure(LoadPhase::Source, e))?; verify_pinned_provenance(source).map_err(|e| input_failure(LoadPhase::Provenance, e))?; let reader = private_copy::freeze(&mut source_file, owner_root, 55_295_529_472) .map_err(|e| input_failure(LoadPhase::Freeze, e))?; - let inspection = leleka_model_format::kar::KarInspection::inspect(reader) - .map_err(|e| kar_failure(LoadPhase::Inspect, e))?; + let inspection = + leleka_model_format::kar::KarInspection::inspect(reader).map_err(|e| kar_failure(LoadPhase::Inspect, e))?; // freeze() returns an owner-controlled immutable snapshot: Linux verifies // irrevocable seals; the macOS test path closes its writer and detaches names. VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile) @@ -73,10 +67,7 @@ pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> { let mut name = source.as_os_str().to_os_string(); name.push(".provenance.json"); let mut file = private_copy::open_regular(Path::new(&name), None)?; - let length = file - .metadata() - .map_err(private_copy::provenance_error)? - .len(); + let length = file.metadata().map_err(private_copy::provenance_error)?.len(); if length == 0 || length > 1024 * 1024 { return Err(InputBindingError::Range); } @@ -84,9 +75,7 @@ pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> { let mut buffer = [0u8; 64 * 1024]; let mut total = 0u64; loop { - let count = file - .read(&mut buffer) - .map_err(private_copy::provenance_error)?; + let count = file.read(&mut buffer).map_err(private_copy::provenance_error)?; if count == 0 { break; } @@ -103,10 +92,7 @@ pub(super) fn verify_pinned_provenance(source: &Path) -> InputResult<()> { } #[cfg(not(target_os = "linux"))] -pub(crate) fn load_pinned_archive( - _source: &Path, - _owner_root: &Path, -) -> InputResult { +pub(crate) fn load_pinned_archive(_source: &Path, _owner_root: &Path) -> InputResult { Err(InputBindingError::UnsupportedKind) } @@ -114,5 +100,7 @@ impl InheritedKarArchive { /// Crate-private metadata observation for provisional digest-stream capture. /// This is the actual retained immutable operator archive, not a producer /// certificate; full KAR hash/provenance admission still runs at binding. - pub(crate) fn expert_capture_observation(&self) -> &File { &self.archive } + pub(crate) fn expert_capture_observation(&self) -> &File { + &self.archive + } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs index 7c896648..0cea8e4a 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/pinned_profile_tests.rs @@ -44,20 +44,12 @@ fn load_diagnostics_redact_causes_and_preserve_typed_failures() { } let mut bytes = Vec::new(); assert_eq!( - input_diagnostic( - &mut bytes, - LoadPhase::ReaderDetached, - InputBindingError::Metadata - ), + input_diagnostic(&mut bytes, LoadPhase::ReaderDetached, InputBindingError::Metadata), InputBindingError::Metadata ); assert_eq!(bytes, b"leleka-kar phase=ReaderDetached class=Metadata\n"); assert_eq!( - input_diagnostic( - &mut BrokenSink, - LoadPhase::ReaderDetached, - InputBindingError::Metadata - ), + input_diagnostic(&mut BrokenSink, LoadPhase::ReaderDetached, InputBindingError::Metadata), InputBindingError::Metadata ); } @@ -70,26 +62,11 @@ fn pins_match_independent_conversion_receipts() { let spec = pinned_profile_spec().unwrap(); assert_eq!(spec.archive_bytes, 55_295_529_472); assert_eq!(spec.virtual_f32_bytes, 707_775_598_080); - assert_eq!( - hex(&spec.archive_sha256), - "536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5" - ); - assert_eq!( - hex(&spec.provenance_sha256), - "3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5" - ); - assert_eq!( - hex(&spec.virtual_f32_sha256), - "c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479" - ); - assert_eq!( - hex(&spec.native_shard_sha256[0]), - "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3" - ); - assert_eq!( - hex(&spec.native_shard_sha256[1]), - "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" - ); + assert_eq!(hex(&spec.archive_sha256), "536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5"); + assert_eq!(hex(&spec.provenance_sha256), "3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5"); + assert_eq!(hex(&spec.virtual_f32_sha256), "c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479"); + assert_eq!(hex(&spec.native_shard_sha256[0]), "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"); + assert_eq!(hex(&spec.native_shard_sha256[1]), "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"); assert_eq!( hex(&spec.parts[0].derived_f32_sha256), "94f83e0c081fd92a824cb74a0d67c6fc2261af101dee251a411a6bb5f0664681" @@ -98,24 +75,15 @@ fn pins_match_independent_conversion_receipts() { hex(&spec.parts[1].derived_f32_sha256), "06623754d1373dd50f21ec99380fb3e7823eb3c9993700ee071965242dc7eb15" ); - assert_eq!( - pinned_profile().unwrap().native_shard_sha256(), - &NATIVE_DIGESTS - ); + assert_eq!(pinned_profile().unwrap().native_shard_sha256(), &NATIVE_DIGESTS); } #[test] fn partitions_cover_exact_rows_and_contiguous_virtual_bytes() { let spec = pinned_profile_spec().unwrap(); assert_eq!(spec.parts.len(), 2); - assert_eq!( - spec.parts[0].name, - "per_layer_token_embd.weight#strata-part-001-of-002" - ); - assert_eq!( - spec.parts[1].name, - "per_layer_token_embd.weight#strata-part-002-of-002" - ); + assert_eq!(spec.parts[0].name, "per_layer_token_embd.weight#strata-part-001-of-002"); + assert_eq!(spec.parts[1].name, "per_layer_token_embd.weight#strata-part-002-of-002"); let mut next_row = 0; let mut next_byte = 502_974_615_040; for part in &spec.parts { diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs index 3f267b91..18f1d8ab 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy.rs @@ -97,37 +97,23 @@ mod private_loader_tests { std::io::Error::other("SECRET_OPERATOR_PATH_AND_CAPTURE"), "leleka-kar phase=CopyWrite kind=Other errno=None\n", ), - ( - std::io::Error::from_raw_os_error(28), - "leleka-kar phase=CopyWrite kind=StorageFull errno=Some(28)\n", - ), + (std::io::Error::from_raw_os_error(28), "leleka-kar phase=CopyWrite kind=StorageFull errno=Some(28)\n"), ] { - let mut writer = ShortWriter { - bytes: Vec::new(), - failure: Some(error), - }; + let mut writer = ShortWriter { bytes: Vec::new(), failure: Some(error) }; let mut captured = Vec::new(); - let result = copy_exact_reporting( - &mut Cursor::new(b"abcdef"), - &mut writer, - 6, - |phase, error| diagnostic(&mut captured, phase, error), - ); + let result = copy_exact_reporting(&mut Cursor::new(b"abcdef"), &mut writer, 6, |phase, error| { + diagnostic(&mut captured, phase, error) + }); assert!(matches!(result, Err(InputBindingError::Read))); assert_eq!(writer.bytes, b"abc"); assert_eq!(captured, expected.as_bytes()); assert!(!captured.windows(6).any(|w| w == b"SECRET")); } - let mut writer = ShortWriter { - bytes: Vec::new(), - failure: Some(std::io::Error::other("PRIVATE_ERROR_DETAIL")), - }; - let result = copy_exact_reporting( - &mut Cursor::new(b"abcdef"), - &mut writer, - 6, - |phase, error| diagnostic(&mut BrokenSink, phase, error), - ); + let mut writer = + ShortWriter { bytes: Vec::new(), failure: Some(std::io::Error::other("PRIVATE_ERROR_DETAIL")) }; + let result = copy_exact_reporting(&mut Cursor::new(b"abcdef"), &mut writer, 6, |phase, error| { + diagnostic(&mut BrokenSink, phase, error) + }); assert!(matches!(result, Err(InputBindingError::Read))); assert_eq!(writer.bytes, b"abc"); } @@ -135,8 +121,7 @@ mod private_loader_tests { struct Fixture(PathBuf); impl Fixture { fn new() -> Self { - let parent = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-loader"); + let parent = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-loader"); fs::create_dir_all(&parent).unwrap(); loop { let id = SEQUENCE.fetch_add(1, Ordering::Relaxed); @@ -154,10 +139,7 @@ mod private_loader_tests { open_regular(&path, Some(bytes.len() as u64)).unwrap() } fn children(&self) -> Vec { - fs::read_dir(&self.0) - .unwrap() - .map(|x| x.unwrap().path()) - .collect() + fs::read_dir(&self.0).unwrap().map(|x| x.unwrap().path()).collect() } } impl Drop for Fixture { @@ -292,26 +274,26 @@ mod private_loader_tests { mod inode_fn; #[allow(unused_imports)] -use inode_fn::inode; -#[allow(unused_imports)] use inode_fn::diagnostic; -#[allow(unused_imports)] -use inode_fn::report_io; -#[allow(unused_imports)] -use inode_fn::phase_error; -#[allow(unused_imports)] -pub(super) use inode_fn::provenance_error; -#[allow(unused_imports)] -pub(super) use inode_fn::open_regular; -#[cfg(target_os = "macos")] -#[allow(unused_imports)] -use inode_fn::protected_root; #[cfg(target_os = "linux")] #[allow(unused_imports)] pub(super) use inode_fn::freeze; #[cfg(target_os = "macos")] #[allow(unused_imports)] pub(super) use inode_fn::freeze; +#[allow(unused_imports)] +use inode_fn::inode; +#[allow(unused_imports)] +pub(super) use inode_fn::open_regular; +#[allow(unused_imports)] +use inode_fn::phase_error; +#[cfg(target_os = "macos")] +#[allow(unused_imports)] +use inode_fn::protected_root; +#[allow(unused_imports)] +pub(super) use inode_fn::provenance_error; +#[allow(unused_imports)] +use inode_fn::report_io; mod checked_reader_fn; #[cfg(target_os = "macos")] #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs index aa7b9187..ae014b10 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/private_copy/checked_reader_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(target_os = "macos")] pub(super) fn checked_reader(own: &OwnedCopy, bytes: u64) -> InputResult { let reader = OpenOptions::new() @@ -11,34 +10,19 @@ pub(super) fn checked_reader(own: &OwnedCopy, bytes: u64) -> InputResult { .custom_flags(SOURCE_FLAGS) .open(&own.path) .map_err(|e| phase_error(IoPhase::OpenReader, e))?; - let meta = reader - .metadata() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + let meta = reader.metadata().map_err(|e| phase_error(IoPhase::OpenReader, e))?; // Preserve open_regular's exact file/length refusal separately from // the existing inode/mode/link checks below. if !meta.is_file() || meta.len() != bytes { - return Err(input_failure( - LoadPhase::ReaderLength, - InputBindingError::Range, - )); + return Err(input_failure(LoadPhase::ReaderLength, InputBindingError::Range)); } - if Some(inode(&meta)) != own.file_inode - || meta.mode() & 0o7777 != 0o400 - || meta.nlink() != 1 - { - return Err(input_failure( - LoadPhase::ReaderIdentity, - InputBindingError::Metadata, - )); + if Some(inode(&meta)) != own.file_inode || meta.mode() & 0o7777 != 0o400 || meta.nlink() != 1 { + return Err(input_failure(LoadPhase::ReaderIdentity, InputBindingError::Metadata)); } Ok(reader) } -pub(super) fn copy_exact( - source: &mut R, - destination: &mut W, - bytes: u64, -) -> InputResult<()> { +pub(super) fn copy_exact(source: &mut R, destination: &mut W, bytes: u64) -> InputResult<()> { copy_exact_reporting(source, destination, bytes, report_io) } @@ -71,10 +55,7 @@ pub(super) fn copy_exact_reporting Inode { (meta.dev(), meta.ino()) } @@ -11,12 +10,7 @@ pub(super) fn inode(meta: &Metadata) -> Inode { // ErrorDisplay can contain an operator path or arbitrary source text. // Only a closed phase/kind and numeric OS code reach this diagnostic. pub(super) fn diagnostic(sink: &mut W, phase: IoPhase, error: &std::io::Error) { - let _ = writeln!( - sink, - "leleka-kar phase={phase:?} kind={:?} errno={:?}", - error.kind(), - error.raw_os_error() - ); + let _ = writeln!(sink, "leleka-kar phase={phase:?} kind={:?} errno={:?}", error.kind(), error.raw_os_error()); } pub(super) fn report_io(phase: IoPhase, error: &std::io::Error) { diagnostic(&mut std::io::stderr().lock(), phase, error); @@ -35,9 +29,7 @@ pub(in super::super) fn open_regular(path: &Path, bytes: Option) -> InputRe .custom_flags(SOURCE_FLAGS) .open(path) .map_err(|e| phase_error(IoPhase::SourceOpen, e))?; - let meta = file - .metadata() - .map_err(|e| phase_error(IoPhase::SourceMetadata, e))?; + let meta = file.metadata().map_err(|e| phase_error(IoPhase::SourceMetadata, e))?; if !meta.is_file() || bytes.is_some_and(|size| meta.len() != size) { return Err(InputBindingError::Range); } @@ -48,21 +40,11 @@ pub(in super::super) fn open_regular(path: &Path, bytes: Option) -> InputRe pub(super) fn protected_root(path: &Path) -> InputResult<(PathBuf, u32)> { let meta = fs::symlink_metadata(path).map_err(|e| phase_error(IoPhase::RootMetadata, e))?; if !meta.is_dir() || meta.permissions().mode() & 0o7777 != 0o700 { - return Err(input_failure( - LoadPhase::RootMode, - InputBindingError::Metadata, - )); + return Err(input_failure(LoadPhase::RootMode, InputBindingError::Metadata)); } - let canonical = path - .canonicalize() - .map_err(|e| phase_error(IoPhase::RootCanonical, e))?; - if inode(&meta) - != inode(&fs::metadata(&canonical).map_err(|e| phase_error(IoPhase::RootMetadata, e))?) - { - return Err(input_failure( - LoadPhase::RootIdentity, - InputBindingError::Metadata, - )); + let canonical = path.canonicalize().map_err(|e| phase_error(IoPhase::RootCanonical, e))?; + if inode(&meta) != inode(&fs::metadata(&canonical).map_err(|e| phase_error(IoPhase::RootMetadata, e))?) { + return Err(input_failure(LoadPhase::RootIdentity, InputBindingError::Metadata)); } Ok((canonical, meta.uid())) } @@ -82,19 +64,11 @@ impl OwnedCopy { } pub(super) fn created(directory: PathBuf, uid: u32) -> InputResult { - let meta = fs::symlink_metadata(&directory) - .map_err(|e| phase_error(IoPhase::DirectoryMetadata, e))?; - let own = Self { - path: directory.join("archive.kar"), - directory, - directory_inode: inode(&meta), - file_inode: None, - }; + let meta = fs::symlink_metadata(&directory).map_err(|e| phase_error(IoPhase::DirectoryMetadata, e))?; + let own = + Self { path: directory.join("archive.kar"), directory, directory_inode: inode(&meta), file_inode: None }; if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o7777 != 0o700 { - return Err(input_failure( - LoadPhase::DirectoryIdentity, - InputBindingError::Metadata, - )); + return Err(input_failure(LoadPhase::DirectoryIdentity, InputBindingError::Metadata)); } Ok(own) } @@ -107,29 +81,17 @@ impl OwnedCopy { .custom_flags(SOURCE_FLAGS) .open(&self.path) .map_err(|e| phase_error(IoPhase::WriterOpen, e))?; - let meta = file - .metadata() - .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; + let meta = file.metadata().map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; self.file_inode = Some(inode(&meta)); - if !meta.is_file() - || meta.uid() != uid - || meta.mode() & 0o7777 != 0o600 - || meta.nlink() != 1 - { - return Err(input_failure( - LoadPhase::WriterIdentity, - InputBindingError::Metadata, - )); + if !meta.is_file() || meta.uid() != uid || meta.mode() & 0o7777 != 0o600 || meta.nlink() != 1 { + return Err(input_failure(LoadPhase::WriterIdentity, InputBindingError::Metadata)); } Ok(file) } pub(super) fn detach(&mut self) -> InputResult<()> { if !self.owns_directory() || !self.owns_file() { - return Err(input_failure( - LoadPhase::DetachIdentity, - InputBindingError::Metadata, - )); + return Err(input_failure(LoadPhase::DetachIdentity, InputBindingError::Metadata)); } fs::remove_file(&self.path).map_err(|e| phase_error(IoPhase::Unlink, e))?; self.file_inode = None; @@ -137,12 +99,10 @@ impl OwnedCopy { Ok(()) } pub(super) fn owns_directory(&self) -> bool { - fs::symlink_metadata(&self.directory) - .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) + fs::symlink_metadata(&self.directory).is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) } pub(super) fn owns_file(&self) -> bool { - fs::symlink_metadata(&self.path) - .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) + fs::symlink_metadata(&self.path).is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) } } #[cfg(target_os = "macos")] @@ -163,49 +123,29 @@ pub(in super::super) fn freeze(source: &mut File, _owner_root: &Path, bytes: u64 // Safe OwnedFd -> File conversion transfers ownership exactly once. // No pathname, filesystem quota, permission change or privileged call // is needed. Unsupported/failed sealing refuses admission outright. - let fd = memfd_create( - "leleka-kar", - MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING, - ) - .map_err(|e| phase_error(IoPhase::Create, e.into()))?; + let fd = memfd_create("leleka-kar", MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING) + .map_err(|e| phase_error(IoPhase::Create, e.into()))?; let mut writer = File::from(fd); copy_exact(source, &mut writer, bytes)?; - writer - .sync_all() - .map_err(|e| phase_error(IoPhase::Sync, e))?; + writer.sync_all().map_err(|e| phase_error(IoPhase::Sync, e))?; let required = SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL; fcntl_add_seals(&writer, required).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; let actual = fcntl_get_seals(&writer).map_err(|e| phase_error(IoPhase::Seal, e.into()))?; if !actual.contains(required) { - return Err(input_failure( - LoadPhase::ReaderIdentity, - InputBindingError::Metadata, - )); + return Err(input_failure(LoadPhase::ReaderIdentity, InputBindingError::Metadata)); } - let meta = writer - .metadata() - .map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; + let meta = writer.metadata().map_err(|e| phase_error(IoPhase::WriterMetadata, e))?; if !meta.is_file() || meta.len() != bytes { - return Err(input_failure( - LoadPhase::ReaderLength, - InputBindingError::Range, - )); + return Err(input_failure(LoadPhase::ReaderLength, InputBindingError::Range)); } if meta.nlink() != 0 { - return Err(input_failure( - LoadPhase::ReaderDetached, - InputBindingError::Metadata, - )); + return Err(input_failure(LoadPhase::ReaderDetached, InputBindingError::Metadata)); } // A cloned descriptor retains the same sealed inode. Its access mode // cannot bypass the kernel seals. Close the copy writer before return. - let mut reader = writer - .try_clone() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + let mut reader = writer.try_clone().map_err(|e| phase_error(IoPhase::OpenReader, e))?; drop(writer); - reader - .rewind() - .map_err(|e| phase_error(IoPhase::OpenReader, e))?; + reader.rewind().map_err(|e| phase_error(IoPhase::OpenReader, e))?; Ok(reader) } @@ -215,25 +155,13 @@ pub(in super::super) fn freeze(source: &mut File, owner_root: &Path, bytes: u64) let mut own = OwnedCopy::create(&root, uid)?; let mut writer = own.writer(uid)?; copy_exact(source, &mut writer, bytes)?; - writer - .sync_all() - .map_err(|e| phase_error(IoPhase::Sync, e))?; - writer - .set_permissions(Permissions::from_mode(0o400)) - .map_err(|e| phase_error(IoPhase::Seal, e))?; + writer.sync_all().map_err(|e| phase_error(IoPhase::Sync, e))?; + writer.set_permissions(Permissions::from_mode(0o400)).map_err(|e| phase_error(IoPhase::Seal, e))?; let reader = checked_reader(&own, bytes)?; drop(writer); own.detach()?; - if reader - .metadata() - .map_err(|e| phase_error(IoPhase::DetachedMetadata, e))? - .nlink() - != 0 - { - return Err(input_failure( - LoadPhase::ReaderDetached, - InputBindingError::Metadata, - )); + if reader.metadata().map_err(|e| phase_error(IoPhase::DetachedMetadata, e))?.nlink() != 0 { + return Err(input_failure(LoadPhase::ReaderDetached, InputBindingError::Metadata)); } Ok(reader) } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs index aee07cf6..e78770bf 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_kar_ple/win_archive.rs @@ -74,8 +74,8 @@ pub(super) fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> let mut buffer = [0u8; 64 * 1024]; let mut offset = 0u64; while offset < length { - let count = usize::try_from((length - offset).min(buffer.len() as u64)) - .map_err(|_| InputBindingError::Range)?; + let count = + usize::try_from((length - offset).min(buffer.len() as u64)).map_err(|_| InputBindingError::Range)?; read_exact_at(file, &mut buffer[..count], offset).map_err(io_error)?; digest.update(&buffer[..count]); offset += count as u64; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_encoded_finite.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_encoded_finite.rs index 33967097..494ca185 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_encoded_finite.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_encoded_finite.rs @@ -1,6 +1,6 @@ //! Exact finite admission for six routed packed formats, without F32 materialization. //! Pinned scalar decoders live in quant-core; no weight or multiply arithmetic changes. -use super::{InputResult, E}; +use super::{E, InputResult}; pub(super) fn validate_row(kind: u32, bytes: &[u8], values: usize) -> InputResult<()> { let block_bytes = match kind { @@ -25,11 +25,7 @@ pub(super) fn validate_row(kind: u32, bytes: &[u8], values: usize) -> InputResul for block in bytes.chunks_exact(block_bytes) { let scale = u16::from_le_bytes([block[0], block[1]]); if scale & 0x7c00 == 0x7c00 { - return Err(if kind == 21 { - E::Geometry - } else { - E::NonFinite - }); + return Err(if kind == 21 { E::Geometry } else { E::NonFinite }); } } Ok(()) @@ -43,12 +39,7 @@ mod tests { fn compare_original_first(kind: u32, bytes: &[u8], values: usize) { let original = decode::row(kind, bytes, values).map(|_| ()); let encoded = validate_row(kind, bytes, values); - assert_eq!( - encoded, - original, - "kind={kind} values={values} bytes={}", - bytes.len() - ); + assert_eq!(encoded, original, "kind={kind} values={values} bytes={}", bytes.len()); } #[test] @@ -67,8 +58,7 @@ mod tests { for bits in 0..=u16::MAX { block[..2].copy_from_slice(&bits.to_le_bytes()); for (index, code) in block[2..].iter_mut().enumerate() { - *code = - (index as u8).wrapping_mul(73).wrapping_add(bits as u8) ^ (bits >> 8) as u8; + *code = (index as u8).wrapping_mul(73).wrapping_add(bits as u8) ^ (bits >> 8) as u8; } compare_original_first(kind, &block, elements); } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert.rs index 1800f78d..e20b1cd3 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert.rs @@ -1,7 +1,5 @@ //! Selected packed MoE rows from the original verified artifact owners. -use super::{ - BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, TensorRole, -}; +use super::{BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, TensorRole}; #[path = "qwen4exp_moe_encoded_finite.rs"] mod encoded_finite; @@ -90,26 +88,11 @@ mod tests { } #[test] fn expert_roles_cannot_reinterpret_rank_format_or_packed_extent() { - assert_eq!( - descriptor(21, &[2560, 640, 512], 360448000, true, false), - Ok((MoeMatrixKind::Iq3S, 1100)) - ); - assert_eq!( - descriptor(20, &[640, 2560, 512], 471859200, true, true), - Ok((MoeMatrixKind::RoutedIq4Nl, 360)) - ); - assert_eq!( - descriptor(42, &[640, 2560, 512], 235929600, true, true), - Ok((MoeMatrixKind::Q2_0, 180)) - ); - assert_eq!( - descriptor(13, &[2560, 640], 1126400, false, false), - Ok((MoeMatrixKind::Q5K, 1760)) - ); - assert_eq!( - descriptor(8, &[640, 2560], 1740800, false, true), - Ok((MoeMatrixKind::Q8_0, 680)) - ); + assert_eq!(descriptor(21, &[2560, 640, 512], 360448000, true, false), Ok((MoeMatrixKind::Iq3S, 1100))); + assert_eq!(descriptor(20, &[640, 2560, 512], 471859200, true, true), Ok((MoeMatrixKind::RoutedIq4Nl, 360))); + assert_eq!(descriptor(42, &[640, 2560, 512], 235929600, true, true), Ok((MoeMatrixKind::Q2_0, 180))); + assert_eq!(descriptor(13, &[2560, 640], 1126400, false, false), Ok((MoeMatrixKind::Q5K, 1760))); + assert_eq!(descriptor(8, &[640, 2560], 1740800, false, true), Ok((MoeMatrixKind::Q8_0, 680))); for (raw, dims, bytes) in [ (21, &[640, 2560, 512][..], 360448000), (21, &[2560, 640][..], 360448000), @@ -131,17 +114,10 @@ mod owned_payload_handoff { fn consumed_encoded_block_retains_allocation_and_whole_payload() { // Ownership-only synthetic bytes; not a model/finite/descriptor proof. // Multiple rows and every byte value exercise the entire moved span. - let expected: Vec = (0..62_720) - .map(|index| ((index * 37 + index / 256) % 256) as u8) - .collect(); + let expected: Vec = (0..62_720).map(|index| ((index * 37 + index / 256) % 256) as u8).collect(); let source = expected.clone().into_boxed_slice(); let pointer = source.as_ptr(); - let block = MoeExpertBlock { - kind: MoeMatrixKind::Iq3Xxs, - columns: 2560, - rows: 64, - bytes: source, - }; + let block = MoeExpertBlock { kind: MoeMatrixKind::Iq3Xxs, columns: 2560, rows: 64, bytes: source }; assert_eq!(block.kind(), MoeMatrixKind::Iq3Xxs); assert_eq!(block.columns(), 2560); assert_eq!(block.rows(), 64); @@ -171,15 +147,15 @@ pub(crate) struct MoeRoutedSourceScope<'source, 'group> { #[path = "qwen4exp_moe_expert/impl_moeexpertweights.rs"] mod impl_moeexpertweights; #[allow(unused_imports)] +use impl_moeexpertweights::descriptor; +#[allow(unused_imports)] use impl_moeexpertweights::index; #[allow(unused_imports)] use impl_moeexpertweights::matrix_kind; #[allow(unused_imports)] -use impl_moeexpertweights::descriptor; +use impl_moeexpertweights::validate_range; #[allow(unused_imports)] use impl_moeexpertweights::validate_selected; -#[allow(unused_imports)] -use impl_moeexpertweights::validate_range; #[path = "qwen4exp_moe_expert/impl_modelbinding.rs"] mod impl_modelbinding; #[path = "qwen4exp_moe_expert/routed_source_descriptor_fn.rs"] diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs index 7df2398a..554b9aa6 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2.rs @@ -3,13 +3,8 @@ #[allow(unused_imports)] use super::*; - impl ModelBinding { - pub(crate) fn moe_expert_weights( - &self, - layer: u32, - selected: [u32; SELECTED], - ) -> InputResult { + pub(crate) fn moe_expert_weights(&self, layer: u32, selected: [u32; SELECTED]) -> InputResult { validate_selected(&selected)?; if layer >= self.layer_count() { return Err(E::Range); @@ -26,30 +21,14 @@ impl ModelBinding { return Err(E::Metadata); } let make = |role: LayerRole, routed: bool, down: bool| -> InputResult { - let role = TensorRole::Layer { - layer: layer_index, - role, - }; + let role = TensorRole::Layer { layer: layer_index, role }; let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; if tensor.shard() != 0 { return Err(E::Geometry); } - let (kind, row_bytes) = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - routed, - down, - )?; + let (kind, row_bytes) = descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), routed, down)?; let (columns, rows) = if down { (FF, N) } else { (N, FF) }; - Ok(Matrix { - role, - kind, - raw_kind: tensor.kind(), - columns, - rows, - row_bytes, - }) + Ok(Matrix { role, kind, raw_kind: tensor.kind(), columns, rows, row_bytes }) }; let routed = [ make(LayerRole::FfnGateExperts, true, false)?, @@ -61,10 +40,7 @@ impl ModelBinding { make(LayerRole::FfnUpShared, false, false)?, make(LayerRole::FfnDownShared, false, true)?, ]; - let role = TensorRole::Layer { - layer: layer_index, - role: LayerRole::FfnGateInpShared, - }; + let role = TensorRole::Layer { layer: layer_index, role: LayerRole::FfnGateInpShared }; let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; if tensor.kind() != 30 || tensor.shard() != 0 @@ -73,13 +49,7 @@ impl ModelBinding { { return Err(E::Geometry); } - Ok(MoeExpertWeights { - binding: self.identity(), - layer, - selected, - routed, - shared, - }) + Ok(MoeExpertWeights { binding: self.identity(), layer, selected, routed, shared }) } /// Actual bound tensor/expert address; no synthetic selected-route object. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -115,18 +85,9 @@ impl ModelBinding { if tensor.shard() != 0 { return Err(E::Geometry); } - let (_, row_bytes) = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - true, - role == MoeMatrixRole::Down, - )?; - let (columns, rows) = if role == MoeMatrixRole::Down { - (FF, N) - } else { - (N, FF) - }; + let (_, row_bytes) = + descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), true, role == MoeMatrixRole::Down)?; + let (columns, rows) = if role == MoeMatrixRole::Down { (FF, N) } else { (N, FF) }; let key = MoeWeightDescriptor { layer, expert: Some(expert), @@ -136,9 +97,7 @@ impl ModelBinding { rows, bytes: rows.checked_mul(row_bytes).ok_or(E::Geometry)?, }; - artifact - .validate_tensor_source(tensor_role) - .map_err(|_| E::Read)?; + artifact.validate_tensor_source(tensor_role).map_err(|_| E::Read)?; Ok(key) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -163,14 +122,11 @@ impl ModelBinding { }; let row_bytes = key.bytes.checked_div(key.rows).ok_or(E::Geometry)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(key.bytes) - .map_err(|_| E::Allocation)?; + bytes.try_reserve_exact(key.bytes).map_err(|_| E::Allocation)?; bytes.resize(key.bytes, 0); let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; let bytes = artifact - .read_expert_rows_owned(tensor_role, u64::from(expert), 0, key.rows as u64, - bytes.into_boxed_slice()) + .read_expert_rows_owned(tensor_role, u64::from(expert), 0, key.rows as u64, bytes.into_boxed_slice()) .map_err(|_| E::Read)?; if bytes.len() != key.bytes { return Err(E::Read); @@ -207,15 +163,10 @@ impl ModelBinding { expert.is_some(), role == MoeMatrixRole::Down, )?; - if tensor.shard() != 0 - || tensor.kind() != matrix.raw_kind - || checked != (matrix.kind, matrix.row_bytes) - { + if tensor.shard() != 0 || tensor.kind() != matrix.raw_kind || checked != (matrix.kind, matrix.row_bytes) { return Err(E::Geometry); } - artifact - .validate_tensor_source(matrix.role) - .map_err(|_| E::Read)?; + artifact.validate_tensor_source(matrix.role).map_err(|_| E::Read)?; Ok(MoeWeightDescriptor { layer: weights.layer, expert, @@ -223,10 +174,7 @@ impl ModelBinding { raw_kind: matrix.raw_kind, columns: matrix.columns, rows: matrix.rows, - bytes: matrix - .rows - .checked_mul(matrix.row_bytes) - .ok_or(E::Geometry)?, + bytes: matrix.rows.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?, }) } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs index 96e44a54..2e118d26 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_modelbinding/impl_modelbinding_2_2.rs @@ -3,12 +3,8 @@ #[allow(unused_imports)] use super::*; - impl ModelBinding { - pub(crate) fn moe_shared_scalar_descriptor( - &self, - weights: &MoeExpertWeights, - ) -> InputResult { + pub(crate) fn moe_shared_scalar_descriptor(&self, weights: &MoeExpertWeights) -> InputResult { if !weights.matches(&self.identity(), weights.layer) { return Err(E::Metadata); } @@ -48,11 +44,7 @@ impl ModelBinding { scalar.try_reserve_exact(N * 2).map_err(|_| E::Allocation)?; artifact .stream_row(role, 0, |chunk| { - if scalar - .len() - .checked_add(chunk.len()) - .is_none_or(|v| v > N * 2) - { + if scalar.len().checked_add(chunk.len()).is_none_or(|v| v > N * 2) { return Err(std::io::ErrorKind::InvalidData.into()); } scalar.extend_from_slice(chunk); @@ -62,12 +54,7 @@ impl ModelBinding { if scalar.len() != N * 2 { return Err(E::Read); } - if scalar - .as_chunks::<2>() - .0 - .iter() - .any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) - { + if scalar.as_chunks::<2>().0.iter().any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) { return Err(E::NonFinite); } Ok(scalar.into_boxed_slice()) @@ -98,10 +85,7 @@ impl ModelBinding { expert.is_some(), role == MoeMatrixRole::Down, )?; - if tensor.shard() != 0 - || tensor.kind() != matrix.raw_kind - || checked != (matrix.kind, matrix.row_bytes) - { + if tensor.shard() != 0 || tensor.kind() != matrix.raw_kind || checked != (matrix.kind, matrix.row_bytes) { return Err(E::Geometry); } let limit = count.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?; @@ -130,34 +114,19 @@ impl ModelBinding { let _finite = super::super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; } } - return Ok(MoeExpertBlock { - kind: matrix.kind, - columns: matrix.columns, - rows: count, - bytes, - }); + return Ok(MoeExpertBlock { kind: matrix.kind, columns: matrix.columns, rows: count, bytes }); } // The retained owner streams one bounded tile or complete matrix. Chunks may // cross row boundaries; decoder admission still checks each exact row. let consume = |chunk: &[u8]| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|v| v > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|v| v > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); Ok(()) }; match expert { - Some(id) => artifact.stream_expert_rows( - matrix.role, - u64::from(id), - first as u64, - count as u64, - consume, - ), + Some(id) => artifact.stream_expert_rows(matrix.role, u64::from(id), first as u64, count as u64, consume), None => artifact.stream_rows(matrix.role, first as u64, count as u64, consume), } .map_err(|_| E::Read)?; @@ -172,11 +141,6 @@ impl ModelBinding { let _finite = super::super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; } } - Ok(MoeExpertBlock { - kind: matrix.kind, - columns: matrix.columns, - rows: count, - bytes: bytes.into_boxed_slice(), - }) + Ok(MoeExpertBlock { kind: matrix.kind, columns: matrix.columns, rows: count, bytes: bytes.into_boxed_slice() }) } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeexpertweights.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeexpertweights.rs index 2e78ee0f..7a4ab5c7 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeexpertweights.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeexpertweights.rs @@ -14,19 +14,11 @@ impl MoeExpertWeights { MoeExpertSelection::Shared => Ok(self.shared[index(role)]), } } - pub(crate) fn shape( - &self, - selection: MoeExpertSelection, - role: MoeMatrixRole, - ) -> InputResult<(usize, usize)> { + pub(crate) fn shape(&self, selection: MoeExpertSelection, role: MoeMatrixRole) -> InputResult<(usize, usize)> { let m = self.matrix(selection, role)?; Ok((m.columns, m.rows)) } - pub(crate) fn kind( - &self, - selection: MoeExpertSelection, - role: MoeMatrixRole, - ) -> InputResult { + pub(crate) fn kind(&self, selection: MoeExpertSelection, role: MoeMatrixRole) -> InputResult { Ok(self.matrix(selection, role)?.kind) } } @@ -87,10 +79,8 @@ pub(super) fn descriptor( return Err(E::Geometry); } let row_bytes = super::super::decode::row_bytes(raw, columns)?; - let extent = row_bytes - .checked_mul(rows) - .and_then(|v| v.checked_mul(if routed { EXPERTS } else { 1 })) - .ok_or(E::Geometry)?; + let extent = + row_bytes.checked_mul(rows).and_then(|v| v.checked_mul(if routed { EXPERTS } else { 1 })).ok_or(E::Geometry)?; if bytes != extent as u64 { return Err(E::Geometry); } @@ -109,10 +99,7 @@ pub(super) fn validate_selected(ids: &[u32; SELECTED]) -> InputResult<()> { } pub(super) fn validate_range(first: usize, count: usize, rows: usize) -> InputResult<()> { let complete = first == 0 && count == rows && [FF, N].contains(&rows); - if count == 0 - || (count > TILE && !complete) - || first.checked_add(count).is_none_or(|end| end > rows) - { + if count == 0 || (count > TILE && !complete) || first.checked_add(count).is_none_or(|end| end > rows) { return Err(E::Range); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeroutedsourcescope.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeroutedsourcescope.rs index 77e7fa8b..b55fb100 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeroutedsourcescope.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/impl_moeroutedsourcescope.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'group> MoeRoutedSourceScope<'_, 'group> { /// Inside a group scope (`with_moe_routed_group_source`): make `members` (one job's route, all @@ -77,7 +76,14 @@ impl ModelBinding { ) .map_err(&map_source_error)?; let source = artifact.begin_routed_moe_source(first.layer, expert).map_err(|_| map_source_error(E::Read))?; - let mut scope = MoeRoutedSourceScope { binding: self, members, expert, layer: first.layer, source: Some(source), finished: false }; + let mut scope = MoeRoutedSourceScope { + binding: self, + members, + expert, + layer: first.layer, + source: Some(source), + finished: false, + }; let result = execute(&mut scope); let explicitly_finished = scope.finished; let cleanup = if scope.source.is_some() { @@ -101,54 +107,73 @@ impl ModelBinding { // Direct bound shared descriptors. No selected route is created for preload. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl ModelBinding { - pub(crate) fn moe_shared_preload_descriptors( - &self, layer: u32, - ) -> InputResult<[MoeWeightDescriptor; 4]> { - if layer >= self.layer_count() { return Err(E::Range); } + pub(crate) fn moe_shared_preload_descriptors(&self, layer: u32) -> InputResult<[MoeWeightDescriptor; 4]> { + if layer >= self.layer_count() { + return Err(E::Range); + } let layer_index = u8::try_from(layer).map_err(|_| E::Range)?; let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; let t = artifact.topology(); - if self.layer_count() != 48 || t.embedding_length() != N as u32 - || t.expert_count() != EXPERTS as u32 || t.expert_used_count() != SELECTED as u32 + if self.layer_count() != 48 + || t.embedding_length() != N as u32 + || t.expert_count() != EXPERTS as u32 + || t.expert_used_count() != SELECTED as u32 || t.expert_feed_forward_length() != FF as u32 || t.expert_shared_feed_forward_length() != FF as u32 - { return Err(E::Metadata); } - let roles = [LayerRole::FfnGateShared, LayerRole::FfnUpShared, - LayerRole::FfnDownShared, LayerRole::FfnGateInpShared]; - let mut keys = [MoeWeightDescriptor { layer, expert: None, role: 0, - raw_kind: 0, columns: 0, rows: 0, bytes: 0 }; 4]; + { + return Err(E::Metadata); + } + let roles = + [LayerRole::FfnGateShared, LayerRole::FfnUpShared, LayerRole::FfnDownShared, LayerRole::FfnGateInpShared]; + let mut keys = + [MoeWeightDescriptor { layer, expert: None, role: 0, raw_kind: 0, columns: 0, rows: 0, bytes: 0 }; 4]; for (index, role) in roles.into_iter().enumerate() { let role = TensorRole::Layer { layer: layer_index, role }; let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; - if tensor.shard() != 0 { return Err(E::Geometry); } + if tensor.shard() != 0 { + return Err(E::Geometry); + } let (columns, rows, bytes) = if index == 3 { - if tensor.kind() != 30 || tensor.dimensions() != [N as u64] - || tensor.byte_length() != (N * 2) as u64 - { return Err(E::Geometry); } + if tensor.kind() != 30 || tensor.dimensions() != [N as u64] || tensor.byte_length() != (N * 2) as u64 { + return Err(E::Geometry); + } (N, 1, N * 2) } else { - let (_, row_bytes) = descriptor(tensor.kind(), tensor.dimensions(), - tensor.byte_length(), false, index == 2)?; + let (_, row_bytes) = + descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), false, index == 2)?; let (columns, rows) = if index == 2 { (FF, N) } else { (N, FF) }; (columns, rows, rows.checked_mul(row_bytes).ok_or(E::Geometry)?) }; - keys[index] = MoeWeightDescriptor { layer, expert: None, role: index as u8, - raw_kind: tensor.kind(), columns, rows, bytes }; + keys[index] = MoeWeightDescriptor { + layer, + expert: None, + role: index as u8, + raw_kind: tensor.kind(), + columns, + rows, + bytes, + }; artifact.validate_tensor_source(role).map_err(|_| E::Read)?; } Ok(keys) } - pub(crate) fn moe_shared_preload_block( - &self, key: MoeWeightDescriptor, - ) -> InputResult> { - if key.expert.is_some() || key.role >= 4 { return Err(E::Range); } + pub(crate) fn moe_shared_preload_block(&self, key: MoeWeightDescriptor) -> InputResult> { + if key.expert.is_some() || key.role >= 4 { + return Err(E::Range); + } if self.moe_shared_preload_descriptors(key.layer)?[usize::from(key.role)] != key { return Err(E::Geometry); } - let role = TensorRole::Layer { layer: u8::try_from(key.layer).map_err(|_| E::Range)?, - role: match key.role { 0 => LayerRole::FfnGateShared, 1 => LayerRole::FfnUpShared, - 2 => LayerRole::FfnDownShared, 3 => LayerRole::FfnGateInpShared, - _ => return Err(E::Range) } }; + let role = TensorRole::Layer { + layer: u8::try_from(key.layer).map_err(|_| E::Range)?, + role: match key.role { + 0 => LayerRole::FfnGateShared, + 1 => LayerRole::FfnUpShared, + 2 => LayerRole::FfnDownShared, + 3 => LayerRole::FfnGateInpShared, + _ => return Err(E::Range), + }, + }; let mut bytes = Vec::new(); bytes.try_reserve_exact(key.bytes).map_err(|_| E::Allocation)?; let mut artifact = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; @@ -159,14 +184,19 @@ impl ModelBinding { bytes.extend_from_slice(chunk); Ok(()) }; - if key.role == 3 { artifact.stream_row(role, 0, consume) } - else { artifact.stream_rows(role, 0, key.rows as u64, consume) } - .map_err(|_| E::Read)?; - if bytes.len() != key.bytes { return Err(E::Read); } if key.role == 3 { - if bytes.as_chunks::<2>().0.iter() - .any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) - { return Err(E::NonFinite); } + artifact.stream_row(role, 0, consume) + } else { + artifact.stream_rows(role, 0, key.rows as u64, consume) + } + .map_err(|_| E::Read)?; + if bytes.len() != key.bytes { + return Err(E::Read); + } + if key.role == 3 { + if bytes.as_chunks::<2>().0.iter().any(|word| u16::from_le_bytes(*word) & 0x7f80 == 0x7f80) { + return Err(E::NonFinite); + } } else { let row_bytes = key.bytes.checked_div(key.rows).ok_or(E::Geometry)?; // SAME original shared decoder admission, including every output. diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/routed_source_descriptor_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/routed_source_descriptor_fn.rs index 005a1e57..3aaa63f7 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/routed_source_descriptor_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_expert/routed_source_descriptor_fn.rs @@ -16,17 +16,9 @@ pub(super) fn routed_source_descriptor( } let matrix = weights.matrix(MoeExpertSelection::Routed { slot }, role)?; let expert = *weights.selected.get(slot).ok_or(E::Range)?; - let checked = descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - true, - role == MoeMatrixRole::Down, - )?; - if tensor.shard() != 0 - || tensor.kind() != matrix.raw_kind - || checked != (matrix.kind, matrix.row_bytes) - { + let checked = + descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), true, role == MoeMatrixRole::Down)?; + if tensor.shard() != 0 || tensor.kind() != matrix.raw_kind || checked != (matrix.kind, matrix.row_bytes) { return Err(E::Geometry); } Ok(MoeWeightDescriptor { @@ -36,10 +28,7 @@ pub(super) fn routed_source_descriptor( raw_kind: matrix.raw_kind, columns: matrix.columns, rows: matrix.rows, - bytes: matrix - .rows - .checked_mul(matrix.row_bytes) - .ok_or(E::Geometry)?, + bytes: matrix.rows.checked_mul(matrix.row_bytes).ok_or(E::Geometry)?, }) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -58,45 +47,27 @@ impl MoeRoutedSourceScope<'_, '_> { } Ok(()) } - pub(crate) fn descriptor( - &self, - member: usize, - role: MoeMatrixRole, - ) -> InputResult { + pub(crate) fn descriptor(&self, member: usize, role: MoeMatrixRole) -> InputResult { let (weights, slot) = *self.members.get(member).ok_or(E::Range)?; if weights.layer != self.layer || weights.selected.get(slot) != Some(&self.expert) { return Err(E::Metadata); } - let tensor = self - .source - .as_ref() - .ok_or(E::Read)? - .tensor(routed_source_role(role)) - .map_err(|_| E::Geometry)?; + let tensor = self.source.as_ref().ok_or(E::Read)?.tensor(routed_source_role(role)).map_err(|_| E::Geometry)?; let key = routed_source_descriptor(&self.binding.identity(), weights, slot, role, tensor)?; - self.source - .as_ref() - .ok_or(E::Read)? - .validate_descriptor(routed_source_role(role)) - .map_err(|_| E::Read)?; + self.source.as_ref().ok_or(E::Read)?.validate_descriptor(routed_source_role(role)).map_err(|_| E::Read)?; Ok(key) } /// Actual fixed-expert full encoded matrix, including original finite /// admission. The cold reader never reenters ModelBinding's RefCell. - pub(crate) fn block( - &mut self, - member: usize, - role: MoeMatrixRole, - ) -> InputResult { + pub(crate) fn block(&mut self, member: usize, role: MoeMatrixRole) -> InputResult { let key = self.descriptor(member, role)?; let (weights, slot) = self.members[member]; let matrix = weights.matrix(MoeExpertSelection::Routed { slot }, role)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(key.bytes) - .map_err(|_| E::Allocation)?; + bytes.try_reserve_exact(key.bytes).map_err(|_| E::Allocation)?; bytes.resize(key.bytes, 0); - let bytes = self.source + let bytes = self + .source .as_mut() .ok_or(E::Read)? .read_matrix_owned(routed_source_role(role), bytes.into_boxed_slice()) @@ -111,36 +82,47 @@ impl MoeRoutedSourceScope<'_, '_> { let _finite = super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; } } - Ok(MoeExpertBlock { - kind: matrix.kind, - columns: matrix.columns, - rows: matrix.rows, - bytes, - }) + Ok(MoeExpertBlock { kind: matrix.kind, columns: matrix.columns, rows: matrix.rows, bytes }) } - pub(crate) fn bank_span(&self, member: usize, role: MoeMatrixRole) - -> InputResult { + pub(crate) fn bank_span( + &self, + member: usize, + role: MoeMatrixRole, + ) -> InputResult { let key = self.descriptor(member, role)?; - let span = self.source.as_ref().ok_or(E::Read)? - .resident_matrix_span(routed_source_role(role)).map_err(|_| E::Read)?; - if span.bytes().len()!=key.bytes || span.raw_kind()!=key.raw_kind - || span.expert()!=key.expert.ok_or(E::Metadata)? {return Err(E::Geometry);} + let span = + self.source.as_ref().ok_or(E::Read)?.resident_matrix_span(routed_source_role(role)).map_err(|_| E::Read)?; + if span.bytes().len() != key.bytes + || span.raw_kind() != key.raw_kind + || span.expert() != key.expert.ok_or(E::Metadata)? + { + return Err(E::Geometry); + } Ok(span) } /// Validate the whole actual encoded matrix in place. Addressability is /// never a finite certificate: every staged role retains original order. - pub(crate) fn mapped_span(&self, member: usize, role: MoeMatrixRole) - -> InputResult { + pub(crate) fn mapped_span( + &self, + member: usize, + role: MoeMatrixRole, + ) -> InputResult { let key = self.descriptor(member, role)?; let (weights, slot) = self.members[member]; let matrix = weights.matrix(MoeExpertSelection::Routed { slot }, role)?; let span = self.bank_span(member, role)?; - if span.bytes().len() != key.bytes || span.raw_kind() != key.raw_kind - || span.expert() != key.expert.ok_or(E::Metadata)? { return Err(E::Geometry); } + if span.bytes().len() != key.bytes + || span.raw_kind() != key.raw_kind + || span.expert() != key.expert.ok_or(E::Metadata)? + { + return Err(E::Geometry); + } for row in span.bytes().chunks_exact(matrix.row_bytes) { if matches!(matrix.raw_kind, 18 | 21 | 22 | 23 | 20 | 42) { encoded_finite::validate_row(matrix.raw_kind, row, matrix.columns)?; - } else { let _finite = super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; } + } else { + let _finite = super::super::decode::row(matrix.raw_kind, row, matrix.columns)?; + } } Ok(span) } @@ -172,11 +154,7 @@ impl ModelBinding { if !first.matches(&self.identity(), first.layer) { return Err(map_source_error(E::Metadata)); } - let expert = *first - .selected - .get(first_slot) - .ok_or(E::Range) - .map_err(&map_source_error)?; + let expert = *first.selected.get(first_slot).ok_or(E::Range).map_err(&map_source_error)?; if expert >= EXPERTS as u32 { return Err(map_source_error(E::Range)); } @@ -184,24 +162,14 @@ impl ModelBinding { if !weights.matches(&self.identity(), first.layer) { return Err(map_source_error(E::Metadata)); } - let selected = weights - .selected - .get(*slot) - .ok_or(E::Range) - .map_err(&map_source_error)?; + let selected = weights.selected.get(*slot).ok_or(E::Range).map_err(&map_source_error)?; if *selected != expert { return Err(map_source_error(E::Metadata)); } } - let mut artifact = self - .artifact - .try_borrow_mut() - .map_err(|_| map_source_error(E::Busy))?; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| map_source_error(E::Busy))?; let first_role = first - .matrix( - MoeExpertSelection::Routed { slot: first_slot }, - MoeMatrixRole::Gate, - ) + .matrix(MoeExpertSelection::Routed { slot: first_slot }, MoeMatrixRole::Gate) .map_err(&map_source_error)? .role; // Preserve first Gate geometry BEFORE the first same-FD observation. @@ -210,14 +178,10 @@ impl ModelBinding { first, first_slot, MoeMatrixRole::Gate, - artifact - .tensor(first_role) - .map_err(|_| map_source_error(E::Geometry))?, + artifact.tensor(first_role).map_err(|_| map_source_error(E::Geometry))?, ) .map_err(&map_source_error)?; - let source = artifact - .begin_routed_moe_source(first.layer, expert) - .map_err(|_| map_source_error(E::Read))?; + let source = artifact.begin_routed_moe_source(first.layer, expert).map_err(|_| map_source_error(E::Read))?; let mut scope = MoeRoutedSourceScope { binding: self, members, diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_route.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_route.rs index 49b2b192..167945c2 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_route.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_moe_route.rs @@ -1,7 +1,5 @@ //! Retained native-profile router matrix; no full-matrix cache or host GEMV. -use super::{ - BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, TensorRole, -}; +use super::{BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, TensorRole}; const COLUMNS: usize = 2560; const ROWS: usize = 512; @@ -35,21 +33,14 @@ impl ModelBinding { if self.expert_count() != ROWS as u32 || self.expert_used_count() != 10 { return Err(E::Metadata); } - let role = TensorRole::Layer { - layer: u8::try_from(layer).map_err(|_| E::Range)?, - role: LayerRole::FfnGateInp, - }; + let role = TensorRole::Layer { layer: u8::try_from(layer).map_err(|_| E::Range)?, role: LayerRole::FfnGateInp }; let artifact = self.artifact.try_borrow().map_err(|_| E::Busy)?; if artifact.topology().embedding_length() != COLUMNS as u32 { return Err(E::Metadata); } let tensor = artifact.tensor(role).map_err(|_| E::Geometry)?; validate_descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length())?; - Ok(MoeRouteWeights { - binding: self.identity(), - layer, - role, - }) + Ok(MoeRouteWeights { binding: self.identity(), layer, role }) } pub(crate) fn moe_route_matrix_block( @@ -72,11 +63,7 @@ impl ModelBinding { bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; artifact .stream_rows(weights.role, first as u64, count as u64, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -87,9 +74,7 @@ impl ModelBinding { return Err(E::Read); } validate_bf16(&bytes)?; - Ok(MoeRouteWeightBlock { - bytes: bytes.into_boxed_slice(), - }) + Ok(MoeRouteWeightBlock { bytes: bytes.into_boxed_slice() }) } } @@ -112,12 +97,7 @@ fn validate_bf16(bytes: &[u8]) -> InputResult<()> { if !bytes.len().is_multiple_of(2) { return Err(E::Geometry); } - if bytes - .as_chunks::<2>() - .0 - .iter() - .any(|pair| u16::from_le_bytes(*pair) & 0x7f80 == 0x7f80) - { + if bytes.as_chunks::<2>().0.iter().any(|pair| u16::from_le_bytes(*pair) & 0x7f80 == 0x7f80) { return Err(E::NonFinite); } Ok(()) @@ -130,16 +110,9 @@ mod tests { fn router_matrix_descriptor_is_exact_retained_kind_shape_and_extent() { assert_eq!(validate_descriptor(30, &[2560, 512], 2621440), Ok(())); for kind in [0, 1, 14] { - assert_eq!( - validate_descriptor(kind, &[2560, 512], 2621440), - Err(E::UnsupportedKind) - ); + assert_eq!(validate_descriptor(kind, &[2560, 512], 2621440), Err(E::UnsupportedKind)); } - for (shape, bytes) in [ - ([512, 2560], 2621440), - ([2560, 511], 2621440), - ([2560, 512], 2621439), - ] { + for (shape, bytes) in [([512, 2560], 2621440), ([2560, 511], 2621440), ([2560, 512], 2621439)] { assert_eq!(validate_descriptor(30, &shape, bytes), Err(E::Geometry)); } } @@ -167,10 +140,7 @@ mod tests { let weights = MoeRouteWeights { binding: binding.clone(), layer: 3, - role: TensorRole::Layer { - layer: 3, - role: LayerRole::FfnGateInp, - }, + role: TensorRole::Layer { layer: 3, role: LayerRole::FfnGateInp }, }; assert!(weights.matches(&binding, 3)); assert!(!weights.matches(&binding, 4)); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs index c1c674b3..5c44ac87 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp.rs @@ -82,13 +82,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[2560, 2560], source_bytes: 13107200, source_sha256: "241d6e87ded317a61b1aeb3ca4e28c53f1caba09ad5be66092e91fe5e3e14751", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 2560, - columns: 2560, - offset: 0, - bytes: 6963200, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 2560, columns: 2560, offset: 0, bytes: 6963200 }), }, Descriptor { role: MtpRole::FcHidden, @@ -98,13 +92,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[2560, 2560], source_bytes: 13107200, source_sha256: "97c8e427ad0177e2c713ed24a397d815b523eda15ef453f1ae6463f6c70a8f96", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 2560, - columns: 2560, - offset: 6963200, - bytes: 6963200, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 2560, columns: 2560, offset: 6963200, bytes: 6963200 }), }, Descriptor { role: MtpRole::FinalNorm, @@ -114,13 +102,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240], source_bytes: 20480, source_sha256: "ce948a398e15aeaa403c424cda34e6eed296ab2570d591bb5ff3da642b255d64", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 10240, - offset: 13926400, - bytes: 40960, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 10240, offset: 13926400, bytes: 40960 }), }, Descriptor { role: MtpRole::FinalDown, @@ -130,13 +112,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[320, 10240], source_bytes: 6553600, source_sha256: "c633d2841fda463e82045e0b93fb8cb8d511ec0c9eda616020f01aca18d71947", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 320, - columns: 10240, - offset: 13967360, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 320, columns: 10240, offset: 13967360, bytes: 6553600 }), }, Descriptor { role: MtpRole::FinalUp, @@ -146,13 +122,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240, 320], source_bytes: 6553600, source_sha256: "6565285f0ba2923703252763cfc11d8a9bda40ab42e7548e12464b04dbdbec13", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 10240, - columns: 320, - offset: 20520960, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 10240, columns: 320, offset: 20520960, bytes: 6553600 }), }, Descriptor { role: MtpRole::AttentionInject, @@ -162,13 +132,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[4, 10240], source_bytes: 81920, source_sha256: "c8afff64e7f54412d02120097c4255033c55245e1c1eed84cc630d428ccb864c", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 4, - columns: 10240, - offset: 27074560, - bytes: 81920, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 4, columns: 10240, offset: 27074560, bytes: 81920 }), }, Descriptor { role: MtpRole::AttentionNorm, @@ -178,13 +142,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240], source_bytes: 20480, source_sha256: "1fb619aeaaf637ccd70f46f1f8f8116e6a46448cb43026b246de8ee8286ed809", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 10240, - offset: 27156480, - bytes: 40960, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 10240, offset: 27156480, bytes: 40960 }), }, Descriptor { role: MtpRole::AttentionDown, @@ -194,13 +152,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[320, 10240], source_bytes: 6553600, source_sha256: "e80ac8bf3e270e9d5a949ec7c913329dc8de017d69851334820fae7b8c86a7f5", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 320, - columns: 10240, - offset: 27197440, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 320, columns: 10240, offset: 27197440, bytes: 6553600 }), }, Descriptor { role: MtpRole::AttentionUp, @@ -210,13 +162,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240, 320], source_bytes: 6553600, source_sha256: "f80f1fd44e1183e7764ea496b11ff89ead9dd758f861d4e79a770bf54956b1a5", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 10240, - columns: 320, - offset: 33751040, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 10240, columns: 320, offset: 33751040, bytes: 6553600 }), }, Descriptor { role: MtpRole::ExpertDown, @@ -246,13 +192,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[512, 2560], source_bytes: 2621440, source_sha256: "f0d35fa41b360a08bc0c5b1e5766aa42df960291716ee189208b5d2599462c20", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 512, - columns: 2560, - offset: 40304640, - bytes: 2621440, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 512, columns: 2560, offset: 40304640, bytes: 2621440 }), }, Descriptor { role: MtpRole::SharedDown, @@ -262,13 +202,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[2560, 640], source_bytes: 3276800, source_sha256: "d2ced8c81367cc494599d1a8cdc279c3dd6579b628ded05acd7495e99cee01d8", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 2560, - columns: 640, - offset: 42926080, - bytes: 1740800, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 2560, columns: 640, offset: 42926080, bytes: 1740800 }), }, Descriptor { role: MtpRole::SharedGate, @@ -278,13 +212,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[640, 2560], source_bytes: 3276800, source_sha256: "f4a81109165853b3b64f36d809f98094b599763364070f5fa079200e1c386d4c", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 640, - columns: 2560, - offset: 44666880, - bytes: 1740800, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 640, columns: 2560, offset: 44666880, bytes: 1740800 }), }, Descriptor { role: MtpRole::SharedUp, @@ -294,13 +222,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[640, 2560], source_bytes: 3276800, source_sha256: "172586861eea53efbff10afc43ded5b6e49c83879e9efc01e089c652bbb0a156", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 640, - columns: 2560, - offset: 46407680, - bytes: 1740800, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 640, columns: 2560, offset: 46407680, bytes: 1740800 }), }, Descriptor { role: MtpRole::SharedScalar, @@ -310,13 +232,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[1, 2560], source_bytes: 5120, source_sha256: "acdd306d9996d356e4667a16ff63af6fef086fc7f570f1bc00bbe882a2a93f6e", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 1, - columns: 2560, - offset: 48148480, - bytes: 5120, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 1, columns: 2560, offset: 48148480, bytes: 5120 }), }, Descriptor { role: MtpRole::FfnInject, @@ -326,13 +242,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[4, 10240], source_bytes: 81920, source_sha256: "c5782dd92b479a1f8ef43d683fe9c917fd9e8fba81f23c1aae8817bfe4b476a6", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 4, - columns: 10240, - offset: 48153600, - bytes: 81920, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 4, columns: 10240, offset: 48153600, bytes: 81920 }), }, Descriptor { role: MtpRole::FfnNorm, @@ -342,13 +252,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240], source_bytes: 20480, source_sha256: "21a504876b5e7b788301557c68dfb757999430eba36c66ec8ab96a63604dbfd1", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 10240, - offset: 48235520, - bytes: 40960, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 10240, offset: 48235520, bytes: 40960 }), }, Descriptor { role: MtpRole::FfnDown, @@ -358,13 +262,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[320, 10240], source_bytes: 6553600, source_sha256: "b71240036dea954e034d5ae04e097bcd7ac51cb28a44e4c93d198af3447278a1", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 320, - columns: 10240, - offset: 48276480, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 320, columns: 10240, offset: 48276480, bytes: 6553600 }), }, Descriptor { role: MtpRole::FfnUp, @@ -374,13 +272,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240, 320], source_bytes: 6553600, source_sha256: "40756866bf2a5e82c28e407f717b6fa07614d593f78e79c7ceb2cd4ffe6dda94", - dense: Some(Dense { - kind: MtpKind::Bf16, - rows: 10240, - columns: 320, - offset: 54830080, - bytes: 6553600, - }), + dense: Some(Dense { kind: MtpKind::Bf16, rows: 10240, columns: 320, offset: 54830080, bytes: 6553600 }), }, Descriptor { role: MtpRole::IndexProjection, @@ -390,13 +282,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[640, 2560], source_bytes: 3276800, source_sha256: "2befafae6e944c1fc651fd73d4d527eb6f138a6c1679065b003128ee3150e859", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 640, - columns: 2560, - offset: 61383680, - bytes: 1740800, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 640, columns: 2560, offset: 61383680, bytes: 1740800 }), }, Descriptor { role: MtpRole::IndexKeyNorm, @@ -406,13 +292,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[128], source_bytes: 256, source_sha256: "2db621f6a08b4085756fc69d60a4a1bd1d7fbf5d406456d2477075842efaae54", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 128, - offset: 63124480, - bytes: 512, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 128, offset: 63124480, bytes: 512 }), }, Descriptor { role: MtpRole::IndexQueryNorm, @@ -422,13 +302,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[128], source_bytes: 256, source_sha256: "afaf59f68e251939970ffdeacad0667dffc657a522bea62cdc44a52816fc49d6", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 128, - offset: 63124992, - bytes: 512, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 128, offset: 63124992, bytes: 512 }), }, Descriptor { role: MtpRole::KeyNorm, @@ -438,13 +312,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[256], source_bytes: 512, source_sha256: "8f924b0357cf936e14fc34518205d000e1423aa60626827df81b0804fae8cdfd", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 256, - offset: 63125504, - bytes: 1024, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 256, offset: 63125504, bytes: 1024 }), }, Descriptor { role: MtpRole::KeyProjection, @@ -454,13 +322,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[512, 2560], source_bytes: 2621440, source_sha256: "1a295dc2d6e633e808aeb19e00c97856a1817bbfcc83f5b610e2bfcacfcb8c38", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 512, - columns: 2560, - offset: 63126528, - bytes: 1392640, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 512, columns: 2560, offset: 63126528, bytes: 1392640 }), }, Descriptor { role: MtpRole::AttentionOutput, @@ -470,13 +332,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[2560, 6144], source_bytes: 31457280, source_sha256: "9d2fcf0ac6ac19de87f638f710cfd1af6ad14141e75b7d3d5d29fbd06f374219", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 2560, - columns: 6144, - offset: 64519168, - bytes: 16711680, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 2560, columns: 6144, offset: 64519168, bytes: 16711680 }), }, Descriptor { role: MtpRole::QueryNorm, @@ -486,13 +342,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[256], source_bytes: 512, source_sha256: "57957aa1e7c5a3ac628bff0ec5522ad55a39b8c0b8bd2d324ae640e3771617ef", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 256, - offset: 81230848, - bytes: 1024, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 256, offset: 81230848, bytes: 1024 }), }, Descriptor { role: MtpRole::QueryProjection, @@ -502,13 +352,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[12288, 2560], source_bytes: 62914560, source_sha256: "5220aef3d288f40759f7356af9ef453e5ac0256a38749a9bb803a4e9db58150d", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 12288, - columns: 2560, - offset: 81231872, - bytes: 33423360, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 12288, columns: 2560, offset: 81231872, bytes: 33423360 }), }, Descriptor { role: MtpRole::ValueProjection, @@ -518,13 +362,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[512, 2560], source_bytes: 2621440, source_sha256: "39cb12f5424e965fa71fb81db0ee230c701b7b1e0b72c36641fde7e0e41bff41", - dense: Some(Dense { - kind: MtpKind::Q8_0, - rows: 512, - columns: 2560, - offset: 114655232, - bytes: 1392640, - }), + dense: Some(Dense { kind: MtpKind::Q8_0, rows: 512, columns: 2560, offset: 114655232, bytes: 1392640 }), }, Descriptor { role: MtpRole::EmbeddingNorm, @@ -534,13 +372,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[2560], source_bytes: 5120, source_sha256: "04c4a570850e06f2d8913da8220d54d4c7f87db6eb6d45480b938e8ba41d6a86", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 2560, - offset: 116047872, - bytes: 10240, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 2560, offset: 116047872, bytes: 10240 }), }, Descriptor { role: MtpRole::HiddenNorm, @@ -550,13 +382,7 @@ const DESCRIPTORS: [Descriptor; 31] = [ source_shape: &[10240], source_bytes: 20480, source_sha256: "b933b44559879449b1baf2af8385c5c237347307e3fd452394870cb53e6eab6d", - dense: Some(Dense { - kind: MtpKind::F32, - rows: 1, - columns: 10240, - offset: 116058112, - bytes: 40960, - }), + dense: Some(Dense { kind: MtpKind::F32, rows: 1, columns: 10240, offset: 116058112, bytes: 40960 }), }, ]; const DENSE_BYTES: u64 = 116_099_072; @@ -567,21 +393,9 @@ const MAX_ROWS: usize = 64; const MAX_READ: usize = 1_310_720; const INDEX_LIMIT: usize = 65_536; const FILE_PINS: [(&str, u64, &str); 3] = [ - ( - "dense.txt", - INDEX_BYTES, - "991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd", - ), - ( - "dense.bin", - DENSE_BYTES, - "c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a", - ), - ( - "experts.bin", - EXPERT_BYTES, - "09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f", - ), + ("dense.txt", INDEX_BYTES, "991456cf4eb266eb8a888c349e548d11bc640f5dbd9149439aa9786af0f732fd"), + ("dense.bin", DENSE_BYTES, "c724dc0b0822ada5d2977bf5bde821605feabaa64ea2e0045b67ca656329070a"), + ("experts.bin", EXPERT_BYTES, "09398406be61f1f54c93861f449e48b8df0bfccbc9ec9b2b7636775a6ea9244f"), ]; /// Validation-only receipt. This cannot construct a verified weights owner. @@ -620,16 +434,16 @@ mod tests; #[path = "qwen4exp_mtp/pack_identity_fn.rs"] mod pack_identity_fn; #[allow(unused_imports)] -pub(super) use pack_identity_fn::pack_identity; -#[allow(unused_imports)] use pack_identity_fn::descriptor; #[allow(unused_imports)] +pub(super) use pack_identity_fn::pack_identity; +#[allow(unused_imports)] pub(crate) use pack_identity_fn::pinned_dense_bytes; #[allow(unused_imports)] -pub(crate) use pack_identity_fn::rt_dense_roles; -#[allow(unused_imports)] pub(crate) use pack_identity_fn::rt_dense_name; #[allow(unused_imports)] +pub(crate) use pack_identity_fn::rt_dense_roles; +#[allow(unused_imports)] pub(crate) use pack_identity_fn::rt_dense_shape; #[path = "qwen4exp_mtp/impl_mtpweights.rs"] mod impl_mtpweights; @@ -638,14 +452,14 @@ use impl_mtpweights::validate_identity; #[path = "qwen4exp_mtp/read_expert_rows_fn.rs"] mod read_expert_rows_fn; #[allow(unused_imports)] +use read_expert_rows_fn::allocate; +#[allow(unused_imports)] +use read_expert_rows_fn::interleave_q2; +#[allow(unused_imports)] +use read_expert_rows_fn::read_exact_range; +#[allow(unused_imports)] use read_expert_rows_fn::read_expert_rows; #[allow(unused_imports)] use read_expert_rows_fn::row_range; #[allow(unused_imports)] -use read_expert_rows_fn::allocate; -#[allow(unused_imports)] -use read_expert_rows_fn::read_exact_range; -#[allow(unused_imports)] -use read_expert_rows_fn::interleave_q2; -#[allow(unused_imports)] use read_expert_rows_fn::validate_numeric; diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs index e203c33e..8abf9a97 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/backing.rs @@ -21,11 +21,7 @@ fn inode(m: &fs::Metadata) -> Inode { (m.dev(), m.ino()) } fn regular(path: &Path, bytes: u64) -> InputResult { - let file = OpenOptions::new() - .read(true) - .custom_flags(FLAGS) - .open(path) - .map_err(|_| InputBindingError::Read)?; + let file = OpenOptions::new().read(true).custom_flags(FLAGS).open(path).map_err(|_| InputBindingError::Read)?; let m = file.metadata().map_err(|_| InputBindingError::Read)?; if !m.is_file() || m.len() != bytes { return Err(InputBindingError::Metadata); @@ -56,8 +52,7 @@ impl OwnedCopy { let directory = root.join(format!(".leleka-mtp-{}-{serial}", std::process::id())); match DirBuilder::new().mode(0o700).create(&directory) { Ok(()) => { - let m = fs::symlink_metadata(&directory) - .map_err(|_| InputBindingError::Read)?; + let m = fs::symlink_metadata(&directory).map_err(|_| InputBindingError::Read)?; let own = Self { path: directory.join("weights"), directory, @@ -91,12 +86,10 @@ impl OwnedCopy { Ok(f) } fn owns_directory(&self) -> bool { - fs::symlink_metadata(&self.directory) - .is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) + fs::symlink_metadata(&self.directory).is_ok_and(|m| m.is_dir() && inode(&m) == self.directory_inode) } fn owns_file(&self) -> bool { - fs::symlink_metadata(&self.path) - .is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) + fs::symlink_metadata(&self.path).is_ok_and(|m| m.is_file() && Some(inode(&m)) == self.file_inode) } fn detach(&mut self) -> InputResult<()> { if !self.owns_directory() || !self.owns_file() { @@ -117,32 +110,18 @@ impl Drop for OwnedCopy { } } } -fn copy_exact( - source: &mut R, - destination: &mut W, - bytes: u64, -) -> InputResult<()> { +fn copy_exact(source: &mut R, destination: &mut W, bytes: u64) -> InputResult<()> { let mut buffer = Vec::new(); - buffer - .try_reserve_exact(SCRATCH) - .map_err(|_| InputBindingError::Allocation)?; + buffer.try_reserve_exact(SCRATCH).map_err(|_| InputBindingError::Allocation)?; buffer.resize(SCRATCH, 0); let mut remaining = bytes; while remaining != 0 { let n = remaining.min(SCRATCH as u64) as usize; - source - .read_exact(&mut buffer[..n]) - .map_err(|_| InputBindingError::Read)?; - destination - .write_all(&buffer[..n]) - .map_err(|_| InputBindingError::Read)?; + source.read_exact(&mut buffer[..n]).map_err(|_| InputBindingError::Read)?; + destination.write_all(&buffer[..n]).map_err(|_| InputBindingError::Read)?; remaining -= n as u64; } - if source - .read(&mut buffer[..1]) - .map_err(|_| InputBindingError::Read)? - != 0 - { + if source.read(&mut buffer[..1]).map_err(|_| InputBindingError::Read)? != 0 { return Err(InputBindingError::Range); } Ok(()) @@ -153,9 +132,7 @@ fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult let mut writer = own.writer(uid)?; copy_exact(source, &mut writer, bytes)?; writer.sync_all().map_err(|_| InputBindingError::Read)?; - writer - .set_permissions(Permissions::from_mode(0o400)) - .map_err(|_| InputBindingError::Read)?; + writer.set_permissions(Permissions::from_mode(0o400)).map_err(|_| InputBindingError::Read)?; let reader = regular(&own.path, bytes)?; let m = reader.metadata().map_err(|_| InputBindingError::Read)?; if Some(inode(&m)) != own.file_inode || m.mode() & 0o7777 != 0o400 || m.nlink() != 1 { @@ -163,21 +140,12 @@ fn freeze(source: &mut File, owner_root: &Path, bytes: u64) -> InputResult } drop(writer); own.detach()?; - if reader - .metadata() - .map_err(|_| InputBindingError::Read)? - .nlink() - != 0 - { + if reader.metadata().map_err(|_| InputBindingError::Read)?.nlink() != 0 { return Err(InputBindingError::Metadata); } Ok(reader) } -pub(super) fn freeze_file( - source: &Path, - owner_root: &Path, - pin: (&str, u64, &str), -) -> InputResult { +pub(super) fn freeze_file(source: &Path, owner_root: &Path, pin: (&str, u64, &str)) -> InputResult { let directory = fs::symlink_metadata(source).map_err(|_| InputBindingError::Read)?; if !directory.is_dir() || directory.file_type().is_symlink() { return Err(InputBindingError::Metadata); @@ -190,26 +158,18 @@ pub(super) fn freeze_file( fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> { use std::io::{Seek, SeekFrom}; let mut buffer = Vec::new(); - buffer - .try_reserve_exact(SCRATCH) - .map_err(|_| InputBindingError::Allocation)?; + buffer.try_reserve_exact(SCRATCH).map_err(|_| InputBindingError::Allocation)?; buffer.resize(SCRATCH, 0); - file.seek(SeekFrom::Start(0)) - .map_err(|_| InputBindingError::Read)?; + file.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?; let mut hasher = Sha256::new(); let mut remaining = bytes; while remaining != 0 { let n = remaining.min(SCRATCH as u64) as usize; - file.read_exact(&mut buffer[..n]) - .map_err(|_| InputBindingError::Read)?; + file.read_exact(&mut buffer[..n]).map_err(|_| InputBindingError::Read)?; hasher.update(&buffer[..n]); remaining -= n as u64; } - if file - .read(&mut buffer[..1]) - .map_err(|_| InputBindingError::Read)? - != 0 - { + if file.read(&mut buffer[..1]).map_err(|_| InputBindingError::Read)? != 0 { return Err(InputBindingError::Range); } let actual: [u8; 32] = hasher.finalize().into(); @@ -218,14 +178,12 @@ fn verify(file: &mut File, bytes: u64, pin: &str) -> InputResult<()> { return Err(InputBindingError::Metadata); } for (i, byte) in expected.iter_mut().enumerate() { - *byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16) - .map_err(|_| InputBindingError::Metadata)?; + *byte = u8::from_str_radix(&pin[i * 2..i * 2 + 2], 16).map_err(|_| InputBindingError::Metadata)?; } if actual != expected { return Err(InputBindingError::Metadata); } - file.seek(SeekFrom::Start(0)) - .map_err(|_| InputBindingError::Read)?; + file.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?; Ok(()) } @@ -236,15 +194,11 @@ mod tests { struct Fixture(PathBuf); impl Fixture { fn new() -> Self { - let parent = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra169-mtp-binder"); + let parent = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/stra169-mtp-binder"); fs::create_dir_all(&parent).unwrap(); loop { - let root = parent.join(format!( - "tiny-{}-{}", - std::process::id(), - SERIAL.fetch_add(1, Ordering::Relaxed) - )); + let root = + parent.join(format!("tiny-{}-{}", std::process::id(), SERIAL.fetch_add(1, Ordering::Relaxed))); match DirBuilder::new().mode(0o700).create(&root) { Ok(()) => return Self(root), Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, @@ -274,16 +228,8 @@ mod tests { assert!((&frozen).write_all(b"replace").is_err()); fs::write(f.0.join("source"), b"new").unwrap(); assert_eq!(read_exact_range(&frozen, 0, 3).unwrap(), b"abc"); - verify( - &mut frozen, - 3, - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", - ) - .unwrap(); - assert_eq!( - verify(&mut frozen, 3, &"0".repeat(64)), - Err(InputBindingError::Metadata) - ); + verify(&mut frozen, 3, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad").unwrap(); + assert_eq!(verify(&mut frozen, 3, &"0".repeat(64)), Err(InputBindingError::Metadata)); assert_eq!(fs::read_dir(&f.0).unwrap().count(), 1); } #[test] @@ -340,12 +286,7 @@ mod tests { // An unverified synthetic plane file tests layout only; it never // becomes MtpWeights or a serving capability. let f = Fixture::new(); - let file = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .open(f.0.join("planes")) - .unwrap(); + let file = OpenOptions::new().read(true).write(true).create_new(true).open(f.0.join("planes")).unwrap(); file.set_len(2 * EXPERT_BLOB).unwrap(); use std::os::unix::fs::FileExt; let cases = [ @@ -358,10 +299,8 @@ mod tests { for expert in 0..2u32 { let base = u64::from(expert) * EXPERT_BLOB; for &(_, _, code, scale, blocks, value) in &cases { - file.write_all_at(&vec![value + expert as u8; blocks * 16], base + code) - .unwrap(); - file.write_all_at(&[0, 0x3c].repeat(blocks), base + scale) - .unwrap(); + file.write_all_at(&vec![value + expert as u8; blocks * 16], base + code).unwrap(); + file.write_all_at(&[0, 0x3c].repeat(blocks), base + scale).unwrap(); } } for expert in 0..2 { diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/impl_mtpweights.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/impl_mtpweights.rs index 26a6e305..6a8630b5 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/impl_mtpweights.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/impl_mtpweights.rs @@ -6,11 +6,7 @@ use super::*; impl MtpWeights { /// Operator-only fixed profile. The copy owns an unnamed read-only inode for /// its full lifetime. This trusted-owner contract is not an OS/root seal. - pub(crate) fn load_pinned( - binding: &ModelBinding, - source: &Path, - owner_root: &Path, - ) -> InputResult { + pub(crate) fn load_pinned(binding: &ModelBinding, source: &Path, owner_root: &Path) -> InputResult { #[cfg(any(target_os = "linux", target_os = "windows"))] { let mut index = backing::freeze_file(source, owner_root, FILE_PINS[0])?; @@ -21,15 +17,8 @@ impl MtpWeights { let experts = backing::freeze_file(source, owner_root, FILE_PINS[2])?; // Keep the exact verified index FD, not a reopened path. use std::io::{Seek, SeekFrom}; - index - .seek(SeekFrom::Start(0)) - .map_err(|_| InputBindingError::Read)?; - Ok(Self { - identity: binding.identity(), - _index: index, - dense, - experts, - }) + index.seek(SeekFrom::Start(0)).map_err(|_| InputBindingError::Read)?; + Ok(Self { identity: binding.identity(), _index: index, dense, experts }) } #[cfg(not(any(target_os = "linux", target_os = "windows")))] { @@ -42,18 +31,8 @@ impl MtpWeights { } pub(crate) fn validate_sources(&self, binding: &ModelBinding) -> InputResult<()> { self.validate_binding(binding)?; - if self - .dense - .metadata() - .map_err(|_| InputBindingError::Read)? - .len() - != DENSE_BYTES - || self - .experts - .metadata() - .map_err(|_| InputBindingError::Read)? - .len() - != EXPERT_BYTES + if self.dense.metadata().map_err(|_| InputBindingError::Read)?.len() != DENSE_BYTES + || self.experts.metadata().map_err(|_| InputBindingError::Read)?.len() != EXPERT_BYTES { return Err(InputBindingError::Read); } @@ -62,41 +41,25 @@ impl MtpWeights { pub(crate) fn dense_roles(&self, binding: &ModelBinding) -> InputResult> { self.validate_sources(binding)?; let mut roles = Vec::new(); - roles - .try_reserve_exact(29) - .map_err(|_| InputBindingError::Allocation)?; + roles.try_reserve_exact(29).map_err(|_| InputBindingError::Allocation)?; for d in DESCRIPTORS { if d.dense.is_some() - && !matches!( - d.role, - MtpRole::IndexProjection | MtpRole::IndexKeyNorm | MtpRole::IndexQueryNorm - ) + && !matches!(d.role, MtpRole::IndexProjection | MtpRole::IndexKeyNorm | MtpRole::IndexQueryNorm) { roles.push(d.role); } } Ok(roles) } - pub(crate) fn dense_complete( - &self, - binding: &ModelBinding, - role: MtpRole, - ) -> InputResult { + pub(crate) fn dense_complete(&self, binding: &ModelBinding, role: MtpRole) -> InputResult { self.validate_sources(binding)?; - let d = descriptor(role) - .dense - .ok_or(InputBindingError::UnsupportedKind)?; + let d = descriptor(role).dense.ok_or(InputBindingError::UnsupportedKind)?; let size = usize::try_from(d.bytes).map_err(|_| InputBindingError::Range)?; let mut data = Vec::new(); - data.try_reserve_exact(size) - .map_err(|_| InputBindingError::Allocation)?; + data.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?; for first in (0..d.rows).step_by(MAX_ROWS) { let rows = self.dense_rows(binding, role, first, (d.rows - first).min(MAX_ROWS))?; - if data - .len() - .checked_add(rows.bytes().len()) - .is_none_or(|v| v > size) - { + if data.len().checked_add(rows.bytes().len()).is_none_or(|v| v > size) { return Err(InputBindingError::Range); } data.extend_from_slice(rows.bytes()); @@ -105,20 +68,14 @@ impl MtpWeights { return Err(InputBindingError::Read); } self.validate_sources(binding)?; - Ok(MtpRows { - kind: d.kind, - rows: d.rows, - columns: d.columns, - bytes: data, - }) + Ok(MtpRows { kind: d.kind, rows: d.rows, columns: d.columns, bytes: data }) } #[cfg(any(target_os = "linux", target_os = "windows"))] pub(crate) fn expert_bank(&self, binding: &ModelBinding) -> InputResult> { self.validate_sources(binding)?; let size = usize::try_from(EXPERT_BYTES).map_err(|_| InputBindingError::Range)?; let mut data = Vec::new(); - data.try_reserve_exact(size) - .map_err(|_| InputBindingError::Allocation)?; + data.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?; data.resize(size, 0); // Immutable same-FD owner was fully SHA-verified before MtpWeights. // Bounded reads, no pathname reopen or weight representation changes. @@ -126,9 +83,7 @@ impl MtpWeights { { use std::os::unix::fs::FileExt; for (i, chunk) in data.chunks_mut(8 * 1024 * 1024).enumerate() { - self.experts - .read_exact_at(chunk, (i * 8 * 1024 * 1024) as u64) - .map_err(|_| InputBindingError::Read)?; + self.experts.read_exact_at(chunk, (i * 8 * 1024 * 1024) as u64).map_err(|_| InputBindingError::Read)?; } } #[cfg(target_os = "windows")] @@ -141,12 +96,7 @@ impl MtpWeights { for blob in data.as_chunks::<{ EXPERT_BLOB as usize }>().0 { // These are all original used weight scales; the Q8 activation // half header (which may legitimately overflow) is not this bank. - if blob[1_228_800..] - .as_chunks::<2>() - .0 - .iter() - .any(|v| u16::from_le_bytes(*v) & 0x7c00 == 0x7c00) - { + if blob[1_228_800..].as_chunks::<2>().0.iter().any(|v| u16::from_le_bytes(*v) & 0x7c00 == 0x7c00) { return Err(InputBindingError::NonFinite); } } @@ -157,15 +107,9 @@ impl MtpWeights { pub(crate) fn expert_bank(&self, _binding: &ModelBinding) -> InputResult> { Err(InputBindingError::UnsupportedKind) } - pub(crate) fn dense_shape( - &self, - binding: &ModelBinding, - role: MtpRole, - ) -> InputResult<(MtpKind, usize, usize)> { + pub(crate) fn dense_shape(&self, binding: &ModelBinding, role: MtpRole) -> InputResult<(MtpKind, usize, usize)> { self.validate_binding(binding)?; - let d = descriptor(role) - .dense - .ok_or(InputBindingError::UnsupportedKind)?; + let d = descriptor(role).dense.ok_or(InputBindingError::UnsupportedKind)?; Ok((d.kind, d.rows, d.columns)) } pub(crate) fn dense_rows( @@ -176,9 +120,7 @@ impl MtpWeights { count: usize, ) -> InputResult { self.validate_binding(binding)?; - let d = descriptor(role) - .dense - .ok_or(InputBindingError::UnsupportedKind)?; + let d = descriptor(role).dense.ok_or(InputBindingError::UnsupportedKind)?; let row = match d.kind { MtpKind::Q8_0 => d.columns.checked_div(32).and_then(|n| n.checked_mul(34)), MtpKind::Bf16 => d.columns.checked_mul(2), @@ -187,18 +129,10 @@ impl MtpWeights { } .ok_or(InputBindingError::Range)?; let (relative, bytes) = row_range(d.rows, row, first, count)?; - let offset = d - .offset - .checked_add(relative) - .ok_or(InputBindingError::Range)?; + let offset = d.offset.checked_add(relative).ok_or(InputBindingError::Range)?; let data = read_exact_range(&self.dense, offset, bytes)?; validate_numeric(d.kind, &data)?; - Ok(MtpRows { - kind: d.kind, - rows: count, - columns: d.columns, - bytes: data, - }) + Ok(MtpRows { kind: d.kind, rows: count, columns: d.columns, bytes: data }) } pub(crate) fn expert_rows( &self, @@ -213,9 +147,5 @@ impl MtpWeights { } } pub(super) fn validate_identity(expected: &BindingIdentity, actual: &BindingIdentity) -> InputResult<()> { - if expected.matches(actual) { - Ok(()) - } else { - Err(InputBindingError::Metadata) - } + if expected.matches(actual) { Ok(()) } else { Err(InputBindingError::Metadata) } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/pack_identity_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/pack_identity_fn.rs index fed51ad7..24660562 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/pack_identity_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/pack_identity_fn.rs @@ -3,16 +3,12 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn pack_identity() -> [&'static str; 3] { FILE_PINS.map(|(_, _, digest)| digest) } pub(super) fn descriptor(role: MtpRole) -> &'static Descriptor { - DESCRIPTORS - .iter() - .find(|d| d.role == role) - .expect("closed MTP role") + DESCRIPTORS.iter().find(|d| d.role == role).expect("closed MTP role") } /// RT-directory contract for a directory read by the Original-literal loader @@ -29,26 +25,16 @@ pub(crate) fn rt_dense_roles() -> Vec { .iter() .filter(|d| { d.dense.is_some() - && !matches!( - d.role, - MtpRole::IndexProjection | MtpRole::IndexKeyNorm | MtpRole::IndexQueryNorm - ) + && !matches!(d.role, MtpRole::IndexProjection | MtpRole::IndexKeyNorm | MtpRole::IndexQueryNorm) }) .map(|d| d.role) .collect() } pub(crate) fn rt_dense_name(role: MtpRole) -> Option<&'static str> { - DESCRIPTORS - .iter() - .find(|d| d.role == role && d.dense.is_some()) - .map(|d| d.name) + DESCRIPTORS.iter().find(|d| d.role == role && d.dense.is_some()).map(|d| d.name) } pub(crate) fn rt_dense_shape(role: MtpRole) -> Option<(MtpKind, usize, usize)> { - DESCRIPTORS - .iter() - .find(|d| d.role == role) - .and_then(|d| d.dense) - .map(|d| (d.kind, d.rows, d.columns)) + DESCRIPTORS.iter().find(|d| d.role == role).and_then(|d| d.dense).map(|d| (d.kind, d.rows, d.columns)) } impl MtpIndex { pub(super) fn inspect(bytes: &[u8]) -> InputResult { @@ -77,13 +63,8 @@ impl MtpIndex { if fields.next().is_some() { return Err(InputBindingError::Metadata); } - let index = DESCRIPTORS - .iter() - .position(|d| d.name == name) - .ok_or(InputBindingError::Metadata)?; - let dense = DESCRIPTORS[index] - .dense - .ok_or(InputBindingError::Metadata)?; + let index = DESCRIPTORS.iter().position(|d| d.name == name).ok_or(InputBindingError::Metadata)?; + let dense = DESCRIPTORS[index].dense.ok_or(InputBindingError::Metadata)?; let expected_kind = match dense.kind { MtpKind::Q8_0 => "q8_0", MtpKind::Bf16 => "bf16", @@ -109,10 +90,7 @@ impl MtpIndex { seen[index] = true; } if count != 29 - || DESCRIPTORS - .iter() - .enumerate() - .any(|(i, d)| d.dense.is_some() != seen[i]) + || DESCRIPTORS.iter().enumerate().any(|(i, d)| d.dense.is_some() != seen[i]) || spans.iter().map(|s| s.1).max() != Some(DENSE_BYTES) { return Err(InputBindingError::Metadata); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/read_expert_rows_fn.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/read_expert_rows_fn.rs index 43540bcd..4d07871b 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/read_expert_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/read_expert_rows_fn.rs @@ -20,9 +20,7 @@ pub(super) fn read_expert_rows( let blocks = columns / 64; let (_, bytes) = row_range(rows, blocks * 18, first, count)?; let mut out = allocate(bytes)?; - let base = u64::from(expert) - .checked_mul(EXPERT_BLOB) - .ok_or(InputBindingError::Range)?; + let base = u64::from(expert).checked_mul(EXPERT_BLOB).ok_or(InputBindingError::Range)?; for r in 0..count { let row = first + r; let (packed_row, code_base, scale_base) = match matrix { @@ -30,9 +28,7 @@ pub(super) fn read_expert_rows( MtpExpertMatrix::Up => (row * 2 + 1, 0, 1_228_800), MtpExpertMatrix::Down => (row, 819_200, 1_331_200), }; - let block_start = packed_row - .checked_mul(blocks) - .ok_or(InputBindingError::Range)?; + let block_start = packed_row.checked_mul(blocks).ok_or(InputBindingError::Range)?; let code_offset = base .checked_add(code_base) .and_then(|x| x.checked_add((block_start * 16) as u64)) @@ -43,57 +39,33 @@ pub(super) fn read_expert_rows( .ok_or(InputBindingError::Range)?; let codes = read_exact_range(experts, code_offset, blocks * 16)?; let scales = read_exact_range(experts, scale_offset, blocks * 2)?; - interleave_q2( - &codes, - &scales, - &mut out[r * blocks * 18..(r + 1) * blocks * 18], - )?; + interleave_q2(&codes, &scales, &mut out[r * blocks * 18..(r + 1) * blocks * 18])?; } - Ok(MtpRows { - kind: MtpKind::Q2_0, - rows: count, - columns, - bytes: out, - }) + Ok(MtpRows { kind: MtpKind::Q2_0, rows: count, columns, bytes: out }) } -pub(super) fn row_range( - rows: usize, - row_bytes: usize, - first: usize, - count: usize, -) -> InputResult<(u64, usize)> { +pub(super) fn row_range(rows: usize, row_bytes: usize, first: usize, count: usize) -> InputResult<(u64, usize)> { if count == 0 || count > MAX_ROWS || first.checked_add(count).is_none_or(|end| end > rows) { return Err(InputBindingError::Range); } - let start = first - .checked_mul(row_bytes) - .ok_or(InputBindingError::Range)?; - let bytes = count - .checked_mul(row_bytes) - .ok_or(InputBindingError::Range)?; + let start = first.checked_mul(row_bytes).ok_or(InputBindingError::Range)?; + let bytes = count.checked_mul(row_bytes).ok_or(InputBindingError::Range)?; if bytes > MAX_READ { return Err(InputBindingError::Range); } - Ok(( - u64::try_from(start).map_err(|_| InputBindingError::Range)?, - bytes, - )) + Ok((u64::try_from(start).map_err(|_| InputBindingError::Range)?, bytes)) } pub(super) fn allocate(bytes: usize) -> InputResult> { if bytes > MAX_READ { return Err(InputBindingError::Range); } let mut data = Vec::new(); - data.try_reserve_exact(bytes) - .map_err(|_| InputBindingError::Allocation)?; + data.try_reserve_exact(bytes).map_err(|_| InputBindingError::Allocation)?; data.resize(bytes, 0); Ok(data) } pub(super) fn read_exact_range(file: &File, offset: u64, count: usize) -> InputResult> { - let end = offset - .checked_add(count as u64) - .ok_or(InputBindingError::Range)?; + let end = offset.checked_add(count as u64).ok_or(InputBindingError::Range)?; if end > file.metadata().map_err(|_| InputBindingError::Read)?.len() { return Err(InputBindingError::Range); } @@ -101,8 +73,7 @@ pub(super) fn read_exact_range(file: &File, offset: u64, count: usize) -> InputR #[cfg(unix)] { use std::os::unix::fs::FileExt; - file.read_exact_at(&mut data, offset) - .map_err(|_| InputBindingError::Read)?; + file.read_exact_at(&mut data, offset).map_err(|_| InputBindingError::Read)?; } #[cfg(windows)] backing::read_exact_at(file, &mut data, offset).map_err(|_| InputBindingError::Read)?; @@ -114,10 +85,7 @@ pub(super) fn read_exact_range(file: &File, offset: u64, count: usize) -> InputR Ok(data) } pub(super) fn interleave_q2(codes: &[u8], scales: &[u8], out: &mut [u8]) -> InputResult<()> { - if !codes.len().is_multiple_of(16) - || scales.len() != codes.len() / 8 - || out.len() != codes.len() / 16 * 18 - { + if !codes.len().is_multiple_of(16) || scales.len() != codes.len() / 8 || out.len() != codes.len() / 16 * 18 { return Err(InputBindingError::Range); } for (i, block) in out.as_chunks_mut::<18>().0.iter_mut().enumerate() { @@ -134,40 +102,20 @@ pub(super) fn validate_numeric(kind: MtpKind, bytes: &[u8]) -> InputResult<()> { let finite = match kind { MtpKind::Bf16 => { bytes.len().is_multiple_of(2) - && bytes - .as_chunks::<2>() - .0 - .iter() - .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7f80 != 0x7f80) + && bytes.as_chunks::<2>().0.iter().all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7f80 != 0x7f80) } MtpKind::F32 => { bytes.len().is_multiple_of(4) - && bytes - .as_chunks::<4>() - .0 - .iter() - .all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()) + && bytes.as_chunks::<4>().0.iter().all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()) } MtpKind::Q8_0 => { bytes.len().is_multiple_of(34) - && bytes - .as_chunks::<34>() - .0 - .iter() - .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) + && bytes.as_chunks::<34>().0.iter().all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) } MtpKind::Q2_0 => { bytes.len().is_multiple_of(18) - && bytes - .as_chunks::<18>() - .0 - .iter() - .all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) + && bytes.as_chunks::<18>().0.iter().all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) } }; - if finite { - Ok(()) - } else { - Err(InputBindingError::NonFinite) - } + if finite { Ok(()) } else { Err(InputBindingError::NonFinite) } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/tests.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/tests.rs index 978a4219..f4c8531e 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/tests.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_mtp/tests.rs @@ -27,10 +27,7 @@ fn index() -> String { #[test] fn exact_closed_receipts_and_runtime_index() { assert_eq!(DESCRIPTORS.len(), 31); - assert_eq!( - DESCRIPTORS.iter().map(|d| d.source_bytes).sum::(), - 5_214_301_696 - ); + assert_eq!(DESCRIPTORS.iter().map(|d| d.source_bytes).sum::(), 5_214_301_696); for d in DESCRIPTORS { assert_eq!(d.source_shape.iter().product::() * 2, d.source_bytes); assert_eq!(d.source_sha256.len(), 64); @@ -43,8 +40,8 @@ fn exact_closed_receipts_and_runtime_index() { assert_eq!( <[u8; 32]>::from(Sha256::digest(text.as_bytes())), [ - 153, 20, 86, 207, 78, 178, 102, 235, 138, 136, 140, 52, 158, 84, 141, 17, 188, 100, - 15, 93, 189, 145, 73, 67, 154, 169, 120, 106, 240, 247, 50, 253 + 153, 20, 86, 207, 78, 178, 102, 235, 138, 136, 140, 52, 158, 84, 141, 17, 188, 100, 15, 93, 189, 145, 73, + 67, 154, 169, 120, 106, 240, 247, 50, 253 ] ); } @@ -65,10 +62,17 @@ fn rt_contract_lists_the_consumed_dense_roles_by_name() { assert_eq!(rt_dense_shape(MtpRole::ExpertGateUp), None); assert_eq!(rt_dense_name(MtpRole::ExpertDown), None); // every nine-name requirement of the Original loader is a q8_0 role here - for name in ["fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", - "self_attn.k_proj.weight", "self_attn.v_proj.weight", "self_attn.o_proj.weight", - "mlp.shared_expert.gate_proj.weight", "mlp.shared_expert.up_proj.weight", - "mlp.shared_expert.down_proj.weight"] { + for name in [ + "fc_embedding.weight", + "fc_hidden.weight", + "self_attn.q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "self_attn.o_proj.weight", + "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", + "mlp.shared_expert.down_proj.weight", + ] { let role = DESCRIPTORS.iter().find(|d| d.name == name).unwrap().role; assert_eq!(rt_dense_shape(role).unwrap().0, MtpKind::Q8_0, "{name}"); } @@ -106,10 +110,7 @@ fn bounded_rows_and_lossless_q2_planes_preserve_signed_zero_and_codes() { assert_eq!(&out[2..18], &codes[..16]); assert_eq!(&out[18..20], &[0, 0x80]); assert_eq!(&out[20..], &codes[16..]); - assert_eq!( - interleave_q2(&codes, &[0, 0x7c, 0, 0], &mut out), - Err(InputBindingError::NonFinite) - ); + assert_eq!(interleave_q2(&codes, &[0, 0x7c, 0, 0], &mut out), Err(InputBindingError::NonFinite)); assert!(interleave_q2(&codes, &[], &mut out).is_err()); } #[test] @@ -128,24 +129,15 @@ fn nonfinite_weights_refuse_and_zero_signs_remain_exact() { v }), ] { - assert_eq!( - validate_numeric(kind, &bytes), - Err(InputBindingError::NonFinite) - ); + assert_eq!(validate_numeric(kind, &bytes), Err(InputBindingError::NonFinite)); } assert_eq!(validate_numeric(MtpKind::Bf16, &[0, 0x80]), Ok(())); - assert_eq!( - validate_numeric(MtpKind::F32, &(-0.0f32).to_le_bytes()), - Ok(()) - ); + assert_eq!(validate_numeric(MtpKind::F32, &(-0.0f32).to_le_bytes()), Ok(())); } #[test] fn identity_is_opaque_and_not_recreated_from_metadata() { let first = BindingIdentity::test_identity(); let second = BindingIdentity::test_identity(); assert_eq!(validate_identity(&first, &first.clone()), Ok(())); - assert_eq!( - validate_identity(&first, &second), - Err(InputBindingError::Metadata) - ); + assert_eq!(validate_identity(&first, &second), Err(InputBindingError::Metadata)); } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_native_head.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_native_head.rs index 72f1e18d..e62b0d6e 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_native_head.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_native_head.rs @@ -1,28 +1,84 @@ //! Whole compressed head/embedding bytes from the actual retained bound artifact. //! Child of qwen4exp_input, not an association between arbitrary host/device bytes. -use super::{BindingIdentity,GlobalRole,InputBindingError,InputResult,ModelBinding,TensorRole}; -pub(crate) enum NativeOutputRole{Head,Embedding} -pub(crate) struct NativeOutputBlock{binding:BindingIdentity,kind:u32,n:usize,vocab:usize,bytes:Box<[u8]>} +use super::{BindingIdentity, GlobalRole, InputBindingError, InputResult, ModelBinding, TensorRole}; +pub(crate) enum NativeOutputRole { + Head, + Embedding, +} +pub(crate) struct NativeOutputBlock { + binding: BindingIdentity, + kind: u32, + n: usize, + vocab: usize, + bytes: Box<[u8]>, +} impl NativeOutputBlock { - pub(crate) fn matches(&self,b:&BindingIdentity)->bool{self.binding.matches(b)} - pub(crate) fn kind(&self)->u32{self.kind}pub(crate) fn columns(&self)->usize{self.n}pub(crate) fn vocabulary(&self)->usize{self.vocab}pub(crate) fn bytes(&self)->&[u8]{&self.bytes} + pub(crate) fn matches(&self, b: &BindingIdentity) -> bool { + self.binding.matches(b) + } + pub(crate) fn kind(&self) -> u32 { + self.kind + } + pub(crate) fn columns(&self) -> usize { + self.n + } + pub(crate) fn vocabulary(&self) -> usize { + self.vocab + } + pub(crate) fn bytes(&self) -> &[u8] { + &self.bytes + } } -impl ModelBinding{ - pub(crate) fn native_output_block(&self,role:NativeOutputRole)->InputResult{ - let key=TensorRole::Global(match role{NativeOutputRole::Head=>GlobalRole::Output,NativeOutputRole::Embedding=>GlobalRole::TokenEmbedding}); - let mut artifact=self.artifact.try_borrow_mut().map_err(|_|InputBindingError::Busy)?; - let tensor=artifact.tensor(key).map_err(|_|InputBindingError::Geometry)?; - let shape=tensor.dimensions();if shape.len()!=2||shape[0]==0||shape[1]==0||shape[0]>i32::MAX as u64||shape[1]>i32::MAX as u64||shape[0]%256!=0{return Err(InputBindingError::Geometry);} - let n=shape[0] as usize;let vocab=shape[1] as usize;let kind=tensor.kind(); - let supported=match role{NativeOutputRole::Head=>leleka_cuda_driver::native_head_supported(kind),NativeOutputRole::Embedding=>leleka_cuda_driver::native_embed_supported(kind)}; - if !supported{return Err(InputBindingError::UnsupportedKind);} - let row=leleka_cuda_driver::native_head_row_bytes(kind,n).map_err(|_|InputBindingError::Geometry)?;let size=row.checked_mul(vocab).ok_or(InputBindingError::Geometry)?; - if tensor.byte_length()!=size as u64{return Err(InputBindingError::Geometry);} - artifact.validate_tensor_source(key).map_err(|_|InputBindingError::Read)?; - let mut bytes=Vec::new();bytes.try_reserve_exact(size).map_err(|_|InputBindingError::Allocation)?; - // One genuine whole-tensor stream, bounded chunks; no per-vocabulary-row source syscalls. - artifact.stream_rows(key,0,vocab as u64,|part|{if bytes.len().checked_add(part.len()).is_none_or(|end|end>size){return Err(std::io::Error::from(std::io::ErrorKind::InvalidData));}bytes.extend_from_slice(part);Ok(())}).map_err(|_|InputBindingError::Read)?; - artifact.validate_tensor_source(key).map_err(|_|InputBindingError::Read)?; - if bytes.len()!=size{return Err(InputBindingError::Read);}Ok(NativeOutputBlock{binding:self.identity(),kind,n,vocab,bytes:bytes.into_boxed_slice()}) - } +impl ModelBinding { + pub(crate) fn native_output_block(&self, role: NativeOutputRole) -> InputResult { + let key = TensorRole::Global(match role { + NativeOutputRole::Head => GlobalRole::Output, + NativeOutputRole::Embedding => GlobalRole::TokenEmbedding, + }); + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?; + let tensor = artifact.tensor(key).map_err(|_| InputBindingError::Geometry)?; + let shape = tensor.dimensions(); + if shape.len() != 2 + || shape[0] == 0 + || shape[1] == 0 + || shape[0] > i32::MAX as u64 + || shape[1] > i32::MAX as u64 + || shape[0] % 256 != 0 + { + return Err(InputBindingError::Geometry); + } + let n = shape[0] as usize; + let vocab = shape[1] as usize; + let kind = tensor.kind(); + let supported = match role { + NativeOutputRole::Head => leleka_cuda_driver::native_head_supported(kind), + NativeOutputRole::Embedding => leleka_cuda_driver::native_embed_supported(kind), + }; + if !supported { + return Err(InputBindingError::UnsupportedKind); + } + let row = leleka_cuda_driver::native_head_row_bytes(kind, n).map_err(|_| InputBindingError::Geometry)?; + let size = row.checked_mul(vocab).ok_or(InputBindingError::Geometry)?; + if tensor.byte_length() != size as u64 { + return Err(InputBindingError::Geometry); + } + artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(size).map_err(|_| InputBindingError::Allocation)?; + // One genuine whole-tensor stream, bounded chunks; no per-vocabulary-row source syscalls. + artifact + .stream_rows(key, 0, vocab as u64, |part| { + if bytes.len().checked_add(part.len()).is_none_or(|end| end > size) { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); + } + bytes.extend_from_slice(part); + Ok(()) + }) + .map_err(|_| InputBindingError::Read)?; + artifact.validate_tensor_source(key).map_err(|_| InputBindingError::Read)?; + if bytes.len() != size { + return Err(InputBindingError::Read); + } + Ok(NativeOutputBlock { binding: self.identity(), kind, n, vocab, bytes: bytes.into_boxed_slice() }) + } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_original_file_source.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_original_file_source.rs index aa38078b..55ed8fd3 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_original_file_source.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_original_file_source.rs @@ -1,15 +1,18 @@ //! Original immutable file-source admission from this actual selected artifact. use super::*; use leleka_model_format::qwen4exp::FileExpertSourceLease; -impl ModelBinding{ - pub(crate) fn original_file_expert_source(&self)->InputResult{ - let artifact=self.artifact.try_borrow().map_err(|_|InputBindingError::Busy)?; - let lease=artifact.file_expert_source_lease().map_err(|_|InputBindingError::Read)?; - artifact.validate_file_expert_source(&lease).map_err(|_|InputBindingError::Geometry)?; +impl ModelBinding { + pub(crate) fn original_file_expert_source(&self) -> InputResult { + let artifact = self.artifact.try_borrow().map_err(|_| InputBindingError::Busy)?; + let lease = artifact.file_expert_source_lease().map_err(|_| InputBindingError::Read)?; + artifact.validate_file_expert_source(&lease).map_err(|_| InputBindingError::Geometry)?; Ok(lease) } - pub(crate) fn validate_original_file_expert_source(&self,lease:&FileExpertSourceLease)->InputResult<()>{ - self.artifact.try_borrow().map_err(|_|InputBindingError::Busy)? - .validate_file_expert_source(lease).map_err(|_|InputBindingError::Geometry) + pub(crate) fn validate_original_file_expert_source(&self, lease: &FileExpertSourceLease) -> InputResult<()> { + self.artifact + .try_borrow() + .map_err(|_| InputBindingError::Busy)? + .validate_file_expert_source(lease) + .map_err(|_| InputBindingError::Geometry) } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_output.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_output.rs index 69d37432..0c23ec67 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_output.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_output.rs @@ -5,9 +5,7 @@ //! already-verified role into one bounded packed owner for the fixed Q6 path. #![allow(dead_code)] -use super::{ - BindingIdentity, GlobalRole, InputBindingError, InputResult, ModelBinding, TensorRole, -}; +use super::{BindingIdentity, GlobalRole, InputBindingError, InputResult, ModelBinding, TensorRole}; use std::io; pub(crate) type OutputBindingError = InputBindingError; @@ -71,13 +69,7 @@ impl OutputWeights { #[cfg(test)] pub(crate) fn test_empty(binding: BindingIdentity) -> Self { - Self { - binding, - kind: 14, - rows: OUTPUT_ROWS, - columns: OUTPUT_COLUMNS, - bytes: Box::new([]), - } + Self { binding, kind: 14, rows: OUTPUT_ROWS, columns: OUTPUT_COLUMNS, bytes: Box::new([]) } } } @@ -86,14 +78,10 @@ impl ModelBinding { /// The artifact owner performs the pinned source-identity admission; this /// check binds the output role/range and never infers from filenames. pub(crate) fn output_weights(&self) -> InputResult { - let mut artifact = self - .artifact - .try_borrow_mut() - .map_err(|_| InputBindingError::Busy)?; + let mut artifact = self.artifact.try_borrow_mut().map_err(|_| InputBindingError::Busy)?; { - let descriptor = artifact - .tensor(TensorRole::Global(GlobalRole::Output)) - .map_err(|_| InputBindingError::Geometry)?; + let descriptor = + artifact.tensor(TensorRole::Global(GlobalRole::Output)).map_err(|_| InputBindingError::Geometry)?; validate_descriptor( descriptor.kind(), descriptor.shard(), @@ -103,44 +91,31 @@ impl ModelBinding { )?; } - let row_blocks = OUTPUT_COLUMNS - .checked_div(256) - .filter(|&blocks| blocks != 0) - .ok_or(InputBindingError::Geometry)?; - let row_bytes = row_blocks - .checked_mul(210) - .ok_or(InputBindingError::Geometry)?; + let row_blocks = + OUTPUT_COLUMNS.checked_div(256).filter(|&blocks| blocks != 0).ok_or(InputBindingError::Geometry)?; + let row_bytes = row_blocks.checked_mul(210).ok_or(InputBindingError::Geometry)?; if row_bytes != OUTPUT_ROW_BYTES - || row_bytes - .checked_mul(OUTPUT_ROWS) - .filter(|&total| total == OUTPUT_WEIGHT_BYTES) - .is_none() + || row_bytes.checked_mul(OUTPUT_ROWS).filter(|&total| total == OUTPUT_WEIGHT_BYTES).is_none() { return Err(InputBindingError::Geometry); } let mut bytes = Vec::new(); - bytes - .try_reserve_exact(OUTPUT_WEIGHT_BYTES) - .map_err(|_| InputBindingError::Allocation)?; + bytes.try_reserve_exact(OUTPUT_WEIGHT_BYTES).map_err(|_| InputBindingError::Allocation)?; for row in 0..OUTPUT_ROWS { let row_start = bytes.len(); artifact - .stream_row( - TensorRole::Global(GlobalRole::Output), - row as u64, - |chunk| { - let next = bytes - .len() - .checked_add(chunk.len()) - .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; - if next > OUTPUT_WEIGHT_BYTES || next - row_start > row_bytes { - return Err(io::Error::from(io::ErrorKind::InvalidData)); - } - bytes.extend_from_slice(chunk); - Ok(()) - }, - ) + .stream_row(TensorRole::Global(GlobalRole::Output), row as u64, |chunk| { + let next = bytes + .len() + .checked_add(chunk.len()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + if next > OUTPUT_WEIGHT_BYTES || next - row_start > row_bytes { + return Err(io::Error::from(io::ErrorKind::InvalidData)); + } + bytes.extend_from_slice(chunk); + Ok(()) + }) .map_err(|_| InputBindingError::Read)?; if bytes.len() - row_start != row_bytes { return Err(InputBindingError::Read); @@ -168,19 +143,13 @@ mod tests { fn fixed_output_descriptor_refusals_preserve_kind_precedence() { // Literal pinned inventory expectations; no tensor bytes or CUDA owner. let dimensions = [2560, 248320]; - assert_eq!( - validate_descriptor(14, 0, &dimensions, 11_024_384, 521_472_000), - Ok(()) - ); + assert_eq!(validate_descriptor(14, 0, &dimensions, 11_024_384, 521_472_000), Ok(())); for kind in [0, 12, 13, 24] { assert_eq!( validate_descriptor(kind, 0, &dimensions, 11_024_384, 521_472_000), Err(InputBindingError::UnsupportedKind) ); - assert_eq!( - validate_descriptor(kind, 1, &[], u64::MAX, u64::MAX), - Err(InputBindingError::UnsupportedKind) - ); + assert_eq!(validate_descriptor(kind, 1, &[], u64::MAX, u64::MAX), Err(InputBindingError::UnsupportedKind)); } for (shard, dimensions, start, length) in [ (1, &[2560, 248320][..], 11_024_384, 521_472_000), @@ -194,10 +163,7 @@ mod tests { (0, &[2560, 248320][..], u64::MAX, 521_472_000), (0, &[2560, 248320][..], 11_024_384, u64::MAX), ] { - assert_eq!( - validate_descriptor(14, shard, dimensions, start, length), - Err(InputBindingError::Geometry) - ); + assert_eq!(validate_descriptor(14, shard, dimensions, start, length), Err(InputBindingError::Geometry)); } } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple.rs index 04d0c554..7709d6c1 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple.rs @@ -1,8 +1,7 @@ //! Retained layer-one PLE weights. Closed matrices may be read once in full; //! compute still uses the original exact 64-row operations. use super::{ - BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, - Qwen4ExpArtifact, TensorRole, + BindingIdentity, InputBindingError as E, InputResult, LayerRole, ModelBinding, Qwen4ExpArtifact, TensorRole, }; const N: usize = 2560; @@ -95,41 +94,14 @@ impl ModelBinding { for r in [PleMatrixRole::Key, PleMatrixRole::Value] { let (r, rows) = matrix(r); let d = a.tensor(r).map_err(|_| E::Geometry)?; - descriptor( - d.kind(), - d.dimensions(), - d.byte_length(), - 30, - &[N as u64, rows as u64], - N * rows * 2, - )?; + descriptor(d.kind(), d.dimensions(), d.byte_length(), 30, &[N as u64, rows as u64], N * rows * 2)?; } - for r in [ - LayerRole::PleNormKey, - LayerRole::PleNormQuery, - LayerRole::PleNormConv, - ] { + for r in [LayerRole::PleNormKey, LayerRole::PleNormQuery, LayerRole::PleNormConv] { let d = a.tensor(role(r)).map_err(|_| E::Geometry)?; - descriptor( - d.kind(), - d.dimensions(), - d.byte_length(), - 0, - &[HC as u64], - HC * 4, - )?; + descriptor(d.kind(), d.dimensions(), d.byte_length(), 0, &[HC as u64], HC * 4)?; } - let d = a - .tensor(role(LayerRole::PleConv1d)) - .map_err(|_| E::Geometry)?; - descriptor( - d.kind(), - d.dimensions(), - d.byte_length(), - 1, - &[4, HC as u64], - HC * 4 * 2, - )?; + let d = a.tensor(role(LayerRole::PleConv1d)).map_err(|_| E::Geometry)?; + descriptor(d.kind(), d.dimensions(), d.byte_length(), 1, &[4, HC as u64], HC * 4 * 2)?; let norm_key = norm(&mut a, LayerRole::PleNormKey)?; let norm_query = norm(&mut a, LayerRole::PleNormQuery)?; let norm_conv = norm(&mut a, LayerRole::PleNormConv)?; @@ -143,13 +115,7 @@ impl ModelBinding { } conv.push(h); } - Ok(PleWeights { - binding: self.identity(), - norm_key, - norm_query, - norm_conv, - conv: conv.into_boxed_slice(), - }) + Ok(PleWeights { binding: self.identity(), norm_key, norm_query, norm_conv, conv: conv.into_boxed_slice() }) } pub(crate) fn ple_matrix_block( &self, @@ -165,11 +131,7 @@ impl ModelBinding { range(first, count, rows)?; self.ple_matrix_span(weights, r, first, count, rows) } - pub(crate) fn ple_matrix_full( - &self, - weights: &PleWeights, - r: PleMatrixRole, - ) -> InputResult { + pub(crate) fn ple_matrix_full(&self, weights: &PleWeights, r: PleMatrixRole) -> InputResult { if !weights.matches(&self.identity()) { return Err(E::Geometry); } @@ -189,24 +151,14 @@ impl ModelBinding { } let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; let d = a.tensor(r).map_err(|_| E::Geometry)?; - descriptor( - d.kind(), - d.dimensions(), - d.byte_length(), - 30, - &[N as u64, rows as u64], - N * rows * 2, - )?; + descriptor(d.kind(), d.dimensions(), d.byte_length(), 30, &[N as u64, rows as u64], N * rows * 2)?; let values = read_rows(&mut a, r, first, count, N * 2 * count)?; for bits in values.as_chunks::<2>().0 { if !f32::from_bits(u32::from(u16::from_le_bytes(*bits)) << 16).is_finite() { return Err(E::NonFinite); } } - Ok(PleWeightBlock { - bytes: values.into_boxed_slice(), - rows: count, - }) + Ok(PleWeightBlock { bytes: values.into_boxed_slice(), rows: count }) } pub(crate) fn validate_ple_sources(&self) -> InputResult<()> { let mut a = self.artifact.try_borrow_mut().map_err(|_| E::Busy)?; @@ -240,11 +192,7 @@ fn read_rows( let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; a.stream_rows(r, first as u64, count as u64, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|end| end > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|end| end > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -260,12 +208,7 @@ fn read(a: &mut Qwen4ExpArtifact, r: TensorRole, row: u64, limit: usize) -> Inpu let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; a.stream_row(r, row, |chunk| { - if chunk.len() > 65536 - || bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|end| end > limit) - { + if chunk.len() > 65536 || bytes.len().checked_add(chunk.len()).is_none_or(|end| end > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -295,32 +238,9 @@ mod tests { use super::*; #[test] fn ple_inventory_requires_original_formats_and_geometry() { - assert_eq!( - descriptor( - 30, - &[2560, 10240], - 52_428_800, - 30, - &[2560, 10240], - 52_428_800 - ), - Ok(()) - ); - assert_eq!( - descriptor( - 0, - &[2560, 10240], - 104_857_600, - 30, - &[2560, 10240], - 52_428_800 - ), - Err(E::UnsupportedKind) - ); - assert_eq!( - descriptor(1, &[10240, 4], 81920, 1, &[4, 10240], 81920), - Err(E::Geometry) - ); + assert_eq!(descriptor(30, &[2560, 10240], 52_428_800, 30, &[2560, 10240], 52_428_800), Ok(())); + assert_eq!(descriptor(0, &[2560, 10240], 104_857_600, 30, &[2560, 10240], 52_428_800), Err(E::UnsupportedKind)); + assert_eq!(descriptor(1, &[10240, 4], 81920, 1, &[4, 10240], 81920), Err(E::Geometry)); } #[test] fn ple_blocks_refuse_zero_large_overflow_and_end_before_read() { diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple_reader.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple_reader.rs index aa573047..d344a72b 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple_reader.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_ple_reader.rs @@ -7,10 +7,7 @@ //! condition that prevents opening the reader falls back to that synchronous //! path, which stays the oracle. -use super::{ - GlobalRole, InputBindingError, InputResult, ModelBinding, PLE_ROW_VALUES, PLE_ROWS, TensorRole, - decode, -}; +use super::{GlobalRole, InputBindingError, InputResult, ModelBinding, PLE_ROW_VALUES, PLE_ROWS, TensorRole, decode}; use crate::settings::EnvSource; use leleka_model_format::ple_reader::{PleReader, PleReaderConfig, Ticket}; use std::time::Duration; @@ -43,15 +40,8 @@ impl PlePolicy { match get(key) { None => Ok(default), Some(text) => { - let value = text - .trim() - .parse::() - .map_err(|_| InputBindingError::Metadata)?; - if (min..=max).contains(&value) { - Ok(value) - } else { - Err(InputBindingError::Metadata) - } + let value = text.trim().parse::().map_err(|_| InputBindingError::Metadata)?; + if (min..=max).contains(&value) { Ok(value) } else { Err(InputBindingError::Metadata) } } } } @@ -70,18 +60,8 @@ impl PlePolicy { cache_rows: number(&get, "LELEKA_PLE_ROW_CACHE", 1 << 20, 0, PLE_ROWS)?, max_inflight: number(&get, "LELEKA_PLE_INFLIGHT", 64, 1, 1024)? as usize, inline, - keepalive: if inline { - Duration::ZERO - } else { - Duration::from_millis(keepalive_ms) - }, - keepalive_window: Duration::from_secs(number( - &get, - "LELEKA_SSD_KEEPALIVE_WINDOW_S", - 60, - 1, - 86_400, - )?), + keepalive: if inline { Duration::ZERO } else { Duration::from_millis(keepalive_ms) }, + keepalive_window: Duration::from_secs(number(&get, "LELEKA_SSD_KEEPALIVE_WINDOW_S", 60, 1, 86_400)?), direct: flag("LELEKA_PLE_DIRECT", cfg!(target_os = "linux"))?, }) } @@ -102,10 +82,7 @@ pub(super) fn decode_batch(bytes: &[u8]) -> InputResult>> { if bytes.len() != HEADS * ROW_BYTES { return Err(InputBindingError::Read); } - bytes - .chunks_exact(ROW_BYTES) - .map(|row| decode::row(20, row, PLE_ROW_VALUES)) - .collect() + bytes.chunks_exact(ROW_BYTES).map(|row| decode::row(20, row, PLE_ROW_VALUES)).collect() } /// An unbuffered duplicate of `file`, accepted only if it names the same inode @@ -141,30 +118,19 @@ impl ModelBinding { return Ok(reader.as_ref()); } let policy = PlePolicy::from_environment()?; - let reader = if policy.enabled { - self.open_ple_reader(&policy)? - } else { - None - }; + let reader = if policy.enabled { self.open_ple_reader(&policy)? } else { None }; Ok(self.ple_reader.get_or_init(|| reader).as_ref()) } fn open_ple_reader(&self, policy: &PlePolicy) -> InputResult> { let source = { - let artifact = self - .artifact - .try_borrow() - .map_err(|_| InputBindingError::Busy)?; + let artifact = self.artifact.try_borrow().map_err(|_| InputBindingError::Busy)?; artifact.row_table_source(TensorRole::Global(GlobalRole::PerLayerTokenEmbedding)) }; let source = match source { - Ok(source) if source.n_rows == PLE_ROWS && source.row_bytes == ROW_BYTES as u64 => { - source - } + Ok(source) if source.n_rows == PLE_ROWS && source.row_bytes == ROW_BYTES as u64 => source, _ => { - eprintln!( - "leleka-ple-reader-unavailable: row table geometry; using synchronous reads" - ); + eprintln!("leleka-ple-reader-unavailable: row table geometry; using synchronous reads"); return Ok(None); } }; @@ -174,11 +140,7 @@ impl ModelBinding { config.cache_rows = policy.cache_rows; config.io_threads = if policy.inline { Some(0) } else { None }; config.expected_len = Some(source.file_size); - let direct = if policy.direct { - direct_handle(&source.file, source.table_offset) - } else { - None - }; + let direct = if policy.direct { direct_handle(&source.file, source.table_offset) } else { None }; let file = direct.unwrap_or(source.file); let mut reader = match PleReader::open(std::sync::Arc::new(file), config) { Ok(reader) => reader, @@ -210,9 +172,7 @@ impl ModelBinding { match pending { PlePending::Reader(ticket, _) => { let reader = self.ple_reader()?.ok_or(InputBindingError::Read)?; - let bytes = reader - .collect(ticket) - .map_err(|_| InputBindingError::Read)?; + let bytes = reader.collect(ticket).map_err(|_| InputBindingError::Read)?; decode_batch(&bytes) } PlePending::Rows(rows) => rows.iter().map(|&row| self.ple_row(row)).collect(), @@ -226,10 +186,7 @@ mod tests { use std::collections::HashMap; fn policy(pairs: &[(&str, &str)]) -> InputResult { - let map: HashMap = pairs - .iter() - .map(|&(k, v)| (k.to_owned(), v.to_owned())) - .collect(); + let map: HashMap = pairs.iter().map(|&(k, v)| (k.to_owned(), v.to_owned())).collect(); PlePolicy::from_values(|key| map.get(key).cloned()) } @@ -238,21 +195,13 @@ mod tests { let p = policy(&[]).unwrap(); assert!(p.enabled); assert_eq!((p.cache_rows, p.max_inflight), (1 << 20, 64)); - assert_eq!( - (p.keepalive, p.keepalive_window), - (Duration::from_millis(100), Duration::from_secs(60)) - ); + assert_eq!((p.keepalive, p.keepalive_window), (Duration::from_millis(100), Duration::from_secs(60))); assert!(!p.inline); } #[test] fn sync_submit_turns_keepalive_off() { - assert_eq!( - policy(&[("LELEKA_PLE_SYNC_SUBMIT", "1")]) - .unwrap() - .keepalive, - Duration::ZERO - ); + assert_eq!(policy(&[("LELEKA_PLE_SYNC_SUBMIT", "1")]).unwrap().keepalive, Duration::ZERO); } #[test] @@ -268,18 +217,9 @@ mod tests { ("LELEKA_PLE_READER", "yes"), ("LELEKA_PLE_DIRECT", "2"), ] { - assert_eq!( - policy(&[(k, v)]), - Err(InputBindingError::Metadata), - "{k}={v}" - ); + assert_eq!(policy(&[(k, v)]), Err(InputBindingError::Metadata), "{k}={v}"); } - assert!( - policy(&[("LELEKA_PLE_ROW_CACHE", "0"), ("LELEKA_PLE_READER", "0")]) - .unwrap() - .cache_rows - == 0 - ); + assert!(policy(&[("LELEKA_PLE_ROW_CACHE", "0"), ("LELEKA_PLE_READER", "0")]).unwrap().cache_rows == 0); } #[test] @@ -287,26 +227,14 @@ mod tests { let mut bytes = Vec::new(); for r in 0..HEADS { for k in 0..ROW_BYTES { - bytes.push(if k % 18 < 2 { - [0x00, 0x3C][k % 18] - } else { - (r * 5 + k) as u8 - }); // f16 1.0 scale per 18-byte block + bytes.push(if k % 18 < 2 { [0x00, 0x3C][k % 18] } else { (r * 5 + k) as u8 }); // f16 1.0 scale per 18-byte block } } let batch = decode_batch(&bytes).unwrap(); for (r, row) in batch.iter().enumerate() { - let single = decode::row( - 20, - &bytes[r * ROW_BYTES..(r + 1) * ROW_BYTES], - PLE_ROW_VALUES, - ) - .unwrap(); + let single = decode::row(20, &bytes[r * ROW_BYTES..(r + 1) * ROW_BYTES], PLE_ROW_VALUES).unwrap(); assert_eq!(row, &single); } - assert_eq!( - decode_batch(&bytes[1..]).unwrap_err(), - InputBindingError::Read - ); + assert_eq!(decode_batch(&bytes[1..]).unwrap_err(), InputBindingError::Read); } } diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_qsa.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_qsa.rs index d0777261..cfb43f9a 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_qsa.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_qsa.rs @@ -1,7 +1,7 @@ //! Closed QSA descriptors and bounded rows from the retained verified artifact. use super::{ - BindingIdentity, BoundLayerKind, InputBindingError as E, InputResult, LayerRole, ModelBinding, - Qwen4ExpArtifact, TensorRole, + BindingIdentity, BoundLayerKind, InputBindingError as E, InputResult, LayerRole, ModelBinding, Qwen4ExpArtifact, + TensorRole, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -37,9 +37,7 @@ pub(crate) struct QsaWeights { impl QsaWeights { pub(crate) fn source_bytes(&self, role: QsaMatrixRole) -> InputResult { let m = self.matrices[index(role)]; - super::decode::row_bytes(m.kind, m.columns)? - .checked_mul(m.rows) - .ok_or(E::Geometry) + super::decode::row_bytes(m.kind, m.columns)?.checked_mul(m.rows).ok_or(E::Geometry) } pub(crate) fn layer(&self) -> u32 { self.layer @@ -160,10 +158,7 @@ impl ModelBinding { return Err(E::Metadata); } let layer8 = u8::try_from(layer).map_err(|_| E::Range)?; - let role = |role| TensorRole::Layer { - layer: layer8, - role, - }; + let role = |role| TensorRole::Layer { layer: layer8, role }; let definitions = [ (QsaMatrixRole::Q, LayerRole::AttnQ, 2560, 12288), (QsaMatrixRole::K, LayerRole::AttnK, 2560, 512), @@ -172,28 +167,11 @@ impl ModelBinding { (QsaMatrixRole::IndexK, LayerRole::IndexerKProj, 2560, 128), (QsaMatrixRole::Out, LayerRole::AttnOutput, 6144, 2560), ]; - let mut matrices = [Matrix { - role: role(LayerRole::AttnQ), - kind: 0, - columns: 0, - rows: 0, - }; 6]; + let mut matrices = [Matrix { role: role(LayerRole::AttnQ), kind: 0, columns: 0, rows: 0 }; 6]; for (r, l, c, n) in definitions { let tensor = a.tensor(role(l)).map_err(|_| E::Geometry)?; - descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - r, - c, - n, - )?; - matrices[index(r)] = Matrix { - role: role(l), - kind: tensor.kind(), - columns: c, - rows: n, - }; + descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), r, c, n)?; + matrices[index(r)] = Matrix { role: role(l), kind: tensor.kind(), columns: c, rows: n }; } let norms = [ (LayerRole::AttnQNorm, 256), @@ -203,10 +181,7 @@ impl ModelBinding { ]; for (r, n) in norms { let tensor = a.tensor(role(r)).map_err(|_| E::Geometry)?; - if tensor.kind() != 0 - || tensor.dimensions() != [n as u64] - || tensor.byte_length() != n as u64 * 4 - { + if tensor.kind() != 0 || tensor.dimensions() != [n as u64] || tensor.byte_length() != n as u64 * 4 { return Err(E::Geometry); } } @@ -214,12 +189,7 @@ impl ModelBinding { let k = read_norm(&mut a, role(norms[1].0), 256)?; let iq = read_norm(&mut a, role(norms[2].0), 128)?; let ik = read_norm(&mut a, role(norms[3].0), 128)?; - Ok(QsaWeights { - binding: self.identity(), - layer, - matrices, - norms: [q, k, iq, ik], - }) + Ok(QsaWeights { binding: self.identity(), layer, matrices, norms: [q, k, iq, ik] }) } pub(crate) fn qsa_matrix_block( &self, @@ -240,24 +210,13 @@ impl ModelBinding { if tensor.kind() != m.kind { return Err(E::Geometry); } - descriptor( - tensor.kind(), - tensor.dimensions(), - tensor.byte_length(), - role, - m.columns, - m.rows, - )?; + descriptor(tensor.kind(), tensor.dimensions(), tensor.byte_length(), role, m.columns, m.rows)?; let row = super::decode::row_bytes(m.kind, m.columns)?; let limit = row.checked_mul(count).ok_or(E::Geometry)?; let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; a.stream_rows(m.role, first as u64, count as u64, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -284,20 +243,11 @@ fn block_range(first: usize, count: usize, rows: usize) -> InputResult<()> { } Ok(()) } -fn read_row( - a: &mut Qwen4ExpArtifact, - role: TensorRole, - row: u64, - limit: usize, -) -> InputResult> { +fn read_row(a: &mut Qwen4ExpArtifact, role: TensorRole, row: u64, limit: usize) -> InputResult> { let mut bytes = Vec::new(); bytes.try_reserve_exact(limit).map_err(|_| E::Allocation)?; a.stream_row(role, row, |chunk| { - if bytes - .len() - .checked_add(chunk.len()) - .is_none_or(|n| n > limit) - { + if bytes.len().checked_add(chunk.len()).is_none_or(|n| n > limit) { return Err(std::io::ErrorKind::InvalidData.into()); } bytes.extend_from_slice(chunk); @@ -337,18 +287,9 @@ mod tests { } #[test] fn descriptor_extent_and_tile_boundaries_fail_without_reads() { - assert_eq!( - descriptor(30, &[2560, 128], 655360, QsaMatrixRole::IndexK, 2560, 128), - Ok(()) - ); - assert_eq!( - descriptor(30, &[128, 2560], 655360, QsaMatrixRole::IndexK, 2560, 128), - Err(E::Geometry) - ); - assert_eq!( - descriptor(30, &[2560, 128], 655359, QsaMatrixRole::IndexK, 2560, 128), - Err(E::Geometry) - ); + assert_eq!(descriptor(30, &[2560, 128], 655360, QsaMatrixRole::IndexK, 2560, 128), Ok(())); + assert_eq!(descriptor(30, &[128, 2560], 655360, QsaMatrixRole::IndexK, 2560, 128), Err(E::Geometry)); + assert_eq!(descriptor(30, &[2560, 128], 655359, QsaMatrixRole::IndexK, 2560, 128), Err(E::Geometry)); assert_eq!(block_range(12224, 64, 12288), Ok(())); for (f, n) in [(0, 0), (0, 65), (12225, 64), (usize::MAX, 1)] { assert_eq!(block_range(f, n, 12288), Err(E::Range)); diff --git a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_resident_expert_source.rs b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_resident_expert_source.rs index e2c65600..36a8e933 100644 --- a/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_resident_expert_source.rs +++ b/crates/engine-qwen35-cuda/src/model_binding/qwen4exp_resident_expert_source.rs @@ -13,52 +13,39 @@ impl ModelBinding { /// KAR/MTP admission, before Driver, preload, sessions or Ready publication. /// The mutable loan excludes binding/source loans; fresh session placement /// remains the selected caller contract (sessions retain an identity Rc). - pub(crate) fn load_resident_expert_source( - &mut self, - ) -> InputResult { + pub(crate) fn load_resident_expert_source(&mut self) -> InputResult { if (self.kar_ple.is_none() && !gguf_ple_opt_in()) || self.mtp.is_none() { return Err(InputBindingError::Metadata); } self.mtp_weights()?; - self.artifact - .get_mut() - .load_resident_expert_source() - .map_err(|error| match error { - ResidentExpertSourceError::Geometry => InputBindingError::Geometry, - ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, - ResidentExpertSourceError::Allocation - | ResidentExpertSourceError::MemoryAdmission => InputBindingError::Allocation, - ResidentExpertSourceError::Read(_) => InputBindingError::Read, - }) + self.artifact.get_mut().load_resident_expert_source().map_err(|error| match error { + ResidentExpertSourceError::Geometry => InputBindingError::Geometry, + ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, + ResidentExpertSourceError::Allocation | ResidentExpertSourceError::MemoryAdmission => { + InputBindingError::Allocation + } + ResidentExpertSourceError::Read(_) => InputBindingError::Read, + }) } /// The low-RAM form of `load_resident_expert_source`: the same banks as read-only shared mappings of shard 0 /// (the Original's `--mmap-experts`, GGUF in place). Same preconditions; no RAM is committed for the experts. #[cfg(any(target_os = "linux", target_os = "windows"))] - pub(crate) fn load_mapped_expert_source( - &mut self, - ) -> InputResult { + pub(crate) fn load_mapped_expert_source(&mut self) -> InputResult { if (self.kar_ple.is_none() && !gguf_ple_opt_in()) || self.mtp.is_none() { return Err(InputBindingError::Metadata); } self.mtp_weights()?; - self.artifact - .get_mut() - .load_mapped_expert_source() - .map_err(|error| match error { - ResidentExpertSourceError::Geometry => InputBindingError::Geometry, - ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, - ResidentExpertSourceError::Allocation - | ResidentExpertSourceError::MemoryAdmission => InputBindingError::Allocation, - ResidentExpertSourceError::Read(_) => InputBindingError::Read, - }) + self.artifact.get_mut().load_mapped_expert_source().map_err(|error| match error { + ResidentExpertSourceError::Geometry => InputBindingError::Geometry, + ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, + ResidentExpertSourceError::Allocation | ResidentExpertSourceError::MemoryAdmission => { + InputBindingError::Allocation + } + ResidentExpertSourceError::Read(_) => InputBindingError::Read, + }) } - pub(crate) fn resident_expert_source_report( - &self, - ) -> InputResult> { - let artifact = self - .artifact - .try_borrow() - .map_err(|_| InputBindingError::Busy)?; + pub(crate) fn resident_expert_source_report(&self) -> InputResult> { + let artifact = self.artifact.try_borrow().map_err(|_| InputBindingError::Busy)?; Ok(artifact.resident_expert_source_report()) } } @@ -74,16 +61,14 @@ impl ModelBinding { return Err(InputBindingError::Metadata); } self.mtp_weights()?; - self.artifact - .get_mut() - .adopt_resident_expert_capture(capture) - .map_err(|error| match error { - ResidentExpertSourceError::Geometry => InputBindingError::Geometry, - ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, - ResidentExpertSourceError::Allocation - | ResidentExpertSourceError::MemoryAdmission => InputBindingError::Allocation, - ResidentExpertSourceError::Read(_) => InputBindingError::Read, - }) + self.artifact.get_mut().adopt_resident_expert_capture(capture).map_err(|error| match error { + ResidentExpertSourceError::Geometry => InputBindingError::Geometry, + ResidentExpertSourceError::AlreadyEnabled => InputBindingError::Metadata, + ResidentExpertSourceError::Allocation | ResidentExpertSourceError::MemoryAdmission => { + InputBindingError::Allocation + } + ResidentExpertSourceError::Read(_) => InputBindingError::Read, + }) } } @@ -96,13 +81,17 @@ impl ModelBinding { members.try_reserve_exact(144).map_err(|_| InputBindingError::Allocation)?; for layer in 0..48 { for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { - members.push(artifact.resident_expert_bank_member(&lease, layer, role) - .map_err(|_| InputBindingError::Read)?); + members.push( + artifact.resident_expert_bank_member(&lease, layer, role).map_err(|_| InputBindingError::Read)?, + ); } } Ok((lease, members)) } } -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -type RetainedExpertBankMembers=(leleka_model_format::qwen4exp::ResidentExpertBankLease,Vec); +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +type RetainedExpertBankMembers = ( + leleka_model_format::qwen4exp::ResidentExpertBankLease, + Vec, +); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_cpu_budget.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_cpu_budget.rs index 0061a2ff..f8933afd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_cpu_budget.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_cpu_budget.rs @@ -8,36 +8,48 @@ const POOL_BYTES: u64 = 160 * 1024 * 1024; const FUTURE_HEADROOM: u64 = 8 * 1024 * 1024 * 1024; pub(super) fn admit_pool(binding: &ModelBinding, metadata: usize) -> Result<()> { - let report = binding.resident_expert_source_report().map_err(binding_error)? - .ok_or(Error::IdentityMismatch)?; - if report.bank_count != 144 || report.source_cap_bytes != MODEL_SOURCE_CAP - || report.future_headroom_bytes != FUTURE_HEADROOM || metadata > HOST_CAP + let report = binding.resident_expert_source_report().map_err(binding_error)?.ok_or(Error::IdentityMismatch)?; + if report.bank_count != 144 + || report.source_cap_bytes != MODEL_SOURCE_CAP + || report.future_headroom_bytes != FUTURE_HEADROOM + || metadata > HOST_CAP || report.source_bytes > report.charged_bytes - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let metadata = u64::try_from(metadata).map_err(|_| Error::Overflow)?; - let charged = report.charged_bytes.checked_add(metadata) - .and_then(|n| n.checked_add(POOL_BYTES)).ok_or(Error::Overflow)?; - if charged > MODEL_SOURCE_CAP { return Err(Error::InputAllocation); } + let charged = + report.charged_bytes.checked_add(metadata).and_then(|n| n.checked_add(POOL_BYTES)).ok_or(Error::Overflow)?; + if charged > MODEL_SOURCE_CAP { + return Err(Error::InputAllocation); + } // Existing bank/KAR/Dense owners are already reflected in MemAvailable. // Charge only not-yet-constructed pool/metadata and genuine future safety. // This is a fail-closed snapshot, not a reservation against other processes. - let needed = POOL_BYTES.checked_add(metadata) - .and_then(|n| n.checked_add(FUTURE_HEADROOM)).ok_or(Error::Overflow)?; - if memory_available()? < needed { return Err(Error::InputAllocation); } + let needed = + POOL_BYTES.checked_add(metadata).and_then(|n| n.checked_add(FUTURE_HEADROOM)).ok_or(Error::Overflow)?; + if memory_available()? < needed { + return Err(Error::InputAllocation); + } Ok(()) } fn memory_available() -> Result { let mut text = String::new(); #[cfg(not(target_os = "windows"))] - File::open("/proc/meminfo").map_err(|_| Error::InputAllocation)? - .take(65537).read_to_string(&mut text).map_err(|_| Error::InputAllocation)?; + File::open("/proc/meminfo") + .map_err(|_| Error::InputAllocation)? + .take(65537) + .read_to_string(&mut text) + .map_err(|_| Error::InputAllocation)?; // Windows: the same text, rendered from GlobalMemoryStatusEx by leleka-memory. #[cfg(target_os = "windows")] { use leleka_memory::ProcSource; text = leleka_memory::RealProc.read("/proc/meminfo").map_err(|_| Error::InputAllocation)?; } - if text.len() > 65536 { return Err(Error::InputAllocation); } + if text.len() > 65536 { + return Err(Error::InputAllocation); + } let mut available = None; let mut total = None; for line in text.lines() { @@ -48,14 +60,19 @@ fn memory_available() -> Result { "MemTotal:" => &mut total, _ => continue, }; - if destination.is_some() { return Err(Error::InputAllocation); } - let value = parts.next().ok_or(Error::InputAllocation)? - .parse::().map_err(|_| Error::InputAllocation)?; - if parts.next() != Some("kB") || parts.next().is_some() { return Err(Error::InputAllocation); } + if destination.is_some() { + return Err(Error::InputAllocation); + } + let value = parts.next().ok_or(Error::InputAllocation)?.parse::().map_err(|_| Error::InputAllocation)?; + if parts.next() != Some("kB") || parts.next().is_some() { + return Err(Error::InputAllocation); + } *destination = Some(value.checked_mul(1024).ok_or(Error::Overflow)?); } let available = available.ok_or(Error::InputAllocation)?; let total = total.ok_or(Error::InputAllocation)?; - if total == 0 || available > total { return Err(Error::InputAllocation); } + if total == 0 || available > total { + return Err(Error::InputAllocation); + } Ok(available) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs index fa869cec..2f3ea0ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed.rs @@ -1,10 +1,10 @@ //! Two temporary, source-bound whole expert triplets. No cache-hit or row proof. //! Root alone supplies the scheduler/current-transaction checks and registration. -use crate::qwen_forward::contract::{Error, Result, Stage}; -use crate::qwen_forward::qsa_index::{binding_error, driver_error}; use crate::model_binding::qwen4exp_input::{ BindingIdentity, ModelBinding, MoeExpertBlock, MoeMatrixRole, MoeRoutedSourceScope, MoeWeightDescriptor, }; +use crate::qwen_forward::contract::{Error, Result, Stage}; +use crate::qwen_forward::qsa_index::{binding_error, driver_error}; use leleka_cuda_driver::{Context, DeviceBuffer, OwnedCopyPoll, PendingOwnedCopy}; use std::cell::Cell; @@ -83,34 +83,43 @@ mod cancel_policy_tests { /// Actual native single-plan16 or explicitly split-plan8 staging. A size or /// verification token count never invents an Original split-plan witness. -#[derive(Clone,Copy)] -pub(in crate::qwen_forward) enum MappedStageShape { Single16, #[allow(dead_code)] Split8 } -use leleka_cuda_driver::{MappedExpertBank,MappedExpertCopyScratch,PendingMappedExpertCopy}; +#[derive(Clone, Copy)] +pub(in crate::qwen_forward) enum MappedStageShape { + Single16, + #[allow(dead_code)] + Split8, +} +use leleka_cuda_driver::{MappedExpertBank, MappedExpertCopyScratch, PendingMappedExpertCopy}; use std::rc::Rc; -enum MappedSlot<'ctx>{ - Idle{buffers:Buffers<'ctx>,scratch:Option>}, - Pending{keys:[MoeWeightDescriptor;3],copy:PendingMappedExpertCopy<'ctx>}, - Completed{keys:[MoeWeightDescriptor;3],buffers:Buffers<'ctx>,scratch:Option>}, +enum MappedSlot<'ctx> { + Idle { buffers: Buffers<'ctx>, scratch: Option> }, + Pending { keys: [MoeWeightDescriptor; 3], copy: PendingMappedExpertCopy<'ctx> }, + Completed { keys: [MoeWeightDescriptor; 3], buffers: Buffers<'ctx>, scratch: Option> }, InUse, } -struct MappedStage<'ctx>{binding:BindingIdentity,context:&'ctx Context<'ctx>,maximum:[usize;3], - bank:Option>>,slots:Vec>} +struct MappedStage<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + bank: Option>>, + slots: Vec>, +} #[path = "cache_ephemeral_routed/healthy_cancel_fn.rs"] mod healthy_cancel_fn; #[allow(unused_imports)] -use healthy_cancel_fn::healthy_cancel; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use healthy_cancel_fn::observe_cancel; -#[allow(unused_imports)] -use healthy_cancel_fn::combine; -#[allow(unused_imports)] use healthy_cancel_fn::close_buffers; #[allow(unused_imports)] use healthy_cancel_fn::close_slot; #[allow(unused_imports)] +use healthy_cancel_fn::combine; +#[allow(unused_imports)] use healthy_cancel_fn::empty_slot; -#[path = "cache_ephemeral_routed/impl_ephemeralroutedowner.rs"] -mod impl_ephemeralroutedowner; +#[allow(unused_imports)] +use healthy_cancel_fn::healthy_cancel; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use healthy_cancel_fn::observe_cancel; #[path = "cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs"] mod impl_drop_for_ephemeralroutedowner; +#[path = "cache_ephemeral_routed/impl_ephemeralroutedowner.rs"] +mod impl_ephemeralroutedowner; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/healthy_cancel_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/healthy_cancel_fn.rs index 6c683a25..f58c616e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/healthy_cancel_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/healthy_cancel_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// A genuinely observed cancellation: the executor's cancelled closure returned true during /// THIS loan. The error code alone never qualifies (it is shared with other producers). pub(super) fn healthy_cancel(error: &Error, observed: bool, failed: bool, poisoned: bool) -> bool { @@ -12,16 +11,22 @@ pub(super) fn healthy_cancel(error: &Error, observed: bool, failed: bool, poison /// Wrap the real `cancelled` closure so a `true` answer is recorded in `observed`. The flag is /// set only here, never from an error value, and starts false for each loan. pub(in crate::qwen_forward) fn observe_cancel<'a>( - observed: &'a Cell, cancelled: &'a mut impl FnMut() -> bool, + observed: &'a Cell, + cancelled: &'a mut impl FnMut() -> bool, ) -> impl FnMut() -> bool + 'a { move || { let answer = cancelled(); - if answer { observed.set(true); } + if answer { + observed.set(true); + } answer } } pub(super) fn combine(primary: Result, cleanup: Result<()>) -> Result { - match primary { Err(error) => Err(error), Ok(value) => cleanup.map(|()| value) } + match primary { + Err(error) => Err(error), + Ok(value) => cleanup.map(|()| value), + } } pub(super) fn close_buffers(buffers: &mut Buffers<'_>) -> Result<()> { let mut result = Ok(()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs index e27de00b..c3b60bb6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_drop_for_ephemeralroutedowner.rs @@ -4,135 +4,321 @@ use super::*; impl Drop for EphemeralRoutedOwner<'_> { - fn drop(&mut self) { let _ = self.release_all(); } -} -impl MappedStageShape { pub(super) fn slots(self)->usize{match self{Self::Single16=>16,Self::Split8=>8}} } -impl<'ctx> EphemeralRoutedOwner<'ctx>{ - pub(in crate::qwen_forward) fn new_mapped(binding:&ModelBinding,context:&'ctx Context<'ctx>,maximum:[usize;3],shape:MappedStageShape)->Result{ - let mapped=MappedStage::new(binding,context,maximum,shape)?; - Ok(Self{binding:binding.identity(),context,maximum,slots:std::array::from_fn(|_|empty_slot()),failed:false,mapped:Some(mapped), - #[cfg(test)] completed_loans:0}) - } - pub(in crate::qwen_forward) fn slot_count(&self)->usize{self.mapped.as_ref().map_or(SLOTS,|owner|owner.slots.len())} - pub(in crate::qwen_forward) fn uses_mapped(&self)->bool{self.mapped.is_some()} - pub(in crate::qwen_forward) fn mapped_eligible(&self,binding:&ModelBinding,source:&MoeRoutedSourceScope<'_, '_>,member:usize)->Result{ - self.validate(binding,self.context)?; - let Some(mapped)=&self.mapped else{return Ok(false);}; - Self::keys(binding,source,member)?; - let spans=[source.bank_span(member,ROLES[0]).map_err(binding_error)?,source.bank_span(member,ROLES[1]).map_err(binding_error)?,source.bank_span(member,ROLES[2]).map_err(binding_error)?]; - Ok(mapped.bank.as_ref().is_some_and(|bank|bank.eligible(&spans))) + fn drop(&mut self) { + let _ = self.release_all(); } } -impl<'ctx> MappedStage<'ctx>{ - pub(super) fn new(binding:&ModelBinding,context:&'ctx Context<'ctx>,maximum:[usize;3],shape:MappedStageShape)->Result{ - for (bytes,ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM){if bytes==0 || bytes>ceiling || !bytes.is_multiple_of(256){return Err(Error::InvalidDimension);}} - let count=shape.slots(); - let extra=maximum.into_iter().try_fold(36usize,|n,b|n.checked_add(b).ok_or(Error::Overflow))? - .checked_mul(count).ok_or(Error::Overflow)?; - EphemeralRoutedOwner::room(context,extra)?; - let (lease,members)=binding.retained_expert_bank_members().map_err(binding_error)?; - let bank=Rc::new(context.mapped_expert_bank(lease,members).map_err(driver_error)?); - let mut owner=Self{binding:binding.identity(),context,maximum,bank:Some(bank),slots:Vec::new()}; - owner.slots.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?; - let operation=(||{ - for _ in 0..count{ - let mut buffers=std::array::from_fn(|_|None); - for (buffer,bytes) in buffers.iter_mut().zip(maximum){*buffer=Some(context.allocate(bytes).map_err(driver_error)?);} - let scratch=context.mapped_expert_copy_scratch().map_err(driver_error)?; - owner.slots.push(MappedSlot::Idle{buffers,scratch:Some(scratch)}); +impl MappedStageShape { + pub(super) fn slots(self) -> usize { + match self { + Self::Single16 => 16, + Self::Split8 => 8, + } + } +} +impl<'ctx> EphemeralRoutedOwner<'ctx> { + pub(in crate::qwen_forward) fn new_mapped( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + shape: MappedStageShape, + ) -> Result { + let mapped = MappedStage::new(binding, context, maximum, shape)?; + Ok(Self { + binding: binding.identity(), + context, + maximum, + slots: std::array::from_fn(|_| empty_slot()), + failed: false, + mapped: Some(mapped), + #[cfg(test)] + completed_loans: 0, + }) + } + pub(in crate::qwen_forward) fn slot_count(&self) -> usize { + self.mapped.as_ref().map_or(SLOTS, |owner| owner.slots.len()) + } + pub(in crate::qwen_forward) fn uses_mapped(&self) -> bool { + self.mapped.is_some() + } + pub(in crate::qwen_forward) fn mapped_eligible( + &self, + binding: &ModelBinding, + source: &MoeRoutedSourceScope<'_, '_>, + member: usize, + ) -> Result { + self.validate(binding, self.context)?; + let Some(mapped) = &self.mapped else { + return Ok(false); + }; + Self::keys(binding, source, member)?; + let spans = [ + source.bank_span(member, ROLES[0]).map_err(binding_error)?, + source.bank_span(member, ROLES[1]).map_err(binding_error)?, + source.bank_span(member, ROLES[2]).map_err(binding_error)?, + ]; + Ok(mapped.bank.as_ref().is_some_and(|bank| bank.eligible(&spans))) + } +} +impl<'ctx> MappedStage<'ctx> { + pub(super) fn new( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + shape: MappedStageShape, + ) -> Result { + for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) { + if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) { + return Err(Error::InvalidDimension); + } + } + let count = shape.slots(); + let extra = maximum + .into_iter() + .try_fold(36usize, |n, b| n.checked_add(b).ok_or(Error::Overflow))? + .checked_mul(count) + .ok_or(Error::Overflow)?; + EphemeralRoutedOwner::room(context, extra)?; + let (lease, members) = binding.retained_expert_bank_members().map_err(binding_error)?; + let bank = Rc::new(context.mapped_expert_bank(lease, members).map_err(driver_error)?); + let mut owner = Self { binding: binding.identity(), context, maximum, bank: Some(bank), slots: Vec::new() }; + owner.slots.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + let operation = (|| { + for _ in 0..count { + let mut buffers = std::array::from_fn(|_| None); + for (buffer, bytes) in buffers.iter_mut().zip(maximum) { + *buffer = Some(context.allocate(bytes).map_err(driver_error)?); + } + let scratch = context.mapped_expert_copy_scratch().map_err(driver_error)?; + owner.slots.push(MappedSlot::Idle { buffers, scratch: Some(scratch) }); + } + EphemeralRoutedOwner::room(context, 0)?; + if owner.metadata_bytes() > HOST_LIMIT { + return Err(Error::InputAllocation); } - EphemeralRoutedOwner::room(context,0)?; - if owner.metadata_bytes()>HOST_LIMIT{return Err(Error::InputAllocation);} Ok(()) })(); - if let Err(primary)=operation{let _=owner.release_all();return Err(primary);} Ok(owner) - } - pub(super) fn metadata_bytes(&self)->usize{std::mem::size_of::()+self.slots.capacity()*std::mem::size_of::>() - +self.bank.as_ref().map_or(0,|bank|bank.metadata_bytes()+bank.page_overhead_bytes())+self.slots.iter().map(|slot|match slot{ - MappedSlot::Idle{scratch,..}|MappedSlot::Completed{scratch,..}=>scratch.as_ref().map_or(0,MappedExpertCopyScratch::metadata_bytes),_=>0}).sum::()} - pub(super) fn allocated_bytes(&self)->usize{ - if self.context.is_poisoned(){return self.context.allocated_bytes();} - self.slots.iter().map(|slot|match slot{ - MappedSlot::Idle{buffers,scratch}|MappedSlot::Completed{buffers,scratch,..}=>buffers.iter().flatten().map(DeviceBuffer::len).sum::()+scratch.as_ref().map_or(0,MappedExpertCopyScratch::allocated_bytes), - MappedSlot::Pending{keys,..}=>keys.iter().map(|key|key.bytes).sum::()+36,MappedSlot::InUse=>0}).sum() - } - pub(super) fn validate(&self,binding:&ModelBinding,slot:usize)->Result<()>{ - if self.context.is_poisoned(){return Err(Error::CudaExecution);} - if slot>=self.slots.len() || !self.binding.matches(&binding.identity()) || self.bank.is_none(){return Err(Error::IdentityMismatch);}Ok(()) - } - pub(super) fn stage(&mut self,slot:usize,binding:&ModelBinding,source:&mut MoeRoutedSourceScope<'_, '_>,member:usize)->Result<()>{ - self.validate(binding,slot)?; - let keys=EphemeralRoutedOwner::keys(binding,source,member)?; - if !matches!(self.slots[slot],MappedSlot::Idle{..}){return Err(Error::IdentityMismatch);} - if keys.iter().zip(self.maximum).any(|(key,max)|key.bytes>max){return Err(Error::InputAllocation);} - // Same exact Gate then Up then Down full encoded finite precedence. - let spans=[source.mapped_span(member,ROLES[0]).map_err(binding_error)?,source.mapped_span(member,ROLES[1]).map_err(binding_error)?,source.mapped_span(member,ROLES[2]).map_err(binding_error)?]; - let bank=self.bank.as_ref().ok_or(Error::IdentityMismatch)?; - if !bank.eligible(&spans){return Err(Error::IdentityMismatch);} - source.finish().map_err(binding_error)?; - let prior=std::mem::replace(&mut self.slots[slot],MappedSlot::InUse); - let MappedSlot::Idle{mut buffers,mut scratch}=prior else{return Err(Error::IdentityMismatch);}; - for (buffer,key) in buffers.iter_mut().zip(&keys){ - if buffer.as_ref().is_some_and(|b|b.len()!=key.bytes){buffer.take().ok_or(Error::IdentityMismatch)?.release().map_err(driver_error)?;} + if let Err(primary) = operation { + let _ = owner.release_all(); + return Err(primary); } - let extra=buffers.iter().zip(&keys).filter(|(b,_)|b.is_none()).try_fold(0usize,|n,(_,key)|n.checked_add(key.bytes).ok_or(Error::Overflow))?; - EphemeralRoutedOwner::room(self.context,extra)?; - for (buffer,key) in buffers.iter_mut().zip(&keys){if buffer.is_none(){*buffer=Some(self.context.allocate(key.bytes).map_err(driver_error)?);}} - let whole=[buffers[0].take().ok_or(Error::IdentityMismatch)?,buffers[1].take().ok_or(Error::IdentityMismatch)?,buffers[2].take().ok_or(Error::IdentityMismatch)?]; - let copy=bank.copy_triplet(spans,whole,scratch.take().ok_or(Error::IdentityMismatch)?).map_err(driver_error)?; - self.slots[slot]=MappedSlot::Pending{keys,copy};Ok(()) + Ok(owner) } - pub(super) fn wait(&mut self,slot:usize,binding:&ModelBinding)->Result<()>{ - self.validate(binding,slot)?; - if matches!(self.slots[slot],MappedSlot::Completed{..}){return Ok(());} - let prior=std::mem::replace(&mut self.slots[slot],MappedSlot::InUse); - let MappedSlot::Pending{keys,copy}=prior else{return Err(Error::IdentityMismatch);}; - let (whole,scratch)=copy.wait().map_err(driver_error)?.into_parts(); - if whole.iter().zip(&keys).any(|(b,key)|b.len()!=key.bytes){return Err(Error::IdentityMismatch);} - self.slots[slot]=MappedSlot::Completed{keys,buffers:whole.map(Some),scratch:Some(scratch)};Ok(()) + pub(super) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + self.slots.capacity() * std::mem::size_of::>() + + self.bank.as_ref().map_or(0, |bank| bank.metadata_bytes() + bank.page_overhead_bytes()) + + self + .slots + .iter() + .map(|slot| match slot { + MappedSlot::Idle { scratch, .. } | MappedSlot::Completed { scratch, .. } => { + scratch.as_ref().map_or(0, MappedExpertCopyScratch::metadata_bytes) + } + _ => 0, + }) + .sum::() } - pub(super) fn with_triplet<'source,'group,T>(&mut self,slot:usize,binding:&ModelBinding,source:&mut MoeRoutedSourceScope<'source,'group>,member:usize, - consume:impl FnOnce([&DeviceBuffer<'ctx>;3],[MoeWeightDescriptor;3],&mut MoeRoutedSourceScope<'source,'group>)->Result)->Result{ - self.validate(binding,slot)?; - let fresh=EphemeralRoutedOwner::keys(binding,source,member)?; - let MappedSlot::Completed{keys,..}=&self.slots[slot] else{return Err(Error::IdentityMismatch);}; - if *keys!=fresh{return Err(Error::IdentityMismatch);} - let prior=std::mem::replace(&mut self.slots[slot],MappedSlot::InUse); - let MappedSlot::Completed{keys,buffers,scratch}=prior else{return Err(Error::IdentityMismatch);}; - let result=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||{ - consume([buffers[0].as_ref().ok_or(Error::IdentityMismatch)?,buffers[1].as_ref().ok_or(Error::IdentityMismatch)?,buffers[2].as_ref().ok_or(Error::IdentityMismatch)?],keys,source) - })); - self.slots[slot]=MappedSlot::Idle{buffers,scratch}; - match result{Ok(value)=>{let value=value?;if self.context.is_poisoned(){return Err(Error::CudaExecution);}Ok(value)},Err(primary)=>{let _=self.release_all();std::panic::resume_unwind(primary)}} + pub(super) fn allocated_bytes(&self) -> usize { + if self.context.is_poisoned() { + return self.context.allocated_bytes(); + } + self.slots + .iter() + .map(|slot| match slot { + MappedSlot::Idle { buffers, scratch } | MappedSlot::Completed { buffers, scratch, .. } => { + buffers.iter().flatten().map(DeviceBuffer::len).sum::() + + scratch.as_ref().map_or(0, MappedExpertCopyScratch::allocated_bytes) + } + MappedSlot::Pending { keys, .. } => keys.iter().map(|key| key.bytes).sum::() + 36, + MappedSlot::InUse => 0, + }) + .sum() } - pub(super) fn drain(&mut self)->Result<()>{ - for n in 0..self.slots.len(){ - if matches!(self.slots[n],MappedSlot::Pending{..}){ - let prior=std::mem::replace(&mut self.slots[n],MappedSlot::InUse); - let MappedSlot::Pending{keys,copy}=prior else{return Err(Error::IdentityMismatch);}; - let (whole,scratch)=copy.wait().map_err(driver_error)?.into_parts(); - if whole.iter().zip(&keys).any(|(b,key)|b.len()!=key.bytes){return Err(Error::IdentityMismatch);} - self.slots[n]=MappedSlot::Idle{buffers:whole.map(Some),scratch:Some(scratch)}; - } else if matches!(self.slots[n],MappedSlot::Completed{..}){ - let prior=std::mem::replace(&mut self.slots[n],MappedSlot::InUse); - let MappedSlot::Completed{buffers,scratch,..}=prior else{return Err(Error::IdentityMismatch);}; - self.slots[n]=MappedSlot::Idle{buffers,scratch}; - } else if matches!(self.slots[n],MappedSlot::InUse){return Err(Error::IdentityMismatch);} - }Ok(()) + pub(super) fn validate(&self, binding: &ModelBinding, slot: usize) -> Result<()> { + if self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if slot >= self.slots.len() || !self.binding.matches(&binding.identity()) || self.bank.is_none() { + return Err(Error::IdentityMismatch); + } + Ok(()) } - pub(super) fn release_all(&mut self)->Result<()>{ - let mut result=Ok(()); - for slot in &mut self.slots{ - let prior=std::mem::replace(slot,MappedSlot::InUse); - match prior{ - MappedSlot::Idle{mut buffers,scratch}|MappedSlot::Completed{mut buffers,scratch,..}=>{ - result=combine(result,close_buffers(&mut buffers)); - if let Some(scratch)=scratch{result=combine(result,scratch.close().map_err(driver_error));} - },MappedSlot::Pending{copy,..}=>result=combine(result,copy.close().map_err(driver_error)),MappedSlot::InUse=>{} + pub(super) fn stage( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'_, '_>, + member: usize, + ) -> Result<()> { + self.validate(binding, slot)?; + let keys = EphemeralRoutedOwner::keys(binding, source, member)?; + if !matches!(self.slots[slot], MappedSlot::Idle { .. }) { + return Err(Error::IdentityMismatch); + } + if keys.iter().zip(self.maximum).any(|(key, max)| key.bytes > max) { + return Err(Error::InputAllocation); + } + // Same exact Gate then Up then Down full encoded finite precedence. + let spans = [ + source.mapped_span(member, ROLES[0]).map_err(binding_error)?, + source.mapped_span(member, ROLES[1]).map_err(binding_error)?, + source.mapped_span(member, ROLES[2]).map_err(binding_error)?, + ]; + let bank = self.bank.as_ref().ok_or(Error::IdentityMismatch)?; + if !bank.eligible(&spans) { + return Err(Error::IdentityMismatch); + } + source.finish().map_err(binding_error)?; + let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse); + let MappedSlot::Idle { mut buffers, mut scratch } = prior else { + return Err(Error::IdentityMismatch); + }; + for (buffer, key) in buffers.iter_mut().zip(&keys) { + if buffer.as_ref().is_some_and(|b| b.len() != key.bytes) { + buffer.take().ok_or(Error::IdentityMismatch)?.release().map_err(driver_error)?; + } + } + let extra = buffers + .iter() + .zip(&keys) + .filter(|(b, _)| b.is_none()) + .try_fold(0usize, |n, (_, key)| n.checked_add(key.bytes).ok_or(Error::Overflow))?; + EphemeralRoutedOwner::room(self.context, extra)?; + for (buffer, key) in buffers.iter_mut().zip(&keys) { + if buffer.is_none() { + *buffer = Some(self.context.allocate(key.bytes).map_err(driver_error)?); + } + } + let whole = [ + buffers[0].take().ok_or(Error::IdentityMismatch)?, + buffers[1].take().ok_or(Error::IdentityMismatch)?, + buffers[2].take().ok_or(Error::IdentityMismatch)?, + ]; + let copy = + bank.copy_triplet(spans, whole, scratch.take().ok_or(Error::IdentityMismatch)?).map_err(driver_error)?; + self.slots[slot] = MappedSlot::Pending { keys, copy }; + Ok(()) + } + pub(super) fn wait(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> { + self.validate(binding, slot)?; + if matches!(self.slots[slot], MappedSlot::Completed { .. }) { + return Ok(()); + } + let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse); + let MappedSlot::Pending { keys, copy } = prior else { + return Err(Error::IdentityMismatch); + }; + let (whole, scratch) = copy.wait().map_err(driver_error)?.into_parts(); + if whole.iter().zip(&keys).any(|(b, key)| b.len() != key.bytes) { + return Err(Error::IdentityMismatch); + } + self.slots[slot] = MappedSlot::Completed { keys, buffers: whole.map(Some), scratch: Some(scratch) }; + Ok(()) + } + pub(super) fn with_triplet<'source, 'group, T>( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'source, 'group>, + member: usize, + consume: impl FnOnce( + [&DeviceBuffer<'ctx>; 3], + [MoeWeightDescriptor; 3], + &mut MoeRoutedSourceScope<'source, 'group>, + ) -> Result, + ) -> Result { + self.validate(binding, slot)?; + let fresh = EphemeralRoutedOwner::keys(binding, source, member)?; + let MappedSlot::Completed { keys, .. } = &self.slots[slot] else { + return Err(Error::IdentityMismatch); + }; + if *keys != fresh { + return Err(Error::IdentityMismatch); + } + let prior = std::mem::replace(&mut self.slots[slot], MappedSlot::InUse); + let MappedSlot::Completed { keys, buffers, scratch } = prior else { + return Err(Error::IdentityMismatch); + }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + consume( + [ + buffers[0].as_ref().ok_or(Error::IdentityMismatch)?, + buffers[1].as_ref().ok_or(Error::IdentityMismatch)?, + buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, + ], + keys, + source, + ) + })); + self.slots[slot] = MappedSlot::Idle { buffers, scratch }; + match result { + Ok(value) => { + let value = value?; + if self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + Ok(value) + } + Err(primary) => { + let _ = self.release_all(); + std::panic::resume_unwind(primary) + } + } + } + pub(super) fn drain(&mut self) -> Result<()> { + for n in 0..self.slots.len() { + if matches!(self.slots[n], MappedSlot::Pending { .. }) { + let prior = std::mem::replace(&mut self.slots[n], MappedSlot::InUse); + let MappedSlot::Pending { keys, copy } = prior else { + return Err(Error::IdentityMismatch); + }; + let (whole, scratch) = copy.wait().map_err(driver_error)?.into_parts(); + if whole.iter().zip(&keys).any(|(b, key)| b.len() != key.bytes) { + return Err(Error::IdentityMismatch); + } + self.slots[n] = MappedSlot::Idle { buffers: whole.map(Some), scratch: Some(scratch) }; + } else if matches!(self.slots[n], MappedSlot::Completed { .. }) { + let prior = std::mem::replace(&mut self.slots[n], MappedSlot::InUse); + let MappedSlot::Completed { buffers, scratch, .. } = prior else { + return Err(Error::IdentityMismatch); + }; + self.slots[n] = MappedSlot::Idle { buffers, scratch }; + } else if matches!(self.slots[n], MappedSlot::InUse) { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } + pub(super) fn release_all(&mut self) -> Result<()> { + let mut result = Ok(()); + for slot in &mut self.slots { + let prior = std::mem::replace(slot, MappedSlot::InUse); + match prior { + MappedSlot::Idle { mut buffers, scratch } | MappedSlot::Completed { mut buffers, scratch, .. } => { + result = combine(result, close_buffers(&mut buffers)); + if let Some(scratch) = scratch { + result = combine(result, scratch.close().map_err(driver_error)); + } + } + MappedSlot::Pending { copy, .. } => result = combine(result, copy.close().map_err(driver_error)), + MappedSlot::InUse => {} + } + } + if let Some(bank) = self.bank.take() { + match Rc::try_unwrap(bank) { + Ok(bank) => result = combine(result, bank.close().map_err(driver_error)), + Err(bank) => { + drop(bank); + result = combine(result, Err(Error::CudaExecution)); + } } } - if let Some(bank)=self.bank.take(){match Rc::try_unwrap(bank){Ok(bank)=>result=combine(result,bank.close().map_err(driver_error)),Err(bank)=>{drop(bank);result=combine(result,Err(Error::CudaExecution));}}} result } } -impl Drop for MappedStage<'_>{fn drop(&mut self){let _=self.release_all();}} +impl Drop for MappedStage<'_> { + fn drop(&mut self) { + let _ = self.release_all(); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner.rs index eecb38f9..05ee938d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner.rs @@ -3,353 +3,9 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> EphemeralRoutedOwner<'ctx> { - /// Maximum is a sizing prediction from Root's actual 48 descriptor triplets, - /// never a source capability. All six WHOLE allocations exist before return. - /// PrefixPlan must observe their actual Context charge; no prediction credit. - pub(in crate::qwen_forward) fn new( - binding: &ModelBinding, context: &'ctx Context<'ctx>, maximum: [usize; 3], - ) -> Result { - for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) { - if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) { return Err(Error::InvalidDimension); } - } - let total = maximum.into_iter().try_fold(0usize, |n, b| n.checked_add(b).ok_or(Error::Overflow))? - .checked_mul(SLOTS).ok_or(Error::Overflow)?; - Self::room(context, total)?; - let mut owner = Self { binding: binding.identity(), context, maximum, - slots: std::array::from_fn(|_| empty_slot()), failed: false, mapped: None, - #[cfg(test)] - completed_loans: 0, - }; - let allocation = (|| -> Result<()> { - for slot in &mut owner.slots { - let Slot::Idle { buffers, .. } = slot else { return Err(Error::IdentityMismatch); }; - for (destination, &bytes) in buffers.iter_mut().zip(&maximum) { - *destination = Some(context.allocate(bytes).map_err(driver_error)?); - } - } - Self::room(context, 0) - })(); - match allocation { Ok(()) => Ok(owner), Err(primary) => owner.fail(primary) } - } - - pub(super) fn room(context: &Context<'_>, extra: usize) -> Result<()> { - let needed = extra.checked_add(RESERVE).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(needed).ok_or(Error::Overflow)? > context.budget_bytes() { - return Err(Error::InputAllocation); - } - if context.memory_info().map_err(driver_error)?.0 < needed { return Err(Error::InputAllocation); } - Ok(()) - } - pub(super) fn validate_slot(&self, binding: &ModelBinding, slot: usize) -> Result<()> { - if self.failed || self.context.is_poisoned() { return Err(Error::CudaExecution); } - if slot >= self.slot_count() || !self.binding.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } - Ok(()) - } - pub(in crate::qwen_forward) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { - self.validate_slot(binding, 0)?; - if !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } - Ok(()) - } - pub(in crate::qwen_forward) fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - #[cfg(test)] - pub(in crate::qwen_forward) fn completed_loans(&self) -> u64 { self.completed_loans } - pub(super) fn keys(binding: &ModelBinding, source: &MoeRoutedSourceScope<'_, '_>, member: usize) - -> Result<[MoeWeightDescriptor; 3]> - { - source.validate_binding(binding).map_err(binding_error)?; - let keys = [source.descriptor(member, ROLES[0]).map_err(binding_error)?, - source.descriptor(member, ROLES[1]).map_err(binding_error)?, - source.descriptor(member, ROLES[2]).map_err(binding_error)?]; - for (role, key) in keys.iter().enumerate() { - let shape = if role == 2 { (2560, 640) } else { (640, 2560) }; - if key.layer >= 48 || key.layer != keys[0].layer || key.expert.is_none() - || key.expert != keys[0].expert || key.expert.is_some_and(|x| x >= 512) - || key.role as usize != role || (key.rows, key.columns) != shape - || key.bytes == 0 || !key.bytes.is_multiple_of(256) - || if role == 2 { !matches!(key.raw_kind, 20 | 42) } - else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) } - { return Err(Error::IdentityMismatch); } - } - Ok(keys) - } - pub(super) fn host_bytes(&self) -> Result { - self.slots.iter().try_fold(std::mem::size_of::(), |n, slot| { - n.checked_add(match slot { Slot::Pending { host_bytes, .. } => *host_bytes, _ => 0 }) - .ok_or(Error::Overflow) - }) - } - pub(in crate::qwen_forward) fn metadata_bytes(&self) -> usize { std::mem::size_of::() + self.mapped.as_ref().map_or(0,MappedStage::metadata_bytes) } - pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { - if let Some(mapped) = &self.mapped { return mapped.allocated_bytes(); } - // Under poison, private driver retention may no longer expose buffers. - // Preserve the actual whole Context charge as a conservative bound; - // never claim zero cleanup from an empty opaque pending state. - if self.context.is_poisoned() { return self.context.allocated_bytes(); } - // Pending destinations are opaque. Their exact key extents stay charged. - self.slots.iter().map(|slot| match slot { - Slot::Pending { keys, .. } => keys.iter().map(|key| key.bytes).sum(), - Slot::Idle { buffers, .. } | Slot::Completed { buffers, .. } => - buffers.iter().flatten().map(DeviceBuffer::len).sum(), - Slot::InUse => 0, - }).sum() - } - - /// Call inside exactly ONE genuine source callback. It finishes that source - /// before Box->Vec detach/enqueue; caller must return, releasing artifact - /// RefMut, BEFORE starting CPU preparation for another group. - pub(in crate::qwen_forward) fn stage( - &mut self, slot: usize, binding: &ModelBinding, - source: &mut MoeRoutedSourceScope<'_, '_>, member: usize, - ) -> Result<()> { - let result = if let Some(mapped) = &mut self.mapped { - mapped.stage(slot,binding,source,member) - } else { self.stage_inner(slot, binding, source, member) }; - match result { Ok(()) => Ok(()), Err(primary) => self.fail(primary) } - } - pub(super) fn stage_inner(&mut self, slot: usize, binding: &ModelBinding, - source: &mut MoeRoutedSourceScope<'_, '_>, member: usize) -> Result<()> - { - self.validate_slot(binding, slot)?; - let keys = Self::keys(binding, source, member)?; - for (key, &maximum) in keys.iter().zip(&self.maximum) { - if key.bytes > maximum { return Err(Error::InputAllocation); } - } - if !matches!(self.slots[slot], Slot::Idle { .. }) { return Err(Error::IdentityMismatch); } - let raw = keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?; - // The complete current role Boxes, any transient read/copy and all old - // pending Vec capacities coexist. No assumption that payload==capacity. - let fixed_preparation = std::mem::size_of::<[Option; 3]>() - + std::mem::size_of::<[Option>; 3]>() - + std::mem::size_of::, Vec)>>() - + std::mem::size_of::<[MoeWeightDescriptor; 3]>(); - let pair_metadata = 3usize.checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec)>()) - .and_then(|n| n.checked_add(fixed_preparation)).ok_or(Error::Overflow)?; - let peak = self.host_bytes()?.checked_add(raw.checked_mul(2).ok_or(Error::Overflow)?) - .and_then(|n| n.checked_add(pair_metadata)).ok_or(Error::Overflow)?; - if peak > HOST_LIMIT { return Err(Error::InputAllocation); } - let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); - let Slot::Idle { layer: _, mut buffers } = previous else { return Err(Error::IdentityMismatch); }; - let exact = buffers.iter().zip(&keys).all(|(b, k)| b.as_ref().is_some_and(|b| b.len() == k.bytes)); - if !exact { - close_buffers(&mut buffers)?; - } - // Exact-size whole owners may be reused after complete overwrite even across layers; never pass padded views. - let extra = buffers.iter().zip(&keys).try_fold(0usize, |n, (buffer, key)| { - n.checked_add(if buffer.is_none() { key.bytes } else { 0 }).ok_or(Error::Overflow) - })?; - Self::room(self.context, extra)?; - for (buffer, key) in buffers.iter_mut().zip(&keys) { - if buffer.is_none() { *buffer = Some(self.context.allocate(key.bytes).map_err(driver_error)?); } - } - // Install actual owners so any subsequent refusal drains both slots. - self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers }; - let mut blocks = std::array::from_fn::<_, 3, _>(|_| None); - let mut retained = self.host_bytes()?.checked_add(pair_metadata).ok_or(Error::Overflow)?; - for (index, role) in ROLES.into_iter().enumerate() { - let block = source.block(member, role).map_err(binding_error)?; - if block.bytes().len() != keys[index].bytes || block.rows() != keys[index].rows - || block.columns() != keys[index].columns { return Err(Error::IdentityMismatch); } - retained = retained.checked_add(block.bytes().len()).ok_or(Error::Overflow)?; - if retained > HOST_LIMIT { return Err(Error::InputAllocation); } - blocks[index] = Some(block); - } - source.finish().map_err(binding_error)?; - let mut pairs = Vec::new(); - pairs.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; - let actual_metadata = pairs.capacity().checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec)>()) - .and_then(|n| n.checked_add(fixed_preparation)).ok_or(Error::Overflow)?; - let mut host_bytes = actual_metadata; - let mut bytes: [Option>; 3] = std::array::from_fn(|_| None); - for (destination, block) in bytes.iter_mut().zip(&mut blocks) { - let payload = block.take().ok_or(Error::IdentityMismatch)?.into_bytes().into_vec(); - host_bytes = host_bytes.checked_add(payload.capacity()).ok_or(Error::Overflow)?; - *destination = Some(payload); - } - if self.host_bytes()?.checked_add(host_bytes).ok_or(Error::Overflow)? > HOST_LIMIT { - return Err(Error::InputAllocation); - } - let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); - let Slot::Idle { mut buffers, .. } = previous else { return Err(Error::IdentityMismatch); }; - for (buffer, payload) in buffers.iter_mut().zip(&mut bytes) { - pairs.push((buffer.take().ok_or(Error::IdentityMismatch)?, payload.take().ok_or(Error::IdentityMismatch)?)); - } - let copy = self.context.copy_owned_batch_async(pairs).map_err(driver_error)?; - self.slots[slot] = Slot::Pending { keys, copy, host_bytes }; - Ok(()) - } - - pub(in crate::qwen_forward) fn wait(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> { - let result = if let Some(mapped)=&mut self.mapped {mapped.wait(slot,binding)} - else {self.complete(slot, binding, true)}; - match result { Ok(()) => Ok(()), Err(primary) => self.fail(primary) } - } - /// Polling never exposes destinations; Pending remains the same real owner. - #[allow(dead_code)] // Scheduler currently uses mandatory actual wait. - pub(in crate::qwen_forward) fn poll(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> { - let result = if let Some(mapped)=&mut self.mapped {mapped.wait(slot,binding)} - else {self.complete(slot, binding, false)}; - match result { Ok(()) => Ok(()), Err(primary) => self.fail(primary) } - } - pub(super) fn complete(&mut self, slot: usize, binding: &ModelBinding, wait: bool) -> Result<()> { - self.validate_slot(binding, slot)?; - if matches!(self.slots[slot], Slot::Completed { .. }) { return Ok(()); } - if !matches!(self.slots[slot], Slot::Pending { .. }) { return Err(Error::IdentityMismatch); } - let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); - let Slot::Pending { keys, copy, host_bytes } = previous else { return Err(Error::IdentityMismatch); }; - let observed = if wait { OwnedCopyPoll::Complete(copy.wait().map_err(driver_error)?) } - else { copy.poll().map_err(driver_error)? }; - match observed { - OwnedCopyPoll::Pending(copy) => self.slots[slot] = Slot::Pending { keys, copy, host_bytes }, - OwnedCopyPoll::Complete(receipt) => { - if receipt.len() != 3 { return Err(Error::IdentityMismatch); } - let mut pairs = receipt.into_pairs(); - let mut buffers = std::array::from_fn(|_| None); - let mut validation = Ok(()); - for (index, destination) in buffers.iter_mut().enumerate() { - if let Some((buffer, payload)) = pairs[index].take() { - if buffer.len() != keys[index].bytes || payload.len() != keys[index].bytes { - validation = Err(Error::IdentityMismatch); - } - *destination = Some(buffer); - drop(payload); // Actual event + unregister completed. - } else { validation = Err(Error::IdentityMismatch); } - } - if pairs.iter().any(Option::is_some) { validation = Err(Error::IdentityMismatch); } - self.slots[slot] = Slot::Completed { keys, buffers }; - validation?; - } - } - Ok(()) - } - - /// Fresh source equality and explicit callback finish are required even though bytes completed. - /// Caller retains real current-row/txn/origin/cancel/packet checks; these - /// buffers are temporary execution owners, never adaptive cache hits. - pub(in crate::qwen_forward) fn with_triplet<'source, 'group, T>( - &mut self, slot: usize, binding: &ModelBinding, - source: &mut MoeRoutedSourceScope<'source, 'group>, member: usize, - cancel_observed: &Cell, - consume: impl FnOnce([&DeviceBuffer<'ctx>; 3], [MoeWeightDescriptor; 3], &mut MoeRoutedSourceScope<'source, 'group>) -> Result, - ) -> Result { - let result = if let Some(mapped)=&mut self.mapped { - mapped.with_triplet(slot,binding,source,member,consume) - } else {self.with_triplet_inner(slot, binding, source, member, consume)}; - #[cfg(test)] - if self.mapped.is_some() && result.is_ok() { - self.completed_loans=self.completed_loans.checked_add(1).ok_or(Error::Overflow)?; - } - match result { - Ok(value) => Ok(value), - // Healthy cancellation: the loaned slot is already back to Idle with its whole - // buffers (the callback only read them). Drain BOTH genuine event copies so - // the other slot can be reused, keep the owner healthy and return the cancel - // error first. A drain failure still fails the owner (drain -> fail). - Err(primary) if self.is_healthy_cancel(&primary, cancel_observed.get()) => { - combine(Err(primary), self.drain()) - } - Err(primary) => self.fail(primary), - } - } - /// Only a cancellation the caller actually observed through its cancelled closure during this - /// loan, with the executor's cancel code, on an owner that is neither failed nor under a - /// poisoned Context. Every other callback error (identity, finite, CUDA, binding) stays fatal. - pub(super) fn is_healthy_cancel(&self, error: &Error, observed: bool) -> bool { - healthy_cancel(error, observed, self.failed, self.context.is_poisoned()) - } - pub(super) fn with_triplet_inner<'source, 'group, T>(&mut self, slot: usize, binding: &ModelBinding, - source: &mut MoeRoutedSourceScope<'source, 'group>, member: usize, - consume: impl FnOnce([&DeviceBuffer<'ctx>; 3], [MoeWeightDescriptor; 3], &mut MoeRoutedSourceScope<'source, 'group>) -> Result) -> Result - { - self.validate_slot(binding, slot)?; - let fresh = Self::keys(binding, source, member)?; - let Slot::Completed { keys, .. } = &self.slots[slot] else { return Err(Error::IdentityMismatch); }; - if *keys != fresh { return Err(Error::IdentityMismatch); } - let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); - let Slot::Completed { keys, buffers } = previous else { return Err(Error::IdentityMismatch); }; - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let whole = [buffers[0].as_ref().ok_or(Error::IdentityMismatch)?, - buffers[1].as_ref().ok_or(Error::IdentityMismatch)?, - buffers[2].as_ref().ok_or(Error::IdentityMismatch)?]; - consume(whole, keys, source) - })); - // The caller explicitly finishes at its packet/current-row boundary. - // The enclosing genuine with_moe_routed_source rejects success without - // that finish and always attempts cleanup on an error. Do not finish - // twice or move the callback's source check past its coverage gate. - self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers }; - match result { - Ok(result) => { - let value = result?; - if self.context.is_poisoned() { return Err(Error::CudaExecution); } - #[cfg(test)] - { self.completed_loans = self.completed_loans.checked_add(1).ok_or(Error::Overflow)?; } - Ok(value) - } - Err(primary) => { - self.failed = true; - let _cleanup = self.release_all(); - std::panic::resume_unwind(primary) - } - } - } - pub(super) fn fail(&mut self, primary: Error) -> Result { - self.failed = true; - combine(Err(primary), self.release_all()) - } - /// Healthy cancellation/iteration drain waits BOTH actual events and discards - /// incoming expert keys/host payloads, retaining exact whole buffers for reuse. - /// Caller must drain real CPU work separately before starting another wave. - pub(in crate::qwen_forward) fn drain(&mut self) -> Result<()> { - if self.is_failed() { return combine(Err(Error::CudaExecution), self.release_all()); } - let result = self.drain_inner(); - match result { Ok(()) => Ok(()), Err(primary) => self.fail(primary) } - } - pub(super) fn drain_inner(&mut self) -> Result<()> { - if let Some(mapped)=&mut self.mapped {return mapped.drain();} - for index in 0..SLOTS { - let actual = std::mem::replace(&mut self.slots[index], Slot::InUse); - let (layer, buffers) = match actual { - Slot::Idle { layer, buffers } => (layer, buffers), - Slot::Completed { keys, buffers } => (Some(keys[0].layer), buffers), - Slot::Pending { keys, copy, .. } => { - let receipt = copy.wait().map_err(driver_error)?; - if receipt.len() != 3 { return Err(Error::IdentityMismatch); } - let mut pairs = receipt.into_pairs(); - let mut buffers = std::array::from_fn(|_| None); - let mut valid = true; - for (role, buffer) in buffers.iter_mut().enumerate() { - if let Some((device, source)) = pairs[role].take() { - valid &= device.len() == keys[role].bytes && source.len() == keys[role].bytes; - *buffer = Some(device); - drop(source); - } else { valid = false; } - } - valid &= !pairs.iter().any(Option::is_some); - self.slots[index] = Slot::Idle { layer: Some(keys[0].layer), buffers }; - if !valid { return Err(Error::IdentityMismatch); } - continue; - } - Slot::InUse => return Err(Error::IdentityMismatch), - }; - self.slots[index] = Slot::Idle { layer, buffers }; - } - Ok(()) - } - /// Close, errors and Drop attempt every real release, including both pending - /// event drains. Poison retains unknown native owners and their real charges. - pub(super) fn release_all(&mut self) -> Result<()> { - let mut result = self.mapped.as_mut().map_or(Ok(()),MappedStage::release_all); - for slot in &mut self.slots { - let actual = std::mem::replace(slot, empty_slot()); - result = combine(result, close_slot(actual)); - } - if self.context.is_poisoned() { result = combine(result, Err(Error::CudaExecution)); } - if result.is_err() { self.failed = true; } - result - } - pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { self.release_all() } -} +#[path = "impl_ephemeralroutedowner/impl_ephemeralroutedowner_2.rs"] +mod impl_ephemeralroutedowner_2; +#[path = "impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs"] +mod impl_ephemeralroutedowner_2_2; +#[path = "impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs"] +mod impl_ephemeralroutedowner_3; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2.rs new file mode 100644 index 00000000..663849c4 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2.rs @@ -0,0 +1,170 @@ +//! Moved out of the parent module by STRA-338: impl EphemeralRoutedOwner. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> EphemeralRoutedOwner<'ctx> { + /// Maximum is a sizing prediction from Root's actual 48 descriptor triplets, + /// never a source capability. All six WHOLE allocations exist before return. + /// PrefixPlan must observe their actual Context charge; no prediction credit. + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + maximum: [usize; 3], + ) -> Result { + for (bytes, ceiling) in maximum.into_iter().zip(CLOSED_MAXIMUM) { + if bytes == 0 || bytes > ceiling || !bytes.is_multiple_of(256) { + return Err(Error::InvalidDimension); + } + } + let total = maximum + .into_iter() + .try_fold(0usize, |n, b| n.checked_add(b).ok_or(Error::Overflow))? + .checked_mul(SLOTS) + .ok_or(Error::Overflow)?; + Self::room(context, total)?; + let mut owner = Self { + binding: binding.identity(), + context, + maximum, + slots: std::array::from_fn(|_| empty_slot()), + failed: false, + mapped: None, + #[cfg(test)] + completed_loans: 0, + }; + let allocation = (|| -> Result<()> { + for slot in &mut owner.slots { + let Slot::Idle { buffers, .. } = slot else { + return Err(Error::IdentityMismatch); + }; + for (destination, &bytes) in buffers.iter_mut().zip(&maximum) { + *destination = Some(context.allocate(bytes).map_err(driver_error)?); + } + } + Self::room(context, 0) + })(); + match allocation { + Ok(()) => Ok(owner), + Err(primary) => owner.fail(primary), + } + } + + pub(in super::super) fn room(context: &Context<'_>, extra: usize) -> Result<()> { + let needed = extra.checked_add(RESERVE).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(needed).ok_or(Error::Overflow)? > context.budget_bytes() { + return Err(Error::InputAllocation); + } + if context.memory_info().map_err(driver_error)?.0 < needed { + return Err(Error::InputAllocation); + } + Ok(()) + } + pub(in super::super) fn validate_slot(&self, binding: &ModelBinding, slot: usize) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if slot >= self.slot_count() || !self.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { + self.validate_slot(binding, 0)?; + if !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + #[cfg(test)] + pub(in crate::qwen_forward) fn completed_loans(&self) -> u64 { + self.completed_loans + } + pub(in super::super) fn keys( + binding: &ModelBinding, + source: &MoeRoutedSourceScope<'_, '_>, + member: usize, + ) -> Result<[MoeWeightDescriptor; 3]> { + source.validate_binding(binding).map_err(binding_error)?; + let keys = [ + source.descriptor(member, ROLES[0]).map_err(binding_error)?, + source.descriptor(member, ROLES[1]).map_err(binding_error)?, + source.descriptor(member, ROLES[2]).map_err(binding_error)?, + ]; + for (role, key) in keys.iter().enumerate() { + let shape = if role == 2 { (2560, 640) } else { (640, 2560) }; + if key.layer >= 48 + || key.layer != keys[0].layer + || key.expert.is_none() + || key.expert != keys[0].expert + || key.expert.is_some_and(|x| x >= 512) + || key.role as usize != role + || (key.rows, key.columns) != shape + || key.bytes == 0 + || !key.bytes.is_multiple_of(256) + || if role == 2 { !matches!(key.raw_kind, 20 | 42) } else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) } + { + return Err(Error::IdentityMismatch); + } + } + Ok(keys) + } + pub(in super::super) fn host_bytes(&self) -> Result { + self.slots.iter().try_fold(std::mem::size_of::(), |n, slot| { + n.checked_add(match slot { + Slot::Pending { host_bytes, .. } => *host_bytes, + _ => 0, + }) + .ok_or(Error::Overflow) + }) + } + pub(in crate::qwen_forward) fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + self.mapped.as_ref().map_or(0, MappedStage::metadata_bytes) + } + pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { + if let Some(mapped) = &self.mapped { + return mapped.allocated_bytes(); + } + // Under poison, private driver retention may no longer expose buffers. + // Preserve the actual whole Context charge as a conservative bound; + // never claim zero cleanup from an empty opaque pending state. + if self.context.is_poisoned() { + return self.context.allocated_bytes(); + } + // Pending destinations are opaque. Their exact key extents stay charged. + self.slots + .iter() + .map(|slot| match slot { + Slot::Pending { keys, .. } => keys.iter().map(|key| key.bytes).sum(), + Slot::Idle { buffers, .. } | Slot::Completed { buffers, .. } => { + buffers.iter().flatten().map(DeviceBuffer::len).sum() + } + Slot::InUse => 0, + }) + .sum() + } + + /// Call inside exactly ONE genuine source callback. It finishes that source + /// before Box->Vec detach/enqueue; caller must return, releasing artifact + /// RefMut, BEFORE starting CPU preparation for another group. + pub(in crate::qwen_forward) fn stage( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'_, '_>, + member: usize, + ) -> Result<()> { + let result = if let Some(mapped) = &mut self.mapped { + mapped.stage(slot, binding, source, member) + } else { + self.stage_inner(slot, binding, source, member) + }; + match result { + Ok(()) => Ok(()), + Err(primary) => self.fail(primary), + } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs new file mode 100644 index 00000000..e8d5d598 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_2_2.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl EphemeralRoutedOwner (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> EphemeralRoutedOwner<'ctx> { + pub(in super::super) fn stage_inner( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'_, '_>, + member: usize, + ) -> Result<()> { + self.validate_slot(binding, slot)?; + let keys = Self::keys(binding, source, member)?; + for (key, &maximum) in keys.iter().zip(&self.maximum) { + if key.bytes > maximum { + return Err(Error::InputAllocation); + } + } + if !matches!(self.slots[slot], Slot::Idle { .. }) { + return Err(Error::IdentityMismatch); + } + let raw = keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?; + // The complete current role Boxes, any transient read/copy and all old + // pending Vec capacities coexist. No assumption that payload==capacity. + let fixed_preparation = std::mem::size_of::<[Option; 3]>() + + std::mem::size_of::<[Option>; 3]>() + + std::mem::size_of::, Vec)>>() + + std::mem::size_of::<[MoeWeightDescriptor; 3]>(); + let pair_metadata = 3usize + .checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec)>()) + .and_then(|n| n.checked_add(fixed_preparation)) + .ok_or(Error::Overflow)?; + let peak = self + .host_bytes()? + .checked_add(raw.checked_mul(2).ok_or(Error::Overflow)?) + .and_then(|n| n.checked_add(pair_metadata)) + .ok_or(Error::Overflow)?; + if peak > HOST_LIMIT { + return Err(Error::InputAllocation); + } + let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); + let Slot::Idle { layer: _, mut buffers } = previous else { + return Err(Error::IdentityMismatch); + }; + let exact = buffers.iter().zip(&keys).all(|(b, k)| b.as_ref().is_some_and(|b| b.len() == k.bytes)); + if !exact { + close_buffers(&mut buffers)?; + } + // Exact-size whole owners may be reused after complete overwrite even across layers; never pass padded views. + let extra = buffers.iter().zip(&keys).try_fold(0usize, |n, (buffer, key)| { + n.checked_add(if buffer.is_none() { key.bytes } else { 0 }).ok_or(Error::Overflow) + })?; + Self::room(self.context, extra)?; + for (buffer, key) in buffers.iter_mut().zip(&keys) { + if buffer.is_none() { + *buffer = Some(self.context.allocate(key.bytes).map_err(driver_error)?); + } + } + // Install actual owners so any subsequent refusal drains both slots. + self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers }; + let mut blocks = std::array::from_fn::<_, 3, _>(|_| None); + let mut retained = self.host_bytes()?.checked_add(pair_metadata).ok_or(Error::Overflow)?; + for (index, role) in ROLES.into_iter().enumerate() { + let block = source.block(member, role).map_err(binding_error)?; + if block.bytes().len() != keys[index].bytes + || block.rows() != keys[index].rows + || block.columns() != keys[index].columns + { + return Err(Error::IdentityMismatch); + } + retained = retained.checked_add(block.bytes().len()).ok_or(Error::Overflow)?; + if retained > HOST_LIMIT { + return Err(Error::InputAllocation); + } + blocks[index] = Some(block); + } + source.finish().map_err(binding_error)?; + let mut pairs = Vec::new(); + pairs.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + let actual_metadata = pairs + .capacity() + .checked_mul(std::mem::size_of::<(DeviceBuffer<'ctx>, Vec)>()) + .and_then(|n| n.checked_add(fixed_preparation)) + .ok_or(Error::Overflow)?; + let mut host_bytes = actual_metadata; + let mut bytes: [Option>; 3] = std::array::from_fn(|_| None); + for (destination, block) in bytes.iter_mut().zip(&mut blocks) { + let payload = block.take().ok_or(Error::IdentityMismatch)?.into_bytes().into_vec(); + host_bytes = host_bytes.checked_add(payload.capacity()).ok_or(Error::Overflow)?; + *destination = Some(payload); + } + if self.host_bytes()?.checked_add(host_bytes).ok_or(Error::Overflow)? > HOST_LIMIT { + return Err(Error::InputAllocation); + } + let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); + let Slot::Idle { mut buffers, .. } = previous else { + return Err(Error::IdentityMismatch); + }; + for (buffer, payload) in buffers.iter_mut().zip(&mut bytes) { + pairs.push((buffer.take().ok_or(Error::IdentityMismatch)?, payload.take().ok_or(Error::IdentityMismatch)?)); + } + let copy = self.context.copy_owned_batch_async(pairs).map_err(driver_error)?; + self.slots[slot] = Slot::Pending { keys, copy, host_bytes }; + Ok(()) + } + + pub(in crate::qwen_forward) fn wait(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> { + let result = if let Some(mapped) = &mut self.mapped { + mapped.wait(slot, binding) + } else { + self.complete(slot, binding, true) + }; + match result { + Ok(()) => Ok(()), + Err(primary) => self.fail(primary), + } + } + /// Polling never exposes destinations; Pending remains the same real owner. + #[allow(dead_code)] // Scheduler currently uses mandatory actual wait. + pub(in crate::qwen_forward) fn poll(&mut self, slot: usize, binding: &ModelBinding) -> Result<()> { + let result = if let Some(mapped) = &mut self.mapped { + mapped.wait(slot, binding) + } else { + self.complete(slot, binding, false) + }; + match result { + Ok(()) => Ok(()), + Err(primary) => self.fail(primary), + } + } + pub(in super::super) fn complete(&mut self, slot: usize, binding: &ModelBinding, wait: bool) -> Result<()> { + self.validate_slot(binding, slot)?; + if matches!(self.slots[slot], Slot::Completed { .. }) { + return Ok(()); + } + if !matches!(self.slots[slot], Slot::Pending { .. }) { + return Err(Error::IdentityMismatch); + } + let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); + let Slot::Pending { keys, copy, host_bytes } = previous else { + return Err(Error::IdentityMismatch); + }; + let observed = if wait { + OwnedCopyPoll::Complete(copy.wait().map_err(driver_error)?) + } else { + copy.poll().map_err(driver_error)? + }; + match observed { + OwnedCopyPoll::Pending(copy) => self.slots[slot] = Slot::Pending { keys, copy, host_bytes }, + OwnedCopyPoll::Complete(receipt) => { + if receipt.len() != 3 { + return Err(Error::IdentityMismatch); + } + let mut pairs = receipt.into_pairs(); + let mut buffers = std::array::from_fn(|_| None); + let mut validation = Ok(()); + for (index, destination) in buffers.iter_mut().enumerate() { + if let Some((buffer, payload)) = pairs[index].take() { + if buffer.len() != keys[index].bytes || payload.len() != keys[index].bytes { + validation = Err(Error::IdentityMismatch); + } + *destination = Some(buffer); + drop(payload); // Actual event + unregister completed. + } else { + validation = Err(Error::IdentityMismatch); + } + } + if pairs.iter().any(Option::is_some) { + validation = Err(Error::IdentityMismatch); + } + self.slots[slot] = Slot::Completed { keys, buffers }; + validation?; + } + } + Ok(()) + } + + /// Fresh source equality and explicit callback finish are required even though bytes completed. + /// Caller retains real current-row/txn/origin/cancel/packet checks; these + /// buffers are temporary execution owners, never adaptive cache hits. + pub(in crate::qwen_forward) fn with_triplet<'source, 'group, T>( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'source, 'group>, + member: usize, + cancel_observed: &Cell, + consume: impl FnOnce( + [&DeviceBuffer<'ctx>; 3], + [MoeWeightDescriptor; 3], + &mut MoeRoutedSourceScope<'source, 'group>, + ) -> Result, + ) -> Result { + let result = if let Some(mapped) = &mut self.mapped { + mapped.with_triplet(slot, binding, source, member, consume) + } else { + self.with_triplet_inner(slot, binding, source, member, consume) + }; + #[cfg(test)] + if self.mapped.is_some() && result.is_ok() { + self.completed_loans = self.completed_loans.checked_add(1).ok_or(Error::Overflow)?; + } + match result { + Ok(value) => Ok(value), + // Healthy cancellation: the loaned slot is already back to Idle with its whole + // buffers (the callback only read them). Drain BOTH genuine event copies so + // the other slot can be reused, keep the owner healthy and return the cancel + // error first. A drain failure still fails the owner (drain -> fail). + Err(primary) if self.is_healthy_cancel(&primary, cancel_observed.get()) => { + combine(Err(primary), self.drain()) + } + Err(primary) => self.fail(primary), + } + } + /// Only a cancellation the caller actually observed through its cancelled closure during this + /// loan, with the executor's cancel code, on an owner that is neither failed nor under a + /// poisoned Context. Every other callback error (identity, finite, CUDA, binding) stays fatal. + pub(in super::super) fn is_healthy_cancel(&self, error: &Error, observed: bool) -> bool { + healthy_cancel(error, observed, self.failed, self.context.is_poisoned()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs new file mode 100644 index 00000000..87279ebe --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_ephemeral_routed/impl_ephemeralroutedowner/impl_ephemeralroutedowner_3.rs @@ -0,0 +1,138 @@ +//! Moved out of the parent module by STRA-338: impl EphemeralRoutedOwner (3). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> EphemeralRoutedOwner<'ctx> { + pub(in super::super) fn with_triplet_inner<'source, 'group, T>( + &mut self, + slot: usize, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'source, 'group>, + member: usize, + consume: impl FnOnce( + [&DeviceBuffer<'ctx>; 3], + [MoeWeightDescriptor; 3], + &mut MoeRoutedSourceScope<'source, 'group>, + ) -> Result, + ) -> Result { + self.validate_slot(binding, slot)?; + let fresh = Self::keys(binding, source, member)?; + let Slot::Completed { keys, .. } = &self.slots[slot] else { + return Err(Error::IdentityMismatch); + }; + if *keys != fresh { + return Err(Error::IdentityMismatch); + } + let previous = std::mem::replace(&mut self.slots[slot], Slot::InUse); + let Slot::Completed { keys, buffers } = previous else { + return Err(Error::IdentityMismatch); + }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let whole = [ + buffers[0].as_ref().ok_or(Error::IdentityMismatch)?, + buffers[1].as_ref().ok_or(Error::IdentityMismatch)?, + buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, + ]; + consume(whole, keys, source) + })); + // The caller explicitly finishes at its packet/current-row boundary. + // The enclosing genuine with_moe_routed_source rejects success without + // that finish and always attempts cleanup on an error. Do not finish + // twice or move the callback's source check past its coverage gate. + self.slots[slot] = Slot::Idle { layer: Some(keys[0].layer), buffers }; + match result { + Ok(result) => { + let value = result?; + if self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + #[cfg(test)] + { + self.completed_loans = self.completed_loans.checked_add(1).ok_or(Error::Overflow)?; + } + Ok(value) + } + Err(primary) => { + self.failed = true; + let _cleanup = self.release_all(); + std::panic::resume_unwind(primary) + } + } + } + pub(in super::super) fn fail(&mut self, primary: Error) -> Result { + self.failed = true; + combine(Err(primary), self.release_all()) + } + /// Healthy cancellation/iteration drain waits BOTH actual events and discards + /// incoming expert keys/host payloads, retaining exact whole buffers for reuse. + /// Caller must drain real CPU work separately before starting another wave. + pub(in crate::qwen_forward) fn drain(&mut self) -> Result<()> { + if self.is_failed() { + return combine(Err(Error::CudaExecution), self.release_all()); + } + let result = self.drain_inner(); + match result { + Ok(()) => Ok(()), + Err(primary) => self.fail(primary), + } + } + pub(in super::super) fn drain_inner(&mut self) -> Result<()> { + if let Some(mapped) = &mut self.mapped { + return mapped.drain(); + } + for index in 0..SLOTS { + let actual = std::mem::replace(&mut self.slots[index], Slot::InUse); + let (layer, buffers) = match actual { + Slot::Idle { layer, buffers } => (layer, buffers), + Slot::Completed { keys, buffers } => (Some(keys[0].layer), buffers), + Slot::Pending { keys, copy, .. } => { + let receipt = copy.wait().map_err(driver_error)?; + if receipt.len() != 3 { + return Err(Error::IdentityMismatch); + } + let mut pairs = receipt.into_pairs(); + let mut buffers = std::array::from_fn(|_| None); + let mut valid = true; + for (role, buffer) in buffers.iter_mut().enumerate() { + if let Some((device, source)) = pairs[role].take() { + valid &= device.len() == keys[role].bytes && source.len() == keys[role].bytes; + *buffer = Some(device); + drop(source); + } else { + valid = false; + } + } + valid &= !pairs.iter().any(Option::is_some); + self.slots[index] = Slot::Idle { layer: Some(keys[0].layer), buffers }; + if !valid { + return Err(Error::IdentityMismatch); + } + continue; + } + Slot::InUse => return Err(Error::IdentityMismatch), + }; + self.slots[index] = Slot::Idle { layer, buffers }; + } + Ok(()) + } + /// Close, errors and Drop attempt every real release, including both pending + /// event drains. Poison retains unknown native owners and their real charges. + pub(in super::super) fn release_all(&mut self) -> Result<()> { + let mut result = self.mapped.as_mut().map_or(Ok(()), MappedStage::release_all); + for slot in &mut self.slots { + let actual = std::mem::replace(slot, empty_slot()); + result = combine(result, close_slot(actual)); + } + if self.context.is_poisoned() { + result = combine(result, Err(Error::CudaExecution)); + } + if result.is_err() { + self.failed = true; + } + result + } + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.release_all() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_learned_main_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_learned_main_sdet.rs index dabbae08..2d112391 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_learned_main_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_learned_main_sdet.rs @@ -1,22 +1,20 @@ //! Pure current-age bootstrap policy proof; no binding/device/weight certificate. -use super::*; use super::super::cache_lru_index::LruIndex; +use super::*; fn key(layer: u32, expert: u32, role: u8) -> MoeWeightDescriptor { - MoeWeightDescriptor { layer, expert: Some(expert), role, raw_kind: 18, - columns: 2560, rows: 640, bytes: 627_200 } + MoeWeightDescriptor { layer, expert: Some(expert), role, raw_kind: 18, columns: 2560, rows: 640, bytes: 627_200 } } #[test] fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() { // Reference FIRST: independent actual-age min over the complete routed map, // including entries belonging to the historical ranked prefix. - let entries: Vec<_> = (0..48u32).map(|layer| { - (key(layer, layer + 1, (layer % 3) as u8), 48 - u64::from(layer)) - }).collect(); + let entries: Vec<_> = + (0..48u32).map(|layer| (key(layer, layer + 1, (layer % 3) as u8), 48 - u64::from(layer))).collect(); let protected = [entries[47].0, entries[46].0, entries[45].0]; - let old_first = entries.iter().filter(|(key, _)| !protected.contains(key)) - .min_by_key(|(_, age)| *age).map(|(key, _)| *key); + let old_first = + entries.iter().filter(|(key, _)| !protected.contains(key)).min_by_key(|(_, age)| *age).map(|(key, _)| *key); let mut index = LruIndex::new().unwrap(); let allocated_metadata = index.metadata_bytes().unwrap(); assert!(index.seed_existing(48, entries.iter().copied()).is_ok()); @@ -32,8 +30,8 @@ fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() { let changed = key(0, 500, 2); let prepared = index.prepare_updates(&[(changed, 49)]).unwrap(); assert!(index.commit_updates(prepared).is_ok()); - let next_reference = entries.iter().filter(|(key, _)| *key != victim) - .min_by_key(|(_, age)| *age).map(|(key, _)| *key); + let next_reference = + entries.iter().filter(|(key, _)| *key != victim).min_by_key(|(_, age)| *age).map(|(key, _)| *key); assert_eq!(index.oldest(&[]).unwrap(), next_reference); assert!(index.validate_coherence()); let before = index.oldest(&[]).unwrap(); @@ -43,8 +41,10 @@ fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() { // coordinate, changed descriptor sharing a slot, stale/zero/equal age, foreign // coordinate and real owner-age overflow. A valid retry uses the same capacity. let mut empty = LruIndex::new().unwrap(); - let mut collision = key(0, 0, 0); collision.raw_kind = 22; - let mut foreign = key(48, 0, 0); foreign.bytes = 627_200; + let mut collision = key(0, 0, 0); + collision.raw_kind = 22; + let mut foreign = key(48, 0, 0); + foreign.bytes = 627_200; for bad in [ vec![(key(0, 0, 0), 1), (key(0, 0, 0), 2)], vec![(key(0, 0, 0), 1), (collision, 2)], @@ -66,20 +66,23 @@ fn original_scan_first_actual_age_seed_learned_main_protection_and_capacity() { // Independent expanded multiset FIRST proves the full per-matrix cardinality // bound (rather than prefix-triplet count) under all actual role charges. let charges = std::array::from_fn::<_, 48, _>(|layer| [3 + layer, 5 + layer, 9 + layer]); - let mut reference: Vec<_> = charges.iter().flatten() - .flat_map(|&charge| std::iter::repeat_n(charge, 512)).collect(); + let mut reference: Vec<_> = charges.iter().flatten().flat_map(|&charge| std::iter::repeat_n(charge, 512)).collect(); reference.sort_unstable(); let total: usize = reference.iter().sum(); for main in [0usize, 2, 3, 3 * 512 - 1, 3 * 512, 17_000, total - 1, total, usize::MAX] { let mut bytes = 0usize; let mut count = 0usize; for charge in &reference { - if bytes.checked_add(*charge).is_none_or(|next| next > main) { break; } - bytes += charge; count += 1; + if bytes.checked_add(*charge).is_none_or(|next| next > main) { + break; + } + bytes += charge; + count += 1; } assert_eq!(learned_main_slot_bound(&charges, main).unwrap(), count); } - let mut bad_charges = charges; bad_charges[47][2] = 0; + let mut bad_charges = charges; + bad_charges[47][2] = 0; assert!(learned_main_slot_bound(&bad_charges, total).is_err()); assert_eq!(learned_main_slot_bound(&[[usize::MAX; 3]; 48], usize::MAX).unwrap(), 1); // Source-policy/metadata witness only. Shared permanent whole descriptors, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex.rs index 81885035..b41a8df6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex.rs @@ -22,19 +22,11 @@ impl LruIndex { return Err(Error::InputAllocation); } let mut heap = Vec::new(); - heap.try_reserve_exact(limit) - .map_err(|_| Error::InputAllocation)?; + heap.try_reserve_exact(limit).map_err(|_| Error::InputAllocation)?; let mut positions = Vec::new(); - positions - .try_reserve_exact(MAX_KEYS) - .map_err(|_| Error::InputAllocation)?; + positions.try_reserve_exact(MAX_KEYS).map_err(|_| Error::InputAllocation)?; positions.resize(MAX_KEYS, ABSENT); - let index = Self { - heap, - positions, - limit, - last_age: 0, - }; + let index = Self { heap, positions, limit, last_age: 0 }; if index.metadata_bytes()? > HOST_LIMIT { return Err(Error::InputAllocation); } @@ -45,13 +37,7 @@ impl LruIndex { self.heap .capacity() .checked_mul(std::mem::size_of::()) - .and_then(|n| { - n.checked_add( - self.positions - .capacity() - .checked_mul(std::mem::size_of::())?, - ) - }) + .and_then(|n| n.checked_add(self.positions.capacity().checked_mul(std::mem::size_of::())?)) .and_then(|n| n.checked_add(std::mem::size_of::())) .ok_or(Error::Overflow) } @@ -69,13 +55,9 @@ impl LruIndex { Ok(Some(index)) } pub(in super::super) fn entry_age(&self, key: MoeWeightDescriptor) -> Result> { - self.position(key) - .map(|position| position.map(|p| self.heap[p].age)) + self.position(key).map(|position| position.map(|p| self.heap[p].age)) } - pub(in super::super) fn prepare_updates( - &self, - updates: &[(MoeWeightDescriptor, u64)], - ) -> Result { + pub(in super::super) fn prepare_updates(&self, updates: &[(MoeWeightDescriptor, u64)]) -> Result { if updates.is_empty() || updates.len() > 3 { return Err(Error::InvalidDimension); } @@ -98,13 +80,7 @@ impl LruIndex { } nodes[index] = Some(Node { key, age: next_age }); } - if self - .heap - .len() - .checked_add(additional) - .ok_or(Error::Overflow)? - > self.limit - { + if self.heap.len().checked_add(additional).ok_or(Error::Overflow)? > self.limit { return Err(Error::InputAllocation); } Ok(PreparedUpdates { @@ -173,11 +149,8 @@ impl LruIndex { break; } let right = left + 1; - let child = if right < self.heap.len() && self.heap[right].age < self.heap[left].age { - right - } else { - left - }; + let child = + if right < self.heap.len() && self.heap[right].age < self.heap[left].age { right } else { left }; if self.heap[position].age <= self.heap[child].age { break; } @@ -200,16 +173,10 @@ impl LruIndex { } Ok(()) } - pub(in super::super) fn oldest( - &self, - protected: &[MoeWeightDescriptor], - ) -> Result> { + pub(in super::super) fn oldest(&self, protected: &[MoeWeightDescriptor]) -> Result> { self.search(protected).map(|(key, _)| key) } - pub(super) fn search( - &self, - protected: &[MoeWeightDescriptor], - ) -> Result<(Option, usize)> { + pub(super) fn search(&self, protected: &[MoeWeightDescriptor]) -> Result<(Option, usize)> { if protected.len() > MAX_PROTECTED { return Err(Error::InvalidDimension); } @@ -267,11 +234,7 @@ impl LruIndex { for (key_slot, &position) in self.positions.iter().enumerate() { if position != ABSENT { occupied += 1; - if self - .heap - .get(position) - .is_none_or(|node| slot(node.key).ok() != Some(key_slot)) - { + if self.heap.get(position).is_none_or(|node| slot(node.key).ok() != Some(key_slot)) { return false; } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex_2.rs index 5656a879..44273649 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index/impl_lruindex_2.rs @@ -3,18 +3,22 @@ #[allow(unused_imports)] use super::*; - impl LruIndex { /// Seed only the already reserved, empty index from completed actual owners. /// This mutates metadata in an unpublished constructor; refusal restores empty. #[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(in super::super) fn seed_existing( - &mut self, actual_age: u64, + &mut self, + actual_age: u64, entries: impl Iterator, ) -> Result<()> { - if !self.heap.is_empty() || self.last_age != 0 || self.positions.len() != MAX_KEYS + if !self.heap.is_empty() + || self.last_age != 0 + || self.positions.len() != MAX_KEYS || self.positions.iter().any(|&p| p != ABSENT) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let operation = (|| { for (key, age) in entries { let key_slot = slot(key)?; @@ -37,7 +41,9 @@ impl LruIndex { self.positions[slot(node.key)?] = position; } self.last_age = actual_age; - if !self.seed_coherent(actual_age) { return Err(Error::IdentityMismatch); } + if !self.seed_coherent(actual_age) { + return Err(Error::IdentityMismatch); + } Ok(()) })(); if operation.is_err() { @@ -49,26 +55,30 @@ impl LruIndex { } #[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(super) fn seed_coherent(&self, actual_age: u64) -> bool { - if self.heap.len() > self.limit || self.positions.len() != MAX_KEYS - || self.last_age > actual_age { return false; } + if self.heap.len() > self.limit || self.positions.len() != MAX_KEYS || self.last_age > actual_age { + return false; + } let occupied = self.positions.iter().filter(|&&p| p != ABSENT).count(); occupied == self.heap.len() && self.positions.iter().enumerate().all(|(key_slot, &position)| { - position == ABSENT || self.heap.get(position) - .is_some_and(|node| slot(node.key).ok() == Some(key_slot)) + position == ABSENT || self.heap.get(position).is_some_and(|node| slot(node.key).ok() == Some(key_slot)) }) && self.heap.iter().enumerate().all(|(i, node)| { - node.age != 0 && node.age <= self.last_age + node.age != 0 + && node.age <= self.last_age && slot(node.key).is_ok_and(|key_slot| self.positions[key_slot] == i) && (i == 0 || self.heap[(i - 1) / 2].age < node.age) }) } #[cfg(any(test, all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] pub(in super::super) fn matches_existing( - &self, actual_age: u64, + &self, + actual_age: u64, entries: impl Iterator, ) -> Result { - if !self.seed_coherent(actual_age) { return Err(Error::IdentityMismatch); } + if !self.seed_coherent(actual_age) { + return Err(Error::IdentityMismatch); + } let mut count = 0usize; for (key, age) in entries { if self.entry_age(key)? != Some(age) || age > actual_age { @@ -76,7 +86,9 @@ impl LruIndex { } count = count.checked_add(1).ok_or(Error::Overflow)?; } - if count != self.len() { return Err(Error::IdentityMismatch); } + if count != self.len() { + return Err(Error::IdentityMismatch); + } Ok(count) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index_sdet.rs index d0bf4d5b..732b831b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_lru_index_sdet.rs @@ -20,15 +20,7 @@ fn descriptor(ordinal: usize) -> MoeWeightDescriptor { (None, 3) => (30, 1, 2560, 5120), _ => unreachable!(), }; - MoeWeightDescriptor { - layer: (ordinal / PER_LAYER) as u32, - expert, - role, - raw_kind, - rows, - columns, - bytes, - } + MoeWeightDescriptor { layer: (ordinal / PER_LAYER) as u32, expert, role, raw_kind, rows, columns, bytes } } fn actual_entries(index: &LruIndex) -> Oracle { @@ -52,10 +44,7 @@ fn assert_live(index: &LruIndex, oracle: &Oracle) { fn compare_old_first(index: &LruIndex, oracle: &Oracle, protected: &[MoeWeightDescriptor]) { // Call the unchanged original minimum scan BEFORE observing the new index. let original = super::super::oldest_weight( - oracle - .iter() - .filter(|(key, _)| !protected.contains(key)) - .map(|(key, age)| (*key, *age)), + oracle.iter().filter(|(key, _)| !protected.contains(key)).map(|(key, age)| (*key, *age)), ); let (actual, visits) = index.oldest_with_visits(protected).unwrap(); assert_eq!(actual, original); @@ -74,13 +63,7 @@ fn update(index: &mut LruIndex, oracle: &mut Oracle, updates: &[(MoeWeightDescri } fn state(index: &LruIndex) -> (Oracle, Vec, u64, usize, usize) { - ( - actual_entries(index), - index.positions.clone(), - index.last_age, - index.heap.capacity(), - index.positions.capacity(), - ) + (actual_entries(index), index.positions.clone(), index.last_age, index.heap.capacity(), index.positions.capacity()) } fn refused_prepare(index: &LruIndex, updates: &[(MoeWeightDescriptor, u64)]) { @@ -98,11 +81,7 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() { assert!(index.validate_coherence()); compare_old_first(&index, &oracle, &[]); let keys = [descriptor(0), descriptor(1), descriptor(2), descriptor(3)]; - update( - &mut index, - &mut oracle, - &[(keys[0], 1), (keys[1], 2), (keys[2], 3)], - ); + update(&mut index, &mut oracle, &[(keys[0], 1), (keys[1], 2), (keys[2], 3)]); update(&mut index, &mut oracle, &[(keys[3], 4)]); for protected in [&keys[..0], &keys[..1], &keys[..3], &keys[..4]] { compare_old_first(&index, &oracle, protected); @@ -190,11 +169,7 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() { update(&mut partial, &mut partial_oracle, &[(keys[0], 1)]); compare_old_first(&partial, &partial_oracle, &[]); refused_prepare(&partial, &[(keys[1], 2), (invalid, 3)]); - update( - &mut partial, - &mut partial_oracle, - &[(keys[1], 2), (keys[2], 3)], - ); + update(&mut partial, &mut partial_oracle, &[(keys[1], 2), (keys[2], 3)]); refused_prepare(&partial, &[(keys[0], 4), (keys[3], 5)]); partial.remove(keys[1]).unwrap(); partial_oracle.remove(&keys[1]); @@ -220,17 +195,12 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() { age = age.checked_add(1).unwrap(); update(&mut churn, &mut churn_oracle, &[(key, age)]); } - let protected: Vec<_> = (0..turn % 5) - .map(|n| descriptor((ordinal + n * 19) % 256)) - .collect(); + let protected: Vec<_> = (0..turn % 5).map(|n| descriptor((ordinal + n * 19) % 256)).collect(); compare_old_first(&churn, &churn_oracle, &protected); if turn.is_multiple_of(257) { assert!(churn.validate_coherence()); } - assert_eq!( - (churn.heap.capacity(), churn.positions.capacity()), - capacities - ); + assert_eq!((churn.heap.capacity(), churn.positions.capacity()), capacities); } assert!(churn.validate_coherence()); @@ -259,31 +229,16 @@ fn original_min_first_bounded_lru_index_matches_scan_and_refuses_incoherence() { assert_live(&full, &full_oracle); assert!(full.validate_coherence()); assert!(full.metadata_bytes().unwrap() <= HOST_LIMIT); - for protected in [ - vec![], - vec![descriptor(0)], - (0..4).map(descriptor).collect(), - ] { + for protected in [vec![], vec![descriptor(0)], (0..4).map(descriptor).collect()] { compare_old_first(&full, &full_oracle, &protected); } let end = descriptor(MAX_KEYS - 1); - update( - &mut full, - &mut full_oracle, - &[(end, age + 1), (descriptor(0), age + 2)], - ); + update(&mut full, &mut full_oracle, &[(end, age + 1), (descriptor(0), age + 2)]); full.remove(end).unwrap(); full_oracle.remove(&end); update(&mut full, &mut full_oracle, &[(end, age + 3)]); - compare_old_first( - &full, - &full_oracle, - &[descriptor(1), descriptor(2), descriptor(3), descriptor(4)], - ); - assert_eq!( - (full.heap.capacity(), full.positions.capacity()), - capacities - ); + compare_old_first(&full, &full_oracle, &[descriptor(1), descriptor(2), descriptor(3), descriptor(4)]); + assert_eq!((full.heap.capacity(), full.positions.capacity()), capacities); assert!(full.validate_coherence()); // Existing caller age arithmetic cannot wrap into a valid metadata update. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs index 12fe22b3..1738ba24 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights.rs @@ -1,213 +1,53 @@ //! Model-lifetime immutable MTP allocations. Cached CUDA graphs own real Rc //! allocations, so a per-call matrix borrow can never outlive its weight bank. -use super::*; use super::super::output_native::OriginalMtpNativeHead; -use crate::model_binding::qwen4exp_input::{pinned_dense_bytes,rt_dense_name,rt_dense_roles,rt_dense_shape}; +use super::*; +use crate::model_binding::qwen4exp_input::{pinned_dense_bytes, rt_dense_name, rt_dense_roles, rt_dense_shape}; #[derive(Clone)] -struct RetainedDense<'ctx>{role:MtpRole,kind:MtpKind,rows:usize,columns:usize,buffer:Rc>} +struct RetainedDense<'ctx> { + role: MtpRole, + kind: MtpKind, + rows: usize, + columns: usize, + buffer: Rc>, +} /// Where the immutable roles came from. `Pinned` is the digest-frozen pack /// owned by the binding; `RtDirectory` is the Original-literal `--mtp DIR` /// load (`Context::original_mtp_rt_bank`), whose bytes are already resident and /// whose kinds/shapes were matched to the role contract at construction. -#[derive(Clone,Copy,PartialEq,Eq)] -enum WeightSource{Pinned,RtDirectory} +#[derive(Clone, Copy, PartialEq, Eq)] +enum WeightSource { + Pinned, + RtDirectory, +} /// Clones share the same device allocations (`Rc`); no buffer is duplicated. #[derive(Clone)] -pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,dense:Vec>, - experts:Rc>,source:WeightSource, +pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + dense: Vec>, + experts: Rc>, + source: WeightSource, /// `dense.bin` length and the device bytes this owner's load itself placed /// (0 for the pinned pack, whose bytes the MoE cache already charged). - dense_file_bytes:u64,loaded_bytes:u64, + dense_file_bytes: u64, + loaded_bytes: u64, /// Indexed RT tensors no role consumes (the optional indexer tensors, or /// extras). Original keeps the whole `dense.bin` resident, so they stay /// owned here for the life of the bank rather than being released early. - extras:Vec>>, + extras: Vec>>, } /// What `MoeWeightCache::share_rt_mtp_dense` did. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub(in crate::qwen_forward) struct MtpDenseShare{ +pub(in crate::qwen_forward) struct MtpDenseShare { /// Roles whose pinned-pack copy was proven byte-equal to the RT bank's and replaced by it. - pub(in crate::qwen_forward) shared:usize, + pub(in crate::qwen_forward) shared: usize, /// Roles left as they were (not in the RT bank, or a different shape or different bytes). - pub(in crate::qwen_forward) kept:usize, + pub(in crate::qwen_forward) kept: usize, /// Roles found different from the RT bank's copy although the shape matches (a subset of `kept`; 0 expected). - pub(in crate::qwen_forward) differing:usize, + pub(in crate::qwen_forward) differing: usize, /// Device bytes the replaced buffers gave back. - pub(in crate::qwen_forward) released_bytes:usize, -} -/// Two copies of a dense role may be merged only when kind, shape, length and every byte agree. -fn dense_copies_equal(a:(MtpKind,usize,usize,&[u8]),b:(MtpKind,usize,usize,&[u8]))->bool{ - (a.0,a.1,a.2)==(b.0,b.1,b.2)&&a.3==b.3 -} -impl<'ctx> MoeWeightCache<'ctx>{ - /// The RT-directory serve path holds the MTP layer's dense roles twice: the pinned pack's copy that this cache uploaded (read by the prompt path's draft-KV recording through - /// `mtp_matrix`) and the RT bank's own. When a role's two device copies are proven byte-equal here (both read back and compared), this cache adopts the RT bank's allocation - /// and releases its own, so the model holds one copy. Values read by any kernel do not change. Roles the RT bank lacks (the indexer roles) and roles that differ are left alone. - pub(in crate::qwen_forward) fn share_rt_mtp_dense(&mut self,retained:&RetainedOriginalMtpWeights<'ctx>)->Result{ - if retained.source!=WeightSource::RtDirectory||!std::ptr::eq(retained.context,self.context){return Err(Error::IdentityMismatch);} - let mut report=MtpDenseShare::default(); - for entry in self.dense.iter_mut(){ - let Some(rt)=retained.dense.iter().find(|r|r.role==entry.role)else{report.kept+=1;continue}; - if Rc::ptr_eq(&rt.buffer,&entry.buffer){continue;} - if (rt.kind,rt.rows,rt.columns)!=(entry.kind,entry.rows,entry.columns)||rt.buffer.len()!=entry.buffer.len(){report.kept+=1;continue;} - let mine=entry.buffer.copy_to_owned(entry.buffer.len()).map_err(driver_error)?; - let theirs=rt.buffer.copy_to_owned(rt.buffer.len()).map_err(driver_error)?; - if !dense_copies_equal((entry.kind,entry.rows,entry.columns,&mine),(rt.kind,rt.rows,rt.columns,&theirs)){report.kept+=1;report.differing+=1;continue;} - let old=std::mem::replace(&mut entry.buffer,Rc::clone(&rt.buffer)); - if let Ok(buffer)=Rc::try_unwrap(old){ - report.released_bytes+=buffer.len(); - if buffer.release().is_err(){self.failed.set(true);return Err(Error::CudaExecution);} - } - report.shared+=1; - } - Ok(report) - } - pub(in crate::qwen_forward) fn retain_original_mtp_weights(&self,binding:&ModelBinding, - context:&Context<'ctx>)->Result>{ - self.validate(binding,context)?; - let pack=binding.mtp_weights().map_err(binding_error)?; - let roles=pack.dense_roles(binding).map_err(binding_error)?; - if roles.len()!=self.dense.len(){return Err(Error::IdentityMismatch);} - let mut dense=Vec::new();dense.try_reserve_exact(roles.len()).map_err(|_|Error::InputAllocation)?; - for role in roles{ - let(kind,rows,columns,_)=self.mtp_matrix(binding,context,role)?; - let entry=self.dense.iter().find(|entry|entry.role==role).ok_or(Error::IdentityMismatch)?; - if self.dense.iter().filter(|entry|entry.role==role).count()!=1{return Err(Error::IdentityMismatch);} - dense.push(RetainedDense{role,kind,rows,columns,buffer:Rc::clone(&entry.buffer)}); - } - let experts=Rc::clone(self.bank.as_ref().ok_or(Error::IdentityMismatch)?); - if experts.len()!=707_788_800{return Err(Error::InvalidDimension);} - Ok(RetainedOriginalMtpWeights{binding:binding.identity(),context:self.context,dense,experts,source:WeightSource::Pinned,dense_file_bytes:pinned_dense_bytes(),loaded_bytes:0,extras:Vec::new()}) - } -} -impl<'ctx> RetainedOriginalMtpWeights<'ctx>{ - /// Original `MtpDrafter::load` weights, taken from the loaded RT bank. - /// Every role of the contract must be present with exactly the retained - /// kind and shape (the pinned path checks the same shapes through its - /// descriptor table); unknown extra tensors stay in the bank, unused, as in - /// Original. The bank's allocations are shared, never copied. - pub(in crate::qwen_forward) fn from_rt_bank(binding:&ModelBinding,context:&'ctx Context<'ctx>, - bank:&leleka_cuda_driver::OriginalMtpRtBank<'ctx>)->Result{ - bank.validate_context(context).map_err(driver_error)?; - let roles=rt_dense_roles(); - let mut dense=Vec::new();dense.try_reserve_exact(roles.len()).map_err(|_|Error::InputAllocation)?; - for role in roles{ - let name=rt_dense_name(role).ok_or(Error::IdentityMismatch)?; - let(kind,rows,columns)=rt_dense_shape(role).ok_or(Error::IdentityMismatch)?; - let tensor=bank.tensor(name,rt_kind(kind)?).ok_or(Error::InvalidDimension)?; - if (tensor.rows(),tensor.columns())!=(rows,columns){return Err(Error::InvalidDimension);} - dense.push(RetainedDense{role,kind,rows,columns,buffer:tensor.buffer()}); - } - let experts=bank.experts(); - if bank.expert_count()!=512||experts.len()!=707_788_800{return Err(Error::InvalidDimension);} - let mut extras=Vec::new();extras.try_reserve_exact(bank.tensors().len()).map_err(|_|Error::InputAllocation)?; - for tensor in bank.tensors(){ - let buffer=tensor.buffer(); - if !dense.iter().any(|entry|Rc::ptr_eq(&entry.buffer,&buffer)){extras.push(buffer);} - } - Ok(Self{binding:binding.identity(),context,dense,experts,source:WeightSource::RtDirectory,dense_file_bytes:bank.dense_file_bytes(),loaded_bytes:bank.vram_bytes(),extras}) - } - pub(in crate::qwen_forward) fn dense_file_bytes(&self)->u64{self.dense_file_bytes} - pub(in crate::qwen_forward) fn loaded_bytes(&self)->u64{self.loaded_bytes} - fn validate(&self,binding:&ModelBinding,context:&Context<'ctx>)->Result<()> { - if self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch);} - match self.source{ - WeightSource::Pinned=>binding.mtp_weights().map_err(binding_error)?.validate_sources(binding).map_err(binding_error), - // The bank is device-resident and was matched at construction; - // re-prove that every retained allocation still belongs to this context. - WeightSource::RtDirectory=>{ - if self.experts.len()!=707_788_800||self.dense.iter().any(|entry|entry.buffer.len()==0) - ||self.extras.iter().any(|buffer|buffer.len()==0){return Err(Error::InvalidDimension);} - Ok(()) - } - } - } - pub(in crate::qwen_forward) fn matrix(&self,binding:&ModelBinding,context:&Context<'ctx>,role:MtpRole) - ->Result<(MtpKind,usize,usize,Rc>)>{ - self.validate(binding,context)?; - let entry=self.dense.iter().find(|entry|entry.role==role).ok_or(Error::IdentityMismatch)?; - let expected=match self.source{ - WeightSource::Pinned=>binding.mtp_weights().map_err(binding_error)?.dense_shape(binding,role).map_err(binding_error)?, - WeightSource::RtDirectory=>rt_dense_shape(role).ok_or(Error::IdentityMismatch)?, - }; - if expected!=(entry.kind,entry.rows,entry.columns){return Err(Error::IdentityMismatch);} - Ok((entry.kind,entry.rows,entry.columns,Rc::clone(&entry.buffer))) - } - pub(in crate::qwen_forward) fn expert_bank(&self,binding:&ModelBinding,context:&Context<'ctx>) - ->Result>>{self.validate(binding,context)?;Ok(Rc::clone(&self.experts))} - /// The scalar prefill graphs retain these exact model allocations, including - /// the genuine whole embedding table. Shape metadata cannot replace an Rc - /// owner or permit a different allocation to be substituted during capture. - pub(in crate::qwen_forward) fn scalar_prefill_weights(&self,binding:&ModelBinding, - context:&Context<'ctx>, - embedding:&super::super::executor::original_prompt::embedding::OriginalPromptEmbedding<'ctx>) - ->Result>>{ - self.validate(binding,context)?; - let acquire=|role,expected|->Result>>{ - let(kind,rows,columns,owner)=self.matrix(binding,context,role)?; - if (kind,rows,columns)!=expected{return Err(Error::InvalidDimension);} - Ok(owner) - }; - let roles=[ - acquire(MtpRole::EmbeddingNorm,(MtpKind::F32,1,2560))?, - acquire(MtpRole::FcEmbedding,(MtpKind::Q8_0,2560,2560))?, - acquire(MtpRole::HiddenNorm,(MtpKind::F32,1,10240))?, - acquire(MtpRole::FcHidden,(MtpKind::Q8_0,2560,2560))?, - acquire(MtpRole::AttentionNorm,(MtpKind::F32,1,10240))?, - acquire(MtpRole::AttentionDown,(MtpKind::Bf16,320,10240))?, - acquire(MtpRole::AttentionUp,(MtpKind::Bf16,10240,320))?, - acquire(MtpRole::KeyProjection,(MtpKind::Q8_0,512,2560))?, - acquire(MtpRole::ValueProjection,(MtpKind::Q8_0,512,2560))?, - acquire(MtpRole::KeyNorm,(MtpKind::F32,1,256))?, - acquire(MtpRole::AttentionInject,(MtpKind::Bf16,4,10240))?, - ]; - let(table,_,_,_)=embedding.retain(binding,context)?; - let descriptor=embedding.borrow(binding,context)?; - let bank=leleka_cuda_driver::OriginalMtpRetainedScalarWeights::retain(self.context,roles,table,&descriptor) - .map_err(driver_error)?; - self.validate(binding,context)?; - Ok(Rc::new(bank)) - } - /// Exact full MTP forward role order. The caller lends the model-affine - /// native-head allocation from `OriginalNativeOutput::mtp_head`; this - /// cache never fabricates a replacement head buffer or dispatch profile. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn full_forward_weights( - &self,binding:&ModelBinding,context:&'ctx Context<'ctx>, - prefix:Rc>, - head:&OriginalMtpNativeHead<'ctx>,id_vocab:usize, - draft_head:Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>, - )->Result>>{ - self.validate(binding,context)?; - if head.columns()!=2560||id_vocab!=head.vocabulary(){return Err(Error::InvalidDimension);} - let acquire=|role,expected|->Result>>{ - let(kind,rows,columns,owner)=self.matrix(binding,context,role)?; - if (kind,rows,columns)!=expected{return Err(Error::InvalidDimension);} - Ok(owner) - }; - let roles=FULL_FORWARD_ROLES.map(|(role,expected)|acquire(role,expected)); - let mut acquired=Vec::new();acquired.try_reserve_exact(roles.len()).map_err(|_|Error::InputAllocation)?; - for role in roles{acquired.push(role?);} - let roles:[Rc>;15]=acquired.try_into().map_err(|_|Error::InvalidDimension)?; - let experts=self.expert_bank(binding,context)?; - // Literal bind: with a draft_vocab subset the draft head is the gathered - // rows (`dhead_`, `n_dvocab_` of them), else the native head itself. - let(head_weights,head_rows,subset)=match draft_head{ - Some(draft)=>(draft.rows(),draft.count(),Some(draft.subset_pair())), - None=>(head.weights(),head.vocabulary(),None), - }; - let weights=leleka_cuda_driver::OriginalMtpRetainedFullWeights::retain( - context,prefix,roles,experts,head_weights,head.kind(),head_rows,id_vocab,subset,head.dispatch(), - ).map_err(driver_error)?; - self.validate(binding,context)?; - Ok(Rc::new(weights)) - } - pub(in crate::qwen_forward) fn metadata_bytes(&self)->Result{ - self.dense.capacity().checked_mul(std::mem::size_of::>()) - .and_then(|n|n.checked_add(std::mem::size_of::())).ok_or(Error::Overflow) - } + pub(in crate::qwen_forward) released_bytes: usize, } /// Role order of `OriginalMtpRetainedFullWeights::retain` (driver `FULL_EXTENTS`; @@ -218,75 +58,81 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx>{ /// The attention hyper-connection is the prefix's. Several of these have equal /// byte extents (gate/up/down, the two hyper-connections), so the driver's /// extent and alias checks cannot catch a permutation: the order is pinned here. -const FULL_FORWARD_ROLES:[(MtpRole,(MtpKind,usize,usize));15]=[ - (MtpRole::QueryProjection,(MtpKind::Q8_0,12288,2560)), - (MtpRole::QueryNorm,(MtpKind::F32,1,256)), - (MtpRole::AttentionOutput,(MtpKind::Q8_0,2560,6144)), - (MtpRole::FfnNorm,(MtpKind::F32,1,10240)), - (MtpRole::FfnDown,(MtpKind::Bf16,320,10240)), - (MtpRole::FfnUp,(MtpKind::Bf16,10240,320)), - (MtpRole::FfnInject,(MtpKind::Bf16,4,10240)), - (MtpRole::Router,(MtpKind::Bf16,512,2560)), - (MtpRole::SharedGate,(MtpKind::Q8_0,640,2560)), - (MtpRole::SharedUp,(MtpKind::Q8_0,640,2560)), - (MtpRole::SharedDown,(MtpKind::Q8_0,2560,640)), - (MtpRole::SharedScalar,(MtpKind::Bf16,1,2560)), - (MtpRole::FinalNorm,(MtpKind::F32,1,10240)), - (MtpRole::FinalDown,(MtpKind::Bf16,320,10240)), - (MtpRole::FinalUp,(MtpKind::Bf16,10240,320)), +const FULL_FORWARD_ROLES: [(MtpRole, (MtpKind, usize, usize)); 15] = [ + (MtpRole::QueryProjection, (MtpKind::Q8_0, 12288, 2560)), + (MtpRole::QueryNorm, (MtpKind::F32, 1, 256)), + (MtpRole::AttentionOutput, (MtpKind::Q8_0, 2560, 6144)), + (MtpRole::FfnNorm, (MtpKind::F32, 1, 10240)), + (MtpRole::FfnDown, (MtpKind::Bf16, 320, 10240)), + (MtpRole::FfnUp, (MtpKind::Bf16, 10240, 320)), + (MtpRole::FfnInject, (MtpKind::Bf16, 4, 10240)), + (MtpRole::Router, (MtpKind::Bf16, 512, 2560)), + (MtpRole::SharedGate, (MtpKind::Q8_0, 640, 2560)), + (MtpRole::SharedUp, (MtpKind::Q8_0, 640, 2560)), + (MtpRole::SharedDown, (MtpKind::Q8_0, 2560, 640)), + (MtpRole::SharedScalar, (MtpKind::Bf16, 1, 2560)), + (MtpRole::FinalNorm, (MtpKind::F32, 1, 10240)), + (MtpRole::FinalDown, (MtpKind::Bf16, 320, 10240)), + (MtpRole::FinalUp, (MtpKind::Bf16, 10240, 320)), ]; -fn rt_kind(kind:MtpKind)->Result{ - use leleka_cuda_driver::OriginalMtpTensorKind as K; - match kind{MtpKind::Q8_0=>Ok(K::Q8_0),MtpKind::Bf16=>Ok(K::Bf16),MtpKind::F32=>Ok(K::F32),MtpKind::Q2_0=>Err(Error::InvalidDimension)} -} - #[cfg(test)] -mod rt_contract_tests{ +mod rt_contract_tests { use super::*; use leleka_cuda_driver::OriginalMtpTensorKind as K; #[test] - fn bank_kinds_map_one_to_one_and_q2_is_never_a_dense_kind(){ - assert!(matches!(rt_kind(MtpKind::Q8_0),Ok(K::Q8_0))); - assert!(matches!(rt_kind(MtpKind::Bf16),Ok(K::Bf16))); - assert!(matches!(rt_kind(MtpKind::F32),Ok(K::F32))); - assert_eq!(rt_kind(MtpKind::Q2_0).err(),Some(Error::InvalidDimension)); + fn bank_kinds_map_one_to_one_and_q2_is_never_a_dense_kind() { + assert!(matches!(rt_kind(MtpKind::Q8_0), Ok(K::Q8_0))); + assert!(matches!(rt_kind(MtpKind::Bf16), Ok(K::Bf16))); + assert!(matches!(rt_kind(MtpKind::F32), Ok(K::F32))); + assert_eq!(rt_kind(MtpKind::Q2_0).err(), Some(Error::InvalidDimension)); } /// mtp.cpp record_forward(full) tensor names, in the driver's role order. #[test] - fn full_forward_role_order_matches_mtp_cpp_tensor_names(){ - let names:Vec<&str>=FULL_FORWARD_ROLES.iter().map(|(role,_)|rt_dense_name(*role).unwrap()).collect(); - assert_eq!(names,[ - "self_attn.q_proj.weight","self_attn.q_norm.weight","self_attn.o_proj.weight", - "mlp_hyper_connection.hc_norm.weight","mlp_hyper_connection.input_mix_weight_down.weight", - "mlp_hyper_connection.input_mix_weight_up.weight","mlp_hyper_connection.block_inject_weight.weight", - "mlp.gate.weight", - "mlp.shared_expert.gate_proj.weight","mlp.shared_expert.up_proj.weight","mlp.shared_expert.down_proj.weight", - "mlp.shared_expert_gate.weight", - "hyper_connection_mixer.hc_norm.weight","hyper_connection_mixer.input_mix_weight_down.weight", - "hyper_connection_mixer.input_mix_weight_up.weight", - ]); - for (role,expected) in FULL_FORWARD_ROLES{ - assert_eq!(rt_dense_shape(role),Some(expected)); + fn full_forward_role_order_matches_mtp_cpp_tensor_names() { + let names: Vec<&str> = FULL_FORWARD_ROLES.iter().map(|(role, _)| rt_dense_name(*role).unwrap()).collect(); + assert_eq!( + names, + [ + "self_attn.q_proj.weight", + "self_attn.q_norm.weight", + "self_attn.o_proj.weight", + "mlp_hyper_connection.hc_norm.weight", + "mlp_hyper_connection.input_mix_weight_down.weight", + "mlp_hyper_connection.input_mix_weight_up.weight", + "mlp_hyper_connection.block_inject_weight.weight", + "mlp.gate.weight", + "mlp.shared_expert.gate_proj.weight", + "mlp.shared_expert.up_proj.weight", + "mlp.shared_expert.down_proj.weight", + "mlp.shared_expert_gate.weight", + "hyper_connection_mixer.hc_norm.weight", + "hyper_connection_mixer.input_mix_weight_down.weight", + "hyper_connection_mixer.input_mix_weight_up.weight", + ] + ); + for (role, expected) in FULL_FORWARD_ROLES { + assert_eq!(rt_dense_shape(role), Some(expected)); } } #[test] - fn every_contract_role_has_a_unique_rt_name_kind_and_shape(){ - let roles=rt_dense_roles(); - assert_eq!(roles.len(),26); - let mut names=Vec::new(); - for role in roles{ - let name=rt_dense_name(role).unwrap(); - let(kind,rows,columns)=rt_dense_shape(role).unwrap(); - assert!(rt_kind(kind).is_ok()&&rows>0&&columns>0,"{name}"); + fn every_contract_role_has_a_unique_rt_name_kind_and_shape() { + let roles = rt_dense_roles(); + assert_eq!(roles.len(), 26); + let mut names = Vec::new(); + for role in roles { + let name = rt_dense_name(role).unwrap(); + let (kind, rows, columns) = rt_dense_shape(role).unwrap(); + assert!(rt_kind(kind).is_ok() && rows > 0 && columns > 0, "{name}"); names.push(name); } - names.sort_unstable();names.dedup(); - assert_eq!(names.len(),26); - assert_eq!(pinned_dense_bytes(),116_099_072); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), 26); + assert_eq!(pinned_dense_bytes(), 116_099_072); } } @@ -295,11 +141,20 @@ mod share_tests { use super::*; #[test] fn dense_copies_merge_only_when_kind_shape_and_every_byte_agree() { - let a=[1u8,2,3,4]; - assert!(dense_copies_equal((MtpKind::Q8_0,2,2,&a),(MtpKind::Q8_0,2,2,&[1,2,3,4]))); - assert!(!dense_copies_equal((MtpKind::Q8_0,2,2,&a),(MtpKind::Q8_0,2,2,&[1,2,3,5])), "one byte"); - assert!(!dense_copies_equal((MtpKind::Q8_0,2,2,&a),(MtpKind::Bf16,2,2,&a)), "kind"); - assert!(!dense_copies_equal((MtpKind::Q8_0,2,2,&a),(MtpKind::Q8_0,1,4,&a)), "shape"); - assert!(!dense_copies_equal((MtpKind::Q8_0,2,2,&a),(MtpKind::Q8_0,2,2,&a[..3])), "length"); + let a = [1u8, 2, 3, 4]; + assert!(dense_copies_equal((MtpKind::Q8_0, 2, 2, &a), (MtpKind::Q8_0, 2, 2, &[1, 2, 3, 4]))); + assert!(!dense_copies_equal((MtpKind::Q8_0, 2, 2, &a), (MtpKind::Q8_0, 2, 2, &[1, 2, 3, 5])), "one byte"); + assert!(!dense_copies_equal((MtpKind::Q8_0, 2, 2, &a), (MtpKind::Bf16, 2, 2, &a)), "kind"); + assert!(!dense_copies_equal((MtpKind::Q8_0, 2, 2, &a), (MtpKind::Q8_0, 1, 4, &a)), "shape"); + assert!(!dense_copies_equal((MtpKind::Q8_0, 2, 2, &a), (MtpKind::Q8_0, 2, 2, &a[..3])), "length"); } } + +#[path = "cache_original_mtp_weights/dense_copies_equal_fn.rs"] +mod dense_copies_equal_fn; +#[allow(unused_imports)] +use dense_copies_equal_fn::dense_copies_equal; +#[path = "cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs"] +mod impl_retainedoriginalmtpweights; +#[allow(unused_imports)] +use impl_retainedoriginalmtpweights::rt_kind; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/dense_copies_equal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/dense_copies_equal_fn.rs new file mode 100644 index 00000000..d7eb7343 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/dense_copies_equal_fn.rs @@ -0,0 +1,94 @@ +//! Moved out of the parent module by STRA-338: fn dense_copies_equal, impl MoeWeightCache. + +#[allow(unused_imports)] +use super::*; + +/// Two copies of a dense role may be merged only when kind, shape, length and every byte agree. +pub(super) fn dense_copies_equal(a: (MtpKind, usize, usize, &[u8]), b: (MtpKind, usize, usize, &[u8])) -> bool { + (a.0, a.1, a.2) == (b.0, b.1, b.2) && a.3 == b.3 +} +impl<'ctx> MoeWeightCache<'ctx> { + /// The RT-directory serve path holds the MTP layer's dense roles twice: the pinned pack's copy that this cache uploaded (read by the prompt path's draft-KV recording through + /// `mtp_matrix`) and the RT bank's own. When a role's two device copies are proven byte-equal here (both read back and compared), this cache adopts the RT bank's allocation + /// and releases its own, so the model holds one copy. Values read by any kernel do not change. Roles the RT bank lacks (the indexer roles) and roles that differ are left alone. + pub(in crate::qwen_forward) fn share_rt_mtp_dense( + &mut self, + retained: &RetainedOriginalMtpWeights<'ctx>, + ) -> Result { + if retained.source != WeightSource::RtDirectory || !std::ptr::eq(retained.context, self.context) { + return Err(Error::IdentityMismatch); + } + let mut report = MtpDenseShare::default(); + for entry in self.dense.iter_mut() { + let Some(rt) = retained.dense.iter().find(|r| r.role == entry.role) else { + report.kept += 1; + continue; + }; + if Rc::ptr_eq(&rt.buffer, &entry.buffer) { + continue; + } + if (rt.kind, rt.rows, rt.columns) != (entry.kind, entry.rows, entry.columns) + || rt.buffer.len() != entry.buffer.len() + { + report.kept += 1; + continue; + } + let mine = entry.buffer.copy_to_owned(entry.buffer.len()).map_err(driver_error)?; + let theirs = rt.buffer.copy_to_owned(rt.buffer.len()).map_err(driver_error)?; + if !dense_copies_equal( + (entry.kind, entry.rows, entry.columns, &mine), + (rt.kind, rt.rows, rt.columns, &theirs), + ) { + report.kept += 1; + report.differing += 1; + continue; + } + let old = std::mem::replace(&mut entry.buffer, Rc::clone(&rt.buffer)); + if let Ok(buffer) = Rc::try_unwrap(old) { + report.released_bytes += buffer.len(); + if buffer.release().is_err() { + self.failed.set(true); + return Err(Error::CudaExecution); + } + } + report.shared += 1; + } + Ok(report) + } + pub(in crate::qwen_forward) fn retain_original_mtp_weights( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + ) -> Result> { + self.validate(binding, context)?; + let pack = binding.mtp_weights().map_err(binding_error)?; + let roles = pack.dense_roles(binding).map_err(binding_error)?; + if roles.len() != self.dense.len() { + return Err(Error::IdentityMismatch); + } + let mut dense = Vec::new(); + dense.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?; + for role in roles { + let (kind, rows, columns, _) = self.mtp_matrix(binding, context, role)?; + let entry = self.dense.iter().find(|entry| entry.role == role).ok_or(Error::IdentityMismatch)?; + if self.dense.iter().filter(|entry| entry.role == role).count() != 1 { + return Err(Error::IdentityMismatch); + } + dense.push(RetainedDense { role, kind, rows, columns, buffer: Rc::clone(&entry.buffer) }); + } + let experts = Rc::clone(self.bank.as_ref().ok_or(Error::IdentityMismatch)?); + if experts.len() != 707_788_800 { + return Err(Error::InvalidDimension); + } + Ok(RetainedOriginalMtpWeights { + binding: binding.identity(), + context: self.context, + dense, + experts, + source: WeightSource::Pinned, + dense_file_bytes: pinned_dense_bytes(), + loaded_bytes: 0, + extras: Vec::new(), + }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs new file mode 100644 index 00000000..cf2bb878 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_mtp_weights/impl_retainedoriginalmtpweights.rs @@ -0,0 +1,219 @@ +//! Moved out of the parent module by STRA-338: impl RetainedOriginalMtpWeights, fn rt_kind. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> RetainedOriginalMtpWeights<'ctx> { + /// Original `MtpDrafter::load` weights, taken from the loaded RT bank. + /// Every role of the contract must be present with exactly the retained + /// kind and shape (the pinned path checks the same shapes through its + /// descriptor table); unknown extra tensors stay in the bank, unused, as in + /// Original. The bank's allocations are shared, never copied. + pub(in crate::qwen_forward) fn from_rt_bank( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bank: &leleka_cuda_driver::OriginalMtpRtBank<'ctx>, + ) -> Result { + bank.validate_context(context).map_err(driver_error)?; + let roles = rt_dense_roles(); + let mut dense = Vec::new(); + dense.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?; + for role in roles { + let name = rt_dense_name(role).ok_or(Error::IdentityMismatch)?; + let (kind, rows, columns) = rt_dense_shape(role).ok_or(Error::IdentityMismatch)?; + let tensor = bank.tensor(name, rt_kind(kind)?).ok_or(Error::InvalidDimension)?; + if (tensor.rows(), tensor.columns()) != (rows, columns) { + return Err(Error::InvalidDimension); + } + dense.push(RetainedDense { role, kind, rows, columns, buffer: tensor.buffer() }); + } + let experts = bank.experts(); + if bank.expert_count() != 512 || experts.len() != 707_788_800 { + return Err(Error::InvalidDimension); + } + let mut extras = Vec::new(); + extras.try_reserve_exact(bank.tensors().len()).map_err(|_| Error::InputAllocation)?; + for tensor in bank.tensors() { + let buffer = tensor.buffer(); + if !dense.iter().any(|entry| Rc::ptr_eq(&entry.buffer, &buffer)) { + extras.push(buffer); + } + } + Ok(Self { + binding: binding.identity(), + context, + dense, + experts, + source: WeightSource::RtDirectory, + dense_file_bytes: bank.dense_file_bytes(), + loaded_bytes: bank.vram_bytes(), + extras, + }) + } + pub(in crate::qwen_forward) fn dense_file_bytes(&self) -> u64 { + self.dense_file_bytes + } + pub(in crate::qwen_forward) fn loaded_bytes(&self) -> u64 { + self.loaded_bytes + } + pub(super) fn validate(&self, binding: &ModelBinding, context: &Context<'ctx>) -> Result<()> { + if self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(context, self.context) { + return Err(Error::IdentityMismatch); + } + match self.source { + WeightSource::Pinned => { + binding.mtp_weights().map_err(binding_error)?.validate_sources(binding).map_err(binding_error) + } + // The bank is device-resident and was matched at construction; + // re-prove that every retained allocation still belongs to this context. + WeightSource::RtDirectory => { + if self.experts.len() != 707_788_800 + || self.dense.iter().any(|entry| entry.buffer.len() == 0) + || self.extras.iter().any(|buffer| buffer.len() == 0) + { + return Err(Error::InvalidDimension); + } + Ok(()) + } + } + } + pub(in crate::qwen_forward) fn matrix( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + role: MtpRole, + ) -> Result<(MtpKind, usize, usize, Rc>)> { + self.validate(binding, context)?; + let entry = self.dense.iter().find(|entry| entry.role == role).ok_or(Error::IdentityMismatch)?; + let expected = match self.source { + WeightSource::Pinned => { + binding.mtp_weights().map_err(binding_error)?.dense_shape(binding, role).map_err(binding_error)? + } + WeightSource::RtDirectory => rt_dense_shape(role).ok_or(Error::IdentityMismatch)?, + }; + if expected != (entry.kind, entry.rows, entry.columns) { + return Err(Error::IdentityMismatch); + } + Ok((entry.kind, entry.rows, entry.columns, Rc::clone(&entry.buffer))) + } + pub(in crate::qwen_forward) fn expert_bank( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + ) -> Result>> { + self.validate(binding, context)?; + Ok(Rc::clone(&self.experts)) + } + /// The scalar prefill graphs retain these exact model allocations, including + /// the genuine whole embedding table. Shape metadata cannot replace an Rc + /// owner or permit a different allocation to be substituted during capture. + pub(in crate::qwen_forward) fn scalar_prefill_weights( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + embedding: &super::super::super::executor::original_prompt::embedding::OriginalPromptEmbedding<'ctx>, + ) -> Result>> { + self.validate(binding, context)?; + let acquire = |role, expected| -> Result>> { + let (kind, rows, columns, owner) = self.matrix(binding, context, role)?; + if (kind, rows, columns) != expected { + return Err(Error::InvalidDimension); + } + Ok(owner) + }; + let roles = [ + acquire(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560))?, + acquire(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560))?, + acquire(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240))?, + acquire(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560))?, + acquire(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240))?, + acquire(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240))?, + acquire(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320))?, + acquire(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560))?, + acquire(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560))?, + acquire(MtpRole::KeyNorm, (MtpKind::F32, 1, 256))?, + acquire(MtpRole::AttentionInject, (MtpKind::Bf16, 4, 10240))?, + ]; + let (table, _, _, _) = embedding.retain(binding, context)?; + let descriptor = embedding.borrow(binding, context)?; + let bank = + leleka_cuda_driver::OriginalMtpRetainedScalarWeights::retain(self.context, roles, table, &descriptor) + .map_err(driver_error)?; + self.validate(binding, context)?; + Ok(Rc::new(bank)) + } + /// Exact full MTP forward role order. The caller lends the model-affine + /// native-head allocation from `OriginalNativeOutput::mtp_head`; this + /// cache never fabricates a replacement head buffer or dispatch profile. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn full_forward_weights( + &self, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + prefix: Rc>, + head: &OriginalMtpNativeHead<'ctx>, + id_vocab: usize, + draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>, + ) -> Result>> { + self.validate(binding, context)?; + if head.columns() != 2560 || id_vocab != head.vocabulary() { + return Err(Error::InvalidDimension); + } + let acquire = |role, expected| -> Result>> { + let (kind, rows, columns, owner) = self.matrix(binding, context, role)?; + if (kind, rows, columns) != expected { + return Err(Error::InvalidDimension); + } + Ok(owner) + }; + let roles = FULL_FORWARD_ROLES.map(|(role, expected)| acquire(role, expected)); + let mut acquired = Vec::new(); + acquired.try_reserve_exact(roles.len()).map_err(|_| Error::InputAllocation)?; + for role in roles { + acquired.push(role?); + } + let roles: [Rc>; 15] = acquired.try_into().map_err(|_| Error::InvalidDimension)?; + let experts = self.expert_bank(binding, context)?; + // Literal bind: with a draft_vocab subset the draft head is the gathered + // rows (`dhead_`, `n_dvocab_` of them), else the native head itself. + let (head_weights, head_rows, subset) = match draft_head { + Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())), + None => (head.weights(), head.vocabulary(), None), + }; + let weights = leleka_cuda_driver::OriginalMtpRetainedFullWeights::retain( + context, + prefix, + roles, + experts, + head_weights, + head.kind(), + head_rows, + id_vocab, + subset, + head.dispatch(), + ) + .map_err(driver_error)?; + self.validate(binding, context)?; + Ok(Rc::new(weights)) + } + pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result { + self.dense + .capacity() + .checked_mul(std::mem::size_of::>()) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .ok_or(Error::Overflow) + } +} + +pub(super) fn rt_kind(kind: MtpKind) -> Result { + use leleka_cuda_driver::OriginalMtpTensorKind as K; + match kind { + MtpKind::Q8_0 => Ok(K::Q8_0), + MtpKind::Bf16 => Ok(K::Bf16), + MtpKind::F32 => Ok(K::F32), + MtpKind::Q2_0 => Err(Error::InvalidDimension), + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs index c51f18a7..4a8e3c19 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt.rs @@ -3,336 +3,25 @@ //! routed experts come from the actual registered retained model bank. //! This does not fabricate scalar FFN rows or publish a session checkpoint. use super::*; -use crate::qwen_forward::{contract::LayerId, dense_weight_cache::DenseWeightCache}; -use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace, - OriginalDeviceBlock, OriginalDeviceGrRead}; -use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage}; - -/// prefill.cpp `stream_all` order (`begin_prompt_stream`): for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows -/// (default 4096: it copies every expert of every layer, while the per-layer ring copies only the routed ones, about -/// 60% of them at 2048 rows, so a 2048-row chunk is DMA-bound and 20% slower with the stream; ~100% at 8192) over a registered bank every layer's experts are copied by an issuer thread with a bounded copy queue, -/// overlapped with the mixers; the compute path's drains are stream-scoped meanwhile. `LELEKA_PREFILL_STREAM=0` -/// keeps the per-layer copy ring. Measured (docs/prefill-throughput.md, jobs 956-965): 16,000 tokens at chunk 8192 -/// +13..27% prefill tok/s over the per-layer ring, identical greedy ids. -fn prompt_stream_settings() -> Option<(usize, f64)> { - use std::sync::atomic::Ordering; - let on = match PREFILL_STREAM_OVERRIDE.load(Ordering::Relaxed) { - 0 => false, - 1 => true, - _ => crate::settings::process().kv.prefill_stream, - }; - if !on { - return None; - } - Some((crate::settings::process().kv.prefill_stream_min, 45e9)) -} +use crate::qwen_forward::{contract::LayerId, dense_weight_cache::DenseWeightCache}; +use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead}; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; /// Test harness switch for in-process paired A/B (`LELEKA_PREFILL_STREAM_SEQ`): -1 = the environment, 0 off, 1 on. pub static PREFILL_STREAM_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); - -fn native_format(key: MoeWeightDescriptor) -> Result { - match key.raw_kind { - 8 => Ok(GdnNativeFormat::Q8_0), 12 => Ok(GdnNativeFormat::Q4K), - 13 => Ok(GdnNativeFormat::Q5K), 14 => Ok(GdnNativeFormat::Q6K), - 20 => Ok(GdnNativeFormat::Iq4Nl), 23 => Ok(GdnNativeFormat::Iq4Xs), - _ => Err(Error::InvalidDimension), - } -} - - -/// `LELEKA_PREFILL_MOE_SPAN_CACHE` (on by default; `0` restores the walk): see `MoeWeightCache::original_span_cache`. -pub(crate) fn span_cache_enabled() -> bool { - match SPAN_CACHE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { - 0 => return false, - 1 => return true, - _ => {} - } - crate::settings::process().kv.prefill_moe_span_cache -} static SPAN_CACHE_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); -/// Per-arm override for the replay harness: 1 on, 0 off, -1 follow the environment. -pub(crate) fn set_span_cache_override(value: i8) { - SPAN_CACHE_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed); -} -impl<'ctx> MoeWeightCache<'ctx> { - /// Explicit selected factory: real arena-backed MMQ, with no second - /// X/weight/GU/H/Q8/Down payload bank or old host-window prefill owner. - /// The caller loads/adopts the authentic model bank before this boundary. - /// `mtp_pack_experts`: also upload the pinned MTP pack's expert bank (675 MiB). Only the pack-driven draft (no RT directory) reads it; - /// see `new_with_mtp_experts`. - pub(crate) fn new_original_prompt_arena( - binding: &ModelBinding, context: &'ctx Context<'ctx>, options: leleka_cuda_driver::PrefillLayoutOptions, mtp_pack_experts: bool, - ) -> Result { - let capacity = u32::try_from(options.capacity).map_err(|_|Error::InvalidDimension)?; - if !(1..=8192).contains(&capacity) || binding.layer_count() != 48 { - return Err(Error::InvalidDimension); - } - crate::bringup_trace!("DBG arena: start capacity={capacity}"); - let (lease, members) = binding.retained_expert_bank_members().map_err(|e|{crate::bringup_trace!("DBG arena members err: {e:?}");binding_error(e)})?; - crate::bringup_trace!("DBG arena: members ok ({})", members.len()); - let mut workspace = context.native_integer_iq3_mmq_original_formats_workspace() - .map_err(|e|{crate::bringup_trace!("DBG arena step 1 driver err: {e:?}");driver_error(e)})?; - if let Err(primary) = workspace.enable_original_expert_group_arena(capacity) { - let _ = workspace.close(); - return Err(driver_error(primary)); - } - crate::bringup_trace!("DBG arena: workspace+group arena ok"); - let mut cache = match Self::assemble_mmq_with_mtp_experts(binding, context, workspace, mtp_pack_experts) { Ok(c)=>c, Err(e)=>{crate::bringup_trace!("DBG arena assemble_mmq err: {e:?}");return Err(e)} }; - crate::bringup_trace!("DBG arena: assemble_mmq ok"); - cache.original_prompt_mmq = true; - cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; - let result = (|| { - // Create persistent actual streams/events before model cache fills. - // Slot count comes from the same options used to carve the arena. - cache.original_copy_schedule = Some(context.original_mmq_copy_schedule(options.original_ring_slots().map_err(|e|{crate::bringup_trace!("DBG arena step 2 driver err: {e:?}");driver_error(e)})?) - .map_err(|e|{crate::bringup_trace!("DBG arena step 3 driver err: {e:?}");driver_error(e)})?); - cache.original_prompt_device = Some(context.original_moe_prompt_device(capacity as usize) - .map_err(|e|{crate::bringup_trace!("DBG arena step 4 driver err: {e:?}");driver_error(e)})?); - cache.original_expert_bank = Some(Rc::new(context.mapped_expert_bank(lease, members) - .map_err(|e|{crate::bringup_trace!("DBG arena step 5 driver err: {e:?}");driver_error(e)})?)); - let schedule = cache.original_copy_schedule.as_ref().ok_or(Error::IdentityMismatch)?; - let bank = cache.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; - cache.original_prompt_metadata_bytes = schedule.metadata_bytes().map_err(|e|{crate::bringup_trace!("DBG arena step 6 driver err: {e:?}");driver_error(e)})? - .checked_add(bank.metadata_bytes()).and_then(|n|n.checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes())) - .ok_or(Error::Overflow)?; - if cache.original_prompt_metadata_bytes > 16<<20 {return Err(Error::InputAllocation)} - crate::bringup_trace!("DBG arena: schedule/device/bank ok"); - cache.room(0).map_err(|e|{crate::bringup_trace!("DBG arena room err: {e:?}");e})?; - cache.validate(binding, context).map_err(|e|{crate::bringup_trace!("DBG arena validate err: {e:?}");e}) - })(); - if let Err(primary) = result { let _ = cache.close(); return Err(primary); } - Ok(cache) - } - - /// Start (`true`: zeroed counts) or stop collecting the prompt chunks' routed rows per (layer, expert). - pub(in crate::qwen_forward) fn capture_prompt_routing(&mut self, on: bool, decay: f32) { - self.prompt_routing = on.then(|| (vec![0f32; 48 * 512], decay)); - } - /// The counts collected since `capture_prompt_routing(true)` (`layer * 512 + expert`), capture off afterwards. - pub(in crate::qwen_forward) fn take_prompt_routing(&mut self) -> Option> { - self.prompt_routing.take().map(|(counts, _)| counts) - } - - /// End the prompt chunk's expert stream, if any (idempotent; every forward exit calls it). - pub(in crate::qwen_forward) fn end_prompt_stream(&mut self) -> Result<()> { - match self.original_copy_schedule.as_mut() { - Some(schedule) => schedule.end_prompt_stream().map_err(driver_error), - None => Ok(()), - } - } - - /// The registered retained model bank the prompt path streams from: also the source of the VRAM expert - /// tier's fills, lent-slot refills, adaptive swaps and PCIe copies. - pub(crate) fn original_expert_bank(&self) -> Option>> { - self.original_expert_bank.clone() - } - - /// The registered gate/up/down spans of routed expert `expert` of `layer` (generate.cpp `srcp->blob(l, e)`: - /// the bytes of one native expert, in the `native_expert::Format` order the window kernels read). - pub(crate) fn original_expert_spans( - &self, binding: &ModelBinding, layer: u32, expert: u32, - ) -> Result<[ResidentExpertBankSpan; 3]> { - let bank = self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; - if layer >= 48 || expert >= 512 { return Err(Error::InvalidExpert); } - let selected = std::array::from_fn(|i| (expert + i as u32) % 512); - let bound = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; - let members = [(&bound, 0)]; - binding.with_moe_routed_source(&members, binding_error, |source| { - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let operation = (|| { - source.validate_binding(binding).map_err(binding_error)?; - for role in roles { - let key = source.descriptor(0, role).map_err(binding_error)?; - if key.layer != layer || key.expert != Some(expert) { return Err(Error::IdentityMismatch); } - } - let spans = [source.mapped_span(0, roles[0]).map_err(binding_error)?, - source.mapped_span(0, roles[1]).map_err(binding_error)?, - source.mapped_span(0, roles[2]).map_err(binding_error)?]; - if !bank.eligible(&spans) { return Err(Error::IdentityMismatch); } - Ok(spans) - })(); - let finish = source.finish().map_err(binding_error); - match operation { Err(e) => Err(e), Ok(v) => { finish?; Ok(v) } } - }) - } - - /// Resolve genuine whole shared G/U/D/scalar buffers before lending any of - /// them to the device program. Protect all four against cache eviction. - pub(super) fn original_shared_layer( - &mut self, binding: &ModelBinding, layer: LayerId, - ) -> Result<[MoeWeightDescriptor; 4]> { - let weights = binding.moe_expert_weights(layer.get(), std::array::from_fn(|i| i as u32)) - .map_err(binding_error)?; - if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let keys = [ - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?, - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?, - binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?, - binding.moe_shared_scalar_descriptor(&weights).map_err(binding_error)?, - ]; - crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?; - if keys.iter().any(|key| key.layer != layer.get()) { return Err(Error::IdentityMismatch); } - for (i, key) in keys.iter().enumerate() { - let _ = self.main_entry_protected(*key, &keys, || { - if i == 3 { binding.moe_shared_scalar(&weights).map_err(binding_error) } - else { Ok(binding.moe_expert_block(&weights, MoeExpertSelection::Shared, - roles[i], 0, key.rows).map_err(binding_error)?.into_bytes()) } - })?; - } - self.room_protected(0, &keys)?; - Ok(keys) - } - - /// Genuine device FFN read -> router/shared -> ascending groups of16 -> - /// weighted combine, preserving the affine arena loan through final drain. - /// The outer PromptDeviceRead authenticates every chronological session row - /// before this call and performs the following GR injection itself. - pub(in crate::qwen_forward) fn original_prompt_moe<'arena, 'loan>( - &mut self, binding: &ModelBinding, dense: &DenseWeightCache<'ctx>, - layer: LayerId, read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, - shared: &mut NativeBatchWorkspace<'ctx>, - ) -> Result> { - self.validate(binding, self.context)?; - if !self.original_prompt_mmq || self.original_prompt_device.is_none() - || self.original_expert_bank.is_none() { return Err(Error::IdentityMismatch); } - let retained = dense.retained_context(binding, self.context)?; - if !std::ptr::eq(retained, self.context) { return Err(Error::IdentityMismatch); } - let keys = self.original_shared_layer(binding, layer)?; - let formats = [native_format(keys[0])?, native_format(keys[1])?, native_format(keys[2])?]; - let router = dense.router(binding, layer.get())?; - let main = &self.main; - let raw = |i: usize| -> Result<&DeviceBuffer<'ctx>> { - let entry = main.get(&keys[i]).ok_or(Error::IdentityMismatch)?; - if entry.charged_bytes != keys[i].bytes { return Err(Error::IdentityMismatch); } - match &entry.weight { EncodedWeight::Raw(b) => Ok(b), _ => Err(Error::IdentityMismatch) } - }; - let weights = [router, raw(3)?, raw(0)?, raw(1)?, raw(2)?]; - let bank = Rc::clone(self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?); - let program = self.original_prompt_device.as_mut().ok_or(Error::IdentityMismatch)?; - let mmq = self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; - let schedule = self.original_copy_schedule.as_mut().ok_or(Error::IdentityMismatch)?; - let finite = &mut self.original_finite_experts; - let span_cache = &mut self.original_span_cache; - let span_cache_on = span_cache_enabled(); - if span_cache_on && span_cache.0 != Rc::as_ptr(&bank) as usize { - *span_cache = (Rc::as_ptr(&bank) as usize, Vec::new()); - } - schedule.validate_context(self.context).map_err(driver_error)?; - let context = self.context; - let drain = Some(context as &dyn prof::Drain); - let last_layer = layer.get() + 1 == binding.layer_count(); - let result = (|| { - if layer.get() == 0 && !schedule.prompt_stream_active() - && let Some((minimum, bytes_per_second)) = prompt_stream_settings() - && read.rows() >= minimum && !bank.pageable() - { - // the whole chunk's expert stream starts with the first MoE layer - schedule.begin_prompt_stream(&read, &bank, 0, bytes_per_second).map_err(driver_error)?; - crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows()); - } - // High-only is the selected literal Original mixed BF16 policy. - let prepare_span = prof::span(PStage::MoePrepare, drain); - let mut layer_program = program.prepare(read, shared, weights, formats, false) - .map_err(driver_error)?; - drop(prepare_span); - if let Some((routing, decay)) = self.prompt_routing.as_mut() { - // seed capture: the routed rows per expert are already on the host (grouping read the route IDs); - // the first layer of a chunk fades the earlier chunks' counts (decay 1: none) - if layer.get() == 0 && *decay != 1.0 { - routing.iter_mut().for_each(|v| *v *= *decay); - } - for (&expert, &rows) in layer_program.experts().iter().zip(layer_program.counts()) { - routing[layer.get() as usize * 512 + expert as usize] += rows as f32; - } - } - let spans_span = prof::span(PStage::MoeSpans, None); - let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); - sources.try_reserve_exact(layer_program.experts().len()).map_err(|_| Error::InputAllocation)?; - let mut routed_formats = None; - for &expert in layer_program.experts() { - // These are binding-resolved weights, not a synthetic RouteRow. - // The expert itself is the actual GPU route's authenticated ID. - let selected = std::array::from_fn(|i| (expert + i as u32) % 512); - let bound = binding.moe_expert_weights(layer.get(), selected).map_err(binding_error)?; - let members = [(&bound, 0)]; - let bit = layer.get() as usize * 512 + expert as usize; - let admitted = bit < 48 * 512 && finite[bit / 64] >> (bit % 64) & 1 == 1; - if span_cache_on && admitted - && let Some((spans, format)) = span_cache.1.get(bit).and_then(Option::as_ref) - { - // the same checks the walk below ends with, on the spans it resolved when this expert was admitted - if !bank.eligible(spans) { return Err(Error::IdentityMismatch); } - if routed_formats.is_some_and(|previous| previous != *format) { return Err(Error::IdentityMismatch); } - routed_formats = Some(*format); - sources.push(spans.clone()); - continue; - } - let ((span, scanned), format) = binding.with_moe_routed_source(&members, binding_error, |source| { - let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; - let operation = (|| { - source.validate_binding(binding).map_err(binding_error)?; - let keys = [source.descriptor(0, roles[0]).map_err(binding_error)?, - source.descriptor(0, roles[1]).map_err(binding_error)?, - source.descriptor(0, roles[2]).map_err(binding_error)?]; - if keys.iter().any(|key| key.layer != layer.get() || key.expert != Some(expert)) { - return Err(Error::IdentityMismatch); - } - let formats = [original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?.0, - original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?.0, - original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?.0]; - // The whole finite admission of an expert's immutable bank bytes runs once per bank; - // later chunks take the same descriptor/geometry-checked span without the rescan. An expert - // the copy ring stages through page-locked host buffers (a pageable bank) is checked by the - // stager's helpers on the bytes they copy, so the source is not read twice. - let located = [source.bank_span(0, roles[0]).map_err(binding_error)?, - source.bank_span(0, roles[1]).map_err(binding_error)?, - source.bank_span(0, roles[2]).map_err(binding_error)?]; - let (spans, scanned) = if admitted || bank.host_staged(&located) { (located, false) } else { - ([source.mapped_span(0, roles[0]).map_err(binding_error)?, - source.mapped_span(0, roles[1]).map_err(binding_error)?, - source.mapped_span(0, roles[2]).map_err(binding_error)?], true) - }; - if !bank.eligible(&spans) { return Err(Error::IdentityMismatch); } - Ok(((spans, scanned), formats)) - })(); - // Actual retained immutable spans survive this source fence; - // every later DMA holds the real bank owner, not this scope. - let finish = source.finish().map_err(binding_error); - match operation { Err(e) => Err(e), Ok(v) => { finish?; Ok(v) } } - })?; - if bit >= 48 * 512 { return Err(Error::InvalidExpert); } - if scanned { finite[bit / 64] |= 1 << (bit % 64); } - if routed_formats.is_some_and(|previous| previous != format) { return Err(Error::IdentityMismatch); } - routed_formats = Some(format); - if span_cache_on && admitted && !scanned { - if span_cache.1.is_empty() { span_cache.1.resize_with(48 * 512, || None); } - span_cache.1[bit] = Some((span.clone(), format)); - } - sources.push(span); - } - let outside = bank.metadata_bytes().checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes()) - .and_then(|n|n.checked_add(sources.capacity().checked_mul(std::mem::size_of::<[ResidentExpertBankSpan;3]>())?)) - .and_then(|n|n.checked_add(layer_program.metadata_bytes().ok()?)).ok_or(Error::Overflow)?; - schedule.retain_host_metadata_charge(outside).map_err(driver_error)?; - drop(spans_span); - let ring_span = prof::span(PStage::MoeRing, drain); - layer_program.execute_original_copy_ring(mmq, schedule, layer.get() as usize, Rc::clone(&bank), - routed_formats.ok_or(Error::IdentityMismatch)?, &sources).map_err(driver_error)?; - drop(ring_span); - let _span = prof::span(PStage::MoeFinish, drain); - let block = layer_program.finish(shared).map_err(driver_error)?; - if last_layer && schedule.prompt_stream_active() { - schedule.end_prompt_stream().map_err(driver_error)?; - } - Ok(block) - })(); - if result.is_err() { - // the stream never outlives a failed layer - let _ = schedule.end_prompt_stream(); - } - if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } - result - } -} +#[path = "cache_original_prompt/prompt_stream_settings_fn.rs"] +mod prompt_stream_settings_fn; +#[allow(unused_imports)] +use prompt_stream_settings_fn::native_format; +#[allow(unused_imports)] +use prompt_stream_settings_fn::prompt_stream_settings; +#[allow(unused_imports)] +pub(crate) use prompt_stream_settings_fn::set_span_cache_override; +#[allow(unused_imports)] +pub(crate) use prompt_stream_settings_fn::span_cache_enabled; +#[path = "cache_original_prompt/impl_moeweightcache.rs"] +mod impl_moeweightcache; +#[path = "cache_original_prompt/impl_moeweightcache_2.rs"] +mod impl_moeweightcache_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs new file mode 100644 index 00000000..048be569 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache.rs @@ -0,0 +1,208 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> MoeWeightCache<'ctx> { + /// Explicit selected factory: real arena-backed MMQ, with no second + /// X/weight/GU/H/Q8/Down payload bank or old host-window prefill owner. + /// The caller loads/adopts the authentic model bank before this boundary. + /// `mtp_pack_experts`: also upload the pinned MTP pack's expert bank (675 MiB). Only the pack-driven draft (no RT directory) reads it; + /// see `new_with_mtp_experts`. + pub(crate) fn new_original_prompt_arena( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + options: leleka_cuda_driver::PrefillLayoutOptions, + mtp_pack_experts: bool, + ) -> Result { + let capacity = u32::try_from(options.capacity).map_err(|_| Error::InvalidDimension)?; + if !(1..=8192).contains(&capacity) || binding.layer_count() != 48 { + return Err(Error::InvalidDimension); + } + crate::bringup_trace!("DBG arena: start capacity={capacity}"); + let (lease, members) = binding.retained_expert_bank_members().map_err(|e| { + crate::bringup_trace!("DBG arena members err: {e:?}"); + binding_error(e) + })?; + crate::bringup_trace!("DBG arena: members ok ({})", members.len()); + let mut workspace = context.native_integer_iq3_mmq_original_formats_workspace().map_err(|e| { + crate::bringup_trace!("DBG arena step 1 driver err: {e:?}"); + driver_error(e) + })?; + if let Err(primary) = workspace.enable_original_expert_group_arena(capacity) { + let _ = workspace.close(); + return Err(driver_error(primary)); + } + crate::bringup_trace!("DBG arena: workspace+group arena ok"); + let mut cache = match Self::assemble_mmq_with_mtp_experts(binding, context, workspace, mtp_pack_experts) { + Ok(c) => c, + Err(e) => { + crate::bringup_trace!("DBG arena assemble_mmq err: {e:?}"); + return Err(e); + } + }; + crate::bringup_trace!("DBG arena: assemble_mmq ok"); + cache.original_prompt_mmq = true; + cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; + let result = (|| { + // Create persistent actual streams/events before model cache fills. + // Slot count comes from the same options used to carve the arena. + cache.original_copy_schedule = Some( + context + .original_mmq_copy_schedule(options.original_ring_slots().map_err(|e| { + crate::bringup_trace!("DBG arena step 2 driver err: {e:?}"); + driver_error(e) + })?) + .map_err(|e| { + crate::bringup_trace!("DBG arena step 3 driver err: {e:?}"); + driver_error(e) + })?, + ); + cache.original_prompt_device = + Some(context.original_moe_prompt_device(capacity as usize).map_err(|e| { + crate::bringup_trace!("DBG arena step 4 driver err: {e:?}"); + driver_error(e) + })?); + cache.original_expert_bank = Some(Rc::new(context.mapped_expert_bank(lease, members).map_err(|e| { + crate::bringup_trace!("DBG arena step 5 driver err: {e:?}"); + driver_error(e) + })?)); + let schedule = cache.original_copy_schedule.as_ref().ok_or(Error::IdentityMismatch)?; + let bank = cache.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; + cache.original_prompt_metadata_bytes = schedule + .metadata_bytes() + .map_err(|e| { + crate::bringup_trace!("DBG arena step 6 driver err: {e:?}"); + driver_error(e) + })? + .checked_add(bank.metadata_bytes()) + .and_then(|n| n.checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes())) + .ok_or(Error::Overflow)?; + if cache.original_prompt_metadata_bytes > 16 << 20 { + return Err(Error::InputAllocation); + } + crate::bringup_trace!("DBG arena: schedule/device/bank ok"); + cache.room(0).map_err(|e| { + crate::bringup_trace!("DBG arena room err: {e:?}"); + e + })?; + cache.validate(binding, context).map_err(|e| { + crate::bringup_trace!("DBG arena validate err: {e:?}"); + e + }) + })(); + if let Err(primary) = result { + let _ = cache.close(); + return Err(primary); + } + Ok(cache) + } + + /// Start (`true`: zeroed counts) or stop collecting the prompt chunks' routed rows per (layer, expert). + pub(in crate::qwen_forward) fn capture_prompt_routing(&mut self, on: bool, decay: f32) { + self.prompt_routing = on.then(|| (vec![0f32; 48 * 512], decay)); + } + /// The counts collected since `capture_prompt_routing(true)` (`layer * 512 + expert`), capture off afterwards. + pub(in crate::qwen_forward) fn take_prompt_routing(&mut self) -> Option> { + self.prompt_routing.take().map(|(counts, _)| counts) + } + + /// End the prompt chunk's expert stream, if any (idempotent; every forward exit calls it). + pub(in crate::qwen_forward) fn end_prompt_stream(&mut self) -> Result<()> { + match self.original_copy_schedule.as_mut() { + Some(schedule) => schedule.end_prompt_stream().map_err(driver_error), + None => Ok(()), + } + } + + /// The registered retained model bank the prompt path streams from: also the source of the VRAM expert + /// tier's fills, lent-slot refills, adaptive swaps and PCIe copies. + pub(crate) fn original_expert_bank(&self) -> Option>> { + self.original_expert_bank.clone() + } + + /// The registered gate/up/down spans of routed expert `expert` of `layer` (generate.cpp `srcp->blob(l, e)`: + /// the bytes of one native expert, in the `native_expert::Format` order the window kernels read). + pub(crate) fn original_expert_spans( + &self, + binding: &ModelBinding, + layer: u32, + expert: u32, + ) -> Result<[ResidentExpertBankSpan; 3]> { + let bank = self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?; + if layer >= 48 || expert >= 512 { + return Err(Error::InvalidExpert); + } + let selected = std::array::from_fn(|i| (expert + i as u32) % 512); + let bound = binding.moe_expert_weights(layer, selected).map_err(binding_error)?; + let members = [(&bound, 0)]; + binding.with_moe_routed_source(&members, binding_error, |source| { + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let operation = (|| { + source.validate_binding(binding).map_err(binding_error)?; + for role in roles { + let key = source.descriptor(0, role).map_err(binding_error)?; + if key.layer != layer || key.expert != Some(expert) { + return Err(Error::IdentityMismatch); + } + } + let spans = [ + source.mapped_span(0, roles[0]).map_err(binding_error)?, + source.mapped_span(0, roles[1]).map_err(binding_error)?, + source.mapped_span(0, roles[2]).map_err(binding_error)?, + ]; + if !bank.eligible(&spans) { + return Err(Error::IdentityMismatch); + } + Ok(spans) + })(); + let finish = source.finish().map_err(binding_error); + match operation { + Err(e) => Err(e), + Ok(v) => { + finish?; + Ok(v) + } + } + }) + } + + /// Resolve genuine whole shared G/U/D/scalar buffers before lending any of + /// them to the device program. Protect all four against cache eviction. + pub(in super::super) fn original_shared_layer( + &mut self, + binding: &ModelBinding, + layer: LayerId, + ) -> Result<[MoeWeightDescriptor; 4]> { + let weights = + binding.moe_expert_weights(layer.get(), std::array::from_fn(|i| i as u32)).map_err(binding_error)?; + if !weights.matches(&binding.identity(), layer.get()) { + return Err(Error::IdentityMismatch); + } + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let keys = [ + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?, + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?, + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?, + binding.moe_shared_scalar_descriptor(&weights).map_err(binding_error)?, + ]; + crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?; + if keys.iter().any(|key| key.layer != layer.get()) { + return Err(Error::IdentityMismatch); + } + for (i, key) in keys.iter().enumerate() { + let _ = self.main_entry_protected(*key, &keys, || { + if i == 3 { + binding.moe_shared_scalar(&weights).map_err(binding_error) + } else { + Ok(binding + .moe_expert_block(&weights, MoeExpertSelection::Shared, roles[i], 0, key.rows) + .map_err(binding_error)? + .into_bytes()) + } + })?; + } + self.room_protected(0, &keys)?; + Ok(keys) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs new file mode 100644 index 00000000..0e964041 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/impl_moeweightcache_2.rs @@ -0,0 +1,218 @@ +//! Moved out of the parent module by STRA-338: impl MoeWeightCache (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> MoeWeightCache<'ctx> { + /// Genuine device FFN read -> router/shared -> ascending groups of16 -> + /// weighted combine, preserving the affine arena loan through final drain. + /// The outer PromptDeviceRead authenticates every chronological session row + /// before this call and performs the following GR injection itself. + pub(in crate::qwen_forward) fn original_prompt_moe<'arena, 'loan>( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + layer: LayerId, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + shared: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.validate(binding, self.context)?; + if !self.original_prompt_mmq || self.original_prompt_device.is_none() || self.original_expert_bank.is_none() { + return Err(Error::IdentityMismatch); + } + let retained = dense.retained_context(binding, self.context)?; + if !std::ptr::eq(retained, self.context) { + return Err(Error::IdentityMismatch); + } + let keys = self.original_shared_layer(binding, layer)?; + let formats = [native_format(keys[0])?, native_format(keys[1])?, native_format(keys[2])?]; + let router = dense.router(binding, layer.get())?; + let main = &self.main; + let raw = |i: usize| -> Result<&DeviceBuffer<'ctx>> { + let entry = main.get(&keys[i]).ok_or(Error::IdentityMismatch)?; + if entry.charged_bytes != keys[i].bytes { + return Err(Error::IdentityMismatch); + } + match &entry.weight { + EncodedWeight::Raw(b) => Ok(b), + _ => Err(Error::IdentityMismatch), + } + }; + let weights = [router, raw(3)?, raw(0)?, raw(1)?, raw(2)?]; + let bank = Rc::clone(self.original_expert_bank.as_ref().ok_or(Error::IdentityMismatch)?); + let program = self.original_prompt_device.as_mut().ok_or(Error::IdentityMismatch)?; + let mmq = self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; + let schedule = self.original_copy_schedule.as_mut().ok_or(Error::IdentityMismatch)?; + let finite = &mut self.original_finite_experts; + let span_cache = &mut self.original_span_cache; + let span_cache_on = span_cache_enabled(); + if span_cache_on && span_cache.0 != Rc::as_ptr(&bank) as usize { + *span_cache = (Rc::as_ptr(&bank) as usize, Vec::new()); + } + schedule.validate_context(self.context).map_err(driver_error)?; + let context = self.context; + let drain = Some(context as &dyn prof::Drain); + let last_layer = layer.get() + 1 == binding.layer_count(); + let result = (|| { + if layer.get() == 0 + && !schedule.prompt_stream_active() + && let Some((minimum, bytes_per_second)) = prompt_stream_settings() + && read.rows() >= minimum + && !bank.pageable() + { + // the whole chunk's expert stream starts with the first MoE layer + schedule.begin_prompt_stream(&read, &bank, 0, bytes_per_second).map_err(driver_error)?; + crate::bringup_trace!("DBG prefill stream: begin rows={}", read.rows()); + } + // High-only is the selected literal Original mixed BF16 policy. + let prepare_span = prof::span(PStage::MoePrepare, drain); + let mut layer_program = program.prepare(read, shared, weights, formats, false).map_err(driver_error)?; + drop(prepare_span); + if let Some((routing, decay)) = self.prompt_routing.as_mut() { + // seed capture: the routed rows per expert are already on the host (grouping read the route IDs); + // the first layer of a chunk fades the earlier chunks' counts (decay 1: none) + if layer.get() == 0 && *decay != 1.0 { + routing.iter_mut().for_each(|v| *v *= *decay); + } + for (&expert, &rows) in layer_program.experts().iter().zip(layer_program.counts()) { + routing[layer.get() as usize * 512 + expert as usize] += rows as f32; + } + } + let spans_span = prof::span(PStage::MoeSpans, None); + let mut sources: Vec<[ResidentExpertBankSpan; 3]> = Vec::new(); + sources.try_reserve_exact(layer_program.experts().len()).map_err(|_| Error::InputAllocation)?; + let mut routed_formats = None; + for &expert in layer_program.experts() { + // These are binding-resolved weights, not a synthetic RouteRow. + // The expert itself is the actual GPU route's authenticated ID. + let selected = std::array::from_fn(|i| (expert + i as u32) % 512); + let bound = binding.moe_expert_weights(layer.get(), selected).map_err(binding_error)?; + let members = [(&bound, 0)]; + let bit = layer.get() as usize * 512 + expert as usize; + let admitted = bit < 48 * 512 && finite[bit / 64] >> (bit % 64) & 1 == 1; + if span_cache_on + && admitted + && let Some((spans, format)) = span_cache.1.get(bit).and_then(Option::as_ref) + { + // the same checks the walk below ends with, on the spans it resolved when this expert was admitted + if !bank.eligible(spans) { + return Err(Error::IdentityMismatch); + } + if routed_formats.is_some_and(|previous| previous != *format) { + return Err(Error::IdentityMismatch); + } + routed_formats = Some(*format); + sources.push(spans.clone()); + continue; + } + let ((span, scanned), format) = binding.with_moe_routed_source(&members, binding_error, |source| { + let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; + let operation = (|| { + source.validate_binding(binding).map_err(binding_error)?; + let keys = [ + source.descriptor(0, roles[0]).map_err(binding_error)?, + source.descriptor(0, roles[1]).map_err(binding_error)?, + source.descriptor(0, roles[2]).map_err(binding_error)?, + ]; + if keys.iter().any(|key| key.layer != layer.get() || key.expert != Some(expert)) { + return Err(Error::IdentityMismatch); + } + let formats = [ + original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?.0, + original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?.0, + original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?.0, + ]; + // The whole finite admission of an expert's immutable bank bytes runs once per bank; + // later chunks take the same descriptor/geometry-checked span without the rescan. An expert + // the copy ring stages through page-locked host buffers (a pageable bank) is checked by the + // stager's helpers on the bytes they copy, so the source is not read twice. + let located = [ + source.bank_span(0, roles[0]).map_err(binding_error)?, + source.bank_span(0, roles[1]).map_err(binding_error)?, + source.bank_span(0, roles[2]).map_err(binding_error)?, + ]; + let (spans, scanned) = if admitted || bank.host_staged(&located) { + (located, false) + } else { + ( + [ + source.mapped_span(0, roles[0]).map_err(binding_error)?, + source.mapped_span(0, roles[1]).map_err(binding_error)?, + source.mapped_span(0, roles[2]).map_err(binding_error)?, + ], + true, + ) + }; + if !bank.eligible(&spans) { + return Err(Error::IdentityMismatch); + } + Ok(((spans, scanned), formats)) + })(); + // Actual retained immutable spans survive this source fence; + // every later DMA holds the real bank owner, not this scope. + let finish = source.finish().map_err(binding_error); + match operation { + Err(e) => Err(e), + Ok(v) => { + finish?; + Ok(v) + } + } + })?; + if bit >= 48 * 512 { + return Err(Error::InvalidExpert); + } + if scanned { + finite[bit / 64] |= 1 << (bit % 64); + } + if routed_formats.is_some_and(|previous| previous != format) { + return Err(Error::IdentityMismatch); + } + routed_formats = Some(format); + if span_cache_on && admitted && !scanned { + if span_cache.1.is_empty() { + span_cache.1.resize_with(48 * 512, || None); + } + span_cache.1[bit] = Some((span.clone(), format)); + } + sources.push(span); + } + let outside = bank + .metadata_bytes() + .checked_add(leleka_cuda_driver::OriginalPromptLeaseIdentity::metadata_bytes()) + .and_then(|n| { + n.checked_add(sources.capacity().checked_mul(std::mem::size_of::<[ResidentExpertBankSpan; 3]>())?) + }) + .and_then(|n| n.checked_add(layer_program.metadata_bytes().ok()?)) + .ok_or(Error::Overflow)?; + schedule.retain_host_metadata_charge(outside).map_err(driver_error)?; + drop(spans_span); + let ring_span = prof::span(PStage::MoeRing, drain); + layer_program + .execute_original_copy_ring( + mmq, + schedule, + layer.get() as usize, + Rc::clone(&bank), + routed_formats.ok_or(Error::IdentityMismatch)?, + &sources, + ) + .map_err(driver_error)?; + drop(ring_span); + let _span = prof::span(PStage::MoeFinish, drain); + let block = layer_program.finish(shared).map_err(driver_error)?; + if last_layer && schedule.prompt_stream_active() { + schedule.end_prompt_stream().map_err(driver_error)?; + } + Ok(block) + })(); + if result.is_err() { + // the stream never outlives a failed layer + let _ = schedule.end_prompt_stream(); + } + if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { + self.failed.set(true); + } + result + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_stream_settings_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_stream_settings_fn.rs new file mode 100644 index 00000000..9f1fb9d0 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_prompt/prompt_stream_settings_fn.rs @@ -0,0 +1,49 @@ +//! Moved out of the parent module by STRA-338: fn prompt_stream_settings, fn native_format, fn span_cache_enabled, fn set_span_cache_override. + +#[allow(unused_imports)] +use super::*; + +/// prefill.cpp `stream_all` order (`begin_prompt_stream`): for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows +/// (default 4096: it copies every expert of every layer, while the per-layer ring copies only the routed ones, about +/// 60% of them at 2048 rows, so a 2048-row chunk is DMA-bound and 20% slower with the stream; ~100% at 8192) over a registered bank every layer's experts are copied by an issuer thread with a bounded copy queue, +/// overlapped with the mixers; the compute path's drains are stream-scoped meanwhile. `LELEKA_PREFILL_STREAM=0` +/// keeps the per-layer copy ring. Measured (docs/prefill-throughput.md, jobs 956-965): 16,000 tokens at chunk 8192 +/// +13..27% prefill tok/s over the per-layer ring, identical greedy ids. +pub(super) fn prompt_stream_settings() -> Option<(usize, f64)> { + use std::sync::atomic::Ordering; + let on = match PREFILL_STREAM_OVERRIDE.load(Ordering::Relaxed) { + 0 => false, + 1 => true, + _ => crate::settings::process().kv.prefill_stream, + }; + if !on { + return None; + } + Some((crate::settings::process().kv.prefill_stream_min, 45e9)) +} + +pub(super) fn native_format(key: MoeWeightDescriptor) -> Result { + match key.raw_kind { + 8 => Ok(GdnNativeFormat::Q8_0), + 12 => Ok(GdnNativeFormat::Q4K), + 13 => Ok(GdnNativeFormat::Q5K), + 14 => Ok(GdnNativeFormat::Q6K), + 20 => Ok(GdnNativeFormat::Iq4Nl), + 23 => Ok(GdnNativeFormat::Iq4Xs), + _ => Err(Error::InvalidDimension), + } +} + +/// `LELEKA_PREFILL_MOE_SPAN_CACHE` (on by default; `0` restores the walk): see `MoeWeightCache::original_span_cache`. +pub(crate) fn span_cache_enabled() -> bool { + match SPAN_CACHE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return false, + 1 => return true, + _ => {} + } + crate::settings::process().kv.prefill_moe_span_cache +} +/// Per-arm override for the replay harness: 1 on, 0 off, -1 follow the environment. +pub(crate) fn set_span_cache_override(value: i8) { + SPAN_CACHE_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_verify.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_verify.rs index 6920ea79..8029a457 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_verify.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_original_verify.rs @@ -21,7 +21,10 @@ pub(in crate::qwen_forward) type SharedKeys = Vec<[MoeWeightDescriptor; 4]>; impl<'ctx> MoeWeightCache<'ctx> { /// Make the shared expert tensors of every layer resident together. Misses fill from the model through the /// cache's own loader; hits only refresh their LRU age. - pub(in crate::qwen_forward) fn ensure_original_verify_shared(&mut self, binding: &ModelBinding) -> Result { + pub(in crate::qwen_forward) fn ensure_original_verify_shared( + &mut self, + binding: &ModelBinding, + ) -> Result { self.validate(binding, self.context)?; let mut all = Vec::new(); all.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile.rs index 18a064c8..e47fd02e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile.rs @@ -7,8 +7,8 @@ const EXPERTS: usize = 512; const PAIRS: usize = LAYERS * EXPERTS; pub(super) const HOST_CAP: usize = 16 * 1024 * 1024; pub(super) const PROFILE_SHA: [u8; 32] = [ - 0x8f, 0x59, 0xb4, 0xaa, 0x88, 0x73, 0x20, 0x9d, 0xff, 0x11, 0xc1, 0x1e, 0x37, 0xbc, 0xda, 0x95, - 0x29, 0xa1, 0x33, 0x5b, 0x72, 0x4a, 0x1a, 0xfe, 0xea, 0x37, 0xbf, 0x63, 0x88, 0x97, 0x5b, 0xaf, + 0x8f, 0x59, 0xb4, 0xaa, 0x88, 0x73, 0x20, 0x9d, 0xff, 0x11, 0xc1, 0x1e, 0x37, 0xbc, 0xda, 0x95, 0x29, 0xa1, 0x33, + 0x5b, 0x72, 0x4a, 0x1a, 0xfe, 0xea, 0x37, 0xbf, 0x63, 0x88, 0x97, 0x5b, 0xaf, ]; pub(super) struct RankedProfile { pairs: Vec<(u16, u16)>, @@ -132,6 +132,6 @@ mod impl_rankedprofile; #[path = "cache_profile/impl_sharedpermanentpool.rs"] mod impl_sharedpermanentpool; #[allow(unused_imports)] -pub(super) use impl_sharedpermanentpool::remaining_shared_main; -#[allow(unused_imports)] pub(super) use impl_sharedpermanentpool::learned_main_slot_bound; +#[allow(unused_imports)] +pub(super) use impl_sharedpermanentpool::remaining_shared_main; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_rankedprofile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_rankedprofile.rs index cd022e04..4825e740 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_rankedprofile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_rankedprofile.rs @@ -8,21 +8,16 @@ impl RankedProfile { const BASE: usize = 24 + PAIRS * 4; if !matches!(bytes.len(), BASE | 196_632) || bytes[..4] != *b"STRP" - || [1, 48, 512, 24_576, 24_576] - .into_iter() - .enumerate() - .any(|(i, value)| { - let p = 4 + i * 4; - u32::from_le_bytes(bytes[p..p + 4].try_into().unwrap()) != value - }) + || [1, 48, 512, 24_576, 24_576].into_iter().enumerate().any(|(i, value)| { + let p = 4 + i * 4; + u32::from_le_bytes(bytes[p..p + 4].try_into().unwrap()) != value + }) || Sha256::digest(bytes).as_slice() != expected_sha { return Err(Error::IdentityMismatch); } let mut pairs = Vec::new(); - pairs - .try_reserve_exact(PAIRS) - .map_err(|_| Error::InputAllocation)?; + pairs.try_reserve_exact(PAIRS).map_err(|_| Error::InputAllocation)?; let mut seen = [false; PAIRS]; for (rank, b) in bytes[24..BASE].as_chunks::<4>().0.iter().enumerate() { let layer = u16::from_le_bytes([b[0], b[1]]); @@ -69,19 +64,11 @@ impl PrefixPlan { if roles.contains(&0) { return Err(Error::InvalidDimension); } - *total = roles - .iter() - .try_fold(0usize, |v, n| v.checked_add(*n)) - .ok_or(Error::Overflow)?; + *total = roles.iter().try_fold(0usize, |v, n| v.checked_add(*n)).ok_or(Error::Overflow)?; } let largest_triplet = *totals.iter().max().ok_or(Error::InvalidDimension)?; - let spill_reserve = limits - .window_spill - .checked_add(largest_triplet) - .ok_or(Error::Overflow)?; - let external = spill_reserve - .checked_add(limits.working_reserve) - .ok_or(Error::Overflow)?; + let spill_reserve = limits.window_spill.checked_add(largest_triplet).ok_or(Error::Overflow)?; + let external = spill_reserve.checked_add(limits.working_reserve).ok_or(Error::Overflow)?; let capacity = limits .main_cap .checked_sub(spill_reserve) @@ -92,17 +79,10 @@ impl PrefixPlan { .and_then(|v| v.checked_sub(external)) .map(|typed| main.min(typed)) }) - .and_then(|typed| { - limits - .physical_free - .checked_sub(external) - .map(|free| typed.min(free)) - }) + .and_then(|typed| limits.physical_free.checked_sub(external).map(|free| typed.min(free))) .ok_or(Error::InputAllocation)?; let mut selected = Vec::new(); - selected - .try_reserve_exact(PAIRS) - .map_err(|_| Error::InputAllocation)?; + selected.try_reserve_exact(PAIRS).map_err(|_| Error::InputAllocation)?; selected.resize(PAIRS, false); if profile .metadata_bytes() @@ -114,9 +94,7 @@ impl PrefixPlan { let mut charged_bytes = 0usize; let mut prefix = 0; for &(layer, expert) in profile.ordered_pairs() { - let next = charged_bytes - .checked_add(totals[usize::from(layer)]) - .ok_or(Error::Overflow)?; + let next = charged_bytes.checked_add(totals[usize::from(layer)]).ok_or(Error::Overflow)?; if next > capacity { break; } @@ -147,19 +125,11 @@ impl PrefixPlan { if roles.contains(&0) { return Err(Error::InvalidDimension); } - *total = roles - .iter() - .try_fold(0usize, |v, n| v.checked_add(*n)) - .ok_or(Error::Overflow)?; + *total = roles.iter().try_fold(0usize, |v, n| v.checked_add(*n)).ok_or(Error::Overflow)?; } let largest_triplet = *totals.iter().max().ok_or(Error::InvalidDimension)?; - let spill_reserve = limits - .window_spill - .checked_add(largest_triplet) - .ok_or(Error::Overflow)?; - let external = spill_reserve - .checked_add(limits.working_reserve) - .ok_or(Error::Overflow)?; + let spill_reserve = limits.window_spill.checked_add(largest_triplet).ok_or(Error::Overflow)?; + let external = spill_reserve.checked_add(limits.working_reserve).ok_or(Error::Overflow)?; let capacity = limits .main_cap .checked_sub(spill_reserve) @@ -170,12 +140,7 @@ impl PrefixPlan { .and_then(|v| v.checked_sub(external)) .map(|typed| main.min(typed)) }) - .and_then(|typed| { - limits - .physical_free - .checked_sub(external) - .map(|free| typed.min(free)) - }) + .and_then(|typed| limits.physical_free.checked_sub(external).map(|free| typed.min(free))) .ok_or(Error::InputAllocation)?; if selected.len() != PAIRS || selected.iter().any(|value| *value) { return Err(Error::IdentityMismatch); @@ -190,9 +155,7 @@ impl PrefixPlan { let mut charged_bytes = 0usize; let mut prefix = 0; for &(layer, expert) in profile.ordered_pairs() { - let next = charged_bytes - .checked_add(totals[usize::from(layer)]) - .ok_or(Error::Overflow)?; + let next = charged_bytes.checked_add(totals[usize::from(layer)]).ok_or(Error::Overflow)?; if next > capacity { break; } @@ -215,8 +178,7 @@ impl PrefixPlan { pub(in super::super) fn contains(&self, layer: u32, expert: Option, role: u8) -> bool { layer < 48 && role < 3 - && expert - .is_some_and(|e| e < 512 && self.selected[layer as usize * EXPERTS + e as usize]) + && expert.is_some_and(|e| e < 512 && self.selected[layer as usize * EXPERTS + e as usize]) } pub(in super::super) fn metadata_bytes(&self) -> usize { self.selected.capacity() * std::mem::size_of::() + std::mem::size_of::() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_sharedpermanentpool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_sharedpermanentpool.rs index dbaf44d2..73e84c5e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_sharedpermanentpool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile/impl_sharedpermanentpool.rs @@ -5,38 +5,61 @@ use super::*; impl SharedPermanentPool { pub(in super::super) fn new(descriptors: Vec<[MoeWeightDescriptor; 4]>) -> Result { - if descriptors.len() != LAYERS { return Err(Error::InvalidDimension); } + if descriptors.len() != LAYERS { + return Err(Error::InvalidDimension); + } let mut bytes = 0usize; for (layer, keys) in descriptors.iter().enumerate() { super::super::super::shared_expert_workspace::validate_descriptors(keys)?; if keys.iter().any(|key| key.layer as usize != layer) { return Err(Error::IdentityMismatch); } - for key in keys { bytes = bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; } + for key in keys { + bytes = bytes.checked_add(key.bytes).ok_or(Error::Overflow)?; + } } - if bytes > SHARED_MAX_BYTES { return Err(Error::InputAllocation); } - Ok(Self { descriptors, bytes, roles: [RoleTraffic::default(); 7], - preload_roles: [RoleTraffic::default(); 7], baseline: [0; 5] }) + if bytes > SHARED_MAX_BYTES { + return Err(Error::InputAllocation); + } + Ok(Self { + descriptors, + bytes, + roles: [RoleTraffic::default(); 7], + preload_roles: [RoleTraffic::default(); 7], + baseline: [0; 5], + }) } pub(in super::super) fn contains(&self, key: MoeWeightDescriptor) -> bool { - key.expert.is_none() && key.role < 4 && self.descriptors - .get(key.layer as usize).is_some_and(|keys| keys[usize::from(key.role)] == key) + key.expert.is_none() + && key.role < 4 + && self.descriptors.get(key.layer as usize).is_some_and(|keys| keys[usize::from(key.role)] == key) } pub(in super::super) fn quartet(&self, layer: usize) -> Result<[MoeWeightDescriptor; 4]> { self.descriptors.get(layer).copied().ok_or(Error::IdentityMismatch) } - pub(in super::super) fn descriptor_count(&self) -> usize { self.descriptors.len() * 4 } + pub(in super::super) fn descriptor_count(&self) -> usize { + self.descriptors.len() * 4 + } pub(in super::super) fn metadata_bytes(&self) -> Result { - self.descriptors.capacity().checked_mul(std::mem::size_of::<[MoeWeightDescriptor; 4]>()) - .and_then(|n| n.checked_add(std::mem::size_of::())).ok_or(Error::Overflow) + self.descriptors + .capacity() + .checked_mul(std::mem::size_of::<[MoeWeightDescriptor; 4]>()) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .ok_or(Error::Overflow) } pub(super) fn role(&self, key: MoeWeightDescriptor) -> Option { if key.expert.is_some_and(|expert| expert < 512) && key.layer < 48 && key.role < 3 { Some(usize::from(key.role)) - } else if self.contains(key) { Some(3 + usize::from(key.role)) } else { None } + } else if self.contains(key) { + Some(3 + usize::from(key.role)) + } else { + None + } } pub(in super::super) fn hit(&mut self, key: MoeWeightDescriptor) { - if let Some(role) = self.role(key) { self.roles[role].hits = self.roles[role].hits.saturating_add(1); } + if let Some(role) = self.role(key) { + self.roles[role].hits = self.roles[role].hits.saturating_add(1); + } } pub(in super::super) fn fill(&mut self, key: MoeWeightDescriptor, read: usize, upload: usize) { if let Some(role) = self.role(key) { @@ -53,15 +76,21 @@ impl SharedPermanentPool { c.eviction_bytes = c.eviction_bytes.saturating_add(bytes as u64); } } - pub(in super::super) fn finish_preload(&mut self) { self.preload_roles = self.roles; } + pub(in super::super) fn finish_preload(&mut self) { + self.preload_roles = self.roles; + } pub(in super::super) fn request_roles(&self) -> Result<[RoleTraffic; 7]> { let mut output = [RoleTraffic::default(); 7]; for (i, out) in output.iter_mut().enumerate() { - let now = self.roles[i]; let old = self.preload_roles[i]; + let now = self.roles[i]; + let old = self.preload_roles[i]; *out = RoleTraffic { hits: now.hits.checked_sub(old.hits).ok_or(Error::IdentityMismatch)?, fills: now.fills.checked_sub(old.fills).ok_or(Error::IdentityMismatch)?, - source_read_bytes: now.source_read_bytes.checked_sub(old.source_read_bytes).ok_or(Error::IdentityMismatch)?, + source_read_bytes: now + .source_read_bytes + .checked_sub(old.source_read_bytes) + .ok_or(Error::IdentityMismatch)?, upload_bytes: now.upload_bytes.checked_sub(old.upload_bytes).ok_or(Error::IdentityMismatch)?, evictions: now.evictions.checked_sub(old.evictions).ok_or(Error::IdentityMismatch)?, eviction_bytes: now.eviction_bytes.checked_sub(old.eviction_bytes).ok_or(Error::IdentityMismatch)?, @@ -73,7 +102,9 @@ impl SharedPermanentPool { // Only MAIN is reduced here: caller's post-upload typed/free values are actual. pub(in super::super) fn remaining_shared_main(main: usize, shared: usize) -> Result { - if shared == 0 || shared > SHARED_MAX_BYTES { return Err(Error::InvalidDimension); } + if shared == 0 || shared > SHARED_MAX_BYTES { + return Err(Error::InvalidDimension); + } main.checked_sub(shared).ok_or(Error::InputAllocation) } @@ -82,7 +113,9 @@ pub(in super::super) fn remaining_shared_main(main: usize, shared: usize) -> Res pub(in super::super) fn learned_main_slot_bound(charges: &[[usize; 3]; 48], main: usize) -> Result { let mut roles = [0usize; 144]; for (slot, charge) in roles.iter_mut().zip(charges.iter().flatten()) { - if *charge == 0 { return Err(Error::InvalidDimension); } + if *charge == 0 { + return Err(Error::InvalidDimension); + } *slot = *charge; } roles.sort_unstable(); @@ -91,9 +124,10 @@ pub(in super::super) fn learned_main_slot_bound(charges: &[[usize; 3]; 48], main for charge in roles { let fits = (remaining / charge).min(512); count = count.checked_add(fits).ok_or(Error::Overflow)?; - remaining = remaining.checked_sub(fits.checked_mul(charge).ok_or(Error::Overflow)?) - .ok_or(Error::Overflow)?; - if fits < 512 { break; } + remaining = remaining.checked_sub(fits.checked_mul(charge).ok_or(Error::Overflow)?).ok_or(Error::Overflow)?; + if fits < 512 { + break; + } } Ok(count) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs index f30ee58c..b66d15ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill.rs @@ -39,10 +39,7 @@ mod concurrent_gdn_budget_regression { let failed_allocated = 29_924_190_656usize; assert!(room_fits(failed_allocated, budget, 0, live_gdn)); assert!(!room_fits(failed_allocated, budget, 0, live_with_inputs)); - assert_eq!( - failed_allocated + live_with_inputs + WORKING_RESERVE - budget, - 11_076, - ); + assert_eq!(failed_allocated + live_with_inputs + WORKING_RESERVE - budget, 11_076,); let guarded_boundary = budget - live_with_inputs - WORKING_RESERVE; assert!(room_fits(guarded_boundary, budget, 0, live_with_inputs)); assert!(!room_fits(guarded_boundary + 1, budget, 0, live_with_inputs)); @@ -92,10 +89,7 @@ mod reusable_spill_floor_planning { assert_eq!(original.charged_bytes, original.prefix * triplet); assert_eq!(original.spill_reserve, original_spill); assert_eq!(profile_window_spill_with_floor(0).unwrap(), window); - let with_floor = ProfileLimits { - window_spill: profile_window_spill_with_floor(floor).unwrap(), - ..old_limits - }; + let with_floor = ProfileLimits { window_spill: profile_window_spill_with_floor(floor).unwrap(), ..old_limits }; let candidate = PrefixPlan::new(&profile, &charges, with_floor).unwrap(); assert_eq!(candidate.prefix, 4); assert_eq!(candidate.charged_bytes, 4 * triplet); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs index 4aa25bb6..4c4243d2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> MoeWeightCache<'ctx> { /// Private candidate only. The caller creates all eager Dense owners first. pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile( @@ -41,8 +39,7 @@ impl<'ctx> MoeWeightCache<'ctx> { reusable_spill_floor: usize, ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; - let mut cache = - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; + let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; let operation = (|| { cache.validate(binding, context)?; if with_mtp_input { @@ -50,21 +47,13 @@ impl<'ctx> MoeWeightCache<'ctx> { } // These are genuine bound tensor descriptors, not chosen routes. let mut layer_keys = Vec::new(); - layer_keys - .try_reserve_exact(48) - .map_err(|_| Error::InputAllocation)?; + layer_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; let mut charges = [[0usize; 3]; 48]; for (layer, charge) in charges.iter_mut().enumerate() { let keys = [ - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up) - .map_err(binding_error)?, - binding - .moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down) - .map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, ]; for (n, key) in keys.iter().enumerate() { charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, n)| n); @@ -95,11 +84,7 @@ impl<'ctx> MoeWeightCache<'ctx> { .checked_add(plan.metadata_bytes()) .and_then(|n| n.checked_add(bytes.len())) .and_then(|n| n.checked_add(std::mem::size_of::())) - .and_then(|n| { - n.checked_add( - layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>(), - ) - }) + .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) .ok_or(Error::Overflow)?; let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; @@ -107,30 +92,18 @@ impl<'ctx> MoeWeightCache<'ctx> { // request fits every real complete prefix allowed by the 24GiB // cap (smallest admitted triplet is >1.5MB). Actual capacity is // rechecked rather than assumed, and bounds all later spill inserts. - cache - .main - .try_reserve(count.max(1 << 15)) - .map_err(|_| Error::InputAllocation)?; + cache.main.try_reserve(count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; let main_slot_limit = cache.main.capacity(); // Current pinned Rust std HashMap uses 7/8 load factor. 4/3 of // reported capacity conservatively covers buckets, plus controls // and the extra SIMD control group. This includes real owner tuples. - let buckets = main_slot_limit - .checked_mul(4) - .and_then(|n| n.checked_add(2)) - .map(|n| n / 3) - .ok_or(Error::Overflow)?; + let buckets = + main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; let map_bytes = buckets .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) - .and_then(|n| { - n.checked_add( - 16 + std::mem::size_of::>>(), - ) - }) - .ok_or(Error::Overflow)?; - let metadata_bytes = metadata_base - .checked_add(map_bytes) + .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) .ok_or(Error::Overflow)?; + let metadata_bytes = metadata_base.checked_add(map_bytes).ok_or(Error::Overflow)?; if metadata_bytes > HOST_CAP || count > main_slot_limit { return Err(Error::InputAllocation); } @@ -152,35 +125,18 @@ impl<'ctx> MoeWeightCache<'ctx> { preload_read_bytes: 0, preload_upload_bytes: 0, }); - let prefix = cache - .pinned - .as_ref() - .ok_or(Error::IdentityMismatch)? - .plan - .prefix; + let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; for &(layer, expert) in &profile.ordered_pairs()[..prefix] { // Re-admit each actual expert source before reading any matrix. let keys = [ binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Gate, - ) + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) .map_err(binding_error)?, binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Up, - ) + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) .map_err(binding_error)?, binding - .moe_preload_descriptor( - u32::from(layer), - u32::from(expert), - MoeMatrixRole::Down, - ) + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) .map_err(binding_error)?, ]; let mut topology_keys = layer_keys[usize::from(layer)]; @@ -194,10 +150,7 @@ impl<'ctx> MoeWeightCache<'ctx> { } if cache.main_bytes != expected_bytes || cache.spill_len()? != 0 - || cache - .pinned - .as_ref() - .is_none_or(|pool| pool.loaded_matrices != count) + || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs index 82c64aa0..03390473 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache/impl_moeweightcache_2_2.rs @@ -3,55 +3,26 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn preload_pinned_triplet( &mut self, binding: &ModelBinding, keys: [MoeWeightDescriptor; 3], ) -> Result<()> { - if keys - .iter() - .any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) - { + if keys.iter().any(|key| !self.is_pinned(*key) || self.main.contains_key(key)) { return Err(Error::IdentityMismatch); } - let layouts = [ - self.weight_layout(keys[0])?, - self.weight_layout(keys[1])?, - self.weight_layout(keys[2])?, - ]; - let charges = - std::array::from_fn::<_, 3, _>(|i| layouts[i].map_or(keys[i].bytes, |(_, n)| n)); - let extra = charges - .iter() - .try_fold(0usize, |n, v| n.checked_add(*v)) - .ok_or(Error::Overflow)?; - let spill = self - .pinned - .as_ref() - .ok_or(Error::IdentityMismatch)? - .plan - .spill_reserve; + let layouts = [self.weight_layout(keys[0])?, self.weight_layout(keys[1])?, self.weight_layout(keys[2])?]; + let charges = std::array::from_fn::<_, 3, _>(|i| layouts[i].map_or(keys[i].bytes, |(_, n)| n)); + let extra = charges.iter().try_fold(0usize, |n, v| n.checked_add(*v)).ok_or(Error::Overflow)?; + let spill = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.spill_reserve; // Requery real physical room for each upload, leaving the complete spill // allowance and working reserve intact. No eviction of already pinned owners. let (free, _) = self.context.memory_info().map_err(driver_error)?; - let required = extra - .checked_add(spill) - .and_then(|n| n.checked_add(WORKING_RESERVE)) - .ok_or(Error::Overflow)?; + let required = extra.checked_add(spill).and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?; if required > free - || self - .context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > self.context.budget_bytes()) - || self - .main_bytes - .checked_add(extra) - .and_then(|n| n.checked_add(spill)) - .is_none_or(|n| n > MAIN_LIMIT) + || self.context.allocated_bytes().checked_add(required).is_none_or(|n| n > self.context.budget_bytes()) + || self.main_bytes.checked_add(extra).and_then(|n| n.checked_add(spill)).is_none_or(|n| n > MAIN_LIMIT) { return Err(Error::InputAllocation); } @@ -69,25 +40,17 @@ impl<'ctx> MoeWeightCache<'ctx> { binding.moe_preload_block(keys[1]).map_err(binding_error)?, binding.moe_preload_block(keys[2]).map_err(binding_error)?, ]; - let read_bytes = raw - .iter() - .try_fold(0usize, |n, b| n.checked_add(b.len())) - .ok_or(Error::Overflow)?; + let read_bytes = raw.iter().try_fold(0usize, |n, b| n.checked_add(b.len())).ok_or(Error::Overflow)?; let mut owned: [Option>; 3] = std::array::from_fn(|_| None); let operation: Result<()> = (|| { if let [Some((gate, _)), Some((up, _)), Some((down, _))] = layouts { let owners = if self.original_prompt_mmq { - self.context.mmq_original_weight_triplet( - [gate, up, down], [&raw[0], &raw[1], &raw[2]]) + self.context.mmq_original_weight_triplet([gate, up, down], [&raw[0], &raw[1], &raw[2]]) } else { - self.context.mmq_weight_triplet( - [gate, up, down], [&raw[0], &raw[1], &raw[2]]) - }.map_err(driver_error)?; - if owners - .iter() - .zip(charges) - .any(|(owner, charge)| owner.allocated_bytes() != charge) - { + self.context.mmq_weight_triplet([gate, up, down], [&raw[0], &raw[1], &raw[2]]) + } + .map_err(driver_error)?; + if owners.iter().zip(charges).any(|(owner, charge)| owner.allocated_bytes() != charge) { for owner in owners.into_iter().rev() { if owner.close().is_err() { self.failed.set(true); @@ -104,10 +67,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(Error::InvalidDimension); } let weight = if let Some((format, expected)) = layouts[i] { - let owner = self - .context - .mmq_weights(format, &raw[i]) - .map_err(driver_error)?; + let owner = self.context.mmq_weights(format, &raw[i]).map_err(driver_error)?; if owner.allocated_bytes() != expected { if owner.close().is_err() { self.failed.set(true); @@ -140,11 +100,7 @@ impl<'ctx> MoeWeightCache<'ctx> { for (i, owner) in owned.into_iter().enumerate() { self.main.insert( keys[i], - Entry { - weight: owner.unwrap(), - charged_bytes: charges[i], - age: self.age + i as u64 + 1, - }, + Entry { weight: owner.unwrap(), charged_bytes: charges[i], age: self.age + i as u64 + 1 }, ); } self.main_bytes = next_bytes; @@ -157,10 +113,8 @@ impl<'ctx> MoeWeightCache<'ctx> { // Raw uploads already update source/upload counters; Dual uploads do not. for i in 0..3 { if layouts[i].is_some() { - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(raw[i].len() as u64); - self.counters.upload_bytes = - self.counters.upload_bytes.saturating_add(charges[i] as u64); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(raw[i].len() as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charges[i] as u64); } } for (key, charge) in keys.into_iter().zip(charges) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs index ef0f463a..e79600a4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_2.rs @@ -3,13 +3,14 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> MoeWeightCache<'ctx> { /// Separately selected only: all target shared weights precede the ranked prefix. #[cfg(test)] pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent( - binding: &ModelBinding, context: &'ctx Context<'ctx>, bytes: &[u8], + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru(binding, context)?; @@ -23,16 +24,20 @@ impl<'ctx> MoeWeightCache<'ctx> { shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; let mut charges = [[0usize; 3]; 48]; for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + let keys = [ + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?]; - for (n, key) in keys.iter().enumerate() { charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); } + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + for (n, key) in keys.iter().enumerate() { + charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); + } layer_keys.push(keys); shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); } let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = [baseline.hits, baseline.misses, baseline.read_bytes, - baseline.upload_bytes, baseline.eviction_bytes]; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; let mut totals = [0usize; 48]; for (total, roles) in totals.iter_mut().zip(charges) { @@ -40,25 +45,34 @@ impl<'ctx> MoeWeightCache<'ctx> { } let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { return Err(Error::InvalidDimension); } + if minimum == 0 { + return Err(Error::InvalidDimension); + } let window_spill = profile_window_spill_with_floor(1usize << 30)?; let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; // Metadata for even the largest possible selected prefix is charged BEFORE H2D. - let maximum_count = remaining_main.checked_sub(spill).ok_or(Error::InputAllocation)? - .checked_div(minimum).ok_or(Error::InvalidDimension)? - .min(profile.ordered_pairs().len()).checked_mul(3) - .and_then(|n| n.checked_add(shared.descriptor_count())).ok_or(Error::Overflow)?; + let maximum_count = remaining_main + .checked_sub(spill) + .ok_or(Error::InputAllocation)? + .checked_div(minimum) + .ok_or(Error::InvalidDimension)? + .min(profile.ordered_pairs().len()) + .checked_mul(3) + .and_then(|n| n.checked_add(shared.descriptor_count())) + .ok_or(Error::Overflow)?; cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; let main_slot_limit = cache.main.capacity(); let mut selected = Vec::new(); selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; selected.resize(48 * 512, false); - let buckets = main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)) - .map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets.checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + let buckets = + main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; + let map_bytes = buckets + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) .ok_or(Error::Overflow)?; - let metadata_bytes = profile.metadata_bytes() + let metadata_bytes = profile + .metadata_bytes() .checked_add(shared.metadata_bytes()?) .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) .and_then(|n| n.checked_add(std::mem::size_of::())) @@ -66,62 +80,110 @@ impl<'ctx> MoeWeightCache<'ctx> { .and_then(|n| n.checked_add(bytes.len())) .and_then(|n| n.checked_add(layer_keys.capacity() * std::mem::size_of::<[MoeWeightDescriptor; 3]>())) .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(map_bytes)).ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { return Err(Error::InputAllocation); } + .and_then(|n| n.checked_add(map_bytes)) + .ok_or(Error::Overflow)?; + if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { + return Err(Error::InputAllocation); + } // Closed source/geometry was checked for every descriptor above. Only // full finite actual owned bytes from the same binding are uploaded. for layer in 0..48 { let keys = shared.quartet(layer)?; cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; } - if cache.main_bytes != shared.bytes || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 { + if cache.main_bytes != shared.bytes + || cache.main.len() != shared.descriptor_count() + || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 + { return Err(Error::IdentityMismatch); } // Actual owners now appear in both allocated_bytes and physical_free. // Subtract their bytes ONLY from the remaining main pool. let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage(&profile, &charges, ProfileLimits { - main_cap: remaining_main, allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), physical_free: free, - working_reserve: WORKING_RESERVE, window_spill, - }, selected)?; + let plan = PrefixPlan::new_shared_with_storage( + &profile, + &charges, + ProfileLimits { + main_cap: remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }, + selected, + )?; let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { return Err(Error::InputAllocation); } let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { plan, loaded_matrices: 0, shared: Some(shared), - #[cfg(test)] metadata_bytes, main_slot_limit, - #[cfg(test)] fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, spill_hits: 0, spill_misses: 0, - preload_read_bytes: shared_bytes, preload_upload_bytes: shared_bytes }); + cache.pinned = Some(PinnedPool { + plan, + loaded_matrices: 0, + shared: Some(shared), + #[cfg(test)] + metadata_bytes, + main_slot_limit, + #[cfg(test)] + fixed_resident_upload_bytes: baseline.upload_bytes, + #[cfg(test)] + fixed_resident_read_bytes: baseline.read_bytes, + pinned_hits: 0, + spill_hits: 0, + spill_misses: 0, + preload_read_bytes: shared_bytes, + preload_upload_bytes: shared_bytes, + }); let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down).map_err(binding_error)?]; + let keys = [ + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) + .map_err(binding_error)?, + ]; let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { key.expert = Some(u32::from(expert)); } - if keys != topology_keys { return Err(Error::IdentityMismatch); } + for key in &mut topology_keys { + key.expert = Some(u32::from(expert)); + } + if keys != topology_keys { + return Err(Error::IdentityMismatch); + } cache.preload_pinned_triplet(binding, keys)?; } - if cache.main_bytes != expected_bytes || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) { + if cache.main_bytes != expected_bytes + || cache.spill_len()? != 0 + || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) + { return Err(Error::IdentityMismatch); } - cache.pinned.as_mut().and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)?.finish_preload(); + cache + .pinned + .as_mut() + .and_then(|pool| pool.shared.as_mut()) + .ok_or(Error::IdentityMismatch)? + .finish_preload(); cache.validate(binding, context) })(); - if let Err(primary) = operation { let _ = cache.close(); return Err(primary); } + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } Ok(cache) } pub(super) fn preload_shared_quartet( - &mut self, binding: &ModelBinding, keys: [MoeWeightDescriptor; 4], - spill: usize, shared: &mut cache_profile::SharedPermanentPool, + &mut self, + binding: &ModelBinding, + keys: [MoeWeightDescriptor; 4], + spill: usize, + shared: &mut cache_profile::SharedPermanentPool, ) -> Result<()> { self.validate(binding, self.context)?; crate::qwen_forward::shared_expert_workspace::validate_descriptors(&keys)?; @@ -140,33 +202,46 @@ impl<'ctx> MoeWeightCache<'ctx> { // read or allocation; no previous permanent weight may be evicted. for (index, key) in keys.iter().copied().enumerate() { let (free, _) = self.context.memory_info().map_err(driver_error)?; - let remaining = keys[index..].iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)) - .ok_or(Error::Overflow)?; - let required = remaining.checked_add(spill).and_then(|n| n.checked_add(WORKING_RESERVE)) - .ok_or(Error::Overflow)?; - if required > free || self.context.allocated_bytes().checked_add(required) - .is_none_or(|n| n > self.context.budget_bytes()) - || next_bytes.checked_add(spill).is_none_or(|n| n > MAIN_LIMIT) { + let remaining = + keys[index..].iter().try_fold(0usize, |n, key| n.checked_add(key.bytes)).ok_or(Error::Overflow)?; + let required = + remaining.checked_add(spill).and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?; + if required > free + || self + .context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > self.context.budget_bytes()) + || next_bytes.checked_add(spill).is_none_or(|n| n > MAIN_LIMIT) + { return Err(Error::InputAllocation); } let raw = binding.moe_shared_preload_block(key).map_err(binding_error)?; - if raw.len() != key.bytes { return Err(Error::InvalidDimension); } + if raw.len() != key.bytes { + return Err(Error::InvalidDimension); + } owned[index] = Some(EncodedWeight::Raw(self.upload(&raw)?)); } Ok(()) })(); if let Err(primary) = operation { for owner in owned.into_iter().rev().flatten() { - if owner.close().is_err() { self.failed.set(true); } + if owner.close().is_err() { + self.failed.set(true); + } + } + if self.context.is_poisoned() { + self.failed.set(true); } - if self.context.is_poisoned() { self.failed.set(true); } return Err(primary); } // All owners/geometry, byte/age/capacity arithmetic admitted before first // insertion. No fallible work follows the quartet publication boundary. for (index, owner) in owned.into_iter().enumerate() { - self.main.insert(keys[index], Entry { weight: owner.unwrap(), - charged_bytes: keys[index].bytes, age: self.age + index as u64 + 1 }); + self.main.insert( + keys[index], + Entry { weight: owner.unwrap(), charged_bytes: keys[index].bytes, age: self.age + index as u64 + 1 }, + ); shared.fill(keys[index], keys[index].bytes, keys[index].bytes); } self.main_bytes = next_bytes; @@ -179,7 +254,9 @@ impl<'ctx> MoeWeightCache<'ctx> { let shared = self.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; if shared.descriptor_count() != 192 || shared.roles[3..].iter().any(|role| role.evictions != 0 || role.eviction_bytes != 0) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } for layer in 0..48 { for key in shared.quartet(layer)? { let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?; @@ -191,26 +268,41 @@ impl<'ctx> MoeWeightCache<'ctx> { let now = self.counters; let mut delta = [0u64; 5]; for (index, (n, old)) in [now.hits, now.misses, now.read_bytes, now.upload_bytes, now.eviction_bytes] - .into_iter().zip(shared.baseline).enumerate() { + .into_iter() + .zip(shared.baseline) + .enumerate() + { delta[index] = n.checked_sub(old).ok_or(Error::IdentityMismatch)?; } let sum = |f: fn(&cache_profile::RoleTraffic) -> u64| -> Result { shared.roles.iter().try_fold(0u64, |n, c| n.checked_add(f(c)).ok_or(Error::Overflow)) }; - Ok(cache_profile::SharedPermanentWitness { descriptors: shared.descriptor_count(), bytes: shared.bytes, - roles: shared.roles, preload_roles: shared.preload_roles, request_roles: shared.request_roles()?, - inclusive_hits: delta[0], inclusive_misses: delta[1], inclusive_source_read_bytes: delta[2], - inclusive_upload_bytes: delta[3], inclusive_eviction_bytes: delta[4], - successful_bytes_reconcile: sum(|c| c.hits)? == delta[0] && sum(|c| c.fills)? == delta[1] - && sum(|c| c.source_read_bytes)? == delta[2] && sum(|c| c.upload_bytes)? == delta[3] - && sum(|c| c.eviction_bytes)? == delta[4] }) + Ok(cache_profile::SharedPermanentWitness { + descriptors: shared.descriptor_count(), + bytes: shared.bytes, + roles: shared.roles, + preload_roles: shared.preload_roles, + request_roles: shared.request_roles()?, + inclusive_hits: delta[0], + inclusive_misses: delta[1], + inclusive_source_read_bytes: delta[2], + inclusive_upload_bytes: delta[3], + inclusive_eviction_bytes: delta[4], + successful_bytes_reconcile: sum(|c| c.hits)? == delta[0] + && sum(|c| c.fills)? == delta[1] + && sum(|c| c.source_read_bytes)? == delta[2] + && sum(|c| c.upload_bytes)? == delta[3] + && sum(|c| c.eviction_bytes)? == delta[4], + }) } /// Actual shared-only counters; raw adaptive slots have their own witness. pub(crate) fn strata_adaptive_shared_witness(&self) -> Result { let shared = self.adaptive_shared.as_ref().ok_or(Error::IdentityMismatch)?; if shared.descriptor_count() != 192 || shared.roles[3..].iter().any(|role| role.evictions != 0 || role.eviction_bytes != 0) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } for layer in 0..48 { for key in shared.quartet(layer)? { let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?; @@ -222,18 +314,31 @@ impl<'ctx> MoeWeightCache<'ctx> { let now = self.counters; let mut delta = [0u64; 5]; for (index, (n, old)) in [now.hits, now.misses, now.read_bytes, now.upload_bytes, now.eviction_bytes] - .into_iter().zip(shared.baseline).enumerate() { + .into_iter() + .zip(shared.baseline) + .enumerate() + { delta[index] = n.checked_sub(old).ok_or(Error::IdentityMismatch)?; } let sum = |f: fn(&cache_profile::RoleTraffic) -> u64| -> Result { shared.roles.iter().try_fold(0u64, |n, c| n.checked_add(f(c)).ok_or(Error::Overflow)) }; - Ok(cache_profile::SharedPermanentWitness { descriptors: shared.descriptor_count(), bytes: shared.bytes, - roles: shared.roles, preload_roles: shared.preload_roles, request_roles: shared.request_roles()?, - inclusive_hits: delta[0], inclusive_misses: delta[1], inclusive_source_read_bytes: delta[2], - inclusive_upload_bytes: delta[3], inclusive_eviction_bytes: delta[4], - successful_bytes_reconcile: sum(|c| c.hits)? == delta[0] && sum(|c| c.fills)? == delta[1] - && sum(|c| c.source_read_bytes)? == delta[2] && sum(|c| c.upload_bytes)? == delta[3] - && sum(|c| c.eviction_bytes)? == delta[4] }) + Ok(cache_profile::SharedPermanentWitness { + descriptors: shared.descriptor_count(), + bytes: shared.bytes, + roles: shared.roles, + preload_roles: shared.preload_roles, + request_roles: shared.request_roles()?, + inclusive_hits: delta[0], + inclusive_misses: delta[1], + inclusive_source_read_bytes: delta[2], + inclusive_upload_bytes: delta[3], + inclusive_eviction_bytes: delta[4], + successful_bytes_reconcile: sum(|c| c.hits)? == delta[0] + && sum(|c| c.fills)? == delta[1] + && sum(|c| c.source_read_bytes)? == delta[2] + && sum(|c| c.upload_bytes)? == delta[3] + && sum(|c| c.eviction_bytes)? == delta[4], + }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs index 28b2d467..fa5a4feb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_3.rs @@ -3,15 +3,17 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> MoeWeightCache<'ctx> { /// New policy only: keep genuine preload bytes, then learn routed main residency. pub(crate) fn new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_profile_mtp_input_spill_floor_shared_permanent_learned_main_lru( - binding: &ModelBinding, context: &'ctx Context<'ctx>, bytes: &[u8], + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; - let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, true)?; + let mut cache = + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, true)?; let operation = (|| { cache.validate(binding, context)?; cache.admit_mtp_input_workspace(binding)?; @@ -22,16 +24,20 @@ impl<'ctx> MoeWeightCache<'ctx> { shared_keys.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?; let mut charges = [[0usize; 3]; 48]; for (layer, charge) in charges.iter_mut().enumerate() { - let keys = [binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, + let keys = [ + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Gate).map_err(binding_error)?, binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?]; - for (n, key) in keys.iter().enumerate() { charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); } + binding.moe_preload_descriptor(layer as u32, 0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + for (n, key) in keys.iter().enumerate() { + charge[n] = cache.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes); + } layer_keys.push(keys); shared_keys.push(binding.moe_shared_preload_descriptors(layer as u32).map_err(binding_error)?); } let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; - shared.baseline = [baseline.hits, baseline.misses, baseline.read_bytes, - baseline.upload_bytes, baseline.eviction_bytes]; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; let mut totals = [0usize; 48]; for (total, roles) in totals.iter_mut().zip(charges) { @@ -39,23 +45,28 @@ impl<'ctx> MoeWeightCache<'ctx> { } let minimum = *totals.iter().min().ok_or(Error::InvalidDimension)?; let largest = *totals.iter().max().ok_or(Error::InvalidDimension)?; - if minimum == 0 { return Err(Error::InvalidDimension); } + if minimum == 0 { + return Err(Error::InvalidDimension); + } let window_spill = profile_window_spill_with_floor(1usize << 30)?; let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; // Metadata for even the largest possible selected prefix is charged BEFORE H2D. let maximum_count = cache_profile::learned_main_slot_bound(&charges, remaining_main)? - .checked_add(shared.descriptor_count()).ok_or(Error::Overflow)?; + .checked_add(shared.descriptor_count()) + .ok_or(Error::Overflow)?; cache.main.try_reserve(maximum_count.max(1 << 15)).map_err(|_| Error::InputAllocation)?; let main_slot_limit = cache.main.capacity(); let mut selected = Vec::new(); selected.try_reserve_exact(48 * 512).map_err(|_| Error::InputAllocation)?; selected.resize(48 * 512, false); - let buckets = main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)) - .map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets.checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + let buckets = + main_slot_limit.checked_mul(4).and_then(|n| n.checked_add(2)).map(|n| n / 3).ok_or(Error::Overflow)?; + let map_bytes = buckets + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) .ok_or(Error::Overflow)?; - let metadata_bytes = profile.metadata_bytes() + let metadata_bytes = profile + .metadata_bytes() .checked_add(shared.metadata_bytes()?) .and_then(|n| n.checked_add(selected.capacity() * std::mem::size_of::())) .and_then(|n| n.checked_add(std::mem::size_of::())) @@ -67,7 +78,9 @@ impl<'ctx> MoeWeightCache<'ctx> { .and_then(|n| n.checked_add(std::mem::size_of::())) .and_then(|n| n.checked_add(std::mem::size_of::<[usize; 144]>())) .ok_or(Error::Overflow)?; - if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { return Err(Error::InputAllocation); } + if metadata_bytes > HOST_CAP || maximum_count > main_slot_limit { + return Err(Error::InputAllocation); + } cache.learned_metadata_bytes = metadata_bytes; // Closed source/geometry was checked for every descriptor above. Only // full finite actual owned bytes from the same binding are uploaded. @@ -75,67 +88,112 @@ impl<'ctx> MoeWeightCache<'ctx> { let keys = shared.quartet(layer)?; cache.preload_shared_quartet(binding, keys, spill, &mut shared)?; } - if cache.main_bytes != shared.bytes || cache.main.len() != shared.descriptor_count() - || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 { + if cache.main_bytes != shared.bytes + || cache.main.len() != shared.descriptor_count() + || cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != 0 + { return Err(Error::IdentityMismatch); } // Actual owners now appear in both allocated_bytes and physical_free. // Subtract their bytes ONLY from the remaining main pool. let (free, _) = context.memory_info().map_err(driver_error)?; - let plan = PrefixPlan::new_shared_with_storage(&profile, &charges, ProfileLimits { - main_cap: remaining_main, allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), physical_free: free, - working_reserve: WORKING_RESERVE, window_spill, - }, selected)?; + let plan = PrefixPlan::new_shared_with_storage( + &profile, + &charges, + ProfileLimits { + main_cap: remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }, + selected, + )?; let count = plan.prefix.checked_mul(3).ok_or(Error::Overflow)?; if count.checked_add(shared.descriptor_count()).is_none_or(|n| n > main_slot_limit) { return Err(Error::InputAllocation); } let expected_bytes = plan.charged_bytes.checked_add(shared.bytes).ok_or(Error::Overflow)?; let shared_bytes = shared.bytes as u64; - cache.pinned = Some(PinnedPool { plan, loaded_matrices: 0, shared: Some(shared), - #[cfg(test)] metadata_bytes, main_slot_limit, - #[cfg(test)] fixed_resident_upload_bytes: baseline.upload_bytes, - #[cfg(test)] fixed_resident_read_bytes: baseline.read_bytes, - pinned_hits: 0, spill_hits: 0, spill_misses: 0, - preload_read_bytes: shared_bytes, preload_upload_bytes: shared_bytes }); + cache.pinned = Some(PinnedPool { + plan, + loaded_matrices: 0, + shared: Some(shared), + #[cfg(test)] + metadata_bytes, + main_slot_limit, + #[cfg(test)] + fixed_resident_upload_bytes: baseline.upload_bytes, + #[cfg(test)] + fixed_resident_read_bytes: baseline.read_bytes, + pinned_hits: 0, + spill_hits: 0, + spill_misses: 0, + preload_read_bytes: shared_bytes, + preload_upload_bytes: shared_bytes, + }); let prefix = cache.pinned.as_ref().ok_or(Error::IdentityMismatch)?.plan.prefix; for &(layer, expert) in &profile.ordered_pairs()[..prefix] { - let keys = [binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate).map_err(binding_error)?, - binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up).map_err(binding_error)?, - binding.moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down).map_err(binding_error)?]; + let keys = [ + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Gate) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Up) + .map_err(binding_error)?, + binding + .moe_preload_descriptor(u32::from(layer), u32::from(expert), MoeMatrixRole::Down) + .map_err(binding_error)?, + ]; let mut topology_keys = layer_keys[usize::from(layer)]; - for key in &mut topology_keys { key.expert = Some(u32::from(expert)); } - if keys != topology_keys { return Err(Error::IdentityMismatch); } + for key in &mut topology_keys { + key.expert = Some(u32::from(expert)); + } + if keys != topology_keys { + return Err(Error::IdentityMismatch); + } cache.preload_pinned_triplet(binding, keys)?; } - if cache.main_bytes != expected_bytes || cache.spill_len()? != 0 - || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) { + if cache.main_bytes != expected_bytes + || cache.spill_len()? != 0 + || cache.pinned.as_ref().is_none_or(|pool| pool.loaded_matrices != count) + { return Err(Error::IdentityMismatch); } - cache.pinned.as_mut().and_then(|pool| pool.shared.as_mut()) - .ok_or(Error::IdentityMismatch)?.finish_preload(); + cache + .pinned + .as_mut() + .and_then(|pool| pool.shared.as_mut()) + .ok_or(Error::IdentityMismatch)? + .finish_preload(); // The same real owners are already complete. Seed the existing empty // metadata only; no source read, allocation or H2D occurs here. - let shared = cache.pinned.as_ref().and_then(|pool| pool.shared.as_ref()) - .ok_or(Error::IdentityMismatch)?; + let shared = cache.pinned.as_ref().and_then(|pool| pool.shared.as_ref()).ok_or(Error::IdentityMismatch)?; for (key, entry) in &cache.main { let expected = cache.weight_layout(*key)?.map_or(key.bytes, |(_, charge)| charge); - if entry.charged_bytes != expected || entry.age == 0 || entry.age > cache.age - || (key.expert.is_none() && !shared.contains(*key)) { + if entry.charged_bytes != expected + || entry.age == 0 + || entry.age > cache.age + || (key.expert.is_none() && !shared.contains(*key)) + { return Err(Error::IdentityMismatch); } } cache.lru.as_mut().ok_or(Error::IdentityMismatch)?.seed_existing( - cache.age, cache.main.iter().filter(|(key, _)| !shared.contains(**key)) - .map(|(key, entry)| (*key, entry.age)))?; + cache.age, + cache.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)), + )?; cache.learned_main = true; if cache.lru.as_ref().ok_or(Error::IdentityMismatch)?.len() != cache.spill_len()? { return Err(Error::IdentityMismatch); } cache.validate(binding, context) })(); - if let Err(primary) = operation { let _ = cache.close(); return Err(primary); } + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } Ok(cache) } } @@ -145,36 +203,56 @@ impl MoeWeightCache<'_> { /// Actual current residency only; historical ranked prefix is not pinned now. pub(crate) fn learned_main_witness(&self, binding: &ModelBinding) -> Result { self.validate(binding, self.context)?; - if !self.learned_main { return Err(Error::IdentityMismatch); } + if !self.learned_main { + return Err(Error::IdentityMismatch); + } let pool = self.pinned.as_ref().ok_or(Error::IdentityMismatch)?; let shared = pool.shared.as_ref().ok_or(Error::IdentityMismatch)?; let _ = self.shared_permanent_witness()?; let index = self.lru.as_ref().ok_or(Error::IdentityMismatch)?; - let routed_matrices = index.matches_existing(self.age, self.main.iter() - .filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)))?; + let routed_matrices = index.matches_existing( + self.age, + self.main.iter().filter(|(key, _)| !shared.contains(**key)).map(|(key, entry)| (*key, entry.age)), + )?; let mut routed_bytes = 0usize; let mut main_bytes = 0usize; for (key, entry) in &self.main { if entry.charged_bytes != self.weight_layout(*key)?.map_or(key.bytes, |(_, bytes)| bytes) - || entry.age == 0 || entry.age > self.age { + || entry.age == 0 + || entry.age > self.age + { return Err(Error::IdentityMismatch); } main_bytes = main_bytes.checked_add(entry.charged_bytes).ok_or(Error::Overflow)?; if !shared.contains(*key) { - if key.expert.is_none() { return Err(Error::IdentityMismatch); } + if key.expert.is_none() { + return Err(Error::IdentityMismatch); + } routed_bytes = routed_bytes.checked_add(entry.charged_bytes).ok_or(Error::Overflow)?; } } - if main_bytes != self.main_bytes || main_bytes > MAIN_LIMIT - || routed_matrices != self.spill_len()? || self.main.len() > pool.main_slot_limit { + if main_bytes != self.main_bytes + || main_bytes > MAIN_LIMIT + || routed_matrices != self.spill_len()? + || self.main.len() > pool.main_slot_limit + { return Err(Error::IdentityMismatch); } let metadata_bytes = self.learned_metadata_bytes; - if metadata_bytes > HOST_CAP { return Err(Error::IdentityMismatch); } - Ok(cache_profile::LearnedMainWitness { routed_matrices, routed_bytes, - shared_matrices: shared.descriptor_count(), shared_bytes: shared.bytes, - main_bytes, main_slot_limit: pool.main_slot_limit, metadata_bytes, - historical_prefix: pool.plan.prefix, historical_routed_preload_bytes: pool.plan.charged_bytes, - age: self.age }) + if metadata_bytes > HOST_CAP { + return Err(Error::IdentityMismatch); + } + Ok(cache_profile::LearnedMainWitness { + routed_matrices, + routed_bytes, + shared_matrices: shared.descriptor_count(), + shared_bytes: shared.bytes, + main_bytes, + main_slot_limit: pool.main_slot_limit, + metadata_bytes, + historical_prefix: pool.plan.prefix, + historical_routed_preload_bytes: pool.plan.charged_bytes, + age: self.age, + }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs index 32b0ba2b..a80d02be 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/impl_moeweightcache_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> MoeWeightCache<'ctx> { /// Authentic Strata frequency/slot policy, selected separately. Initial @@ -11,28 +10,39 @@ impl<'ctx> MoeWeightCache<'ctx> { /// Root must wire actual route observation + verifier cadence + CPU miss /// producer before exposing this constructor in a serving identity. pub(crate) fn new_native_strata_adaptive_shared_permanent( - binding: &ModelBinding, context: &'ctx Context<'ctx>, bytes: &[u8], + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], ) -> Result { Self::native_strata_adaptive_source_transport(binding, context, bytes, false) } /// Separately selected direct-port constructor. Root must bind this policy /// into the operator digest and seal the fixed byte-copy PTX before Ready. pub(crate) fn new_native_strata_adaptive_shared_permanent_mapped( - binding: &ModelBinding, context: &'ctx Context<'ctx>, bytes: &[u8], + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], ) -> Result { Self::native_strata_adaptive_source_transport(binding, context, bytes, true) } pub(super) fn native_strata_adaptive_source_transport( - binding: &ModelBinding, context: &'ctx Context<'ctx>, bytes: &[u8], mapped: bool, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + bytes: &[u8], + mapped: bool, ) -> Result { let profile = RankedProfile::parse(bytes, PROFILE_SHA)?; - let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, mapped)?; + let mut cache = + Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_lru_with_prompt(binding, context, mapped)?; let operation = (|| { cache.validate(binding, context)?; let required = 46_612usize.checked_add(WORKING_RESERVE).ok_or(Error::Overflow)?; let (free, _) = context.memory_info().map_err(driver_error)?; - if free < required || context.allocated_bytes().checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } + if free < required + || context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) + { + return Err(Error::InputAllocation); + } cache.routed_resident = Some(Rc::new(super::super::RoutedResidentOwner::new(context)?)); cache.admit_mtp_input_workspace(binding)?; let mut layer_keys = Vec::new(); @@ -46,90 +56,138 @@ impl<'ctx> MoeWeightCache<'ctx> { binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Up).map_err(binding_error)?, binding.moe_preload_descriptor(layer, 0, MoeMatrixRole::Down).map_err(binding_error)?, ]; - largest = largest.max(keys.iter().try_fold(0usize, |n, k| - n.checked_add(k.bytes).ok_or(Error::Overflow))?); + largest = + largest.max(keys.iter().try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?); layer_keys.push(keys); shared_keys.push(binding.moe_shared_preload_descriptors(layer).map_err(binding_error)?); } - let template: [[MoeWeightDescriptor; 3]; 48] = layer_keys.try_into() - .map_err(|_| Error::InvalidDimension)?; + let template: [[MoeWeightDescriptor; 3]; 48] = + layer_keys.try_into().map_err(|_| Error::InvalidDimension)?; // These are genuine whole owners allocated before PrefixPlan. Their // bytes are already in Context::allocated_bytes, charged once. - cache.routed_outputs = Some(Rc::new(super::super::cache_routed_outputs::RoutedOutputBank::new( - binding.identity(), context, - )?)); + cache.routed_outputs = + Some(Rc::new(super::super::cache_routed_outputs::RoutedOutputBank::new(binding.identity(), context)?)); if cache.routed_outputs.as_ref().ok_or(Error::IdentityMismatch)?.allocated_bytes() != 37_273_600 { return Err(Error::IdentityMismatch); } let maximum = std::array::from_fn(|role| template.iter().map(|keys| keys[role].bytes).max().unwrap_or(0)); cache.ephemeral_routed = Some(Rc::new(RefCell::new(if mapped { - super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new_mapped(binding,context,maximum, - super::super::cache_ephemeral_routed::MappedStageShape::Single16)? + super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new_mapped( + binding, + context, + maximum, + super::super::cache_ephemeral_routed::MappedStageShape::Single16, + )? } else { super::super::cache_ephemeral_routed::EphemeralRoutedOwner::new(binding, context, maximum)? }))); - let ephemeral_charge = maximum.into_iter().try_fold(if mapped {36usize} else {0}, |n, b| n.checked_add(b).ok_or(Error::Overflow))? - .checked_mul(if mapped {16} else {2}).ok_or(Error::Overflow)?; - if cache.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?.try_borrow() - .map_err(|_| Error::IdentityMismatch)?.allocated_bytes() != ephemeral_charge { + let ephemeral_charge = maximum + .into_iter() + .try_fold(if mapped { 36usize } else { 0 }, |n, b| n.checked_add(b).ok_or(Error::Overflow))? + .checked_mul(if mapped { 16 } else { 2 }) + .ok_or(Error::Overflow)?; + if cache + .ephemeral_routed + .as_ref() + .ok_or(Error::IdentityMismatch)? + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .allocated_bytes() + != ephemeral_charge + { return Err(Error::IdentityMismatch); } let mut shared = cache_profile::SharedPermanentPool::new(shared_keys)?; let baseline = cache.counters; - shared.baseline = [baseline.hits, baseline.misses, baseline.read_bytes, - baseline.upload_bytes, baseline.eviction_bytes]; + shared.baseline = + [baseline.hits, baseline.misses, baseline.read_bytes, baseline.upload_bytes, baseline.eviction_bytes]; let remaining_main = cache_profile::remaining_shared_main(MAIN_LIMIT, shared.bytes)?; let window_spill = profile_window_spill_with_floor(1usize << 30)?; let spill = window_spill.checked_add(largest).ok_or(Error::Overflow)?; // Only the permanent192 descriptor map survives. No second routed // HashMap/LRU representation competes with the actual slot map. cache.main.try_reserve(shared.descriptor_count()).map_err(|_| Error::InputAllocation)?; - let buckets = cache.main.capacity().checked_mul(4).and_then(|n| n.checked_add(2)) - .map(|n| n / 3).ok_or(Error::Overflow)?; - let map_bytes = buckets.checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) + let buckets = cache + .main + .capacity() + .checked_mul(4) + .and_then(|n| n.checked_add(2)) + .map(|n| n / 3) + .ok_or(Error::Overflow)?; + let map_bytes = buckets + .checked_mul(std::mem::size_of::<(MoeWeightDescriptor, Entry<'ctx>)>() + 1) .and_then(|n| n.checked_add(16 + std::mem::size_of::>>())) .ok_or(Error::Overflow)?; - let metadata = profile.metadata_bytes() + let metadata = profile + .metadata_bytes() .checked_add(shared.metadata_bytes()?) .and_then(|n| n.checked_add(cache.routed_outputs.as_ref()?.metadata_bytes())) .and_then(|n| n.checked_add(cache.ephemeral_routed.as_ref()?.try_borrow().ok()?.metadata_bytes())) .and_then(|n| n.checked_add(map_bytes)) .and_then(|n| n.checked_add(cache.lru.as_ref()?.metadata_bytes().ok()?)) - .and_then(|n| n.checked_add(bytes.len())).ok_or(Error::Overflow)?; + .and_then(|n| n.checked_add(bytes.len())) + .ok_or(Error::Overflow)?; // Prove the COMPLETE adaptive allocation bound before first shared // H2D, not after the remaining physical memory became tight. let (free, _) = context.memory_info().map_err(driver_error)?; - let before = cache_strata_adaptive::AdaptivePolicy::new(&profile, template, - ProfileLimits { main_cap: remaining_main, + let before = cache_strata_adaptive::AdaptivePolicy::new( + &profile, + template, + ProfileLimits { + main_cap: remaining_main, allocated: context.allocated_bytes().checked_add(shared.bytes).ok_or(Error::Overflow)?, device_budget: context.budget_bytes(), physical_free: free.checked_sub(shared.bytes).ok_or(Error::InputAllocation)?, - working_reserve: WORKING_RESERVE, window_spill })?; - let adaptive_metadata = before.metadata_bytes() + working_reserve: WORKING_RESERVE, + window_spill, + }, + )?; + let adaptive_metadata = before + .metadata_bytes() .checked_add(before.initial_slots().len() * std::mem::size_of::; 3]>>()) .and_then(|n| n.checked_add(cache_strata_adaptive::transfer_metadata_bound())) - .and_then(|n| n.checked_add(metadata)).ok_or(Error::Overflow)?; - if adaptive_metadata > HOST_CAP { return Err(Error::InputAllocation); } + .and_then(|n| n.checked_add(metadata)) + .ok_or(Error::Overflow)?; + if adaptive_metadata > HOST_CAP { + return Err(Error::InputAllocation); + } drop(before); // Persistent15-worker stacks/coordinator/fixed scratch belong to // the model source lifetime, not every request's CPU job budget. cpu_budget::admit_pool(binding, adaptive_metadata)?; let cpu = super::super::super::cpu_expert_miss::CpuMissWorkspace::new(binding, 15) .map_err(super::super::super::cpu_expert_miss::runtime_error)?; - if cpu.workers() != 15 { return Err(Error::IdentityMismatch); } + if cpu.workers() != 15 { + return Err(Error::IdentityMismatch); + } cache.cpu_miss = Some(Rc::new(RefCell::new(cpu))); for layer in 0..48 { cache.preload_shared_quartet(binding, shared.quartet(layer)?, spill, &mut shared)?; } - if cache.main_bytes != shared.bytes || cache.main.len() != 192 { return Err(Error::IdentityMismatch); } + if cache.main_bytes != shared.bytes || cache.main.len() != 192 { + return Err(Error::IdentityMismatch); + } shared.finish_preload(); let (free, _) = context.memory_info().map_err(driver_error)?; - let owner = cache_strata_adaptive::AdaptiveCache::preload(binding, context, &profile, template, - ProfileLimits { main_cap: remaining_main, allocated: context.allocated_bytes(), - device_budget: context.budget_bytes(), physical_free: free, - working_reserve: WORKING_RESERVE, window_spill }, shared.bytes, metadata)?; + let owner = cache_strata_adaptive::AdaptiveCache::preload( + binding, + context, + &profile, + template, + ProfileLimits { + main_cap: remaining_main, + allocated: context.allocated_bytes(), + device_budget: context.budget_bytes(), + physical_free: free, + working_reserve: WORKING_RESERVE, + window_spill, + }, + shared.bytes, + metadata, + )?; let Some(main_bytes) = cache.main_bytes.checked_add(owner.charged_bytes()) else { - let _ = owner.close(); return Err(Error::Overflow); + let _ = owner.close(); + return Err(Error::Overflow); }; cache.adaptive_shared = Some(shared); cache.adaptive = Some(owner); @@ -140,7 +198,10 @@ impl<'ctx> MoeWeightCache<'ctx> { } cache.validate(binding, context) })(); - if let Err(primary) = operation { let _ = cache.close(); return Err(primary); } + if let Err(primary) = operation { + let _ = cache.close(); + return Err(primary); + } Ok(cache) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_window_spill_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_window_spill_fn.rs index c1d644bf..b28629f1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_window_spill_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_fill/profile_window_spill_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // Complete simultaneously live prefill owners; reserve is additive. pub(super) fn profile_window_spill() -> Result { 64usize @@ -17,7 +16,5 @@ pub(super) fn profile_window_spill() -> Result { // No allocation or device capability: retain the whole existing window margin. pub(super) fn profile_window_spill_with_floor(reusable_spill_floor: usize) -> Result { - profile_window_spill()? - .checked_add(reusable_spill_floor) - .ok_or(Error::Overflow) + profile_window_spill()?.checked_add(reusable_spill_floor).ok_or(Error::Overflow) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_sdet.rs index 14cafcc9..ecb0eede 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_profile_sdet.rs @@ -86,21 +86,14 @@ fn expected_prefix( charges: &[[usize; 3]; 48], limits: ProfileLimits, ) -> (usize, usize, usize, usize) { - let largest = charges - .iter() - .map(|roles| roles.iter().sum::()) - .max() - .unwrap(); + let largest = charges.iter().map(|roles| roles.iter().sum::()).max().unwrap(); let spill = largest + limits.window_spill; let work = spill + limits.working_reserve; - let capacity = [ - limits.main_cap - spill, - limits.device_budget - limits.allocated - work, - limits.physical_free - work, - ] - .into_iter() - .min() - .unwrap(); + let capacity = + [limits.main_cap - spill, limits.device_budget - limits.allocated - work, limits.physical_free - work] + .into_iter() + .min() + .unwrap(); let mut available = capacity; let mut count = 0; for &(layer, _) in pairs { @@ -114,33 +107,15 @@ fn expected_prefix( (count, capacity - available, spill, largest) } -fn compare_plan( - profile: &RankedProfile, - charges: &[[usize; 3]; 48], - limits: ProfileLimits, -) -> PrefixPlan { +fn compare_plan(profile: &RankedProfile, charges: &[[usize; 3]; 48], limits: ProfileLimits) -> PrefixPlan { // Original-order ledger is established BEFORE the candidate plan. let expected = expected_prefix(profile.ordered_pairs(), charges, limits); let plan = PrefixPlan::new(profile, charges, limits).unwrap(); - assert_eq!( - ( - plan.prefix, - plan.charged_bytes, - plan.spill_reserve, - plan.largest_triplet - ), - expected - ); - assert_eq!( - plan.selected.iter().filter(|selected| **selected).count(), - expected.0 - ); + assert_eq!((plan.prefix, plan.charged_bytes, plan.spill_reserve, plan.largest_triplet), expected); + assert_eq!(plan.selected.iter().filter(|selected| **selected).count(), expected.0); for (rank, &(layer, expert)) in profile.ordered_pairs().iter().enumerate() { for role in 0..3 { - assert_eq!( - plan.contains(u32::from(layer), Some(u32::from(expert)), role), - rank < expected.0 - ); + assert_eq!(plan.contains(u32::from(layer), Some(u32::from(expert)), role), rank < expected.0); } } assert!(!plan.contains(48, Some(0), 0)); @@ -150,8 +125,7 @@ fn compare_plan( assert!(profile.metadata_bytes() + plan.metadata_bytes() < HOST_CAP); assert_eq!( profile.metadata_bytes(), - profile.pairs.capacity() * std::mem::size_of::<(u16, u16)>() - + std::mem::size_of::() + profile.pairs.capacity() * std::mem::size_of::<(u16, u16)>() + std::mem::size_of::() ); assert_eq!( plan.metadata_bytes(), @@ -177,14 +151,7 @@ fn original_decoder_first_ranked_profile_prefix_spill_and_atomic_refusals() { assert_eq!(profile.ordered_pairs().len(), 24_576); assert!(RankedProfile::parse(&full, [0; 32]).is_err()); - for length in [ - 0usize, - 4, - 23, - BASE_BYTES - 1, - BASE_BYTES + 1, - full.len() - 1, - ] { + for length in [0usize, 4, 23, BASE_BYTES - 1, BASE_BYTES + 1, full.len() - 1] { refused(&full[..length], Error::IdentityMismatch); } let mut extra = full.clone(); @@ -261,12 +228,7 @@ fn original_decoder_first_ranked_profile_prefix_spill_and_atomic_refusals() { } assert_eq!(compare_plan(&profile, &charges, one).prefix, 1); } - let snapshot = ( - profile.pairs.clone(), - accepted.selected.clone(), - accepted.prefix, - accepted.charged_bytes, - ); + let snapshot = (profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes); let mut rejects = Vec::new(); for field in 0..3 { let mut no = tiny; @@ -298,16 +260,9 @@ fn original_decoder_first_ranked_profile_prefix_spill_and_atomic_refusals() { no.working_reserve = usize::MAX; rejects.push((charges, no, Error::Overflow)); for (bad_charges, bad_limits, expected) in rejects { - assert!( - matches!(PrefixPlan::new(&profile,&bad_charges,bad_limits),Err(error) if error == expected) - ); + assert!(matches!(PrefixPlan::new(&profile,&bad_charges,bad_limits),Err(error) if error == expected)); assert_eq!( - ( - profile.pairs.clone(), - accepted.selected.clone(), - accepted.prefix, - accepted.charged_bytes - ), + (profile.pairs.clone(), accepted.selected.clone(), accepted.prefix, accepted.charged_bytes), snapshot ); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_routed_outputs.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_routed_outputs.rs index 1224c028..0edeeea9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_routed_outputs.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_routed_outputs.rs @@ -23,24 +23,15 @@ pub(in crate::qwen_forward) struct RoutedOutputBank<'ctx> { } impl<'ctx> RoutedOutputBank<'ctx> { - pub(in crate::qwen_forward) fn new( - binding: BindingIdentity, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(in crate::qwen_forward) fn new(binding: BindingIdentity, context: &'ctx Context<'ctx>) -> Result { if context.is_poisoned() { return Err(Error::CudaExecution); } if Self::metadata_extent() > METADATA_LIMIT { return Err(Error::InputAllocation); } - let needed = ROUTED_OUTPUT_BANK_BYTES - .checked_add(RESERVE) - .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > context.budget_bytes()) - { + let needed = ROUTED_OUTPUT_BANK_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } let (free, _) = context.memory_info().map_err(driver_error)?; @@ -98,11 +89,7 @@ impl<'ctx> RoutedOutputBank<'ctx> { self.failed.get() || self.context.is_poisoned() } - pub(in crate::qwen_forward) fn validate( - &self, - binding: &BindingIdentity, - context: &Context<'_>, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate(&self, binding: &BindingIdentity, context: &Context<'_>) -> Result<()> { if !self.binding.matches(binding) || !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } @@ -132,19 +119,12 @@ impl<'ctx> RoutedOutputBank<'ctx> { return Err(Error::InvalidDimension); } let next = self.completed.get().checked_add(1).ok_or(Error::Overflow)?; - let mut loan = self - .slots - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut loan = self.slots.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let start = (columns - 1) * ROLES; - let roles: &mut [Option>; ROLES] = (&mut loan[start..start + ROLES]) - .try_into() - .map_err(|_| Error::IdentityMismatch)?; + let roles: &mut [Option>; ROLES] = + (&mut loan[start..start + ROLES]).try_into().map_err(|_| Error::IdentityMismatch)?; for (slot, per_column) in roles.iter().zip(ROLE_BYTES) { - if slot - .as_ref() - .is_none_or(|buffer| buffer.len() != per_column * columns) - { + if slot.as_ref().is_none_or(|buffer| buffer.len() != per_column * columns) { self.failed.set(true); return Err(Error::IdentityMismatch); } @@ -176,11 +156,7 @@ impl<'ctx> RoutedOutputBank<'ctx> { } fn drain(&mut self) -> Result<()> { - let mut primary = if self.is_failed() { - Some(Error::CudaExecution) - } else { - None - }; + let mut primary = if self.is_failed() { Some(Error::CudaExecution) } else { None }; for slot in self.slots.get_mut() { if let Some(buffer) = slot.take() && let Err(error) = buffer.release() diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs index 4f3902f5..32164ac1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_shared_permanent_sdet.rs @@ -2,25 +2,60 @@ use super::*; fn descriptor_set() -> Vec<[MoeWeightDescriptor; 4]> { - (0..48u32).map(|layer| [ - MoeWeightDescriptor { layer, expert: None, role: 0, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 }, - MoeWeightDescriptor { layer, expert: None, role: 1, raw_kind: 14, columns: 2560, rows: 640, bytes: 1_344_000 }, - MoeWeightDescriptor { layer, expert: None, role: 2, raw_kind: 8, columns: 640, rows: 2560, bytes: 1_740_800 }, - MoeWeightDescriptor { layer, expert: None, role: 3, raw_kind: 30, columns: 2560, rows: 1, bytes: 5120 }, - ]).collect() + (0..48u32) + .map(|layer| { + [ + MoeWeightDescriptor { + layer, + expert: None, + role: 0, + raw_kind: 14, + columns: 2560, + rows: 640, + bytes: 1_344_000, + }, + MoeWeightDescriptor { + layer, + expert: None, + role: 1, + raw_kind: 14, + columns: 2560, + rows: 640, + bytes: 1_344_000, + }, + MoeWeightDescriptor { + layer, + expert: None, + role: 2, + raw_kind: 8, + columns: 640, + rows: 2560, + bytes: 1_740_800, + }, + MoeWeightDescriptor { layer, expert: None, role: 3, raw_kind: 30, columns: 2560, rows: 1, bytes: 5120 }, + ] + }) + .collect() +} +fn selected_storage() -> Vec { + vec![false; 48 * 512] } -fn selected_storage() -> Vec { vec![false; 48 * 512] } fn reference_prefix(profile: &RankedProfile, totals: &[usize; 48], capacity: usize) -> (usize, usize) { - let mut bytes = 0; let mut count = 0; + let mut bytes = 0; + let mut count = 0; for &(layer, _) in profile.ordered_pairs() { - if bytes + totals[usize::from(layer)] > capacity { break; } - bytes += totals[usize::from(layer)]; count += 1; + if bytes + totals[usize::from(layer)] > capacity { + break; + } + bytes += totals[usize::from(layer)]; + count += 1; } (count, bytes) } #[test] fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger() { - let profile = RankedProfile { pairs: (0..48u16).flat_map(|layer| (0..512u16).map(move |expert| (layer, expert))).collect() }; + let profile = + RankedProfile { pairs: (0..48u16).flat_map(|layer| (0..512u16).map(move |expert| (layer, expert))).collect() }; let charges = std::array::from_fn::<_, 48, _>(|layer| [627_200 + layer, 627_200 + layer, 921_816 + layer]); let totals = charges.map(|roles| roles.into_iter().sum::()); let shared_keys = descriptor_set(); @@ -35,30 +70,52 @@ fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger let initial_free = 26usize << 30; // Old production planner FIRST, using the independently precharged ledger. // The new API receives actual post-upload allocated/free and reduces MAIN only. - let old_limits = ProfileLimits { main_cap: (24usize << 30) - shared_total, - allocated: base + shared_total, device_budget: budget, - physical_free: initial_free - shared_total, working_reserve: safety, window_spill }; + let old_limits = ProfileLimits { + main_cap: (24usize << 30) - shared_total, + allocated: base + shared_total, + device_budget: budget, + physical_free: initial_free - shared_total, + working_reserve: safety, + window_spill, + }; let old = PrefixPlan::new(&profile, &charges, old_limits).unwrap(); let remaining = remaining_shared_main(24usize << 30, shared_total).unwrap(); assert_eq!(remaining, (24usize << 30) - shared_total); - let current = PrefixPlan::new_shared_with_storage(&profile, &charges, ProfileLimits { - main_cap: remaining, allocated: base + shared_total, device_budget: budget, - physical_free: initial_free - shared_total, working_reserve: safety, window_spill, - }, selected_storage()).unwrap(); + let current = PrefixPlan::new_shared_with_storage( + &profile, + &charges, + ProfileLimits { + main_cap: remaining, + allocated: base + shared_total, + device_budget: budget, + physical_free: initial_free - shared_total, + working_reserve: safety, + window_spill, + }, + selected_storage(), + ) + .unwrap(); let independently_available = ((24usize << 30) - shared_total - spill) .min(budget - base - shared_total - spill - safety) .min(initial_free - shared_total - spill - safety); let expected = reference_prefix(&profile, &totals, independently_available); assert_eq!((current.prefix, current.charged_bytes), expected); - assert_eq!((current.prefix, current.charged_bytes, current.spill_reserve), - (old.prefix, old.charged_bytes, old.spill_reserve)); + assert_eq!( + (current.prefix, current.charged_bytes, current.spill_reserve), + (old.prefix, old.charged_bytes, old.spill_reserve) + ); assert_eq!(current.selected, old.selected); // Each independent MAIN / typed / physical boundary is exact; one byte short refuses. for constraint in 0..3 { for deficit in [0usize, 1] { - let mut limits = ProfileLimits { main_cap: remaining, allocated: base + shared_total, - device_budget: budget, physical_free: initial_free - shared_total, - working_reserve: safety, window_spill }; + let mut limits = ProfileLimits { + main_cap: remaining, + allocated: base + shared_total, + device_budget: budget, + physical_free: initial_free - shared_total, + working_reserve: safety, + window_spill, + }; match constraint { 0 => limits.main_cap = spill + totals[0] - deficit, 1 => limits.device_budget = limits.allocated + spill + safety + totals[0] - deficit, @@ -67,7 +124,8 @@ fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger let first = PrefixPlan::new(&profile, &charges, limits); let next = PrefixPlan::new_shared_with_storage(&profile, &charges, limits, selected_storage()); if deficit == 0 { - assert_eq!(first.unwrap().prefix, 1); assert_eq!(next.unwrap().prefix, 1); + assert_eq!(first.unwrap().prefix, 1); + assert_eq!(next.unwrap().prefix, 1); } else { assert!(matches!(first, Err(Error::InputAllocation))); assert!(matches!(next, Err(Error::InputAllocation))); @@ -77,15 +135,40 @@ fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger assert!(matches!(remaining_shared_main(shared_total - 1, shared_total), Err(Error::InputAllocation))); assert!(matches!(remaining_shared_main(usize::MAX, SHARED_MAX_BYTES + 1), Err(Error::InvalidDimension))); assert!(matches!(remaining_shared_main(usize::MAX, 0), Err(Error::InvalidDimension))); - assert!(matches!(PrefixPlan::new_shared_with_storage(&profile, &charges, ProfileLimits { - main_cap: remaining, allocated: base, device_budget: budget, physical_free: initial_free, - working_reserve: safety, window_spill: usize::MAX, - }, selected_storage()), Err(Error::Overflow))); - let mut changed_storage = selected_storage(); changed_storage[24_575] = true; - assert!(matches!(PrefixPlan::new_shared_with_storage(&profile, &charges, ProfileLimits { - main_cap: remaining, allocated: base, device_budget: budget, physical_free: initial_free, - working_reserve: safety, window_spill, - }, changed_storage), Err(Error::IdentityMismatch))); + assert!(matches!( + PrefixPlan::new_shared_with_storage( + &profile, + &charges, + ProfileLimits { + main_cap: remaining, + allocated: base, + device_budget: budget, + physical_free: initial_free, + working_reserve: safety, + window_spill: usize::MAX, + }, + selected_storage() + ), + Err(Error::Overflow) + )); + let mut changed_storage = selected_storage(); + changed_storage[24_575] = true; + assert!(matches!( + PrefixPlan::new_shared_with_storage( + &profile, + &charges, + ProfileLimits { + main_cap: remaining, + allocated: base, + device_budget: budget, + physical_free: initial_free, + working_reserve: safety, + window_spill, + }, + changed_storage + ), + Err(Error::IdentityMismatch) + )); // Exact whole descriptor identity, never just layer/role/count matches. let mut pool = SharedPermanentPool::new(shared_keys.clone()).unwrap(); assert_eq!(pool.descriptor_count(), 192); @@ -93,30 +176,50 @@ fn original_plan_first_shared_main_only_precharge_and_actual_role_counter_ledger assert!(pool.metadata_bytes().unwrap() < HOST_CAP); for key in shared_keys.iter().flatten().copied() { assert!(pool.contains(key)); - let mut bad = key; bad.bytes += 1; assert!(!pool.contains(bad)); - bad = key; bad.raw_kind += 1; assert!(!pool.contains(bad)); - bad = key; bad.expert = Some(0); assert!(!pool.contains(bad)); + let mut bad = key; + bad.bytes += 1; + assert!(!pool.contains(bad)); + bad = key; + bad.raw_kind += 1; + assert!(!pool.contains(bad)); + bad = key; + bad.expert = Some(0); + assert!(!pool.contains(bad)); pool.fill(key, key.bytes, key.bytes); } // A quartet that is internally consistent but sits at the wrong layer index is an identity mismatch; // a quartet whose members disagree on the layer fails descriptor validation first. - let mut malformed = shared_keys.clone(); malformed[47].iter_mut().for_each(|key| key.layer = 0); + let mut malformed = shared_keys.clone(); + malformed[47].iter_mut().for_each(|key| key.layer = 0); assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::IdentityMismatch))); - let mut malformed = shared_keys.clone(); malformed[47][3].layer = 0; + let mut malformed = shared_keys.clone(); + malformed[47][3].layer = 0; assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension))); - let mut malformed = shared_keys.clone(); malformed[0][0].bytes -= 1; + let mut malformed = shared_keys.clone(); + malformed[0][0].bytes -= 1; assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension))); - let mut malformed = shared_keys.clone(); malformed.pop(); + let mut malformed = shared_keys.clone(); + malformed.pop(); assert!(matches!(SharedPermanentPool::new(malformed), Err(Error::InvalidDimension))); assert_eq!(pool.roles.iter().map(|c| c.source_read_bytes).sum::(), shared_total as u64); assert_eq!(pool.roles.iter().map(|c| c.upload_bytes).sum::(), shared_total as u64); assert_eq!(pool.roles.iter().map(|c| c.fills).sum::(), 192); pool.finish_preload(); - for key in shared_keys.iter().flatten().copied() { pool.hit(key); } - let routed = MoeWeightDescriptor { layer: 47, expert: Some(511), role: 2, raw_kind: 20, - columns: 640, rows: 2560, bytes: 921_600 }; + for key in shared_keys.iter().flatten().copied() { + pool.hit(key); + } + let routed = MoeWeightDescriptor { + layer: 47, + expert: Some(511), + role: 2, + raw_kind: 20, + columns: 640, + rows: 2560, + bytes: 921_600, + }; pool.fill(routed, routed.bytes, routed.bytes + 216); - pool.hit(routed); pool.evict(routed, routed.bytes + 216); + pool.hit(routed); + pool.evict(routed, routed.bytes + 216); let requests = pool.request_roles().unwrap(); assert_eq!(requests.iter().map(|c| c.hits).sum::(), 193); assert_eq!(requests.iter().map(|c| c.fills).sum::(), 1); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs index 30130595..336d79e6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive.rs @@ -45,9 +45,10 @@ pub(super) struct AdaptivePolicy { mod tests; use super::{CachedMoeMatrix, WORKING_RESERVE, binding_error, driver_error}; -use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, MoeExpertWeights, - MoeExpertSelection, MoeMatrixRole}; -use leleka_cuda_driver::{Context, DeviceBuffer, PendingOwnedCopy, CompletedOwnedCopy, OwnedCopyPoll}; +use crate::model_binding::qwen4exp_input::{ + BindingIdentity, ModelBinding, MoeExpertSelection, MoeExpertWeights, MoeMatrixRole, +}; +use leleka_cuda_driver::{CompletedOwnedCopy, Context, DeviceBuffer, OwnedCopyPoll, PendingOwnedCopy}; struct Transfer<'ctx> { swap: Swap, @@ -89,11 +90,11 @@ pub(crate) struct AdaptiveWitness { #[path = "cache_strata_adaptive/reserve_fn.rs"] mod reserve_fn; #[allow(unused_imports)] -use reserve_fn::reserve; +use reserve_fn::blob_bytes; #[allow(unused_imports)] use reserve_fn::cell; #[allow(unused_imports)] -use reserve_fn::blob_bytes; +use reserve_fn::reserve; #[path = "cache_strata_adaptive/impl_adaptivecache.rs"] mod impl_adaptivecache; #[path = "cache_strata_adaptive/transfer_metadata_bound_fn.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs index a14548fa..5ec2650a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/impl_adaptivecache.rs @@ -5,25 +5,43 @@ use super::*; impl<'ctx> AdaptiveCache<'ctx> { pub(in super::super) fn preload( - binding: &ModelBinding, context: &'ctx Context<'ctx>, profile: &RankedProfile, - template: [[MoeWeightDescriptor; 3]; LAYERS], limits: ProfileLimits, - shared_bytes: usize, external_metadata: usize, + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + profile: &RankedProfile, + template: [[MoeWeightDescriptor; 3]; LAYERS], + limits: ProfileLimits, + shared_bytes: usize, + external_metadata: usize, ) -> Result { - let largest = template.iter().try_fold(0usize, |max, keys| { - Ok::<_, Error>(max.max(blob_bytes(keys)?)) - })?; + let largest = template.iter().try_fold(0usize, |max, keys| Ok::<_, Error>(max.max(blob_bytes(keys)?)))?; let spill_reserve = limits.window_spill.checked_add(largest).ok_or(Error::Overflow)?; let policy = AdaptivePolicy::new(profile, template, limits)?; let mut buffers = reserve(policy.initial_slots().len())?; buffers.resize_with(policy.initial_slots().len(), || None); let transfers = reserve(ADAPT_SWAPS)?; - let metadata = policy.metadata_bytes() + let metadata = policy + .metadata_bytes() .checked_add(buffers.capacity() * std::mem::size_of::; 3]>>()) .and_then(|n| n.checked_add(transfers.capacity() * std::mem::size_of::>())) - .and_then(|n| n.checked_add(external_metadata)).ok_or(Error::Overflow)?; - if metadata > HOST_CAP { return Err(Error::InputAllocation); } - let mut owner = Self { binding: binding.identity(), context, policy, buffers, - transfers, failed: false, uploads: 0, swaps: 0, swap_uploads: 0, occurrences: 0, hits: 0, misses: 0 }; + .and_then(|n| n.checked_add(external_metadata)) + .ok_or(Error::Overflow)?; + if metadata > HOST_CAP { + return Err(Error::InputAllocation); + } + let mut owner = Self { + binding: binding.identity(), + context, + policy, + buffers, + transfers, + failed: false, + uploads: 0, + swaps: 0, + swap_uploads: 0, + occurrences: 0, + hits: 0, + misses: 0, + }; let operation = (|| { for slot in 0..owner.buffers.len() { let keys = owner.policy.slots[slot].keys; @@ -33,22 +51,35 @@ impl<'ctx> AdaptiveCache<'ctx> { for (role, key) in keys.iter().copied().enumerate() { // Future whole slot plus fixed spill is never credited as // already free. Actual typed/physical snapshots each role. - let remaining = keys[role..].iter().try_fold(0usize, |n, k| - n.checked_add(k.bytes).ok_or(Error::Overflow))?; - let required = remaining.checked_add(spill_reserve) - .and_then(|n| n.checked_add(WORKING_RESERVE)).ok_or(Error::Overflow)?; + let remaining = keys[role..] + .iter() + .try_fold(0usize, |n, k| n.checked_add(k.bytes).ok_or(Error::Overflow))?; + let required = remaining + .checked_add(spill_reserve) + .and_then(|n| n.checked_add(WORKING_RESERVE)) + .ok_or(Error::Overflow)?; let (free, _) = context.memory_info().map_err(driver_error)?; - if required > free || context.allocated_bytes().checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || shared_bytes.checked_add(owner.policy.charged_bytes()) + if required > free + || context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || shared_bytes + .checked_add(owner.policy.charged_bytes()) .and_then(|n| n.checked_add(spill_reserve)) .is_none_or(|n| n > super::super::MAIN_LIMIT) - { return Err(Error::InputAllocation); } + { + return Err(Error::InputAllocation); + } let raw = binding.moe_preload_block(key).map_err(binding_error)?; - if raw.len() != key.bytes { return Err(Error::InvalidDimension); } + if raw.len() != key.bytes { + return Err(Error::InvalidDimension); + } let mut buffer = context.allocate(key.bytes).map_err(driver_error)?; if let Err(primary) = buffer.copy_from(&raw).map_err(driver_error) { - if buffer.release().is_err() { owner.failed = true; } + if buffer.release().is_err() { + owner.failed = true; + } return Err(primary); } loaded[role] = Some(buffer); @@ -58,7 +89,9 @@ impl<'ctx> AdaptiveCache<'ctx> { })(); if let Err(primary) = load { for buffer in loaded.into_iter().rev().flatten() { - if buffer.release().is_err() { owner.failed = true; } + if buffer.release().is_err() { + owner.failed = true; + } } return Err(primary); } @@ -66,20 +99,34 @@ impl<'ctx> AdaptiveCache<'ctx> { } owner.validate(binding) })(); - if let Err(primary) = operation { let _ = owner.close(); return Err(primary); } + if let Err(primary) = operation { + let _ = owner.close(); + return Err(primary); + } Ok(owner) } pub(in super::super) fn validate(&self, binding: &ModelBinding) -> Result<()> { - if self.failed || self.context.is_poisoned() { return Err(Error::CudaExecution); } - if !self.binding.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } Ok(()) } pub(super) fn revalidate_keys(&self, binding: &ModelBinding, keys: [MoeWeightDescriptor; 3]) -> Result<()> { self.validate(binding)?; for (role, key) in keys.into_iter().enumerate() { - let actual = binding.moe_preload_descriptor(key.layer, key.expert.ok_or(Error::InvalidExpert)?, - [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down][role]).map_err(binding_error)?; - if actual != key { return Err(Error::IdentityMismatch); } + let actual = binding + .moe_preload_descriptor( + key.layer, + key.expert.ok_or(Error::InvalidExpert)?, + [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down][role], + ) + .map_err(binding_error)?; + if actual != key { + return Err(Error::IdentityMismatch); + } } Ok(()) } @@ -90,33 +137,50 @@ impl<'ctx> AdaptiveCache<'ctx> { let mut ids = [0u32; 10]; let mut layer = None; for (slot, id) in ids.iter_mut().enumerate() { - let key = binding.moe_weight_descriptor(weights, MoeExpertSelection::Routed { slot }, - MoeMatrixRole::Gate).map_err(binding_error)?; - if layer.is_some_and(|old| old != key.layer) { return Err(Error::IdentityMismatch); } - layer = Some(key.layer); *id = key.expert.ok_or(Error::InvalidExpert)?; + let key = binding + .moe_weight_descriptor(weights, MoeExpertSelection::Routed { slot }, MoeMatrixRole::Gate) + .map_err(binding_error)?; + if layer.is_some_and(|old| old != key.layer) { + return Err(Error::IdentityMismatch); + } + layer = Some(key.layer); + *id = key.expert.ok_or(Error::InvalidExpert)?; } let layer = layer.ok_or(Error::IdentityMismatch)?; let mut hits = 0u64; - for &expert in &ids { hits += u64::from(self.policy.resident_slot(layer, expert)?.is_some()); } + for &expert in &ids { + hits += u64::from(self.policy.resident_slot(layer, expert)?.is_some()); + } let occurrences = self.occurrences.checked_add(10).ok_or(Error::Overflow)?; let next_hits = self.hits.checked_add(hits).ok_or(Error::Overflow)?; let next_misses = self.misses.checked_add(10 - hits).ok_or(Error::Overflow)?; self.policy.observe(layer, &ids)?; - self.occurrences = occurrences; self.hits = next_hits; self.misses = next_misses; + self.occurrences = occurrences; + self.hits = next_hits; + self.misses = next_misses; Ok(()) } /// Missing, in-flight incoming, and evicted outgoing are genuine CPU misses. /// This does no source read, upload, eviction, or GPU miss fill. - pub(in super::super) fn matrix(&self, binding: &ModelBinding, key: MoeWeightDescriptor) - -> Result>> { + pub(in super::super) fn matrix( + &self, + binding: &ModelBinding, + key: MoeWeightDescriptor, + ) -> Result>> { self.validate(binding)?; let expert = key.expert.ok_or(Error::InvalidExpert)?; - let Some(slot) = self.policy.resident_slot(key.layer, expert)? else { return Ok(None); }; + let Some(slot) = self.policy.resident_slot(key.layer, expert)? else { + return Ok(None); + }; let keys = self.policy.slots[slot].keys; - if key.role > 2 || keys[key.role as usize] != key { return Err(Error::IdentityMismatch); } + if key.role > 2 || keys[key.role as usize] != key { + return Err(Error::IdentityMismatch); + } let owned = self.buffers[slot].as_ref().ok_or(Error::IdentityMismatch)?; let buffer = &owned[key.role as usize]; - if buffer.len() != key.bytes { return Err(Error::IdentityMismatch); } + if buffer.len() != key.bytes { + return Err(Error::IdentityMismatch); + } Ok(Some(CachedMoeMatrix::Raw(buffer))) } /// Same verified-window cadence and decision as source, scheduled after @@ -128,7 +192,9 @@ impl<'ctx> AdaptiveCache<'ctx> { self.validate(binding)?; let due = self.policy.rounds.checked_add(1).ok_or(Error::Overflow)? % ADAPT_EVERY == 0; self.policy.completed_window()?; - if !due || !self.transfers.is_empty() { return Ok(()); } + if !due || !self.transfers.is_empty() { + return Ok(()); + } let selected: [Option; ADAPT_SWAPS] = std::array::from_fn(|i| self.policy.ranked.get(i).copied()); // All staged byte owners are reserved before any enqueue. Full actual // finite source checks are maintained; bank retains outgoing source too. @@ -140,11 +206,15 @@ impl<'ctx> AdaptiveCache<'ctx> { let keys = self.policy.incoming_keys(swap)?; self.revalidate_keys(binding, keys)?; staged_bytes = staged_bytes.checked_add(blob_bytes(&keys)?).ok_or(Error::Overflow)?; - if staged_bytes > 512 * 1024 * 1024 { return Err(Error::InputAllocation); } + if staged_bytes > 512 * 1024 * 1024 { + return Err(Error::InputAllocation); + } let mut raw: [Option>; 3] = std::array::from_fn(|_| None); for (role, key) in keys.iter().copied().enumerate() { let block = binding.moe_preload_block(key).map_err(binding_error)?; - if block.len() != key.bytes { return Err(Error::InvalidDimension); } + if block.len() != key.bytes { + return Err(Error::InvalidDimension); + } raw[role] = Some(block.into_vec()); } let mut pairs = reserve(3)?; @@ -168,22 +238,31 @@ impl<'ctx> AdaptiveCache<'ctx> { if let Err(primary) = self.policy.mark_enqueued(&swaps_vec) { self.failed = true; for (_, pairs) in staged.drain(..) { - for (buffer, _) in pairs.into_iter().rev() { let _ = buffer.release(); } + for (buffer, _) in pairs.into_iter().rev() { + let _ = buffer.release(); + } } return Err(primary); } let mut primary = None; for (swap, pairs) in staged.drain(..) { if primary.is_some() { - for (buffer, _) in pairs.into_iter().rev() { let _ = buffer.release(); } + for (buffer, _) in pairs.into_iter().rev() { + let _ = buffer.release(); + } continue; } match self.context.copy_owned_batch_async(pairs).map_err(driver_error) { Ok(pending) => self.transfers.push(Transfer { swap, pending: Some(pending), complete: None }), - Err(error) => { self.failed = true; primary = Some(error); } + Err(error) => { + self.failed = true; + primary = Some(error); + } } } - if let Some(primary) = primary { return Err(primary); } + if let Some(primary) = primary { + return Err(primary); + } Ok(()) } /// Query actual driver events. A completed owner is retained privately until @@ -193,12 +272,14 @@ impl<'ctx> AdaptiveCache<'ctx> { let operation = (|| { // Admit every success counter before any incoming publication. let next_swaps = self.swaps.checked_add(self.transfers.len() as u64).ok_or(Error::Overflow)?; - let next_uploads = self.transfers.iter().try_fold(self.swap_uploads, |n, transfer| - n.checked_add(self.policy.slots[transfer.swap.slot].bytes as u64).ok_or(Error::Overflow))?; + let next_uploads = self.transfers.iter().try_fold(self.swap_uploads, |n, transfer| { + n.checked_add(self.policy.slots[transfer.swap.slot].bytes as u64).ok_or(Error::Overflow) + })?; for transfer in &mut self.transfers { if let Some(pending) = transfer.pending.take() { - if wait { transfer.complete = Some(pending.wait().map_err(driver_error)?); } - else { + if wait { + transfer.complete = Some(pending.wait().map_err(driver_error)?); + } else { match pending.poll().map_err(driver_error)? { OwnedCopyPoll::Pending(owner) => transfer.pending = Some(owner), OwnedCopyPoll::Complete(receipt) => transfer.complete = Some(receipt), @@ -206,58 +287,83 @@ impl<'ctx> AdaptiveCache<'ctx> { } } } - if self.transfers.iter().any(|t| t.complete.is_none()) { return Ok(()); } + if self.transfers.iter().any(|t| t.complete.is_none()) { + return Ok(()); + } if self.transfers.iter().any(|t| t.complete.as_ref().is_none_or(|receipt| receipt.len() != 3)) { return Err(Error::IdentityMismatch); } for swap in &self.policy.pending { if self.policy.resident[cell(swap.layer, swap.incoming)?] != -1 || self.policy.resident[cell(swap.layer, swap.outgoing)?] != -1 - || self.policy.slots[swap.slot].keys[0].expert != Some(swap.outgoing) { + || self.policy.slots[swap.slot].keys[0].expert != Some(swap.outgoing) + { return Err(Error::IdentityMismatch); } } for transfer in self.transfers.drain(..) { let receipt = transfer.complete.ok_or(Error::IdentityMismatch)?; if receipt.len() != 3 { - for (buffer, _) in receipt.into_pairs().into_iter().flatten() { let _ = buffer.release(); } + for (buffer, _) in receipt.into_pairs().into_iter().flatten() { + let _ = buffer.release(); + } return Err(Error::IdentityMismatch); } let mut pairs = receipt.into_pairs(); - let buffers = [pairs[0].take().ok_or(Error::IdentityMismatch)?.0, + let buffers = [ + pairs[0].take().ok_or(Error::IdentityMismatch)?.0, pairs[1].take().ok_or(Error::IdentityMismatch)?.0, - pairs[2].take().ok_or(Error::IdentityMismatch)?.0]; - if buffers.iter().zip(self.policy.slots[transfer.swap.slot].keys) + pairs[2].take().ok_or(Error::IdentityMismatch)?.0, + ]; + if buffers + .iter() + .zip(self.policy.slots[transfer.swap.slot].keys) .any(|(buffer, key)| buffer.len() != key.bytes) { - for buffer in buffers.into_iter().rev() { let _ = buffer.release(); } + for buffer in buffers.into_iter().rev() { + let _ = buffer.release(); + } return Err(Error::IdentityMismatch); } // Genuine receipt is consumed and whole buffers installed before // metadata incoming publication. No fake external Ready bit. self.buffers[transfer.swap.slot] = Some(buffers); self.policy.publish_completed(0)?; - } - self.swaps = next_swaps; self.swap_uploads = next_uploads; + self.swaps = next_swaps; + self.swap_uploads = next_uploads; self.validate(binding) })(); - if operation.is_err() { self.failed = true; } + if operation.is_err() { + self.failed = true; + } operation } pub(in super::super) fn witness(&self, binding: &ModelBinding) -> Result { self.validate(binding)?; - Ok(AdaptiveWitness { initial_slots: self.buffers.len(), resident_slots: self.policy.resident.iter().filter(|s| **s >= 0).count(), - pending_swaps: self.transfers.len(), verified_windows: self.policy.rounds, - routed_occurrences: self.occurrences, resident_occurrences: self.hits, cpu_occurrences: self.misses, - preload_upload_bytes: self.uploads, completed_swap_upload_bytes: self.swap_uploads, - completed_swaps: self.swaps, raw_slot_bytes: self.policy.charged_bytes() }) + Ok(AdaptiveWitness { + initial_slots: self.buffers.len(), + resident_slots: self.policy.resident.iter().filter(|s| **s >= 0).count(), + pending_swaps: self.transfers.len(), + verified_windows: self.policy.rounds, + routed_occurrences: self.occurrences, + resident_occurrences: self.hits, + cpu_occurrences: self.misses, + preload_upload_bytes: self.uploads, + completed_swap_upload_bytes: self.swap_uploads, + completed_swaps: self.swaps, + raw_slot_bytes: self.policy.charged_bytes(), + }) + } + pub(in super::super) fn charged_bytes(&self) -> usize { + self.policy.charged_bytes() } - pub(in super::super) fn charged_bytes(&self) -> usize { self.policy.charged_bytes() } pub(in super::super) fn close(mut self) -> Result<()> { let mut failed = self.failed; for transfer in self.transfers.drain(..) { - if let Some(pending) = transfer.pending { failed |= pending.close().is_err(); } + if let Some(pending) = transfer.pending { + failed |= pending.close().is_err(); + } if let Some(complete) = transfer.complete { for (buffer, _) in complete.into_pairs().into_iter().flatten() { failed |= buffer.release().is_err(); @@ -265,7 +371,9 @@ impl<'ctx> AdaptiveCache<'ctx> { } } for buffers in self.buffers.drain(..).flatten() { - for buffer in buffers.into_iter().rev() { failed |= buffer.release().is_err(); } + for buffer in buffers.into_iter().rev() { + failed |= buffer.release().is_err(); + } } if failed { Err(Error::CudaExecution) } else { Ok(()) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/reserve_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/reserve_fn.rs index 6ff52dd7..2382cf8e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/reserve_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/reserve_fn.rs @@ -21,11 +21,13 @@ pub(super) fn blob_bytes(keys: &[MoeWeightDescriptor; 3]) -> Result { let mut bytes = 0usize; for (role, key) in keys.iter().enumerate() { let (rows, columns) = if role == 2 { (2560, 640) } else { (640, 2560) }; - if key.layer != layer || key.expert != Some(expert) || key.role as usize != role - || (key.rows, key.columns) != (rows, columns) || key.bytes == 0 + if key.layer != layer + || key.expert != Some(expert) + || key.role as usize != role + || (key.rows, key.columns) != (rows, columns) + || key.bytes == 0 || key.bytes % 256 != 0 - || if role == 2 { !matches!(key.raw_kind, 20 | 42) } - else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) } + || if role == 2 { !matches!(key.raw_kind, 20 | 42) } else { !matches!(key.raw_kind, 18 | 21 | 22 | 23) } { return Err(Error::InvalidDimension); } @@ -65,10 +67,14 @@ impl AdaptivePolicy { let mut slots = reserve(plan.prefix)?; for &(layer, expert) in &profile.ordered_pairs()[..plan.prefix] { let mut keys = template[usize::from(layer)]; - for key in &mut keys { key.expert = Some(u32::from(expert)); } + for key in &mut keys { + key.expert = Some(u32::from(expert)); + } let bytes = blob_bytes(&keys)?; let index = cell(u32::from(layer), u32::from(expert))?; - if resident[index] != -1 { return Err(Error::IdentityMismatch); } + if resident[index] != -1 { + return Err(Error::IdentityMismatch); + } resident[index] = i32::try_from(slots.len()).map_err(|_| Error::Overflow)?; slots.push(Slot { keys, bytes }); } @@ -76,43 +82,76 @@ impl AdaptivePolicy { let victims = reserve(EXPERTS)?; let ranked = reserve(CELLS)?; let pending = reserve(ADAPT_SWAPS)?; - let mut owner = Self { usage, resident, slots, candidates, victims, ranked, pending, - rounds: 0, template, charged_bytes: plan.charged_bytes, metadata_bytes: 0 }; + let mut owner = Self { + usage, + resident, + slots, + candidates, + victims, + ranked, + pending, + rounds: 0, + template, + charged_bytes: plan.charged_bytes, + metadata_bytes: 0, + }; let mut metadata = std::mem::size_of::(); - for bytes in [owner.usage.capacity() * std::mem::size_of::(), + for bytes in [ + owner.usage.capacity() * std::mem::size_of::(), owner.resident.capacity() * std::mem::size_of::(), owner.slots.capacity() * std::mem::size_of::(), owner.candidates.capacity() * std::mem::size_of::<(f32, u32)>(), owner.victims.capacity() * std::mem::size_of::<(f32, u32)>(), owner.ranked.capacity() * std::mem::size_of::(), - owner.pending.capacity() * std::mem::size_of::()] { + owner.pending.capacity() * std::mem::size_of::(), + ] { metadata = metadata.checked_add(bytes).ok_or(Error::Overflow)?; } - if metadata > HOST_CAP { return Err(Error::InputAllocation); } + if metadata > HOST_CAP { + return Err(Error::InputAllocation); + } owner.metadata_bytes = metadata; Ok(owner) } - pub(in super::super) fn metadata_bytes(&self) -> usize { self.metadata_bytes } - pub(in super::super) fn charged_bytes(&self) -> usize { self.charged_bytes } - pub(in super::super) fn initial_slots(&self) -> &[Slot] { &self.slots } + pub(in super::super) fn metadata_bytes(&self) -> usize { + self.metadata_bytes + } + pub(in super::super) fn charged_bytes(&self) -> usize { + self.charged_bytes + } + pub(in super::super) fn initial_slots(&self) -> &[Slot] { + &self.slots + } pub(in super::super) fn resident_slot(&self, layer: u32, expert: u32) -> Result> { let slot = self.resident[cell(layer, expert)?]; - if slot < 0 { return Ok(None); } + if slot < 0 { + return Ok(None); + } let slot = slot as usize; let key = self.slots.get(slot).ok_or(Error::IdentityMismatch)?.keys[0]; - if key.layer != layer || key.expert != Some(expert) { return Err(Error::IdentityMismatch); } + if key.layer != layer || key.expert != Some(expert) { + return Err(Error::IdentityMismatch); + } Ok(Some(slot)) } /// Exactly one increment per actual routed occurrence, including repeated /// expert IDs on different rows. No matrix-hit/miss or accepted-only proxy. pub(in super::super) fn observe(&mut self, layer: u32, experts: &[u32]) -> Result<()> { - if experts.is_empty() || experts.len() > 640 { return Err(Error::InvalidDimension); } - for &expert in experts { cell(layer, expert)?; } + if experts.is_empty() || experts.len() > 640 { + return Err(Error::InvalidDimension); + } + for &expert in experts { + cell(layer, expert)?; + } // Admission is atomic even near the floating-point domain boundary. for &expert in experts { - if !(self.usage[cell(layer, expert)?] + experts.len() as f32).is_finite() { return Err(Error::NonFinite); } + if !(self.usage[cell(layer, expert)?] + experts.len() as f32).is_finite() { + return Err(Error::NonFinite); + } + } + for &expert in experts { + self.usage[cell(layer, expert)?] += 1.0; } - for &expert in experts { self.usage[cell(layer, expert)?] += 1.0; } Ok(()) } /// Called only after the actual verifier completed, before commit/draft, @@ -125,23 +164,39 @@ impl AdaptivePolicy { return Ok(&self.ranked); } for layer in 0..LAYERS { - self.candidates.clear(); self.victims.clear(); + self.candidates.clear(); + self.victims.clear(); for expert in 0..EXPERTS { let index = layer * EXPERTS + expert; let value = self.usage[index]; - if !value.is_finite() { return Err(Error::NonFinite); } + if !value.is_finite() { + return Err(Error::NonFinite); + } if self.resident[index] < 0 { - if value >= 2.0 { self.candidates.push((value, expert as u32)); } - } else { self.victims.push((value, expert as u32)); } + if value >= 2.0 { + self.candidates.push((value, expert as u32)); + } + } else { + self.victims.push((value, expert as u32)); + } } self.candidates.sort_unstable_by(|a, b| b.0.total_cmp(&a.0)); self.victims.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); for (&candidate, &victim) in self.candidates.iter().zip(&self.victims) { - if candidate.0 < victim.0 + 1.5 { break; } + if candidate.0 < victim.0 + 1.5 { + break; + } let slot = self.resident[layer * EXPERTS + victim.1 as usize]; - if slot < 0 { return Err(Error::IdentityMismatch); } - self.ranked.push(Swap { gain: candidate.0 - victim.0, layer: layer as u32, - incoming: candidate.1, outgoing: victim.1, slot: slot as usize }); + if slot < 0 { + return Err(Error::IdentityMismatch); + } + self.ranked.push(Swap { + gain: candidate.0 - victim.0, + layer: layer as u32, + incoming: candidate.1, + outgoing: victim.1, + slot: slot as usize, + }); } } self.ranked.sort_unstable_by(|a, b| b.gain.total_cmp(&a.gain)); @@ -151,28 +206,41 @@ impl AdaptivePolicy { pub(in super::super) fn incoming_keys(&self, swap: Swap) -> Result<[MoeWeightDescriptor; 3]> { self.validate_swap(swap)?; let mut keys = self.template[swap.layer as usize]; - for key in &mut keys { key.expert = Some(swap.incoming); } - if blob_bytes(&keys)? != self.slots[swap.slot].bytes { return Err(Error::IdentityMismatch); } + for key in &mut keys { + key.expert = Some(swap.incoming); + } + if blob_bytes(&keys)? != self.slots[swap.slot].bytes { + return Err(Error::IdentityMismatch); + } Ok(keys) } pub(super) fn validate_swap(&self, swap: Swap) -> Result<()> { - if !swap.gain.is_finite() || swap.gain < 1.5 || swap.incoming == swap.outgoing + if !swap.gain.is_finite() + || swap.gain < 1.5 + || swap.incoming == swap.outgoing || self.resident_slot(swap.layer, swap.outgoing)? != Some(swap.slot) || self.resident_slot(swap.layer, swap.incoming)?.is_some() || !self.ranked.contains(&swap) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } Ok(()) } /// PRIVATE adapter seam, only after the real driver took ownership of the /// entire selected slot batch. Incoming and outgoing both CPU until genuine /// event completion. Not exposed as an external launch/ready certificate. pub(in super::super) fn mark_enqueued(&mut self, swaps: &[Swap]) -> Result<()> { - if !self.pending.is_empty() || swaps.len() > ADAPT_SWAPS { return Err(Error::IdentityMismatch); } + if !self.pending.is_empty() || swaps.len() > ADAPT_SWAPS { + return Err(Error::IdentityMismatch); + } for (index, &swap) in swaps.iter().enumerate() { self.validate_swap(swap)?; - if swaps[..index].iter().any(|s| s.slot == swap.slot - || (s.layer == swap.layer && (s.incoming == swap.incoming || s.outgoing == swap.outgoing))) - { return Err(Error::IdentityMismatch); } + if swaps[..index].iter().any(|s| { + s.slot == swap.slot + || (s.layer == swap.layer && (s.incoming == swap.incoming || s.outgoing == swap.outgoing)) + }) { + return Err(Error::IdentityMismatch); + } } for &swap in swaps { self.resident[cell(swap.layer, swap.outgoing)?] = -1; @@ -180,7 +248,9 @@ impl AdaptivePolicy { } // Source decays on a due scheduling round, including zero swaps. It // does not decay while the previous pending batch is still in flight. - for value in &mut self.usage { *value *= 0.7; } + for value in &mut self.usage { + *value *= 0.7; + } Ok(()) } /// Must be invoked ONLY by the owning adapter after consuming the opaque @@ -190,9 +260,13 @@ impl AdaptivePolicy { if self.resident[cell(swap.layer, swap.incoming)?] != -1 || self.resident[cell(swap.layer, swap.outgoing)?] != -1 || self.slots[swap.slot].keys[0].expert != Some(swap.outgoing) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let mut keys = self.template[swap.layer as usize]; - for key in &mut keys { key.expert = Some(swap.incoming); } + for key in &mut keys { + key.expert = Some(swap.incoming); + } self.slots[swap.slot].keys = keys; self.resident[cell(swap.layer, swap.incoming)?] = swap.slot as i32; self.pending.remove(index); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/transfer_metadata_bound_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/transfer_metadata_bound_fn.rs index 3252b698..3bae9aab 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/transfer_metadata_bound_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive/transfer_metadata_bound_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn transfer_metadata_bound() -> usize { ADAPT_SWAPS * std::mem::size_of::>() } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive_sdet.rs index 40c5fb88..2ae9cbcb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cache_strata_adaptive_sdet.rs @@ -6,23 +6,31 @@ use sha2::{Digest, Sha256}; fn fixture() -> (RankedProfile, [[MoeWeightDescriptor; 3]; LAYERS]) { let mut bytes = Vec::new(); bytes.extend_from_slice(b"STRP"); - for n in [1u32, 48, 512, 24_576, 24_576] { bytes.extend_from_slice(&n.to_le_bytes()); } + for n in [1u32, 48, 512, 24_576, 24_576] { + bytes.extend_from_slice(&n.to_le_bytes()); + } // Sanitized whole-domain profile; every layer receives the same initial // first two slots under the deliberately tiny metadata test capacity. for expert in 0..EXPERTS as u16 { for layer in 0..LAYERS as u16 { - bytes.extend_from_slice(&layer.to_le_bytes()); bytes.extend_from_slice(&expert.to_le_bytes()); + bytes.extend_from_slice(&layer.to_le_bytes()); + bytes.extend_from_slice(&expert.to_le_bytes()); } } let sha: [u8; 32] = Sha256::digest(&bytes).into(); let profile = RankedProfile::parse(&bytes, sha).unwrap(); - let template = std::array::from_fn(|layer| std::array::from_fn(|role| MoeWeightDescriptor { - layer: layer as u32, expert: Some(0), role: role as u8, - raw_kind: if role == 2 { 20 } else { 18 }, - rows: if role == 2 { 2560 } else { 640 }, columns: if role == 2 { 640 } else { 2560 }, - // These bytes are metadata coordinates only, NOT real format tensors. - bytes: 256, - })); + let template = std::array::from_fn(|layer| { + std::array::from_fn(|role| MoeWeightDescriptor { + layer: layer as u32, + expert: Some(0), + role: role as u8, + raw_kind: if role == 2 { 20 } else { 18 }, + rows: if role == 2 { 2560 } else { 640 }, + columns: if role == 2 { 640 } else { 2560 }, + // These bytes are metadata coordinates only, NOT real format tensors. + bytes: 256, + }) + }); (profile, template) } /// Literal independent old-source algorithm FIRST, using separate host tables. @@ -31,34 +39,50 @@ fn fixture() -> (RankedProfile, [[MoeWeightDescriptor; 3]; LAYERS]) { fn original(usage: &[f32], resident: &[i32]) -> Vec { let mut swaps = Vec::new(); for layer in 0..LAYERS { - let mut cand = Vec::new(); let mut vict = Vec::new(); + let mut cand = Vec::new(); + let mut vict = Vec::new(); for expert in 0..EXPERTS { let value = usage[layer * EXPERTS + expert]; if resident[layer * EXPERTS + expert] < 0 { - if value >= 2.0 { cand.push((value, expert as u32)); } - } else { vict.push((value, expert as u32)); } + if value >= 2.0 { + cand.push((value, expert as u32)); + } + } else { + vict.push((value, expert as u32)); + } } cand.sort_unstable_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); vict.sort_unstable_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); for i in 0..cand.len().min(vict.len()) { - if cand[i].0 < vict[i].0 + 1.5 { break; } - swaps.push(Swap { gain: cand[i].0 - vict[i].0, layer: layer as u32, - incoming: cand[i].1, outgoing: vict[i].1, - slot: resident[layer * EXPERTS + vict[i].1 as usize] as usize }); + if cand[i].0 < vict[i].0 + 1.5 { + break; + } + swaps.push(Swap { + gain: cand[i].0 - vict[i].0, + layer: layer as u32, + incoming: cand[i].1, + outgoing: vict[i].1, + slot: resident[layer * EXPERTS + vict[i].1 as usize] as usize, + }); } } swaps.sort_unstable_by(|a, b| b.gain.partial_cmp(&a.gain).unwrap()); - swaps.truncate(96); swaps + swaps.truncate(96); + swaps } #[test] fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer_slots() { let (profile, template) = fixture(); let slots = 2 * LAYERS; let capacity = slots * 768; - let limits = ProfileLimits { main_cap: capacity + 768, allocated: 0, + let limits = ProfileLimits { + main_cap: capacity + 768, + allocated: 0, device_budget: capacity + 768 + 128 * 1024 * 1024, physical_free: capacity + 768 + 128 * 1024 * 1024, - working_reserve: 128 * 1024 * 1024, window_spill: 0 }; + working_reserve: 128 * 1024 * 1024, + window_spill: 0, + }; let mut owner = AdaptivePolicy::new(&profile, template, limits).unwrap(); assert_eq!(owner.initial_slots().len(), slots); assert_eq!(owner.charged_bytes(), capacity); @@ -71,25 +95,33 @@ fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer owner.observe(layer as u32, &vec![3; 10 + layer]).unwrap(); owner.observe(layer as u32, &[4]).unwrap(); // floor2 refuses singleton } - let old_usage = owner.usage.clone(); let old_resident = owner.resident.clone(); + let old_usage = owner.usage.clone(); + let old_resident = owner.resident.clone(); let expected = original(&old_usage, &old_resident); assert_eq!(expected.len(), 96); - for _ in 0..3 { assert!(owner.completed_window().unwrap().is_empty()); } + for _ in 0..3 { + assert!(owner.completed_window().unwrap().is_empty()); + } let got = owner.completed_window().unwrap().to_vec(); assert_eq!(got, expected); // Pure metadata transition, explicitly not a real event/driver proof. owner.mark_enqueued(&got).unwrap(); - for (now, old) in owner.usage.iter().zip(&old_usage) { assert_eq!(now.to_bits(), (old * 0.7).to_bits()); } + for (now, old) in owner.usage.iter().zip(&old_usage) { + assert_eq!(now.to_bits(), (old * 0.7).to_bits()); + } for swap in &got { assert_eq!(owner.resident_slot(swap.layer, swap.outgoing).unwrap(), None); assert_eq!(owner.resident_slot(swap.layer, swap.incoming).unwrap(), None); assert_eq!(owner.incoming_keys_for_test(*swap)[0].layer, swap.layer); } let decayed = owner.usage.clone(); - for _ in 0..4 { assert!(owner.completed_window().unwrap().is_empty()); } + for _ in 0..4 { + assert!(owner.completed_window().unwrap().is_empty()); + } assert_eq!(owner.usage, decayed); // pending skips decay as original does while !owner.pending.is_empty() { - let swap = owner.pending[0]; owner.publish_completed(0).unwrap(); + let swap = owner.pending[0]; + owner.publish_completed(0).unwrap(); assert_eq!(owner.resident_slot(swap.layer, swap.incoming).unwrap(), Some(swap.slot)); assert_eq!(owner.slots[swap.slot].keys[0].expert, Some(swap.incoming)); } @@ -101,19 +133,27 @@ fn original_policy_first_actual_frequency_threshold_pending_decay_and_same_layer assert_eq!(owner.completed_window().unwrap_err(), Error::Overflow); // Exact candidate floor and threshold equality source comparisons FIRST. let mut singleton = AdaptivePolicy::new(&profile, template, limits).unwrap(); - singleton.usage[0] = 0.5; singleton.usage[1] = 0.75; - singleton.usage[2] = 2.0; singleton.usage[3] = 1.999; + singleton.usage[0] = 0.5; + singleton.usage[1] = 0.75; + singleton.usage[2] = 2.0; + singleton.usage[3] = 1.999; let expected = original(&singleton.usage, &singleton.resident); assert_eq!(expected.len(), 1); - for _ in 0..3 { singleton.completed_window().unwrap(); } + for _ in 0..3 { + singleton.completed_window().unwrap(); + } assert_eq!(singleton.completed_window().unwrap(), expected); // Zero-swap due rounds still decay, while non-due rounds do not. - singleton.ranked.clear(); singleton.mark_enqueued(&[]).unwrap(); + singleton.ranked.clear(); + singleton.mark_enqueued(&[]).unwrap(); assert_eq!(singleton.usage[2].to_bits(), (2.0f32 * 0.7).to_bits()); } impl AdaptivePolicy { fn incoming_keys_for_test(&self, swap: Swap) -> [MoeWeightDescriptor; 3] { let mut keys = self.template[swap.layer as usize]; - for key in &mut keys { key.expert = Some(swap.incoming); } keys + for key in &mut keys { + key.expert = Some(swap.incoming); + } + keys } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/chunk_modules.rs b/crates/engine-qwen35-cuda/src/qwen_forward/chunk_modules.rs index d94afef4..f0dd9a09 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/chunk_modules.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/chunk_modules.rs @@ -51,10 +51,7 @@ impl<'ctx> ChunkModules<'ctx> { context: &Context<'_>, ) -> Result>> { self.check(context)?; - let mut slot = self - .q6 - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut slot = self.q6.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; if slot.is_none() { match leleka_cuda_driver::q6_layer_preview::Batch::new(self.context) { Ok(module) => *slot = Some(module), @@ -75,15 +72,9 @@ impl<'ctx> ChunkModules<'ctx> { RefMut::filter_map(slot, Option::as_mut).map_err(|_| Error::IdentityMismatch) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn gr( - &self, - context: &Context<'_>, - ) -> Result>> { + pub(super) fn gr(&self, context: &Context<'_>) -> Result>> { self.check(context)?; - let mut slot = self - .gr - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut slot = self.gr.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; if slot.is_none() { match leleka_cuda_driver::GrBatchModule::new(self.context) { Ok(module) => *slot = Some(module), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs index 544c19f2..60a9c40c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/contract.rs @@ -148,10 +148,7 @@ impl Position { } pub(crate) fn from_signed(value: i64, bound: Dimension) -> Result { - Self::new( - u64::try_from(value).map_err(|_| Error::InvalidPosition)?, - bound, - ) + Self::new(u64::try_from(value).map_err(|_| Error::InvalidPosition)?, bound) } pub(crate) fn get(self) -> u64 { @@ -186,9 +183,7 @@ impl Extent { } pub(crate) fn bytes(self, element_bytes: Dimension) -> Result { - self.0 - .checked_mul(usize::try_from(element_bytes.get()).map_err(|_| Error::Overflow)?) - .ok_or(Error::Overflow) + self.0.checked_mul(usize::try_from(element_bytes.get()).map_err(|_| Error::Overflow)?).ok_or(Error::Overflow) } } @@ -217,11 +212,7 @@ pub(crate) struct TokenLayer { impl TokenLayer { pub(crate) fn new(token: TokenId, position: Position, layer: LayerId) -> Self { - Self { - token, - position, - layer, - } + Self { token, position, layer } } pub(crate) fn token(self) -> TokenId { @@ -259,10 +250,7 @@ mod tests { assert_eq!(Dimension::new(value), Err(Error::InvalidDimension)); } assert_eq!(Dimension::from_signed(-1), Err(Error::InvalidDimension)); - assert_eq!( - Dimension::from_signed(i64::MIN), - Err(Error::InvalidDimension) - ); + assert_eq!(Dimension::from_signed(i64::MIN), Err(Error::InvalidDimension)); } #[test] @@ -294,10 +282,7 @@ mod tests { for value in [i32::MAX as u64, u64::MAX] { assert_eq!(Position::new(value, bound), Err(Error::InvalidPosition)); } - assert_eq!( - Position::from_signed(-1, bound), - Err(Error::InvalidPosition) - ); + assert_eq!(Position::from_signed(-1, bound), Err(Error::InvalidPosition)); } #[test] @@ -307,10 +292,7 @@ mod tests { assert_eq!(shape.elements(), 30); assert_eq!(shape.bytes(d(4)), Ok(120)); assert_eq!(Extent::product(&[]), Err(Error::InvalidDimension)); - assert_eq!( - Extent::product(&[d(i32::MAX as u64); 3]), - Err(Error::Overflow) - ); + assert_eq!(Extent::product(&[d(i32::MAX as u64); 3]), Err(Error::Overflow)); let large = Extent::product(&[d(i32::MAX as u64); 2]); if usize::BITS == 64 { assert_eq!(large.unwrap().bytes(d(16)), Err(Error::Overflow)); @@ -321,26 +303,10 @@ mod tests { #[test] fn finite_values_preserve_bits_and_refuse_nan_and_infinity() { - for value in [ - 0.0_f32, - -0.0, - 1.0, - -1.0, - f32::MAX, - f32::MIN, - f32::MIN_POSITIVE, - ] { - assert_eq!( - FiniteF32::new(value).unwrap().get().to_bits(), - value.to_bits() - ); + for value in [0.0_f32, -0.0, 1.0, -1.0, f32::MAX, f32::MIN, f32::MIN_POSITIVE] { + assert_eq!(FiniteF32::new(value).unwrap().get().to_bits(), value.to_bits()); } - for value in [ - f32::NAN, - f32::from_bits(0x7f80_0001), - f32::INFINITY, - f32::NEG_INFINITY, - ] { + for value in [f32::NAN, f32::from_bits(0x7f80_0001), f32::INFINITY, f32::NEG_INFINITY] { assert_eq!(FiniteF32::new(value), Err(Error::NonFinite)); } } @@ -355,46 +321,24 @@ mod tests { assert_eq!(identity.token(), token); assert_eq!(identity.layer(), layer); assert_eq!(identity.position(), position); - assert_eq!( - identity.validate(token, Position::new(1, bound).unwrap(), layer), - Err(Error::IdentityMismatch) - ); + assert_eq!(identity.validate(token, Position::new(1, bound).unwrap(), layer), Err(Error::IdentityMismatch)); assert_eq!(identity.validate(token, position, layer), Ok(())); + assert_eq!(identity.validate(TokenId::new(1, bound).unwrap(), position, layer), Err(Error::IdentityMismatch)); + assert_eq!(identity.validate(token, position, LayerId::new(1, bound).unwrap()), Err(Error::IdentityMismatch)); assert_eq!( - identity.validate(TokenId::new(1, bound).unwrap(), position, layer), - Err(Error::IdentityMismatch) - ); - assert_eq!( - identity.validate(token, position, LayerId::new(1, bound).unwrap()), - Err(Error::IdentityMismatch) - ); - assert_eq!( - identity.validate( - TokenId::new(0, Dimension::new(5).unwrap()).unwrap(), - position, - layer - ), + identity.validate(TokenId::new(0, Dimension::new(5).unwrap()).unwrap(), position, layer), Err(Error::IdentityMismatch) ); } #[test] fn model_binding_shell_refuses_without_loading_or_returning_a_model() { - assert!(matches!( - ModelBinding::bind(), - Err(BindingError::Unsupported) - )); - assert_eq!( - Error::from(BindingError::Unsupported), - Error::Unsupported(Stage::Binding) - ); + assert!(matches!(ModelBinding::bind(), Err(BindingError::Unsupported))); + assert_eq!(Error::from(BindingError::Unsupported), Error::Unsupported(Stage::Binding)); } #[test] fn session_shell_cannot_create_committed_or_pending_state() { - assert!(matches!( - super::super::session::QwenSession::new(), - Err(Error::Unsupported(Stage::Session)) - )); + assert!(matches!(super::super::session::QwenSession::new(), Err(Error::Unsupported(Stage::Session)))); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/cpu_expert_miss.rs b/crates/engine-qwen35-cuda/src/qwen_forward/cpu_expert_miss.rs index c97e71af..91a48d52 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/cpu_expert_miss.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/cpu_expert_miss.rs @@ -1,134 +1,236 @@ //! Safe actor-side source association; native ownership lives in the leaf crate. //! Returned bytes are NOT source/current-row/Context/publication certificates. -use leleka_native_cpu_expert::{CpuPool, PreparedJob, PendingBatch, GateUpFormat, DownFormat}; use crate::model_binding::qwen4exp_input::{ BindingIdentity, InputBindingError, ModelBinding, MoeMatrixRole, MoeRoutedSourceScope, MoeWeightDescriptor, }; -const H:usize=2560; -const FF:usize=640; -#[derive(Clone,Copy,Debug,Eq,PartialEq)] +use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PendingBatch, PreparedJob}; +const H: usize = 2560; +const FF: usize = 640; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum CpuMissError { - Source(InputBindingError), Identity, Shape, Unsupported, Allocation, NonFinite, NativeFailure, + Source(InputBindingError), + Identity, + Shape, + Unsupported, + Allocation, + NonFinite, + NativeFailure, +} +type Result = std::result::Result; +pub(crate) struct CpuMissWorkspace { + binding: BindingIdentity, + pool: CpuPool, } -type Result = std::result::Result; -pub(crate) struct CpuMissWorkspace { binding:BindingIdentity, pool:CpuPool } pub(crate) struct PreparedCpuMiss { - binding:BindingIdentity, descriptors:[MoeWeightDescriptor;3], job:PreparedJob, + binding: BindingIdentity, + descriptors: [MoeWeightDescriptor; 3], + job: PreparedJob, } impl PreparedCpuMiss { - pub(crate) fn owned_bytes(&self)->Result { - self.job.owned_bytes().map_err(native_error)?.checked_add(std::mem::size_of::()) + pub(crate) fn owned_bytes(&self) -> Result { + self.job + .owned_bytes() + .map_err(native_error)? + .checked_add(std::mem::size_of::()) .ok_or(CpuMissError::Allocation) } } pub(crate) struct CpuMissRows { - binding:BindingIdentity, descriptors:[MoeWeightDescriptor;3], values:Box<[f32]>, + binding: BindingIdentity, + descriptors: [MoeWeightDescriptor; 3], + values: Box<[f32]>, } impl CpuMissRows { - pub(crate) fn matches(&self,binding:&ModelBinding,keys:&[MoeWeightDescriptor;3])->bool { - self.binding.matches(&binding.identity()) && self.descriptors==*keys + pub(crate) fn matches(&self, binding: &ModelBinding, keys: &[MoeWeightDescriptor; 3]) -> bool { + self.binding.matches(&binding.identity()) && self.descriptors == *keys + } + pub(crate) fn values(&self) -> &[f32] { + &self.values + } + pub(crate) fn into_values(self) -> Box<[f32]> { + self.values } - pub(crate) fn values(&self)->&[f32] { &self.values } - pub(crate) fn into_values(self)->Box<[f32]> { self.values } } impl CpuMissWorkspace { - pub(crate) fn new(binding:&ModelBinding,workers:i32)->Result { - Ok(Self { binding:binding.identity(),pool:CpuPool::new(workers).map_err(native_error)? }) + pub(crate) fn new(binding: &ModelBinding, workers: i32) -> Result { + Ok(Self { binding: binding.identity(), pool: CpuPool::new(workers).map_err(native_error)? }) + } + pub(crate) fn workers(&self) -> usize { + self.pool.workers() } - pub(crate) fn workers(&self)->usize { self.pool.workers() } /// Copies only actual source-scoped bytes. Caller explicitly finishes this /// scope BEFORE starting GPU callbacks; it cannot send a source/Binding loan. - pub(crate) fn prepare_scoped(&self,binding:&ModelBinding,source:&mut MoeRoutedSourceScope<'_,'_>, - member:usize,activations:&[&[f32]])->Result { - if !self.binding.matches(&binding.identity()) { return Err(CpuMissError::Identity); } - source.validate_binding(binding).map_err(CpuMissError::Source)?; - if !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&activations.len()) { return Err(CpuMissError::Shape); } - for input in activations { - if input.len()!=H { return Err(CpuMissError::Shape); } - if input.iter().any(|x| !x.is_finite()) { return Err(CpuMissError::NonFinite); } + pub(crate) fn prepare_scoped( + &self, + binding: &ModelBinding, + source: &mut MoeRoutedSourceScope<'_, '_>, + member: usize, + activations: &[&[f32]], + ) -> Result { + if !self.binding.matches(&binding.identity()) { + return Err(CpuMissError::Identity); } - let gate=source.descriptor(member,MoeMatrixRole::Gate).map_err(CpuMissError::Source)?; - let up=source.descriptor(member,MoeMatrixRole::Up).map_err(CpuMissError::Source)?; - let down=source.descriptor(member,MoeMatrixRole::Down).map_err(CpuMissError::Source)?; - let (gu,dt)=validate_triplet([gate,up,down])?; - let gate_bytes=source.block(member,MoeMatrixRole::Gate).map_err(CpuMissError::Source)?.into_bytes(); - let up_bytes=source.block(member,MoeMatrixRole::Up).map_err(CpuMissError::Source)?.into_bytes(); - let down_bytes=source.block(member,MoeMatrixRole::Down).map_err(CpuMissError::Source)?.into_bytes(); - if [gate_bytes.len(),up_bytes.len(),down_bytes.len()]!=[gate.bytes,up.bytes,down.bytes] { return Err(CpuMissError::Shape); } - let mut input=Vec::new(); - input.try_reserve_exact(activations.len()*H).map_err(|_|CpuMissError::Allocation)?; - for row in activations { input.extend_from_slice(row); } - let job=PreparedJob::new(gu,dt,gate_bytes,up_bytes,down_bytes,input.into_boxed_slice(),activations.len()) - .map_err(native_error)?; source.validate_binding(binding).map_err(CpuMissError::Source)?; - Ok(PreparedCpuMiss { binding:binding.identity(),descriptors:[gate,up,down],job }) + if !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&activations.len()) { + return Err(CpuMissError::Shape); + } + for input in activations { + if input.len() != H { + return Err(CpuMissError::Shape); + } + if input.iter().any(|x| !x.is_finite()) { + return Err(CpuMissError::NonFinite); + } + } + let gate = source.descriptor(member, MoeMatrixRole::Gate).map_err(CpuMissError::Source)?; + let up = source.descriptor(member, MoeMatrixRole::Up).map_err(CpuMissError::Source)?; + let down = source.descriptor(member, MoeMatrixRole::Down).map_err(CpuMissError::Source)?; + let (gu, dt) = validate_triplet([gate, up, down])?; + let gate_bytes = source.block(member, MoeMatrixRole::Gate).map_err(CpuMissError::Source)?.into_bytes(); + let up_bytes = source.block(member, MoeMatrixRole::Up).map_err(CpuMissError::Source)?.into_bytes(); + let down_bytes = source.block(member, MoeMatrixRole::Down).map_err(CpuMissError::Source)?.into_bytes(); + if [gate_bytes.len(), up_bytes.len(), down_bytes.len()] != [gate.bytes, up.bytes, down.bytes] { + return Err(CpuMissError::Shape); + } + let mut input = Vec::new(); + input.try_reserve_exact(activations.len() * H).map_err(|_| CpuMissError::Allocation)?; + for row in activations { + input.extend_from_slice(row); + } + let job = + PreparedJob::new(gu, dt, gate_bytes, up_bytes, down_bytes, input.into_boxed_slice(), activations.len()) + .map_err(native_error)?; + source.validate_binding(binding).map_err(CpuMissError::Source)?; + Ok(PreparedCpuMiss { binding: binding.identity(), descriptors: [gate, up, down], job }) } /// Single bounded batch; actor metadata never crosses the coordinator thread. /// Root must include all preparation peak/live owners in its host admission. - pub(crate) fn start(&mut self,jobs:Vec,allowance:usize)->Result> { - let count=jobs.len(); - if !(1..=leleka_native_cpu_expert::MAX_JOBS).contains(&count) || jobs.capacity()>leleka_native_cpu_expert::MAX_JOBS { + pub(crate) fn start(&mut self, jobs: Vec, allowance: usize) -> Result> { + let count = jobs.len(); + if !(1..=leleka_native_cpu_expert::MAX_JOBS).contains(&count) + || jobs.capacity() > leleka_native_cpu_expert::MAX_JOBS + { return Err(CpuMissError::Shape); } - let first=jobs[0].descriptors; - for (i,job) in jobs.iter().enumerate() { - if !job.binding.matches(&self.binding) { return Err(CpuMissError::Identity); } - if job.descriptors[0].layer!=first[0].layer || job.descriptors[0].raw_kind!=first[0].raw_kind || - job.descriptors[2].raw_kind!=first[2].raw_kind || - jobs[..i].iter().any(|old|old.descriptors[0].expert==job.descriptors[0].expert) { return Err(CpuMissError::Shape); } + let first = jobs[0].descriptors; + for (i, job) in jobs.iter().enumerate() { + if !job.binding.matches(&self.binding) { + return Err(CpuMissError::Identity); + } + if job.descriptors[0].layer != first[0].layer + || job.descriptors[0].raw_kind != first[0].raw_kind + || job.descriptors[2].raw_kind != first[2].raw_kind + || jobs[..i].iter().any(|old| old.descriptors[0].expert == job.descriptors[0].expert) + { + return Err(CpuMissError::Shape); + } } - if allowance>leleka_native_cpu_expert::MAX_BATCH_BYTES { return Err(CpuMissError::Allocation); } - let mut descriptors=Vec::new(); descriptors.try_reserve_exact(count).map_err(|_|CpuMissError::Allocation)?; - let mut native=Vec::new(); native.try_reserve_exact(count).map_err(|_|CpuMissError::Allocation)?; - let mut results=Vec::new(); results.try_reserve_exact(count).map_err(|_|CpuMissError::Allocation)?; - let metadata=jobs.capacity().checked_mul(std::mem::size_of::()) - .and_then(|n| descriptors.capacity().checked_mul(std::mem::size_of::<[MoeWeightDescriptor;3]>()).and_then(|m|n.checked_add(m))) - .and_then(|n| results.capacity().checked_mul(std::mem::size_of::()).and_then(|m|n.checked_add(m))) + if allowance > leleka_native_cpu_expert::MAX_BATCH_BYTES { + return Err(CpuMissError::Allocation); + } + let mut descriptors = Vec::new(); + descriptors.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?; + let mut native = Vec::new(); + native.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?; + let mut results = Vec::new(); + results.try_reserve_exact(count).map_err(|_| CpuMissError::Allocation)?; + let metadata = jobs + .capacity() + .checked_mul(std::mem::size_of::()) + .and_then(|n| { + descriptors + .capacity() + .checked_mul(std::mem::size_of::<[MoeWeightDescriptor; 3]>()) + .and_then(|m| n.checked_add(m)) + }) + .and_then(|n| { + results.capacity().checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m)) + }) .ok_or(CpuMissError::Allocation)?; - let remaining=allowance.checked_sub(metadata).ok_or(CpuMissError::Allocation)?; - for job in jobs { descriptors.push(job.descriptors); native.push(job.job); } - let pending=self.pool.start(native,remaining).map_err(native_error)?; - Ok(PendingCpuMissBatch { native:pending,binding:self.binding.clone(),descriptors,results }) + let remaining = allowance.checked_sub(metadata).ok_or(CpuMissError::Allocation)?; + for job in jobs { + descriptors.push(job.descriptors); + native.push(job.job); + } + let pending = self.pool.start(native, remaining).map_err(native_error)?; + Ok(PendingCpuMissBatch { native: pending, binding: self.binding.clone(), descriptors, results }) } } pub(crate) struct PendingCpuMissBatch<'pool> { - native:PendingBatch<'pool>, binding:BindingIdentity, descriptors:Vec<[MoeWeightDescriptor;3]>,results:Vec, + native: PendingBatch<'pool>, + binding: BindingIdentity, + descriptors: Vec<[MoeWeightDescriptor; 3]>, + results: Vec, } impl PendingCpuMissBatch<'_> { /// Waits for genuine completion even on cancellation/error/unwind. Before /// any packet admission caller reopens the real source, compares ALL actual /// descriptors via matches, finishes, and rechecks current row/Context/epoch. - pub(crate) fn join(mut self)->Result> { - let rows=self.native.join().map_err(native_error)?; - if rows.len()!=self.descriptors.len() { return Err(CpuMissError::NativeFailure); } - for (row,descriptors) in rows.into_iter().zip(self.descriptors) { - let values=row.into_values(); - if values.len()%H!=0 || !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&(values.len()/H)) { + pub(crate) fn join(mut self) -> Result> { + let rows = self.native.join().map_err(native_error)?; + if rows.len() != self.descriptors.len() { + return Err(CpuMissError::NativeFailure); + } + for (row, descriptors) in rows.into_iter().zip(self.descriptors) { + let values = row.into_values(); + if values.len() % H != 0 || !(1..=leleka_native_cpu_expert::MAX_ROWS).contains(&(values.len() / H)) { return Err(CpuMissError::Shape); } - if values.iter().any(|x| !x.is_finite()) { return Err(CpuMissError::NonFinite); } - self.results.push(CpuMissRows { binding:self.binding.clone(),descriptors,values }); + if values.iter().any(|x| !x.is_finite()) { + return Err(CpuMissError::NonFinite); + } + self.results.push(CpuMissRows { binding: self.binding.clone(), descriptors, values }); } Ok(self.results) } } -fn native_error(error:leleka_native_cpu_expert::Error)->CpuMissError { +fn native_error(error: leleka_native_cpu_expert::Error) -> CpuMissError { use leleka_native_cpu_expert::Error as E; - match error { E::Shape=>CpuMissError::Shape,E::Unsupported=>CpuMissError::Unsupported, - E::Allocation|E::BudgetExceeded=>CpuMissError::Allocation,E::NonFinite=>CpuMissError::NonFinite, - E::NativeFailure|E::Closed=>CpuMissError::NativeFailure } + match error { + E::Shape => CpuMissError::Shape, + E::Unsupported => CpuMissError::Unsupported, + E::Allocation | E::BudgetExceeded => CpuMissError::Allocation, + E::NonFinite => CpuMissError::NonFinite, + E::NativeFailure | E::Closed => CpuMissError::NativeFailure, + } } -pub(crate) fn validate_triplet([gate,up,down]:[MoeWeightDescriptor;3])->Result<(GateUpFormat,DownFormat)> { - if gate.expert.is_none() || gate.expert!=up.expert || gate.expert!=down.expert || gate.layer!=up.layer || gate.layer!=down.layer || - gate.role!=0 || up.role!=1 || down.role!=2 || gate.columns!=H || up.columns!=H || gate.rows!=FF || up.rows!=FF || - down.columns!=FF || down.rows!=H || gate.raw_kind!=up.raw_kind || gate.bytes!=up.bytes { return Err(CpuMissError::Shape); } - let (gu,block,bytes)=match gate.raw_kind { - 18=>(GateUpFormat::Iq3Xxs,256,98),21=>(GateUpFormat::Iq3S,256,110),22=>(GateUpFormat::Iq2S,256,82), - 23=>(GateUpFormat::Iq4Xs,256,136),42=>(GateUpFormat::Q2_0,64,18),_=>return Err(CpuMissError::Unsupported), +pub(crate) fn validate_triplet([gate, up, down]: [MoeWeightDescriptor; 3]) -> Result<(GateUpFormat, DownFormat)> { + if gate.expert.is_none() + || gate.expert != up.expert + || gate.expert != down.expert + || gate.layer != up.layer + || gate.layer != down.layer + || gate.role != 0 + || up.role != 1 + || down.role != 2 + || gate.columns != H + || up.columns != H + || gate.rows != FF + || up.rows != FF + || down.columns != FF + || down.rows != H + || gate.raw_kind != up.raw_kind + || gate.bytes != up.bytes + { + return Err(CpuMissError::Shape); + } + let (gu, block, bytes) = match gate.raw_kind { + 18 => (GateUpFormat::Iq3Xxs, 256, 98), + 21 => (GateUpFormat::Iq3S, 256, 110), + 22 => (GateUpFormat::Iq2S, 256, 82), + 23 => (GateUpFormat::Iq4Xs, 256, 136), + 42 => (GateUpFormat::Q2_0, 64, 18), + _ => return Err(CpuMissError::Unsupported), }; - let (dt,dblock,dbytes)=match down.raw_kind { 20=>(DownFormat::Iq4Nl,32,18),42=>(DownFormat::Q2_0,64,18),_=>return Err(CpuMissError::Unsupported) }; - if gate.bytes!=H/block*bytes*FF || down.bytes!=FF/dblock*dbytes*H { return Err(CpuMissError::Shape); } - Ok((gu,dt)) + let (dt, dblock, dbytes) = match down.raw_kind { + 20 => (DownFormat::Iq4Nl, 32, 18), + 42 => (DownFormat::Q2_0, 64, 18), + _ => return Err(CpuMissError::Unsupported), + }; + if gate.bytes != H / block * bytes * FF || down.bytes != FF / dblock * dbytes * H { + return Err(CpuMissError::Shape); + } + Ok((gu, dt)) } pub(crate) fn runtime_error(error: CpuMissError) -> super::contract::Error { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs index 441e0c08..85d3b4ef 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache.rs @@ -9,19 +9,19 @@ use super::qsa_index::{QsaInputLease, QsaInputScratch}; use super::qsa_index::{binding_error, driver_error}; use super::router_scratch::{RouterLease, RouterScratch}; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, GrWeights, - ModelBinding, PleMatrixRole, PleWeights, QsaMatrixKind, QsaMatrixRole, QsaWeights, + BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, GrWeights, ModelBinding, + PleMatrixRole, PleWeights, QsaMatrixKind, QsaMatrixRole, QsaWeights, }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use leleka_cuda_driver::GrBatchInjectWorkspace; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use leleka_cuda_driver::OriginalVerifyGdnWeights; +use leleka_cuda_driver::{Context, DeviceBuffer, DeviceSlice, SlabAllocator, SlabPolicy}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use leleka_cuda_driver::{ - OriginalVerifyGdnProjections, OriginalVerifyGeometry, OriginalVerifyNativeMatrix, - OriginalVerifyProjBinding, OriginalVerifyQsaProjections, + OriginalVerifyGdnProjections, OriginalVerifyGeometry, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, + OriginalVerifyQsaProjections, }; -use leleka_cuda_driver::{Context, DeviceBuffer, DeviceSlice, SlabAllocator, SlabPolicy}; use std::{ cell::{Cell, RefCell, RefMut}, rc::Rc, @@ -118,8 +118,8 @@ pub(crate) struct DenseWeightCache<'ctx> { counters: Cell, } -mod impl_denseweightcache; mod dense_slab_policy_fn; +mod impl_denseweightcache; #[allow(unused_imports)] use dense_slab_policy_fn::dense_slab_policy; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/dense_slab_policy_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/dense_slab_policy_fn.rs index 642ed2ab..92298a7c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/dense_slab_policy_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/dense_slab_policy_fn.rs @@ -15,7 +15,10 @@ pub(super) fn dense_slab_policy() -> SlabPolicy { } /// Startup refusals collapse into one error class; name the step that refused on stderr. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(super) fn startup_step(step: &str, result: std::result::Result) -> std::result::Result { +pub(super) fn startup_step( + step: &str, + result: std::result::Result, +) -> std::result::Result { if let Err(error) = &result { eprintln!("DenseWeightCache::new_original_prompt_capacity: {step} refused: {error:?}"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs index 61b2e492..96c6541c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2.rs @@ -3,29 +3,18 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { pub(crate) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { Self::new_with_selected(binding, context, false) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(crate) fn new_qsa_selected(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { Self::new_with_selected(binding, context, true) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_qsa_selected_router( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(crate) fn new_qsa_selected_router(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { let mut result = Self::new_qsa_selected(binding, context)?; - match RouterScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - ) { + match RouterScratch::new(result.binding.clone(), context, result.mirror_failed.clone()) { Ok(slot) => result.router_scratch = Some(RefCell::new(slot)), Err(primary) => { let _ = result.close(); @@ -57,11 +46,7 @@ impl<'ctx> DenseWeightCache<'ctx> { context: &'ctx Context<'ctx>, ) -> Result { let mut result = Self::new_qsa_selected_router_gr_batch(binding, context)?; - match QkScratch::new( - result.binding.clone(), - context, - result.mirror_failed.clone(), - ) { + match QkScratch::new(result.binding.clone(), context, result.mirror_failed.clone()) { Ok(slot) => result.gdn_qk_workspace = Some(Rc::new(slot)), Err(primary) => { let _ = result.close(); @@ -76,18 +61,22 @@ impl<'ctx> DenseWeightCache<'ctx> { binding: &ModelBinding, context: &'ctx Context<'ctx>, ) -> Result { - Self::new_attention_capacity(binding,context,64) + Self::new_attention_capacity(binding, context, 64) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in super::super) fn new_attention_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} + pub(in super::super) fn new_attention_capacity( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + capacity: usize, + ) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidDimension); + } let mut result = Self::new_qsa_selected_router_gr_batch_qk(binding, context)?; - result.native_prompt_capacity=capacity; - match QsaAttentionScratch::new_experimental(binding, context, result.mirror_failed.clone()) - { + result.native_prompt_capacity = capacity; + match QsaAttentionScratch::new_experimental(binding, context, result.mirror_failed.clone()) { Ok(slot) => { - if slot.allocated_bytes() != super::super::super::qsa_attention::attention_scratch::SCRATCH_BYTES - { + if slot.allocated_bytes() != super::super::super::qsa_attention::attention_scratch::SCRATCH_BYTES { let _ = slot.close(); let _ = result.close(); return Err(Error::InvalidDimension); @@ -122,7 +111,11 @@ impl<'ctx> DenseWeightCache<'ctx> { } // Original selected mode17 profile has STRATA_PREFILL_BF16X2 absent. // HighOnly is explicit. Hi+Lo is a separately qualified load profile. - match if capacity==64 {context.ple_batch_queue(leleka_cuda_driver::PleBf16Mode::HighOnly)}else{context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly,capacity)} { + match if capacity == 64 { + context.ple_batch_queue(leleka_cuda_driver::PleBf16Mode::HighOnly) + } else { + context.ple_batch_queue_for_prompt(leleka_cuda_driver::PleBf16Mode::HighOnly, capacity) + } { Ok(queue) => result.ple_batch_queue = Some(RefCell::new(queue)), Err(error) => { let primary = driver_error(error); @@ -130,14 +123,29 @@ impl<'ctx> DenseWeightCache<'ctx> { return Err(primary); } } - match if capacity==64 {super::super::super::gdn::prefill_batch::GdnBatchResources::new(context,super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly)}else{super::super::super::gdn::prefill_batch::GdnBatchResources::new_for_prompt(context,super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly,capacity)} { + match if capacity == 64 { + super::super::super::gdn::prefill_batch::GdnBatchResources::new( + context, + super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly, + ) + } else { + super::super::super::gdn::prefill_batch::GdnBatchResources::new_for_prompt( + context, + super::super::super::gdn::prefill_batch::Bf16Profile::HighOnly, + capacity, + ) + } { Ok(resources) => result.gdn_batch_resources = Some(RefCell::new(resources)), Err(primary) => { let _ = result.close(); return Err(primary); } } - match if capacity==64 {context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly)}else{context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly,capacity)} { + match if capacity == 64 { + context.qsa_native_batch_workspace(leleka_cuda_driver::QsaNativePacking::HighOnly) + } else { + context.qsa_native_batch_workspace_for_prompt(leleka_cuda_driver::QsaNativePacking::HighOnly, capacity) + } { Ok(owner) => result.qsa_native_workspace = Some(RefCell::new(owner)), Err(error) => { let primary = driver_error(error); @@ -145,7 +153,15 @@ impl<'ctx> DenseWeightCache<'ctx> { return Err(primary); } } - match if capacity==64 {super::super::super::qsa_native_resources::NativeQsaResources::new(context,result.mirror_failed.clone())}else{super::super::super::qsa_native_resources::NativeQsaResources::new_for_prompt(context,result.mirror_failed.clone(),capacity)} { + match if capacity == 64 { + super::super::super::qsa_native_resources::NativeQsaResources::new(context, result.mirror_failed.clone()) + } else { + super::super::super::qsa_native_resources::NativeQsaResources::new_for_prompt( + context, + result.mirror_failed.clone(), + capacity, + ) + } { Ok(owner) => result.native_qsa = Some(RefCell::new(owner)), Err(primary) => { let _ = result.close(); @@ -173,9 +189,7 @@ impl<'ctx> DenseWeightCache<'ctx> { ) -> Result>> { self.retained_context(binding, context)?; let resource = self.native_qsa.as_ref().ok_or(Error::IdentityMismatch)?; - let owner = resource - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let owner = resource.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; owner.validate(context)?; Ok(owner) } @@ -202,22 +216,14 @@ impl<'ctx> DenseWeightCache<'ctx> { } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn test_retained_scratch_witness(&self) -> Result<(usize, u64)> { - let qk = self - .gdn_qk_workspace - .as_ref() - .ok_or(Error::IdentityMismatch)? - .test_slot_bytes()?; + let qk = self.gdn_qk_workspace.as_ref().ok_or(Error::IdentityMismatch)?.test_slot_bytes()?; let qsa = self .qsa_attention_workspace .as_ref() .ok_or(Error::IdentityMismatch)? .try_borrow() .map_err(|_| Error::IdentityMismatch)?; - Ok(( - qk.checked_add(qsa.allocated_bytes()) - .ok_or(Error::Overflow)?, - qsa.completed_rows(), - )) + Ok((qk.checked_add(qsa.allocated_bytes()).ok_or(Error::Overflow)?, qsa.completed_rows())) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn new_qsa_selected_router_gr_batch_qk_attention_mtp_journal( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs index b131f930..9df65731 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_2_2.rs @@ -3,49 +3,97 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn new_original_prompt_capacity(binding:&ModelBinding,context:&'ctx Context<'ctx>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity){return Err(Error::InvalidDimension);} + pub(crate) fn new_original_prompt_capacity( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + capacity: usize, + ) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidDimension); + } // Actual weights and scalar/decode state remain model-lifetime owners. // Prompt payloads live in the Original aliased arena, so this factory // never allocates the legacy capacity-sized PLE/GDN/QSA row banks. - let mut cache=startup_step("new_with_selected",Self::new_with_selected(binding,context,false))?; - cache.native_prompt_capacity=capacity; - let loaded=(||->Result<()>{ - cache.native_batch_workspace=Some(RefCell::new(startup_step("native_batch_workspace",context.native_batch_workspace()).map_err(driver_error)?)); - cache.ple_queue=Some(RefCell::new(startup_step("ple_closed_queue",context.ple_closed_queue()).map_err(driver_error)?)); - cache.native_gdn_fused=Some(Rc::new(RefCell::new(startup_step("gdn_fused_t1",context.gdn_fused_t1()).map_err(driver_error)?))); - cache.gdn_verification=Some(Rc::new(RefCell::new(startup_step("gdn verification workspace",super::super::super::gdn::verification::Workspace::new( - cache.binding.clone(),context,cache.mirror_failed.clone()))?))); - cache.gdn_qk_workspace=Some(Rc::new(startup_step("gdn qk scratch",QkScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); - cache.router_scratch=Some(RefCell::new(startup_step("router scratch",RouterScratch::new(cache.binding.clone(),context,cache.mirror_failed.clone()))?)); - cache.gr_batch_workspace=Some(RefCell::new(startup_step("gr_batch_inject_workspace",context.gr_batch_inject_workspace()).map_err(driver_error)?)); - cache.gdn_four_borrow=true; - startup_step("validate",cache.validate(binding)) + let mut cache = startup_step("new_with_selected", Self::new_with_selected(binding, context, false))?; + cache.native_prompt_capacity = capacity; + let loaded = (|| -> Result<()> { + cache.native_batch_workspace = Some(RefCell::new( + startup_step("native_batch_workspace", context.native_batch_workspace()).map_err(driver_error)?, + )); + cache.ple_queue = + Some(RefCell::new(startup_step("ple_closed_queue", context.ple_closed_queue()).map_err(driver_error)?)); + cache.native_gdn_fused = Some(Rc::new(RefCell::new( + startup_step("gdn_fused_t1", context.gdn_fused_t1()).map_err(driver_error)?, + ))); + cache.gdn_verification = Some(Rc::new(RefCell::new(startup_step( + "gdn verification workspace", + super::super::super::gdn::verification::Workspace::new( + cache.binding.clone(), + context, + cache.mirror_failed.clone(), + ), + )?))); + cache.gdn_qk_workspace = Some(Rc::new(startup_step( + "gdn qk scratch", + QkScratch::new(cache.binding.clone(), context, cache.mirror_failed.clone()), + )?)); + cache.router_scratch = Some(RefCell::new(startup_step( + "router scratch", + RouterScratch::new(cache.binding.clone(), context, cache.mirror_failed.clone()), + )?)); + cache.gr_batch_workspace = Some(RefCell::new( + startup_step("gr_batch_inject_workspace", context.gr_batch_inject_workspace()).map_err(driver_error)?, + )); + cache.gdn_four_borrow = true; + startup_step("validate", cache.validate(binding)) })(); - if loaded.is_ok() && let Some(slabs) = cache.slabs.as_ref() { + if loaded.is_ok() + && let Some(slabs) = cache.slabs.as_ref() + { let stats = slabs.stats(); eprintln!( "leleka-serve dense weights: {} buffers; {} slabs of {} MiB hold {} of them ({:.1} MiB), {} buffers above {} MiB keep their own allocation ({:.1} MiB driver-estimated)", - cache.buffers.len(), stats.slabs, SlabPolicy::DENSE.slab_bytes >> 20, stats.carved, stats.carved_bytes as f64 / 1048576.0, - stats.direct, SlabPolicy::DENSE.direct_above >> 20, stats.direct_bytes as f64 / 1048576.0, + cache.buffers.len(), + stats.slabs, + SlabPolicy::DENSE.slab_bytes >> 20, + stats.carved, + stats.carved_bytes as f64 / 1048576.0, + stats.direct, + SlabPolicy::DENSE.direct_above >> 20, + stats.direct_bytes as f64 / 1048576.0, ); } - match loaded{Ok(())=>Ok(cache),Err(primary)=>{let _=cache.close();Err(primary)}} + match loaded { + Ok(()) => Ok(cache), + Err(primary) => { + let _ = cache.close(); + Err(primary) + } + } } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_prompt_capacity(&self,binding:&ModelBinding,context:&Context<'_>)->Result { - self.retained_context(binding,context)?; - if self.native_batch_workspace.is_none()||!(1..=8192).contains(&self.native_prompt_capacity) {return Err(Error::IdentityMismatch);} + pub(in crate::qwen_forward) fn native_prompt_capacity( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result { + self.retained_context(binding, context)?; + if self.native_batch_workspace.is_none() || !(1..=8192).contains(&self.native_prompt_capacity) { + return Err(Error::IdentityMismatch); + } Ok(self.native_prompt_capacity) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn native_prompt_transient_device_bytes(&self,binding:&ModelBinding,context:&Context<'_>)->Result { - let capacity=self.native_prompt_capacity(binding,context)?; - let gr=leleka_cuda_driver::GrNativeBatch::prompt_device_bytes(capacity).map_err(driver_error)?; - let qsa=leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?; + pub(in crate::qwen_forward) fn native_prompt_transient_device_bytes( + &self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result { + let capacity = self.native_prompt_capacity(binding, context)?; + let gr = leleka_cuda_driver::GrNativeBatch::prompt_device_bytes(capacity).map_err(driver_error)?; + let qsa = leleka_cuda_driver::QsaPromptIndexWorkspace::prompt_output_bytes(capacity).map_err(driver_error)?; gr.checked_add(qsa).ok_or(Error::Overflow) } /// An idle GDN next-state finite guard of this cache's Context, or a new one. @@ -66,7 +114,11 @@ impl<'ctx> DenseWeightCache<'ctx> { } } /// A 3.1 MB GDN state buffer: an idle pooled one when `LELEKA_PREFILL_GDN_POOL` is on, else a fresh allocation. Contents are never assumed. - pub(in crate::qwen_forward) fn take_gdn_scratch(&self, context: &'ctx Context<'ctx>, bytes: usize) -> Result> { + pub(in crate::qwen_forward) fn take_gdn_scratch( + &self, + context: &'ctx Context<'ctx>, + bytes: usize, + ) -> Result> { if super::super::super::gdn::pool_enabled() { let idle = self.gdn_scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.pop(); if let Some(buffer) = idle { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs index 44420f84..c19e4a14 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { pub(in super::super) fn new_with_selected( binding: &ModelBinding, @@ -62,10 +61,8 @@ impl<'ctx> DenseWeightCache<'ctx> { ple: None, counters: Cell::new(DenseCacheCounters::default()), }; - result.modules = Some(super::super::super::chunk_modules::ChunkModules::new( - context, - result.mirror_failed.clone(), - )); + result.modules = + Some(super::super::super::chunk_modules::ChunkModules::new(context, result.mirror_failed.clone())); let loaded = (|| -> Result<()> { // Optional fixed byte workspace is eagerly charged before lazy MoE growth. if selected { @@ -91,31 +88,12 @@ impl<'ctx> DenseWeightCache<'ctx> { context, result.mirror_failed.clone(), )?)); - result.gr_scratch = Some(RefCell::new(GrScratch::new( - binding, - context, - result.mirror_failed.clone(), - )?)); - result - .gdn - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .gdn_mirrors - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .qsa - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; - result - .gr - .try_reserve_exact(n * 2 + 1) - .map_err(|_| Error::InputAllocation)?; - result - .router - .try_reserve_exact(n) - .map_err(|_| Error::InputAllocation)?; + result.gr_scratch = Some(RefCell::new(GrScratch::new(binding, context, result.mirror_failed.clone())?)); + result.gdn.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + result.gdn_mirrors.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + result.qsa.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + result.gr.try_reserve_exact(n * 2 + 1).map_err(|_| Error::InputAllocation)?; + result.router.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; for layer in binding.ordered_layers() { let id = layer.index(); let gdn = if layer.kind() == BoundLayerKind::Gdn { @@ -135,10 +113,7 @@ impl<'ctx> DenseWeightCache<'ctx> { .gdn_matrix_block(&weights, role, 0, weights.shape(role).1) .map_err(binding_error)?; matrices[i] = ( - result.add( - block.bytes(), - weights.source_bytes(role).map_err(binding_error)?, - )?, + result.add(block.bytes(), weights.source_bytes(role).map_err(binding_error)?)?, block.kind(), ); } @@ -148,12 +123,7 @@ impl<'ctx> DenseWeightCache<'ctx> { result.add_f32(weights.a())?, result.add_f32(weights.norm())?, ]; - Some(GdnResident { - owner: result.owner.clone(), - weights, - matrices, - aux, - }) + Some(GdnResident { owner: result.owner.clone(), weights, matrices, aux }) } else { None }; @@ -175,10 +145,7 @@ impl<'ctx> DenseWeightCache<'ctx> { .qsa_matrix_block(&weights, role, 0, weights.shape(role).1) .map_err(binding_error)?; matrices[i] = ( - result.add( - block.bytes(), - weights.source_bytes(role).map_err(binding_error)?, - )?, + result.add(block.bytes(), weights.source_bytes(role).map_err(binding_error)?)?, block.kind(), ); } @@ -188,25 +155,13 @@ impl<'ctx> DenseWeightCache<'ctx> { result.add_f32(weights.index_q_norm())?, result.add_f32(weights.index_k_norm())?, ]; - Some(QsaResident { - owner: result.owner.clone(), - weights, - matrices, - norms, - }) + Some(QsaResident { owner: result.owner.clone(), weights, matrices, norms }) } else { None }; let mirror = gdn .as_ref() - .map(|_| { - GdnStateMirror::new( - result.binding.clone(), - id, - context, - result.mirror_failed.clone(), - ) - }) + .map(|_| GdnStateMirror::new(result.binding.clone(), id, context, result.mirror_failed.clone())) .transpose()? .map(RefCell::new); result.gdn.push(gdn); @@ -216,19 +171,13 @@ impl<'ctx> DenseWeightCache<'ctx> { result.add_gr(binding, role)?; } let weights = binding.moe_route_weights(id).map_err(binding_error)?; - let block = binding - .moe_route_matrix_block(&weights, 0, 512) - .map_err(binding_error)?; + let block = binding.moe_route_matrix_block(&weights, 0, 512).map_err(binding_error)?; let index = result.add(block.bytes(), block.bytes().len())?; result.router.push(index); } result.add_gr(binding, GrRole::Final)?; result.add_ple(binding)?; - let mirror_count = result - .gdn_mirrors - .iter() - .filter(|entry| entry.is_some()) - .count(); + let mirror_count = result.gdn_mirrors.iter().filter(|entry| entry.is_some()).count(); if mirror_count.checked_mul(786432 * 4) != Some(ALL_MIRROR_BYTES) { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs index 64937ea5..0d544e72 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { pub(in super::super) fn add(&mut self, bytes: &[u8], source_bytes: usize) -> Result { if self @@ -15,9 +14,7 @@ impl<'ctx> DenseWeightCache<'ctx> { { return Err(Error::InputAllocation); } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut b = self.slabs.as_mut().ok_or(Error::IdentityMismatch)?.allocate(bytes.len()).map_err(driver_error)?; if let Err(error) = b.copy_from(bytes) { let primary = driver_error(error); @@ -28,14 +25,8 @@ impl<'ctx> DenseWeightCache<'ctx> { self.buffers.push(b); let mut c = self.counters.get(); c.matrices = c.matrices.checked_add(1).ok_or(Error::Overflow)?; - c.read_bytes = c - .read_bytes - .checked_add(source_bytes as u64) - .ok_or(Error::Overflow)?; - c.upload_bytes = c - .upload_bytes - .checked_add(bytes.len() as u64) - .ok_or(Error::Overflow)?; + c.read_bytes = c.read_bytes.checked_add(source_bytes as u64).ok_or(Error::Overflow)?; + c.upload_bytes = c.upload_bytes.checked_add(bytes.len() as u64).ok_or(Error::Overflow)?; self.counters.set(c); Ok(index) } @@ -72,42 +63,30 @@ impl<'ctx> DenseWeightCache<'ctx> { Some(self.add_f32(weights.norm())?), Some(self.add_bf16(weights.down(), source_bytes[1])?), Some(self.add_bf16(weights.up(), source_bytes[2])?), - weights - .inject() - .map(|v| self.add_bf16(v, source_bytes[3])) - .transpose()?, + weights.inject().map(|v| self.add_bf16(v, source_bytes[3])).transpose()?, ]; - self.gr.push(GrResident { - owner: self.owner.clone(), - weights, - buffers, - }); + self.gr.push(GrResident { owner: self.owner.clone(), weights, buffers }); Ok(()) } pub(in super::super) fn add_ple(&mut self, binding: &ModelBinding) -> Result<()> { let weights = Rc::new(binding.ple_weights().map_err(binding_error)?); // Key retains one complete immutable matrix with the same total byte // charge as its former 160 tiles; per-row projection math is unchanged. - let key_matrix = binding - .ple_matrix_full(&weights, PleMatrixRole::Key) - .map_err(binding_error)?; + let key_matrix = binding.ple_matrix_full(&weights, PleMatrixRole::Key).map_err(binding_error)?; if key_matrix.rows() != 10240 || key_matrix.bytes().len() != 52_428_800 { return Err(Error::InvalidDimension); } let key = self.add(key_matrix.bytes(), key_matrix.bytes().len())?; drop(key_matrix); // Value retains one whole immutable matrix; forty CTAs keep the original row arithmetic. - let value_matrix = binding - .ple_matrix_full(&weights, PleMatrixRole::Value) - .map_err(binding_error)?; + let value_matrix = binding.ple_matrix_full(&weights, PleMatrixRole::Value).map_err(binding_error)?; if value_matrix.rows() != 2560 || value_matrix.bytes().len() != 2560 * 2560 * 2 { return Err(Error::InvalidDimension); } let value = self.add(value_matrix.bytes(), value_matrix.bytes().len())?; drop(value_matrix); let mut conv = Vec::new(); - conv.try_reserve_exact(weights.conv().len() * 2) - .map_err(|_| Error::InputAllocation)?; + conv.try_reserve_exact(weights.conv().len() * 2).map_err(|_| Error::InputAllocation)?; for v in weights.conv() { if !leleka_quant_core::f16_bits_to_f32(*v).is_finite() { return Err(Error::NonFinite); @@ -120,13 +99,7 @@ impl<'ctx> DenseWeightCache<'ctx> { self.add_f32(weights.norm_conv())?, self.add(&conv, conv.len())?, ]; - self.ple = Some(PleResident { - owner: self.owner.clone(), - weights, - key, - value, - aux, - }); + self.ple = Some(PleResident { owner: self.owner.clone(), weights, key, value, aux }); Ok(()) } pub(in super::super::super) fn validate(&self, binding: &ModelBinding) -> Result<()> { @@ -192,11 +165,7 @@ impl<'ctx> DenseWeightCache<'ctx> { context: &Context<'_>, ) -> Result>> { self.retained_context(binding, context)?; - self.gr_scratch - .as_ref() - .ok_or(Error::IdentityMismatch)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch) + self.gr_scratch.as_ref().ok_or(Error::IdentityMismatch)?.try_borrow_mut().map_err(|_| Error::IdentityMismatch) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super::super) fn gr_batch_workspace( @@ -208,9 +177,7 @@ impl<'ctx> DenseWeightCache<'ctx> { return Ok(None); }; self.retained_context(binding, context)?; - slot.try_borrow_mut() - .map(Some) - .map_err(|_| Error::IdentityMismatch) + slot.try_borrow_mut().map(Some).map_err(|_| Error::IdentityMismatch) } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super::super) fn ple_queue( @@ -219,10 +186,7 @@ impl<'ctx> DenseWeightCache<'ctx> { context: &Context<'_>, ) -> Result>>> { self.retained_context(binding, context)?; - self.ple_queue - .as_ref() - .map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() + self.ple_queue.as_ref().map(|queue| queue.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose() } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super::super) fn native_batch_workspace( @@ -243,9 +207,6 @@ impl<'ctx> DenseWeightCache<'ctx> { context: &Context<'_>, ) -> Result>>> { self.retained_context(binding, context)?; - self.ple_batch_queue - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() + self.ple_batch_queue.as_ref().map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose() } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs index 646866d7..e76f3f08 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_5.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super::super) fn gdn_batch_resources( @@ -45,11 +44,7 @@ impl<'ctx> DenseWeightCache<'ctx> { if self.gr_batch_workspace.is_none() { return Err(Error::IdentityMismatch); } - let count = self - .gr_batch_completed - .get() - .checked_add(1) - .ok_or(Error::Overflow)?; + let count = self.gr_batch_completed.get().checked_add(1).ok_or(Error::Overflow)?; self.gr_batch_completed.set(count); Ok(()) } @@ -67,11 +62,8 @@ impl<'ctx> DenseWeightCache<'ctx> { identity: super::super::super::contract::TokenLayer, ) -> Result>> { self.retained_context(binding, context)?; - let resident = self - .gdn - .get(identity.layer().get() as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; + let resident = + self.gdn.get(identity.layer().get() as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer)?; if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != identity.layer().get() || identity.layer().get() % 4 == 3 @@ -104,11 +96,7 @@ impl<'ctx> DenseWeightCache<'ctx> { source: &'source [f32], ) -> Result> { self.retained_context(binding, context)?; - let resident = self - .qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; + let resident = self.qsa.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer)?; if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { return Err(Error::IdentityMismatch); } @@ -130,18 +118,11 @@ impl<'ctx> DenseWeightCache<'ctx> { context: &Context<'_>, ) -> Result>>> { self.retained_context(binding, context)?; - let resident = self - .qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; + let resident = self.qsa.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer)?; if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { return Err(Error::IdentityMismatch); } - self.qsa_selected - .as_ref() - .map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)) - .transpose() + self.qsa_selected.as_ref().map(|slot| slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)).transpose() } pub(in super::super::super) fn qsa_select( &self, @@ -167,11 +148,7 @@ impl<'ctx> DenseWeightCache<'ctx> { source: &'source [f32], ) -> Result> { self.retained_context(binding, context)?; - let resident = self - .gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; + let resident = self.gdn.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer)?; if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { return Err(Error::IdentityMismatch); } @@ -192,10 +169,7 @@ impl<'ctx> DenseWeightCache<'ctx> { pub(in super::super::super) fn gdn(&self, binding: &ModelBinding, layer: u32) -> Result<&GdnResident> { self.check(binding)?; self.hit()?; - self.gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer) + self.gdn.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer) } pub(in super::super::super) fn gdn_mirror( &self, @@ -207,11 +181,7 @@ impl<'ctx> DenseWeightCache<'ctx> { if !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } - let resident = self - .gdn - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer)?; + let resident = self.gdn.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer)?; if !Rc::ptr_eq(&self.owner, &resident.owner) || resident.weights.layer() != layer { return Err(Error::IdentityMismatch); } @@ -225,10 +195,7 @@ impl<'ctx> DenseWeightCache<'ctx> { pub(in super::super::super) fn qsa(&self, binding: &ModelBinding, layer: u32) -> Result<&QsaResident> { self.check(binding)?; self.hit()?; - self.qsa - .get(layer as usize) - .and_then(Option::as_ref) - .ok_or(Error::InvalidLayer) + self.qsa.get(layer as usize).and_then(Option::as_ref).ok_or(Error::InvalidLayer) } pub(in super::super::super) fn gr(&self, binding: &ModelBinding, role: GrRole) -> Result<&GrResident> { self.check(binding)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs index 63b4ded2..6c26b5f8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_6.rs @@ -3,13 +3,8 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { - pub(in super::super::super) fn ple( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&PleResident> { + pub(in super::super::super) fn ple(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<&PleResident> { self.check(binding)?; if !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); @@ -107,9 +102,7 @@ impl<'ctx> DenseWeightCache<'ctx> { ) -> Result<[OriginalVerifyGdnWeights<'a, 'ctx>; 36]> { self.check(binding)?; let mut retained = Vec::new(); - retained - .try_reserve_exact(36) - .map_err(|_| Error::InputAllocation)?; + retained.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; for layer in binding.ordered_layers() { if layer.kind() != BoundLayerKind::Gdn { continue; @@ -121,14 +114,7 @@ impl<'ctx> DenseWeightCache<'ctx> { return Err(Error::Unsupported(super::super::super::contract::Stage::Gdn)); } let aux = self.gdn_aux(resident)?; - retained.push(OriginalVerifyGdnWeights { - conv: aux[0], - alpha, - beta, - dt: aux[1], - a: aux[2], - norm: aux[3], - }); + retained.push(OriginalVerifyGdnWeights { conv: aux[0], alpha, beta, dt: aux[1], a: aux[2], norm: aux[3] }); } retained.try_into().map_err(|_| Error::InvalidDimension) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs index 2547fb3f..5a876e52 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/dense_weight_cache/impl_denseweightcache/impl_denseweightcache_7.rs @@ -3,12 +3,8 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> DenseWeightCache<'ctx> { - pub(in super::super::super) fn gr_buffers( - &self, - entry: &GrResident, - ) -> Result<[Option<&DeviceBuffer<'ctx>>; 4]> { + pub(in super::super::super) fn gr_buffers(&self, entry: &GrResident) -> Result<[Option<&DeviceBuffer<'ctx>>; 4]> { if !Rc::ptr_eq(&self.owner, &entry.owner) { return Err(Error::IdentityMismatch); } @@ -58,9 +54,8 @@ impl<'ctx> DenseWeightCache<'ctx> { error.get_or_insert(e); } if let Some(slot) = self.gdn_verification { - let result = Rc::try_unwrap(slot) - .map_err(|_| Error::IdentityMismatch) - .and_then(|slot| slot.into_inner().close()); + let result = + Rc::try_unwrap(slot).map_err(|_| Error::IdentityMismatch).and_then(|slot| slot.into_inner().close()); if let Err(failure) = result { error.get_or_insert(failure); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs index 8563ff8d..e458c1a9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor.rs @@ -20,11 +20,11 @@ use crate::model_binding::qwen4exp_input::{BindingIdentity, BoundLayerKind, Mode type StepCoreResult = (Option, Option>); +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "executor_original_prompt.rs"] +pub(in crate::qwen_forward) mod original_prompt; #[path = "executor_prefill_chunk.rs"] mod prefill_chunk; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="executor_original_prompt.rs"] -pub(in crate::qwen_forward) mod original_prompt; /// MTP input from one fully committed target step. No public constructor. pub(crate) struct TargetStepProduct { @@ -85,43 +85,19 @@ mod reset_replay_sdet { index: usize, ) -> CapturedStep { // Called only after the selected complete forward returned commit success. - let logits = output - .test_reset_replay_take_logits() - .expect("committed logit observation missing"); - assert_eq!( - logits.len(), - VOCABULARY, - "full vocabulary observation required" - ); - assert!( - greedy.get() < VOCABULARY as u32, - "greedy outside vocabulary" - ); - let state = session - .test_reset_replay_snapshot(binding) - .expect("committed numeric state snapshot refused"); - let predecessors = if index == 0 { - [-1, TOKENS[0] as i32] - } else { - [TOKENS[index - 1] as i32, TOKENS[index] as i32] - }; - assert!( - state.has_prefix((index + 1) as u64, predecessors), - "committed prefix metadata differs" - ); + let logits = output.test_reset_replay_take_logits().expect("committed logit observation missing"); + assert_eq!(logits.len(), VOCABULARY, "full vocabulary observation required"); + assert!(greedy.get() < VOCABULARY as u32, "greedy outside vocabulary"); + let state = session.test_reset_replay_snapshot(binding).expect("committed numeric state snapshot refused"); + let predecessors = + if index == 0 { [-1, TOKENS[0] as i32] } else { [TOKENS[index - 1] as i32, TOKENS[index] as i32] }; + assert!(state.has_prefix((index + 1) as u64, predecessors), "committed prefix metadata differs"); let retained = state .retained_bytes() .and_then(|n| n.checked_add(logits.len().checked_mul(4)?)) .expect("retained prefix byte extent overflow"); - assert!( - retained <= PREFIX_BOUND, - "retained prefix exceeds predeclared bound" - ); - CapturedStep { - state, - logits, - greedy: greedy.get(), - } + assert!(retained <= PREFIX_BOUND, "retained prefix exceeds predeclared bound"); + CapturedStep { state, logits, greedy: greedy.get() } } /// Narrow test entry can borrow an already verified/loaded operator owner. @@ -134,17 +110,9 @@ mod reset_replay_sdet { moe_cache: &mut MoeWeightCache<'_>, dense_cache: &DenseWeightCache<'_>, ) { - let charged = PREFIX_BOUND - .checked_mul(6) - .expect("reset/replay retention extent overflow"); - assert!( - charged <= HOST_RETENTION_LIMIT, - "reset/replay host budget refused" - ); - assert!( - binding.kar_ple_binding().is_some(), - "explicit pinned KAR required" - ); + let charged = PREFIX_BOUND.checked_mul(6).expect("reset/replay retention extent overflow"); + assert!(charged <= HOST_RETENTION_LIMIT, "reset/replay host budget refused"); + assert!(binding.kar_ple_binding().is_some(), "explicit pinned KAR required"); let layer_bound = validate_layer_plan(binding).expect("verified topology refused"); assert_eq!(layer_bound.get(), 48, "pinned complete topology required"); let mut gdn_count = 0; @@ -154,35 +122,21 @@ mod reset_replay_sdet { BoundLayerKind::Gdn => gdn_count += 1, BoundLayerKind::Qsa => qsa_count += 1, } - eprintln!( - "reset-replay disposition layer={} kind={:?}", - descriptor.index(), - descriptor.kind() - ); + eprintln!("reset-replay disposition layer={} kind={:?}", descriptor.index(), descriptor.kind()); } assert_eq!((gdn_count, qsa_count), (36, 12)); // The verified closed artifact/binder fixes the main vocabulary; PLE // hash-table vocabularies are separate and must not be used here. - let vocabulary = - Dimension::new(u64::from(crate::model_binding::qwen4exp_input::VOCABULARY)) - .expect("verified vocabulary refused"); + let vocabulary = Dimension::new(u64::from(crate::model_binding::qwen4exp_input::VOCABULARY)) + .expect("verified vocabulary refused"); assert_eq!(vocabulary.get(), VOCABULARY as u32); - let context_length = Dimension::new(u64::from(binding.input_constants().context_length())) - .expect("verified context refused"); - let fresh = session - .test_reset_replay_snapshot(binding) - .expect("fresh session snapshot refused"); - assert!( - fresh.has_prefix(0, [-1, -1]), - "already-used session refused" - ); + let context_length = + Dimension::new(u64::from(binding.input_constants().context_length())).expect("verified context refused"); + let fresh = session.test_reset_replay_snapshot(binding).expect("fresh session snapshot refused"); + assert!(fresh.has_prefix(0, [-1, -1]), "already-used session refused"); let mut baseline = Vec::new(); - baseline - .try_reserve_exact(TOKENS.len()) - .expect("baseline retention allocation failed"); - output - .test_reset_replay_record(true) - .expect("logit observer refused"); + baseline.try_reserve_exact(TOKENS.len()).expect("baseline retention allocation failed"); + output.test_reset_replay_record(true).expect("logit observer refused"); for (index, token) in TOKENS.into_iter().enumerate() { let greedy = QwenForward::step_cached( binding, @@ -209,13 +163,8 @@ mod reset_replay_sdet { ); QwenForward::reset(session).expect("actual owner reset failed"); - let reset = session - .test_reset_replay_snapshot(binding) - .expect("reset state snapshot refused"); - assert!( - fresh.numeric_eq(&reset), - "reset did not clear complete committed state" - ); + let reset = session.test_reset_replay_snapshot(binding).expect("reset state snapshot refused"); + assert!(fresh.numeric_eq(&reset), "reset did not clear complete committed state"); for (index, (token, expected)) in TOKENS.into_iter().zip(&baseline).enumerate() { let greedy = QwenForward::step_with_kar_ple_output( binding, @@ -227,14 +176,8 @@ mod reset_replay_sdet { ) .expect("legacy uncached full forward refused"); let actual = capture_committed(binding, session, output, greedy, index); - assert!( - actual.greedy == expected.greedy, - "replay greedy mismatch at step {index}" - ); - assert!( - actual.logits.as_ref() == expected.logits.as_ref(), - "full logit word mismatch at step {index}" - ); + assert!(actual.greedy == expected.greedy, "replay greedy mismatch at step {index}"); + assert!(actual.logits.as_ref() == expected.logits.as_ref(), "full logit word mismatch at step {index}"); assert!( actual.state.numeric_eq(&expected.state), "complete committed numeric state mismatch at step {index}" @@ -261,9 +204,7 @@ mod reset_replay_sdet { && dense_before_replay.upload_bytes == dense_after_replay.upload_bytes, "legacy replay unexpectedly used the dense weight cache" ); - output - .test_reset_replay_record(false) - .expect("logit observer did not drain"); + output.test_reset_replay_record(false).expect("logit observer did not drain"); eprintln!( "cache-reset-replay numerical PASS cached=4 legacy=4 resets=1 logits_per_step=248320 gdn=36 qsa=12 host_retention_bound={charged} moe_hits={} moe_misses={} read_bytes={} upload_bytes={} eviction_bytes={} dense_hits={} dense_matrices={} dense_read_bytes={} dense_upload_bytes={}", moe_before_replay.hits, @@ -281,11 +222,7 @@ mod reset_replay_sdet { #[test] #[ignore = "one explicitly scheduled pinned KAR model load and NVIDIA GPU; no live-load duplication"] fn pinned_kar_cached_vs_legacy_same_session_reset_replays_all_logits_and_numeric_state() { - let path = |name| { - env::var_os(name) - .map(PathBuf::from) - .expect("missing pinned reset/replay test path") - }; + let path = |name| env::var_os(name).map(PathBuf::from).expect("missing pinned reset/replay test path"); let shard0 = VerifiedGgufFile::open( &path("LELEKA_STRA169_IQ3S_SHARD0"), "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3", @@ -296,8 +233,7 @@ mod reset_replay_sdet { "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", ) .expect("pinned reset/replay shard1 verification failed"); - let artifact = Qwen4ExpArtifact::bind(shard0, shard1) - .expect("pinned reset/replay artifact binding failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned reset/replay artifact binding failed"); let binding = ModelBinding::from_artifact_with_pinned_kar_ple( artifact, &path("LELEKA_STRA169_KAR_ARCHIVE"), @@ -305,36 +241,18 @@ mod reset_replay_sdet { ) .expect("pinned reset/replay KAR binding failed"); let driver = Driver::load().expect("reset/replay CUDA driver load failed"); - let device = driver - .device(0) - .expect("reset/replay device selection failed"); - let context = Rc::new( - device - .create_context(DEVICE_BUDGET) - .expect("reset/replay Context refused"), - ); - let output = - OutputStage::load(&binding, context.as_ref()).expect("resident head load failed"); - let mut cache = KarPleCache::new( - context.as_ref(), - binding - .kar_ple_binding() - .expect("pinned KAR provider missing"), - ) - .expect("resident KAR cache load failed"); - let mut moe_cache = MoeWeightCache::new(&binding, context.as_ref()) - .expect("actor-owned MoE weight cache load failed"); - let dense_cache = DenseWeightCache::new(&binding, context.as_ref()) - .expect("actor-owned dense weight cache load failed"); + let device = driver.device(0).expect("reset/replay device selection failed"); + let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("reset/replay Context refused")); + let output = OutputStage::load(&binding, context.as_ref()).expect("resident head load failed"); + let mut cache = + KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("pinned KAR provider missing")) + .expect("resident KAR cache load failed"); + let mut moe_cache = + MoeWeightCache::new(&binding, context.as_ref()).expect("actor-owned MoE weight cache load failed"); + let dense_cache = + DenseWeightCache::new(&binding, context.as_ref()).expect("actor-owned dense weight cache load failed"); let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); - check_on_loaded( - &binding, - &mut session, - &output, - &mut cache, - &mut moe_cache, - &dense_cache, - ); + check_on_loaded(&binding, &mut session, &output, &mut cache, &mut moe_cache, &dense_cache); drop(session); // Attempt both explicit cache closes before checking either result. let moe_closed = moe_cache.close(); @@ -343,15 +261,10 @@ mod reset_replay_sdet { drop(output); let synchronized = context.synchronize(); let allocated = context.allocated_bytes(); - let closed = Rc::try_unwrap(context) - .unwrap_or_else(|_| panic!("reset/replay Context still borrowed")) - .close(); + let closed = Rc::try_unwrap(context).unwrap_or_else(|_| panic!("reset/replay Context still borrowed")).close(); assert!(moe_closed.is_ok(), "MoE cache teardown failed"); assert!(dense_closed.is_ok(), "dense cache teardown failed"); - assert!( - synchronized.is_ok(), - "reset/replay final synchronization failed" - ); + assert!(synchronized.is_ok(), "reset/replay final synchronization failed"); assert_eq!(allocated, 0, "owned device buffers retained after teardown"); assert!(closed.is_ok(), "reset/replay Context teardown failed"); eprintln!("cache-reset-replay teardown PASS allocated_bytes=0"); @@ -386,12 +299,12 @@ mod impl_prefillstepproduct; use impl_prefillstepproduct::diagnose; mod impl_qwenforward; mod read_layer_attention_fn; -#[allow(unused_imports)] -use read_layer_attention_fn::read_layer_attention; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use read_layer_attention_fn::prepare_layer_attention_micro; #[allow(unused_imports)] -use read_layer_attention_fn::validate_layer_plan; +use read_layer_attention_fn::read_layer_attention; #[allow(unused_imports)] use read_layer_attention_fn::validate_descriptors; +#[allow(unused_imports)] +use read_layer_attention_fn::validate_layer_plan; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_prefillstepproduct.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_prefillstepproduct.rs index d30adb48..01ec6777 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_prefillstepproduct.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_prefillstepproduct.rs @@ -16,22 +16,13 @@ impl PrefillStepProduct { { return Err(Error::IdentityMismatch); } - Ok(( - self.token, - self.position, - &self.streams, - self.origin.clone(), - )) + Ok((self.token, self.position, &self.streams, self.origin.clone())) } } impl TargetStepProduct { /// Observation only: validates the actual current committed product first. #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn test_prefix_residual( - &self, - binding: &ModelBinding, - session: &QwenSession<'_>, - ) -> Result> { + pub(crate) fn test_prefix_residual(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result> { let (_, _, values, _) = self.mtp_source(binding, session)?; Ok(values.iter().map(|value| value.to_bits()).collect()) } @@ -48,12 +39,7 @@ impl TargetStepProduct { { return Err(Error::IdentityMismatch); } - Ok(( - self.token, - self.position, - &self.streams, - self.origin.clone(), - )) + Ok((self.token, self.position, &self.streams, self.origin.clone())) } pub(crate) fn predicted(&self, session: &QwenSession<'_>) -> Result { @@ -72,10 +58,7 @@ impl TargetStepProduct { session: &QwenSession<'_>, ) -> Result<&[f32]> { self.origin.validate(session)?; - if !self.binding.matches(&binding.identity()) - || self.token != token - || self.position != position - { + if !self.binding.matches(&binding.identity()) || self.token != token || self.position != position { return Err(Error::IdentityMismatch); } Ok(&self.streams) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs index 7d5cd4a0..00e9c6b8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { pub(crate) fn step( binding: &ModelBinding, @@ -48,10 +46,8 @@ impl QwenForward { output: Option<&OutputStage<'_, '_>>, kar_cache: Option<&mut KarPleCache<'_>>, ) -> Result { - Self::step_core( - binding, token, pos, session, output, kar_cache, None, None, false, false, - ) - .and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch)) + Self::step_core(binding, token, pos, session, output, kar_cache, None, None, false, false) + .and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch)) } /// Retain the pre-output four-stream residual only for explicit MTP use. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs index d5168ac0..892410b0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { - #[allow(clippy::too_many_arguments)] pub(in super::super) fn step_core( binding: &ModelBinding, @@ -30,11 +27,7 @@ impl QwenForward { } if let Some(cache) = moe_cache.as_deref_mut() { let context = txn.cuda_context()?; - if dense_cache - .map(|dense| dense.gdn_four_borrow(binding, context)) - .transpose()? - .unwrap_or(false) - { + if dense_cache.map(|dense| dense.gdn_four_borrow(binding, context)).transpose()?.unwrap_or(false) { cache.reserve_mmq_transient(binding, context, super::super::super::gdn::FOUR_BORROW_BYTES)?; } else { cache.prepare_step(binding, txn.cuda_context()?)?; @@ -52,9 +45,7 @@ impl QwenForward { pos, match (binding.kar_ple_binding(), kar_cache) { (None, None) => InputStage::consume(binding, token, pos, txn), - (Some(_), Some(cache)) => { - InputStage::consume_kar(binding, cache, token, pos, txn) - } + (Some(_), Some(cache)) => InputStage::consume_kar(binding, cache, token, pos, txn), // Never interpret a missing or wrong loaded provider as a // request to switch modes or fall back to the native rows. _ => Err(Error::IdentityMismatch), @@ -67,11 +58,7 @@ impl QwenForward { super::super::super::oracle_capture::stage_f32( -1, "embedding", - input - .streams() - .values() - .get(..2560) - .ok_or(Error::InvalidDimension)?, + input.streams().values().get(..2560).ok_or(Error::InvalidDimension)?, )?; } txn.stage_input(input)?; @@ -95,10 +82,7 @@ impl QwenForward { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { - super::super::super::oracle_capture::stage_current( - "gr_attention_mixed", - residual.ready().mixed(), - )?; + super::super::super::oracle_capture::stage_current("gr_attention_mixed", residual.ready().mixed())?; super::super::super::oracle_capture::stage_current( "gr_attention_inject", residual.ready().oracle_inject(), @@ -112,14 +96,7 @@ impl QwenForward { ForwardPhase::Gdn, layer.get(), pos, - GdnStage::step( - binding, - layer, - residual.ready(), - &prior, - txn, - dense_cache, - ), + GdnStage::step(binding, layer, residual.ready(), &prior, txn, dense_cache), )?; attention.validate_origin(&binding.identity())?; attention.identity().validate(token, pos, layer)?; @@ -137,13 +114,7 @@ impl QwenForward { ForwardPhase::GrAttentionInject, layer.get(), pos, - GrStage::inject( - binding, - &mut residual, - attention.output(), - attention.identity(), - txn, - ), + GrStage::inject(binding, &mut residual, attention.output(), attention.identity(), txn), )? } BoundLayerKind::Qsa => { @@ -166,7 +137,10 @@ impl QwenForward { ) }) .transpose()?; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )))] let native = None; if let Some(completed) = native { completed @@ -200,9 +174,7 @@ impl QwenForward { prepared, txn, dense_cache, - dense_cache.and_then( - DenseWeightCache::qsa_attention_workspace, - ), + dense_cache.and_then(DenseWeightCache::qsa_attention_workspace), ), )?; attention @@ -222,13 +194,7 @@ impl QwenForward { ForwardPhase::GrAttentionInject, layer.get(), pos, - GrStage::inject( - binding, - &mut residual, - attention.output(), - attention.identity(), - txn, - ), + GrStage::inject(binding, &mut residual, attention.output(), attention.identity(), txn), )? } }; @@ -237,10 +203,7 @@ impl QwenForward { let injected = residual.finish(injected_result)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { - super::super::super::oracle_capture::stage_current( - "residual_after_attention", - injected.streams(), - )?; + super::super::super::oracle_capture::stage_current("residual_after_attention", injected.streams())?; } let mut ffn = diagnose( @@ -253,29 +216,19 @@ impl QwenForward { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { super::super::super::oracle_capture::stage_current("gr_ffn_mixed", ffn.ready().mixed())?; - super::super::super::oracle_capture::stage_current( - "gr_ffn_inject", - ffn.ready().oracle_inject(), - )?; + super::super::super::oracle_capture::stage_current("gr_ffn_inject", ffn.ready().oracle_inject())?; } let completed_result = (|| { let route = diagnose( ForwardPhase::MoeRoute, layer.get(), pos, - MoeRouteStage::route_from_ffn( - binding, - layer, - ffn.ready(), - txn, - dense_cache, - ), + MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, dense_cache), )?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { - let ids = - std::array::from_fn::<_, 10, _>(|i| route.experts()[i].get() as i32); + let ids = std::array::from_fn::<_, 10, _>(|i| route.experts()[i].get() as i32); let weights = std::array::from_fn::<_, 10, _>(|i| route.weights()[i].get()); super::super::super::oracle_capture::stage_i32(layer.get() as i32, "router_ids", &ids)?; super::super::super::oracle_capture::stage_current("router_weights", &weights)?; @@ -284,14 +237,7 @@ impl QwenForward { ForwardPhase::MoeExpert, layer.get(), pos, - MoeExpertStage::execute( - binding, - layer, - route, - ffn.ready(), - txn, - moe_cache.as_deref_mut(), - ), + MoeExpertStage::execute(binding, layer, route, ffn.ready(), txn, moe_cache.as_deref_mut()), )?; experts.validate_origin(&binding.identity())?; experts.identity().validate(token, pos, layer)?; @@ -304,13 +250,7 @@ impl QwenForward { ForwardPhase::GrFfnInject, layer.get(), pos, - GrStage::inject( - binding, - &mut ffn, - experts.output(), - experts.identity(), - txn, - ), + GrStage::inject(binding, &mut ffn, experts.output(), experts.identity(), txn), )?; Ok(completed) })(); @@ -318,10 +258,7 @@ impl QwenForward { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::super::oracle_capture::enabled() { - super::super::super::oracle_capture::stage_current( - "residual_after_moe", - completed.streams(), - )?; + super::super::super::oracle_capture::stage_current("residual_after_moe", completed.streams())?; } txn.mark_layer_complete(&completed)?; previous = Some(completed); @@ -343,9 +280,7 @@ impl QwenForward { }; if capture_mtp { let mut owned = Vec::new(); - owned - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + owned.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; owned.extend_from_slice(final_residual.streams()); streams = Some(owned.into_boxed_slice()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs index e42ecb91..9af2c91c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/impl_qwenforward/impl_qwenforward_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { - pub(crate) fn reset(session: &mut QwenSession<'_>) -> Result<()> { session.reset() } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs index 98661620..c59a44ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/read_layer_attention_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The layer-one path consumes and stages the real PLE producer before GR. /// This helper is also the entry for later layers when their FFN provider is /// connected; it cannot manufacture a missing preceding residual. @@ -31,8 +30,7 @@ pub(super) fn read_layer_attention<'cache, 'ctx>( InputStage::apply_ple_cached(binding, previous, &prior, txn, cache), )?; ple.validate_origin(&binding.identity())?; - ple.identity() - .validate(txn.token(), txn.position(), layer)?; + ple.identity().validate(txn.token(), txn.position(), layer)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::oracle_capture::enabled() { @@ -42,13 +40,7 @@ pub(super) fn read_layer_attention<'cache, 'ctx>( txn.stage_ple(&prior, pending)?; GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache) } - _ => GrStage::read_attention( - binding, - layer, - previous.ok_or(Error::IdentityMismatch)?, - txn, - cache, - ), + _ => GrStage::read_attention(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn, cache), } } @@ -80,34 +72,23 @@ pub(super) fn prepare_layer_attention_micro( txn.position(), match ple_micro { Some(batch) => batch.take_ready(binding, previous, &prior, txn), - None => { - InputStage::apply_ple_cached(binding, previous, &prior, txn, Some(cache)) - } + None => InputStage::apply_ple_cached(binding, previous, &prior, txn, Some(cache)), }, )?; ple.validate_origin(&binding.identity())?; - ple.identity() - .validate(txn.token(), txn.position(), layer)?; + ple.identity().validate(txn.token(), txn.position(), layer)?; let pending = ple.take_pending()?; txn.stage_ple(&prior, pending)?; GrStage::prepare_micro_after_ple(binding, layer, &ple, txn) } - _ => GrStage::prepare_micro_after_ffn( - binding, - layer, - previous.ok_or(Error::IdentityMismatch)?, - txn, - ), + _ => GrStage::prepare_micro_after_ffn(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn), } } pub(super) fn validate_layer_plan(binding: &ModelBinding) -> Result { validate_descriptors( binding.layer_count(), - binding - .ordered_layers() - .iter() - .map(|layer| (layer.index(), layer.kind())), + binding.ordered_layers().iter().map(|layer| (layer.index(), layer.kind())), ) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor/tests.rs index 79f4ceb8..d7ab3a3a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor/tests.rs @@ -7,40 +7,23 @@ fn topology_validation_requires_the_exact_contiguous_closed_sequence() { assert_eq!( validate_descriptors( 3, - [ - (0, BoundLayerKind::Gdn), - (1, BoundLayerKind::Qsa), - (2, BoundLayerKind::Gdn), - ] - .into_iter(), + [(0, BoundLayerKind::Gdn), (1, BoundLayerKind::Qsa), (2, BoundLayerKind::Gdn),].into_iter(), ), Ok(Dimension::new(3).unwrap()) ); assert_eq!( - validate_descriptors( - 2, - [(0, BoundLayerKind::Gdn), (0, BoundLayerKind::Qsa)].into_iter(), - ), + validate_descriptors(2, [(0, BoundLayerKind::Gdn), (0, BoundLayerKind::Qsa)].into_iter(),), Err(Error::InvalidLayer) ); assert_eq!( - validate_descriptors( - 2, - [(0, BoundLayerKind::Gdn), (2, BoundLayerKind::Qsa)].into_iter(), - ), + validate_descriptors(2, [(0, BoundLayerKind::Gdn), (2, BoundLayerKind::Qsa)].into_iter(),), Err(Error::InvalidLayer) ); assert_eq!( - validate_descriptors( - 1, - [(0, BoundLayerKind::Qsa), (1, BoundLayerKind::Gdn)].into_iter() - ), - Err(Error::InvalidDimension) - ); - assert_eq!( - validate_descriptors(0, std::iter::empty()), + validate_descriptors(1, [(0, BoundLayerKind::Qsa), (1, BoundLayerKind::Gdn)].into_iter()), Err(Error::InvalidDimension) ); + assert_eq!(validate_descriptors(0, std::iter::empty()), Err(Error::InvalidDimension)); } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -52,10 +35,8 @@ fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() { use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; use std::{env, path::PathBuf, rc::Rc}; - const SHARD0_SHA256: &str = - "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; - const SHARD1_SHA256: &str = - "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; + const SHARD0_SHA256: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; + const SHARD1_SHA256: &str = "sha256:316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"; // Paths are supplied only by the operator for this ignored test; the // artifact identities remain fixed in source and cannot be overridden. @@ -72,26 +53,18 @@ fn pinned_artifact_refuses_missing_output_before_layers_without_state_commit() { .unwrap_or_else(|_| panic!("pinned shard 1 verification failed")); let artifact = Qwen4ExpArtifact::bind(shard0, shard1) .unwrap_or_else(|error| panic!("pinned Qwen artifact binding failed: {error}")); - let binding = ModelBinding::from_artifact(artifact) - .unwrap_or_else(|_| panic!("pinned runtime binding failed")); + let binding = ModelBinding::from_artifact(artifact).unwrap_or_else(|_| panic!("pinned runtime binding failed")); let driver = Driver::load().unwrap_or_else(|_| panic!("CUDA driver load failed")); - let device = driver - .device(0) - .unwrap_or_else(|_| panic!("CUDA device selection failed")); - let context = device - .create_context(64 * 1024 * 1024) - .unwrap_or_else(|_| panic!("CUDA context creation failed")); + let device = driver.device(0).unwrap_or_else(|_| panic!("CUDA device selection failed")); + let context = device.create_context(64 * 1024 * 1024).unwrap_or_else(|_| panic!("CUDA context creation failed")); let context = Rc::new(context); let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let token = TokenId::new(0, Dimension::new(248_320).unwrap()).unwrap(); let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); let identity = binding.identity(); - assert_eq!( - QwenForward::step(&binding, token, position, &mut session), - Err(Error::Unsupported(Stage::Output)) - ); + assert_eq!(QwenForward::step(&binding, token, position, &mut session), Err(Error::Unsupported(Stage::Output))); // Verify rollback in a no-GPU transaction at the same position. The // deliberate error keeps this inspection transaction unpublished. @@ -120,11 +93,7 @@ fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() { use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; use std::{env, path::PathBuf, rc::Rc}; - let path = |name| { - env::var_os(name) - .map(PathBuf::from) - .expect("missing pinned test path") - }; + let path = |name| env::var_os(name).map(PathBuf::from).expect("missing pinned test path"); // Neither the supplied path nor the test can override the model identity. let shard0 = VerifiedGgufFile::open( &path("LELEKA_STRA169_IQ3S_SHARD0"), @@ -143,13 +112,8 @@ fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() { let driver = Driver::load().expect("CUDA driver load failed"); let device = driver.device(0).expect("CUDA device selection failed"); - let context = Rc::new( - device - .create_context(1024 * 1024 * 1024) - .expect("CUDA context creation failed"), - ); - let output = - OutputStage::load(&binding, context.as_ref()).expect("output head load failed"); + let context = Rc::new(device.create_context(1024 * 1024 * 1024).expect("CUDA context creation failed")); + let output = OutputStage::load(&binding, context.as_ref()).expect("output head load failed"); let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); let vocabulary = Dimension::new(248_320).unwrap(); let context_length = crate::qwen_forward::contract::position_dimension(); @@ -159,17 +123,10 @@ fn pinned_artifact_two_tokens_finish_all_layers_and_commit_state() { for (position, id) in [0, 1].into_iter().enumerate() { let token = TokenId::new(id, vocabulary).unwrap(); let position = Position::new(position as u64, context_length).unwrap(); - let greedy = - QwenForward::step_with_output(&binding, token, position, &mut session, &output) - .unwrap_or_else(|error| { - panic!("full forward at {} failed: {error:?}", position.get()) - }); + let greedy = QwenForward::step_with_output(&binding, token, position, &mut session, &output) + .unwrap_or_else(|error| panic!("full forward at {} failed: {error:?}", position.get())); assert!(greedy.get() < 248_320); - eprintln!( - "integration: 48 layers and finite head completed at {}, greedy={}", - position.get(), - greedy.get() - ); + eprintln!("integration: 48 layers and finite head completed at {}, greedy={}", position.get(), greedy.get()); } let identity = binding.identity(); let inspected = session.transact( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs index 13a70fb3..9d119a17 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mmq_evaluation.rs @@ -24,20 +24,13 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( use crate::qwen_forward::mtp_decode::MtpDecoder; let vocab = Dimension::new(248320).expect("vocabulary refused"); let bounds = crate::qwen_forward::contract::position_dimension(); - let ids: Vec<_> = [0, 1, 0, 1] - .into_iter() - .map(|n| TokenId::new(n, vocab).expect("fixed token refused")) - .collect(); + let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect(); let next = TokenId::new(0, vocab).expect("known next refused"); let follow = TokenId::new(1, vocab).expect("known successor refused"); - let fresh = session - .test_reset_replay_snapshot(binding) - .expect("fresh snapshot refused"); + let fresh = session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused"); - output - .test_reset_replay_record(true) - .expect("head observer refused"); + output.test_reset_replay_record(true).expect("head observer refused"); for index in 0..3 { let source = QwenForward::prefill_for_mtp_cached( binding, @@ -65,9 +58,7 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( Some(dense), ) .expect("scalar final target refused"); - let baseline_logits = output - .test_reset_replay_take_logits() - .expect("scalar head missing"); + let baseline_logits = output.test_reset_replay_take_logits().expect("scalar head missing"); let baseline_greedy = source.predicted(session).expect("scalar source invalid"); let baseline_streams: Vec<_> = source .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) @@ -75,13 +66,9 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( .iter() .map(|v| v.to_bits()) .collect(); - let baseline_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar state invalid"); + let baseline_state = session.test_reset_replay_snapshot(binding).expect("scalar state invalid"); let baseline_draft = scalar_draft.test_chunk_snapshot(); - scalar_draft - .warm_retained(binding, session, &source, next, moe) - .expect("scalar retained edge refused"); + scalar_draft.warm_retained(binding, session, &source, next, moe).expect("scalar retained edge refused"); let continuation = QwenForward::step_for_mtp_cached( binding, next, @@ -93,18 +80,10 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( Some(dense), ) .expect("scalar continuation refused"); - scalar_draft - .warm_retained(binding, session, &continuation, follow, moe) - .expect("scalar continuation warm refused"); - let continued_greedy = continuation - .predicted(session) - .expect("baseline continuation origin invalid"); - let continued_logits = output - .test_reset_replay_take_logits() - .expect("baseline continuation head missing"); - let continued_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar continuation state invalid"); + scalar_draft.warm_retained(binding, session, &continuation, follow, moe).expect("scalar continuation warm refused"); + let continued_greedy = continuation.predicted(session).expect("baseline continuation origin invalid"); + let continued_logits = output.test_reset_replay_take_logits().expect("baseline continuation head missing"); + let continued_state = session.test_reset_replay_snapshot(binding).expect("scalar continuation state invalid"); let continued_draft = scalar_draft.test_chunk_snapshot(); QwenForward::reset(session).expect("real owner reset refused"); let mut candidate_draft = MtpDecoder::new(binding).expect("candidate draft refused"); @@ -126,21 +105,10 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( callbacks == 16 }, ); - assert!( - matches!(aborted, Err(Error::Unsupported(Stage::Executor))), - "late-row cancellation not refused" - ); - let after_abort = session - .test_reset_replay_snapshot(binding) - .expect("abort snapshot refused"); - assert!( - fresh.numeric_eq(&after_abort), - "cancel changed committed target" - ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "cancel changed committed draft" - ); + assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused"); + let after_abort = session.test_reset_replay_snapshot(binding).expect("abort snapshot refused"); + assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target"); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "cancel changed committed draft"); // Real phase-local cancellation: the second MTP callback occurs after // the first actual private draft warm. Group routing changes the number // of earlier target callbacks, so no global callback ordinal is guessed. @@ -159,34 +127,21 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( || false, ChunkMoePolicy::ExperimentalResidentMmq, )?; - let _ready = - candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { - mtp_callbacks += 1; - mtp_callbacks == 2 - })?; + let _ready = candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { + mtp_callbacks += 1; + mtp_callbacks == 2 + })?; Err(Error::IdentityMismatch) })(); - assert!( - matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), - "actual MTP-row cancellation not refused" - ); - let discarded = output - .test_reset_replay_take_logits() - .expect("computed canceled head observation missing"); + assert!(matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), "actual MTP-row cancellation not refused"); + let discarded = output.test_reset_replay_take_logits().expect("computed canceled head observation missing"); assert_eq!(discarded.len(), 248320, "canceled full head extent changed"); drop(discarded); assert!( - fresh.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("MTP abort target invalid") - ), + fresh.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("MTP abort target invalid")), "MTP cancel changed committed target" ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "MTP cancel changed committed draft" - ); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "MTP cancel changed committed draft"); let before_dispatch = moe.test_mmq_dispatch_witness(); let actual = QwenForward::prefill_chunk_mmq_joint( binding, @@ -211,27 +166,15 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( resident_layers > 0 && resident_columns > 0, "candidate completed without any actual resident MMQ producer" ); - assert_eq!( - resident_layers + native_fallback_layers, - 48, - "candidate layer producer coverage incomplete" - ); - let actual_logits = output - .test_reset_replay_take_logits() - .expect("chunk head missing"); - let mismatch_words = baseline_logits - .iter() - .zip(actual_logits.iter()) - .filter(|(a, b)| a != b) - .count(); + assert_eq!(resident_layers + native_fallback_layers, 48, "candidate layer producer coverage incomplete"); + let actual_logits = output.test_reset_replay_take_logits().expect("chunk head missing"); + let mismatch_words = baseline_logits.iter().zip(actual_logits.iter()).filter(|(a, b)| a != b).count(); let max_abs = baseline_logits .iter() .zip(actual_logits.iter()) .map(|(a, b)| (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs()) .fold(0.0f64, f64::max); - let actual_greedy = actual - .predicted(session) - .expect("MMQ current origin invalid"); + let actual_greedy = actual.predicted(session).expect("MMQ current origin invalid"); eprintln!( "resident MMQ model observation rows=4 fullhead_words=248320 mismatches={} max_abs={} greedy_equal={} baseline_greedy={} candidate_greedy={}; tensor equality reported; GateC remains unqualified", mismatch_words, @@ -241,32 +184,15 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( actual_greedy.get() ); let head_exact = baseline_logits.as_ref() == actual_logits.as_ref(); - assert_eq!( - baseline_greedy, - actual - .predicted(session) - .expect("chunk current origin invalid"), - "greedy mismatch" - ); - let actual_streams = actual - .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) - .expect("chunk residual invalid"); - let residual_exact = baseline_streams - .iter() - .zip(actual_streams.iter()) - .all(|(a, b)| *a == b.to_bits()); - let target_exact = baseline_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk state invalid"), - ); + assert_eq!(baseline_greedy, actual.predicted(session).expect("chunk current origin invalid"), "greedy mismatch"); + let actual_streams = + actual.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session).expect("chunk residual invalid"); + let residual_exact = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits()); + let target_exact = + baseline_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk state invalid")); let draft_exact = candidate_draft.test_chunk_eq(&baseline_draft); - candidate_draft - .validate_resume(binding, session, &actual, &[0, 1, 0, 1]) - .expect("chunk resume fence refused"); - candidate_draft - .warm_retained(binding, session, &actual, next, moe) - .expect("chunk retained edge refused"); + candidate_draft.validate_resume(binding, session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused"); + candidate_draft.warm_retained(binding, session, &actual, next, moe).expect("chunk retained edge refused"); let continuation = QwenForward::step_for_mtp_cached( binding, next, @@ -281,18 +207,11 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( candidate_draft .warm_retained(binding, session, &continuation, follow, moe) .expect("chunk continuation warm refused"); - let actual_continued_greedy = continuation - .predicted(session) - .expect("candidate continuation origin invalid"); - let actual_continued_logits = output - .test_reset_replay_take_logits() - .expect("candidate continuation head missing"); + let actual_continued_greedy = continuation.predicted(session).expect("candidate continuation origin invalid"); + let actual_continued_logits = output.test_reset_replay_take_logits().expect("candidate continuation head missing"); let continued_head_exact = continued_logits.as_ref() == actual_continued_logits.as_ref(); - let continued_target_exact = continued_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk continuation invalid"), - ); + let continued_target_exact = + continued_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk continuation invalid")); eprintln!( "resident MMQ model observation continuation_greedy_equal={} head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={}", continued_greedy == actual_continued_greedy, @@ -303,14 +222,9 @@ pub(in crate::qwen_forward) fn check_mmq_on_loaded<'driver>( continued_head_exact, continued_target_exact ); - assert_eq!( - continued_greedy, actual_continued_greedy, - "MMQ continuation greedy mismatch" - ); + assert_eq!(continued_greedy, actual_continued_greedy, "MMQ continuation greedy mismatch"); let continued_draft_exact = candidate_draft.test_chunk_eq(&continued_draft); - output - .test_reset_replay_record(false) - .expect("head observer did not drain"); + output.test_reset_replay_record(false).expect("head observer did not drain"); eprintln!( "resident MMQ bounded greedy GateB PASS rows=4 layers=48 actual_final_outputs=2 logit_words=248320 final_head_exact={} residual_exact={} target_exact={} draft_exact={} continued_head_exact={} continued_target_exact={} continued_draft_exact={} early_cancelled_prefix_unchanged=true canceled_actual_mtp_warm=true actual_q6_attention_columns=true actual_ffn_gr_batch=true actual_resident_mmq=true resident_layers={} resident_columns={} native_fallback_layers={} experimental=true GateC=false longcontext=false speed_claim=false", head_exact, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs index df99a642..5d259118 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_mtp_window.rs @@ -27,12 +27,8 @@ impl VerifiedDraftPublication for ReadyVerifiedDraft<'_, '_> { { return Err(Error::IdentityMismatch); } - let end = self - .start - .checked_add(self.warmed as u64) - .ok_or(Error::Overflow)?; - self.stage - .validate_completed(self.binding, txn.original_session()?, end) + let end = self.start.checked_add(self.warmed as u64).ok_or(Error::Overflow)?; + self.stage.validate_completed(self.binding, txn.original_session()?, end) } fn publish(self) { self.stage.publish(); @@ -47,9 +43,13 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { /// residual is returned as the next current source; its draft warm belongs /// to the following window. Tail draft states are never computed/published. pub(in crate::qwen_forward) fn publish_joint( - self, binding:&ModelBinding, draft:&mut MtpSession, cache:&MoeWeightCache<'_>, cancelled:impl FnMut()->bool, - )->Result{ - self.publish_joint_with_gdn_replay(binding,draft,cache,None,cancelled) + self, + binding: &ModelBinding, + draft: &mut MtpSession, + cache: &MoeWeightCache<'_>, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.publish_joint_with_gdn_replay(binding, draft, cache, None, cancelled) } pub(in crate::qwen_forward) fn publish_joint_with_gdn_replay( mut self, @@ -64,14 +64,13 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { return Err(Error::Unsupported(Stage::Executor)); } if self.txn.device_gdn_lease()?.is_some() { - let dense=dense.ok_or(Error::IdentityMismatch)?; - self.txn.seal_device_gdn_prefix(binding,dense,&self.prefix,&mut cancelled)?; + let dense = dense.ok_or(Error::IdentityMismatch)?; + self.txn.seal_device_gdn_prefix(binding, dense, &self.prefix, &mut cancelled)?; } let start = self.txn.start_position(); let count = self.prefix.count(); let mut rows = Vec::new(); - rows.try_reserve_exact(count - 1) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(count - 1).map_err(|_| Error::InputAllocation)?; rows.extend(self.txn.rows().iter().take(count - 1).cloned()); if rows.len().checked_add(1) != Some(count) { return Err(Error::IdentityMismatch); @@ -84,9 +83,7 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { return Err(Error::Unsupported(Stage::Executor)); } let (_, position, next, _) = self.txn.validate_row(row)?; - if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? - || next.is_none() - { + if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? || next.is_none() { return Err(Error::IdentityMismatch); } mtp::warm_chunk_row(binding, &mut self.txn, row, &mut stage, cache)?; @@ -94,24 +91,12 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let ready = ReadyVerifiedDraft { - stage, - binding, - start, - count, - warmed: rows.len(), - }; - self.txn - .publish_verified_joint(self.prefix, ready)? - .into_target_product() - .ok_or(Error::IdentityMismatch) + let ready = ReadyVerifiedDraft { stage, binding, start, count, warmed: rows.len() }; + self.txn.publish_verified_joint(self.prefix, ready)?.into_target_product().ok_or(Error::IdentityMismatch) } } // Descending bounded admission, never a numeric/identity/poison retry. -fn legal_target_rows( - limit: usize, - mut preflight: impl FnMut(usize) -> Result<()>, -) -> Result { +fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()>) -> Result { if !(1..=4).contains(&limit) { return Err(Error::InvalidDimension); } @@ -136,9 +121,7 @@ impl QwenForward { host_remaining: usize, ) -> Result { QwenChunkTxn::validate_verification_source(binding, source, eos, target)?; - legal_target_rows(limit, |rows| { - QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining) - }) + legal_target_rows(limit, |rows| QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining)) } /// Explicit source-only candidate. Preserves Native/scalar MTP/defaults. @@ -169,12 +152,7 @@ impl QwenForward { return Err(Error::Unsupported(Stage::Executor)); } // Refuse the complete journal charge before cache/provider growth. - QwenChunkTxn::preflight_mtp_verification( - session, - binding, - proposals.len(), - host_remaining, - )?; + QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), host_remaining)?; let txn = Self::prepare_prefill_chunk_with_policy_windowed( binding, proposals, @@ -208,35 +186,14 @@ mod caller_admission_tests { assert_eq!( legal_target_rows(4, |rows| { attempts.push(rows); - if rows == 3 { - Err(Error::InputAllocation) - } else { - Ok(()) - } + if rows == 3 { Err(Error::InputAllocation) } else { Ok(()) } }), Ok(2) ); assert_eq!(attempts, [3, 2]); - assert_eq!( - legal_target_rows(3, |rows| { - if rows > 1 { - Err(Error::InvalidPosition) - } else { - Ok(()) - } - }), - Ok(1) - ); - assert_eq!( - legal_target_rows(0, |_| panic!("invalid limit must not preflight")), - Err(Error::InvalidDimension) - ); - for error in [ - Error::CudaExecution, - Error::IdentityMismatch, - Error::NonFinite, - Error::Overflow, - ] { + assert_eq!(legal_target_rows(3, |rows| { if rows > 1 { Err(Error::InvalidPosition) } else { Ok(()) } }), Ok(1)); + assert_eq!(legal_target_rows(0, |_| panic!("invalid limit must not preflight")), Err(Error::InvalidDimension)); + for error in [Error::CudaExecution, Error::IdentityMismatch, Error::NonFinite, Error::Overflow] { let mut calls = 0; assert_eq!( legal_target_rows(4, |_| { @@ -247,9 +204,6 @@ mod caller_admission_tests { ); assert_eq!(calls, 1); } - assert_eq!( - legal_target_rows(3, |_| Err(Error::InputAllocation)), - Err(Error::InputAllocation) - ); + assert_eq!(legal_target_rows(3, |_| Err(Error::InputAllocation)), Err(Error::InputAllocation)); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs index 262bd3ec..cc0be951 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_native_mmq_evaluation.rs @@ -12,25 +12,11 @@ pub(crate) struct HeadObservation { impl HeadObservation { fn new(baseline: &[u32], candidate: &[u32], a: TokenId, b: TokenId) -> Self { assert_eq!(baseline.len(), 248320, "baseline full head extent changed"); - assert_eq!( - candidate.len(), - 248320, - "candidate full head extent changed" - ); - assert!( - baseline - .iter() - .chain(candidate) - .all(|v| f32::from_bits(*v).is_finite()), - "nonfinite full head" - ); + assert_eq!(candidate.len(), 248320, "candidate full head extent changed"); + assert!(baseline.iter().chain(candidate).all(|v| f32::from_bits(*v).is_finite()), "nonfinite full head"); Self { words: baseline.len(), - different: baseline - .iter() - .zip(candidate) - .filter(|(a, b)| a != b) - .count(), + different: baseline.iter().zip(candidate).filter(|(a, b)| a != b).count(), max_abs: baseline .iter() .zip(candidate) @@ -79,20 +65,13 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( use crate::qwen_forward::mtp_decode::MtpDecoder; let vocab = Dimension::new(248320).expect("vocabulary refused"); let bounds = crate::qwen_forward::contract::position_dimension(); - let ids: Vec<_> = [0, 1, 0, 1] - .into_iter() - .map(|n| TokenId::new(n, vocab).expect("fixed token refused")) - .collect(); + let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect(); let next = TokenId::new(0, vocab).expect("known next refused"); let follow = TokenId::new(1, vocab).expect("known successor refused"); - let fresh = session - .test_reset_replay_snapshot(binding) - .expect("fresh snapshot refused"); + let fresh = session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused"); - output - .test_reset_replay_record(true) - .expect("head observer refused"); + output.test_reset_replay_record(true).expect("head observer refused"); for index in 0..3 { let source = QwenForward::prefill_for_mtp_cached( binding, @@ -120,9 +99,7 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( Some(dense), ) .expect("scalar final target refused"); - let baseline_logits = output - .test_reset_replay_take_logits() - .expect("scalar head missing"); + let baseline_logits = output.test_reset_replay_take_logits().expect("scalar head missing"); let baseline_greedy = source.predicted(session).expect("scalar source invalid"); let baseline_streams: Vec<_> = source .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) @@ -130,13 +107,9 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( .iter() .map(|v| v.to_bits()) .collect(); - let baseline_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar state invalid"); + let baseline_state = session.test_reset_replay_snapshot(binding).expect("scalar state invalid"); let baseline_draft = scalar_draft.test_chunk_snapshot(); - scalar_draft - .warm_retained(binding, session, &source, next, moe) - .expect("scalar retained edge refused"); + scalar_draft.warm_retained(binding, session, &source, next, moe).expect("scalar retained edge refused"); let continuation = QwenForward::step_for_mtp_cached( binding, next, @@ -148,18 +121,10 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( Some(dense), ) .expect("scalar continuation refused"); - scalar_draft - .warm_retained(binding, session, &continuation, follow, moe) - .expect("scalar continuation warm refused"); - let continued_greedy = continuation - .predicted(session) - .expect("baseline continuation origin invalid"); - let continued_logits = output - .test_reset_replay_take_logits() - .expect("baseline continuation head missing"); - let continued_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar continuation state invalid"); + scalar_draft.warm_retained(binding, session, &continuation, follow, moe).expect("scalar continuation warm refused"); + let continued_greedy = continuation.predicted(session).expect("baseline continuation origin invalid"); + let continued_logits = output.test_reset_replay_take_logits().expect("baseline continuation head missing"); + let continued_state = session.test_reset_replay_snapshot(binding).expect("scalar continuation state invalid"); let continued_draft = scalar_draft.test_chunk_snapshot(); QwenForward::reset(session).expect("real owner reset refused"); let mut candidate_draft = MtpDecoder::new(binding).expect("candidate draft refused"); @@ -181,21 +146,10 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( callbacks == 16 }, ); - assert!( - matches!(aborted, Err(Error::Unsupported(Stage::Executor))), - "late-row cancellation not refused" - ); - let after_abort = session - .test_reset_replay_snapshot(binding) - .expect("abort snapshot refused"); - assert!( - fresh.numeric_eq(&after_abort), - "cancel changed committed target" - ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "cancel changed committed draft" - ); + assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused"); + let after_abort = session.test_reset_replay_snapshot(binding).expect("abort snapshot refused"); + assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target"); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "cancel changed committed draft"); // Real phase-local cancellation: the second MTP callback occurs after // the first actual private draft warm. Group routing changes the number // of earlier target callbacks, so no global callback ordinal is guessed. @@ -214,34 +168,21 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( || false, ChunkMoePolicy::ExperimentalResidentMmq, )?; - let _ready = - candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { - mtp_callbacks += 1; - mtp_callbacks == 2 - })?; + let _ready = candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { + mtp_callbacks += 1; + mtp_callbacks == 2 + })?; Err(Error::IdentityMismatch) })(); - assert!( - matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), - "actual MTP-row cancellation not refused" - ); - let discarded = output - .test_reset_replay_take_logits() - .expect("computed canceled head observation missing"); + assert!(matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), "actual MTP-row cancellation not refused"); + let discarded = output.test_reset_replay_take_logits().expect("computed canceled head observation missing"); assert_eq!(discarded.len(), 248320, "canceled full head extent changed"); drop(discarded); assert!( - fresh.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("MTP abort target invalid") - ), + fresh.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("MTP abort target invalid")), "MTP cancel changed committed target" ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "MTP cancel changed committed draft" - ); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "MTP cancel changed committed draft"); let before_dispatch = moe.test_mmq_dispatch_witness(); let actual = QwenForward::prefill_chunk_mmq_joint( binding, @@ -266,37 +207,18 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( resident_layers > 0 && resident_columns > 0, "candidate completed without any actual resident MMQ producer" ); - assert_eq!( - resident_layers + native_fallback_layers, - 48, - "candidate layer producer coverage incomplete" - ); - let actual_logits = output - .test_reset_replay_take_logits() - .expect("chunk head missing"); - let actual_greedy = actual - .predicted(session) - .expect("MMQ current origin invalid"); + assert_eq!(resident_layers + native_fallback_layers, 48, "candidate layer producer coverage incomplete"); + let actual_logits = output.test_reset_replay_take_logits().expect("chunk head missing"); + let actual_greedy = actual.predicted(session).expect("MMQ current origin invalid"); let head_exact = baseline_logits.as_ref() == actual_logits.as_ref(); - let actual_streams = actual - .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) - .expect("chunk residual invalid"); - let residual_exact = baseline_streams - .iter() - .zip(actual_streams.iter()) - .all(|(a, b)| *a == b.to_bits()); - let target_exact = baseline_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk state invalid"), - ); + let actual_streams = + actual.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session).expect("chunk residual invalid"); + let residual_exact = baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits()); + let target_exact = + baseline_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk state invalid")); let draft_exact = candidate_draft.test_chunk_eq(&baseline_draft); - candidate_draft - .validate_resume(binding, session, &actual, &[0, 1, 0, 1]) - .expect("chunk resume fence refused"); - candidate_draft - .warm_retained(binding, session, &actual, next, moe) - .expect("chunk retained edge refused"); + candidate_draft.validate_resume(binding, session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused"); + candidate_draft.warm_retained(binding, session, &actual, next, moe).expect("chunk retained edge refused"); let continuation = QwenForward::step_for_mtp_cached( binding, next, @@ -311,29 +233,15 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>( candidate_draft .warm_retained(binding, session, &continuation, follow, moe) .expect("chunk continuation warm refused"); - let actual_continued_greedy = continuation - .predicted(session) - .expect("candidate continuation origin invalid"); - let actual_continued_logits = output - .test_reset_replay_take_logits() - .expect("candidate continuation head missing"); + let actual_continued_greedy = continuation.predicted(session).expect("candidate continuation origin invalid"); + let actual_continued_logits = output.test_reset_replay_take_logits().expect("candidate continuation head missing"); let continued_head_exact = continued_logits.as_ref() == actual_continued_logits.as_ref(); - let continued_target_exact = continued_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk continuation invalid"), - ); + let continued_target_exact = + continued_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk continuation invalid")); let continued_draft_exact = candidate_draft.test_chunk_eq(&continued_draft); - output - .test_reset_replay_record(false) - .expect("head observer did not drain"); + output.test_reset_replay_record(false).expect("head observer did not drain"); NativeMmqReport { - final_head: HeadObservation::new( - &baseline_logits, - &actual_logits, - baseline_greedy, - actual_greedy, - ), + final_head: HeadObservation::new(&baseline_logits, &actual_logits, baseline_greedy, actual_greedy), continuation_head: HeadObservation::new( &continued_logits, &actual_continued_logits, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs index c0ef3916..77b4887c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt.rs @@ -1,60 +1,89 @@ //! Whole layer-major Original prefill on one actual affine arena. The target //! result stays pending until the real MTP forward owner joins publication. //! This is an unselected source port, not a serving qualification. -use super::*; -use super::super::{dense_weight_cache::DenseWeightCache,moe_weight_cache::{MoeWeightCache,RetainedOriginalMtpWeights}}; -use super::super::prompt_device_rows::{PromptDeviceSource,PromptDeviceRows,PromptDeviceNormedRows,PromptDeviceFinal}; -use super::super::session::original_prompt::{OriginalPromptTxn,OriginalSessionCheckpoint,OriginalPromptInput,ParkedSession,ParkedBlock}; -use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaLayer,ResidentQsaPrior}; +use super::super::original_mtp_full_owner::{ + OriginalMtpFullAssembly, OriginalMtpFullOwner, OriginalMtpLoadError, OriginalMtpRequest, +}; use super::super::output::OriginalPromptSample; -use super::super::session::original_prompt::draft::{OriginalDraftSession,OriginalDraftCheckpoint}; use super::super::output_native::OriginalNativeOutput; -use super::super::original_mtp_full_owner::{OriginalMtpFullAssembly,OriginalMtpFullOwner,OriginalMtpLoadError,OriginalMtpRequest}; -use super::super::prompt_device_rows::{OriginalDraftKvPending,OriginalPromptDraftOutcome}; -#[path="original_prompt_embedding.rs"] +use super::super::prompt_device_rows::{OriginalDraftKvPending, OriginalPromptDraftOutcome}; +use super::super::prompt_device_rows::{ + PromptDeviceFinal, PromptDeviceNormedRows, PromptDeviceRows, PromptDeviceSource, +}; +use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaLayer, ResidentQsaPrior}; +use super::super::session::original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}; +use super::super::session::original_prompt::{ + OriginalPromptInput, OriginalPromptTxn, OriginalSessionCheckpoint, ParkedBlock, ParkedSession, +}; +use super::super::{ + dense_weight_cache::DenseWeightCache, + moe_weight_cache::{MoeWeightCache, RetainedOriginalMtpWeights}, +}; +use super::*; +#[path = "original_prompt_embedding.rs"] pub(in crate::qwen_forward) mod embedding; -use embedding::OriginalPromptEmbedding; -use super::super::prefill_profile::{self as prof,Stage as PStage}; use super::super::input::StagedInput; -use leleka_cuda_driver::{Context,OriginalPromptDevice,PromptInputStage,OriginalGdnPromptDevice,OriginalQsaResidentPromptDevice, - OriginalQsaResidentTransport,OriginalQsaResidentAttention,OriginalPrefillArena, - GrNativeProfile,PleBf16Mode,QsaNativePacking,OriginalMtpPrefill, - OriginalMtpScalarPrefill,OriginalMtpRetainedScalarWeights,OriginalMtpScalarPolicy}; +use super::super::prefill_profile::{self as prof, Stage as PStage}; +use embedding::OriginalPromptEmbedding; +use leleka_cuda_driver::{ + Context, GrNativeProfile, OriginalGdnPromptDevice, OriginalMtpPrefill, OriginalMtpRetainedScalarWeights, + OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalPrefillArena, OriginalPromptDevice, + OriginalQsaResidentAttention, OriginalQsaResidentPromptDevice, OriginalQsaResidentTransport, PleBf16Mode, + PromptInputStage, QsaNativePacking, +}; -pub(in crate::qwen_forward) struct OriginalPromptExecutor<'ctx>{ - pub(in crate::qwen_forward) context:&'ctx Context<'ctx>,binding:BindingIdentity,capacity:usize,fused:bool, - prompt:Option>,gdn:Option>, - qsa:Option>,transport:Option>, - attention:Option>, - mtp_prefill:Option>, - mtp_scalar:Option>, - mtp_scalar_weights:Option>>, - mtp_weights:Option>, +pub(in crate::qwen_forward) struct OriginalPromptExecutor<'ctx> { + pub(in crate::qwen_forward) context: &'ctx Context<'ctx>, + binding: BindingIdentity, + capacity: usize, + fused: bool, + prompt: Option>, + gdn: Option>, + qsa: Option>, + transport: Option>, + attention: Option>, + mtp_prefill: Option>, + mtp_scalar: Option>, + mtp_scalar_weights: Option>>, + mtp_weights: Option>, // Installed only through `install_full_mtp`: this full owner and the // returned draft session share the literal MtpDrafter physical ring. - mtp_full:Option>, - max_t:usize, - layers:[Option>;48],failed:bool, + mtp_full: Option>, + max_t: usize, + layers: [Option>; 48], + failed: bool, } -enum Carrier<'w,'arena,'loan,'ctx>{ - Plain(PromptDeviceRows<'static,'arena,'loan,'ctx>), - Normed(PromptDeviceNormedRows<'w,'static,'arena,'loan,'ctx>), +enum Carrier<'w, 'arena, 'loan, 'ctx> { + Plain(PromptDeviceRows<'static, 'arena, 'loan, 'ctx>), + Normed(PromptDeviceNormedRows<'w, 'static, 'arena, 'loan, 'ctx>), } /// Affine pending target. Discarding it restores the real physical accepted /// prefix; no public target-only commit can expose an unwarmed draft session. -pub(in crate::qwen_forward) struct OriginalPromptPending<'session,'program,'ctx>{ - txn:Option>,binding:&'program ModelBinding,dense:&'program DenseWeightCache<'ctx>, - layers:&'program mut[Option>;48],checkpoint:OriginalSessionCheckpoint<'ctx>, - failed:&'program mut bool, - completed:PromptDeviceFinal,sample:OriginalPromptSample,draft_kv:OriginalDraftKvPending, - draft:&'program mut OriginalDraftSession<'ctx>,draft_checkpoint:OriginalDraftCheckpoint, +pub(in crate::qwen_forward) struct OriginalPromptPending<'session, 'program, 'ctx> { + txn: Option>, + binding: &'program ModelBinding, + dense: &'program DenseWeightCache<'ctx>, + layers: &'program mut [Option>; 48], + checkpoint: OriginalSessionCheckpoint<'ctx>, + failed: &'program mut bool, + completed: PromptDeviceFinal, + sample: OriginalPromptSample, + draft_kv: OriginalDraftKvPending, + draft: &'program mut OriginalDraftSession<'ctx>, + draft_checkpoint: OriginalDraftCheckpoint, } /// The three prompt actions the batched path does not own (verifier windows, the final seed, session checkpoints). /// Defaults refuse: those belong to the Original Verifier / serving owner, which hands its own implementation in. pub(in crate::qwen_forward) trait OriginalPromptHooks { - fn verify_window(&mut self,_first:usize,_count:usize)->Result<()>{Err(Error::Unsupported(Stage::Session))} - fn final_seed(&mut self,_first:usize)->Result<()>{Err(Error::Unsupported(Stage::Session))} - fn checkpoint(&mut self,_end:usize)->Result<()>{Err(Error::Unsupported(Stage::Session))} + fn verify_window(&mut self, _first: usize, _count: usize) -> Result<()> { + Err(Error::Unsupported(Stage::Session)) + } + fn final_seed(&mut self, _first: usize) -> Result<()> { + Err(Error::Unsupported(Stage::Session)) + } + fn checkpoint(&mut self, _end: usize) -> Result<()> { + Err(Error::Unsupported(Stage::Session)) + } } /// Hooks that refuse everything except an all-batched plan. pub(in crate::qwen_forward) struct NoPromptHooks; @@ -62,34 +91,34 @@ pub(in crate::qwen_forward) struct NoPromptHooks; /// [`PromptPlan`](crate::backend::original_prompt::PromptPlan) is walked by `drive`; every `Batched` action is one /// real `OriginalPromptExecutor::forward` + `publish` transaction on the shared arena/session/draft, so the chunk loop /// of `Prefill::run` is the action sequence. This is an unselected source owner: nothing in `backend` constructs it. -pub(in crate::qwen_forward) struct OriginalPromptComposer<'a,'arena,'ctx>{ - pub executor:&'a mut OriginalPromptExecutor<'ctx>, - pub binding:&'a ModelBinding, - pub dense:&'a DenseWeightCache<'ctx>, - pub session:&'a mut QwenSession<'ctx>, - pub source:&'a std::rc::Rc, - pub kar:Option<&'a mut KarPleCache<'ctx>>, - pub moe:&'a mut MoeWeightCache<'ctx>, - pub arena:&'a mut OriginalPrefillArena<'arena,'ctx>, - pub draft:&'a mut OriginalDraftSession<'ctx>, - pub embedding:&'a OriginalPromptEmbedding<'ctx>, - pub policy:&'a OriginalMtpScalarPolicy, +pub(in crate::qwen_forward) struct OriginalPromptComposer<'a, 'arena, 'ctx> { + pub executor: &'a mut OriginalPromptExecutor<'ctx>, + pub binding: &'a ModelBinding, + pub dense: &'a DenseWeightCache<'ctx>, + pub session: &'a mut QwenSession<'ctx>, + pub source: &'a std::rc::Rc, + pub kar: Option<&'a mut KarPleCache<'ctx>>, + pub moe: &'a mut MoeWeightCache<'ctx>, + pub arena: &'a mut OriginalPrefillArena<'arena, 'ctx>, + pub draft: &'a mut OriginalDraftSession<'ctx>, + pub embedding: &'a OriginalPromptEmbedding<'ctx>, + pub policy: &'a OriginalMtpScalarPolicy, /// `should_stop` of the Original; also forwarded into every chunk's draft-KV recording. - pub cancel:&'a mut dyn FnMut()->bool, - pub hooks:&'a mut dyn OriginalPromptHooks, + pub cancel: &'a mut dyn FnMut() -> bool, + pub hooks: &'a mut dyn OriginalPromptHooks, /// The last chunk's publication (new origin and the known-next sample), for the caller's first decode window. - pub last_published:Option<(TargetStepOrigin,Option)>, + pub last_published: Option<(TargetStepOrigin, Option)>, } #[path = "executor_original_prompt/staged_input_enabled_fn.rs"] mod staged_input_enabled_fn; #[allow(unused_imports)] use staged_input_enabled_fn::staged_input_enabled; -#[path = "executor_original_prompt/impl_originalpromptexecutor.rs"] -mod impl_originalpromptexecutor; #[path = "executor_original_prompt/impl_drop_for_originalpromptexecutor.rs"] mod impl_drop_for_originalpromptexecutor; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use impl_drop_for_originalpromptexecutor::run_original_prompt; +#[path = "executor_original_prompt/impl_originalpromptexecutor.rs"] +mod impl_originalpromptexecutor; #[allow(unused_imports)] use impl_drop_for_originalpromptexecutor::driver_error; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use impl_drop_for_originalpromptexecutor::run_original_prompt; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs index 63e6ca35..dde7f0e1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_drop_for_originalpromptexecutor.rs @@ -3,56 +3,112 @@ #[allow(unused_imports)] use super::*; -impl Drop for OriginalPromptExecutor<'_>{fn drop(&mut self){let _=self.close_inner();}} -impl OriginalPromptPending<'_, '_, '_>{ +impl Drop for OriginalPromptExecutor<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +impl OriginalPromptPending<'_, '_, '_> { /// Any fallible publication leaves the owning transaction present so Drop /// restores both real physical accepted prefixes. Success consumes it. - pub(in crate::qwen_forward) fn publish(mut self)->Result<(TargetStepOrigin,Option)>{ - let result=self.txn.as_mut().ok_or(Error::IdentityMismatch)?.publish(self.binding,self.dense,self.layers, - &self.completed,self.draft,&self.draft_kv,&self.sample); - if result.is_ok(){self.txn.take();} + pub(in crate::qwen_forward) fn publish(mut self) -> Result<(TargetStepOrigin, Option)> { + let result = self.txn.as_mut().ok_or(Error::IdentityMismatch)?.publish( + self.binding, + self.dense, + self.layers, + &self.completed, + self.draft, + &self.draft_kv, + &self.sample, + ); + if result.is_ok() { + self.txn.take(); + } result } } -impl Drop for OriginalPromptPending<'_, '_, '_>{fn drop(&mut self){if let Some(txn)=self.txn.take(){ - if txn.abort_with_draft(self.binding,self.dense,self.layers,&self.checkpoint,self.draft,&self.draft_checkpoint).is_err(){*self.failed=true;} -}}} -impl OriginalPromptHooks for NoPromptHooks{} -impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_,'_,'_>{ - type Error=Error; - fn cancelled(&mut self)->bool{(self.cancel)()} - fn batched(&mut self,action:&crate::backend::original_prompt::PromptAction)->Result<()>{ +impl Drop for OriginalPromptPending<'_, '_, '_> { + fn drop(&mut self) { + if let Some(txn) = self.txn.take() { + if txn + .abort_with_draft( + self.binding, + self.dense, + self.layers, + &self.checkpoint, + self.draft, + &self.draft_checkpoint, + ) + .is_err() + { + *self.failed = true; + } + } + } +} +impl OriginalPromptHooks for NoPromptHooks {} +impl crate::backend::original_prompt::PromptRunner for OriginalPromptComposer<'_, '_, '_> { + type Error = Error; + fn cancelled(&mut self) -> bool { + (self.cancel)() + } + fn batched(&mut self, action: &crate::backend::original_prompt::PromptAction) -> Result<()> { // `resume`/`reread_to` are scheduler operands, never certificates: the chronological session must already be // exactly at the chunk's first position. - if self.session.target_origin()?.next_position()!=action.first as u64{return Err(Error::IdentityMismatch);} - let pending=self.executor.forward(self.binding,self.dense,&mut *self.session,self.source,action.count, - self.kar.as_deref_mut(),&mut *self.moe,&mut *self.arena,&mut *self.draft,self.embedding,self.policy,&mut *self.cancel)?; - self.last_published=Some(pending.publish()?); + if self.session.target_origin()?.next_position() != action.first as u64 { + return Err(Error::IdentityMismatch); + } + let pending = self.executor.forward( + self.binding, + self.dense, + &mut *self.session, + self.source, + action.count, + self.kar.as_deref_mut(), + &mut *self.moe, + &mut *self.arena, + &mut *self.draft, + self.embedding, + self.policy, + &mut *self.cancel, + )?; + self.last_published = Some(pending.publish()?); Ok(()) } - fn verify_window(&mut self,action:&crate::backend::original_prompt::PromptAction)->Result<()>{self.hooks.verify_window(action.first,action.count)} - fn final_seed(&mut self,action:&crate::backend::original_prompt::PromptAction)->Result<()>{self.hooks.final_seed(action.first)} - fn checkpoint(&mut self,end:usize)->Result<()>{self.hooks.checkpoint(end)} + fn verify_window(&mut self, action: &crate::backend::original_prompt::PromptAction) -> Result<()> { + self.hooks.verify_window(action.first, action.count) + } + fn final_seed(&mut self, action: &crate::backend::original_prompt::PromptAction) -> Result<()> { + self.hooks.final_seed(action.first) + } + fn checkpoint(&mut self, end: usize) -> Result<()> { + self.hooks.checkpoint(end) + } } /// Runs `plan` to its final seed through `composer`. `admitted_capacity` is the capacity the executor, arena and cache /// were built for. Cancellation maps to the same refusal `forward` returns when its draft recording is cancelled. -pub(in crate::qwen_forward) fn run_original_prompt(plan:crate::backend::original_prompt::PromptPlan<'_>, - admitted_capacity:usize,composer:&mut OriginalPromptComposer<'_,'_,'_>)->Result{ - use crate::backend::original_prompt::{drive,DriveError}; - drive(plan,admitted_capacity,composer).map_err(|e|match e{ - DriveError::Cancelled{..}=>Error::Unsupported(Stage::Session), - DriveError::Contract(_)=>Error::InvalidDimension, - DriveError::Runner(e)=>e, +pub(in crate::qwen_forward) fn run_original_prompt( + plan: crate::backend::original_prompt::PromptPlan<'_>, + admitted_capacity: usize, + composer: &mut OriginalPromptComposer<'_, '_, '_>, +) -> Result { + use crate::backend::original_prompt::{DriveError, drive}; + drive(plan, admitted_capacity, composer).map_err(|e| match e { + DriveError::Cancelled { .. } => Error::Unsupported(Stage::Session), + DriveError::Contract(_) => Error::InvalidDimension, + DriveError::Runner(e) => e, }) } -pub(super) fn driver_error(error:leleka_cuda_driver::Error)->Error{ - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} - match error{ - leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite, - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize=>Error::InvalidDimension, - leleka_cuda_driver::Error::UnsupportedQwenOperation=>Error::Unsupported(Stage::Session), - _=>Error::CudaExecution, +pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error { + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } + match error { + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + leleka_cuda_driver::Error::InvalidQwenShape | leleka_cuda_driver::Error::InvalidSize => Error::InvalidDimension, + leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(Stage::Session), + _ => Error::CudaExecution, } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs index 5dbb8ee8..8b9b48f8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2.rs @@ -3,227 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalPromptExecutor<'ctx>{ - /// Eager model/session owners precede expert prefix planning. The twelve - /// resident checkpoints are installed together only after all producers exist. - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>, - embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, - )->Result{ - // Pinned-pack source: the MoE cache already holds and charged the roles. - let retained=moe.retain_original_mtp_weights(binding,context)?; - Self::new_with_mtp_weights(binding,dense,session,context,retained,embedding,capacity,max_t,fused) - } - /// Same construction over any retained MTP role bank (the pinned pack, or - /// the Original-literal RT directory bank of `select_rt_mtp`). - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn new_with_mtp_weights(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,retained:RetainedOriginalMtpWeights<'ctx>, - embedding:&OriginalPromptEmbedding<'ctx>,capacity:usize,max_t:usize,fused:bool, - )->Result{ - if binding.layer_count()!=48||!(1..=8192).contains(&capacity)||!(1..=8).contains(&max_t) - ||dense.native_prompt_capacity(binding,context)?!=capacity - ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - let mut owner=Self{context,binding:binding.identity(),capacity,fused,prompt:None,gdn:None,qsa:None, - transport:None,attention:None,mtp_prefill:None,mtp_scalar:None,mtp_scalar_weights:None, - mtp_weights:None,mtp_full:None,max_t,layers:std::array::from_fn(|_|None),failed:false}; - let result=(||{ - owner.prompt=Some(context.original_prompt_device(capacity,PleBf16Mode::HighOnly,GrNativeProfile::HighOnly).map_err(driver_error)?); - owner.gdn=Some(context.original_gdn_prompt_device(capacity,GrNativeProfile::HighOnly).map_err(driver_error)?); - owner.qsa=Some(context.original_qsa_resident_prompt_device(capacity,QsaNativePacking::HighOnly).map_err(driver_error)?); - owner.transport=Some(context.original_qsa_resident_transport().map_err(driver_error)?); - owner.attention=Some(context.original_qsa_resident_attention(capacity).map_err(driver_error)?); - owner.mtp_prefill=Some(context.original_mtp_prefill().map_err(driver_error)?); - owner.mtp_scalar_weights=Some(retained.scalar_prefill_weights(binding,context,embedding)?); - owner.mtp_weights=Some(retained); - owner.mtp_scalar=Some(context.original_mtp_scalar_prefill(max_t,capacity).map_err(driver_error)?); - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - for layer in binding.ordered_layers(){if layer.kind()==BoundLayerKind::Qsa{ - let id=LayerId::new(layer.index()as u64,Dimension::new(48)?)?; - let empty=session.original_qsa_seed(binding,id)?; - let index=context.original_qsa_resident_index().map_err(driver_error)?; - let kv=context.qsa_prompt_kv().map_err(driver_error)?.into_original_mapped_journal().map_err(driver_error)?; - owner.layers[layer.index()as usize]=Some(ResidentQsaLayer::new(binding,dense,session,&empty,index,kv,&mut workspace)?); - }} - drop(workspace); - let priors=std::array::from_fn(|slot|owner.layers[slot].as_ref().map(ResidentQsaLayer::current)); - session.install_original_qsa_seed_set(binding,priors)?;Ok(()) - })(); - if let Err(primary)=result{let _=owner.close_inner();return Err(primary);} - Ok(owner) - } - /// The immutable MTP roles this executor retains (the RT bank's on the product path). - pub(in crate::qwen_forward) fn retained_mtp_weights(&self)->Option<&RetainedOriginalMtpWeights<'ctx>>{self.mtp_weights.as_ref()} - /// Joins the source-created full MTP graph owner to this exact prompt - /// executor. The draft session is validated against the same target - /// session before it leaves the assembly, so callers cannot pair a full - /// graph with a separately allocated MTP ring. - pub(in crate::qwen_forward) fn install_full_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,assembly:OriginalMtpFullAssembly<'ctx>)->Result>{ - if self.failed||self.context.is_poisoned()||!self.binding.matches(&binding.identity()) - ||!std::ptr::eq(self.context,session.mtp_context()?)||self.mtp_full.is_some(){return Err(Error::IdentityMismatch);} - assembly.draft.checkpoint(binding,session)?; - assembly.owner.validate(binding,self.context,self.max_t)?; - self.mtp_full=Some(assembly.owner); - Ok(assembly.draft) - } - /// Source-level MTP selection, the `--mtp DIR` branch of generate.cpp - /// (`mtp.load` ... `mtp.bind`): load the RT directory banks (dense.txt, - /// dense.bin, experts.bin, nine-name check), build the prompt executor over - /// those exact retained roles, then bind the native head (optional - /// draft_vocab subset), the shared scalar/full/ring layout, the coupled - /// setup and the actor, and install the matching draft session. - /// - /// Returns both owners; the draft session is the sole mutator of the - /// ring, the executor holds the actor. Any failure releases everything - /// built so far through the owners' own closure order. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn select_rt_mtp(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,context:&'ctx Context<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - output:&OriginalNativeOutput<'ctx>,rt_directory:&std::path::Path,capacity:usize,fused:bool, - request:&OriginalMtpRequest)->std::result::Result<(Self,OriginalDraftSession<'ctx>),OriginalMtpLoadError>{ - if !(1..=8).contains(&request.max_t)||request.prompt_capacity!=capacity||binding.layer_count()!=48{ - return Err(Error::IdentityMismatch.into());} - let bank=context.original_mtp_rt_bank(rt_directory,binding.expert_count() as usize)?; - let retained=RetainedOriginalMtpWeights::from_rt_bank(binding,context,&bank)?; - // The bank object is only a loader receipt: every allocation it holds is - // shared with (or retained alongside) `retained`. - drop(bank); - let mut executor=Self::new_with_mtp_weights(binding,dense,session,context,retained.clone(),embedding, - capacity,request.max_t,fused)?; - let assembly=OriginalMtpFullOwner::assemble_rt(binding,session,context,&retained,embedding,output,request,rt_directory)?; - let draft=executor.install_full_mtp(binding,session,assembly)?; - Ok((executor,draft)) - } - /// The loaded `MtpDrafter` of this executor. The caller still borrows the - /// ring through the draft session (`with_pending_ring`, - /// `with_mtp_transition_ring`), which keeps SessionState as the sole mutable - /// authority for its snapshot. - pub(in crate::qwen_forward) fn mtp_actor(&mut self,binding:&ModelBinding) - ->Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>>{ - let(context,max_t)=(self.context,self.max_t); - self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t) - } - /// generate.cpp `mtp.set_prompt_len(n)`. - pub(in crate::qwen_forward) fn set_mtp_prompt_len(&mut self,binding:&ModelBinding,n:i64)->Result<()> { - self.mtp_actor(binding)?.set_prompt_len(n);Ok(()) - } - /// generate.cpp `mtp.set_max_drafts(S_mtp - 1)`. - pub(in crate::qwen_forward) fn set_mtp_max_drafts(&mut self,binding:&ModelBinding,k:i32)->Result<()> { - self.mtp_actor(binding)?.set_max_drafts(k);Ok(()) - } - /// `MtpDrafter::idle()`: drain its own capture stream, nothing else. - pub(in crate::qwen_forward) fn mtp_idle(&mut self,binding:&ModelBinding)->Result<()> { - self.mtp_actor(binding)?.idle().map_err(driver_error) - } - /// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round programs read the - /// bank's final-R span and its tail keeps the last staged window), so the bank can close and the next request's first draft - /// captures against its own bank. See `OriginalMtpActor::release_verifier_bindings`. - pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self,binding:&ModelBinding)->Result<()> { - self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error) - } - /// `MtpDrafter::device()`. - pub(in crate::qwen_forward) fn mtp_device(&mut self,binding:&ModelBinding)->Result { - Ok(self.mtp_actor(binding)?.device()) - } - /// generate.cpp `if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume)` - /// on the retained ring of the CURRENT, already restored target branch. - pub(in crate::qwen_forward) fn mtp_kv_restore(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,upto:i64)->Result<()> { - let origin=session.target_origin()?; - let actor=self.mtp_actor(binding)?; - draft.with_mtp_current_ring(binding,session,&origin,|ring,prior|actor.kv_restore(ring,prior,upto).map_err(driver_error)) - } - /// One-way handoff of the twelve resident QSA layers (index image + mapped K/V) to the native - /// verifier for a decode phase. All twelve are validated before any is moved, so a refusal leaves the - /// executor whole. While the owners are out the executor cannot run a prompt transaction; `adopt_qsa_owners` - /// takes the very same physical owners back. - #[allow(clippy::type_complexity)] - pub(in crate::qwen_forward) fn take_qsa_owners(&mut self)->Result<[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, - leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - for layer in self.layers.iter().flatten(){layer.check_handoff()?;} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - let mut owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>,leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48]= - std::array::from_fn(|_|None); - for(slot,layer)in self.layers.iter_mut().enumerate(){if let Some(layer)=layer.take(){ - // the session keeps the lineage prior; only the physical owners travel - let(index,kv,_prior)=layer.into_verifier_owners()?;owners[slot]=Some((index,kv)); - }} - Ok(owners) - } - /// The reverse of `take_qsa_owners`, after the verifier closed and its journal returned the owners. - /// Each layer is rebuilt at the session's current lineage witness and its physical image rolled back to - /// it (a no-op copy when the last window committed; the repair when a window was abandoned). The - /// roll-back mints a fresh witness object per layer for the SAME lineage, so the session adopts those - /// objects before the layers can be used again (a layer and the session must name one witness). - #[allow(clippy::type_complexity)] - pub(in crate::qwen_forward) fn adopt_qsa_owners(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,owners:[Option<(leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, - leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>)>;48])->Result<()>{ - if self.failed||self.context.is_poisoned()||self.layers.iter().any(Option::is_some){return Err(Error::IdentityMismatch);} - let witnesses=session.original_qsa_witnesses()?; - let context=dense.retained_context(binding,session.mtp_context()?)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let mut first=None; - for(slot,owner)in owners.into_iter().enumerate(){if let Some((index,kv))=owner{ - let rebuilt=witnesses[slot].clone().ok_or(Error::IdentityMismatch).and_then(|prior| - ResidentQsaLayer::from_verifier_owners(binding,dense,session,index,kv,prior,&mut workspace)); - match rebuilt{Ok(layer)=>self.layers[slot]=Some(layer),Err(error)=>{first.get_or_insert(error);}} - }} - drop(workspace); - if let Some(error)=first{self.failed=true;return Err(error);} - let current:[Option>;48]=std::array::from_fn(|slot|self.layers[slot].as_ref().map(ResidentQsaLayer::current)); - let adopted=session.adopt_original_qsa_witnesses(current); - if adopted.is_err(){self.failed=true;} - adopted - } - /// The session's Original checkpoint (position, predecessors, PLE/GDN priors and the twelve resident QSA - /// witnesses). Refused while the recurrent priors lag a verified-window publication. - pub(in crate::qwen_forward) fn checkpoint_session(&mut self,binding:&ModelBinding, - session:&mut QwenSession<'ctx>)->Result>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.original_checkpoint(binding) - } - /// Prefix cache: park the point the session stands at (see `ParkedSession`). - pub(in crate::qwen_forward) fn park_session(&mut self,binding:&ModelBinding, - session:&mut QwenSession<'ctx>)->Result{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.park_original(binding,&self.layers) - } - /// Prefix cache: the cells `first..first + tokens` of the twelve layers as plain bytes. - pub(in crate::qwen_forward) fn park_block(&self,session:&QwenSession<'ctx>,first:usize,tokens:usize)->Result{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if self.layers.iter().flatten().count()!=12{return Err(Error::IdentityMismatch);} - session.park_block(&self.layers,first,tokens) - } - /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons - /// the executor, as for `restore_session`. - pub(in crate::qwen_forward) fn import_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - let imported=session.import_parked(binding,dense,&mut self.layers,parked,blocks); - if imported.is_err(){self.failed=true;} - imported - } - /// Roll the session AND the twelve physical resident layers back to `checkpoint` (a request reset to the - /// empty prompt, or an abandoned prompt transaction). A failure poisons the executor. - pub(in crate::qwen_forward) fn restore_session(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&mut QwenSession<'ctx>,checkpoint:&OriginalSessionCheckpoint<'ctx>)->Result<()>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - let restored=session.restore_original_checkpoint(binding,dense,&mut self.layers,checkpoint); - if restored.is_err(){self.failed=true;} - restored - } - /// Whether the twelve resident layers are home (a prompt transaction can run). - pub(in crate::qwen_forward) fn qsa_owners_home(&self)->bool{self.layers.iter().flatten().count()==12} - pub(in super::super) fn validate(&self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>)->Result<()> { - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?) - ||dense.native_prompt_capacity(binding,self.context)?!=self.capacity{return Err(Error::IdentityMismatch);} - dense.validate(binding)?;Ok(()) - } -} +#[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs"] +mod impl_originalpromptexecutor; +#[path = "impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs"] +mod impl_originalpromptexecutor_2_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs new file mode 100644 index 00000000..94c5b600 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor.rs @@ -0,0 +1,242 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalPromptExecutor<'ctx> { + /// Eager model/session owners precede expert prefix planning. The twelve + /// resident checkpoints are installed together only after all producers exist. + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + moe: &MoeWeightCache<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + capacity: usize, + max_t: usize, + fused: bool, + ) -> Result { + // Pinned-pack source: the MoE cache already holds and charged the roles. + let retained = moe.retain_original_mtp_weights(binding, context)?; + Self::new_with_mtp_weights(binding, dense, session, context, retained, embedding, capacity, max_t, fused) + } + /// Same construction over any retained MTP role bank (the pinned pack, or + /// the Original-literal RT directory bank of `select_rt_mtp`). + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn new_with_mtp_weights( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + retained: RetainedOriginalMtpWeights<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + capacity: usize, + max_t: usize, + fused: bool, + ) -> Result { + if binding.layer_count() != 48 + || !(1..=8192).contains(&capacity) + || !(1..=8).contains(&max_t) + || dense.native_prompt_capacity(binding, context)? != capacity + || !std::ptr::eq(context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + let mut owner = Self { + context, + binding: binding.identity(), + capacity, + fused, + prompt: None, + gdn: None, + qsa: None, + transport: None, + attention: None, + mtp_prefill: None, + mtp_scalar: None, + mtp_scalar_weights: None, + mtp_weights: None, + mtp_full: None, + max_t, + layers: std::array::from_fn(|_| None), + failed: false, + }; + let result = (|| { + owner.prompt = Some( + context + .original_prompt_device(capacity, PleBf16Mode::HighOnly, GrNativeProfile::HighOnly) + .map_err(driver_error)?, + ); + owner.gdn = + Some(context.original_gdn_prompt_device(capacity, GrNativeProfile::HighOnly).map_err(driver_error)?); + owner.qsa = Some( + context + .original_qsa_resident_prompt_device(capacity, QsaNativePacking::HighOnly) + .map_err(driver_error)?, + ); + owner.transport = Some(context.original_qsa_resident_transport().map_err(driver_error)?); + owner.attention = Some(context.original_qsa_resident_attention(capacity).map_err(driver_error)?); + owner.mtp_prefill = Some(context.original_mtp_prefill().map_err(driver_error)?); + owner.mtp_scalar_weights = Some(retained.scalar_prefill_weights(binding, context, embedding)?); + owner.mtp_weights = Some(retained); + owner.mtp_scalar = Some(context.original_mtp_scalar_prefill(max_t, capacity).map_err(driver_error)?); + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + for layer in binding.ordered_layers() { + if layer.kind() == BoundLayerKind::Qsa { + let id = LayerId::new(layer.index() as u64, Dimension::new(48)?)?; + let empty = session.original_qsa_seed(binding, id)?; + let index = context.original_qsa_resident_index().map_err(driver_error)?; + let kv = context + .qsa_prompt_kv() + .map_err(driver_error)? + .into_original_mapped_journal() + .map_err(driver_error)?; + owner.layers[layer.index() as usize] = + Some(ResidentQsaLayer::new(binding, dense, session, &empty, index, kv, &mut workspace)?); + } + } + drop(workspace); + let priors = std::array::from_fn(|slot| owner.layers[slot].as_ref().map(ResidentQsaLayer::current)); + session.install_original_qsa_seed_set(binding, priors)?; + Ok(()) + })(); + if let Err(primary) = result { + let _ = owner.close_inner(); + return Err(primary); + } + Ok(owner) + } + /// The immutable MTP roles this executor retains (the RT bank's on the product path). + pub(in crate::qwen_forward) fn retained_mtp_weights(&self) -> Option<&RetainedOriginalMtpWeights<'ctx>> { + self.mtp_weights.as_ref() + } + /// Joins the source-created full MTP graph owner to this exact prompt + /// executor. The draft session is validated against the same target + /// session before it leaves the assembly, so callers cannot pair a full + /// graph with a separately allocated MTP ring. + pub(in crate::qwen_forward) fn install_full_mtp( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + assembly: OriginalMtpFullAssembly<'ctx>, + ) -> Result> { + if self.failed + || self.context.is_poisoned() + || !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, session.mtp_context()?) + || self.mtp_full.is_some() + { + return Err(Error::IdentityMismatch); + } + assembly.draft.checkpoint(binding, session)?; + assembly.owner.validate(binding, self.context, self.max_t)?; + self.mtp_full = Some(assembly.owner); + Ok(assembly.draft) + } + /// Source-level MTP selection, the `--mtp DIR` branch of generate.cpp + /// (`mtp.load` ... `mtp.bind`): load the RT directory banks (dense.txt, + /// dense.bin, experts.bin, nine-name check), build the prompt executor over + /// those exact retained roles, then bind the native head (optional + /// draft_vocab subset), the shared scalar/full/ring layout, the coupled + /// setup and the actor, and install the matching draft session. + /// + /// Returns both owners; the draft session is the sole mutator of the + /// ring, the executor holds the actor. Any failure releases everything + /// built so far through the owners' own closure order. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn select_rt_mtp( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + output: &OriginalNativeOutput<'ctx>, + rt_directory: &std::path::Path, + capacity: usize, + fused: bool, + request: &OriginalMtpRequest, + ) -> std::result::Result<(Self, OriginalDraftSession<'ctx>), OriginalMtpLoadError> { + if !(1..=8).contains(&request.max_t) || request.prompt_capacity != capacity || binding.layer_count() != 48 { + return Err(Error::IdentityMismatch.into()); + } + let bank = context.original_mtp_rt_bank(rt_directory, binding.expert_count() as usize)?; + let retained = RetainedOriginalMtpWeights::from_rt_bank(binding, context, &bank)?; + // The bank object is only a loader receipt: every allocation it holds is + // shared with (or retained alongside) `retained`. + drop(bank); + let mut executor = Self::new_with_mtp_weights( + binding, + dense, + session, + context, + retained.clone(), + embedding, + capacity, + request.max_t, + fused, + )?; + let assembly = OriginalMtpFullOwner::assemble_rt( + binding, + session, + context, + &retained, + embedding, + output, + request, + rt_directory, + )?; + let draft = executor.install_full_mtp(binding, session, assembly)?; + Ok((executor, draft)) + } + /// The loaded `MtpDrafter` of this executor. The caller still borrows the + /// ring through the draft session (`with_pending_ring`, + /// `with_mtp_transition_ring`), which keeps SessionState as the sole mutable + /// authority for its snapshot. + pub(in crate::qwen_forward) fn mtp_actor( + &mut self, + binding: &ModelBinding, + ) -> Result<&mut leleka_cuda_driver::OriginalMtpActor<'ctx>> { + let (context, max_t) = (self.context, self.max_t); + self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t) + } + /// generate.cpp `mtp.set_prompt_len(n)`. + pub(in crate::qwen_forward) fn set_mtp_prompt_len(&mut self, binding: &ModelBinding, n: i64) -> Result<()> { + self.mtp_actor(binding)?.set_prompt_len(n); + Ok(()) + } + /// generate.cpp `mtp.set_max_drafts(S_mtp - 1)`. + pub(in crate::qwen_forward) fn set_mtp_max_drafts(&mut self, binding: &ModelBinding, k: i32) -> Result<()> { + self.mtp_actor(binding)?.set_max_drafts(k); + Ok(()) + } + /// `MtpDrafter::idle()`: drain its own capture stream, nothing else. + pub(in crate::qwen_forward) fn mtp_idle(&mut self, binding: &ModelBinding) -> Result<()> { + self.mtp_actor(binding)?.idle().map_err(driver_error) + } + /// End of a request's verifier: release what the MTP drafter bound to that verifier's bank (its cached round programs read the + /// bank's final-R span and its tail keeps the last staged window), so the bank can close and the next request's first draft + /// captures against its own bank. See `OriginalMtpActor::release_verifier_bindings`. + pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self, binding: &ModelBinding) -> Result<()> { + self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error) + } + /// `MtpDrafter::device()`. + pub(in crate::qwen_forward) fn mtp_device(&mut self, binding: &ModelBinding) -> Result { + Ok(self.mtp_actor(binding)?.device()) + } + /// generate.cpp `if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume)` + /// on the retained ring of the CURRENT, already restored target branch. + pub(in crate::qwen_forward) fn mtp_kv_restore( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + upto: i64, + ) -> Result<()> { + let origin = session.target_origin()?; + let actor = self.mtp_actor(binding)?; + draft.with_mtp_current_ring(binding, session, &origin, |ring, prior| { + actor.kv_restore(ring, prior, upto).map_err(driver_error) + }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs new file mode 100644 index 00000000..4ce1d038 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2/impl_originalpromptexecutor_2_2.rs @@ -0,0 +1,194 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalPromptExecutor<'ctx> { + /// One-way handoff of the twelve resident QSA layers (index image + mapped K/V) to the native + /// verifier for a decode phase. All twelve are validated before any is moved, so a refusal leaves the + /// executor whole. While the owners are out the executor cannot run a prompt transaction; `adopt_qsa_owners` + /// takes the very same physical owners back. + #[allow(clippy::type_complexity)] + pub(in crate::qwen_forward) fn take_qsa_owners( + &mut self, + ) -> Result< + [Option<( + leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, + leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>, + )>; 48], + > { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + for layer in self.layers.iter().flatten() { + layer.check_handoff()?; + } + if self.layers.iter().flatten().count() != 12 { + return Err(Error::IdentityMismatch); + } + let mut owners: [Option<( + leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, + leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>, + )>; 48] = std::array::from_fn(|_| None); + for (slot, layer) in self.layers.iter_mut().enumerate() { + if let Some(layer) = layer.take() { + // the session keeps the lineage prior; only the physical owners travel + let (index, kv, _prior) = layer.into_verifier_owners()?; + owners[slot] = Some((index, kv)); + } + } + Ok(owners) + } + /// The reverse of `take_qsa_owners`, after the verifier closed and its journal returned the owners. + /// Each layer is rebuilt at the session's current lineage witness and its physical image rolled back to + /// it (a no-op copy when the last window committed; the repair when a window was abandoned). The + /// roll-back mints a fresh witness object per layer for the SAME lineage, so the session adopts those + /// objects before the layers can be used again (a layer and the session must name one witness). + #[allow(clippy::type_complexity)] + pub(in crate::qwen_forward) fn adopt_qsa_owners( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + owners: [Option<( + leleka_cuda_driver::OriginalQsaResidentIndex<'ctx>, + leleka_cuda_driver::OriginalQsaMappedJournal<'ctx>, + )>; 48], + ) -> Result<()> { + if self.failed || self.context.is_poisoned() || self.layers.iter().any(Option::is_some) { + return Err(Error::IdentityMismatch); + } + let witnesses = session.original_qsa_witnesses()?; + let context = dense.retained_context(binding, session.mtp_context()?)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let mut first = None; + for (slot, owner) in owners.into_iter().enumerate() { + if let Some((index, kv)) = owner { + let rebuilt = witnesses[slot].clone().ok_or(Error::IdentityMismatch).and_then(|prior| { + ResidentQsaLayer::from_verifier_owners(binding, dense, session, index, kv, prior, &mut workspace) + }); + match rebuilt { + Ok(layer) => self.layers[slot] = Some(layer), + Err(error) => { + first.get_or_insert(error); + } + } + } + } + drop(workspace); + if let Some(error) = first { + self.failed = true; + return Err(error); + } + let current: [Option>; 48] = + std::array::from_fn(|slot| self.layers[slot].as_ref().map(ResidentQsaLayer::current)); + let adopted = session.adopt_original_qsa_witnesses(current); + if adopted.is_err() { + self.failed = true; + } + adopted + } + /// The session's Original checkpoint (position, predecessors, PLE/GDN priors and the twelve resident QSA + /// witnesses). Refused while the recurrent priors lag a verified-window publication. + pub(in crate::qwen_forward) fn checkpoint_session( + &mut self, + binding: &ModelBinding, + session: &mut QwenSession<'ctx>, + ) -> Result> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if self.layers.iter().flatten().count() != 12 { + return Err(Error::IdentityMismatch); + } + session.original_checkpoint(binding) + } + /// Prefix cache: park the point the session stands at (see `ParkedSession`). + pub(in crate::qwen_forward) fn park_session( + &mut self, + binding: &ModelBinding, + session: &mut QwenSession<'ctx>, + ) -> Result { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if self.layers.iter().flatten().count() != 12 { + return Err(Error::IdentityMismatch); + } + session.park_original(binding, &self.layers) + } + /// Prefix cache: the cells `first..first + tokens` of the twelve layers as plain bytes. + pub(in crate::qwen_forward) fn park_block( + &self, + session: &QwenSession<'ctx>, + first: usize, + tokens: usize, + ) -> Result { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if self.layers.iter().flatten().count() != 12 { + return Err(Error::IdentityMismatch); + } + session.park_block(&self.layers, first, tokens) + } + /// Prefix cache: make the session and the twelve layers stand at `parked`, writing `blocks`. A failure poisons + /// the executor, as for `restore_session`. + pub(in crate::qwen_forward) fn import_session( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + parked: &ParkedSession, + blocks: &[&ParkedBlock], + ) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + let imported = session.import_parked(binding, dense, &mut self.layers, parked, blocks); + if imported.is_err() { + self.failed = true; + } + imported + } + /// Roll the session AND the twelve physical resident layers back to `checkpoint` (a request reset to the + /// empty prompt, or an abandoned prompt transaction). A failure poisons the executor. + pub(in crate::qwen_forward) fn restore_session( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &mut QwenSession<'ctx>, + checkpoint: &OriginalSessionCheckpoint<'ctx>, + ) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + let restored = session.restore_original_checkpoint(binding, dense, &mut self.layers, checkpoint); + if restored.is_err() { + self.failed = true; + } + restored + } + /// Whether the twelve resident layers are home (a prompt transaction can run). + pub(in crate::qwen_forward) fn qsa_owners_home(&self) -> bool { + self.layers.iter().flatten().count() == 12 + } + pub(in super::super::super) fn validate( + &self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + ) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, session.mtp_context()?) + || dense.native_prompt_capacity(binding, self.context)? != self.capacity + { + return Err(Error::IdentityMismatch); + } + dense.validate(binding)?; + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs index f73249c1..00ba2798 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2.rs @@ -3,244 +3,7 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalPromptExecutor<'ctx>{ - /// No target position is advanced here. Every read is actual GR arithmetic; - /// recurrent/KV/PLE seals belong to the same still-private source transaction. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn forward<'session,'program,'loan>( - &'program mut self,binding:&'program ModelBinding,dense:&'program DenseWeightCache<'ctx>, - session:&'session mut QwenSession<'ctx>,source:&std::rc::Rc,count:usize, - mut kar:Option<&mut KarPleCache<'ctx>>,moe:&mut MoeWeightCache<'ctx>, - arena:&mut OriginalPrefillArena<'loan,'ctx>, - draft:&'program mut OriginalDraftSession<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - policy:&OriginalMtpScalarPolicy,mut cancelled:impl FnMut()->bool, - )->Result>{ - self.validate(binding,dense,session)?; - let first_position=session.target_origin()?.next_position(); - let tokens=source.window(binding,first_position,count)?; - crate::bringup_trace!("DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}",crate::qwen_forward::original_serve_stack::dbg_el(),tokens.len(),self.capacity,arena.capacity()); - let _launch_sync=leleka_cuda_driver::PromptSyncTrace::enter(); - if tokens.is_empty()||tokens.len()>self.capacity||arena.capacity()!=self.capacity{return Err(Error::InvalidDimension);} - let checkpoint=session.original_checkpoint(binding)?; - let draft_checkpoint=draft.checkpoint(binding,session)?; - let mut txn=OriginalPromptTxn::begin(session,binding,source,count)?; - let profile_context=self.context; - let drain=Some(profile_context as &dyn prof::Drain); - let operation=(||{ - // The last prompt seed belongs to Original Verifier. Every row - // admitted here must have its authentic next token in the source. - txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; - let input_span=prof::span(PStage::Input,None); - // KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device - // (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm). - let mut staged_input=None;let mut staged_ple=None;let mut first_predecessors:Option<[i32;2]>=None; - if binding.kar_ple_binding().is_some()&&staged_input_enabled(){ - let mut staged=StagedInput::default(); - for &token in tokens{ - txn.stage_input(|step|{let pos=step.position(); - if first_predecessors.is_none(){first_predecessors=Some(step.input_predecessors()?);} - match kar.as_deref(){ - Some(cache)=>InputStage::consume_kar_deferred(binding,cache,token,pos,step,&mut staged), - None=>Err(Error::IdentityMismatch), - } - })?; - } - let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; - let kar_binding=binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; - let _ple_span=prof::span(PStage::InputPle,None); - staged_ple=Some(cache.stage_batch(kar_binding,staged.ple_rows())?); - staged_input=Some(staged); - }else{ - for &token in tokens{ - txn.stage_input(|step|{let pos=step.position(); - match (binding.kar_ple_binding(),kar.as_deref_mut()){ - (None,None)=>InputStage::consume(binding,token,pos,step), - (Some(_),Some(cache))=>InputStage::consume_kar(binding,cache,token,pos,step), - _=>Err(Error::IdentityMismatch), - } - })?; - } - } - drop(input_span); - let init_span=prof::span(PStage::Initialize,drain); - let mut sources=Vec::new();sources.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; - let sources_span=prof::span(PStage::InitSources,None); - for local in 0..tokens.len(){sources.push(PromptDeviceSource::from_original(binding,self.context,&txn,local)?);} - drop(sources_span); - let upload_span=prof::span(PStage::InitUpload,drain); - let prompt=self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; - let lease=arena.begin_rows(tokens.len()).map_err(driver_error)?; - let rows=match (staged_input.as_ref(),staged_ple){ - (Some(input),Some(ple))=>{ - let cache=kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; - let result={ - let (ple_cache,ple_books)=cache.device_parts(); - let stage=PromptInputStage{embedding_rows:input.embedding_rows(),embedding_index:input.embedding_index(), - ple_cache,ple_books,ple_updates:ple.updates(),ple_slots:ple.slots()}; - PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,Some(stage)) - }; - match result{ - Ok(rows)=>{cache.commit(ple);rows}, - // the device may already hold part of the scatter: the cache is not trusted again - Err(error)=>{cache.invalidate();return Err(error);}, - } - }, - _=>PromptDeviceRows::initialize(binding,dense,self.context,prompt,lease,sources,None)?, - }; - drop(upload_span);drop(init_span); - // The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes - // (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there. - if let (Some(cache),Some(kar_binding),Some(mut before))=(kar.as_deref_mut(),binding.kar_ple_binding(),first_predecessors){ - let next_first=first_position+tokens.len() as u64; - let want=self.capacity.min(source.len().saturating_sub(next_first as usize)); - if want>0{ - if let Ok(next)=source.window(binding,next_first,want){ - for &token in tokens{before=[before[1],token.get() as i32];} - if let Ok(rows)=InputStage::ple_rows_ahead(binding,before,next){cache.read_ahead(kar_binding,&rows);} - } - } - } - let mut carrier=Carrier::Plain(rows); - for layer in binding.ordered_layers(){ - let index=layer.index();let role=super::super::super::super::gr::GrRole::Attention(index); - crate::bringup_trace!("DBG[{:.0}s] forward layer {index} {:?} begin",crate::qwen_forward::original_serve_stack::dbg_el(),layer.kind()); - if index==1{ - let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::Ple,drain); - let prior=txn.ple_prior()?; - let mut history=InputStage::prepare_original_prompt_history(binding,dense,self.context,&txn)?; - rows=rows.apply_ple(binding,dense,prompt,&mut history)?; - InputStage::finish_original_prompt_history(binding,&txn,&prior,history)?; - // The completed PLE operation changes the real row state. - // Its output must pass fresh current-row validation. - carrier=Carrier::Plain(rows); - } - let mut read=match carrier{ - Carrier::Plain(mut rows)=>{ - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::AttnRead,drain); - rows.read(binding,dense,prompt,role)? - }, - Carrier::Normed(mut rows)=>{ - {let _span=prof::span(PStage::Validate,None);rows.validate_original_rows(binding,dense)?;} - let _span=prof::span(PStage::AttnRead,drain); - rows.read(binding,dense,prompt)? - }, - }; - crate::bringup_trace!("DBG[{:.0}s] L{index} attn-read ok",crate::qwen_forward::original_serve_stack::dbg_el()); - {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} - let mixer_span=prof::span(match layer.kind(){BoundLayerKind::Gdn=>PStage::Gdn,BoundLayerKind::Qsa=>PStage::Qsa},drain); - let mut ffn=if self.fused { - let rows=match layer.kind(){ - BoundLayerKind::Gdn=>read.complete_original_gdn_normed(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, - BoundLayerKind::Qsa=>read.complete_original_qsa_normed(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, - };Carrier::Normed(rows) - }else{ - let rows=match layer.kind(){ - BoundLayerKind::Gdn=>read.complete_original_gdn(binding,dense,&txn,prompt,self.gdn.as_mut().ok_or(Error::IdentityMismatch)?)?, - BoundLayerKind::Qsa=>read.complete_original_qsa(binding,dense,&txn,prompt,self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, - self.qsa.as_mut().ok_or(Error::IdentityMismatch)?,self.transport.as_mut().ok_or(Error::IdentityMismatch)?,self.attention.as_mut().ok_or(Error::IdentityMismatch)?)?, - };Carrier::Plain(rows) - }; - drop(mixer_span); - crate::bringup_trace!("DBG[{:.0}s] L{index} mixer ok",crate::qwen_forward::original_serve_stack::dbg_el()); - {let _span=prof::span(PStage::Validate,None);match &mut ffn{ - Carrier::Plain(rows)=>{rows.validate_original_rows(binding,dense)?;}, - Carrier::Normed(rows)=>{rows.validate_original_rows(binding,dense)?;}, - };} - crate::bringup_trace!("DBG[{:.0}s] L{index} ffn-validate ok",crate::qwen_forward::original_serve_stack::dbg_el()); - let ffn_span=prof::span(PStage::FfnRead,drain); - let mut read=match ffn{ - Carrier::Plain(rows)=>rows.read(binding,dense,prompt,super::super::super::super::gr::GrRole::Ffn(index))?, - Carrier::Normed(rows)=>rows.read(binding,dense,prompt)?, - }; - drop(ffn_span); - {let _span=prof::span(PStage::Validate,None);read.validate_original_rows(binding,dense)?;} - let moe_span=prof::span(PStage::Moe,drain); - // Literal fused GR norm is prohibited across PLE and final head. - carrier=if self.fused&&index!=0&&index!=47{ - Carrier::Normed(read.complete_original_moe_normed(binding,dense,moe,prompt)?) - }else{Carrier::Plain(read.complete_original_moe(binding,dense,moe,prompt)?)}; - drop(moe_span); - crate::bringup_trace!("DBG[{:.0}s] L{index} moe ok",crate::qwen_forward::original_serve_stack::dbg_el()); - } - let Carrier::Plain(mut rows)=carrier else{return Err(Error::IdentityMismatch);}; - // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers - moe.end_prompt_stream()?; - let final_span=prof::span(PStage::Final,drain); - crate::bringup_trace!("DBG[{:.0}s] forward: all layers ok, final row",crate::qwen_forward::original_serve_stack::dbg_el()); - let final_row=rows.preview_conditioning(binding,dense,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] preview_conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] final_row ok",crate::qwen_forward::original_serve_stack::dbg_el()); - // Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R - // (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default. - if crate::settings::process().diagnostics.trace_prefill_r{ - let first=txn.start_position();let count=txn.len(); - let hash=rows.with_final_residual(binding,dense,&txn,&final_row,|residual|{ - let mut hash=0xcbf29ce484222325u64;let mut rows_hash=Vec::with_capacity(count); - for index in 0..count{ - let row=residual.read_prompt_row(index).map_err(driver_error)?; - let mut row_hash=0xcbf29ce484222325u64; - for value in row.iter(){for byte in value.to_le_bytes(){row_hash^=u64::from(byte);row_hash=row_hash.wrapping_mul(0x100000001b3);}} - hash^=row_hash;hash=hash.wrapping_mul(0x100000001b3);rows_hash.push(row_hash); - } - Ok((hash,rows_hash)) - })?; - eprintln!("PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}",hash.0,hash.1[0],hash.1[count-1]); - } - let sample=OriginalPromptSample::conditioning(binding,&final_row,&txn).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] sample conditioning err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] sample ok",crate::qwen_forward::original_serve_stack::dbg_el()); - drop(final_span); - let draft_span=prof::span(PStage::DraftKv,drain); - let producer=self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; - // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared layout is paired - // with that owner's main arena, a standalone owner is refused with InvalidQwenShape. - let (context,max_t)=(self.context,self.max_t); - let scalar=self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding,context,max_t)?; - let scalar_weights=std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); - let retained_mtp=self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?; - let draft_kv=draft.with_pending_ring(binding,&txn,|ring,prior,first_needed|{ - crate::bringup_trace!("DBG[{:.0}s] draft ring open first_needed={first_needed:?}",crate::qwen_forward::original_serve_stack::dbg_el()); - let mut workspace=dense.native_batch_workspace(binding,self.context)?.ok_or(Error::IdentityMismatch)?; - let outcome=rows.record_original_draft_kv(binding,dense,moe,&txn,&final_row,sample.next(), - producer,&mut workspace,ring,prior,embedding.borrow(binding,self.context)?,first_needed,&policy.kv,&mut cancelled)?; - crate::bringup_trace!("DBG[{:.0}s] record_original_draft_kv -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(reason)=>{crate::bringup_trace!("DBG fallback reason: {reason:?}");"Fallback"},OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); - let outcome=match outcome{ - OriginalPromptDraftOutcome::Fallback(_)=>rows.record_original_scalar_draft_kv( - binding,dense,&retained_mtp,&txn,&final_row,sample.next(),scalar,&mut workspace,ring,prior, - scalar_weights,first_needed,policy,&mut cancelled)?, - other=>other, - }; - crate::bringup_trace!("DBG[{:.0}s] after scalar fallback -> {}",crate::qwen_forward::original_serve_stack::dbg_el(),match &outcome{OriginalPromptDraftOutcome::Completed(_)=>"Completed",OriginalPromptDraftOutcome::Fallback(_)=>"Fallback",OriginalPromptDraftOutcome::Skipped=>"Skipped",OriginalPromptDraftOutcome::Cancelled=>"Cancelled"}); - match outcome{ - OriginalPromptDraftOutcome::Completed(completed)=>Ok(completed), - // Optional unported storage and actual no-materialization - // need separate genuine outcomes; refusal advances neither. - OriginalPromptDraftOutcome::Fallback(_)|OriginalPromptDraftOutcome::Skipped| - OriginalPromptDraftOutcome::Cancelled=>Err(Error::Unsupported(Stage::Session)), - } - }).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] with_pending_ring err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - crate::bringup_trace!("DBG[{:.0}s] forward: draft kv ok",crate::qwen_forward::original_serve_stack::dbg_el()); - drop(draft_span); - if cancelled(){return Err(Error::Unsupported(Stage::Session));} - let _span=prof::span(PStage::FinishPreview,drain); - rows.finish_after_preview(binding,dense,&txn,&final_row).map_err(|e|{crate::bringup_trace!("DBG[{:.0}s] finish_after_preview err {e:?}",crate::qwen_forward::original_serve_stack::dbg_el());e})?; - Ok((final_row,sample,draft_kv)) - })(); - match operation{ - Err(primary)=>{ - crate::bringup_trace!("DBG[{:.0}s] forward operation failed: {primary:?}",crate::qwen_forward::original_serve_stack::dbg_el()); - // stop the chunk's expert stream before the transaction rolls back - if moe.end_prompt_stream().is_err(){self.failed=true;} - let cleanup=txn.abort_with_draft(binding,dense,&mut self.layers,&checkpoint,draft,&draft_checkpoint); - if cleanup.is_err()||self.context.is_poisoned(){self.failed=true;} - Err(primary) - }, - Ok((completed,sample,draft_kv))=>Ok(OriginalPromptPending{txn:Some(txn),binding,dense,layers:&mut self.layers, - failed:&mut self.failed,checkpoint,completed,sample,draft_kv,draft,draft_checkpoint}), - } - } - pub(in crate::qwen_forward) fn close(mut self)->Result<()>{self.close_inner()} -} +#[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs"] +mod impl_originalpromptexecutor; +#[path = "impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs"] +mod impl_originalpromptexecutor_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs new file mode 100644 index 00000000..a2f313ec --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor.rs @@ -0,0 +1,492 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalPromptExecutor<'ctx> { + /// No target position is advanced here. Every read is actual GR arithmetic; + /// recurrent/KV/PLE seals belong to the same still-private source transaction. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn forward<'session, 'program, 'loan>( + &'program mut self, + binding: &'program ModelBinding, + dense: &'program DenseWeightCache<'ctx>, + session: &'session mut QwenSession<'ctx>, + source: &std::rc::Rc, + count: usize, + mut kar: Option<&mut KarPleCache<'ctx>>, + moe: &mut MoeWeightCache<'ctx>, + arena: &mut OriginalPrefillArena<'loan, 'ctx>, + draft: &'program mut OriginalDraftSession<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + policy: &OriginalMtpScalarPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result> { + self.validate(binding, dense, session)?; + let first_position = session.target_origin()?.next_position(); + let tokens = source.window(binding, first_position, count)?; + crate::bringup_trace!( + "DBG[{:.0}s] forward: tokens={} self.capacity={} arena.capacity={} count={count}", + crate::qwen_forward::original_serve_stack::dbg_el(), + tokens.len(), + self.capacity, + arena.capacity() + ); + let _launch_sync = leleka_cuda_driver::PromptSyncTrace::enter(); + if tokens.is_empty() || tokens.len() > self.capacity || arena.capacity() != self.capacity { + return Err(Error::InvalidDimension); + } + let checkpoint = session.original_checkpoint(binding)?; + let draft_checkpoint = draft.checkpoint(binding, session)?; + let mut txn = OriginalPromptTxn::begin(session, binding, source, count)?; + let profile_context = self.context; + let drain = Some(profile_context as &dyn prof::Drain); + let operation = (|| { + // The last prompt seed belongs to Original Verifier. Every row + // admitted here must have its authentic next token in the source. + txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; + let input_span = prof::span(PStage::Input, None); + // KAR inputs are staged chunk-wide: embeddings broadcast and PLE rows decoded on the device + // (LELEKA_PREFILL_STAGED_INPUT=0: the per-token host path, the A/B arm). + let mut staged_input = None; + let mut staged_ple = None; + let mut first_predecessors: Option<[i32; 2]> = None; + if binding.kar_ple_binding().is_some() && staged_input_enabled() { + let mut staged = StagedInput::default(); + for &token in tokens { + txn.stage_input(|step| { + let pos = step.position(); + if first_predecessors.is_none() { + first_predecessors = Some(step.input_predecessors()?); + } + match kar.as_deref() { + Some(cache) => { + InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged) + } + None => Err(Error::IdentityMismatch), + } + })?; + } + let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; + let kar_binding = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; + let _ple_span = prof::span(PStage::InputPle, None); + staged_ple = Some(cache.stage_batch(kar_binding, staged.ple_rows())?); + staged_input = Some(staged); + } else { + for &token in tokens { + txn.stage_input(|step| { + let pos = step.position(); + match (binding.kar_ple_binding(), kar.as_deref_mut()) { + (None, None) => InputStage::consume(binding, token, pos, step), + (Some(_), Some(cache)) => InputStage::consume_kar(binding, cache, token, pos, step), + _ => Err(Error::IdentityMismatch), + } + })?; + } + } + drop(input_span); + let init_span = prof::span(PStage::Initialize, drain); + let mut sources = Vec::new(); + sources.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; + let sources_span = prof::span(PStage::InitSources, None); + for local in 0..tokens.len() { + sources.push(PromptDeviceSource::from_original(binding, self.context, &txn, local)?); + } + drop(sources_span); + let upload_span = prof::span(PStage::InitUpload, drain); + let prompt = self.prompt.as_mut().ok_or(Error::IdentityMismatch)?; + let lease = arena.begin_rows(tokens.len()).map_err(driver_error)?; + let rows = match (staged_input.as_ref(), staged_ple) { + (Some(input), Some(ple)) => { + let cache = kar.as_deref_mut().ok_or(Error::IdentityMismatch)?; + let result = { + let (ple_cache, ple_books) = cache.device_parts(); + let stage = PromptInputStage { + embedding_rows: input.embedding_rows(), + embedding_index: input.embedding_index(), + ple_cache, + ple_books, + ple_updates: ple.updates(), + ple_slots: ple.slots(), + }; + PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, Some(stage)) + }; + match result { + Ok(rows) => { + cache.commit(ple); + rows + } + // the device may already hold part of the scatter: the cache is not trusted again + Err(error) => { + cache.invalidate(); + return Err(error); + } + } + } + _ => PromptDeviceRows::initialize(binding, dense, self.context, prompt, lease, sources, None)?, + }; + drop(upload_span); + drop(init_span); + // The PLE packets of the next chunk are read from the archive on a thread of their own while this chunk computes + // (they are a function of the tokens and the archive only); `stage_batch` of that chunk takes them from there. + if let (Some(cache), Some(kar_binding), Some(mut before)) = + (kar.as_deref_mut(), binding.kar_ple_binding(), first_predecessors) + { + let next_first = first_position + tokens.len() as u64; + let want = self.capacity.min(source.len().saturating_sub(next_first as usize)); + if want > 0 { + if let Ok(next) = source.window(binding, next_first, want) { + for &token in tokens { + before = [before[1], token.get() as i32]; + } + if let Ok(rows) = InputStage::ple_rows_ahead(binding, before, next) { + cache.read_ahead(kar_binding, &rows); + } + } + } + } + let mut carrier = Carrier::Plain(rows); + for layer in binding.ordered_layers() { + let index = layer.index(); + let role = super::super::super::super::super::gr::GrRole::Attention(index); + crate::bringup_trace!( + "DBG[{:.0}s] forward layer {index} {:?} begin", + crate::qwen_forward::original_serve_stack::dbg_el(), + layer.kind() + ); + if index == 1 { + let Carrier::Plain(mut rows) = carrier else { + return Err(Error::IdentityMismatch); + }; + { + let _span = prof::span(PStage::Validate, None); + rows.validate_original_rows(binding, dense)?; + } + let _span = prof::span(PStage::Ple, drain); + let prior = txn.ple_prior()?; + let mut history = InputStage::prepare_original_prompt_history(binding, dense, self.context, &txn)?; + rows = rows.apply_ple(binding, dense, prompt, &mut history)?; + InputStage::finish_original_prompt_history(binding, &txn, &prior, history)?; + // The completed PLE operation changes the real row state. + // Its output must pass fresh current-row validation. + carrier = Carrier::Plain(rows); + } + let mut read = match carrier { + Carrier::Plain(mut rows) => { + { + let _span = prof::span(PStage::Validate, None); + rows.validate_original_rows(binding, dense)?; + } + let _span = prof::span(PStage::AttnRead, drain); + rows.read(binding, dense, prompt, role)? + } + Carrier::Normed(mut rows) => { + { + let _span = prof::span(PStage::Validate, None); + rows.validate_original_rows(binding, dense)?; + } + let _span = prof::span(PStage::AttnRead, drain); + rows.read(binding, dense, prompt)? + } + }; + crate::bringup_trace!( + "DBG[{:.0}s] L{index} attn-read ok", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + { + let _span = prof::span(PStage::Validate, None); + read.validate_original_rows(binding, dense)?; + } + let mixer_span = prof::span( + match layer.kind() { + BoundLayerKind::Gdn => PStage::Gdn, + BoundLayerKind::Qsa => PStage::Qsa, + }, + drain, + ); + let mut ffn = if self.fused { + let rows = match layer.kind() { + BoundLayerKind::Gdn => read.complete_original_gdn_normed( + binding, + dense, + &txn, + prompt, + self.gdn.as_mut().ok_or(Error::IdentityMismatch)?, + )?, + BoundLayerKind::Qsa => read.complete_original_qsa_normed( + binding, + dense, + &txn, + prompt, + self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, + self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, + self.transport.as_mut().ok_or(Error::IdentityMismatch)?, + self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + )?, + }; + Carrier::Normed(rows) + } else { + let rows = match layer.kind() { + BoundLayerKind::Gdn => read.complete_original_gdn( + binding, + dense, + &txn, + prompt, + self.gdn.as_mut().ok_or(Error::IdentityMismatch)?, + )?, + BoundLayerKind::Qsa => read.complete_original_qsa( + binding, + dense, + &txn, + prompt, + self.layers[index as usize].as_mut().ok_or(Error::IdentityMismatch)?, + self.qsa.as_mut().ok_or(Error::IdentityMismatch)?, + self.transport.as_mut().ok_or(Error::IdentityMismatch)?, + self.attention.as_mut().ok_or(Error::IdentityMismatch)?, + )?, + }; + Carrier::Plain(rows) + }; + drop(mixer_span); + crate::bringup_trace!( + "DBG[{:.0}s] L{index} mixer ok", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + { + let _span = prof::span(PStage::Validate, None); + match &mut ffn { + Carrier::Plain(rows) => { + rows.validate_original_rows(binding, dense)?; + } + Carrier::Normed(rows) => { + rows.validate_original_rows(binding, dense)?; + } + }; + } + crate::bringup_trace!( + "DBG[{:.0}s] L{index} ffn-validate ok", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + let ffn_span = prof::span(PStage::FfnRead, drain); + let mut read = match ffn { + Carrier::Plain(rows) => { + rows.read(binding, dense, prompt, super::super::super::super::super::gr::GrRole::Ffn(index))? + } + Carrier::Normed(rows) => rows.read(binding, dense, prompt)?, + }; + drop(ffn_span); + { + let _span = prof::span(PStage::Validate, None); + read.validate_original_rows(binding, dense)?; + } + let moe_span = prof::span(PStage::Moe, drain); + // Literal fused GR norm is prohibited across PLE and final head. + carrier = if self.fused && index != 0 && index != 47 { + Carrier::Normed(read.complete_original_moe_normed(binding, dense, moe, prompt)?) + } else { + Carrier::Plain(read.complete_original_moe(binding, dense, moe, prompt)?) + }; + drop(moe_span); + crate::bringup_trace!( + "DBG[{:.0}s] L{index} moe ok", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + } + let Carrier::Plain(mut rows) = carrier else { + return Err(Error::IdentityMismatch); + }; + // the chunk's expert stream (if any) ended with the last MoE layer; never carried past the layers + moe.end_prompt_stream()?; + let final_span = prof::span(PStage::Final, drain); + crate::bringup_trace!( + "DBG[{:.0}s] forward: all layers ok, final row", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + let final_row = rows.preview_conditioning(binding, dense, &txn).map_err(|e| { + crate::bringup_trace!( + "DBG[{:.0}s] preview_conditioning err {e:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + e + })?; + crate::bringup_trace!("DBG[{:.0}s] final_row ok", crate::qwen_forward::original_serve_stack::dbg_el()); + // Bring-up gate (LELEKA_TRACE_PREFILL_R=1): FNV-1a of the bits of every row of the chunk's final residual R + // (all four streams), for bit-exact A/B comparison of prefill variants. Slow (one drain per row); off by default. + if crate::settings::process().diagnostics.trace_prefill_r { + let first = txn.start_position(); + let count = txn.len(); + let hash = rows.with_final_residual(binding, dense, &txn, &final_row, |residual| { + let mut hash = 0xcbf29ce484222325u64; + let mut rows_hash = Vec::with_capacity(count); + for index in 0..count { + let row = residual.read_prompt_row(index).map_err(driver_error)?; + let mut row_hash = 0xcbf29ce484222325u64; + for value in row.iter() { + for byte in value.to_le_bytes() { + row_hash ^= u64::from(byte); + row_hash = row_hash.wrapping_mul(0x100000001b3); + } + } + hash ^= row_hash; + hash = hash.wrapping_mul(0x100000001b3); + rows_hash.push(row_hash); + } + Ok((hash, rows_hash)) + })?; + eprintln!( + "PREFILL-R first={first} rows={count} fnv1a64={:016x} first_row={:016x} last_row={:016x}", + hash.0, + hash.1[0], + hash.1[count - 1] + ); + } + let sample = OriginalPromptSample::conditioning(binding, &final_row, &txn).map_err(|e| { + crate::bringup_trace!( + "DBG[{:.0}s] sample conditioning err {e:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + e + })?; + crate::bringup_trace!("DBG[{:.0}s] sample ok", crate::qwen_forward::original_serve_stack::dbg_el()); + drop(final_span); + let draft_span = prof::span(PStage::DraftKv, drain); + let producer = self.mtp_prefill.as_mut().ok_or(Error::IdentityMismatch)?; + // The scalar (short prompt) fallback must run on the drafter's OWN scalar owner: the ring of the shared layout is paired + // with that owner's main arena, a standalone owner is refused with InvalidQwenShape. + let (context, max_t) = (self.context, self.max_t); + let scalar = self.mtp_full.as_mut().ok_or(Error::IdentityMismatch)?.actor_mut(binding, context, max_t)?; + let scalar_weights = std::rc::Rc::clone(self.mtp_scalar_weights.as_ref().ok_or(Error::IdentityMismatch)?); + let retained_mtp = self.mtp_weights.clone().ok_or(Error::IdentityMismatch)?; + let draft_kv = draft + .with_pending_ring(binding, &txn, |ring, prior, first_needed| { + crate::bringup_trace!( + "DBG[{:.0}s] draft ring open first_needed={first_needed:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + let mut workspace = + dense.native_batch_workspace(binding, self.context)?.ok_or(Error::IdentityMismatch)?; + let outcome = rows.record_original_draft_kv( + binding, + dense, + moe, + &txn, + &final_row, + sample.next(), + producer, + &mut workspace, + ring, + prior, + embedding.borrow(binding, self.context)?, + first_needed, + &policy.kv, + &mut cancelled, + )?; + crate::bringup_trace!( + "DBG[{:.0}s] record_original_draft_kv -> {}", + crate::qwen_forward::original_serve_stack::dbg_el(), + match &outcome { + OriginalPromptDraftOutcome::Completed(_) => "Completed", + OriginalPromptDraftOutcome::Fallback(reason) => { + crate::bringup_trace!("DBG fallback reason: {reason:?}"); + "Fallback" + } + OriginalPromptDraftOutcome::Skipped => "Skipped", + OriginalPromptDraftOutcome::Cancelled => "Cancelled", + } + ); + let outcome = match outcome { + OriginalPromptDraftOutcome::Fallback(_) => rows.record_original_scalar_draft_kv( + binding, + dense, + &retained_mtp, + &txn, + &final_row, + sample.next(), + scalar, + &mut workspace, + ring, + prior, + scalar_weights, + first_needed, + policy, + &mut cancelled, + )?, + other => other, + }; + crate::bringup_trace!( + "DBG[{:.0}s] after scalar fallback -> {}", + crate::qwen_forward::original_serve_stack::dbg_el(), + match &outcome { + OriginalPromptDraftOutcome::Completed(_) => "Completed", + OriginalPromptDraftOutcome::Fallback(_) => "Fallback", + OriginalPromptDraftOutcome::Skipped => "Skipped", + OriginalPromptDraftOutcome::Cancelled => "Cancelled", + } + ); + match outcome { + OriginalPromptDraftOutcome::Completed(completed) => Ok(completed), + // Optional unported storage and actual no-materialization + // need separate genuine outcomes; refusal advances neither. + OriginalPromptDraftOutcome::Fallback(_) + | OriginalPromptDraftOutcome::Skipped + | OriginalPromptDraftOutcome::Cancelled => Err(Error::Unsupported(Stage::Session)), + } + }) + .map_err(|e| { + crate::bringup_trace!( + "DBG[{:.0}s] with_pending_ring err {e:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + e + })?; + crate::bringup_trace!( + "DBG[{:.0}s] forward: draft kv ok", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + drop(draft_span); + if cancelled() { + return Err(Error::Unsupported(Stage::Session)); + } + let _span = prof::span(PStage::FinishPreview, drain); + rows.finish_after_preview(binding, dense, &txn, &final_row).map_err(|e| { + crate::bringup_trace!( + "DBG[{:.0}s] finish_after_preview err {e:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + e + })?; + Ok((final_row, sample, draft_kv)) + })(); + match operation { + Err(primary) => { + crate::bringup_trace!( + "DBG[{:.0}s] forward operation failed: {primary:?}", + crate::qwen_forward::original_serve_stack::dbg_el() + ); + // stop the chunk's expert stream before the transaction rolls back + if moe.end_prompt_stream().is_err() { + self.failed = true; + } + let cleanup = + txn.abort_with_draft(binding, dense, &mut self.layers, &checkpoint, draft, &draft_checkpoint); + if cleanup.is_err() || self.context.is_poisoned() { + self.failed = true; + } + Err(primary) + } + Ok((completed, sample, draft_kv)) => Ok(OriginalPromptPending { + txn: Some(txn), + binding, + dense, + layers: &mut self.layers, + failed: &mut self.failed, + checkpoint, + completed, + sample, + draft_kv, + draft, + draft_checkpoint, + }), + } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs new file mode 100644 index 00000000..76d30ca0 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_2_2/impl_originalpromptexecutor_2.rs @@ -0,0 +1,10 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptExecutor (2). + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalPromptExecutor<'ctx> { + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.close_inner() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs index 4c89860d..e7a129f9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/impl_originalpromptexecutor/impl_originalpromptexecutor_3.rs @@ -3,18 +3,40 @@ #[allow(unused_imports)] use super::*; - -impl<'ctx> OriginalPromptExecutor<'ctx>{ - pub(in super::super) fn close_inner(&mut self)->Result<()>{ - let mut first=None; - macro_rules! retire {($v:expr)=>{if let Some(owner)=$v.take(){if let Err(e)=owner.close().map_err(driver_error){first.get_or_insert(e);}}};} - retire!(self.prompt);retire!(self.gdn);retire!(self.qsa);retire!(self.transport);retire!(self.attention); +impl<'ctx> OriginalPromptExecutor<'ctx> { + pub(in super::super) fn close_inner(&mut self) -> Result<()> { + let mut first = None; + macro_rules! retire { + ($v:expr) => { + if let Some(owner) = $v.take() { + if let Err(e) = owner.close().map_err(driver_error) { + first.get_or_insert(e); + } + } + }; + } + retire!(self.prompt); + retire!(self.gdn); + retire!(self.qsa); + retire!(self.transport); + retire!(self.attention); retire!(self.mtp_prefill); retire!(self.mtp_scalar); self.mtp_scalar_weights.take(); self.mtp_weights.take(); - if let Some(owner)=self.mtp_full.take(){if let Err(error)=owner.close(){first.get_or_insert(error);}} - for slot in &mut self.layers{if let Some(layer)=slot.take(){if let Err(e)=layer.close(){first.get_or_insert(e);}}} - self.failed=true;first.map_or(Ok(()),Err) + if let Some(owner) = self.mtp_full.take() { + if let Err(error) = owner.close() { + first.get_or_insert(error); + } + } + for slot in &mut self.layers { + if let Some(layer) = slot.take() { + if let Err(e) = layer.close() { + first.get_or_insert(e); + } + } + } + self.failed = true; + first.map_or(Ok(()), Err) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/staged_input_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/staged_input_enabled_fn.rs index 1c8b8f8e..d913f24d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/staged_input_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_original_prompt/staged_input_enabled_fn.rs @@ -4,6 +4,6 @@ use super::*; /// `LELEKA_PREFILL_STAGED_INPUT=0` keeps the per-token host path of the KAR inputs (the A/B arm). -pub(super) fn staged_input_enabled()->bool{ +pub(super) fn staged_input_enabled() -> bool { crate::settings::process().kv.prefill_staged_input } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs index ea1f29b7..f19630eb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/check_chunk_on_loaded_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Root-only observer entry on the already loaded pinned operator. No model /// opening or second serving process; exact words/counts only, never tensors. #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -19,20 +18,13 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( use super::super::super::mtp_decode::MtpDecoder; let vocab = Dimension::new(248320).expect("vocabulary refused"); let bounds = crate::qwen_forward::contract::position_dimension(); - let ids: Vec<_> = [0, 1, 0, 1] - .into_iter() - .map(|n| TokenId::new(n, vocab).expect("fixed token refused")) - .collect(); + let ids: Vec<_> = [0, 1, 0, 1].into_iter().map(|n| TokenId::new(n, vocab).expect("fixed token refused")).collect(); let next = TokenId::new(0, vocab).expect("known next refused"); let follow = TokenId::new(1, vocab).expect("known successor refused"); - let fresh = session - .test_reset_replay_snapshot(binding) - .expect("fresh snapshot refused"); + let fresh = session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused"); assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required"); let mut scalar_draft = MtpDecoder::new(binding).expect("baseline draft refused"); - output - .test_reset_replay_record(true) - .expect("head observer refused"); + output.test_reset_replay_record(true).expect("head observer refused"); for index in 0..3 { let source = QwenForward::prefill_for_mtp_cached( binding, @@ -60,9 +52,7 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( Some(dense), ) .expect("scalar final target refused"); - let baseline_logits = output - .test_reset_replay_take_logits() - .expect("scalar head missing"); + let baseline_logits = output.test_reset_replay_take_logits().expect("scalar head missing"); let baseline_greedy = source.predicted(session).expect("scalar source invalid"); let baseline_streams: Vec<_> = source .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) @@ -70,13 +60,9 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( .iter() .map(|v| v.to_bits()) .collect(); - let baseline_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar state invalid"); + let baseline_state = session.test_reset_replay_snapshot(binding).expect("scalar state invalid"); let baseline_draft = scalar_draft.test_chunk_snapshot(); - scalar_draft - .warm_retained(binding, session, &source, next, moe) - .expect("scalar retained edge refused"); + scalar_draft.warm_retained(binding, session, &source, next, moe).expect("scalar retained edge refused"); let continuation = QwenForward::prefill_for_mtp_cached( binding, next, @@ -88,12 +74,8 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( dense, ) .expect("scalar continuation refused"); - scalar_draft - .warm_prefill(binding, session, &continuation, follow, moe) - .expect("scalar continuation warm refused"); - let continued_state = session - .test_reset_replay_snapshot(binding) - .expect("scalar continuation state invalid"); + scalar_draft.warm_prefill(binding, session, &continuation, follow, moe).expect("scalar continuation warm refused"); + let continued_state = session.test_reset_replay_snapshot(binding).expect("scalar continuation state invalid"); let continued_draft = scalar_draft.test_chunk_snapshot(); QwenForward::reset(session).expect("real owner reset refused"); let mut candidate_draft = MtpDecoder::new(binding).expect("candidate draft refused"); @@ -115,21 +97,10 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( callbacks == 16 }, ); - assert!( - matches!(aborted, Err(Error::Unsupported(Stage::Executor))), - "late-row cancellation not refused" - ); - let after_abort = session - .test_reset_replay_snapshot(binding) - .expect("abort snapshot refused"); - assert!( - fresh.numeric_eq(&after_abort), - "cancel changed committed target" - ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "cancel changed committed draft" - ); + assert!(matches!(aborted, Err(Error::Unsupported(Stage::Executor))), "late-row cancellation not refused"); + let after_abort = session.test_reset_replay_snapshot(binding).expect("abort snapshot refused"); + assert!(fresh.numeric_eq(&after_abort), "cancel changed committed target"); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "cancel changed committed draft"); // Real phase-local cancellation: the second MTP callback occurs after // the first actual private draft warm. Group routing changes the number // of earlier target callbacks, so no global callback ordinal is guessed. @@ -147,34 +118,21 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( 512 * 1024 * 1024, || false, )?; - let _ready = - candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { - mtp_callbacks += 1; - mtp_callbacks == 2 - })?; + let _ready = candidate_draft.stage_prefill_chunk(binding, &mut pending, moe, &mut || { + mtp_callbacks += 1; + mtp_callbacks == 2 + })?; Err(Error::IdentityMismatch) })(); - assert!( - matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), - "actual MTP-row cancellation not refused" - ); - let discarded = output - .test_reset_replay_take_logits() - .expect("computed canceled head observation missing"); + assert!(matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))), "actual MTP-row cancellation not refused"); + let discarded = output.test_reset_replay_take_logits().expect("computed canceled head observation missing"); assert_eq!(discarded.len(), 248320, "canceled full head extent changed"); drop(discarded); assert!( - fresh.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("MTP abort target invalid") - ), + fresh.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("MTP abort target invalid")), "MTP cancel changed committed target" ); - assert!( - candidate_draft.test_chunk_eq(&fresh_draft), - "MTP cancel changed committed draft" - ); + assert!(candidate_draft.test_chunk_eq(&fresh_draft), "MTP cancel changed committed draft"); let actual = QwenForward::prefill_chunk_cached_joint( binding, &ids, @@ -190,48 +148,22 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( ) .expect("candidate chunk refused") .expect("genuine final product missing"); - let actual_logits = output - .test_reset_replay_take_logits() - .expect("chunk head missing"); + let actual_logits = output.test_reset_replay_take_logits().expect("chunk head missing"); + assert!(baseline_logits.as_ref() == actual_logits.as_ref(), "full248320 logit mismatch"); + assert_eq!(baseline_greedy, actual.predicted(session).expect("chunk current origin invalid"), "greedy mismatch"); + let actual_streams = + actual.streams(binding, ids[3], Position::new(3, bounds).unwrap(), session).expect("chunk residual invalid"); assert!( - baseline_logits.as_ref() == actual_logits.as_ref(), - "full248320 logit mismatch" - ); - assert_eq!( - baseline_greedy, - actual - .predicted(session) - .expect("chunk current origin invalid"), - "greedy mismatch" - ); - let actual_streams = actual - .streams(binding, ids[3], Position::new(3, bounds).unwrap(), session) - .expect("chunk residual invalid"); - assert!( - baseline_streams - .iter() - .zip(actual_streams.iter()) - .all(|(a, b)| *a == b.to_bits()), + baseline_streams.iter().zip(actual_streams.iter()).all(|(a, b)| *a == b.to_bits()), "full10240 residual mismatch" ); assert!( - baseline_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk state invalid") - ), + baseline_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk state invalid")), "PLE/36GDN/12QSA state mismatch" ); - assert!( - candidate_draft.test_chunk_eq(&baseline_draft), - "actual draft KV/residual mismatch" - ); - candidate_draft - .validate_resume(binding, session, &actual, &[0, 1, 0, 1]) - .expect("chunk resume fence refused"); - candidate_draft - .warm_retained(binding, session, &actual, next, moe) - .expect("chunk retained edge refused"); + assert!(candidate_draft.test_chunk_eq(&baseline_draft), "actual draft KV/residual mismatch"); + candidate_draft.validate_resume(binding, session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused"); + candidate_draft.warm_retained(binding, session, &actual, next, moe).expect("chunk retained edge refused"); let continuation = QwenForward::prefill_for_mtp_cached( binding, next, @@ -247,20 +179,11 @@ pub(in crate::qwen_forward) fn check_chunk_on_loaded<'driver>( .warm_prefill(binding, session, &continuation, follow, moe) .expect("chunk continuation warm refused"); assert!( - continued_state.numeric_eq( - &session - .test_reset_replay_snapshot(binding) - .expect("chunk continuation invalid") - ), + continued_state.numeric_eq(&session.test_reset_replay_snapshot(binding).expect("chunk continuation invalid")), "continued target mismatch" ); - assert!( - candidate_draft.test_chunk_eq(&continued_draft), - "continued draft mismatch" - ); - output - .test_reset_replay_record(false) - .expect("head observer did not drain"); + assert!(candidate_draft.test_chunk_eq(&continued_draft), "continued draft mismatch"); + output.test_reset_replay_record(false).expect("head observer did not drain"); eprintln!( "chunk numerical PASS rows=4 layers=48 PLE=1 GDN=36 QSA=12 residual_words=10240 logit_words=248320 draft_exact=true continued_exact=true cancelled_prefix_unchanged=true canceled_actual_mtp_warm=true actual_q6_attention_columns=true actual_ffn_gr_batch=true other_math_scalar=true" ); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs index 8c93c38f..0c39730e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn test_chunk_on_loaded<'driver>( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs index 639599d2..1b64f722 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { - /// Explicit private composition using the owned IntegerIQ3 cache. Each /// outer256 layer uses <=64-row windows and existing retained GR transport; /// unsupported GU selects native whole-layer execution before any MMQ launch. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs index 181871bd..3bb20339 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_qwenforward/impl_qwenforward_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl QwenForward { - #[allow(clippy::too_many_arguments)] pub(in super::super) fn prepare_prefill_chunk_with_policy_windowed<'session, 'driver>( binding: &ModelBinding, @@ -29,9 +26,7 @@ impl QwenForward { let host_remaining = if moe_cache.uses_strata_adaptive_experts() { // Independent actual CPU wave and ephemeral staging coexist. // Both are inside the unchanged 512MiB request admission. - host_remaining - .checked_sub((48 + 16) * 1024 * 1024) - .ok_or(Error::InputAllocation)? + host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)? } else { host_remaining }; @@ -39,51 +34,24 @@ impl QwenForward { if layer_bound.get() != 48 { return Err(Error::Unsupported(Stage::Executor)); } - chunk_diagnostic( - "dense-cache-validate", - None, - 0, - tokens.len(), - dense_cache.validate(binding), - )?; + chunk_diagnostic("dense-cache-validate", None, 0, tokens.len(), dense_cache.validate(binding))?; // Immutable weights and eagerly reserved scratch are charged before // chunk admission. The existing 128MiB transient reserve is preserved. - let context = chunk_diagnostic( - "target-context", - None, - 0, - tokens.len(), - session.mtp_context(), - )?; + let context = chunk_diagnostic("target-context", None, 0, tokens.len(), session.mtp_context())?; // Revalidate the genuine actor Context and retain its cache lifetime, // independent of the upcoming mutable session transaction borrow. let context = moe_cache.mmq_context(binding, context)?; - chunk_diagnostic( - "moe-prepare-step", - None, - 0, - tokens.len(), - moe_cache.prepare_step(binding, context), - )?; - if !matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) && dense_cache.gdn_four_borrow(binding, context)? + chunk_diagnostic("moe-prepare-step", None, 0, tokens.len(), moe_cache.prepare_step(binding, context))?; + if !matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) + && dense_cache.gdn_four_borrow(binding, context)? { // Retained full QK/H/Gate/Beta are additional to the unchanged // typed+physical128MiB reserve, before any row/input/weight loan. - moe_cache.reserve_mmq_transient( - binding, - context, - super::super::super::super::gdn::FOUR_BORROW_BYTES, - )?; + moe_cache.reserve_mmq_transient(binding, context, super::super::super::super::gdn::FOUR_BORROW_BYTES)?; } // Only the existing explicit experimental windowed256 policy opts in. - let recurrence_context = if windowed - && matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { + let recurrence_context = if windowed && matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) + { Some(dense_cache.retained_context(binding, context)?) } else { None @@ -98,16 +66,12 @@ impl QwenForward { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let micro_gr = matches!( policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification + ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr | ChunkMoePolicy::ExperimentalMtpVerification ); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let micro_gr = false; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let host_remaining = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { + let host_remaining = if matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) { host_remaining .min(512 * 1024 * 1024) .checked_sub(QwenChunkTxn::native_prefill_host_charge(tokens.len())?) @@ -126,13 +90,7 @@ impl QwenForward { } QwenChunkTxn::begin_mtp_verification(session, binding, tokens, host_remaining) } else if windowed { - QwenChunkTxn::begin_windowed256( - session, - binding, - tokens, - known_next, - host_remaining, - ) + QwenChunkTxn::begin_windowed256(session, binding, tokens, known_next, host_remaining) } else { QwenChunkTxn::begin(session, binding, tokens, known_next, host_remaining) }, @@ -144,15 +102,9 @@ impl QwenForward { if verification_context.is_some() { chunk.enable_device_gdn_verification(binding, dense_cache, host_remaining)?; } - let verification_lease = if verification_context.is_some() { - chunk.device_gdn_lease()? - } else { - None - }; + let verification_lease = if verification_context.is_some() { chunk.device_gdn_lease()? } else { None }; let mut previous = Vec::new(); - previous - .try_reserve_exact(chunk.len()) - .map_err(|_| Error::InputAllocation)?; + previous.try_reserve_exact(chunk.len()).map_err(|_| Error::InputAllocation)?; previous.resize_with(chunk.len(), || None); for index in 0..chunk.len() { if cancelled() { @@ -164,14 +116,10 @@ impl QwenForward { None, index, 1, - chunk.input(index, |txn| { - match (binding.kar_ple_binding(), kar_cache.as_deref_mut()) { - (None, None) => InputStage::consume(binding, token, pos, txn), - (Some(_), Some(cache)) => { - InputStage::consume_kar(binding, cache, token, pos, txn) - } - _ => Err(Error::IdentityMismatch), - } + chunk.input(index, |txn| match (binding.kar_ple_binding(), kar_cache.as_deref_mut()) { + (None, None) => InputStage::consume(binding, token, pos, txn), + (Some(_), Some(cache)) => InputStage::consume_kar(binding, cache, token, pos, txn), + _ => Err(Error::IdentityMismatch), }), )?; } @@ -180,19 +128,15 @@ impl QwenForward { for descriptor in binding.ordered_layers() { let layer = LayerId::new(u64::from(descriptor.index()), layer_bound)?; let mut gdn_device = if descriptor.kind() == BoundLayerKind::Gdn { - if let (Some(context), Some(lease)) = - (verification_context, verification_lease.as_ref()) - { + if let (Some(context), Some(lease)) = (verification_context, verification_lease.as_ref()) { let start = chunk.begin_gdn_chunk(layer)?; - Some( - super::super::super::super::gdn::chunk_device::GdnChunkDevice::new_verification( - binding, - context, - dense_cache, - start, - lease.clone(), - )?, - ) + Some(super::super::super::super::gdn::chunk_device::GdnChunkDevice::new_verification( + binding, + context, + dense_cache, + start, + lease.clone(), + )?) } else if let Some(context) = recurrence_context { // Both actual state owners/status coexist with the eager // prompt bank. No scalar four-input chain is loaned here. @@ -208,10 +152,7 @@ impl QwenForward { )?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if micro_gr - && !matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) + && !matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) && dense_cache.has_gdn_qk_workspace() { owner.enable_row_queue()?; @@ -227,54 +168,35 @@ impl QwenForward { // bounded window before the next. Kernel geometry remains<=64. let stride = if windowed { 64 } else { chunk.len() }; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let stride = if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { - 2 - } else { - stride - }; + let stride = if matches!(boundary, Some(window_numeric::BoundaryPlan::FullMicro2)) { 2 } else { stride }; for first in (0..chunk.len()).step_by(stride) { - let window = if windowed { - Some(chunk.open_micro_window(layer)?) - } else { - None - }; + let window = if windowed { Some(chunk.open_micro_window(layer)?) } else { None }; let count = chunk.micro_len()?; let end = first.checked_add(count).ok_or(Error::Overflow)?; if end > chunk.len() || chunk.micro_row_index(0)? != first { return Err(Error::IdentityMismatch); } let mut attention = Vec::new(); - attention - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + attention.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let mut gr_micro_bank = None; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let mut ple_micro = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) && layer.get() == 1 - { - let (prior, inputs) = chunk.prepare_ple_micro_inputs(layer, |index, txn| { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - InputStage::prepare_ple_micro_input( - binding, - previous[index].as_ref().ok_or(Error::IdentityMismatch)?, - txn, - ) - })?; - Some(InputStage::apply_ple_micro_cached( - binding, - context, - prior, - inputs, - dense_cache, - )?) - } else { - None - }; + let mut ple_micro = + if matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) && layer.get() == 1 { + let (prior, inputs) = chunk.prepare_ple_micro_inputs(layer, |index, txn| { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + InputStage::prepare_ple_micro_input( + binding, + previous[index].as_ref().ok_or(Error::IdentityMismatch)?, + txn, + ) + })?; + Some(InputStage::apply_ple_micro_cached(binding, context, prior, inputs, dense_cache)?) + } else { + None + }; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if micro_gr { let retained_bytes = count.checked_mul(227888).ok_or(Error::Overflow)?; @@ -300,10 +222,7 @@ impl QwenForward { if txn.position().get() != 193 { return Err(Error::IdentityMismatch); } - observed.set(Some(( - index, - closed_end.ok_or(Error::IdentityMismatch)?, - ))); + observed.set(Some((index, closed_end.ok_or(Error::IdentityMismatch)?))); latch.set(true); } if cancelled() { @@ -319,24 +238,12 @@ impl QwenForward { ) }, |inputs| { - let completed = if matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ) { - GrStage::read_micro_attention_native( - binding, - context, - inputs, - dense_cache, - )? - } else { - GrStage::read_micro_attention( - binding, - context, - inputs, - dense_cache, - )? - }; + let completed = + if matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr) { + GrStage::read_micro_attention_native(binding, context, inputs, dense_cache)? + } else { + GrStage::read_micro_attention(binding, context, inputs, dense_cache)? + }; let (bank, rows) = completed.into_parts(); gr_micro_bank = Some(bank); Ok(rows) @@ -354,10 +261,8 @@ impl QwenForward { for (local, prior) in previous[first..end].iter().enumerate() { let index = chunk.micro_row_index(local)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { - observed, - cancelled: latch, - }) = &boundary + if let Some(window_numeric::BoundaryPlan::CancelFirstLayerAt193 { observed, cancelled: latch }) = + &boundary && layer.get() == 0 && index == 193 { @@ -365,8 +270,7 @@ impl QwenForward { if position.get() != 193 { return Err(Error::IdentityMismatch); } - let closed_end = - chunk.test_window_journal().last().map(|(_, _, end)| *end); + let closed_end = chunk.test_window_journal().last().map(|(_, _, end)| *end); observed.set(Some((index, closed_end.ok_or(Error::IdentityMismatch)?))); // Set only at the genuine global row. The unchanged // cancellation callback/fence below performs refusal. @@ -381,25 +285,16 @@ impl QwenForward { index, 1, chunk.read_attention_column(index, layer, |txn| { - let read = read_layer_attention( - binding, - layer, - prior.as_ref(), - txn, - Some(dense_cache), - )?; + let read = + read_layer_attention(binding, layer, prior.as_ref(), txn, Some(dense_cache))?; GrStage::detach_attention(binding, read, txn) }), )?); } } - let native_prompt = matches!( - policy, - ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - ); + let native_prompt = matches!(policy, ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let native_decode_qsa = - dense_cache.has_native_qsa() && descriptor.kind() == BoundLayerKind::Qsa; + let native_decode_qsa = dense_cache.has_native_qsa() && descriptor.kind() == BoundLayerKind::Qsa; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let native_decode_qsa = false; let mut projected = if native_prompt || native_decode_qsa { @@ -426,9 +321,7 @@ impl QwenForward { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let mut native_moe = None; let mut ffn_rows = Vec::new(); - ffn_rows - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + ffn_rows.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(bank) = gr_micro_bank { for slot in &mut previous[first..end] { @@ -508,18 +401,13 @@ impl QwenForward { Some(dense_cache), ), )?; - let prepared = MoeExpertStage::prepare_chunk_row( - binding, layer, ffn, route, txn, - )?; + let prepared = + MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn)?; Ok((prepared, attention.into_edge())) }, ) } else { - chunk.prepare_attention_ffn( - index, - layer, - &attention[local], - |txn, residual| { + chunk.prepare_attention_ffn(index, layer, &attention[local], |txn, residual| { let ffn = if matches!( policy, ChunkMoePolicy::ExperimentalRetainedGr @@ -535,9 +423,7 @@ impl QwenForward { ForwardPhase::Gdn, layer.get(), pos, - if let Some(projection) = - projected[local].first_mut() - { + if let Some(projection) = projected[local].first_mut() { GdnStage::step_projected( binding, layer, @@ -558,11 +444,8 @@ impl QwenForward { ) }, )?; - attention - .validate_origin(&binding.identity())?; - attention - .identity() - .validate(token, pos, layer)?; + attention.validate_origin(&binding.identity())?; + attention.identity().validate(token, pos, layer)?; let pending = attention.take_pending()?; txn.stage_gdn(&prior, pending)?; read_chunk_attention_ffn( @@ -577,61 +460,74 @@ impl QwenForward { } BoundLayerKind::Qsa => { let attention = { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| - diagnose(ForwardPhase::QsaAttention,layer.get(),pos, - QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + ))] + let native = dense_cache + .has_native_qsa() + .then_some(dense_cache) + .map(|cache| { + diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_native( + binding, + layer, + residual.ready(), + txn, + cache, + ), + ) + }) + .transpose()?; + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )))] let native = None; - if let Some(completed)=native { completed } else { + if let Some(completed) = native { + completed + } else { let prior = txn.qsa_prior(layer)?; - let mut prepared = diagnose( - ForwardPhase::QsaIndex, - layer.get(), - pos, - QsaIndexStage::prepare_projected( - binding, - layer, - residual.ready(), + let mut prepared = diagnose( + ForwardPhase::QsaIndex, + layer.get(), pos, - &prior, - txn, - dense_cache, - &mut projected[local], - ), - )?; - prepared.validate_origin( - &binding.identity(), - layer, - )?; - prepared - .identity() - .validate(token, pos, layer)?; - let pending = prepared.take_pending()?; - txn.stage_qsa(&prior, pending)?; - let attention = diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_with_scratch( - binding, - layer, - prepared, - txn, - Some(dense_cache), - dense_cache.qsa_attention_workspace(), - ), - )?; + QsaIndexStage::prepare_projected( + binding, + layer, + residual.ready(), + pos, + &prior, + txn, + dense_cache, + &mut projected[local], + ), + )?; + prepared.validate_origin(&binding.identity(), layer)?; + prepared.identity().validate(token, pos, layer)?; + let pending = prepared.take_pending()?; + txn.stage_qsa(&prior, pending)?; + let attention = diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_with_scratch( + binding, + layer, + prepared, + txn, + Some(dense_cache), + dense_cache.qsa_attention_workspace(), + ), + )?; attention } }; - attention.validate_origin( - &binding.identity(), - layer, - )?; - attention - .identity() - .validate(token, pos, layer)?; + attention.validate_origin(&binding.identity(), layer)?; + attention.identity().validate(token, pos, layer)?; read_chunk_attention_ffn( binding, residual, @@ -655,9 +551,7 @@ impl QwenForward { ForwardPhase::Gdn, layer.get(), pos, - if let Some(projection) = - projected[local].first_mut() - { + if let Some(projection) = projected[local].first_mut() { GdnStage::step_projected( binding, layer, @@ -678,11 +572,8 @@ impl QwenForward { ) }, )?; - attention - .validate_origin(&binding.identity())?; - attention - .identity() - .validate(token, pos, layer)?; + attention.validate_origin(&binding.identity())?; + attention.identity().validate(token, pos, layer)?; let pending = attention.take_pending()?; txn.stage_gdn(&prior, pending)?; diagnose( @@ -700,61 +591,74 @@ impl QwenForward { } BoundLayerKind::Qsa => { let attention = { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - let native = dense_cache.has_native_qsa().then_some(dense_cache).map(|cache| - diagnose(ForwardPhase::QsaAttention,layer.get(),pos, - QsaAttentionStage::decode_native(binding,layer,residual.ready(),txn,cache))).transpose()?; - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + #[cfg(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + ))] + let native = dense_cache + .has_native_qsa() + .then_some(dense_cache) + .map(|cache| { + diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_native( + binding, + layer, + residual.ready(), + txn, + cache, + ), + ) + }) + .transpose()?; + #[cfg(not(all( + any(target_os = "linux", target_os = "windows"), + target_arch = "x86_64" + )))] let native = None; - if let Some(completed)=native { completed } else { + if let Some(completed) = native { + completed + } else { let prior = txn.qsa_prior(layer)?; - let mut prepared = diagnose( - ForwardPhase::QsaIndex, - layer.get(), - pos, - QsaIndexStage::prepare_projected( - binding, - layer, - residual.ready(), + let mut prepared = diagnose( + ForwardPhase::QsaIndex, + layer.get(), pos, - &prior, - txn, - dense_cache, - &mut projected[local], - ), - )?; - prepared.validate_origin( - &binding.identity(), - layer, - )?; - prepared - .identity() - .validate(token, pos, layer)?; - let pending = prepared.take_pending()?; - txn.stage_qsa(&prior, pending)?; - let attention = diagnose( - ForwardPhase::QsaAttention, - layer.get(), - pos, - QsaAttentionStage::decode_with_scratch( - binding, - layer, - prepared, - txn, - Some(dense_cache), - dense_cache.qsa_attention_workspace(), - ), - )?; + QsaIndexStage::prepare_projected( + binding, + layer, + residual.ready(), + pos, + &prior, + txn, + dense_cache, + &mut projected[local], + ), + )?; + prepared.validate_origin(&binding.identity(), layer)?; + prepared.identity().validate(token, pos, layer)?; + let pending = prepared.take_pending()?; + txn.stage_qsa(&prior, pending)?; + let attention = diagnose( + ForwardPhase::QsaAttention, + layer.get(), + pos, + QsaAttentionStage::decode_with_scratch( + binding, + layer, + prepared, + txn, + Some(dense_cache), + dense_cache.qsa_attention_workspace(), + ), + )?; attention } }; - attention.validate_origin( - &binding.identity(), - layer, - )?; - attention - .identity() - .validate(token, pos, layer)?; + attention.validate_origin(&binding.identity(), layer)?; + attention.identity().validate(token, pos, layer)?; diagnose( ForwardPhase::GrAttentionInject, layer.get(), @@ -770,20 +674,13 @@ impl QwenForward { } }; Ok(injected) - })( - ); + })(); let injected = residual.finish(injected_result)?; diagnose( ForwardPhase::GrFfn, layer.get(), pos, - GrStage::read_ffn( - binding, - layer, - &injected, - txn, - Some(dense_cache), - ), + GrStage::read_ffn(binding, layer, &injected, txn, Some(dense_cache)), )? }; (|| { @@ -799,12 +696,9 @@ impl QwenForward { Some(dense_cache), ), )?; - MoeExpertStage::prepare_chunk_row( - binding, layer, ffn, route, txn, - ) + MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn) })() - }, - ) + }) }, )?; ffn_rows.push(prepared); @@ -817,9 +711,7 @@ impl QwenForward { if layer.get() != 0 { return Err(Error::IdentityMismatch); } - MoeExpertStage::test_layer0_same_rows( - binding, layer, &ffn_rows, &mut chunk, moe_cache, - )?; + MoeExpertStage::test_layer0_same_rows(binding, layer, &ffn_rows, &mut chunk, moe_cache)?; // Actual unpublished chunk drops here, before FFN injection/MTP/head. return Err(Error::Unsupported(Stage::Executor)); } @@ -863,23 +755,19 @@ impl QwenForward { } ChunkMoePolicy::ExperimentalResidentMmq | ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr - | ChunkMoePolicy::ExperimentalMtpVerification => { - MoeExpertStage::execute_chunk_mmq( - binding, - layer, - &ffn_rows, - &mut chunk, - moe_cache, - &mut cancelled, - ) - } + | ChunkMoePolicy::ExperimentalMtpVerification => MoeExpertStage::execute_chunk_mmq( + binding, + layer, + &ffn_rows, + &mut chunk, + moe_cache, + &mut cancelled, + ), } } }); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let cleanup = native_moe - .take() - .map_or(Ok(()), |products| products.release()); + let cleanup = native_moe.take().map_or(Ok(()), |products| products.release()); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let cleanup = Ok(()); if cleanup.is_err() { @@ -891,19 +779,14 @@ impl QwenForward { } let mut batch_rows = Vec::new(); let mut proofs = Vec::new(); - batch_rows - .try_reserve_exact(ffn_rows.len()) - .map_err(|_| Error::InputAllocation)?; - proofs - .try_reserve_exact(ffn_rows.len()) - .map_err(|_| Error::InputAllocation)?; + batch_rows.try_reserve_exact(ffn_rows.len()).map_err(|_| Error::InputAllocation)?; + proofs.try_reserve_exact(ffn_rows.len()).map_err(|_| Error::InputAllocation)?; for (local, (row, expert)) in ffn_rows.into_iter().zip(experts).enumerate() { let index = chunk.micro_row_index(local)?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let (prepared, proof) = - chunk.prepare_ffn_injection(index, layer, row, binding, expert)?; + let (prepared, proof) = chunk.prepare_ffn_injection(index, layer, row, binding, expert)?; batch_rows.push(prepared); proofs.push(proof); } @@ -914,16 +797,12 @@ impl QwenForward { Some(layer.get()), first, count, - chunk.batch_outputs(|context| { - GrStage::inject_batch(binding, context, batch_rows, dense_cache) - }), + chunk.batch_outputs(|context| GrStage::inject_batch(binding, context, batch_rows, dense_cache)), )?; if completed.len() != proofs.len() { return Err(Error::IdentityMismatch); } - for ((slot, proof), residual) in - previous[first..end].iter_mut().zip(proofs).zip(completed) - { + for ((slot, proof), residual) in previous[first..end].iter_mut().zip(proofs).zip(completed) { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -941,9 +820,7 @@ impl QwenForward { chunk.finish_gdn_chunk(owner, binding, dense_cache)?; } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if matches!(boundary, Some(window_numeric::BoundaryPlan::FirstLayer)) - && layer.get() == 0 - { + if matches!(boundary, Some(window_numeric::BoundaryPlan::FirstLayer)) && layer.get() == 0 { chunk.test_observe_first_layer(&previous)?; return Ok(chunk); // Deliberately unfinished: cannot warm or publish. } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_targetstepproduct.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_targetstepproduct.rs index 0bccfc5f..caa3d87b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_targetstepproduct.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/impl_targetstepproduct.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl TargetStepProduct { // Only the already checked joint chunk publisher supplies this owned // actual final source. Intermediate rows never have predicted IDs. @@ -11,14 +10,7 @@ impl TargetStepProduct { commit: super::super::super::session::chunk::ChunkCommit, ) -> Option { let (binding, token, position, output, streams, origin) = commit.into_parts(); - output.map(|predicted| Self { - binding, - token, - position, - predicted, - streams, - origin, - }) + output.map(|predicted| Self { binding, token, position, predicted, streams, origin }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs index e59a3de4..0a5788a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_micro_ffn_rows_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Causal attention advances once in the real chunk journal. Its completed /// blocks are coupled to the retained GR bank, which then performs one whole /// FFN read before actual per-row routing. No detached row is reconstructed. @@ -32,12 +31,8 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( } let mut blocks = Vec::new(); let mut proofs = Vec::new(); - blocks - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - proofs - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + blocks.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + proofs.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; if native_prompt && kind == BoundLayerKind::Gdn { let owner = device_gdn.as_deref_mut().ok_or(Error::IdentityMismatch)?; if cancelled() { @@ -47,36 +42,19 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( layer, attention, |micro, current| { - let mut resources = cache - .gdn_batch_resources(binding, current)? - .ok_or(Error::IdentityMismatch)?; - let mut workspace = cache - .native_batch_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; - let gemm = workspace - .gdn_gemm() - .map_err(super::super::super::gdn::driver_error)?; + let mut resources = cache.gdn_batch_resources(binding, current)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; + let gemm = workspace.gdn_gemm().map_err(super::super::super::gdn::driver_error)?; // Keep both real owners and the exclusive shared stream loan // alive until the whole producer's complete finite drain. - GdnStage::step_chunk_batch( - binding, - layer, - micro, - current, - cache, - owner, - &mut resources, - &gemm, - ) + GdnStage::step_chunk_batch(binding, layer, micro, current, cache, owner, &mut resources, &gemm) }, |local, txn, read, result| { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } result.validate_origin(&binding.identity())?; - result - .identity() - .validate(txn.token(), txn.position(), layer)?; + result.identity().validate(txn.token(), txn.position(), layer)?; let block = GrStage::prepare_micro_attention_block( binding, &bank, @@ -100,12 +78,8 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( let inputs = attention.iter().map(|row| row.ready()).collect::>(); let current = cache.retained_context(binding, chunk.context()?)?; let mut native = { - let mut owner = cache - .qsa_native_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; - let mut workspace = cache - .native_batch_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; + let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; super::super::super::qsa_prefill_batch::project( binding, cache, @@ -117,13 +91,10 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( )? }; let mut attended = Vec::new(); - attended - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + attended.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; { let mut resources = cache.native_qsa(binding, current)?; - let slot = - super::super::super::qsa_native_resources::NativeQsaResources::layer_slot(layer.get())?; + let slot = super::super::super::qsa_native_resources::NativeQsaResources::layer_slot(layer.get())?; let super::super::super::qsa_native_resources::NativeQsaResources { index, stage, @@ -133,9 +104,7 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( } = &mut *resources; let kv = kv.get_mut(slot).ok_or(Error::IdentityMismatch)?; let prior = chunk.prompt_native_qsa_prior(layer, kv)?; - let mut workspace = cache - .native_batch_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; let index = super::super::super::qsa_prompt_index::prepare( binding, cache, @@ -165,14 +134,9 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( return Err(Error::Unsupported(Stage::Executor)); } let index = chunk.micro_row_index(local)?; - let (row, proof) = chunk.prepare_attention_layer_batch( - index, - layer, - source, - |txn, read| { - completed.publish_row(binding, cache, txn, layer, read.ready(), kv) - }, - )?; + let (row, proof) = chunk.prepare_attention_layer_batch(index, layer, source, |txn, read| { + completed.publish_row(binding, cache, txn, layer, read.ready(), kv) + })?; attended.push(row); proofs.push(proof); } @@ -186,12 +150,8 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( return Err(Error::Unsupported(Stage::Executor)); } let output = { - let mut owner = cache - .qsa_native_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; - let mut workspace = cache - .native_batch_workspace(binding, current)? - .ok_or(Error::IdentityMismatch)?; + let mut owner = cache.qsa_native_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, current)?.ok_or(Error::IdentityMismatch)?; super::super::super::qsa_prefill_batch::project_out( binding, cache, @@ -207,29 +167,23 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( return Err(Error::IdentityMismatch); } for (local, (result, source)) in output.into_iter().zip(attention).enumerate() { - blocks.push(chunk.prepare_attention_output_after_causal( - &proofs[local], - source, - |txn, read| { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - attended[local].validate_for_txn(binding, txn, layer)?; - result.validate_origin(&binding.identity(), layer)?; - result - .identity() - .validate(txn.token(), txn.position(), layer)?; - GrStage::prepare_micro_attention_block( - binding, - &bank, - local, - read, - result.output(), - result.identity(), - txn, - ) - }, - )?); + blocks.push(chunk.prepare_attention_output_after_causal(&proofs[local], source, |txn, read| { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + attended[local].validate_for_txn(binding, txn, layer)?; + result.validate_origin(&binding.identity(), layer)?; + result.identity().validate(txn.token(), txn.position(), layer)?; + GrStage::prepare_micro_attention_block( + binding, + &bank, + local, + read, + result.output(), + result.identity(), + txn, + ) + })?); } } else { for (local, source) in attention.iter().enumerate() { @@ -280,24 +234,9 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( layer.get(), position, if let Some(projection) = projected[local].first_mut() { - GdnStage::step_projected( - binding, - layer, - read.ready(), - &prior, - txn, - cache, - projection, - ) + GdnStage::step_projected(binding, layer, read.ready(), &prior, txn, cache, projection) } else { - GdnStage::step( - binding, - layer, - read.ready(), - &prior, - txn, - Some(cache), - ) + GdnStage::step(binding, layer, read.ready(), &prior, txn, Some(cache)) }, )?; result.validate_origin(&binding.identity())?; @@ -325,13 +264,7 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( ForwardPhase::QsaAttention, layer.get(), position, - QsaAttentionStage::decode_native( - binding, - layer, - read.ready(), - txn, - cache, - ), + QsaAttentionStage::decode_native(binding, layer, read.ready(), txn, cache), ) }) .transpose()?; @@ -397,8 +330,7 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let reads = chunk - .batch_outputs(|_| GrStage::inject_micro_attention_ffn(binding, bank, blocks, cache))?; + let reads = chunk.batch_outputs(|_| GrStage::inject_micro_attention_ffn(binding, bank, blocks, cache))?; if reads.len() != proofs.len() { return Err(Error::IdentityMismatch); } @@ -414,31 +346,20 @@ pub(super) fn prepare_micro_ffn_rows<'source, 'ctx, 'driver>( super::super::super::moe_prefill_batch::MoeBf16Profile::HighOnly, )?; moe_cache.reserve_mmq_transient(binding, current, transient)?; - moe_cache.with_native_shared_weights( - binding, - current, - layer, - transient, - |context, weights, resources| { - cache.retained_context(binding, context)?; - let mut workspace = cache - .native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; - let gemm = workspace - .gdn_gemm() - .map_err(super::super::super::qsa_index::driver_error)?; - super::super::super::moe_prefill_batch::MoePrefillStage::route_shared_micro( - binding, layer, &inputs, context, router, weights, None, resources, &gemm, - ) - }, - ) + moe_cache.with_native_shared_weights(binding, current, layer, transient, |context, weights, resources| { + cache.retained_context(binding, context)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let gemm = workspace.gdn_gemm().map_err(super::super::super::qsa_index::driver_error)?; + super::super::super::moe_prefill_batch::MoePrefillStage::route_shared_micro( + binding, layer, &inputs, context, router, weights, None, resources, &gemm, + ) + }) })?) } else { None }; let mut rows = Vec::new(); - rows.try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; for (local, (proof, read)) in proofs.into_iter().zip(reads).enumerate() { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_q6_layer_columns_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_q6_layer_columns_fn.rs index 6a69bb50..c7a5772a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_q6_layer_columns_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/prepare_q6_layer_columns_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn prepare_q6_layer_columns<'source, 'ctx>( binding: &ModelBinding, cache: &DenseWeightCache<'ctx>, @@ -14,26 +13,18 @@ pub(super) fn prepare_q6_layer_columns<'source, 'ctx>( retain_gdn_qkv: bool, ) -> Result>>> { use super::super::super::q6_attention_columns::{self, Role}; - use crate::model_binding::qwen4exp_input::{ - GdnMatrixKind, GdnMatrixRole, QsaMatrixKind, QsaMatrixRole, - }; + use crate::model_binding::qwen4exp_input::{GdnMatrixKind, GdnMatrixRole, QsaMatrixKind, QsaMatrixRole}; let mut columns = Vec::new(); - columns - .try_reserve_exact(attention.len()) - .map_err(|_| Error::InputAllocation)?; + columns.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; columns.resize_with(attention.len(), Vec::new); let mut inputs = Vec::new(); - inputs - .try_reserve_exact(attention.len()) - .map_err(|_| Error::InputAllocation)?; + inputs.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in attention.iter().enumerate() { chunk.validate_attention_column(chunk.micro_row_index(index)?, layer, row)?; inputs.push(row.ready()); } let mut roles = Vec::new(); - roles - .try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + roles.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; match kind { BoundLayerKind::Gdn => { let entry = cache.gdn(binding, layer.get())?; @@ -43,11 +34,9 @@ pub(super) fn prepare_q6_layer_columns<'source, 'ctx>( } BoundLayerKind::Qsa => { let entry = cache.qsa(binding, layer.get())?; - for (matrix, role) in [ - (QsaMatrixRole::Q, Role::QsaQ), - (QsaMatrixRole::K, Role::QsaK), - (QsaMatrixRole::V, Role::QsaV), - ] { + for (matrix, role) in + [(QsaMatrixRole::Q, Role::QsaQ), (QsaMatrixRole::K, Role::QsaK), (QsaMatrixRole::V, Role::QsaV)] + { if cache.qsa_matrix(entry, matrix)?.1 == QsaMatrixKind::Q6K { roles.push(role); } @@ -70,8 +59,7 @@ pub(super) fn prepare_q6_layer_columns<'source, 'ctx>( return Err(Error::IdentityMismatch); } for (slot, row) in columns.iter_mut().zip(rows) { - slot.try_reserve_exact(1) - .map_err(|_| Error::InputAllocation)?; + slot.try_reserve_exact(1).map_err(|_| Error::InputAllocation)?; slot.push(row); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/read_chunk_attention_ffn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/read_chunk_attention_ffn_fn.rs index 228e4848..1509fff1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/read_chunk_attention_ffn_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_prefill_chunk/read_chunk_attention_ffn_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // Explicit private entry selects the retained path. Normal serving enters // prepare_prefill_chunk_cached(false) and keeps its original host transport. pub(super) fn read_chunk_attention_ffn<'cache, 'ctx>( @@ -24,12 +23,7 @@ pub(super) fn read_chunk_attention_ffn<'cache, 'ctx>( pos, GrStage::inject_retained(binding, residual, block, identity, txn, cache), )?; - diagnose( - ForwardPhase::GrFfn, - layer.get(), - pos, - GrStage::read_retained_ffn(binding, owner, txn, cache), - ) + diagnose(ForwardPhase::GrFfn, layer.get(), pos, GrStage::read_retained_ffn(binding, owner, txn, cache)) } else { let result = diagnose( ForwardPhase::GrAttentionInject, @@ -38,12 +32,7 @@ pub(super) fn read_chunk_attention_ffn<'cache, 'ctx>( GrStage::inject_detached(binding, residual, block, identity, txn), ); let injected = residual.finish(result)?; - diagnose( - ForwardPhase::GrFfn, - layer.get(), - pos, - GrStage::read_ffn(binding, layer, &injected, txn, Some(cache)), - ) + diagnose(ForwardPhase::GrFfn, layer.get(), pos, GrStage::read_ffn(binding, layer, &injected, txn, Some(cache))) } } @@ -63,12 +52,7 @@ impl QwenForward { } let observation = crate::qwen_forward::layer0_mmq_observation::Scope::begin()?; let vocab = Dimension::new(248320)?; - let ids = [ - TokenId::new(0, vocab)?, - TokenId::new(1, vocab)?, - TokenId::new(0, vocab)?, - TokenId::new(1, vocab)?, - ]; + let ids = [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?, TokenId::new(1, vocab)?]; let result = Self::prepare_prefill_chunk_with_policy( binding, &ids, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs index 900c784a..6ae90e3a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/executor_window_numeric.rs @@ -8,10 +8,7 @@ use std::{cell::Cell, rc::Rc}; pub(super) enum BoundaryPlan { FullMicro2, FirstLayer, - CancelFirstLayerAt193 { - observed: Rc>>, - cancelled: Rc>, - }, + CancelFirstLayerAt193 { observed: Rc>>, cancelled: Rc> }, } struct PartialReport { @@ -100,17 +97,13 @@ impl QwenForward { fn owned_journal(txn: &QwenChunkTxn<'_, '_>) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(txn.test_window_journal().len()) - .map_err(|_| Error::InputAllocation)?; + result.try_reserve_exact(txn.test_window_journal().len()).map_err(|_| Error::InputAllocation)?; result.extend_from_slice(txn.test_window_journal()); Ok(result) } fn tokens(count: usize, vocab: Dimension) -> Result> { let mut result = Vec::new(); - result - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + result.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; for index in 0..count { result.push(TokenId::new((index % 2) as u64, vocab)?); } @@ -130,10 +123,7 @@ fn run<'driver>( let ids = tokens(4, vocab)?; let next = TokenId::new(0, vocab)?; let follow = TokenId::new(1, vocab)?; - if !session - .test_reset_replay_snapshot(binding)? - .has_prefix(0, [-1, -1]) - { + if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) { return Err(Error::IdentityMismatch); } output.test_reset_replay_record(true)?; @@ -159,9 +149,7 @@ fn run<'driver>( let baseline_greedy = baseline.predicted(session)?; let baseline_stream = baseline.streams(binding, ids[3], Position::new(3, bounds)?, session)?; let mut baseline_bits = Vec::new(); - baseline_bits - .try_reserve_exact(baseline_stream.len()) - .map_err(|_| Error::InputAllocation)?; + baseline_bits.try_reserve_exact(baseline_stream.len()).map_err(|_| Error::InputAllocation)?; baseline_bits.extend(baseline_stream.iter().map(|v| v.to_bits())); let baseline_target = session.test_reset_replay_snapshot(binding)?; let baseline_mtp = baseline_draft.test_chunk_snapshot(); @@ -203,31 +191,20 @@ fn run<'driver>( )?; let journal = owned_journal(&txn)?; let ready = candidate_draft.stage_prefill_chunk(binding, &mut txn, moe, || false)?; - let source = txn - .publish_joint(ready)? - .into_target_product() - .ok_or(Error::IdentityMismatch)?; + let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?; (source, journal) }; let candidate_logits = output.test_reset_replay_take_logits()?; let logit_words = candidate_logits.len(); let logit_differences = if baseline_logits.len() == candidate_logits.len() { - baseline_logits - .iter() - .zip(candidate_logits.iter()) - .filter(|(a, b)| a != b) - .count() + baseline_logits.iter().zip(candidate_logits.iter()).filter(|(a, b)| a != b).count() } else { usize::MAX }; let actual_stream = candidate.streams(binding, ids[3], Position::new(3, bounds)?, session)?; let residual_words = actual_stream.len(); let residual_differences = if baseline_bits.len() == actual_stream.len() { - baseline_bits - .iter() - .zip(actual_stream.iter()) - .filter(|(a, b)| **a != b.to_bits()) - .count() + baseline_bits.iter().zip(actual_stream.iter()).filter(|(a, b)| **a != b.to_bits()).count() } else { usize::MAX }; @@ -247,8 +224,7 @@ fn run<'driver>( dense, )?; candidate_draft.warm_prefill(binding, session, &continuation, follow, moe)?; - let continued_target_equal = - continued_target.numeric_eq(&session.test_reset_replay_snapshot(binding)?); + let continued_target_equal = continued_target.numeric_eq(&session.test_reset_replay_snapshot(binding)?); let continued_draft_equal = candidate_draft.test_chunk_eq(&continued_mtp); drop(continuation); drop(candidate); @@ -263,9 +239,7 @@ fn run<'driver>( // B: genuine65/193/256 row inputs and real first-layer outputs, not a // metadata-only fabricated completion. No finish/head/MTP publication. let mut partials = Vec::new(); - partials - .try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + partials.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; for count in [65, 193, 256] { QwenForward::reset(session)?; let fresh = session.test_reset_replay_snapshot(binding)?; @@ -291,10 +265,8 @@ fn run<'driver>( let finite_words = txn.test_partial_words(); let journal = owned_journal(&txn)?; let publication_refused = txn.test_publication_preflight_refused(); - let mtp_refused = matches!( - draft.stage_prefill_chunk(binding, &mut txn, moe, || false), - Err(Error::IdentityMismatch) - ); + let mtp_refused = + matches!(draft.stage_prefill_chunk(binding, &mut txn, moe, || false), Err(Error::IdentityMismatch)); (finite_words, journal, publication_refused, mtp_refused) }; partials.push(PartialReport { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs index 3bd12076..2427656c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn.rs @@ -6,12 +6,11 @@ use super::dense_weight_cache::DenseWeightCache; use super::gr::ResidualReady; use super::session::QwenStepTxn; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, - InputBindingError, ModelBinding, + BindingIdentity, BoundLayerKind, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, InputBindingError, ModelBinding, }; use leleka_cuda_driver::{ - Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, - ProjectionSpec, Q5KProjectionShape, Q6KProjectionShape, + Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, ProjectionSpec, + Q5KProjectionShape, Q6KProjectionShape, }; #[path = "gdn_state.rs"] mod state; @@ -27,17 +26,17 @@ pub(super) use input_scratch::{GdnInputLease, GdnInputScratch}; mod chain; pub(in crate::qwen_forward) use chain::QkScratch; // Original default fused T1 step (STRA-169): runtime entry of the closed `GdnFusedT1` driver program. -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "gdn_fused_t1_step.rs"] -mod fused_t1_step; +#[path = "gdn_chunk_device.rs"] +pub(in crate::qwen_forward) mod chunk_device; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_chunk_fused.rs"] mod chunk_fused; -#[path = "gdn_chunk_device.rs"] -pub(in crate::qwen_forward) mod chunk_device; #[path = "gdn_chunk_producer.rs"] mod chunk_producer; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "gdn_fused_t1_step.rs"] +mod fused_t1_step; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_prefill_batch.rs"] pub(in crate::qwen_forward) mod prefill_batch; #[path = "gdn_verification.rs"] @@ -83,27 +82,12 @@ mod tests { #[test] fn budget_and_typed_failures_refuse_before_weights() { assert_eq!(preflight_budget(DEVICE_PEAK, 0), Ok(())); - assert_eq!( - preflight_budget(DEVICE_PEAK, 1), - Err(Error::InputAllocation) - ); - assert_eq!( - preflight_budget(usize::MAX, usize::MAX), - Err(Error::InputAllocation) - ); + assert_eq!(preflight_budget(DEVICE_PEAK, 1), Err(Error::InputAllocation)); + assert_eq!(preflight_budget(usize::MAX, usize::MAX), Err(Error::InputAllocation)); assert_eq!(binding_error(InputBindingError::Read), Error::InputRead); - assert_eq!( - binding_error(InputBindingError::Allocation), - Error::InputAllocation - ); - assert_eq!( - driver_error(DriverError::UnsupportedQwenOperation), - Error::Unsupported(Stage::Gdn) - ); - assert_eq!( - driver_error(DriverError::ContextPoisoned), - Error::CudaExecution - ); + assert_eq!(binding_error(InputBindingError::Allocation), Error::InputAllocation); + assert_eq!(driver_error(DriverError::UnsupportedQwenOperation), Error::Unsupported(Stage::Gdn)); + assert_eq!(driver_error(DriverError::ContextPoisoned), Error::CudaExecution); } #[test] fn branch_free_finite_check_equals_is_finite() { @@ -142,12 +126,7 @@ mod tests { #[test] fn original_state_layout_and_modulo_mapping_distinguish_rivals() { // Literal source addresses from native_gdn.cu, independent of PTX. - for (r, h, c, index) in [ - (0, 0, 0, 0), - (0, 1, 0, 128), - (1, 0, 0, 6144), - (127, 47, 127, 786431), - ] { + for (r, h, c, index) in [(0, 0, 0, 0), (0, 1, 0, 128), (1, 0, 0, 6144), (127, 47, 127, 786431)] { assert_eq!(state_index(r, h, c), Ok(index)); } for (h, k) in [(0, 0), (15, 15), (16, 0), (31, 15), (32, 0), (47, 15)] { @@ -181,10 +160,7 @@ mod tests { ), Err(Error::NonFinite) )); - assert_eq!( - prior.iter().map(|v| v.to_bits()).collect::>(), - prior_bits - ); + assert_eq!(prior.iter().map(|v| v.to_bits()).collect::>(), prior_bits); } assert!(matches!( validate_candidates( @@ -203,14 +179,7 @@ mod tests { ) .unwrap(); assert_eq!(ready.0, identity()); - assert!( - ready - .1 - .iter() - .chain(ready.2.iter()) - .chain(ready.3.iter()) - .all(|v| v.to_bits() == 0x80000000) - ); + assert!(ready.1.iter().chain(ready.2.iter()).chain(ready.3.iter()).all(|v| v.to_bits() == 0x80000000)); } #[test] fn finite_input_overflow_must_not_hide_behind_sigmoid_zero() { @@ -219,10 +188,7 @@ mod tests { assert!(exponential.is_infinite()); assert_eq!(1.0 / (1.0 + exponential), 0.0); assert_eq!(validate_values(&[exponential], 1), Err(Error::NonFinite)); - assert_eq!( - validate_values(&[f32::NEG_INFINITY], 1), - Err(Error::NonFinite) - ); + assert_eq!(validate_values(&[f32::NEG_INFINITY], 1), Err(Error::NonFinite)); } } @@ -242,58 +208,58 @@ mod impl_gdnready; mod impl_gdnstage; mod step_cached_fn; #[allow(unused_imports)] -use step_cached_fn::step_cached; +use step_cached_fn::preflight_budget; #[allow(unused_imports)] use step_cached_fn::project_chain_input; #[allow(unused_imports)] -use step_cached_fn::preflight_budget; +use step_cached_fn::step_cached; mod project_fn; #[allow(unused_imports)] -use project_fn::project; -#[allow(unused_imports)] -use project_fn::dispatch_projection; -#[allow(unused_imports)] -use project_fn::project_retained; -#[allow(unused_imports)] use project_fn::convolve; #[allow(unused_imports)] +use project_fn::dispatch_projection; +#[allow(unused_imports)] use project_fn::normalize_qk; +#[allow(unused_imports)] +use project_fn::project; +#[allow(unused_imports)] +use project_fn::project_retained; mod gates_fn; #[allow(unused_imports)] -use gates_fn::gates; -#[allow(unused_imports)] -use gates_fn::recur; -#[allow(unused_imports)] -use gates_fn::out_norm; -#[allow(unused_imports)] -use gates_fn::allocate; -#[allow(unused_imports)] -use gates_fn::upload; -#[allow(unused_imports)] -pub(super) use gates_fn::pool_enabled; -#[allow(unused_imports)] -pub(crate) use gates_fn::set_pool_override; -#[allow(unused_imports)] -use gates_fn::download_unchecked; -#[allow(unused_imports)] -use gates_fn::download; -#[allow(unused_imports)] -use gates_fn::release; -#[allow(unused_imports)] -use gates_fn::zeros; -#[allow(unused_imports)] -use gates_fn::validate_values; -#[allow(unused_imports)] use gates_fn::all_finite; #[allow(unused_imports)] +use gates_fn::allocate; +#[allow(unused_imports)] use gates_fn::binding_error; +#[allow(unused_imports)] +use gates_fn::download; +#[allow(unused_imports)] +use gates_fn::download_unchecked; +#[allow(unused_imports)] +use gates_fn::gates; +#[allow(unused_imports)] +use gates_fn::out_norm; +#[allow(unused_imports)] +pub(super) use gates_fn::pool_enabled; +#[allow(unused_imports)] +use gates_fn::recur; +#[allow(unused_imports)] +use gates_fn::release; +#[allow(unused_imports)] +pub(crate) use gates_fn::set_pool_override; +#[allow(unused_imports)] +use gates_fn::upload; +#[allow(unused_imports)] +use gates_fn::validate_values; +#[allow(unused_imports)] +use gates_fn::zeros; mod driver_error_fn; #[allow(unused_imports)] pub(super) use driver_error_fn::driver_error; +#[allow(unused_imports)] +use driver_error_fn::key_head; +#[allow(unused_imports)] +use driver_error_fn::state_index; #[cfg(test)] #[allow(unused_imports)] use driver_error_fn::validate_candidates; -#[allow(unused_imports)] -use driver_error_fn::state_index; -#[allow(unused_imports)] -use driver_error_fn::key_head; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error_fn.rs index 247c5169..f25aedf4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/driver_error_fn.rs @@ -4,7 +4,9 @@ use super::*; pub(in super::super) fn driver_error(error: DriverError) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } match error { DriverError::UnsupportedQwenOperation | DriverError::UnsupportedProjection diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/gates_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/gates_fn.rs index ce5f0be9..4966ee3e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/gates_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/gates_fn.rs @@ -16,33 +16,15 @@ pub(super) fn gates( } let alpha = upload(context, alpha)?; let beta = upload(context, beta)?; - let dt_owned = if resident.is_none() { - Some(upload(context, dt)?) - } else { - None - }; - let a_owned = if resident.is_none() { - Some(upload(context, a)?) - } else { - None - }; - let dt = resident - .map(|v| v[0]) - .or(dt_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let a = resident - .map(|v| v[1]) - .or(a_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; + let dt_owned = if resident.is_none() { Some(upload(context, dt)?) } else { None }; + let a_owned = if resident.is_none() { Some(upload(context, a)?) } else { None }; + let dt = resident.map(|v| v[0]).or(dt_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let a = resident.map(|v| v[1]).or(a_owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut gate = allocate(context, 48)?; let mut sigmoid = allocate(context, 48)?; - context - .gdn_beta_sigmoid_f32(&beta, &mut sigmoid) - .map_err(driver_error)?; + context.gdn_beta_sigmoid_f32(&beta, &mut sigmoid).map_err(driver_error)?; let sigmoid_values = download(&sigmoid, 48)?; - context - .gdn_gate_softplus_f32(&alpha, dt, a, &mut gate) - .map_err(driver_error)?; + context.gdn_gate_softplus_f32(&alpha, dt, a, &mut gate).map_err(driver_error)?; let gate_values = download(&gate, 48)?; release([alpha, beta, gate, sigmoid])?; if let Some(v) = dt_owned { @@ -63,14 +45,7 @@ pub(super) fn recur( gate: &[f32], beta: &[f32], ) -> Result { - for (values, count) in [ - (state, STATE_ELEMENTS), - (q, 2048), - (k, 2048), - (v, VALUES), - (gate, 48), - (beta, 48), - ] { + for (values, count) in [(state, STATE_ELEMENTS), (q, 2048), (k, 2048), (v, VALUES), (gate, 48), (beta, 48)] { validate_values(values, count)?; } let state = upload(context, state)?; @@ -81,9 +56,7 @@ pub(super) fn recur( let beta = upload(context, beta)?; let mut next = allocate(context, STATE_ELEMENTS)?; let mut output = allocate(context, VALUES)?; - context - .gdn_step_f32(&state, &q, &k, &v, &gate, &beta, &mut next, &mut output) - .map_err(driver_error)?; + context.gdn_step_f32(&state, &q, &k, &v, &gate, &beta, &mut next, &mut output).map_err(driver_error)?; let next_values = download(&next, STATE_ELEMENTS)?; let output_values = download(&output, VALUES)?; release([state, q, k, v, gate, beta, next, output])?; @@ -102,16 +75,10 @@ pub(super) fn out_norm( validate_values(gamma, 128)?; let input = upload(context, input)?; let z = upload(context, z)?; - let owned = if resident.is_none() { - Some(upload(context, gamma)?) - } else { - None - }; + let owned = if resident.is_none() { Some(upload(context, gamma)?) } else { None }; let gamma = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut output = allocate(context, VALUES)?; - context - .gdn_out_norm_f32(&input, &z, gamma, &mut output, epsilon) - .map_err(driver_error)?; + context.gdn_out_norm_f32(&input, &z, gamma, &mut output, epsilon).map_err(driver_error)?; let values = download(&output, VALUES)?; release([input, z, output])?; if let Some(v) = owned { @@ -120,16 +87,12 @@ pub(super) fn out_norm( Ok(values) } pub(super) fn allocate<'a>(context: &'a Context<'_>, count: usize) -> Result> { - context - .allocate(count.checked_mul(4).ok_or(Error::Overflow)?) - .map_err(driver_error) + context.allocate(count.checked_mul(4).ok_or(Error::Overflow)?).map_err(driver_error) } pub(super) fn upload<'a>(context: &'a Context<'_>, values: &[f32]) -> Result> { validate_values(values, values.len())?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; bytes.resize(values.len() * 4, 0); for (word, value) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(values) { *word = value.to_le_bytes(); @@ -167,16 +130,8 @@ pub(super) fn download(buffer: &DeviceBuffer<'_>, count: usize) -> Result() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); validate_values(&values, count)?; Ok(values.into_boxed_slice()) } @@ -191,9 +146,7 @@ pub(super) fn release(buffers: [DeviceBuffer<'_>; N]) -> Result< } pub(super) fn zeros(count: usize) -> Result> { let mut values = Vec::new(); - values - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; values.resize(count, 0.0); Ok(values.into_boxed_slice()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/impl_gdnstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/impl_gdnstage.rs index dd1d1ef3..a8a5aed8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/impl_gdnstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/impl_gdnstage.rs @@ -21,8 +21,7 @@ impl GdnStage { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if cache.has_native_qsa() { let program = cache.native_gdn_fused(binding, txn.cuda_context()?)?; - return Self::step_chunk_fused(binding, layer, input, txn, cache, - owner, row, program, projection); + return Self::step_chunk_fused(binding, layer, input, txn, cache, owner, row, program, projection); } Self::step_chunk(binding, layer, input, txn, cache, owner, row, projection) } @@ -45,15 +44,7 @@ impl GdnStage { cache: &DenseWeightCache<'_>, projection: &mut super::super::q6_attention_columns::ProjectionRow<'_, '_>, ) -> Result { - Self::step_impl( - binding, - layer, - input, - prior, - txn, - Some(cache), - Some(projection), - ) + Self::step_impl(binding, layer, input, prior, txn, Some(cache), Some(projection)) } pub(super) fn step_impl( binding: &ModelBinding, @@ -68,25 +59,17 @@ impl GdnStage { if let Some(cache) = cache.filter(|cache| cache.has_native_qsa()) { let owner = cache.native_gdn_fused(binding, txn.cuda_context()?)?; let mut fused = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - return Self::step_fused(binding, layer, input, prior, txn, cache, - &mut fused, projection); + return Self::step_fused(binding, layer, input, prior, txn, cache, &mut fused, projection); } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); txn.validate_binding(&binding.identity())?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer || input.identity().layer() != layer { return Err(Error::IdentityMismatch); } - let descriptor = binding - .ordered_layers() - .get(layer.get() as usize) - .ok_or(Error::InvalidLayer)?; + let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { return Err(Error::InvalidLayer); } @@ -97,150 +80,57 @@ impl GdnStage { let context = txn.cuda_context()?; preflight_budget(context.budget_bytes(), context.allocated_bytes())?; if let Some(cache) = cache { - return step_cached( - binding, layer, input, prior, context, cache, txn, projection, - ); + return step_cached(binding, layer, input, prior, context, cache, txn, projection); } if projection.is_some() { return Err(Error::IdentityMismatch); } let resident = cache.map(|c| c.gdn(binding, layer.get())).transpose()?; - let mut mirror = cache - .map(|c| c.gdn_mirror(binding, layer.get(), context)) - .transpose()?; + let mut mirror = cache.map(|c| c.gdn_mirror(binding, layer.get(), context)).transpose()?; let mut mirror_next = None; let operation = (|| -> Result { - let input_lease = cache - .map(|c| c.gdn_input(binding, layer.get(), context, input.mixed())) - .transpose()?; + let input_lease = cache.map(|c| c.gdn_input(binding, layer.get(), context, input.mixed())).transpose()?; let weights = if let Some(r) = resident { r.weights.clone() } else { std::rc::Rc::new(binding.gdn_weights(layer.get()).map_err(binding_error)?) }; let aux = cache.zip(resident).map(|(c, r)| c.gdn_aux(r)).transpose()?; - let qkv = project( - context, - binding, - &weights, - GdnMatrixRole::Qkv, - input.mixed(), - cache, - input_lease.as_ref(), - )?; - let (history, h) = convolve( - context, - prior.history(), - &qkv, - weights.conv(), - aux.map(|v| v[0]), - )?; + let qkv = + project(context, binding, &weights, GdnMatrixRole::Qkv, input.mixed(), cache, input_lease.as_ref())?; + let (history, h) = convolve(context, prior.history(), &qkv, weights.conv(), aux.map(|v| v[0]))?; let qk = normalize_qk(context, &h, weights.epsilon())?; - let alpha = project( - context, - binding, - &weights, - GdnMatrixRole::Alpha, - input.mixed(), - cache, - input_lease.as_ref(), - )?; - let beta_raw = project( - context, - binding, - &weights, - GdnMatrixRole::Beta, - input.mixed(), - cache, - input_lease.as_ref(), - )?; - let (gate, beta) = gates( - context, - &alpha, - &beta_raw, - weights.dt(), - weights.a(), - aux.map(|v| [v[1], v[2]]), - )?; + let alpha = + project(context, binding, &weights, GdnMatrixRole::Alpha, input.mixed(), cache, input_lease.as_ref())?; + let beta_raw = + project(context, binding, &weights, GdnMatrixRole::Beta, input.mixed(), cache, input_lease.as_ref())?; + let (gate, beta) = gates(context, &alpha, &beta_raw, weights.dt(), weights.a(), aux.map(|v| [v[1], v[2]]))?; let (next_state, readout) = if let Some(mirror) = mirror.as_deref_mut() { - let (readout, next) = mirror.compute( - prior, - &qk[..2048], - &qk[2048..4096], - &h[4096..], - &gate, - &beta, - )?; + let (readout, next) = mirror.compute(prior, &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?; mirror_next = Some(next); (None, readout) } else { - let (state, readout) = recur( - context, - prior.values(), - &qk[..2048], - &qk[2048..4096], - &h[4096..], - &gate, - &beta, - )?; + let (state, readout) = + recur(context, prior.values(), &qk[..2048], &qk[2048..4096], &h[4096..], &gate, &beta)?; (Some(state), readout) }; - let z = project( - context, - binding, - &weights, - GdnMatrixRole::Z, - input.mixed(), - cache, - input_lease.as_ref(), - )?; - let normalized = out_norm( - context, - &readout, - &z, - weights.norm(), - weights.epsilon(), - aux.map(|v| v[3]), - )?; - let output = project( - context, - binding, - &weights, - GdnMatrixRole::Out, - &normalized, - cache, - None, - )?; + let z = project(context, binding, &weights, GdnMatrixRole::Z, input.mixed(), cache, input_lease.as_ref())?; + let normalized = out_norm(context, &readout, &z, weights.norm(), weights.epsilon(), aux.map(|v| v[3]))?; + let output = project(context, binding, &weights, GdnMatrixRole::Out, &normalized, cache, None)?; validate_values(&output, 2560)?; // No numeric/session candidate can retain the scratch borrow. drop(input_lease); let pending = if let Some(next) = mirror_next.take() { - mirror - .as_deref_mut() - .ok_or(Error::IdentityMismatch)? - .publish(next, input.identity(), history)? + mirror.as_deref_mut().ok_or(Error::IdentityMismatch)?.publish(next, input.identity(), history)? } else { - GdnPending::new( - prior, - input.identity(), - next_state.ok_or(Error::IdentityMismatch)?, - history, - )? + GdnPending::new(prior, input.identity(), next_state.ok_or(Error::IdentityMismatch)?, history)? }; - Ok(GdnReady { - identity: input.identity(), - binding: binding.identity(), - output, - pending: Some(pending), - }) + Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) }) })(); if let Some(next) = mirror_next { // Downstream failures never publish a mirror key. Explicitly free // the completed candidate; cleanup uncertainty poisons the cache. - let cleanup = mirror - .as_deref_mut() - .ok_or(Error::IdentityMismatch)? - .discard(next); + let cleanup = mirror.as_deref_mut().ok_or(Error::IdentityMismatch)?.discard(next); if operation.is_ok() { cleanup?; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/project_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/project_fn.rs index ff7d0969..643e38ae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/project_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/project_fn.rs @@ -15,13 +15,7 @@ pub(super) fn project( let (c, r) = weights.shape(role); validate_values(activation, c)?; if let Some(source) = source { - source.buffer( - &binding.identity(), - context, - weights.layer(), - role, - activation, - )?; + source.buffer(&binding.identity(), context, weights.layer(), role, activation)?; let cache = cache.ok_or(Error::IdentityMismatch)?; let entry = cache.gdn(binding, weights.layer())?; if !std::ptr::eq(entry.weights.as_ref(), weights) { @@ -36,12 +30,8 @@ pub(super) fn project( let entry = cache.gdn(binding, weights.layer())?; cache.gdn_matrix(entry, role)? } else { - let block = binding - .gdn_matrix_block(weights, role, 0, r) - .map_err(binding_error)?; - let mut buffer = context - .allocate(block.bytes().len()) - .map_err(driver_error)?; + let block = binding.gdn_matrix_block(weights, role, 0, r).map_err(binding_error)?; + let mut buffer = context.allocate(block.bytes().len()).map_err(driver_error)?; buffer.copy_from(block.bytes()).map_err(driver_error)?; let kind = block.kind(); owned = Some(buffer); @@ -69,33 +59,9 @@ pub(super) fn dispatch_projection( r: usize, ) -> std::result::Result<(), DriverError> { match kind { - GdnMatrixKind::Bf16 => context.bf16_f32( - matrix, - a, - output, - Bf16ProjectionShape { - rows: r, - columns: c, - }, - ), - GdnMatrixKind::Q5K => context.q5_k_q8_1( - matrix, - a, - output, - Q5KProjectionShape { - rows: r, - columns: c, - }, - ), - GdnMatrixKind::Q6K => context.q6_k_q8_1( - matrix, - a, - output, - Q6KProjectionShape { - rows: r, - columns: c, - }, - ), + GdnMatrixKind::Bf16 => context.bf16_f32(matrix, a, output, Bf16ProjectionShape { rows: r, columns: c }), + GdnMatrixKind::Q5K => context.q5_k_q8_1(matrix, a, output, Q5KProjectionShape { rows: r, columns: c }), + GdnMatrixKind::Q6K => context.q6_k_q8_1(matrix, a, output, Q6KProjectionShape { rows: r, columns: c }), kind => context.project_q8_1( matrix, a, @@ -135,16 +101,7 @@ pub(super) fn project_retained( } }; let operation = (|| { - dispatch_projection( - context, - matrix, - activation, - &mut output, - kind, - columns, - rows, - ) - .map_err(driver_error)?; + dispatch_projection(context, matrix, activation, &mut output, kind, columns, rows).map_err(driver_error)?; download(&output, rows) })(); let cleanup = output.release().map_err(driver_error); @@ -168,18 +125,12 @@ pub(super) fn convolve( validate_values(weights, 4 * CHANNELS)?; let hist = upload(context, history)?; let x = upload(context, input)?; - let owned = if resident.is_none() { - Some(upload(context, weights)?) - } else { - None - }; + let owned = if resident.is_none() { Some(upload(context, weights)?) } else { None }; let w = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut next = allocate(context, HISTORY_ELEMENTS)?; let mut raw = allocate(context, CHANNELS)?; let mut h = allocate(context, CHANNELS)?; - context - .gdn_conv_silu_f32(&hist, &x, w, &mut next, &mut raw, &mut h) - .map_err(driver_error)?; + context.gdn_conv_silu_f32(&hist, &x, w, &mut next, &mut raw, &mut h).map_err(driver_error)?; // Validate raw too: a later SiLU must never mask a failed convolution. let _raw = download(&raw, CHANNELS)?; let next_values = download(&next, HISTORY_ELEMENTS)?; @@ -195,9 +146,7 @@ pub(super) fn normalize_qk(context: &Context<'_>, h: &[f32], epsilon: f32) -> Re // Fixed ABI writes only4096 of10240 words. Initialize all other words. let zeros = zeros(CHANNELS)?; let mut output = upload(context, &zeros)?; - context - .gdn_qk_l2_f32(&input, &mut output, epsilon) - .map_err(driver_error)?; + context.gdn_qk_l2_f32(&input, &mut output, epsilon).map_err(driver_error)?; let values = download(&output, CHANNELS)?; release([input, output])?; Ok(values) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/step_cached_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/step_cached_fn.rs index 0ee2a713..5f56e382 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn/step_cached_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn/step_cached_fn.rs @@ -22,12 +22,7 @@ pub(super) fn step_cached<'ctx>( let aux = cache.gdn_aux(resident)?; let mut mirror = cache.gdn_mirror(binding, layer.get(), context)?; let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?; - let mut chain = chain::Chain::new( - context, - binding.identity(), - input.identity(), - failed.clone(), - )?; + let mut chain = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?; chain.validate(context, &binding.identity(), input.identity())?; if cache.has_gdn_qk_workspace() { chain.set_qk_workspace(cache.gdn_qk_workspace(binding, context, input.identity())?)?; @@ -138,17 +133,8 @@ pub(super) fn step_cached<'ctx>( return Err(primary); } }; - let pending = mirror.publish( - mirror_next.take().ok_or(Error::IdentityMismatch)?, - input.identity(), - history, - )?; - Ok(GdnReady { - identity: input.identity(), - binding: binding.identity(), - output, - pending: Some(pending), - }) + let pending = mirror.publish(mirror_next.take().ok_or(Error::IdentityMismatch)?, input.identity(), history)?; + Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) }) } #[allow(clippy::too_many_arguments)] // Explicit closed provider and current input-lease checks. @@ -171,13 +157,7 @@ pub(super) fn project_chain_input<'ctx>( }; let (columns, rows) = weights.shape(role); validate_values(activation, columns)?; - let activation = source.buffer( - &binding.identity(), - context, - weights.layer(), - role, - activation, - )?; + let activation = source.buffer(&binding.identity(), context, weights.layer(), role, activation)?; let resident = cache.gdn(binding, weights.layer())?; if !std::ptr::eq(resident.weights.as_ref(), weights) { return Err(Error::IdentityMismatch); @@ -188,10 +168,7 @@ pub(super) fn project_chain_input<'ctx>( Ok(product) } pub(super) fn preflight_budget(budget: usize, allocated: usize) -> Result<()> { - if allocated - .checked_add(DEVICE_PEAK) - .is_none_or(|peak| peak > budget) - { + if allocated.checked_add(DEVICE_PEAK).is_none_or(|peak| peak > budget) { return Err(Error::InputAllocation); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain.rs index 25ca5839..0f36d898 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain.rs @@ -1,11 +1,13 @@ //! Step-local actual CUDA products; canonical finite host readbacks stay intact. use super::{ - BindingIdentity, CHANNELS, Context, DeviceBuffer, Error, GdnMatrixKind, HISTORY_ELEMENTS, - Result, TokenLayer, VALUES, allocate, dispatch_projection, download, driver_error, - validate_values, + BindingIdentity, CHANNELS, Context, DeviceBuffer, Error, GdnMatrixKind, HISTORY_ELEMENTS, Result, TokenLayer, + VALUES, allocate, dispatch_projection, download, driver_error, validate_values, }; -use std::{cell::{Cell, RefCell}, rc::Rc}; use leleka_cuda_driver::GdnRowQueue; +use std::{ + cell::{Cell, RefCell}, + rc::Rc, +}; // The fused T1 row of the chain (STRA-169): needs the private slot/epoch/operand machinery. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "gdn_chain_fused.rs"] @@ -166,7 +168,7 @@ mod retained_qk_gpu { let operation = (|| { let mut zeros = vec![0u8; QK_BYTES]; if bad_tail { - zeros[QK_BYTES-4..].copy_from_slice(&f32::NAN.to_le_bytes()); + zeros[QK_BYTES - 4..].copy_from_slice(&f32::NAN.to_le_bytes()); } out.copy_from(&zeros).map_err(driver_error)?; context.gdn_qk_l2_f32(h, &mut out, 1e-6).map_err(driver_error)?; @@ -184,14 +186,18 @@ mod retained_qk_gpu { assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_QK_SLOT").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); - let context = device.create_context(160*1024*1024).unwrap(); - let foreign = device.create_context(160*1024*1024).unwrap(); - let small = device.create_context(16*1024*1024).unwrap(); + let context = device.create_context(160 * 1024 * 1024).unwrap(); + let foreign = device.create_context(160 * 1024 * 1024).unwrap(); + let small = device.create_context(16 * 1024 * 1024).unwrap(); let mut retained = None; let operation = (|| -> Result<(usize, usize)> { - let ordinary: Vec = (0..CHANNELS).map(|i| (i%23) as f32/64.-11./64.).collect(); + let ordinary: Vec = (0..CHANNELS).map(|i| (i % 23) as f32 / 64. - 11. / 64.).collect(); let mut signed = vec![0.; CHANNELS]; - for (i, value) in signed.iter_mut().enumerate() { if i%2 == 0 { *value = -0.; } } + for (i, value) in signed.iter_mut().enumerate() { + if i % 2 == 0 { + *value = -0.; + } + } let mut changed = ordinary.clone(); changed[4095] = -0.75; let mut words = 0; @@ -201,49 +207,73 @@ mod retained_qk_gpu { let pair = (|| -> Result<()> { // Original per-call allocation/zero/projection/readback FIRST. let expected = original(&context, &h, false)?; - if retained.is_none() { retained = Some(allocate_qk_slot(&context)?); } - let actual = normalize_retained_qk(&context, &h, retained.as_mut().ok_or(Error::IdentityMismatch)?, 1e-6)?; - if expected.len() != actual.len() || expected.iter().zip(actual.iter()).any(|(a,b)| a.to_bits()!=b.to_bits()) { + if retained.is_none() { + retained = Some(allocate_qk_slot(&context)?); + } + let actual = + normalize_retained_qk(&context, &h, retained.as_mut().ok_or(Error::IdentityMismatch)?, 1e-6)?; + if expected.len() != actual.len() + || expected.iter().zip(actual.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) + { return Err(Error::IdentityMismatch); } words += actual.len(); Ok(()) })(); let cleanup = h.release().map_err(driver_error); - pair?; cleanup?; + pair?; + cleanup?; } let h = raw_h(&context, &ordinary)?; let faults = (|| -> Result<()> { - if !matches!(original(&context, &h, true), Err(Error::NonFinite)) { return Err(Error::IdentityMismatch); } + if !matches!(original(&context, &h, true), Err(Error::NonFinite)) { + return Err(Error::IdentityMismatch); + } let slot = retained.as_mut().ok_or(Error::IdentityMismatch)?; // A private proof poisons the unused final tail word. The kernel // writes only4096 words, so the full finite boundary must refuse. - slot.copy_from_range(QK_BYTES-4, &f32::NAN.to_le_bytes()).map_err(driver_error)?; - if !matches!(normalize_retained_qk(&context, &h, slot, 1e-6), Err(Error::NonFinite)) { return Err(Error::IdentityMismatch); } + slot.copy_from_range(QK_BYTES - 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?; + if !matches!(normalize_retained_qk(&context, &h, slot, 1e-6), Err(Error::NonFinite)) { + return Err(Error::IdentityMismatch); + } guards += 1; - slot.copy_from_range(QK_BYTES-4, &0f32.to_le_bytes()).map_err(driver_error)?; + slot.copy_from_range(QK_BYTES - 4, &0f32.to_le_bytes()).map_err(driver_error)?; let expected = original(&context, &h, false)?; let actual = normalize_retained_qk(&context, &h, slot, 1e-6)?; - if expected.iter().zip(actual.iter()).any(|(a,b)| a.to_bits()!=b.to_bits()) { return Err(Error::IdentityMismatch); } + if expected.iter().zip(actual.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) { + return Err(Error::IdentityMismatch); + } words += actual.len(); let before = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?; - let short = raw_h(&context, &[0.; CHANNELS-1])?; - let refused = matches!(normalize_retained_qk(&context, &short, slot, 1e-6), Err(Error::InvalidDimension)); + let short = raw_h(&context, &[0.; CHANNELS - 1])?; + let refused = + matches!(normalize_retained_qk(&context, &short, slot, 1e-6), Err(Error::InvalidDimension)); let cleanup = short.release().map_err(driver_error); - if !refused { return Err(Error::IdentityMismatch); } cleanup?; + if !refused { + return Err(Error::IdentityMismatch); + } + cleanup?; let other = raw_h(&foreign, &ordinary)?; let refused = normalize_retained_qk(&context, &other, slot, 1e-6).is_err(); let cleanup = other.release().map_err(driver_error); - if !refused { return Err(Error::IdentityMismatch); } cleanup?; + if !refused { + return Err(Error::IdentityMismatch); + } + cleanup?; let after = slot.copy_to_owned(QK_BYTES).map_err(driver_error)?; - if before != after { return Err(Error::IdentityMismatch); } + if before != after { + return Err(Error::IdentityMismatch); + } guards += 2; - if !matches!(allocate_qk_slot(&small), Err(Error::InputAllocation)) { return Err(Error::IdentityMismatch); } + if !matches!(allocate_qk_slot(&small), Err(Error::InputAllocation)) { + return Err(Error::IdentityMismatch); + } guards += 1; Ok(()) })(); let cleanup = h.release().map_err(driver_error); - faults?; cleanup?; + faults?; + cleanup?; Ok((words, guards)) })(); let release = retained.take().map(|buffer| buffer.release()).transpose(); @@ -252,7 +282,7 @@ mod retained_qk_gpu { let closes = [context.close(), foreign.close(), small.close()]; // Every owned buffer and Context is closed before final proof assertions. assert!(release.is_ok()); - assert_eq!(allocated, [0;3]); + assert_eq!(allocated, [0; 3]); assert!(closes.into_iter().all(|result| result.is_ok())); assert_eq!(operation.unwrap(), (71680, 4)); println!("GDN_QK_SLOT exact_words=71680 guards=4 allocated=0"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/allocate_qk_slot_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/allocate_qk_slot_fn.rs index 32f30e68..0543172e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/allocate_qk_slot_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/allocate_qk_slot_fn.rs @@ -5,13 +5,13 @@ use super::*; pub(super) fn allocate_qk_slot<'ctx>(context: &'ctx Context<'ctx>) -> Result> { let required = QK_BYTES.checked_add(QK_RESERVE).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(required) - .is_none_or(|total| total > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(required).is_none_or(|total| total > context.budget_bytes()) { return Err(Error::InputAllocation); } let (free, _) = context.memory_info().map_err(driver_error)?; - if free < required { return Err(Error::InputAllocation); } + if free < required { + return Err(Error::InputAllocation); + } let mut buffer = allocate(context, CHANNELS)?; if let Err(primary) = buffer.copy_from(&[0u8; QK_BYTES]).map_err(driver_error) { let _ = buffer.release(); @@ -20,7 +20,10 @@ pub(super) fn allocate_qk_slot<'ctx>(context: &'ctx Context<'ctx>) -> Result, h: &DeviceBuffer<'_>, output: &mut DeviceBuffer<'_>, epsilon: f32, + context: &Context<'_>, + h: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + epsilon: f32, ) -> Result> { if h.len() != QK_BYTES || output.len() != QK_BYTES { return Err(Error::InvalidDimension); @@ -36,25 +39,42 @@ impl<'ctx> QkScratch<'ctx> { slot.as_ref().map(DeviceBuffer::len).ok_or(Error::IdentityMismatch) } pub(in crate::qwen_forward) fn new( - binding: BindingIdentity, context: &'ctx Context<'ctx>, failed: Rc>, + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + failed: Rc>, ) -> Result { - if failed.get() { return Err(Error::CudaExecution); } + if failed.get() { + return Err(Error::CudaExecution); + } let buffer = allocate_qk_slot(context).inspect_err(|error| { - if *error == Error::CudaExecution { failed.set(true); } + if *error == Error::CudaExecution { + failed.set(true); + } })?; Ok(Self { context, binding, failed, buffer: RefCell::new(Some(buffer)) }) } - pub(super) fn validate(&self, context: &Context<'_>, binding: &BindingIdentity, failed: &Rc>) -> Result<()> { - if self.failed.get() { return Err(Error::CudaExecution); } - if !std::ptr::eq(self.context, context) || !self.binding.matches(binding) - || !Rc::ptr_eq(&self.failed, failed) - { return Err(Error::IdentityMismatch); } + pub(super) fn validate( + &self, + context: &Context<'_>, + binding: &BindingIdentity, + failed: &Rc>, + ) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !std::ptr::eq(self.context, context) || !self.binding.matches(binding) || !Rc::ptr_eq(&self.failed, failed) { + return Err(Error::IdentityMismatch); + } Ok(()) } - pub(super) fn take(&self, context: &Context<'_>, binding: &BindingIdentity, failed: &Rc>) -> Result> { + pub(super) fn take( + &self, + context: &Context<'_>, + binding: &BindingIdentity, + failed: &Rc>, + ) -> Result> { self.validate(context, binding, failed)?; - self.buffer.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? - .take().ok_or(Error::IdentityMismatch) + self.buffer.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take().ok_or(Error::IdentityMismatch) } pub(super) fn put(&self, buffer: DeviceBuffer<'ctx>) -> Result<()> { // The private caller returns the SAME actual allocation after a @@ -81,9 +101,10 @@ impl<'ctx> QkScratch<'ctx> { } }; let primary = slot.failed.get().then_some(Error::CudaExecution); - let cleanup = slot.buffer.into_inner().ok_or(Error::IdentityMismatch)? - .release().map_err(driver_error); - if cleanup.is_err() { slot.failed.set(true); } + let cleanup = slot.buffer.into_inner().ok_or(Error::IdentityMismatch)?.release().map_err(driver_error); + if cleanup.is_err() { + slot.failed.set(true); + } primary.map_or(cleanup, Err) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs index b6cb3f59..174e3c7c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> Chain<'ctx> { pub(in super::super::super) fn new( context: &'ctx Context<'ctx>, @@ -18,9 +17,7 @@ impl<'ctx> Chain<'ctx> { return Err(Error::InvalidLayer); } let mut buffers = Vec::new(); - buffers - .try_reserve_exact(32) - .map_err(|_| Error::InputAllocation)?; + buffers.try_reserve_exact(32).map_err(|_| Error::InputAllocation)?; Ok(Self { context, binding, @@ -43,33 +40,43 @@ impl<'ctx> Chain<'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - if !std::ptr::eq(self.context, context) - || !self.binding.matches(binding) - || self.identity != identity - { + if !std::ptr::eq(self.context, context) || !self.binding.matches(binding) || self.identity != identity { return Err(Error::IdentityMismatch); } Ok(()) } - pub(in super::super::super) fn set_verification_pool(&mut self, pool: super::super::super::verification::PoolRow<'ctx>) -> Result<()> { + pub(in super::super::super) fn set_verification_pool( + &mut self, + pool: super::super::super::verification::PoolRow<'ctx>, + ) -> Result<()> { self.check()?; - if !self.buffers.is_empty() || self.qk_workspace.is_some() || self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } + if !self.buffers.is_empty() || self.qk_workspace.is_some() || self.verification_pool.is_some() { + return Err(Error::IdentityMismatch); + } self.fixed_slots.try_reserve_exact(5).map_err(|_| Error::InputAllocation)?; self.verification_pool = Some(RefCell::new(pool)); Ok(()) } pub(in super::super) fn return_fixed(&self, role: Role, buffer: DeviceBuffer<'ctx>) -> Option { - let result = self.verification_pool.as_ref().ok_or(Error::IdentityMismatch).and_then(|pool| { - pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.put(role, buffer) - }); - if result.is_err() { self.failed.set(true); } + let result = self + .verification_pool + .as_ref() + .ok_or(Error::IdentityMismatch) + .and_then(|pool| pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.put(role, buffer)); + if result.is_err() { + self.failed.set(true); + } result.err() } pub(in super::super::super) fn set_qk_workspace(&mut self, owner: Rc>) -> Result<()> { self.check()?; - if self.qk_workspace.is_some() || !self.buffers.is_empty() - || self.identity.layer().get() >= 48 || self.identity.layer().get() % 4 == 3 - { return Err(Error::IdentityMismatch); } + if self.qk_workspace.is_some() + || !self.buffers.is_empty() + || self.identity.layer().get() >= 48 + || self.identity.layer().get() % 4 == 3 + { + return Err(Error::IdentityMismatch); + } owner.validate(self.context, &self.binding, &self.failed)?; self.qk_workspace = Some(owner); Ok(()) @@ -78,11 +85,7 @@ impl<'ctx> Chain<'ctx> { self.epoch.clone() } pub(in super::super) fn check(&self) -> Result<()> { - if self.failed.get() { - Err(Error::CudaExecution) - } else { - Ok(()) - } + if self.failed.get() { Err(Error::CudaExecution) } else { Ok(()) } } pub(in super::super::super) fn buffer(&self, product: &Product, role: Role) -> Result<&DeviceBuffer<'ctx>> { self.check()?; @@ -93,23 +96,25 @@ impl<'ctx> Chain<'ctx> { if let Some(returning) = &self.qk_return && returning.slot == product.slot { - if role != Role::Qk || returning.row != self.identity - || !Rc::ptr_eq(&returning.epoch, &self.epoch) - { return Err(Error::IdentityMismatch); } + if role != Role::Qk || returning.row != self.identity || !Rc::ptr_eq(&returning.epoch, &self.epoch) { + return Err(Error::IdentityMismatch); + } returning.owner.validate(self.context, &self.binding, &self.failed)?; } - let buffer = self - .buffers - .get(product.slot) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; + let buffer = self.buffers.get(product.slot).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?; if buffer.len() != role.count() * 4 { return Err(Error::InvalidDimension); } Ok(buffer) } // Shared slot validation of pending operands and completed products. - pub(in super::super) fn device_slot(&self, slot: usize, product_role: Role, epoch: &Rc<()>, role: Role) -> Result<&DeviceBuffer<'ctx>> { + pub(in super::super) fn device_slot( + &self, + slot: usize, + product_role: Role, + epoch: &Rc<()>, + role: Role, + ) -> Result<&DeviceBuffer<'ctx>> { self.check()?; if product_role != role || !Rc::ptr_eq(&self.epoch, epoch) { return Err(Error::IdentityMismatch); @@ -117,22 +122,22 @@ impl<'ctx> Chain<'ctx> { if let Some(returning) = &self.qk_return && returning.slot == slot { - if role != Role::Qk || returning.row != self.identity - || !Rc::ptr_eq(&returning.epoch, &self.epoch) - { return Err(Error::IdentityMismatch); } + if role != Role::Qk || returning.row != self.identity || !Rc::ptr_eq(&returning.epoch, &self.epoch) { + return Err(Error::IdentityMismatch); + } returning.owner.validate(self.context, &self.binding, &self.failed)?; } - let buffer = self - .buffers - .get(slot) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; + let buffer = self.buffers.get(slot).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?; if buffer.len() != role.count() * 4 { return Err(Error::InvalidDimension); } Ok(buffer) } - pub(in super::super::super) fn device_buffer(&self, product: &DeviceProduct, role: Role) -> Result<&DeviceBuffer<'ctx>> { + pub(in super::super::super) fn device_buffer( + &self, + product: &DeviceProduct, + role: Role, + ) -> Result<&DeviceBuffer<'ctx>> { self.device_slot(product.slot, product.role, &product.epoch, role) } // Pending operands are admissible only as inputs/outputs of the queued prefix. @@ -153,7 +158,9 @@ impl<'ctx> Chain<'ctx> { // scalar path unchanged. pub(in super::super) fn reserve_device(&mut self, role: Role) -> Result { self.check()?; - if self.verification_pool.is_some() { return Err(Error::IdentityMismatch); } + if self.verification_pool.is_some() { + return Err(Error::IdentityMismatch); + } self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let buffer = allocate(self.context, role.count())?; Ok(self.track_device(role, buffer)) @@ -170,9 +177,8 @@ impl<'ctx> Chain<'ctx> { self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let buffer = owner.take(self.context, &self.binding, &self.failed)?; let product = self.track_device(Role::Qk, buffer); - self.qk_return = Some(QkReturn { - owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), - }); + self.qk_return = + Some(QkReturn { owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch) }); Ok(product) } // Same projection call as `project`, but the output stays on device; its @@ -189,13 +195,8 @@ impl<'ctx> Chain<'ctx> { } let product = self.reserve_device(role)?; let operation = { - let output = self - .buffers - .get_mut(product.slot) - .and_then(Option::as_mut) - .ok_or(Error::IdentityMismatch)?; - dispatch_projection(self.context, matrix, source, output, kind, 2560, role.count()) - .map_err(driver_error) + let output = self.buffers.get_mut(product.slot).and_then(Option::as_mut).ok_or(Error::IdentityMismatch)?; + dispatch_projection(self.context, matrix, source, output, kind, 2560, role.count()).map_err(driver_error) }; if let Err(primary) = operation { self.note(primary); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs index 70ace468..f6664af9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> Chain<'ctx> { // ONE drain for conv, QK, beta sigmoid, gates, recurrence, out-norm and a // full finite scan of every stage output. The scalar chain's twelve @@ -59,23 +58,13 @@ impl<'ctx> Chain<'ctx> { .conv_silu(history, qkv, inputs.conv_weights, next_buffer, raw_buffer, h_buffer) .map_err(driver_error)?, (QkvInput::Columns { buffer, row }, None) => prefix - .conv_silu_columns( - history, - buffer, - *row, - inputs.conv_weights, - next_buffer, - raw_buffer, - h_buffer, - ) + .conv_silu_columns(history, buffer, *row, inputs.conv_weights, next_buffer, raw_buffer, h_buffer) .map_err(driver_error)?, _ => return Err(Error::IdentityMismatch), } prefix.qk_l2(h_buffer, qk_buffer, inputs.epsilon).map_err(driver_error)?; prefix.beta_sigmoid(beta_raw, sigmoid_buffer).map_err(driver_error)?; - prefix - .gate_softplus(alpha, inputs.dt, inputs.a, gate_buffer) - .map_err(driver_error)?; + prefix.gate_softplus(alpha, inputs.dt, inputs.a, gate_buffer).map_err(driver_error)?; prefix .recurrence( inputs.state, @@ -103,17 +92,10 @@ impl<'ctx> Chain<'ctx> { }; // A completed numerical refusal is the same NonFinite as the scalar // chain's full readback validation; no history is returned. - let values = completion - .into_next_history() - .map_err(|_| Error::NonFinite)?; + let values = completion.into_next_history().map_err(|_| Error::NonFinite)?; validate_values(&values, Role::NextHistory.count())?; Ok(QueuedRow { - next_history: Product { - slot: next.slot, - role: Role::NextHistory, - epoch: next.epoch.clone(), - values, - }, + next_history: Product { slot: next.slot, role: Role::NextHistory, epoch: next.epoch.clone(), values }, normalized: self.complete(normalized), }) } @@ -141,12 +123,7 @@ impl<'ctx> Chain<'ctx> { // History has already been consumed as its unchanged canonical host // product. Retain only the four current recurrence input allocations. self.release_in_scope(&slots)?; - Ok(RecurrenceBorrow { - row: row.readout_key(), - scope: Rc::clone(&self.epoch), - chain: self, - products, - }) + Ok(RecurrenceBorrow { row: row.readout_key(), scope: Rc::clone(&self.epoch), chain: self, products }) } pub(in super::super::super) fn borrow_scalar_recurrence<'chain>( &'chain mut self, @@ -158,10 +135,7 @@ impl<'ctx> Chain<'ctx> { txn.validate_input(self.identity.token(), self.identity.position())?; txn.validate_gdn_prior(prior, self.identity.layer())?; self.validate(txn.cuda_context()?, &self.binding, self.identity)?; - for (product, role) in products - .into_iter() - .zip([Role::Qk, Role::H, Role::Gate, Role::Beta]) - { + for (product, role) in products.into_iter().zip([Role::Qk, Role::H, Role::Gate, Role::Beta]) { self.buffer(product, role)?; } let slots = products.map(|product| product.slot); @@ -172,12 +146,7 @@ impl<'ctx> Chain<'ctx> { } // All witnesses and current producer identities precede any cleanup. self.release_in_scope(&slots)?; - Ok(ScalarRecurrenceBorrow { - prior: prior.clone(), - scope: Rc::clone(&self.epoch), - chain: self, - products, - }) + Ok(ScalarRecurrenceBorrow { prior: prior.clone(), scope: Rc::clone(&self.epoch), chain: self, products }) } pub(in super::super::super) fn release_chunk_sources(&mut self) -> Result<()> { self.release_in_scope(&[]) @@ -196,7 +165,9 @@ impl<'ctx> Chain<'ctx> { } else { self.free(buffer) }; - if let Some(failure) = failure { error.get_or_insert(failure); } + if let Some(failure) = failure { + error.get_or_insert(failure); + } } } // Keep every vacated slot until ordinary drain rotates the epoch. @@ -206,23 +177,17 @@ impl<'ctx> Chain<'ctx> { } pub(in super::super) fn track(&mut self, role: Role, buffer: DeviceBuffer<'ctx>, values: Box<[f32]>) -> Product { let slot = self.buffers.len(); - if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta | Role::Readout) { + if self.verification_pool.is_some() + && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta | Role::Readout) + { self.fixed_slots.push((slot, role)); } self.buffers.push(Some(buffer)); - Product { - slot, - role, - epoch: self.epoch.clone(), - values, - } + Product { slot, role, epoch: self.epoch.clone(), values } } pub(in super::super::super) fn upload(&mut self, role: Role, values: &[f32]) -> Result { self.check()?; - if !matches!( - role, - Role::Input | Role::History | Role::Conv | Role::Dt | Role::A | Role::Gamma - ) { + if !matches!(role, Role::Input | Role::History | Role::Conv | Role::Dt | Role::A | Role::Gamma) { return Err(Error::IdentityMismatch); } self.upload_values(role, values) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs index f25211d8..61d714de 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_3.rs @@ -3,24 +3,18 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> Chain<'ctx> { pub(in super::super) fn upload_values(&mut self, role: Role, values: &[f32]) -> Result { self.check()?; - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; validate_values(values, role.count())?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len() * 4) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } let mut host = Vec::new(); - host.try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; + host.try_reserve_exact(values.len()).map_err(|_| Error::InputAllocation)?; host.extend_from_slice(values); let mut buffer = allocate(self.context, role.count())?; if let Err(error) = buffer.copy_from(&bytes) { @@ -53,23 +47,23 @@ impl<'ctx> Chain<'ctx> { operation: impl FnOnce(&Self, &mut [DeviceBuffer<'ctx>]) -> Result<[Box<[f32]>; N]>, ) -> Result<[Product; N]> { self.check()?; - self.buffers - .try_reserve(N) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(N).map_err(|_| Error::InputAllocation)?; let mut buffers = Vec::new(); - buffers - .try_reserve_exact(N) - .map_err(|_| Error::InputAllocation)?; + buffers.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?; let mut products = Vec::new(); - products - .try_reserve_exact(N) - .map_err(|_| Error::InputAllocation)?; + products.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?; let result = (|| { for role in roles { - let fixed = self.verification_pool.as_ref().map(|pool| { - pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(role) - }).transpose()?.flatten(); - buffers.push(match fixed { Some(buffer) => buffer, None => allocate(self.context, role.count())? }); + let fixed = self + .verification_pool + .as_ref() + .map(|pool| pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(role)) + .transpose()? + .flatten(); + buffers.push(match fixed { + Some(buffer) => buffer, + None => allocate(self.context, role.count())?, + }); } operation(self, &mut buffers) })(); @@ -78,9 +72,12 @@ impl<'ctx> Chain<'ctx> { Err(primary) => { self.note(primary); for (buffer, role) in buffers.into_iter().zip(roles) { - if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta) { + if self.verification_pool.is_some() && matches!(role, Role::Qk | Role::H | Role::Gate | Role::Beta) + { self.return_fixed(role, buffer); - } else { self.free(buffer); } + } else { + self.free(buffer); + } } return Err(primary); } @@ -102,16 +99,8 @@ impl<'ctx> Chain<'ctx> { _ => return Err(Error::IdentityMismatch), }; let [product] = self.produce([role], |chain, out| { - dispatch_projection( - chain.context, - matrix, - source, - &mut out[0], - kind, - columns, - role.count(), - ) - .map_err(driver_error)?; + dispatch_projection(chain.context, matrix, source, &mut out[0], kind, columns, role.count()) + .map_err(driver_error)?; Ok([download(&out[0], role.count())?]) })?; Ok(product) @@ -143,37 +132,37 @@ impl<'ctx> Chain<'ctx> { qkv: &Product, weights: &DeviceBuffer<'_>, ) -> Result<(Product, Product)> { - let [next, _raw, h] = - self.produce([Role::NextHistory, Role::Raw, Role::H], |chain, out| { - let (next, rest) = out.split_at_mut(1); - let (raw, h) = rest.split_at_mut(1); - chain - .context - .gdn_conv_silu_f32( - chain.buffer(history, Role::History)?, - chain.buffer(qkv, Role::Qkv)?, - weights, - &mut next[0], - &mut raw[0], - &mut h[0], - ) - .map_err(driver_error)?; - let raw_values = download(&raw[0], CHANNELS)?; - let next_values = download(&next[0], HISTORY_ELEMENTS)?; - let h_values = download(&h[0], CHANNELS)?; - Ok([next_values, raw_values, h_values]) - })?; + let [next, _raw, h] = self.produce([Role::NextHistory, Role::Raw, Role::H], |chain, out| { + let (next, rest) = out.split_at_mut(1); + let (raw, h) = rest.split_at_mut(1); + chain + .context + .gdn_conv_silu_f32( + chain.buffer(history, Role::History)?, + chain.buffer(qkv, Role::Qkv)?, + weights, + &mut next[0], + &mut raw[0], + &mut h[0], + ) + .map_err(driver_error)?; + let raw_values = download(&raw[0], CHANNELS)?; + let next_values = download(&next[0], HISTORY_ELEMENTS)?; + let h_values = download(&h[0], CHANNELS)?; + Ok([next_values, raw_values, h_values]) + })?; Ok((next, h)) } pub(in super::super::super) fn normalize_qk(&mut self, h: &Product, epsilon: f32) -> Result { if let Some(owner) = self.qk_workspace.clone() { self.check()?; - if self.qk_return.is_some() { return Err(Error::IdentityMismatch); } + if self.qk_return.is_some() { + return Err(Error::IdentityMismatch); + } self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut buffer = owner.take(self.context, &self.binding, &self.failed)?; - let operation = self.buffer(h, Role::H).and_then(|h| { - normalize_retained_qk(self.context, h, &mut buffer, epsilon) - }); + let operation = + self.buffer(h, Role::H).and_then(|h| normalize_retained_qk(self.context, h, &mut buffer, epsilon)); let values = match operation { Ok(values) => values, Err(primary) => { @@ -183,20 +172,14 @@ impl<'ctx> Chain<'ctx> { } }; let product = self.track(Role::Qk, buffer, values); - self.qk_return = Some(QkReturn { - owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch), - }); + self.qk_return = + Some(QkReturn { owner, slot: product.slot, row: self.identity, epoch: Rc::clone(&self.epoch) }); return Ok(product); } let [product] = self.produce([Role::Qk], |chain, out| { // Fixed ABI writes only4096 words; preserve original initialized tail. - out[0] - .copy_from(&[0u8; CHANNELS * 4]) - .map_err(driver_error)?; - chain - .context - .gdn_qk_l2_f32(chain.buffer(h, Role::H)?, &mut out[0], epsilon) - .map_err(driver_error)?; + out[0].copy_from(&[0u8; CHANNELS * 4]).map_err(driver_error)?; + chain.context.gdn_qk_l2_f32(chain.buffer(h, Role::H)?, &mut out[0], epsilon).map_err(driver_error)?; Ok([download(&out[0], CHANNELS)?]) })?; Ok(product) @@ -232,16 +215,8 @@ impl<'ctx> Chain<'ctx> { if !prior.mirror_admits(&self.binding, self.identity.layer().get()) { return Err(Error::IdentityMismatch); } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - let (buffer, values) = readout.into_parts( - self.context, - &self.failed, - prior, - self.identity, - &self.epoch, - )?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; + let (buffer, values) = readout.into_parts(self.context, &self.failed, prior, self.identity, &self.epoch)?; Ok(self.track(Role::Readout, buffer, values)) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs index ede1c650..10fda653 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain/impl_chain/impl_chain_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> Chain<'ctx> { pub(in super::super::super) fn import_chunk_readout( &mut self, @@ -11,9 +10,7 @@ impl<'ctx> Chain<'ctx> { row: &super::super::super::super::session::chunk::GdnChunkRow, ) -> Result { self.check()?; - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; if row.identity() != self.identity { return Err(Error::IdentityMismatch); } @@ -57,7 +54,9 @@ impl<'ctx> Chain<'ctx> { } else { self.free(buffer) }; - if let Some(failure) = failure { error.get_or_insert(failure); } + if let Some(failure) = failure { + error.get_or_insert(failure); + } } } error.map_or(Ok(()), Err) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs index acaa459f..32fa9491 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_fused.rs @@ -57,9 +57,7 @@ impl<'ctx> Chain<'ctx> { let y = self.reserve_device(Role::Normalized)?; { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(inputs.prior_history.len() * 4) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(inputs.prior_history.len() * 4).map_err(|_| Error::InputAllocation)?; for value in inputs.prior_history { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -86,27 +84,15 @@ impl<'ctx> Chain<'ctx> { let y_buffer = this.operand_buffer(&y, Role::Normalized)?; let mut prefix = program.begin().map_err(driver_error)?; let admitted = (|| -> Result<()> { - prefix.scan_inputs(qkv, z).map_err(driver_error)?; - prefix.seed_state(resident, next_state).map_err(driver_error)?; - prefix - .conv_l2(next_buffer, inputs.conv_weights, h_buffer, inputs.epsilon) - .map_err(driver_error)?; - prefix - .ab( - inputs.mixed, - inputs.w_alpha, - inputs.w_beta, - inputs.dt, - inputs.a, - gate_buffer, - beta_buffer, - ) - .map_err(driver_error)?; - prefix - .step_norm(inputs.gamma, y_buffer, inputs.epsilon) - .map_err(driver_error)?; - prefix.fetch_candidate().map_err(driver_error)?; - Ok(()) + prefix.scan_inputs(qkv, z).map_err(driver_error)?; + prefix.seed_state(resident, next_state).map_err(driver_error)?; + prefix.conv_l2(next_buffer, inputs.conv_weights, h_buffer, inputs.epsilon).map_err(driver_error)?; + prefix + .ab(inputs.mixed, inputs.w_alpha, inputs.w_beta, inputs.dt, inputs.a, gate_buffer, beta_buffer) + .map_err(driver_error)?; + prefix.step_norm(inputs.gamma, y_buffer, inputs.epsilon).map_err(driver_error)?; + prefix.fetch_candidate().map_err(driver_error)?; + Ok(()) })(); // The driver's methods latch admission errors; drain every real // admitted command so earlier numerics remain primary. @@ -150,9 +136,14 @@ impl<'ctx> Chain<'ctx> { self.fixed_slots.try_reserve(1).map_err(|_| Error::InputAllocation)?; let fixed = pool.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(role)?; let is_fixed = fixed.is_some(); - let buffer = match fixed { Some(buffer) => buffer, None => allocate(self.context, role.count())? }; + let buffer = match fixed { + Some(buffer) => buffer, + None => allocate(self.context, role.count())?, + }; let operand = self.track_device(role, buffer); - if is_fixed { self.fixed_slots.push((operand.slot, role)); } + if is_fixed { + self.fixed_slots.push((operand.slot, role)); + } Ok(operand) } pub(in crate::qwen_forward::gdn) fn run_fused_verification_row( @@ -176,9 +167,7 @@ impl<'ctx> Chain<'ctx> { let y = self.reserve_fused_verified(Role::Normalized)?; { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(inputs.prior_history.len() * 4) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(inputs.prior_history.len() * 4).map_err(|_| Error::InputAllocation)?; for value in inputs.prior_history { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -205,26 +194,14 @@ impl<'ctx> Chain<'ctx> { let y_buffer = this.operand_buffer(&y, Role::Normalized)?; let mut prefix = program.begin().map_err(driver_error)?; let admitted = (|| -> Result<()> { - prefix.scan_inputs(qkv, z).map_err(driver_error)?; - prefix.seed_state(resident, next_state).map_err(driver_error)?; - prefix - .conv_l2(next_buffer, inputs.conv_weights, h_buffer, inputs.epsilon) - .map_err(driver_error)?; - prefix - .ab( - inputs.mixed, - inputs.w_alpha, - inputs.w_beta, - inputs.dt, - inputs.a, - gate_buffer, - beta_buffer, - ) - .map_err(driver_error)?; - prefix - .step_norm(inputs.gamma, y_buffer, inputs.epsilon) - .map_err(driver_error)?; - Ok(()) + prefix.scan_inputs(qkv, z).map_err(driver_error)?; + prefix.seed_state(resident, next_state).map_err(driver_error)?; + prefix.conv_l2(next_buffer, inputs.conv_weights, h_buffer, inputs.epsilon).map_err(driver_error)?; + prefix + .ab(inputs.mixed, inputs.w_alpha, inputs.w_beta, inputs.dt, inputs.a, gate_buffer, beta_buffer) + .map_err(driver_error)?; + prefix.step_norm(inputs.gamma, y_buffer, inputs.epsilon).map_err(driver_error)?; + Ok(()) })(); let _ = admitted; prefix.finish_device().map_err(driver_error) @@ -236,7 +213,9 @@ impl<'ctx> Chain<'ctx> { return Err(primary); } }; - if completion.is_some() { return Err(Error::NonFinite); } + if completion.is_some() { + return Err(Error::NonFinite); + } // Full completed native H already contains the Original normalized Q/K. // Copy all actual bytes into the separately owned QK journal slot; do // not relabel H or reconstruct a caller-supplied numeric certificate. @@ -244,14 +223,28 @@ impl<'ctx> Chain<'ctx> { let qk = self.reserve_fused_verified(Role::Qk)?; let mut qk_bytes = Vec::new(); qk_bytes.try_reserve_exact(Role::Qk.count() * 4).map_err(|_| Error::InputAllocation)?; - for value in &h_values { qk_bytes.extend_from_slice(&value.to_le_bytes()); } - let copied = self.buffers.get_mut(qk.slot).and_then(Option::as_mut) - .ok_or(Error::IdentityMismatch)?.copy_from_owned(qk_bytes).map_err(driver_error); - if let Err(primary) = copied { self.note(primary); return Err(primary); } + for value in &h_values { + qk_bytes.extend_from_slice(&value.to_le_bytes()); + } + let copied = self + .buffers + .get_mut(qk.slot) + .and_then(Option::as_mut) + .ok_or(Error::IdentityMismatch)? + .copy_from_owned(qk_bytes) + .map_err(driver_error); + if let Err(primary) = copied { + self.note(primary); + return Err(primary); + } let history = download(self.operand_buffer(&next, Role::NextHistory)?, Role::NextHistory.count())?; Ok(FusedRow { - next_history: Product { slot: next.slot, role: Role::NextHistory, - epoch: next.epoch.clone(), values: history }, + next_history: Product { + slot: next.slot, + role: Role::NextHistory, + epoch: next.epoch.clone(), + values: history, + }, normalized: self.complete(y), }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs index 7acfc5da..51e7c933 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chain_reuse_gpu.rs @@ -1,8 +1,7 @@ //! Independent exact old-transfer versus retained GDN chain component proof. #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::{ - GdnOwner, GdnPrior, GdnStateMirror, convolve, gates, normalize_qk, out_norm, recur, release, - upload, + GdnOwner, GdnPrior, GdnStateMirror, convolve, gates, normalize_qk, out_norm, recur, release, upload, }; use super::*; use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId}; @@ -30,24 +29,10 @@ fn upload_bytes<'ctx>(ctx: &'ctx Context<'ctx>, bytes: &[u8]) -> DeviceBuffer<'c b.copy_from(bytes).unwrap(); b } -fn original_projection( - ctx: &Context<'_>, - weights: &DeviceBuffer<'_>, - input: &[f32], - rows: usize, -) -> Box<[f32]> { +fn original_projection(ctx: &Context<'_>, weights: &DeviceBuffer<'_>, input: &[f32], rows: usize) -> Box<[f32]> { let x = upload(ctx, input).unwrap(); let mut y = allocate(ctx, rows).unwrap(); - ctx.bf16_f32( - weights, - &x, - &mut y, - Bf16ProjectionShape { - rows, - columns: input.len(), - }, - ) - .unwrap(); + ctx.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns: input.len() }).unwrap(); let result = download(&y, rows).unwrap(); release([x, y]).unwrap(); result @@ -63,9 +48,7 @@ fn pair_projection<'ctx>( let bytes = matrix(role.count(), 2560, seed); let weights = upload_bytes(ctx, &bytes); let expected = original_projection(ctx, &weights, input, role.count()); - let product = chain - .project(&weights, GdnMatrixKind::Bf16, source, role) - .unwrap(); + let product = chain.project(&weights, GdnMatrixKind::Bf16, source, role).unwrap(); exact(product.values(), &expected); let mut after = vec![0; bytes.len()]; weights.copy_to(&mut after).unwrap(); @@ -96,28 +79,14 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { let mut mirror = GdnStateMirror::new(binding.clone(), 0, &ctx, failed.clone()).unwrap(); let mut chain = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); let input: Vec = (0..2560) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - ((i % 17) as f32 - 8.) / 128. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 128. }) .collect(); let input_bytes: Vec = input.iter().flat_map(|v| v.to_le_bytes()).collect(); let source = upload(&ctx, &input).unwrap(); let history: Vec = (0..HISTORY_ELEMENTS) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - ((i % 13) as f32 - 6.) / 256. - } - }) - .collect(); - let conv: Vec = (0..4 * CHANNELS) - .map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 13) as f32 - 6.) / 256. }) .collect(); + let conv: Vec = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); let conv_buffer = upload(&ctx, &conv).unwrap(); let dt = [-2.; 48]; let a = [1.; 48]; @@ -128,55 +97,31 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { let (qkv, expected_qkv) = pair_projection(&mut chain, &source, &input, Role::Qkv, 0); let expected_conv = convolve(&ctx, &history, &expected_qkv, &conv, None).unwrap(); let history_product = chain.upload(Role::History, &history).unwrap(); - let (next_history, h) = chain - .convolve(&history_product, &qkv, &conv_buffer) - .unwrap(); + let (next_history, h) = chain.convolve(&history_product, &qkv, &conv_buffer).unwrap(); exact(next_history.values(), &expected_conv.0); exact(h.values(), &expected_conv.1); let expected_qk = normalize_qk(&ctx, &expected_conv.1, 1e-6).unwrap(); let qk = chain.normalize_qk(&h, 1e-6).unwrap(); exact(qk.values(), &expected_qk); let (alpha, expected_alpha) = pair_projection(&mut chain, &source, &input, Role::Alpha, 1); - let (beta_raw, expected_beta_raw) = - pair_projection(&mut chain, &source, &input, Role::BetaRaw, 2); - let expected_gates = - gates(&ctx, &expected_alpha, &expected_beta_raw, &dt, &a, None).unwrap(); - let (gate, beta) = chain - .gates(&alpha, &beta_raw, &dt_buffer, &a_buffer) - .unwrap(); + let (beta_raw, expected_beta_raw) = pair_projection(&mut chain, &source, &input, Role::BetaRaw, 2); + let expected_gates = gates(&ctx, &expected_alpha, &expected_beta_raw, &dt, &a, None).unwrap(); + let (gate, beta) = chain.gates(&alpha, &beta_raw, &dt_buffer, &a_buffer).unwrap(); exact(gate.values(), &expected_gates.0); exact(beta.values(), &expected_gates.1); if !zero { - assert_eq!( - chain.buffer(&qkv, Role::Z).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - chain.validate(&foreign, &binding, identity(0, 0)), - Err(Error::IdentityMismatch) - ); + assert_eq!(chain.buffer(&qkv, Role::Z).err(), Some(Error::IdentityMismatch)); + assert_eq!(chain.validate(&foreign, &binding, identity(0, 0)), Err(Error::IdentityMismatch)); assert_eq!( chain.validate(&ctx, &BindingIdentity::test_identity(), identity(0, 0)), Err(Error::IdentityMismatch) ); - assert_eq!( - chain.validate(&ctx, &binding, identity(0, 1)), - Err(Error::IdentityMismatch) - ); + assert_eq!(chain.validate(&ctx, &binding, identity(0, 1)), Err(Error::IdentityMismatch)); let charge = ctx.allocated_bytes(); let mut bad_conv = conv.clone(); bad_conv[4 * CHANNELS - 1] = f32::from_bits(0x7fc00001); - let bad = upload_bytes( - &ctx, - &bad_conv - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>(), - ); - assert_eq!( - chain.convolve(&history_product, &qkv, &bad).err(), - Some(Error::NonFinite) - ); + let bad = upload_bytes(&ctx, &bad_conv.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + assert_eq!(chain.convolve(&history_product, &qkv, &bad).err(), Some(Error::NonFinite)); bad.release().unwrap(); assert_eq!(ctx.allocated_bytes(), charge); assert!(!failed.get()); @@ -194,10 +139,7 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { // Mandatory drain changes epoch and removes every pre-recurrence buffer. chain.drain().unwrap(); if !zero { - assert_eq!( - chain.buffer(&qkv, Role::Qkv).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(chain.buffer(&qkv, Role::Qkv).err(), Some(Error::IdentityMismatch)); } if !zero { // Genuine recurrence output with a different step-local epoch cannot @@ -217,10 +159,7 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { ], ) .unwrap(); - assert_eq!( - chain.import_readout(foreign_scope, &prior).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(chain.import_readout(foreign_scope, &prior).err(), Some(Error::IdentityMismatch)); mirror.discard(discarded_next).unwrap(); assert_eq!(ctx.allocated_bytes(), charge); assert!(!failed.get()); @@ -242,16 +181,13 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { let readout = chain.import_readout(carrier, &prior).unwrap(); exact(readout.values(), &expected_recur.1); let (z, expected_z) = pair_projection(&mut chain, &source, &input, Role::Z, 3); - let expected_normalized = - out_norm(&ctx, &expected_recur.1, &expected_z, &gamma, 1e-6, None).unwrap(); + let expected_normalized = out_norm(&ctx, &expected_recur.1, &expected_z, &gamma, 1e-6, None).unwrap(); let normalized = chain.out_norm(&readout, &z, &gamma_buffer, 1e-6).unwrap(); exact(normalized.values(), &expected_normalized); let out_bytes = matrix(2560, VALUES, 4); let mut weights = upload_bytes(&ctx, &out_bytes); let expected_out = original_projection(&ctx, &weights, &expected_normalized, 2560); - let actual_out = chain - .project_out(&weights, GdnMatrixKind::Bf16, &normalized) - .unwrap(); + let actual_out = chain.project_out(&weights, GdnMatrixKind::Bf16, &normalized).unwrap(); exact(actual_out.values(), &expected_out); let mut immutable = vec![0; out_bytes.len()]; weights.copy_to(&mut immutable).unwrap(); @@ -261,18 +197,11 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { let end = immutable.len(); immutable[end - 2..].copy_from_slice(&0x7fc1u16.to_le_bytes()); weights.copy_from(&immutable).unwrap(); - assert_eq!( - chain - .project_out(&weights, GdnMatrixKind::Bf16, &normalized) - .err(), - Some(Error::NonFinite) - ); + assert_eq!(chain.project_out(&weights, GdnMatrixKind::Bf16, &normalized).err(), Some(Error::NonFinite)); assert_eq!(ctx.allocated_bytes(), charge); assert!(!failed.get()); } - let pending = mirror - .publish(next, identity(0, 0), expected_conv.0.clone()) - .unwrap(); + let pending = mirror.publish(next, identity(0, 0), expected_conv.0.clone()).unwrap(); let committed = pending.into_prior(); exact(committed.values(), &expected_recur.0); exact(committed.history(), &expected_conv.0); @@ -289,45 +218,21 @@ fn retained_gdn_chain_matches_legacy_intermediates_and_fences_products() { println!("GDN_CHAIN PAIR zero={zero} exact_intermediate_and_state_words=899776"); } let mut chain = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); - assert_eq!( - Chain::new(&ctx, binding.clone(), identity(3, 0), failed.clone()).err(), - Some(Error::InvalidLayer) - ); - assert_eq!( - chain.upload(Role::Readout, &vec![0.; VALUES]).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - chain.upload(Role::Input, &[0.; 2559]).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(Chain::new(&ctx, binding.clone(), identity(3, 0), failed.clone()).err(), Some(Error::InvalidLayer)); + assert_eq!(chain.upload(Role::Readout, &vec![0.; VALUES]).err(), Some(Error::IdentityMismatch)); + assert_eq!(chain.upload(Role::Input, &[0.; 2559]).err(), Some(Error::InvalidDimension)); let mut bad = vec![0.; 2560]; bad[2559] = f32::NAN; - assert_eq!( - chain.upload(Role::Input, &bad).err(), - Some(Error::NonFinite) - ); + assert_eq!(chain.upload(Role::Input, &bad).err(), Some(Error::NonFinite)); let input = chain.upload(Role::Input, &[0.; 2560]).unwrap(); let other = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); - assert_eq!( - other.buffer(&input, Role::Input).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(other.buffer(&input, Role::Input).err(), Some(Error::IdentityMismatch)); other.finish().unwrap(); let charge = ctx.allocated_bytes(); failed.set(true); // Explicit shared policy, not injected CUDA failure. - assert_eq!( - chain.buffer(&input, Role::Input).err(), - Some(Error::CudaExecution) - ); - assert_eq!( - chain.upload(Role::Input, &[0.; 2560]).err(), - Some(Error::CudaExecution) - ); - assert_eq!( - Chain::new(&ctx, binding, identity(0, 0), failed.clone()).err(), - Some(Error::CudaExecution) - ); + assert_eq!(chain.buffer(&input, Role::Input).err(), Some(Error::CudaExecution)); + assert_eq!(chain.upload(Role::Input, &[0.; 2560]).err(), Some(Error::CudaExecution)); + assert_eq!(Chain::new(&ctx, binding, identity(0, 0), failed.clone()).err(), Some(Error::CudaExecution)); assert_eq!(ctx.allocated_bytes(), charge); drop(chain); // Sticky abandoned-chain cleanup must free all actual owners. assert!(failed.get()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device.rs index e2ca15e5..c9e02f89 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device.rs @@ -1,7 +1,7 @@ //! One actual outer-layer recurrence. Host state is published only at its seal. -use super::super::session::chunk::{GdnChunkRow, GdnChunkSeal, GdnChunkStart}; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use super::super::session::chunk::GdnChunkMicro; +use super::super::session::chunk::{GdnChunkRow, GdnChunkSeal, GdnChunkStart}; use super::*; use leleka_cuda_driver::{GdnRowQueue, GdnStateFiniteGuard}; use std::{cell::Cell, rc::Rc}; @@ -34,7 +34,8 @@ pub(in crate::qwen_forward) struct GdnChunkDevice<'ctx> { cursor: usize, inflight: bool, valid: bool, - verification: Option<(Rc>>, Rc)>, + verification: + Option<(Rc>>, Rc)>, verified_rows: Vec>, initial: Option>, // Explicit opt-in closed row queue; absent unless `enable_row_queue` ran. @@ -48,12 +49,12 @@ pub(in crate::qwen_forward) mod numeric_gpu; #[path = "gdn_chunk_device/mirror_reuse_enabled_fn.rs"] mod mirror_reuse_enabled_fn; -#[allow(unused_imports)] -use mirror_reuse_enabled_fn::mirror_reuse_enabled; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use mirror_reuse_enabled_fn::micro_rows; -#[path = "gdn_chunk_device/impl_gdnchunkdevice.rs"] -mod impl_gdnchunkdevice; +#[allow(unused_imports)] +use mirror_reuse_enabled_fn::mirror_reuse_enabled; #[path = "gdn_chunk_device/impl_drop_for_gdnchunkdevice.rs"] mod impl_drop_for_gdnchunkdevice; +#[path = "gdn_chunk_device/impl_gdnchunkdevice.rs"] +mod impl_gdnchunkdevice; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_drop_for_gdnchunkdevice.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_drop_for_gdnchunkdevice.rs index 5b59c22c..88adf0e4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_drop_for_gdnchunkdevice.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_drop_for_gdnchunkdevice.rs @@ -12,21 +12,27 @@ impl Drop for GdnChunkDevice<'_> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> GdnChunkDevice<'ctx> { pub(in super::super) fn bind_native_fused( - &self, row: &GdnChunkRow, + &self, + row: &GdnChunkRow, program: Rc>>, ) -> Result<()> { self.validate_row(row, &self.start.binding(), self.context)?; let (workspace, lease) = self.verification.as_ref().ok_or(Error::IdentityMismatch)?; - workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? - .bind_native_fused(lease, program) + workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.bind_native_fused(lease, program) } pub(in super::super) fn native_fused_operands( - &self, row: &GdnChunkRow, + &self, + row: &GdnChunkRow, ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { self.validate_row(row, &self.start.binding(), self.context)?; - Ok((self.initial.as_ref().filter(|_| self.cursor == 0).or(self.state.as_ref()) + Ok(( + self.initial + .as_ref() + .filter(|_| self.cursor == 0) + .or(self.state.as_ref()) .ok_or(Error::IdentityMismatch)?, - self.next.as_ref().ok_or(Error::IdentityMismatch)?)) + self.next.as_ref().ok_or(Error::IdentityMismatch)?, + )) } pub(in super::super) fn complete_native_fused_step(&mut self, row: &GdnChunkRow) -> Result<()> { self.validate_row(row, &self.start.binding(), self.context)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs index b1485d18..d192cf63 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GdnChunkDevice<'ctx> { pub(in crate::qwen_forward) fn new( binding: &ModelBinding, @@ -18,10 +17,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { validate_values(start.prior().history(), HISTORY_ELEMENTS)?; preflight_budget( context.budget_bytes(), - context - .allocated_bytes() - .checked_add(CHUNK_DEVICE_CHARGE) - .ok_or(Error::Overflow)?, + context.allocated_bytes().checked_add(CHUNK_DEVICE_CHARGE).ok_or(Error::Overflow)?, )?; let mut owner = Self { context, @@ -42,9 +38,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { }; let operation = (|| { let mut history = Vec::new(); - history - .try_reserve_exact(HISTORY_ELEMENTS) - .map_err(|_| Error::InputAllocation)?; + history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_| Error::InputAllocation)?; history.extend_from_slice(owner.start.prior().history()); owner.history = Some(history.into_boxed_slice()); // One canonical upload per layer/chunk, even on an old mirror hit. @@ -73,30 +67,64 @@ impl<'ctx> GdnChunkDevice<'ctx> { Ok(owner) } pub(in crate::qwen_forward) fn new_verification( - binding: &ModelBinding, current: &Context<'_>, cache: &DenseWeightCache<'ctx>, start: GdnChunkStart, + binding: &ModelBinding, + current: &Context<'_>, + cache: &DenseWeightCache<'ctx>, + start: GdnChunkStart, lease: Rc, ) -> Result { let context = cache.retained_context(binding, current)?; let failed = cache.transport_failure_flag(binding, context)?; let workspace = cache.gdn_verification_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; validate_values(start.prior().history(), HISTORY_ELEMENTS)?; - let mut history = Vec::new(); history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_|Error::InputAllocation)?; + let mut history = Vec::new(); + history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_| Error::InputAllocation)?; history.extend_from_slice(start.prior().history()); - let mut verified_rows = Vec::new(); verified_rows.try_reserve_exact(start.count()).map_err(|_|Error::InputAllocation)?; - let ([state,next,initial],guard) = workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_layer(&lease,&start)?; - Ok(Self { context, failed, start, state:Some(state),next:Some(next),guard:Some(guard),history:Some(history.into_boxed_slice()), - cursor:0,inflight:false,valid:true,verification:Some((workspace,lease)),verified_rows,initial:Some(initial), - queue:None,queue_enabled:false }) + let mut verified_rows = Vec::new(); + verified_rows.try_reserve_exact(start.count()).map_err(|_| Error::InputAllocation)?; + let ([state, next, initial], guard) = + workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take_layer(&lease, &start)?; + Ok(Self { + context, + failed, + start, + state: Some(state), + next: Some(next), + guard: Some(guard), + history: Some(history.into_boxed_slice()), + cursor: 0, + inflight: false, + valid: true, + verification: Some((workspace, lease)), + verified_rows, + initial: Some(initial), + queue: None, + queue_enabled: false, + }) } - pub(in super::super::super) fn verification_pool(&self, row:&GdnChunkRow)->Result>> { - if self.verification.is_none(){return Ok(None);} - self.validate_row(row,&self.start.binding(),self.context)?; - self.verification.as_ref().map(|(owner,lease)|super::super::super::verification::Workspace::row_pool(owner.clone(),lease.clone(),row)).transpose() + pub(in super::super::super) fn verification_pool( + &self, + row: &GdnChunkRow, + ) -> Result>> { + if self.verification.is_none() { + return Ok(None); + } + self.validate_row(row, &self.start.binding(), self.context)?; + self.verification + .as_ref() + .map(|(owner, lease)| { + super::super::super::verification::Workspace::row_pool(owner.clone(), lease.clone(), row) + }) + .transpose() + } + pub(in crate::qwen_forward) fn is_verification(&self) -> bool { + self.verification.is_some() } - pub(in crate::qwen_forward) fn is_verification(&self)->bool {self.verification.is_some()} pub(in super::super) fn note(&mut self, error: Error) { self.valid = false; - if let Some((_,lease))=&self.verification { lease.refuse(); } + if let Some((_, lease)) = &self.verification { + lease.refuse(); + } if error == Error::CudaExecution { self.failed.set(true); } @@ -164,10 +192,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { if !self.row_queue_enabled() { return Err(Error::IdentityMismatch); } - Ok(( - self.state.as_ref().ok_or(Error::IdentityMismatch)?, - self.next.as_ref().ok_or(Error::IdentityMismatch)?, - )) + Ok((self.state.as_ref().ok_or(Error::IdentityMismatch)?, self.next.as_ref().ok_or(Error::IdentityMismatch)?)) } pub(in super::super::super) fn complete_queued_step(&mut self, row: &GdnChunkRow) -> Result<()> { self.validate_row(row, &self.start.binding(), self.context)?; @@ -192,10 +217,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { let cursor = self.cursor.checked_add(offset).ok_or(Error::Overflow)?; self.validate_batch_row(row, cursor)?; } - Ok(( - self.state.as_ref().ok_or(Error::IdentityMismatch)?, - self.next.as_ref().ok_or(Error::IdentityMismatch)?, - )) + Ok((self.state.as_ref().ok_or(Error::IdentityMismatch)?, self.next.as_ref().ok_or(Error::IdentityMismatch)?)) } pub(in super::super) fn validate_batch_row(&self, row: &GdnChunkRow, cursor: usize) -> Result<()> { if self.failed.get() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs index 1d1edde3..f604fcfb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GdnChunkDevice<'ctx> { /// Adopt the final state of a batch that drained clean: the separate `next` /// owner becomes the chunk state, the history becomes the batch's canonical @@ -27,9 +26,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { } let cursor = self.cursor.checked_add(rows.len()).ok_or(Error::Overflow)?; let mut edges = Vec::new(); - edges - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + edges.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; std::mem::swap(&mut self.state, &mut self.next); self.history = Some(history); self.cursor = cursor; @@ -38,7 +35,9 @@ impl<'ctx> GdnChunkDevice<'ctx> { Ok(edges) } pub(in super::super::super) fn history(&self) -> Result<&[f32]> { - if let Some(row)=self.verified_rows.last() { return Ok(row.history()); } + if let Some(row) = self.verified_rows.last() { + return Ok(row.history()); + } self.history.as_deref().ok_or(Error::IdentityMismatch) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -54,9 +53,7 @@ impl<'ctx> GdnChunkDevice<'ctx> { } preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; let mut temporary = Vec::new(); - temporary - .try_reserve_exact(5) - .map_err(|_| Error::InputAllocation)?; + temporary.try_reserve_exact(5).map_err(|_| Error::InputAllocation)?; let mut output = None; let operation = (|| { for values in inputs { @@ -65,7 +62,11 @@ impl<'ctx> GdnChunkDevice<'ctx> { output = Some(allocate(self.context, VALUES)?); self.context .gdn_step_f32( - self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, + self.initial + .as_ref() + .filter(|_| self.cursor == 0) + .or(self.state.as_ref()) + .ok_or(Error::IdentityMismatch)?, &temporary[0], &temporary[1], &temporary[2], @@ -126,25 +127,38 @@ impl<'ctx> GdnChunkDevice<'ctx> { inputs: super::super::super::chain::RecurrenceBorrow<'_, 'ctx>, ) -> Result> { self.validate_row(row, &self.start.binding(), self.context)?; - let (scope, [qk, h, gate, beta]) = - inputs.into_parts(self.context, &self.start.binding(), &self.failed, row)?; + let (scope, [qk, h, gate, beta]) = inputs.into_parts(self.context, &self.start.binding(), &self.failed, row)?; preflight_budget(self.context.budget_bytes(), self.context.allocated_bytes())?; let mut output = None; let operation = (|| { - output = Some(if let Some((workspace,lease))=&self.verification { - workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.take_readout(lease)? - } else { allocate(self.context, VALUES)? }); - if self.verification.is_some(){ - return super::super::super::verification::compute_row(self.context, - self.initial.as_ref().filter(|_|self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, - [qk,h,gate,beta],self.next.as_mut().ok_or(Error::IdentityMismatch)?, - output.as_mut().ok_or(Error::IdentityMismatch)?,self.guard.as_mut().ok_or(Error::IdentityMismatch)?); + output = Some(if let Some((workspace, lease)) = &self.verification { + workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take_readout(lease)? + } else { + allocate(self.context, VALUES)? + }); + if self.verification.is_some() { + return super::super::super::verification::compute_row( + self.context, + self.initial + .as_ref() + .filter(|_| self.cursor == 0) + .or(self.state.as_ref()) + .ok_or(Error::IdentityMismatch)?, + [qk, h, gate, beta], + self.next.as_mut().ok_or(Error::IdentityMismatch)?, + output.as_mut().ok_or(Error::IdentityMismatch)?, + self.guard.as_mut().ok_or(Error::IdentityMismatch)?, + ); } // The driver admits these actual whole producers, then derives // only fixed Q/K/V subspans. No view/handle is fabricated here. self.context .gdn_step_from_products_f32( - self.initial.as_ref().filter(|_| self.cursor==0).or(self.state.as_ref()).ok_or(Error::IdentityMismatch)?, + self.initial + .as_ref() + .filter(|_| self.cursor == 0) + .or(self.state.as_ref()) + .ok_or(Error::IdentityMismatch)?, qk, h, gate, @@ -176,26 +190,29 @@ impl<'ctx> GdnChunkDevice<'ctx> { scope, buffer: output.take(), values: Some(values), - verification: self.verification.as_ref().map(|(workspace,_)|workspace.clone()), + verification: self.verification.as_ref().map(|(workspace, _)| workspace.clone()), }) } Err(primary) => { self.note(primary); if let Some(buffer) = output { - let cleanup=if let Some((workspace,_))=&self.verification { - workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch).and_then(|mut owner|owner.put_readout(buffer)) - } else {buffer.release().map_err(driver_error)}; - if cleanup.is_err(){self.failed.set(true);} + let cleanup = if let Some((workspace, _)) = &self.verification { + workspace + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch) + .and_then(|mut owner| owner.put_readout(buffer)) + } else { + buffer.release().map_err(driver_error) + }; + if cleanup.is_err() { + self.failed.set(true); + } } Err(primary) } } } - pub(in super::super::super) fn finish_row( - &mut self, - row: GdnChunkRow, - history: Box<[f32]>, - ) -> Result { + pub(in super::super::super) fn finish_row(&mut self, row: GdnChunkRow, history: Box<[f32]>) -> Result { if self.failed.get() { return Err(Error::CudaExecution); } @@ -204,12 +221,19 @@ impl<'ctx> GdnChunkDevice<'ctx> { } row.validate(&self.start, self.cursor, &self.start.binding())?; validate_values(&history, HISTORY_ELEMENTS)?; - if let Some((workspace,lease))=&self.verification { - let proof=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.record(lease,&self.start,row.clone(),history)?; + if let Some((workspace, lease)) = &self.verification { + let proof = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.record( + lease, + &self.start, + row.clone(), + history, + )?; self.verified_rows.push(proof.clone()); - std::mem::swap(&mut self.state,&mut self.next); - self.history=None;self.cursor=self.cursor.checked_add(1).ok_or(Error::Overflow)?;self.inflight=false; - return Ok(ChunkEdge {row,verified:Some(proof)}); + std::mem::swap(&mut self.state, &mut self.next); + self.history = None; + self.cursor = self.cursor.checked_add(1).ok_or(Error::Overflow)?; + self.inflight = false; + return Ok(ChunkEdge { row, verified: Some(proof) }); } std::mem::swap(&mut self.state, &mut self.next); self.history = Some(history); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs index ce5169ef..7f1d3876 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/impl_gdnchunkdevice/impl_gdnchunkdevice_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> GdnChunkDevice<'ctx> { pub(in crate::qwen_forward) fn finish( mut self, @@ -12,9 +11,8 @@ impl<'ctx> GdnChunkDevice<'ctx> { cache: &DenseWeightCache<'ctx>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); if self.failed.get() { return Err(Error::CudaExecution); } @@ -48,21 +46,41 @@ impl<'ctx> GdnChunkDevice<'ctx> { self.valid = false; Ok(prior) } - pub(in crate::qwen_forward) fn finish_verification(mut self, seal:GdnChunkSeal, binding:&ModelBinding, cache:&DenseWeightCache<'ctx>)->Result<()> { - if self.failed.get(){return Err(Error::CudaExecution);} - if !self.valid || self.inflight || self.verification.is_none() || self.verified_rows.len()!=self.cursor {return Err(Error::IdentityMismatch);} - seal.validate(&self.start,self.cursor)?;cache.retained_context(binding,self.context)?; - self.return_verification_owners()?;self.valid=false;Ok(()) - } - pub(in super::super) fn return_verification_owners(&mut self)->Result<()> { - let Some((workspace,_))=self.verification.as_ref() else {return Ok(());}; - if self.state.is_none() || self.next.is_none() || self.initial.is_none() || self.guard.is_none() { - self.failed.set(true);return Err(Error::IdentityMismatch); + pub(in crate::qwen_forward) fn finish_verification( + mut self, + seal: GdnChunkSeal, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + ) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); } - let mut workspace=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?; - workspace.return_layer([self.state.take().ok_or(Error::IdentityMismatch)?, - self.next.take().ok_or(Error::IdentityMismatch)?,self.initial.take().ok_or(Error::IdentityMismatch)?], - self.guard.take().ok_or(Error::IdentityMismatch)?) + if !self.valid || self.inflight || self.verification.is_none() || self.verified_rows.len() != self.cursor { + return Err(Error::IdentityMismatch); + } + seal.validate(&self.start, self.cursor)?; + cache.retained_context(binding, self.context)?; + self.return_verification_owners()?; + self.valid = false; + Ok(()) + } + pub(in super::super) fn return_verification_owners(&mut self) -> Result<()> { + let Some((workspace, _)) = self.verification.as_ref() else { + return Ok(()); + }; + if self.state.is_none() || self.next.is_none() || self.initial.is_none() || self.guard.is_none() { + self.failed.set(true); + return Err(Error::IdentityMismatch); + } + let mut workspace = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + workspace.return_layer( + [ + self.state.take().ok_or(Error::IdentityMismatch)?, + self.next.take().ok_or(Error::IdentityMismatch)?, + self.initial.take().ok_or(Error::IdentityMismatch)?, + ], + self.guard.take().ok_or(Error::IdentityMismatch)?, + ) } pub(in super::super) fn cleanup(&mut self) -> Result<()> { self.valid = false; @@ -75,11 +93,15 @@ impl<'ctx> GdnChunkDevice<'ctx> { } if self.verification.is_some() && self.initial.is_some() { match self.return_verification_owners() { - Ok(())=>return Ok(()), - Err(primary)=>{ + Ok(()) => return Ok(()), + Err(primary) => { self.failed.set(true); - if let Some(guard)=self.guard.take(){let _=guard.close();} - for buffer in [self.state.take(),self.next.take(),self.initial.take()].into_iter().flatten(){let _=buffer.release();} + if let Some(guard) = self.guard.take() { + let _ = guard.close(); + } + for buffer in [self.state.take(), self.next.take(), self.initial.take()].into_iter().flatten() { + let _ = buffer.release(); + } return Err(primary); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/mirror_reuse_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/mirror_reuse_enabled_fn.rs index 75c10979..207db6e5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/mirror_reuse_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_device/mirror_reuse_enabled_fn.rs @@ -3,12 +3,15 @@ #[allow(unused_imports)] use super::*; - pub(super) fn mirror_reuse_enabled() -> bool { crate::settings::process().kv.prefill_gdn_mirror } impl ChunkEdge { - pub(in crate::qwen_forward) fn into_parts(self) -> (GdnChunkRow, Option>) { (self.row, self.verified) } + pub(in crate::qwen_forward) fn into_parts( + self, + ) -> (GdnChunkRow, Option>) { + (self.row, self.verified) + } pub(in crate::qwen_forward) fn into_row(self) -> GdnChunkRow { self.row } @@ -17,8 +20,7 @@ impl ChunkEdge { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn micro_rows(micro: &GdnChunkMicro) -> Result> { let mut rows = Vec::new(); - rows.try_reserve_exact(micro.len()) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(micro.len()).map_err(|_| Error::InputAllocation)?; for local in 0..micro.len() { rows.push(micro.row(local)?.clone()); } @@ -45,23 +47,24 @@ impl<'ctx> ChunkReadout<'ctx> { if self.buffer.as_ref().is_none_or(|b| b.len() != VALUES * 4) { return Err(Error::InvalidDimension); } - validate_values( - self.values.as_deref().ok_or(Error::IdentityMismatch)?, - VALUES, - )?; - Ok(( - self.buffer.take().ok_or(Error::IdentityMismatch)?, - self.values.take().ok_or(Error::IdentityMismatch)?, - )) + validate_values(self.values.as_deref().ok_or(Error::IdentityMismatch)?, VALUES)?; + Ok((self.buffer.take().ok_or(Error::IdentityMismatch)?, self.values.take().ok_or(Error::IdentityMismatch)?)) } } impl Drop for ChunkReadout<'_> { fn drop(&mut self) { if let Some(buffer) = self.buffer.take() { let cleanup = if let Some(owner) = &self.verification { - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.put_readout(buffer)) - } else { buffer.release().map_err(driver_error) }; - if cleanup.is_err() { self.failed.set(true); } + owner + .try_borrow_mut() + .map_err(|_| Error::IdentityMismatch) + .and_then(|mut owner| owner.put_readout(buffer)) + } else { + buffer.release().map_err(driver_error) + }; + if cleanup.is_err() { + self.failed.set(true); + } } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_fused.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_fused.rs index 78f5ab0e..729c9ad9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_fused.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_fused.rs @@ -1,25 +1,28 @@ //! Selected native fused chunk row; actual journal authority remains in //! GdnChunkDevice/PoolRow. Original per-token fused arithmetic, not prompt B. -use super::*; +use super::super::session::chunk::GdnChunkRow; use super::chain::{FusedInputs, Role}; use super::chunk_producer::ChunkReady; -use super::super::session::chunk::GdnChunkRow; +use super::*; use leleka_cuda_driver::GdnFusedT1; use std::{cell::RefCell, rc::Rc}; impl GdnStage { #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn step_chunk_fused<'ctx>( - binding: &ModelBinding, layer: LayerId, input: &ResidualReady, - txn: &mut QwenStepTxn, cache: &DenseWeightCache<'ctx>, - owner: &mut chunk_device::GdnChunkDevice<'ctx>, row: GdnChunkRow, + binding: &ModelBinding, + layer: LayerId, + input: &ResidualReady, + txn: &mut QwenStepTxn, + cache: &DenseWeightCache<'ctx>, + owner: &mut chunk_device::GdnChunkDevice<'ctx>, + row: GdnChunkRow, program: Rc>>, projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); txn.validate_binding(&binding.identity())?; let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer || input.identity().layer() != layer || row.identity() != input.identity() { @@ -37,7 +40,9 @@ impl GdnStage { let context = cache.retained_context(binding, current)?; owner.validate_row(&row, &binding.identity(), context)?; let verification = owner.is_verification(); - if verification { owner.bind_native_fused(&row, program.clone())?; } + if verification { + owner.bind_native_fused(&row, program.clone())?; + } let failed = cache.transport_failure_flag(binding, context)?; let resident = cache.gdn(binding, layer.get())?; let weights = resident.weights.clone(); @@ -52,14 +57,27 @@ impl GdnStage { let qkv = if let Some(projection) = projection { chain.import_projected_qkv(projection, binding, cache, txn, layer, input)? } else { - project_chain_input(&mut chain, context, binding, &weights, GdnMatrixRole::Qkv, - &input_lease, input.mixed(), cache)? + project_chain_input( + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Qkv, + &input_lease, + input.mixed(), + cache, + )? }; let (w_alpha, alpha_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Alpha)?; - if alpha_kind != GdnMatrixKind::Bf16 { return Err(Error::Unsupported(Stage::Gdn)); } + if alpha_kind != GdnMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::Gdn)); + } let (w_beta, beta_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Beta)?; - if beta_kind != GdnMatrixKind::Bf16 { return Err(Error::Unsupported(Stage::Gdn)); } - let mixed = input_lease.buffer(&binding.identity(), context, layer.get(), GdnMatrixRole::Z, input.mixed())?; + if beta_kind != GdnMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::Gdn)); + } + let mixed = + input_lease.buffer(&binding.identity(), context, layer.get(), GdnMatrixRole::Z, input.mixed())?; let (z_matrix, z_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Z)?; let z = chain.project_device(z_matrix, z_kind, mixed, Role::Z)?; let produced = { @@ -67,8 +85,17 @@ impl GdnStage { let mut program = program.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; program.validate_context(context).map_err(driver_error)?; let inputs = FusedInputs { - qkv: &qkv, z: &z, prior_history: owner.history()?, mixed, w_alpha, w_beta, - conv_weights: aux[0], dt: aux[1], a: aux[2], gamma: aux[3], epsilon: weights.epsilon(), + qkv: &qkv, + z: &z, + prior_history: owner.history()?, + mixed, + w_alpha, + w_beta, + conv_weights: aux[0], + dt: aux[1], + a: aux[2], + gamma: aux[3], + epsilon: weights.epsilon(), }; if verification { chain.run_fused_verification_row(&mut program, Some(state), next, inputs)? @@ -93,13 +120,18 @@ impl GdnStage { owner.complete_native_fused_step(&row)?; Ok((produced.next_history.into_values(), output)) })(); - if matches!(operation, Err(Error::CudaExecution)) { failed.set(true); } + if matches!(operation, Err(Error::CudaExecution)) { + failed.set(true); + } let cleanup = chain.finish(); drop(input_lease); let result = operation.and_then(|values| cleanup.map(|()| values)); let (history, output) = match result { Ok(values) => values, - Err(primary) => { owner.refuse(primary); return Err(primary); } + Err(primary) => { + owner.refuse(primary); + return Err(primary); + } }; // Verification operands have returned to the actual journal pool. // Ordinary rows retain their real state/candidate and host history; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu.rs index aaff26fa..2709c413 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu.rs @@ -35,20 +35,14 @@ struct Counts { #[test] #[ignore = "Root-only changed GDN65-row recurrence/finite/abort component"] fn sixty_five_actual_recurrences_finite_and_local_abort_match_same_ptx_reference() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GDN_CHUNK_COMPONENT").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_CHUNK_COMPONENT").as_deref(), Ok("yes")); run_gdn_chunk_numeric().expect("changed GDN component refused after cleanup attempts"); } #[test] #[ignore = "Root-only changed GDN batch adoption component"] fn batch_adoption_is_consecutive_atomic_and_swaps_the_final_state_once() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GDN_CHUNK_COMPONENT").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_CHUNK_COMPONENT").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(BUDGET).unwrap(); @@ -62,7 +56,7 @@ fn batch_adoption_is_consecutive_atomic_and_swaps_the_final_state_once() { #[path = "gdn_chunk_numeric_gpu/operands_fn.rs"] mod operands_fn; #[allow(unused_imports)] -use operands_fn::operands; +use operands_fn::component_owner; #[allow(unused_imports)] use operands_fn::convolution_input; #[allow(unused_imports)] @@ -70,11 +64,11 @@ use operands_fn::convolution_weights; #[allow(unused_imports)] use operands_fn::difference; #[allow(unused_imports)] -use operands_fn::require; +use operands_fn::operands; #[allow(unused_imports)] use operands_fn::reference; #[allow(unused_imports)] -use operands_fn::component_owner; +use operands_fn::require; #[path = "gdn_chunk_numeric_gpu/exercise_fn.rs"] mod exercise_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/batch_adoption_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/batch_adoption_fn.rs index 9624f257..b74fdbf5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/batch_adoption_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/batch_adoption_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // Batch adoption of the Strata-prefill step. Pure ownership/identity: no kernel // runs here, the final state is a recognisable pattern written into `next`. pub(super) fn batch_adoption(context: &Context<'_>) -> Result<()> { @@ -32,12 +31,7 @@ pub(super) fn batch_adoption(context: &Context<'_>) -> Result<()> { for value in &pattern { bytes.extend_from_slice(&value.to_le_bytes()); } - owner - .next - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from(&bytes) - .map_err(driver_error)?; + owner.next.as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&bytes).map_err(driver_error)?; let mut history = vec![0.25f32; HISTORY_ELEMENTS]; history[7] = -0.5; let wrong = owner.finish_batch(first[1..4].to_vec(), history.clone().into_boxed_slice()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/exercise_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/exercise_fn.rs index cfbd349c..7a34e59e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/exercise_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/exercise_fn.rs @@ -16,24 +16,11 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { let mut owner = component_owner(context, rows.start())?; let live_bytes = context.allocated_bytes(); require(live_bytes == CHUNK_DEVICE_CHARGE)?; - let mut counts = Counts { - readout: 0, - state: 0, - history: 0, - differences: 0, - guards: 0, - }; + let mut counts = Counts { readout: 0, state: 0, history: 0, differences: 0, guards: 0 }; + require(owner.validate_row(&rival.row(0)?, &binding, context).err() == Some(Error::IdentityMismatch))?; + require(owner.validate_row(&rows.row(1)?, &binding, context).err() == Some(Error::IdentityMismatch))?; require( - owner.validate_row(&rival.row(0)?, &binding, context).err() - == Some(Error::IdentityMismatch), - )?; - require( - owner.validate_row(&rows.row(1)?, &binding, context).err() == Some(Error::IdentityMismatch), - )?; - require( - owner - .validate_row(&rows.row(0)?, &BindingIdentity::test_identity(), context) - .err() + owner.validate_row(&rows.row(0)?, &BindingIdentity::test_identity(), context).err() == Some(Error::IdentityMismatch), )?; require(rows.row(65).err() == Some(Error::IdentityMismatch))?; @@ -41,28 +28,13 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { counts.guards += 5; let weights = convolution_weights(); for (index, expected_readout) in expected.readouts.iter().enumerate() { - let (history, h) = convolve( - context, - owner.history()?, - &convolution_input(index), - &weights, - None, - )?; + let (history, h) = convolve(context, owner.history()?, &convolution_input(index), &weights, None)?; let p = operands(index); let row = rows.row(index)?; let scope = Rc::new(()); - let readout = owner.compute( - &row, - scope.clone(), - [&p.q, &p.k, &h[4096..], &p.gate, &p.beta], - )?; + let readout = owner.compute(&row, scope.clone(), [&p.q, &p.k, &h[4096..], &p.gate, &p.beta])?; require(owner.cursor == index && owner.inflight)?; - require( - owner - .validate_row(&rows.row(index)?, &binding, context) - .err() - == Some(Error::IdentityMismatch), - )?; + require(owner.validate_row(&rows.row(index)?, &binding, context).err() == Some(Error::IdentityMismatch))?; let (buffer, values) = readout.into_parts(context, &owner.failed, &row, &scope)?; counts.differences += difference(&values, expected_readout)?; counts.readout += values.len(); @@ -73,17 +45,13 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { require(owner.cursor == index + 1 && !owner.inflight)?; require(context.allocated_bytes() == live_bytes)?; if index == 63 || index == 64 { - let actual = download( - owner.state.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?; + let actual = download(owner.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?; let (state, history) = if index == 63 { (&expected.state64, &expected.history64) } else { (&expected.state65, &expected.history65) }; - counts.differences += - difference(&actual, state)? + difference(owner.history()?, history)?; + counts.differences += difference(&actual, state)? + difference(owner.history()?, history)?; counts.state += actual.len(); counts.history += history.len(); } @@ -91,29 +59,20 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { let seal = rows.seal(owner.cursor)?; seal.validate(&owner.start, owner.cursor)?; let rival_seal = rival.seal(65)?; - require( - rival_seal.validate(&owner.start, owner.cursor).err() == Some(Error::IdentityMismatch), - )?; + require(rival_seal.validate(&owner.start, owner.cursor).err() == Some(Error::IdentityMismatch))?; counts.guards += 1; - let actual = download( - owner.state.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?; + let actual = download(owner.state.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?; // Actual canonical factory, but TEST-ONLY seal: no genuine layer/cache adoption claim. - let canonical = GdnPrior::from_chunk_boundary( - &prior, - &seal, - actual, - owner.history.take().ok_or(Error::IdentityMismatch)?, - )?; + let canonical = + GdnPrior::from_chunk_boundary(&prior, &seal, actual, owner.history.take().ok_or(Error::IdentityMismatch)?)?; canonical.validate( &binding, &gdn_owner, layer, super::super::super::super::contract::Position::new(65, crate::qwen_forward::contract::position_dimension())?, )?; - counts.differences += difference(canonical.values(), &expected.state65)? - + difference(canonical.history(), &expected.history65)?; + counts.differences += + difference(canonical.values(), &expected.state65)? + difference(canonical.history(), &expected.history65)?; let rival_prior = GdnPrior::zero(binding.clone(), &gdn_owner, layer)?; require(seal.validate_prior(&rival_prior).err() == Some(Error::IdentityMismatch))?; counts.guards += 1; @@ -124,13 +83,9 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { let mut state = upload(context, &expected.state64)?; let mut guard = context.gdn_state_finite_guard().map_err(driver_error)?; for word in [17usize, STATE_ELEMENTS - 17] { - state - .copy_from_range(word * 4, &0x7fc0_0001u32.to_le_bytes()) - .map_err(driver_error)?; + state.copy_from_range(word * 4, &0x7fc0_0001u32.to_le_bytes()).map_err(driver_error)?; require(!guard.check_next_state(&state).map_err(driver_error)?)?; - state - .copy_from_range(word * 4, &expected.state64[word].to_bits().to_le_bytes()) - .map_err(driver_error)?; + state.copy_from_range(word * 4, &expected.state64[word].to_bits().to_le_bytes()).map_err(driver_error)?; require(guard.check_next_state(&state).map_err(driver_error)?)?; require(!context.is_poisoned())?; counts.guards += 2; @@ -148,21 +103,9 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { .copy_from_range(word * 4, &0x7fc0_0001u32.to_le_bytes()) .map_err(driver_error)?; let p = operands(0); - let (_, h) = convolve( - context, - prior.history(), - &convolution_input(0), - &weights, - None, - )?; + let (_, h) = convolve(context, prior.history(), &convolution_input(0), &weights, None)?; require( - rejected - .compute( - &rows.row(0)?, - Rc::new(()), - [&p.q, &p.k, &h[4096..], &p.gate, &p.beta], - ) - .err() + rejected.compute(&rows.row(0)?, Rc::new(()), [&p.q, &p.k, &h[4096..], &p.gate, &p.beta]).err() == Some(Error::NonFinite), )?; require( @@ -180,36 +123,22 @@ pub(super) fn exercise(context: &Context<'_>) -> Result { // Real computed readout is dropped before finish_row: local abort cannot // swap state/history, install a canonical prior or modify the original Rc. let mut aborted = component_owner(context, rows.start())?; - let (_, h) = convolve( - context, - aborted.history()?, - &convolution_input(0), - &weights, - None, - )?; + let (_, h) = convolve(context, aborted.history()?, &convolution_input(0), &weights, None)?; let p = operands(0); - let readout = aborted.compute( - &rows.row(0)?, - Rc::new(()), - [&p.q, &p.k, &h[4096..], &p.gate, &p.beta], - )?; + let readout = aborted.compute(&rows.row(0)?, Rc::new(()), [&p.q, &p.k, &h[4096..], &p.gate, &p.beta])?; drop(readout); require(aborted.cursor == 0 && aborted.inflight)?; aborted.cleanup()?; drop(aborted); require(context.allocated_bytes() == 0)?; - counts.differences += difference(prior.values(), &original_values)? - + difference(prior.history(), &original_history)?; + counts.differences += + difference(prior.values(), &original_values)? + difference(prior.history(), &original_history)?; require(prior.next_position() == 0)?; // Replay the same prior after abort; new actual owner must reproduce first reference. let mut replay = component_owner(context, rows.start())?; let row = rows.row(0)?; let scope = Rc::new(()); - let readout = replay.compute( - &row, - scope.clone(), - [&p.q, &p.k, &h[4096..], &p.gate, &p.beta], - )?; + let readout = replay.compute(&row, scope.clone(), [&p.q, &p.k, &h[4096..], &p.gate, &p.beta])?; let (buffer, values) = readout.into_parts(context, &replay.failed, &row, &scope)?; counts.differences += difference(&values, &expected.readouts[0])?; buffer.release().map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/operands_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/operands_fn.rs index dd683d2b..d25c8c61 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/operands_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_numeric_gpu/operands_fn.rs @@ -5,37 +5,19 @@ use super::*; pub(super) fn operands(row: usize) -> Operands { Operands { - q: (0..2048) - .map(|i| ((i + row * 3) % 17) as f32 / 128.0 - 0.0625) - .collect(), - k: (0..2048) - .map(|i| ((i * 3 + row * 5) % 19) as f32 / 128.0 - 0.0703125) - .collect(), + q: (0..2048).map(|i| ((i + row * 3) % 17) as f32 / 128.0 - 0.0625).collect(), + k: (0..2048).map(|i| ((i * 3 + row * 5) % 19) as f32 / 128.0 - 0.0703125).collect(), gate: std::array::from_fn(|i| -0.125 - ((i + row) % 4) as f32 / 16.0), - beta: std::array::from_fn(|i| { - if (i + row).is_multiple_of(2) { - 0.25 - } else { - 0.5 - } - }), + beta: std::array::from_fn(|i| if (i + row).is_multiple_of(2) { 0.25 } else { 0.5 }), } } pub(super) fn convolution_input(row: usize) -> Vec { (0..super::super::super::CHANNELS) - .map(|i| { - if row == 2 && i.is_multiple_of(2) { - -0.0 - } else { - ((i + row * 7) % 23) as f32 / 64.0 - 0.171875 - } - }) + .map(|i| if row == 2 && i.is_multiple_of(2) { -0.0 } else { ((i + row * 7) % 23) as f32 / 64.0 - 0.171875 }) .collect() } pub(super) fn convolution_weights() -> Vec { - (0..4 * super::super::super::CHANNELS) - .map(|i| ((i % 7) as f32 - 3.0) / 32.0) - .collect() + (0..4 * super::super::super::CHANNELS).map(|i| ((i % 7) as f32 - 3.0) / 32.0).collect() } pub(super) fn difference(left: &[f32], right: &[f32]) -> Result { if left.len() != right.len() { @@ -44,33 +26,22 @@ pub(super) fn difference(left: &[f32], right: &[f32]) -> Result { if left.iter().chain(right).any(|v| !v.is_finite()) { return Err(Error::NonFinite); } - Ok(left - .iter() - .zip(right) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count()) + Ok(left.iter().zip(right).filter(|(a, b)| a.to_bits() != b.to_bits()).count()) } pub(super) fn require(value: bool) -> Result<()> { - if value { - Ok(()) - } else { - Err(Error::IdentityMismatch) - } + if value { Ok(()) } else { Err(Error::IdentityMismatch) } } pub(super) fn reference(context: &Context<'_>, prior: &GdnPrior) -> Result { let mut state = prior.values().to_vec().into_boxed_slice(); let mut history = prior.history().to_vec().into_boxed_slice(); let weights = convolution_weights(); let mut readouts = Vec::new(); - readouts - .try_reserve_exact(ROWS) - .map_err(|_| Error::InputAllocation)?; + readouts.try_reserve_exact(ROWS).map_err(|_| Error::InputAllocation)?; let mut state64 = None; let mut history64 = None; for row in 0..ROWS { // Actual unchanged convolution and recurrence FIRST for every row. - let (next_history, h) = - convolve(context, &history, &convolution_input(row), &weights, None)?; + let (next_history, h) = convolve(context, &history, &convolution_input(row), &weights, None)?; let p = operands(row); let (next, readout) = recur(context, &state, &p.q, &p.k, &h[4096..], &p.gate, &p.beta)?; state = next; @@ -116,10 +87,7 @@ pub(super) fn component_owner<'ctx>( validate_values(owner.start.prior().values(), STATE_ELEMENTS)?; preflight_budget( context.budget_bytes(), - context - .allocated_bytes() - .checked_add(CHUNK_DEVICE_CHARGE) - .ok_or(Error::Overflow)?, + context.allocated_bytes().checked_add(CHUNK_DEVICE_CHARGE).ok_or(Error::Overflow)?, )?; owner.history = Some(owner.start.prior().history().to_vec().into_boxed_slice()); owner.state = Some(upload(context, owner.start.prior().values())?); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_producer.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_producer.rs index 55c82c95..b12ca35a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_producer.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_chunk_producer.rs @@ -32,12 +32,7 @@ impl ChunkReady { output: Box<[f32]>, edge: chunk_device::ChunkEdge, ) -> Self { - Self { - identity, - binding, - output, - edge, - } + Self { identity, binding, output, edge } } } impl GdnStage { @@ -53,21 +48,14 @@ impl GdnStage { projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, 'ctx>>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); txn.validate_binding(&binding.identity())?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer || input.identity().layer() != layer { return Err(Error::IdentityMismatch); } - let descriptor = binding - .ordered_layers() - .get(layer.get() as usize) - .ok_or(Error::InvalidLayer)?; + let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { return Err(Error::InvalidLayer); } @@ -82,13 +70,9 @@ impl GdnStage { // Explicit opt-in only: the closed one-drain queue never replaces the // scalar chain for verification rows or without the retained QK slot. if owner.row_queue_enabled() && cache.has_gdn_qk_workspace() { - return step_chain_queued( - binding, layer, input, owner, row, context, cache, txn, projection, - ); + return step_chain_queued(binding, layer, input, owner, row, context, cache, txn, projection); } - step_chain( - binding, layer, input, owner, row, context, cache, txn, projection, - ) + step_chain(binding, layer, input, owner, row, context, cache, txn, projection) } } // Device-only projection: the same pre-checks and library call as @@ -140,14 +124,9 @@ fn step_chain<'ctx>( let aux = cache.gdn_aux(resident)?; owner.validate_row(&row, &binding.identity(), context)?; let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?; - let mut chain = chain::Chain::new( - context, - binding.identity(), - input.identity(), - failed.clone(), - )?; + let mut chain = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?; chain.validate(context, &binding.identity(), input.identity())?; - if let Some(pool)=owner.verification_pool(&row)? { + if let Some(pool) = owner.verification_pool(&row)? { chain.set_verification_pool(pool)?; } else if cache.has_gdn_qk_workspace() { chain.set_qk_workspace(cache.gdn_qk_workspace(binding, context, input.identity())?)?; @@ -235,12 +214,7 @@ fn step_chain<'ctx>( } }; let edge = owner.finish_row(row, history)?; - Ok(ChunkReady { - identity: input.identity(), - binding: binding.identity(), - output, - edge, - }) + Ok(ChunkReady { identity: input.identity(), binding: binding.identity(), output, edge }) } // Same row contract as `step_chain`; the twelve intermediate host readbacks and @@ -268,12 +242,7 @@ fn step_chain_queued<'ctx>( let aux = cache.gdn_aux(resident)?; owner.validate_row(&row, &binding.identity(), context)?; let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?; - let mut chain = chain::Chain::new( - context, - binding.identity(), - input.identity(), - failed.clone(), - )?; + let mut chain = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?; chain.validate(context, &binding.identity(), input.identity())?; chain.set_qk_workspace(cache.gdn_qk_workspace(binding, context, input.identity())?)?; let mut queue = owner.take_row_queue()?; @@ -293,9 +262,7 @@ fn step_chain_queued<'ctx>( input, super::super::q6_attention_columns::Role::GdnQkv, )?), - Some(projection) => { - Qkv::Host(chain.import_projected_qkv(projection, binding, cache, txn, layer, input)?) - } + Some(projection) => Qkv::Host(chain.import_projected_qkv(projection, binding, cache, txn, layer, input)?), None => Qkv::Host(project_chain_input( &mut chain, context, @@ -309,16 +276,34 @@ fn step_chain_queued<'ctx>( }; let history = chain.upload(Role::History, owner.history()?)?; let alpha = project_device_input( - &mut chain, context, binding, &weights, GdnMatrixRole::Alpha, - &input_lease, input.mixed(), cache, + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Alpha, + &input_lease, + input.mixed(), + cache, )?; let beta_raw = project_device_input( - &mut chain, context, binding, &weights, GdnMatrixRole::Beta, - &input_lease, input.mixed(), cache, + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Beta, + &input_lease, + input.mixed(), + cache, )?; let z = project_device_input( - &mut chain, context, binding, &weights, GdnMatrixRole::Z, - &input_lease, input.mixed(), cache, + &mut chain, + context, + binding, + &weights, + GdnMatrixRole::Z, + &input_lease, + input.mixed(), + cache, )?; let queued = { let (state, next_state) = owner.queue_operands(&row)?; @@ -369,10 +354,5 @@ fn step_chain_queued<'ctx>( } }; let edge = owner.finish_row(row, history)?; - Ok(ChunkReady { - identity: input.identity(), - binding: binding.identity(), - output, - edge, - }) + Ok(ChunkReady { identity: input.identity(), binding: binding.identity(), output, edge }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_four_borrow_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_four_borrow_gpu.rs index e4bcb142..9baee883 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_four_borrow_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_four_borrow_gpu.rs @@ -39,8 +39,7 @@ pub(super) fn observe_readout(values: &[f32]) -> Result<()> { } validate_values(values, VALUES)?; let mut copy = Vec::new(); - copy.try_reserve_exact(VALUES) - .map_err(|_| Error::InputAllocation)?; + copy.try_reserve_exact(VALUES).map_err(|_| Error::InputAllocation)?; copy.extend_from_slice(values); rows.push(copy.into_boxed_slice()); Ok(()) @@ -50,8 +49,7 @@ struct Observation; impl Observation { fn begin(old: bool) -> Result { let mut rows = Vec::new(); - rows.try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; READOUTS.with(|slot| -> Result<()> { if slot.borrow().is_some() { return Err(Error::IdentityMismatch); @@ -96,10 +94,7 @@ impl FourBorrowReport { /// Root calls only after all bound caches/session/Context have closed. pub(crate) fn assert_after_teardown(self) { assert_eq!(self.differences, 0); - assert_eq!( - self.exact_words, - 2 * 3 * (STATE_ELEMENTS + HISTORY_ELEMENTS + VALUES + 2560) - ); + assert_eq!(self.exact_words, 2 * 3 * (STATE_ELEMENTS + HISTORY_ELEMENTS + VALUES + 2560)); assert!( self.foreign_refused && self.cancelled @@ -119,10 +114,7 @@ fn same(a: &[f32], b: &[f32]) -> Result { } validate_values(a, a.len())?; validate_values(b, b.len())?; - Ok(a.iter() - .zip(b) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count()) + Ok(a.iter().zip(b).filter(|(a, b)| a.to_bits() != b.to_bits()).count()) } fn compare(a: &Arm, b: &Arm) -> Result<(usize, usize)> { if a.rows.len() != 3 || b.rows.len() != 3 || a.readouts.len() != 3 || b.readouts.len() != 3 { @@ -162,11 +154,7 @@ fn arm<'ctx>( } moe.reserve_mmq_transient(binding, context, FOUR_BORROW_BYTES)?; let vocab = Dimension::new(248320)?; - let ids = [ - TokenId::new(0, vocab)?, - TokenId::new(1, vocab)?, - TokenId::new(0, vocab)?, - ]; + let ids = [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?]; let mut foreign = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context)); let mut foreign_prior = None; let refused = foreign.transact_completion( @@ -186,14 +174,10 @@ fn arm<'ctx>( let mut chunk = QwenChunkTxn::begin(session, binding, &ids, None, 512 * 1024 * 1024)?; for index in 0..3 { let (token, position) = chunk.row_ids(index)?; - chunk.input(index, |txn| { - InputStage::consume_kar(binding, kar, token, position, txn) - })?; + chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?; } let mut reads = Vec::new(); - reads - .try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; for index in 0..3 { reads.push(chunk.read_attention_column(index, layer, |txn| { let read = GrStage::apply(binding, layer, txn, Some(dense))?; @@ -201,8 +185,7 @@ fn arm<'ctx>( })?); } let mut rows = Vec::new(); - rows.try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; let mut foreign_refused = false; for (index, read) in reads.iter().enumerate() { // The actual caller callback, after a genuine completed row0, owns @@ -210,51 +193,33 @@ fn arm<'ctx>( if cancel_at_one && index == 1 && cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let (row, _unpublished_proof) = - chunk.prepare_attention_layer_batch(index, layer, read, |txn, residual| { - let prior = txn.gdn_prior(layer)?; - if index == 0 { - foreign_refused = matches!( - GdnStage::step( - binding, - layer, - residual.ready(), - &foreign_prior, - txn, - Some(dense) - ), - Err(Error::IdentityMismatch) - ); - if !foreign_refused { - return Err(Error::IdentityMismatch); - } + let (row, _unpublished_proof) = chunk.prepare_attention_layer_batch(index, layer, read, |txn, residual| { + let prior = txn.gdn_prior(layer)?; + if index == 0 { + foreign_refused = matches!( + GdnStage::step(binding, layer, residual.ready(), &foreign_prior, txn, Some(dense)), + Err(Error::IdentityMismatch) + ); + if !foreign_refused { + return Err(Error::IdentityMismatch); } - let mut actual = - GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?; - actual.validate_origin(&binding.identity())?; - let pending = actual.take_pending()?; - let state = pending.mirror_next(&prior)?.clone(); - let mut output = Vec::new(); - output - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; - output.extend_from_slice(actual.output()); - txn.stage_gdn(&prior, pending)?; - Ok(Row { - state, - output: output.into_boxed_slice(), - }) - })?; + } + let mut actual = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?; + actual.validate_origin(&binding.identity())?; + let pending = actual.take_pending()?; + let state = pending.mirror_next(&prior)?.clone(); + let mut output = Vec::new(); + output.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; + output.extend_from_slice(actual.output()); + txn.stage_gdn(&prior, pending)?; + Ok(Row { state, output: output.into_boxed_slice() }) + })?; rows.push(row); } let readouts = observation.take()?; // No FFN/head/all48 barrier: genuine completed GDN candidates stay private. drop(chunk); - Ok(Arm { - rows, - readouts, - foreign_refused, - }) + Ok(Arm { rows, readouts, foreign_refused }) } impl QwenForward { /// Callable after ONE genuine binding admission/eager cache load. It does @@ -277,68 +242,27 @@ impl QwenForward { let allocated = context.allocated_bytes(); // Original five uploaded operands first, all three rows, independent // genuine priors and original kernels, before new four-owner dispatch. - let reference = arm( - binding, - context, - session, - kar, - moe, - dense, - true, - false, - || false, - )?; - let candidate = arm( - binding, - context, - session, - kar, - moe, - dense, - false, - false, - || false, - )?; + let reference = arm(binding, context, session, kar, moe, dense, true, false, || false)?; + let candidate = arm(binding, context, session, kar, moe, dense, false, false, || false)?; let (mut differences, mut words) = compare(&reference, &candidate)?; let original_unchanged = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); let callback_seen = Cell::new(false); let cancelled = matches!( - arm( - binding, - context, - session, - kar, - moe, - dense, - false, - true, - || { - callback_seen.set(true); - true - } - ), + arm(binding, context, session, kar, moe, dense, false, true, || { + callback_seen.set(true); + true + }), Err(Error::Unsupported(Stage::Executor)) ) && callback_seen.get(); let after_cancel = session.test_reset_replay_snapshot(binding)?; let cancelled_unchanged = initial.numeric_eq(&after_cancel); session.reset()?; let reset_recovered = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let recovery = arm( - binding, - context, - session, - kar, - moe, - dense, - false, - false, - || false, - )?; + let recovery = arm(binding, context, session, kar, moe, dense, false, false, || false)?; let compared = compare(&reference, &recovery)?; differences += compared.0; words += compared.1; - let foreign_refused = - reference.foreign_refused && candidate.foreign_refused && recovery.foreign_refused; + let foreign_refused = reference.foreign_refused && candidate.foreign_refused && recovery.foreign_refused; drop(reference); drop(candidate); drop(recovery); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_fused_t1_step.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_fused_t1_step.rs index baa1eaec..b072634f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_fused_t1_step.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_fused_t1_step.rs @@ -29,21 +29,14 @@ impl GdnStage { projection: Option<&mut super::super::q6_attention_columns::ProjectionRow<'_, '_>>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); txn.validate_binding(&binding.identity())?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer || input.identity().layer() != layer { return Err(Error::IdentityMismatch); } - let descriptor = binding - .ordered_layers() - .get(layer.get() as usize) - .ok_or(Error::InvalidLayer)?; + let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { return Err(Error::InvalidLayer); } @@ -53,9 +46,7 @@ impl GdnStage { validate_values(input.mixed(), 2560)?; let context = txn.cuda_context()?; preflight_budget(context.budget_bytes(), context.allocated_bytes())?; - step_cached_fused( - binding, layer, input, prior, context, cache, txn, projection, fused, - ) + step_cached_fused(binding, layer, input, prior, context, cache, txn, projection, fused) } } @@ -78,12 +69,7 @@ fn step_cached_fused<'ctx>( let aux = cache.gdn_aux(resident)?; let mut mirror = cache.gdn_mirror(binding, layer.get(), context)?; let input_lease = cache.gdn_input(binding, layer.get(), context, input.mixed())?; - let mut chain = chain::Chain::new( - context, - binding.identity(), - input.identity(), - failed.clone(), - )?; + let mut chain = chain::Chain::new(context, binding.identity(), input.identity(), failed.clone())?; chain.validate(context, &binding.identity(), input.identity())?; let mut mirror_next = None; let operation = (|| -> Result<(Box<[f32]>, Box<[f32]>)> { @@ -109,13 +95,7 @@ fn step_cached_fused<'ctx>( )? }; // The same device activation serves Z (a GEMV) and the fused alpha/beta kernel (`mixed`). - let mixed = input_lease.buffer( - &binding.identity(), - context, - layer.get(), - GdnMatrixRole::Z, - input.mixed(), - )?; + let mixed = input_lease.buffer(&binding.identity(), context, layer.get(), GdnMatrixRole::Z, input.mixed())?; let (z_matrix, z_kind) = cache.gdn_matrix(resident, GdnMatrixRole::Z)?; // Z stays on device; the closed program scans it before any consumer reads it. let z = chain.project_device(z_matrix, z_kind, mixed, Role::Z)?; @@ -141,9 +121,7 @@ fn step_cached_fused<'ctx>( })?; mirror_next = Some(next); let (matrix, kind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?; - let output = chain - .project_out_device(matrix, kind, &row.normalized)? - .into_values(); + let output = chain.project_out_device(matrix, kind, &row.normalized)?.into_values(); validate_values(&output, 2560)?; Ok((row.next_history.into_values(), output)) })(); @@ -162,15 +140,6 @@ fn step_cached_fused<'ctx>( return Err(primary); } }; - let pending = mirror.publish( - mirror_next.take().ok_or(Error::IdentityMismatch)?, - input.identity(), - history, - )?; - Ok(GdnReady { - identity: input.identity(), - binding: binding.identity(), - output, - pending: Some(pending), - }) + let pending = mirror.publish(mirror_next.take().ok_or(Error::IdentityMismatch)?, input.identity(), history)?; + Ok(GdnReady { identity: input.identity(), binding: binding.identity(), output, pending: Some(pending) }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch.rs index 72def0a3..f7a9b046 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch.rs @@ -1,7 +1,7 @@ //! One actor-owned activation slot; every layer lease copies its immutable source. use super::{ - BindingIdentity, Context, DeviceBuffer, Error, GdnMatrixRole, Result, driver_error, - preflight_budget, validate_values, + BindingIdentity, Context, DeviceBuffer, Error, GdnMatrixRole, Result, driver_error, preflight_budget, + validate_values, }; use std::{ cell::{Cell, RefMut}, @@ -32,10 +32,7 @@ impl<'ctx> GdnInputScratch<'ctx> { if failed.get() { return Err(Error::CudaExecution); } - let peak = context - .allocated_bytes() - .checked_add(INPUT_BYTES) - .ok_or(Error::Overflow)?; + let peak = context.allocated_bytes().checked_add(INPUT_BYTES).ok_or(Error::Overflow)?; preflight_budget(context.budget_bytes(), peak)?; let buffer = context.allocate(INPUT_BYTES).map_err(driver_error)?; Ok(Self { @@ -80,11 +77,7 @@ impl<'ctx> GdnInputScratch<'ctx> { { slot.uploads += 1; } - Ok(GdnInputLease { - slot, - source, - layer, - }) + Ok(GdnInputLease { slot, source, layer }) } pub(in crate::qwen_forward) fn close(self) -> Result<()> { let primary = self.failed.get().then_some(Error::CudaExecution); @@ -96,11 +89,7 @@ impl<'ctx> GdnInputScratch<'ctx> { } } impl<'ctx> GdnInputLease<'_, '_, 'ctx> { - pub(super) fn activation( - &self, - context: &Context<'_>, - columns: usize, - ) -> Result<&DeviceBuffer<'ctx>> { + pub(super) fn activation(&self, context: &Context<'_>, columns: usize) -> Result<&DeviceBuffer<'ctx>> { if self.slot.failed.get() { return Err(Error::CudaExecution); } @@ -130,10 +119,8 @@ impl<'ctx> GdnInputLease<'_, '_, 'ctx> { { return Err(Error::IdentityMismatch); } - if !matches!( - role, - GdnMatrixRole::Qkv | GdnMatrixRole::Alpha | GdnMatrixRole::Beta | GdnMatrixRole::Z - ) || self.slot.buffer.len() != INPUT_BYTES + if !matches!(role, GdnMatrixRole::Qkv | GdnMatrixRole::Alpha | GdnMatrixRole::Beta | GdnMatrixRole::Z) + || self.slot.buffer.len() != INPUT_BYTES { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs index 46442c2e..d1792f8d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_input_scratch_gpu.rs @@ -41,22 +41,14 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() let context = device.create_context(160 * 1024 * 1024).unwrap(); let binding = BindingIdentity::test_identity(); // Tag only, no artifact capability. let failed = Rc::new(Cell::new(false)); - let scratch = - RefCell::new(GdnInputScratch::new(binding.clone(), &context, failed.clone()).unwrap()); + let scratch = RefCell::new(GdnInputScratch::new(binding.clone(), &context, failed.clone()).unwrap()); assert_eq!(context.allocated_bytes(), INPUT_BYTES); for zero in [false, true] { let input: Vec = (0..2560) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 17) as f32 / 64. - 8. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 17) as f32 / 64. - 8. / 64. }) .collect(); let source_bits: Vec = input.iter().map(|v| v.to_bits()).collect(); - let lease = - GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 0, &input).unwrap(); + let lease = GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 0, &input).unwrap(); assert!(scratch.try_borrow_mut().is_err()); // Actual exclusive RefCell lease. for (role, rows, seed) in [ (GdnMatrixRole::Qkv, 10240, 0), @@ -68,16 +60,7 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() let matrix = bytes_upload(&context, &bytes); let fresh = upload(&context, &input).unwrap(); let mut output = allocate(&context, rows).unwrap(); - dispatch_projection( - &context, - &matrix, - &fresh, - &mut output, - GdnMatrixKind::Bf16, - 2560, - rows, - ) - .unwrap(); + dispatch_projection(&context, &matrix, &fresh, &mut output, GdnMatrixKind::Bf16, 2560, rows).unwrap(); let expected = download(&output, rows).unwrap(); output.release().unwrap(); fresh.release().unwrap(); @@ -85,16 +68,8 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() let admitted = lease.buffer(&binding, &context, 0, role, &input).unwrap(); let mut retained_input = vec![0; INPUT_BYTES]; admitted.copy_to(&mut retained_input).unwrap(); - assert_eq!( - retained_input, - input - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); - let actual = - project_retained(&context, &matrix, GdnMatrixKind::Bf16, 2560, rows, &lease) - .unwrap(); + assert_eq!(retained_input, input.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let actual = project_retained(&context, &matrix, GdnMatrixKind::Bf16, 2560, rows, &lease).unwrap(); exact(&actual, &expected); assert_eq!(context.allocated_bytes(), charged); let mut unchanged = vec![0; bytes.len()]; @@ -103,10 +78,7 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() matrix.release().unwrap(); println!("GDN_INPUT PAIR role={role:?} zero={zero} exact_words={rows}"); } - assert_eq!( - input.iter().map(|v| v.to_bits()).collect::>(), - source_bits - ); + assert_eq!(input.iter().map(|v| v.to_bits()).collect::>(), source_bits); drop(lease); assert_eq!(scratch.borrow().uploads, if zero { 2 } else { 1 }); assert_eq!(context.allocated_bytes(), INPUT_BYTES); @@ -120,14 +92,7 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() (&binding, &context, 48, Error::InvalidLayer), ] { assert_eq!( - GdnInputScratch::lease( - scratch.borrow_mut(), - candidate_binding, - candidate_context, - layer, - &input - ) - .err(), + GdnInputScratch::lease(scratch.borrow_mut(), candidate_binding, candidate_context, layer, &input).err(), Some(expected) ); } @@ -142,62 +107,18 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() Some(Error::InvalidDimension) ); assert_eq!(scratch.borrow().uploads, 2); - let lease = - GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 0, &input).unwrap(); + let lease = GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 0, &input).unwrap(); let copy = input.clone(); for (candidate_binding, candidate_context, layer, role, source, expected) in [ - ( - &rival, - &context, - 0, - GdnMatrixRole::Qkv, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &foreign, - 0, - GdnMatrixRole::Qkv, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 1, - GdnMatrixRole::Qkv, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 0, - GdnMatrixRole::Qkv, - copy.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 0, - GdnMatrixRole::Out, - input.as_slice(), - Error::InvalidDimension, - ), + (&rival, &context, 0, GdnMatrixRole::Qkv, input.as_slice(), Error::IdentityMismatch), + (&binding, &foreign, 0, GdnMatrixRole::Qkv, input.as_slice(), Error::IdentityMismatch), + (&binding, &context, 1, GdnMatrixRole::Qkv, input.as_slice(), Error::IdentityMismatch), + (&binding, &context, 0, GdnMatrixRole::Qkv, copy.as_slice(), Error::IdentityMismatch), + (&binding, &context, 0, GdnMatrixRole::Out, input.as_slice(), Error::InvalidDimension), ] { - assert_eq!( - lease - .buffer(candidate_binding, candidate_context, layer, role, source) - .err(), - Some(expected) - ); + assert_eq!(lease.buffer(candidate_binding, candidate_context, layer, role, source).err(), Some(expected)); } - assert_eq!( - lease.activation(&context, 6144).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(lease.activation(&context, 6144).err(), Some(Error::InvalidDimension)); // A completed late NaN is withheld and output freed, while the finite // original input slot remains valid. No simulated numerical provider. let mut bytes = matrix_bytes(48, 4); @@ -222,18 +143,10 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() matrix.release().unwrap(); drop(lease); // Abort releases exclusive ownership without releasing actor slot. assert_eq!(scratch.borrow().uploads, 3); - let lease = - GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 1, &input).unwrap(); - assert!( - lease - .buffer(&binding, &context, 1, GdnMatrixRole::Z, &input) - .is_ok() - ); + let lease = GdnInputScratch::lease(scratch.borrow_mut(), &binding, &context, 1, &input).unwrap(); + assert!(lease.buffer(&binding, &context, 1, GdnMatrixRole::Z, &input).is_ok()); lease.poison(); // Exercise explicit sticky policy, not an injected CUDA fault. - assert_eq!( - lease.activation(&context, 2560).err(), - Some(Error::CudaExecution) - ); + assert_eq!(lease.activation(&context, 2560).err(), Some(Error::CudaExecution)); drop(lease); assert_eq!(scratch.borrow().uploads, 4); assert_eq!( @@ -248,16 +161,9 @@ fn one_input_upload_matches_four_legacy_projections_and_preserves_lease_guards() context.close().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); - let small = device - .create_context(128 * 1024 * 1024 + INPUT_BYTES - 1) - .unwrap(); - assert_eq!( - GdnInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), - Some(Error::InputAllocation) - ); + let small = device.create_context(128 * 1024 * 1024 + INPUT_BYTES - 1).unwrap(); + assert_eq!(GdnInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation)); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); - println!( - "GDN_INPUT COMPLETE exact_words=32960 finite_leases=2 guard_refusals=17 uploads=4 allocated=0" - ); + println!("GDN_INPUT COMPLETE exact_words=32960 finite_leases=2 guard_refusals=17 uploads=4 allocated=0"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs index 2c879f2f..3ce215c0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch.rs @@ -14,9 +14,7 @@ use super::super::session::chunk::GdnChunkMicro; use super::chunk_device::GdnChunkDevice; use super::chunk_producer::ChunkReady; use super::*; -use leleka_cuda_driver::{ - GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnGemm, GdnNativeFormat, GdnPrefillBatch, -}; +use leleka_cuda_driver::{GDN_BATCH_EPSILON, GDN_BATCH_MAX_TOKENS, GdnGemm, GdnNativeFormat, GdnPrefillBatch}; const MIXED: usize = 2560; const ALPHA_BETA: usize = 96; @@ -86,10 +84,7 @@ mod tests { ] { assert_eq!(native_format(kind).unwrap(), format); } - assert!(matches!( - native_format(GdnMatrixKind::Bf16), - Err(Error::Unsupported(Stage::Gdn)) - )); + assert!(matches!(native_format(GdnMatrixKind::Bf16), Err(Error::Unsupported(Stage::Gdn)))); } #[test] @@ -101,8 +96,15 @@ mod tests { // + ab 24,576 + gate/beta 2 x 12,288 + histories 2 x 122,880 + y16 786,432 + bo 655,360. assert_eq!( high, - 655_360 + 2 * 327_680 + 2 * 2_621_440 + 2 * 1_572_864 + 24_576 + 2 * 12_288 - + 2 * 122_880 + 786_432 + 655_360 + 655_360 + + 2 * 327_680 + + 2 * 2_621_440 + + 2 * 1_572_864 + + 24_576 + + 2 * 12_288 + + 2 * 122_880 + + 786_432 + + 655_360 ); assert!(batch_device_bytes(GDN_BATCH_MAX_TOKENS, Bf16Profile::HighPlusLow).is_ok()); } @@ -128,11 +130,11 @@ mod impl_gdnbatchresources; #[allow(unused_imports)] use impl_gdnbatchresources::admit_batch_bytes; #[allow(unused_imports)] -use impl_gdnbatchresources::native_format; -#[allow(unused_imports)] pub(in crate::qwen_forward) use impl_gdnbatchresources::batch_device_bytes; #[allow(unused_imports)] use impl_gdnbatchresources::f32_bytes; +#[allow(unused_imports)] +use impl_gdnbatchresources::native_format; #[path = "gdn_prefill_batch/impl_buffers.rs"] mod impl_buffers; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_buffers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_buffers.rs index 59fe20a7..51057777 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_buffers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_buffers.rs @@ -5,20 +5,31 @@ use super::*; impl<'ctx> Buffers<'ctx> { pub(super) fn allocated_bytes(&self) -> usize { - [&self.mixed, &self.mixed_h, &self.mixed_bf, &self.qkv, &self.z, - &self.ab, &self.gate, &self.beta, &self.history, &self.next_history, - &self.h, &self.y, &self.y16, &self.bo] - .into_iter().map(DeviceBuffer::len).sum::() + [ + &self.mixed, + &self.mixed_h, + &self.mixed_bf, + &self.qkv, + &self.z, + &self.ab, + &self.gate, + &self.beta, + &self.history, + &self.next_history, + &self.h, + &self.y, + &self.y16, + &self.bo, + ] + .into_iter() + .map(DeviceBuffer::len) + .sum::() + self.mixed_bf_lo.as_ref().map_or(0, DeviceBuffer::len) } pub(super) fn new(context: &'ctx Context<'ctx>, tokens: usize, profile: Bf16Profile) -> Result { let images = tokens * MIXED * 2; let lo = profile == Bf16Profile::HighPlusLow; - let mut sizes = vec![ - tokens * MIXED * 4, - images, - images, - ]; + let mut sizes = vec![tokens * MIXED * 4, images, images]; if lo { sizes.push(images); } @@ -36,8 +47,7 @@ impl<'ctx> Buffers<'ctx> { tokens * MIXED * 4, ]); let mut pool = Vec::new(); - pool.try_reserve_exact(sizes.len()) - .map_err(|_| Error::InputAllocation)?; + pool.try_reserve_exact(sizes.len()).map_err(|_| Error::InputAllocation)?; for bytes in sizes { match context.allocate(bytes) { Ok(buffer) => pool.push(buffer), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnbatchresources.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnbatchresources.rs index c3dc5f5e..71ba6911 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnbatchresources.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnbatchresources.rs @@ -4,25 +4,41 @@ use super::*; impl<'ctx> GdnBatchResources<'ctx> { - pub(in crate::qwen_forward) fn new( + pub(in crate::qwen_forward) fn new(context: &'ctx Context<'ctx>, profile: Bf16Profile) -> Result { + Self::new_capacity(context, profile, EAGER_TOKENS, GDN_BATCH_MAX_TOKENS) + } + pub(in crate::qwen_forward) fn new_for_prompt( context: &'ctx Context<'ctx>, profile: Bf16Profile, + capacity: usize, ) -> Result { - Self::new_capacity(context,profile,EAGER_TOKENS,GDN_BATCH_MAX_TOKENS) + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidDimension); + } + Self::new_capacity(context, profile, capacity, capacity) } - pub(in crate::qwen_forward) fn new_for_prompt(context:&'ctx Context<'ctx>,profile:Bf16Profile,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} - Self::new_capacity(context,profile,capacity,capacity) - } - pub(super) fn new_capacity(context:&'ctx Context<'ctx>,profile:Bf16Profile,eager:usize,capacity:usize)->Result { + pub(super) fn new_capacity( + context: &'ctx Context<'ctx>, + profile: Bf16Profile, + eager: usize, + capacity: usize, + ) -> Result { // Charge the actual persistent bank, dequant scratch and fifteen // status words before the model's routed PrefixPlan is admitted. // Typed budget and physical free memory must both leave the reserve. - admit_batch_bytes(context, BATCH_SCRATCH_BYTES - .checked_add(15 * 4) - .and_then(|n| n.checked_add(batch_device_bytes(eager, profile).ok()?)) - .ok_or(Error::Overflow)?)?; - let batch = if capacity==GDN_BATCH_MAX_TOKENS {context.gdn_prefill_batch()}else{context.gdn_prefill_batch_for_prompt(capacity)}.map_err(driver_error)?; + admit_batch_bytes( + context, + BATCH_SCRATCH_BYTES + .checked_add(15 * 4) + .and_then(|n| n.checked_add(batch_device_bytes(eager, profile).ok()?)) + .ok_or(Error::Overflow)?, + )?; + let batch = if capacity == GDN_BATCH_MAX_TOKENS { + context.gdn_prefill_batch() + } else { + context.gdn_prefill_batch_for_prompt(capacity) + } + .map_err(driver_error)?; if batch.allocated_bytes() != 15 * 4 { let _ = batch.close(); return Err(Error::IdentityMismatch); @@ -39,18 +55,26 @@ impl<'ctx> GdnBatchResources<'ctx> { batch: Some(batch), scratch: Some(scratch), buffers: None, - capacity, buffer_tokens: eager, + capacity, + buffer_tokens: eager, profile, }; match Buffers::new(context, eager, profile) { Ok(buffers) => resources.buffers = Some(buffers), - Err(primary) => { let _ = resources.close_inner(); return Err(primary); } + Err(primary) => { + let _ = resources.close_inner(); + return Err(primary); + } } Ok(resources) } - pub(in crate::qwen_forward) fn prompt_device_bytes(capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} - batch_device_bytes(capacity,Bf16Profile::HighOnly)?.checked_add(BATCH_SCRATCH_BYTES+60).ok_or(Error::Overflow) + pub(in crate::qwen_forward) fn prompt_device_bytes(capacity: usize) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidDimension); + } + batch_device_bytes(capacity, Bf16Profile::HighOnly)? + .checked_add(BATCH_SCRATCH_BYTES + 60) + .ok_or(Error::Overflow) } pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { self.batch.as_ref().map_or(0, GdnPrefillBatch::allocated_bytes) @@ -66,7 +90,9 @@ impl<'ctx> GdnBatchResources<'ctx> { // owners; never shorten a DeviceBuffer to invent an active extent. return admit_batch_bytes(self.context, 0); } - if let Some(buffers) = self.buffers.take() { buffers.release()?; } + if let Some(buffers) = self.buffers.take() { + buffers.release()?; + } admit_batch_bytes(self.context, batch_device_bytes(tokens, self.profile)?)?; self.buffers = Some(Buffers::new(self.context, tokens, self.profile)?); self.buffer_tokens = tokens; @@ -79,7 +105,9 @@ impl<'ctx> GdnBatchResources<'ctx> { let mut failure = None; if let Some(buffers) = self.buffers.take() && let Err(error) = buffers.release() - { failure.get_or_insert(error); } + { + failure.get_or_insert(error); + } if let Some(scratch) = self.scratch.take() && let Err(error) = scratch.release() { @@ -96,10 +124,11 @@ impl<'ctx> GdnBatchResources<'ctx> { pub(super) fn admit_batch_bytes(context: &Context<'_>, additional: usize) -> Result<()> { let required = additional.checked_add(BATCH_RESERVE).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) + if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) || context.memory_info().map_err(driver_error)?.0 < required - { return Err(Error::InputAllocation); } + { + return Err(Error::InputAllocation); + } Ok(()) } impl Drop for GdnBatchResources<'_> { @@ -128,21 +157,21 @@ pub(in crate::qwen_forward) fn batch_device_bytes(tokens: usize, profile: Bf16Pr let images = tokens * MIXED * 2; let lo = if profile == Bf16Profile::HighPlusLow { images } else { 0 }; [ - tokens * MIXED * 4, // mixed (f32 upload) - images, // mixed_h - images, // mixed_bf - lo, // mixed_bf_lo - tokens * CHANNELS * 4, // qkv - tokens * VALUES * 4, // z - tokens * ALPHA_BETA * 4, // ab - tokens * VALUE_HEADS * 4, // gate - tokens * VALUE_HEADS * 4, // beta - HISTORY_ELEMENTS * 4, // history - HISTORY_ELEMENTS * 4, // next_history - tokens * CHANNELS * 4, // h - tokens * VALUES * 4, // y - tokens * VALUES * 2, // y16 - tokens * MIXED * 4, // bo + tokens * MIXED * 4, // mixed (f32 upload) + images, // mixed_h + images, // mixed_bf + lo, // mixed_bf_lo + tokens * CHANNELS * 4, // qkv + tokens * VALUES * 4, // z + tokens * ALPHA_BETA * 4, // ab + tokens * VALUE_HEADS * 4, // gate + tokens * VALUE_HEADS * 4, // beta + HISTORY_ELEMENTS * 4, // history + HISTORY_ELEMENTS * 4, // next_history + tokens * CHANNELS * 4, // h + tokens * VALUES * 4, // y + tokens * VALUES * 2, // y16 + tokens * MIXED * 4, // bo ] .into_iter() .try_fold(0usize, |sum, bytes| sum.checked_add(bytes)) @@ -151,9 +180,7 @@ pub(in crate::qwen_forward) fn batch_device_bytes(tokens: usize, profile: Bf16Pr pub(super) fn f32_bytes(values: &[f32]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs index 83d32795..076e3756 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch/impl_gdnstage.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl GdnStage { /// The batched Strata-prefill GDN step over one genuine current causal /// micro-window (`prepare_attention_micro_gdn`'s `execute` callback). Rows, @@ -27,34 +26,24 @@ impl GdnStage { gemm: &dyn GdnGemm, ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gdn, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gdn); let tokens = micro.len(); if tokens == 0 || tokens > resources.capacity || owner.is_verification() { return Err(Error::IdentityMismatch); } - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer { return Err(Error::IdentityMismatch); } - let descriptor = binding - .ordered_layers() - .get(layer.get() as usize) - .ok_or(Error::InvalidLayer)?; + let descriptor = binding.ordered_layers().get(layer.get() as usize).ok_or(Error::InvalidLayer)?; if descriptor.index() != layer.get() || descriptor.kind() != BoundLayerKind::Gdn { return Err(Error::InvalidLayer); } let mut host = Vec::new(); - host.try_reserve_exact(tokens * MIXED) - .map_err(|_| Error::InputAllocation)?; + host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; let mut identities = Vec::new(); - identities - .try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; + identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; for local in 0..tokens { let row = micro.row(local)?; let input = micro.input(local)?; @@ -82,11 +71,7 @@ impl GdnStage { if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 { return Err(Error::Unsupported(Stage::Gdn)); } - let formats = [ - native_format(qkv_kind)?, - native_format(z_kind)?, - native_format(out_kind)?, - ]; + let formats = [native_format(qkv_kind)?, native_format(z_kind)?, native_format(out_kind)?]; for (role, columns, rows_) in [ (GdnMatrixRole::Qkv, MIXED, CHANNELS), (GdnMatrixRole::Z, MIXED, VALUES), @@ -99,7 +84,9 @@ impl GdnStage { } } if let Err(primary) = resources.prepare_buffers(context, tokens) { - if primary == Error::CudaExecution { failed.set(true); } + if primary == Error::CudaExecution { + failed.set(true); + } owner.refuse(primary); return Err(primary); } @@ -109,24 +96,13 @@ impl GdnStage { let operation = (|| -> Result<(Box<[f32]>, Box<[f32]>)> { let GdnBatchResources { batch, scratch, buffers, .. } = &mut *resources; let buffers = buffers.as_mut().ok_or(Error::IdentityMismatch)?; - buffers - .mixed - .copy_from(&mixed_bytes) - .map_err(driver_error)?; - buffers - .history - .copy_from(&history_bytes) - .map_err(driver_error)?; + buffers.mixed.copy_from(&mixed_bytes).map_err(driver_error)?; + buffers.history.copy_from(&history_bytes).map_err(driver_error)?; let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; let mut prefix = batch.begin(tokens, gemm).map_err(driver_error)?; let program = (|| -> std::result::Result<(), leleka_cuda_driver::Error> { - prefix.pack_mixed( - &buffers.mixed, - &buffers.mixed_h, - &buffers.mixed_bf, - buffers.mixed_bf_lo.as_ref(), - )?; + prefix.pack_mixed(&buffers.mixed, &buffers.mixed_h, &buffers.mixed_bf, buffers.mixed_bf_lo.as_ref())?; prefix.project_qkv(formats[0], qkv_w, scratch, &buffers.qkv)?; prefix.project_z(formats[1], z_w, scratch, &buffers.z)?; prefix.project_alpha_beta(alpha_w, beta_w, &buffers.ab)?; @@ -145,9 +121,7 @@ impl GdnStage { // so an earlier non-finite stage outranks a later admission error. let _ = program; let completion = prefix.finish().map_err(driver_error)?; - let next_history = completion - .into_next_history() - .map_err(|_| Error::NonFinite)?; + let next_history = completion.into_next_history().map_err(|_| Error::NonFinite)?; let output = download(&buffers.bo, tokens * MIXED)?; Ok((next_history, output)) })(); @@ -166,25 +140,12 @@ impl GdnStage { }; let edges = owner.finish_micro(micro, &binding.identity(), history)?; let mut ready = Vec::new(); - ready - .try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; - for ((edge, identity), row_output) in edges - .into_iter() - .zip(identities) - .zip(output.chunks_exact(MIXED)) - { + ready.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; + for ((edge, identity), row_output) in edges.into_iter().zip(identities).zip(output.chunks_exact(MIXED)) { let mut values = Vec::new(); - values - .try_reserve_exact(MIXED) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(MIXED).map_err(|_| Error::InputAllocation)?; values.extend_from_slice(row_output); - ready.push(ChunkReady::from_batch( - identity, - binding.identity(), - values.into_boxed_slice(), - edge, - )); + ready.push(ChunkReady::from_batch(identity, binding.identity(), values.into_boxed_slice(), edge)); } Ok(ready) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch_gpu.rs index 7a02cc3b..356249ef 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prefill_batch_gpu.rs @@ -9,18 +9,16 @@ use leleka_cuda_driver::Driver; #[test] #[ignore = "Root-only GPU lifecycle proof; never run by the source owner"] fn batch_resources_charge_exactly_scratch_and_status_and_release_everything() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GDN_BATCH_RESOURCES").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_BATCH_RESOURCES").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(512 * 1024 * 1024).unwrap(); { - let resources = - GdnBatchResources::new(&context, Bf16Profile::HighOnly).unwrap(); - assert_eq!(resources.allocated_bytes(), BATCH_SCRATCH_BYTES + 15 * 4 - + batch_device_bytes(EAGER_TOKENS, Bf16Profile::HighOnly).unwrap()); + let resources = GdnBatchResources::new(&context, Bf16Profile::HighOnly).unwrap(); + assert_eq!( + resources.allocated_bytes(), + BATCH_SCRATCH_BYTES + 15 * 4 + batch_device_bytes(EAGER_TOKENS, Bf16Profile::HighOnly).unwrap() + ); assert_eq!(context.allocated_bytes(), resources.allocated_bytes()); resources.close().unwrap(); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs index bae2aef5..393b3643 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_prompt_device.rs @@ -1,56 +1,126 @@ //! Genuine prompt chunk end-state over the affine physical GR read. No host //! ResidualReady or ChunkReady array is invented from completed device bytes. -use super::*; -use super::chunk_device::{GdnChunkDevice,ChunkEdge}; use super::super::session::chunk::GdnChunkRow; -use leleka_cuda_driver::{OriginalDeviceGrRead,OriginalDeviceBlock,OriginalGdnPromptDevice,OriginalGdnPromptWeights,NativeBatchWorkspace,GdnNativeFormat,GDN_BATCH_EPSILON}; -fn device_error(e:DriverError)->Error{match e{DriverError::NonFiniteMmqOutput(_)=>Error::NonFinite,other=>driver_error(other)}} -fn format(kind:GdnMatrixKind)->Result{Ok(match kind{ - GdnMatrixKind::Q8_0=>GdnNativeFormat::Q8_0,GdnMatrixKind::Q4K=>GdnNativeFormat::Q4K, - GdnMatrixKind::Q5K=>GdnNativeFormat::Q5K,GdnMatrixKind::Q6K=>GdnNativeFormat::Q6K, - GdnMatrixKind::Iq4Nl=>GdnNativeFormat::Iq4Nl,GdnMatrixKind::Iq4Xs=>GdnNativeFormat::Iq4Xs, - GdnMatrixKind::Bf16=>return Err(Error::Unsupported(Stage::Gdn)), -})} -impl GdnStage{ +use super::chunk_device::{ChunkEdge, GdnChunkDevice}; +use super::*; +use leleka_cuda_driver::{ + GDN_BATCH_EPSILON, GdnNativeFormat, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, + OriginalGdnPromptDevice, OriginalGdnPromptWeights, +}; +fn device_error(e: DriverError) -> Error { + match e { + DriverError::NonFiniteMmqOutput(_) => Error::NonFinite, + other => driver_error(other), + } +} +fn format(kind: GdnMatrixKind) -> Result { + Ok(match kind { + GdnMatrixKind::Q8_0 => GdnNativeFormat::Q8_0, + GdnMatrixKind::Q4K => GdnNativeFormat::Q4K, + GdnMatrixKind::Q5K => GdnNativeFormat::Q5K, + GdnMatrixKind::Q6K => GdnNativeFormat::Q6K, + GdnMatrixKind::Iq4Nl => GdnNativeFormat::Iq4Nl, + GdnMatrixKind::Iq4Xs => GdnNativeFormat::Iq4Xs, + GdnMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::Gdn)), + }) +} +impl GdnStage { /// Root first authenticates every actual PromptDeviceRead transaction/role /// and current chronological chunk phase. The genuine chunk rows below /// remain bound to the untouched chunk start and current owner cursor. /// Returned edges carry only true completed end-state causality, not /// fabricated intermediate recurrent state or host readout arrays. #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn produce_prompt_device<'arena,'loan,'ctx>( - binding:&ModelBinding,layer:LayerId,cache:&DenseWeightCache<'ctx>,current:&Context<'_>, - owner:&mut GdnChunkDevice<'ctx>,rows:Vec,read:OriginalDeviceGrRead<'arena,'loan,'ctx>, - producer:&mut OriginalGdnPromptDevice<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>, - )->Result<(OriginalDeviceBlock<'arena,'loan,'ctx>,Vec)>{ - let context=cache.retained_context(binding,current)?;cache.validate(binding)?; - if owner.is_verification()||rows.is_empty()||rows.len()!=read.rows()||!read.context_matches(context){return Err(Error::IdentityMismatch)} - let expected=LayerId::new(u64::from(layer.get()),Dimension::new(u64::from(binding.layer_count()))?)?; - if layer!=expected||binding.ordered_layers().get(layer.get()as usize).is_none_or(|d|d.index()!=layer.get()||d.kind()!=BoundLayerKind::Gdn){return Err(Error::InvalidLayer)} - for row in &rows{if row.identity().layer()!=layer{return Err(Error::IdentityMismatch)}} - let failed=cache.transport_failure_flag(binding,context)?; - let resident=cache.gdn(binding,layer.get())?;let weights=&resident.weights; - if weights.epsilon().to_bits()!=GDN_BATCH_EPSILON.to_bits(){return Err(Error::Unsupported(Stage::Gdn))} - for(role,n,k)in[(GdnMatrixRole::Qkv,10240,2560),(GdnMatrixRole::Z,6144,2560),(GdnMatrixRole::Out,2560,6144),(GdnMatrixRole::Alpha,48,2560),(GdnMatrixRole::Beta,48,2560)]{ - if weights.shape(role)!=(k,n){return Err(Error::InvalidDimension)} + pub(in crate::qwen_forward) fn produce_prompt_device<'arena, 'loan, 'ctx>( + binding: &ModelBinding, + layer: LayerId, + cache: &DenseWeightCache<'ctx>, + current: &Context<'_>, + owner: &mut GdnChunkDevice<'ctx>, + rows: Vec, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + producer: &mut OriginalGdnPromptDevice<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, Vec)> { + let context = cache.retained_context(binding, current)?; + cache.validate(binding)?; + if owner.is_verification() || rows.is_empty() || rows.len() != read.rows() || !read.context_matches(context) { + return Err(Error::IdentityMismatch); } - let(qkv,qkind)=cache.gdn_matrix(resident,GdnMatrixRole::Qkv)?; - let(z,zkind)=cache.gdn_matrix(resident,GdnMatrixRole::Z)?; - let(out,okind)=cache.gdn_matrix(resident,GdnMatrixRole::Out)?; - let(alpha,ak)=cache.gdn_matrix(resident,GdnMatrixRole::Alpha)?; - let(beta,bk)=cache.gdn_matrix(resident,GdnMatrixRole::Beta)?; - if ak!=GdnMatrixKind::Bf16||bk!=GdnMatrixKind::Bf16{return Err(Error::Unsupported(Stage::Gdn))} - let aux=cache.gdn_aux(resident)?; - let(state,next)=owner.batch_operands(&rows)?; - let operation=producer.produce(read,workspace,OriginalGdnPromptWeights{matrices:[qkv,z,out,alpha,beta],formats:[format(qkind)?,format(zkind)?,format(okind)?],aux},state,next,owner.history()?).map_err(device_error); - if producer.is_failed(){failed.set(true)} - let(block,history)=match operation{Ok(r)=>r,Err(e)=>{owner.refuse(e);return Err(e)}}; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; + if layer != expected + || binding + .ordered_layers() + .get(layer.get() as usize) + .is_none_or(|d| d.index() != layer.get() || d.kind() != BoundLayerKind::Gdn) + { + return Err(Error::InvalidLayer); + } + for row in &rows { + if row.identity().layer() != layer { + return Err(Error::IdentityMismatch); + } + } + let failed = cache.transport_failure_flag(binding, context)?; + let resident = cache.gdn(binding, layer.get())?; + let weights = &resident.weights; + if weights.epsilon().to_bits() != GDN_BATCH_EPSILON.to_bits() { + return Err(Error::Unsupported(Stage::Gdn)); + } + for (role, n, k) in [ + (GdnMatrixRole::Qkv, 10240, 2560), + (GdnMatrixRole::Z, 6144, 2560), + (GdnMatrixRole::Out, 2560, 6144), + (GdnMatrixRole::Alpha, 48, 2560), + (GdnMatrixRole::Beta, 48, 2560), + ] { + if weights.shape(role) != (k, n) { + return Err(Error::InvalidDimension); + } + } + let (qkv, qkind) = cache.gdn_matrix(resident, GdnMatrixRole::Qkv)?; + let (z, zkind) = cache.gdn_matrix(resident, GdnMatrixRole::Z)?; + let (out, okind) = cache.gdn_matrix(resident, GdnMatrixRole::Out)?; + let (alpha, ak) = cache.gdn_matrix(resident, GdnMatrixRole::Alpha)?; + let (beta, bk) = cache.gdn_matrix(resident, GdnMatrixRole::Beta)?; + if ak != GdnMatrixKind::Bf16 || bk != GdnMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::Gdn)); + } + let aux = cache.gdn_aux(resident)?; + let (state, next) = owner.batch_operands(&rows)?; + let operation = producer + .produce( + read, + workspace, + OriginalGdnPromptWeights { + matrices: [qkv, z, out, alpha, beta], + formats: [format(qkind)?, format(zkind)?, format(okind)?], + aux, + }, + state, + next, + owner.history()?, + ) + .map_err(device_error); + if producer.is_failed() { + failed.set(true) + } + let (block, history) = match operation { + Ok(r) => r, + Err(e) => { + owner.refuse(e); + return Err(e); + } + }; // No cursor/state/capability publication until complete source/cache // health revalidation. Root still closes its real source fence and // current chunk/cancel proof before consuming these private products. - if let Err(e)=cache.validate(binding){owner.refuse(e);return Err(e)} - cache.retained_context(binding,current)?; - let edges=owner.finish_batch(rows,history)?; - Ok((block,edges)) + if let Err(e) = cache.validate(binding) { + owner.refuse(e); + return Err(e); + } + cache.retained_context(binding, current)?; + let edges = owner.finish_batch(rows, history)?; + Ok((block, edges)) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs index b8f1f4e5..98019d33 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_row_queue_gpu.rs @@ -3,9 +3,7 @@ //! original projections) FIRST. Synthetic Context and tag identity only: this //! is not a Binding, Session, row or model certificate. #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -use super::super::{ - STATE_ELEMENTS, convolve, gates, normalize_qk, out_norm, recur, release, upload, -}; +use super::super::{STATE_ELEMENTS, convolve, gates, normalize_qk, out_norm, recur, release, upload}; use super::*; use crate::qwen_forward::contract::{Dimension, LayerId, Position, TokenId}; use leleka_cuda_driver::{Bf16ProjectionShape, Driver}; @@ -32,24 +30,10 @@ fn upload_bytes<'ctx>(ctx: &'ctx Context<'ctx>, bytes: &[u8]) -> DeviceBuffer<'c b.copy_from(bytes).unwrap(); b } -fn original_projection( - ctx: &Context<'_>, - weights: &DeviceBuffer<'_>, - input: &[f32], - rows: usize, -) -> Box<[f32]> { +fn original_projection(ctx: &Context<'_>, weights: &DeviceBuffer<'_>, input: &[f32], rows: usize) -> Box<[f32]> { let x = upload(ctx, input).unwrap(); let mut y = allocate(ctx, rows).unwrap(); - ctx.bf16_f32( - weights, - &x, - &mut y, - Bf16ProjectionShape { - rows, - columns: input.len(), - }, - ) - .unwrap(); + ctx.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns: input.len() }).unwrap(); let result = download(&y, rows).unwrap(); release([x, y]).unwrap(); result @@ -62,9 +46,7 @@ fn identity(layer: u64, position: u64) -> TokenLayer { ) } fn pattern(count: usize, salt: usize, modulus: usize, scale: f32, offset: f32) -> Vec { - (0..count) - .map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset) - .collect() + (0..count).map(|i| ((i * 7 + salt * 13) % modulus) as f32 * scale - offset).collect() } struct Weights<'ctx> { @@ -82,10 +64,7 @@ struct Weights<'ctx> { impl Weights<'_> { fn release(self) { - for buffer in [ - self.qkv, self.alpha, self.beta, self.z, self.out, self.conv, self.dt, self.a, - self.gamma, - ] { + for buffer in [self.qkv, self.alpha, self.beta, self.z, self.out, self.conv, self.dt, self.a, self.gamma] { buffer.release().unwrap(); } } @@ -102,9 +81,7 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { let dt_host = [-2.; 48]; let a_host = [1.; 48]; let gamma_host = [1.; 128]; - let conv_host: Vec = (0..4 * CHANNELS) - .map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]) - .collect(); + let conv_host: Vec = (0..4 * CHANNELS).map(|i| [0.25, 0.5, -0.25, 0.125][i % 4]).collect(); let weights = Weights { qkv: upload_bytes(&ctx, &matrix(CHANNELS, 2560, 0)), alpha: upload_bytes(&ctx, &matrix(48, 2560, 1)), @@ -125,13 +102,9 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { let mut refusals = 0usize; // Clean rows, then refusal rows, all on ONE queue and ONE QK slot. - for (salt, bad_conv, bad_state) in [ - (0usize, false, false), - (1, false, false), - (2, true, false), - (3, false, true), - (4, false, false), - ] { + for (salt, bad_conv, bad_state) in + [(0usize, false, false), (1, false, false), (2, true, false), (3, false, true), (4, false, false)] + { let input = pattern(2560, salt, 17, 1. / 128., 0.0625); let history = pattern(HISTORY_ELEMENTS, salt, 13, 1. / 256., 0.0234); let state_values = pattern(STATE_ELEMENTS, salt, 19, 1. / 512., 0.0175); @@ -143,10 +116,7 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { } state }; - let state = upload_bytes( - &ctx, - &state_host.iter().flat_map(|v| v.to_le_bytes()).collect::>(), - ); + let state = upload_bytes(&ctx, &state_host.iter().flat_map(|v| v.to_le_bytes()).collect::>()); let next_state = allocate(&ctx, STATE_ELEMENTS).unwrap(); // Poisoned convolution weights stay a private buffer for this row. let bad = bad_conv.then(|| { @@ -165,16 +135,9 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { let conv = convolve(&ctx, &history, &qkv, &weights.conv_host, None).unwrap(); let qk = normalize_qk(&ctx, &conv.1, 1e-6).unwrap(); let gate_beta = gates(&ctx, &alpha, &beta_raw, &dt_host, &a_host, None).unwrap(); - let step = recur( - &ctx, - &state_values, - &qk[..2048], - &qk[2048..4096], - &conv.1[4096..], - &gate_beta.0, - &gate_beta.1, - ) - .unwrap(); + let step = + recur(&ctx, &state_values, &qk[..2048], &qk[2048..4096], &conv.1[4096..], &gate_beta.0, &gate_beta.1) + .unwrap(); let readout = step.1.clone(); let normalized = out_norm(&ctx, &readout, &z, &gamma_host, 1e-6, None).unwrap(); let out = original_projection(&ctx, &weights.out, &normalized, 2560); @@ -183,28 +146,15 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { let mut chain = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); chain.set_qk_workspace(scratch.clone()).unwrap(); - let qkv = chain - .project(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv) - .unwrap(); + let qkv = chain.project(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv).unwrap(); let history_product = chain.upload(Role::History, &history).unwrap(); - let alpha = chain - .project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha) - .unwrap(); - let beta_raw = chain - .project_device(&weights.beta, GdnMatrixKind::Bf16, &source, Role::BetaRaw) - .unwrap(); - let z = chain - .project_device(&weights.z, GdnMatrixKind::Bf16, &source, Role::Z) - .unwrap(); + let alpha = chain.project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha).unwrap(); + let beta_raw = chain.project_device(&weights.beta, GdnMatrixKind::Bf16, &source, Role::BetaRaw).unwrap(); + let z = chain.project_device(&weights.z, GdnMatrixKind::Bf16, &source, Role::Z).unwrap(); // The three device-only products refuse a wrong role and a roleless use. + assert_eq!(chain.operand_buffer(&alpha, Role::Z).err(), Some(Error::IdentityMismatch)); assert_eq!( - chain.operand_buffer(&alpha, Role::Z).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - chain - .project_device(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv) - .err(), + chain.project_device(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv).err(), Some(Error::IdentityMismatch) ); let outcome = chain.run_row_queue( @@ -227,24 +177,16 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { match (outcome, expected) { (Ok(row), Some((history_next, state_next, normalized, out))) => { exact(row.next_history.values(), &history_next); - let device_normalized = download( - chain.device_buffer(&row.normalized, Role::Normalized).unwrap(), - VALUES, - ) - .unwrap(); + let device_normalized = + download(chain.device_buffer(&row.normalized, Role::Normalized).unwrap(), VALUES).unwrap(); exact(&device_normalized, &normalized); exact(&download(&next_state, STATE_ELEMENTS).unwrap(), &state_next); - let actual_out = chain - .project_out_device(&weights.out, GdnMatrixKind::Bf16, &row.normalized) - .unwrap(); + let actual_out = chain.project_out_device(&weights.out, GdnMatrixKind::Bf16, &row.normalized).unwrap(); exact(actual_out.values(), &out); compared_words += HISTORY_ELEMENTS + VALUES + STATE_ELEMENTS + 2560; // A mandatory drain invalidates every old capability. chain.drain().unwrap(); - assert_eq!( - chain.device_buffer(&row.normalized, Role::Normalized).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(chain.device_buffer(&row.normalized, Role::Normalized).err(), Some(Error::IdentityMismatch)); } (Err(error), None) => { // Completed numerical refusal: exactly the scalar chain's @@ -257,34 +199,19 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { } // A product minted by ANOTHER chain is never accepted by this one. if salt == 0 { - let mut other = - Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); - let foreign = other - .project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha) - .unwrap(); - assert_eq!( - chain.operand_buffer(&foreign, Role::Alpha).err(), - Some(Error::IdentityMismatch) - ); + let mut other = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); + let foreign = other.project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha).unwrap(); + assert_eq!(chain.operand_buffer(&foreign, Role::Alpha).err(), Some(Error::IdentityMismatch)); other.finish().unwrap(); } // Without the retained QK slot a chain cannot run the queue. if salt == 1 { - let mut bare = - Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); + let mut bare = Chain::new(&ctx, binding.clone(), identity(0, 0), failed.clone()).unwrap(); let bare_history = bare.upload(Role::History, &history).unwrap(); - let bare_qkv = bare - .project(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv) - .unwrap(); - let bare_alpha = bare - .project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha) - .unwrap(); - let bare_beta = bare - .project_device(&weights.beta, GdnMatrixKind::Bf16, &source, Role::BetaRaw) - .unwrap(); - let bare_z = bare - .project_device(&weights.z, GdnMatrixKind::Bf16, &source, Role::Z) - .unwrap(); + let bare_qkv = bare.project(&weights.qkv, GdnMatrixKind::Bf16, &source, Role::Qkv).unwrap(); + let bare_alpha = bare.project_device(&weights.alpha, GdnMatrixKind::Bf16, &source, Role::Alpha).unwrap(); + let bare_beta = bare.project_device(&weights.beta, GdnMatrixKind::Bf16, &source, Role::BetaRaw).unwrap(); + let bare_z = bare.project_device(&weights.z, GdnMatrixKind::Bf16, &source, Role::Z).unwrap(); let refused = bare .run_row_queue( &mut queue, @@ -319,9 +246,7 @@ fn queued_gdn_chain_matches_scalar_oracles_refuses_and_cleans_up() { queue.close().unwrap(); QkScratch::close(scratch).unwrap(); let _ = resident_charge; - println!( - "GDN_ROW_QUEUE_CHAIN compared_words={compared_words} refusals={refusals} allocated_after_rows=resident" - ); + println!("GDN_ROW_QUEUE_CHAIN compared_words={compared_words} refusals={refusals} allocated_after_rows=resident"); // Fixed weights and the QK workspace slot are released last. weights.release(); ctx.synchronize().unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state.rs index be735d06..2a9f289d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state.rs @@ -48,34 +48,16 @@ impl GdnPrior { && self.next_position() == other.next_position() && self.0.values.len() == other.0.values.len() && self.0.history.len() == other.0.history.len() - && self - .0 - .values - .iter() - .zip(other.0.values.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) - && self - .0 - .history - .iter() - .zip(other.0.history.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) + && self.0.values.iter().zip(other.0.values.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) + && self.0.history.iter().zip(other.0.history.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn test_reset_replay_payload_bytes(&self) -> Option { - self.0 - .values - .len() - .checked_add(self.0.history.len())? - .checked_mul(4) + self.0.values.len().checked_add(self.0.history.len())?.checked_mul(4) } - pub(in crate::qwen_forward) fn zero( - binding: BindingIdentity, - owner: &GdnOwner, - layer: LayerId, - ) -> Result { + pub(in crate::qwen_forward) fn zero(binding: BindingIdentity, owner: &GdnOwner, layer: LayerId) -> Result { Ok(Self(Rc::new(State { binding, owner: owner.clone(), @@ -120,13 +102,22 @@ impl GdnPrior { }))) } pub(super) fn from_verified_prefix( - prior: &Self, seal: super::verification::ReplaySeal, values: Box<[f32]>, history: Box<[f32]>, + prior: &Self, + seal: super::verification::ReplaySeal, + values: Box<[f32]>, + history: Box<[f32]>, ) -> Result { let next_position = seal.validate_prior(prior)?; validate_values(&values, STATE_ELEMENTS)?; validate_values(&history, HISTORY_ELEMENTS)?; - Ok(Self(Rc::new(State { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), - layer: prior.layer(), next_position, values, history }))) + Ok(Self(Rc::new(State { + binding: prior.0.binding.clone(), + owner: prior.0.owner.clone(), + layer: prior.layer(), + next_position, + values, + history, + }))) } /// The recurrent state after a verifier accepted-prefix commit. The verifier journals the window and /// the commit graph replays exactly the accepted rows into its canonical state; `values`/`history` are @@ -143,10 +134,7 @@ impl GdnPrior { } validate_values(&values, STATE_ELEMENTS)?; validate_values(&history, HISTORY_ELEMENTS)?; - let next_position = prior - .next_position() - .checked_add(rows as u64) - .ok_or(Error::Overflow)?; + let next_position = prior.next_position().checked_add(rows as u64).ok_or(Error::Overflow)?; Ok(Self(Rc::new(State { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), @@ -182,21 +170,13 @@ impl GdnPending { self.validate(prior, self.identity)?; Ok(&self.next) } - pub(super) fn new( - prior: &GdnPrior, - identity: TokenLayer, - values: Box<[f32]>, - history: Box<[f32]>, - ) -> Result { + pub(super) fn new(prior: &GdnPrior, identity: TokenLayer, values: Box<[f32]>, history: Box<[f32]>) -> Result { if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() { return Err(Error::IdentityMismatch); } validate_values(&values, STATE_ELEMENTS)?; validate_values(&history, HISTORY_ELEMENTS)?; - let next_position = prior - .next_position() - .checked_add(1) - .ok_or(Error::Overflow)?; + let next_position = prior.next_position().checked_add(1).ok_or(Error::Overflow)?; let next = GdnPrior(Rc::new(State { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), @@ -205,30 +185,14 @@ impl GdnPending { values, history, })); - Ok(Self { - prior: prior.clone(), - next, - identity, - }) + Ok(Self { prior: prior.clone(), next, identity }) } #[cfg(test)] - pub(in crate::qwen_forward) fn test_next( - prior: &GdnPrior, - identity: &TokenLayer, - ) -> Result { + pub(in crate::qwen_forward) fn test_next(prior: &GdnPrior, identity: &TokenLayer) -> Result { // Explicit synthetic zero candidates for transaction tests only. - Self::new( - prior, - *identity, - zeros(STATE_ELEMENTS)?, - zeros(HISTORY_ELEMENTS)?, - ) + Self::new(prior, *identity, zeros(STATE_ELEMENTS)?, zeros(HISTORY_ELEMENTS)?) } - pub(in crate::qwen_forward) fn validate( - &self, - prior: &GdnPrior, - identity: TokenLayer, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate(&self, prior: &GdnPrior, identity: TokenLayer) -> Result<()> { if !self.prior.same_state(prior) || self.identity != identity { return Err(Error::IdentityMismatch); } @@ -243,8 +207,7 @@ impl GdnPending { } fn zeros(count: usize) -> Result> { let mut v = Vec::new(); - v.try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + v.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; v.resize(count, 0.0); Ok(v.into_boxed_slice()) } @@ -260,48 +223,22 @@ mod tests { let owner = GdnOwner::new(); let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); let pos = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); - let identity = TokenLayer::new( - TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(), - pos, - layer, - ); + let identity = TokenLayer::new(TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(), pos, layer); let prior = GdnPrior::zero(binding.clone(), &owner, layer).unwrap(); assert_eq!(prior.validate(&binding, &owner, layer, pos), Ok(())); - assert_eq!( - prior.validate(&binding, &GdnOwner::new(), layer, pos), - Err(Error::IdentityMismatch) - ); - assert_eq!( - prior.validate(&BindingIdentity::test_identity(), &owner, layer, pos), - Err(Error::IdentityMismatch) - ); + assert_eq!(prior.validate(&binding, &GdnOwner::new(), layer, pos), Err(Error::IdentityMismatch)); + assert_eq!(prior.validate(&BindingIdentity::test_identity(), &owner, layer, pos), Err(Error::IdentityMismatch)); let rival = GdnPrior::zero(binding.clone(), &owner, layer).unwrap(); - let pending = GdnPending::new( - &prior, - identity, - zeros(STATE_ELEMENTS).unwrap(), - zeros(HISTORY_ELEMENTS).unwrap(), - ) - .unwrap(); - assert_eq!( - pending.validate(&rival, identity), - Err(Error::IdentityMismatch) - ); + let pending = + GdnPending::new(&prior, identity, zeros(STATE_ELEMENTS).unwrap(), zeros(HISTORY_ELEMENTS).unwrap()) + .unwrap(); + assert_eq!(pending.validate(&rival, identity), Err(Error::IdentityMismatch)); assert_eq!(pending.validate(&prior, identity), Ok(())); let next = pending.into_prior(); assert_eq!(next.next_position(), 1); assert_eq!(prior.next_position(), 0); - assert!( - prior - .values() - .iter() - .chain(prior.history()) - .all(|v| v.to_bits() == 0) - ); - assert_eq!( - next.validate(&binding, &owner, layer, pos), - Err(Error::IdentityMismatch) - ); + assert!(prior.values().iter().chain(prior.history()).all(|v| v.to_bits() == 0)); + assert_eq!(next.validate(&binding, &owner, layer, pos), Err(Error::IdentityMismatch)); assert_eq!( GdnPending::new( &prior, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror.rs index f5a65061..94baeeab 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror.rs @@ -1,8 +1,7 @@ //! One latest device recurrence per layer; immutable host state remains canonical. use super::{ - BindingIdentity, Context, DeviceBuffer, Error, GdnPending, GdnPrior, GdnStateKey, Result, - STATE_ELEMENTS, TokenLayer, VALUES, allocate, download, driver_error, preflight_budget, - validate_values, + BindingIdentity, Context, DeviceBuffer, Error, GdnPending, GdnPrior, GdnStateKey, Result, STATE_ELEMENTS, + TokenLayer, VALUES, allocate, download, driver_error, preflight_budget, validate_values, }; use std::{cell::Cell, rc::Rc}; // In-place fused T1 candidate (STRA-169): needs the private resident buffer, key and candidate constructor. @@ -50,10 +49,10 @@ pub(super) struct MirrorReadout<'ctx> { #[path = "gdn_state_mirror_gpu.rs"] mod gpu_tests; -#[path = "gdn_state_mirror/impl_mirrorreadout.rs"] -mod impl_mirrorreadout; #[path = "gdn_state_mirror/impl_gdnstatemirror.rs"] mod impl_gdnstatemirror; +#[path = "gdn_state_mirror/impl_mirrorreadout.rs"] +mod impl_mirrorreadout; #[path = "gdn_state_mirror/upload_checked_fn.rs"] mod upload_checked_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs index 13a7dc77..ec4f265e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> GdnStateMirror<'ctx> { pub(in crate::qwen_forward) fn new( binding: BindingIdentity, @@ -22,10 +20,7 @@ impl<'ctx> GdnStateMirror<'ctx> { // consume the scratch reserve. Uninitialized placeholders cannot hit. preflight_budget( context.budget_bytes(), - context - .allocated_bytes() - .checked_add(MIRROR_BYTES) - .ok_or(Error::Overflow)?, + context.allocated_bytes().checked_add(MIRROR_BYTES).ok_or(Error::Overflow)?, )?; let buffer = context.allocate(MIRROR_BYTES).map_err(driver_error)?; Ok(Self { @@ -71,8 +66,7 @@ impl<'ctx> GdnStateMirror<'ctx> { if identity.layer() != prior.layer() || identity.position().get() != prior.next_position() { return Err(Error::IdentityMismatch); } - let (mut readout, next) = - self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?; + let (mut readout, next) = self.compute_inner(prior, inputs[0], inputs[1], inputs[2], inputs[3], inputs[4])?; readout.identity = Some(identity); readout.scope = Some(scope); Ok((readout, next)) @@ -93,14 +87,9 @@ impl<'ctx> GdnStateMirror<'ctx> { if !prior.mirror_admits(&self.binding, self.layer) { return Err(Error::IdentityMismatch); } - for (values, count) in [ - (prior.values(), STATE_ELEMENTS), - (q, 2048), - (k, 2048), - (v, VALUES), - (gate, 48), - (beta, 48), - ] { + for (values, count) in + [(prior.values(), STATE_ELEMENTS), (q, 2048), (k, 2048), (v, VALUES), (gate, 48), (beta, 48)] + { validate_values(values, count)?; } let resident = self.buffer.as_ref().ok_or(Error::CudaExecution)?; @@ -116,9 +105,7 @@ impl<'ctx> GdnStateMirror<'ctx> { self.misses += 1; } let mut temporary = Vec::new(); - temporary - .try_reserve_exact(7) - .map_err(|_| Error::InputAllocation)?; + temporary.try_reserve_exact(7).map_err(|_| Error::InputAllocation)?; let mut next = None; let mut output = None; let operation = (|| -> Result { @@ -147,10 +134,7 @@ impl<'ctx> GdnStateMirror<'ctx> { ) .map_err(driver_error)?; Ok(( - download( - next.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?, + download(next.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?, download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, )) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs index ae227671..63a9217a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_gdnstatemirror/impl_gdnstatemirror_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'ctx> GdnStateMirror<'ctx> { - pub(in super::super::super) fn compute_borrowed( &mut self, prior: &GdnPrior, @@ -14,14 +11,8 @@ impl<'ctx> GdnStateMirror<'ctx> { txn: &super::super::super::QwenStepTxn<'_, '_>, inputs: super::super::super::chain::ScalarRecurrenceBorrow<'_, 'ctx>, ) -> Result<(MirrorReadout<'ctx>, MirrorNext<'ctx>)> { - let (scope, [qk, h, gate, beta]) = inputs.into_parts( - self.context, - &self.binding, - &self.failed, - prior, - identity, - txn, - )?; + let (scope, [qk, h, gate, beta]) = + inputs.into_parts(self.context, &self.binding, &self.failed, prior, identity, txn)?; if self.failed.get() { return Err(Error::CudaExecution); } @@ -42,9 +33,7 @@ impl<'ctx> GdnStateMirror<'ctx> { self.misses += 1; } let mut temporary = Vec::new(); - temporary - .try_reserve_exact(1) - .map_err(|_| Error::InputAllocation)?; + temporary.try_reserve_exact(1).map_err(|_| Error::InputAllocation)?; let mut next = None; let mut output = None; let operation = (|| -> Result { @@ -68,10 +57,7 @@ impl<'ctx> GdnStateMirror<'ctx> { ) .map_err(driver_error)?; Ok(( - download( - next.as_ref().ok_or(Error::IdentityMismatch)?, - STATE_ELEMENTS, - )?, + download(next.as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?, download(output.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?, )) })(); @@ -129,12 +115,7 @@ impl<'ctx> GdnStateMirror<'ctx> { identity: TokenLayer, history: Box<[f32]>, ) -> Result { - let MirrorNext { - context, - source, - buffer, - values, - } = next; + let MirrorNext { context, source, buffer, values } = next; let admitted = (|| -> Result<(GdnStateKey, GdnPending)> { if self.failed.get() { return Err(Error::CudaExecution); @@ -180,7 +161,11 @@ impl<'ctx> GdnStateMirror<'ctx> { /// The device image of `prior` when this mirror holds exactly that state (identity of the producing state, never a /// position): the buffer moves to the caller and a fresh one takes its place, so the chunk starts from the very bytes /// it downloaded as `prior` instead of converting and uploading them again. `adopt_chunk` releases the stand-in. - pub(in super::super::super) fn take_resident_for(&mut self, prior: &GdnPrior, cache: &super::super::super::DenseWeightCache<'ctx>) -> Result>> { + pub(in super::super::super) fn take_resident_for( + &mut self, + prior: &GdnPrior, + cache: &super::super::super::DenseWeightCache<'ctx>, + ) -> Result>> { if self.failed.get() || !prior.mirror_admits(&self.binding, self.layer) || !self.key.as_ref().is_some_and(|key| key.matches(prior)) @@ -207,11 +192,7 @@ impl<'ctx> GdnStateMirror<'ctx> { || !prior.mirror_admits(&self.binding, self.layer) { let _ = self.release_buffer(buffer); - return Err(if self.failed.get() { - Error::CudaExecution - } else { - Error::IdentityMismatch - }); + return Err(if self.failed.get() { Error::CudaExecution } else { Error::IdentityMismatch }); } self.key = None; let Some(old) = self.buffer.take() else { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_mirrorreadout.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_mirrorreadout.rs index 9c72b139..91844cad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_mirrorreadout.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/impl_mirrorreadout.rs @@ -24,24 +24,15 @@ impl<'ctx> MirrorReadout<'ctx> { || !Rc::ptr_eq(&self.failed, failed) || !self.source.same_state(prior) || self.identity != Some(identity) - || self - .scope - .as_ref() - .is_none_or(|key| !Rc::ptr_eq(key, scope)) + || self.scope.as_ref().is_none_or(|key| !Rc::ptr_eq(key, scope)) { return Err(Error::IdentityMismatch); } if self.buffer.as_ref().is_none_or(|b| b.len() != VALUES * 4) { return Err(Error::InvalidDimension); } - validate_values( - self.values.as_deref().ok_or(Error::IdentityMismatch)?, - VALUES, - )?; - Ok(( - self.buffer.take().ok_or(Error::IdentityMismatch)?, - self.values.take().ok_or(Error::IdentityMismatch)?, - )) + validate_values(self.values.as_deref().ok_or(Error::IdentityMismatch)?, VALUES)?; + Ok((self.buffer.take().ok_or(Error::IdentityMismatch)?, self.values.take().ok_or(Error::IdentityMismatch)?)) } pub(super) fn into_host(mut self) -> Result> { if let Some(buffer) = self.buffer.take() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/upload_checked_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/upload_checked_fn.rs index 27c8463f..6f597d4c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/upload_checked_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror/upload_checked_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn upload_checked<'ctx>( context: &'ctx Context<'ctx>, values: &[f32], @@ -11,9 +10,7 @@ pub(super) fn upload_checked<'ctx>( ) -> Result> { let size = values.len().checked_mul(4).ok_or(Error::Overflow)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(size) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(size).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_fused.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_fused.rs index 93d839f0..45e73261 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_fused.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_fused.rs @@ -39,9 +39,7 @@ impl<'ctx> GdnStateMirror<'ctx> { let operation = (|| -> Result<(R, Box<[f32]>)> { if !hit { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(MIRROR_BYTES) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(MIRROR_BYTES).map_err(|_| Error::InputAllocation)?; for value in prior.values() { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -63,15 +61,7 @@ impl<'ctx> GdnStateMirror<'ctx> { } return Err(Error::InvalidDimension); } - Ok(( - value, - MirrorNext { - context: self.context, - source: prior.clone(), - buffer: next, - values: state, - }, - )) + Ok((value, MirrorNext { context: self.context, source: prior.clone(), buffer: next, values: state })) } Err(primary) => { if primary == Error::CudaExecution { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs index 6aee91d7..8338efff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_state_mirror_gpu.rs @@ -15,12 +15,8 @@ struct Inputs { fn inputs(seed: usize) -> Inputs { Inputs { - q: (0..2048) - .map(|i| ((i + seed * 3) % 17) as f32 / 128. - 0.0625) - .collect(), - k: (0..2048) - .map(|i| ((i * 3 + seed * 5) % 19) as f32 / 128. - 0.0703125) - .collect(), + q: (0..2048).map(|i| ((i + seed * 3) % 17) as f32 / 128. - 0.0625).collect(), + k: (0..2048).map(|i| ((i * 3 + seed * 5) % 19) as f32 / 128. - 0.0703125).collect(), v: (0..VALUES) .map(|i| { if seed == 2 { @@ -31,13 +27,7 @@ fn inputs(seed: usize) -> Inputs { }) .collect(), gate: std::array::from_fn(|i| -0.125 - ((i + seed) % 4) as f32 / 16.), - beta: std::array::from_fn(|i| { - if (i + seed).is_multiple_of(2) { - 0.25 - } else { - 0.5 - } - }), + beta: std::array::from_fn(|i| if (i + seed).is_multiple_of(2) { 0.25 } else { 0.5 }), } } @@ -59,39 +49,15 @@ fn pair<'ctx>( let initial = context.allocated_bytes(); // Existing uncached CUDA producer is the reference. Its original input // upload/release, arithmetic and finite readbacks remain unchanged. - let (expected_state, expected_readout) = recur( - context, - prior.values(), - &inputs.q, - &inputs.k, - &inputs.v, - &inputs.gate, - &inputs.beta, - ) - .unwrap(); + let (expected_state, expected_readout) = + recur(context, prior.values(), &inputs.q, &inputs.k, &inputs.v, &inputs.gate, &inputs.beta).unwrap(); assert_eq!(context.allocated_bytes(), initial); let source_bits: Vec = prior.values().iter().map(|v| v.to_bits()).collect(); - let (readout, next) = mirror - .compute( - prior, - &inputs.q, - &inputs.k, - &inputs.v, - &inputs.gate, - &inputs.beta, - ) - .unwrap(); + let (readout, next) = mirror.compute(prior, &inputs.q, &inputs.k, &inputs.v, &inputs.gate, &inputs.beta).unwrap(); exact(&next.values, &expected_state); exact(&readout, &expected_readout); assert_eq!(context.allocated_bytes(), initial + MIRROR_BYTES); - assert_eq!( - prior - .values() - .iter() - .map(|v| v.to_bits()) - .collect::>(), - source_bits - ); + assert_eq!(prior.values().iter().map(|v| v.to_bits()).collect::>(), source_bits); println!("GDN_MIRROR PAIR seed={seed} state_words=786432 readout_words=6144 exact=true"); next } @@ -122,20 +88,12 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { let mut rollback = None; for seed in 0..4 { let next = pair(&context, &mut mirror, &prior, seed); - let candidate = mirror - .publish(next, identity(&prior, seed), prior.history().into()) - .unwrap(); - assert_eq!( - candidate.validate(&prior.clone(), identity(&prior, seed)), - Ok(()) - ); + let candidate = mirror.publish(next, identity(&prior, seed), prior.history().into()).unwrap(); + assert_eq!(candidate.validate(&prior.clone(), identity(&prior, seed)), Ok(())); if seed == 0 { let rival = GdnPrior::zero(binding.clone(), &owner, layer).unwrap(); assert!(!prior.same_state(&rival)); - assert_eq!( - candidate.validate(&rival, identity(&prior, seed)), - Err(Error::IdentityMismatch) - ); + assert_eq!(candidate.validate(&rival, identity(&prior, seed)), Err(Error::IdentityMismatch)); } prior = candidate.into_prior(); if seed == 0 { @@ -148,9 +106,7 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { let restored = rollback.unwrap(); assert_eq!(restored.next_position(), 1); let next = pair(&context, &mut mirror, &restored, 4); - let candidate = mirror - .publish(next, identity(&restored, 4), restored.history().into()) - .unwrap(); + let candidate = mirror.publish(next, identity(&restored, 4), restored.history().into()).unwrap(); assert_eq!((mirror.hits, mirror.misses), (3, 2)); let accepted_restored = candidate.into_prior(); assert_eq!(accepted_restored.next_position(), 2); @@ -166,19 +122,9 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(), layer, ); - assert_eq!( - mirror - .publish(next, wrong_identity, reset.history().into()) - .err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(mirror.publish(next, wrong_identity, reset.history().into()).err(), Some(Error::IdentityMismatch)); assert_eq!(context.allocated_bytes(), MIRROR_BYTES); - assert!( - mirror - .key - .as_ref() - .is_some_and(|key| key.matches(&accepted_restored)) - ); + assert!(mirror.key.as_ref().is_some_and(|key| key.matches(&accepted_restored))); assert_eq!(reset.next_position(), 0); assert!(reset.values().iter().all(|v| v.to_bits() == 0)); assert_eq!(reset.history().len(), HISTORY_ELEMENTS); @@ -188,51 +134,20 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { let mut malformed = ordinary.q.clone(); malformed[2047] = f32::from_bits(0x7fc00001); assert_eq!( - mirror - .compute( - &reset, - &malformed, - &ordinary.k, - &ordinary.v, - &ordinary.gate, - &ordinary.beta - ) - .err(), + mirror.compute(&reset, &malformed, &ordinary.k, &ordinary.v, &ordinary.gate, &ordinary.beta).err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), initial); assert_eq!((mirror.hits, mirror.misses), (3, 3)); - let wrong_layer = GdnPrior::zero( - binding.clone(), - &owner, - LayerId::new(1, Dimension::new(48).unwrap()).unwrap(), - ) - .unwrap(); + let wrong_layer = + GdnPrior::zero(binding.clone(), &owner, LayerId::new(1, Dimension::new(48).unwrap()).unwrap()).unwrap(); assert_eq!( - mirror - .compute( - &wrong_layer, - &ordinary.q, - &ordinary.k, - &ordinary.v, - &ordinary.gate, - &ordinary.beta - ) - .err(), + mirror.compute(&wrong_layer, &ordinary.q, &ordinary.k, &ordinary.v, &ordinary.gate, &ordinary.beta).err(), Some(Error::IdentityMismatch) ); let wrong_binding = GdnPrior::zero(BindingIdentity::test_identity(), &owner, layer).unwrap(); assert_eq!( - mirror - .compute( - &wrong_binding, - &ordinary.q, - &ordinary.k, - &ordinary.v, - &ordinary.gate, - &ordinary.beta - ) - .err(), + mirror.compute(&wrong_binding, &ordinary.q, &ordinary.k, &ordinary.v, &ordinary.gate, &ordinary.beta).err(), Some(Error::IdentityMismatch) ); assert_eq!(context.allocated_bytes(), initial); @@ -241,35 +156,16 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { // Finite raw inputs can overflow the native recurrence. Unlike the early // NaN refusal above, this reaches full D2H validation and candidate cleanup. let mut preserved = vec![0; MIRROR_BYTES]; - mirror - .buffer - .as_ref() - .unwrap() - .copy_to(&mut preserved) - .unwrap(); + mirror.buffer.as_ref().unwrap().copy_to(&mut preserved).unwrap(); let mut overflow = inputs(6); overflow.v.fill(f32::MAX); overflow.beta.fill(f32::MAX); assert_eq!( - mirror - .compute( - &accepted_restored, - &overflow.q, - &overflow.k, - &overflow.v, - &overflow.gate, - &overflow.beta - ) - .err(), + mirror.compute(&accepted_restored, &overflow.q, &overflow.k, &overflow.v, &overflow.gate, &overflow.beta).err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), initial); - assert!( - mirror - .key - .as_ref() - .is_some_and(|key| key.matches(&accepted_restored)) - ); + assert!(mirror.key.as_ref().is_some_and(|key| key.matches(&accepted_restored))); let mut after = vec![0; MIRROR_BYTES]; mirror.buffer.as_ref().unwrap().copy_to(&mut after).unwrap(); assert_eq!(after, preserved); @@ -279,31 +175,13 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { // Real completed next is discarded on a downstream abort. This is a // lifecycle check, not another independently paired numerical case. let valid = inputs(7); - let (readout, next) = mirror - .compute( - &accepted_restored, - &valid.q, - &valid.k, - &valid.v, - &valid.gate, - &valid.beta, - ) - .unwrap(); - assert!( - readout - .iter() - .chain(next.values.iter()) - .all(|v| v.is_finite()) - ); + let (readout, next) = + mirror.compute(&accepted_restored, &valid.q, &valid.k, &valid.v, &valid.gate, &valid.beta).unwrap(); + assert!(readout.iter().chain(next.values.iter()).all(|v| v.is_finite())); assert_eq!(context.allocated_bytes(), initial + MIRROR_BYTES); mirror.discard(next).unwrap(); assert_eq!(context.allocated_bytes(), initial); - assert!( - mirror - .key - .as_ref() - .is_some_and(|key| key.matches(&accepted_restored)) - ); + assert!(mirror.key.as_ref().is_some_and(|key| key.matches(&accepted_restored))); mirror.buffer.as_ref().unwrap().copy_to(&mut after).unwrap(); assert_eq!(after, preserved); assert!(!failed.get()); @@ -314,10 +192,7 @@ fn mirror_matches_uncached_steps_and_exact_rollback_reset_identity() { context.close().unwrap(); // One byte below exact eager mirror + mandatory scratch reserve. let small = device.create_context(137363455).unwrap(); - assert_eq!( - GdnStateMirror::new(binding, 0, &small, Rc::new(Cell::new(false))).err(), - Some(Error::InputAllocation) - ); + assert_eq!(GdnStateMirror::new(binding, 0, &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation)); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); println!( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification.rs index d46bb802..efbd135c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification.rs @@ -1,14 +1,20 @@ //! Private actual device owners for bounded MTP verification, never canonical state. +use super::super::session::{ + TargetStepOrigin, + chunk::{GdnChunkRow, GdnChunkStart}, +}; use super::*; -use super::super::session::{chunk::{GdnChunkRow, GdnChunkStart}, TargetStepOrigin}; use leleka_cuda_driver::GdnStateFiniteGuard; -use std::{cell::{Cell, RefCell}, rc::{Rc, Weak}}; +use std::{ + cell::{Cell, RefCell}, + rc::{Rc, Weak}, +}; pub(in crate::qwen_forward) const DEVICE_BYTES: usize = 18_350_596; const SLOTS: usize = 36 * 3; const COUNTS: [usize; 4] = [CHANNELS, CHANNELS, 48, 48]; const RESERVE: usize = 128 * 1024 * 1024; -type LayerStorage<'ctx> = ([DeviceBuffer<'ctx>;3], GdnStateFiniteGuard<'ctx>); +type LayerStorage<'ctx> = ([DeviceBuffer<'ctx>; 3], GdnStateFiniteGuard<'ctx>); pub(in crate::qwen_forward) struct ActiveLease { binding: BindingIdentity, @@ -40,9 +46,18 @@ pub(in crate::qwen_forward) struct Workspace<'ctx> { native_fused: Option<(u64, Rc>>)>, } -pub(super) struct ReplaySeal {lease:Rc,last:Rc,count:usize} +pub(super) struct ReplaySeal { + lease: Rc, + last: Rc, + count: usize, +} -pub(super) struct PoolRow<'ctx>{owner:Rc>>,lease:Rc,index:usize,buffers:[Option>;4]} +pub(super) struct PoolRow<'ctx> { + owner: Rc>>, + lease: Rc, + index: usize, + buffers: [Option>; 4], +} // Numerical transport proof only. This helper owns real CUDA buffers and calls // the same production recurrence; it does not mint Binding/Row/Prefix authority. @@ -60,154 +75,288 @@ mod numeric_gpu { } impl<'ctx> Numerical<'ctx> { fn new(context: &'ctx Context<'ctx>) -> Result { - let mut owner = Self { prior: None, rolling: [None,None], operands: Vec::new(), readout: None, guard: None }; + let mut owner = + Self { prior: None, rolling: [None, None], operands: Vec::new(), readout: None, guard: None }; let operation = (|| -> Result<()> { owner.operands.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; for _ in 0..3 { - owner.operands.push([None,None,None,None]); - for (buffer,count) in owner.operands.last_mut().ok_or(Error::IdentityMismatch)?.iter_mut().zip(COUNTS) { - *buffer=Some(allocate(context,count)?); + owner.operands.push([None, None, None, None]); + for (buffer, count) in + owner.operands.last_mut().ok_or(Error::IdentityMismatch)?.iter_mut().zip(COUNTS) + { + *buffer = Some(allocate(context, count)?); } } - owner.prior=Some(allocate(context,STATE_ELEMENTS)?); - for state in &mut owner.rolling {*state=Some(allocate(context,STATE_ELEMENTS)?);} - owner.readout=Some(allocate(context,VALUES)?); - owner.guard=Some(context.gdn_state_finite_guard().map_err(driver_error)?); + owner.prior = Some(allocate(context, STATE_ELEMENTS)?); + for state in &mut owner.rolling { + *state = Some(allocate(context, STATE_ELEMENTS)?); + } + owner.readout = Some(allocate(context, VALUES)?); + owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?); Ok(()) })(); - if let Err(primary)=operation {let _=owner.close();return Err(primary);} + if let Err(primary) = operation { + let _ = owner.close(); + return Err(primary); + } Ok(owner) } - fn row(&mut self,context:&Context<'_>,index:usize,input:Option,output:usize)->Result> { - let mut next=self.rolling[output].take().ok_or(Error::IdentityMismatch)?; - let operation=(|| { - let state=match input {Some(slot)=>self.rolling[slot].as_ref(),None=>self.prior.as_ref()}.ok_or(Error::IdentityMismatch)?; - let row=self.operands.get(index).ok_or(Error::IdentityMismatch)?; - compute_row(context,state,[row[0].as_ref().ok_or(Error::IdentityMismatch)?,row[1].as_ref().ok_or(Error::IdentityMismatch)?, - row[2].as_ref().ok_or(Error::IdentityMismatch)?,row[3].as_ref().ok_or(Error::IdentityMismatch)?], - &mut next,self.readout.as_mut().ok_or(Error::IdentityMismatch)?,self.guard.as_mut().ok_or(Error::IdentityMismatch)?) + fn row( + &mut self, + context: &Context<'_>, + index: usize, + input: Option, + output: usize, + ) -> Result> { + let mut next = self.rolling[output].take().ok_or(Error::IdentityMismatch)?; + let operation = (|| { + let state = match input { + Some(slot) => self.rolling[slot].as_ref(), + None => self.prior.as_ref(), + } + .ok_or(Error::IdentityMismatch)?; + let row = self.operands.get(index).ok_or(Error::IdentityMismatch)?; + compute_row( + context, + state, + [ + row[0].as_ref().ok_or(Error::IdentityMismatch)?, + row[1].as_ref().ok_or(Error::IdentityMismatch)?, + row[2].as_ref().ok_or(Error::IdentityMismatch)?, + row[3].as_ref().ok_or(Error::IdentityMismatch)?, + ], + &mut next, + self.readout.as_mut().ok_or(Error::IdentityMismatch)?, + self.guard.as_mut().ok_or(Error::IdentityMismatch)?, + ) })(); - self.rolling[output]=Some(next); + self.rolling[output] = Some(next); operation } - fn close(&mut self)->Result<()> { - let mut primary=None; - if let Some(guard)=self.guard.take() && let Err(error)=guard.close(){primary.get_or_insert(driver_error(error));} - for row in &mut self.operands {for buffer in row {if let Some(buffer)=buffer.take() && let Err(error)=buffer.release(){primary.get_or_insert(driver_error(error));}}} - for buffer in self.rolling.iter_mut().filter_map(Option::take).chain(self.prior.take()).chain(self.readout.take()) { - if let Err(error)=buffer.release(){primary.get_or_insert(driver_error(error));} + fn close(&mut self) -> Result<()> { + let mut primary = None; + if let Some(guard) = self.guard.take() + && let Err(error) = guard.close() + { + primary.get_or_insert(driver_error(error)); } - primary.map_or(Ok(()),Err) + for row in &mut self.operands { + for buffer in row { + if let Some(buffer) = buffer.take() + && let Err(error) = buffer.release() + { + primary.get_or_insert(driver_error(error)); + } + } + } + for buffer in + self.rolling.iter_mut().filter_map(Option::take).chain(self.prior.take()).chain(self.readout.take()) + { + if let Err(error) = buffer.release() { + primary.get_or_insert(driver_error(error)); + } + } + primary.map_or(Ok(()), Err) } } - impl Drop for Numerical<'_>{fn drop(&mut self){let _=self.close();}} - fn write(buffer:&mut DeviceBuffer<'_>,values:&[f32])->Result<()> { - let mut bytes=Vec::new();bytes.try_reserve_exact(values.len()*4).map_err(|_|Error::InputAllocation)?; - for value in values {bytes.extend_from_slice(&value.to_le_bytes());} + impl Drop for Numerical<'_> { + fn drop(&mut self) { + let _ = self.close(); + } + } + fn write(buffer: &mut DeviceBuffer<'_>, values: &[f32]) -> Result<()> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(values.len() * 4).map_err(|_| Error::InputAllocation)?; + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } buffer.copy_from_owned(bytes).map_err(driver_error) } // Literal old five-input native recurrence, including its complete state // D2H finite check BEFORE readout. Always called before candidate execution. - fn original(context:&Context<'_>,state:&[f32],row:&[Vec;4])->Result { - let mut buffers=Vec::new();buffers.try_reserve_exact(8).map_err(|_|Error::InputAllocation)?; - let operation=(|| -> Result { - for values in [state,&row[0][..2048],&row[0][2048..4096],&row[1][4096..],&row[2],&row[3]] {buffers.push(upload(context,values)?);} - let mut next=allocate(context,STATE_ELEMENTS)?; - let mut readout=allocate(context,VALUES)?; - let run=(|| { - context.gdn_step_f32(&buffers[0],&buffers[1],&buffers[2],&buffers[3],&buffers[4],&buffers[5],&mut next,&mut readout).map_err(driver_error)?; - Ok((download(&next,STATE_ELEMENTS)?,download(&readout,VALUES)?)) + fn original(context: &Context<'_>, state: &[f32], row: &[Vec; 4]) -> Result { + let mut buffers = Vec::new(); + buffers.try_reserve_exact(8).map_err(|_| Error::InputAllocation)?; + let operation = (|| -> Result { + for values in [state, &row[0][..2048], &row[0][2048..4096], &row[1][4096..], &row[2], &row[3]] { + buffers.push(upload(context, values)?); + } + let mut next = allocate(context, STATE_ELEMENTS)?; + let mut readout = allocate(context, VALUES)?; + let run = (|| { + context + .gdn_step_f32( + &buffers[0], + &buffers[1], + &buffers[2], + &buffers[3], + &buffers[4], + &buffers[5], + &mut next, + &mut readout, + ) + .map_err(driver_error)?; + Ok((download(&next, STATE_ELEMENTS)?, download(&readout, VALUES)?)) })(); - buffers.push(next);buffers.push(readout);run + buffers.push(next); + buffers.push(readout); + run })(); - let mut cleanup=None; - for buffer in buffers {if let Err(error)=buffer.release(){cleanup.get_or_insert(driver_error(error));}} - operation.and_then(|pair|cleanup.map_or(Ok(pair),Err)) + let mut cleanup = None; + for buffer in buffers { + if let Err(error) = buffer.release() { + cleanup.get_or_insert(driver_error(error)); + } + } + operation.and_then(|pair| cleanup.map_or(Ok(pair), Err)) } - fn exact(actual:&[f32],expected:&[f32],words:&mut usize)->Result<()> { - if actual.len()!=expected.len() || actual.iter().zip(expected).any(|(a,b)|a.to_bits()!=b.to_bits()){return Err(Error::IdentityMismatch);} - *words=words.checked_add(actual.len()).ok_or(Error::Overflow)?;Ok(()) + fn exact(actual: &[f32], expected: &[f32], words: &mut usize) -> Result<()> { + if actual.len() != expected.len() || actual.iter().zip(expected).any(|(a, b)| a.to_bits() != b.to_bits()) { + return Err(Error::IdentityMismatch); + } + *words = words.checked_add(actual.len()).ok_or(Error::Overflow)?; + Ok(()) } - fn rows(signed_zero:bool)->[[Vec;4];3] { - std::array::from_fn(|row|std::array::from_fn(|role| { - (0..COUNTS[role]).map(|index| { - if signed_zero && role<2 {if (index+row)%2==0 {-0.0}else{0.0}} - else {match role { - 0=>((index%17) as f32-8.0)/128.0+(row as f32)/256.0, - 1=>((index%23) as f32-11.0)/64.0-(row as f32)/128.0, - 2=>0.875+(index%2) as f32/16.0, - _=>0.25+(row as f32)/16.0, - }} - }).collect() - })) + fn rows(signed_zero: bool) -> [[Vec; 4]; 3] { + std::array::from_fn(|row| { + std::array::from_fn(|role| { + (0..COUNTS[role]) + .map(|index| { + if signed_zero && role < 2 { + if (index + row) % 2 == 0 { -0.0 } else { 0.0 } + } else { + match role { + 0 => ((index % 17) as f32 - 8.0) / 128.0 + (row as f32) / 256.0, + 1 => ((index % 23) as f32 - 11.0) / 64.0 - (row as f32) / 128.0, + 2 => 0.875 + (index % 2) as f32 / 16.0, + _ => 0.25 + (row as f32) / 16.0, + } + } + }) + .collect() + }) + }) } #[test] #[ignore = "Root runs only this changed exact-device journal recurrence boundary"] fn original_first_three_rows_and_each_accepted_replay_full_state_finite_abort_cleanup() { - assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_MTP_JOURNAL").as_deref(),Ok("yes")); - let driver=Driver::load().unwrap();let device=driver.device(0).unwrap(); - let context=device.create_context(192*1024*1024).unwrap(); - let mut owner=None; - let operation=(|| -> Result<(usize,usize)> { - let mut words=0usize;let mut guards=0usize; - for signed_zero in [false,true] { - let prior:Vec=(0..STATE_ELEMENTS).map(|index| { - if signed_zero {if index%2==0 {-0.0}else{0.0}} else {((index%19)as f32-9.0)/1024.0} - }).collect(); - let inputs=rows(signed_zero); - let mut expected=Vec::new();expected.try_reserve_exact(3).map_err(|_|Error::InputAllocation)?; + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GDN_MTP_JOURNAL").as_deref(), Ok("yes")); + let driver = Driver::load().unwrap(); + let device = driver.device(0).unwrap(); + let context = device.create_context(192 * 1024 * 1024).unwrap(); + let mut owner = None; + let operation = (|| -> Result<(usize, usize)> { + let mut words = 0usize; + let mut guards = 0usize; + for signed_zero in [false, true] { + let prior: Vec = (0..STATE_ELEMENTS) + .map(|index| { + if signed_zero { + if index % 2 == 0 { -0.0 } else { 0.0 } + } else { + ((index % 19) as f32 - 9.0) / 1024.0 + } + }) + .collect(); + let inputs = rows(signed_zero); + let mut expected = Vec::new(); + expected.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; // All three genuine causal old results FIRST, not fitted to candidate. for row in &inputs { - let previous=expected.last().map(|pair:&CandidatePair|pair.0.as_ref()).unwrap_or(&prior); - expected.push(original(&context,previous,row)?); + let previous = expected.last().map(|pair: &CandidatePair| pair.0.as_ref()).unwrap_or(&prior); + expected.push(original(&context, previous, row)?); } - if owner.is_none(){owner=Some(Numerical::new(&context)?);} - let workspace=owner.as_mut().ok_or(Error::IdentityMismatch)?; - write(workspace.prior.as_mut().ok_or(Error::IdentityMismatch)?,&prior)?; - for (buffers,row) in workspace.operands.iter_mut().zip(&inputs) { - for (buffer,values) in buffers.iter_mut().zip(row){write(buffer.as_mut().ok_or(Error::IdentityMismatch)?,values)?;} + if owner.is_none() { + owner = Some(Numerical::new(&context)?); } - let before=workspace.prior.as_ref().ok_or(Error::IdentityMismatch)?.copy_to_owned(STATE_ELEMENTS*4).map_err(driver_error)?; + let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; + write(workspace.prior.as_mut().ok_or(Error::IdentityMismatch)?, &prior)?; + for (buffers, row) in workspace.operands.iter_mut().zip(&inputs) { + for (buffer, values) in buffers.iter_mut().zip(row) { + write(buffer.as_mut().ok_or(Error::IdentityMismatch)?, values)?; + } + } + let before = workspace + .prior + .as_ref() + .ok_or(Error::IdentityMismatch)? + .copy_to_owned(STATE_ELEMENTS * 4) + .map_err(driver_error)?; // Provisional full T3, then discard/replay each real accepted length. - for (index,pair) in expected.iter().enumerate() { - let output=index%2; - let actual=workspace.row(&context,index,index.checked_sub(1).map(|n|n%2),output)?; - exact(&actual,&pair.1,&mut words)?; + for (index, pair) in expected.iter().enumerate() { + let output = index % 2; + let actual = workspace.row(&context, index, index.checked_sub(1).map(|n| n % 2), output)?; + exact(&actual, &pair.1, &mut words)?; } for accepted in 1..=3 { - for (index,pair) in expected.iter().take(accepted).enumerate() { - let actual=workspace.row(&context,index,index.checked_sub(1).map(|n|n%2),index%2)?; - exact(&actual,&pair.1,&mut words)?; + for (index, pair) in expected.iter().take(accepted).enumerate() { + let actual = workspace.row(&context, index, index.checked_sub(1).map(|n| n % 2), index % 2)?; + exact(&actual, &pair.1, &mut words)?; } - let actual=download(workspace.rolling[(accepted-1)%2].as_ref().ok_or(Error::IdentityMismatch)?,STATE_ELEMENTS)?; - exact(&actual,&expected[accepted-1].0,&mut words)?; + let actual = download( + workspace.rolling[(accepted - 1) % 2].as_ref().ok_or(Error::IdentityMismatch)?, + STATE_ELEMENTS, + )?; + exact(&actual, &expected[accepted - 1].0, &mut words)?; } - let after=workspace.prior.as_ref().ok_or(Error::IdentityMismatch)?.copy_to_owned(STATE_ELEMENTS*4).map_err(driver_error)?; - if before!=after {return Err(Error::IdentityMismatch);} - guards+=1; // Abort/rejected prefix scratch never mutated the actual prior. - for bad in [17usize,STATE_ELEMENTS-17] { - let state=workspace.rolling[0].as_mut().ok_or(Error::IdentityMismatch)?; - state.copy_from_range(bad*4,&f32::NAN.to_le_bytes()).map_err(driver_error)?; - if !matches!(download(state,STATE_ELEMENTS),Err(Error::NonFinite)) {return Err(Error::IdentityMismatch);} - if workspace.guard.as_mut().ok_or(Error::IdentityMismatch)?.check_next_state(state).map_err(driver_error)? {return Err(Error::IdentityMismatch);} - guards+=1; - write(state,&expected[0].0)?; - if !workspace.guard.as_mut().ok_or(Error::IdentityMismatch)?.check_next_state(state).map_err(driver_error)? {return Err(Error::IdentityMismatch);} - guards+=1; + let after = workspace + .prior + .as_ref() + .ok_or(Error::IdentityMismatch)? + .copy_to_owned(STATE_ELEMENTS * 4) + .map_err(driver_error)?; + if before != after { + return Err(Error::IdentityMismatch); + } + guards += 1; // Abort/rejected prefix scratch never mutated the actual prior. + for bad in [17usize, STATE_ELEMENTS - 17] { + let state = workspace.rolling[0].as_mut().ok_or(Error::IdentityMismatch)?; + state.copy_from_range(bad * 4, &f32::NAN.to_le_bytes()).map_err(driver_error)?; + if !matches!(download(state, STATE_ELEMENTS), Err(Error::NonFinite)) { + return Err(Error::IdentityMismatch); + } + if workspace + .guard + .as_mut() + .ok_or(Error::IdentityMismatch)? + .check_next_state(state) + .map_err(driver_error)? + { + return Err(Error::IdentityMismatch); + } + guards += 1; + write(state, &expected[0].0)?; + if !workspace + .guard + .as_mut() + .ok_or(Error::IdentityMismatch)? + .check_next_state(state) + .map_err(driver_error)? + { + return Err(Error::IdentityMismatch); + } + guards += 1; } // A valid row after the final late nonfinite refusal resets guard status. - let actual=workspace.row(&context,0,None,0)?; - exact(&actual,&expected[0].1,&mut words)?; - exact(&download(workspace.rolling[0].as_ref().ok_or(Error::IdentityMismatch)?,STATE_ELEMENTS)?,&expected[0].0,&mut words)?; + let actual = workspace.row(&context, 0, None, 0)?; + exact(&actual, &expected[0].1, &mut words)?; + exact( + &download(workspace.rolling[0].as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?, + &expected[0].0, + &mut words, + )?; } - Ok((words,guards)) + Ok((words, guards)) })(); - let cleanup=owner.take().map(|mut owner|owner.close()).transpose(); + let cleanup = owner.take().map(|mut owner| owner.close()).transpose(); drop(owner); - let allocated=context.allocated_bytes();let close=context.close(); + let allocated = context.allocated_bytes(); + let close = context.close(); // Cleanup and Context close precede every final quality assertion. - assert!(cleanup.is_ok());assert_eq!(allocated,0);assert!(close.is_ok()); - assert_eq!(operation.unwrap(),(6_414_336,10)); + assert!(cleanup.is_ok()); + assert_eq!(allocated, 0); + assert!(close.is_ok()); + assert_eq!(operation.unwrap(), (6_414_336, 10)); println!("GDN_MTP_JOURNAL exact_words=6414336 guards=10 allocated=0 numerical_only=true"); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn.rs index a9dc0763..84dfeee0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn.rs @@ -3,237 +3,11 @@ #[allow(unused_imports)] use super::*; - -pub(in super::super) fn compute_row( - context:&Context<'_>, state:&DeviceBuffer<'_>, operands:[&DeviceBuffer<'_>;4], - next:&mut DeviceBuffer<'_>, readout:&mut DeviceBuffer<'_>, guard:&mut GdnStateFiniteGuard<'_>, -)->Result>{ - context.gdn_step_from_products_f32(state,operands[0],operands[1],operands[2],operands[3],next,readout).map_err(driver_error)?; - if !guard.check_next_state(next).map_err(driver_error)? {return Err(Error::NonFinite);} - download(readout,VALUES) -} -impl ActiveLease { - pub(in crate::qwen_forward) fn validate( - &self, binding: &BindingIdentity, origin: &TargetStepOrigin, chunk: &Rc<()>, count: usize, - ) -> Result<()> { - if !self.valid.get() || !self.binding.matches(binding) || !self.origin.same_prefix(origin) - || !Rc::ptr_eq(&self.chunk, chunk) || self.count != count - { return Err(Error::IdentityMismatch); } - Ok(()) - } - pub(in super::super) fn refuse(&self) { self.valid.set(false); } -} -impl VerifiedRow { - pub(in super::super) fn history(&self) -> &[f32] { &self.history } - pub(in crate::qwen_forward) fn validate( - &self, lease: &Rc, layer: LayerId, index: usize, identity: TokenLayer, - ) -> Result<()> { - if !Rc::ptr_eq(&self.lease, lease) || !lease.valid.get() || self.row.identity() != identity - || identity.layer() != layer - { return Err(Error::IdentityMismatch); } - self.row.validate(&self.start, index, &lease.binding)?; - validate_values(&self.history, HISTORY_ELEMENTS) - } -} -impl<'ctx> Workspace<'ctx> { - pub(in crate::qwen_forward) fn new(binding: BindingIdentity, context: &'ctx Context<'ctx>, failed: Rc>) -> Result { - let needed = DEVICE_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; - if context.allocated_bytes().checked_add(needed).is_none_or(|v| v > context.budget_bytes()) - || context.memory_info().map_err(driver_error)?.0 < needed - { return Err(Error::InputAllocation); } - let mut owner = Self { context, binding, failed, operands: Vec::new(), states: [None,None,None], readout: None, guard: None, - ready: Vec::new(), active: Weak::new(), generation: 0, #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native_fused: None }; - let allocation = (|| -> Result<()> { - owner.operands.try_reserve_exact(SLOTS).map_err(|_| Error::InputAllocation)?; - owner.ready.try_reserve_exact(SLOTS).map_err(|_| Error::InputAllocation)?; - owner.operands.resize_with(SLOTS, || [None,None,None,None]); - owner.ready.resize_with(SLOTS, || None); - // Actual capacities are bounded metadata charged separately to host admission. - let metadata = owner.metadata_bytes()?; - if metadata > 1024*1024 { return Err(Error::InputAllocation); } - for slot in &mut owner.operands { - for (buffer, count) in slot.iter_mut().zip(COUNTS) { *buffer = Some(allocate(context, count)?); } - } - for state in &mut owner.states { *state = Some(allocate(context, STATE_ELEMENTS)?); } - owner.readout = Some(allocate(context, VALUES)?); - owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?); - if context.memory_info().map_err(driver_error)?.0 < RESERVE { return Err(Error::InputAllocation); } - Ok(()) - })(); - if let Err(primary) = allocation { if primary == Error::CudaExecution { owner.failed.set(true); } let _ = owner.cleanup(); return Err(primary); } - Ok(owner) - } - pub(in crate::qwen_forward) fn begin(&mut self, binding: &BindingIdentity, origin: &TargetStepOrigin, chunk: &Rc<()>, count: usize) -> Result> { - if self.failed.get() { return Err(Error::CudaExecution); } - if !self.binding.matches(binding) || !(1..=3).contains(&count) || self.active.upgrade().is_some() - || self.operands.iter().any(|row| row.iter().any(Option::is_none)) - || self.states.iter().any(Option::is_none) || self.readout.is_none() || self.guard.is_none() - { return Err(Error::IdentityMismatch); } - let generation = self.generation.checked_add(1).ok_or(Error::Overflow)?; - self.ready.iter_mut().for_each(|entry| *entry = None); - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { self.native_fused = None; } - let lease = Rc::new(ActiveLease { binding: binding.clone(), origin: origin.clone(), chunk: chunk.clone(), generation, count, valid: Cell::new(true) }); - self.generation = generation; self.active = Rc::downgrade(&lease); Ok(lease) - } - pub(in crate::qwen_forward) fn metadata_bytes(&self)->Result{ - self.operands.capacity().checked_mul(std::mem::size_of::<[Option>;4]>()) - .and_then(|n|self.ready.capacity().checked_mul(std::mem::size_of::>>()).and_then(|bytes|n.checked_add(bytes))) - .and_then(|n|n.checked_add(SLOTS*(std::mem::size_of::()+2*std::mem::size_of::()))) - .and_then(|n|n.checked_add(std::mem::size_of::()+std::mem::size_of::()+4*std::mem::size_of::())) - .ok_or(Error::Overflow) - } - pub(super) fn check(&self, lease: &Rc) -> Result<()> { - if self.failed.get() { return Err(Error::CudaExecution); } - if !lease.valid.get() || lease.generation != self.generation || !Weak::ptr_eq(&self.active, &Rc::downgrade(lease)) { return Err(Error::IdentityMismatch); } - Ok(()) - } - pub(super) fn slot(layer: LayerId, index: usize) -> Result { - let layer = layer.get() as usize; - if layer >=48 || layer%4 ==3 || index>=3 { return Err(Error::InvalidDimension); } - Ok((layer-layer/4)*3+index) - } - pub(in super::super) fn take_layer(&mut self, lease: &Rc, start: &GdnChunkStart) -> Result> { - self.check(lease)?; start.validate_binding(&self.binding)?; - if start.count() != lease.count { return Err(Error::IdentityMismatch); } - validate_values(start.prior().values(), STATE_ELEMENTS)?; - if self.states.iter().any(Option::is_none) || self.guard.is_none() { return Err(Error::IdentityMismatch); } - // Immutable device prior occupies state2; state0/1 alone roll. - let mut bytes = Vec::new(); bytes.try_reserve_exact(STATE_ELEMENTS*4).map_err(|_| Error::InputAllocation)?; - for value in start.prior().values() { bytes.extend_from_slice(&value.to_le_bytes()); } - self.states[2].as_mut().ok_or(Error::IdentityMismatch)?.copy_from_owned(bytes).map_err(|error| { self.failed.set(true); lease.refuse(); driver_error(error) })?; - Ok(([ - self.states[0].take().ok_or(Error::IdentityMismatch)?, - self.states[1].take().ok_or(Error::IdentityMismatch)?, - self.states[2].take().ok_or(Error::IdentityMismatch)?, - ], self.guard.take().ok_or(Error::IdentityMismatch)?)) - } - pub(in super::super) fn return_layer(&mut self, states: [DeviceBuffer<'ctx>;3], guard: GdnStateFiniteGuard<'ctx>) -> Result<()> { - if self.states.iter().any(Option::is_some) || self.guard.is_some() { self.failed.set(true); return Err(Error::IdentityMismatch); } - self.states = states.map(Some); self.guard = Some(guard); Ok(()) - } - pub(in super::super) fn row_pool(owner: Rc>, lease: Rc, row: &GdnChunkRow) -> Result> { - let mut workspace = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - workspace.check(&lease)?; - let index = Self::slot(row.identity().layer(), row.ordinal())?; - if row.ordinal() >= lease.count || workspace.ready[index].is_some() { return Err(Error::IdentityMismatch); } - if workspace.operands[index].iter().any(Option::is_none) { lease.refuse(); return Err(Error::IdentityMismatch); } - let buffers = std::array::from_fn(|i| workspace.operands[index][i].take()); - drop(workspace); - Ok(PoolRow { owner, lease, index, buffers }) - } - pub(in super::super) fn take_readout(&mut self, lease: &Rc) -> Result> { - self.check(lease)?; self.readout.take().ok_or(Error::IdentityMismatch) - } - pub(in super::super) fn put_readout(&mut self, buffer: DeviceBuffer<'ctx>) -> Result<()> { - if self.readout.is_some() || buffer.len()!=VALUES*4 { self.failed.set(true); return Err(Error::IdentityMismatch); } - self.readout = Some(buffer); Ok(()) - } - pub(in super::super) fn record(&mut self, lease: &Rc, start: &GdnChunkStart, row: GdnChunkRow, history: Box<[f32]>) -> Result> { - self.check(lease)?; row.validate(start, row.ordinal(), &self.binding)?; validate_values(&history,HISTORY_ELEMENTS)?; - let slot = Self::slot(row.identity().layer(),row.ordinal())?; - if self.ready[slot].is_some() || self.operands[slot].iter().any(Option::is_none) { return Err(Error::IdentityMismatch); } - let proof=Rc::new(VerifiedRow { lease: lease.clone(), start:start.clone(), row, history:Rc::new(history) }); - self.ready[slot]=Some(Rc::downgrade(&proof)); Ok(proof) - } - pub(in crate::qwen_forward) fn replay(&mut self, lease: &Rc, rows: &[Rc], mut cancelled: impl FnMut()->bool) -> Result { - self.check(lease)?; - let last=rows.last().ok_or(Error::IdentityMismatch)?; - if rows.len()>lease.count { return Err(Error::IdentityMismatch); } - let start=&last.start; let prior=start.prior(); - let mut state=0usize; - for (index,row) in rows.iter().enumerate() { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - row.validate(lease,prior.layer(),index,row.row.identity())?; - let slot=Self::slot(prior.layer(),index)?; - if self.ready[slot].as_ref().and_then(Weak::upgrade).is_none_or(|saved| !Rc::ptr_eq(&saved,row)) { return Err(Error::IdentityMismatch); } - let input=if index==0 { 2 } else { state }; - let output=if index==0 { 0 } else { 1-state }; - // Re-upload untouched actual prior once per replayed layer. The same - // third whole owner is immutable throughout its accepted prefix. - if index==0 { - let mut bytes=Vec::new();bytes.try_reserve_exact(STATE_ELEMENTS*4).map_err(|_|Error::InputAllocation)?; - for value in prior.values(){bytes.extend_from_slice(&value.to_le_bytes());} - self.states[2].as_mut().ok_or(Error::IdentityMismatch)?.copy_from_owned(bytes).map_err(|error| { self.failed.set(true); lease.refuse(); driver_error(error) })?; - } - let operands=&self.operands[slot]; - let mut out=self.states[output].take().ok_or(Error::IdentityMismatch)?; - let operation=(|| -> Result<()> { - // Preserve the completed full readout finite boundary even on replay. - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let native_completed = if let Some((generation, program)) = &self.native_fused { - if *generation != lease.generation { return Err(Error::IdentityMismatch); } - let mut program = program.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - program.validate_context(self.context).map_err(driver_error)?; - if !program.replay_state_from_products( - self.states[input].as_ref().ok_or(Error::IdentityMismatch)?, - operands[0].as_ref().ok_or(Error::IdentityMismatch)?, - operands[1].as_ref().ok_or(Error::IdentityMismatch)?, - operands[2].as_ref().ok_or(Error::IdentityMismatch)?, - operands[3].as_ref().ok_or(Error::IdentityMismatch)?, &out, - self.readout.as_ref().ok_or(Error::IdentityMismatch)?, - ).map_err(driver_error)? { return Err(Error::NonFinite); } - // Preserve the actual complete state boundary and whole - // readout domain on accepted-prefix replay. - if !self.guard.as_mut().ok_or(Error::IdentityMismatch)? - .check_next_state(&out).map_err(driver_error)? { return Err(Error::NonFinite); } - let _ = download(self.readout.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?; - true - } else { false }; - #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let native_completed = false; - if !native_completed { - let _=compute_row(self.context,self.states[input].as_ref().ok_or(Error::IdentityMismatch)?,[ - operands[0].as_ref().ok_or(Error::IdentityMismatch)?,operands[1].as_ref().ok_or(Error::IdentityMismatch)?, - operands[2].as_ref().ok_or(Error::IdentityMismatch)?,operands[3].as_ref().ok_or(Error::IdentityMismatch)?], - &mut out,self.readout.as_mut().ok_or(Error::IdentityMismatch)?,self.guard.as_mut().ok_or(Error::IdentityMismatch)?)?; - } - Ok(()) - })(); - self.states[output]=Some(out); - if let Err(primary)=operation { lease.refuse();if primary==Error::CudaExecution{self.failed.set(true);}return Err(primary); } - state=output; - } - if cancelled(){return Err(Error::Unsupported(Stage::Executor));} - let values=download(self.states[state].as_ref().ok_or(Error::IdentityMismatch)?,STATE_ELEMENTS)?; - let mut history=Vec::new();history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_|Error::InputAllocation)?; - history.extend_from_slice(&last.history); - GdnPrior::from_verified_prefix(prior, ReplaySeal { lease:lease.clone(), last:last.clone(), count:rows.len() }, values,history.into_boxed_slice()) - } - pub(in crate::qwen_forward) fn close(mut self)->Result<()> {self.cleanup()} - pub(super) fn cleanup(&mut self)->Result<()> { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - { self.native_fused = None; } - let mut failure=None; - if let Some(guard)=self.guard.take() && let Err(error)=guard.close(){self.failed.set(true);failure.get_or_insert(driver_error(error));} - for row in &mut self.operands {for buffer in row {if let Some(buffer)=buffer.take() && let Err(error)=buffer.release(){self.failed.set(true);failure.get_or_insert(driver_error(error));}}} - for buffer in self.states.iter_mut().filter_map(Option::take).chain(self.readout.take()) {if let Err(error)=buffer.release(){self.failed.set(true);failure.get_or_insert(driver_error(error));}} - failure.map_or(Ok(()),Err) - } -} -impl Drop for Workspace<'_>{fn drop(&mut self){let _=self.cleanup();}} -impl ReplaySeal { - pub(in super::super) fn validate_prior(&self,prior:&GdnPrior)->Result{ - if !self.last.start.prior().same_state(prior) || self.count==0 || self.count>self.lease.count - || self.last.row.ordinal()+1 !=self.count {return Err(Error::IdentityMismatch);} - self.last.validate(&self.lease,prior.layer(),self.count-1,self.last.row.identity())?; - prior.next_position().checked_add(self.count as u64).ok_or(Error::Overflow) - } -} -impl<'ctx> PoolRow<'ctx>{ - pub(in super::super) fn take(&mut self,role:chain::Role)->Result>>{ - let index=match role{chain::Role::Qk=>0,chain::Role::H=>1,chain::Role::Gate=>2,chain::Role::Beta=>3,_=>return Ok(None)}; - self.owner.try_borrow().map_err(|_|Error::IdentityMismatch)?.check(&self.lease)?; - Ok(Some(self.buffers[index].take().ok_or(Error::IdentityMismatch)?)) - } - pub(in super::super) fn put(&mut self,role:chain::Role,buffer:DeviceBuffer<'ctx>)->Result<()> { - if role==chain::Role::Readout { return self.owner.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.put_readout(buffer); } - let index=match role{chain::Role::Qk=>0,chain::Role::H=>1,chain::Role::Gate=>2,chain::Role::Beta=>3,_=>return Err(Error::IdentityMismatch)}; - let mut owner=self.owner.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?; - if owner.operands[self.index][index].is_some() || buffer.len()!=COUNTS[index]*4 {owner.failed.set(true);return Err(Error::IdentityMismatch);} - owner.operands[self.index][index]=Some(buffer);Ok(()) - } -} -impl Drop for PoolRow<'_>{fn drop(&mut self){ - for index in 0..4 {if let Some(buffer)=self.buffers[index].take(){let role=[chain::Role::Qk,chain::Role::H,chain::Role::Gate,chain::Role::Beta][index];let _=self.put(role,buffer);}} -}} +#[path = "compute_row_fn/compute_row_fn_2.rs"] +mod compute_row_fn_2; +#[allow(unused_imports)] +pub(in super::super) use compute_row_fn_2::compute_row; +#[path = "compute_row_fn/impl_workspace.rs"] +mod impl_workspace; +#[path = "compute_row_fn/impl_workspace_2.rs"] +mod impl_workspace_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/compute_row_fn_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/compute_row_fn_2.rs new file mode 100644 index 00000000..8a7c9189 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/compute_row_fn_2.rs @@ -0,0 +1,65 @@ +//! Moved out of the parent module by STRA-338: fn compute_row, impl ActiveLease, impl VerifiedRow. + +#[allow(unused_imports)] +use super::*; + +pub(in super::super::super) fn compute_row( + context: &Context<'_>, + state: &DeviceBuffer<'_>, + operands: [&DeviceBuffer<'_>; 4], + next: &mut DeviceBuffer<'_>, + readout: &mut DeviceBuffer<'_>, + guard: &mut GdnStateFiniteGuard<'_>, +) -> Result> { + context + .gdn_step_from_products_f32(state, operands[0], operands[1], operands[2], operands[3], next, readout) + .map_err(driver_error)?; + if !guard.check_next_state(next).map_err(driver_error)? { + return Err(Error::NonFinite); + } + download(readout, VALUES) +} +impl ActiveLease { + pub(in crate::qwen_forward) fn validate( + &self, + binding: &BindingIdentity, + origin: &TargetStepOrigin, + chunk: &Rc<()>, + count: usize, + ) -> Result<()> { + if !self.valid.get() + || !self.binding.matches(binding) + || !self.origin.same_prefix(origin) + || !Rc::ptr_eq(&self.chunk, chunk) + || self.count != count + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in super::super::super) fn refuse(&self) { + self.valid.set(false); + } +} +impl VerifiedRow { + pub(in super::super::super) fn history(&self) -> &[f32] { + &self.history + } + pub(in crate::qwen_forward) fn validate( + &self, + lease: &Rc, + layer: LayerId, + index: usize, + identity: TokenLayer, + ) -> Result<()> { + if !Rc::ptr_eq(&self.lease, lease) + || !lease.valid.get() + || self.row.identity() != identity + || identity.layer() != layer + { + return Err(Error::IdentityMismatch); + } + self.row.validate(&self.start, index, &lease.binding)?; + validate_values(&self.history, HISTORY_ELEMENTS) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace.rs new file mode 100644 index 00000000..8988de1a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: impl Workspace. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> Workspace<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + failed: Rc>, + ) -> Result { + let needed = DEVICE_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(needed).is_none_or(|v| v > context.budget_bytes()) + || context.memory_info().map_err(driver_error)?.0 < needed + { + return Err(Error::InputAllocation); + } + let mut owner = Self { + context, + binding, + failed, + operands: Vec::new(), + states: [None, None, None], + readout: None, + guard: None, + ready: Vec::new(), + active: Weak::new(), + generation: 0, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native_fused: None, + }; + let allocation = (|| -> Result<()> { + owner.operands.try_reserve_exact(SLOTS).map_err(|_| Error::InputAllocation)?; + owner.ready.try_reserve_exact(SLOTS).map_err(|_| Error::InputAllocation)?; + owner.operands.resize_with(SLOTS, || [None, None, None, None]); + owner.ready.resize_with(SLOTS, || None); + // Actual capacities are bounded metadata charged separately to host admission. + let metadata = owner.metadata_bytes()?; + if metadata > 1024 * 1024 { + return Err(Error::InputAllocation); + } + for slot in &mut owner.operands { + for (buffer, count) in slot.iter_mut().zip(COUNTS) { + *buffer = Some(allocate(context, count)?); + } + } + for state in &mut owner.states { + *state = Some(allocate(context, STATE_ELEMENTS)?); + } + owner.readout = Some(allocate(context, VALUES)?); + owner.guard = Some(context.gdn_state_finite_guard().map_err(driver_error)?); + if context.memory_info().map_err(driver_error)?.0 < RESERVE { + return Err(Error::InputAllocation); + } + Ok(()) + })(); + if let Err(primary) = allocation { + if primary == Error::CudaExecution { + owner.failed.set(true); + } + let _ = owner.cleanup(); + return Err(primary); + } + Ok(owner) + } + pub(in crate::qwen_forward) fn begin( + &mut self, + binding: &BindingIdentity, + origin: &TargetStepOrigin, + chunk: &Rc<()>, + count: usize, + ) -> Result> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(binding) + || !(1..=3).contains(&count) + || self.active.upgrade().is_some() + || self.operands.iter().any(|row| row.iter().any(Option::is_none)) + || self.states.iter().any(Option::is_none) + || self.readout.is_none() + || self.guard.is_none() + { + return Err(Error::IdentityMismatch); + } + let generation = self.generation.checked_add(1).ok_or(Error::Overflow)?; + self.ready.iter_mut().for_each(|entry| *entry = None); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.native_fused = None; + } + let lease = Rc::new(ActiveLease { + binding: binding.clone(), + origin: origin.clone(), + chunk: chunk.clone(), + generation, + count, + valid: Cell::new(true), + }); + self.generation = generation; + self.active = Rc::downgrade(&lease); + Ok(lease) + } + pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result { + self.operands + .capacity() + .checked_mul(std::mem::size_of::<[Option>; 4]>()) + .and_then(|n| { + self.ready + .capacity() + .checked_mul(std::mem::size_of::>>()) + .and_then(|bytes| n.checked_add(bytes)) + }) + .and_then(|n| { + n.checked_add(SLOTS * (std::mem::size_of::() + 2 * std::mem::size_of::())) + }) + .and_then(|n| { + n.checked_add( + std::mem::size_of::() + std::mem::size_of::() + 4 * std::mem::size_of::(), + ) + }) + .ok_or(Error::Overflow) + } + pub(in super::super) fn check(&self, lease: &Rc) -> Result<()> { + if self.failed.get() { + return Err(Error::CudaExecution); + } + if !lease.valid.get() + || lease.generation != self.generation + || !Weak::ptr_eq(&self.active, &Rc::downgrade(lease)) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in super::super) fn slot(layer: LayerId, index: usize) -> Result { + let layer = layer.get() as usize; + if layer >= 48 || layer % 4 == 3 || index >= 3 { + return Err(Error::InvalidDimension); + } + Ok((layer - layer / 4) * 3 + index) + } + pub(in super::super::super) fn take_layer( + &mut self, + lease: &Rc, + start: &GdnChunkStart, + ) -> Result> { + self.check(lease)?; + start.validate_binding(&self.binding)?; + if start.count() != lease.count { + return Err(Error::IdentityMismatch); + } + validate_values(start.prior().values(), STATE_ELEMENTS)?; + if self.states.iter().any(Option::is_none) || self.guard.is_none() { + return Err(Error::IdentityMismatch); + } + // Immutable device prior occupies state2; state0/1 alone roll. + let mut bytes = Vec::new(); + bytes.try_reserve_exact(STATE_ELEMENTS * 4).map_err(|_| Error::InputAllocation)?; + for value in start.prior().values() { + bytes.extend_from_slice(&value.to_le_bytes()); + } + self.states[2].as_mut().ok_or(Error::IdentityMismatch)?.copy_from_owned(bytes).map_err(|error| { + self.failed.set(true); + lease.refuse(); + driver_error(error) + })?; + Ok(( + [ + self.states[0].take().ok_or(Error::IdentityMismatch)?, + self.states[1].take().ok_or(Error::IdentityMismatch)?, + self.states[2].take().ok_or(Error::IdentityMismatch)?, + ], + self.guard.take().ok_or(Error::IdentityMismatch)?, + )) + } + pub(in super::super::super) fn return_layer( + &mut self, + states: [DeviceBuffer<'ctx>; 3], + guard: GdnStateFiniteGuard<'ctx>, + ) -> Result<()> { + if self.states.iter().any(Option::is_some) || self.guard.is_some() { + self.failed.set(true); + return Err(Error::IdentityMismatch); + } + self.states = states.map(Some); + self.guard = Some(guard); + Ok(()) + } + pub(in super::super::super) fn row_pool( + owner: Rc>, + lease: Rc, + row: &GdnChunkRow, + ) -> Result> { + let mut workspace = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + workspace.check(&lease)?; + let index = Self::slot(row.identity().layer(), row.ordinal())?; + if row.ordinal() >= lease.count || workspace.ready[index].is_some() { + return Err(Error::IdentityMismatch); + } + if workspace.operands[index].iter().any(Option::is_none) { + lease.refuse(); + return Err(Error::IdentityMismatch); + } + let buffers = std::array::from_fn(|i| workspace.operands[index][i].take()); + drop(workspace); + Ok(PoolRow { owner, lease, index, buffers }) + } + pub(in super::super::super) fn take_readout(&mut self, lease: &Rc) -> Result> { + self.check(lease)?; + self.readout.take().ok_or(Error::IdentityMismatch) + } + pub(in super::super::super) fn put_readout(&mut self, buffer: DeviceBuffer<'ctx>) -> Result<()> { + if self.readout.is_some() || buffer.len() != VALUES * 4 { + self.failed.set(true); + return Err(Error::IdentityMismatch); + } + self.readout = Some(buffer); + Ok(()) + } + pub(in super::super::super) fn record( + &mut self, + lease: &Rc, + start: &GdnChunkStart, + row: GdnChunkRow, + history: Box<[f32]>, + ) -> Result> { + self.check(lease)?; + row.validate(start, row.ordinal(), &self.binding)?; + validate_values(&history, HISTORY_ELEMENTS)?; + let slot = Self::slot(row.identity().layer(), row.ordinal())?; + if self.ready[slot].is_some() || self.operands[slot].iter().any(Option::is_none) { + return Err(Error::IdentityMismatch); + } + let proof = Rc::new(VerifiedRow { lease: lease.clone(), start: start.clone(), row, history: Rc::new(history) }); + self.ready[slot] = Some(Rc::downgrade(&proof)); + Ok(proof) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs new file mode 100644 index 00000000..a0e9d65f --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/compute_row_fn/impl_workspace_2.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: impl Workspace (2), impl Drop_for_Workspace, impl ReplaySeal, impl PoolRow, impl Drop_for_PoolRow. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> Workspace<'ctx> { + pub(in crate::qwen_forward) fn replay( + &mut self, + lease: &Rc, + rows: &[Rc], + mut cancelled: impl FnMut() -> bool, + ) -> Result { + self.check(lease)?; + let last = rows.last().ok_or(Error::IdentityMismatch)?; + if rows.len() > lease.count { + return Err(Error::IdentityMismatch); + } + let start = &last.start; + let prior = start.prior(); + let mut state = 0usize; + for (index, row) in rows.iter().enumerate() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + row.validate(lease, prior.layer(), index, row.row.identity())?; + let slot = Self::slot(prior.layer(), index)?; + if self.ready[slot].as_ref().and_then(Weak::upgrade).is_none_or(|saved| !Rc::ptr_eq(&saved, row)) { + return Err(Error::IdentityMismatch); + } + let input = if index == 0 { 2 } else { state }; + let output = if index == 0 { 0 } else { 1 - state }; + // Re-upload untouched actual prior once per replayed layer. The same + // third whole owner is immutable throughout its accepted prefix. + if index == 0 { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(STATE_ELEMENTS * 4).map_err(|_| Error::InputAllocation)?; + for value in prior.values() { + bytes.extend_from_slice(&value.to_le_bytes()); + } + self.states[2].as_mut().ok_or(Error::IdentityMismatch)?.copy_from_owned(bytes).map_err(|error| { + self.failed.set(true); + lease.refuse(); + driver_error(error) + })?; + } + let operands = &self.operands[slot]; + let mut out = self.states[output].take().ok_or(Error::IdentityMismatch)?; + let operation = (|| -> Result<()> { + // Preserve the completed full readout finite boundary even on replay. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + let native_completed = if let Some((generation, program)) = &self.native_fused { + if *generation != lease.generation { + return Err(Error::IdentityMismatch); + } + let mut program = program.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + program.validate_context(self.context).map_err(driver_error)?; + if !program + .replay_state_from_products( + self.states[input].as_ref().ok_or(Error::IdentityMismatch)?, + operands[0].as_ref().ok_or(Error::IdentityMismatch)?, + operands[1].as_ref().ok_or(Error::IdentityMismatch)?, + operands[2].as_ref().ok_or(Error::IdentityMismatch)?, + operands[3].as_ref().ok_or(Error::IdentityMismatch)?, + &out, + self.readout.as_ref().ok_or(Error::IdentityMismatch)?, + ) + .map_err(driver_error)? + { + return Err(Error::NonFinite); + } + // Preserve the actual complete state boundary and whole + // readout domain on accepted-prefix replay. + if !self + .guard + .as_mut() + .ok_or(Error::IdentityMismatch)? + .check_next_state(&out) + .map_err(driver_error)? + { + return Err(Error::NonFinite); + } + let _ = download(self.readout.as_ref().ok_or(Error::IdentityMismatch)?, VALUES)?; + true + } else { + false + }; + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + let native_completed = false; + if !native_completed { + let _ = compute_row( + self.context, + self.states[input].as_ref().ok_or(Error::IdentityMismatch)?, + [ + operands[0].as_ref().ok_or(Error::IdentityMismatch)?, + operands[1].as_ref().ok_or(Error::IdentityMismatch)?, + operands[2].as_ref().ok_or(Error::IdentityMismatch)?, + operands[3].as_ref().ok_or(Error::IdentityMismatch)?, + ], + &mut out, + self.readout.as_mut().ok_or(Error::IdentityMismatch)?, + self.guard.as_mut().ok_or(Error::IdentityMismatch)?, + )?; + } + Ok(()) + })(); + self.states[output] = Some(out); + if let Err(primary) = operation { + lease.refuse(); + if primary == Error::CudaExecution { + self.failed.set(true); + } + return Err(primary); + } + state = output; + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let values = download(self.states[state].as_ref().ok_or(Error::IdentityMismatch)?, STATE_ELEMENTS)?; + let mut history = Vec::new(); + history.try_reserve_exact(HISTORY_ELEMENTS).map_err(|_| Error::InputAllocation)?; + history.extend_from_slice(&last.history); + GdnPrior::from_verified_prefix( + prior, + ReplaySeal { lease: lease.clone(), last: last.clone(), count: rows.len() }, + values, + history.into_boxed_slice(), + ) + } + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.cleanup() + } + pub(in super::super) fn cleanup(&mut self) -> Result<()> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.native_fused = None; + } + let mut failure = None; + if let Some(guard) = self.guard.take() + && let Err(error) = guard.close() + { + self.failed.set(true); + failure.get_or_insert(driver_error(error)); + } + for row in &mut self.operands { + for buffer in row { + if let Some(buffer) = buffer.take() + && let Err(error) = buffer.release() + { + self.failed.set(true); + failure.get_or_insert(driver_error(error)); + } + } + } + for buffer in self.states.iter_mut().filter_map(Option::take).chain(self.readout.take()) { + if let Err(error) = buffer.release() { + self.failed.set(true); + failure.get_or_insert(driver_error(error)); + } + } + failure.map_or(Ok(()), Err) + } +} +impl Drop for Workspace<'_> { + fn drop(&mut self) { + let _ = self.cleanup(); + } +} +impl ReplaySeal { + pub(in super::super::super) fn validate_prior(&self, prior: &GdnPrior) -> Result { + if !self.last.start.prior().same_state(prior) + || self.count == 0 + || self.count > self.lease.count + || self.last.row.ordinal() + 1 != self.count + { + return Err(Error::IdentityMismatch); + } + self.last.validate(&self.lease, prior.layer(), self.count - 1, self.last.row.identity())?; + prior.next_position().checked_add(self.count as u64).ok_or(Error::Overflow) + } +} +impl<'ctx> PoolRow<'ctx> { + pub(in super::super::super) fn take(&mut self, role: chain::Role) -> Result>> { + let index = match role { + chain::Role::Qk => 0, + chain::Role::H => 1, + chain::Role::Gate => 2, + chain::Role::Beta => 3, + _ => return Ok(None), + }; + self.owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.check(&self.lease)?; + Ok(Some(self.buffers[index].take().ok_or(Error::IdentityMismatch)?)) + } + pub(in super::super::super) fn put(&mut self, role: chain::Role, buffer: DeviceBuffer<'ctx>) -> Result<()> { + if role == chain::Role::Readout { + return self.owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.put_readout(buffer); + } + let index = match role { + chain::Role::Qk => 0, + chain::Role::H => 1, + chain::Role::Gate => 2, + chain::Role::Beta => 3, + _ => return Err(Error::IdentityMismatch), + }; + let mut owner = self.owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + if owner.operands[self.index][index].is_some() || buffer.len() != COUNTS[index] * 4 { + owner.failed.set(true); + return Err(Error::IdentityMismatch); + } + owner.operands[self.index][index] = Some(buffer); + Ok(()) + } +} +impl Drop for PoolRow<'_> { + fn drop(&mut self) { + for index in 0..4 { + if let Some(buffer) = self.buffers[index].take() { + let role = [chain::Role::Qk, chain::Role::H, chain::Role::Gate, chain::Role::Beta][index]; + let _ = self.put(role, buffer); + } + } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/impl_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/impl_workspace.rs index 741e6ccc..1a430da0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/impl_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gdn_verification/impl_workspace.rs @@ -3,21 +3,26 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> Workspace<'ctx> { pub(in super::super) fn bind_native_fused( - &mut self, lease: &Rc, + &mut self, + lease: &Rc, program: Rc>>, ) -> Result<()> { self.check(lease)?; - program.try_borrow().map_err(|_| Error::IdentityMismatch)? - .validate_context(self.context).map_err(driver_error)?; + program + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .validate_context(self.context) + .map_err(driver_error)?; if let Some((generation, current)) = &self.native_fused { if *generation != lease.generation || !Rc::ptr_eq(current, &program) { return Err(Error::IdentityMismatch); } - } else { self.native_fused = Some((lease.generation, program)); } + } else { + self.native_fused = Some((lease.generation, program)); + } Ok(()) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs index de5083d5..7e267cae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr.rs @@ -6,10 +6,8 @@ use super::contract::{Dimension, Error, LayerId, Result, Stage, TokenLayer}; use super::dense_weight_cache::DenseWeightCache; use super::input::PleReady; use super::session::QwenStepTxn; -use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrWeights, InputBindingError, ModelBinding, -}; pub(crate) use crate::model_binding::qwen4exp_input::GrRole; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrWeights, InputBindingError, ModelBinding}; use leleka_cuda_driver::{Context, DeviceBuffer, Error as DriverError}; use std::{ cell::{Cell, RefCell, RefMut}, @@ -117,38 +115,38 @@ mod diagnose_fn; use diagnose_fn::diagnose; #[allow(unused_imports)] use diagnose_fn::diagnose_extrema; -mod impl_residualready; mod impl_grstage; +mod impl_residualready; mod read_cuda_fn; #[allow(unused_imports)] use read_cuda_fn::read_cuda; mod read_cached_cuda_fn; #[allow(unused_imports)] -use read_cached_cuda_fn::read_cached_cuda; -#[allow(unused_imports)] -use read_cached_cuda_fn::inject_cached_cuda; +use read_cached_cuda_fn::admit_budget; #[allow(unused_imports)] use read_cached_cuda_fn::copy_cached_f32; #[allow(unused_imports)] -use read_cached_cuda_fn::upload_cached_f32; +use read_cached_cuda_fn::inject_cached_cuda; +#[allow(unused_imports)] +use read_cached_cuda_fn::read_cached_cuda; #[allow(unused_imports)] use read_cached_cuda_fn::release_all; #[allow(unused_imports)] -use read_cached_cuda_fn::admit_budget; +use read_cached_cuda_fn::upload_bf16; +#[allow(unused_imports)] +use read_cached_cuda_fn::upload_cached_f32; #[allow(unused_imports)] use read_cached_cuda_fn::upload_f32; -#[allow(unused_imports)] -use read_cached_cuda_fn::upload_bf16; mod download_f32_fn; #[allow(unused_imports)] +use download_f32_fn::binding_error; +#[allow(unused_imports)] use download_f32_fn::download_f32; #[allow(unused_imports)] use download_f32_fn::driver_error; #[allow(unused_imports)] -use download_f32_fn::binding_error; -#[allow(unused_imports)] -use download_f32_fn::validate_values; -#[allow(unused_imports)] use download_f32_fn::validate_layer; #[allow(unused_imports)] use download_f32_fn::validate_streams; +#[allow(unused_imports)] +use download_f32_fn::validate_values; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/diagnose_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/diagnose_fn.rs index e0e948c4..5f3824d8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/diagnose_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/diagnose_fn.rs @@ -3,15 +3,11 @@ #[allow(unused_imports)] use super::*; - pub(super) fn diagnose(phase: GrPhase, result: Result) -> Result { result.inspect_err(|error| { use std::io::Write; // Preserve the real error even when stderr is unavailable. - let _ = writeln!( - std::io::stderr().lock(), - "leleka-gr phase={phase:?} error={error:?}" - ); + let _ = writeln!(std::io::stderr().lock(), "leleka-gr phase={phase:?} error={error:?}"); }) } @@ -21,10 +17,7 @@ pub(super) fn diagnose_extrema(phase: GrPhase, result: Result, finite_inpu result.inspect_err(|error| { use std::io::Write; let min = finite_input.iter().copied().fold(f32::INFINITY, f32::min); - let max = finite_input - .iter() - .copied() - .fold(f32::NEG_INFINITY, f32::max); + let max = finite_input.iter().copied().fold(f32::NEG_INFINITY, f32::max); let _ = writeln!( std::io::stderr().lock(), "leleka-gr phase={phase:?} error={error:?} input_min={min} input_max={max}" @@ -49,11 +42,7 @@ impl<'ctx> GrScratch<'ctx> { } admit_budget(context, GR_OWNED_DEVICE_BYTES + 128 * 1024 * 1024)?; let mut owned: [Option>; 11] = std::array::from_fn(|_| None); - for (slot, bytes) in std::iter::once(40960) - .chain(GR_OUTPUT_BYTES) - .chain(GR_INJECT_BYTES) - .enumerate() - { + for (slot, bytes) in std::iter::once(40960).chain(GR_OUTPUT_BYTES).chain(GR_INJECT_BYTES).enumerate() { match context.allocate(bytes).map_err(driver_error) { Ok(buffer) => owned[slot] = Some(buffer), Err(primary) => { @@ -68,19 +57,7 @@ impl<'ctx> GrScratch<'ctx> { } } } - let [ - residual, - xn, - down, - activated, - gates, - products, - mixed, - read_inject, - block, - inject, - candidate, - ] = owned; + let [residual, xn, down, activated, gates, products, mixed, read_inject, block, inject, candidate] = owned; Ok(Self { binding, context, @@ -117,32 +94,20 @@ impl<'ctx> GrScratch<'ctx> { Ok(buffer) } pub(super) fn validate_outputs(&self) -> Result<()> { - let outputs = self - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; + let outputs = + self.outputs.as_ref().ok_or(Error::CudaExecution)?.try_borrow().map_err(|_| Error::IdentityMismatch)?; for (buffer, bytes) in outputs.iter().zip(GR_OUTPUT_BYTES) { if buffer.len() != bytes { return Err(Error::InvalidDimension); } } - let read_inject = self - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; + let read_inject = + self.read_inject.as_ref().ok_or(Error::CudaExecution)?.try_borrow().map_err(|_| Error::IdentityMismatch)?; if read_inject.len() != 16 { return Err(Error::InvalidDimension); } - let injection = self - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; + let injection = + self.injection.as_ref().ok_or(Error::CudaExecution)?.try_borrow().map_err(|_| Error::IdentityMismatch)?; for (buffer, bytes) in injection.iter().zip([10240, 16, 40960]) { if buffer.len() != bytes { return Err(Error::InvalidDimension); @@ -150,12 +115,7 @@ impl<'ctx> GrScratch<'ctx> { } Ok(()) } - pub(super) fn write( - &mut self, - binding: &BindingIdentity, - context: &Context<'_>, - streams: &[f32], - ) -> Result<()> { + pub(super) fn write(&mut self, binding: &BindingIdentity, context: &Context<'_>, streams: &[f32]) -> Result<()> { if !self.binding.matches(binding) { return Err(Error::IdentityMismatch); } @@ -163,18 +123,11 @@ impl<'ctx> GrScratch<'ctx> { self.validate_outputs()?; validate_streams(streams)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(40960) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(40960).map_err(|_| Error::InputAllocation)?; for value in streams { bytes.extend_from_slice(&value.to_le_bytes()); } - let result = self - .residual - .as_mut() - .ok_or(Error::CudaExecution)? - .copy_from(&bytes) - .map_err(driver_error); + let result = self.residual.as_mut().ok_or(Error::CudaExecution)?.copy_from(&bytes).map_err(driver_error); if result.is_err() { self.failed.set(true); } @@ -182,9 +135,8 @@ impl<'ctx> GrScratch<'ctx> { } pub(super) fn release_owned(&mut self) -> Result<()> { let outputs = self.outputs.take().map(|outputs| outputs.into_inner()); - let [xn, down, activated, gates, products, mixed] = outputs - .map(|outputs| outputs.map(Some)) - .unwrap_or_else(|| std::array::from_fn(|_| None)); + let [xn, down, activated, gates, products, mixed] = + outputs.map(|outputs| outputs.map(Some)).unwrap_or_else(|| std::array::from_fn(|_| None)); let read_inject = self.read_inject.take().map(|slot| slot.into_inner()); let [block, inject, candidate] = self .injection @@ -210,11 +162,7 @@ impl<'ctx> GrScratch<'ctx> { result } pub(in super::super) fn close(mut self) -> Result<()> { - let prior = if self.failed.get() { - Err(Error::CudaExecution) - } else { - Ok(()) - }; + let prior = if self.failed.get() { Err(Error::CudaExecution) } else { Ok(()) }; let cleanup = self.release_owned(); prior?; cleanup @@ -235,9 +183,7 @@ impl GrRead<'_, '_> { return Err(Error::IdentityMismatch); } if let Some(scratch) = &self.scratch - && result - .as_ref() - .is_err_and(|error| *error == Error::CudaExecution) + && result.as_ref().is_err_and(|error| *error == Error::CudaExecution) { scratch.failed.set(true); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/download_f32_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/download_f32_fn.rs index 7eea2796..b61d48c5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/download_f32_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/download_f32_fn.rs @@ -6,27 +6,19 @@ use super::*; pub(super) fn download_f32(buffer: &DeviceBuffer<'_>, count: usize) -> Result> { let byte_count = count.checked_mul(4).ok_or(Error::Overflow)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(byte_count) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(byte_count).map_err(|_| Error::InputAllocation)?; bytes.resize(byte_count, 0); buffer.copy_to(&mut bytes).map_err(driver_error)?; let mut values = Vec::new(); - values - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - values.extend( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|chunk| f32::from_le_bytes(*chunk)), - ); + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|chunk| f32::from_le_bytes(*chunk))); validate_values(&values, count)?; Ok(values.into_boxed_slice()) } pub(super) fn driver_error(error: DriverError) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } #[cfg(test)] eprintln!("PUBLIC CUDA raw adapter=gr error={error:?}"); match error { @@ -89,9 +81,7 @@ impl GrStage { validate_layer(layer, binding.layer_count())?; let ready = read.ready(); ready.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; - ready - .identity() - .validate(txn.token(), txn.position(), layer)?; + ready.identity().validate(txn.token(), txn.position(), layer)?; validate_streams(ready.streams())?; validate_values(ready.mixed(), 2560)?; validate_values(&ready.inject, 4)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs index c196b338..1abe8d54 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_grstage.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl GrStage { pub(in super::super) fn apply<'cache, 'ctx>( binding: &ModelBinding, @@ -22,14 +21,7 @@ impl GrStage { return Err(Error::IdentityMismatch); } let identity = TokenLayer::new(input.token(), input.position(), layer); - Self::read( - binding, - GrRole::Attention(layer.get()), - identity, - input.streams().values(), - txn, - cache, - ) + Self::read(binding, GrRole::Attention(layer.get()), identity, input.streams().values(), txn, cache) } pub(in super::super) fn read_ffn<'cache, 'ctx>( @@ -40,17 +32,8 @@ impl GrStage { cache: Option<&'cache DenseWeightCache<'ctx>>, ) -> Result> { residual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; - residual - .identity - .validate(txn.token(), txn.position(), layer)?; - Self::read( - binding, - GrRole::Ffn(layer.get()), - residual.identity, - residual.streams(), - txn, - cache, - ) + residual.identity.validate(txn.token(), txn.position(), layer)?; + Self::read(binding, GrRole::Ffn(layer.get()), residual.identity, residual.streams(), txn, cache) } pub(in super::super) fn read_attention<'cache, 'ctx>( @@ -68,13 +51,8 @@ impl GrStage { } let previous = layer.get().checked_sub(1).ok_or(Error::IdentityMismatch)?; residual.validate_origin(&binding.identity(), GrRole::Ffn(previous))?; - let previous_layer = LayerId::new( - u64::from(previous), - Dimension::new(u64::from(binding.layer_count()))?, - )?; - residual - .identity - .validate(txn.token(), txn.position(), previous_layer)?; + let previous_layer = LayerId::new(u64::from(previous), Dimension::new(u64::from(binding.layer_count()))?)?; + residual.identity.validate(txn.token(), txn.position(), previous_layer)?; Self::read( binding, GrRole::Attention(layer.get()), @@ -98,16 +76,8 @@ impl GrStage { return Err(Error::IdentityMismatch); } ple.validate_origin(&binding.identity())?; - ple.identity() - .validate(txn.token(), txn.position(), layer)?; - Self::read( - binding, - GrRole::Attention(1), - ple.identity(), - ple.streams(), - txn, - cache, - ) + ple.identity().validate(txn.token(), txn.position(), layer)?; + Self::read(binding, GrRole::Attention(1), ple.identity(), ple.streams(), txn, cache) } pub(super) fn read<'cache, 'ctx>( @@ -128,18 +98,12 @@ impl GrStage { let weights = if let Some(r) = resident { r.weights.clone() } else { - std::rc::Rc::new(diagnose( - GrPhase::Weights, - binding.gr_weights(role).map_err(binding_error), - )?) + std::rc::Rc::new(diagnose(GrPhase::Weights, binding.gr_weights(role).map_err(binding_error))?) }; if !weights.matches(&binding.identity(), role) { return Err(Error::IdentityMismatch); } - let gpu = cache - .zip(resident) - .map(|(c, r)| c.gr_buffers(r)) - .transpose()?; + let gpu = cache.zip(resident).map(|(c, r)| c.gr_buffers(r)).transpose()?; let mut scratch = cache.map(|c| c.gr_scratch(binding, context)).transpose()?; let candidate = if let Some(slot) = scratch.as_mut() { slot.write(&binding.identity(), context, streams)?; @@ -155,9 +119,7 @@ impl GrStage { }; let inject = candidate.inject.ok_or(Error::InvalidDimension)?; let mut saved = Vec::new(); - saved - .try_reserve_exact(streams.len()) - .map_err(|_| Error::InputAllocation)?; + saved.try_reserve_exact(streams.len()).map_err(|_| Error::InputAllocation)?; saved.extend_from_slice(streams); Ok(GrRead { ready: ResidualReady { @@ -180,50 +142,45 @@ impl GrStage { cache: Option<&DenseWeightCache<'_>>, ) -> Result> { txn.validate_binding(&binding.identity())?; - let last = binding - .layer_count() - .checked_sub(1) - .ok_or(Error::InvalidDimension)?; + let last = binding.layer_count().checked_sub(1).ok_or(Error::InvalidDimension)?; residual.validate_origin(&binding.identity(), GrRole::Ffn(last))?; validate_layer(residual.identity.layer(), binding.layer_count())?; - residual - .identity - .validate(txn.token(), txn.position(), residual.identity.layer())?; + residual.identity.validate(txn.token(), txn.position(), residual.identity.layer())?; diagnose(GrPhase::Inputs, validate_streams(residual.streams()))?; let context = txn.cuda_context()?; - Self::final_mix_values(binding,context,residual.streams(),cache) + Self::final_mix_values(binding, context, residual.streams(), cache) } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn final_mix_original_prompt( - binding:&ModelBinding,completed:&super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>,cache:&DenseWeightCache<'_>, - )->Result>{ + binding: &ModelBinding, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + cache: &DenseWeightCache<'_>, + ) -> Result> { txn.validate_final(completed)?; - let streams=completed.streams()?; - diagnose(GrPhase::Inputs,validate_streams(streams))?; - Self::final_mix_values(binding,txn.context()?,streams,Some(cache)) + let streams = completed.streams()?; + diagnose(GrPhase::Inputs, validate_streams(streams))?; + Self::final_mix_values(binding, txn.context()?, streams, Some(cache)) } - pub(super) fn final_mix_values(binding:&ModelBinding,context:&Context<'_>,streams:&[f32], - cache:Option<&DenseWeightCache<'_>>)->Result> { + pub(super) fn final_mix_values( + binding: &ModelBinding, + context: &Context<'_>, + streams: &[f32], + cache: Option<&DenseWeightCache<'_>>, + ) -> Result> { admit_budget(context, READ_DEVICE_BYTES)?; let resident = cache.map(|c| c.gr(binding, GrRole::Final)).transpose()?; let weights = if let Some(r) = resident { r.weights.clone() } else { - std::rc::Rc::new(diagnose( - GrPhase::Weights, - binding.gr_weights(GrRole::Final).map_err(binding_error), - )?) + std::rc::Rc::new(diagnose(GrPhase::Weights, binding.gr_weights(GrRole::Final).map_err(binding_error))?) }; if !weights.matches(&binding.identity(), GrRole::Final) || weights.inject().is_some() { return Err(Error::IdentityMismatch); } - let gpu = cache - .zip(resident) - .map(|(c, r)| c.gr_buffers(r)) - .transpose()?; + let gpu = cache.zip(resident).map(|(c, r)| c.gr_buffers(r)).transpose()?; let candidate = read_cuda(context, &weights, streams, true, gpu)?; if candidate.inject.is_some() { return Err(Error::IdentityMismatch); @@ -248,8 +205,7 @@ impl GrStage { { return Err(Error::IdentityMismatch); } - read.identity - .validate(txn.token(), txn.position(), read.identity.layer())?; + read.identity.validate(txn.token(), txn.position(), read.identity.layer())?; if block_identity != read.identity { return Err(Error::IdentityMismatch); } @@ -265,21 +221,14 @@ impl GrStage { scratch.buffer(context)?; let read = &owner.ready; let values = inject_cached_cuda(context, scratch, block_out, &read.inject)?; - return InjectedResidual::from_candidates( - read.identity, - read.binding.clone(), - read.role, - values, - ); + return InjectedResidual::from_candidates(read.identity, read.binding.clone(), read.role, values); } admit_budget(context, 2 * 40960 + 10240 + 16)?; let residual = upload_f32(context, &read.streams)?; let output = upload_f32(context, block_out)?; let inject = upload_f32(context, &read.inject)?; let mut candidate = context.allocate(40960).map_err(driver_error)?; - context - .gr_inject_residual_f32(&residual, &output, &inject, &mut candidate) - .map_err(driver_error)?; + context.gr_inject_residual_f32(&residual, &output, &inject, &mut candidate).map_err(driver_error)?; let values = download_f32(&candidate, 10240)?; for buffer in [candidate, inject, output, residual] { buffer.release().map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_residualready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_residualready.rs index 38453b29..9709966a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_residualready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/impl_residualready.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl ResidualReady { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super) fn oracle_inject(&self) -> &[f32; 4] { @@ -32,17 +31,11 @@ impl InjectedResidual { role: GrRole, streams: Box<[f32]>, ) -> Result { - if !matches!(role, GrRole::Attention(layer) | GrRole::Ffn(layer) if layer == identity.layer().get()) - { + if !matches!(role, GrRole::Attention(layer) | GrRole::Ffn(layer) if layer == identity.layer().get()) { return Err(Error::IdentityMismatch); } validate_streams(&streams)?; - Ok(Self { - identity, - binding, - role, - streams, - }) + Ok(Self { identity, binding, role, streams }) } pub(in super::super) fn validate_origin(&self, binding: &BindingIdentity, role: GrRole) -> Result<()> { if !self.binding.matches(binding) || self.role != role { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs index 6102ef27..3f175ac8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu.rs @@ -6,33 +6,20 @@ use leleka_cuda_driver::Driver; #[test] #[ignore = "Root-only changed persistent GR outputs, no model/old-suite replay"] fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GR_OUTPUT_WORKSPACE").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GR_OUTPUT_WORKSPACE").as_deref(), Ok("yes")); let driver = Driver::load().expect("actual driver"); let device = driver.device(0).expect("device"); - let context = device - .create_context(160 * 1024 * 1024) - .expect("bounded context"); - let foreign = device - .create_context(160 * 1024 * 1024) - .expect("foreign context"); + let context = device.create_context(160 * 1024 * 1024).expect("bounded context"); + let foreign = device.create_context(160 * 1024 * 1024).expect("foreign context"); let binding = BindingIdentity::test_identity(); // CPU owner tag, NOT actual ModelBinding. let failed = Rc::new(Cell::new(false)); let mut scratch = None; let mut matrices = Vec::new(); let operation: Result<(usize, usize, usize)> = (|| { - scratch = Some(RefCell::new(GrScratch::new_identity( - binding.clone(), - &context, - failed.clone(), - )?)); + scratch = Some(RefCell::new(GrScratch::new_identity(binding.clone(), &context, failed.clone())?)); matrices.push(upload_f32(&context, &vec![1.0; 10240])?); for (count, seed) in [(3276800, 0), (3276800, 1), (40960, 2)] { - let values: Vec = (0..count) - .map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }) - .collect(); + let values: Vec = (0..count).map(|i| if (i + seed) % 3 == 0 { 0x3b00 } else { 0xbb00 }).collect(); matrices.push(upload_bf16(&context, &values)?); } let cell = scratch.as_ref().ok_or(Error::CudaExecution)?; @@ -43,30 +30,15 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { for pattern in [0, 1, 1, 2] { let mut lease = cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; lease.write(&binding, &context, &streams(pattern))?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; + let weights: &[DeviceBuffer<'_>; 4] = + matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; let block = block(pattern); - let expected_injected = fresh_inject( - &context, - lease.buffer(&context)?, - &block, - &coefficients(&expected)?, - )?; + let expected_injected = fresh_inject(&context, lease.buffer(&context)?, &block, &coefficients(&expected)?)?; // Poison every retained byte BEFORE candidate, proving all // six fixed outputs overwrite rather than reuse old results. - for buffer in lease - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; + for buffer in lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; } lease .read_inject @@ -75,67 +47,35 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { .borrow_mut() .copy_from(&f32::NAN.to_le_bytes().repeat(4)) .map_err(driver_error)?; - for buffer in lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; + for buffer in lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; } let actual = read_cached_cuda( &context, 1e-6, true, &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], )?; let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); for (buffer, expected) in outputs.iter().zip(&expected) { let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); + differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); words += bytes.len() / 4; } let mixed: Vec = actual.mixed.iter().flat_map(|v| v.to_le_bytes()).collect(); if mixed != expected[5] { differences += 1; } - let injected: Vec = actual - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injected - .chunks_exact(4) - .zip(expected[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); + let injected: Vec = + actual.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); + differences += injected.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); words += 4; - let injected = inject_cached_cuda( - &context, - &lease, - &block, - &actual.inject.ok_or(Error::InvalidDimension)?, - )?; - differences += injected - .iter() - .zip(expected_injected.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + let injected = + inject_cached_cuda(&context, &lease, &block, &actual.inject.ok_or(Error::InvalidDimension)?)?; + differences += + injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); words += injected.len(); if cell.try_borrow_mut().is_ok() || context.allocated_bytes() != charged { differences += 1; @@ -147,35 +87,20 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { } let mut lease = cell.borrow_mut(); let before = context.allocated_bytes(); - for (owner, ctx) in [ - (&BindingIdentity::test_identity(), &context), - (&binding, &foreign), - ] { + for (owner, ctx) in [(&BindingIdentity::test_identity(), &context), (&binding, &foreign)] { if lease.write(owner, ctx, &streams(1)) != Err(Error::IdentityMismatch) { differences += 1; } guards += 1; } - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; - let held = lease - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); + let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; + let held = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); if read_cached_cuda( &context, 1e-6, true, &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], ) .err() != Some(Error::IdentityMismatch) @@ -186,29 +111,14 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { drop(held); let mut gamma = vec![1.0f32; 10240]; gamma[10239] = f32::NAN; - matrices[0] - .copy_from( - &gamma - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>(), - ) - .map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; + matrices[0].copy_from(&gamma.iter().flat_map(|v| v.to_le_bytes()).collect::>()).map_err(driver_error)?; + let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; if read_cached_cuda( &context, 1e-6, true, &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], ) .err() != Some(Error::NonFinite) @@ -217,90 +127,47 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { differences += 1; } guards += 1; - matrices[0] - .copy_from(&1.0f32.to_le_bytes().repeat(10240)) - .map_err(driver_error)?; - let weights: &[DeviceBuffer<'_>; 4] = matrices - .as_slice() - .try_into() - .map_err(|_| Error::InvalidDimension)?; + matrices[0].copy_from(&1.0f32.to_le_bytes().repeat(10240)).map_err(driver_error)?; + let weights: &[DeviceBuffer<'_>; 4] = matrices.as_slice().try_into().map_err(|_| Error::InvalidDimension)?; lease.write(&binding, &context, &streams(3))?; let expected = fresh_read(&context, lease.buffer(&context)?, weights)?; let block = block(3); - let expected_injected = fresh_inject( - &context, - lease.buffer(&context)?, - &block, - &coefficients(&expected)?, - )?; + let expected_injected = fresh_inject(&context, lease.buffer(&context)?, &block, &coefficients(&expected)?)?; let recovered = read_cached_cuda( &context, 1e-6, true, &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], )?; let outputs = lease.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); for (buffer, expected) in outputs.iter().zip(&expected) { let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); + differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); words += bytes.len() / 4; } - let injection: Vec = recovered - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injection - .chunks_exact(4) - .zip(expected[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); + let injection: Vec = + recovered.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); + differences += injection.chunks_exact(4).zip(expected[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); words += 4; drop(outputs); - let actual_injected = inject_cached_cuda( - &context, - &lease, - &block, - &recovered.inject.ok_or(Error::InvalidDimension)?, - )?; - differences += actual_injected - .iter() - .zip(expected_injected.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + let actual_injected = + inject_cached_cuda(&context, &lease, &block, &recovered.inject.ok_or(Error::InvalidDimension)?)?; + differences += + actual_injected.iter().zip(expected_injected.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); words += actual_injected.len(); if context.allocated_bytes() != before { differences += 1; } guards += 1; - let held = lease - .read_inject - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); + let held = lease.read_inject.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); if read_cached_cuda( &context, 1e-6, true, &lease, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], ) .err() != Some(Error::IdentityMismatch) @@ -309,11 +176,7 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { } guards += 1; drop(held); - let held = lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut(); + let held = lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut(); if inject_cached_cuda(&context, &lease, &block, &coefficients(&expected)?).err() != Some(Error::IdentityMismatch) { @@ -321,14 +184,7 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { } guards += 1; drop(held); - let before_refusal = download_f32( - &lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; + let before_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; if inject_cached_cuda(&context, &lease, &block[..2559], &coefficients(&expected)?).err() != Some(Error::InvalidDimension) { @@ -337,29 +193,17 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { guards += 1; let mut invalid = block.clone(); invalid[2559] = f32::NAN; - if inject_cached_cuda(&context, &lease, &invalid, &coefficients(&expected)?).err() - != Some(Error::NonFinite) + if inject_cached_cuda(&context, &lease, &invalid, &coefficients(&expected)?).err() != Some(Error::NonFinite) || failed.get() { differences += 1; } guards += 1; - let after_refusal = download_f32( - &lease - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; - differences += before_refusal - .iter() - .zip(after_refusal.iter()) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + let after_refusal = download_f32(&lease.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; + differences += + before_refusal.iter().zip(after_refusal.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); for pattern in [0, 1, 1, 2] { - let (checked, different) = - check_handoff(&mut lease, &context, &binding, weights, pattern)?; + let (checked, different) = check_handoff(&mut lease, &context, &binding, weights, pattern)?; words += checked; differences += different; if context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() { @@ -371,18 +215,10 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { let input = streams(1); let block = self::block(1); let coefficients = [0.5, -0.25, 0.0, 1.0]; - for (ctx, current, expected) in [ - (&foreign, &block[..], Error::IdentityMismatch), - (&context, &block[..2559], Error::InvalidDimension), - ] { - if retained_handoff::inject_replace_residual( - &mut lease, - ctx, - &input, - current, - &coefficients, - ) - .err() + for (ctx, current, expected) in + [(&foreign, &block[..], Error::IdentityMismatch), (&context, &block[..2559], Error::InvalidDimension)] + { + if retained_handoff::inject_replace_residual(&mut lease, ctx, &input, current, &coefficients).err() != Some(expected) { differences += 1; @@ -391,44 +227,26 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { } let mut invalid = block.clone(); invalid[2559] = f32::NAN; - if retained_handoff::inject_replace_residual( - &mut lease, - &context, - &input, - &invalid, - &coefficients, - ) - .err() + if retained_handoff::inject_replace_residual(&mut lease, &context, &input, &invalid, &coefficients).err() != Some(Error::NonFinite) { differences += 1; } guards += 1; let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += sentinel - .iter() - .zip(&after) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + differences += sentinel.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); words += 10240; // Valid finite inputs producing a genuinely nonfinite output must // refuse BEFORE the residual swap; the current input remains. let overflow = vec![f32::MAX; 2560]; - if retained_handoff::inject_replace_residual( - &mut lease, &context, &input, &overflow, &[20.0; 4], - ) - .err() + if retained_handoff::inject_replace_residual(&mut lease, &context, &input, &overflow, &[20.0; 4]).err() != Some(Error::NonFinite) || failed.get() { differences += 1; } let after = download_f32(lease.buffer(&context)?, 10240)?; - differences += input - .iter() - .zip(&after) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + differences += input.iter().zip(&after).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); words += 10240; guards += 1; // Abort exposes no readiness capability. Next actual call fully @@ -479,14 +297,14 @@ fn original_first_fixed_outputs_repeat_overwrite_abort_and_cleanup() { mod fresh_read_fn; #[allow(unused_imports)] -use fresh_read_fn::fresh_read; -#[allow(unused_imports)] -use fresh_read_fn::fresh_inject; -#[allow(unused_imports)] use fresh_read_fn::block; #[allow(unused_imports)] use fresh_read_fn::coefficients; #[allow(unused_imports)] +use fresh_read_fn::fresh_inject; +#[allow(unused_imports)] +use fresh_read_fn::fresh_read; +#[allow(unused_imports)] use fresh_read_fn::streams; mod check_handoff_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs index 520a24f3..2fbdb1b8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/check_handoff_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn check_handoff<'ctx>( scratch: &mut GrScratch<'ctx>, context: &'ctx Context<'ctx>, @@ -20,16 +19,8 @@ pub(super) fn check_handoff<'ctx>( let reference = fresh_inject(context, scratch.buffer(context)?, &block, &coefficients)?; scratch.write(binding, context, &reference)?; let reference_ffn = fresh_read(context, scratch.buffer(context)?, weights)?; - for buffer in scratch - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; + for buffer in scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; } scratch .read_inject @@ -38,44 +29,15 @@ pub(super) fn check_handoff<'ctx>( .borrow_mut() .copy_from(&f32::NAN.to_le_bytes().repeat(4)) .map_err(driver_error)?; - for buffer in scratch - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow_mut() - .iter_mut() - { - buffer - .copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)) - .map_err(driver_error)?; + for buffer in scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow_mut().iter_mut() { + buffer.copy_from(&f32::NAN.to_le_bytes().repeat(buffer.len() / 4)).map_err(driver_error)?; } - let actual = retained_handoff::inject_replace_residual( - scratch, - context, - &input, - &block, - &coefficients, - )?; + let actual = retained_handoff::inject_replace_residual(scratch, context, &input, &block, &coefficients)?; let resident = download_f32(scratch.buffer(context)?, 10240)?; - let previous = download_f32( - &scratch - .injection - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow()[2], - 10240, - )?; + let previous = download_f32(&scratch.injection.as_ref().ok_or(Error::CudaExecution)?.borrow()[2], 10240)?; let mut differences = 0; - for (left, right) in [ - (&actual[..], &reference[..]), - (&resident[..], &reference[..]), - (&previous[..], &input[..]), - ] { - differences += left - .iter() - .zip(right) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + for (left, right) in [(&actual[..], &reference[..]), (&resident[..], &reference[..]), (&previous[..], &input[..])] { + differences += left.iter().zip(right).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); } // No host residual upload: the actual swapped producer feeds FFN. let ffn = read_cached_cuda( @@ -83,45 +45,17 @@ pub(super) fn check_handoff<'ctx>( 1e-6, true, scratch, - [ - Some(&weights[0]), - Some(&weights[1]), - Some(&weights[2]), - Some(&weights[3]), - ], + [Some(&weights[0]), Some(&weights[1]), Some(&weights[2]), Some(&weights[3])], )?; - let outputs = scratch - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .borrow(); + let outputs = scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.borrow(); for (buffer, expected) in outputs.iter().zip(&reference_ffn) { let mut bytes = vec![0; buffer.len()]; buffer.copy_to(&mut bytes).map_err(driver_error)?; - differences += bytes - .chunks_exact(4) - .zip(expected.chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); + differences += bytes.chunks_exact(4).zip(expected.chunks_exact(4)).filter(|(a, b)| a != b).count(); } - let injected: Vec = ffn - .inject - .ok_or(Error::InvalidDimension)? - .into_iter() - .flat_map(f32::to_le_bytes) - .collect(); - differences += injected - .chunks_exact(4) - .zip(reference_ffn[6].chunks_exact(4)) - .filter(|(a, b)| a != b) - .count(); - if ffn - .mixed - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - != reference_ffn[5] - { + let injected: Vec = ffn.inject.ok_or(Error::InvalidDimension)?.into_iter().flat_map(f32::to_le_bytes).collect(); + differences += injected.chunks_exact(4).zip(reference_ffn[6].chunks_exact(4)).filter(|(a, b)| a != b).count(); + if ffn.mixed.iter().flat_map(|v| v.to_le_bytes()).collect::>() != reference_ffn[5] { differences += 1; } Ok((3 * 10240 + GR_OUTPUT_DEVICE_BYTES / 4 + 4, differences)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs index 5ea7dbbc..0ee0a779 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/output_workspace_gpu/fresh_read_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn fresh_read( context: &Context<'_>, residual: &DeviceBuffer<'_>, @@ -16,8 +15,7 @@ pub(super) fn fresh_read( for bytes in GR_OUTPUT_BYTES.into_iter().chain([16]) { owned.push(context.allocate(bytes).map_err(driver_error)?); } - let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() - else { + let [xn, down, activated, gates, products, mixed, injection] = owned.as_mut_slice() else { return Err(Error::InvalidDimension); }; let mask = context @@ -38,9 +36,7 @@ pub(super) fn fresh_read( if mask != 0 { return Err(Error::NonFinite); } - context - .gr_inject_projection_bf16_f32(&weights[3], xn, injection) - .map_err(driver_error)?; + context.gr_inject_projection_bf16_f32(&weights[3], xn, injection).map_err(driver_error)?; owned .iter() .map(|buffer| { @@ -77,9 +73,7 @@ pub(super) fn fresh_inject( let [block, coefficients, candidate] = owned.as_mut_slice() else { return Err(Error::InvalidDimension); }; - context - .gr_inject_residual_f32(residual, block, coefficients, candidate) - .map_err(driver_error)?; + context.gr_inject_residual_f32(residual, block, coefficients, candidate).map_err(driver_error)?; download_f32(candidate, 10240) })(); let mut cleanup = Ok(()); @@ -97,11 +91,7 @@ pub(super) fn fresh_inject( pub(super) fn block(pattern: usize) -> Vec { (0..2560) .map(|i| { - if pattern == 0 { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - ((i % (13 + pattern)) as f32 - 6.0) / 128.0 - } + if pattern == 0 { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i % (13 + pattern)) as f32 - 6.0) / 128.0 } }) .collect() } @@ -111,23 +101,13 @@ pub(super) fn coefficients(expected: &[Vec]) -> Result<[f32; 4]> { if bytes.len() != 16 { return Err(Error::InvalidDimension); } - Ok(std::array::from_fn(|i| { - f32::from_le_bytes( - bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed four bytes"), - ) - })) + Ok(std::array::from_fn(|i| f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("fixed four bytes")))) } pub(super) fn streams(pattern: usize) -> Vec { (0..10240) .map(|i| { - if pattern == 0 { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - ((i % (19 + pattern)) as f32 - 9.0) / 64.0 - } + if pattern == 0 { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i % (19 + pattern)) as f32 - 9.0) / 64.0 } }) .collect() } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cached_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cached_cuda_fn.rs index 7069651d..d92e1acc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cached_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cached_cuda_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn read_cached_cuda( context: &Context<'_>, epsilon: f32, @@ -12,19 +11,14 @@ pub(super) fn read_cached_cuda( resident: [Option<&DeviceBuffer<'_>>; 4], ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); let gamma = resident[0].ok_or(Error::IdentityMismatch)?; let down_weights = resident[1].ok_or(Error::IdentityMismatch)?; let up_weights = resident[2].ok_or(Error::IdentityMismatch)?; scratch.buffer(context)?; - let mut outputs = scratch - .outputs - .as_ref() - .ok_or(Error::CudaExecution)? - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut outputs = + scratch.outputs.as_ref().ok_or(Error::CudaExecution)?.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; for (buffer, bytes) in outputs.iter().zip(GR_OUTPUT_BYTES) { if buffer.len() != bytes { return Err(Error::InvalidDimension); @@ -75,29 +69,16 @@ pub(super) fn read_cached_cuda( let matrix = resident[3].ok_or(Error::IdentityMismatch)?; diagnose( GrPhase::InjectProjection, - context - .gr_inject_projection_bf16_f32(matrix, xn, &mut output) - .map_err(driver_error), + context.gr_inject_projection_bf16_f32(matrix, xn, &mut output).map_err(driver_error), )?; let values = diagnose(GrPhase::InjectProjection, download_f32(&output, 4))?; - Some( - values - .as_ref() - .try_into() - .map_err(|_| Error::InvalidDimension)?, - ) + Some(values.as_ref().try_into().map_err(|_| Error::InvalidDimension)?) } else { None }; - Ok(ReadCandidate { - mixed: mixed_values, - inject: inject_values, - }) + Ok(ReadCandidate { mixed: mixed_values, inject: inject_values }) })(); - if result - .as_ref() - .is_err_and(|error| *error == Error::CudaExecution) - { + if result.as_ref().is_err_and(|error| *error == Error::CudaExecution) { scratch.failed.set(true); } result @@ -110,9 +91,8 @@ pub(super) fn inject_cached_cuda( inject_values: &[f32; 4], ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); // Preserve the original admission reserve; the actual buffers are eager. admit_budget(context, 40960 + 10240 + 16)?; scratch.buffer(context)?; @@ -135,9 +115,7 @@ pub(super) fn inject_cached_cuda( // reuse only, not a host/device numeric certificate or cache hit. copy_cached_f32(block, block_out, &scratch.failed)?; copy_cached_f32(inject, inject_values, &scratch.failed)?; - context - .gr_inject_residual_f32(scratch.buffer(context)?, block, inject, candidate) - .map_err(driver_error)?; + context.gr_inject_residual_f32(scratch.buffer(context)?, block, inject, candidate).map_err(driver_error)?; download_f32(candidate, 10240) })(); if matches!(result, Err(Error::CudaExecution)) { @@ -146,19 +124,13 @@ pub(super) fn inject_cached_cuda( result } -pub(super) fn copy_cached_f32( - buffer: &mut DeviceBuffer<'_>, - values: &[f32], - failed: &Cell, -) -> Result<()> { +pub(super) fn copy_cached_f32(buffer: &mut DeviceBuffer<'_>, values: &[f32], failed: &Cell) -> Result<()> { let byte_count = values.len().checked_mul(4).ok_or(Error::Overflow)?; if byte_count != buffer.len() { return Err(Error::InvalidDimension); } let mut bytes = Vec::new(); - bytes - .try_reserve_exact(byte_count) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(byte_count).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -175,9 +147,7 @@ pub(super) fn upload_cached_f32<'ctx>( failed: &Cell, ) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -203,20 +173,14 @@ pub(super) fn release_all(buffers: [Option>; N] } pub(super) fn admit_budget(context: &Context<'_>, required: usize) -> Result<()> { - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|total| total > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(required).is_none_or(|total| total > context.budget_bytes()) { return Err(Error::InputAllocation); } Ok(()) } pub(super) fn upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -226,9 +190,7 @@ pub(super) fn upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> Re } pub(super) fn upload_bf16<'ctx>(context: &'ctx Context<'_>, values: &[u16]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cuda_fn.rs index e065a77a..06c61fad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/read_cuda_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn read_cuda( context: &Context<'_>, weights: &GrWeights, @@ -12,129 +11,64 @@ pub(super) fn read_cuda( resident: Option<[Option<&DeviceBuffer<'_>>; 4]>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); let residual = upload_f32(context, streams)?; - let gamma_owned = if resident.is_none() { - Some(upload_f32(context, weights.norm())?) - } else { - None - }; - let down_owned = if resident.is_none() { - Some(upload_bf16(context, weights.down())?) - } else { - None - }; - let up_owned = if resident.is_none() { - Some(upload_bf16(context, weights.up())?) - } else { - None - }; - let gamma = resident - .and_then(|v| v[0]) - .or(gamma_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let down_weights = resident - .and_then(|v| v[1]) - .or(down_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let up_weights = resident - .and_then(|v| v[2]) - .or(up_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; + let gamma_owned = if resident.is_none() { Some(upload_f32(context, weights.norm())?) } else { None }; + let down_owned = if resident.is_none() { Some(upload_bf16(context, weights.down())?) } else { None }; + let up_owned = if resident.is_none() { Some(upload_bf16(context, weights.up())?) } else { None }; + let gamma = resident.and_then(|v| v[0]).or(gamma_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let down_weights = resident.and_then(|v| v[1]).or(down_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let up_weights = resident.and_then(|v| v[2]).or(up_owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut xn = context.allocate(40960).map_err(driver_error)?; let mut down = context.allocate(1280).map_err(driver_error)?; let mut activated = context.allocate(1280).map_err(driver_error)?; let mut gates = context.allocate(40960).map_err(driver_error)?; let mut products = context.allocate(40960).map_err(driver_error)?; let mut mixed = context.allocate(10240).map_err(driver_error)?; - diagnose( - GrPhase::Norm, - context - .gr_norm_f32(&residual, gamma, weights.epsilon(), &mut xn) - .map_err(driver_error), - )?; + diagnose(GrPhase::Norm, context.gr_norm_f32(&residual, gamma, weights.epsilon(), &mut xn).map_err(driver_error))?; let xn_values = diagnose(GrPhase::Norm, download_f32(&xn, 10240))?; - diagnose( - GrPhase::Down, - context - .gr_down_projection_bf16_f32(down_weights, &xn, &mut down) - .map_err(driver_error), - )?; + diagnose(GrPhase::Down, context.gr_down_projection_bf16_f32(down_weights, &xn, &mut down).map_err(driver_error))?; let down_values = diagnose(GrPhase::Down, download_f32(&down, 320))?; diagnose_extrema( GrPhase::Silu, - context - .gr_down_silu_hc_f32(&down, &mut activated) - .map_err(driver_error), + context.gr_down_silu_hc_f32(&down, &mut activated).map_err(driver_error), &down_values, )?; diagnose_extrema(GrPhase::Silu, download_f32(&activated, 320), &down_values)?; drop(down_values); - diagnose( - GrPhase::Up, - context - .gr_up_projection_bf16_f32(up_weights, &activated, &mut gates) - .map_err(driver_error), - )?; + diagnose(GrPhase::Up, context.gr_up_projection_bf16_f32(up_weights, &activated, &mut gates).map_err(driver_error))?; let gate_values = diagnose(GrPhase::Up, download_f32(&gates, 10240))?; if final_mix { diagnose_extrema( GrPhase::GateProducts, - context - .gr_gate_mean_final_unfused_f32(&xn, &gates, &mut products, &mut mixed) - .map_err(driver_error), + context.gr_gate_mean_final_unfused_f32(&xn, &gates, &mut products, &mut mixed).map_err(driver_error), &gate_values, )?; } else { diagnose_extrema( GrPhase::GateProducts, - context - .gr_gate_mean_layer_fused_f32(&xn, &gates, &mut products, &mut mixed) - .map_err(driver_error), + context.gr_gate_mean_layer_fused_f32(&xn, &gates, &mut products, &mut mixed).map_err(driver_error), &gate_values, )?; } - diagnose_extrema( - GrPhase::GateProducts, - download_f32(&products, 10240), - &gate_values, - )?; + diagnose_extrema(GrPhase::GateProducts, download_f32(&products, 10240), &gate_values)?; drop(gate_values); let mixed_values = diagnose(GrPhase::GateMixed, download_f32(&mixed, 2560))?; let inject_values = if let Some(values) = weights.inject() { if final_mix { return Err(Error::IdentityMismatch); } - let owned = if resident.is_none() { - Some(upload_bf16(context, values)?) - } else { - None - }; - let matrix = resident - .and_then(|v| v[3]) - .or(owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; + let owned = if resident.is_none() { Some(upload_bf16(context, values)?) } else { None }; + let matrix = resident.and_then(|v| v[3]).or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut output = context.allocate(16).map_err(driver_error)?; diagnose_extrema( GrPhase::InjectProjection, - context - .gr_inject_projection_bf16_f32(matrix, &xn, &mut output) - .map_err(driver_error), + context.gr_inject_projection_bf16_f32(matrix, &xn, &mut output).map_err(driver_error), &xn_values, )?; - let values = diagnose_extrema( - GrPhase::InjectProjection, - download_f32(&output, 4), - &xn_values, - )?; - let result = Some( - values - .as_ref() - .try_into() - .map_err(|_| Error::InvalidDimension)?, - ); + let values = diagnose_extrema(GrPhase::InjectProjection, download_f32(&output, 4), &xn_values)?; + let result = Some(values.as_ref().try_into().map_err(|_| Error::InvalidDimension)?); output.release().map_err(driver_error)?; if let Some(v) = owned { v.release().map_err(driver_error)?; @@ -151,8 +85,5 @@ pub(super) fn read_cuda( for v in [gamma_owned, down_owned, up_owned].into_iter().flatten() { v.release().map_err(driver_error)?; } - Ok(ReadCandidate { - mixed: mixed_values, - inject: inject_values, - }) + Ok(ReadCandidate { mixed: mixed_values, inject: inject_values }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs index 6b9b5f25..813a3a55 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr/tests.rs @@ -7,22 +7,13 @@ fn gr_preflight_keeps_all_inputs_unchanged_on_shape_or_numeric_refusal() { let mut values = vec![-0.0_f32; 4 * 2560]; let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); assert_eq!(validate_streams(&values), Ok(())); - assert_eq!( - validate_streams(&values[..values.len() - 1]), - Err(Error::InvalidDimension) - ); - assert_eq!( - values.iter().map(|v| v.to_bits()).collect::>(), - before - ); + assert_eq!(validate_streams(&values[..values.len() - 1]), Err(Error::InvalidDimension)); + assert_eq!(values.iter().map(|v| v.to_bits()).collect::>(), before); for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { values[10239] = invalid; let before: Vec<_> = values.iter().map(|v| v.to_bits()).collect(); assert_eq!(validate_streams(&values), Err(Error::NonFinite)); - assert_eq!( - values.iter().map(|v| v.to_bits()).collect::>(), - before - ); + assert_eq!(values.iter().map(|v| v.to_bits()).collect::>(), before); } } @@ -59,10 +50,7 @@ fn gr_candidate_quiet_nan_refuses_late_failure_without_stream_publication() { ), Err(Error::NonFinite) )); - assert_eq!( - caller.iter().map(|v| v.to_bits()).collect::>(), - before - ); + assert_eq!(caller.iter().map(|v| v.to_bits()).collect::>(), before); let accepted = InjectedResidual::from_candidates( identity(), BindingIdentity::test_identity(), @@ -70,14 +58,7 @@ fn gr_candidate_quiet_nan_refuses_late_failure_without_stream_publication() { caller.into_boxed_slice(), ) .unwrap(); - assert_eq!( - accepted - .streams() - .iter() - .map(|v| v.to_bits()) - .collect::>(), - before - ); + assert_eq!(accepted.streams().iter().map(|v| v.to_bits()).collect::>(), before); assert_eq!(accepted.identity(), identity()); } @@ -92,28 +73,14 @@ fn gr_injected_capability_refuses_cross_model_or_wrong_stage_before_read() { vec![-0.0; 10240].into_boxed_slice(), ) .unwrap(); - assert_eq!( - residual.validate_origin(&binding, GrRole::Attention(0)), - Ok(()) - ); + assert_eq!(residual.validate_origin(&binding, GrRole::Attention(0)), Ok(())); for wrong in [GrRole::Ffn(0), GrRole::Attention(1), GrRole::Final] { - assert_eq!( - residual.validate_origin(&binding, wrong), - Err(Error::IdentityMismatch) - ); + assert_eq!(residual.validate_origin(&binding, wrong), Err(Error::IdentityMismatch)); } - assert_eq!( - residual.validate_origin(&other, GrRole::Attention(0)), - Err(Error::IdentityMismatch) - ); + assert_eq!(residual.validate_origin(&other, GrRole::Attention(0)), Err(Error::IdentityMismatch)); for role in [GrRole::Attention(1), GrRole::Ffn(1), GrRole::Final] { assert!(matches!( - InjectedResidual::from_candidates( - identity(), - binding.clone(), - role, - vec![0.0; 10240].into_boxed_slice() - ), + InjectedResidual::from_candidates(identity(), binding.clone(), role, vec![0.0; 10240].into_boxed_slice()), Err(Error::IdentityMismatch) )); } @@ -129,10 +96,7 @@ fn gr_candidate_norm_overflow_oracle_distinguishes_masked_finite_zero() { let masked_native = (1.0 / (square / 2560.0).sqrt()) * large; assert_eq!(masked_native.to_bits(), 0); assert_eq!(validate_streams(&vec![masked_native; 4 * 2560]), Ok(())); - assert_eq!( - validate_streams(&vec![f32::from_bits(0x7fc0_0000); 4 * 2560]), - Err(Error::NonFinite) - ); + assert_eq!(validate_streams(&vec![f32::from_bits(0x7fc0_0000); 4 * 2560]), Err(Error::NonFinite)); assert!((1.0_f32 / 0.0_f32.sqrt()).is_infinite()); } @@ -147,9 +111,6 @@ fn gr_candidate_postop_overflow_oracles_require_signal_not_masked_success() { let sum = product + product + product + product; assert!(sum.is_infinite()); for output in [f32::from_bits(0x7fc0_0000), sum, exponential] { - assert_eq!( - validate_streams(&vec![output; 4 * 2560]), - Err(Error::NonFinite) - ); + assert_eq!(validate_streams(&vec![output; 4 * 2560]), Err(Error::NonFinite)); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_attention_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_attention_chunk.rs index cd40cd06..8b06c886 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_attention_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_attention_chunk.rs @@ -6,15 +6,11 @@ pub(in crate::qwen_forward) struct DetachedGrRead { transport_failed: Option>>, } impl DetachedGrRead { -// The parent creates this only from the actual completed T-bank read. -// No caller-defined device/host association or ready boolean is admitted. -pub(super) fn from_micro_ready(ready: ResidualReady, failed: Rc>) -> Self { - Self { - ready, - injected: Cell::new(false), - transport_failed: Some(failed), + // The parent creates this only from the actual completed T-bank read. + // No caller-defined device/host association or ready boolean is admitted. + pub(super) fn from_micro_ready(ready: ResidualReady, failed: Rc>) -> Self { + Self { ready, injected: Cell::new(false), transport_failed: Some(failed) } } -} // Closed gr-parent-only interface for the retained handoff. No field or // caller-defined host/device association is exposed to sibling producers. pub(super) fn retained_handoff_available(&self) -> Result<()> { @@ -25,10 +21,7 @@ pub(super) fn from_micro_ready(ready: ResidualReady, failed: Rc>) -> } pub(super) fn validate_retained_transport(&self, expected: &Rc>) -> Result<()> { self.retained_handoff_available()?; - let actual = self - .transport_failed - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let actual = self.transport_failed.as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(actual, expected) { return Err(Error::IdentityMismatch); } @@ -39,22 +32,13 @@ pub(super) fn from_micro_ready(ready: ResidualReady, failed: Rc>) -> self.injected.set(true); Ok(()) } - pub(super) fn into_ffn_ready( - self, - binding: &ModelBinding, - txn: &mut QwenStepTxn, - ) -> Result { + pub(super) fn into_ffn_ready(self, binding: &ModelBinding, txn: &mut QwenStepTxn) -> Result { if self.injected.get() { return Err(Error::IdentityMismatch); } txn.validate_binding(&binding.identity())?; - self.ready.validate_origin( - &binding.identity(), - GrRole::Ffn(self.ready.identity.layer().get()), - )?; - self.ready - .identity - .validate(txn.token(), txn.position(), self.ready.identity.layer())?; + self.ready.validate_origin(&binding.identity(), GrRole::Ffn(self.ready.identity.layer().get()))?; + self.ready.identity.validate(txn.token(), txn.position(), self.ready.identity.layer())?; validate_streams(&self.ready.streams)?; validate_values(&self.ready.mixed, 2560)?; validate_values(&self.ready.inject, 4)?; @@ -63,10 +47,7 @@ pub(super) fn from_micro_ready(ready: ResidualReady, failed: Rc>) -> pub(in crate::qwen_forward) fn ready(&self) -> &ResidualReady { &self.ready } - pub(in crate::qwen_forward) fn finish( - &self, - result: Result, - ) -> Result { + pub(in crate::qwen_forward) fn finish(&self, result: Result) -> Result { if result.is_ok() && !self.injected.get() { return Err(Error::IdentityMismatch); } @@ -84,13 +65,8 @@ impl GrStage { } let ready = &owner.ready; txn.validate_binding(&binding.identity())?; - ready.validate_origin( - &binding.identity(), - GrRole::Attention(ready.identity.layer().get()), - )?; - ready - .identity - .validate(txn.token(), txn.position(), ready.identity.layer())?; + ready.validate_origin(&binding.identity(), GrRole::Attention(ready.identity.layer().get()))?; + ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?; validate_streams(&ready.streams)?; validate_values(&ready.mixed, 2560)?; validate_values(&ready.inject, 4)?; @@ -103,11 +79,7 @@ impl GrStage { // Move the actual producer; no float reconstruction. Dropping the // exclusive actor scratch lease retains its eagerly charged allocation. let transport_failed = owner.scratch.as_ref().map(|slot| Rc::clone(&slot.failed)); - Ok(DetachedGrRead { - ready: owner.ready, - injected: Cell::new(false), - transport_failed, - }) + Ok(DetachedGrRead { ready: owner.ready, injected: Cell::new(false), transport_failed }) } pub(in crate::qwen_forward) fn detach_ffn( binding: &ModelBinding, @@ -119,13 +91,8 @@ impl GrStage { } let ready = &owner.ready; txn.validate_binding(&binding.identity())?; - ready.validate_origin( - &binding.identity(), - GrRole::Ffn(ready.identity.layer().get()), - )?; - ready - .identity - .validate(txn.token(), txn.position(), ready.identity.layer())?; + ready.validate_origin(&binding.identity(), GrRole::Ffn(ready.identity.layer().get()))?; + ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?; validate_streams(&ready.streams)?; validate_values(&ready.mixed, 2560)?; validate_values(&ready.inject, 4)?; @@ -138,11 +105,7 @@ impl GrStage { // Move the actual producer; no float reconstruction. Dropping the // exclusive actor scratch lease retains its eagerly charged allocation. let transport_failed = owner.scratch.as_ref().map(|slot| Rc::clone(&slot.failed)); - Ok(DetachedGrRead { - ready: owner.ready, - injected: Cell::new(false), - transport_failed, - }) + Ok(DetachedGrRead { ready: owner.ready, injected: Cell::new(false), transport_failed }) } pub(in crate::qwen_forward) fn inject_detached( binding: &ModelBinding, @@ -156,13 +119,8 @@ impl GrStage { } let ready = &read.ready; txn.validate_binding(&binding.identity())?; - ready.validate_origin( - &binding.identity(), - GrRole::Attention(ready.identity.layer().get()), - )?; - ready - .identity - .validate(txn.token(), txn.position(), ready.identity.layer())?; + ready.validate_origin(&binding.identity(), GrRole::Attention(ready.identity.layer().get()))?; + ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?; if ready.identity != block_identity { return Err(Error::IdentityMismatch); } @@ -189,27 +147,16 @@ impl GrStage { ) .map_err(driver_error)?; let values = download_f32(candidate.as_ref().ok_or(Error::CudaExecution)?, 10240)?; - InjectedResidual::from_candidates( - ready.identity, - ready.binding.clone(), - ready.role, - values, - ) + InjectedResidual::from_candidates(ready.identity, ready.binding.clone(), ready.role, values) })(); let mut cleanup = Ok(()); - for buffer in [candidate, injection, output, residual] - .into_iter() - .flatten() - { + for buffer in [candidate, injection, output, residual].into_iter().flatten() { let released = buffer.release().map_err(driver_error); if cleanup.is_ok() { cleanup = released; } } - if (cleanup.is_err() - || result - .as_ref() - .is_err_and(|error| *error == Error::CudaExecution)) + if (cleanup.is_err() || result.as_ref().is_err_and(|error| *error == Error::CudaExecution)) && let Some(failed) = &read.transport_failed { failed.set(true); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs index b1f544b5..359294ee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk.rs @@ -46,9 +46,9 @@ pub(in crate::qwen_forward) struct GrBatchRow { #[path = "gr_batch_chunk/impl_grmicroinput.rs"] mod impl_grmicroinput; #[allow(unused_imports)] -pub(super) use impl_grmicroinput::save_micro_values; -#[allow(unused_imports)] pub(super) use impl_grmicroinput::micro_driver_error; +#[allow(unused_imports)] +pub(super) use impl_grmicroinput::save_micro_values; #[path = "gr_batch_chunk/impl_grstage.rs"] mod impl_grstage; #[path = "gr_batch_chunk/impl_grstage_2.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs index 546ad6b9..fced0546 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grmicroinput.rs @@ -4,11 +4,7 @@ use super::*; impl GrMicroInput { - pub(in crate::qwen_forward) fn validate_origin( - &self, - binding: &BindingIdentity, - role: GrRole, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate_origin(&self, binding: &BindingIdentity, role: GrRole) -> Result<()> { if !self.binding.matches(binding) || self.role != role { return Err(Error::IdentityMismatch); } @@ -19,9 +15,7 @@ impl GrMicroInput { } } impl<'ctx> GrMicroAttention<'ctx> { - pub(in crate::qwen_forward) fn into_parts( - self, - ) -> (GrMicroAttentionBank<'ctx>, Vec) { + pub(in crate::qwen_forward) fn into_parts(self) -> (GrMicroAttentionBank<'ctx>, Vec) { (self.bank, self.rows) } } @@ -33,20 +27,13 @@ impl<'ctx> GrMicroDevice<'ctx> { ) -> std::result::Result { match self { Self::Legacy(owner) => owner.read(weights, epsilon), - Self::Native(_) => Err(DriverError::InvalidDriverValue( - "native shared workspace required", - )), + Self::Native(_) => Err(DriverError::InvalidDriverValue("native shared workspace required")), } } - pub(in super::super) fn inject( - &mut self, - blocks: &[f32], - ) -> std::result::Result, DriverError> { + pub(in super::super) fn inject(&mut self, blocks: &[f32]) -> std::result::Result, DriverError> { match self { Self::Legacy(owner) => owner.inject(blocks), - Self::Native(_) => Err(DriverError::InvalidDriverValue( - "native shared workspace required", - )), + Self::Native(_) => Err(DriverError::InvalidDriverValue("native shared workspace required")), } } pub(in super::super) fn read_native( @@ -57,13 +44,9 @@ impl<'ctx> GrMicroDevice<'ctx> { weights: [&DeviceBuffer<'_>; 4], epsilon: f32, ) -> Result { - let mut workspace = cache - .native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; match self { - Self::Native(owner) => owner - .read(weights, epsilon, &mut workspace) - .map_err(micro_driver_error), + Self::Native(owner) => owner.read(weights, epsilon, &mut workspace).map_err(micro_driver_error), Self::Legacy(_) => Err(Error::IdentityMismatch), } } @@ -74,13 +57,9 @@ impl<'ctx> GrMicroDevice<'ctx> { context: &Context<'_>, blocks: &[f32], ) -> Result> { - let mut workspace = cache - .native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; match self { - Self::Native(owner) => owner - .inject(blocks, &mut workspace) - .map_err(micro_driver_error), + Self::Native(owner) => owner.inject(blocks, &mut workspace).map_err(micro_driver_error), Self::Legacy(_) => Err(Error::IdentityMismatch), } } @@ -100,9 +79,7 @@ impl<'ctx> GrMicroDevice<'ctx> { pub(in super::super) fn save_micro_values(values: &[f32], count: usize) -> Result> { validate_values(values, count)?; let mut saved = Vec::new(); - saved - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + saved.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; saved.extend_from_slice(values); Ok(saved.into_boxed_slice()) } @@ -110,9 +87,7 @@ pub(in super::super) fn micro_driver_error(error: DriverError) -> Error { crate::bringup_trace!("DBG micro_driver_error(gr_batch_chunk): {error:?}"); match error { DriverError::NonFiniteMmqOutput(_) => Error::NonFinite, - DriverError::InvalidDriverValue("GR micro input finite" | "GR micro block finite") => { - Error::NonFinite - } + DriverError::InvalidDriverValue("GR micro input finite" | "GR micro block finite") => Error::NonFinite, other => driver_error(other), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs index b7cd3003..f4d3172a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage.rs @@ -38,12 +38,7 @@ impl GrStage { let identity = TokenLayer::new(input.token(), input.position(), layer); validate_layer(layer, binding.layer_count())?; identity.validate(txn.token(), txn.position(), layer)?; - Ok(GrMicroInput { - binding: binding.identity(), - role: GrRole::Attention(layer.get()), - identity, - streams, - }) + Ok(GrMicroInput { binding: binding.identity(), role: GrRole::Attention(layer.get()), identity, streams }) } pub(in crate::qwen_forward) fn prepare_micro_after_ple( binding: &ModelBinding, @@ -56,8 +51,7 @@ impl GrStage { return Err(Error::IdentityMismatch); } ple.validate_origin(&binding.identity())?; - ple.identity() - .validate(txn.token(), txn.position(), layer)?; + ple.identity().validate(txn.token(), txn.position(), layer)?; Self::mint_micro_input(binding, layer, ple.streams(), ple.identity(), txn) } pub(in crate::qwen_forward) fn prepare_micro_after_ffn( @@ -72,14 +66,9 @@ impl GrStage { return Err(Error::IdentityMismatch); } let prior = layer.get().checked_sub(1).ok_or(Error::IdentityMismatch)?; - let previous_layer = LayerId::new( - u64::from(prior), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let previous_layer = LayerId::new(u64::from(prior), Dimension::new(u64::from(binding.layer_count()))?)?; previous.validate_origin(&binding.identity(), GrRole::Ffn(prior))?; - previous - .identity - .validate(txn.token(), txn.position(), previous_layer)?; + previous.identity.validate(txn.token(), txn.position(), previous_layer)?; Self::mint_micro_input( binding, layer, @@ -106,18 +95,13 @@ impl GrStage { return Err(Error::IdentityMismatch); } let mut streams = Vec::new(); - streams - .try_reserve_exact(inputs.len() * 10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(inputs.len() * 10240).map_err(|_| Error::InputAllocation)?; let mut identities = Vec::new(); - identities - .try_reserve_exact(inputs.len()) - .map_err(|_| Error::InputAllocation)?; + identities.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; for (index, input) in inputs.iter().enumerate() { input.validate_origin(&binding.identity(), role)?; if input.identity.layer() != layer - || input.identity.position().get() - != first.checked_add(index as u64).ok_or(Error::Overflow)? + || input.identity.position().get() != first.checked_add(index as u64).ok_or(Error::Overflow)? { return Err(Error::IdentityMismatch); } @@ -128,24 +112,17 @@ impl GrStage { if !resident.weights.matches(&binding.identity(), role) { return Err(Error::IdentityMismatch); } - let weights = cache - .gr_buffers(resident)? - .map(|w| w.ok_or(Error::IdentityMismatch)); + let weights = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); let [gamma, down, up, inject] = weights; - let mut device = GrMicroDevice::Legacy( - context - .gr_microbatch_read(inputs.len(), &streams) - .map_err(micro_driver_error)?, - ); + let mut device = + GrMicroDevice::Legacy(context.gr_microbatch_read(inputs.len(), &streams).map_err(micro_driver_error)?); let result = (|| { - let values = device - .read([gamma?, down?, up?, inject?], resident.weights.epsilon()) - .map_err(micro_driver_error)?; + let values = + device.read([gamma?, down?, up?, inject?], resident.weights.epsilon()).map_err(micro_driver_error)?; validate_values(&values.mixed, inputs.len() * 2560)?; validate_values(&values.inject, inputs.len() * 4)?; let mut rows = Vec::new(); - rows.try_reserve_exact(inputs.len()) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; for (index, input) in inputs.into_iter().enumerate() { rows.push(DetachedGrRead::from_micro_ready( ResidualReady { @@ -153,10 +130,7 @@ impl GrStage { identity: input.identity, role: input.role, streams: input.streams, - mixed: save_micro_values( - &values.mixed[index * 2560..(index + 1) * 2560], - 2560, - )?, + mixed: save_micro_values(&values.mixed[index * 2560..(index + 1) * 2560], 2560)?, inject: values.inject[index * 4..(index + 1) * 4] .try_into() .map_err(|_| Error::InvalidDimension)?, @@ -201,7 +175,7 @@ impl GrStage { ) -> Result> { let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; - if inputs.is_empty() || inputs.len()>cache.native_prompt_capacity(binding,context)? { + if inputs.is_empty() || inputs.len() > cache.native_prompt_capacity(binding, context)? { return Err(Error::InvalidDimension); } let role = inputs[0].role; @@ -211,18 +185,13 @@ impl GrStage { return Err(Error::IdentityMismatch); } let mut streams = Vec::new(); - streams - .try_reserve_exact(inputs.len() * 10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(inputs.len() * 10240).map_err(|_| Error::InputAllocation)?; let mut identities = Vec::new(); - identities - .try_reserve_exact(inputs.len()) - .map_err(|_| Error::InputAllocation)?; + identities.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; for (index, input) in inputs.iter().enumerate() { input.validate_origin(&binding.identity(), role)?; if input.identity.layer() != layer - || input.identity.position().get() - != first.checked_add(index as u64).ok_or(Error::Overflow)? + || input.identity.position().get() != first.checked_add(index as u64).ok_or(Error::Overflow)? { return Err(Error::IdentityMismatch); } @@ -233,15 +202,17 @@ impl GrStage { if !resident.weights.matches(&binding.identity(), role) { return Err(Error::IdentityMismatch); } - let weights = cache - .gr_buffers(resident)? - .map(|w| w.ok_or(Error::IdentityMismatch)); + let weights = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); let [gamma, down, up, inject] = weights; // Actual owned baseline config39b9 selects Original HighOnly. // Hi+low must use a separately identity-bound factory, not env inference. let mut device = GrMicroDevice::Native( - if cache.native_prompt_capacity(binding,context)?==64 {context.gr_native_batch(inputs.len(),&streams,leleka_cuda_driver::GrNativeProfile::HighOnly)}else{context.gr_native_prompt_batch(inputs.len(),&streams,leleka_cuda_driver::GrNativeProfile::HighOnly)} - .map_err(micro_driver_error)?, + if cache.native_prompt_capacity(binding, context)? == 64 { + context.gr_native_batch(inputs.len(), &streams, leleka_cuda_driver::GrNativeProfile::HighOnly) + } else { + context.gr_native_prompt_batch(inputs.len(), &streams, leleka_cuda_driver::GrNativeProfile::HighOnly) + } + .map_err(micro_driver_error)?, ); let result = (|| { let values = device.read_native( @@ -254,8 +225,7 @@ impl GrStage { validate_values(&values.mixed, inputs.len() * 2560)?; validate_values(&values.inject, inputs.len() * 4)?; let mut rows = Vec::new(); - rows.try_reserve_exact(inputs.len()) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; for (index, input) in inputs.into_iter().enumerate() { rows.push(DetachedGrRead::from_micro_ready( ResidualReady { @@ -263,10 +233,7 @@ impl GrStage { identity: input.identity, role: input.role, streams: input.streams, - mixed: save_micro_values( - &values.mixed[index * 2560..(index + 1) * 2560], - 2560, - )?, + mixed: save_micro_values(&values.mixed[index * 2560..(index + 1) * 2560], 2560)?, inject: values.inject[index * 4..(index + 1) * 4] .try_into() .map_err(|_| Error::InvalidDimension)?, @@ -330,10 +297,6 @@ impl GrStage { let block = save_micro_values(block, 2560)?; // Original single-use detached row remains the source of publication. read.claim_retained_handoff(&bank.failed)?; - Ok(GrMicroAttentionBlock { - owner: Rc::clone(&bank.owner), - identity, - block, - }) + Ok(GrMicroAttentionBlock { owner: Rc::clone(&bank.owner), identity, block }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs index d9d122b2..66d45d7a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_batch_chunk/impl_grstage_2.rs @@ -17,14 +17,9 @@ impl GrStage { } validate_values(block, 2560)?; let mut saved = Vec::new(); - saved - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; + saved.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; saved.extend_from_slice(block); - Ok(GrBatchRow { - ready, - block: saved.into_boxed_slice(), - }) + Ok(GrBatchRow { ready, block: saved.into_boxed_slice() }) } pub(in crate::qwen_forward) fn prepare_batch_injection( binding: &ModelBinding, @@ -38,12 +33,8 @@ impl GrStage { } let read = &owner.ready; txn.validate_binding(&binding.identity())?; - read.validate_origin( - &binding.identity(), - GrRole::Ffn(read.identity.layer().get()), - )?; - read.identity - .validate(txn.token(), txn.position(), read.identity.layer())?; + read.validate_origin(&binding.identity(), GrRole::Ffn(read.identity.layer().get()))?; + read.identity.validate(txn.token(), txn.position(), read.identity.layer())?; if read.identity != block_identity { return Err(Error::IdentityMismatch); } @@ -58,16 +49,11 @@ impl GrStage { scratch.buffer(context)?; } let mut saved = Vec::new(); - saved - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; + saved.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; saved.extend_from_slice(block); // End the exclusive residual scratch lease. The immutable host ready // producer retains the exact original bytes for the batch injection. - Ok(GrBatchRow { - ready: owner.ready, - block: saved.into_boxed_slice(), - }) + Ok(GrBatchRow { ready: owner.ready, block: saved.into_boxed_slice() }) } pub(in crate::qwen_forward) fn inject_batch( binding: &ModelBinding, @@ -76,9 +62,8 @@ impl GrStage { cache: &DenseWeightCache<'_>, ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; if !(1..=64).contains(&rows.len()) { @@ -90,20 +75,12 @@ impl GrStage { let mut streams = Vec::new(); let mut blocks = Vec::new(); let mut injects = Vec::new(); - streams - .try_reserve_exact(rows.len() * 10240) - .map_err(|_| Error::InputAllocation)?; - blocks - .try_reserve_exact(rows.len() * 2560) - .map_err(|_| Error::InputAllocation)?; - injects - .try_reserve_exact(rows.len() * 4) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(rows.len() * 10240).map_err(|_| Error::InputAllocation)?; + blocks.try_reserve_exact(rows.len() * 2560).map_err(|_| Error::InputAllocation)?; + injects.try_reserve_exact(rows.len() * 4).map_err(|_| Error::InputAllocation)?; for (i, row) in rows.iter().enumerate() { row.ready.validate_origin(&binding.identity(), role)?; - if row.ready.identity.layer() != layer - || row.ready.identity.position().get() != first + i as u64 - { + if row.ready.identity.layer() != layer || row.ready.identity.position().get() != first + i as u64 { return Err(Error::IdentityMismatch); } validate_streams(&row.ready.streams)?; @@ -124,12 +101,11 @@ impl GrStage { let queued = if let Some(shape) = shape && let Some(mut workspace) = cache.gr_batch_workspace(binding, context)? { - let result = workspace - .inject(context, shape, &streams, &blocks, &injects) - .map_err(|error| match error { - leleka_cuda_driver::Error::InvalidDriverValue( - "GR batch injection finite input", - ) => Error::NonFinite, + let result = + workspace.inject(context, shape, &streams, &blocks, &injects).map_err(|error| match error { + leleka_cuda_driver::Error::InvalidDriverValue("GR batch injection finite input") => { + Error::NonFinite + } other => driver_error(other), }); if workspace.is_failed() || context.is_poisoned() { @@ -148,14 +124,10 @@ impl GrStage { } validate_values(&values, rows.len() * 10240)?; let mut completed = Vec::new(); - completed - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + completed.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (row, column) in rows.into_iter().zip(values.as_chunks::<10240>().0) { let mut copied = Vec::new(); - copied - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + copied.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; copied.extend_from_slice(column); completed.push(InjectedResidual::from_candidates( row.ready.identity, @@ -199,19 +171,12 @@ impl GrStage { candidate.as_mut().ok_or(Error::CudaExecution)?, ) .map_err(driver_error)?; - let values = download_f32( - candidate.as_ref().ok_or(Error::CudaExecution)?, - rows.len() * 10240, - )?; + let values = download_f32(candidate.as_ref().ok_or(Error::CudaExecution)?, rows.len() * 10240)?; let mut completed = Vec::new(); - completed - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + completed.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (row, column) in rows.into_iter().zip(values.as_chunks::<10240>().0) { let mut copied = Vec::new(); - copied - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + copied.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; copied.extend_from_slice(column); completed.push(InjectedResidual::from_candidates( row.ready.identity, @@ -224,10 +189,7 @@ impl GrStage { })(); // Attempt every owned release even after a CUDA or finite refusal. let mut cleanup = Ok(()); - for buffer in [candidate, injection, output, residual] - .into_iter() - .flatten() - { + for buffer in [candidate, injection, output, residual].into_iter().flatten() { let released = buffer.release().map_err(driver_error); if cleanup.is_ok() { cleanup = released; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_residual_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_residual_reuse_gpu.rs index 6ffe4244..93edd9a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_residual_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_residual_reuse_gpu.rs @@ -30,12 +30,7 @@ impl<'ctx> Matrices<'ctx> { } } fn resident(&self) -> [Option<&DeviceBuffer<'ctx>>; 4] { - [ - Some(&self.gamma), - Some(&self.down), - Some(&self.up), - Some(&self.inject), - ] + [Some(&self.gamma), Some(&self.down), Some(&self.up), Some(&self.inject)] } fn close(self) { for matrix in [self.inject, self.up, self.down, self.gamma] { @@ -51,11 +46,7 @@ fn exact(left: &[f32], right: &[f32]) { } } -fn original_trace( - context: &Context<'_>, - residual: &DeviceBuffer<'_>, - matrices: &Matrices<'_>, -) -> Vec> { +fn original_trace(context: &Context<'_>, residual: &DeviceBuffer<'_>, matrices: &Matrices<'_>) -> Vec> { // Original qualified source order, not a host exp/dot implementation. let mut xn = context.allocate(40960).unwrap(); let mut down = context.allocate(1280).unwrap(); @@ -64,28 +55,18 @@ fn original_trace( let mut products = context.allocate(40960).unwrap(); let mut mixed = context.allocate(10240).unwrap(); let mut inject = context.allocate(16).unwrap(); - context - .gr_norm_f32(residual, &matrices.gamma, 1e-6, &mut xn) - .unwrap(); + context.gr_norm_f32(residual, &matrices.gamma, 1e-6, &mut xn).unwrap(); let mut trace = vec![download_f32(&xn, 10240).unwrap()]; - context - .gr_down_projection_bf16_f32(&matrices.down, &xn, &mut down) - .unwrap(); + context.gr_down_projection_bf16_f32(&matrices.down, &xn, &mut down).unwrap(); trace.push(download_f32(&down, 320).unwrap()); context.gr_down_silu_hc_f32(&down, &mut activated).unwrap(); trace.push(download_f32(&activated, 320).unwrap()); - context - .gr_up_projection_bf16_f32(&matrices.up, &activated, &mut gates) - .unwrap(); + context.gr_up_projection_bf16_f32(&matrices.up, &activated, &mut gates).unwrap(); trace.push(download_f32(&gates, 10240).unwrap()); - context - .gr_gate_mean_layer_fused_f32(&xn, &gates, &mut products, &mut mixed) - .unwrap(); + context.gr_gate_mean_layer_fused_f32(&xn, &gates, &mut products, &mut mixed).unwrap(); trace.push(download_f32(&products, 10240).unwrap()); trace.push(download_f32(&mixed, 2560).unwrap()); - context - .gr_inject_projection_bf16_f32(&matrices.inject, &xn, &mut inject) - .unwrap(); + context.gr_inject_projection_bf16_f32(&matrices.inject, &xn, &mut inject).unwrap(); trace.push(download_f32(&inject, 4).unwrap()); for buffer in [inject, mixed, products, gates, activated, down, xn] { buffer.release().unwrap(); @@ -93,20 +74,13 @@ fn original_trace( trace } -fn original_inject( - context: &Context<'_>, - streams: &[f32], - block: &[f32], - inject: &[f32; 4], -) -> Box<[f32]> { +fn original_inject(context: &Context<'_>, streams: &[f32], block: &[f32], inject: &[f32; 4]) -> Box<[f32]> { // Genuine previous stage re-uploaded the canonical host residual here. let residual = upload_f32(context, streams).unwrap(); let block = upload_f32(context, block).unwrap(); let inject = upload_f32(context, inject).unwrap(); let mut output = context.allocate(40960).unwrap(); - context - .gr_inject_residual_f32(&residual, &block, &inject, &mut output) - .unwrap(); + context.gr_inject_residual_f32(&residual, &block, &inject, &mut output).unwrap(); let values = download_f32(&output, 10240).unwrap(); for buffer in [output, inject, block, residual] { buffer.release().unwrap(); @@ -122,28 +96,15 @@ fn retained_residual_matches_original_read_inject_and_fences_abort_sticky_failur let context = device.create_context(160 * 1024 * 1024).unwrap(); let binding = BindingIdentity::test_identity(); // Identity tag, not ModelBinding. let failed = Rc::new(Cell::new(false)); - let scratch = - RefCell::new(GrScratch::new_identity(binding.clone(), &context, failed.clone()).unwrap()); + let scratch = RefCell::new(GrScratch::new_identity(binding.clone(), &context, failed.clone()).unwrap()); let mut matrices = Matrices::new(&context); let charged = context.allocated_bytes(); for zero in [false, true] { let streams: Vec = (0..10240) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 19) as f32 / 64. - 9. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 19) as f32 / 64. - 9. / 64. }) .collect(); let block: Vec = (0..2560) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 13) as f32 / 128. - 6. / 128. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 13) as f32 / 128. - 6. / 128. }) .collect(); let source_bits: Vec = streams.iter().map(|value| value.to_bits()).collect(); let old = upload_f32(&context, &streams).unwrap(); @@ -165,17 +126,8 @@ fn retained_residual_matches_original_read_inject_and_fences_abort_sticky_failur exact(&actual.inject.unwrap(), &coefficients); let injected = inject_cached_cuda(&context, &lease, &block, &coefficients).unwrap(); exact(&injected, &expected_injected); - exact( - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - &streams, - ); - assert_eq!( - streams - .iter() - .map(|value| value.to_bits()) - .collect::>(), - source_bits - ); + exact(&download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), &streams); + assert_eq!(streams.iter().map(|value| value.to_bits()).collect::>(), source_bits); assert_eq!(context.allocated_bytes(), charged); drop(lease); println!( @@ -187,88 +139,44 @@ fn retained_residual_matches_original_read_inject_and_fences_abort_sticky_failur let rival = BindingIdentity::test_identity(); let mut lease = scratch.borrow_mut(); let original = download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(); - assert_eq!( - lease.write(&rival, &context, &streams), - Err(Error::IdentityMismatch) - ); - assert_eq!( - lease.write(&binding, &foreign, &streams), - Err(Error::IdentityMismatch) - ); - assert_eq!( - lease.write(&binding, &context, &streams[..10239]), - Err(Error::InvalidDimension) - ); + assert_eq!(lease.write(&rival, &context, &streams), Err(Error::IdentityMismatch)); + assert_eq!(lease.write(&binding, &foreign, &streams), Err(Error::IdentityMismatch)); + assert_eq!(lease.write(&binding, &context, &streams[..10239]), Err(Error::InvalidDimension)); for bits in [0x7fc00001u32, 0x7f800000] { let mut malformed = streams.clone(); malformed[10239] = f32::from_bits(bits); - assert_eq!( - lease.write(&binding, &context, &malformed), - Err(Error::NonFinite) - ); + assert_eq!(lease.write(&binding, &context, &malformed), Err(Error::NonFinite)); } assert_eq!(lease.buffer(&foreign).err(), Some(Error::IdentityMismatch)); - exact( - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - &original, - ); + exact(&download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), &original); assert_eq!(context.allocated_bytes(), charged); lease.write(&binding, &context, &streams).unwrap(); let mut missing = matrices.resident(); missing[0] = None; - assert_eq!( - read_cached_cuda(&context, 1e-6, true, &lease, missing).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(read_cached_cuda(&context, 1e-6, true, &lease, missing).err(), Some(Error::IdentityMismatch)); // A late actual kernel result must be withheld and every intermediate // freed. Numerical refusal is not an ambiguous CUDA/context failure. let mut gamma = vec![1.0f32; 10240]; gamma[10239] = f32::from_bits(0x7fc00001); - matrices - .gamma - .copy_from( - &gamma - .iter() - .flat_map(|value| value.to_le_bytes()) - .collect::>(), - ) - .unwrap(); - assert_eq!( - read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).err(), - Some(Error::NonFinite) - ); + matrices.gamma.copy_from(&gamma.iter().flat_map(|value| value.to_le_bytes()).collect::>()).unwrap(); + assert_eq!(read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).err(), Some(Error::NonFinite)); assert_eq!(context.allocated_bytes(), charged); assert!(!failed.get()); - matrices - .gamma - .copy_from(&[1.0f32.to_le_bytes(); 10240].concat()) - .unwrap(); - assert_eq!( - inject_cached_cuda(&context, &lease, &[0.25; 2559], &[0.5; 4]).err(), - Some(Error::InvalidDimension) - ); + matrices.gamma.copy_from(&[1.0f32.to_le_bytes(); 10240].concat()).unwrap(); + assert_eq!(inject_cached_cuda(&context, &lease, &[0.25; 2559], &[0.5; 4]).err(), Some(Error::InvalidDimension)); let mut malformed_block = vec![0.25; 2560]; malformed_block[2559] = f32::from_bits(0x7fc00001); - assert_eq!( - inject_cached_cuda(&context, &lease, &malformed_block, &[0.5; 4]).err(), - Some(Error::NonFinite) - ); + assert_eq!(inject_cached_cuda(&context, &lease, &malformed_block, &[0.5; 4]).err(), Some(Error::NonFinite)); assert_eq!(context.allocated_bytes(), charged); assert!(!failed.get()); drop(lease); // Abort releases actual exclusive slot ownership. let replacement = vec![-0.0625; 10240]; let mut lease = scratch.borrow_mut(); lease.write(&binding, &context, &replacement).unwrap(); - exact( - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - &replacement, - ); + exact(&download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), &replacement); failed.set(true); // Sticky policy only; no fake native failure injection. assert_eq!(lease.buffer(&context).err(), Some(Error::CudaExecution)); - assert_eq!( - lease.write(&binding, &context, &streams), - Err(Error::CudaExecution) - ); + assert_eq!(lease.write(&binding, &context, &streams), Err(Error::CudaExecution)); drop(lease); matrices.close(); assert_eq!(scratch.into_inner().close(), Err(Error::CudaExecution)); @@ -278,17 +186,12 @@ fn retained_residual_matches_original_read_inject_and_fences_abort_sticky_failur context.close().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); - let small = device - .create_context(128 * 1024 * 1024 + 40960 - 1) - .unwrap(); + let small = device.create_context(128 * 1024 * 1024 + 40960 - 1).unwrap(); assert_eq!( GrScratch::new_identity(binding.clone(), &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation) ); - assert_eq!( - GrScratch::new_identity(binding, &small, Rc::new(Cell::new(true))).err(), - Some(Error::CudaExecution) - ); + assert_eq!(GrScratch::new_identity(binding, &small, Rc::new(Cell::new(true))).err(), Some(Error::CudaExecution)); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); println!("GR_RETAINED COMPLETE exact_words=93536 finite_cases=2 guard_refusals=15 allocated=0"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs index f2e72180..b804b69c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff.rs @@ -29,9 +29,7 @@ impl GrStage { return Err(Error::IdentityMismatch); } let mut values = Vec::new(); - values - .try_reserve_exact(blocks.len() * 2560) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(blocks.len() * 2560).map_err(|_| Error::InputAllocation)?; for (index, block) in blocks.iter().enumerate() { if !Rc::ptr_eq(&bank.owner, &block.owner) || block.identity != bank.rows[index] { return Err(Error::IdentityMismatch); @@ -40,15 +38,10 @@ impl GrStage { values.extend_from_slice(&block.block); } let resident = cache.gr(binding, GrRole::Ffn(layer.get()))?; - if !resident - .weights - .matches(&binding.identity(), GrRole::Ffn(layer.get())) - { + if !resident.weights.matches(&binding.identity(), GrRole::Ffn(layer.get())) { return Err(Error::IdentityMismatch); } - let [gamma, down, up, inject] = cache - .gr_buffers(resident)? - .map(|w| w.ok_or(Error::IdentityMismatch)); + let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); let mut device = bank.device.take().ok_or(Error::IdentityMismatch)?; let result = (|| { // Full original canonical host streams are read once from the @@ -56,9 +49,7 @@ impl GrStage { let streams = if matches!(&device, batch_chunk::GrMicroDevice::Native(_)) { device.inject_native(binding, cache, context, &values)? } else { - device - .inject(&values) - .map_err(batch_chunk::micro_driver_error)? + device.inject(&values).map_err(batch_chunk::micro_driver_error)? }; validate_values(&streams, blocks.len() * 10240)?; let next = if matches!(&device, batch_chunk::GrMicroDevice::Native(_)) { @@ -77,22 +68,15 @@ impl GrStage { validate_values(&next.mixed, blocks.len() * 2560)?; validate_values(&next.inject, blocks.len() * 4)?; let mut rows = Vec::new(); - rows.try_reserve_exact(blocks.len()) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(blocks.len()).map_err(|_| Error::InputAllocation)?; for (index, identity) in bank.rows.iter().copied().enumerate() { rows.push(DetachedGrRead::from_micro_ready( ResidualReady { identity, binding: binding.identity(), role: GrRole::Ffn(layer.get()), - streams: batch_chunk::save_micro_values( - &streams[index * 10240..(index + 1) * 10240], - 10240, - )?, - mixed: batch_chunk::save_micro_values( - &next.mixed[index * 2560..(index + 1) * 2560], - 2560, - )?, + streams: batch_chunk::save_micro_values(&streams[index * 10240..(index + 1) * 10240], 10240)?, + mixed: batch_chunk::save_micro_values(&next.mixed[index * 2560..(index + 1) * 2560], 2560)?, inject: next.inject[index * 4..(index + 1) * 4] .try_into() .map_err(|_| Error::InvalidDimension)?, @@ -131,9 +115,7 @@ fn replace_residual_buffer<'ctx>( old: &mut Option>, candidate: &mut Option>, ) -> Result<()> { - if old.as_ref().is_none_or(|b| b.len() != 40960) - || candidate.as_ref().is_none_or(|b| b.len() != 40960) - { + if old.as_ref().is_none_or(|b| b.len() != 40960) || candidate.as_ref().is_none_or(|b| b.len() != 40960) { return Err(Error::InvalidDimension); } std::mem::swap(old, candidate); @@ -151,9 +133,8 @@ pub(super) fn inject_replace_residual<'ctx>( inject: &[f32; 4], ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); validate_streams(streams)?; validate_values(block, 2560)?; validate_values(inject, 4)?; @@ -181,9 +162,7 @@ pub(super) fn inject_replace_residual<'ctx>( let result: Result> = (|| { copy_cached_f32(output, block, &failed)?; copy_cached_f32(injection, inject, &failed)?; - context - .gr_inject_residual_f32(residual, output, injection, candidate) - .map_err(driver_error)?; + context.gr_inject_residual_f32(residual, output, injection, candidate).map_err(driver_error)?; let values = download_f32(candidate, 10240)?; // The actual finite output allocation replaces the actor input only // after its original readback has passed. No raw/caller view is minted. @@ -223,13 +202,8 @@ impl GrStage { read.retained_handoff_available()?; let ready = read.ready(); txn.validate_binding(&binding.identity())?; - ready.validate_origin( - &binding.identity(), - GrRole::Attention(ready.identity.layer().get()), - )?; - ready - .identity - .validate(txn.token(), txn.position(), ready.identity.layer())?; + ready.validate_origin(&binding.identity(), GrRole::Attention(ready.identity.layer().get()))?; + ready.identity.validate(txn.token(), txn.position(), ready.identity.layer())?; if ready.identity != block_identity { return Err(Error::IdentityMismatch); } @@ -248,23 +222,11 @@ impl GrStage { admit_budget(context, 40960 + 10240 + 16)?; read.claim_retained_handoff(&failed)?; let transaction = txn.residual_handoff_owner()?; - let values = - inject_replace_residual(&mut scratch, context, &ready.streams, block, &ready.inject)?; - let actual = InjectedResidual::from_candidates( - ready.identity, - ready.binding.clone(), - ready.role, - values, - )?; + let values = inject_replace_residual(&mut scratch, context, &ready.streams, block, &ready.inject)?; + let actual = InjectedResidual::from_candidates(ready.identity, ready.binding.clone(), ready.role, values)?; txn.validate_binding(&binding.identity())?; - actual - .identity - .validate(txn.token(), txn.position(), ready.identity.layer())?; - Ok(RetainedAttentionInjection { - actual, - transaction, - scratch, - }) + actual.identity.validate(txn.token(), txn.position(), ready.identity.layer())?; + Ok(RetainedAttentionInjection { actual, transaction, scratch }) } pub(in crate::qwen_forward) fn read_retained_ffn<'cache, 'ctx>( @@ -273,11 +235,7 @@ impl GrStage { txn: &mut QwenStepTxn, cache: &'cache DenseWeightCache<'ctx>, ) -> Result> { - let RetainedAttentionInjection { - actual, - transaction, - scratch, - } = retained; + let RetainedAttentionInjection { actual, transaction, scratch } = retained; if !Rc::ptr_eq(&transaction, &txn.residual_handoff_owner()?) { return Err(Error::IdentityMismatch); } @@ -304,13 +262,7 @@ impl GrStage { let gpu = cache.gr_buffers(resident)?; // EXACT qualified norm/projection/Silu/gate/mix/finite-mask math. The // scratch already contains this producer: intentionally no write/H2D. - let candidate = read_cached_cuda( - context, - weights.epsilon(), - weights.inject().is_some(), - &scratch, - gpu, - )?; + let candidate = read_cached_cuda(context, weights.epsilon(), weights.inject().is_some(), &scratch, gpu)?; let inject = candidate.inject.ok_or(Error::InvalidDimension)?; txn.validate_binding(&binding.identity())?; identity.validate(txn.token(), txn.position(), layer)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff_gpu.rs index bcd25c7c..3653bb77 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/gr_retained_handoff_gpu.rs @@ -30,12 +30,7 @@ impl<'ctx> Matrices<'ctx> { } } fn resident(&self) -> [Option<&DeviceBuffer<'ctx>>; 4] { - [ - Some(&self.gamma), - Some(&self.down), - Some(&self.up), - Some(&self.inject), - ] + [Some(&self.gamma), Some(&self.down), Some(&self.up), Some(&self.inject)] } fn close(self) { for matrix in [self.inject, self.up, self.down, self.gamma] { @@ -54,65 +49,40 @@ fn exact(left: &[f32], right: &[f32]) { #[test] #[ignore = "root schedules only the new retained injection to FFN GR seam"] fn retained_attention_injection_to_ffn_gr_matches_original_host_roundtrip() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_GR_HANDOFF").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_GR_HANDOFF").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let context = device.create_context(160 * 1024 * 1024).unwrap(); // Identity tag for the actual scratch object; not a ModelBinding/session. let identity = BindingIdentity::test_identity(); let failed = Rc::new(Cell::new(false)); - let scratch = - RefCell::new(GrScratch::new_identity(identity.clone(), &context, failed.clone()).unwrap()); + let scratch = RefCell::new(GrScratch::new_identity(identity.clone(), &context, failed.clone()).unwrap()); let matrices = Matrices::new(&context); let charged = context.allocated_bytes(); let coefficients = [0.5, -0.25, 0., 1.]; for zero in [false, true] { let streams: Vec = (0..10240) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 19) as f32 / 64. - 9. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 19) as f32 / 64. - 9. / 64. }) .collect(); let block: Vec = (0..2560) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 13) as f32 / 128. - 6. / 128. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 13) as f32 / 128. - 6. / 128. }) .collect(); let mut lease = scratch.borrow_mut(); // Original qualified producer FIRST, with the original extra upload. lease.write(&identity, &context, &streams).unwrap(); let reference = inject_cached_cuda(&context, &lease, &block, &coefficients).unwrap(); lease.write(&identity, &context, &reference).unwrap(); - let reference_ffn = - read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).unwrap(); + let reference_ffn = read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).unwrap(); assert_eq!(context.allocated_bytes(), charged); // SAME private numerical/ownership producer used by real new runtime. - let candidate = - inject_replace_residual(&mut lease, &context, &streams, &block, &coefficients).unwrap(); + let candidate = inject_replace_residual(&mut lease, &context, &streams, &block, &coefficients).unwrap(); exact(&reference, &candidate); - exact( - &reference, - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - ); + exact(&reference, &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap()); assert!(scratch.try_borrow_mut().is_err()); // No scratch.write here: genuine candidate allocation feeds FFN GR. - let candidate_ffn = - read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).unwrap(); + let candidate_ffn = read_cached_cuda(&context, 1e-6, true, &lease, matrices.resident()).unwrap(); exact(&reference_ffn.mixed, &candidate_ffn.mixed); - exact( - &reference_ffn.inject.unwrap(), - &candidate_ffn.inject.unwrap(), - ); + exact(&reference_ffn.inject.unwrap(), &candidate_ffn.inject.unwrap()); assert_eq!(context.allocated_bytes(), charged); assert!(!failed.get()); drop(lease); @@ -124,25 +94,11 @@ fn retained_attention_injection_to_ffn_gr_matches_original_host_roundtrip() { let streams = vec![0.125; 10240]; let block = vec![0.0625; 2560]; assert_eq!( - inject_replace_residual( - &mut lease, - &context, - &streams[..10239], - &block, - &coefficients - ) - .err(), + inject_replace_residual(&mut lease, &context, &streams[..10239], &block, &coefficients).err(), Some(Error::InvalidDimension) ); assert_eq!( - inject_replace_residual( - &mut lease, - &context, - &streams, - &block[..2559], - &coefficients - ) - .err(), + inject_replace_residual(&mut lease, &context, &streams, &block[..2559], &coefficients).err(), Some(Error::InvalidDimension) ); for bits in [0x7fc00001u32, 0x7f800000] { @@ -150,16 +106,14 @@ fn retained_attention_injection_to_ffn_gr_matches_original_host_roundtrip() { let mut malformed = streams.clone(); malformed[position] = f32::from_bits(bits); assert_eq!( - inject_replace_residual(&mut lease, &context, &malformed, &block, &coefficients) - .err(), + inject_replace_residual(&mut lease, &context, &malformed, &block, &coefficients).err(), Some(Error::NonFinite) ); } let mut malformed = block.clone(); malformed[2559] = f32::from_bits(bits); assert_eq!( - inject_replace_residual(&mut lease, &context, &streams, &malformed, &coefficients) - .err(), + inject_replace_residual(&mut lease, &context, &streams, &malformed, &coefficients).err(), Some(Error::NonFinite) ); let mut malformed = coefficients; @@ -169,23 +123,14 @@ fn retained_attention_injection_to_ffn_gr_matches_original_host_roundtrip() { Some(Error::NonFinite) ); } - exact( - &sentinel, - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - ); + exact(&sentinel, &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap()); assert_eq!(context.allocated_bytes(), charged); assert!(!failed.get()); // Actual malformed allocation is withheld; old persistent bytes remain. let mut malformed = Some(context.allocate(40956).unwrap()); - assert_eq!( - replace_residual_buffer(&mut lease.residual, &mut malformed), - Err(Error::InvalidDimension) - ); + assert_eq!(replace_residual_buffer(&mut lease.residual, &mut malformed), Err(Error::InvalidDimension)); assert_eq!(malformed.as_ref().unwrap().len(), 40956); - exact( - &sentinel, - &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap(), - ); + exact(&sentinel, &download_f32(lease.buffer(&context).unwrap(), 10240).unwrap()); malformed.take().unwrap().release().unwrap(); drop(malformed); assert_eq!(context.allocated_bytes(), charged); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input.rs index f4f81b5f..0aaa08f9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input.rs @@ -81,11 +81,7 @@ mod tests { assert_eq!( gather_rows(&rows, |_| { calls += 1; - if calls == 7 { - Err(InputBindingError::Read) - } else { - Ok(vec![0.0; 160].into_boxed_slice()) - } + if calls == 7 { Err(InputBindingError::Read) } else { Ok(vec![0.0; 160].into_boxed_slice()) } }), Err(InputError::Binding(InputBindingError::Read)) ); @@ -93,20 +89,14 @@ mod tests { } #[test] fn gather_refuses_bad_shape_and_nonfinite_rows_before_publication() { - for (values, expected) in [ - (vec![0.0; 159], Error::InvalidDimension), - (vec![f32::NAN; 160], Error::NonFinite), - ] { + for (values, expected) in [(vec![0.0; 159], Error::InvalidDimension), (vec![f32::NAN; 160], Error::NonFinite)] { assert_eq!( gather_rows(&[0; 16], |_| Ok(values.clone().into_boxed_slice())), Err(InputError::Validation(expected)) ); } assert_eq!(binding_error(InputBindingError::Read), Error::InputRead); - assert_eq!( - binding_error(InputBindingError::Allocation), - Error::InputAllocation - ); + assert_eq!(binding_error(InputBindingError::Allocation), Error::InputAllocation); } #[test] fn validated_ids_cannot_substitute_another_vocabulary_or_context() { @@ -117,15 +107,9 @@ mod tests { let pos = Position::new(0, context).unwrap(); assert_eq!(validate_ids(&constants, token, pos), Ok(())); let alien_token = TokenId::new(0, Dimension::new(99).unwrap()).unwrap(); - assert_eq!( - validate_ids(&constants, alien_token, pos), - Err(Error::IdentityMismatch) - ); + assert_eq!(validate_ids(&constants, alien_token, pos), Err(Error::IdentityMismatch)); let alien_pos = Position::new(0, Dimension::new(99).unwrap()).unwrap(); - assert_eq!( - validate_ids(&constants, token, alien_pos), - Err(Error::IdentityMismatch) - ); + assert_eq!(validate_ids(&constants, token, alien_pos), Err(Error::IdentityMismatch)); } #[test] fn broadcast_is_exact_and_has_no_partial_acceptance_for_invalid_embedding() { @@ -210,28 +194,19 @@ mod ple_tests { let prior = PlePrior::zero(binding.clone(), &owner).unwrap(); let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap(); assert_eq!(prior.validate(&binding, &owner, position), Ok(())); - assert_eq!( - prior.validate(&binding, &PleOwner::new(), position), - Err(Error::IdentityMismatch) - ); + assert_eq!(prior.validate(&binding, &PleOwner::new(), position), Err(Error::IdentityMismatch)); let token = TokenId::new(0, Dimension::new(248320).unwrap()).unwrap(); let layer = LayerId::new(1, Dimension::new(48).unwrap()).unwrap(); let identity = TokenLayer::new(token, position, layer); let mut bad = ple_zeros(PLE_HISTORY).unwrap(); bad[7] = f32::NAN; - assert!(matches!( - PlePending::new(&prior, identity, bad), - Err(Error::NonFinite) - )); + assert!(matches!(PlePending::new(&prior, identity, bad), Err(Error::NonFinite))); assert_eq!(prior.next_position(), 0); assert!(prior.0.history.iter().all(|v| v.to_bits() == 0)); let pending = PlePending::test_next(&prior, &identity).unwrap(); assert_eq!(pending.validate(&prior, identity), Ok(())); let alien = PlePrior::zero(binding, &owner).unwrap(); - assert_eq!( - pending.validate(&alien, identity), - Err(Error::IdentityMismatch) - ); + assert_eq!(pending.validate(&alien, identity), Err(Error::IdentityMismatch)); assert_eq!(pending.into_prior().next_position(), 1); assert_eq!(prior.next_position(), 0); } @@ -244,41 +219,41 @@ mod ple_tests { } } -mod impl_residualstreams; mod impl_inputstage; +mod impl_residualstreams; +#[allow(unused_imports)] +use impl_inputstage::gather_ple; #[allow(unused_imports)] use impl_inputstage::trace_ple; #[allow(unused_imports)] use impl_inputstage::validate_ids; -#[allow(unused_imports)] -use impl_inputstage::gather_ple; mod gather_rows_fn; #[allow(unused_imports)] -use gather_rows_fn::gather_rows; -#[allow(unused_imports)] pub(super) use gather_rows_fn::binding_error; +#[allow(unused_imports)] +use gather_rows_fn::gather_rows; mod impl_inputstage_2; #[allow(unused_imports)] use impl_inputstage_2::ple_cuda_cached; mod ple_cuda_fn; #[allow(unused_imports)] +use ple_cuda_fn::ple_budget; +#[allow(unused_imports)] use ple_cuda_fn::ple_cuda; #[allow(unused_imports)] use ple_cuda_fn::ple_project; #[allow(unused_imports)] -use ple_cuda_fn::ple_budget; +use ple_cuda_fn::ple_upload; #[allow(unused_imports)] use ple_cuda_fn::ple_values; #[allow(unused_imports)] use ple_cuda_fn::ple_zeros; -#[allow(unused_imports)] -use ple_cuda_fn::ple_upload; mod ple_upload_f32_fn; #[allow(unused_imports)] -use ple_upload_f32_fn::ple_upload_f32; -#[allow(unused_imports)] -use ple_upload_f32_fn::ple_upload_u16; -#[allow(unused_imports)] use ple_upload_f32_fn::ple_download; #[allow(unused_imports)] use ple_upload_f32_fn::ple_driver_error; +#[allow(unused_imports)] +use ple_upload_f32_fn::ple_upload_f32; +#[allow(unused_imports)] +use ple_upload_f32_fn::ple_upload_u16; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs index 821094b3..6899bdbf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs @@ -7,16 +7,11 @@ pub(super) fn gather_rows( rows: &[u64; 16], mut read: impl FnMut(u64) -> crate::model_binding::qwen4exp_input::InputResult>, ) -> std::result::Result, InputError> { - if rows - .iter() - .any(|&row| row >= crate::model_binding::qwen4exp_input::PLE_ROWS) - { + if rows.iter().any(|&row| row >= crate::model_binding::qwen4exp_input::PLE_ROWS) { return Err(InputError::Binding(InputBindingError::Range)); } let mut output = Vec::new(); - output - .try_reserve_exact(EMBEDDING_VALUES) - .map_err(|_| InputError::Binding(InputBindingError::Allocation))?; + output.try_reserve_exact(EMBEDDING_VALUES).map_err(|_| InputError::Binding(InputBindingError::Allocation))?; for &row in rows { let decoded = read(row).map_err(InputError::Binding)?; if decoded.len() != PLE_ROW_VALUES { @@ -42,18 +37,12 @@ pub(in super::super) fn binding_error(error: InputBindingError) -> Error { #[cfg(test)] impl InputReady { - pub(in super::super) fn test_fixture( - token: TokenId, - position: Position, - binding: BindingIdentity, - ) -> Self { + pub(in super::super) fn test_fixture(token: TokenId, position: Position, binding: BindingIdentity) -> Self { Self { binding, token, position, - streams: ResidualStreams { - values: vec![0.0; 4 * EMBEDDING_VALUES].into_boxed_slice(), - }, + streams: ResidualStreams { values: vec![0.0; 4 * EMBEDDING_VALUES].into_boxed_slice() }, ple: vec![0.0; EMBEDDING_VALUES].into_boxed_slice(), ple_rows: [0; 16], deferred: false, @@ -81,12 +70,7 @@ impl PlePrior { pub(in super::super) fn test_reset_replay_numeric_eq(&self, other: &Self) -> bool { self.next_position() == other.next_position() && self.0.history.len() == other.0.history.len() - && self - .0 - .history - .iter() - .zip(other.0.history.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) + && self.0.history.iter().zip(other.0.history.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -102,16 +86,8 @@ impl PlePrior { history: ple_zeros(PLE_HISTORY)?, }))) } - pub(in super::super) fn validate( - &self, - binding: &BindingIdentity, - owner: &PleOwner, - pos: Position, - ) -> Result<()> { - if !self.0.binding.matches(binding) - || !self.0.owner.matches(owner) - || self.next_position() != pos.get() - { + pub(in super::super) fn validate(&self, binding: &BindingIdentity, owner: &PleOwner, pos: Position) -> Result<()> { + if !self.0.binding.matches(binding) || !self.0.owner.matches(owner) || self.next_position() != pos.get() { return Err(Error::IdentityMismatch); } Ok(()) @@ -141,10 +117,7 @@ impl PlePrior { Ok(Self(Rc::new(PleState { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), - next_position: prior - .next_position() - .checked_add(rows as u64) - .ok_or(Error::Overflow)?, + next_position: prior.next_position().checked_add(rows as u64).ok_or(Error::Overflow)?, history, }))) } @@ -161,10 +134,7 @@ impl PlePending { next: PlePrior(Rc::new(PleState { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), - next_position: prior - .next_position() - .checked_add(1) - .ok_or(Error::Overflow)?, + next_position: prior.next_position().checked_add(1).ok_or(Error::Overflow)?, history, })), }) @@ -186,13 +156,18 @@ impl PlePending { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl PleMicroBatchReady<'_> { pub(in super::super) fn take_ready( - &mut self, binding: &ModelBinding, residual: &InjectedResidual, - prior: &PlePrior, txn: &QwenStepTxn<'_, '_>, + &mut self, + binding: &ModelBinding, + residual: &InjectedResidual, + prior: &PlePrior, + txn: &QwenStepTxn<'_, '_>, ) -> Result { if !self.binding.matches(&binding.identity()) || !self.prior.same_state(prior) || !std::ptr::eq(self.context, txn.cuda_context()?) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } txn.validate_binding(&self.binding)?; txn.validate_ple_prior(prior)?; residual.validate_origin(&self.binding, GrRole::Ffn(0))?; @@ -209,9 +184,10 @@ impl PleMicroBatchReady<'_> { if source.embedding.as_ref() != input.ple_embedding() || source.streams.as_ref() != residual.streams() || !source.binding.matches(&self.binding) - { return Err(Error::IdentityMismatch); } - let row = self.rows.get_mut(self.next).and_then(Option::take) - .ok_or(Error::IdentityMismatch)?; + { + return Err(Error::IdentityMismatch); + } + let row = self.rows.get_mut(self.next).and_then(Option::take).ok_or(Error::IdentityMismatch)?; ple_values(&row.streams, PLE_HC)?; let pending = PlePending::new(prior, source.identity, row.history)?; // This is the genuine completed causal history, not a final history @@ -219,8 +195,10 @@ impl PleMicroBatchReady<'_> { self.prior = pending.next.clone(); self.next += 1; Ok(PleReady { - binding: self.binding.clone(), identity: source.identity, - streams: row.streams, pending: Some(pending), + binding: self.binding.clone(), + identity: source.identity, + streams: row.streams, + pending: Some(pending), }) } pub(in super::super) fn is_consumed(&self) -> bool { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs index 90f9010e..5e4e45b8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs @@ -31,12 +31,9 @@ impl InputStage { validate_ids(binding.input_constants(), token, pos)?; txn.validate_binding(&binding.identity())?; txn.validate_input(token, pos)?; - let rows = hash::rows( - token.get(), - txn.input_predecessors()?, - binding.input_constants(), - )?; - let embedding_span = super::super::prefill_profile::span(super::super::prefill_profile::Stage::InputEmbedding, None); + let rows = hash::rows(token.get(), txn.input_predecessors()?, binding.input_constants())?; + let embedding_span = + super::super::prefill_profile::span(super::super::prefill_profile::Stage::InputEmbedding, None); let embedding = binding.embedding_row(token.get()).map_err(binding_error)?; let streams = ResidualStreams::broadcast(&embedding)?; drop(embedding_span); @@ -70,11 +67,7 @@ impl InputStage { validate_ids(binding.input_constants(), token, pos)?; txn.validate_binding(&binding.identity())?; txn.validate_input(token, pos)?; - let rows = hash::rows( - token.get(), - txn.input_predecessors()?, - binding.input_constants(), - )?; + let rows = hash::rows(token.get(), txn.input_predecessors()?, binding.input_constants())?; let unique = match staged.unique.get(&token.get()) { Some(&u) => u, None => { @@ -86,10 +79,7 @@ impl InputStage { return Err(Error::NonFinite); } let u = u32::try_from(staged.unique.len()).map_err(|_| Error::Overflow)?; - staged - .embedding_bytes - .try_reserve(EMBEDDING_VALUES * 4) - .map_err(|_| Error::InputAllocation)?; + staged.embedding_bytes.try_reserve(EMBEDDING_VALUES * 4).map_err(|_| Error::InputAllocation)?; for v in embedding.iter() { staged.embedding_bytes.extend_from_slice(&v.to_le_bytes()); } @@ -112,7 +102,11 @@ impl InputStage { /// The sixteen PLE rows of each of `tokens` (flattened), where `before` are the two tokens that precede the first /// of them (-1: none): the read-ahead of the chunk after the one being computed. Pure; the same rows /// `consume_kar_deferred` records when that chunk is staged. - pub(in super::super) fn ple_rows_ahead(binding: &ModelBinding, mut before: [i32; 2], tokens: &[TokenId]) -> Result> { + pub(in super::super) fn ple_rows_ahead( + binding: &ModelBinding, + mut before: [i32; 2], + tokens: &[TokenId], + ) -> Result> { let mut out = Vec::new(); out.try_reserve_exact(tokens.len() * 16).map_err(|_| Error::InputAllocation)?; for &token in tokens { @@ -138,8 +132,7 @@ impl InputStage { return Err(Error::InvalidDimension); } let mut out = Vec::new(); - out.try_reserve_exact(tokens.len() * EMBEDDING_VALUES) - .map_err(|_| Error::InputAllocation)?; + out.try_reserve_exact(tokens.len() * EMBEDDING_VALUES).map_err(|_| Error::InputAllocation)?; let mut before = predecessors; for &token in tokens { if !(0..VOCABULARY as i32).contains(&token) { @@ -177,19 +170,14 @@ impl InputStage { txn: &mut QwenStepTxn, ) -> std::result::Result { validate_ids(binding.input_constants(), token, pos).map_err(InputError::Validation)?; - txn.validate_binding(&binding.identity()) - .map_err(InputError::Validation)?; - txn.validate_input(token, pos) - .map_err(InputError::Validation)?; + txn.validate_binding(&binding.identity()).map_err(InputError::Validation)?; + txn.validate_input(token, pos).map_err(InputError::Validation)?; let prior = txn.input_predecessors().map_err(InputError::Validation)?; - let rows = hash::rows(token.get(), prior, binding.input_constants()) - .map_err(InputError::Validation)?; + let rows = hash::rows(token.get(), prior, binding.input_constants()).map_err(InputError::Validation)?; // The 16 rows depend only on the token and its predecessors: start the // SSD reads now so they overlap the embedding read. let pending = binding.ple_issue(&rows).map_err(InputError::Binding)?; - let embedding = binding - .embedding_row(token.get()) - .map_err(InputError::Binding)?; + let embedding = binding.embedding_row(token.get()).map_err(InputError::Binding)?; let ple = gather_ple(binding, &rows, pending)?; let streams = ResidualStreams::broadcast(&embedding).map_err(InputError::Validation)?; Ok(InputReady { @@ -214,9 +202,7 @@ pub(super) fn validate_ids( ) -> Result<()> { let vocabulary = Dimension::new(u64::from(VOCABULARY))?; let context = Dimension::new(u64::from(constants.context_length()))?; - if token != TokenId::new(u64::from(token.get()), vocabulary)? - || pos != Position::new(pos.get(), context)? - { + if token != TokenId::new(u64::from(token.get()), vocabulary)? || pos != Position::new(pos.get(), context)? { return Err(Error::IdentityMismatch); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs index 1bf7f827..b9392937 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs @@ -6,7 +6,8 @@ use super::*; impl InputStage { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super) fn prepare_ple_micro_input( - binding: &ModelBinding, residual: &InjectedResidual, + binding: &ModelBinding, + residual: &InjectedResidual, txn: &QwenStepTxn<'_, '_>, ) -> Result { txn.validate_binding(&binding.identity())?; @@ -28,69 +29,79 @@ impl InputStage { Ok(PleMicroInput { binding: binding.identity(), identity: TokenLayer::new(txn.token(), txn.position(), layer1), - embedding: copy(input.ple_embedding())?, streams: copy(residual.streams())?, + embedding: copy(input.ple_embedding())?, + streams: copy(residual.streams())?, }) } /// Whole genuine micro-window, using Original BF16/GEMM PLE arithmetic. /// No pending session history escapes on numerical or transport refusal. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super) fn apply_ple_micro_cached<'ctx>( - binding: &ModelBinding, context: &Context<'_>, - prior: PlePrior, sources: Vec, cache: &DenseWeightCache<'ctx>, + binding: &ModelBinding, + context: &Context<'_>, + prior: PlePrior, + sources: Vec, + cache: &DenseWeightCache<'ctx>, ) -> Result> { - if !(1..=64).contains(&sources.len()) - || !prior.0.binding.matches(&binding.identity()) - { return Err(Error::IdentityMismatch); } + if !(1..=64).contains(&sources.len()) || !prior.0.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; let entry = cache.ple(binding, context)?; - if !entry.weights.matches(&binding.identity()) { return Err(Error::IdentityMismatch); } + if !entry.weights.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } ple_values(&prior.0.history, PLE_HISTORY)?; let mut embedding = Vec::new(); let mut streams = Vec::new(); - embedding.try_reserve_exact(sources.len()*2560).map_err(|_| Error::InputAllocation)?; - streams.try_reserve_exact(sources.len()*PLE_HC).map_err(|_| Error::InputAllocation)?; + embedding.try_reserve_exact(sources.len() * 2560).map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(sources.len() * PLE_HC).map_err(|_| Error::InputAllocation)?; for (row, source) in sources.iter().enumerate() { if !source.binding.matches(&binding.identity()) || source.identity.layer().get() != 1 - || source.identity.position().get() != prior.next_position() - .checked_add(row as u64).ok_or(Error::Overflow)? - { return Err(Error::IdentityMismatch); } + || source.identity.position().get() + != prior.next_position().checked_add(row as u64).ok_or(Error::Overflow)? + { + return Err(Error::IdentityMismatch); + } ple_values(&source.embedding, 2560)?; ple_values(&source.streams, PLE_HC)?; embedding.extend_from_slice(&source.embedding); streams.extend_from_slice(&source.streams); } let result = (|| { - let mut queue = cache.ple_batch_queue(binding, context)? - .ok_or(Error::IdentityMismatch)?; - let mut workspace = cache.native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; + let mut queue = cache.ple_batch_queue(binding, context)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; let weights = leleka_cuda_driver::PleClosedWeights { - key: cache.ple_key(entry)?, value: cache.ple_value(entry)?, + key: cache.ple_key(entry)?, + value: cache.ple_value(entry)?, aux: cache.ple_aux(entry)?, }; - let mut completed = queue.compose( - &mut workspace, weights, &embedding, &streams, &prior.0.history, - ).map_err(ple_driver_error)?; - if completed.rows() != sources.len() { return Err(Error::IdentityMismatch); } - if completed.numerical_refusal().is_some() { return Err(Error::NonFinite); } + let mut completed = queue + .compose(&mut workspace, weights, &embedding, &streams, &prior.0.history) + .map_err(ple_driver_error)?; + if completed.rows() != sources.len() { + return Err(Error::IdentityMismatch); + } + if completed.numerical_refusal().is_some() { + return Err(Error::NonFinite); + } let mut rows = Vec::new(); rows.try_reserve_exact(sources.len()).map_err(|_| Error::InputAllocation)?; for row in 0..sources.len() { - rows.push(Some(completed.take_row(row).map_err(ple_driver_error)? - .ok_or(Error::NonFinite)?)); + rows.push(Some(completed.take_row(row).map_err(ple_driver_error)?.ok_or(Error::NonFinite)?)); } // Completed owner and both exclusive RefMut loans end here before // GR borrows the same model-lifetime vendor workspace. Ok(rows) })(); - if matches!(result, Err(Error::CudaExecution)) { failed.set(true); } + if matches!(result, Err(Error::CudaExecution)) { + failed.set(true); + } let rows = result?; cache.validate(binding)?; - Ok(PleMicroBatchReady { - context, binding: binding.identity(), prior, sources, rows, next: 0, - }) + Ok(PleMicroBatchReady { context, binding: binding.identity(), prior, sources, rows, next: 0 }) } pub(in super::super) fn apply_ple( binding: &ModelBinding, @@ -110,9 +121,7 @@ impl InputStage { txn.validate_binding(&binding.identity())?; residual.validate_origin(&binding.identity(), GrRole::Ffn(0))?; let layer0 = LayerId::new(0, Dimension::new(u64::from(binding.layer_count()))?)?; - residual - .identity() - .validate(txn.token(), txn.position(), layer0)?; + residual.identity().validate(txn.token(), txn.position(), layer0)?; txn.validate_ple_prior(prior)?; let input = txn.input()?; txn.validate_binding(input.binding_identity())?; @@ -145,23 +154,10 @@ impl InputStage { identity, )? } else { - ple_cuda( - context, - binding, - &weights, - input.ple_embedding(), - residual.streams(), - &prior.0.history, - None, - )? + ple_cuda(context, binding, &weights, input.ple_embedding(), residual.streams(), &prior.0.history, None)? }; let pending = PlePending::new(prior, identity, candidate.history)?; - Ok(PleReady { - binding: binding.identity(), - identity, - streams: candidate.streams, - pending: Some(pending), - }) + Ok(PleReady { binding: binding.identity(), identity, streams: candidate.streams, pending: Some(pending) }) } } #[allow(clippy::too_many_arguments)] @@ -194,18 +190,12 @@ pub(super) fn ple_cuda_cached( let aux = cache.ple_aux(entry)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let result = if let Some(mut queue) = cache.ple_queue(binding, context)? { - ple_transport::compose_queued( - &mut queue, context, key, value, aux, embedding, streams, history, failed, - ) + ple_transport::compose_queued(&mut queue, context, key, value, aux, embedding, streams, history, failed) } else { - ple_transport::compose( - context, key, value, aux, embedding, streams, history, failed, - ) + ple_transport::compose(context, key, value, aux, embedding, streams, history, failed) }; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - let result = ple_transport::compose( - context, key, value, aux, embedding, streams, history, failed, - ); + let result = ple_transport::compose(context, key, value, aux, embedding, streams, history, failed); let candidate = result?; cache.validate(binding)?; if !weights.matches(&binding.identity()) || !Rc::ptr_eq(weights, &entry.weights) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_residualstreams.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_residualstreams.rs index 6c6bb177..0ea2daca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_residualstreams.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_residualstreams.rs @@ -12,15 +12,11 @@ impl ResidualStreams { return Err(Error::NonFinite); } let mut values = Vec::new(); - values - .try_reserve_exact(4 * EMBEDDING_VALUES) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(4 * EMBEDDING_VALUES).map_err(|_| Error::InputAllocation)?; for _ in 0..4 { values.extend_from_slice(embedding); } - Ok(Self { - values: values.into_boxed_slice(), - }) + Ok(Self { values: values.into_boxed_slice() }) } pub(in super::super) fn values(&self) -> &[f32] { &self.values diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs index a6671d01..4c582196 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs @@ -13,64 +13,22 @@ pub(super) fn ple_cuda( resident: Option<(&DenseWeightCache<'_>, &PleResident)>, ) -> Result { let emb = ple_upload_f32(context, embedding)?; - let key_values = ple_project( - context, - binding, - weights, - PleMatrixRole::Key, - &emb, - resident, - )?; - let value_values = ple_project( - context, - binding, - weights, - PleMatrixRole::Value, - &emb, - resident, - )?; + let key_values = ple_project(context, binding, weights, PleMatrixRole::Key, &emb, resident)?; + let value_values = ple_project(context, binding, weights, PleMatrixRole::Value, &emb, resident)?; emb.release().map_err(ple_driver_error)?; let raw_key = ple_upload_f32(context, &key_values)?; let value = ple_upload_f32(context, &value_values)?; let residual = ple_upload_f32(context, streams)?; let prior = ple_upload_f32(context, history)?; let aux = resident.map(|(c, r)| c.ple_aux(r)).transpose()?; - let norm_key_owned = if aux.is_none() { - Some(ple_upload_f32(context, weights.norm_key())?) - } else { - None - }; - let norm_query_owned = if aux.is_none() { - Some(ple_upload_f32(context, weights.norm_query())?) - } else { - None - }; - let norm_conv_owned = if aux.is_none() { - Some(ple_upload_f32(context, weights.norm_conv())?) - } else { - None - }; - let conv_owned = if aux.is_none() { - Some(ple_upload_u16(context, weights.conv())?) - } else { - None - }; - let norm_key = aux - .map(|v| v[0]) - .or(norm_key_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let norm_query = aux - .map(|v| v[1]) - .or(norm_query_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let norm_conv = aux - .map(|v| v[2]) - .or(norm_conv_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; - let conv_weights = aux - .map(|v| v[3]) - .or(conv_owned.as_ref()) - .ok_or(Error::IdentityMismatch)?; + let norm_key_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_key())?) } else { None }; + let norm_query_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_query())?) } else { None }; + let norm_conv_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_conv())?) } else { None }; + let conv_owned = if aux.is_none() { Some(ple_upload_u16(context, weights.conv())?) } else { None }; + let norm_key = aux.map(|v| v[0]).or(norm_key_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let norm_query = aux.map(|v| v[1]).or(norm_query_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let norm_conv = aux.map(|v| v[2]).or(norm_conv_owned.as_ref()).ok_or(Error::IdentityMismatch)?; + let conv_weights = aux.map(|v| v[3]).or(conv_owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut key = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; let mut query = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; let mut gate = context.allocate(16).map_err(ple_driver_error)?; @@ -78,59 +36,30 @@ pub(super) fn ple_cuda( let mut normalized = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; let mut conv = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; let mut result = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut next = context - .allocate(PLE_HISTORY * 4) - .map_err(ple_driver_error)?; - context - .ple_grouped_norm_f32(&raw_key, norm_key, &mut key) - .map_err(ple_driver_error)?; + let mut next = context.allocate(PLE_HISTORY * 4).map_err(ple_driver_error)?; + context.ple_grouped_norm_f32(&raw_key, norm_key, &mut key).map_err(ple_driver_error)?; let _ = ple_download(&key, PLE_HC)?; - context - .ple_grouped_norm_f32(&residual, norm_query, &mut query) - .map_err(ple_driver_error)?; + context.ple_grouped_norm_f32(&residual, norm_query, &mut query).map_err(ple_driver_error)?; let _ = ple_download(&query, PLE_HC)?; - context - .ple_signed_gate_f32(&key, &query, &mut gate) - .map_err(ple_driver_error)?; + context.ple_signed_gate_f32(&key, &query, &mut gate).map_err(ple_driver_error)?; let _ = ple_download(&gate, 4)?; - context - .ple_broadcast_f32(&value, &gate, &mut gated) - .map_err(ple_driver_error)?; + context.ple_broadcast_f32(&value, &gate, &mut gated).map_err(ple_driver_error)?; let _ = ple_download(&gated, PLE_HC)?; - context - .ple_grouped_norm_f32(&gated, norm_conv, &mut normalized) - .map_err(ple_driver_error)?; + context.ple_grouped_norm_f32(&gated, norm_conv, &mut normalized).map_err(ple_driver_error)?; let _ = ple_download(&normalized, PLE_HC)?; - context - .ple_conv_history_f32(&prior, &normalized, conv_weights, &mut conv, &mut next) - .map_err(ple_driver_error)?; + context.ple_conv_history_f32(&prior, &normalized, conv_weights, &mut conv, &mut next).map_err(ple_driver_error)?; let _ = ple_download(&conv, PLE_HC)?; let next_values = ple_download(&next, PLE_HISTORY)?; - context - .ple_residual_f32(&residual, &gated, &conv, &mut result) - .map_err(ple_driver_error)?; + context.ple_residual_f32(&residual, &gated, &conv, &mut result).map_err(ple_driver_error)?; let result_values = ple_download(&result, PLE_HC)?; // No candidate can escape until fallible owned resource release succeeds. - for buffer in [ - next, result, conv, normalized, gated, gate, query, key, prior, residual, value, raw_key, - ] { + for buffer in [next, result, conv, normalized, gated, gate, query, key, prior, residual, value, raw_key] { buffer.release().map_err(ple_driver_error)?; } - for buffer in [ - conv_owned, - norm_conv_owned, - norm_query_owned, - norm_key_owned, - ] - .into_iter() - .flatten() - { + for buffer in [conv_owned, norm_conv_owned, norm_query_owned, norm_key_owned].into_iter().flatten() { buffer.release().map_err(ple_driver_error)?; } - Ok(PleCandidate { - streams: result_values, - history: next_values, - }) + Ok(PleCandidate { streams: result_values, history: next_values }) } pub(super) fn ple_project( context: &Context<'_>, @@ -149,15 +78,7 @@ pub(super) fn ple_project( let mut output = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; let result = (|| { context - .bf16_f32( - matrix, - embedding, - &mut output, - Bf16ProjectionShape { - rows: PLE_HC, - columns: 2560, - }, - ) + .bf16_f32(matrix, embedding, &mut output, Bf16ProjectionShape { rows: PLE_HC, columns: 2560 }) .map_err(ple_driver_error)?; ple_download(&output, PLE_HC) })(); @@ -168,15 +89,9 @@ pub(super) fn ple_project( close?; return Ok(values); } - let rows = if role == PleMatrixRole::Key { - PLE_HC - } else { - 2560 - }; + let rows = if role == PleMatrixRole::Key { PLE_HC } else { 2560 }; let mut values = Vec::new(); - values - .try_reserve_exact(rows) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(rows).map_err(|_| Error::InputAllocation)?; // Every admitted tile overwrites all 64 outputs. Reuse one scratch buffer // per projection instead of allocating and freeing it for every tile. let mut output = context.allocate(64 * 4).map_err(ple_driver_error)?; @@ -186,9 +101,7 @@ pub(super) fn ple_project( owned = None; cache.ple_value_tile(entry, first)? } else { - let block = binding - .ple_matrix_block(weights, role, first, 64) - .map_err(binding_error)?; + let block = binding.ple_matrix_block(weights, role, first, 64).map_err(binding_error)?; if block.rows() != 64 || block.bytes().len() != 64 * 2560 * 2 { return Err(Error::InvalidDimension); } @@ -196,15 +109,7 @@ pub(super) fn ple_project( owned.as_ref().ok_or(Error::IdentityMismatch)? }; context - .bf16_f32( - matrix, - embedding, - &mut output, - Bf16ProjectionShape { - rows: 64, - columns: 2560, - }, - ) + .bf16_f32(matrix, embedding, &mut output, Bf16ProjectionShape { rows: 64, columns: 2560 }) .map_err(ple_driver_error)?; let decoded = ple_download(&output, 64)?; values.extend_from_slice(&decoded); @@ -216,11 +121,7 @@ pub(super) fn ple_project( Ok(values.into_boxed_slice()) } pub(super) fn ple_budget(context: &Context<'_>) -> Result<()> { - if context - .allocated_bytes() - .checked_add(PLE_DEVICE_PEAK) - .is_none_or(|n| n > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(PLE_DEVICE_PEAK).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } Ok(()) @@ -236,9 +137,7 @@ pub(super) fn ple_values(values: &[f32], count: usize) -> Result<()> { } pub(super) fn ple_zeros(count: usize) -> Result> { let mut values = Vec::new(); - values - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; values.resize(count, 0.0); Ok(values.into_boxed_slice()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_upload_f32_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_upload_f32_fn.rs index f79e9156..0bd489b1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_upload_f32_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_upload_f32_fn.rs @@ -5,9 +5,7 @@ use super::*; pub(super) fn ple_upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for v in values { bytes.extend_from_slice(&v.to_le_bytes()); } @@ -15,9 +13,7 @@ pub(super) fn ple_upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) - } pub(super) fn ple_upload_u16<'ctx>(context: &'ctx Context<'_>, values: &[u16]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(2).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for v in values { bytes.extend_from_slice(&v.to_le_bytes()); } @@ -26,22 +22,12 @@ pub(super) fn ple_upload_u16<'ctx>(context: &'ctx Context<'_>, values: &[u16]) - pub(super) fn ple_download(buffer: &DeviceBuffer<'_>, count: usize) -> Result> { let size = count.checked_mul(4).ok_or(Error::Overflow)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(size) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(size).map_err(|_| Error::InputAllocation)?; bytes.resize(size, 0); buffer.copy_to(&mut bytes).map_err(ple_driver_error)?; let mut values = Vec::new(); - values - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - values.extend( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|w| f32::from_le_bytes(*w)), - ); + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|w| f32::from_le_bytes(*w))); ple_values(&values, count)?; Ok(values.into_boxed_slice()) } @@ -66,56 +52,75 @@ pub(super) fn ple_driver_error(error: DriverError) -> Error { // Original physical prompt source adapter. No fake per-row PleReady or final // history assigned to earlier positions; the Root chunk journal commits the // actual completed end state separately. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl InputStage { pub(in crate::qwen_forward) fn prepare_original_prompt_history<'ctx>( - binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,context:&Context<'_>, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, - )->Result>{ - txn.validate_phase(GrRole::Attention(1),false)?; - let prior=txn.ple_prior()?; - let context=cache.retained_context(binding,context)?; - if !std::ptr::eq(context,txn.context()?){return Err(Error::IdentityMismatch)} - ple_values(&prior.0.history,PLE_HISTORY)?; - let device=context.original_ple_history(&prior.0.history).map_err(ple_driver_error)?; + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + ) -> Result> { + txn.validate_phase(GrRole::Attention(1), false)?; + let prior = txn.ple_prior()?; + let context = cache.retained_context(binding, context)?; + if !std::ptr::eq(context, txn.context()?) { + return Err(Error::IdentityMismatch); + } + ple_values(&prior.0.history, PLE_HISTORY)?; + let device = context.original_ple_history(&prior.0.history).map_err(ple_driver_error)?; cache.validate(binding)?; - Ok(super::super::prompt_device_rows::PromptPleHistory::from_prior(binding.identity(),prior,device)) + Ok(super::super::prompt_device_rows::PromptPleHistory::from_prior(binding.identity(), prior, device)) } pub(in crate::qwen_forward) fn finish_original_prompt_history( - binding:&ModelBinding,txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, - prior:&PlePrior,completed:super::super::prompt_device_rows::PromptPleHistory<'_>, - )->Result<()> { - let next=Self::finish_prompt_device_history(binding,prior,completed)?; - txn.stage_ple(prior,next) + binding: &ModelBinding, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + prior: &PlePrior, + completed: super::super::prompt_device_rows::PromptPleHistory<'_>, + ) -> Result<()> { + let next = Self::finish_prompt_device_history(binding, prior, completed)?; + txn.stage_ple(prior, next) } - pub(in super::super) fn prepare_prompt_device_source<'source,'ctx>( - binding:&ModelBinding,context:&'ctx Context<'ctx>,input:&'source InputReady, - txn:&QwenStepTxn<'_, '_>, - )->Result>{ - super::super::prompt_device_rows::PromptDeviceSource::from_current(binding,context,input,txn) + pub(in super::super) fn prepare_prompt_device_source<'source, 'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + input: &'source InputReady, + txn: &QwenStepTxn<'_, '_>, + ) -> Result> { + super::super::prompt_device_rows::PromptDeviceSource::from_current(binding, context, input, txn) } pub(in super::super) fn prepare_prompt_device_history<'ctx>( - binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,context:&Context<'_>, - prior:&PlePrior,txn:&QwenStepTxn<'_, '_>, - )->Result>{ - txn.validate_binding(&binding.identity())?;txn.validate_ple_prior(prior)?; - let context=cache.retained_context(binding,context)?; - if !std::ptr::eq(context,txn.cuda_context()?){return Err(Error::IdentityMismatch)} - ple_values(&prior.0.history,PLE_HISTORY)?; - let device=context.original_ple_history(&prior.0.history).map_err(ple_driver_error)?; + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + prior: &PlePrior, + txn: &QwenStepTxn<'_, '_>, + ) -> Result> { + txn.validate_binding(&binding.identity())?; + txn.validate_ple_prior(prior)?; + let context = cache.retained_context(binding, context)?; + if !std::ptr::eq(context, txn.cuda_context()?) { + return Err(Error::IdentityMismatch); + } + ple_values(&prior.0.history, PLE_HISTORY)?; + let device = context.original_ple_history(&prior.0.history).map_err(ple_driver_error)?; cache.validate(binding)?; - Ok(super::super::prompt_device_rows::PromptPleHistory::from_prior(binding.identity(),prior.clone(),device)) + Ok(super::super::prompt_device_rows::PromptPleHistory::from_prior(binding.identity(), prior.clone(), device)) } pub(in super::super) fn finish_prompt_device_history( - binding:&ModelBinding,prior:&PlePrior, - completed:super::super::prompt_device_rows::PromptPleHistory<'_>, - )->Result{ - let (actual_prior,count,history)=completed.into_completed(binding,prior)?; - if count==0||count>8192||!actual_prior.same_state(prior){return Err(Error::IdentityMismatch)} - ple_values(&history,PLE_HISTORY)?; - Ok(PlePrior(Rc::new(PleState{ - binding:prior.0.binding.clone(),owner:prior.0.owner.clone(), - next_position:prior.next_position().checked_add(count as u64).ok_or(Error::Overflow)?,history, + binding: &ModelBinding, + prior: &PlePrior, + completed: super::super::prompt_device_rows::PromptPleHistory<'_>, + ) -> Result { + let (actual_prior, count, history) = completed.into_completed(binding, prior)?; + if count == 0 || count > 8192 || !actual_prior.same_state(prior) { + return Err(Error::IdentityMismatch); + } + ple_values(&history, PLE_HISTORY)?; + Ok(PlePrior(Rc::new(PleState { + binding: prior.0.binding.clone(), + owner: prior.0.owner.clone(), + next_position: prior.next_position().checked_add(count as u64).ok_or(Error::Overflow)?, + history, }))) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input_hash.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input_hash.rs index f89f942d..cfe43abb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input_hash.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input_hash.rs @@ -1,16 +1,8 @@ use super::super::contract::{Error, Result}; use crate::model_binding::qwen4exp_input::{InputConstants, PLE_ROWS, VOCABULARY}; -pub(super) fn rows( - token: u32, - predecessors: [i32; 2], - constants: &InputConstants, -) -> Result<[u64; 16]> { - if token >= VOCABULARY - || predecessors - .iter() - .any(|&v| v < -1 || v >= VOCABULARY as i32) - { +pub(super) fn rows(token: u32, predecessors: [i32; 2], constants: &InputConstants) -> Result<[u64; 16]> { + if token >= VOCABULARY || predecessors.iter().any(|&v| v < -1 || v >= VOCABULARY as i32) { return Err(Error::InvalidToken); } let context = context(token, predecessors, constants.eos()); @@ -18,9 +10,7 @@ pub(super) fn rows( for (head, row) in output.iter_mut().enumerate() { let count = if head < 8 { 2 } else { 3 }; let hash = mixed(&context[..count], constants.multipliers()); - *row = (hash % constants.vocabularies()[head]) - .checked_add(constants.offsets()[head]) - .ok_or(Error::Overflow)?; + *row = (hash % constants.vocabularies()[head]).checked_add(constants.offsets()[head]).ok_or(Error::Overflow)?; if *row >= PLE_ROWS { return Err(Error::InvalidDimension); } @@ -37,12 +27,7 @@ fn context(token: u32, predecessors: [i32; 2], eos: u32) -> [u64; 3] { context } fn mixed(context: &[u64], multipliers: &[u64; 3]) -> u64 { - context - .iter() - .zip(multipliers) - .fold(0, |hash, (&token, &multiplier)| { - hash ^ token.wrapping_mul(multiplier) - }) + context.iter().zip(multipliers).fold(0, |hash, (&token, &multiplier)| hash ^ token.wrapping_mul(multiplier)) } #[cfg(test)] @@ -61,24 +46,10 @@ mod tests { #[test] fn wrapping_recurrence_does_not_widen_token_domain() { let constants = InputConstants::test_fixture(); - for (count, expected) in [ - (2, reference::RAW_WRAP_MIXED[0]), - (3, reference::RAW_WRAP_MIXED[1]), - ] { - assert_eq!( - mixed( - &reference::RAW_WRAP_CONTEXT[..count], - constants.multipliers() - ), - expected - ); + for (count, expected) in [(2, reference::RAW_WRAP_MIXED[0]), (3, reference::RAW_WRAP_MIXED[1])] { + assert_eq!(mixed(&reference::RAW_WRAP_CONTEXT[..count], constants.multipliers()), expected); } - for (token, prior) in [ - (248320, [0, 0]), - (u32::MAX, [-1, -1]), - (0, [-2, 1]), - (0, [1, 248320]), - ] { + for (token, prior) in [(248320, [0, 0]), (u32::MAX, [-1, -1]), (0, [-2, 1]), (0, [1, 248320])] { assert_eq!(rows(token, prior, &constants), Err(Error::InvalidToken)); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs index 1bd8d1ad..5c29d0ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache.rs @@ -122,16 +122,16 @@ mod lru_tests; mod scratch_bytes_fn; #[allow(unused_imports)] -use scratch_bytes_fn::scratch_bytes; +use scratch_bytes_fn::assign_slots; #[allow(unused_imports)] use scratch_bytes_fn::lookup_rows; #[allow(unused_imports)] -use scratch_bytes_fn::assign_slots; -#[allow(unused_imports)] use scratch_bytes_fn::plan_gather; +#[allow(unused_imports)] +use scratch_bytes_fn::scratch_bytes; mod publish_gather_fn; #[allow(unused_imports)] -use publish_gather_fn::publish_gather; -#[allow(unused_imports)] use publish_gather_fn::ahead_enabled; +#[allow(unused_imports)] +use publish_gather_fn::publish_gather; mod impl_karplecache; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/impl_karplecache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/impl_karplecache.rs index 83cc8392..978d4371 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/impl_karplecache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/impl_karplecache.rs @@ -5,51 +5,30 @@ use super::*; impl<'ctx> KarPleCache<'ctx> { pub(crate) fn new(context: &'ctx Context<'ctx>, binding: &KarPleBinding) -> Result { - let book_bytes = binding - .books() - .len() - .checked_mul(8) - .ok_or(Error::Overflow)?; + let book_bytes = binding.books().len().checked_mul(8).ok_or(Error::Overflow)?; let needed = CACHE_BYTES .checked_add(book_bytes) .and_then(|n| n.checked_add(64 + OUTPUT_BYTES + scratch_bytes())) .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } let mut data = Vec::new(); - data.try_reserve_exact(book_bytes) - .map_err(|_| Error::InputAllocation)?; + data.try_reserve_exact(book_bytes).map_err(|_| Error::InputAllocation)?; for book in binding.books() { for value in book { data.extend_from_slice(&value.to_le_bytes()); } } - let cache = context - .allocate(CACHE_BYTES) - .map_err(|_| Error::CudaExecution)?; - let mut books = context - .allocate(book_bytes) - .map_err(|_| Error::CudaExecution)?; + let cache = context.allocate(CACHE_BYTES).map_err(|_| Error::CudaExecution)?; + let mut books = context.allocate(book_bytes).map_err(|_| Error::CudaExecution)?; books.copy_from(&data).map_err(|_| Error::CudaExecution)?; let slots = context.allocate(64).map_err(|_| Error::CudaExecution)?; - let output = context - .allocate(OUTPUT_BYTES) - .map_err(|_| Error::CudaExecution)?; + let output = context.allocate(OUTPUT_BYTES).map_err(|_| Error::CudaExecution)?; let mut scratch = Vec::new(); - scratch - .try_reserve_exact(MAX_MISSES) - .map_err(|_| Error::InputAllocation)?; + scratch.try_reserve_exact(MAX_MISSES).map_err(|_| Error::InputAllocation)?; for misses in 1..=MAX_MISSES { - scratch.push( - context - .allocate(misses * UPDATE_RECORD_BYTES) - .map_err(|_| Error::CudaExecution)?, - ); + scratch.push(context.allocate(misses * UPDATE_RECORD_BYTES).map_err(|_| Error::CudaExecution)?); } Ok(Self { ahead: Ahead::default(), @@ -103,20 +82,14 @@ impl<'ctx> KarPleCache<'ctx> { return Err(Error::InvalidDimension); } let stamp = self.age.checked_add(1).ok_or(Error::Overflow)?; - let Lookup { - mut slots, - miss_rows, - pending, - } = lookup_rows(&mut self.entries, rows, stamp)?; + let Lookup { mut slots, miss_rows, pending } = lookup_rows(&mut self.entries, rows, stamp)?; let packets = if miss_rows.is_empty() { Vec::new() } else { self.ahead.collect(); // the rows the read-ahead already holds come from it; the others are read now, as before let mut packets = Vec::>::new(); - packets - .try_reserve_exact(miss_rows.len()) - .map_err(|_| Error::InputAllocation)?; + packets.try_reserve_exact(miss_rows.len()).map_err(|_| Error::InputAllocation)?; let mut rest_at = Vec::::new(); let mut rest_rows = Vec::::new(); let mut from_ahead = Vec::<(usize, u64)>::new(); @@ -134,9 +107,7 @@ impl<'ctx> KarPleCache<'ctx> { } } if !rest_rows.is_empty() { - let read = binding - .read_rows_batch(&rest_rows) - .map_err(super::super::input::binding_error)?; + let read = binding.read_rows_batch(&rest_rows).map_err(super::super::input::binding_error)?; if read.len() != rest_rows.len() { return Err(Error::InvalidDimension); } @@ -147,9 +118,7 @@ impl<'ctx> KarPleCache<'ctx> { // LELEKA_PLE_AHEAD_VERIFY=1: every packet taken from the read-ahead is compared with a direct read of its row if !from_ahead.is_empty() && crate::settings::process().kv.ple_ahead_verify { let rows: Vec = from_ahead.iter().map(|(_, row)| *row).collect(); - let direct = binding - .read_rows_batch(&rows) - .map_err(super::super::input::binding_error)?; + let direct = binding.read_rows_batch(&rows).map_err(super::super::input::binding_error)?; for ((at, row), direct) in from_ahead.iter().zip(&direct) { let held = packets[*at].as_ref().ok_or(Error::InvalidDimension)?; if held.payload() != direct.payload() || held.partition() != direct.partition() { @@ -157,40 +126,30 @@ impl<'ctx> KarPleCache<'ctx> { return Err(Error::IdentityMismatch); } } - eprintln!("leleka-ple-ahead: {} of {} missed rows came from the read-ahead, all equal to a direct read", from_ahead.len(), miss_rows.len()); + eprintln!( + "leleka-ple-ahead: {} of {} missed rows came from the read-ahead, all equal to a direct read", + from_ahead.len(), + miss_rows.len() + ); } - packets - .into_iter() - .collect::>>() - .ok_or(Error::InvalidDimension)? + packets.into_iter().collect::>>().ok_or(Error::InvalidDimension)? }; let misses = miss_rows.len(); - let (miss_slot, victims, next_slot) = - assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; + let (miss_slot, victims, next_slot) = assign_slots(&self.entries, self.next_slot, SLOTS, stamp, misses)?; for (at, miss) in pending { slots[at as usize] = miss_slot[miss as usize]; } let mut updates = Vec::new(); - updates - .try_reserve_exact(misses * 56) - .map_err(|_| Error::InputAllocation)?; + updates.try_reserve_exact(misses * 56).map_err(|_| Error::InputAllocation)?; let mut inserts = Vec::new(); - inserts - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; + inserts.try_reserve_exact(misses).map_err(|_| Error::InputAllocation)?; for (i, packet) in packets.iter().enumerate() { updates.extend_from_slice(&miss_slot[i].to_le_bytes()); updates.extend_from_slice(packet.payload()); updates.extend_from_slice(&packet.partition().to_le_bytes()); inserts.push((miss_rows[i], miss_slot[i], victims[i])); } - Ok(KarPleStaged { - updates, - slots, - inserts, - next_slot, - stamp, - }) + Ok(KarPleStaged { updates, slots, inserts, next_slot, stamp }) } /// Start reading, on a thread of its own, the packets of the PLE `rows` (the sixteen rows of each token of the /// chunk after the one being computed) that neither the device cache nor an earlier read-ahead holds. Call it @@ -246,11 +205,7 @@ impl<'ctx> KarPleCache<'ctx> { self.next_slot = staged.next_slot; self.age = staged.stamp; } - pub(in super::super) fn gather( - &mut self, - binding: &KarPleBinding, - rows: &[u64; 16], - ) -> Result> { + pub(in super::super) fn gather(&mut self, binding: &KarPleBinding, rows: &[u64; 16]) -> Result> { if self.failed { return Err(Error::CudaExecution); } @@ -267,23 +222,14 @@ impl<'ctx> KarPleCache<'ctx> { } let packets = if rows.iter().any(|r| !self.entries.contains_key(r)) { let _p = super::super::original_serve_profile::span("ple.read_rows"); - Some( - binding - .read_rows(rows) - .map_err(super::super::input::binding_error)?, - ) + Some(binding.read_rows(rows).map_err(super::super::input::binding_error)?) } else { None }; - let GatherPlan { - misses: planned, - selected, - next_slot, - } = plan_gather(&self.entries, self.next_slot, SLOTS, rows)?; + let GatherPlan { misses: planned, selected, next_slot } = + plan_gather(&self.entries, self.next_slot, SLOTS, rows)?; let mut misses = Vec::::new(); - misses - .try_reserve_exact(planned.len()) - .map_err(|_| Error::InputAllocation)?; + misses.try_reserve_exact(planned.len()).map_err(|_| Error::InputAllocation)?; for p in &planned { let packet = &packets.as_ref().expect("missing rows require packets")[p.at]; misses.push(Miss { @@ -295,13 +241,9 @@ impl<'ctx> KarPleCache<'ctx> { }); } let growth = misses.iter().filter(|m| m.victim.is_none()).count(); - self.entries - .try_reserve(growth) - .map_err(|_| Error::InputAllocation)?; + self.entries.try_reserve(growth).map_err(|_| Error::InputAllocation)?; let mut updates = Vec::new(); - updates - .try_reserve_exact(misses.len() * 56) - .map_err(|_| Error::InputAllocation)?; + updates.try_reserve_exact(misses.len() * 56).map_err(|_| Error::InputAllocation)?; for m in &misses { updates.extend_from_slice(&m.slot.to_le_bytes()); updates.extend_from_slice(&m.payload); @@ -312,14 +254,10 @@ impl<'ctx> KarPleCache<'ctx> { slot_bytes[i * 4..i * 4 + 4].copy_from_slice(&slot.to_le_bytes()); } let mut output = Vec::new(); - output - .try_reserve_exact(OUTPUT_BYTES) - .map_err(|_| Error::InputAllocation)?; + output.try_reserve_exact(OUTPUT_BYTES).map_err(|_| Error::InputAllocation)?; output.resize(OUTPUT_BYTES, 0); let mut values = Vec::new(); - values - .try_reserve_exact(2560) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; // From the first mutating operation onward, any failure permanently invalidates // this cache, including a partial scatter; no stale success mapping is reusable. let _device_span = super::super::original_serve_profile::span("ple.device"); @@ -330,22 +268,16 @@ impl<'ctx> KarPleCache<'ctx> { .get_mut(misses.len() - 1) .filter(|b| b.len() == updates.len()) .ok_or(Error::CudaExecution)?; - device - .copy_from(&updates) - .map_err(|_| Error::CudaExecution)?; + device.copy_from(&updates).map_err(|_| Error::CudaExecution)?; self.context .kar_ple_scatter(&mut self.cache, device, misses.len() as u32) .map_err(|_| Error::CudaExecution)?; } - self.slots - .copy_from(&slot_bytes) - .map_err(|_| Error::CudaExecution)?; + self.slots.copy_from(&slot_bytes).map_err(|_| Error::CudaExecution)?; self.context .kar_ple_decode(&self.cache, &self.slots, &self.books, &mut self.output) .map_err(|_| Error::CudaExecution)?; - self.output - .copy_to(&mut output) - .map_err(|_| Error::CudaExecution)?; + self.output.copy_to(&mut output).map_err(|_| Error::CudaExecution)?; for word in output.as_chunks::<4>().0 { let v = f32::from_le_bytes(*word); if !v.is_finite() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs index fe643617..f6435ba6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/lru_tests.rs @@ -13,11 +13,7 @@ impl Rng { } /// Half the draws from a hot set, the rest from the whole universe. fn row(&mut self, hot: u64, universe: u64) -> u64 { - if self.next() % 2 == 0 { - self.next() % hot - } else { - self.next() % universe - } + if self.next() % 2 == 0 { self.next() % hot } else { self.next() % universe } } } @@ -30,12 +26,7 @@ struct Scan { } impl Scan { fn new(capacity: u32) -> Self { - Self { - map: HashMap::new(), - next_slot: 0, - age: 0, - capacity, - } + Self { map: HashMap::new(), next_slot: 0, age: 0, capacity } } /// (selected slots, misses as (row, slot, victim)) exactly as `KarPleCache::gather` chose them before the recency queue. fn gather(&mut self, rows: &[u64; 16]) -> ([u32; 16], Vec<(u64, u32, Option)>) { @@ -93,7 +84,9 @@ fn token(rng: &mut Rng, hot: u64, universe: u64) -> [u64; 16] { /// and ends in the same state as the full scan, and every gathered row is its own row. #[test] fn gather_equals_the_full_scan_on_random_sequences() { - for (capacity, hot, universe, seed) in [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] { + for (capacity, hot, universe, seed) in + [(64u32, 40u64, 500u64, 1u64), (257, 200, 3000, 2), (1000, 300, 1200, 3), (32, 20, 40, 4)] + { let mut rng = Rng(0x9e3779b97f4a7c15 ^ seed); let mut old = Scan::new(capacity); let mut new = Residents::default(); @@ -115,7 +108,10 @@ fn gather_equals_the_full_scan_on_random_sequences() { next_slot = plan.next_slot; age += 16; for (i, row) in rows.iter().enumerate() { - assert_eq!(device.0[plan.selected[i] as usize], *row, "step {step} position {i}: wrong row in the slot"); + assert_eq!( + device.0[plan.selected[i] as usize], *row, + "step {step} position {i}: wrong row in the slot" + ); } } assert!(evictions > 1000, "capacity {capacity}: the cache never filled ({evictions} evictions)"); @@ -124,7 +120,12 @@ fn gather_equals_the_full_scan_on_random_sequences() { a.sort(); b.sort(); assert_eq!(a, b, "capacity {capacity}: final state"); - assert!(new.order.len() <= 2 * new.len() + 4096 + 16, "queue grew to {} for {} rows", new.order.len(), new.len()); + assert!( + new.order.len() <= 2 * new.len() + 4096 + 16, + "queue grew to {} for {} rows", + new.order.len(), + new.len() + ); } } @@ -144,14 +145,19 @@ fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { let rows: Vec<[u64; 16]> = (0..n).map(|_| token(&mut rng, 150, 2500)).collect(); let stamp = age + 1; let lookup = lookup_rows(&mut entries, &rows, stamp).unwrap(); - let (miss_slot, victims, next) = assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); + let (miss_slot, victims, next) = + assign_slots(&entries, next_slot, capacity, stamp, lookup.miss_rows.len()).unwrap(); // a victim is no younger than any row left in the cache that the chunk did not touch let youngest_victim = victims.iter().flatten().map(|v| entries.map[v].age).max(); if let Some(limit) = youngest_victim { let victims_set: std::collections::HashSet = victims.iter().flatten().copied().collect(); for (r, e) in &entries.map { if e.age < stamp && !victims_set.contains(r) { - assert!(e.age >= limit, "step {step}: row {r} (age {}) outlived a victim of age {limit}", e.age); + assert!( + e.age >= limit, + "step {step}: row {r} (age {}) outlived a victim of age {limit}", + e.age + ); } } } @@ -193,11 +199,7 @@ fn chunks_and_gathers_interleaved_keep_every_row_in_its_own_slot() { } assert!(entries.len() <= capacity as usize); // one live queue item per row - let live = entries - .order - .iter() - .filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)) - .count(); + let live = entries.order.iter().filter(|(a, r)| entries.map.get(r).is_some_and(|e| e.age == *a)).count(); assert_eq!(live, entries.len(), "step {step}"); } assert!(chunk_evictions > 500, "the chunks never evicted ({chunk_evictions})"); @@ -294,11 +296,7 @@ fn scan_against_queue_on_a_full_cache() { let n = 20; for _ in 0..n { std::hint::black_box( - old.map - .iter() - .filter(|(r, _)| !rows.contains(r)) - .min_by_key(|(_, e)| e.1) - .map(|(r, _)| *r), + old.map.iter().filter(|(r, _)| !rows.contains(r)).min_by_key(|(_, e)| e.1).map(|(r, _)| *r), ); } let scan = t.elapsed() / n; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/publish_gather_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/publish_gather_fn.rs index 425be820..dd898a1a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/publish_gather_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/publish_gather_fn.rs @@ -13,9 +13,7 @@ pub(super) fn publish_gather(entries: &mut Residents, misses: &[PlannedMiss], ro entries.insert(m.row, m.slot, age_base + 1); } for (i, row) in rows.iter().enumerate() { - entries - .touch(row, age_base + i as u64 + 1) - .expect("completed batch mapping"); + entries.touch(row, age_base + i as u64 + 1).expect("completed batch mapping"); } } /// `LELEKA_PLE_AHEAD=on|off` (read once) turns the read-ahead of the next chunk's PLE packets on or off. Unset: on for Windows, where the diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs index da7b4f8a..6bcc9b73 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/row_parity_probe.rs @@ -33,18 +33,15 @@ fn dump_decoded_rows_for_original_comparison() { } let file = std::fs::File::open(archive).expect("archive opens"); let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); + let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); let identity = BindingIdentity::test_identity(); let binding = KarPleBinding::new(&identity, artifact).expect("binding"); let driver = Driver::load().expect("driver"); let device = driver.device(0).expect("device0"); let context = device.create_context(2usize << 30).expect("context"); let mut cache = KarPleCache::new(&context, &binding).expect("cache"); - let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP") - .ok() - .map(|p| std::fs::File::create(p).expect("dump file")); + let mut dump = std::env::var("LELEKA_PLE_PROBE_DUMP").ok().map(|p| std::fs::File::create(p).expect("dump file")); let mut done = 0; for chunk in rows.chunks_exact(16) { let batch: [u64; 16] = chunk.try_into().unwrap(); @@ -69,9 +66,8 @@ fn batch_read_equals_the_sixteen_row_reads() { let archive = std::env::var("LELEKA_PLE_PROBE_ARCHIVE").expect("archive path"); let file = std::fs::File::open(archive).expect("archive opens"); let inspection = KarInspection::inspect(file).expect("inspect"); - let artifact = - VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) - .expect("pinned verify"); + let artifact = VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), pinned_profile().unwrap()) + .expect("pinned verify"); let identity = BindingIdentity::test_identity(); let binding = KarPleBinding::new(&identity, artifact).expect("binding"); // a deterministic spread over the whole table plus the first and last rows, more than one reader thread's share diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/scratch_bytes_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/scratch_bytes_fn.rs index a0dc393a..f10b9266 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/scratch_bytes_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/scratch_bytes_fn.rs @@ -33,7 +33,10 @@ impl Residents { pub(super) fn contains_key(&self, row: &u64) -> bool { self.map.contains_key(row) } - pub(super) fn try_reserve(&mut self, additional: usize) -> std::result::Result<(), std::collections::TryReserveError> { + pub(super) fn try_reserve( + &mut self, + additional: usize, + ) -> std::result::Result<(), std::collections::TryReserveError> { self.map.try_reserve(additional)?; self.order.try_reserve(additional) } @@ -71,10 +74,14 @@ impl Residents { /// The `need` least recently used rows with age below `below` that `skip` does not name, oldest first, as `(row, slot)` /// (rows of equal age in queue order); fewer when the cache holds fewer. Also returns how many items were examined: the cost, /// which a test bounds. The queue answers; the full scan runs only when the queue gave fewer rows than asked. - pub(super) fn oldest(&self, need: usize, below: u64, skip: impl Fn(u64) -> bool) -> Result<(Vec<(u64, u32)>, usize)> { + pub(super) fn oldest( + &self, + need: usize, + below: u64, + skip: impl Fn(u64) -> bool, + ) -> Result<(Vec<(u64, u32)>, usize)> { let mut out = Vec::<(u64, u32)>::new(); - out.try_reserve_exact(need.min(self.map.len())) - .map_err(|_| Error::InputAllocation)?; + out.try_reserve_exact(need.min(self.map.len())).map_err(|_| Error::InputAllocation)?; let mut examined = 0usize; for &(age, row) in &self.order { if out.len() == need || age >= below { @@ -89,14 +96,8 @@ impl Residents { } if out.len() < need { let mut all: Vec<(u64, u64, u32)> = Vec::new(); - all.try_reserve_exact(self.map.len()) - .map_err(|_| Error::InputAllocation)?; - all.extend( - self.map - .iter() - .filter(|(r, e)| e.age < below && !skip(**r)) - .map(|(r, e)| (e.age, *r, e.slot)), - ); + all.try_reserve_exact(self.map.len()).map_err(|_| Error::InputAllocation)?; + all.extend(self.map.iter().filter(|(r, e)| e.age < below && !skip(**r)).map(|(r, e)| (e.age, *r, e.slot))); examined += self.map.len(); if all.len() > out.len() { let take = need.min(all.len()); @@ -125,9 +126,7 @@ impl KarPleStaged { pub(super) fn lookup_rows(entries: &mut Residents, rows: &[[u64; 16]], stamp: u64) -> Result { let total = rows.len().checked_mul(16).ok_or(Error::Overflow)?; let mut slots = Vec::new(); - slots - .try_reserve_exact(total) - .map_err(|_| Error::InputAllocation)?; + slots.try_reserve_exact(total).map_err(|_| Error::InputAllocation)?; let mut miss_rows = Vec::::new(); let mut miss_of = RowMap::::default(); let mut pending = Vec::<(u32, u32)>::new(); @@ -148,11 +147,7 @@ pub(super) fn lookup_rows(entries: &mut Residents, rows: &[[u64; 16]], stamp: u6 slots.push(u32::MAX); pending.push((at as u32, miss)); } - Ok(Lookup { - slots, - miss_rows, - pending, - }) + Ok(Lookup { slots, miss_rows, pending }) } /// A slot for each missing row: free slots first (`next_slot..capacity`), then the least recently used rows the chunk /// did not touch (age below `stamp`). Returns the slot and the evicted row (if any) per miss, and the new `next_slot`. @@ -167,13 +162,9 @@ pub(super) fn assign_slots( let free = (capacity - next_slot) as usize; let from_free = free.min(misses); let mut miss_slot = Vec::::new(); - miss_slot - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; + miss_slot.try_reserve_exact(misses).map_err(|_| Error::InputAllocation)?; let mut victims = Vec::>::new(); - victims - .try_reserve_exact(misses) - .map_err(|_| Error::InputAllocation)?; + victims.try_reserve_exact(misses).map_err(|_| Error::InputAllocation)?; for i in 0..from_free { miss_slot.push(next_slot + i as u32); victims.push(None); @@ -194,7 +185,12 @@ pub(super) fn assign_slots( /// The slot of each of the sixteen rows of one token: held rows keep theirs, each distinct missing row gets a free slot /// (`next_slot..capacity`) or the slot of the least recently used row that is neither one of the sixteen nor already a victim. /// Nothing is mutated. -pub(super) fn plan_gather(entries: &Residents, mut next_slot: u32, capacity: u32, rows: &[u64; 16]) -> Result { +pub(super) fn plan_gather( + entries: &Residents, + mut next_slot: u32, + capacity: u32, + rows: &[u64; 16], +) -> Result { let mut misses = Vec::::new(); misses.try_reserve_exact(16).map_err(|_| Error::InputAllocation)?; let mut selected = [0u32; 16]; @@ -212,23 +208,13 @@ pub(super) fn plan_gather(entries: &Residents, mut next_slot: u32, capacity: u32 next_slot += 1; (slot, None) } else { - let (oldest, _) = entries.oldest(1, u64::MAX, |r| { - rows.contains(&r) || misses.iter().any(|m| m.victim == Some(r)) - })?; + let (oldest, _) = + entries.oldest(1, u64::MAX, |r| rows.contains(&r) || misses.iter().any(|m| m.victim == Some(r)))?; let &(victim, slot) = oldest.first().ok_or(Error::InvalidDimension)?; (slot, Some(victim)) }; selected[i] = slot; - misses.push(PlannedMiss { - at: i, - row: *row, - slot, - victim, - }); + misses.push(PlannedMiss { at: i, row: *row, slot, victim }); } - Ok(GatherPlan { - misses, - selected, - next_slot, - }) + Ok(GatherPlan { misses, selected, next_slot }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs index 16852964..83891d8b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/kar_ple_cache/slot_tests.rs @@ -3,13 +3,7 @@ use super::*; /// What `KarPleCache::commit` does to the map, over the pure parts. -fn apply( - entries: &mut Residents, - lookup: &Lookup, - miss_slot: &[u32], - victims: &[Option], - stamp: u64, -) { +fn apply(entries: &mut Residents, lookup: &Lookup, miss_slot: &[u32], victims: &[Option], stamp: u64) { for victim in victims.iter().flatten() { entries.remove(victim); } @@ -35,9 +29,7 @@ fn the_scatter_staging_buffers_match_the_update_records() { } fn chunk(rows: &[u64]) -> Vec<[u64; 16]> { - rows.chunks(16) - .map(|c| std::array::from_fn(|i| c[i % c.len()])) - .collect() + rows.chunks(16).map(|c| std::array::from_fn(|i| c[i % c.len()])).collect() } /// Every row maps to one slot and no slot serves two rows. fn consistent(entries: &Residents) { @@ -176,8 +168,5 @@ fn a_chunk_that_needs_more_slots_than_the_untouched_rows_hold_is_refused() { // touches 6 of the 8 rows and needs 4 new ones: only 2 rows are evictable let lookup = lookup_rows(&mut entries, &chunk(&[0, 1, 2, 3, 4, 5, 90, 91, 92, 93]), 2).unwrap(); assert_eq!(lookup.miss_rows.len(), 4); - assert_eq!( - assign_slots(&entries, next, 8, 2, 4).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(assign_slots(&entries, next, 8, 2, 4).err(), Some(Error::InvalidDimension)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs index c1f6c6c5..0886e2a8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/layer0_mmq_observation.rs @@ -46,12 +46,7 @@ impl Scope { reserve(&mut arm.shared, ROWS * N)?; reserve(&mut arm.final_values, ROWS * N)?; } - *state = Some(Capture { - report, - arm: None, - row: None, - complete: false, - }); + *state = Some(Capture { report, arm: None, row: None, complete: false }); Ok(Self) }) } @@ -62,10 +57,7 @@ impl Scope { if !capture.complete || capture.arm.is_some() || capture.row.is_some() { return Err(Error::IdentityMismatch); } - state - .take() - .map(|c| c.report) - .ok_or(Error::IdentityMismatch) + state.take().map(|c| c.report).ok_or(Error::IdentityMismatch) }) } } @@ -77,17 +69,11 @@ impl Drop for Scope { } } fn reserve(values: &mut Vec, len: usize) -> Result<()> { - values - .try_reserve_exact(len) - .map_err(|_| Error::InputAllocation) + values.try_reserve_exact(len).map_err(|_| Error::InputAllocation) } fn with_capture(f: impl FnOnce(&mut Capture) -> Result) -> Result { ACTIVE.with(|cell| { - f(cell - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)? - .as_mut() - .ok_or(Error::IdentityMismatch)?) + f(cell.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.as_mut().ok_or(Error::IdentityMismatch)?) }) } pub(crate) fn enabled() -> bool { @@ -113,12 +99,7 @@ pub(crate) fn input(index: usize, values: &[f32], ids: &[u32], weights: &[f32]) Ok(()) }) } -pub(crate) fn validate_input( - index: usize, - values: &[f32], - ids: &[u32], - weights: &[f32], -) -> Result<()> { +pub(crate) fn validate_input(index: usize, values: &[f32], ids: &[u32], weights: &[f32]) -> Result<()> { with_capture(|c| { if index >= ROWS || values.len() != N @@ -128,17 +109,12 @@ pub(crate) fn validate_input( { return Err(Error::IdentityMismatch); } - if !values - .iter() - .map(|v| v.to_bits()) - .eq(c.report.input[index * N..(index + 1) * N].iter().copied()) + if !values.iter().map(|v| v.to_bits()).eq(c.report.input[index * N..(index + 1) * N].iter().copied()) || ids != &c.report.ids[index * SLOTS..(index + 1) * SLOTS] || !weights .iter() .map(|v| v.to_bits()) - .eq(c.report.weights[index * SLOTS..(index + 1) * SLOTS] - .iter() - .copied()) + .eq(c.report.weights[index * SLOTS..(index + 1) * SLOTS].iter().copied()) { return Err(Error::IdentityMismatch); } @@ -178,10 +154,7 @@ pub(crate) fn row(position: u64) -> Result<()> { with_capture(|c| { let i = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; let a = c.arm.ok_or(Error::IdentityMismatch)?; - if i >= ROWS - || c.report.arms[a].packed.len() != i * SLOTS * N - || c.report.arms[a].shared.len() != i * N - { + if i >= ROWS || c.report.arms[a].packed.len() != i * SLOTS * N || c.report.arms[a].shared.len() != i * N { return Err(Error::IdentityMismatch); } c.row = Some(i); @@ -231,9 +204,7 @@ pub(crate) fn complete(witness: [u64; 3]) -> Result<()> { || c.report.ids.len() != ROWS * SLOTS || c.report.weights.len() != ROWS * SLOTS || c.report.arms.iter().any(|a| { - a.packed.len() != ROWS * SLOTS * N - || a.shared.len() != ROWS * N - || a.final_values.len() != ROWS * N + a.packed.len() != ROWS * SLOTS * N || a.shared.len() != ROWS * N || a.final_values.len() != ROWS * N }) { return Err(Error::IdentityMismatch); @@ -246,14 +217,7 @@ pub(crate) fn complete(witness: [u64; 3]) -> Result<()> { Ok(()) }) } -fn comparison( - role: &str, - row: usize, - slot: Option, - expert: Option, - a: &[u32], - b: &[u32], -) -> String { +fn comparison(role: &str, row: usize, slot: Option, expert: Option, a: &[u32], b: &[u32]) -> String { assert_eq!(a.len(), b.len()); let first = a.iter().zip(b).position(|(a, b)| a != b); let count = a.iter().zip(b).filter(|(a, b)| a != b).count(); @@ -262,10 +226,7 @@ fn comparison( .zip(b) .map(|(a, b)| (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs()) .fold(0.0, f64::max); - format!( - "{role}\t{row}\t{slot:?}\t{expert:?}\t{}\t{count}\t{first:?}\t{max}\n", - a.len() - ) + format!("{role}\t{row}\t{slot:?}\t{expert:?}\t{}\t{count}\t{first:?}\t{max}\n", a.len()) } impl Report { pub(crate) fn write_after_cleanup(&self, root: &Path) -> std::io::Result<()> { @@ -295,10 +256,7 @@ impl Report { use sha2::Digest; use std::fmt::Write as _; total += words.len(); - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(root.join(name))?; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(root.join(name))?; let mut digest = sha2::Sha256::new(); for word in words { let b = word.to_le_bytes(); @@ -313,8 +271,7 @@ impl Report { manifest.push_str(&format!("{name}\t{}\t{hex}\n", words.len())); } assert_eq!(total, RAW_WORDS); - let mut comparisons = - String::from("role\trow\tslot\texpert\twords\tdifferent\tfirst_word\tmax_abs\n"); + let mut comparisons = String::from("role\trow\tslot\texpert\twords\tdifferent\tfirst_word\tmax_abs\n"); for row in 0..ROWS { for slot in 0..SLOTS { let lo = (row * SLOTS + slot) * N; @@ -356,10 +313,7 @@ impl Report { ), ), ] { - let mut f = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(root.join(name))?; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(root.join(name))?; f.write_all(text.as_bytes())?; f.sync_all()?; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs index 59b6c250..d860c67d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mod.rs @@ -13,17 +13,17 @@ pub(crate) mod moe_route; // Original Strata prefill MoE router + shared expert over a whole micro-window of genuine FFN reads. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod moe_prefill_batch; -mod router_scratch; pub(crate) mod moe_weight_cache; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod oracle_capture; pub(crate) mod output; -pub(crate) mod step_sampler; pub(crate) mod qsa_attention; pub(crate) mod qsa_index; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod qsa_prefill_batch; +mod router_scratch; pub(crate) mod session; +pub(crate) mod step_sampler; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(dead_code)] @@ -47,15 +47,15 @@ mod shared_expert_workspace; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod owner_wall_profile; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod qsa_prompt_index; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -mod qsa_native_resources; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -mod qsa_decode_index; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod qsa_decode_attention; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_decode_index; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod qsa_native_resources; pub(crate) mod original_sampler; // Sampled mode-17 serve glue: called by the serve port once it implements run_window (docs/port-remaining.md item 3). @@ -68,61 +68,61 @@ pub(crate) mod prefill_profile; // Literal Original serve draft/verification scheduling; actual device adapters own execution. pub(crate) use leleka_engine_core::spec::adaptive as original_spec_adaptive; +pub(crate) mod original_serve_engine; pub(crate) mod original_spec_adaptive_env; pub(crate) mod original_spec_controller; -pub(crate) mod original_serve_engine; pub(crate) mod original_spec_draft; pub(crate) use leleka_engine_core::spec::policy as original_spec_policy; pub(crate) mod original_spec_suffix; // Per-round checks over the whole token history, proportional to what was appended since the last round. pub(crate) mod token_memo; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_cache_startup; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_file_cache_source; -#[cfg(all(any(target_os="linux",target_os="windows"),target_pointer_width="64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] pub(crate) mod output_native; // The selected Original MTP owner joins the exact native output, retained // weights and one shared scalar/full/ring layout. Execution still enters only // through the verified-session adapter, never through host-made row metadata. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod original_mtp_full_owner; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod original_mtp_verified_adapter; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mod original_serve_native; // Teacher forcing for the quality gate (docs/quality-gate.md): nothing installs a sequence outside the smoke. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod quality_force; // The routed-expert tier of the Original verifier window (all-CPU pool over the pinned mapped weights). -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -pub(crate) mod original_serve_pool; -mod prefetch_policy; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_serve_lookahead; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod original_serve_pool; +mod prefetch_policy; // The VRAM expert tier of that window (R4 residency, PCIe share, adaptive swaps, prompt-path slot loan). -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -pub(crate) mod original_serve_residency; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -pub(crate) mod original_serve_seed; -#[cfg(all(test,any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -mod original_serve_residency_gpu; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -pub(crate) mod original_serve_ledger; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_serve_config; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -pub(crate) mod original_serve_verifier; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_serve_host; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod original_serve_ledger; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_serve_request; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod original_serve_residency; +#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +mod original_serve_residency_gpu; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod original_serve_seed; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) mod original_serve_stack; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(crate) mod original_serve_verifier; // Operator profile of the serve path's host phases (LELEKA_SERVE_PROFILE). pub(crate) mod original_serve_profile; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu.rs index b9ab33de..811d89b2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu.rs @@ -28,12 +28,9 @@ fn retained_gate_up_matches_legacy_chain_and_closes_failed_candidates() { saturation_and_refusals(&context); let small = device.create_context(2 * FF * 4).unwrap(); assert_eq!( - finish_cached_mlp( - &small, - raw(&small, &[0.25; FF]), - raw(&small, &[0.5; FF]), - |_| panic!("budget must refuse before Down") - ) + finish_cached_mlp(&small, raw(&small, &[0.25; FF]), raw(&small, &[0.5; FF]), |_| panic!( + "budget must refuse before Down" + )) .err(), Some(Error::InputAllocation) ); @@ -57,21 +54,21 @@ fn retained_gate_up_matches_legacy_chain_and_closes_failed_candidates() { #[path = "moe_activation_reuse_gpu/encoded_fn.rs"] mod encoded_fn; #[allow(unused_imports)] +use encoded_fn::bounded_gate_up; +#[allow(unused_imports)] +use encoded_fn::compare_mlp; +#[allow(unused_imports)] +use encoded_fn::down; +#[allow(unused_imports)] +use encoded_fn::down_projection; +#[allow(unused_imports)] use encoded_fn::encoded; #[allow(unused_imports)] use encoded_fn::exact; #[allow(unused_imports)] -use encoded_fn::bounded_gate_up; -#[allow(unused_imports)] -use encoded_fn::down_projection; +use encoded_fn::format_case; #[allow(unused_imports)] use encoded_fn::raw; -#[allow(unused_imports)] -use encoded_fn::down; -#[allow(unused_imports)] -use encoded_fn::compare_mlp; -#[allow(unused_imports)] -use encoded_fn::format_case; #[path = "moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs"] mod former_fixture_domain_refusal_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs index 8f3981ca..f0552bd1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/encoded_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn encoded(kind: MoeMatrixKind, rows: usize, columns: usize, variant: usize) -> Vec { use MoeMatrixKind as K; let (elements, bytes) = match kind { @@ -83,16 +82,7 @@ pub(super) fn down_projection( MoeMatrixKind::Q8_0 => ProjectionKind::Dense(DenseFormat::Q8_0), _ => panic!("fixture admits only the original two Down formats"), }; - context.project_q8_1( - matrix, - hidden, - output, - ProjectionSpec { - kind: projection, - rows: N, - columns: FF, - }, - ) + context.project_q8_1(matrix, hidden, output, ProjectionSpec { kind: projection, rows: N, columns: FF }) } pub(super) fn raw<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> DeviceBuffer<'ctx> { @@ -131,15 +121,10 @@ pub(super) fn compare_mlp( let old_gate = upload_f32(context, &gate_values).unwrap(); let old_up = upload_f32(context, &up_values).unwrap(); let mut old_hidden = context.allocate(FF * 4).unwrap(); - context - .moe_swiglu_f32(&old_gate, &old_up, &mut old_hidden) - .unwrap(); + context.moe_swiglu_f32(&old_gate, &old_up, &mut old_hidden).unwrap(); let expected_hidden = download_f32(&old_hidden, FF).unwrap(); for value in expected_hidden.iter() { - assert!( - value.abs() <= 400., - "fixture exceeds predeclared Q8 header domain" - ); + assert!(value.abs() <= 400., "fixture exceeds predeclared Q8 header domain"); } let expected = down(context, down_kind, down_matrix, &old_hidden).unwrap(); old_hidden.release().unwrap(); @@ -160,49 +145,28 @@ pub(super) fn compare_mlp( pub(super) fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bool, zero: bool) { let input: Vec = (0..N) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - ((i % 31) as f32 - 15.) / 2048. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { ((i % 31) as f32 - 15.) / 2048. }) .collect(); let gate_bytes = bounded_gate_up(kind, 0); let up_bytes = bounded_gate_up(kind, 1); - let down_kind = if routed { - MoeMatrixKind::RoutedIq4Nl - } else { - MoeMatrixKind::Q8_0 - }; + let down_kind = if routed { MoeMatrixKind::RoutedIq4Nl } else { MoeMatrixKind::Q8_0 }; let down_bytes = encoded(down_kind, N, FF, 2); let x = upload_f32(context, &input).unwrap(); let gate_matrix = upload_bytes(context, &gate_bytes).unwrap(); let up_matrix = upload_bytes(context, &up_bytes).unwrap(); let down_matrix = upload_bytes(context, &down_bytes).unwrap(); - let gate = project_retained_gate_up(context, |out| { - launch_projection(context, kind, &gate_matrix, &x, out, FF, N) - }) - .unwrap(); - let up = project_retained_gate_up(context, |out| { - launch_projection(context, kind, &up_matrix, &x, out, FF, N) - }) - .unwrap(); + let gate = project_retained_gate_up(context, |out| launch_projection(context, kind, &gate_matrix, &x, out, FF, N)) + .unwrap(); + let up = + project_retained_gate_up(context, |out| launch_projection(context, kind, &up_matrix, &x, out, FF, N)).unwrap(); for buffer in [&gate, &up] { for value in download_f32(buffer, FF).unwrap().iter() { - assert!( - value.abs() < 20., - "fixture exceeds predeclared Gate/Up bound" - ); + assert!(value.abs() < 20., "fixture exceeds predeclared Gate/Up bound"); } } compare_mlp(context, gate, up, down_kind, &down_matrix); exact(&download_f32(&x, N).unwrap(), &input); - for (matrix, bytes) in [ - (&gate_matrix, &gate_bytes), - (&up_matrix, &up_bytes), - (&down_matrix, &down_bytes), - ] { + for (matrix, bytes) in [(&gate_matrix, &gate_bytes), (&up_matrix, &up_bytes), (&down_matrix, &down_bytes)] { let mut unchanged = vec![0; bytes.len()]; matrix.copy_to(&mut unchanged).unwrap(); assert_eq!(&unchanged, bytes); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs index 16ba9665..eca2a3f7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_activation_reuse_gpu/former_fixture_domain_refusal_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) { // One new diagnostic of the actual prior failure, in the same scheduled // run: original scale1/input/8 chain, preserving the raw driver error. @@ -11,61 +10,30 @@ pub(super) fn former_fixture_domain_refusal(context: &Context<'_>) { let x = upload_f32(context, &input).unwrap(); let gate_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 0)).unwrap(); let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap(); - let down_matrix = - upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap(); + let down_matrix = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap(); let gate = project_retained_gate_up(context, |output| { - launch_projection( - context, - MoeMatrixKind::Iq3Xxs, - &gate_matrix, - &x, - output, - FF, - N, - ) + launch_projection(context, MoeMatrixKind::Iq3Xxs, &gate_matrix, &x, output, FF, N) }) .unwrap(); let up = project_retained_gate_up(context, |output| { - launch_projection( - context, - MoeMatrixKind::Iq3Xxs, - &up_matrix, - &x, - output, - FF, - N, - ) + launch_projection(context, MoeMatrixKind::Iq3Xxs, &up_matrix, &x, output, FF, N) }) .unwrap(); let mut hidden = context.allocate(FF * 4).unwrap(); context.moe_swiglu_f32(&gate, &up, &mut hidden).unwrap(); let values = download_f32(&hidden, FF).unwrap(); - let maximum = values - .iter() - .map(|value| value.abs()) - .fold(0.0f32, f32::max); + let maximum = values.iter().map(|value| value.abs()).fold(0.0f32, f32::max); let maximum_sum = values .as_chunks::<32>() .0 .iter() - .map(|warp| { - warp.iter() - .map(|value| f64::from(*value)) - .sum::() - .abs() - }) + .map(|warp| warp.iter().map(|value| f64::from(*value)).sum::().abs()) .fold(0.0f64, f64::max); let mut output = context.allocate(N * 4).unwrap(); let sentinel = vec![0xa5; N * 4]; output.copy_from(&sentinel).unwrap(); let charged = context.allocated_bytes(); - let result = down_projection( - context, - MoeMatrixKind::RoutedIq4Nl, - &down_matrix, - &hidden, - &mut output, - ); + let result = down_projection(context, MoeMatrixKind::RoutedIq4Nl, &down_matrix, &hidden, &mut output); println!( "MOE_RETAINED original_domain raw_down_error={result:?} hidden_abs_max={maximum} warp_sum_abs_max={maximum_sum}" ); @@ -103,15 +71,10 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) { up_values[FF - 1] = f32::from_bits(bits); } let called = Cell::new(false); - let result = finish_cached_mlp( - context, - raw(context, &gate_values), - raw(context, &up_values), - |_| { - called.set(true); - panic!("nonfinite hidden must not enter Down"); - }, - ); + let result = finish_cached_mlp(context, raw(context, &gate_values), raw(context, &up_values), |_| { + called.set(true); + panic!("nonfinite hidden must not enter Down"); + }); assert_eq!(result.err(), Some(Error::NonFinite)); assert!(!called.get()); assert_eq!(context.allocated_bytes(), 0); @@ -125,16 +88,8 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) { let x = upload_f32(context, &[0.25; N]).unwrap(); let initial = context.allocated_bytes(); assert_eq!( - project_retained_gate_up(context, |out| launch_projection( - context, - MoeMatrixKind::Q6K, - &w, - &x, - out, - FF, - N - )) - .err(), + project_retained_gate_up(context, |out| launch_projection(context, MoeMatrixKind::Q6K, &w, &x, out, FF, N)) + .err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), initial); @@ -146,23 +101,10 @@ pub(super) fn saturation_and_refusals(context: &Context<'_>) { let sentinel = vec![0xa5; N * 4 - 4]; wrong.copy_from(&sentinel).unwrap(); let initial = context.allocated_bytes(); - let result = finish_cached_mlp( - context, - raw(context, &[0.25; FF]), - raw(context, &[0.5; FF]), - |hidden| { - launch_projection( - context, - MoeMatrixKind::RoutedIq4Nl, - &w, - hidden, - &mut wrong, - N, - FF, - )?; - panic!("wrong Down output must refuse"); - }, - ); + let result = finish_cached_mlp(context, raw(context, &[0.25; FF]), raw(context, &[0.5; FF]), |hidden| { + launch_projection(context, MoeMatrixKind::RoutedIq4Nl, &w, hidden, &mut wrong, N, FF)?; + panic!("wrong Down output must refuse"); + }); assert_eq!(result.err(), Some(Error::InvalidDimension)); assert_eq!(context.allocated_bytes(), initial); let mut unchanged = vec![0; sentinel.len()]; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down.rs index c3f54570..b352048a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down.rs @@ -1,7 +1,7 @@ //! Step-local actual Down outputs; no host/device pair constructor. +use super::super::moe_weight_cache::{RoutedFiniteOwner, RoutedWorkspaceOwner}; use super::{Error, K, N, Result, download_f32, driver_error, validate_values}; use leleka_cuda_driver::{Context, DeviceBuffer, RoutedFiniteStage, RoutedGroupWorkspace}; -use super::super::moe_weight_cache::{RoutedFiniteOwner, RoutedWorkspaceOwner}; use std::{cell::Cell, rc::Rc}; #[derive(Clone, Copy, PartialEq, Eq)] @@ -60,7 +60,7 @@ mod moe_down_reuse_gpu; #[path = "moe_down/impl_downscope.rs"] mod impl_downscope; -#[path = "moe_down/impl_retainedscalar.rs"] -mod impl_retainedscalar; #[path = "moe_down/impl_residentpackeddown.rs"] mod impl_residentpackeddown; +#[path = "moe_down/impl_retainedscalar.rs"] +mod impl_retainedscalar; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_downscope.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_downscope.rs index 66921995..efcae17d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_downscope.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_downscope.rs @@ -5,23 +5,25 @@ use super::*; impl<'ctx> DownScope<'ctx> { pub(in super::super) fn new(context: &'ctx Context<'ctx>, failed: Rc>) -> Self { - Self { - context, - epoch: Rc::new(()), - failed, - routed_finite: None, - routed_workspace: None, - } + Self { context, epoch: Rc::new(()), failed, routed_finite: None, routed_workspace: None } } pub(in super::super) fn with_routed_finite(mut self, owner: Rc>) -> Result { - if !owner.matches_context(self.context) { return Err(Error::IdentityMismatch); } - if owner.is_failed() { return Err(Error::CudaExecution); } + if !owner.matches_context(self.context) { + return Err(Error::IdentityMismatch); + } + if owner.is_failed() { + return Err(Error::CudaExecution); + } self.routed_finite = Some(owner); Ok(self) } pub(in super::super) fn with_routed_workspace(mut self, owner: Rc>) -> Result { - if !owner.matches_context(self.context) { return Err(Error::IdentityMismatch); } - if owner.is_failed() { return Err(Error::CudaExecution); } + if !owner.matches_context(self.context) { + return Err(Error::IdentityMismatch); + } + if owner.is_failed() { + return Err(Error::CudaExecution); + } self.routed_workspace = Some(owner); Ok(self) } @@ -30,17 +32,24 @@ impl<'ctx> DownScope<'ctx> { execute: impl FnOnce(&mut RoutedGroupWorkspace<'ctx>) -> Result, ) -> Result { self.check()?; - let result = self.routed_workspace.as_ref().ok_or(Error::IdentityMismatch)? - .with_workspace(execute); + let result = self.routed_workspace.as_ref().ok_or(Error::IdentityMismatch)?.with_workspace(execute); self.record(&result); result } - pub(in super::super) fn finite_stage(&self, source: &DeviceBuffer<'_>, stage: RoutedFiniteStage, columns: usize) -> Result<()> { + pub(in super::super) fn finite_stage( + &self, + source: &DeviceBuffer<'_>, + stage: RoutedFiniteStage, + columns: usize, + ) -> Result<()> { self.check()?; let result = match &self.routed_finite { Some(owner) => owner.check_stage(source, stage, columns), None => { - let width = match stage { RoutedFiniteStage::Gate | RoutedFiniteStage::Up | RoutedFiniteStage::Hidden => super::super::FF, RoutedFiniteStage::Down => N }; + let width = match stage { + RoutedFiniteStage::Gate | RoutedFiniteStage::Up | RoutedFiniteStage::Hidden => super::super::FF, + RoutedFiniteStage::Down => N, + }; download_f32(source, columns.checked_mul(width).ok_or(Error::Overflow)?).map(|_| ()) } }; @@ -48,8 +57,10 @@ impl<'ctx> DownScope<'ctx> { result } pub(super) fn check(&self) -> Result<()> { - if self.failed.get() || self.routed_finite.as_ref().is_some_and(|owner| owner.is_failed()) - || self.routed_workspace.as_ref().is_some_and(|owner| owner.is_failed()) { + if self.failed.get() + || self.routed_finite.as_ref().is_some_and(|owner| owner.is_failed()) + || self.routed_workspace.as_ref().is_some_and(|owner| owner.is_failed()) + { Err(Error::CudaExecution) } else { Ok(()) @@ -64,10 +75,7 @@ impl<'ctx> DownScope<'ctx> { self.check()?; let result = self.context.allocate(bytes).map_err(driver_error); self.record(&result); - Ok(TransportBuffer { - buffer: Some(result?), - failed: Rc::clone(&self.failed), - }) + Ok(TransportBuffer { buffer: Some(result?), failed: Rc::clone(&self.failed) }) } pub(in super::super) fn upload(&self, values: &[f32]) -> Result> { validate_values(values, values.len())?; @@ -108,13 +116,7 @@ impl<'ctx> DownScope<'ctx> { return Err(primary); } }; - Ok(RetainedDown { - output, - values, - epoch: Rc::clone(&self.epoch), - context: self.context, - selection, - }) + Ok(RetainedDown { output, values, epoch: Rc::clone(&self.epoch), context: self.context, selection }) } /// Closed CPU completion handoff. Host values retain the real CPU result /// association; only the completed upload and full device finite producer @@ -128,9 +130,7 @@ impl<'ctx> DownScope<'ctx> { row: usize, ) -> Result> { self.check()?; - if !matches!(selection, DownSelection::Routed(slot) if slot < K) - || !completed.matches(binding, keys) - { + if !matches!(selection, DownSelection::Routed(slot) if slot < K) || !completed.matches(binding, keys) { return Err(Error::IdentityMismatch); } let start = row.checked_mul(N).ok_or(Error::Overflow)?; @@ -138,7 +138,9 @@ impl<'ctx> DownScope<'ctx> { let source = completed.values().get(start..end).ok_or(Error::IdentityMismatch)?; let mut bytes = Vec::new(); bytes.try_reserve_exact(N * 4).map_err(|_| Error::InputAllocation)?; - for value in source { bytes.extend_from_slice(&value.to_le_bytes()); } + for value in source { + bytes.extend_from_slice(&value.to_le_bytes()); + } // An owner without the selected full-device guard keeps the original // completed upload/full readback path; host values are no certificate. if self.routed_finite.is_none() { @@ -161,13 +163,7 @@ impl<'ctx> DownScope<'ctx> { return Err(primary); } }; - Ok(RetainedDown { - output, - values, - epoch: Rc::clone(&self.epoch), - context: self.context, - selection, - }) + Ok(RetainedDown { output, values, epoch: Rc::clone(&self.epoch), context: self.context, selection }) } /// Closed real grouped producer: validate its own bulk readback before /// splitting actual columns into the original selected Down owners. @@ -179,9 +175,7 @@ impl<'ctx> DownScope<'ctx> { ) -> Result>> { self.check()?; if !(1..=64).contains(&selections.len()) - || selections - .iter() - .any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K)) + || selections.iter().any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K)) { return Err(Error::InvalidExpert); } @@ -190,9 +184,7 @@ impl<'ctx> DownScope<'ctx> { project(grouped.buffer_mut()?, cancelled)?; let values = download_f32(grouped.buffer()?, selections.len() * N)?; let mut outputs = Vec::new(); - outputs - .try_reserve_exact(selections.len()) - .map_err(|_| Error::InputAllocation)?; + outputs.try_reserve_exact(selections.len()).map_err(|_| Error::InputAllocation)?; for (index, selection) in selections.iter().copied().enumerate() { if cancelled() { return Err(Error::Unsupported(super::super::Stage::Executor)); @@ -200,12 +192,7 @@ impl<'ctx> DownScope<'ctx> { let mut output = self.allocate(N * 4)?; let copy = self .context - .copy_routed_down_column( - grouped.buffer()?, - selections.len(), - index, - output.buffer_mut()?, - ) + .copy_routed_down_column(grouped.buffer()?, selections.len(), index, output.buffer_mut()?) .map_err(driver_error); self.record(©); if let Err(primary) = copy { @@ -213,9 +200,7 @@ impl<'ctx> DownScope<'ctx> { return Err(primary); } let mut actual = Vec::new(); - actual - .try_reserve_exact(N) - .map_err(|_| Error::InputAllocation)?; + actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?; actual.extend_from_slice(&values[index * N..(index + 1) * N]); outputs.push(RetainedDown { output, @@ -241,15 +226,19 @@ impl<'ctx> DownScope<'ctx> { cancelled: &mut F, ) -> Result<()> { self.check()?; - if !(1..=64).contains(&selections.len()) || selections.iter() - .any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K)) - { return Err(Error::InvalidExpert); } + if !(1..=64).contains(&selections.len()) + || selections.iter().any(|s| !matches!(s, DownSelection::Routed(slot) if *slot < K)) + { + return Err(Error::InvalidExpert); + } let mut grouped = self.allocate(selections.len() * N * 4)?; let result = (|| { project(grouped.buffer_mut()?, cancelled)?; // Complete original Down finite boundary precedes packet mutation. self.finite_stage(grouped.buffer()?, RoutedFiniteStage::Down, selections.len())?; - if cancelled() { return Err(Error::Unsupported(super::super::Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(super::super::Stage::Executor)); + } copy(grouped.buffer()?, cancelled) })(); self.record(&result); @@ -279,10 +268,6 @@ impl<'ctx> DownScope<'ctx> { let _ = output.close(); return Err(Error::NonFinite); } - Ok(RetainedScalar { - output, - epoch: Rc::clone(&self.epoch), - context: self.context, - }) + Ok(RetainedScalar { output, epoch: Rc::clone(&self.epoch), context: self.context }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_residentpackeddown.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_residentpackeddown.rs index 7b67f3da..a5749338 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_residentpackeddown.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_residentpackeddown.rs @@ -15,10 +15,7 @@ impl<'ctx> ResidentPackedDown<'ctx> { } pub(super) fn validate(&self, scope: &DownScope<'_>) -> Result<()> { scope.check()?; - if self.refused - || !Rc::ptr_eq(&self.epoch, &scope.epoch) - || !std::ptr::eq(self.context, scope.context) - { + if self.refused || !Rc::ptr_eq(&self.epoch, &scope.epoch) || !std::ptr::eq(self.context, scope.context) { return Err(Error::IdentityMismatch); } Ok(()) @@ -42,8 +39,9 @@ impl<'ctx> ResidentPackedDown<'ctx> { } /// Private whole-window loan. The actual scope and complete slot coverage /// are checked before lending; no public buffer/row certificate is created. - pub(in super::super) fn completed_buffer(&self,scope:&DownScope<'ctx>)->Result<&DeviceBuffer<'ctx>> { - self.complete(scope)?;self.output.buffer() + pub(in super::super) fn completed_buffer(&self, scope: &DownScope<'ctx>) -> Result<&DeviceBuffer<'ctx>> { + self.complete(scope)?; + self.output.buffer() } /// All actual disjoint packets are admitted before a closed finite producer /// performs its one synchronized group copy. No partial coverage publish. @@ -64,9 +62,7 @@ impl<'ctx> ResidentPackedDown<'ctx> { } { let mut copies = Vec::new(); - copies - .try_reserve_exact(packets.len()) - .map_err(|_| Error::InputAllocation)?; + copies.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?; for (column, (packet, slot)) in packets.iter_mut().enumerate() { copies.push(( u32::try_from(column).map_err(|_| Error::Overflow)?, @@ -128,12 +124,7 @@ impl<'ctx> ResidentPackedDown<'ctx> { let mut output = scope.allocate(N * 4)?; let result = scope .context - .moe_combine_f64( - self.output.buffer()?, - weights, - scaled.output.buffer()?, - output.buffer_mut()?, - ) + .moe_combine_f64(self.output.buffer()?, weights, scaled.output.buffer()?, output.buffer_mut()?) .map_err(driver_error) .and_then(|()| download_f32(output.buffer()?, N)); scope.record(&result); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_retainedscalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_retainedscalar.rs index f8dbbbcd..3e062eee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_retainedscalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down/impl_retainedscalar.rs @@ -27,10 +27,7 @@ impl<'ctx> TransportBuffer<'ctx> { primary.map_or(release, Err) } pub(super) fn release(&mut self) -> Result<()> { - let result = self - .buffer - .take() - .map_or(Ok(()), |buffer| buffer.release().map_err(driver_error)); + let result = self.buffer.take().map_or(Ok(()), |buffer| buffer.release().map_err(driver_error)); if result.is_err() { self.failed.set(true); } @@ -46,7 +43,9 @@ impl<'ctx> RetainedDown<'ctx> { /// Borrow only this genuine completed row after original epoch/context, /// selection and full finite validation; no mutable or replacement owner. pub(in super::super) fn with_completed( - &self, scope: &DownScope<'ctx>, selection: DownSelection, + &self, + scope: &DownScope<'ctx>, + selection: DownSelection, consume: impl FnOnce(&DeviceBuffer<'ctx>) -> Result, ) -> Result { self.validate(scope, selection)?; @@ -77,18 +76,13 @@ impl<'ctx> RetainedDown<'ctx> { scalar: &RetainedScalar<'_>, ) -> Result> { self.validate(scope, DownSelection::Shared)?; - if !Rc::ptr_eq(&scalar.epoch, &scope.epoch) || !std::ptr::eq(scalar.context, scope.context) - { + if !Rc::ptr_eq(&scalar.epoch, &scope.epoch) || !std::ptr::eq(scalar.context, scope.context) { return Err(Error::IdentityMismatch); } let mut output = scope.allocate(N * 4)?; let result = scope .context - .moe_shared_scale_f32( - self.output.buffer()?, - scalar.output.buffer()?, - output.buffer_mut()?, - ) + .moe_shared_scale_f32(self.output.buffer()?, scalar.output.buffer()?, output.buffer_mut()?) .map_err(driver_error) .and_then(|()| download_f32(output.buffer()?, N)); scope.record(&result); @@ -101,11 +95,7 @@ impl<'ctx> RetainedDown<'ctx> { let _ = output.close(); return Err(primary); } - Ok(ScaledDown { - output, - epoch: Rc::clone(&scope.epoch), - context: scope.context, - }) + Ok(ScaledDown { output, epoch: Rc::clone(&scope.epoch), context: scope.context }) } } impl ScaledDown<'_> { @@ -115,29 +105,17 @@ impl ScaledDown<'_> { } impl<'ctx> PackedDown<'ctx> { pub(in super::super) fn new(scope: &DownScope<'ctx>) -> Result { - Ok(Self { - output: scope.allocate(K * N * 4)?, - epoch: Rc::clone(&scope.epoch), - context: scope.context, - next: 0, - }) + Ok(Self { output: scope.allocate(K * N * 4)?, epoch: Rc::clone(&scope.epoch), context: scope.context, next: 0 }) } pub(in super::super) fn pack(&mut self, scope: &DownScope<'_>, down: RetainedDown<'_>) -> Result<()> { let result = (|| { - if !Rc::ptr_eq(&self.epoch, &scope.epoch) - || !std::ptr::eq(self.context, scope.context) - || self.next >= K - { + if !Rc::ptr_eq(&self.epoch, &scope.epoch) || !std::ptr::eq(self.context, scope.context) || self.next >= K { return Err(Error::IdentityMismatch); } down.validate(scope, DownSelection::Routed(self.next))?; scope .context - .pack_moe_down_f32( - down.output.buffer()?, - self.output.buffer_mut()?, - self.next as u32, - ) + .pack_moe_down_f32(down.output.buffer()?, self.output.buffer_mut()?, self.next as u32) .map_err(driver_error) })(); scope.record(&result); @@ -155,10 +133,7 @@ impl<'ctx> PackedDown<'ctx> { execute: impl FnOnce(&DeviceBuffer<'ctx>) -> Result, ) -> Result { scope.check()?; - if self.next != K - || !Rc::ptr_eq(&self.epoch, &scope.epoch) - || !std::ptr::eq(self.context, scope.context) - { + if self.next != K || !Rc::ptr_eq(&self.epoch, &scope.epoch) || !std::ptr::eq(self.context, scope.context) { return Err(Error::IdentityMismatch); } let result = execute(self.output.buffer()?); @@ -201,12 +176,7 @@ impl<'ctx> PackedDown<'ctx> { let mut output = scope.allocate(N * 4)?; let result = scope .context - .moe_combine_f64( - self.output.buffer()?, - weights, - scaled.output.buffer()?, - output.buffer_mut()?, - ) + .moe_combine_f64(self.output.buffer()?, weights, scaled.output.buffer()?, output.buffer_mut()?) .map_err(driver_error) .and_then(|()| download_f32(output.buffer()?, N)); scope.record(&result); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu.rs index aecc367b..177807a6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu.rs @@ -15,46 +15,29 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { let route: [f32; K] = std::array::from_fn(|i| if i < 6 { 0.125 } else { 0.0625 }); for zero in [false, true] { let hidden: Vec = (0..640) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - ((i % 17) as f32 - 8.) / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 64. }) .collect(); let input: Vec = (0..N) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - ((i % 13) as f32 - 6.) / 128. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 13) as f32 - 6.) / 128. }) .collect(); let scalar_bytes = scalar_weights(); // Independent genuine old path FIRST, complete host concatenation. - let expected_parts: Vec = (0..K) - .flat_map(|i| original_down(&ctx, &hidden, i).into_vec()) - .collect(); + let expected_parts: Vec = (0..K).flat_map(|i| original_down(&ctx, &hidden, i).into_vec()).collect(); let expected_shared = original_down(&ctx, &hidden, K); let scalar_input = upload_f32(&ctx, &input).unwrap(); let scalar_matrix = upload_bytes(&ctx, &scalar_bytes).unwrap(); let mut scalar = ctx.allocate(4).unwrap(); - ctx.moe_shared_scalar_f32_bf16(&scalar_input, &scalar_matrix, &mut scalar) - .unwrap(); + ctx.moe_shared_scalar_f32_bf16(&scalar_input, &scalar_matrix, &mut scalar).unwrap(); let expected_scalar = download_f32(&scalar, 1).unwrap(); assert!((0.0..=1.0).contains(&expected_scalar[0])); let old_shared = upload_f32(&ctx, &expected_shared).unwrap(); let mut old_scaled = ctx.allocate(N * 4).unwrap(); - ctx.moe_shared_scale_f32(&old_shared, &scalar, &mut old_scaled) - .unwrap(); + ctx.moe_shared_scale_f32(&old_shared, &scalar, &mut old_scaled).unwrap(); let expected_scaled = download_f32(&old_scaled, N).unwrap(); let old_parts = upload_f32(&ctx, &expected_parts).unwrap(); let weights = upload_f32(&ctx, &route).unwrap(); let mut old_output = ctx.allocate(N * 4).unwrap(); - ctx.moe_combine_f64(&old_parts, &weights, &old_scaled, &mut old_output) - .unwrap(); + ctx.moe_combine_f64(&old_parts, &weights, &old_scaled, &mut old_output).unwrap(); let expected_out = download_f32(&old_output, N).unwrap(); old_output.release().unwrap(); old_parts.release().unwrap(); @@ -70,92 +53,43 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { parts.pack(&scope, down).unwrap(); assert_eq!(parts.next, slot + 1); } - exact( - &download_f32(parts.output.buffer().unwrap(), K * N).unwrap(), - &expected_parts, - ); + exact(&download_f32(parts.output.buffer().unwrap(), K * N).unwrap(), &expected_parts); let shared = retained(&scope, &x, DownSelection::Shared, K); exact(shared.values(), &expected_shared); let scalar = scope.shared_scalar(&scalar_input, &scalar_matrix).unwrap(); - exact( - &download_f32(scalar.output.buffer().unwrap(), 1).unwrap(), - &expected_scalar, - ); + exact(&download_f32(scalar.output.buffer().unwrap(), 1).unwrap(), &expected_scalar); let scaled = shared.scale(&scope, &scalar).unwrap(); - exact( - &download_f32(scaled.output.buffer().unwrap(), N).unwrap(), - &expected_scaled, - ); - exact( - &parts.combine(&scope, &weights, &scaled).unwrap(), - &expected_out, - ); + exact(&download_f32(scaled.output.buffer().unwrap(), N).unwrap(), &expected_scaled); + exact(&parts.combine(&scope, &weights, &scaled).unwrap(), &expected_out); if !zero { let wrong = DownScope::new(&ctx, failed.clone()); - refused( - parts.combine(&wrong, &weights, &scaled), - Error::IdentityMismatch, - &refusals, - ); + refused(parts.combine(&wrong, &weights, &scaled), Error::IdentityMismatch, &refusals); let malformed = upload_bytes(&ctx, &[0; 4]).unwrap(); let charge = ctx.allocated_bytes(); - refused( - parts.combine(&scope, &malformed, &scaled), - Error::InvalidDimension, - &refusals, - ); + refused(parts.combine(&scope, &malformed, &scaled), Error::InvalidDimension, &refusals); assert_eq!(ctx.allocated_bytes(), charge); malformed.release().unwrap(); let mut bad_route = route; bad_route[K - 1] = f32::NAN; - let bad = upload_bytes( - &ctx, - &bad_route - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>(), - ) - .unwrap(); + let bad = upload_bytes(&ctx, &bad_route.iter().flat_map(|v| v.to_le_bytes()).collect::>()).unwrap(); let charge = ctx.allocated_bytes(); - refused( - parts.combine(&scope, &bad, &scaled), - Error::NonFinite, - &refusals, - ); + refused(parts.combine(&scope, &bad, &scaled), Error::NonFinite, &refusals); assert_eq!(ctx.allocated_bytes(), charge); bad.release().unwrap(); assert!(!failed.get()); } let mut unchanged = vec![0; hidden.len() * 4]; x.copy_to(&mut unchanged).unwrap(); - assert_eq!( - unchanged, - hidden - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); + assert_eq!(unchanged, hidden.iter().flat_map(|v| v.to_le_bytes()).collect::>()); let mut unchanged = vec![0; scalar_bytes.len()]; scalar_matrix.copy_to(&mut unchanged).unwrap(); assert_eq!(unchanged, scalar_bytes); let mut unchanged = vec![0; input.len() * 4]; scalar_input.copy_to(&mut unchanged).unwrap(); - assert_eq!( - unchanged, - input - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); + assert_eq!(unchanged, input.iter().flat_map(|v| v.to_le_bytes()).collect::>()); let mut unchanged = vec![0; K * 4]; weights.copy_to(&mut unchanged).unwrap(); - assert_eq!( - unchanged, - route - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); + assert_eq!(unchanged, route.iter().flat_map(|v| v.to_le_bytes()).collect::>()); x.release().unwrap(); parts.close().unwrap(); scaled.close().unwrap(); @@ -175,46 +109,22 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { let rival_scalar = rival.shared_scalar(&input, &matrix).unwrap(); let mut parts = PackedDown::new(&scope).unwrap(); let charge = ctx.allocated_bytes(); - refused( - parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(1), 1)), - Error::IdentityMismatch, - &refusals, - ); - refused( - parts.pack(&scope, retained(&scope, &x, DownSelection::Shared, K)), - Error::IdentityMismatch, - &refusals, - ); - refused( - parts.pack(&scope, retained(&rival, &x, DownSelection::Routed(0), 0)), - Error::IdentityMismatch, - &refusals, - ); + refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(1), 1)), Error::IdentityMismatch, &refusals); + refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Shared, K)), Error::IdentityMismatch, &refusals); + refused(parts.pack(&scope, retained(&rival, &x, DownSelection::Routed(0), 0)), Error::IdentityMismatch, &refusals); assert_eq!(parts.next, 0); assert_eq!(ctx.allocated_bytes(), charge); - parts - .pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)) - .unwrap(); - refused( - parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)), - Error::IdentityMismatch, - &refusals, - ); + parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)).unwrap(); + refused(parts.pack(&scope, retained(&scope, &x, DownSelection::Routed(0), 0)), Error::IdentityMismatch, &refusals); assert_eq!(parts.next, 1); refused( retained(&scope, &x, DownSelection::Shared, K).scale(&scope, &rival_scalar), Error::IdentityMismatch, &refusals, ); - let scaled = retained(&scope, &x, DownSelection::Shared, K) - .scale(&scope, &scalar) - .unwrap(); + let scaled = retained(&scope, &x, DownSelection::Shared, K).scale(&scope, &scalar).unwrap(); let weights = upload_f32(&ctx, &route).unwrap(); - refused( - parts.combine(&scope, &weights, &scaled), - Error::IdentityMismatch, - &refusals, - ); + refused(parts.combine(&scope, &weights, &scaled), Error::IdentityMismatch, &refusals); let called = Cell::new(false); refused( scope.project(DownSelection::Routed(K), |_| { @@ -228,17 +138,11 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { let malformed = upload_bytes(&ctx, &[0; 2]).unwrap(); let charge = ctx.allocated_bytes(); refused( - scope.project(DownSelection::Routed(1), |out| { - project(&ctx, &malformed, &x, out) - }), - Error::InvalidDimension, - &refusals, - ); - refused( - scope.shared_scalar(&input, &malformed), + scope.project(DownSelection::Routed(1), |out| project(&ctx, &malformed, &x, out)), Error::InvalidDimension, &refusals, ); + refused(scope.shared_scalar(&input, &malformed), Error::InvalidDimension, &refusals); assert_eq!(ctx.allocated_bytes(), charge); malformed.release().unwrap(); let mut bad_down = down_weights(1); @@ -246,11 +150,7 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { bad_down[end - 34..end - 32].copy_from_slice(&0x7c00u16.to_le_bytes()); let bad = upload_bytes(&ctx, &bad_down).unwrap(); let charge = ctx.allocated_bytes(); - refused( - scope.project(DownSelection::Routed(1), |out| project(&ctx, &bad, &x, out)), - Error::NonFinite, - &refusals, - ); + refused(scope.project(DownSelection::Routed(1), |out| project(&ctx, &bad, &x, out)), Error::NonFinite, &refusals); assert_eq!(ctx.allocated_bytes(), charge); bad.release().unwrap(); // Actual scalar kernel refuses malformed raw operands and finite F32_MAX @@ -258,17 +158,9 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { for value in [f32::NAN, f32::INFINITY, f32::MAX] { let mut raw = vec![0.125; N]; raw[N - 1] = value; - let bad = upload_bytes( - &ctx, - &raw.iter().flat_map(|v| v.to_le_bytes()).collect::>(), - ) - .unwrap(); + let bad = upload_bytes(&ctx, &raw.iter().flat_map(|v| v.to_le_bytes()).collect::>()).unwrap(); let charge = ctx.allocated_bytes(); - refused( - scope.shared_scalar(&bad, &matrix), - Error::NonFinite, - &refusals, - ); + refused(scope.shared_scalar(&bad, &matrix), Error::NonFinite, &refusals); assert_eq!(ctx.allocated_bytes(), charge); bad.release().unwrap(); } @@ -277,10 +169,7 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { let foreign_x = upload_f32(&foreign, &[0.125; 640]).unwrap(); let charge = ctx.allocated_bytes(); refused( - parts.pack( - &scope, - retained(&foreign_scope, &foreign_x, DownSelection::Routed(1), 1), - ), + parts.pack(&scope, retained(&foreign_scope, &foreign_x, DownSelection::Routed(1), 1)), Error::IdentityMismatch, &refusals, ); @@ -300,16 +189,8 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { failed.set(true); // Explicit shared policy only; never clear it. refused(PackedDown::new(&scope), Error::CudaExecution, &refusals); refused(scope.upload(&[0.]), Error::CudaExecution, &refusals); - refused( - partial.pack(&scope, pending), - Error::CudaExecution, - &refusals, - ); - refused( - partial.combine(&scope, &weights, &scaled), - Error::CudaExecution, - &refusals, - ); + refused(partial.pack(&scope, pending), Error::CudaExecution, &refusals); + refused(partial.combine(&scope, &weights, &scaled), Error::CudaExecution, &refusals); assert_eq!(partial.close(), Err(Error::CudaExecution)); assert_eq!(scalar.close(), Err(Error::CudaExecution)); assert_eq!(rival_scalar.close(), Err(Error::CudaExecution)); @@ -335,16 +216,16 @@ fn retained_down_pack_scale_combine_matches_old_uploads_and_fences_abort() { #[path = "moe_down_reuse_gpu/exact_fn.rs"] mod exact_fn; #[allow(unused_imports)] -use exact_fn::exact; -#[allow(unused_imports)] use exact_fn::down_weights; #[allow(unused_imports)] -use exact_fn::scalar_weights; -#[allow(unused_imports)] -use exact_fn::project; +use exact_fn::exact; #[allow(unused_imports)] use exact_fn::original_down; #[allow(unused_imports)] -use exact_fn::retained; +use exact_fn::project; #[allow(unused_imports)] use exact_fn::refused; +#[allow(unused_imports)] +use exact_fn::retained; +#[allow(unused_imports)] +use exact_fn::scalar_weights; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu/exact_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu/exact_fn.rs index d2c14b68..048b7359 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu/exact_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_down_reuse_gpu/exact_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn exact(a: &[f32], b: &[f32]) { assert_eq!(a.len(), b.len()); for (i, (a, b)) in a.iter().zip(b).enumerate() { @@ -42,11 +41,7 @@ pub(super) fn project( weights, input, out, - ProjectionSpec { - rows: N, - columns: 640, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows: N, columns: 640, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ) .map_err(driver_error) } @@ -68,11 +63,7 @@ pub(super) fn retained<'ctx>( seed: usize, ) -> RetainedDown<'ctx> { let weights = upload_bytes(scope.context, &down_weights(seed)).unwrap(); - let result = scope - .project(selection, |out| { - project(scope.context, &weights, input, out) - }) - .unwrap(); + let result = scope.project(selection, |out| project(scope.context, &weights, input, out)).unwrap(); weights.release().unwrap(); result } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs index 60adb3b8..2264e4bf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert.rs @@ -7,12 +7,12 @@ use super::moe_weight_cache::{CachedMoeMatrix, MoeWeightCache}; use super::session::QwenStepTxn; use crate::model_binding::kar_expert_source::{KarExpertSource, KarSourceError}; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrRole, InputBindingError, ModelBinding, MoeExpertBlock, MoeExpertSelection, - MoeExpertWeights, MoeMatrixKind, MoeMatrixRole, + BindingIdentity, GrRole, InputBindingError, ModelBinding, MoeExpertBlock, MoeExpertSelection, MoeExpertWeights, + MoeMatrixKind, MoeMatrixRole, }; use leleka_cuda_driver::{ - Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, ProjectionSpec, - Q5KProjectionShape, Q6KProjectionShape, RoutedFormat, RoutedGateUpQ8, + Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, ProjectionSpec, Q5KProjectionShape, + Q6KProjectionShape, RoutedFormat, RoutedGateUpQ8, }; use std::{cell::Cell, rc::Rc}; #[path = "moe_down.rs"] @@ -70,26 +70,26 @@ use impl_expertready::execute_cuda_kar; use impl_expertready::kar_error; mod finish_with_parts_fn; #[allow(unused_imports)] -use finish_with_parts_fn::finish_with_parts; -#[allow(unused_imports)] use finish_with_parts_fn::execute_cuda_cached; +#[allow(unused_imports)] +use finish_with_parts_fn::finish_with_parts; mod cached_mlp_down_fn; #[allow(unused_imports)] -use cached_mlp_down_fn::cached_mlp_down; -#[allow(unused_imports)] use cached_mlp_down_fn::cached_gate_up_scoped; +#[allow(unused_imports)] +use cached_mlp_down_fn::cached_mlp_down; mod expert_mlp_fn; #[allow(unused_imports)] use expert_mlp_fn::expert_mlp; #[allow(unused_imports)] +use expert_mlp_fn::finish_cached_mlp; +#[allow(unused_imports)] use expert_mlp_fn::project_cached_gate_up; #[allow(unused_imports)] use expert_mlp_fn::project_retained_gate_up; -#[allow(unused_imports)] -use expert_mlp_fn::finish_cached_mlp; mod project_matrix_fn; #[allow(unused_imports)] -use project_matrix_fn::project_matrix; +use project_matrix_fn::admit_budget; #[cfg(test)] #[allow(unused_imports)] use project_matrix_fn::collect_rows; @@ -98,23 +98,23 @@ use project_matrix_fn::dual_format_kind; #[allow(unused_imports)] use project_matrix_fn::dual_routed_format; #[allow(unused_imports)] -use project_matrix_fn::launch_cached_projection; -#[allow(unused_imports)] use project_matrix_fn::launch_cached_prepared; #[allow(unused_imports)] +use project_matrix_fn::launch_cached_projection; +#[allow(unused_imports)] use project_matrix_fn::launch_projection; #[allow(unused_imports)] -use project_matrix_fn::admit_budget; +use project_matrix_fn::project_matrix; mod validate_values_fn; #[allow(unused_imports)] -use validate_values_fn::validate_values; +use validate_values_fn::binding_error; +#[allow(unused_imports)] +use validate_values_fn::download_f32; +#[allow(unused_imports)] +use validate_values_fn::driver_error; #[allow(unused_imports)] use validate_values_fn::upload_bytes; #[allow(unused_imports)] use validate_values_fn::upload_f32; #[allow(unused_imports)] -use validate_values_fn::download_f32; -#[allow(unused_imports)] -use validate_values_fn::binding_error; -#[allow(unused_imports)] -use validate_values_fn::driver_error; +use validate_values_fn::validate_values; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs index e540ef75..1c38498d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/cached_mlp_down_fn.rs @@ -57,21 +57,15 @@ pub(super) fn cached_mlp_down<'ctx>( } }; let result = (|| { - let swiglu = context - .moe_swiglu_f32(gate.buffer()?, up.buffer()?, hidden.buffer_mut()?) - .map_err(driver_error); + let swiglu = context.moe_swiglu_f32(gate.buffer()?, up.buffer()?, hidden.buffer_mut()?).map_err(driver_error); scope.record(&swiglu); swiglu?; let readback = download_f32(hidden.buffer()?, FF); scope.record(&readback); readback?; cache.validate(binding, context)?; - let (columns, rows) = weights - .shape(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; - let kind = weights - .kind(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; + let (columns, rows) = weights.shape(selection, MoeMatrixRole::Down).map_err(binding_error)?; + let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; if columns != FF || rows != N { return Err(Error::InvalidDimension); } @@ -81,15 +75,7 @@ pub(super) fn cached_mlp_down<'ctx>( MoeExpertSelection::Shared => DownSelection::Shared, }; scope.project(numeric_selection, |output| { - launch_cached_projection( - context, - kind, - matrix, - hidden.buffer()?, - output, - rows, - columns, - ) + launch_cached_projection(context, kind, matrix, hidden.buffer()?, output, rows, columns) }) })(); scope.record(&result); @@ -100,11 +86,7 @@ pub(super) fn cached_mlp_down<'ctx>( gate_close?; up_close?; hidden_close?; - Ok(ActualDown { - origin: Rc::clone(origin), - selection, - output, - }) + Ok(ActualDown { origin: Rc::clone(origin), selection, output }) } #[allow(clippy::too_many_arguments)] pub(super) fn cached_gate_up_scoped<'ctx>( @@ -140,15 +122,7 @@ pub(super) fn cached_gate_up_scoped<'ctx>( }; launch_cached_prepared(context, matrix, prepared, output.buffer_mut()?, format)?; } else { - launch_cached_projection( - context, - kind, - matrix, - activation, - output.buffer_mut()?, - rows, - columns, - )?; + launch_cached_projection(context, kind, matrix, activation, output.buffer_mut()?, rows, columns)?; } download_f32(output.buffer()?, FF).map(|_| ()) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs index 36536179..9929c7b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/expert_mlp_fn.rs @@ -40,16 +40,7 @@ pub(super) fn expert_mlp( } }; return finish_cached_mlp(context, gate, up, |hidden| { - project_matrix( - context, - binding, - weights, - selection, - MoeMatrixRole::Down, - hidden, - Some(cache), - None, - ) + project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, hidden, Some(cache), None) }); } // Genuine uncached diagnostic: keep its original download/reupload chain. @@ -76,22 +67,11 @@ pub(super) fn expert_mlp( let gate = upload_f32(context, &gate)?; let up = upload_f32(context, &up)?; let mut hidden = context.allocate(FF * 4).map_err(driver_error)?; - context - .moe_swiglu_f32(&gate, &up, &mut hidden) - .map_err(driver_error)?; + context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(driver_error)?; download_f32(&hidden, FF)?; gate.release().map_err(driver_error)?; up.release().map_err(driver_error)?; - let result = project_matrix( - context, - binding, - weights, - selection, - MoeMatrixRole::Down, - &hidden, - cache, - None, - ); + let result = project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, &hidden, cache, None); let release = hidden.release().map_err(driver_error); match result { Err(error) => Err(error), @@ -169,9 +149,7 @@ pub(super) fn finish_cached_mlp( }; let result = (|| { // Original arithmetic, including valid saturated negative-gate zero. - context - .moe_swiglu_f32(&gate, &up, &mut hidden) - .map_err(driver_error)?; + context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(driver_error)?; download_f32(&hidden, FF)?; down(&hidden) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs index e6f2d2f6..bfb193f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/finish_with_parts_fn.rs @@ -14,15 +14,8 @@ pub(super) fn finish_with_parts( parts: &[f32], mut cache: Option<&mut MoeWeightCache<'_>>, ) -> Result> { - let shared = expert_mlp( - context, - binding, - weights, - MoeExpertSelection::Shared, - activation, - cache.as_deref_mut(), - None, - )?; + let shared = + expert_mlp(context, binding, weights, MoeExpertSelection::Shared, activation, cache.as_deref_mut(), None)?; let shared_input = upload_f32(context, &shared)?; let owned_scalar; let scalar_weights = match cache { @@ -37,17 +30,13 @@ pub(super) fn finish_with_parts( } }; let mut scalar = context.allocate(4).map_err(driver_error)?; - context - .moe_shared_scalar_f32_bf16(activation, scalar_weights, &mut scalar) - .map_err(driver_error)?; + context.moe_shared_scalar_f32_bf16(activation, scalar_weights, &mut scalar).map_err(driver_error)?; let scalar_value = download_f32(&scalar, 1)?; if !(0.0..=1.0).contains(&scalar_value[0]) { return Err(Error::NonFinite); } let mut scaled = context.allocate(N * 4).map_err(driver_error)?; - context - .moe_shared_scale_f32(&shared_input, &scalar, &mut scaled) - .map_err(driver_error)?; + context.moe_shared_scale_f32(&shared_input, &scalar, &mut scaled).map_err(driver_error)?; download_f32(&scaled, N)?; if let Some(buffer) = owned_scalar { buffer.release().map_err(driver_error)?; @@ -60,9 +49,7 @@ pub(super) fn finish_with_parts( let route_weights = upload_f32(context, &route_values)?; let mut output = context.allocate(N * 4).map_err(driver_error)?; // Source default DOUBLE accumulation; shared already scalar-scaled. - context - .moe_combine_f64(&parts, &route_weights, &scaled, &mut output) - .map_err(driver_error)?; + context.moe_combine_f64(&parts, &route_weights, &scaled, &mut output).map_err(driver_error)?; let result = download_f32(&output, N)?; for buffer in [output, route_weights, parts, scaled] { buffer.release().map_err(driver_error)?; @@ -70,12 +57,13 @@ pub(super) fn finish_with_parts( Ok(result) } impl<'ctx> ActualSlotPacket<'ctx> { - pub(super) fn validate(&self, origin: &Rc, binding: &ModelBinding, - identity: TokenLayer) -> Result<()> { + pub(super) fn validate(&self, origin: &Rc, binding: &ModelBinding, identity: TokenLayer) -> Result<()> { if !Rc::ptr_eq(&self.origin, origin) || !self.origin.binding.matches(&binding.identity()) || self.origin.identity != identity - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } Ok(()) } } @@ -113,10 +101,7 @@ pub(super) fn execute_cuda_cached( if !weights.matches(&binding.identity(), route.identity().layer().get()) { return Err(Error::IdentityMismatch); } - let origin = Rc::new(DownOrigin { - binding: binding.identity(), - identity: route.identity(), - }); + let origin = Rc::new(DownOrigin { binding: binding.identity(), identity: route.identity() }); let failed = Rc::new(Cell::new(false)); let scope = DownScope::new(context, Rc::clone(&failed)); let mut parts = None; @@ -124,47 +109,44 @@ pub(super) fn execute_cuda_cached( let mut scalar = None; let mut scaled = None; let mut route_weights = None; - let result = (|| { - // Charge the single destination before any cache miss/eviction, so - // the existing Context-aware room policy accounts for its lifetime. - parts = Some(PackedDown::new(&scope)?); - for slot in 0..K { - let selection = MoeExpertSelection::Routed { slot }; - let down = cached_mlp_down( - context, binding, weights, selection, activation, cache, prepared, &scope, &origin, - )?; - parts.as_mut().ok_or(Error::IdentityMismatch)?.pack( + let result = + (|| { + // Charge the single destination before any cache miss/eviction, so + // the existing Context-aware room policy accounts for its lifetime. + parts = Some(PackedDown::new(&scope)?); + for slot in 0..K { + let selection = MoeExpertSelection::Routed { slot }; + let down = cached_mlp_down( + context, binding, weights, selection, activation, cache, prepared, &scope, &origin, + )?; + parts + .as_mut() + .ok_or(Error::IdentityMismatch)? + .pack(&scope, down.take(&origin, binding, route.identity(), selection)?)?; + } + let selection = MoeExpertSelection::Shared; + shared = + Some( + cached_mlp_down(context, binding, weights, selection, activation, cache, None, &scope, &origin)? + .take(&origin, binding, route.identity(), selection)?, + ); + let scalar_weights = cache.shared_scalar(binding, weights)?; + scalar = Some(scope.shared_scalar(activation, scalar_weights)?); + scaled = Some( + shared + .take() + .ok_or(Error::IdentityMismatch)? + .scale(&scope, scalar.as_ref().ok_or(Error::IdentityMismatch)?)?, + ); + scalar.take().ok_or(Error::IdentityMismatch)?.close()?; + let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get()); + route_weights = Some(scope.upload(&route_values)?); + parts.as_ref().ok_or(Error::IdentityMismatch)?.combine( &scope, - down.take(&origin, binding, route.identity(), selection)?, - )?; - } - let selection = MoeExpertSelection::Shared; - shared = Some( - cached_mlp_down( - context, binding, weights, selection, activation, cache, None, &scope, &origin, - )? - .take(&origin, binding, route.identity(), selection)?, - ); - let scalar_weights = cache.shared_scalar(binding, weights)?; - scalar = Some(scope.shared_scalar(activation, scalar_weights)?); - scaled = Some( - shared - .take() - .ok_or(Error::IdentityMismatch)? - .scale(&scope, scalar.as_ref().ok_or(Error::IdentityMismatch)?)?, - ); - scalar.take().ok_or(Error::IdentityMismatch)?.close()?; - let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get()); - route_weights = Some(scope.upload(&route_values)?); - parts.as_ref().ok_or(Error::IdentityMismatch)?.combine( - &scope, - route_weights - .as_ref() - .ok_or(Error::IdentityMismatch)? - .buffer()?, - scaled.as_ref().ok_or(Error::IdentityMismatch)?, - ) - })(); + route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, + scaled.as_ref().ok_or(Error::IdentityMismatch)?, + ) + })(); scope.record(&result); // Attempt every partial owner explicitly before selecting a primary. let shared_close = shared.map_or(Ok(()), |owner| owner.close()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs index 5c2d346f..e1e5dd2f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/impl_expertready.rs @@ -16,17 +16,9 @@ impl ExpertReady { } validate_values(&self.values, N) } - pub(super) fn from_completed( - binding: BindingIdentity, - identity: TokenLayer, - values: Box<[f32]>, - ) -> Result { + pub(super) fn from_completed(binding: BindingIdentity, identity: TokenLayer, values: Box<[f32]>) -> Result { validate_values(&values, N)?; - Ok(Self { - binding, - identity, - values, - }) + Ok(Self { binding, identity, values }) } } impl MoeExpertStage { @@ -39,16 +31,13 @@ impl MoeExpertStage { mut cache: Option<&mut MoeWeightCache<'_>>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Moe, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); txn.validate_binding(&binding.identity())?; route.validate_binding(&binding.identity())?; route.validate_for(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; if input.identity() != route.identity() || layer.get() >= binding.layer_count() { return Err(Error::IdentityMismatch); } @@ -61,9 +50,7 @@ impl MoeExpertStage { admit_budget(context.allocated_bytes(), context.budget_bytes())?; let ids = std::array::from_fn(|i| route.experts()[i].get()); // All seven descriptors and all ten IDs admitted before CUDA work. - let weights = binding - .moe_expert_weights(layer.get(), ids) - .map_err(binding_error)?; + let weights = binding.moe_expert_weights(layer.get(), ids).map_err(binding_error)?; if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } @@ -77,29 +64,13 @@ impl MoeExpertStage { // refuse: it is simply not consulted for any expert here (the // shared expert takes the uncached path inside the KAR branch). ( - execute_cuda_kar( - context, - binding, - &weights, - &activation, - &route, - input.mixed(), - (layer.get(), kar), - ), + execute_cuda_kar(context, binding, &weights, &activation, &route, input.mixed(), (layer.get(), kar)), Ok(()), ) } else if cache.is_some() { match context.prepare_routed_gate_up_q8(&activation) { Ok(prepared) => { - let result = execute_cuda( - context, - binding, - &weights, - &activation, - &route, - cache, - Some(&prepared), - ); + let result = execute_cuda(context, binding, &weights, &activation, &route, cache, Some(&prepared)); // Always attempt owner close before releasing its borrowed // activation, including a projection/readback failure. let closed = prepared.close().map_err(driver_error); @@ -108,10 +79,7 @@ impl MoeExpertStage { Err(error) => (Err(driver_error(error)), Ok(())), } } else { - ( - execute_cuda(context, binding, &weights, &activation, &route, None, None), - Ok(()), - ) + (execute_cuda(context, binding, &weights, &activation, &route, None, None), Ok(())) }; let activation_close = activation.release().map_err(driver_error); let values = result?; @@ -130,14 +98,10 @@ pub(super) fn execute_cuda( prepared: Option<&RoutedGateUpQ8<'_>>, ) -> Result> { if let Some(cache) = cache.as_deref_mut() { - return execute_cuda_cached( - context, binding, weights, activation, route, cache, prepared, - ); + return execute_cuda_cached(context, binding, weights, activation, route, cache, prepared); } let mut parts = Vec::new(); - parts - .try_reserve_exact(K * N) - .map_err(|_| Error::InputAllocation)?; + parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?; for slot in 0..K { let output = expert_mlp( context, @@ -165,14 +129,10 @@ pub(super) fn execute_cuda_kar( (layer, kar): (u32, &KarExpertSource), ) -> Result> { let mut parts = Vec::new(); - parts - .try_reserve_exact(K * N) - .map_err(|_| Error::InputAllocation)?; + parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?; for slot in 0..K { let expert = route.experts()[slot].get(); - let output = kar - .routed_mlp(context, layer, expert, host_input) - .map_err(kar_error)?; + let output = kar.routed_mlp(context, layer, expert, host_input).map_err(kar_error)?; validate_values(&output, N)?; parts.extend_from_slice(&output); } @@ -184,9 +144,7 @@ pub(super) fn kar_error(error: KarSourceError) -> Error { KarSourceError::Read => Error::InputRead, KarSourceError::NonFinite => Error::NonFinite, KarSourceError::Unsupported => Error::Unsupported(Stage::MoeExpert), - KarSourceError::Layout(_) | KarSourceError::Level(_) | KarSourceError::Config(_) => { - Error::InvalidExpert - } + KarSourceError::Layout(_) | KarSourceError::Level(_) | KarSourceError::Config(_) => Error::InvalidExpert, KarSourceError::Open | KarSourceError::Verify => Error::IdentityMismatch, KarSourceError::Device(_) => Error::CudaExecution, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs index 7990446f..a50f882c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/project_matrix_fn.rs @@ -27,9 +27,8 @@ pub(super) fn project_matrix( cache.matrix(binding, weights, selection, role)? } None => { - let block: MoeExpertBlock = binding - .moe_expert_block(weights, selection, role, 0, rows) - .map_err(binding_error)?; + let block: MoeExpertBlock = + binding.moe_expert_block(weights, selection, role, 0, rows).map_err(binding_error)?; if block.kind() != expected_kind || block.columns() != columns || block.rows() != rows { return Err(Error::InvalidDimension); } @@ -57,15 +56,7 @@ pub(super) fn project_matrix( }; launch_cached_prepared(context, matrix, prepared, &mut output, format)?; } else { - launch_cached_projection( - context, - expected_kind, - matrix, - activation, - &mut output, - rows, - columns, - )?; + launch_cached_projection(context, expected_kind, matrix, activation, &mut output, rows, columns)?; } download_f32(&output, rows) })(); @@ -90,9 +81,7 @@ pub(super) fn collect_rows( return Err(Error::InvalidDimension); } let mut candidate = Vec::new(); - candidate - .try_reserve_exact(rows) - .map_err(|_| Error::InputAllocation)?; + candidate.try_reserve_exact(rows).map_err(|_| Error::InputAllocation)?; for first in (0..rows).step_by(TILE) { let count = TILE.min(rows - first); let values = read(first, count)?; @@ -136,9 +125,7 @@ pub(super) fn launch_cached_projection( columns: usize, ) -> Result<()> { match matrix { - CachedMoeMatrix::Raw(raw) => { - launch_projection(context, kind, raw, activation, output, rows, columns) - } + CachedMoeMatrix::Raw(raw) => launch_projection(context, kind, raw, activation, output, rows, columns), CachedMoeMatrix::Dual(format, owner) => { if dual_format_kind(format) != (kind, rows, columns) { return Err(Error::IdentityMismatch); @@ -155,9 +142,9 @@ pub(super) fn launch_cached_prepared( format: RoutedFormat, ) -> Result<()> { match matrix { - CachedMoeMatrix::Raw(raw) => context - .project_routed_gate_up_prepared(raw, prepared, output, format) - .map_err(driver_error), + CachedMoeMatrix::Raw(raw) => { + context.project_routed_gate_up_prepared(raw, prepared, output, format).map_err(driver_error) + } CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format || !matches!( @@ -171,9 +158,7 @@ pub(super) fn launch_cached_prepared( { return Err(Error::IdentityMismatch); } - owner - .native_gate_up_prepared(prepared, output) - .map_err(driver_error) + owner.native_gate_up_prepared(prepared, output).map_err(driver_error) } } } @@ -190,22 +175,12 @@ pub(super) fn launch_projection( let projection = match kind { K::Q5K => { return context - .q5_k_q8_1( - matrix, - activation, - output, - Q5KProjectionShape { rows, columns }, - ) + .q5_k_q8_1(matrix, activation, output, Q5KProjectionShape { rows, columns }) .map_err(driver_error); } K::Q6K => { return context - .q6_k_q8_1( - matrix, - activation, - output, - Q6KProjectionShape { rows, columns }, - ) + .q6_k_q8_1(matrix, activation, output, Q6KProjectionShape { rows, columns }) .map_err(driver_error); } K::Q4K => ProjectionKind::Dense(DenseFormat::Q4_K), @@ -220,16 +195,7 @@ pub(super) fn launch_projection( K::Q2_0 => ProjectionKind::Routed(RoutedFormat::Q2_0), }; context - .project_q8_1( - matrix, - activation, - output, - ProjectionSpec { - kind: projection, - rows, - columns, - }, - ) + .project_q8_1(matrix, activation, output, ProjectionSpec { kind: projection, rows, columns }) .map_err(driver_error) } pub(super) fn admit_budget(allocated: usize, budget: usize) -> Result<()> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs index 27c48869..73aac01e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/tests.rs @@ -4,36 +4,22 @@ use super::*; #[test] fn completed_tiles_keep_all_rows_and_late_failure_withholds_candidate() { let values = collect_rows(N, |first, count| { - Ok((first..first + count) - .map(|i| i as f32) - .collect::>() - .into_boxed_slice()) + Ok((first..first + count).map(|i| i as f32).collect::>().into_boxed_slice()) }) .unwrap(); assert_eq!(values[0], 0.0); assert_eq!(values[639], 639.0); assert_eq!(values[2559], 2559.0); - for error in [ - Error::InputRead, - Error::InputAllocation, - Error::CudaExecution, - ] { + for error in [Error::InputRead, Error::InputAllocation, Error::CudaExecution] { let mut calls = 0; let result = collect_rows(N, |first, count| { calls += 1; - if first == 2496 { - Err(error) - } else { - Ok(vec![1.0; count].into_boxed_slice()) - } + if first == 2496 { Err(error) } else { Ok(vec![1.0; count].into_boxed_slice()) } }); assert_eq!(result, Err(error)); assert_eq!(calls, 40); } - assert_eq!( - collect_rows(639, |_, _| unreachable!()), - Err(Error::InvalidDimension) - ); + assert_eq!(collect_rows(639, |_, _| unreachable!()), Err(Error::InvalidDimension)); } #[test] fn nonfinite_last_expert_output_refuses_and_signedzero_is_retained() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/validate_values_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/validate_values_fn.rs index c4dadcdf..926fac32 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/validate_values_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_expert/validate_values_fn.rs @@ -20,9 +20,7 @@ pub(super) fn upload_bytes<'ctx>(context: &'ctx Context<'_>, bytes: &[u8]) -> Re pub(super) fn upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> Result> { validate_values(values, values.len())?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -31,22 +29,12 @@ pub(super) fn upload_f32<'ctx>(context: &'ctx Context<'_>, values: &[f32]) -> Re pub(super) fn download_f32(buffer: &DeviceBuffer<'_>, count: usize) -> Result> { let mut bytes = Vec::new(); let byte_count = count.checked_mul(4).ok_or(Error::Overflow)?; - bytes - .try_reserve_exact(byte_count) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(byte_count).map_err(|_| Error::InputAllocation)?; bytes.resize(byte_count, 0); buffer.copy_to(&mut bytes).map_err(driver_error)?; let mut values = Vec::new(); - values - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; - values.extend( - bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)), - ); + values.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + values.extend(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word))); validate_values(&values, count)?; Ok(values.into_boxed_slice()) } @@ -60,7 +48,9 @@ pub(super) fn binding_error(error: InputBindingError) -> Error { } } pub(super) fn driver_error(error: DriverError) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } match error { DriverError::UnsupportedQwenOperation | DriverError::UnsupportedProjection diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs index ba598d9c..e558ba87 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive.rs @@ -5,36 +5,50 @@ use crate::qwen_forward::cpu_expert_miss::runtime_error; #[allow(clippy::too_many_arguments)] pub(super) fn project_adaptive_groups<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[Vec], cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, origins: &[Rc], - down: &mut [[Option>; K]], cancelled: &mut impl FnMut() -> bool, + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[Vec], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + down: &mut [[Option>; K]], + cancelled: &mut impl FnMut() -> bool, actual: Option<&QwenChunkTxn<'_, '_>>, ) -> Result<()> { cache.poll_strata_adaptive(binding, false)?; - for row in rows { cache.observe_strata_adaptive_row(binding, &row.row().weights)?; } + for row in rows { + cache.observe_strata_adaptive_row(binding, &row.row().weights)?; + } let mut residents = Vec::new(); let mut misses = Vec::new(); residents.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; misses.try_reserve_exact(groups.len() * 8).map_err(|_| Error::InputAllocation)?; for pairs in groups.iter().filter(|p| !p.is_empty()) { let first = pairs[0]; - if cache.strata_adaptive_resident(binding, &rows[first.row].row().weights, - MoeExpertSelection::Routed { slot: first.slot })? { + if cache.strata_adaptive_resident( + binding, + &rows[first.row].row().weights, + MoeExpertSelection::Routed { slot: first.slot }, + )? { residents.push(pairs.as_slice()); } else { // Original native expert job supports MAXT=8. No scalarization of // genuine multi-row groups; each admitted batch preserves row order. - for batch in pairs.chunks(8) { misses.push(batch); } + for batch in pairs.chunks(8) { + misses.push(batch); + } } } // Actual outer wave directories coexist with owned jobs until join. - let wave_metadata = residents.capacity().checked_add(misses.capacity()) + let wave_metadata = residents + .capacity() + .checked_add(misses.capacity()) .and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>())) .and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>())) .ok_or(Error::Overflow)?; - let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata) - .ok_or(Error::InputAllocation)?; + let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?; let mut gpu_done = false; let cpu_owner = cache.cpu_miss_owner(binding)?; let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; @@ -45,19 +59,28 @@ pub(super) fn project_adaptive_groups<'ctx>( while end < misses.len() && end - offset < 16 { let first = misses[end][0]; let expert = rows[first.row].row().route.experts()[first.slot].get() as usize; - if expert >= 512 { return Err(Error::InvalidExpert); } - if seen[expert] { break; } + if expert >= 512 { + return Err(Error::InvalidExpert); + } + if seen[expert] { + break; + } seen[expert] = true; end += 1; } - if end == offset { return Err(Error::IdentityMismatch); } + if end == offset { + return Err(Error::IdentityMismatch); + } let batch = &misses[offset..end]; offset = end; - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } let mut jobs = Vec::new(); jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; let mut prepared_bytes = 0usize; - let preparation_metadata = jobs.capacity() + let preparation_metadata = jobs + .capacity() .checked_mul(std::mem::size_of::()) .ok_or(Error::Overflow)?; for pairs in batch { @@ -65,33 +88,47 @@ pub(super) fn project_adaptive_groups<'ctx>( let members = [(&rows[first.row].row().weights, first.slot)]; let mut inputs = Vec::new(); inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - for pair in *pairs { inputs.push(rows[pair.row].row().read.ready().mixed()); } + for pair in *pairs { + inputs.push(rows[pair.row].row().read.ready().mixed()); + } let job = binding.with_moe_routed_source(&members, binding_error, |source| { // Final immutable native blob temporarily coexists with all // three actual source role Boxes and the owned row inputs. - let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] - .into_iter().try_fold(0usize, |n, role| { - n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes) - .ok_or(Error::Overflow) - })?; - let preparation_peak = raw_bytes.checked_mul(2) + let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold( + 0usize, + |n, role| { + n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow) + }, + )?; + let preparation_peak = raw_bytes + .checked_mul(2) .and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows))) .and_then(|n| n.checked_add(prepared_bytes)) .and_then(|n| n.checked_add(preparation_metadata)) - .and_then(|n| inputs.capacity().checked_mul(std::mem::size_of::<&[f32]>()) - .and_then(|refs| n.checked_add(refs))) - .and_then(|n| n.checked_add(std::mem::size_of::())) + .and_then(|n| { + inputs + .capacity() + .checked_mul(std::mem::size_of::<&[f32]>()) + .and_then(|refs| n.checked_add(refs)) + }) + .and_then(|n| { + n.checked_add(std::mem::size_of::()) + }) .ok_or(Error::Overflow)?; - if preparation_peak > job_allowance { return Err(Error::InputAllocation); } + if preparation_peak > job_allowance { + return Err(Error::InputAllocation); + } let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; // Owned immutable validated bytes detach before other actor GPU // callbacks; no RefMut/source/Context crosses the CPU thread. source.finish().map_err(binding_error)?; Ok(job) })?; - prepared_bytes = prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?) - .ok_or(Error::InputAllocation)?; - if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { return Err(Error::InputAllocation); } + prepared_bytes = + prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?).ok_or(Error::InputAllocation)?; + if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { + return Err(Error::InputAllocation); + } jobs.push(job); } // Model-lifetime stacks/native scratch were admitted before the pool. @@ -102,7 +139,9 @@ pub(super) fn project_adaptive_groups<'ctx>( let gpu_result = (|| { if !gpu_done { for pairs in &residents { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; } gpu_done = true; @@ -114,15 +153,21 @@ pub(super) fn project_adaptive_groups<'ctx>( let completed = pending.join().map_err(runtime_error); gpu_result?; let completed = completed?; - if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } + if completed.len() != batch.len() { + return Err(Error::IdentityMismatch); + } for (values, pairs) in completed.into_iter().zip(batch) { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } let first = pairs[0]; let members = [(&rows[first.row].row().weights, first.slot)]; let keys = binding.with_moe_routed_source(&members, binding_error, |source| { - let keys = [source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + let keys = [ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?]; + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { return Err(Error::IdentityMismatch); } @@ -130,14 +175,21 @@ pub(super) fn project_adaptive_groups<'ctx>( cache.validate(binding, context)?; for pair in *pairs { if let Some(actual) = actual { - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), &rows[pair.row])?; + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; } let row = rows[pair.row].row(); let id = row.route.identity(); row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id - || down[pair.row][pair.slot].is_some() { return Err(Error::IdentityMismatch); } + if !origins[pair.row].binding.matches(&binding.identity()) + || origins[pair.row].identity != id + || down[pair.row][pair.slot].is_some() + { + return Err(Error::IdentityMismatch); + } } Ok(keys) })?; @@ -145,11 +197,16 @@ pub(super) fn project_adaptive_groups<'ctx>( // and device Down finite check has completed. No host-only proof. for (row_index, pair) in pairs.iter().enumerate() { let output = scope.upload_cpu_completed_row( - binding, &keys, DownSelection::Routed(pair.slot), &values, row_index, + binding, + &keys, + DownSelection::Routed(pair.slot), + &values, + row_index, )?; down[pair.row][pair.slot] = Some(ActualDown { origin: Rc::clone(&origins[pair.row]), - selection: MoeExpertSelection::Routed { slot: pair.slot }, output, + selection: MoeExpertSelection::Routed { slot: pair.slot }, + output, }); } drop(values.into_values()); @@ -157,7 +214,9 @@ pub(super) fn project_adaptive_groups<'ctx>( } if !gpu_done { for pairs in residents { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?; } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs index b081b7ca..8991508f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets.rs @@ -3,314 +3,17 @@ use super::*; use crate::qwen_forward::cpu_expert_miss::runtime_error; -#[allow(clippy::too_many_arguments)] -pub(super) fn project_adaptive_packets<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[Vec], cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, -) -> Result<()> { - let ephemeral = cache.ephemeral_routed_owner(binding, context)?; - let operation = project_inner(context, binding, rows, groups, cache, prepared, scope, - origins, packets, cancelled, actual); - // Every genuine pending owner is drained, including prepare/copy/cancel errors. - let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch) - .and_then(|mut owner| owner.drain()); - operation.and(cleanup) -} - -#[allow(clippy::too_many_arguments)] -fn project_inner<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[Vec], cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, -) -> Result<()> { - cache.poll_strata_adaptive(binding, false)?; - for row in rows { cache.observe_strata_adaptive_row(binding, &row.row().weights)?; } - let mut residents = Vec::new(); - let mut distinct_misses = Vec::new(); - let mut misses = Vec::new(); - let mut gpu_misses = Vec::new(); - let mut seen = [false; 512]; - residents.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; - distinct_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; - gpu_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; - misses.try_reserve_exact(groups.len() * 8).map_err(|_| Error::InputAllocation)?; - // Literal Strata row-major first occurrence. Group storage remains indexed - // by expert; packet combine keeps its original ten-slot f64 ordering. - for row in rows { - for selected in row.row().route.experts() { - let expert = selected.get() as usize; - if expert >= groups.len() || expert >= 512 { return Err(Error::InvalidExpert); } - if seen[expert] { continue; } - seen[expert] = true; - let pairs = groups[expert].as_slice(); - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let first = pairs[0]; - if cache.strata_adaptive_resident(binding, &rows[first.row].row().weights, - MoeExpertSelection::Routed { slot: first.slot })? { - residents.push(pairs); - } else { distinct_misses.push(pairs); } - } - } - if actual.is_mtp_verification()? { - // Private mode binds 141/256 explicitly. It is not an assertion that the - // bandwidth-adjusted live Original17 selected exactly 0.55. - let gpu_count = distinct_misses.len().checked_mul(141).ok_or(Error::Overflow)? / 256; - let cpu_count = distinct_misses.len().checked_sub(gpu_count).ok_or(Error::Overflow)?; - for (index, pairs) in distinct_misses.iter().enumerate() { - let mut eligible=index>=cpu_count; - if eligible && cache.uses_mapped_expert_source()? { - let owner=cache.ephemeral_routed_owner(binding,context)?; - let capacity=owner.try_borrow().map_err(|_|Error::IdentityMismatch)?.slot_count(); - // Native tail only: no replacement quota from the CPU prefix. - // Capacity is actual allocated single16/split8 owner, not T. - eligible=gpu_misses.len()]=if slot_count==2 {&mut legacy_slots} - else {&mut mapped_slots[..slot_count]}; - stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; - // Actual outer wave directories coexist with owned jobs until join. - let wave_metadata = residents.capacity().checked_add(misses.capacity()) - .and_then(|n| n.checked_add(distinct_misses.capacity())) - .and_then(|n| n.checked_add(gpu_misses.capacity())) - .and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>())) - .and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>())) - .and_then(|n|n.checked_add(std::mem::size_of::<[Option;18]>()+std::mem::size_of::<&mut[Option]>())) - .ok_or(Error::Overflow)?; - let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata) - .ok_or(Error::InputAllocation)?; - let mut gpu_done = false; - let cpu_owner = cache.cpu_miss_owner(binding)?; - let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - let mut offset = 0usize; - while offset < misses.len() { - let mut end = offset; - let mut seen = [false; 512]; - while end < misses.len() && end - offset < 16 { - let first = misses[end][0]; - let expert = rows[first.row].row().route.experts()[first.slot].get() as usize; - if expert >= 512 { return Err(Error::InvalidExpert); } - if seen[expert] { break; } - seen[expert] = true; - end += 1; - } - if end == offset { return Err(Error::IdentityMismatch); } - let batch = &misses[offset..end]; - offset = end; - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let mut jobs = Vec::new(); - jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; - let mut prepared_bytes = 0usize; - let preparation_metadata = jobs.capacity() - .checked_mul(std::mem::size_of::()) - .ok_or(Error::Overflow)?; - for pairs in batch { - let first = pairs[0]; - let members = [(&rows[first.row].row().weights, first.slot)]; - let mut inputs = Vec::new(); - inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - for pair in *pairs { inputs.push(rows[pair.row].row().read.ready().mixed()); } - let job = binding.with_moe_routed_source(&members, binding_error, |source| { - // Final immutable native blob temporarily coexists with all - // three actual source role Boxes and the owned row inputs. - let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] - .into_iter().try_fold(0usize, |n, role| { - n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes) - .ok_or(Error::Overflow) - })?; - let preparation_peak = raw_bytes.checked_mul(2) - .and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows))) - .and_then(|n| n.checked_add(prepared_bytes)) - .and_then(|n| n.checked_add(preparation_metadata)) - .and_then(|n| inputs.capacity().checked_mul(std::mem::size_of::<&[f32]>()) - .and_then(|refs| n.checked_add(refs))) - .and_then(|n| n.checked_add(std::mem::size_of::())) - .ok_or(Error::Overflow)?; - if preparation_peak > job_allowance { return Err(Error::InputAllocation); } - let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; - // Owned immutable validated bytes detach before other actor GPU - // callbacks; no RefMut/source/Context crosses the CPU thread. - source.finish().map_err(binding_error)?; - Ok(job) - })?; - prepared_bytes = prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?) - .ok_or(Error::InputAllocation)?; - if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { return Err(Error::InputAllocation); } - jobs.push(job); - } - // Model-lifetime stacks/native scratch were admitted before the pool. - // This request admits <=16 jobs and <=48MiB INCLUDING actual directory, - // preparation and start/join metadata/capacities. Callees measure their - // own retained capacities against this remaining allowance before send. - let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; - let gpu_result = (|| { - if !gpu_done { - for pairs in &residents { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - resident_queue::project_group_packets(context, binding, rows, pairs, cache, prepared, - scope, origins, packets, cancelled, actual, None)?; - } - gpu_done = true; - } - consume_gpu_wave(context, binding, rows, &gpu_misses, cache, prepared, scope, - origins, packets, &mut slots, cancelled, actual)?; - stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; - Ok(()) - })(); - // Always drain actual CPU consumers, including GPU failure/cancellation. - // Preserve the primary GPU failure; no source allocation outlives join. - let completed = pending.join().map_err(runtime_error); - gpu_result?; - let completed = completed?; - if completed.len() != batch.len() { return Err(Error::IdentityMismatch); } - for (values, pairs) in completed.into_iter().zip(batch) { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let first = pairs[0]; - let members = [(&rows[first.row].row().weights, first.slot)]; - let keys = binding.with_moe_routed_source(&members, binding_error, |source| { - let keys = [source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, - source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?]; - if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { - return Err(Error::IdentityMismatch); - } - source.finish().map_err(binding_error)?; - cache.validate(binding, context)?; - for pair in *pairs { - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), &rows[pair.row])?; - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { - return Err(Error::IdentityMismatch); - } - packets[pair.row].validate(&origins[pair.row], binding, id)?; - } - Ok(keys) - })?; - // Retain the genuine completed CPU owner until every actual upload - // and device Down finite check has completed. No host-only proof. - for (row_index, pair) in pairs.iter().enumerate() { - let output = scope.upload_cpu_completed_row( - binding, &keys, DownSelection::Routed(pair.slot), &values, row_index, - )?; - // The actual CPU row owns a completed H2D and whole Down finite - // scan. Its device owner and the completed CPU owner stay alive - // through the direct copy and post-copy causal checks. - let copy_result = output.with_completed(scope, DownSelection::Routed(pair.slot), |buffer| { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let mut target = [(&mut packets[pair.row].packet, pair.slot)]; - super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut target, |copies| { - context.copy_routed_down_columns_to_slots(buffer, 1, copies).map_err(driver_error)?; - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - cache.validate(binding, context)?; - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), &rows[pair.row])?; - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { - return Err(Error::IdentityMismatch); - } - Ok(()) - }) - }); - let cleanup = output.close(); - copy_result.and(cleanup)?; - } - drop(values.into_values()); - } - } - if !gpu_done { - for pairs in residents { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - resident_queue::project_group_packets(context, binding, rows, pairs, cache, prepared, - scope, origins, packets, cancelled, actual, None)?; - } - } - while slots.iter().any(Option::is_some) { - consume_gpu_wave(context, binding, rows, &gpu_misses, cache, prepared, scope, - origins, packets, &mut slots, cancelled, actual)?; - stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; - } - Ok(()) -} - -#[allow(clippy::too_many_arguments)] -fn stage_gpu_wave<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[&[Pair]], cache: &MoeWeightCache<'_>, next: &mut usize, - slots: &mut [Option], cancelled: &mut impl FnMut() -> bool, -) -> Result<()> { - let owner = cache.ephemeral_routed_owner(binding, context)?; - for (slot, directory) in slots.iter_mut().enumerate() { - if directory.is_some() || *next == groups.len() { continue; } - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let first = *groups[*next].first().ok_or(Error::IdentityMismatch)?; - let members = [(&rows[first.row].row().weights, first.slot)]; - // Source is actually validated and explicitly finished by stage before - // the next source/CPU preparation borrows the artifact RefCell. - binding.with_moe_routed_source(&members, binding_error, |source| { - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? - .stage(slot, binding, source, 0) - })?; - *directory = Some(*next); - *next += 1; - } - Ok(()) -} -#[allow(clippy::too_many_arguments)] -fn consume_gpu_wave<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[&[Pair]], cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, origins: &[Rc], packets: &mut [ActualSlotPacket<'ctx>], - slots: &mut [Option], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, -) -> Result<()> { - for (slot, directory) in slots.iter_mut().enumerate() { - let Some(index) = *directory else { continue; }; - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let owner = cache.ephemeral_routed_owner(binding, context)?; - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; - resident_queue::project_group_packets(context, binding, rows, - groups.get(index).ok_or(Error::IdentityMismatch)?, cache, prepared, - scope, origins, packets, cancelled, actual, Some(slot))?; - *directory = None; - } - Ok(()) -} +#[path = "moe_group_adaptive_packets/project_adaptive_packets_fn.rs"] +mod project_adaptive_packets_fn; +#[allow(unused_imports)] +pub(super) use project_adaptive_packets_fn::project_adaptive_packets; +#[path = "moe_group_adaptive_packets/project_inner_fn.rs"] +mod project_inner_fn; +#[allow(unused_imports)] +use project_inner_fn::project_inner; +#[path = "moe_group_adaptive_packets/stage_gpu_wave_fn.rs"] +mod stage_gpu_wave_fn; +#[allow(unused_imports)] +use stage_gpu_wave_fn::consume_gpu_wave; +#[allow(unused_imports)] +use stage_gpu_wave_fn::stage_gpu_wave; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_adaptive_packets_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_adaptive_packets_fn.rs new file mode 100644 index 00000000..713a7c49 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_adaptive_packets_fn.rs @@ -0,0 +1,26 @@ +//! Moved out of the parent module by STRA-338: fn project_adaptive_packets. + +#[allow(unused_imports)] +use super::*; + +#[allow(clippy::too_many_arguments)] +pub(in super::super) fn project_adaptive_packets<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[Vec], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + packets: &mut [ActualSlotPacket<'ctx>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, +) -> Result<()> { + let ephemeral = cache.ephemeral_routed_owner(binding, context)?; + let operation = + project_inner(context, binding, rows, groups, cache, prepared, scope, origins, packets, cancelled, actual); + // Every genuine pending owner is drained, including prepare/copy/cancel errors. + let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.drain()); + operation.and(cleanup) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs new file mode 100644 index 00000000..4afafdcc --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/project_inner_fn.rs @@ -0,0 +1,361 @@ +//! Moved out of the parent module by STRA-338: fn project_inner. + +#[allow(unused_imports)] +use super::*; + +#[allow(clippy::too_many_arguments)] +pub(super) fn project_inner<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[Vec], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + packets: &mut [ActualSlotPacket<'ctx>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, +) -> Result<()> { + cache.poll_strata_adaptive(binding, false)?; + for row in rows { + cache.observe_strata_adaptive_row(binding, &row.row().weights)?; + } + let mut residents = Vec::new(); + let mut distinct_misses = Vec::new(); + let mut misses = Vec::new(); + let mut gpu_misses = Vec::new(); + let mut seen = [false; 512]; + residents.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; + distinct_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; + gpu_misses.try_reserve_exact(groups.len()).map_err(|_| Error::InputAllocation)?; + misses.try_reserve_exact(groups.len() * 8).map_err(|_| Error::InputAllocation)?; + // Literal Strata row-major first occurrence. Group storage remains indexed + // by expert; packet combine keeps its original ten-slot f64 ordering. + for row in rows { + for selected in row.row().route.experts() { + let expert = selected.get() as usize; + if expert >= groups.len() || expert >= 512 { + return Err(Error::InvalidExpert); + } + if seen[expert] { + continue; + } + seen[expert] = true; + let pairs = groups[expert].as_slice(); + validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + let first = pairs[0]; + if cache.strata_adaptive_resident( + binding, + &rows[first.row].row().weights, + MoeExpertSelection::Routed { slot: first.slot }, + )? { + residents.push(pairs); + } else { + distinct_misses.push(pairs); + } + } + } + if actual.is_mtp_verification()? { + // Private mode binds 141/256 explicitly. It is not an assertion that the + // bandwidth-adjusted live Original17 selected exactly 0.55. + let gpu_count = distinct_misses.len().checked_mul(141).ok_or(Error::Overflow)? / 256; + let cpu_count = distinct_misses.len().checked_sub(gpu_count).ok_or(Error::Overflow)?; + for (index, pairs) in distinct_misses.iter().enumerate() { + let mut eligible = index >= cpu_count; + if eligible && cache.uses_mapped_expert_source()? { + let owner = cache.ephemeral_routed_owner(binding, context)?; + let capacity = owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count(); + // Native tail only: no replacement quota from the CPU prefix. + // Capacity is actual allocated single16/split8 owner, not T. + eligible = gpu_misses.len() < capacity && pairs.len() <= 64; + if eligible { + let first = pairs[0]; + let members = [(&rows[first.row].row().weights, first.slot)]; + eligible = binding.with_moe_routed_source(&members, binding_error, |source| { + let eligible = owner + .try_borrow() + .map_err(|_| Error::IdentityMismatch)? + .mapped_eligible(binding, source, 0)?; + source.finish().map_err(binding_error)?; + Ok(eligible) + })?; + } + } + if eligible { + gpu_misses.push(*pairs); + } else { + for batch in pairs.chunks(8) { + misses.push(batch); + } + } + } + } else { + // Prompt phase stages every used nonresident expert by actual expert ID. + // Legacy factory remains two-slot detached copies. The separately + // selected mapped factory owns real registered banks and16 fixed slots; + // prompt groups preserve expert-ID order with bounded reuse waves. + // Every pair was authenticated above; sorting allocates no directory. + distinct_misses.sort_unstable_by_key(|pairs| { + let first = pairs[0]; + rows[first.row].row().route.experts()[first.slot].get() + }); + for pairs in &distinct_misses { + gpu_misses.push(*pairs); + } + } + let mut gpu_next = 0; + let slot_count = + cache.ephemeral_routed_owner(binding, context)?.try_borrow().map_err(|_| Error::IdentityMismatch)?.slot_count(); + let mut legacy_slots = [None; 2]; + let mut mapped_slots = [None; 16]; + if !matches!(slot_count, 2 | 8 | 16) { + return Err(Error::IdentityMismatch); + } + let mut slots: &mut [Option] = + if slot_count == 2 { &mut legacy_slots } else { &mut mapped_slots[..slot_count] }; + stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; + // Actual outer wave directories coexist with owned jobs until join. + let wave_metadata = residents + .capacity() + .checked_add(misses.capacity()) + .and_then(|n| n.checked_add(distinct_misses.capacity())) + .and_then(|n| n.checked_add(gpu_misses.capacity())) + .and_then(|n| n.checked_mul(std::mem::size_of::<&[Pair]>())) + .and_then(|n| n.checked_add(std::mem::size_of::<[bool; 512]>())) + .and_then(|n| { + n.checked_add(std::mem::size_of::<[Option; 18]>() + std::mem::size_of::<&mut [Option]>()) + }) + .ok_or(Error::Overflow)?; + let job_allowance = (48usize * 1024 * 1024).checked_sub(wave_metadata).ok_or(Error::InputAllocation)?; + let mut gpu_done = false; + let cpu_owner = cache.cpu_miss_owner(binding)?; + let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let mut offset = 0usize; + while offset < misses.len() { + let mut end = offset; + let mut seen = [false; 512]; + while end < misses.len() && end - offset < 16 { + let first = misses[end][0]; + let expert = rows[first.row].row().route.experts()[first.slot].get() as usize; + if expert >= 512 { + return Err(Error::InvalidExpert); + } + if seen[expert] { + break; + } + seen[expert] = true; + end += 1; + } + if end == offset { + return Err(Error::IdentityMismatch); + } + let batch = &misses[offset..end]; + offset = end; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let mut jobs = Vec::new(); + jobs.try_reserve_exact(batch.len()).map_err(|_| Error::InputAllocation)?; + let mut prepared_bytes = 0usize; + let preparation_metadata = jobs + .capacity() + .checked_mul(std::mem::size_of::()) + .ok_or(Error::Overflow)?; + for pairs in batch { + let first = pairs[0]; + let members = [(&rows[first.row].row().weights, first.slot)]; + let mut inputs = Vec::new(); + inputs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + for pair in *pairs { + inputs.push(rows[pair.row].row().read.ready().mixed()); + } + let job = binding.with_moe_routed_source(&members, binding_error, |source| { + // Final immutable native blob temporarily coexists with all + // three actual source role Boxes and the owned row inputs. + let raw_bytes = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().try_fold( + 0usize, + |n, role| { + n.checked_add(source.descriptor(0, role).map_err(binding_error)?.bytes).ok_or(Error::Overflow) + }, + )?; + let preparation_peak = raw_bytes + .checked_mul(2) + .and_then(|n| inputs.len().checked_mul(N * 8).and_then(|rows| n.checked_add(rows))) + .and_then(|n| n.checked_add(prepared_bytes)) + .and_then(|n| n.checked_add(preparation_metadata)) + .and_then(|n| { + inputs + .capacity() + .checked_mul(std::mem::size_of::<&[f32]>()) + .and_then(|refs| n.checked_add(refs)) + }) + .and_then(|n| { + n.checked_add(std::mem::size_of::()) + }) + .ok_or(Error::Overflow)?; + if preparation_peak > job_allowance { + return Err(Error::InputAllocation); + } + let job = cpu.prepare_scoped(binding, source, 0, &inputs).map_err(runtime_error)?; + // Owned immutable validated bytes detach before other actor GPU + // callbacks; no RefMut/source/Context crosses the CPU thread. + source.finish().map_err(binding_error)?; + Ok(job) + })?; + prepared_bytes = + prepared_bytes.checked_add(job.owned_bytes().map_err(runtime_error)?).ok_or(Error::InputAllocation)?; + if prepared_bytes.checked_add(preparation_metadata).is_none_or(|n| n > job_allowance) { + return Err(Error::InputAllocation); + } + jobs.push(job); + } + // Model-lifetime stacks/native scratch were admitted before the pool. + // This request admits <=16 jobs and <=48MiB INCLUDING actual directory, + // preparation and start/join metadata/capacities. Callees measure their + // own retained capacities against this remaining allowance before send. + let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?; + let gpu_result = (|| { + if !gpu_done { + for pairs in &residents { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + resident_queue::project_group_packets( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, + None, + )?; + } + gpu_done = true; + } + consume_gpu_wave( + context, + binding, + rows, + &gpu_misses, + cache, + prepared, + scope, + origins, + packets, + &mut slots, + cancelled, + actual, + )?; + stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; + Ok(()) + })(); + // Always drain actual CPU consumers, including GPU failure/cancellation. + // Preserve the primary GPU failure; no source allocation outlives join. + let completed = pending.join().map_err(runtime_error); + gpu_result?; + let completed = completed?; + if completed.len() != batch.len() { + return Err(Error::IdentityMismatch); + } + for (values, pairs) in completed.into_iter().zip(batch) { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let first = pairs[0]; + let members = [(&rows[first.row].row().weights, first.slot)]; + let keys = binding.with_moe_routed_source(&members, binding_error, |source| { + let keys = [ + source.descriptor(0, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(0, MoeMatrixRole::Down).map_err(binding_error)?, + ]; + if !values.matches(binding, &keys) || values.values().len() != pairs.len() * N { + return Err(Error::IdentityMismatch); + } + source.finish().map_err(binding_error)?; + cache.validate(binding, context)?; + for pair in *pairs { + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; + let row = rows[pair.row].row(); + let id = row.route.identity(); + row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; + if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { + return Err(Error::IdentityMismatch); + } + packets[pair.row].validate(&origins[pair.row], binding, id)?; + } + Ok(keys) + })?; + // Retain the genuine completed CPU owner until every actual upload + // and device Down finite check has completed. No host-only proof. + for (row_index, pair) in pairs.iter().enumerate() { + let output = scope.upload_cpu_completed_row( + binding, + &keys, + DownSelection::Routed(pair.slot), + &values, + row_index, + )?; + // The actual CPU row owns a completed H2D and whole Down finite + // scan. Its device owner and the completed CPU owner stay alive + // through the direct copy and post-copy causal checks. + let copy_result = output.with_completed(scope, DownSelection::Routed(pair.slot), |buffer| { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let mut target = [(&mut packets[pair.row].packet, pair.slot)]; + super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut target, |copies| { + context.copy_routed_down_columns_to_slots(buffer, 1, copies).map_err(driver_error)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + cache.validate(binding, context)?; + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; + let row = rows[pair.row].row(); + let id = row.route.identity(); + row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; + if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { + return Err(Error::IdentityMismatch); + } + Ok(()) + }) + }); + let cleanup = output.close(); + copy_result.and(cleanup)?; + } + drop(values.into_values()); + } + } + if !gpu_done { + for pairs in residents { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + resident_queue::project_group_packets( + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, None, + )?; + } + } + while slots.iter().any(Option::is_some) { + consume_gpu_wave( + context, + binding, + rows, + &gpu_misses, + cache, + prepared, + scope, + origins, + packets, + &mut slots, + cancelled, + actual, + )?; + stage_gpu_wave(context, binding, rows, &gpu_misses, cache, &mut gpu_next, &mut slots, cancelled)?; + } + Ok(()) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs new file mode 100644 index 00000000..110fd9d0 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_adaptive_packets/stage_gpu_wave_fn.rs @@ -0,0 +1,78 @@ +//! Moved out of the parent module by STRA-338: fn stage_gpu_wave, fn consume_gpu_wave. + +#[allow(unused_imports)] +use super::*; + +#[allow(clippy::too_many_arguments)] +pub(super) fn stage_gpu_wave<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[&[Pair]], + cache: &MoeWeightCache<'_>, + next: &mut usize, + slots: &mut [Option], + cancelled: &mut impl FnMut() -> bool, +) -> Result<()> { + let owner = cache.ephemeral_routed_owner(binding, context)?; + for (slot, directory) in slots.iter_mut().enumerate() { + if directory.is_some() || *next == groups.len() { + continue; + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let first = *groups[*next].first().ok_or(Error::IdentityMismatch)?; + let members = [(&rows[first.row].row().weights, first.slot)]; + // Source is actually validated and explicitly finished by stage before + // the next source/CPU preparation borrows the artifact RefCell. + binding.with_moe_routed_source(&members, binding_error, |source| { + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) + })?; + *directory = Some(*next); + *next += 1; + } + Ok(()) +} +#[allow(clippy::too_many_arguments)] +pub(super) fn consume_gpu_wave<'ctx>( + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[&[Pair]], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + packets: &mut [ActualSlotPacket<'ctx>], + slots: &mut [Option], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, +) -> Result<()> { + for (slot, directory) in slots.iter_mut().enumerate() { + let Some(index) = *directory else { + continue; + }; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let owner = cache.ephemeral_routed_owner(binding, context)?; + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; + resident_queue::project_group_packets( + context, + binding, + rows, + groups.get(index).ok_or(Error::IdentityMismatch)?, + cache, + prepared, + scope, + origins, + packets, + cancelled, + actual, + Some(slot), + )?; + *directory = None; + } + Ok(()) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs index 5c8491a2..991ceacb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk.rs @@ -3,19 +3,19 @@ use super::super::gr::{DetachedGrRead, GrStage}; use super::super::session::chunk::{ChunkFfnRow, QwenChunkTxn}; use super::*; -#[path = "moe_mmq_chunk.rs"] -mod resident; -#[path = "moe_mmq_slotpack.rs"] -mod resident_slotpack; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="moe_prompt_finish.rs"] -mod prompt_finish; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "moe_group_resident_queue.rs"] -mod resident_queue; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "moe_group_adaptive_packets.rs"] mod adaptive_packets; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "moe_prompt_finish.rs"] +mod prompt_finish; +#[path = "moe_mmq_chunk.rs"] +mod resident; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "moe_group_resident_queue.rs"] +mod resident_queue; +#[path = "moe_mmq_slotpack.rs"] +mod resident_slotpack; pub(in crate::qwen_forward) struct PreparedMoeRow { read: DetachedGrRead, @@ -32,34 +32,21 @@ mod tests { use super::*; #[test] fn actual_group_inverse_preserves_row_slots_and_refuses_duplicate_experts() { - let ids = [ - [7, 2, 3, 4, 5, 6, 8, 9, 10, 11], - [11, 2, 7, 4, 5, 6, 8, 9, 10, 3], - ]; + let ids = [[7, 2, 3, 4, 5, 6, 8, 9, 10, 11], [11, 2, 7, 4, 5, 6, 8, 9, 10, 3]]; let groups = grouped_pairs(&ids).unwrap(); let mut inverse = [[None; K]; 2]; for (expert, group) in groups.iter().enumerate() { for pair in group { - assert!( - inverse[pair.row][pair.slot] - .replace(expert as u32) - .is_none() - ); + assert!(inverse[pair.row][pair.slot].replace(expert as u32).is_none()); } } for row in 0..2 { assert_eq!(inverse[row].map(Option::unwrap), ids[row]); } - assert_eq!( - groups[7], - [Pair { row: 0, slot: 0 }, Pair { row: 1, slot: 2 }] - ); + assert_eq!(groups[7], [Pair { row: 0, slot: 0 }, Pair { row: 1, slot: 2 }]); let mut duplicate = ids; duplicate[1][9] = duplicate[1][0]; - assert!(matches!( - grouped_pairs(&duplicate), - Err(Error::InvalidExpert) - )); + assert!(matches!(grouped_pairs(&duplicate), Err(Error::InvalidExpert))); let mut outside = ids; outside[0][0] = 512; assert!(matches!(grouped_pairs(&outside), Err(Error::InvalidExpert))); @@ -108,19 +95,19 @@ use project_group_source_consumers_fn::project_group_source_consumers; #[path = "moe_group_chunk/ordered_down_refusal_fn.rs"] mod ordered_down_refusal_fn; #[allow(unused_imports)] -use ordered_down_refusal_fn::ordered_down_refusal; -#[allow(unused_imports)] -use ordered_down_refusal_fn::use_direct_packets; -#[allow(unused_imports)] -use ordered_down_refusal_fn::validate_packet_pairs; -#[allow(unused_imports)] use ordered_down_refusal_fn::execute_direct_packets; #[allow(unused_imports)] use ordered_down_refusal_fn::finish_shared; #[allow(unused_imports)] +use ordered_down_refusal_fn::finish_shared_queued; +#[allow(unused_imports)] +use ordered_down_refusal_fn::ordered_down_refusal; +#[allow(unused_imports)] +use ordered_down_refusal_fn::use_direct_packets; +#[allow(unused_imports)] use ordered_down_refusal_fn::use_shared_tail; #[allow(unused_imports)] -use ordered_down_refusal_fn::finish_shared_queued; +use ordered_down_refusal_fn::validate_packet_pairs; #[path = "moe_group_chunk/finish_shared_with_fn.rs"] mod finish_shared_with_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs index c9795ed2..8b50e5f7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/execute_bound_fn.rs @@ -10,8 +10,9 @@ pub(super) fn execute_bound<'ctx>( cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, actual: Option<&QwenChunkTxn<'_, 'ctx>>, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - native:Option>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< + prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, ) -> Result> { // The same binding/pointer validation returns the stable actor Context. // This keeps a finite-guard loan independent of the immutable matrix loan. @@ -44,11 +45,7 @@ pub(super) fn execute_bound<'ctx>( .checked_mul(K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) .and_then(|v| v.checked_add(DEVICE_PEAK)) .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(extra) - .is_none_or(|v| v > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(extra).is_none_or(|v| v > context.budget_bytes()) { return Err(Error::Unsupported(Stage::MoeExpert)); } let kind = rows[0] @@ -61,13 +58,7 @@ pub(super) fn execute_bound<'ctx>( let grouped = grouped || cache.uses_strata_adaptive_experts(); for row in rows { for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up] { - if row - .row() - .weights - .kind(MoeExpertSelection::Routed { slot: 0 }, role) - .map_err(binding_error)? - != kind - { + if row.row().weights.kind(MoeExpertSelection::Routed { slot: 0 }, role).map_err(binding_error)? != kind { return Err(Error::IdentityMismatch); } } @@ -84,17 +75,16 @@ pub(super) fn execute_bound<'ctx>( let failed = Rc::new(Cell::new(false)); let scope = DownScope::new(context, Rc::clone(&failed)); let scope = if use_direct_packets(cache) { - scope.with_routed_finite(cache.routed_finite_owner(binding, context)?)? + scope + .with_routed_finite(cache.routed_finite_owner(binding, context)?)? .with_routed_workspace(cache.routed_workspace_owner(binding, context)?)? - } else { scope }; + } else { + scope + }; let mut activations = Vec::new(); - activations - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + activations.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; let mut prepared = Vec::new(); - prepared - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + prepared.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; let upload_result = (|| { for row in rows { if cancelled() { @@ -111,11 +101,8 @@ pub(super) fn execute_bound<'ctx>( admission = Err(Error::Unsupported(Stage::Executor)); break; } - let next = activation.buffer().and_then(|buffer| { - context - .prepare_routed_gate_up_q8(buffer) - .map_err(driver_error) - }); + let next = + activation.buffer().and_then(|buffer| context.prepare_routed_gate_up_q8(buffer).map_err(driver_error)); match next { Ok(owner) => prepared.push(owner), Err(error) => { @@ -127,12 +114,12 @@ pub(super) fn execute_bound<'ctx>( } let result = admission.and_then(|()| { if !grouped { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if native.is_some() {return Err(Error::IdentityMismatch);} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if native.is_some() { + return Err(Error::IdentityMismatch); + } let mut outputs = Vec::new(); - outputs - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (i, row) in rows.iter().enumerate() { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -147,61 +134,57 @@ pub(super) fn execute_bound<'ctx>( cache, Some(&prepared[i]), )?; - outputs.push(ExpertReady::from_completed( - binding.identity(), - row.route.identity(), - values, - )?); + outputs.push(ExpertReady::from_completed(binding.identity(), row.route.identity(), values)?); } return Ok(outputs); } let mut ids = Vec::new(); - ids.try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + ids.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for row in rows { ids.push(std::array::from_fn(|i| row.row().route.experts()[i].get())); } let groups = grouped_pairs(&ids)?; let mut origins = Vec::new(); - origins - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for row in rows { - origins.push(Rc::new(DownOrigin { - binding: binding.identity(), - identity: row.row().route.identity(), - })); + origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() })); } if use_direct_packets(cache) { - return execute_direct_packets(context, binding, rows, &groups, cache, - &prepared, &activations, &scope, &origins, cancelled, + return execute_direct_packets( + context, + binding, + rows, + &groups, + cache, + &prepared, + &activations, + &scope, + &origins, + cancelled, actual.ok_or(Error::IdentityMismatch)?, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] native); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native, + ); } let mut down = Vec::new(); - down.try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + down.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; down.resize_with(rows.len(), || std::array::from_fn::<_, K, _>(|_| None)); let operation = (|| { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if cache.uses_strata_adaptive_experts() { - adaptive::project_adaptive_groups(context, binding, rows, &groups, cache, &prepared, - &scope, &origins, &mut down, cancelled, actual)?; + adaptive::project_adaptive_groups( + context, binding, rows, &groups, cache, &prepared, &scope, &origins, &mut down, cancelled, actual, + )?; } let adaptive_done = uses_adaptive(cache); for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive_done) { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - project_group( - context, binding, rows, pairs, cache, &prepared, &scope, &origins, &mut down, - cancelled, - )?; + project_group(context, binding, rows, pairs, cache, &prepared, &scope, &origins, &mut down, cancelled)?; } let mut outputs = Vec::new(); - outputs - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; // Sorting compute by expert never changes the original slot 0..9 // order of the exact f64 combine kernel. for (i, row) in rows.iter().enumerate() { @@ -225,25 +208,12 @@ pub(super) fn execute_bound<'ctx>( } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] packed.with_completed(&scope, |packet| direct_gpu::observe_packet(packet))?; - finish_shared( - context, - binding, - row, - activations[i].buffer()?, - cache, - &scope, - &origins[i], - &packed, - ) + finish_shared(context, binding, row, activations[i].buffer()?, cache, &scope, &origins[i], &packed) })(); let close = packed.close(); let values = output?; close?; - outputs.push(ExpertReady::from_completed( - binding.identity(), - row.route.identity(), - values, - )?); + outputs.push(ExpertReady::from_completed(binding.identity(), row.route.identity(), values)?); } Ok(outputs) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs index 395b5f92..b397c999 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/finish_shared_with_fn.rs @@ -24,20 +24,11 @@ pub(super) fn finish_shared_with<'ctx>( let mut scaled = None; let mut route_weights = None; let operation = (|| { - shared = Some( - cached_mlp_down( - context, - binding, - &row.weights, - selection, - activation, - cache, - None, - scope, - origin, - )? - .take(origin, binding, row.route.identity(), selection)?, - ); + shared = + Some( + cached_mlp_down(context, binding, &row.weights, selection, activation, cache, None, scope, origin)? + .take(origin, binding, row.route.identity(), selection)?, + ); let scalar_weights = cache.shared_scalar(binding, &row.weights)?; scalar = Some(scope.shared_scalar(activation, scalar_weights)?); scaled = Some( @@ -50,10 +41,7 @@ pub(super) fn finish_shared_with<'ctx>( let values: [f32; K] = std::array::from_fn(|i| row.route.weights()[i].get()); route_weights = Some(scope.upload(&values)?); combine( - route_weights - .as_ref() - .ok_or(Error::IdentityMismatch)? - .buffer()?, + route_weights.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, scaled.as_ref().ok_or(Error::IdentityMismatch)?, ) })(); @@ -73,8 +61,13 @@ pub(super) fn finish_shared_with<'ctx>( } pub(super) fn uses_adaptive(cache: &MoeWeightCache<'_>) -> bool { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - { cache.uses_strata_adaptive_experts() } - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] - { let _ = cache; false } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + cache.uses_strata_adaptive_experts() + } + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] + { + let _ = cache; + false + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs index 470a0695..6d0901cc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/impl_preparedmoerow.rs @@ -11,13 +11,8 @@ impl PreparedMoeRow { position: super::super::super::contract::Position, layer: LayerId, ) -> Result<()> { - self.read - .ready() - .validate_origin(binding, GrRole::Ffn(layer.get()))?; - self.read - .ready() - .identity() - .validate(token, position, layer)?; + self.read.ready().validate_origin(binding, GrRole::Ffn(layer.get()))?; + self.read.ready().identity().validate(token, position, layer)?; self.route.validate_binding(binding)?; self.route.validate_for(token, position, layer)?; if !self.weights.matches(binding, layer.get()) { @@ -39,14 +34,8 @@ impl MoeExpertStage { ) -> Result { let read = GrStage::detach_ffn(binding, read, txn)?; let ids = std::array::from_fn(|i| route.experts()[i].get()); - let weights = binding - .moe_expert_weights(layer.get(), ids) - .map_err(binding_error)?; - let row = PreparedMoeRow { - read, - route, - weights, - }; + let weights = binding.moe_expert_weights(layer.get(), ids).map_err(binding_error)?; + let row = PreparedMoeRow { read, route, weights }; row.validate(&binding.identity(), txn.token(), txn.position(), layer)?; Ok(row) } @@ -62,9 +51,7 @@ impl MoeExpertStage { ) -> Result { GrStage::validate_detached_ffn(binding, layer, &read, txn)?; let ids = std::array::from_fn(|i| route.experts()[i].get()); - let weights = binding - .moe_expert_weights(layer.get(), ids) - .map_err(binding_error)?; + let weights = binding.moe_expert_weights(layer.get(), ids).map_err(binding_error)?; let row = PreparedMoeRow { read, route, weights }; row.validate(&binding.identity(), txn.token(), txn.position(), layer)?; Ok(row) @@ -78,9 +65,8 @@ impl MoeExpertStage { cancelled: &mut impl FnMut() -> bool, ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Moe, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) { return Err(Error::InvalidDimension); } @@ -89,29 +75,58 @@ impl MoeExpertStage { } if use_direct_packets(cache) { return chunk.batch_outputs_ffn(layer, rows, |actual, context| { - execute_bound(context, binding, rows, cache, cancelled, Some(actual), - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] None) + execute_bound( + context, + binding, + rows, + cache, + cancelled, + Some(actual), + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + ) }); } - chunk.batch_outputs(|context| execute_bound(context, binding, rows, cache, cancelled, None, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] None)) + chunk.batch_outputs(|context| { + execute_bound( + context, + binding, + rows, + cache, + cancelled, + None, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + ) + }) } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn execute_chunk_native_prompt<'ctx>( - binding:&ModelBinding, layer:LayerId, rows:&[ChunkFfnRow], - chunk:&mut QwenChunkTxn<'_, 'ctx>, cache:&mut MoeWeightCache<'ctx>, - cancelled:&mut impl FnMut()->bool, - products:&mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, - dense:&super::super::super::dense_weight_cache::DenseWeightCache<'_>, - )->Result> { - if rows.len()!=chunk.micro_len()? || !(1..=64).contains(&rows.len()) - || !use_direct_packets(cache) {return Err(Error::IdentityMismatch);} - for(index,row)in rows.iter().enumerate(){ - chunk.validate_ffn_row(chunk.micro_row_index(index)?,layer,row)?; + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + products: &mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, + dense: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + ) -> Result> { + if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) || !use_direct_packets(cache) { + return Err(Error::IdentityMismatch); } - chunk.batch_outputs_ffn(layer,rows,|actual,context|{ - execute_bound(context,binding,rows,cache,cancelled,Some(actual), - Some(prompt_finish::NativePromptFinish{products,dense})) + for (index, row) in rows.iter().enumerate() { + chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?; + } + chunk.batch_outputs_ffn(layer, rows, |actual, context| { + execute_bound( + context, + binding, + rows, + cache, + cancelled, + Some(actual), + Some(prompt_finish::NativePromptFinish { products, dense }), + ) }) } } @@ -122,9 +137,7 @@ pub(super) fn grouped_pairs(ids: &[[u32; K]]) -> Result>> { return Err(Error::InvalidDimension); } let mut groups = Vec::new(); - groups - .try_reserve_exact(512) - .map_err(|_| Error::InputAllocation)?; + groups.try_reserve_exact(512).map_err(|_| Error::InputAllocation)?; groups.resize_with(512, Vec::new); for (row, values) in ids.iter().enumerate() { let mut seen = [false; 512]; @@ -134,9 +147,7 @@ pub(super) fn grouped_pairs(ids: &[[u32; K]]) -> Result>> { return Err(Error::InvalidExpert); } seen[expert] = true; - groups[expert] - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + groups[expert].try_reserve(1).map_err(|_| Error::InputAllocation)?; groups[expert].push(Pair { row, slot }); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs index 4c140cfc..7af2394b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/ordered_down_refusal_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn ordered_down_refusal( context: &Context<'_>, kind: MoeMatrixKind, @@ -44,9 +43,9 @@ pub(super) fn ordered_down_refusal( pub(super) fn use_direct_packets(cache: &MoeWeightCache<'_>) -> bool { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] { - if crate::qwen_forward::oracle_capture::enabled() - || crate::qwen_forward::layer0_mmq_observation::enabled() - { return false; } + if crate::qwen_forward::oracle_capture::enabled() || crate::qwen_forward::layer0_mmq_observation::enabled() { + return false; + } direct_gpu::policy(cache.uses_direct_native_down_packets()) } #[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] @@ -60,12 +59,17 @@ pub(super) fn validate_packet_pairs( origins: &[Rc], packets: &[ActualSlotPacket<'_>], ) -> Result<()> { - if !(1..=64).contains(&pairs.len()) || packets.len() != rows.len() + if !(1..=64).contains(&pairs.len()) + || packets.len() != rows.len() || origins.len() != rows.len() || pairs.windows(2).any(|p| p[0].row >= p[1].row) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } for pair in pairs { - if pair.row >= rows.len() || pair.slot >= K { return Err(Error::IdentityMismatch); } + if pair.row >= rows.len() || pair.slot >= K { + return Err(Error::IdentityMismatch); + } let row = rows[pair.row].row(); let identity = row.route.identity(); actual.validate_ffn_row(actual.micro_row_index(pair.row)?, identity.layer(), &rows[pair.row])?; @@ -76,14 +80,20 @@ pub(super) fn validate_packet_pairs( } #[allow(clippy::too_many_arguments)] pub(super) fn execute_direct_packets<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - groups: &[Vec], cache: &mut MoeWeightCache<'ctx>, - prepared: &[RoutedGateUpQ8<'_>], activations: &[TransportBuffer<'ctx>], - scope: &DownScope<'ctx>, origins: &[Rc], + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + groups: &[Vec], + cache: &mut MoeWeightCache<'ctx>, + prepared: &[RoutedGateUpQ8<'_>], + activations: &[TransportBuffer<'ctx>], + scope: &DownScope<'ctx>, + origins: &[Rc], cancelled: &mut impl FnMut() -> bool, actual: &QwenChunkTxn<'_, 'ctx>, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - mut native:Option>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< + prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, ) -> Result> { let mut packets = Vec::new(); packets.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; @@ -91,43 +101,82 @@ pub(super) fn execute_direct_packets<'ctx>( for (index, row) in rows.iter().enumerate() { let identity = row.row().route.identity(); row.row().validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; - packets.push(ActualSlotPacket { origin: Rc::clone(&origins[index]), - packet: super::super::moe_down::ResidentPackedDown::new(scope)? }); + packets.push(ActualSlotPacket { + origin: Rc::clone(&origins[index]), + packet: super::super::moe_down::ResidentPackedDown::new(scope)?, + }); } let adaptive = uses_adaptive(cache); #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if adaptive { - adaptive_packets::project_adaptive_packets(context, binding, rows, groups, cache, - prepared, scope, origins, &mut packets, cancelled, actual)?; + adaptive_packets::project_adaptive_packets( + context, + binding, + rows, + groups, + cache, + prepared, + scope, + origins, + &mut packets, + cancelled, + actual, + )?; } for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive) { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - project_group_source_fenced(context, binding, rows, pairs, cache, prepared, scope, - origins, &mut packets, cancelled, actual)?; + project_group_source_fenced( + context, + binding, + rows, + pairs, + cache, + prepared, + scope, + origins, + &mut packets, + cancelled, + actual, + )?; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] - project_group_direct(context, binding, rows, pairs, cache, prepared, scope, - origins, &mut packets, cancelled, actual)?; + project_group_direct( + context, + binding, + rows, + pairs, + cache, + prepared, + scope, + origins, + &mut packets, + cancelled, + actual, + )?; } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if let Some(finish)=native.as_mut(){ - let layer=rows[0].row().route.identity().layer(); - let mut refs=Vec::new(); - refs.try_reserve_exact(rows.len()).map_err(|_|Error::InputAllocation)?; - for(index,packet)in packets.iter().enumerate(){ - actual.validate_ffn_row(actual.micro_row_index(index)?,layer,&rows[index])?; - packet.validate(&origins[index],binding,rows[index].row().route.identity())?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(finish) = native.as_mut() { + let layer = rows[0].row().route.identity().layer(); + let mut refs = Vec::new(); + refs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; + for (index, packet) in packets.iter().enumerate() { + actual.validate_ffn_row(actual.micro_row_index(index)?, layer, &rows[index])?; + packet.validate(&origins[index], binding, rows[index].row().route.identity())?; refs.push(&packet.packet); } - return prompt_finish::finish(context,binding,layer,rows,actual,scope, - &refs,cache,finish,cancelled); + return prompt_finish::finish( + context, binding, layer, rows, actual, scope, &refs, cache, finish, cancelled, + ); } let mut outputs = Vec::new(); outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in rows.iter().enumerate() { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - actual.validate_ffn_row(actual.micro_row_index(index)?, - row.row().route.identity().layer(), row)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + actual.validate_ffn_row(actual.micro_row_index(index)?, row.row().route.identity().layer(), row)?; let row = row.row(); let actual = &packets[index]; actual.validate(&origins[index], binding, row.route.identity())?; @@ -135,13 +184,33 @@ pub(super) fn execute_direct_packets<'ctx>( #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] actual.packet.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?; let values = if use_shared_tail(cache) { - actual.packet.with_completed(scope, |packet| finish_shared_queued(context, binding, - row, activations[index].buffer()?, cache, scope, &origins[index], packet))? + actual.packet.with_completed(scope, |packet| { + finish_shared_queued( + context, + binding, + row, + activations[index].buffer()?, + cache, + scope, + &origins[index], + packet, + ) + })? } else { - finish_shared_with(context, binding, row, activations[index].buffer()?, cache, - scope, &origins[index], |weights, scaled| actual.packet.combine(scope, weights, scaled))? + finish_shared_with( + context, + binding, + row, + activations[index].buffer()?, + cache, + scope, + &origins[index], + |weights, scaled| actual.packet.combine(scope, weights, scaled), + )? }; - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } outputs.push(ExpertReady::from_completed(binding.identity(), row.route.identity(), values)?); } Ok(outputs) @@ -150,7 +219,9 @@ pub(super) fn execute_direct_packets<'ctx>( let mut cleanup = Ok(()); for actual in packets { let next = actual.packet.close(); - if cleanup.is_ok() { cleanup = next; } + if cleanup.is_ok() { + cleanup = next; + } } operation.and_then(|values| cleanup.map(|()| values)) } @@ -167,29 +238,18 @@ pub(super) fn finish_shared<'ctx>( ) -> Result> { if use_shared_tail(cache) { return packed.with_completed(scope, |packet| { - finish_shared_queued( - context, binding, row, activation, cache, scope, origin, packet, - ) + finish_shared_queued(context, binding, row, activation, cache, scope, origin, packet) }); } - finish_shared_with( - context, - binding, - row, - activation, - cache, - scope, - origin, - |weights, scaled| packed.combine(scope, weights, scaled), - ) + finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| { + packed.combine(scope, weights, scaled) + }) } // Existing capture providers require their original intermediate readbacks. // Their reference path is retained rather than emitting incomplete observations. pub(super) fn use_shared_tail(cache: &MoeWeightCache<'_>) -> bool { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if crate::qwen_forward::oracle_capture::enabled() - || crate::qwen_forward::layer0_mmq_observation::enabled() - { + if crate::qwen_forward::oracle_capture::enabled() || crate::qwen_forward::layer0_mmq_observation::enabled() { return false; } cache.has_target_shared_tail() @@ -206,32 +266,14 @@ pub(super) fn finish_shared_queued( packet: &DeviceBuffer<'_>, ) -> Result> { let identity = row.route.identity(); - row.validate( - &binding.identity(), - identity.token(), - identity.position(), - identity.layer(), - )?; + row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; if !origin.binding.matches(&binding.identity()) || origin.identity != identity { return Err(Error::IdentityMismatch); } let route = std::array::from_fn(|i| row.route.weights()[i].get()); - let result = cache.compose_target_shared_tail( - binding, - context, - &row.weights, - identity, - activation, - packet, - &route, - ); + let result = cache.compose_target_shared_tail(binding, context, &row.weights, identity, activation, packet, &route); scope.record(&result); let values = result?; - row.validate( - &binding.identity(), - identity.token(), - identity.position(), - identity.layer(), - )?; + row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?; Ok(values) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs index c0c4e456..616febf4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_direct_fn.rs @@ -23,9 +23,7 @@ pub(super) fn project_group_direct<'ctx>( let selection = MoeExpertSelection::Routed { slot: first.slot }; // All three native matrix descriptors must match before a cache mutation. for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let original = binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?; + let original = binding.moe_weight_descriptor(weights, selection, role).map_err(binding_error)?; for pair in pairs { let other = binding .moe_weight_descriptor( @@ -44,15 +42,11 @@ pub(super) fn project_group_direct<'ctx>( let mut hidden = None; let operation = (|| { let mut refs = Vec::new(); - refs.try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + refs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { refs.push(&prepared[pair.row]); } - for (role, output) in [ - (MoeMatrixRole::Gate, &mut gate), - (MoeMatrixRole::Up, &mut up), - ] { + for (role, output) in [(MoeMatrixRole::Gate, &mut gate), (MoeMatrixRole::Up, &mut up)] { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -67,12 +61,9 @@ pub(super) fn project_group_direct<'ctx>( let grouped = output.as_mut().ok_or(Error::IdentityMismatch)?; let matrix = cache.matrix(binding, weights, selection, role)?; match matrix { - CachedMoeMatrix::Raw(raw) => context.project_routed_gate_up_columns( - raw, - &refs, - grouped.buffer_mut()?, - format, - ), + CachedMoeMatrix::Raw(raw) => { + context.project_routed_gate_up_columns(raw, &refs, grouped.buffer_mut()?, format) + } CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); @@ -93,32 +84,21 @@ pub(super) fn project_group_direct<'ctx>( .moe_swiglu_columns( gate.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, up.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, - hidden - .as_mut() - .ok_or(Error::IdentityMismatch)? - .buffer_mut()?, + hidden.as_mut().ok_or(Error::IdentityMismatch)?.buffer_mut()?, pairs.len(), ) .map_err(driver_error)?; - let hidden_values = download_f32( - hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, - pairs.len() * FF, - )?; - let kind = weights - .kind(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; + let hidden_values = download_f32(hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, pairs.len() * FF)?; + let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; let format = match kind { MoeMatrixKind::RoutedIq4Nl => RoutedFormat::IQ4_NL, MoeMatrixKind::Q2_0 => RoutedFormat::Q2_0, _ => return Err(Error::Unsupported(Stage::MoeExpert)), }; let mut selections = Vec::new(); - selections - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + selections.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { - packets[pair.row].validate(&origins[pair.row], binding, - rows[pair.row].row().route.identity())?; + packets[pair.row].validate(&origins[pair.row], binding, rows[pair.row].row().route.identity())?; selections.push(DownSelection::Routed(pair.slot)); } if cancelled() { @@ -137,11 +117,7 @@ pub(super) fn project_group_direct<'ctx>( if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); } - owner.native_down_columns( - input, - u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, - out, - ) + owner.native_down_columns(input, u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, out) } }; match result { @@ -151,15 +127,9 @@ pub(super) fn project_group_direct<'ctx>( // projection ran and these private outputs are discarded. // Replay only this numerical refusal in original row order // using the exact finite hidden values already read back. - Err(DriverError::InvalidQ8Activation) => ordered_down_refusal( - context, - kind, - matrix, - &hidden_values, - &selections, - scope, - cancel, - ), + Err(DriverError::InvalidQ8Activation) => { + ordered_down_refusal(context, kind, matrix, &hidden_values, &selections, scope, cancel) + } Err(error) => Err(driver_error(error)), } }, @@ -176,23 +146,28 @@ pub(super) fn project_group_direct<'ctx>( next += 1; } } - if next != pairs.len() { return Err(Error::IdentityMismatch); } + if next != pairs.len() { + return Err(Error::IdentityMismatch); + } super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut targets, |copies| { - context.copy_routed_down_columns_to_slots(source, pairs.len(), copies) - .map_err(driver_error)?; + context.copy_routed_down_columns_to_slots(source, pairs.len(), copies).map_err(driver_error)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] direct_gpu::copy_completed(); - if cancel() { return Err(Error::Unsupported(Stage::Executor)); } + if cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } // Actual immutable row/binding/selection remains current // after completion, before any coverage is published. for pair in pairs { - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), &rows[pair.row])?; + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; let row = rows[pair.row].row(); let id = row.route.identity(); row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) - || origins[pair.row].identity != id { + if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { return Err(Error::IdentityMismatch); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs index 9c48c043..314a3469 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_fn.rs @@ -21,9 +21,7 @@ pub(super) fn project_group<'ctx>( let selection = MoeExpertSelection::Routed { slot: first.slot }; // All three native matrix descriptors must match before a cache mutation. for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let original = binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?; + let original = binding.moe_weight_descriptor(weights, selection, role).map_err(binding_error)?; for pair in pairs { let other = binding .moe_weight_descriptor( @@ -42,15 +40,11 @@ pub(super) fn project_group<'ctx>( let mut hidden = None; let operation = (|| { let mut refs = Vec::new(); - refs.try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + refs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { refs.push(&prepared[pair.row]); } - for (role, output) in [ - (MoeMatrixRole::Gate, &mut gate), - (MoeMatrixRole::Up, &mut up), - ] { + for (role, output) in [(MoeMatrixRole::Gate, &mut gate), (MoeMatrixRole::Up, &mut up)] { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } @@ -71,12 +65,9 @@ pub(super) fn project_group<'ctx>( // this complete projection. Gate and Up remain separate calls. scope.with_workspace(|workspace| { match matrix { - CachedMoeMatrix::Raw(raw) => workspace.project_gate_up_columns( - raw, - &refs, - grouped.buffer_mut()?, - format, - ), + CachedMoeMatrix::Raw(raw) => { + workspace.project_gate_up_columns(raw, &refs, grouped.buffer_mut()?, format) + } CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); @@ -87,29 +78,34 @@ pub(super) fn project_group<'ctx>( .map_err(driver_error) })?; } else { - match matrix { - CachedMoeMatrix::Raw(raw) => context.project_routed_gate_up_columns( - raw, - &refs, - grouped.buffer_mut()?, - format, - ), - CachedMoeMatrix::Dual(actual, owner) => { - if dual_routed_format(actual) != format { - return Err(Error::IdentityMismatch); + match matrix { + CachedMoeMatrix::Raw(raw) => { + context.project_routed_gate_up_columns(raw, &refs, grouped.buffer_mut()?, format) + } + CachedMoeMatrix::Dual(actual, owner) => { + if dual_routed_format(actual) != format { + return Err(Error::IdentityMismatch); + } + owner.native_gate_up_columns(&refs, grouped.buffer_mut()?) } - owner.native_gate_up_columns(&refs, grouped.buffer_mut()?) } - } - .map_err(driver_error)?; + .map_err(driver_error)?; } // Preserve the original finite Gate then Up stage boundary. No // per-column transfer or ownership reconstruction occurs here. if uses_adaptive(cache) { - scope.finite_stage(grouped.buffer()?, if role == MoeMatrixRole::Gate { - leleka_cuda_driver::RoutedFiniteStage::Gate - } else { leleka_cuda_driver::RoutedFiniteStage::Up }, pairs.len())?; - } else { download_f32(grouped.buffer()?, pairs.len() * FF)?; } + scope.finite_stage( + grouped.buffer()?, + if role == MoeMatrixRole::Gate { + leleka_cuda_driver::RoutedFiniteStage::Gate + } else { + leleka_cuda_driver::RoutedFiniteStage::Up + }, + pairs.len(), + )?; + } else { + download_f32(grouped.buffer()?, pairs.len() * FF)?; + } } if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -119,30 +115,28 @@ pub(super) fn project_group<'ctx>( .moe_swiglu_columns( gate.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, up.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, - hidden - .as_mut() - .ok_or(Error::IdentityMismatch)? - .buffer_mut()?, + hidden.as_mut().ok_or(Error::IdentityMismatch)?.buffer_mut()?, pairs.len(), ) .map_err(driver_error)?; let hidden_values = if uses_adaptive(cache) { - scope.finite_stage(hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, - leleka_cuda_driver::RoutedFiniteStage::Hidden, pairs.len())?; + scope.finite_stage( + hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, + leleka_cuda_driver::RoutedFiniteStage::Hidden, + pairs.len(), + )?; None - } else { Some(download_f32(hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, pairs.len() * FF)?) }; - let kind = weights - .kind(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; + } else { + Some(download_f32(hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, pairs.len() * FF)?) + }; + let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; let format = match kind { MoeMatrixKind::RoutedIq4Nl => RoutedFormat::IQ4_NL, MoeMatrixKind::Q2_0 => RoutedFormat::Q2_0, _ => return Err(Error::Unsupported(Stage::MoeExpert)), }; let mut selections = Vec::new(); - selections - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + selections.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { if down[pair.row][pair.slot].is_some() { return Err(Error::IdentityMismatch); @@ -161,9 +155,9 @@ pub(super) fn project_group<'ctx>( if adaptive_workspace { return scope.with_workspace(|workspace| { let result = match matrix { - CachedMoeMatrix::Raw(raw) => workspace.project_down_columns( - raw, input, out, pairs.len(), format, - ), + CachedMoeMatrix::Raw(raw) => { + workspace.project_down_columns(raw, input, out, pairs.len(), format) + } CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); @@ -199,11 +193,7 @@ pub(super) fn project_group<'ctx>( if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); } - owner.native_down_columns( - input, - u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, - out, - ) + owner.native_down_columns(input, u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, out) } }; match result { @@ -219,7 +209,7 @@ pub(super) fn project_group<'ctx>( None => download_f32(input, pairs.len() * FF)?, }; ordered_down_refusal(context, kind, matrix, &actual_values, &selections, scope, cancel) - }, + } Err(error) => Err(driver_error(error)), } }, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs index ef7700c5..c6478109 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_consumers_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(clippy::too_many_arguments)] pub(super) fn project_group_source_consumers<'ctx>( @@ -40,18 +39,14 @@ pub(super) fn project_group_source_consumers<'ctx>( let mut hidden = None; let operation = (|| { let mut refs = Vec::new(); - refs.try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + refs.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { refs.push(&prepared[pair.row]); } if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let format = match weights - .kind(selection, MoeMatrixRole::Gate) - .map_err(binding_error)? - { + let format = match weights.kind(selection, MoeMatrixRole::Gate).map_err(binding_error)? { MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS, MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S, MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S, @@ -66,11 +61,7 @@ pub(super) fn project_group_source_consumers<'ctx>( let mut columns = workspace.begin_columns(&refs); cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Gate, |matrix, _, _| { match matrix { - CachedMoeMatrix::Raw(raw) => columns.project_gate_up( - raw, - grouped.buffer_mut()?, - format, - ), + CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format), CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); @@ -80,20 +71,13 @@ pub(super) fn project_group_source_consumers<'ctx>( } .map_err(driver_error)?; // Same full Gate completion precedes every Up operation. - scope.finite_stage( - grouped.buffer()?, - leleka_cuda_driver::RoutedFiniteStage::Gate, - pairs.len(), - )?; + scope.finite_stage(grouped.buffer()?, leleka_cuda_driver::RoutedFiniteStage::Gate, pairs.len())?; Ok(()) })?; if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - let format = match weights - .kind(selection, MoeMatrixRole::Up) - .map_err(binding_error)? - { + let format = match weights.kind(selection, MoeMatrixRole::Up).map_err(binding_error)? { MoeMatrixKind::Iq3Xxs => RoutedFormat::IQ3_XXS, MoeMatrixKind::Iq2S => RoutedFormat::IQ2_S, MoeMatrixKind::Iq3S => RoutedFormat::IQ3_S, @@ -104,11 +88,7 @@ pub(super) fn project_group_source_consumers<'ctx>( let grouped = up.as_mut().ok_or(Error::IdentityMismatch)?; cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Up, |matrix, _, _| { match matrix { - CachedMoeMatrix::Raw(raw) => columns.project_gate_up( - raw, - grouped.buffer_mut()?, - format, - ), + CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format), CachedMoeMatrix::Dual(actual, owner) => { if dual_routed_format(actual) != format { return Err(Error::IdentityMismatch); @@ -118,11 +98,7 @@ pub(super) fn project_group_source_consumers<'ctx>( } .map_err(driver_error)?; // Same full Up completion precedes SwiGLU and Down reuse. - scope.finite_stage( - grouped.buffer()?, - leleka_cuda_driver::RoutedFiniteStage::Up, - pairs.len(), - )?; + scope.finite_stage(grouped.buffer()?, leleka_cuda_driver::RoutedFiniteStage::Up, pairs.len())?; Ok(()) })?; Ok(()) @@ -135,10 +111,7 @@ pub(super) fn project_group_source_consumers<'ctx>( .moe_swiglu_columns( gate.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, up.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?, - hidden - .as_mut() - .ok_or(Error::IdentityMismatch)? - .buffer_mut()?, + hidden.as_mut().ok_or(Error::IdentityMismatch)?.buffer_mut()?, pairs.len(), ) .map_err(driver_error)?; @@ -147,145 +120,111 @@ pub(super) fn project_group_source_consumers<'ctx>( leleka_cuda_driver::RoutedFiniteStage::Hidden, pairs.len(), )?; - let kind = weights - .kind(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; + let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; let format = match kind { MoeMatrixKind::RoutedIq4Nl => RoutedFormat::IQ4_NL, MoeMatrixKind::Q2_0 => RoutedFormat::Q2_0, _ => return Err(Error::Unsupported(Stage::MoeExpert)), }; let mut selections = Vec::new(); - selections - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + selections.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { - packets[pair.row].validate( - &origins[pair.row], - binding, - rows[pair.row].row().route.identity(), - )?; + packets[pair.row].validate(&origins[pair.row], binding, rows[pair.row].row().route.identity())?; selections.push(DownSelection::Routed(pair.slot)); } if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } scope.with_workspace(|workspace| { - cache.with_matrix_routed_source( - binding, - source, - 0, - MoeMatrixRole::Down, - |matrix, health, source| { - scope.project_columns_direct( - &selections, - |out, cancel| { - let input = hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?; - let result = match matrix { - CachedMoeMatrix::Raw(raw) => workspace.project_down_columns( - raw, + cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Down, |matrix, health, source| { + scope.project_columns_direct( + &selections, + |out, cancel| { + let input = hidden.as_ref().ok_or(Error::IdentityMismatch)?.buffer()?; + let result = match matrix { + CachedMoeMatrix::Raw(raw) => { + workspace.project_down_columns(raw, input, out, pairs.len(), format) + } + CachedMoeMatrix::Dual(actual, owner) => { + if dual_routed_format(actual) != format { + return Err(Error::IdentityMismatch); + } + owner.native_down_columns_in( + workspace, input, + u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, out, - pairs.len(), - format, - ), - CachedMoeMatrix::Dual(actual, owner) => { - if dual_routed_format(actual) != format { - return Err(Error::IdentityMismatch); - } - owner.native_down_columns_in( - workspace, - input, - u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?, - out, - ) - } - }; - match result { - Ok(()) => Ok(()), - // A later column's quantizer refusal must not overtake an - // earlier column's original Down NonFinite. No grouped - // projection ran and these private outputs are discarded. - // Only this numerical refusal needs host values. The - // unchanged full Hidden download observes the same alive - // allocation, then original ascending-row arbitration runs. - Err(DriverError::InvalidQ8Activation) => { - let hidden_values = download_f32(input, pairs.len() * FF)?; - ordered_down_refusal(context, kind, matrix, &hidden_values, - &selections, scope, cancel) - }, - Err(error) => Err(driver_error(error)), + ) } - }, - |down_source, cancel| { - // Private grouping has one pair per actual row, in ascending - // row order. Validate all row origins before mutable loans. - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let mut targets = Vec::new(); - targets - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; - let mut next = 0; - for (row, packet) in packets.iter_mut().enumerate() { - if next < pairs.len() && pairs[next].row == row { - targets.push((&mut packet.packet, pairs[next].slot)); - next += 1; + }; + match result { + Ok(()) => Ok(()), + // A later column's quantizer refusal must not overtake an + // earlier column's original Down NonFinite. No grouped + // projection ran and these private outputs are discarded. + // Only this numerical refusal needs host values. The + // unchanged full Hidden download observes the same alive + // allocation, then original ascending-row arbitration runs. + Err(DriverError::InvalidQ8Activation) => { + let hidden_values = download_f32(input, pairs.len() * FF)?; + ordered_down_refusal(context, kind, matrix, &hidden_values, &selections, scope, cancel) + } + Err(error) => Err(driver_error(error)), + } + }, + |down_source, cancel| { + // Private grouping has one pair per actual row, in ascending + // row order. Validate all row origins before mutable loans. + validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + let mut targets = Vec::new(); + targets.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + let mut next = 0; + for (row, packet) in packets.iter_mut().enumerate() { + if next < pairs.len() && pairs[next].row == row { + targets.push((&mut packet.packet, pairs[next].slot)); + next += 1; + } + } + if next != pairs.len() { + return Err(Error::IdentityMismatch); + } + super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut targets, |copies| { + context + .copy_routed_down_columns_to_slots(down_source, pairs.len(), copies) + .map_err(driver_error)?; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + direct_gpu::copy_completed(); + if cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + // End the actual opened-FD scope after the final private + // consumer, before any packet coverage or group acceptance. + // Failure discards all copied private packets. + source.finish().map_err(binding_error)?; + health.validate(binding, context)?; + // Actual immutable row/binding/selection remains current + // after successful source finish, before coverage publish. + for pair in pairs { + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; + let row = rows[pair.row].row(); + let id = row.route.identity(); + row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; + if !origins[pair.row].binding.matches(&binding.identity()) + || origins[pair.row].identity != id + { + return Err(Error::IdentityMismatch); } } - if next != pairs.len() { - return Err(Error::IdentityMismatch); - } - super::super::moe_down::ResidentPackedDown::copy_group_with( - scope, - &mut targets, - |copies| { - context - .copy_routed_down_columns_to_slots( - down_source, - pairs.len(), - copies, - ) - .map_err(driver_error)?; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - direct_gpu::copy_completed(); - if cancel() { - return Err(Error::Unsupported(Stage::Executor)); - } - // End the actual opened-FD scope after the final private - // consumer, before any packet coverage or group acceptance. - // Failure discards all copied private packets. - source.finish().map_err(binding_error)?; - health.validate(binding, context)?; - // Actual immutable row/binding/selection remains current - // after successful source finish, before coverage publish. - for pair in pairs { - actual.validate_ffn_row( - actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), - &rows[pair.row], - )?; - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate( - &binding.identity(), - id.token(), - id.position(), - id.layer(), - )?; - if !origins[pair.row].binding.matches(&binding.identity()) - || origins[pair.row].identity != id - { - return Err(Error::IdentityMismatch); - } - } - Ok(()) - }, - ) - }, - cancelled, - ) - }, - ) + Ok(()) + }) + }, + cancelled, + ) + }) })?; Ok(()) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs index 03d28c36..8d6bd48a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_chunk/project_group_source_fenced_fn.rs @@ -24,9 +24,7 @@ pub(super) fn project_group_source_fenced<'ctx>( return Err(Error::IdentityMismatch); } let mut members = Vec::new(); - members - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { members.push((&rows[pair.row].row().weights, pair.slot)); } @@ -35,8 +33,7 @@ pub(super) fn project_group_source_fenced<'ctx>( // primary failures while still attempting the mandatory source finish. let operation = binding.with_moe_routed_source(&members, binding_error, |source| { project_group_source_consumers( - context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, - actual, source, + context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, source, ) }); // Recheck the real cache after the matrix loan and source loan have ended. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs index cce5565a..532e4d40 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_down_direct_gpu.rs @@ -1,9 +1,16 @@ //! ONE loaded actual-row transport proof. No source admission, ModelBinding, //! session advancement, standalone Load or full-model qualification is minted. use super::*; -use crate::qwen_forward::{executor::QwenForward,session::QwenSession,dense_weight_cache::DenseWeightCache, - contract::{Dimension,TokenId},input::InputStage,kar_ple_cache::KarPleCache, - gdn::GdnStage,moe_route::MoeRouteStage}; +use crate::qwen_forward::{ + contract::{Dimension, TokenId}, + dense_weight_cache::DenseWeightCache, + executor::QwenForward, + gdn::GdnStage, + input::InputStage, + kar_ple_cache::KarPleCache, + moe_route::MoeRouteStage, + session::QwenSession, +}; use std::cell::{Cell, RefCell}; thread_local! { static OLD: Cell = const { Cell::new(false) }; @@ -11,13 +18,21 @@ thread_local! { static CANCELLED_ON_COPY: Cell = const { Cell::new(false) }; static PACKETS: RefCell>>> = const { RefCell::new(None) }; } -pub(super) fn policy(actual: bool) -> bool { actual && !OLD.get() } -pub(super) fn copy_completed() { COPIED.set(true); } +pub(super) fn policy(actual: bool) -> bool { + actual && !OLD.get() +} +pub(super) fn copy_completed() { + COPIED.set(true); +} pub(super) fn observe_packet(packet: &DeviceBuffer<'_>) -> Result<()> { PACKETS.with(|slot| { let mut slot = slot.borrow_mut(); - let Some(packets) = slot.as_mut() else { return Ok(()); }; - if packets.len() >= 3 { return Err(Error::InvalidDimension); } + let Some(packets) = slot.as_mut() else { + return Ok(()); + }; + if packets.len() >= 3 { + return Err(Error::InvalidDimension); + } packets.push(download_f32(packet, K * N)?); Ok(()) }) @@ -28,10 +43,16 @@ impl Observation { let mut rows = Vec::new(); rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; PACKETS.with(|slot| -> Result<()> { - if slot.borrow().is_some() { return Err(Error::IdentityMismatch); } - *slot.borrow_mut() = Some(rows); Ok(()) + if slot.borrow().is_some() { + return Err(Error::IdentityMismatch); + } + *slot.borrow_mut() = Some(rows); + Ok(()) })?; - OLD.set(old); COPIED.set(false); CANCELLED_ON_COPY.set(false); Ok(Self) + OLD.set(old); + COPIED.set(false); + CANCELLED_ON_COPY.set(false); + Ok(Self) } fn take(&self) -> Result>> { PACKETS.with(|slot| slot.borrow_mut().take().ok_or(Error::IdentityMismatch)) @@ -39,13 +60,20 @@ impl Observation { } impl Drop for Observation { fn drop(&mut self) { - OLD.set(false); COPIED.set(false); - PACKETS.with(|slot| { slot.borrow_mut().take(); }); + OLD.set(false); + COPIED.set(false); + PACKETS.with(|slot| { + slot.borrow_mut().take(); + }); } } pub(crate) struct DirectDownReport { - differences: usize, words: usize, cancelled_after_copy: bool, - allocated_unchanged: bool, reset_exact: bool, guards: bool, + differences: usize, + words: usize, + cancelled_after_copy: bool, + allocated_unchanged: bool, + reset_exact: bool, + guards: bool, } impl DirectDownReport { /// The loaded caller retains this report, then closes every cache/session @@ -53,84 +81,113 @@ impl DirectDownReport { pub(crate) fn assert_after_teardown(self) { assert_eq!(self.differences, 0); assert!(self.cancelled_after_copy && self.allocated_unchanged && self.reset_exact && self.guards); - eprintln!("direct native Down PASS exact_words={} original_copy_first=true real_rows=true packet_mapping=true signedzero=true postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false", self.words); + eprintln!( + "direct native Down PASS exact_words={} original_copy_first=true real_rows=true packet_mapping=true signedzero=true postcopy_cancel=true cleanup_checked=true full_model=false speed_claim=false", + self.words + ); } } fn compare(a: &[Box<[f32]>], b: &[Box<[f32]>]) -> Result<(usize, usize)> { - if a.len() != b.len() { return Err(Error::IdentityMismatch); } + if a.len() != b.len() { + return Err(Error::IdentityMismatch); + } let mut differences = 0; let mut words = 0; - for (a,b) in a.iter().zip(b) { - if a.len() != b.len() { return Err(Error::InvalidDimension); } - validate_values(a,a.len())?; validate_values(b,b.len())?; - differences += a.iter().zip(b.iter()).filter(|(a,b)| a.to_bits()!=b.to_bits()).count(); + for (a, b) in a.iter().zip(b) { + if a.len() != b.len() { + return Err(Error::InvalidDimension); + } + validate_values(a, a.len())?; + validate_values(b, b.len())?; + differences += a.iter().zip(b.iter()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); words += a.len(); } - Ok((differences,words)) + Ok((differences, words)) } type ObservedArm = (Vec, Vec>); #[allow(clippy::too_many_arguments)] -fn arm<'ctx>(binding: &ModelBinding, context: &Rc>, - session: &mut QwenSession<'ctx>,kar: &mut KarPleCache<'_>, - cache: &mut MoeWeightCache<'ctx>,dense:&DenseWeightCache<'ctx>,old:bool, - cancel_after_copy:bool) -> Result { - let observation=Observation::begin(old)?; - let layer=LayerId::new(0,Dimension::new(48)?)?; - let vocab=Dimension::new(248320)?; - let tokens=[TokenId::new(0,vocab)?,TokenId::new(1,vocab)?,TokenId::new(0,vocab)?]; - cache.reserve_mmq_transient(binding,context, - 3*(K*N*4+10240+2884+3*FF*4+N*4+720)+DEVICE_PEAK)?; - let mut chunk=QwenChunkTxn::begin(session,binding,&tokens,None,512*1024*1024)?; +fn arm<'ctx>( + binding: &ModelBinding, + context: &Rc>, + session: &mut QwenSession<'ctx>, + kar: &mut KarPleCache<'_>, + cache: &mut MoeWeightCache<'ctx>, + dense: &DenseWeightCache<'ctx>, + old: bool, + cancel_after_copy: bool, +) -> Result { + let observation = Observation::begin(old)?; + let layer = LayerId::new(0, Dimension::new(48)?)?; + let vocab = Dimension::new(248320)?; + let tokens = [TokenId::new(0, vocab)?, TokenId::new(1, vocab)?, TokenId::new(0, vocab)?]; + cache.reserve_mmq_transient( + binding, + context, + 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK, + )?; + let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?; for index in 0..3 { - let (token,position)=chunk.row_ids(index)?; - chunk.input(index,|txn|InputStage::consume_kar(binding,kar,token,position,txn))?; + let (token, position) = chunk.row_ids(index)?; + chunk.input(index, |txn| InputStage::consume_kar(binding, kar, token, position, txn))?; } - let mut reads=Vec::new(); reads.try_reserve_exact(3).map_err(|_|Error::InputAllocation)?; + let mut reads = Vec::new(); + reads.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; for index in 0..3 { - reads.push(chunk.read_attention_column(index,layer,|txn| { - let read=GrStage::apply(binding,layer,txn,Some(dense))?; - GrStage::detach_attention(binding,read,txn) + reads.push(chunk.read_attention_column(index, layer, |txn| { + let read = GrStage::apply(binding, layer, txn, Some(dense))?; + GrStage::detach_attention(binding, read, txn) })?); } - let mut rows=Vec::new(); rows.try_reserve_exact(3).map_err(|_|Error::InputAllocation)?; - for (index,read) in reads.iter().enumerate() { - rows.push(chunk.prepare_attention_ffn(index,layer,read,|txn,residual| { - let prior=txn.gdn_prior(layer)?; - let mut attention=GdnStage::step(binding,layer,residual.ready(),&prior,txn,Some(dense))?; + let mut rows = Vec::new(); + rows.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + for (index, read) in reads.iter().enumerate() { + rows.push(chunk.prepare_attention_ffn(index, layer, read, |txn, residual| { + let prior = txn.gdn_prior(layer)?; + let mut attention = GdnStage::step(binding, layer, residual.ready(), &prior, txn, Some(dense))?; attention.validate_origin(&binding.identity())?; - let pending=attention.take_pending()?; txn.stage_gdn(&prior,pending)?; - let retained=GrStage::inject_retained(binding,residual,attention.output(), - attention.identity(),txn,dense)?; - let ffn=GrStage::read_retained_ffn(binding,retained,txn,dense)?; - let route=MoeRouteStage::route_from_ffn(binding,layer,ffn.ready(),txn,Some(dense))?; - MoeExpertStage::prepare_chunk_row(binding,layer,ffn,route,txn) + let pending = attention.take_pending()?; + txn.stage_gdn(&prior, pending)?; + let retained = + GrStage::inject_retained(binding, residual, attention.output(), attention.identity(), txn, dense)?; + let ffn = GrStage::read_retained_ffn(binding, retained, txn, dense)?; + let route = MoeRouteStage::route_from_ffn(binding, layer, ffn.ready(), txn, Some(dense))?; + MoeExpertStage::prepare_chunk_row(binding, layer, ffn, route, txn) })?); } - let values=MoeExpertStage::execute_chunk(binding,layer,&rows,&mut chunk,cache,&mut|| { - let cancel=cancel_after_copy && COPIED.get(); - if cancel { CANCELLED_ON_COPY.set(true); } + let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || { + let cancel = cancel_after_copy && COPIED.get(); + if cancel { + CANCELLED_ON_COPY.set(true); + } cancel })?; - let packets=observation.take()?; + let packets = observation.take()?; // Completed layer0 FFN products remain private: no injection/head/all48 or // joint target publication. A canceled real chunk is dropped, not repaired. drop(chunk); - Ok((values,packets)) + Ok((values, packets)) } // Independent byte-only old split+pack FIRST, then direct whole-group copy. // Genuine selected rows supply scope/origin. The finite payload deliberately // contains both signed zeros and different columns/slots; no model state is faked. fn transport_probe(context: &Context<'_>) -> Result { let failed = Rc::new(Cell::new(false)); - let scope = DownScope::new(context,failed.clone()); - let slots = [9usize,0,4]; + let scope = DownScope::new(context, failed.clone()); + let slots = [9usize, 0, 4]; let selections = slots.map(DownSelection::Routed); let mut payload = Vec::new(); - payload.try_reserve_exact(3*N).map_err(|_| Error::InputAllocation)?; - for c in 0..3 { for i in 0..N { - payload.push(if i%11==0 { -0.0 } else if i%13==0 { 0.0 } - else { (c as f32+1.0)*(i as f32-1279.0)/1024.0 }); - }} + payload.try_reserve_exact(3 * N).map_err(|_| Error::InputAllocation)?; + for c in 0..3 { + for i in 0..N { + payload.push(if i % 11 == 0 { + -0.0 + } else if i % 13 == 0 { + 0.0 + } else { + (c as f32 + 1.0) * (i as f32 - 1279.0) / 1024.0 + }); + } + } let source = scope.upload(&payload)?; let mut old_parts = Vec::new(); let mut direct_parts = Vec::new(); @@ -139,124 +196,200 @@ fn transport_probe(context: &Context<'_>) -> Result { let operation = (|| { // Both whole packets are sentinel initialized, so every untouched slot // is compared too. Original scalar copies establish the reference. - let mut sentinel=Vec::new(); sentinel.try_reserve_exact(K*N).map_err(|_|Error::InputAllocation)?; - sentinel.resize(K*N,17.0); + let mut sentinel = Vec::new(); + sentinel.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?; + sentinel.resize(K * N, 17.0); for _ in 0..3 { old_parts.push(scope.upload(&sentinel)?); direct_parts.push(scope.upload(&sentinel)?); } - for (c,slot) in slots.iter().enumerate() { - let mut split=scope.allocate(N*4)?; - let op=context.copy_routed_down_column(source.buffer()?,3,c,split.buffer_mut()?) - .map_err(driver_error).and_then(|()| context.pack_moe_down_f32( - split.buffer()?,old_parts[c].buffer_mut()?,*slot as u32).map_err(driver_error)); - let close=split.close(); op?; close?; + for (c, slot) in slots.iter().enumerate() { + let mut split = scope.allocate(N * 4)?; + let op = context + .copy_routed_down_column(source.buffer()?, 3, c, split.buffer_mut()?) + .map_err(driver_error) + .and_then(|()| { + context + .pack_moe_down_f32(split.buffer()?, old_parts[c].buffer_mut()?, *slot as u32) + .map_err(driver_error) + }); + let close = split.close(); + op?; + close?; } { - let mut copies=Vec::new(); copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; - for (c,part) in direct_parts.iter_mut().enumerate() { - copies.push((c as u32,part.buffer_mut()?,slots[c] as u32)); + let mut copies = Vec::new(); + copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + for (c, part) in direct_parts.iter_mut().enumerate() { + copies.push((c as u32, part.buffer_mut()?, slots[c] as u32)); } - context.copy_routed_down_columns_to_slots(source.buffer()?,3,&mut copies).map_err(driver_error)?; + context.copy_routed_down_columns_to_slots(source.buffer()?, 3, &mut copies).map_err(driver_error)?; } - for (old,new) in old_parts.iter().zip(&direct_parts) { - let a=download_f32(old.buffer()?,K*N)?; let b=download_f32(new.buffer()?,K*N)?; - if a.iter().zip(b.iter()).any(|(a,b)|a.to_bits()!=b.to_bits()) { return Err(Error::IdentityMismatch); } - } - let mut before=Vec::new(); before.try_reserve_exact(3).map_err(|_|Error::InputAllocation)?; - for part in &direct_parts { before.push(download_f32(part.buffer()?,K*N)?); } - // All-copy preflight: last slot/column invalid cannot mutate earlier - // valid destinations. Exact full-size genuine buffers, not fake aliases. - for bad_column in [false,true] { - let mut copies=Vec::new(); copies.try_reserve_exact(3).map_err(|_|Error::InputAllocation)?; - for (c,part) in direct_parts.iter_mut().enumerate() { - copies.push((if bad_column && c==2 {3} else {c as u32},part.buffer_mut()?, - if !bad_column && c==2 {10} else {slots[c] as u32})); - } - if !matches!(context.copy_routed_down_columns_to_slots(source.buffer()?,3,&mut copies), - Err(DriverError::InvalidProjectionShape)) { return Err(Error::IdentityMismatch); } - } - for (part,before) in direct_parts.iter().zip(before) { - let after=download_f32(part.buffer()?,K*N)?; - if before.iter().zip(after.iter()).any(|(a,b)|a.to_bits()!=b.to_bits()) { + for (old, new) in old_parts.iter().zip(&direct_parts) { + let a = download_f32(old.buffer()?, K * N)?; + let b = download_f32(new.buffer()?, K * N)?; + if a.iter().zip(b.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) { return Err(Error::IdentityMismatch); } } - let alien_scope=DownScope::new(context,Rc::new(Cell::new(false))); - let mut packet=super::super::moe_down::ResidentPackedDown::new(&scope)?; - let scope_guard=(|| { - if packet.complete(&scope).is_ok() { return Err(Error::IdentityMismatch); } - let called=Cell::new(false); - let refusal=super::super::moe_down::ResidentPackedDown::copy_group_with( - &alien_scope,&mut[(&mut packet,0)],|_|{called.set(true);Ok(())}); - if !matches!(refusal,Err(Error::IdentityMismatch)) || called.get() { + let mut before = Vec::new(); + before.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + for part in &direct_parts { + before.push(download_f32(part.buffer()?, K * N)?); + } + // All-copy preflight: last slot/column invalid cannot mutate earlier + // valid destinations. Exact full-size genuine buffers, not fake aliases. + for bad_column in [false, true] { + let mut copies = Vec::new(); + copies.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; + for (c, part) in direct_parts.iter_mut().enumerate() { + copies.push(( + if bad_column && c == 2 { 3 } else { c as u32 }, + part.buffer_mut()?, + if !bad_column && c == 2 { 10 } else { slots[c] as u32 }, + )); + } + if !matches!( + context.copy_routed_down_columns_to_slots(source.buffer()?, 3, &mut copies), + Err(DriverError::InvalidProjectionShape) + ) { + return Err(Error::IdentityMismatch); + } + } + for (part, before) in direct_parts.iter().zip(before) { + let after = download_f32(part.buffer()?, K * N)?; + if before.iter().zip(after.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) { + return Err(Error::IdentityMismatch); + } + } + let alien_scope = DownScope::new(context, Rc::new(Cell::new(false))); + let mut packet = super::super::moe_down::ResidentPackedDown::new(&scope)?; + let scope_guard = (|| { + if packet.complete(&scope).is_ok() { + return Err(Error::IdentityMismatch); + } + let called = Cell::new(false); + let refusal = super::super::moe_down::ResidentPackedDown::copy_group_with( + &alien_scope, + &mut [(&mut packet, 0)], + |_| { + called.set(true); + Ok(()) + }, + ); + if !matches!(refusal, Err(Error::IdentityMismatch)) || called.get() { return Err(Error::IdentityMismatch); } // A refused packet cannot be completed/reused within the old scope. - if packet.complete(&scope).is_ok() { return Err(Error::IdentityMismatch); } + if packet.complete(&scope).is_ok() { + return Err(Error::IdentityMismatch); + } Ok(()) })(); - let close=packet.close(); scope_guard?; close?; + let close = packet.close(); + scope_guard?; + close?; // Full finite source refusal precedes any copy callback, including an // interior NaN; the old producer is evaluated first on exact bytes. - for invalid in [f32::NAN,f32::INFINITY,f32::NEG_INFINITY] { - let mut bytes=Vec::new(); bytes.try_reserve_exact(payload.len()*4).map_err(|_|Error::InputAllocation)?; - for (i,v) in payload.iter().copied().enumerate() { - bytes.extend_from_slice(&(if i==2*N+17 { invalid } else {v}).to_le_bytes()); + for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(payload.len() * 4).map_err(|_| Error::InputAllocation)?; + for (i, v) in payload.iter().copied().enumerate() { + bytes.extend_from_slice(&(if i == 2 * N + 17 { invalid } else { v }).to_le_bytes()); } - let old=scope.project_columns(&selections,|out,_|out.copy_from(&bytes).map_err(driver_error),&mut||false); - let called=Cell::new(false); - let new=scope.project_columns_direct(&selections,|out,_|out.copy_from(&bytes).map_err(driver_error), - |_,_|{called.set(true);Ok(())},&mut||false); - if !matches!(old,Err(Error::NonFinite)) || !matches!(new,Err(Error::NonFinite)) || called.get() { + let old = + scope.project_columns(&selections, |out, _| out.copy_from(&bytes).map_err(driver_error), &mut || false); + let called = Cell::new(false); + let new = scope.project_columns_direct( + &selections, + |out, _| out.copy_from(&bytes).map_err(driver_error), + |_, _| { + called.set(true); + Ok(()) + }, + &mut || false, + ); + if !matches!(old, Err(Error::NonFinite)) || !matches!(new, Err(Error::NonFinite)) || called.get() { return Err(Error::IdentityMismatch); } } Ok(true) })(); scope.record(&operation); - let mut cleanup=Ok(()); + let mut cleanup = Ok(()); for owner in old_parts.into_iter().chain(direct_parts).chain(std::iter::once(source)) { - let next=owner.close(); if cleanup.is_ok(){cleanup=next;} + let next = owner.close(); + if cleanup.is_ok() { + cleanup = next; + } } - operation.and_then(|value|cleanup.map(|()|value)) + operation.and_then(|value| cleanup.map(|()| value)) } impl QwenForward { /// ONE genuine loaded binding/fresh session. Every arm independently mints /// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged. - pub(crate) fn test_direct_down_on_loaded<'ctx>(binding:&ModelBinding, - context:&Rc>,session:&mut QwenSession<'ctx>,kar:&mut KarPleCache<'_>, - cache:&mut MoeWeightCache<'ctx>,dense:&DenseWeightCache<'ctx>) -> Result { - cache.validate(binding,context)?;dense.retained_context(binding,context)?; - if !cache.uses_direct_native_down_packets() { return Err(Error::IdentityMismatch); } - let initial=session.test_reset_replay_snapshot(binding)?; - if !initial.has_prefix(0,[-1,-1]) { return Err(Error::IdentityMismatch); } - let (reference,old_packets)=arm(binding,context,session,kar,cache,dense,true,false)?; - let original_unchanged=initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let allocated=context.allocated_bytes(); - let (candidate,new_packets)=arm(binding,context,session,kar,cache,dense,false,false)?; - if reference.len()!=3 || candidate.len()!=3 || old_packets.len()!=3 || new_packets.len()!=3 { + pub(crate) fn test_direct_down_on_loaded<'ctx>( + binding: &ModelBinding, + context: &Rc>, + session: &mut QwenSession<'ctx>, + kar: &mut KarPleCache<'_>, + cache: &mut MoeWeightCache<'ctx>, + dense: &DenseWeightCache<'ctx>, + ) -> Result { + cache.validate(binding, context)?; + dense.retained_context(binding, context)?; + if !cache.uses_direct_native_down_packets() { return Err(Error::IdentityMismatch); } - let (mut differences,mut words)=compare(&old_packets,&new_packets)?; - for (a,b) in reference.iter().zip(&candidate) { - validate_values(a.output(),N)?;validate_values(b.output(),N)?; - differences+=a.output().iter().zip(b.output()).filter(|(a,b)|a.to_bits()!=b.to_bits()).count(); - words+=N; + let initial = session.test_reset_replay_snapshot(binding)?; + if !initial.has_prefix(0, [-1, -1]) { + return Err(Error::IdentityMismatch); } - let cancelled_after_copy=matches!(arm(binding,context,session,kar,cache,dense,false,true), - Err(Error::Unsupported(Stage::Executor))) && CANCELLED_ON_COPY.get() + let (reference, old_packets) = arm(binding, context, session, kar, cache, dense, true, false)?; + let original_unchanged = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); + let allocated = context.allocated_bytes(); + let (candidate, new_packets) = arm(binding, context, session, kar, cache, dense, false, false)?; + if reference.len() != 3 || candidate.len() != 3 || old_packets.len() != 3 || new_packets.len() != 3 { + return Err(Error::IdentityMismatch); + } + let (mut differences, mut words) = compare(&old_packets, &new_packets)?; + for (a, b) in reference.iter().zip(&candidate) { + validate_values(a.output(), N)?; + validate_values(b.output(), N)?; + differences += a.output().iter().zip(b.output()).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + words += N; + } + let cancelled_after_copy = matches!( + arm(binding, context, session, kar, cache, dense, false, true), + Err(Error::Unsupported(Stage::Executor)) + ) && CANCELLED_ON_COPY.get() && initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); session.reset()?; - let reset_prefix=initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); - let (recovery,recovered_packets)=arm(binding,context,session,kar,cache,dense,false,false)?; - if recovery.len()!=3 || recovered_packets.len()!=3 { return Err(Error::IdentityMismatch); } - let (d,n)=compare(&old_packets,&recovered_packets)?;differences+=d;words+=n; - let reset_exact=original_unchanged && reset_prefix && reference.iter().zip(&recovery) - .all(|(a,b)|a.output().iter().zip(b.output()).all(|(a,b)|a.to_bits()==b.to_bits())); - let guards=transport_probe(context)?; - if words!=3*(2*K*N+N) { return Err(Error::IdentityMismatch); } - Ok(DirectDownReport { differences,words,cancelled_after_copy,reset_exact,guards, - allocated_unchanged:allocated==context.allocated_bytes() }) + let reset_prefix = initial.numeric_eq(&session.test_reset_replay_snapshot(binding)?); + let (recovery, recovered_packets) = arm(binding, context, session, kar, cache, dense, false, false)?; + if recovery.len() != 3 || recovered_packets.len() != 3 { + return Err(Error::IdentityMismatch); + } + let (d, n) = compare(&old_packets, &recovered_packets)?; + differences += d; + words += n; + let reset_exact = original_unchanged + && reset_prefix + && reference + .iter() + .zip(&recovery) + .all(|(a, b)| a.output().iter().zip(b.output()).all(|(a, b)| a.to_bits() == b.to_bits())); + let guards = transport_probe(context)?; + if words != 3 * (2 * K * N + N) { + return Err(Error::IdentityMismatch); + } + Ok(DirectDownReport { + differences, + words, + cancelled_after_copy, + reset_exact, + guards, + allocated_unchanged: allocated == context.allocated_bytes(), + }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs index 0c0dedd9..34db16da 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_group_resident_queue.rs @@ -4,15 +4,24 @@ use leleka_cuda_driver::{RoutedResidentRefusal, RoutedResidentWeights}; #[allow(clippy::too_many_arguments)] pub(super) fn project_group_packets<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, rows: &[ChunkFfnRow], - pairs: &[Pair], cache: &mut MoeWeightCache<'_>, prepared: &[RoutedGateUpQ8<'_>], - scope: &DownScope<'ctx>, origins: &[Rc], - packets: &mut [ActualSlotPacket<'ctx>], cancelled: &mut impl FnMut() -> bool, - actual: &QwenChunkTxn<'_, '_>, ephemeral_slot: Option, + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + rows: &[ChunkFfnRow], + pairs: &[Pair], + cache: &mut MoeWeightCache<'_>, + prepared: &[RoutedGateUpQ8<'_>], + scope: &DownScope<'ctx>, + origins: &[Rc], + packets: &mut [ActualSlotPacket<'ctx>], + cancelled: &mut impl FnMut() -> bool, + actual: &QwenChunkTxn<'_, '_>, + ephemeral_slot: Option, ) -> Result<()> { validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; cache.validate(binding, context)?; - if !uses_adaptive(cache) || !use_direct_packets(cache) { return Err(Error::IdentityMismatch); } + if !uses_adaptive(cache) || !use_direct_packets(cache) { + return Err(Error::IdentityMismatch); + } let queue_owner = cache.routed_resident_owner(binding, context)?; let output_owner = cache.routed_output_owner(binding, context)?; let first = pairs[0]; @@ -45,70 +54,113 @@ pub(super) fn project_group_packets<'ctx>( } let operation = output_owner.with_outputs(context, pairs.len(), |[gate, up, hidden, down]| { binding.with_moe_routed_source(&members, binding_error, |source| { - // Every grouped member must name the same actual whole expert triplet. - for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let key = source.descriptor(0, role).map_err(binding_error)?; - for member in 1..pairs.len() { - if source.descriptor(member, role).map_err(binding_error)? != key { - return Err(Error::IdentityMismatch); + // Every grouped member must name the same actual whole expert triplet. + for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { + let key = source.descriptor(0, role).map_err(binding_error)?; + for member in 1..pairs.len() { + if source.descriptor(member, role).map_err(binding_error)? != key { + return Err(Error::IdentityMismatch); + } } } - } - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } - // Fresh per loan; set only when the real cancelled closure answers true inside the callback. - let cancel_observed = std::cell::Cell::new(false); - let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); - let consume = |raw: [&DeviceBuffer<'_>; 3], health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { - queue_owner.with_queue(|queue| { - let complete = queue.compose(RoutedResidentWeights { - gate: raw[0], up: raw[1], down: raw[2], gu_formats, down_format, - }, &refs, gate, up, hidden, down) - .map_err(driver_error)?; - match complete.numerical_refusal() { - Some(RoutedResidentRefusal::DownQuant) => { - let values = download_f32(complete.completed_hidden().ok_or(Error::IdentityMismatch)?, pairs.len() * FF)?; - return ordered_down_refusal(context, down_kind, CachedMoeMatrix::Raw(raw[2]), - &values, &selections, scope, &mut observed_cancel); - } - Some(_) => return Err(Error::NonFinite), - None => {} - } - let down_source = complete.completed_down().ok_or(Error::IdentityMismatch)?; - if observed_cancel() { return Err(Error::Unsupported(Stage::Executor)); } - validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; - let mut targets = Vec::new(); - targets.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; - let mut next = 0; - for (row, packet) in packets.iter_mut().enumerate() { - if next < pairs.len() && pairs[next].row == row { - targets.push((&mut packet.packet, pairs[next].slot)); - next += 1; - } - } - if next != pairs.len() { return Err(Error::IdentityMismatch); } - super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut targets, |copies| { - context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?; - if observed_cancel() { return Err(Error::Unsupported(Stage::Executor)); } - source.finish().map_err(binding_error)?; - health.validate(binding, context)?; - for pair in pairs { - actual.validate_ffn_row(actual.micro_row_index(pair.row)?, - rows[pair.row].row().route.identity().layer(), &rows[pair.row])?; - let row = rows[pair.row].row(); - let id = row.route.identity(); - row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; - if !origins[pair.row].binding.matches(&binding.identity()) || origins[pair.row].identity != id { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + // Fresh per loan; set only when the real cancelled closure answers true inside the callback. + let cancel_observed = std::cell::Cell::new(false); + let mut observed_cancel = + crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); + let consume = + |raw: [&DeviceBuffer<'_>; 3], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { + queue_owner.with_queue(|queue| { + let complete = queue + .compose( + RoutedResidentWeights { + gate: raw[0], + up: raw[1], + down: raw[2], + gu_formats, + down_format, + }, + &refs, + gate, + up, + hidden, + down, + ) + .map_err(driver_error)?; + match complete.numerical_refusal() { + Some(RoutedResidentRefusal::DownQuant) => { + let values = download_f32( + complete.completed_hidden().ok_or(Error::IdentityMismatch)?, + pairs.len() * FF, + )?; + return ordered_down_refusal( + context, + down_kind, + CachedMoeMatrix::Raw(raw[2]), + &values, + &selections, + scope, + &mut observed_cancel, + ); + } + Some(_) => return Err(Error::NonFinite), + None => {} + } + let down_source = complete.completed_down().ok_or(Error::IdentityMismatch)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?; + let mut targets = Vec::new(); + targets.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + let mut next = 0; + for (row, packet) in packets.iter_mut().enumerate() { + if next < pairs.len() && pairs[next].row == row { + targets.push((&mut packet.packet, pairs[next].slot)); + next += 1; + } + } + if next != pairs.len() { return Err(Error::IdentityMismatch); } - } - Ok(()) - }) - }) - }; - match ephemeral_slot { - Some(slot) => cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume), - None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), - } + super::super::moe_down::ResidentPackedDown::copy_group_with(scope, &mut targets, |copies| { + context + .copy_routed_down_columns_to_slots(down_source, pairs.len(), copies) + .map_err(driver_error)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + source.finish().map_err(binding_error)?; + health.validate(binding, context)?; + for pair in pairs { + actual.validate_ffn_row( + actual.micro_row_index(pair.row)?, + rows[pair.row].row().route.identity().layer(), + &rows[pair.row], + )?; + let row = rows[pair.row].row(); + let id = row.route.identity(); + row.validate(&binding.identity(), id.token(), id.position(), id.layer())?; + if !origins[pair.row].binding.matches(&binding.identity()) + || origins[pair.row].identity != id + { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + }) + }) + }; + match ephemeral_slot { + Some(slot) => { + cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) + } + None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), + } }) }); scope.record(&operation); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs index 21249bfb..55a3650c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_layer0_pair.rs @@ -3,13 +3,7 @@ use super::*; use crate::qwen_forward::layer0_mmq_observation as observation; fn counters(cache: &MoeWeightCache<'_>) -> [u64; 5] { let c = cache.counters(); - [ - c.hits, - c.misses, - c.read_bytes, - c.upload_bytes, - c.eviction_bytes, - ] + [c.hits, c.misses, c.read_bytes, c.upload_bytes, c.eviction_bytes] } fn validate_sources( binding: &ModelBinding, @@ -27,8 +21,7 @@ fn validate_sources( if position.get() != index as u64 { return Err(Error::IdentityMismatch); } - row.row() - .validate(&binding.identity(), token, position, layer)?; + row.row().validate(&binding.identity(), token, position, layer)?; let ids: [u32; K] = std::array::from_fn(|slot| row.row().route.experts()[slot].get()); let weights: [f32; K] = std::array::from_fn(|slot| row.row().route.weights()[slot].get()); if initial { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs index e8c15247..680c5e1d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_adaptive.rs @@ -23,22 +23,19 @@ pub(super) fn execute_adaptive_groups<'ctx>( || !cache.uses_strata_adaptive_experts() || txn.is_mtp_verification()? || rows.is_empty() - || u32::try_from(rows.len()).map_err(|_|Error::Overflow)? > workspace.original_expert_capacity().map_err(mmq_error)? + || u32::try_from(rows.len()).map_err(|_| Error::Overflow)? + > workspace.original_expert_capacity().map_err(mmq_error)? || rows.len() != txn.micro_len()? || groups.len() != 512 { return Err(Error::IdentityMismatch); } let ephemeral = cache.ephemeral_routed_owner(binding, context)?; - let operation = execute_inner( - txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled, - ); + let operation = + execute_inner(txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled); // Even an identity, numeric, copy, or cancellation refusal drains all real // pending events. Healthy idle allocations remain owned for the next layer. - let cleanup = ephemeral - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch) - .and_then(|mut owner| owner.drain()); + let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.drain()); if context.is_poisoned() || matches!(&cleanup, Err(Error::CudaExecution)) { cache.note_transport_failure(); } @@ -60,24 +57,32 @@ fn execute_inner<'ctx>( cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { let mut counts = Vec::new(); - counts.try_reserve_exact(512).map_err(|_|Error::InputAllocation)?; + counts.try_reserve_exact(512).map_err(|_| Error::InputAllocation)?; let mut sorted_rows = Vec::new(); - sorted_rows.try_reserve_exact(rows.len().checked_mul(K).ok_or(Error::Overflow)?) - .map_err(|_|Error::InputAllocation)?; - for pairs in groups.iter().filter(|pairs|!pairs.is_empty()) { - counts.push(u32::try_from(pairs.len()).map_err(|_|Error::Overflow)?); - for pair in pairs { sorted_rows.push(u32::try_from(pair.row).map_err(|_|Error::Overflow)?); } + sorted_rows + .try_reserve_exact(rows.len().checked_mul(K).ok_or(Error::Overflow)?) + .map_err(|_| Error::InputAllocation)?; + for pairs in groups.iter().filter(|pairs| !pairs.is_empty()) { + counts.push(u32::try_from(pairs.len()).map_err(|_| Error::Overflow)?); + for pair in pairs { + sorted_rows.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); + } } // Authenticate every actual row/group before the first device command. // Frequency/event policy still runs at its original point below. - for (index,row) in rows.iter().enumerate() { - txn.validate_ffn_row(txn.micro_row_index(index)?,layer,row)?; + for (index, row) in rows.iter().enumerate() { + txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; } - for (expert,pairs) in groups.iter().enumerate().filter(|(_,pairs)|!pairs.is_empty()) { - let _ = packets.group(u32::try_from(expert).map_err(|_|Error::Overflow)?,pairs)?; + for (expert, pairs) in groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) { + let _ = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; } - let mut source = workspace.prepare_original_expert_layer(inputs, - u32::try_from(rows.len()).map_err(|_|Error::Overflow)?, &counts, &sorted_rows) + let mut source = workspace + .prepare_original_expert_layer( + inputs, + u32::try_from(rows.len()).map_err(|_| Error::Overflow)?, + &counts, + &sorted_rows, + ) .map_err(mmq_error)?; cache.poll_strata_adaptive(binding, false)?; for (index, row) in rows.iter().enumerate() { @@ -97,8 +102,7 @@ fn execute_inner<'ctx>( let mut charge = 0usize; for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { let key = binding - .moe_weight_descriptor(&row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, role) + .moe_weight_descriptor(&row.row().weights, MoeExpertSelection::Routed { slot: first.slot }, role) .map_err(binding_error)?; if key.layer != layer.get() || key.expert != Some(expert as u32) { return Err(Error::IdentityMismatch); @@ -107,8 +111,11 @@ fn execute_inner<'ctx>( charge = charge.checked_add(bytes).ok_or(Error::Overflow)?; } maximum_charge = maximum_charge.max(charge); - resident[expert] = cache.strata_adaptive_resident(binding, &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot })?; + resident[expert] = cache.strata_adaptive_resident( + binding, + &row.row().weights, + MoeExpertSelection::Routed { slot: first.slot }, + )?; if !resident[expert] { misses[miss_count] = expert; miss_count += 1; @@ -125,7 +132,9 @@ fn execute_inner<'ctx>( let mut slots = [None; 16]; let mut next = 0usize; for (slot, directory) in slots[..capacity].iter_mut().enumerate() { - if next == miss_count { break; } + if next == miss_count { + break; + } let expert = misses[next]; stage(cache, context, binding, rows, &groups[expert], slot, cancelled)?; *directory = Some(expert); @@ -133,39 +142,46 @@ fn execute_inner<'ctx>( } // Literal prompt order: residents and staged misses share one ID walk. // The real bank retains gathered bytes until the <=16-expert numerical run. - let mut staged_experts = [0usize;16]; + let mut staged_experts = [0usize; 16]; let mut staged_count = 0usize; let used_count = counts.len(); let mut consumed = 0usize; for (expert, pairs) in groups.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } let slot = if resident[expert] { None } else { - let slot = slots[..capacity].iter().position(|entry| *entry == Some(expert)) - .ok_or(Error::IdentityMismatch)?; + let slot = + slots[..capacity].iter().position(|entry| *entry == Some(expert)).ok_or(Error::IdentityMismatch)?; owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, binding)?; Some(slot) }; - gather_expert(txn, context, binding, layer, rows, expert, pairs, cache, - &mut source, packets, slot, cancelled)?; + gather_expert(txn, context, binding, layer, rows, expert, pairs, cache, &mut source, packets, slot, cancelled)?; staged_experts[staged_count] = expert; staged_count += 1; consumed += 1; if staged_count == 16 || consumed == used_count { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } { let finite = source.run_group().map_err(mmq_error)?; for (group_index, expert) in staged_experts[..staged_count].iter().copied().enumerate() { let pairs = &groups[expert]; - let origin = packets.group(u32::try_from(expert).map_err(|_|Error::Overflow)?,pairs)?; - packets.copy_group(&origin, |destinations| { - finite.copy_expert_down_columns_to_slots(group_index,destinations).map_err(mmq_error)?; - // Each genuine source scope was explicitly finished after - // its completed gather. Revalidate current model/context - // before the actual packet owner publishes coverage. - cache.validate(binding,context) - },cancelled)?; + let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + packets.copy_group( + &origin, + |destinations| { + finite.copy_expert_down_columns_to_slots(group_index, destinations).map_err(mmq_error)?; + // Each genuine source scope was explicitly finished after + // its completed gather. Revalidate current model/context + // before the actual packet owner publishes coverage. + cache.validate(binding, context) + }, + cancelled, + )?; } } source.finish_group().map_err(mmq_error)?; @@ -197,14 +213,15 @@ fn stage( slot: usize, cancelled: &mut impl FnMut() -> bool, ) -> Result<()> { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } let first = pairs.first().ok_or(Error::IdentityMismatch)?; let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; let members = [(&row.row().weights, first.slot)]; let owner = cache.ephemeral_routed_owner(binding, context)?; binding.with_moe_routed_source(&members, binding_error, |source| { - owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? - .stage(slot, binding, source, 0) + owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0) }) } @@ -228,16 +245,20 @@ fn gather_expert<'ctx>( members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; let first = pairs.first().ok_or(Error::IdentityMismatch)?; let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let descriptor = |role| binding.moe_weight_descriptor(&row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, role).map_err(binding_error); - let keys = [descriptor(MoeMatrixRole::Gate)?, descriptor(MoeMatrixRole::Up)?, - descriptor(MoeMatrixRole::Down)?]; - let layouts = [original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?, + let descriptor = |role| { + binding + .moe_weight_descriptor(&row.row().weights, MoeExpertSelection::Routed { slot: first.slot }, role) + .map_err(binding_error) + }; + let keys = [descriptor(MoeMatrixRole::Gate)?, descriptor(MoeMatrixRole::Up)?, descriptor(MoeMatrixRole::Down)?]; + let layouts = [ + original_dual_layout(keys[0])?.ok_or(Error::InvalidDimension)?, original_dual_layout(keys[1])?.ok_or(Error::InvalidDimension)?, - original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?]; + original_dual_layout(keys[2])?.ok_or(Error::InvalidDimension)?, + ]; let formats = layouts.map(|(format, _)| format); - let charge = layouts.into_iter().try_fold(0usize, |sum, (_, bytes)| - sum.checked_add(bytes).ok_or(Error::Overflow))?; + let charge = + layouts.into_iter().try_fold(0usize, |sum, (_, bytes)| sum.checked_add(bytes).ok_or(Error::Overflow))?; for pair in pairs { let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, row)?; @@ -245,10 +266,12 @@ fn gather_expert<'ctx>( } cache.reserve_mmq_transient(binding, context, charge)?; binding.with_moe_routed_source(&members, binding_error, |source| { - for (role_index, role) in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] - .into_iter().enumerate() { + for (role_index, role) in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down].into_iter().enumerate() + { let key = source.descriptor(0, role).map_err(binding_error)?; - if key != keys[role_index] { return Err(Error::IdentityMismatch); } + if key != keys[role_index] { + return Err(Error::IdentityMismatch); + } for member in 1..pairs.len() { if source.descriptor(member, role).map_err(binding_error)? != key { return Err(Error::IdentityMismatch); @@ -256,27 +279,34 @@ fn gather_expert<'ctx>( } } let cancel_observed = Cell::new(false); - let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel( - &cancel_observed, cancelled); - let consume = |raw: [&DeviceBuffer<'ctx>; 3], health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { - if observed_cancel() { return Err(Error::Unsupported(Stage::Executor)); } - activation.stage_expert(formats,raw).map_err(mmq_error)?; - source.finish().map_err(binding_error)?; - health.validate(binding,context)?; - if observed_cancel() { return Err(Error::Unsupported(Stage::Executor)); } - for pair in pairs { - let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; - txn.validate_ffn_row(txn.micro_row_index(pair.row)?,layer,row)?; - } - // The genuine bytes are now retained in the admitted bank, not a - // synthetic MmqWeights view. Actual staging owner can be reused only - // after this confirmed gather + source/current-row health boundary. - let _ = origin; - Ok(()) - }; + let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled); + let consume = + |raw: [&DeviceBuffer<'ctx>; 3], + health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>, + source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| { + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + activation.stage_expert(formats, raw).map_err(mmq_error)?; + source.finish().map_err(binding_error)?; + health.validate(binding, context)?; + if observed_cancel() { + return Err(Error::Unsupported(Stage::Executor)); + } + for pair in pairs { + let row = rows.get(pair.row).ok_or(Error::IdentityMismatch)?; + txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, row)?; + } + // The genuine bytes are now retained in the admitted bank, not a + // synthetic MmqWeights view. Actual staging owner can be reused only + // after this confirmed gather + source/current-row health boundary. + let _ = origin; + Ok(()) + }; match ephemeral_slot { - Some(slot) => cache.with_ephemeral_triplet_routed_source(binding, source, 0, - slot, &cancel_observed, consume), + Some(slot) => { + cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume) + } None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume), } }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs index 3e6dc351..f392f400 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_chunk.rs @@ -3,8 +3,8 @@ use super::resident_slotpack::SlotPacks; use super::*; use leleka_cuda_driver::MmqWorkspace; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="moe_mmq_adaptive.rs"] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "moe_mmq_adaptive.rs"] mod original_adaptive; impl MoeExpertStage { @@ -16,59 +16,76 @@ impl MoeExpertStage { cache: &mut MoeWeightCache<'ctx>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { - Self::execute_chunk_mmq_with_finish(binding,layer,rows,chunk,cache,cancelled, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] None) + Self::execute_chunk_mmq_with_finish( + binding, + layer, + rows, + chunk, + cache, + cancelled, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + None, + ) } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn execute_chunk_mmq_native_prompt<'ctx>( - binding:&ModelBinding, layer:LayerId, rows:&[ChunkFfnRow], - chunk:&mut QwenChunkTxn<'_, 'ctx>,cache:&mut MoeWeightCache<'ctx>, - cancelled:&mut impl FnMut()->bool, - products:&mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, - dense:&super::super::super::dense_weight_cache::DenseWeightCache<'_>, - )->Result>{ - Self::execute_chunk_mmq_with_finish(binding,layer,rows,chunk,cache,cancelled, - Some(super::prompt_finish::NativePromptFinish{products,dense})) + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + products: &mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>, + dense: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + ) -> Result> { + Self::execute_chunk_mmq_with_finish( + binding, + layer, + rows, + chunk, + cache, + cancelled, + Some(super::prompt_finish::NativePromptFinish { products, dense }), + ) } fn execute_chunk_mmq_with_finish<'ctx>( - binding:&ModelBinding,layer:LayerId,rows:&[ChunkFfnRow], - chunk:&mut QwenChunkTxn<'_, 'ctx>,cache:&mut MoeWeightCache<'ctx>, - cancelled:&mut impl FnMut()->bool, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - native:Option>, - )->Result>{ + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], + chunk: &mut QwenChunkTxn<'_, 'ctx>, + cache: &mut MoeWeightCache<'ctx>, + cancelled: &mut impl FnMut() -> bool, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option< + super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, + ) -> Result> { if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) { return Err(Error::InvalidDimension); } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let original_prompt = false; let mut supported = original_prompt || rows.len() > 1; for (index, row) in rows.iter().enumerate() { chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?; for slot in 0..K { let selection = MoeExpertSelection::Routed { slot }; - let gate = row - .row() - .weights - .kind(selection, MoeMatrixRole::Gate) - .map_err(binding_error)?; - let up = row - .row() - .weights - .kind(selection, MoeMatrixRole::Up) - .map_err(binding_error)?; - let down = row - .row() - .weights - .kind(selection, MoeMatrixRole::Down) - .map_err(binding_error)?; + let gate = row.row().weights.kind(selection, MoeMatrixRole::Gate).map_err(binding_error)?; + let up = row.row().weights.kind(selection, MoeMatrixRole::Up).map_err(binding_error)?; + let down = row.row().weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?; supported &= (if original_prompt { - matches!(gate, MoeMatrixKind::Iq3Xxs | MoeMatrixKind::Iq2S - | MoeMatrixKind::Iq3S | MoeMatrixKind::RoutedIq4Xs | MoeMatrixKind::RoutedIq4Nl) - } else { matches!(gate, MoeMatrixKind::Iq3Xxs | MoeMatrixKind::Iq2S) }) - && gate == up + matches!( + gate, + MoeMatrixKind::Iq3Xxs + | MoeMatrixKind::Iq2S + | MoeMatrixKind::Iq3S + | MoeMatrixKind::RoutedIq4Xs + | MoeMatrixKind::RoutedIq4Nl + ) + } else { + matches!(gate, MoeMatrixKind::Iq3Xxs | MoeMatrixKind::Iq2S) + }) && gate == up && matches!(down, MoeMatrixKind::RoutedIq4Nl | MoeMatrixKind::Q2_0); } } @@ -82,21 +99,13 @@ impl MoeExpertStage { let selection = MoeExpertSelection::Routed { slot }; let keys = [ binding - .moe_weight_descriptor( - &row.row().weights, - selection, - MoeMatrixRole::Gate, - ) + .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Gate) .map_err(binding_error)?, binding .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Up) .map_err(binding_error)?, binding - .moe_weight_descriptor( - &row.row().weights, - selection, - MoeMatrixRole::Down, - ) + .moe_weight_descriptor(&row.row().weights, selection, MoeMatrixRole::Down) .map_err(binding_error)?, ]; if keys.iter().any(|key| key.layer != layer.get()) { @@ -115,10 +124,18 @@ impl MoeExpertStage { if !supported { // Actual21/23, T1 and GU22 under the IQ3-only policy take native. This is // an admission decision BEFORE MMQ numerics, not error fallback. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if let Some(finish)=native { - return Self::execute_chunk_native_prompt(binding,layer,rows,chunk,cache, - cancelled,finish.products,finish.dense); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(finish) = native { + return Self::execute_chunk_native_prompt( + binding, + layer, + rows, + chunk, + cache, + cancelled, + finish.products, + finish.dense, + ); } let result = Self::execute_chunk(binding, layer, rows, chunk, cache, cancelled); #[cfg(test)] @@ -135,8 +152,16 @@ impl MoeExpertStage { } cache.with_mmq_workspace(binding, context, &admission, |cache, workspace| { execute_resident( - actual, context, binding, layer, rows, cache, workspace, cancelled, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] native, + actual, + context, + binding, + layer, + rows, + cache, + workspace, + cancelled, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + native, ) }) }); @@ -165,22 +190,19 @@ fn execute_resident<'ctx>( cache: &mut MoeWeightCache<'ctx>, workspace: &mut MmqWorkspace<'ctx>, cancelled: &mut impl FnMut() -> bool, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - mut native:Option>, + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option< + super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + >, ) -> Result> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Moe, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); cache.validate(binding, context)?; // Workspace is ALREADY allocated/charged by the explicit cache factory. // Account all simultaneous slot packets and unchanged shared activations; // existing cache.room retains the independent 128MiB transient reserve. - let extra = rows - .len() - .checked_mul(K * N * 4 + N * 4) - .and_then(|v| v.checked_add(DEVICE_PEAK)) - .ok_or(Error::Overflow)?; + let extra = + rows.len().checked_mul(K * N * 4 + N * 4).and_then(|v| v.checked_add(DEVICE_PEAK)).ok_or(Error::Overflow)?; #[cfg(test)] let allocated_before = context.allocated_bytes(); #[cfg(test)] @@ -222,126 +244,120 @@ fn execute_resident<'ctx>( .try_reserve_exact(rows.len().checked_mul(N).ok_or(Error::Overflow)?) .map_err(|_| Error::InputAllocation)?; let mut ids = Vec::new(); - ids.try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + ids.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in rows.iter().enumerate() { txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; inputs.extend_from_slice(row.row().read.ready().mixed()); - ids.push(std::array::from_fn(|slot| { - row.row().route.experts()[slot].get() - })); + ids.push(std::array::from_fn(|slot| row.row().route.experts()[slot].get())); } let groups = grouped_pairs(&ids)?; let mut packets = SlotPacks::new(txn, binding, layer, rows, context, &scope)?; let mut activations = Vec::new(); - activations - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + activations.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; let operation = (|| { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } { let tokens = u32::try_from(rows.len()).map_err(|_| Error::Overflow)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let original_prompt = native.is_some() && cache.has_original_prompt_mmq(); - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let original_prompt = false; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] let adaptive_prompt = original_prompt && cache.uses_strata_adaptive_experts(); - #[cfg(not(all(any(target_os="linux",target_os="windows"),target_arch="x86_64")))] + #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let adaptive_prompt = false; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if adaptive_prompt { - original_adaptive::execute_adaptive_groups(txn, context, binding, layer, rows, - &groups, cache, workspace, &inputs, &mut packets, cancelled)?; + original_adaptive::execute_adaptive_groups( + txn, + context, + binding, + layer, + rows, + &groups, + cache, + workspace, + &inputs, + &mut packets, + cancelled, + )?; } if !adaptive_prompt { - let mut source = if original_prompt { - workspace.prepare_original_gate_up_chunk(&inputs, tokens) - } else { workspace.prepare_gate_up_chunk(&inputs, tokens) }.map_err(mmq_error)?; - for (expert, pairs) in groups - .iter() - .enumerate() - .filter(|(_, pairs)| !pairs.is_empty() && !adaptive_prompt) - { - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); + let mut source = if original_prompt { + workspace.prepare_original_gate_up_chunk(&inputs, tokens) + } else { + workspace.prepare_gate_up_chunk(&inputs, tokens) } - let origin = packets - .group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; - let first = pairs.first().ok_or(Error::IdentityMismatch)?; - let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; - let mut indices = Vec::new(); - indices - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; - for pair in pairs { - txn.validate_ffn_row( - txn.micro_row_index(pair.row)?, - layer, - &rows[pair.row], - )?; - for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { - let source_key = binding - .moe_weight_descriptor( - &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, - role, - ) - .map_err(binding_error)?; - let actual_key = binding - .moe_weight_descriptor( - &rows[pair.row].row().weights, - MoeExpertSelection::Routed { slot: pair.slot }, - role, - ) - .map_err(binding_error)?; - if source_key != actual_key { - return Err(Error::IdentityMismatch); - } + .map_err(mmq_error)?; + for (expert, pairs) in + groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty() && !adaptive_prompt) + { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); } - indices.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); + let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?; + let first = pairs.first().ok_or(Error::IdentityMismatch)?; + let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?; + let mut indices = Vec::new(); + indices.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; + for pair in pairs { + txn.validate_ffn_row(txn.micro_row_index(pair.row)?, layer, &rows[pair.row])?; + for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { + let source_key = binding + .moe_weight_descriptor( + &row.row().weights, + MoeExpertSelection::Routed { slot: first.slot }, + role, + ) + .map_err(binding_error)?; + let actual_key = binding + .moe_weight_descriptor( + &rows[pair.row].row().weights, + MoeExpertSelection::Routed { slot: pair.slot }, + role, + ) + .map_err(binding_error)?; + if source_key != actual_key { + return Err(Error::IdentityMismatch); + } + } + indices.push(u32::try_from(pair.row).map_err(|_| Error::Overflow)?); + } + let group = source.gather_gate_up(&indices).map_err(mmq_error)?; + cache.with_mmq_triplet( + binding, + &row.row().weights, + MoeExpertSelection::Routed { slot: first.slot }, + original_prompt, + |gate, up, down| { + let hidden = group.gate_up(gate, up).map_err(mmq_error)?; + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + let finite = hidden.down(down).map_err(mmq_error)?; + if finite.tokens() as usize != pairs.len() { + return Err(Error::IdentityMismatch); + } + packets.copy_group( + &origin, + |destinations| finite.copy_down_columns_to_slots(destinations).map_err(mmq_error), + cancelled, + )?; + Ok(()) + }, + )?; + // finite group lease has expired; the same workspace is reused. } - let group = source.gather_gate_up(&indices).map_err(mmq_error)?; - cache.with_mmq_triplet( - binding, - &row.row().weights, - MoeExpertSelection::Routed { slot: first.slot }, - original_prompt, - |gate, up, down| { - let hidden = group.gate_up(gate, up).map_err(mmq_error)?; - if cancelled() { - return Err(Error::Unsupported(Stage::Executor)); - } - let finite = hidden.down(down).map_err(mmq_error)?; - if finite.tokens() as usize != pairs.len() { - return Err(Error::IdentityMismatch); - } - packets.copy_group( - &origin, - |destinations| { - finite - .copy_down_columns_to_slots(destinations) - .map_err(mmq_error) - }, - cancelled, - )?; - Ok(()) - }, - )?; - // finite group lease has expired; the same workspace is reused. - } } } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if let Some(finish)=native.as_mut(){ - return packets.finish_native_micro(cache,finish,cancelled); + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if let Some(finish) = native.as_mut() { + return packets.finish_native_micro(cache, finish, cancelled); } let mut outputs = Vec::new(); - outputs - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in rows.iter().enumerate() { if cancelled() { return Err(Error::Unsupported(Stage::Executor)); @@ -349,17 +365,12 @@ fn execute_resident<'ctx>( // Shared expert is unchanged native math. Its existing private // scalar staging is retained, not advertised as device-resident. activations.push(scope.upload(row.row().read.ready().mixed())?); - outputs.push( - packets.finish_row( - index, - activations - .last() - .ok_or(Error::IdentityMismatch)? - .buffer()?, - cache, - cancelled, - )?, - ); + outputs.push(packets.finish_row( + index, + activations.last().ok_or(Error::IdentityMismatch)?.buffer()?, + cache, + cancelled, + )?); } Ok(outputs) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs index bd111448..ed222359 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_mmq_slotpack.rs @@ -31,13 +31,11 @@ fn validate_row( let global = txn.micro_row_index(index)?; txn.validate_ffn_row(global, layer, row)?; let (token, position) = txn.row_ids(global)?; - if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() - { + if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() { return Err(Error::IdentityMismatch); } origin.identity.validate(token, position, layer)?; - row.row() - .validate(&binding.identity(), token, position, layer) + row.row().validate(&binding.identity(), token, position, layer) } impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { pub(super) fn new( @@ -48,10 +46,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { context: &'ctx Context<'ctx>, scope: &'source DownScope<'ctx>, ) -> Result { - if rows.len() != txn.micro_len()? - || !(1..=64).contains(&rows.len()) - || !std::ptr::eq(context, txn.context()?) - { + if rows.len() != txn.micro_len()? || !(1..=64).contains(&rows.len()) || !std::ptr::eq(context, txn.context()?) { return Err(Error::IdentityMismatch); } // Before allocating any private destinations, validate every actual @@ -60,35 +55,17 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { let global = txn.micro_row_index(index)?; txn.validate_ffn_row(global, layer, row)?; let (token, position) = txn.row_ids(global)?; - row.row() - .validate(&binding.identity(), token, position, layer)?; + row.row().validate(&binding.identity(), token, position, layer)?; } let mut origins = Vec::new(); - origins - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + origins.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; let mut packets = Vec::new(); - packets - .try_reserve_exact(rows.len()) - .map_err(|_| Error::InputAllocation)?; + packets.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for row in rows { - origins.push(Rc::new(DownOrigin { - binding: binding.identity(), - identity: row.row().route.identity(), - })); + origins.push(Rc::new(DownOrigin { binding: binding.identity(), identity: row.row().route.identity() })); packets.push(ResidentPackedDown::new(scope)?); } - Ok(Self { - owner: Rc::new(()), - txn, - binding, - layer, - rows, - context, - scope, - origins, - packets, - }) + Ok(Self { owner: Rc::new(()), txn, binding, layer, rows, context, scope, origins, packets }) } pub(super) fn group(&self, expert: u32, pairs: &[Pair]) -> Result { if expert >= 512 || !(1..=self.rows.len()).contains(&pairs.len()) { @@ -96,13 +73,9 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { } let mut previous = None; let mut actual = Vec::new(); - actual - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + actual.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; let mut origins = Vec::new(); - origins - .try_reserve_exact(pairs.len()) - .map_err(|_| Error::InputAllocation)?; + origins.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?; for pair in pairs { let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?; let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?; @@ -117,12 +90,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { actual.push(*pair); origins.push(Rc::clone(origin)); } - Ok(GroupOrigin { - owner: Rc::clone(&self.owner), - expert, - pairs: actual, - origins, - }) + Ok(GroupOrigin { owner: Rc::clone(&self.owner), expert, pairs: actual, origins }) } fn validate_group(&self, group: &GroupOrigin) -> Result<()> { if !Rc::ptr_eq(&self.owner, &group.owner) @@ -161,9 +129,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { // Genuine group row order is strictly ascending, so producer column // index remains its real inverse route mapping without raw buffer views. let mut selected = Vec::new(); - selected - .try_reserve_exact(group.pairs.len()) - .map_err(|_| Error::InputAllocation)?; + selected.try_reserve_exact(group.pairs.len()).map_err(|_| Error::InputAllocation)?; let mut pairs = group.pairs.iter().peekable(); for (row, packet) in self.packets.iter_mut().enumerate() { if pairs.peek().is_some_and(|pair| pair.row == row) { @@ -197,20 +163,32 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> { Ok(()) }) } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn finish_native_micro( - &self,cache:&mut MoeWeightCache<'ctx>, - finish:&mut super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, - cancelled:&mut impl FnMut()->bool, - )->Result>{ - let mut packets=Vec::new(); - packets.try_reserve_exact(self.rows.len()).map_err(|_|Error::InputAllocation)?; - for(index,packet)in self.packets.iter().enumerate(){ - validate_row(self.txn,self.binding,self.layer,index,&self.rows[index],&self.origins[index])?; - packet.complete(self.scope)?;packets.push(packet); + &self, + cache: &mut MoeWeightCache<'ctx>, + finish: &mut super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + let mut packets = Vec::new(); + packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; + for (index, packet) in self.packets.iter().enumerate() { + validate_row(self.txn, self.binding, self.layer, index, &self.rows[index], &self.origins[index])?; + packet.complete(self.scope)?; + packets.push(packet); } - super::prompt_finish::finish(self.context,self.binding,self.layer,self.rows, - self.txn,self.scope,&packets,cache,finish,cancelled) + super::prompt_finish::finish( + self.context, + self.binding, + self.layer, + self.rows, + self.txn, + self.scope, + &packets, + cache, + finish, + cancelled, + ) } pub(super) fn finish_row( &self, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs index addec783..5b66d1ca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch.rs @@ -15,12 +15,10 @@ use super::contract::{Dimension, Error, LayerId, Result, TokenLayer}; use super::gr::ResidualReady; use super::qsa_index::driver_error; use super::shared_expert_workspace::validate_descriptors; -use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrRole, ModelBinding, MoeWeightDescriptor, -}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, MoeWeightDescriptor}; use leleka_cuda_driver::{ - Context, DeviceBuffer, GdnGemm, GdnNativeFormat, MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, - MoePrefillBatch, MoeRouteBatch, + Context, DeviceBuffer, GdnGemm, GdnNativeFormat, MOE_BATCH_MAX_TOKENS, MOE_BATCH_SCRATCH_BYTES, MoePrefillBatch, + MoeRouteBatch, }; const MIXED: usize = 2560; @@ -118,13 +116,13 @@ mod impl_moeprefillresources; #[allow(unused_imports)] use impl_moeprefillresources::admit; #[allow(unused_imports)] -use impl_moeprefillresources::gate_up_format; -#[allow(unused_imports)] use impl_moeprefillresources::down_format; #[allow(unused_imports)] -pub(in crate::qwen_forward) use impl_moeprefillresources::validate_route_row; -#[allow(unused_imports)] use impl_moeprefillresources::f32_bytes; +#[allow(unused_imports)] +use impl_moeprefillresources::gate_up_format; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use impl_moeprefillresources::validate_route_row; #[path = "moe_prefill_batch/device_bytes_fn.rs"] mod device_bytes_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs index e2fd44ed..1f0360b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/device_bytes_fn.rs @@ -3,16 +3,11 @@ #[allow(unused_imports)] use super::*; - /// Device bytes one batched step allocates for `tokens` rows (without the persistent scratch / owner words and /// without the caller's `dm`). pub(super) fn device_bytes(tokens: usize, profile: MoeBf16Profile, combine: bool) -> Result { let images = tokens * MIXED * 2; - let lo = if profile == MoeBf16Profile::HighPlusLow { - images - } else { - 0 - }; + let lo = if profile == MoeBf16Profile::HighPlusLow { images } else { 0 }; [ tokens * MIXED * 4, // mixed (f32 upload) images, // mixed_h @@ -59,8 +54,7 @@ impl<'ctx> Buffers<'ctx> { sizes.push(tokens * MIXED * 4); } let mut pool = Vec::new(); - pool.try_reserve_exact(sizes.len()) - .map_err(|_| Error::InputAllocation)?; + pool.try_reserve_exact(sizes.len()).map_err(|_| Error::InputAllocation)?; for bytes in sizes { match context.allocate(bytes) { Ok(buffer) => pool.push(buffer), @@ -92,20 +86,10 @@ impl<'ctx> Buffers<'ctx> { pub(super) fn into_outputs( self, keep_weights: bool, - ) -> ( - ( - DeviceBuffer<'ctx>, - DeviceBuffer<'ctx>, - Option>, - Option>, - ), - Result<()>, - ) { - let (weights_out, weights_pool) = if keep_weights { - (Some(self.weights), None) - } else { - (None, Some(self.weights)) - }; + ) -> ((DeviceBuffer<'ctx>, DeviceBuffer<'ctx>, Option>, Option>), Result<()>) + { + let (weights_out, weights_pool) = + if keep_weights { (Some(self.weights), None) } else { (None, Some(self.weights)) }; let pool = [ Some(self.mixed), Some(self.mixed_h), @@ -121,10 +105,7 @@ impl<'ctx> Buffers<'ctx> { .into_iter() .flatten() .collect::>(); - ( - (self.shared, self.sg, self.bo, weights_out), - release_pool(pool), - ) + ((self.shared, self.sg, self.bo, weights_out), release_pool(pool)) } pub(super) fn release(self) -> Result<()> { let ((shared, sg, bo, _), internal) = self.into_outputs(false); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillresources.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillresources.rs index 63d800bd..1c4aadb6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillresources.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillresources.rs @@ -4,10 +4,7 @@ use super::*; impl<'ctx> MoePrefillResources<'ctx> { - pub(in crate::qwen_forward) fn new( - context: &'ctx Context<'ctx>, - profile: MoeBf16Profile, - ) -> Result { + pub(in crate::qwen_forward) fn new(context: &'ctx Context<'ctx>, profile: MoeBf16Profile) -> Result { admit(context, MOE_PREFILL_PERSISTENT_BYTES)?; let batch = context.moe_prefill_batch().map_err(driver_error)?; let scratch = match context.allocate(MOE_BATCH_SCRATCH_BYTES) { @@ -17,29 +14,20 @@ impl<'ctx> MoePrefillResources<'ctx> { return Err(driver_error(error)); } }; - Ok(Self { - context, - batch: Some(batch), - scratch: Some(scratch), - profile, - }) + Ok(Self { context, batch: Some(batch), scratch: Some(scratch), profile }) } pub(in crate::qwen_forward) fn validate_context(&self, context: &Context<'_>) -> Result<()> { if !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } - if context.is_poisoned() - || self.batch.as_ref().is_none_or(MoePrefillBatch::is_failed) - || self.scratch.is_none() + if context.is_poisoned() || self.batch.as_ref().is_none_or(MoePrefillBatch::is_failed) || self.scratch.is_none() { return Err(Error::CudaExecution); } Ok(()) } pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { - self.batch - .as_ref() - .map_or(0, MoePrefillBatch::allocated_bytes) + self.batch.as_ref().map_or(0, MoePrefillBatch::allocated_bytes) + self.scratch.as_ref().map_or(0, DeviceBuffer::len) } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { @@ -100,15 +88,8 @@ pub(super) fn down_format(key: MoeWeightDescriptor) -> Result { impl RouteRow { /// The consumer's origin fence: the row came from a genuine FFN read of `layer` under exactly this binding. - pub(in crate::qwen_forward) fn validate_origin( - &self, - binding: &BindingIdentity, - layer: LayerId, - ) -> Result<()> { - if !self.binding.matches(binding) - || self.origin != GrRole::Ffn(layer.get()) - || self.identity.layer() != layer - { + pub(in crate::qwen_forward) fn validate_origin(&self, binding: &BindingIdentity, layer: LayerId) -> Result<()> { + if !self.binding.matches(binding) || self.origin != GrRole::Ffn(layer.get()) || self.identity.layer() != layer { return Err(Error::IdentityMismatch); } Ok(()) @@ -143,13 +124,8 @@ impl<'ctx> MoeMicroProducts<'ctx> { (rows, release) } /// Shared expert output `[T][2560]` f32 and the shared scalar gate logits `[T]` f32. - pub(in crate::qwen_forward) fn shared( - &self, - ) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { - Ok(( - self.shared.as_ref().ok_or(Error::IdentityMismatch)?, - self.sg.as_ref().ok_or(Error::IdentityMismatch)?, - )) + pub(in crate::qwen_forward) fn shared(&self) -> Result<(&DeviceBuffer<'ctx>, &DeviceBuffer<'ctx>)> { + Ok((self.shared.as_ref().ok_or(Error::IdentityMismatch)?, self.sg.as_ref().ok_or(Error::IdentityMismatch)?)) } /// The combined `[T][2560]` output when the optional combine ran. pub(in crate::qwen_forward) fn combined(&self) -> Option<&DeviceBuffer<'ctx>> { @@ -160,14 +136,8 @@ impl<'ctx> MoeMicroProducts<'ctx> { } pub(super) fn close_inner(&mut self) -> Result<()> { let mut failure = None; - for buffer in [ - self.shared.take(), - self.sg.take(), - self.bo.take(), - self.route_weights.take(), - ] - .into_iter() - .flatten() + for buffer in + [self.shared.take(), self.sg.take(), self.bo.take(), self.route_weights.take()].into_iter().flatten() { if let Err(error) = buffer.release() { failure.get_or_insert(driver_error(error)); @@ -184,10 +154,7 @@ impl Drop for MoeMicroProducts<'_> { /// The same checks `route_with` applies to a CUDA route, on raw values: ids in range and distinct, weights /// finite, inside `[0, 1]` and non-increasing (equal weights are valid). -pub(in crate::qwen_forward) fn validate_route_row( - ids: &[i32; SELECTED], - weights: &[f32; SELECTED], -) -> Result<()> { +pub(in crate::qwen_forward) fn validate_route_row(ids: &[i32; SELECTED], weights: &[f32; SELECTED]) -> Result<()> { let mut seen = [false; EXPERTS]; for index in 0..SELECTED { let slot = usize::try_from(ids[index]).map_err(|_| Error::InvalidExpert)?; @@ -209,9 +176,7 @@ pub(in crate::qwen_forward) fn validate_route_row( pub(super) fn f32_bytes(values: &[f32]) -> Result> { let mut bytes = Vec::new(); - bytes - .try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(values.len().checked_mul(4).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs index de46efc1..4425a10a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/impl_moeprefillstage.rs @@ -3,14 +3,10 @@ #[allow(unused_imports)] use super::*; - impl MoePrefillStage { /// Exact per-window device owners; the genuine caller preflights cache /// headroom before acquiring immutable shared weights. - pub(in crate::qwen_forward) fn transient_bytes( - tokens: usize, - profile: MoeBf16Profile, - ) -> Result { + pub(in crate::qwen_forward) fn transient_bytes(tokens: usize, profile: MoeBf16Profile) -> Result { if !(1..=64).contains(&tokens) { return Err(Error::InvalidDimension); } @@ -38,33 +34,23 @@ impl MoePrefillStage { if tokens == 0 || tokens > MOE_BATCH_MAX_TOKENS { return Err(Error::IdentityMismatch); } - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if expected != layer { return Err(Error::IdentityMismatch); } - if binding.expert_count() != EXPERTS as u32 - || binding.expert_used_count() != SELECTED as u32 - { + if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { return Err(Error::InvalidDimension); } // The layer's router weights must be this binding's own (as in `route_from_ffn`). - let route_weights = binding - .moe_route_weights(layer.get()) - .map_err(|_| Error::IdentityMismatch)?; + let route_weights = binding.moe_route_weights(layer.get()).map_err(|_| Error::IdentityMismatch)?; if !route_weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } // Genuine reads only: origin, layer, and strictly consecutive positions. let mut host = Vec::new(); - host.try_reserve_exact(tokens * MIXED) - .map_err(|_| Error::InputAllocation)?; + host.try_reserve_exact(tokens * MIXED).map_err(|_| Error::InputAllocation)?; let mut identities: Vec = Vec::new(); - identities - .try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; + identities.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; for read in reads { read.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; let identity = read.identity(); @@ -106,8 +92,7 @@ impl MoePrefillStage { let profile = resources.profile; let with_combine = combine.is_some(); if let Some(input) = &combine - && (input.slot.len() != tokens * SELECTED - || input.dm.len() != tokens * SELECTED * MIXED * 4) + && (input.slot.len() != tokens * SELECTED || input.dm.len() != tokens * SELECTED * MIXED * 4) { return Err(Error::InvalidDimension); } @@ -116,21 +101,13 @@ impl MoePrefillStage { let mut buffers = Buffers::new(current, tokens, profile, with_combine)?; let operation = (|| -> Result { - buffers - .mixed - .copy_from(&mixed_bytes) - .map_err(driver_error)?; + buffers.mixed.copy_from(&mixed_bytes).map_err(driver_error)?; let MoePrefillResources { batch, scratch, .. } = &mut *resources; let batch = batch.as_mut().ok_or(Error::IdentityMismatch)?; let scratch = scratch.as_ref().ok_or(Error::IdentityMismatch)?; let mut prefix = batch.begin(tokens, gemm).map_err(driver_error)?; let program = (|| -> std::result::Result<(), leleka_cuda_driver::Error> { - prefix.pack_mixed( - &buffers.mixed, - &buffers.mixed_h, - &buffers.mixed_bf, - buffers.mixed_bf_lo.as_ref(), - )?; + prefix.pack_mixed(&buffers.mixed, &buffers.mixed_h, &buffers.mixed_bf, buffers.mixed_bf_lo.as_ref())?; prefix.route(router, &buffers.logits, &buffers.ids, &buffers.weights)?; prefix.shared_gate(gate_format, weights.buffers[0], scratch, &buffers.sgate)?; prefix.shared_up(up_format, weights.buffers[1], scratch, &buffers.sup)?; @@ -156,16 +133,14 @@ impl MoePrefillStage { } }; let mut rows = Vec::new(); - rows.try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; let assembled = (|| -> Result<()> { if route.ids.len() != tokens * SELECTED || route.weights.len() != tokens * SELECTED { return Err(Error::InvalidDimension); } for (index, identity) in identities.into_iter().enumerate() { let ids: [i32; SELECTED] = std::array::from_fn(|k| route.ids[index * SELECTED + k]); - let row_weights: [f32; SELECTED] = - std::array::from_fn(|k| route.weights[index * SELECTED + k]); + let row_weights: [f32; SELECTED] = std::array::from_fn(|k| route.weights[index * SELECTED + k]); validate_route_row(&ids, &row_weights)?; rows.push(RouteRow { binding: binding.identity(), @@ -183,13 +158,7 @@ impl MoePrefillStage { return Err(primary); } let ((shared, sg, bo, route_weights), internal) = buffers.into_outputs(!with_combine); - let products = MoeMicroProducts { - rows, - shared: Some(shared), - sg: Some(sg), - bo, - route_weights, - }; + let products = MoeMicroProducts { rows, shared: Some(shared), sg: Some(sg), bo, route_weights }; if let Err(error) = internal { drop(products); return Err(error); @@ -222,16 +191,11 @@ impl MoePrefillStage { if tokens == 0 || tokens > MOE_BATCH_MAX_TOKENS { return Err(Error::IdentityMismatch); } - let checked = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let checked = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(binding.layer_count()))?)?; if checked != layer { return Err(Error::IdentityMismatch); } - if binding.expert_count() != EXPERTS as u32 - || binding.expert_used_count() != SELECTED as u32 - { + if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { return Err(Error::InvalidDimension); } // The window's own origin: actual binding, FFN role of this layer, exactly the caller's rows. @@ -239,9 +203,7 @@ impl MoePrefillStage { if products.bo.is_some() || products.route_weights.is_none() { return Err(Error::IdentityMismatch); } - if combine.slot.len() != tokens * SELECTED - || combine.dm.len() != tokens * SELECTED * MIXED * 4 - { + if combine.slot.len() != tokens * SELECTED || combine.dm.len() != tokens * SELECTED * MIXED * 4 { return Err(Error::InvalidDimension); } let bytes = tokens * MIXED * 4; @@ -249,10 +211,7 @@ impl MoePrefillStage { let bo = current.allocate(bytes).map_err(driver_error)?; let operation = (|| -> Result<()> { let batch = resources.batch.as_mut().ok_or(Error::IdentityMismatch)?; - let route_weights = products - .route_weights - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let route_weights = products.route_weights.as_ref().ok_or(Error::IdentityMismatch)?; let shared = products.shared.as_ref().ok_or(Error::IdentityMismatch)?; let sg = products.sg.as_ref().ok_or(Error::IdentityMismatch)?; let mut prefix = batch.begin_combine(tokens, gemm).map_err(driver_error)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/tests.rs index 3e604eaf..f5208eb1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prefill_batch/tests.rs @@ -3,10 +3,7 @@ use super::*; fn descending() -> ([i32; SELECTED], [f32; SELECTED]) { - ( - std::array::from_fn(|i| (i * 7) as i32), - std::array::from_fn(|i| 0.2 - i as f32 * 0.01), - ) + (std::array::from_fn(|i| (i * 7) as i32), std::array::from_fn(|i| 0.2 - i as f32 * 0.01)) } #[test] @@ -17,37 +14,22 @@ fn a_route_row_needs_distinct_in_range_ids_and_finite_ordered_unit_weights() { assert!(validate_route_row(&ids, &[0.1; SELECTED]).is_ok()); let mut duplicate = ids; duplicate[3] = duplicate[1]; - assert_eq!( - validate_route_row(&duplicate, &weights), - Err(Error::InvalidExpert) - ); + assert_eq!(validate_route_row(&duplicate, &weights), Err(Error::InvalidExpert)); let mut high = ids; high[0] = EXPERTS as i32; - assert_eq!( - validate_route_row(&high, &weights), - Err(Error::InvalidExpert) - ); + assert_eq!(validate_route_row(&high, &weights), Err(Error::InvalidExpert)); let mut negative = ids; negative[0] = -1; - assert_eq!( - validate_route_row(&negative, &weights), - Err(Error::InvalidExpert) - ); + assert_eq!(validate_route_row(&negative, &weights), Err(Error::InvalidExpert)); let mut nan = weights; nan[2] = f32::NAN; assert_eq!(validate_route_row(&ids, &nan), Err(Error::NonFinite)); let mut over = weights; over[0] = 1.5; - assert_eq!( - validate_route_row(&ids, &over), - Err(Error::InvalidDimension) - ); + assert_eq!(validate_route_row(&ids, &over), Err(Error::InvalidDimension)); let mut rising = weights; rising.swap(0, 9); - assert_eq!( - validate_route_row(&ids, &rising), - Err(Error::InvalidDimension) - ); + assert_eq!(validate_route_row(&ids, &rising), Err(Error::InvalidDimension)); } #[test] @@ -85,16 +67,10 @@ fn device_bytes_follow_the_prompt_path_buffer_set() { assert_eq!(combined - high, 64 * MIXED * 4); // 64 rows: mixed 655,360 + images 2 x 327,680 + logits 131,072 + ids/weights 2 x 2,560 // + sgate/sup 2 x 163,840 + H 81,920 + shared 655,360 + sg 256. - assert_eq!( - high, - 655_360 + 2 * 327_680 + 131_072 + 2 * 2_560 + 2 * 163_840 + 81_920 + 655_360 + 256 - ); + assert_eq!(high, 655_360 + 2 * 327_680 + 131_072 + 2 * 2_560 + 2 * 163_840 + 81_920 + 655_360 + 256); } #[test] fn f32_staging_is_little_endian() { - assert_eq!( - f32_bytes(&[1.0, -2.0]).unwrap(), - [0, 0, 128, 63, 0, 0, 0, 192] - ); + assert_eq!(f32_bytes(&[1.0, -2.0]).unwrap(), [0, 0, 128, 63, 0, 0, 0, 192]); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs index d380c55d..7a07d497 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_prompt_finish.rs @@ -1,8 +1,8 @@ //! Closed native prompt finish over actual complete, unweighted Down packets. -use super::*; use super::super::super::dense_weight_cache::DenseWeightCache; use super::super::super::moe_prefill_batch::{CombineInput, MoeMicroProducts, MoePrefillStage}; use super::super::moe_down::ResidentPackedDown; +use super::*; pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> { pub(super) products: &'loan mut MoeMicroProducts<'ctx>, @@ -11,15 +11,24 @@ pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> { #[allow(clippy::too_many_arguments)] pub(super) fn finish<'ctx>( - context: &'ctx Context<'ctx>, binding: &ModelBinding, layer: LayerId, - rows: &[ChunkFfnRow], txn: &QwenChunkTxn<'_, 'ctx>, scope: &DownScope<'ctx>, - packets: &[&ResidentPackedDown<'ctx>], cache: &mut MoeWeightCache<'ctx>, + context: &'ctx Context<'ctx>, + binding: &ModelBinding, + layer: LayerId, + rows: &[ChunkFfnRow], + txn: &QwenChunkTxn<'_, 'ctx>, + scope: &DownScope<'ctx>, + packets: &[&ResidentPackedDown<'ctx>], + cache: &mut MoeWeightCache<'ctx>, finish: &mut NativePromptFinish<'_, 'ctx, '_>, cancelled: &mut impl FnMut() -> bool, ) -> Result> { - if rows.len() != txn.micro_len()? || rows.len() != packets.len() - || !(1..=64).contains(&rows.len()) || !std::ptr::eq(context, txn.context()?) - { return Err(Error::IdentityMismatch); } + if rows.len() != txn.micro_len()? + || rows.len() != packets.len() + || !(1..=64).contains(&rows.len()) + || !std::ptr::eq(context, txn.context()?) + { + return Err(Error::IdentityMismatch); + } cache.validate(binding, context)?; finish.dense.retained_context(binding, context)?; let mut expected = Vec::new(); @@ -38,59 +47,79 @@ pub(super) fn finish<'ctx>( for slot in 0..K { if route.ids[slot] != row.row().route.experts()[slot].get() as i32 || route.weights[slot].to_bits() != row.row().route.weights()[slot].get().to_bits() - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } } } - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } // Both actual packet storage and the produced shared/route owners already // exist. Reserve the simultaneous gathered Dm and whole Bo before allocation. let dm_bytes = rows.len().checked_mul(K * N * 4).ok_or(Error::Overflow)?; let extra = dm_bytes.checked_add(rows.len() * N * 4).ok_or(Error::Overflow)?; cache.reserve_mmq_transient(binding, context, extra)?; - let needed = extra.checked_add(super::super::super::moe_weight_cache::WORKING_RESERVE) - .ok_or(Error::Overflow)?; + let needed = extra.checked_add(super::super::super::moe_weight_cache::WORKING_RESERVE).ok_or(Error::Overflow)?; if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) || context.memory_info().map_err(driver_error)?.0 < needed - { return Err(Error::InputAllocation); } + { + return Err(Error::InputAllocation); + } let mut dm = scope.allocate(dm_bytes)?; let operation = (|| { - let mut sources=Vec::new(); - sources.try_reserve_exact(packets.len()).map_err(|_|Error::InputAllocation)?; - for (index,packet) in packets.iter().enumerate() { - if cancelled() {return Err(Error::Unsupported(Stage::Executor));} - txn.validate_ffn_row(txn.micro_row_index(index)?,layer,&rows[index])?; + let mut sources = Vec::new(); + sources.try_reserve_exact(packets.len()).map_err(|_| Error::InputAllocation)?; + for (index, packet) in packets.iter().enumerate() { + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + txn.validate_ffn_row(txn.micro_row_index(index)?, layer, &rows[index])?; sources.push(packet.completed_buffer(scope)?); } - context.copy_moe_prompt_packets(&sources,dm.buffer_mut()?).map_err(driver_error)?; - for (index,packet) in packets.iter().enumerate() { + context.copy_moe_prompt_packets(&sources, dm.buffer_mut()?).map_err(driver_error)?; + for (index, packet) in packets.iter().enumerate() { packet.complete(scope)?; - txn.validate_ffn_row(txn.micro_row_index(index)?,layer,&rows[index])?; + txn.validate_ffn_row(txn.micro_row_index(index)?, layer, &rows[index])?; + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); } - if cancelled() {return Err(Error::Unsupported(Stage::Executor));} let mut slots = Vec::new(); slots.try_reserve_exact(rows.len() * K).map_err(|_| Error::InputAllocation)?; for slot in 0..rows.len() * K { slots.push(i32::try_from(slot).map_err(|_| Error::Overflow)?); } let mut resources = cache.native_prefill_resources(binding, context)?; - let mut workspace = finish.dense.native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; + let mut workspace = finish.dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; let gemm = workspace.gdn_gemm().map_err(driver_error)?; - MoePrefillStage::combine_micro(binding, layer, &expected, context, - finish.products, CombineInput { dm: dm.buffer()?, slot: &slots }, - &mut resources, &gemm)?; + MoePrefillStage::combine_micro( + binding, + layer, + &expected, + context, + finish.products, + CombineInput { dm: dm.buffer()?, slot: &slots }, + &mut resources, + &gemm, + )?; let values = download_f32(finish.products.combined().ok_or(Error::IdentityMismatch)?, rows.len() * N)?; let mut outputs = Vec::new(); outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?; for (index, row) in rows.iter().enumerate() { - if cancelled() { return Err(Error::Unsupported(Stage::Executor)); } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } txn.validate_ffn_row(txn.micro_row_index(index)?, layer, row)?; let start = index * N; let mut actual = Vec::new(); actual.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?; actual.extend_from_slice(&values[start..start + N]); - outputs.push(ExpertReady::from_completed(binding.identity(), - row.row().route.identity(), actual.into_boxed_slice())?); + outputs.push(ExpertReady::from_completed( + binding.identity(), + row.row().route.identity(), + actual.into_boxed_slice(), + )?); } Ok(outputs) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs index d3e850df..a8524d0d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route.rs @@ -1,15 +1,11 @@ //! STRA-166 fixed CUDA router and its producer-owned opaque products. #![allow(dead_code)] -use super::contract::{ - Dimension, Error, ExpertId, FiniteF32, LayerId, Position, Result, Stage, TokenId, TokenLayer, -}; +use super::contract::{Dimension, Error, ExpertId, FiniteF32, LayerId, Position, Result, Stage, TokenId, TokenLayer}; use super::dense_weight_cache::DenseWeightCache; use super::gr::ResidualReady; use super::session::QwenStepTxn; -use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrRole, InputBindingError, ModelBinding, MoeRouteWeights, -}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, InputBindingError, ModelBinding, MoeRouteWeights}; use leleka_cuda_driver::{Bf16ProjectionShape, Context, Error as DriverError}; const EXPERTS: usize = 512; @@ -48,14 +44,8 @@ mod projection_tests { #[test] fn projection_budget_counts_live_charge_before_weights_or_cuda() { assert_eq!(admit_projection_budget(1024, 1024 + 338176), Ok(())); - assert_eq!( - admit_projection_budget(1024, 1024 + 338175), - Err(Error::InputAllocation) - ); - assert_eq!( - admit_projection_budget(usize::MAX, usize::MAX), - Err(Error::Overflow) - ); + assert_eq!(admit_projection_budget(1024, 1024 + 338175), Err(Error::InputAllocation)); + assert_eq!(admit_projection_budget(usize::MAX, usize::MAX), Err(Error::Overflow)); } #[test] fn projection_tiles_preserve_all_row_positions_without_host_math() { @@ -73,19 +63,11 @@ mod projection_tests { } #[test] fn projection_late_tile_failure_returns_no_array_and_stops() { - for error in [ - Error::InputRead, - Error::InputAllocation, - Error::CudaExecution, - ] { + for error in [Error::InputRead, Error::InputAllocation, Error::CudaExecution] { let mut calls = 0; let result = collect_logits(|first| { calls += 1; - if first == 384 { - Err(error) - } else { - Ok([1.0; TILE_ROWS]) - } + if first == 384 { Err(error) } else { Ok([1.0; TILE_ROWS]) } }); assert_eq!(result, Err(error)); assert_eq!(calls, 7); @@ -103,10 +85,7 @@ mod projection_tests { }); assert_eq!(result, Err(Error::NonFinite)); } - assert_eq!( - validate_activation(&[0.0; COLUMNS - 1]), - Err(Error::InvalidDimension) - ); + assert_eq!(validate_activation(&[0.0; COLUMNS - 1]), Err(Error::InvalidDimension)); let mut values = [0.0; COLUMNS]; values[2559] = f32::NAN; assert_eq!(validate_activation(&values), Err(Error::NonFinite)); @@ -115,29 +94,29 @@ mod projection_tests { mod impl_routerlogits; #[allow(unused_imports)] -pub(super) use impl_routerlogits::validate_activation; -#[allow(unused_imports)] use impl_routerlogits::admit_projection_budget; +#[allow(unused_imports)] +pub(super) use impl_routerlogits::validate_activation; mod project_logits_fn; #[allow(unused_imports)] -use project_logits_fn::project_logits; -#[allow(unused_imports)] -use project_logits_fn::collect_logits; -#[allow(unused_imports)] use project_logits_fn::binding_error; #[allow(unused_imports)] -use project_logits_fn::validate_request; +use project_logits_fn::collect_logits; #[allow(unused_imports)] -pub(super) use project_logits_fn::validate_logits; +use project_logits_fn::project_logits; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unused_imports)] +pub(super) use project_logits_fn::route_batch_row; #[allow(unused_imports)] use project_logits_fn::route_with; #[allow(unused_imports)] use project_logits_fn::routed_from_raw; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] -pub(super) use project_logits_fn::route_batch_row; +pub(super) use project_logits_fn::validate_logits; +#[allow(unused_imports)] +use project_logits_fn::validate_request; mod run_cuda_fn; #[allow(unused_imports)] -use run_cuda_fn::run_cuda; -#[allow(unused_imports)] pub(super) use run_cuda_fn::map_driver_error; +#[allow(unused_imports)] +use run_cuda_fn::run_cuda; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs index edb02400..c9d406d6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/impl_routerlogits.rs @@ -14,11 +14,7 @@ impl RouterLogits { values: [f32; EXPERTS], ) -> Result { validate_logits(&values)?; - Ok(Self { - binding: binding.identity(), - identity: TokenLayer::new(token, position, layer), - values, - }) + Ok(Self { binding: binding.identity(), identity: TokenLayer::new(token, position, layer), values }) } #[cfg(test)] @@ -30,11 +26,7 @@ impl RouterLogits { values: [f32; EXPERTS], ) -> Result { validate_logits(&values)?; - Ok(Self { - binding, - identity: TokenLayer::new(token, position, layer), - values, - }) + Ok(Self { binding, identity: TokenLayer::new(token, position, layer), values }) } } impl RoutedExperts { @@ -44,12 +36,7 @@ impl RoutedExperts { experts: [ExpertId; SELECTED], weights: [FiniteF32; SELECTED], ) -> Self { - Self { - binding, - identity, - experts, - weights, - } + Self { binding, identity, experts, weights } } pub(in super::super) fn identity(&self) -> TokenLayer { @@ -64,21 +51,12 @@ impl RoutedExperts { &self.weights } - pub(in super::super) fn validate_for( - &self, - token: TokenId, - position: Position, - layer: LayerId, - ) -> Result<()> { + pub(in super::super) fn validate_for(&self, token: TokenId, position: Position, layer: LayerId) -> Result<()> { self.identity.validate(token, position, layer) } pub(in super::super) fn validate_binding(&self, binding: &BindingIdentity) -> Result<()> { - if self.binding.matches(binding) { - Ok(()) - } else { - Err(Error::IdentityMismatch) - } + if self.binding.matches(binding) { Ok(()) } else { Err(Error::IdentityMismatch) } } } @@ -95,9 +73,7 @@ impl MoeRouteStage { if layer.get() >= binding.layer_count() { return Err(Error::InvalidLayer); } - if binding.expert_count() != EXPERTS as u32 - || binding.expert_used_count() != SELECTED as u32 - { + if binding.expert_count() != EXPERTS as u32 || binding.expert_used_count() != SELECTED as u32 { return Err(Error::InvalidDimension); } residual.validate_origin(&binding.identity(), GrRole::Ffn(layer.get()))?; @@ -107,9 +83,7 @@ impl MoeRouteStage { validate_activation(residual.mixed())?; let context = txn.cuda_context()?; admit_projection_budget(context.allocated_bytes(), context.budget_bytes())?; - let weights = binding - .moe_route_weights(layer.get()) - .map_err(binding_error)?; + let weights = binding.moe_route_weights(layer.get()).map_err(binding_error)?; if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } @@ -121,44 +95,20 @@ impl MoeRouteStage { if super::super::oracle_capture::enabled() { super::super::oracle_capture::stage_current("router_logits", &values)?; } - let logits = RouterLogits::from_preceding( - binding, - identity.token(), - identity.position(), - layer, - values, - )?; + let logits = RouterLogits::from_preceding(binding, identity.token(), identity.position(), layer, values)?; let current = validate_request(binding, layer, &logits, identity.token(), txn)?; - let routed = route_with( - binding.identity(), - binding.expert_count(), - &logits, - current, - |values| lease.route(values), - )?; + let routed = + route_with(binding.identity(), binding.expert_count(), &logits, current, |values| lease.route(values))?; lease.complete()?; return Ok(routed); } - let values = project_logits( - context, - binding, - &weights, - residual.mixed(), - layer.get(), - cache, - )?; + let values = project_logits(context, binding, &weights, residual.mixed(), layer.get(), cache)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if super::super::oracle_capture::enabled() { super::super::oracle_capture::stage_current("router_logits", &values)?; } - let logits = RouterLogits::from_preceding( - binding, - identity.token(), - identity.position(), - layer, - values, - )?; + let logits = RouterLogits::from_preceding(binding, identity.token(), identity.position(), layer, values)?; Self::route(binding, layer, &logits, identity.token(), txn) } @@ -174,13 +124,7 @@ impl MoeRouteStage { ) -> Result { let identity = validate_request(binding, layer, logits, token, txn)?; let context = txn.cuda_context()?; - route_with( - binding.identity(), - binding.expert_count(), - logits, - identity, - |values| run_cuda(context, values), - ) + route_with(binding.identity(), binding.expert_count(), logits, identity, |values| run_cuda(context, values)) } } @@ -195,9 +139,7 @@ pub(in super::super) fn validate_activation(values: &[f32]) -> Result<()> { } pub(super) fn admit_projection_budget(allocated: usize, budget: usize) -> Result<()> { - let charge = allocated - .checked_add(PROJECTION_BYTES) - .ok_or(Error::Overflow)?; + let charge = allocated.checked_add(PROJECTION_BYTES).ok_or(Error::Overflow)?; if charge > budget { return Err(Error::InputAllocation); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs index ec9f8206..f9e3a4cb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/project_logits_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn project_logits( context: &Context<'_>, binding: &ModelBinding, @@ -13,43 +12,24 @@ pub(super) fn project_logits( cache: Option<&DenseWeightCache<'_>>, ) -> Result<[f32; EXPERTS]> { let mut input_bytes = [0u8; COLUMNS * 4]; - for (bytes, value) in input_bytes - .as_chunks_mut::<4>() - .0 - .iter_mut() - .zip(activation) - { + for (bytes, value) in input_bytes.as_chunks_mut::<4>().0.iter_mut().zip(activation) { *bytes = value.to_bits().to_le_bytes(); } - let mut input = context - .allocate(input_bytes.len()) - .map_err(map_driver_error)?; + let mut input = context.allocate(input_bytes.len()).map_err(map_driver_error)?; input.copy_from(&input_bytes).map_err(map_driver_error)?; let mut owned = None; let matrix = if let Some(cache) = cache { cache.router(binding, layer)? } else { - let block = binding - .moe_route_matrix_block(weights, 0, EXPERTS) - .map_err(binding_error)?; - let mut b = context - .allocate(block.bytes().len()) - .map_err(map_driver_error)?; + let block = binding.moe_route_matrix_block(weights, 0, EXPERTS).map_err(binding_error)?; + let mut b = context.allocate(block.bytes().len()).map_err(map_driver_error)?; b.copy_from(block.bytes()).map_err(map_driver_error)?; owned = Some(b); owned.as_ref().ok_or(Error::IdentityMismatch)? }; let mut output = context.allocate(EXPERTS * 4).map_err(map_driver_error)?; context - .bf16_f32( - matrix, - &input, - &mut output, - Bf16ProjectionShape { - rows: EXPERTS, - columns: COLUMNS, - }, - ) + .bf16_f32(matrix, &input, &mut output, Bf16ProjectionShape { rows: EXPERTS, columns: COLUMNS }) .map_err(map_driver_error)?; let mut bytes = [0u8; EXPERTS * 4]; output.copy_to(&mut bytes).map_err(map_driver_error)?; @@ -58,20 +38,13 @@ pub(super) fn project_logits( v.release().map_err(map_driver_error)?; } input.release().map_err(map_driver_error)?; - let values = std::array::from_fn(|i| { - f32::from_le_bytes( - bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed router output"), - ) - }); + let values = + std::array::from_fn(|i| f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("fixed router output"))); validate_logits(&values)?; Ok(values) } -pub(super) fn collect_logits( - mut tile: impl FnMut(usize) -> Result<[f32; TILE_ROWS]>, -) -> Result<[f32; EXPERTS]> { +pub(super) fn collect_logits(mut tile: impl FnMut(usize) -> Result<[f32; TILE_ROWS]>) -> Result<[f32; EXPERTS]> { let mut values = [0.0; EXPERTS]; for first in (0..EXPERTS).step_by(TILE_ROWS) { let rows = tile(first)?; @@ -187,7 +160,6 @@ pub(super) fn routed_from_raw( Ok(RoutedExperts::new(binding, identity, ids, weights)) } - /// One row of the Original whole-window router (`MoePrefillStage::route_shared_micro`): the genuine FFN read's /// identity and its raw top-10, checked by exactly the checks of a per-row CUDA route. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -204,11 +176,5 @@ pub(in super::super) fn route_batch_row( if binding.expert_count() != EXPERTS as u32 { return Err(Error::InvalidDimension); } - routed_from_raw( - binding.identity(), - binding.expert_count(), - row.identity, - row.ids, - row.weights, - ) + routed_from_raw(binding.identity(), binding.expert_count(), row.identity, row.ids, row.weights) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/run_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/run_cuda_fn.rs index 4b78b67f..0ccc6f42 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/run_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/run_cuda_fn.rs @@ -3,18 +3,9 @@ #[allow(unused_imports)] use super::*; - -pub(super) fn run_cuda( - context: &Context<'_>, - values: &[f32; EXPERTS], -) -> Result<([i32; SELECTED], [f32; SELECTED])> { +pub(super) fn run_cuda(context: &Context<'_>, values: &[f32; EXPERTS]) -> Result<([i32; SELECTED], [f32; SELECTED])> { let mut logits_bytes = [0_u8; LOGITS_BYTES]; - for (chunk, value) in logits_bytes - .as_chunks_mut::<{ std::mem::size_of::() }>() - .0 - .iter_mut() - .zip(values) - { + for (chunk, value) in logits_bytes.as_chunks_mut::<{ std::mem::size_of::() }>().0.iter_mut().zip(values) { chunk.copy_from_slice(&value.to_ne_bytes()); } @@ -23,18 +14,12 @@ pub(super) fn run_cuda( let mut weights_buffer = context.allocate(WEIGHTS_BYTES).map_err(map_driver_error)?; input.copy_from(&logits_bytes).map_err(map_driver_error)?; - context - .qwen_route_top10(&input, &mut ids_buffer, &mut weights_buffer) - .map_err(map_driver_error)?; + context.qwen_route_top10(&input, &mut ids_buffer, &mut weights_buffer).map_err(map_driver_error)?; let mut ids_bytes = [0_u8; IDS_BYTES]; let mut weights_bytes = [0_u8; WEIGHTS_BYTES]; - ids_buffer - .copy_to(&mut ids_bytes) - .map_err(map_driver_error)?; - weights_buffer - .copy_to(&mut weights_bytes) - .map_err(map_driver_error)?; + ids_buffer.copy_to(&mut ids_bytes).map_err(map_driver_error)?; + weights_buffer.copy_to(&mut weights_bytes).map_err(map_driver_error)?; // Explicit releases are part of success: a cleanup/restoration failure // withholds the host result. On an earlier error, Drop remains best-effort @@ -45,19 +30,11 @@ pub(super) fn run_cuda( let ids = std::array::from_fn(|index| { let start = index * std::mem::size_of::(); - i32::from_ne_bytes( - ids_bytes[start..start + 4] - .try_into() - .expect("fixed ID extent"), - ) + i32::from_ne_bytes(ids_bytes[start..start + 4].try_into().expect("fixed ID extent")) }); let weights = std::array::from_fn(|index| { let start = index * std::mem::size_of::(); - f32::from_ne_bytes( - weights_bytes[start..start + 4] - .try_into() - .expect("fixed weight extent"), - ) + f32::from_ne_bytes(weights_bytes[start..start + 4].try_into().expect("fixed weight extent")) }); Ok((ids, weights)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/tests.rs index aee947da..c4818cf0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_route/tests.rs @@ -29,9 +29,7 @@ fn route_fixture( weights: [f32; SELECTED], ) -> Result { let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), values)?; - route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| { - Ok((ids, weights)) - }) + route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| Ok((ids, weights))) } #[test] @@ -41,25 +39,14 @@ fn typed_result_preserves_independent_tie_order_and_weights() { let expected = independent_reference::reference(&values).unwrap(); let routed = route_fixture(binding.clone(), values, expected.ids, expected.weights).unwrap(); - assert_eq!( - (*routed.experts()).map(ExpertId::get), - expected.ids.map(|id| id as u32) - ); + assert_eq!((*routed.experts()).map(ExpertId::get), expected.ids.map(|id| id as u32)); for (actual, expected) in routed.weights().iter().zip(expected.weights) { assert_eq!(actual.get().to_bits(), expected.to_bits()); } assert_eq!(routed.validate_binding(&binding), Ok(())); - routed - .validate_for(token(7), position(0), layer(3)) - .unwrap(); - assert_eq!( - routed.validate_for(token(7), position(0), layer(4)), - Err(Error::IdentityMismatch) - ); - assert_eq!( - routed.validate_binding(&BindingIdentity::test_identity()), - Err(Error::IdentityMismatch) - ); + routed.validate_for(token(7), position(0), layer(3)).unwrap(); + assert_eq!(routed.validate_for(token(7), position(0), layer(4)), Err(Error::IdentityMismatch)); + assert_eq!(routed.validate_binding(&BindingIdentity::test_identity()), Err(Error::IdentityMismatch)); } #[test] @@ -69,30 +56,16 @@ fn dominant_route_keeps_zero_weights_and_exact_id_order() { values[511] = 1000.0; let expected = independent_reference::reference(&values).unwrap(); let routed = route_fixture(binding, values, expected.ids, expected.weights).unwrap(); - assert_eq!( - (*routed.experts()).map(ExpertId::get), - [511, 0, 1, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!((*routed.experts()).map(ExpertId::get), [511, 0, 1, 2, 3, 4, 5, 6, 7, 8]); assert_eq!(routed.weights()[0].get(), 1.0); - assert!( - routed.weights()[1..] - .iter() - .all(|weight| weight.get() == 0.0) - ); + assert!(routed.weights()[1..].iter().all(|weight| weight.get() == 0.0)); } #[test] fn wrong_binding_or_token_layer_identity_refuses_before_dispatch() { let binding = BindingIdentity::test_identity(); let other = BindingIdentity::test_identity(); - let logits = RouterLogits::fixture( - binding.clone(), - token(7), - position(0), - layer(3), - [0.0; EXPERTS], - ) - .unwrap(); + let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), [0.0; EXPERTS]).unwrap(); let mut called = false; let wrong_binding = route_with(other, EXPERTS as u32, &logits, logits.identity, |_| { called = true; @@ -101,13 +74,10 @@ fn wrong_binding_or_token_layer_identity_refuses_before_dispatch() { assert_eq!(wrong_binding.err(), Some(Error::IdentityMismatch)); assert!(!called); - let mismatched = route_with( - binding, - EXPERTS as u32, - &logits, - TokenLayer::new(token(8), position(0), layer(3)), - |_| panic!("identity mismatch must fail before CUDA dispatch"), - ); + let mismatched = + route_with(binding, EXPERTS as u32, &logits, TokenLayer::new(token(8), position(0), layer(3)), |_| { + panic!("identity mismatch must fail before CUDA dispatch") + }); assert_eq!(mismatched.err(), Some(Error::IdentityMismatch)); } @@ -117,24 +87,15 @@ fn malformed_ids_and_duplicate_experts_are_rejected() { let values = [0.0; EXPERTS]; let mut ids = base_ids(); ids[0] = -1; - assert_eq!( - route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(), - Some(Error::InvalidExpert) - ); + assert_eq!(route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(), Some(Error::InvalidExpert)); let mut ids = base_ids(); ids[9] = 512; - assert_eq!( - route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(), - Some(Error::InvalidExpert) - ); + assert_eq!(route_fixture(binding.clone(), values, ids, [0.1; SELECTED]).err(), Some(Error::InvalidExpert)); let mut ids = base_ids(); ids[9] = ids[0]; - assert_eq!( - route_fixture(binding, values, ids, [0.1; SELECTED]).err(), - Some(Error::InvalidExpert) - ); + assert_eq!(route_fixture(binding, values, ids, [0.1; SELECTED]).err(), Some(Error::InvalidExpert)); } #[test] @@ -143,10 +104,7 @@ fn nonfinite_or_out_of_range_weights_are_never_published() { for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { let mut weights = [0.1; SELECTED]; weights[4] = invalid; - assert_eq!( - route_fixture(binding.clone(), [0.0; EXPERTS], base_ids(), weights).err(), - Some(Error::NonFinite) - ); + assert_eq!(route_fixture(binding.clone(), [0.0; EXPERTS], base_ids(), weights).err(), Some(Error::NonFinite)); } for invalid in [-f32::MIN_POSITIVE, 1.0 + f32::EPSILON] { let mut weights = [0.1; SELECTED]; @@ -161,14 +119,7 @@ fn nonfinite_or_out_of_range_weights_are_never_published() { #[test] fn invalid_topology_and_logits_fail_before_dispatch() { let binding = BindingIdentity::test_identity(); - let logits = RouterLogits::fixture( - binding.clone(), - token(7), - position(0), - layer(3), - [0.0; EXPERTS], - ) - .unwrap(); + let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), [0.0; EXPERTS]).unwrap(); let mut called = false; assert_eq!( route_with(binding.clone(), 511, &logits, logits.identity, |_| { @@ -191,60 +142,24 @@ fn invalid_topology_and_logits_fail_before_dispatch() { #[test] fn driver_failure_never_returns_a_partial_route() { let binding = BindingIdentity::test_identity(); - let logits = RouterLogits::fixture( - binding.clone(), - token(7), - position(0), - layer(3), - [0.0; EXPERTS], - ) - .unwrap(); - let result = route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| { - Err(Error::CudaExecution) - }); + let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), [0.0; EXPERTS]).unwrap(); + let result = route_with(binding, EXPERTS as u32, &logits, logits.identity, |_| Err(Error::CudaExecution)); assert!(matches!(result, Err(Error::CudaExecution))); } #[test] fn fixed_driver_errors_map_to_closed_runtime_categories() { + assert_eq!(map_driver_error(DriverError::UnsupportedQwenOperation), Error::Unsupported(Stage::MoeRoute)); + assert_eq!(map_driver_error(DriverError::InvalidQwenShape), Error::InvalidDimension); assert_eq!( - map_driver_error(DriverError::UnsupportedQwenOperation), - Error::Unsupported(Stage::MoeRoute) - ); - assert_eq!( - map_driver_error(DriverError::InvalidQwenShape), + map_driver_error(DriverError::ShapeMismatch { expected: LOGITS_BYTES, actual: LOGITS_BYTES - 4 }), Error::InvalidDimension ); - assert_eq!( - map_driver_error(DriverError::ShapeMismatch { - expected: LOGITS_BYTES, - actual: LOGITS_BYTES - 4, - }), - Error::InvalidDimension - ); - assert_eq!( - map_driver_error(DriverError::ContextMismatch), - Error::IdentityMismatch - ); - assert_eq!( - map_driver_error(DriverError::HostAllocation), - Error::InputAllocation - ); - assert_eq!( - map_driver_error(DriverError::BudgetExceeded), - Error::InputAllocation - ); - assert_eq!( - map_driver_error(DriverError::Driver { - operation: "synthetic", - code: 7, - }), - Error::CudaExecution - ); - assert_eq!( - map_driver_error(DriverError::ContextPoisoned), - Error::CudaExecution - ); + assert_eq!(map_driver_error(DriverError::ContextMismatch), Error::IdentityMismatch); + assert_eq!(map_driver_error(DriverError::HostAllocation), Error::InputAllocation); + assert_eq!(map_driver_error(DriverError::BudgetExceeded), Error::InputAllocation); + assert_eq!(map_driver_error(DriverError::Driver { operation: "synthetic", code: 7 }), Error::CudaExecution); + assert_eq!(map_driver_error(DriverError::ContextPoisoned), Error::CudaExecution); } #[test] @@ -258,30 +173,19 @@ fn returned_rank_weights_refuse_increases_and_preserve_equal_zero_order() { values[3] = 0.25; values[511] = -0.5; let input_bits = values.map(f32::to_bits); - let logits = - RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), values).unwrap(); + let logits = RouterLogits::fixture(binding.clone(), token(7), position(0), layer(3), values).unwrap(); let identity = logits.identity; for weights in [ - [ - 0.125, 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, - ], - [ - 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0, 0.0, 0.0, 0.125, - ], + [0.125, 0.25, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125], + [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0, 0.0, 0.0, 0.125], ] { let mut calls = 0; - let result = route_with( - binding.clone(), - EXPERTS as u32, - &logits, - identity, - |input| { - calls += 1; - assert_eq!(input.map(f32::to_bits), input_bits); - Ok((ids, weights)) - }, - ); + let result = route_with(binding.clone(), EXPERTS as u32, &logits, identity, |input| { + calls += 1; + assert_eq!(input.map(f32::to_bits), input_bits); + Ok((ids, weights)) + }); assert!(matches!(result, Err(Error::InvalidDimension))); assert_eq!(calls, 1); assert_eq!(logits.values.map(f32::to_bits), input_bits); @@ -290,32 +194,21 @@ fn returned_rank_weights_refuse_increases_and_preserve_equal_zero_order() { } for weights in [ - [ - 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.0, -0.0, - ], + [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.0, -0.0], [0.1; SELECTED], [0.0; SELECTED], [-0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0], ] { let mut calls = 0; - let routed = route_with( - binding.clone(), - EXPERTS as u32, - &logits, - identity, - |input| { - calls += 1; - assert_eq!(input.map(f32::to_bits), input_bits); - Ok((ids, weights)) - }, - ) + let routed = route_with(binding.clone(), EXPERTS as u32, &logits, identity, |input| { + calls += 1; + assert_eq!(input.map(f32::to_bits), input_bits); + Ok((ids, weights)) + }) .unwrap(); assert_eq!(calls, 1); assert_eq!(routed.experts().map(ExpertId::get), ids.map(|id| id as u32)); - assert_eq!( - routed.weights().map(|weight| weight.get().to_bits()), - weights.map(f32::to_bits) - ); + assert_eq!(routed.weights().map(|weight| weight.get().to_bits()), weights.map(f32::to_bits)); assert_eq!(routed.identity(), identity); assert_eq!(routed.validate_binding(&binding), Ok(())); assert_eq!(logits.values.map(f32::to_bits), input_bits); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs index 311d3db7..f08bb4ae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache.rs @@ -2,12 +2,12 @@ use super::contract::{Error, Result}; use super::qsa_index::{binding_error, driver_error}; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, ModelBinding, MoeExpertSelection, MoeExpertWeights, MoeMatrixRole, - MoeWeightDescriptor, MtpKind, MtpRole, + BindingIdentity, ModelBinding, MoeExpertSelection, MoeExpertWeights, MoeMatrixRole, MoeWeightDescriptor, MtpKind, + MtpRole, }; use leleka_cuda_driver::{ - Context, DeviceBuffer, MmqFormat, MmqWeights, MmqWorkspace, MtpInputWorkspace, - RoutedFiniteStage, RoutedGroupWorkspace, RoutedStageFiniteGuard, + Context, DeviceBuffer, MmqFormat, MmqWeights, MmqWorkspace, MtpInputWorkspace, RoutedFiniteStage, + RoutedGroupWorkspace, RoutedStageFiniteGuard, }; use std::cell::{Cell, RefCell}; #[path = "mtp_kv_resident.rs"] @@ -20,6 +20,9 @@ use cache_lru_index::{LruIndex, PreparedUpdates}; #[path = "cache_ephemeral_routed.rs"] mod cache_ephemeral_routed; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "cache_original_prompt.rs"] +mod cache_original_prompt; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[path = "cache_profile.rs"] mod cache_profile; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -32,9 +35,6 @@ mod cache_routed_outputs; #[path = "cache_strata_adaptive.rs"] mod cache_strata_adaptive; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[path = "cache_original_prompt.rs"] -mod cache_original_prompt; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) use cache_original_prompt::{PREFILL_STREAM_OVERRIDE, set_span_cache_override}; pub(crate) use cache_profile::{LearnedMainWitness, SharedPermanentWitness}; pub(crate) use cache_strata_adaptive::AdaptiveWitness; @@ -42,9 +42,9 @@ pub(crate) use cache_strata_adaptive::AdaptiveWitness; #[path = "cache_original_verify.rs"] mod cache_original_verify; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -pub(in crate::qwen_forward) use cache_original_verify::SharedKeys; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use cache_ephemeral_routed::observe_cancel; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +pub(in crate::qwen_forward) use cache_original_verify::SharedKeys; use std::collections::HashMap; use std::rc::Rc; @@ -189,7 +189,8 @@ pub(crate) struct MoeWeightCache<'ctx> { /// `LELEKA_PREFILL_MOE_SPAN_CACHE`: the resolved bank spans and formats of every admitted (layer, expert), keyed like `original_finite_experts` /// and valid for the same bank (its address is kept); a later chunk takes them without re-walking the binding (descriptors, bank spans). #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - original_span_cache: (usize, Vec>), + original_span_cache: + (usize, Vec>), /// `LELEKA_ORIGINAL_SERVE_SEED`: routed rows per (layer, expert) the prompt chunks produced, collected from the host /// route counts the MoE stage already reads (no device work); `None` while no capture is requested. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -283,75 +284,27 @@ mod cache_policy_sdet { }; let keys = [ routed, - MoeWeightDescriptor { - layer: 13, - ..routed - }, - MoeWeightDescriptor { - expert: Some(0), - ..routed - }, - MoeWeightDescriptor { - expert: Some(511), - ..routed - }, + MoeWeightDescriptor { layer: 13, ..routed }, + MoeWeightDescriptor { expert: Some(0), ..routed }, + MoeWeightDescriptor { expert: Some(511), ..routed }, MoeWeightDescriptor { role: 1, ..routed }, - MoeWeightDescriptor { - raw_kind: 18, - bytes: 627_200, - ..routed - }, - MoeWeightDescriptor { - expert: None, - raw_kind: 13, - bytes: 1_126_400, - ..routed - }, - MoeWeightDescriptor { - role: 2, - raw_kind: 42, - columns: 640, - rows: 2560, - bytes: 460_800, - ..routed - }, - MoeWeightDescriptor { - expert: None, - role: 3, - raw_kind: 30, - rows: 1, - bytes: 5120, - ..routed - }, + MoeWeightDescriptor { raw_kind: 18, bytes: 627_200, ..routed }, + MoeWeightDescriptor { expert: None, raw_kind: 13, bytes: 1_126_400, ..routed }, + MoeWeightDescriptor { role: 2, raw_kind: 42, columns: 640, rows: 2560, bytes: 460_800, ..routed }, + MoeWeightDescriptor { expert: None, role: 3, raw_kind: 30, rows: 1, bytes: 5120, ..routed }, ]; - let mut ages: HashMap<_, _> = keys - .into_iter() - .enumerate() - .map(|(i, key)| (key, (i + 1) as u64)) - .collect(); + let mut ages: HashMap<_, _> = keys.into_iter().enumerate().map(|(i, key)| (key, (i + 1) as u64)).collect(); assert_eq!(ages.len(), 9); - assert_eq!( - oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), - Some(routed) - ); + assert_eq!(oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), Some(routed)); // A route reorder that selects the same actual expert reuses its key. assert_eq!(ages.insert(routed, 20), Some(1)); assert_eq!(ages.len(), 9); - assert_eq!( - oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), - Some(keys[1]) - ); + assert_eq!(oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), Some(keys[1])); assert_eq!(ages.insert(keys[1], 21), Some(2)); - assert_eq!( - oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), - Some(keys[2]) - ); + assert_eq!(oldest_weight(ages.iter().map(|(key, age)| (*key, *age))), Some(keys[2])); // Selection returns the complete original descriptor, including a // shared scalar role, and never just a route slot or expert number. - assert_eq!( - oldest_weight([(keys[7], 9), (keys[8], 1), (keys[3], 8)].into_iter()), - Some(keys[8]) - ); + assert_eq!(oldest_weight([(keys[7], 9), (keys[8], 1), (keys[3], 8)].into_iter()), Some(keys[8])); } } @@ -362,29 +315,29 @@ pub(super) struct RoutedSourceHealth<'cache, 'ctx> { failed: &'cache Cell, } -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="cache_original_mtp_weights.rs"] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "cache_original_mtp_weights.rs"] mod original_mtp_weights; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use original_mtp_weights::RetainedOriginalMtpWeights; mod validate_ranked_profile_fn; -#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -#[allow(unused_imports)] -pub(crate) use validate_ranked_profile_fn::validate_ranked_profile; -#[allow(unused_imports)] -pub(super) use validate_ranked_profile_fn::room_fits; -#[allow(unused_imports)] -pub(super) use validate_ranked_profile_fn::oldest_weight; #[allow(unused_imports)] use validate_ranked_profile_fn::dual_layout; #[allow(unused_imports)] +use validate_ranked_profile_fn::integer_iq3_triplet; +#[allow(unused_imports)] +pub(super) use validate_ranked_profile_fn::oldest_weight; +#[allow(unused_imports)] pub(in crate::qwen_forward) use validate_ranked_profile_fn::original_dual_layout; #[allow(unused_imports)] use validate_ranked_profile_fn::original_mmq_triplet; #[allow(unused_imports)] -use validate_ranked_profile_fn::integer_iq3_triplet; -mod impl_routedworkspaceowner; +pub(super) use validate_ranked_profile_fn::room_fits; +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[allow(unused_imports)] +pub(crate) use validate_ranked_profile_fn::validate_ranked_profile; mod impl_moeweightcache; -mod impl_routedsourcehealth; mod impl_moeweightcache_2; +mod impl_routedsourcehealth; +mod impl_routedworkspaceowner; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs index bfc96d3f..aad5b84b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache.rs @@ -3,6 +3,8 @@ #[allow(unused_imports)] use super::*; +#[path = "impl_moeweightcache/impl_moeweightcache_10.rs"] +mod impl_moeweightcache_10; #[path = "impl_moeweightcache/impl_moeweightcache_2.rs"] mod impl_moeweightcache_2; #[path = "impl_moeweightcache/impl_moeweightcache_2_2.rs"] @@ -21,5 +23,3 @@ mod impl_moeweightcache_7; mod impl_moeweightcache_8; #[path = "impl_moeweightcache/impl_moeweightcache_9.rs"] mod impl_moeweightcache_9; -#[path = "impl_moeweightcache/impl_moeweightcache_10.rs"] -mod impl_moeweightcache_10; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs index a3489c95..c3ad4782 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_10.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { pub(crate) fn close(mut self) -> Result<()> { let mut failed = self.failed.get(); @@ -24,7 +23,10 @@ impl<'ctx> MoeWeightCache<'ctx> { if let Some(bank) = self.original_expert_bank.take() { failed |= match Rc::try_unwrap(bank) { Ok(bank) => bank.close().is_err(), - Err(bank) => { drop(bank); true } + Err(bank) => { + drop(bank); + true + } }; } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -112,15 +114,15 @@ impl<'ctx> MoeWeightCache<'ctx> { for entry in self.dense.drain(..) { // Captured graphs retain genuine immutable allocations. Releasing // this cache's reference cannot free a graph's live weight bank. - if let Ok(buffer)=Rc::try_unwrap(entry.buffer){failed|=buffer.release().is_err();} + if let Ok(buffer) = Rc::try_unwrap(entry.buffer) { + failed |= buffer.release().is_err(); + } } if let Some(bank) = self.bank.take() { - if let Ok(bank)=Rc::try_unwrap(bank){failed|=bank.release().is_err();} - } - if failed { - Err(Error::CudaExecution) - } else { - Ok(()) + if let Ok(bank) = Rc::try_unwrap(bank) { + failed |= bank.release().is_err(); + } } + if failed { Err(Error::CudaExecution) } else { Ok(()) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs index 236c07c1..e400c15d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { /// Source-only experimental candidate: preserve a reusable 1 GiB spill floor. /// Root must bind this policy in fixture/serving identity before selection. @@ -29,7 +28,11 @@ impl<'ctx> MoeWeightCache<'ctx> { /// passes false when it loads the draft layer from an RT directory (`--mtp-rt-dir`, the product path): that path streams its own copy of the /// experts (`original_mtp_rt_bank`) and never reads this one, so keeping both held 675 MiB of VRAM (and the host copy during the upload) for nothing. /// The pack's dense roles are still uploaded: the draft-KV recording of the prompt path reads them through `mtp_matrix`. - pub(crate) fn new_with_mtp_experts(binding: &ModelBinding, context: &'ctx Context<'ctx>, mtp_experts: bool) -> Result { + pub(crate) fn new_with_mtp_experts( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + mtp_experts: bool, + ) -> Result { let mut cache = Self { context, binding: binding.identity(), @@ -110,17 +113,13 @@ impl<'ctx> MoeWeightCache<'ctx> { let mut total = 0usize; for role in pack.dense_roles(binding).map_err(binding_error)? { let rows = pack.dense_complete(binding, role).map_err(binding_error)?; - total = total - .checked_add(rows.bytes().len()) - .ok_or(Error::Overflow)?; + total = total.checked_add(rows.bytes().len()).ok_or(Error::Overflow)?; if total > MTP_DENSE_LIMIT { return Err(Error::InvalidDimension); } let f32 = if rows.kind() == MtpKind::F32 { let mut values = Vec::new(); - values - .try_reserve_exact(rows.bytes().len() / 4) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(rows.bytes().len() / 4).map_err(|_| Error::InputAllocation)?; for word in rows.bytes().as_chunks::<4>().0 { values.push(f32::from_le_bytes(*word)); } @@ -129,17 +128,14 @@ impl<'ctx> MoeWeightCache<'ctx> { None }; let buffer = cache.upload(rows.bytes())?; - cache - .dense - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + cache.dense.try_reserve(1).map_err(|_| Error::InputAllocation)?; cache.counters.misses = cache.counters.misses.saturating_add(1); cache.dense.push(Dense { role, kind: rows.kind(), rows: rows.rows(), columns: rows.columns(), - buffer:Rc::new(buffer), + buffer: Rc::new(buffer), f32, }); } @@ -156,20 +152,14 @@ impl<'ctx> MoeWeightCache<'ctx> { /// Explicit private native-certified activation experiment. The immutable /// workspace policy applies to GU and Down; normal new()/new_mmq() retain /// their existing native/original-D4 policy, respectively. - pub(crate) fn new_native_mmq( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(crate) fn new_native_mmq(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { let workspace = context.native_mmq_workspace().map_err(driver_error)?; Self::assemble_mmq(binding, context, workspace) } /// Private source-only candidate: raw integer MMA is admitted only for /// legal routed GU18. All persistent scratch (including 13,107,200 bytes /// of integer dots) is charged before MTP upload and main-cache growth. - pub(crate) fn new_native_integer_iq3_mmq( - binding: &ModelBinding, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(crate) fn new_native_integer_iq3_mmq(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { Self::new_native_integer_iq3_mmq_with_prompt(binding, context, false) } pub(in super::super) fn new_native_integer_iq3_mmq_with_prompt( @@ -181,7 +171,8 @@ impl<'ctx> MoeWeightCache<'ctx> { context.native_integer_iq3_mmq_original_formats_workspace() } else { context.native_integer_iq3_mmq_workspace() - }.map_err(driver_error)?; + } + .map_err(driver_error)?; let mut cache = Self::assemble_mmq(binding, context, workspace)?; cache.mmq_policy = MmqRoutingPolicy::NativeIntegerIq3; cache.original_prompt_mmq = original_prompt; @@ -224,12 +215,7 @@ impl<'ctx> MoeWeightCache<'ctx> { if !binding.has_mtp() { return Err(Error::IdentityMismatch); } - if !room_fits( - context.allocated_bytes(), - context.budget_bytes(), - 0, - 128 * 1024 * 1024, - ) { + if !room_fits(context.allocated_bytes(), context.budget_bytes(), 0, 128 * 1024 * 1024) { return Err(Error::InputAllocation); } let ring = context.mtp_dense_kv_ring().map_err(driver_error)?; @@ -240,12 +226,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(primary); } }; - let resident = MtpKvResident::new( - binding.identity(), - context, - Rc::clone(&cache.mmq_owner), - ring, - )?; + let resident = MtpKvResident::new(binding.identity(), context, Rc::clone(&cache.mmq_owner), ring)?; *cache.mtp_kv.borrow_mut() = Some(resident); Ok(cache) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs index 5ad06de5..7fec7712 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_2_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { /// Explicit candidate-only target tail. The fixed owner is admitted while /// main LRU is still empty; all default/Native/draft factories stay exact. @@ -20,7 +19,8 @@ impl<'ctx> MoeWeightCache<'ctx> { context: &'ctx Context<'ctx>, original_prompt: bool, ) -> Result { - let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, original_prompt)?; + let mut cache = + Self::new_native_integer_iq3_mmq_retained_mtp_kv_with_prompt(binding, context, original_prompt)?; let operation = (|| { cache.reserve_mmq_transient( binding, @@ -70,8 +70,11 @@ impl<'ctx> MoeWeightCache<'ctx> { original_prompt: bool, ) -> Result { let index = LruIndex::new()?; - let mut cache = - Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt(binding, context, original_prompt)?; + let mut cache = Self::new_native_integer_iq3_mmq_retained_mtp_kv_shared_tail_with_prompt( + binding, + context, + original_prompt, + )?; if !cache.main.is_empty() || cache.main_bytes != 0 { let _ = cache.close(); return Err(Error::IdentityMismatch); @@ -101,21 +104,15 @@ impl<'ctx> MoeWeightCache<'ctx> { } #[cfg(test)] pub(crate) fn test_lru_metadata_bytes(&self) -> Result { - self.lru - .as_ref() - .ok_or(Error::IdentityMismatch)? - .metadata_bytes() + self.lru.as_ref().ok_or(Error::IdentityMismatch)?.metadata_bytes() } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn profile_preload_upload_bytes(&self) -> u64 { - self.pinned - .as_ref() - .map_or(0, |pool| pool.preload_upload_bytes) + self.pinned.as_ref().map_or(0, |pool| pool.preload_upload_bytes) } pub(in super::super::super) fn uses_direct_native_down_packets(&self) -> bool { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - return (self.pinned.is_some() || self.adaptive.is_some()) - && self.requires_iq3_mmq_admission(); + return (self.pinned.is_some() || self.adaptive.is_some()) && self.requires_iq3_mmq_admission(); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] false } @@ -128,10 +125,7 @@ impl<'ctx> MoeWeightCache<'ctx> { if !self.uses_direct_native_down_packets() { return Err(Error::IdentityMismatch); } - self.routed_finite - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) + self.routed_finite.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(in super::super::super) fn routed_workspace_owner( &self, @@ -142,25 +136,16 @@ impl<'ctx> MoeWeightCache<'ctx> { if !self.uses_direct_native_down_packets() { return Err(Error::IdentityMismatch); } - self.routed_workspace - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) + self.routed_workspace.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(in super::super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if self - .adaptive_shared - .as_ref() - .is_some_and(|pool| pool.contains(key)) - { + if self.adaptive_shared.as_ref().is_some_and(|pool| pool.contains(key)) { return true; } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] return self.pinned.as_ref().is_some_and(|pool| { - pool.shared - .as_ref() - .is_some_and(|shared| shared.contains(key)) + pool.shared.as_ref().is_some_and(|shared| shared.contains(key)) || (!self.learned_main && pool.plan.contains(key.layer, key.expert, key.role)) }); #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] @@ -175,39 +160,21 @@ impl<'ctx> MoeWeightCache<'ctx> { return self .main .len() - .checked_sub(if self.learned_main { - 0 - } else { - pool.loaded_matrices - }) - .and_then(|n| { - n.checked_sub( - pool.shared - .as_ref() - .map_or(0, |shared| shared.descriptor_count()), - ) - }) + .checked_sub(if self.learned_main { 0 } else { pool.loaded_matrices }) + .and_then(|n| n.checked_sub(pool.shared.as_ref().map_or(0, |shared| shared.descriptor_count()))) .ok_or(Error::IdentityMismatch); } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(shared) = &self.adaptive_shared { - return self - .main - .len() - .checked_sub(shared.descriptor_count()) - .ok_or(Error::IdentityMismatch); + return self.main.len().checked_sub(shared.descriptor_count()).ok_or(Error::IdentityMismatch); } Ok(self.main.len()) } pub(in super::super) fn note_profile_request(&mut self, key: MoeWeightDescriptor, hit: bool) { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(pool) = &mut self.pinned { - let counter = if (!self.learned_main - && pool.plan.contains(key.layer, key.expert, key.role)) - || pool - .shared - .as_ref() - .is_some_and(|shared| shared.contains(key)) + let counter = if (!self.learned_main && pool.plan.contains(key.layer, key.expert, key.role)) + || pool.shared.as_ref().is_some_and(|shared| shared.contains(key)) { &mut pool.pinned_hits } else if hit { @@ -237,8 +204,6 @@ impl<'ctx> MoeWeightCache<'ctx> { // rehash pinned-policy metadata after deletion/tombstone churn. return Ok(()); } - self.main - .try_reserve(additional) - .map_err(|_| Error::InputAllocation) + self.main.try_reserve(additional).map_err(|_| Error::InputAllocation) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs index 1691327a..d90a4990 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn prepare_lru_updates( &self, @@ -54,8 +53,7 @@ impl<'ctx> MoeWeightCache<'ctx> { #[cfg(test)] { let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups, updates.saturating_add(count), removals)); + self.lru_witness.set((lookups, updates.saturating_add(count), removals)); } #[cfg(not(test))] let _ = count; @@ -70,16 +68,13 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(Error::IdentityMismatch); } let key = index.oldest(protected)?.ok_or(Error::InputAllocation)?; - if self.is_pinned(key) - || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) - { + if self.is_pinned(key) || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) { return Err(Error::IdentityMismatch); } #[cfg(test)] { let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups.saturating_add(1), updates, removals)); + self.lru_witness.set((lookups.saturating_add(1), updates, removals)); } key } else { @@ -99,17 +94,14 @@ impl<'ctx> MoeWeightCache<'ctx> { } let spill_len = self.spill_len()?; if let Some(index) = &mut self.lru { - if index.len() != spill_len - || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) - { + if index.len() != spill_len || index.entry_age(key)? != self.main.get(&key).map(|entry| entry.age) { return Err(Error::IdentityMismatch); } index.remove(key)?; #[cfg(test)] { let (lookups, updates, removals) = self.lru_witness.get(); - self.lru_witness - .set((lookups, updates, removals.saturating_add(1))); + self.lru_witness.set((lookups, updates, removals.saturating_add(1))); } } Ok(()) @@ -146,26 +138,17 @@ impl<'ctx> MoeWeightCache<'ctx> { ) -> Result, ) -> Result { self.validate(binding, context)?; - let weights = binding - .moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)) - .map_err(binding_error)?; + let weights = + binding.moe_expert_weights(layer.get(), std::array::from_fn(|slot| slot as u32)).map_err(binding_error)?; if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let keys = [ - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]) - .map_err(binding_error)?, - binding - .moe_shared_scalar_descriptor(&weights) - .map_err(binding_error)?, + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?, + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?, + binding.moe_weight_descriptor(&weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?, + binding.moe_shared_scalar_descriptor(&weights).map_err(binding_error)?, ]; super::super::super::shared_expert_workspace::validate_descriptors(&keys)?; if keys.iter().any(|key| key.layer != layer.get()) { @@ -177,13 +160,7 @@ impl<'ctx> MoeWeightCache<'ctx> { binding.moe_shared_scalar(&weights).map_err(binding_error) } else { Ok(binding - .moe_expert_block( - &weights, - MoeExpertSelection::Shared, - roles[index], - 0, - key.rows, - ) + .moe_expert_block(&weights, MoeExpertSelection::Shared, roles[index], 0, key.rows) .map_err(binding_error)? .into_bytes()) } @@ -207,10 +184,7 @@ impl<'ctx> MoeWeightCache<'ctx> { let mut owner = self.native_prefill_resources(binding, context)?; let result = execute( self.context, - super::super::super::moe_prefill_batch::SharedWeights { - keys: &keys, - buffers, - }, + super::super::super::moe_prefill_batch::SharedWeights { keys: &keys, buffers }, &mut owner, ); if self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs index d8618e3d..2ac8c41a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_4.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { /// Source-descriptor admission precedes all fills. Requested entries cannot /// evict one another; every actual weight remains immutably borrowed until @@ -25,18 +24,10 @@ impl<'ctx> MoeWeightCache<'ctx> { } let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let keys = [ - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[2]) - .map_err(binding_error)?, - binding - .moe_shared_scalar_descriptor(weights) - .map_err(binding_error)?, + binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[0]).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[1]).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, MoeExpertSelection::Shared, roles[2]).map_err(binding_error)?, + binding.moe_shared_scalar_descriptor(weights).map_err(binding_error)?, ]; super::super::super::shared_expert_workspace::validate_descriptors(&keys)?; for (index, key) in keys.iter().enumerate() { @@ -45,13 +36,7 @@ impl<'ctx> MoeWeightCache<'ctx> { binding.moe_shared_scalar(weights).map_err(binding_error) } else { Ok(binding - .moe_expert_block( - weights, - MoeExpertSelection::Shared, - roles[index], - 0, - key.rows, - ) + .moe_expert_block(weights, MoeExpertSelection::Shared, roles[index], 0, key.rows) .map_err(binding_error)? .into_bytes()) } @@ -70,28 +55,23 @@ impl<'ctx> MoeWeightCache<'ctx> { } }; let buffers = [raw(0)?, raw(1)?, raw(2)?, raw(3)?]; - let result = self - .target_shared - .as_mut() - .ok_or(Error::IdentityMismatch)? - .compose( - binding, - &self.mmq_owner, - context, - identity, - &keys, - buffers, - activation, - packed, - route, - ); + let result = self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose( + binding, + &self.mmq_owner, + context, + identity, + &keys, + buffers, + activation, + packed, + route, + ); if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } if result.is_ok() { #[cfg(test)] - self.shared_tail_witness - .set(self.shared_tail_witness.get().saturating_add(1)); + self.shared_tail_witness.set(self.shared_tail_witness.get().saturating_add(1)); } result } @@ -116,35 +96,18 @@ impl<'ctx> MoeWeightCache<'ctx> { } // Admit only these actual cache-owned immutable draft weight owners. // No second descriptor/source read or hit-counter mutation is needed. - if self - .bank - .as_ref() - .is_none_or(|actual| !std::ptr::eq(&**actual, bank)) - { + if self.bank.as_ref().is_none_or(|actual| !std::ptr::eq(&**actual, bank)) { return Err(Error::IdentityMismatch); } - for (role, buffer) in [ - MtpRole::SharedGate, - MtpRole::SharedUp, - MtpRole::SharedDown, - MtpRole::SharedScalar, - ] - .into_iter() - .zip(shared) + for (role, buffer) in + [MtpRole::SharedGate, MtpRole::SharedUp, MtpRole::SharedDown, MtpRole::SharedScalar].into_iter().zip(shared) { - let actual = self - .dense - .iter() - .find(|entry| entry.role == role) - .ok_or(Error::IdentityMismatch)?; + let actual = self.dense.iter().find(|entry| entry.role == role).ok_or(Error::IdentityMismatch)?; if !std::ptr::eq(&*actual.buffer, buffer) { return Err(Error::IdentityMismatch); } } - let mut slot = self - .mtp_experts - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.compose( binding, &self.mmq_owner, @@ -164,10 +127,7 @@ impl<'ctx> MoeWeightCache<'ctx> { result } pub(in super::super::super) fn has_mtp_kv_ring(&self) -> Result { - let slot = self - .mtp_kv - .try_borrow() - .map_err(|_| Error::IdentityMismatch)?; + let slot = self.mtp_kv.try_borrow().map_err(|_| Error::IdentityMismatch)?; Ok(slot.is_some()) } pub(in super::super::super) fn prepare_mtp_kv( @@ -178,17 +138,9 @@ impl<'ctx> MoeWeightCache<'ctx> { frame: &super::super::super::mtp::MtpFrame, ) -> Result<()> { self.validate(binding, context)?; - let mut slot = self - .mtp_kv - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare( - binding, - context, - &self.mmq_owner, - next, - frame, - ); + let mut slot = self.mtp_kv.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + let result = + slot.as_mut().ok_or(Error::IdentityMismatch)?.prepare(binding, context, &self.mmq_owner, next, frame); if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } @@ -204,10 +156,7 @@ impl<'ctx> MoeWeightCache<'ctx> { output: &mut DeviceBuffer<'_>, ) -> Result<()> { self.prepare_mtp_kv(binding, context, next, frame)?; - let mut slot = self - .mtp_kv - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut slot = self.mtp_kv.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.attend( query, output, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs index 8e023f4f..3b8e1bcc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_5.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { #[cfg(test)] pub(in crate::qwen_forward) fn note_test_mmq_dispatch(&self, resident: bool, rows: usize) { @@ -27,19 +26,26 @@ impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn weight_layout(&self, key: MoeWeightDescriptor) -> Result> { if self.original_prompt_mmq { original_dual_layout(key) } else { dual_layout(key) } } - pub(in super::super::super) fn has_original_prompt_mmq(&self) -> bool { self.original_prompt_mmq } + pub(in super::super::super) fn has_original_prompt_mmq(&self) -> bool { + self.original_prompt_mmq + } /// Root's selected adaptive capacity factory calls this before any routed /// prefix/adaptive publication. Same actual workspace, no second experiment. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(crate) fn admit_original_expert_groups(&mut self,binding:&ModelBinding, - context:&Context<'_>,capacity:u32)->Result<()> { - self.validate(binding,context)?; - if !self.original_prompt_mmq || !self.main.is_empty() || self.main_bytes!=0 - || self.adaptive.is_some() {return Err(Error::IdentityMismatch);} - let workspace=self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(crate) fn admit_original_expert_groups( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + capacity: u32, + ) -> Result<()> { + self.validate(binding, context)?; + if !self.original_prompt_mmq || !self.main.is_empty() || self.main_bytes != 0 || self.adaptive.is_some() { + return Err(Error::IdentityMismatch); + } + let workspace = self.mmq_workspace.as_mut().ok_or(Error::IdentityMismatch)?; workspace.enable_original_expert_groups(capacity).map_err(driver_error)?; self.room(0)?; - self.validate(binding,context) + self.validate(binding, context) } pub(in super::super::super) fn requires_iq3_mmq_admission(&self) -> bool { @@ -58,7 +64,9 @@ impl<'ctx> MoeWeightCache<'ctx> { ) -> Result> { self.validate(binding, context)?; if !(if original_prompt { 1..=64 } else { 2..=64 }).contains(&rows) - || self.mmq_workspace.is_none() || (original_prompt && !self.original_prompt_mmq) { + || self.mmq_workspace.is_none() + || (original_prompt && !self.original_prompt_mmq) + { return Err(Error::IdentityMismatch); } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -75,11 +83,7 @@ impl<'ctx> MoeWeightCache<'ctx> { } } } - Ok(Some(MmqChunkAdmission { - owner: Rc::clone(&self.mmq_owner), - policy: self.mmq_policy, - original_prompt, - })) + Ok(Some(MmqChunkAdmission { owner: Rc::clone(&self.mmq_owner), policy: self.mmq_policy, original_prompt })) } pub(in super::super::super) fn with_mmq_workspace( &mut self, @@ -89,8 +93,10 @@ impl<'ctx> MoeWeightCache<'ctx> { execute: impl FnOnce(&mut Self, &mut MmqWorkspace<'ctx>) -> Result, ) -> Result { self.validate(binding, context)?; - if !Rc::ptr_eq(&self.mmq_owner, &admission.owner) || admission.policy != self.mmq_policy - || (admission.original_prompt && !self.original_prompt_mmq) { + if !Rc::ptr_eq(&self.mmq_owner, &admission.owner) + || admission.policy != self.mmq_policy + || (admission.original_prompt && !self.original_prompt_mmq) + { return Err(Error::IdentityMismatch); } let mut workspace = self.mmq_workspace.take().ok_or(Error::IdentityMismatch)?; @@ -112,27 +118,20 @@ impl<'ctx> MoeWeightCache<'ctx> { original_prompt: bool, execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result, ) -> Result { - if original_prompt && !self.original_prompt_mmq { return Err(Error::IdentityMismatch); } + if original_prompt && !self.original_prompt_mmq { + return Err(Error::IdentityMismatch); + } if original_prompt || self.requires_iq3_mmq_admission() { return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute); } self.validate(binding, self.context)?; let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let mut keys = Vec::new(); - keys.try_reserve_exact(3) - .map_err(|_| Error::InputAllocation)?; + keys.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?; for role in roles { let _ = self.matrix(binding, weights, selection, role)?; - keys.push( - binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?, - ); + keys.push(binding.moe_weight_descriptor(weights, selection, role).map_err(binding_error)?); } - execute( - self.mmq_owner(&keys[0])?, - self.mmq_owner(&keys[1])?, - self.mmq_owner(&keys[2])?, - ) + execute(self.mmq_owner(&keys[0])?, self.mmq_owner(&keys[1])?, self.mmq_owner(&keys[2])?) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs index d2ba4a82..3ed90030 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_6.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { - // Only the explicit integer candidate uses the closed three-weight fill. // Every requested owner stays resident while missing roles are admitted. pub(in super::super) fn with_integer_mmq_triplet( @@ -19,15 +17,9 @@ impl<'ctx> MoeWeightCache<'ctx> { self.validate(binding, self.context)?; let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down]; let keys = [ - binding - .moe_weight_descriptor(weights, selection, roles[0]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, selection, roles[1]) - .map_err(binding_error)?, - binding - .moe_weight_descriptor(weights, selection, roles[2]) - .map_err(binding_error)?, + binding.moe_weight_descriptor(weights, selection, roles[0]).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, selection, roles[1]).map_err(binding_error)?, + binding.moe_weight_descriptor(weights, selection, roles[2]).map_err(binding_error)?, ]; let layouts = [ self.weight_layout(keys[0])?.ok_or(Error::InvalidDimension)?, @@ -52,10 +44,7 @@ impl<'ctx> MoeWeightCache<'ctx> { if !(if original_prompt { original_mmq_triplet(&keys)? } else { integer_iq3_triplet(&keys)? }) { return Err(Error::InvalidDimension); } - if keys - .iter() - .any(|key| self.is_pinned(*key) && !self.main.contains_key(key)) - { + if keys.iter().any(|key| self.is_pinned(*key) && !self.main.contains_key(key)) { return Err(Error::IdentityMismatch); } if missing == 0 || missing == 3 { @@ -69,19 +58,14 @@ impl<'ctx> MoeWeightCache<'ctx> { self.reserve_main(missing)?; } if missing == 3 { - let update = self.prepare_lru_updates(&[ - (keys[0], self.age + 1), - (keys[1], self.age + 2), - (keys[2], next_age), - ])?; + let update = + self.prepare_lru_updates(&[(keys[0], self.age + 1), (keys[1], self.age + 2), (keys[2], next_age)])?; // Read actual bound spans before any upload. The driver owns its // padded staging until all attempted copies have completed. let mut raw: [Box<[u8]>; 3] = std::array::from_fn(|_| Box::default()); let mut read_bytes = 0usize; for (index, (role, key)) in roles.into_iter().zip(&keys).enumerate() { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; + let block = binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; if block.bytes().len() != key.bytes { return Err(Error::InvalidDimension); } @@ -104,11 +88,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(driver_error(error)); } }; - if owners - .iter() - .zip(&charges) - .any(|(owner, &charge)| owner.allocated_bytes() != charge) - { + if owners.iter().zip(&charges).any(|(owner, &charge)| owner.allocated_bytes() != charge) { for owner in owners.into_iter().rev() { if owner.close().is_err() { self.failed.set(true); @@ -149,20 +129,16 @@ impl<'ctx> MoeWeightCache<'ctx> { // later physical-room query protects all requested roles again. for (role, key) in roles.into_iter().zip(&keys) { let _ = self.main_entry_protected(*key, &keys, || { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; + let block = + binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; Ok(block.into_bytes()) })?; } } else { // A complete resident hit allocates/uploads nothing, so it needs // no physical-memory query or new admission reservation. - let update = self.prepare_lru_updates(&[ - (keys[0], self.age + 1), - (keys[1], self.age + 2), - (keys[2], next_age), - ])?; + let update = + self.prepare_lru_updates(&[(keys[0], self.age + 1), (keys[1], self.age + 2), (keys[2], next_age)])?; self.commit_lru_updates(update, 3)?; for (index, key) in keys.iter().enumerate() { let entry = self.main.get_mut(key).ok_or(Error::IdentityMismatch)?; @@ -186,11 +162,7 @@ impl<'ctx> MoeWeightCache<'ctx> { }); } self.validate(binding, self.context)?; - execute( - self.mmq_owner(&keys[0])?, - self.mmq_owner(&keys[1])?, - self.mmq_owner(&keys[2])?, - ) + execute(self.mmq_owner(&keys[0])?, self.mmq_owner(&keys[1])?, self.mmq_owner(&keys[2])?) } #[cfg(test)] @@ -201,16 +173,9 @@ impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn room_protected(&mut self, extra: usize, protected: &[MoeWeightDescriptor]) -> Result<()> { loop { let (free, _) = self.context.memory_info().map_err(driver_error)?; - let physical_room = extra - .checked_add(WORKING_RESERVE) - .is_some_and(|n| n <= free); + let physical_room = extra.checked_add(WORKING_RESERVE).is_some_and(|n| n <= free); if physical_room - && room_fits( - self.context.allocated_bytes(), - self.context.budget_bytes(), - self.main_bytes, - extra, - ) + && room_fits(self.context.allocated_bytes(), self.context.budget_bytes(), self.main_bytes, extra) { return Ok(()); } @@ -221,14 +186,8 @@ impl<'ctx> MoeWeightCache<'ctx> { self.failed.set(true); return Err(Error::CudaExecution); } - self.main_bytes = self - .main_bytes - .checked_sub(entry.charged_bytes) - .ok_or(Error::Overflow)?; - self.counters.eviction_bytes = self - .counters - .eviction_bytes - .saturating_add(entry.charged_bytes as u64); + self.main_bytes = self.main_bytes.checked_sub(entry.charged_bytes).ok_or(Error::Overflow)?; + self.counters.eviction_bytes = self.counters.eviction_bytes.saturating_add(entry.charged_bytes as u64); self.note_permanent_eviction(key, entry.charged_bytes); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs index b31a2913..c137f396 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_7.rs @@ -3,27 +3,14 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { if self.failed.get() || self.context.is_poisoned() - || self - .routed_finite - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .routed_workspace - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .routed_resident - .as_ref() - .is_some_and(|owner| owner.is_failed()) - || self - .mtp_input_workspace - .as_ref() - .is_some_and(|owner| owner.is_failed()) + || self.routed_finite.as_ref().is_some_and(|owner| owner.is_failed()) + || self.routed_workspace.as_ref().is_some_and(|owner| owner.is_failed()) + || self.routed_resident.as_ref().is_some_and(|owner| owner.is_failed()) + || self.mtp_input_workspace.as_ref().is_some_and(|owner| owner.is_failed()) { return Err(Error::CudaExecution); } @@ -37,21 +24,14 @@ impl<'ctx> MoeWeightCache<'ctx> { } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(owner) = &self.ephemeral_routed { - owner - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .validate(binding, context)?; + owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.validate(binding, context)?; } if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { return Err(Error::IdentityMismatch); } Ok(()) } - pub(crate) fn prepare_step( - &mut self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<()> { + pub(crate) fn prepare_step(&mut self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { self.validate(binding, context)?; self.room(0) } @@ -74,16 +54,9 @@ impl<'ctx> MoeWeightCache<'ctx> { // Query actual current-context availability before own-cache // admission; a snapshot is not a reservation against other actors. let (free, _) = self.context.memory_info().map_err(driver_error)?; - let physical_room = extra - .checked_add(WORKING_RESERVE) - .is_some_and(|needed| needed <= free); + let physical_room = extra.checked_add(WORKING_RESERVE).is_some_and(|needed| needed <= free); if physical_room - && room_fits( - self.context.allocated_bytes(), - self.context.budget_bytes(), - self.main_bytes, - extra, - ) + && room_fits(self.context.allocated_bytes(), self.context.budget_bytes(), self.main_bytes, extra) { return Ok(()); } @@ -94,14 +67,8 @@ impl<'ctx> MoeWeightCache<'ctx> { self.failed.set(true); return Err(Error::CudaExecution); } - self.main_bytes = self - .main_bytes - .checked_sub(entry.charged_bytes) - .ok_or(Error::Overflow)?; - self.counters.eviction_bytes = self - .counters - .eviction_bytes - .saturating_add(entry.charged_bytes as u64); + self.main_bytes = self.main_bytes.checked_sub(entry.charged_bytes).ok_or(Error::Overflow)?; + self.counters.eviction_bytes = self.counters.eviction_bytes.saturating_add(entry.charged_bytes as u64); self.note_permanent_eviction(key, entry.charged_bytes); } } @@ -119,10 +86,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(Error::CudaExecution); } self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(bytes.len() as u64); Ok(buffer) } pub(in super::super) fn main_entry_protected( @@ -172,20 +136,13 @@ impl<'ctx> MoeWeightCache<'ctx> { } return Err(Error::IdentityMismatch); } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64); EncodedWeight::Dual(format, owner) } else { EncodedWeight::Raw(self.upload(&bytes)?) }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; + let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?; if let Err(primary) = self.commit_lru_updates(update, 1) { if weight.close().is_err() { self.failed.set(true); @@ -193,14 +150,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(primary); } self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); + self.main.insert(key, Entry { weight, charged_bytes, age: self.age }); } self.note_permanent_lookup(key, hit); let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs index 8f03f6d6..ee74bfb7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_8.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn main_entry( &mut self, @@ -51,20 +50,13 @@ impl<'ctx> MoeWeightCache<'ctx> { } return Err(Error::IdentityMismatch); } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(bytes.len() as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(bytes.len() as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64); EncodedWeight::Dual(format, owner) } else { EncodedWeight::Raw(self.upload(&bytes)?) }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; + let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?; if let Err(primary) = self.commit_lru_updates(update, 1) { if weight.close().is_err() { self.failed.set(true); @@ -72,14 +64,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(primary); } self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); + self.main.insert(key, Entry { weight, charged_bytes, age: self.age }); } self.note_permanent_lookup(key, hit); let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; @@ -133,19 +118,15 @@ impl<'ctx> MoeWeightCache<'ctx> { rows: key.rows, columns: key.columns, }; - let owner = - match self - .context - .mmq_weights_owned_gate_up(shape, format, bytes.into_vec()) - { - Ok(owner) => owner, - Err(error) => { - if self.context.is_poisoned() { - self.failed.set(true); - } - return Err(driver_error(error)); + let owner = match self.context.mmq_weights_owned_gate_up(shape, format, bytes.into_vec()) { + Ok(owner) => owner, + Err(error) => { + if self.context.is_poisoned() { + self.failed.set(true); } - }; + return Err(driver_error(error)); + } + }; if owner.allocated_bytes() != expected { let cleanup = owner.close(); if cleanup.is_err() { @@ -153,20 +134,13 @@ impl<'ctx> MoeWeightCache<'ctx> { } return Err(Error::IdentityMismatch); } - self.counters.read_bytes = - self.counters.read_bytes.saturating_add(raw_bytes as u64); - self.counters.upload_bytes = self - .counters - .upload_bytes - .saturating_add(charged_bytes as u64); + self.counters.read_bytes = self.counters.read_bytes.saturating_add(raw_bytes as u64); + self.counters.upload_bytes = self.counters.upload_bytes.saturating_add(charged_bytes as u64); EncodedWeight::Dual(format, owner) } else { EncodedWeight::Raw(self.upload(&bytes)?) }; - let main_bytes = self - .main_bytes - .checked_add(charged_bytes) - .ok_or(Error::Overflow)?; + let main_bytes = self.main_bytes.checked_add(charged_bytes).ok_or(Error::Overflow)?; if let Err(primary) = self.commit_lru_updates(update, 1) { if weight.close().is_err() { self.failed.set(true); @@ -174,14 +148,7 @@ impl<'ctx> MoeWeightCache<'ctx> { return Err(primary); } self.main_bytes = main_bytes; - self.main.insert( - key, - Entry { - weight, - charged_bytes, - age: self.age, - }, - ); + self.main.insert(key, Entry { weight, charged_bytes, age: self.age }); } self.note_permanent_lookup(key, hit); let entry = self.main.get_mut(&key).ok_or(Error::IdentityMismatch)?; @@ -218,39 +185,24 @@ impl<'ctx> MoeWeightCache<'ctx> { let matrix = adaptive .matrix(binding, key)? .ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert))?; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; + let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }; return consume(matrix, &health, source); } // The temporary returned view ends here. No cache fill/eviction occurs // while the consumer below holds actual cache fields immutably. - let read = || { - Ok(source - .block(member, role) - .map_err(binding_error)? - .into_bytes()) + let read = || Ok(source.block(member, role).map_err(binding_error)?.into_bytes()); + let _ = if key.expert.is_some() && matches!(key.role, 0 | 1) && matches!(key.raw_kind, 18 | 22) { + self.main_entry_owned_gate_up(key, read)? + } else { + self.main_entry(key, read)? }; - let _ = - if key.expert.is_some() && matches!(key.role, 0 | 1) && matches!(key.raw_kind, 18 | 22) - { - self.main_entry_owned_gate_up(key, read)? - } else { - self.main_entry(key, read)? - }; self.validate(binding, self.context)?; let entry = self.main.get(&key).ok_or(Error::IdentityMismatch)?; let matrix = match &entry.weight { EncodedWeight::Raw(buffer) => CachedMoeMatrix::Raw(buffer), EncodedWeight::Dual(format, owner) => CachedMoeMatrix::Dual(*format, owner), }; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; + let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }; consume(matrix, &health, source) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs index 82648291..ca96ade4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache/impl_moeweightcache_9.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super::super) fn matrix( &mut self, @@ -13,9 +12,7 @@ impl<'ctx> MoeWeightCache<'ctx> { role: MoeMatrixRole, ) -> Result> { self.validate(binding, self.context)?; - let key = binding - .moe_weight_descriptor(weights, selection, role) - .map_err(binding_error)?; + let key = binding.moe_weight_descriptor(weights, selection, role).map_err(binding_error)?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if self.adaptive.is_some() && key.expert.is_some() { return self @@ -26,9 +23,7 @@ impl<'ctx> MoeWeightCache<'ctx> { .ok_or(Error::Unsupported(super::super::super::contract::Stage::MoeExpert)); } self.main_entry(key, || { - let block = binding - .moe_expert_block(weights, selection, role, 0, key.rows) - .map_err(binding_error)?; + let block = binding.moe_expert_block(weights, selection, role, 0, key.rows).map_err(binding_error)?; Ok(block.into_bytes()) }) } @@ -38,12 +33,8 @@ impl<'ctx> MoeWeightCache<'ctx> { weights: &MoeExpertWeights, ) -> Result<&DeviceBuffer<'ctx>> { self.validate(binding, self.context)?; - let key = binding - .moe_shared_scalar_descriptor(weights) - .map_err(binding_error)?; - match self.main_entry(key, || { - binding.moe_shared_scalar(weights).map_err(binding_error) - })? { + let key = binding.moe_shared_scalar_descriptor(weights).map_err(binding_error)?; + match self.main_entry(key, || binding.moe_shared_scalar(weights).map_err(binding_error))? { CachedMoeMatrix::Raw(buffer) => Ok(buffer), CachedMoeMatrix::Dual(_, _) => Err(Error::IdentityMismatch), } @@ -56,43 +47,31 @@ impl<'ctx> MoeWeightCache<'ctx> { if !self.main.is_empty() || self.main_bytes != 0 || self.mtp_input_workspace.is_some() { return Err(Error::IdentityMismatch); } - let supported = [MtpRole::FcEmbedding, MtpRole::FcHidden] - .into_iter() - .all(|role| { + let supported = + [MtpRole::FcEmbedding, MtpRole::FcHidden].into_iter().all(|role| { + self.dense.iter().any(|entry| { + entry.role == role && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560) + }) + }) && [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)].into_iter().all(|(role, words)| { self.dense.iter().any(|entry| { entry.role == role - && (entry.kind, entry.rows, entry.columns) == (MtpKind::Q8_0, 2560, 2560) + && entry.kind == MtpKind::F32 + && entry.f32.as_ref().is_some_and(|values| values.len() == words) }) - }) - && [(MtpRole::EmbeddingNorm, 2560), (MtpRole::HiddenNorm, 10240)] - .into_iter() - .all(|(role, words)| { - self.dense.iter().any(|entry| { - entry.role == role - && entry.kind == MtpKind::F32 - && entry - .f32 - .as_ref() - .is_some_and(|values| values.len() == words) - }) - }); + }); if !supported { return Ok(()); } // Actual Context charge is counted once. Both admission predicates leave // the independent working reserve; metadata plan sees the eager allocation. self.reserve_mmq_transient(binding, self.context, MTP_INPUT_WORKSPACE_BYTES)?; - self.mtp_input_workspace = Some(Rc::new(MtpInputWorkspaceOwner::new( - self.binding.clone(), - self.context, - )?)); + self.mtp_input_workspace = Some(Rc::new(MtpInputWorkspaceOwner::new(self.binding.clone(), self.context)?)); self.room(0)?; self.validate(binding, self.context) } #[cfg(test)] pub(in super::super::super) fn note_mtp_input_completed(&self) { - self.mtp_input_completions - .set(self.mtp_input_completions.get().saturating_add(1)); + self.mtp_input_completions.set(self.mtp_input_completions.get().saturating_add(1)); } #[cfg(test)] pub(crate) fn test_mtp_input_completions(&self) -> u64 { @@ -107,26 +86,15 @@ impl<'ctx> MoeWeightCache<'ctx> { context: &Context<'_>, ) -> Result>> { self.validate(binding, context)?; - let owner = self - .mtp_input_workspace - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let owner = self.mtp_input_workspace.as_ref().ok_or(Error::IdentityMismatch)?; if !owner.binding.matches(&binding.identity()) || !std::ptr::eq(owner.context, context) { return Err(Error::IdentityMismatch); } Ok(Rc::clone(owner)) } - pub(crate) fn mtp_bank( - &self, - binding: &ModelBinding, - context: &Context<'_>, - ) -> Result<&DeviceBuffer<'ctx>> { + pub(crate) fn mtp_bank(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<&DeviceBuffer<'ctx>> { self.validate(binding, context)?; - binding - .mtp_weights() - .map_err(binding_error)? - .validate_sources(binding) - .map_err(binding_error)?; + binding.mtp_weights().map_err(binding_error)?.validate_sources(binding).map_err(binding_error)?; self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); self.bank.as_deref().ok_or(Error::IdentityMismatch) } @@ -139,14 +107,8 @@ impl<'ctx> MoeWeightCache<'ctx> { self.validate(binding, context)?; let pack = binding.mtp_weights().map_err(binding_error)?; pack.validate_sources(binding).map_err(binding_error)?; - let entry = self - .dense - .iter() - .find(|e| e.role == role) - .ok_or(Error::IdentityMismatch)?; - if pack.dense_shape(binding, role).map_err(binding_error)? - != (entry.kind, entry.rows, entry.columns) - { + let entry = self.dense.iter().find(|e| e.role == role).ok_or(Error::IdentityMismatch)?; + if pack.dense_shape(binding, role).map_err(binding_error)? != (entry.kind, entry.rows, entry.columns) { return Err(Error::IdentityMismatch); } self.mtp_hits.set(self.mtp_hits.get().saturating_add(1)); @@ -154,11 +116,7 @@ impl<'ctx> MoeWeightCache<'ctx> { } pub(crate) fn mtp_f32(&self, binding: &ModelBinding, role: MtpRole) -> Result<&[f32]> { self.mtp_matrix(binding, self.context, role)?; - self.dense - .iter() - .find(|e| e.role == role) - .and_then(|e| e.f32.as_deref()) - .ok_or(Error::InvalidDimension) + self.dense.iter().find(|e| e.role == role).and_then(|e| e.f32.as_deref()).ok_or(Error::InvalidDimension) } pub(crate) fn counters(&self) -> WeightCacheCounters { let mut counters = self.counters; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs index 6cfb7490..566fd787 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_moeweightcache_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl<'ctx> MoeWeightCache<'ctx> { pub(in super::super) fn routed_output_owner( @@ -12,19 +11,13 @@ impl<'ctx> MoeWeightCache<'ctx> { context: &Context<'_>, ) -> Result>> { self.validate(binding, context)?; - self.routed_outputs - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) + self.routed_outputs.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(in super::super) fn uses_mapped_expert_source(&self) -> Result { let Some(owner) = &self.ephemeral_routed else { return Ok(false); }; - Ok(owner - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .uses_mapped()) + Ok(owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.uses_mapped()) } pub(in super::super) fn ephemeral_routed_owner( &self, @@ -32,10 +25,7 @@ impl<'ctx> MoeWeightCache<'ctx> { context: &Context<'_>, ) -> Result>>> { self.validate(binding, context)?; - self.ephemeral_routed - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) + self.ephemeral_routed.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(in super::super) fn routed_resident_owner( &self, @@ -46,10 +36,7 @@ impl<'ctx> MoeWeightCache<'ctx> { if !self.uses_strata_adaptive_experts() { return Err(Error::IdentityMismatch); } - let owner = self - .routed_resident - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let owner = self.routed_resident.as_ref().ok_or(Error::IdentityMismatch)?; if !owner.matches_context(context) { return Err(Error::IdentityMismatch); } @@ -73,20 +60,11 @@ impl<'ctx> MoeWeightCache<'ctx> { source.validate_binding(binding).map_err(binding_error)?; let adaptive = self.adaptive.as_ref().ok_or(Error::IdentityMismatch)?; let keys = [ - source - .descriptor(member, MoeMatrixRole::Gate) - .map_err(binding_error)?, - source - .descriptor(member, MoeMatrixRole::Up) - .map_err(binding_error)?, - source - .descriptor(member, MoeMatrixRole::Down) - .map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Down).map_err(binding_error)?, ]; - if keys - .iter() - .any(|key| key.layer != keys[0].layer || key.expert != keys[0].expert) - || keys[0].expert.is_none() + if keys.iter().any(|key| key.layer != keys[0].layer || key.expert != keys[0].expert) || keys[0].expert.is_none() { return Err(Error::IdentityMismatch); } @@ -95,11 +73,7 @@ impl<'ctx> MoeWeightCache<'ctx> { _ => Err(Error::IdentityMismatch), }; let buffers = [raw(keys[0])?, raw(keys[1])?, raw(keys[2])?]; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; + let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }; consume(buffers, &health, source) } pub(in super::super) fn with_ephemeral_triplet_routed_source<'source, 'group, T>( @@ -118,64 +92,32 @@ impl<'ctx> MoeWeightCache<'ctx> { self.validate(binding, self.context)?; source.validate_binding(binding).map_err(binding_error)?; let keys = [ - source - .descriptor(member, MoeMatrixRole::Gate) - .map_err(binding_error)?, - source - .descriptor(member, MoeMatrixRole::Up) - .map_err(binding_error)?, - source - .descriptor(member, MoeMatrixRole::Down) - .map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Gate).map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Up).map_err(binding_error)?, + source.descriptor(member, MoeMatrixRole::Down).map_err(binding_error)?, ]; - let health = RoutedSourceHealth { - binding: &self.binding, - context: self.context, - failed: &self.failed, - }; - let owner = self - .ephemeral_routed - .as_ref() - .ok_or(Error::IdentityMismatch)?; - let mut owner = owner - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; - owner.with_triplet( - slot, - binding, - source, - member, - cancel_observed, - |raw, actual_keys, source| { - if actual_keys != keys { - return Err(Error::IdentityMismatch); - } - consume(raw, &health, source) - }, - ) + let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed }; + let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?; + let mut owner = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; + owner.with_triplet(slot, binding, source, member, cancel_observed, |raw, actual_keys, source| { + if actual_keys != keys { + return Err(Error::IdentityMismatch); + } + consume(raw, &health, source) + }) } #[cfg(test)] pub(crate) fn test_routed_resident_queue_completions(&self) -> u64 { - self.routed_resident - .as_ref() - .map_or(0, |owner| owner.completions.get()) + self.routed_resident.as_ref().map_or(0, |owner| owner.completions.get()) } #[cfg(test)] pub(crate) fn test_routed_output_reuse_completions(&self) -> u64 { - self.routed_outputs - .as_ref() - .map_or(0, |owner| owner.completed_callbacks()) + self.routed_outputs.as_ref().map_or(0, |owner| owner.completed_callbacks()) } #[cfg(test)] pub(crate) fn test_ephemeral_routed_completions(&self) -> Result { - let owner = self - .ephemeral_routed - .as_ref() - .ok_or(Error::IdentityMismatch)?; - Ok(owner - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .completed_loans()) + let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?; + Ok(owner.try_borrow().map_err(|_| Error::IdentityMismatch)?.completed_loans()) } pub(crate) fn uses_strata_adaptive_experts(&self) -> bool { self.adaptive.is_some() @@ -188,10 +130,7 @@ impl<'ctx> MoeWeightCache<'ctx> { if self.adaptive.is_none() { return Err(Error::IdentityMismatch); } - self.cpu_miss - .as_ref() - .map(Rc::clone) - .ok_or(Error::IdentityMismatch) + self.cpu_miss.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch) } pub(crate) fn strata_adaptive_witness( @@ -199,10 +138,7 @@ impl<'ctx> MoeWeightCache<'ctx> { binding: &ModelBinding, ) -> Result { self.validate(binding, self.context)?; - self.adaptive - .as_ref() - .ok_or(Error::IdentityMismatch)? - .witness(binding) + self.adaptive.as_ref().ok_or(Error::IdentityMismatch)?.witness(binding) } pub(crate) fn observe_strata_adaptive_row( &mut self, @@ -210,37 +146,19 @@ impl<'ctx> MoeWeightCache<'ctx> { weights: &MoeExpertWeights, ) -> Result<()> { self.validate(binding, self.context)?; - self.adaptive - .as_mut() - .ok_or(Error::IdentityMismatch)? - .observe_row(binding, weights) + self.adaptive.as_mut().ok_or(Error::IdentityMismatch)?.observe_row(binding, weights) } - pub(crate) fn strata_adaptive_completed_window( - &mut self, - binding: &ModelBinding, - ) -> Result<()> { + pub(crate) fn strata_adaptive_completed_window(&mut self, binding: &ModelBinding) -> Result<()> { self.validate(binding, self.context)?; - let result = self - .adaptive - .as_mut() - .ok_or(Error::IdentityMismatch)? - .completed_window(binding); + let result = self.adaptive.as_mut().ok_or(Error::IdentityMismatch)?.completed_window(binding); if self.context.is_poisoned() { self.failed.set(true); } result } - pub(crate) fn poll_strata_adaptive( - &mut self, - binding: &ModelBinding, - wait: bool, - ) -> Result<()> { + pub(crate) fn poll_strata_adaptive(&mut self, binding: &ModelBinding, wait: bool) -> Result<()> { self.validate(binding, self.context)?; - let result = self - .adaptive - .as_mut() - .ok_or(Error::IdentityMismatch)? - .poll(binding, wait); + let result = self.adaptive.as_mut().ok_or(Error::IdentityMismatch)?.poll(binding, wait); if result.is_err() { self.failed.set(true); } @@ -254,14 +172,7 @@ impl<'ctx> MoeWeightCache<'ctx> { selection: MoeExpertSelection, ) -> Result { self.validate(binding, self.context)?; - let key = binding - .moe_weight_descriptor(weights, selection, MoeMatrixRole::Gate) - .map_err(binding_error)?; - Ok(self - .adaptive - .as_ref() - .ok_or(Error::IdentityMismatch)? - .matrix(binding, key)? - .is_some()) + let key = binding.moe_weight_descriptor(weights, selection, MoeMatrixRole::Gate).map_err(binding_error)?; + Ok(self.adaptive.as_ref().ok_or(Error::IdentityMismatch)?.matrix(binding, key)?.is_some()) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedsourcehealth.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedsourcehealth.rs index b9609d06..20b6c771 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedsourcehealth.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedsourcehealth.rs @@ -19,11 +19,7 @@ impl RoutedSourceHealth<'_, '_> { impl MoeWeightCache<'_> { pub(super) fn note_permanent_lookup(&mut self, key: MoeWeightDescriptor, hit: bool) { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if (self - .pinned - .as_ref() - .is_some_and(|pool| pool.shared.is_some()) - || self.adaptive_shared.is_some()) + if (self.pinned.as_ref().is_some_and(|pool| pool.shared.is_some()) || self.adaptive_shared.is_some()) && let Some(charged) = self.main.get(&key).map(|entry| entry.charged_bytes) { if hit { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedworkspaceowner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedworkspaceowner.rs index 8a60a253..d9ef2d41 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedworkspaceowner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/impl_routedworkspaceowner.rs @@ -11,11 +11,7 @@ impl<'ctx> RoutedWorkspaceOwner<'ctx> { let _ = workspace.close(); return Err(Error::IdentityMismatch); } - Ok(Self { - context, - workspace: RefCell::new(Some(workspace)), - failed: Cell::new(false), - }) + Ok(Self { context, workspace: RefCell::new(Some(workspace)), failed: Cell::new(false) }) } pub(in crate::qwen_forward) fn matches_context(&self, context: &Context<'_>) -> bool { std::ptr::eq(self.context, context) @@ -30,38 +26,25 @@ impl<'ctx> RoutedWorkspaceOwner<'ctx> { if self.is_failed() { return Err(Error::CudaExecution); } - let mut loan = self - .workspace - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut loan = self.workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let workspace = loan.as_mut().ok_or(Error::IdentityMismatch)?; if workspace.is_failed() { self.failed.set(true); return Err(Error::CudaExecution); } let result = execute(workspace); - if workspace.is_failed() - || self.context.is_poisoned() - || matches!(result, Err(Error::CudaExecution)) - { + if workspace.is_failed() || self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } result } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { - let release = self - .workspace - .get_mut() - .take() - .map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); + let release = + self.workspace.get_mut().take().map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); if release.is_err() { self.failed.set(true); } - if self.is_failed() { - Err(Error::CudaExecution) - } else { - release - } + if self.is_failed() { Err(Error::CudaExecution) } else { release } } } impl Drop for RoutedWorkspaceOwner<'_> { @@ -102,43 +85,29 @@ impl<'ctx> RoutedResidentOwner<'ctx> { if self.is_failed() { return Err(Error::CudaExecution); } - let mut loan = self - .workspace - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut loan = self.workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let workspace = loan.as_mut().ok_or(Error::IdentityMismatch)?; if workspace.is_failed() { self.failed.set(true); return Err(Error::CudaExecution); } let result = execute(workspace); - if workspace.is_failed() - || self.context.is_poisoned() - || matches!(result, Err(Error::CudaExecution)) - { + if workspace.is_failed() || self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } #[cfg(test)] if result.is_ok() { - self.completions - .set(self.completions.get().saturating_add(1)); + self.completions.set(self.completions.get().saturating_add(1)); } result } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { - let release = self - .workspace - .get_mut() - .take() - .map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); + let release = + self.workspace.get_mut().take().map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); if release.is_err() { self.failed.set(true); } - if self.is_failed() { - Err(Error::CudaExecution) - } else { - release - } + if self.is_failed() { Err(Error::CudaExecution) } else { release } } } impl Drop for RoutedResidentOwner<'_> { @@ -157,12 +126,7 @@ impl<'ctx> MtpInputWorkspaceOwner<'ctx> { let _ = workspace.close(); return Err(Error::IdentityMismatch); } - Ok(Self { - binding, - context, - workspace: RefCell::new(Some(workspace)), - failed: Cell::new(false), - }) + Ok(Self { binding, context, workspace: RefCell::new(Some(workspace)), failed: Cell::new(false) }) } pub(super) fn is_failed(&self) -> bool { self.failed.get() || self.context.is_poisoned() @@ -174,38 +138,25 @@ impl<'ctx> MtpInputWorkspaceOwner<'ctx> { if self.is_failed() { return Err(Error::CudaExecution); } - let mut loan = self - .workspace - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut loan = self.workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let workspace = loan.as_mut().ok_or(Error::IdentityMismatch)?; if workspace.is_failed() { self.failed.set(true); return Err(Error::CudaExecution); } let result = execute(workspace); - if workspace.is_failed() - || self.context.is_poisoned() - || matches!(result, Err(Error::CudaExecution)) - { + if workspace.is_failed() || self.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) { self.failed.set(true); } result } pub(super) fn close(mut self) -> Result<()> { - let release = self - .workspace - .get_mut() - .take() - .map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); + let release = + self.workspace.get_mut().take().map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); if release.is_err() { self.failed.set(true); } - if self.is_failed() { - Err(Error::CudaExecution) - } else { - release - } + if self.is_failed() { Err(Error::CudaExecution) } else { release } } } impl Drop for MtpInputWorkspaceOwner<'_> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/validate_ranked_profile_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/validate_ranked_profile_fn.rs index 4044f25a..2702a31a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/validate_ranked_profile_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/moe_weight_cache/validate_ranked_profile_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Pure, bounded profile admission before Driver load; no device capability. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) fn validate_ranked_profile(bytes: &[u8]) -> Result<()> { @@ -12,13 +11,8 @@ pub(crate) fn validate_ranked_profile(bytes: &[u8]) -> Result<()> { /// Exact production admission predicate; overflow always refuses. pub(in super::super) fn room_fits(allocated: usize, budget: usize, main_bytes: usize, extra: usize) -> bool { - allocated - .checked_add(extra) - .and_then(|n| n.checked_add(WORKING_RESERVE)) - .is_some_and(|n| n <= budget) - && main_bytes - .checked_add(extra) - .is_some_and(|n| n <= MAIN_LIMIT) + allocated.checked_add(extra).and_then(|n| n.checked_add(WORKING_RESERVE)).is_some_and(|n| n <= budget) + && main_bytes.checked_add(extra).is_some_and(|n| n <= MAIN_LIMIT) } pub(in super::super) fn oldest_weight( entries: impl Iterator, @@ -46,12 +40,8 @@ pub(super) fn dual_layout(key: MoeWeightDescriptor) -> Result { (MmqFormat::Iq2SGateUp, 524_800, 0) } - 20 if key.role == 2 && key.rows == 2560 && key.columns == 640 => { - (MmqFormat::Iq4NlDown, 921_600, 216) - } - 42 if key.role == 2 && key.rows == 2560 && key.columns == 640 => { - (MmqFormat::Q2Down, 460_800, 108) - } + 20 if key.role == 2 && key.rows == 2560 && key.columns == 640 => (MmqFormat::Iq4NlDown, 921_600, 216), + 42 if key.role == 2 && key.rows == 2560 && key.columns == 640 => (MmqFormat::Q2Down, 460_800, 108), 18 | 22 | 20 | 42 => return Err(Error::InvalidDimension), _ => return Ok(None), }; @@ -63,7 +53,9 @@ pub(super) fn dual_layout(key: MoeWeightDescriptor) -> Result Result> { - if key.expert.is_none() { return Ok(None); } + if key.expert.is_none() { + return Ok(None); + } if matches!(key.role, 0 | 1) && key.rows == 640 && key.columns == 2560 { let (format, raw) = match key.raw_kind { 21 => (MmqFormat::Iq3SGateUp, 704_000), @@ -71,17 +63,27 @@ pub(in crate::qwen_forward) fn original_dual_layout(key: MoeWeightDescriptor) -> 20 => (MmqFormat::Iq4NlGateUp, 921_600), _ => return dual_layout(key), }; - if key.bytes != raw { return Err(Error::InvalidDimension); } + if key.bytes != raw { + return Err(Error::InvalidDimension); + } return Ok(Some((format, raw))); } dual_layout(key) } pub(super) fn original_mmq_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result { let [gate, up, down] = *keys; - if gate.role != 0 || up.role != 1 || down.role != 2 - || gate.expert.is_none_or(|e| e >= 512) || gate.expert != up.expert - || gate.expert != down.expert || gate.layer != up.layer || gate.layer != down.layer - || gate.raw_kind != up.raw_kind { return Err(Error::IdentityMismatch); } + if gate.role != 0 + || up.role != 1 + || down.role != 2 + || gate.expert.is_none_or(|e| e >= 512) + || gate.expert != up.expert + || gate.expert != down.expert + || gate.layer != up.layer + || gate.layer != down.layer + || gate.raw_kind != up.raw_kind + { + return Err(Error::IdentityMismatch); + } let layouts = [original_dual_layout(gate)?, original_dual_layout(up)?, original_dual_layout(down)?]; Ok(layouts.iter().all(Option::is_some)) } @@ -111,10 +113,7 @@ pub(super) fn integer_iq3_triplet(keys: &[MoeWeightDescriptor; 3]) -> Result RoutedFiniteOwner<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -124,11 +123,7 @@ impl<'ctx> RoutedFiniteOwner<'ctx> { let _ = guard.close(); return Err(Error::IdentityMismatch); } - Ok(Self { - context, - guard: RefCell::new(Some(guard)), - failed: Cell::new(false), - }) + Ok(Self { context, guard: RefCell::new(Some(guard)), failed: Cell::new(false) }) } pub(in crate::qwen_forward) fn matches_context(&self, context: &Context<'_>) -> bool { std::ptr::eq(self.context, context) @@ -145,41 +140,24 @@ impl<'ctx> RoutedFiniteOwner<'ctx> { if self.is_failed() { return Err(Error::CudaExecution); } - let mut loan = self - .guard - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut loan = self.guard.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let result = loan .as_mut() .ok_or(Error::IdentityMismatch)? .check_stage(source, stage, columns) .map_err(driver_error) - .and_then(|finite| { - if finite { - Ok(()) - } else { - Err(Error::NonFinite) - } - }); + .and_then(|finite| if finite { Ok(()) } else { Err(Error::NonFinite) }); if matches!(result, Err(Error::CudaExecution)) || self.context.is_poisoned() { self.failed.set(true); } result } pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { - let release = self - .guard - .get_mut() - .take() - .map_or(Ok(()), |guard| guard.close().map_err(driver_error)); + let release = self.guard.get_mut().take().map_or(Ok(()), |guard| guard.close().map_err(driver_error)); if release.is_err() { self.failed.set(true); } - if self.is_failed() { - Err(Error::CudaExecution) - } else { - release - } + if self.is_failed() { Err(Error::CudaExecution) } else { release } } } impl Drop for RoutedFiniteOwner<'_> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs index 14e9fe9a..b35381bb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp.rs @@ -4,26 +4,22 @@ use super::moe_weight_cache::MoeWeightCache; use super::{ contract::{Dimension, Error, Position, Result, Stage, TokenId}, executor::{PrefillStepProduct, TargetStepProduct}, - qsa_index::{ - allocate, binding_error, download, driver_error, release, upload, validate_values, - }, + qsa_index::{allocate, binding_error, download, driver_error, release, upload, validate_values}, session::{QwenSession, TargetStepOrigin}, }; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, MtpKind, MtpRole}; -use leleka_cuda_driver::{ - Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, ProjectionKind, ProjectionSpec, -}; +use leleka_cuda_driver::{Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, ProjectionKind, ProjectionSpec}; use std::{cell::Cell, rc::Rc}; -#[path = "mtp_state.rs"] -mod state; #[path = "mtp_kv_only.rs"] mod kv_only; +#[path = "mtp_state.rs"] +mod state; pub(super) use kv_only::produce_chunk_kv_only; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use state::MtpChunkNumericSnapshot; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(crate) use state::PrefixDraftSnapshot; -pub(super) use state::{DenseKv, MtpChunkStage, MtpSession, MtpKvPrefill, ReadyMtpKvPrefill}; +pub(super) use state::{DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill}; /// Created only from a successful current target product or a checked draft /// successor. Reset/rewind invalidates every prior branch capability. @@ -57,30 +53,30 @@ pub(super) struct MtpFinalMixed { mod impl_mtpframe; #[allow(unused_imports)] -use impl_mtpframe::queued_fc_shape; -#[allow(unused_imports)] use impl_mtpframe::input_refusal; +#[allow(unused_imports)] +use impl_mtpframe::queued_fc_shape; mod step_fn; #[allow(unused_imports)] -pub(super) use step_fn::step; -#[allow(unused_imports)] -pub(super) use step_fn::warm_step; -#[allow(unused_imports)] -pub(super) use step_fn::warm_chunk_row; -#[allow(unused_imports)] -use step_fn::step_core; -#[allow(unused_imports)] -pub(super) use step_fn::preflight; -#[allow(unused_imports)] -pub(super) use step_fn::reserve; -#[allow(unused_imports)] pub(super) use step_fn::f32_weights; #[allow(unused_imports)] use step_fn::norm; #[allow(unused_imports)] +pub(super) use step_fn::preflight; +#[allow(unused_imports)] pub(super) use step_fn::project; #[allow(unused_imports)] pub(super) use step_fn::project_attention_output; +#[allow(unused_imports)] +pub(super) use step_fn::reserve; +#[allow(unused_imports)] +pub(super) use step_fn::step; +#[allow(unused_imports)] +use step_fn::step_core; +#[allow(unused_imports)] +pub(super) use step_fn::warm_chunk_row; +#[allow(unused_imports)] +pub(super) use step_fn::warm_step; mod project_attention_out_numeric_fn; #[allow(unused_imports)] pub(super) use project_attention_out_numeric_fn::project_attention_out_numeric; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs index eb3f8c55..30803b27 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs @@ -9,11 +9,7 @@ impl MtpFrame { if !self.binding.matches(&binding.identity()) || self.epoch.get() != self.generation { return Err(Error::IdentityMismatch); } - binding - .mtp_weights() - .map_err(binding_error)? - .validate_binding(binding) - .map_err(binding_error)?; + binding.mtp_weights().map_err(binding_error)?.validate_binding(binding).map_err(binding_error)?; if self.token != TokenId::new(u64::from(self.token.get()), Dimension::new(248320)?)? || self.position.get() >= crate::qwen_forward::contract::serving_cells() || self.depth >= 4 @@ -48,20 +44,10 @@ impl MtpInput { ) -> Result { previous.frame.validate(binding, session)?; let position = Position::new( - previous - .frame - .position - .get() - .checked_add(1) - .ok_or(Error::Overflow)?, + previous.frame.position.get().checked_add(1).ok_or(Error::Overflow)?, crate::qwen_forward::contract::position_dimension(), )?; - let mut frame = draft.frame( - binding, - position, - previous.predicted, - previous.frame.origin.clone(), - )?; + let mut frame = draft.frame(binding, position, previous.predicted, previous.frame.origin.clone())?; frame.depth = previous.frame.depth.checked_add(1).ok_or(Error::Overflow)?; frame.validate(binding, session)?; Self::compute(binding, session, frame, &previous.streams, cache) @@ -115,20 +101,11 @@ impl MtpInput { validate_values(streams, 10240)?; let context = session.mtp_context()?; preflight(context, 2 * 40960 + 5 * 10240 + 2 * 1310720 + 10000)?; - let embedding = binding - .embedding_row(frame.token.get()) - .map_err(binding_error)?; + let embedding = binding.embedding_row(frame.token.get()).map_err(binding_error)?; if cache.has_mtp_input_workspace() { return Self::compute_queued(binding, session, frame, streams, &embedding, cache); } - let en = norm( - context, - binding, - MtpRole::EmbeddingNorm, - &embedding, - false, - cache, - )?; + let en = norm(context, binding, MtpRole::EmbeddingNorm, &embedding, false, cache)?; let e2 = project(context, binding, MtpRole::FcEmbedding, &en, cache)?; let hn = norm(context, binding, MtpRole::HiddenNorm, streams, true, cache)?; let mut h2 = reserve(10240)?; @@ -138,16 +115,11 @@ impl MtpInput { let hidden = upload(context, &h2)?; let emb = upload(context, &e2)?; let mut out = allocate(context, 10240)?; - context - .mtp_broadcast_f32(&hidden, &emb, &mut out) - .map_err(driver_error)?; + context.mtp_broadcast_f32(&hidden, &emb, &mut out).map_err(driver_error)?; let result = download(&out, 10240)?; release([hidden, emb, out])?; frame.validate(binding, session)?; - Ok(Self { - frame, - streams: result, - }) + Ok(Self { frame, streams: result }) } // Each role is acquired at the original stage. Scratch is exclusively // borrowed from a separate owner while actual dense weights stay immutable. @@ -169,23 +141,20 @@ impl MtpInput { let mut prefix = workspace.begin(embedding, streams).map_err(driver_error)?; let admitted: Result<()> = (|| { prefix.embedding_norm(en_weights).map_err(driver_error)?; - let (kind, rows, columns, weights) = - cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?; + let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?; queued_fc_shape(kind, rows, columns)?; preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; prefix.embedding_projection(weights).map_err(driver_error)?; let hn_gamma = f32_weights(binding, MtpRole::HiddenNorm, cache)?; validate_values(streams, 10240)?; validate_values(&hn_gamma, 10240)?; - let (_, _, _, hn_weights) = - cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?; + let (_, _, _, hn_weights) = cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?; prefix.hidden_norm(hn_weights).map_err(driver_error)?; // The original host H assembly allocation remains at its role // point; this queue changes only numerical transport storage. let _h2 = reserve::(10240)?; for _ in 0..4 { - let (kind, rows, columns, weights) = - cache.mtp_matrix(binding, context, MtpRole::FcHidden)?; + let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcHidden)?; queued_fc_shape(kind, rows, columns)?; preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; prefix.hidden_projection(weights).map_err(driver_error)?; @@ -229,16 +198,13 @@ pub(super) fn queued_fc_shape(kind: MtpKind, rows: usize, columns: usize) -> Res pub(super) fn input_refusal(refusal: leleka_cuda_driver::MtpInputRefusal) -> Error { match refusal { // Preserve the existing driver_error(InvalidQ8Activation) mapping. - leleka_cuda_driver::MtpInputRefusal::NonFinite - | leleka_cuda_driver::MtpInputRefusal::InvalidQ8Activation => Error::NonFinite, + leleka_cuda_driver::MtpInputRefusal::NonFinite | leleka_cuda_driver::MtpInputRefusal::InvalidQ8Activation => { + Error::NonFinite + } } } impl MtpStepProduct { - pub(in super::super) fn predicted( - &self, - binding: &ModelBinding, - session: &QwenSession<'_>, - ) -> Result { + pub(in super::super) fn predicted(&self, binding: &ModelBinding, session: &QwenSession<'_>) -> Result { self.frame.validate(binding, session)?; Ok(self.predicted) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs index ada82a6b..9362f345 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs @@ -21,11 +21,7 @@ pub(in super::super) fn project_attention_out_numeric( weights, activation, &mut y, - ProjectionSpec { - rows: ROWS, - columns: COLUMNS, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows: ROWS, columns: COLUMNS, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ) .map_err(driver_error)?; download(&y, ROWS) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs index efa86c72..c2f98430 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs @@ -85,9 +85,7 @@ pub(super) fn step_core( if !input.frame.same(final_mixed.frame()) || !input.frame.same(attention.frame()) { return Err(Error::IdentityMismatch); } - let predicted = output - .map(|head| head.mtp_greedy(binding, final_mixed.mixed(), session)) - .transpose()?; + let predicted = output.map(|head| head.mtp_greedy(binding, final_mixed.mixed(), session)).transpose()?; let mut streams = reserve(10240)?; streams.extend_from_slice(final_mixed.streams()); let mut retained = reserve(10240)?; @@ -95,11 +93,7 @@ pub(super) fn step_core( // Teardown/synchronization ambiguity is sticky, never erased by rewind. session.finish_mtp_device()?; input.frame.validate(binding, session)?; - draft.commit( - &input.frame, - attention.into_pending_kv(), - retained.into_boxed_slice(), - )?; + draft.commit(&input.frame, attention.into_pending_kv(), retained.into_boxed_slice())?; Ok(predicted.map(|predicted| MtpStepProduct { frame: input.frame, predicted, @@ -127,11 +121,7 @@ impl MtpFinalMixed { } } pub(in super::super) fn preflight(context: &Context<'_>, bytes: usize) -> Result<()> { - if context - .allocated_bytes() - .checked_add(bytes) - .is_none_or(|v| v > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(bytes).is_none_or(|v| v > context.budget_bytes()) { Err(Error::InputAllocation) } else { Ok(()) @@ -167,12 +157,8 @@ pub(super) fn norm( let x = upload(context, values)?; let (_, _, _, w) = cache.mtp_matrix(binding, context, role)?; let mut y = allocate(context, n)?; - if hidden { - context.mtp_hidden_norm_f32(&x, w, &mut y) - } else { - context.mtp_embedding_norm_f32(&x, w, &mut y) - } - .map_err(driver_error)?; + if hidden { context.mtp_hidden_norm_f32(&x, w, &mut y) } else { context.mtp_embedding_norm_f32(&x, w, &mut y) } + .map_err(driver_error)?; let result = download(&y, n)?; release([x, y])?; Ok(result) @@ -197,18 +183,12 @@ pub(in super::super) fn project( let mut y = allocate(context, rows)?; let result = (|| { match kind { - MtpKind::Bf16 => { - context.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns }) - } + MtpKind::Bf16 => context.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns }), MtpKind::Q8_0 => context.project_q8_1( weights, &x, &mut y, - ProjectionSpec { - rows, - columns, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ), _ => unreachable!(), } @@ -234,8 +214,7 @@ pub(in super::super) fn project_attention_output( if !std::ptr::eq(session.mtp_context()?, context) { return Err(Error::IdentityMismatch); } - let (kind, rows, columns, weights) = - cache.mtp_matrix(binding, context, MtpRole::AttentionOutput)?; + let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::AttentionOutput)?; if (kind, rows, columns) != (MtpKind::Q8_0, 2560, 6144) { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention.rs index e6f47c2f..1e73123a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention.rs @@ -3,14 +3,10 @@ use super::moe_weight_cache::MoeWeightCache; use super::{ contract::{Error, Result, Stage}, - mtp::{ - DenseKv, MtpFrame, MtpSession, f32_weights, preflight, project, project_attention_output, - reserve, - }, + mtp::{DenseKv, MtpFrame, MtpSession, f32_weights, preflight, project, project_attention_output, reserve}, mtp_gr::MtpAttentionRead, qsa_index::{ - allocate, binding_error, download, download_bytes, driver_error, release, upload, - upload_bytes, validate_values, + allocate, binding_error, download, download_bytes, driver_error, release, upload, upload_bytes, validate_values, }, session::QwenSession, }; @@ -71,28 +67,30 @@ mod impl_mtpattentionready; pub(super) use impl_mtpattentionready::produce_kv_cell; mod release_transport_fn; #[allow(unused_imports)] -use release_transport_fn::release_transport; -#[allow(unused_imports)] -use release_transport_fn::close_transport; -#[allow(unused_imports)] -use release_transport_fn::note_transport; -#[allow(unused_imports)] -use release_transport_fn::upload_transport; -#[allow(unused_imports)] -use release_transport_fn::upload_transport_f32; -#[allow(unused_imports)] use release_transport_fn::attend_retained; #[allow(unused_imports)] use release_transport_fn::attend_ring_retained; #[allow(unused_imports)] +use release_transport_fn::attention_driver_error; +#[allow(unused_imports)] +use release_transport_fn::close_transport; +#[allow(unused_imports)] use release_transport_fn::gate_retained; #[allow(unused_imports)] -use release_transport_fn::attention_driver_error; +use release_transport_fn::note_transport; +#[allow(unused_imports)] +use release_transport_fn::release_transport; +#[allow(unused_imports)] +use release_transport_fn::upload_transport; +#[allow(unused_imports)] +use release_transport_fn::upload_transport_f32; mod geometry_fn; #[allow(unused_imports)] -use geometry_fn::geometry; +use geometry_fn::apply_gate; #[allow(unused_imports)] -use geometry_fn::validate_window; +use geometry_fn::attend; +#[allow(unused_imports)] +use geometry_fn::geometry; #[allow(unused_imports)] use geometry_fn::norm_rope; #[allow(unused_imports)] @@ -100,6 +98,4 @@ use geometry_fn::pack_kv; #[allow(unused_imports)] use geometry_fn::split; #[allow(unused_imports)] -use geometry_fn::attend; -#[allow(unused_imports)] -use geometry_fn::apply_gate; +use geometry_fn::validate_window; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs index 83600f97..701024eb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs @@ -8,11 +8,8 @@ pub(super) fn geometry(position: u64) -> Result { return Err(Error::InvalidPosition); } let position = u32::try_from(position).map_err(|_| Error::InvalidPosition)?; - let width = usize::try_from(position) - .map_err(|_| Error::Overflow)? - .checked_add(1) - .ok_or(Error::Overflow)? - .min(WINDOW); + let width = + usize::try_from(position).map_err(|_| Error::Overflow)?.checked_add(1).ok_or(Error::Overflow)?.min(WINDOW); let half_bytes = width.checked_mul(HALF_CELL).ok_or(Error::Overflow)?; let scratch = width .div_ceil(64) @@ -29,25 +26,14 @@ pub(super) fn geometry(position: u64) -> Result { .and_then(|n| n.checked_add(2 * Q * 4)) .and_then(|n| n.checked_add(2 * 1024 * 1024)) .ok_or(Error::Overflow)?; - Ok(DenseGeometry { - position, - width, - half_bytes, - scratch, - device_bytes, - }) + Ok(DenseGeometry { position, width, half_bytes, scratch, device_bytes }) } pub(super) fn validate_window(keys: &[u8], values: &[u8], geometry: &DenseGeometry) -> Result<()> { if keys.len() != geometry.half_bytes || values.len() != geometry.half_bytes { return Err(Error::InvalidDimension); } for bytes in [keys, values] { - if bytes - .as_chunks::<2>() - .0 - .iter() - .any(|word| u16::from_le_bytes(*word) & 0x7c00 == 0x7c00) - { + if bytes.as_chunks::<2>().0.iter().any(|word| u16::from_le_bytes(*word) & 0x7c00 == 0x7c00) { return Err(Error::NonFinite); } } @@ -93,20 +79,11 @@ pub(super) fn pack_kv(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result = (|| { - context - .qsa_pack_kv(&k, &v, &mut key, &mut value) - .map_err(attention_driver_error)?; - Ok(( - download_bytes(&key, HALF_CELL)?, - download_bytes(&value, HALF_CELL)?, - )) + context.qsa_pack_kv(&k, &v, &mut key, &mut value).map_err(attention_driver_error)?; + Ok((download_bytes(&key, HALF_CELL)?, download_bytes(&value, HALF_CELL)?)) })(); let cleanup = release([k, v, key, value]); let result = result?; @@ -119,9 +96,7 @@ pub(super) fn split(context: &Context<'_>, full: &[f32]) -> Result { let mut q = allocate(context, Q)?; let mut gate = allocate(context, Q)?; let result: Result = (|| { - context - .qsa_split_q_gate(&full, &mut q, &mut gate) - .map_err(attention_driver_error)?; + context.qsa_split_q_gate(&full, &mut q, &mut gate).map_err(attention_driver_error)?; Ok((download(&q, Q)?, download(&gate, Q)?)) })(); let cleanup = release([full, q, gate]); @@ -163,9 +138,7 @@ pub(super) fn apply_gate(context: &Context<'_>, values: &[f32], gate: &[f32]) -> let gate = upload(context, gate)?; let mut out = allocate(context, Q)?; let result: Result> = (|| { - context - .qsa_gate_f32(&x, &gate, &mut out) - .map_err(attention_driver_error)?; + context.qsa_gate_f32(&x, &gate, &mut out).map_err(attention_driver_error)?; download(&out, Q) })(); let cleanup = release([x, gate, out]); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs index 1cb30960..180212c2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs @@ -55,30 +55,15 @@ impl MtpAttentionStage { let context = session.mtp_context()?; let ring_enabled = cache.has_mtp_kv_ring()?; let temporary_bytes = if ring_enabled { - geometry - .device_bytes - .checked_sub(2 * geometry.half_bytes) - .ok_or(Error::Overflow)? + geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)? } else { geometry.device_bytes }; preflight(context, temporary_bytes)?; // Preserve the source K/V-before-query sequence. No indexer, sparse // selection, rotation/INT8/Q4 cache, or target QSA state is substituted. - let k = project( - context, - binding, - MtpRole::KeyProjection, - input.mixed(), - cache, - )?; - let v = project( - context, - binding, - MtpRole::ValueProjection, - input.mixed(), - cache, - )?; + let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?; + let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?; let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?; let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?; let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?; @@ -92,13 +77,7 @@ impl MtpAttentionStage { validate_window(&window.0, &window.1, &geometry)?; Some(window) }; - let full = project( - context, - binding, - MtpRole::QueryProjection, - input.mixed(), - cache, - )?; + let full = project(context, binding, MtpRole::QueryProjection, input.mixed(), cache)?; let (q, gate) = split(context, &full)?; let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?; let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?; @@ -106,21 +85,9 @@ impl MtpAttentionStage { let attention = if let Some((keys, values)) = host_window { attend_retained(context, &q, &keys, &values, &geometry, failed)? } else { - attend_ring_retained( - context, - &q, - &geometry, - failed, - binding, - cache, - &pending, - input.frame(), - )? - }; - let gated = MtpGated { - frame: input.frame().clone(), - numeric: gate_retained(context, attention, &gate)?, + attend_ring_retained(context, &q, &geometry, failed, binding, cache, &pending, input.frame())? }; + let gated = MtpGated { frame: input.frame().clone(), numeric: gate_retained(context, attention, &gate)? }; let result = project_attention_output(context, binding, session, &gated, cache); let cleanup = gated.close(); let output = result?; @@ -130,10 +97,7 @@ impl MtpAttentionStage { draft.prior(input.frame())?; let mut streams = reserve(4 * N)?; streams.extend_from_slice(input.streams()); - let inject = input - .inject() - .try_into() - .map_err(|_| Error::InvalidDimension)?; + let inject = input.inject().try_into().map_err(|_| Error::InvalidDimension)?; Ok(MtpAttentionReady { frame: input.frame().clone(), output, @@ -168,20 +132,8 @@ pub(in super::super) fn produce_kv_cell( } let context = session.mtp_context()?; preflight(context, 2 * 1024 * 1024)?; - let k = project( - context, - binding, - MtpRole::KeyProjection, - input.mixed(), - cache, - )?; - let v = project( - context, - binding, - MtpRole::ValueProjection, - input.mixed(), - cache, - )?; + let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?; + let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?; let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?; let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?; let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs index 1f7f42e5..1f493edd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs @@ -34,9 +34,7 @@ pub(super) fn upload_transport<'ctx>( if failed.get() { return Err(Error::CudaExecution); } - let mut buffer = context - .allocate(bytes.len()) - .map_err(attention_driver_error)?; + let mut buffer = context.allocate(bytes.len()).map_err(attention_driver_error)?; let copy = buffer.copy_from(bytes).map_err(attention_driver_error); note_transport(©, failed); if let Err(primary) = copy { @@ -96,12 +94,7 @@ pub(super) fn attend_retained<'ctx>( y_cleanup?; return Err(Error::CudaExecution); } - Ok(RetainedAttended { - context, - buffer: y, - values: result?, - failed, - }) + Ok(RetainedAttended { context, buffer: y, values: result?, failed }) } // Numeric query/attend/gate/output remains the existing sequence. Only the // canonical K/V ownership moves to the actor's bounded transport mirror. @@ -120,13 +113,7 @@ pub(super) fn attend_ring_retained<'ctx>( return Err(Error::CudaExecution); } validate_values(query, Q)?; - preflight( - context, - geometry - .device_bytes - .checked_sub(2 * geometry.half_bytes) - .ok_or(Error::Overflow)?, - )?; + preflight(context, geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)?)?; let (mut q, mut y) = (None, None); let result = (|| { q = Some(upload_transport_f32(context, query, &failed)?); @@ -150,12 +137,7 @@ pub(super) fn attend_ring_retained<'ctx>( y_cleanup?; return Err(Error::CudaExecution); } - Ok(RetainedAttended { - context, - buffer: y, - values: result?, - failed, - }) + Ok(RetainedAttended { context, buffer: y, values: result?, failed }) } pub(super) fn gate_retained<'ctx>( context: &'ctx Context<'ctx>, @@ -197,12 +179,7 @@ pub(super) fn gate_retained<'ctx>( gated_cleanup?; return Err(Error::CudaExecution); } - Ok(RetainedGated { - context, - buffer: gated, - values: result?, - failed, - }) + Ok(RetainedGated { context, buffer: gated, values: result?, failed }) } pub(super) fn attention_driver_error(error: leleka_cuda_driver::Error) -> Error { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs index 6bd91dc8..b2b322a2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/tests.rs @@ -14,10 +14,7 @@ fn mtp_attention_new_causal_geometry_and_budget_boundaries() { (262143, 32768, 33554432, 12681472), ] { let g = geometry(position).unwrap(); - assert_eq!( - (g.width, g.half_bytes, g.scratch), - (width, half_bytes, scratch) - ); + assert_eq!((g.width, g.half_bytes, g.scratch), (width, half_bytes, scratch)); assert_eq!(g.device_bytes, 2 * half_bytes + scratch + 49152 + 2097152); } for position in [crate::qwen_forward::contract::serving_cells(), u32::MAX as u64, u64::MAX] { @@ -34,10 +31,7 @@ fn mtp_attention_new_window_shape_halfdomains_and_caller_preservation() { values[1022 - 2 * i..1024 - 2 * i].copy_from_slice(&word.to_le_bytes()); } assert!(validate_window(&keys, &values, &g).is_ok()); - assert_eq!( - validate_window(&keys[..1023], &values, &g), - Err(Error::InvalidDimension) - ); + assert_eq!(validate_window(&keys[..1023], &values, &g), Err(Error::InvalidDimension)); for word in [0x7c00u16, 0xfc00, 0x7e00] { let mut bad = values.clone(); bad[1022..].copy_from_slice(&word.to_le_bytes()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention_reuse_gpu.rs index ab265990..32e50acc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention_reuse_gpu.rs @@ -31,16 +31,10 @@ fn half_kv(width: usize, zero: bool) -> (Vec, Vec) { // Original dense qsa_decode_attn.cu layout: ((cell*2+head)*256+dimension). const KEY: [u16; 6] = [0x0000, 0x3400, 0xb800, 0x3a00, 0xbc00, 0x3800]; const VALUE: [u16; 6] = [0x3c00, 0xbc00, 0x4000, 0xb800, 0x3400, 0x4200]; - let keys = (0..width * 512) - .flat_map(|i| KEY[(i * 7 + i / 256) % 6].to_le_bytes()) - .collect(); + let keys = (0..width * 512).flat_map(|i| KEY[(i * 7 + i / 256) % 6].to_le_bytes()).collect(); let values = (0..width * 512) .flat_map(|i| { - let word = if zero { - if i % 2 == 0 { 0x8000u16 } else { 0 } - } else { - VALUE[(i * 11 + i / 512) % 6] - }; + let word = if zero { if i % 2 == 0 { 0x8000u16 } else { 0 } } else { VALUE[(i * 11 + i / 512) % 6] }; word.to_le_bytes() }) .collect(); @@ -61,9 +55,7 @@ fn original_transfer_chain( let k = upload_bytes(context, keys).unwrap(); let v = upload_bytes(context, values).unwrap(); let mut y = allocate(context, Q).unwrap(); - context - .mtp_dense_attend_f16(&q, &k, &v, &mut y, position) - .unwrap(); + context.mtp_dense_attend_f16(&q, &k, &v, &mut y, position).unwrap(); let attended = download(&y, Q).unwrap(); release([q, k, v, y]).unwrap(); let a = upload(context, &attended).unwrap(); @@ -79,11 +71,7 @@ fn original_transfer_chain( matrix, &a, &mut y, - ProjectionSpec { - rows: 2560, - columns: Q, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows: 2560, columns: Q, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ) .unwrap(); let out = download(&y, 2560).unwrap(); @@ -104,63 +92,31 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals( let shape = geometry(u64::from(position)).unwrap(); let width = shape.width; let query: Vec = (0..Q) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - (i % 17) as f32 / 64. - 8. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 17) as f32 / 64. - 8. / 64. }) .collect(); let gate: Vec = (0..Q) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - (i % 13) as f32 / 8. - 6. / 8. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 13) as f32 / 8. - 6. / 8. }) .collect(); let query_bits: Vec = query.iter().map(|v| v.to_bits()).collect(); let gate_bits: Vec = gate.iter().map(|v| v.to_bits()).collect(); let (keys, values) = half_kv(width, zero); - let legacy = - original_transfer_chain(&context, &query, &keys, &values, &gate, position, &matrix); + let legacy = original_transfer_chain(&context, &query, &keys, &values, &gate, position, &matrix); let charged = context.allocated_bytes(); - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); exact(attended.values(), &legacy.0); assert_eq!(context.allocated_bytes(), charged + Q * 4); let gated = gate_retained(&context, attended, &gate).unwrap(); exact(gated.values(), &legacy.1); assert_eq!(context.allocated_bytes(), charged + Q * 4); let mut actual_bytes = vec![0; Q * 4]; - gated - .buffer(&context) - .unwrap() - .copy_to(&mut actual_bytes) - .unwrap(); - assert_eq!( - actual_bytes, - legacy - .1 - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); - let actual = - super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).unwrap(); + gated.buffer(&context).unwrap().copy_to(&mut actual_bytes).unwrap(); + assert_eq!(actual_bytes, legacy.1.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let actual = super::super::mtp::project_attention_out_numeric(&context, &matrix, &gated).unwrap(); exact(&actual, &legacy.2); gated.close().unwrap(); assert_eq!(context.allocated_bytes(), charged); - assert_eq!( - query.iter().map(|v| v.to_bits()).collect::>(), - query_bits - ); - assert_eq!( - gate.iter().map(|v| v.to_bits()).collect::>(), - gate_bits - ); + assert_eq!(query.iter().map(|v| v.to_bits()).collect::>(), query_bits); + assert_eq!(gate.iter().map(|v| v.to_bits()).collect::>(), gate_bits); println!("MTP_RETAINED PAIR width={width} zero={zero} exact_words=14848"); } let mut unchanged = vec![0; weights.len()]; @@ -174,15 +130,7 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals( let (keys, values) = half_kv(1, false); let shape = geometry(0).unwrap(); assert_eq!( - attend_retained( - &context, - &query[..Q - 1], - &keys, - &values, - &shape, - failed.clone() - ) - .err(), + attend_retained(&context, &query[..Q - 1], &keys, &values, &shape, failed.clone()).err(), Some(Error::InvalidDimension) ); let mut bad_query = query.clone(); @@ -192,15 +140,7 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals( Some(Error::NonFinite) ); assert_eq!( - attend_retained( - &context, - &query, - &keys[..1022], - &values, - &shape, - failed.clone() - ) - .err(), + attend_retained(&context, &query, &keys[..1022], &values, &shape, failed.clone()).err(), Some(Error::InvalidDimension) ); let mut bad_keys = keys.clone(); @@ -234,12 +174,10 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals( // Successful abandoned owners exercise the new Drop fallback. This is // ownership/abort evidence only, not an additional numeric oracle pair. - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); attended.close().unwrap(); assert_eq!(context.allocated_bytes(), 0); - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); let abandoned = gate_retained(&context, attended, &gate).unwrap(); assert_eq!(context.allocated_bytes(), Q * 4); drop(abandoned); @@ -250,30 +188,17 @@ fn retained_mtp_attention_gate_out_matches_legacy_transfers_and_cleans_refusals( let mut bad_gate = gate.clone(); bad_gate[Q - 1] = f32::NAN; for malformed in [&bad_gate[..], &gate[..Q - 1]] { - let expected = if malformed.len() == Q { - Error::NonFinite - } else { - Error::InvalidDimension - }; - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); - assert_eq!( - gate_retained(&context, attended, malformed).err(), - Some(expected) - ); + let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension }; + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + assert_eq!(gate_retained(&context, attended, malformed).err(), Some(expected)); assert_eq!(context.allocated_bytes(), 0); } - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); - assert_eq!( - gate_retained(&foreign, attended, &gate).err(), - Some(Error::IdentityMismatch) - ); + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + assert_eq!(gate_retained(&foreign, attended, &gate).err(), Some(Error::IdentityMismatch)); assert_eq!(context.allocated_bytes(), 0); assert_eq!(foreign.allocated_bytes(), 0); - let attended = - attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); + let attended = attend_retained(&context, &query, &keys, &values, &shape, failed.clone()).unwrap(); let gated = gate_retained(&context, attended, &gate).unwrap(); assert_eq!(gated.buffer(&foreign).err(), Some(Error::IdentityMismatch)); let malformed = upload_bytes(&context, &[0; 2]).unwrap(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs index ec5b8033..ac44fb49 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode.rs @@ -52,16 +52,10 @@ mod tests { assert!(MtpWindowSpec::new(depth, 10, Some(eos)).is_ok()); } for depth in [0, 5, usize::MAX] { - assert!(matches!( - MtpWindowSpec::new(depth, 10, None), - Err(Error::InvalidDimension) - )); + assert!(matches!(MtpWindowSpec::new(depth, 10, None), Err(Error::InvalidDimension))); } let foreign = TokenId::new(1, Dimension::new(2).unwrap()).unwrap(); - assert!(matches!( - MtpWindowSpec::new(1, 10, Some(foreign)), - Err(Error::InvalidToken) - )); + assert!(matches!(MtpWindowSpec::new(1, 10, Some(foreign)), Err(Error::InvalidToken))); } #[test] @@ -84,10 +78,8 @@ mod draft_bound_tests { #[test] fn original_first_consumed_prefix_matches_capacity_depth_remaining_and_eos() { let vocabulary = Dimension::new(248320).unwrap(); - let original_predictions = [101, 203, 307, 409, 503] - .map(|id| TokenId::new(id, vocabulary).unwrap()); - let candidate_predictions = [101, 203, 307, 409, 503] - .map(|id| TokenId::new(id, vocabulary).unwrap()); + let original_predictions = [101, 203, 307, 409, 503].map(|id| TokenId::new(id, vocabulary).unwrap()); + let candidate_predictions = [101, 203, 307, 409, 503].map(|id| TokenId::new(id, vocabulary).unwrap()); let absent_eos = TokenId::new(248044, vocabulary).unwrap(); for position in [0, 262140, 262142] { for depth in 1..=4 { @@ -109,11 +101,8 @@ mod draft_bound_tests { original_steps += 1; } } - let original_rows = if Some(original[0]) == eos { - 0 - } else { - capacity.min(limit).min(original.len()) - }; + let original_rows = + if Some(original[0]) == eos { 0 } else { capacity.min(limit).min(original.len()) }; let original_consumed = &original[..original_rows]; let mut candidate = vec![candidate_predictions[0]]; @@ -128,11 +117,8 @@ mod draft_bound_tests { candidate_steps += 1; } } - let candidate_rows = if Some(candidate[0]) == eos { - 0 - } else { - capacity.min(limit).min(candidate.len()) - }; + let candidate_rows = + if Some(candidate[0]) == eos { 0 } else { capacity.min(limit).min(candidate.len()) }; assert_eq!(&candidate[..candidate_rows], original_consumed); assert_eq!(candidate_steps, candidate.len() - 1); assert!(candidate_steps <= needed); @@ -140,8 +126,7 @@ mod draft_bound_tests { if candidate_rows == 0 { assert_eq!(candidate_steps, 0); } else { - assert_eq!(candidate.last().copied() == eos, - original_consumed.last().copied() == eos); + assert_eq!(candidate.last().copied() == eos, original_consumed.last().copied() == eos); } } } @@ -177,8 +162,8 @@ pub(in crate::qwen_forward) mod batch_gpu; mod impl_mtpwindowspec; #[allow(unused_imports)] use impl_mtpwindowspec::kv_prefill_host_charge; -mod impl_mtpdecoder; mod first_seed_reuse_enabled_fn; +mod impl_mtpdecoder; #[allow(unused_imports)] use first_seed_reuse_enabled_fn::first_seed_reuse_enabled; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled_fn.rs index 46a3a4ea..c8d89dc9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/first_seed_reuse_enabled_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // Only the selected adaptive policy, with numerical observer paths unchanged. pub(super) fn first_seed_reuse_enabled(cache: &MoeWeightCache<'_>) -> bool { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -25,14 +24,8 @@ pub(super) fn needed_draft_predictions(capacity: usize, limit: usize) -> Result< pub(super) fn window_limit(position: u64, depth: usize, remaining: usize) -> Result { let next = position.checked_add(1).ok_or(Error::Overflow)?; let available = crate::qwen_forward::contract::serving_cells().checked_sub(next).ok_or(Error::InvalidPosition)?; - let limit = depth - .min(remaining) - .min(usize::try_from(available).map_err(|_| Error::Overflow)?); - if limit == 0 { - Err(Error::InvalidPosition) - } else { - Ok(limit) - } + let limit = depth.min(remaining).min(usize::try_from(available).map_err(|_| Error::Overflow)?); + if limit == 0 { Err(Error::InvalidPosition) } else { Ok(limit) } } // Callback cancellation is remembered across a provider call. Translate only diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs index 024ebc10..a3921ff3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2.rs @@ -3,23 +3,14 @@ #[allow(unused_imports)] use super::*; - impl MtpDecoder { pub(crate) fn new(binding: &ModelBinding) -> Result { - Ok(Self { - draft: MtpSession::new(binding)?, - kv_prefill: None, - kv_prefill_host_charge: 0, - }) + Ok(Self { draft: MtpSession::new(binding)?, kv_prefill: None, kv_prefill_host_charge: 0 }) } /// Fresh explicit outer256 policy, using the entire actual framed prompt. /// The original Native constructor and retained continuations stay unchanged. - pub(crate) fn new_kv_prefill( - binding: &ModelBinding, - target: &QwenSession<'_>, - prompt: &[u32], - ) -> Result { + pub(crate) fn new_kv_prefill(binding: &ModelBinding, target: &QwenSession<'_>, prompt: &[u32]) -> Result { let mut decoder = Self::new(binding)?; if prompt.len() == 1 { return Ok(decoder); @@ -37,21 +28,14 @@ impl MtpDecoder { for &token in prompt { tokens.push(TokenId::new(u64::from(token), vocabulary)?); } - decoder.kv_prefill = Some(mtp::MtpKvPrefill::new( - binding, - target, - &decoder.draft, - &tokens, - )?); + decoder.kv_prefill = Some(mtp::MtpKvPrefill::new(binding, target, &decoder.draft, &tokens)?); decoder.kv_prefill_host_charge = host_charge; Ok(decoder) } /// Persistent baseline remains charged while any warming owner is live. pub(crate) fn prefill_host_remaining(&self, available: usize) -> Result { - available - .checked_sub(self.kv_prefill_host_charge) - .ok_or(Error::InputAllocation) + available.checked_sub(self.kv_prefill_host_charge).ok_or(Error::InputAllocation) } /// Require the actual final target head and the jointly published real @@ -90,9 +74,7 @@ impl MtpDecoder { { return Err(Error::IdentityMismatch); } - let frame = self - .draft - .frame(binding, position, source.predicted(target)?, origin)?; + let frame = self.draft.frame(binding, position, source.predicted(target)?, origin)?; frame.validate(binding, target)?; self.draft.prior(&frame)?; Ok(()) @@ -108,9 +90,7 @@ impl MtpDecoder { ) -> Result { self.validate_resume(binding, target, source, committed)?; let (_, position, _, origin) = source.mtp_source(binding, target)?; - let frame = self - .draft - .frame(binding, position, source.predicted(target)?, origin)?; + let frame = self.draft.frame(binding, position, source.predicted(target)?, origin)?; frame.validate(binding, target)?; self.draft.test_prefix_snapshot(binding, &frame) } @@ -129,8 +109,7 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = - MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; + let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; mtp::step(binding, target, &mut self.draft, input, output, cache)?; Ok(()) })(); @@ -154,8 +133,7 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = - MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; + let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?; mtp::warm_step(binding, target, &mut self.draft, input, cache) })(); if let Err(error) = result { @@ -176,8 +154,7 @@ impl MtpDecoder { ) -> Result<()> { let prior = self.draft.checkpoint()?; let result = (|| { - let input = - MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; + let input = MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?; mtp::warm_step(binding, target, &mut self.draft, input, cache) })(); if let Err(error) = result { @@ -202,29 +179,9 @@ impl MtpDecoder { cancelled: impl FnMut() -> bool, ) -> std::result::Result { if cache.requires_iq3_mmq_admission() { - self.window_batched( - binding, - source, - target, - output, - kar_cache, - cache, - dense_cache, - spec, - cancelled, - ) + self.window_batched(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled) } else { - self.window_scalar( - binding, - source, - target, - output, - kar_cache, - cache, - dense_cache, - spec, - cancelled, - ) + self.window_scalar(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled) } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs index 5c0d5d11..ce35f894 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_2_2.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl MtpDecoder { - /// Selected only by the existing explicit IQ3 integer/native Down policy. /// Draft depth remains configured; target batch capacity is separately /// admitted. Only predictions consumed by that capacity are generated/countable. @@ -44,9 +42,10 @@ impl MtpDecoder { let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 }; let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?; let host_remaining = if reuse_first_seed { - host_remaining.checked_sub(seed_host_charge) - .ok_or(Error::InputAllocation)? - } else { host_remaining }; + host_remaining.checked_sub(seed_host_charge).ok_or(Error::InputAllocation)? + } else { + host_remaining + }; // Pure complete-state admission before any draft/canonical mutation. let capacity = QwenForward::mtp_target_window_capacity( binding, @@ -58,7 +57,9 @@ impl MtpDecoder { // Independent actual CPU wave and ephemeral staging coexist. // Both are inside the unchanged 512MiB request admission. host_remaining.checked_sub((48 + 16) * 1024 * 1024).ok_or(Error::InputAllocation)? - } else { host_remaining }, + } else { + host_remaining + }, )?; let target_prior = target.checkpoint()?; let mut draft_priors = reserve(1)?; @@ -79,21 +80,11 @@ impl MtpDecoder { break; } let input = match previous.as_ref() { - Some(product) => { - MtpInput::from_previous(binding, target, &self.draft, product, cache)? - } - None => MtpInput::from_target( - binding, - target, - &self.draft, - &source, - candidate, - cache, - )?, + Some(product) => MtpInput::from_previous(binding, target, &self.draft, product, cache)?, + None => MtpInput::from_target(binding, target, &self.draft, &source, candidate, cache)?, }; - let seed_frame = if reuse_first_seed && previous.is_none() { - Some(input.frame().clone()) - } else { None }; + let seed_frame = + if reuse_first_seed && previous.is_none() { Some(input.frame().clone()) } else { None }; let product = mtp::step(binding, target, &mut self.draft, input, output, cache)?; if let Some(frame) = seed_frame { first_seed = Some((self.draft.checkpoint_first_seed(seed_host_charge)?, frame)); @@ -106,14 +97,10 @@ impl MtpDecoder { if let Some((seed, frame)) = first_seed { // Recheck the authoritative target source before coupled restore. source.mtp_source(binding, target)?; - if source.predicted(target)? != frame.token() - || source.position(target)? != frame.position() - { + if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() { return Err(Error::IdentityMismatch.into()); } - self.draft.restore_first_seed( - binding, target, &frame, &seed, &mut draft_priors[0], - )?; + self.draft.restore_first_seed(binding, target, &frame, &seed, &mut draft_priors[0])?; // The seed is now the actual committed draft; dropping its extra // checkpoint precedes target journal/catchup allocation. } else { @@ -136,7 +123,9 @@ impl MtpDecoder { // Complete the previous refill after genuine draft compute but before // target window journal allocation, preserving the shared host cap. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - if cache.uses_strata_adaptive_experts() { cache.poll_strata_adaptive(binding, true)?; } + if cache.uses_strata_adaptive_experts() { + cache.poll_strata_adaptive(binding, true)?; + } let pending_result = { let mut observe_cancel = || { let current = cancelled(); @@ -157,11 +146,9 @@ impl MtpDecoder { &mut observe_cancel, ) }; - let pending = - pending_result.map_err(|error| window_stage_error(error, stage_cancelled))?; + let pending = pending_result.map_err(|error| window_stage_error(error, stage_cancelled))?; let accepted = pending.accepted_rows(); - if accepted == 0 || accepted > rows || accepted > capacity || accepted > spec.remaining - { + if accepted == 0 || accepted > rows || accepted > capacity || accepted > spec.remaining { return Err(Error::IdentityMismatch.into()); } // Capacity was reserved before work; accepted IDs/counters are @@ -174,7 +161,13 @@ impl MtpDecoder { stage_cancelled |= current; current }; - pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense_cache), &mut observe_cancel) + pending.publish_joint_with_gdn_replay( + binding, + &mut self.draft, + cache, + Some(dense_cache), + &mut observe_cancel, + ) }; let product = published.map_err(|error| window_stage_error(error, stage_cancelled))?; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -191,12 +184,7 @@ impl MtpDecoder { Ok((product, eos, draft_steps)) })(); match result { - Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { - tokens, - latest: product, - eos, - draft_steps, - }), + Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens, latest: product, eos, draft_steps }), Err(error) => { if let MtpWindowError::Forward(cause) = error { target.note_mtp_failure(&cause); @@ -213,7 +201,9 @@ impl MtpDecoder { } #[cfg(test)] if target_restore.is_err() || draft_restore.is_err() { - eprintln!("MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}"); + eprintln!( + "MTP candidate rollback primary={error:?} target={target_restore:?} draft={draft_restore:?}" + ); } let _ = draft_restore; Err(error) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs index 303c6320..d885a8e1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpdecoder/impl_mtpdecoder_3.rs @@ -3,9 +3,7 @@ #[allow(unused_imports)] use super::*; - impl MtpDecoder { - #[allow(clippy::too_many_arguments)] pub(crate) fn window_scalar( &mut self, @@ -26,20 +24,10 @@ impl MtpDecoder { return Err(MtpWindowError::Cancelled); } if spec.remaining == 0 { - return Ok(MtpVerifiedWindow { - tokens: Vec::new(), - latest: source, - eos: false, - draft_steps: 0, - }); + return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos: false, draft_steps: 0 }); } if Some(first) == spec.eos { - return Ok(MtpVerifiedWindow { - tokens: Vec::new(), - latest: source, - eos: true, - draft_steps: 0, - }); + return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos: true, draft_steps: 0 }); } let limit = window_limit(source_position, spec.depth, spec.remaining)?; let target_prior = target.checkpoint()?; @@ -63,9 +51,7 @@ impl MtpDecoder { break; } let input = match previous.as_ref() { - Some(product) => { - MtpInput::from_previous(binding, target, &self.draft, product, cache)? - } + Some(product) => MtpInput::from_previous(binding, target, &self.draft, product, cache)?, None => MtpInput::from_target( binding, target, @@ -105,10 +91,8 @@ impl MtpDecoder { break; } let offset = u64::try_from(tokens.len()).map_err(|_| Error::Overflow)?; - let position = source_position - .checked_add(1) - .and_then(|p| p.checked_add(offset)) - .ok_or(Error::Overflow)?; + let position = + source_position.checked_add(1).and_then(|p| p.checked_add(offset)).ok_or(Error::Overflow)?; // Rebuild persistent cell i from CURRENT actual target R_i and // verified token i+1 before target advancement invalidates R_i. // Do not call warm(): its nested rewind would invalidate this @@ -153,12 +137,7 @@ impl MtpDecoder { Ok((product, eos, draft_steps)) })(); match result { - Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { - tokens, - latest: product, - eos, - draft_steps, - }), + Ok((product, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens, latest: product, eos, draft_steps }), Err(error) => { if let MtpWindowError::Forward(cause) = error { target.note_mtp_failure(&cause); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpwindowspec.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpwindowspec.rs index 2226f7d1..d6280a1f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpwindowspec.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode/impl_mtpwindowspec.rs @@ -13,11 +13,7 @@ impl MtpWindowSpec { { return Err(Error::InvalidToken); } - Ok(Self { - depth, - remaining, - eos, - }) + Ok(Self { depth, remaining, eos }) } } impl From for MtpWindowError { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs index 1b1125a7..7efeffed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decode_chunk.rs @@ -47,9 +47,7 @@ impl MtpDecoder { cancelled: impl FnMut() -> bool, ) -> Result> { if self.kv_prefill.is_none() { - return self - .stage_prefill_chunk(binding, txn, cache, cancelled) - .map(ReadyMtpPrefill::Full); + return self.stage_prefill_chunk(binding, txn, cache, cancelled).map(ReadyMtpPrefill::Full); } self.kv_prefill .as_mut() @@ -101,14 +99,7 @@ impl MtpDecoder { if cancelled() { return Err(Error::Unsupported(super::super::contract::Stage::Executor)); } - let ready = ReadyMtpChunk { - stage, - binding, - start, - end, - draft_end, - warmed, - }; + let ready = ReadyMtpChunk { stage, binding, start, end, draft_end, warmed }; ready.validate(txn)?; Ok(ready) } @@ -126,12 +117,7 @@ impl ChunkDraftPublication for ReadyMtpChunk<'_, '_> { let mut warmed = 0; for (index, row) in txn.rows().iter().enumerate() { let (_, position, next, _) = txn.validate_row(row)?; - if position.get() - != self - .start - .checked_add(index as u64) - .ok_or(Error::Overflow)? - { + if position.get() != self.start.checked_add(index as u64).ok_or(Error::Overflow)? { return Err(Error::IdentityMismatch); } match next { @@ -143,8 +129,7 @@ impl ChunkDraftPublication for ReadyMtpChunk<'_, '_> { if warmed != self.warmed || self.start.checked_add(warmed as u64) != Some(self.draft_end) { return Err(Error::IdentityMismatch); } - self.stage - .validate_completed(self.binding, txn.original_session()?, self.draft_end) + self.stage.validate_completed(self.binding, txn.original_session()?, self.draft_end) } fn publish(self) { @@ -157,10 +142,7 @@ impl MtpDecoder { pub(in crate::qwen_forward) fn test_chunk_snapshot(&self) -> mtp::MtpChunkNumericSnapshot { self.draft.test_chunk_snapshot() } - pub(in crate::qwen_forward) fn test_chunk_eq( - &self, - expected: &mtp::MtpChunkNumericSnapshot, - ) -> bool { + pub(in crate::qwen_forward) fn test_chunk_eq(&self, expected: &mtp::MtpChunkNumericSnapshot) -> bool { self.draft.test_chunk_eq(expected) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs index b53722cb..e4149e4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu.rs @@ -67,10 +67,7 @@ struct Report { #[ignore = "Root-only exact pinned binding/one load/changed GPU boundary; no live overlap"] fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() { assert!(env::var("LELEKA_STRA169_RUN_MTP_BATCH_NUMERIC").is_ok_and(|v| v == "yes")); - let fd: u32 = env::var("LELEKA_STRA169_KAR_FD") - .expect("sealed FD missing") - .parse() - .unwrap(); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("sealed FD missing").parse().unwrap(); assert!((3..=1048576).contains(&fd)); let shard0 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).unwrap(); let shard1 = VerifiedGgufFile::open(&path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).unwrap(); @@ -90,9 +87,8 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() { let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap(); let mut cache = Some(MoeWeightCache::new(&binding, context.as_ref()).unwrap()); let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap(); - let numerical = catch_unwind(AssertUnwindSafe(|| { - check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense) - })); + let numerical = + catch_unwind(AssertUnwindSafe(|| check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense))); COLLECTOR.with(|s| { s.borrow_mut().take(); }); @@ -124,13 +120,8 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() { report.predicates.len(), report.guards ); - assert!( - report.predicates.iter().all(|p| *p), - "authentic changed MTP numerical/transaction predicate failed" - ); - eprintln!( - "MTP_BATCH_COMPLETE exact=true allocated_bytes=0 context_closed=true speed_claim=false" - ); + assert!(report.predicates.iter().all(|p| *p), "authentic changed MTP numerical/transaction predicate failed"); + eprintln!("MTP_BATCH_COMPLETE exact=true allocated_bytes=0 context_closed=true speed_claim=false"); } #[path = "mtp_decoder_batch_gpu/impl_collection.rs"] @@ -138,19 +129,19 @@ mod impl_collection; #[allow(unused_imports)] pub(in crate::qwen_forward) use impl_collection::after_joint_publish; #[allow(unused_imports)] -pub(in crate::qwen_forward) use impl_collection::collecting; -#[allow(unused_imports)] pub(in crate::qwen_forward) use impl_collection::collect_head; #[allow(unused_imports)] pub(in crate::qwen_forward) use impl_collection::collect_row; #[allow(unused_imports)] -use impl_collection::observe; -#[allow(unused_imports)] -use impl_collection::row_matches; +pub(in crate::qwen_forward) use impl_collection::collecting; #[allow(unused_imports)] use impl_collection::different_token; #[allow(unused_imports)] +use impl_collection::observe; +#[allow(unused_imports)] use impl_collection::path; +#[allow(unused_imports)] +use impl_collection::row_matches; #[path = "mtp_decoder_batch_gpu/check_loaded_fn.rs"] mod check_loaded_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs index 06ae4d4e..cc68a45e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/check_loaded_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[allow(clippy::too_many_arguments)] pub(super) fn check_loaded<'ctx>( binding: &ModelBinding, @@ -17,13 +16,10 @@ pub(super) fn check_loaded<'ctx>( // this explicit host cap; production transaction remains exactly512MiB. assert!(ROW_CAP.checked_mul(10).unwrap() + TRANSACTION_CAP + 4 * 1024 * 1024 <= SNAPSHOT_CAP); assert_eq!(binding.layer_count(), 48); - let disposition = binding - .ordered_layers() - .iter() - .fold((0, 0), |(g, q), d| match d.kind() { - crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q), - crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1), - }); + let disposition = binding.ordered_layers().iter().fold((0, 0), |(g, q), d| match d.kind() { + crate::model_binding::qwen4exp_input::BoundLayerKind::Gdn => (g + 1, q), + crate::model_binding::qwen4exp_input::BoundLayerKind::Qsa => (g, q + 1), + }); assert_eq!(disposition, (36, 12)); let bounds = crate::qwen_forward::contract::position_dimension(); let vocab = Dimension::new(VOCAB as u64).unwrap(); @@ -48,9 +44,7 @@ pub(super) fn check_loaded<'ctx>( let seed_expected = observe(binding, &target, output, &source); let seed = source.predicted(&target).unwrap(); let mut draft = MtpDecoder::new(binding).unwrap(); - draft - .warm_retained(binding, &mut target, &source, seed, native) - .expect("actual seed draft warm refused"); + draft.warm_retained(binding, &mut target, &source, seed, native).expect("actual seed draft warm refused"); let row0 = QwenForward::step_for_mtp_cached( binding, seed, @@ -64,9 +58,7 @@ pub(super) fn check_loaded<'ctx>( .expect("scalar row0 refused"); let expected0 = observe(binding, &target, output, &row0); let next = row0.predicted(&target).unwrap(); - draft - .warm_retained(binding, &mut target, &row0, next, native) - .expect("actual row0 draft warm refused"); + draft.warm_retained(binding, &mut target, &row0, next, native).expect("actual row0 draft warm refused"); let row1 = QwenForward::step_for_mtp_cached( binding, next, @@ -83,9 +75,7 @@ pub(super) fn check_loaded<'ctx>( let true_next = row1.predicted(&target).unwrap(); let wrong = different_token(&[seed, next, true_next]); let prior = target.checkpoint().unwrap(); - draft - .warm_retained(binding, &mut target, &row1, true_next, native) - .expect("continuation draft warm refused"); + draft.warm_retained(binding, &mut target, &row1, true_next, native).expect("continuation draft warm refused"); let continued = QwenForward::step_for_mtp_cached( binding, true_next, @@ -128,12 +118,7 @@ pub(super) fn check_loaded<'ctx>( ); let candidate = cache_slot.as_mut().unwrap(); QwenForward::reset(&mut target).unwrap(); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&fresh), - ); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh)); output.test_reset_replay_record(true).unwrap(); let source = QwenForward::step_for_mtp_cached( binding, @@ -157,9 +142,7 @@ pub(super) fn check_loaded<'ctx>( drop(seed_expected); output.test_reset_replay_record(false).unwrap(); let mut decoder = MtpDecoder::new(binding).unwrap(); - decoder - .warm_retained(binding, &mut target, &source, seed, candidate) - .unwrap(); + decoder.warm_retained(binding, &mut target, &source, seed, candidate).unwrap(); let target_before = target.test_reset_replay_snapshot(binding).unwrap(); let draft_before = decoder.test_chunk_snapshot(); let target_prior = target.checkpoint().unwrap(); @@ -198,10 +181,7 @@ pub(super) fn check_loaded<'ctx>( drop(at_eos); report.guards += 1; report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&target_before) + target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before) && decoder.test_chunk_eq(&draft_before), ); // ONE actual completed T3 transaction. Cancellation is at the private @@ -237,10 +217,7 @@ pub(super) fn check_loaded<'ctx>( report.check(matches!(cancelled, Err(Error::Unsupported(Stage::Executor))) && phase_calls == 3); report.guards += 1; report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&target_before) + target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before) && decoder.test_chunk_eq(&draft_before), ); report.check(target.restore_checkpoint(&target_prior).is_ok()); @@ -251,12 +228,7 @@ pub(super) fn check_loaded<'ctx>( // the seed; never relabel that product as a fresh origin. drop(source); QwenForward::reset(&mut target).unwrap(); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&fresh), - ); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh)); let source = QwenForward::step_for_mtp_cached( binding, zero, @@ -292,10 +264,7 @@ pub(super) fn check_loaded<'ctx>( report.words += VOCAB + 10240; report.guards += 1; report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&target_before) + target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&target_before) && decoder.test_chunk_eq(&automatic_draft_before), ); drop(actual); @@ -305,12 +274,7 @@ pub(super) fn check_loaded<'ctx>( // Automatic full restore invalidates the consumed source. Recover via // genuine reset/forward, never a clone/remint of that stale capability. QwenForward::reset(&mut target).unwrap(); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&fresh), - ); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh)); let source = QwenForward::step_for_mtp_cached( binding, zero, @@ -323,9 +287,7 @@ pub(super) fn check_loaded<'ctx>( ) .expect("automatic caller cancellation recovery refused"); let mut decoder = MtpDecoder::new(binding).unwrap(); - decoder - .warm_retained(binding, &mut target, &source, seed, candidate) - .unwrap(); + decoder.warm_retained(binding, &mut target, &source, seed, candidate).unwrap(); let pending = QwenForward::prepare_mtp_target_window( binding, &source, @@ -341,23 +303,14 @@ pub(super) fn check_loaded<'ctx>( ) .expect("SomeEOS accepted prefix refused"); report.check(pending.accepted_rows() == 2); - let latest = pending - .publish_joint(binding, &mut decoder.draft, candidate, || false) - .expect("real jointprefix refused"); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&expected1.state), - ); + let latest = + pending.publish_joint(binding, &mut decoder.draft, candidate, || false).expect("real jointprefix refused"); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&expected1.state)); report.check(decoder.test_chunk_eq(&expected_draft)); let (_, _, streams, _) = latest.mtp_source(binding, &target).unwrap(); report.check( latest.predicted(&target).unwrap() == expected1.head - && streams - .iter() - .map(|v| v.to_bits()) - .eq(expected1.residual.iter().copied()), + && streams.iter().map(|v| v.to_bits()).eq(expected1.residual.iter().copied()), ); drop(expected0); drop(expected1); @@ -383,12 +336,7 @@ pub(super) fn check_loaded<'ctx>( report.check(row_matches(&observed[0], &expected_continued)); let (tokens, latest, stopped) = window.into_parts(); report.check(tokens == vec![true_next] && !stopped); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&expected_continued.state), - ); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&expected_continued.state)); report.check(decoder.test_chunk_eq(&continued_draft)); report.words += VOCAB + 10240; drop(observed); @@ -433,22 +381,13 @@ pub(super) fn check_loaded<'ctx>( report.check(stopped); report.guards += 1; report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&before) - && decoder.test_chunk_eq(&draft_before), + target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&before) && decoder.test_chunk_eq(&draft_before), ); drop(latest); drop(decoder); drop(before); drop(draft_before); QwenForward::reset(&mut target).unwrap(); - report.check( - target - .test_reset_replay_snapshot(binding) - .unwrap() - .numeric_eq(&fresh), - ); + report.check(target.test_reset_replay_snapshot(binding).unwrap().numeric_eq(&fresh)); report } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/impl_collection.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/impl_collection.rs index 5cf970ba..2b851281 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/impl_collection.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_decoder_batch_gpu/impl_collection.rs @@ -14,24 +14,17 @@ impl Collection { return Err(Error::IdentityMismatch); } let mut rows = Vec::new(); - rows.try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; *slot = Some(Collector { rows, count }); Ok(Self) }) } pub(super) fn finish(self) -> Result> { COLLECTOR.with(|slot| { - let collected = slot - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)? - .take() - .ok_or(Error::IdentityMismatch)?; + let collected = + slot.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take().ok_or(Error::IdentityMismatch)?; if collected.rows.len() != collected.count - || collected - .rows - .iter() - .any(|r| r.head.is_none() || r.state.is_none() || r.residual.len() != 10240) + || collected.rows.iter().any(|r| r.head.is_none() || r.state.is_none() || r.residual.len() != 10240) { return Err(Error::IdentityMismatch); } @@ -95,9 +88,7 @@ pub(in crate::qwen_forward) fn collect_head( return Err(Error::IdentityMismatch); } let mut logits = Vec::new(); - logits - .try_reserve_exact(VOCAB) - .map_err(|_| Error::InputAllocation)?; + logits.try_reserve_exact(VOCAB).map_err(|_| Error::InputAllocation)?; for word in words { if logits.len() == VOCAB || !f32::from_bits(word).is_finite() { return Err(Error::NonFinite); @@ -141,8 +132,7 @@ pub(in crate::qwen_forward) fn collect_row( return Err(Error::IdentityMismatch); } let mut bits = Vec::new(); - bits.try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + bits.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; bits.extend(residual.iter().map(|v| v.to_bits())); row.head = Some(head); row.residual = bits.into_boxed_slice(); @@ -156,15 +146,9 @@ pub(super) fn observe( output: &OutputStage<'_, '_>, source: &TargetStepProduct, ) -> Expected { - let (token, position, streams, _) = source - .mtp_source(binding, session) - .expect("actual scalar source refused"); - let state = session - .test_reset_replay_snapshot(binding) - .expect("actual complete scalar state refused"); - let logits = output - .test_reset_replay_take_logits() - .expect("full scalar head absent"); + let (token, position, streams, _) = source.mtp_source(binding, session).expect("actual scalar source refused"); + let state = session.test_reset_replay_snapshot(binding).expect("actual complete scalar state refused"); + let logits = output.test_reset_replay_take_logits().expect("full scalar head absent"); assert_eq!(logits.len(), VOCAB); assert!(logits.iter().all(|v| f32::from_bits(*v).is_finite())); assert_eq!(streams.len(), 10240); @@ -185,10 +169,7 @@ pub(super) fn row_matches(actual: &RowObservation, expected: &Expected) -> bool && actual.head == Some(expected.head) && actual.logits == expected.logits && actual.residual == expected.residual - && actual - .state - .as_ref() - .is_some_and(|s| s.numeric_eq(&expected.state)) + && actual.state.as_ref().is_some_and(|s| s.numeric_eq(&expected.state)) } pub(super) fn different_token(excluded: &[TokenId]) -> TokenId { (0..4) @@ -197,9 +178,7 @@ pub(super) fn different_token(excluded: &[TokenId]) -> TokenId { .expect("closed nonEOS mismatch unavailable") } pub(super) fn path(name: &str) -> PathBuf { - env::var_os(name) - .map(PathBuf::from) - .expect("missing Root-owned fixture path") + env::var_os(name).map(PathBuf::from).expect("missing Root-owned fixture path") } impl Report { pub(super) fn check(&mut self, ok: bool) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs index e730b71a..e1eb0a34 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport.rs @@ -1,7 +1,6 @@ //! Closed current-invocation MTP expert transport; canonical host checks stay. use super::{ - DEVICE_PEAK, Error, FF, K, N, Result, download, moe_driver_error, preflight, validate_route, - validate_values, + DEVICE_PEAK, Error, FF, K, N, Result, download, moe_driver_error, preflight, validate_route, validate_values, }; use leleka_cuda_driver::{Context, DenseFormat, DeviceBuffer, ProjectionKind, ProjectionSpec}; use std::{cell::Cell, rc::Rc}; @@ -65,10 +64,6 @@ use impl_role::routed; #[path = "mtp_expert_transport/shared_project_fn.rs"] mod shared_project_fn; #[allow(unused_imports)] -use shared_project_fn::shared_project; -#[allow(unused_imports)] -use shared_project_fn::shared; -#[allow(unused_imports)] pub(super) use shared_project_fn::compose; #[allow(unused_imports)] use shared_project_fn::compose_inner; @@ -78,3 +73,7 @@ use shared_project_fn::compose_observed; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] pub(super) use shared_project_fn::fixed_reference; +#[allow(unused_imports)] +use shared_project_fn::shared; +#[allow(unused_imports)] +use shared_project_fn::shared_project; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs index e88020fd..70b487ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/impl_role.rs @@ -39,9 +39,7 @@ impl<'ctx> Transport<'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let result = self.context.allocate(bytes).map_err(moe_driver_error); self.note(&result); let index = self.buffers.len(); @@ -52,10 +50,7 @@ impl<'ctx> Transport<'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - self.buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) + self.buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } pub(super) fn upload(&mut self, values: &[f32]) -> Result { validate_values(values, values.len())?; @@ -67,11 +62,8 @@ impl<'ctx> Transport<'ctx> { bytes.extend_from_slice(&value.to_le_bytes()); } let index = self.allocate(bytes.len())?; - let result = self.buffers[index] - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from(&bytes) - .map_err(moe_driver_error); + let result = + self.buffers[index].as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&bytes).map_err(moe_driver_error); self.note(&result); result?; Ok(index) @@ -84,33 +76,19 @@ impl<'ctx> Transport<'ctx> { let index = self.allocate(role.count() * 4)?; let (inputs, output) = self.buffers.split_at_mut(index); let result = operation(inputs, output[0].as_mut().ok_or(Error::IdentityMismatch)?) - .and_then(|()| { - download( - output[0].as_ref().ok_or(Error::IdentityMismatch)?, - role.count(), - ) - }); + .and_then(|()| download(output[0].as_ref().ok_or(Error::IdentityMismatch)?, role.count())); self.note(&result); let values = result?; #[cfg(test)] self.observe(role, &values)?; - Ok(Finite { - index, - values, - role, - invocation: Rc::clone(&self.invocation), - }) + Ok(Finite { index, values, role, invocation: Rc::clone(&self.invocation) }) } #[cfg(test)] pub(super) fn observe(&mut self, role: Role, values: &[f32]) -> Result<()> { if let Some(observations) = &mut self.observations { - observations - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + observations.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut copied = Vec::new(); - copied - .try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; + copied.try_reserve_exact(values.len()).map_err(|_| Error::InputAllocation)?; copied.extend_from_slice(values); observations.push((role, copied.into_boxed_slice())); } @@ -127,11 +105,7 @@ impl<'ctx> Transport<'ctx> { Ok(value.index) } pub(super) fn release(&mut self, index: usize) -> Result<()> { - let buffer = self - .buffers - .get_mut(index) - .ok_or(Error::IdentityMismatch)? - .take(); + let buffer = self.buffers.get_mut(index).ok_or(Error::IdentityMismatch)?.take(); let result = buffer.map_or(Ok(()), |buffer| buffer.release().map_err(moe_driver_error)); if result.is_err() { self.failed.set(true); @@ -184,9 +158,7 @@ impl<'ctx> Transport<'ctx> { ) } .map_err(moe_driver_error) - .and_then(|()| { - download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 }).map(|_| ()) - }); + .and_then(|()| download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 }).map(|_| ())); self.note(&result); result?; Ok((q, scales)) @@ -197,14 +169,8 @@ impl Drop for Transport<'_> { let _ = self.close(); } } -pub(super) fn at<'a, 'ctx>( - buffers: &'a [Option>], - index: usize, -) -> Result<&'a DeviceBuffer<'ctx>> { - buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) +pub(super) fn at<'a, 'ctx>(buffers: &'a [Option>], index: usize) -> Result<&'a DeviceBuffer<'ctx>> { + buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } pub(super) fn routed( transport: &mut Transport<'_>, @@ -219,24 +185,18 @@ pub(super) fn routed( } let context = transport.context; let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| { - context - .mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out) - .map_err(moe_driver_error) + context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error) })?; let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?; let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| { - context - .mtp_swiglu_640(at(inputs, gateup_index)?, out) - .map_err(moe_driver_error) + context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error) })?; transport.release(gateup_index)?; let hidden_index = transport.validate(&hidden, Role::RoutedHidden(slot, expert))?; let (q, scales) = transport.quantize(hidden_index, true)?; transport.release(hidden_index)?; let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| { - context - .mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out) - .map_err(moe_driver_error) + context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[q, scales]); let output = result?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs index d3444b08..5ee3faae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport/shared_project_fn.rs @@ -22,29 +22,19 @@ pub(super) fn shared_project( weights, at(inputs, input)?, out, - ProjectionSpec { - rows, - columns, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ) .map_err(moe_driver_error) }) } -pub(super) fn shared( - transport: &mut Transport<'_>, - weights: [&DeviceBuffer<'_>; 4], - input: usize, -) -> Result { +pub(super) fn shared(transport: &mut Transport<'_>, weights: [&DeviceBuffer<'_>; 4], input: usize) -> Result { let gate = shared_project(transport, Role::SharedGate, weights[0], input)?; let up = shared_project(transport, Role::SharedUp, weights[1], input)?; let gate_index = transport.validate(&gate, Role::SharedGate)?; let up_index = transport.validate(&up, Role::SharedUp)?; let context = transport.context; let result = transport.produce(Role::SharedHidden, |inputs, out| { - context - .moe_swiglu_f32(at(inputs, gate_index)?, at(inputs, up_index)?, out) - .map_err(moe_driver_error) + context.moe_swiglu_f32(at(inputs, gate_index)?, at(inputs, up_index)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[gate_index, up_index]); let hidden = result?; @@ -56,18 +46,14 @@ pub(super) fn shared( cleanup?; let down_index = transport.validate(&down, Role::SharedDown)?; let scalar = transport.produce(Role::Scalar, |inputs, out| { - context - .moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out) - .map_err(moe_driver_error) + context.moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out).map_err(moe_driver_error) })?; if !(0.0..=1.0).contains(&scalar.values[0]) { return Err(Error::NonFinite); } let scalar_index = transport.validate(&scalar, Role::Scalar)?; let result = transport.produce(Role::Scaled, |inputs, out| { - context - .moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out) - .map_err(moe_driver_error) + context.moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[down_index, scalar_index]); let scaled = result?; @@ -81,12 +67,7 @@ impl Packed { return Err(Error::InvalidExpert); } } - Ok(Self { - index: transport.allocate(K * N * 4)?, - invocation: Rc::clone(&transport.invocation), - ids, - next: 0, - }) + Ok(Self { index: transport.allocate(K * N * 4)?, invocation: Rc::clone(&transport.invocation), ids, next: 0 }) } pub(super) fn pack(&mut self, transport: &mut Transport<'_>, down: Finite) -> Result<()> { if self.next >= K || !Rc::ptr_eq(&self.invocation, &transport.invocation) { @@ -101,9 +82,7 @@ impl Packed { .context .pack_moe_down_f32( source[0].as_ref().ok_or(Error::IdentityMismatch)?, - destination[self.index] - .as_mut() - .ok_or(Error::IdentityMismatch)?, + destination[self.index].as_mut().ok_or(Error::IdentityMismatch)?, self.next as u32, ) .map_err(moe_driver_error); @@ -114,12 +93,7 @@ impl Packed { self.next += 1; Ok(()) } - pub(super) fn combine( - &self, - transport: &mut Transport<'_>, - weights: usize, - shared: &Finite, - ) -> Result { + pub(super) fn combine(&self, transport: &mut Transport<'_>, weights: usize, shared: &Finite) -> Result { if self.next != K || !Rc::ptr_eq(&self.invocation, &transport.invocation) { return Err(Error::IdentityMismatch); } @@ -133,12 +107,7 @@ impl Packed { let context = transport.context; transport.produce(Role::Combined, |inputs, out| { context - .moe_combine_f64( - at(inputs, self.index)?, - at(inputs, weights)?, - at(inputs, shared)?, - out, - ) + .moe_combine_f64(at(inputs, self.index)?, at(inputs, weights)?, at(inputs, shared)?, out) .map_err(moe_driver_error) }) } @@ -196,10 +165,7 @@ pub(super) fn compose_observed( let mut transport = Transport::new(context, failed)?; transport.observations = Some(Vec::new()); let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights); - let observations = transport - .observations - .take() - .ok_or(Error::IdentityMismatch)?; + let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?; let values = transport.finish(result)?; Ok((values, observations)) } @@ -212,20 +178,6 @@ pub(in super::super) fn fixed_reference( ids: [u32; K], weights: [f32; K], ) -> Result { - let (output, observed) = compose_observed( - context, - bank, - shared, - mixed, - ids, - weights, - Rc::new(Cell::new(false)), - )?; - Ok(( - output, - observed - .into_iter() - .map(|(role, values)| (format!("{role:?}"), values)) - .collect(), - )) + let (output, observed) = compose_observed(context, bank, shared, mixed, ids, weights, Rc::new(Cell::new(false)))?; + Ok((output, observed.into_iter().map(|(role, values)| (format!("{role:?}"), values)).collect())) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu.rs index 137533f6..5d3b97dd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu.rs @@ -7,9 +7,7 @@ use leleka_cuda_driver::Driver; const BANK_BYTES: usize = 707_788_800; const BLOB_BYTES: usize = 1_382_400; const IDS: [u32; K] = [511, 0, 257, 31, 7, 9, 255, 256, 3, 4]; -const ROUTE: [f32; K] = [ - 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625, -]; +const ROUTE: [f32; K] = [0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625]; struct Original { routed_gu: Vec>, routed_hidden: Vec>, @@ -33,25 +31,14 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { let refusals = Cell::new(0); let mut bank_bytes = bank_fixture(); let mut bank = bytes(&ctx, &bank_bytes); - let shared_bytes = [ - matrix(FF, N, 0x0c00, 0), - matrix(FF, N, 0x0c00, 1), - matrix(N, FF, 0x1c00, 2), - scalar_matrix(), - ]; + let shared_bytes = [matrix(FF, N, 0x0c00, 0), matrix(FF, N, 0x0c00, 1), matrix(N, FF, 0x1c00, 2), scalar_matrix()]; let shared_buffers = shared_bytes.each_ref().map(|b| bytes(&ctx, b)); let w = shared_buffers.each_ref(); let charge = ctx.allocated_bytes(); assert_eq!(charge, 713_016_320); for zero in [false, true] { let mixed: Vec = (0..N) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - ((i % 17) as f32 - 8.) / 2048. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { ((i % 17) as f32 - 8.) / 2048. }) .collect(); let expected = original(&ctx, &bank, w, &mixed); assert_eq!(ctx.allocated_bytes(), charge); @@ -60,9 +47,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { compare_observed(&ctx, &bank, w, &mixed, &expected, failed.clone()); assert_eq!(ctx.allocated_bytes(), charge); assert!(!failed.get()); - println!( - "MTP_EXPERT_RETAINED PAIR zero={zero} observed_words=80001 returned_words=2560 unique_words=54401" - ); + println!("MTP_EXPERT_RETAINED PAIR zero={zero} observed_words=80001 returned_words=2560 unique_words=54401"); } let mixed = vec![0.125 / 64.; N]; refusal( @@ -74,13 +59,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { ); let mut bad_mixed = mixed.clone(); bad_mixed[N - 1] = f32::NAN; - refusal( - compose(&ctx, &bank, w, &bad_mixed, IDS, ROUTE, failed.clone()), - Error::NonFinite, - &ctx, - charge, - &refusals, - ); + refusal(compose(&ctx, &bank, w, &bad_mixed, IDS, ROUTE, failed.clone()), Error::NonFinite, &ctx, charge, &refusals); for (slot, id) in [(K - 1, 512), (K - 1, IDS[0])] { let mut bad = IDS; bad[slot] = id; @@ -95,13 +74,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { for value in [f32::NAN, -0.01, 1.01] { let mut bad = ROUTE; bad[K - 1] = value; - refusal( - compose(&ctx, &bank, w, &mixed, IDS, bad, failed.clone()), - Error::NonFinite, - &ctx, - charge, - &refusals, - ); + refusal(compose(&ctx, &bank, w, &mixed, IDS, bad, failed.clone()), Error::NonFinite, &ctx, charge, &refusals); } let malformed = bytes(&ctx, &[0; 4]); let with_bad = ctx.allocated_bytes(); @@ -128,13 +101,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { let old = [bank_bytes[last], bank_bytes[last + 1]]; bank_bytes[last..last + 2].copy_from_slice(&0x7e00u16.to_le_bytes()); bank.copy_from(&bank_bytes).unwrap(); - refusal( - compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), - Error::NonFinite, - &ctx, - charge, - &refusals, - ); + refusal(compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), Error::NonFinite, &ctx, charge, &refusals); bank_bytes[last..last + 2].copy_from_slice(&old); bank.copy_from(&bank_bytes).unwrap(); let mut bad_down = shared_bytes[2].clone(); @@ -172,15 +139,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { assert_eq!(ctx.allocated_bytes(), charge); let foreign = device.create_context(144 * 1024 * 1024).unwrap(); refusal( - compose( - &foreign, - &bank, - w, - &mixed, - IDS, - ROUTE, - Rc::new(Cell::new(false)), - ), + compose(&foreign, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))), Error::IdentityMismatch, &foreign, 0, @@ -189,15 +148,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { foreign.close().unwrap(); let low = device.create_context(DEVICE_PEAK - 1).unwrap(); refusal( - compose( - &low, - &bank, - w, - &mixed, - IDS, - ROUTE, - Rc::new(Cell::new(false)), - ), + compose(&low, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))), Error::InputAllocation, &low, 0, @@ -209,13 +160,7 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { unchanged(buffer, expected); } failed.set(true); // Explicit shared policy, not physical CUDA fault injection. - refusal( - compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), - Error::CudaExecution, - &ctx, - charge, - &refusals, - ); + refusal(compose(&ctx, &bank, w, &mixed, IDS, ROUTE, failed.clone()), Error::CudaExecution, &ctx, charge, &refusals); for buffer in shared_buffers { buffer.release().unwrap(); } @@ -234,24 +179,24 @@ fn retained_mtp_experts_match_original_s2_shared_and_combine_and_clean_abort() { #[path = "mtp_expert_transport_gpu/exact_fn.rs"] mod exact_fn; #[allow(unused_imports)] -use exact_fn::exact; +use exact_fn::bank_fixture; #[allow(unused_imports)] use exact_fn::bytes; #[allow(unused_imports)] -use exact_fn::bank_fixture; +use exact_fn::compare_observed; +#[allow(unused_imports)] +use exact_fn::exact; #[allow(unused_imports)] use exact_fn::matrix; #[allow(unused_imports)] -use exact_fn::scalar_matrix; +use exact_fn::original; #[allow(unused_imports)] use exact_fn::original_project; #[allow(unused_imports)] -use exact_fn::original; -#[allow(unused_imports)] -use exact_fn::compare_observed; -#[allow(unused_imports)] use exact_fn::refusal; #[allow(unused_imports)] +use exact_fn::scalar_matrix; +#[allow(unused_imports)] use exact_fn::unchanged; #[path = "mtp_expert_transport_gpu/private_owner_guards_fn.rs"] mod private_owner_guards_fn; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs index 1cb3a590..032806c0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/exact_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn exact(a: &[f32], b: &[f32]) { assert_eq!(a.len(), b.len()); for (i, (a, b)) in a.iter().zip(b).enumerate() { @@ -22,23 +21,16 @@ pub(super) fn bank_fixture() -> Vec { for expert in IDS { let base = expert as usize * BLOB_BYTES; let blob = &mut bank[base..base + BLOB_BYTES]; - for (rows, columns, codes, scales, chunks) in [ - (1280, 640, 0, 1_228_800, 40), - (2560, 160, 819_200, 1_331_200, 10), - ] { + for (rows, columns, codes, scales, chunks) in + [(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)] + { for row in 0..rows { for col in 0..columns { - blob[codes + row * columns + col] = - palette[(expert as usize + row * 3 + col * 5 + col / 8) % 4]; + blob[codes + row * columns + col] = palette[(expert as usize + row * 3 + col * 5 + col / 8) % 4]; } for chunk in 0..chunks { // Literal half 2^-10, alternating sign with distinct rows. - let half = 0x1400u16 - | if (row + chunk + expert as usize).is_multiple_of(2) { - 0 - } else { - 0x8000 - }; + let half = 0x1400u16 | if (row + chunk + expert as usize).is_multiple_of(2) { 0 } else { 0x8000 }; let at = scales + (row * chunks + chunk) * 2; blob[at..at + 2].copy_from_slice(&half.to_le_bytes()); } @@ -76,17 +68,8 @@ pub(super) fn original_project( ) -> Box<[f32]> { let x = upload(ctx, x).unwrap(); let mut out = allocate(ctx, rows).unwrap(); - ctx.project_q8_1( - w, - &x, - &mut out, - ProjectionSpec { - rows, - columns, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, - ) - .unwrap(); + ctx.project_q8_1(w, &x, &mut out, ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }) + .unwrap(); let result = download(&out, rows).unwrap(); release([x, out]).unwrap(); result @@ -100,16 +83,14 @@ pub(super) fn original( let x = upload(ctx, mixed).unwrap(); let mut q = ctx.allocate(2720).unwrap(); let mut scales = allocate(ctx, 80).unwrap(); - ctx.mtp_quantize_scaled_2560(&x, &mut q, &mut scales) - .unwrap(); + ctx.mtp_quantize_scaled_2560(&x, &mut q, &mut scales).unwrap(); download(&scales, 80).unwrap(); let mut routed_gu = Vec::new(); let mut routed_hidden = Vec::new(); let mut routed = Vec::new(); for expert in IDS { let mut gu = allocate(ctx, 2 * FF).unwrap(); - ctx.mtp_s2_gate_up_full(bank, expert, &q, &scales, &mut gu) - .unwrap(); + ctx.mtp_s2_gate_up_full(bank, expert, &q, &scales, &mut gu).unwrap(); routed_gu.push(download(&gu, 2 * FF).unwrap()); let mut hidden = allocate(ctx, FF).unwrap(); ctx.mtp_swiglu_640(&gu, &mut hidden).unwrap(); @@ -117,13 +98,11 @@ pub(super) fn original( gu.release().unwrap(); let mut hq = ctx.allocate(680).unwrap(); let mut hs = allocate(ctx, 20).unwrap(); - ctx.mtp_quantize_scaled_640(&hidden, &mut hq, &mut hs) - .unwrap(); + ctx.mtp_quantize_scaled_640(&hidden, &mut hq, &mut hs).unwrap(); download(&hs, 20).unwrap(); hidden.release().unwrap(); let mut down = allocate(ctx, N).unwrap(); - ctx.mtp_s2_down_full(bank, expert, &hq, &hs, &mut down) - .unwrap(); + ctx.mtp_s2_down_full(bank, expert, &hq, &hs, &mut down).unwrap(); routed.push(download(&down, N).unwrap()); release([hq, hs, down]).unwrap(); } @@ -139,21 +118,18 @@ pub(super) fn original( let down = original_project(ctx, w[2], &hidden_values, N, FF); let down_gpu = upload(ctx, &down).unwrap(); let mut scalar = allocate(ctx, 1).unwrap(); - ctx.moe_shared_scalar_f32_bf16(&x, w[3], &mut scalar) - .unwrap(); + ctx.moe_shared_scalar_f32_bf16(&x, w[3], &mut scalar).unwrap(); let scalar_values = download(&scalar, 1).unwrap(); assert!((0.0..=1.0).contains(&scalar_values[0])); let mut scaled = allocate(ctx, N).unwrap(); - ctx.moe_shared_scale_f32(&down_gpu, &scalar, &mut scaled) - .unwrap(); + ctx.moe_shared_scale_f32(&down_gpu, &scalar, &mut scaled).unwrap(); let scaled_values = download(&scaled, N).unwrap(); // This upload baseline precedes every retained candidate, in router order. let parts: Vec = routed.iter().flat_map(|v| v.iter().copied()).collect(); let parts = upload(ctx, &parts).unwrap(); let weights = upload(ctx, &ROUTE).unwrap(); let mut out = allocate(ctx, N).unwrap(); - ctx.moe_combine_f64(&parts, &weights, &scaled, &mut out) - .unwrap(); + ctx.moe_combine_f64(&parts, &weights, &scaled, &mut out).unwrap(); let combined = download(&out, N).unwrap(); release([x, down_gpu, scalar, scaled, parts, weights, out]).unwrap(); Original { @@ -180,21 +156,14 @@ pub(super) fn compare_observed( ) { let (output, observed) = compose_observed(ctx, bank, w, mixed, IDS, ROUTE, failed).unwrap(); assert_eq!(observed.len(), 38); - let parts: Vec = expected - .routed - .iter() - .flat_map(|v| v.iter().copied()) - .collect(); + let parts: Vec = expected.routed.iter().flat_map(|v| v.iter().copied()).collect(); let mut words = 0; for (i, (role, value)) in observed.iter().enumerate() { if i < 30 { let slot = i / 3; let (expected_role, original) = match i % 3 { 0 => (Role::RoutedGu(slot, IDS[slot]), &expected.routed_gu[slot]), - 1 => ( - Role::RoutedHidden(slot, IDS[slot]), - &expected.routed_hidden[slot], - ), + 1 => (Role::RoutedHidden(slot, IDS[slot]), &expected.routed_hidden[slot]), _ => (Role::RoutedDown(slot, IDS[slot]), &expected.routed[slot]), }; assert!(*role == expected_role); @@ -220,21 +189,12 @@ pub(super) fn compare_observed( exact(&output, &expected.combined); } -pub(super) fn refusal( - result: Result, - error: Error, - ctx: &Context<'_>, - charge: usize, - count: &Cell, -) { +pub(super) fn refusal(result: Result, error: Error, ctx: &Context<'_>, charge: usize, count: &Cell) { assert_eq!(result.err(), Some(error)); assert_eq!(ctx.allocated_bytes(), charge); count.set(count.get() + 1); } pub(super) fn unchanged(buffer: &DeviceBuffer<'_>, expected: &[u8]) { - assert_eq!( - download_bytes(buffer, expected.len()).unwrap().as_ref(), - expected - ); + assert_eq!(download_bytes(buffer, expected.len()).unwrap().as_ref(), expected); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs index 8d100a4c..4fe01429 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_transport_gpu/private_owner_guards_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn private_owner_guards( ctx: &Context<'_>, bank: &DeviceBuffer<'_>, @@ -19,66 +18,27 @@ pub(super) fn private_owner_guards( let mut packed = Packed::new(&mut t, IDS).unwrap(); let gate = shared_project(&mut t, Role::SharedGate, w[0], input).unwrap(); let charge = ctx.allocated_bytes(); - refusal( - t.validate(&gate, Role::SharedUp), - Error::IdentityMismatch, - ctx, - charge, - count, - ); - refusal( - rival.validate(&gate, Role::SharedGate), - Error::IdentityMismatch, - ctx, - charge, - count, - ); + refusal(t.validate(&gate, Role::SharedUp), Error::IdentityMismatch, ctx, charge, count); + refusal(rival.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, charge, count); t.release(gate.index).unwrap(); - refusal( - t.validate(&gate, Role::SharedGate), - Error::IdentityMismatch, - ctx, - ctx.allocated_bytes(), - count, - ); + refusal(t.validate(&gate, Role::SharedGate), Error::IdentityMismatch, ctx, ctx.allocated_bytes(), count); let (q, scales) = t.quantize(input, false).unwrap(); let wrong_slot = routed(&mut t, bank, 1, IDS[1], q, scales).unwrap(); let charge = ctx.allocated_bytes(); - refusal( - packed.pack(&mut t, wrong_slot), - Error::IdentityMismatch, - ctx, - charge, - count, - ); + refusal(packed.pack(&mut t, wrong_slot), Error::IdentityMismatch, ctx, charge, count); assert_eq!(packed.next, 0); let scaled = shared(&mut t, w, input).unwrap(); let weights = t.upload(&ROUTE).unwrap(); let charge = ctx.allocated_bytes(); - refusal( - packed.combine(&mut t, weights, &scaled), - Error::IdentityMismatch, - ctx, - charge, - count, - ); + refusal(packed.combine(&mut t, weights, &scaled), Error::IdentityMismatch, ctx, charge, count); let rival_input = rival.upload(mixed).unwrap(); let (rq, rs) = rival.quantize(rival_input, false).unwrap(); let foreign_invocation = routed(&mut rival, bank, 0, IDS[0], rq, rs).unwrap(); let charge = ctx.allocated_bytes(); - refusal( - packed.pack(&mut t, foreign_invocation), - Error::IdentityMismatch, - ctx, - charge, - count, - ); + refusal(packed.pack(&mut t, foreign_invocation), Error::IdentityMismatch, ctx, charge, count); assert_eq!(packed.next, 0); // Abort both actual partially completed invocations; no detached constructor. - assert_eq!( - t.finish::<()>(Err(Error::IdentityMismatch)), - Err(Error::IdentityMismatch) - ); + assert_eq!(t.finish::<()>(Err(Error::IdentityMismatch)), Err(Error::IdentityMismatch)); rival.finish(Ok(())).unwrap(); assert_eq!(ctx.allocated_bytes(), starting); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs index 3cb9a02e..60ed7a7c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace.rs @@ -1,7 +1,6 @@ //! Explicit integer-cache fixed draft MoE storage; original arithmetic/fences stay. use super::{ - DEVICE_PEAK, Error, FF, K, N, Result, download, moe_driver_error, preflight, validate_route, - validate_values, + DEVICE_PEAK, Error, FF, K, N, Result, download, moe_driver_error, preflight, validate_route, validate_values, }; use leleka_cuda_driver::{Context, DenseFormat, DeviceBuffer, ProjectionKind, ProjectionSpec}; use std::{cell::Cell, rc::Rc}; @@ -56,10 +55,8 @@ struct Packed { use super::super::{mtp::MtpFrame, session::QwenSession}; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; -const CHARGES: [usize; 17] = [ - 10240, 102400, 2720, 320, 5120, 2560, 680, 80, 10240, 2560, 2560, 2560, 10240, 4, 10240, 40, - 10240, -]; +const CHARGES: [usize; 17] = + [10240, 102400, 2720, 320, 5120, 2560, 680, 80, 10240, 2560, 2560, 2560, 10240, 4, 10240, 40, 10240]; pub(in crate::qwen_forward) const ALLOCATED_BYTES: usize = 172804; #[derive(Clone, Copy)] #[repr(usize)] @@ -103,9 +100,7 @@ mod fixed_workspace_gpu { const BANK_BYTES: usize = 707_788_800; const BLOB_BYTES: usize = 1_382_400; const IDS: [u32; K] = [511, 0, 257, 31, 7, 9, 255, 256, 3, 4]; - const ROUTE: [f32; K] = [ - 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625, - ]; + const ROUTE: [f32; K] = [0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.0625, 0.0625, 0.0625, 0.0625]; fn exact(a: &[f32], b: &[f32]) { assert_eq!(a.len(), b.len()); @@ -125,10 +120,9 @@ mod fixed_workspace_gpu { for expert in IDS { let base = expert as usize * BLOB_BYTES; let blob = &mut bank[base..base + BLOB_BYTES]; - for (rows, columns, codes, scales, chunks) in [ - (1280, 640, 0, 1_228_800, 40), - (2560, 160, 819_200, 1_331_200, 10), - ] { + for (rows, columns, codes, scales, chunks) in + [(1280, 640, 0, 1_228_800, 40), (2560, 160, 819_200, 1_331_200, 10)] + { for row in 0..rows { for col in 0..columns { blob[codes + row * columns + col] = @@ -136,12 +130,8 @@ mod fixed_workspace_gpu { } for chunk in 0..chunks { // Literal half 2^-10, alternating sign with distinct rows. - let half = 0x1400u16 - | if (row + chunk + expert as usize).is_multiple_of(2) { - 0 - } else { - 0x8000 - }; + let half = + 0x1400u16 | if (row + chunk + expert as usize).is_multiple_of(2) { 0 } else { 0x8000 }; let at = scales + (row * chunks + chunk) * 2; blob[at..at + 2].copy_from_slice(&half.to_le_bytes()); } @@ -178,11 +168,9 @@ mod fixed_workspace_gpu { let mut q = ctx.allocate(if hidden { 680 } else { 2720 }).unwrap(); let mut scales = ctx.allocate(if hidden { 80 } else { 320 }).unwrap(); if hidden { - ctx.mtp_quantize_scaled_640(&x, &mut q, &mut scales) - .unwrap(); + ctx.mtp_quantize_scaled_640(&x, &mut q, &mut scales).unwrap(); } else { - ctx.mtp_quantize_scaled_2560(&x, &mut q, &mut scales) - .unwrap(); + ctx.mtp_quantize_scaled_2560(&x, &mut q, &mut scales).unwrap(); } let values = download(&scales, if hidden { 20 } else { 80 }).unwrap(); scales.release().unwrap(); @@ -205,10 +193,7 @@ mod fixed_workspace_gpu { #[test] #[ignore = "Root sole GPU: one new original-first fixed draft MoE storage proof"] fn original_first_fixed_draft_moe_repeat_abort_and_cleanup() { - assert_eq!( - std::env::var("LELEKA_STRA169_RUN_FIXED_DRAFT_MOE").as_deref(), - Ok("yes") - ); + assert_eq!(std::env::var("LELEKA_STRA169_RUN_FIXED_DRAFT_MOE").as_deref(), Ok("yes")); let driver = Driver::load().unwrap(); let device = driver.device(0).unwrap(); let ctx = device.create_context(1024 * 1024 * 1024).unwrap(); @@ -225,9 +210,7 @@ mod fixed_workspace_gpu { assert_eq!(CHARGES.into_iter().sum::(), ALLOCATED_BYTES); let mut words = 0usize; for pattern in 0..2 { - let mixed: Vec = (0..N) - .map(|i| ((i * 7 + pattern * 13) % 61) as f32 / 128. - 0.25) - .collect(); + let mixed: Vec = (0..N).map(|i| ((i * 7 + pattern * 13) % 61) as f32 / 128. - 0.25).collect(); // Original allocation path and its direct unchanged quantizers FIRST. let (expected, original) = fixed_reference(&ctx, &bank, w, &mixed, IDS, ROUTE).unwrap(); let mut scales = vec![reference_scales(&ctx, &mixed, false)]; @@ -276,19 +259,10 @@ mod fixed_workspace_gpu { .map_err(moe_driver_error) }) .unwrap(); - assert_eq!( - t.validate(&gu, Role::RoutedGu(1, IDS[1])).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(t.validate(&gu, Role::RoutedGu(1, IDS[1])).err(), Some(Error::IdentityMismatch)); t.release(gu.index).unwrap(); - assert_eq!( - t.validate(&gu, Role::RoutedGu(0, IDS[0])).err(), - Some(Error::IdentityMismatch) - ); - assert_eq!( - t.finish::<()>(Err(Error::IdentityMismatch)), - Err(Error::IdentityMismatch) - ); + assert_eq!(t.validate(&gu, Role::RoutedGu(0, IDS[0])).err(), Some(Error::IdentityMismatch)); + assert_eq!(t.finish::<()>(Err(Error::IdentityMismatch)), Err(Error::IdentityMismatch)); } storage.check().unwrap(); // Late actual expert GU nonfinite: both original and fixed must refuse. @@ -296,65 +270,26 @@ mod fixed_workspace_gpu { let saved: [u8; 2] = corpus[at..at + 2].try_into().unwrap(); corpus[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes()); bank.copy_from(&corpus).unwrap(); + assert_eq!(fixed_reference(&ctx, &bank, w, &mixed, IDS, ROUTE).err(), Some(Error::NonFinite)); assert_eq!( - fixed_reference(&ctx, &bank, w, &mixed, IDS, ROUTE).err(), - Some(Error::NonFinite) - ); - assert_eq!( - compose( - &mut storage, - &bank, - w, - &mixed, - IDS, - ROUTE, - Rc::new(Cell::new(false)) - ) - .err(), + compose(&mut storage, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))).err(), Some(Error::NonFinite) ); storage.check().unwrap(); corpus[at..at + 2].copy_from_slice(&saved); bank.copy_from(&corpus).unwrap(); let (expected, _) = fixed_reference(&ctx, &bank, w, &mixed, IDS, ROUTE).unwrap(); - let actual = compose( - &mut storage, - &bank, - w, - &mixed, - IDS, - ROUTE, - Rc::new(Cell::new(false)), - ) - .unwrap(); + let actual = compose(&mut storage, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(false))).unwrap(); exact(&expected, &actual); words += actual.len(); let mut bad = mixed.clone(); bad[N - 1] = f32::NAN; assert_eq!( - compose( - &mut storage, - &bank, - w, - &bad, - IDS, - ROUTE, - Rc::new(Cell::new(false)) - ) - .err(), + compose(&mut storage, &bank, w, &bad, IDS, ROUTE, Rc::new(Cell::new(false))).err(), Some(Error::NonFinite) ); assert_eq!( - compose( - &mut storage, - &bank, - w, - &mixed, - IDS, - ROUTE, - Rc::new(Cell::new(true)) - ) - .err(), + compose(&mut storage, &bank, w, &mixed, IDS, ROUTE, Rc::new(Cell::new(true))).err(), Some(Error::CudaExecution) ); storage.close_inner().unwrap(); @@ -367,27 +302,25 @@ mod fixed_workspace_gpu { assert_eq!(ctx.allocated_bytes(), 0); ctx.close().unwrap(); assert_eq!(words, 168242); - eprintln!( - "FIXED-DRAFT-MOE words={words} guards=6 allocated=0 production_frame_model_proof=false" - ); + eprintln!("FIXED-DRAFT-MOE words={words} guards=6 allocated=0 production_frame_model_proof=false"); } } -#[path = "mtp_expert_workspace/impl_role.rs"] -mod impl_role; #[path = "mtp_expert_workspace/impl_drop_for_transport.rs"] mod impl_drop_for_transport; +#[path = "mtp_expert_workspace/impl_role.rs"] +mod impl_role; #[allow(unused_imports)] use impl_drop_for_transport::at; #[allow(unused_imports)] -use impl_drop_for_transport::routed; -#[allow(unused_imports)] -use impl_drop_for_transport::shared_project; -#[allow(unused_imports)] -use impl_drop_for_transport::shared; -#[allow(unused_imports)] use impl_drop_for_transport::compose; #[allow(unused_imports)] use impl_drop_for_transport::compose_inner; +#[allow(unused_imports)] +use impl_drop_for_transport::routed; +#[allow(unused_imports)] +use impl_drop_for_transport::shared; +#[allow(unused_imports)] +use impl_drop_for_transport::shared_project; #[path = "mtp_expert_workspace/impl_fixedbuffers.rs"] mod impl_fixedbuffers; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs index 6bcedabe..4bdc06b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_drop_for_transport.rs @@ -8,14 +8,8 @@ impl Drop for Transport<'_, '_> { let _ = self.close(); } } -pub(super) fn at<'a, 'ctx>( - buffers: &'a [Option>], - index: usize, -) -> Result<&'a DeviceBuffer<'ctx>> { - buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) +pub(super) fn at<'a, 'ctx>(buffers: &'a [Option>], index: usize) -> Result<&'a DeviceBuffer<'ctx>> { + buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } pub(super) fn routed( transport: &mut Transport<'_, '_>, @@ -30,24 +24,18 @@ pub(super) fn routed( } let context = transport.context; let gateup = transport.produce(Role::RoutedGu(slot, expert), |inputs, out| { - context - .mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out) - .map_err(moe_driver_error) + context.mtp_s2_gate_up_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error) })?; let gateup_index = transport.validate(&gateup, Role::RoutedGu(slot, expert))?; let hidden = transport.produce(Role::RoutedHidden(slot, expert), |inputs, out| { - context - .mtp_swiglu_640(at(inputs, gateup_index)?, out) - .map_err(moe_driver_error) + context.mtp_swiglu_640(at(inputs, gateup_index)?, out).map_err(moe_driver_error) })?; transport.release(gateup_index)?; let hidden_index = transport.validate(&hidden, Role::RoutedHidden(slot, expert))?; let (q, scales) = transport.quantize(hidden_index, true)?; transport.release(hidden_index)?; let result = transport.produce(Role::RoutedDown(slot, expert), |inputs, out| { - context - .mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out) - .map_err(moe_driver_error) + context.mtp_s2_down_full(bank, expert, at(inputs, q)?, at(inputs, scales)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[q, scales]); let output = result?; @@ -73,11 +61,7 @@ pub(super) fn shared_project( weights, at(inputs, input)?, out, - ProjectionSpec { - rows, - columns, - kind: ProjectionKind::Dense(DenseFormat::Q8_0), - }, + ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, ) .map_err(moe_driver_error) }) @@ -93,9 +77,7 @@ pub(super) fn shared( let up_index = transport.validate(&up, Role::SharedUp)?; let context = transport.context; let result = transport.produce(Role::SharedHidden, |inputs, out| { - context - .moe_swiglu_f32(at(inputs, gate_index)?, at(inputs, up_index)?, out) - .map_err(moe_driver_error) + context.moe_swiglu_f32(at(inputs, gate_index)?, at(inputs, up_index)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[gate_index, up_index]); let hidden = result?; @@ -107,18 +89,14 @@ pub(super) fn shared( cleanup?; let down_index = transport.validate(&down, Role::SharedDown)?; let scalar = transport.produce(Role::Scalar, |inputs, out| { - context - .moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out) - .map_err(moe_driver_error) + context.moe_shared_scalar_f32_bf16(at(inputs, input)?, weights[3], out).map_err(moe_driver_error) })?; if !(0.0..=1.0).contains(&scalar.values[0]) { return Err(Error::NonFinite); } let scalar_index = transport.validate(&scalar, Role::Scalar)?; let result = transport.produce(Role::Scaled, |inputs, out| { - context - .moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out) - .map_err(moe_driver_error) + context.moe_shared_scale_f32(at(inputs, down_index)?, at(inputs, scalar_index)?, out).map_err(moe_driver_error) }); let cleanup = transport.release_all(&[down_index, scalar_index]); let scaled = result?; @@ -152,9 +130,7 @@ impl Packed { .context .pack_moe_down_f32( source[0].as_ref().ok_or(Error::IdentityMismatch)?, - destination[self.index] - .as_mut() - .ok_or(Error::IdentityMismatch)?, + destination[self.index].as_mut().ok_or(Error::IdentityMismatch)?, self.next as u32, ) .map_err(moe_driver_error); @@ -165,12 +141,7 @@ impl Packed { self.next += 1; Ok(()) } - pub(super) fn combine( - &self, - transport: &mut Transport<'_, '_>, - weights: usize, - shared: &Finite, - ) -> Result { + pub(super) fn combine(&self, transport: &mut Transport<'_, '_>, weights: usize, shared: &Finite) -> Result { if self.next != K || !Rc::ptr_eq(&self.invocation, &transport.invocation) { return Err(Error::IdentityMismatch); } @@ -184,12 +155,7 @@ impl Packed { let context = transport.context; transport.produce(Role::Combined, |inputs, out| { context - .moe_combine_f64( - at(inputs, self.index)?, - at(inputs, weights)?, - at(inputs, shared)?, - out, - ) + .moe_combine_f64(at(inputs, self.index)?, at(inputs, weights)?, at(inputs, shared)?, out) .map_err(moe_driver_error) }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs index 53e7f59e..2b7ae51b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_fixedbuffers.rs @@ -5,17 +5,8 @@ use super::*; impl<'ctx> FixedBuffers<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>) -> Result { - preflight( - context, - ALLOCATED_BYTES - .checked_add(DEVICE_PEAK) - .ok_or(Error::Overflow)?, - )?; - let mut storage = Self { - context, - buffers: std::array::from_fn(|_| None), - failed: false, - }; + preflight(context, ALLOCATED_BYTES.checked_add(DEVICE_PEAK).ok_or(Error::Overflow)?)?; + let mut storage = Self { context, buffers: std::array::from_fn(|_| None), failed: false }; for (index, charge) in CHARGES.into_iter().enumerate() { match context.allocate(charge).map_err(moe_driver_error) { Ok(buffer) => storage.buffers[index] = Some(buffer), @@ -42,9 +33,7 @@ impl<'ctx> FixedBuffers<'ctx> { if self.failed || self.context.is_poisoned() { return Err(Error::CudaExecution); } - self.buffers[slot as usize] - .take() - .ok_or(Error::IdentityMismatch) + self.buffers[slot as usize].take().ok_or(Error::IdentityMismatch) } pub(super) fn put(&mut self, slot: Slot, buffer: DeviceBuffer<'ctx>) -> Result<()> { if buffer.len() != slot.bytes() || self.buffers[slot as usize].is_some() { @@ -79,11 +68,7 @@ impl<'ctx> MtpExpertWorkspace<'ctx> { owner: Rc<()>, context: &'ctx Context<'ctx>, ) -> Result { - Ok(Self { - binding, - owner, - storage: FixedBuffers::new(context)?, - }) + Ok(Self { binding, owner, storage: FixedBuffers::new(context)? }) } #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn compose( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_role.rs index 653ba9be..6b30425b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_expert_workspace/impl_role.rs @@ -67,12 +67,8 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; - self.slots - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; + self.slots.try_reserve(1).map_err(|_| Error::InputAllocation)?; let result = self.storage.take(slot); self.note(&result); let index = self.buffers.len(); @@ -84,10 +80,7 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - self.buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) + self.buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } pub(super) fn upload(&mut self, values: &[f32], slot: Slot) -> Result { validate_values(values, values.len())?; @@ -102,11 +95,8 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { return Err(Error::InvalidDimension); } let index = self.allocate(slot)?; - let result = self.buffers[index] - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from(&bytes) - .map_err(moe_driver_error); + let result = + self.buffers[index].as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&bytes).map_err(moe_driver_error); self.note(&result); result?; Ok(index) @@ -119,33 +109,19 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { let index = self.allocate(role.slot())?; let (inputs, output) = self.buffers.split_at_mut(index); let result = operation(inputs, output[0].as_mut().ok_or(Error::IdentityMismatch)?) - .and_then(|()| { - download( - output[0].as_ref().ok_or(Error::IdentityMismatch)?, - role.count(), - ) - }); + .and_then(|()| download(output[0].as_ref().ok_or(Error::IdentityMismatch)?, role.count())); self.note(&result); let values = result?; #[cfg(test)] self.observe(role, &values)?; - Ok(Finite { - index, - values, - role, - invocation: Rc::clone(&self.invocation), - }) + Ok(Finite { index, values, role, invocation: Rc::clone(&self.invocation) }) } #[cfg(test)] pub(super) fn observe(&mut self, role: Role, values: &[f32]) -> Result<()> { if let Some(observations) = &mut self.observations { - observations - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + observations.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut copied = Vec::new(); - copied - .try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; + copied.try_reserve_exact(values.len()).map_err(|_| Error::InputAllocation)?; copied.extend_from_slice(values); observations.push((role, copied.into_boxed_slice())); } @@ -162,11 +138,7 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { Ok(value.index) } pub(super) fn release(&mut self, index: usize) -> Result<()> { - let buffer = self - .buffers - .get_mut(index) - .ok_or(Error::IdentityMismatch)? - .take(); + let buffer = self.buffers.get_mut(index).ok_or(Error::IdentityMismatch)?.take(); let slot = *self.slots.get(index).ok_or(Error::IdentityMismatch)?; let result = buffer.map_or(Ok(()), |buffer| self.storage.put(slot, buffer)); if result.is_err() { @@ -206,11 +178,7 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { // completed scale before any original grouped dot consumes the pair. pub(super) fn quantize(&mut self, input: usize, hidden: bool) -> Result<(usize, usize)> { let q = self.allocate(if hidden { Slot::HiddenQ } else { Slot::InputQ })?; - let scales = self.allocate(if hidden { - Slot::HiddenScales - } else { - Slot::InputScales - })?; + let scales = self.allocate(if hidden { Slot::HiddenScales } else { Slot::InputScales })?; let (inputs, outputs) = self.buffers.split_at_mut(q); let (quant, scale) = outputs.split_at_mut(1); let result = if hidden { @@ -230,14 +198,7 @@ impl<'lease, 'ctx> Transport<'lease, 'ctx> { .and_then(|()| { let values = download(at(&self.buffers, scales)?, if hidden { 20 } else { 80 })?; #[cfg(test)] - self.observe( - if hidden { - Role::HiddenScales - } else { - Role::InputScales - }, - &values, - )?; + self.observe(if hidden { Role::HiddenScales } else { Role::InputScales }, &values)?; let _ = values; Ok(()) }); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs index bbeefdb9..c6312287 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts.rs @@ -5,10 +5,7 @@ use super::{ contract::{Error, Result, Stage}, mtp::{MtpFrame, preflight, project, reserve}, mtp_gr::MtpMlpReady, - qsa_index::{ - allocate, binding_error, download, download_bytes, driver_error, release, upload, - validate_values, - }, + qsa_index::{allocate, binding_error, download, download_bytes, driver_error, release, upload, validate_values}, session::QwenSession, }; use crate::model_binding::qwen4exp_input::{ModelBinding, MtpKind, MtpRole}; @@ -46,9 +43,8 @@ impl MtpExpertStage { failed: Rc>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Moe, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe); let result = (|| { if failed.get() { return Err(Error::CudaExecution); @@ -75,22 +71,10 @@ impl MtpExpertStage { let logits = project(context, binding, MtpRole::Router, input.mixed(), cache)?; validate_values(&logits, 512)?; let (ids, weights) = route(context, &logits)?; - let output = compose_bound( - context, - binding, - input, - session, - ids, - weights, - cache, - Rc::clone(&failed), - )?; + let output = compose_bound(context, binding, input, session, ids, weights, cache, Rc::clone(&failed))?; validate_values(&output, N)?; input.frame().validate(binding, session)?; - Ok(MtpBlock { - frame: input.frame().clone(), - output, - }) + Ok(MtpBlock { frame: input.frame().clone(), output }) })(); if matches!(result, Err(Error::CudaExecution)) { failed.set(true); @@ -182,17 +166,10 @@ fn route(context: &Context<'_>, logits: &[f32]) -> Result<([u32; K], [f32; K])> let mut ids = context.allocate(K * 4).map_err(moe_driver_error)?; let mut weights = allocate(context, K)?; let result: Result<([u32; K], [f32; K])> = (|| { - context - .qwen_route_top10(&x, &mut ids, &mut weights) - .map_err(moe_driver_error)?; + context.qwen_route_top10(&x, &mut ids, &mut weights).map_err(moe_driver_error)?; let raw = download_bytes(&ids, K * 4)?; - let ids = std::array::from_fn(|i| { - i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs")) - }); - let weights: [f32; K] = download(&weights, K)? - .as_ref() - .try_into() - .map_err(|_| Error::InvalidDimension)?; + let ids = std::array::from_fn(|i| i32::from_le_bytes(raw[i * 4..(i + 1) * 4].try_into().expect("fixed IDs"))); + let weights: [f32; K] = download(&weights, K)?.as_ref().try_into().map_err(|_| Error::InvalidDimension)?; Ok((validate_route(ids, &weights)?, weights)) })(); let cleanup = release([x, ids, weights]); @@ -211,9 +188,7 @@ fn compose( ) -> Result> { let mut q = context.allocate(2720).map_err(moe_driver_error)?; let mut scales = allocate(context, 80)?; - context - .mtp_quantize_scaled_2560(x, &mut q, &mut scales) - .map_err(moe_driver_error)?; + context.mtp_quantize_scaled_2560(x, &mut q, &mut scales).map_err(moe_driver_error)?; download(&scales, 80)?; // Must inspect FP32 scales before any dot. let mut parts = reserve(K * N)?; for expert in ids { @@ -229,9 +204,7 @@ fn compose( let mut out = allocate(context, N)?; let result: Result> = (|| { // Original default DOUBLE ordered combine; parts remain router-slot order. - context - .moe_combine_f64(&parts, &weights, &shared, &mut out) - .map_err(moe_driver_error)?; + context.moe_combine_f64(&parts, &weights, &shared, &mut out).map_err(moe_driver_error)?; download(&out, N) })(); let cleanup = release([parts, weights, shared, out]); @@ -255,16 +228,12 @@ fn routed( .and_then(|()| download(&gateup, 2 * FF)); let _finite = result?; let mut hidden = allocate(context, FF)?; - context - .mtp_swiglu_640(&gateup, &mut hidden) - .map_err(moe_driver_error)?; + context.mtp_swiglu_640(&gateup, &mut hidden).map_err(moe_driver_error)?; download(&hidden, FF)?; gateup.release().map_err(moe_driver_error)?; let mut q = context.allocate(680).map_err(moe_driver_error)?; let mut scales = allocate(context, 20)?; - context - .mtp_quantize_scaled_640(&hidden, &mut q, &mut scales) - .map_err(moe_driver_error)?; + context.mtp_quantize_scaled_640(&hidden, &mut q, &mut scales).map_err(moe_driver_error)?; download(&scales, 20)?; hidden.release().map_err(moe_driver_error)?; let mut out = allocate(context, N)?; @@ -289,27 +258,21 @@ fn shared( let gate = upload(context, &gate)?; let up = upload(context, &up)?; let mut hidden = allocate(context, FF)?; - context - .moe_swiglu_f32(&gate, &up, &mut hidden) - .map_err(moe_driver_error)?; + context.moe_swiglu_f32(&gate, &up, &mut hidden).map_err(moe_driver_error)?; let hidden_values = download(&hidden, FF)?; release([gate, up, hidden])?; let shared = project(context, binding, MtpRole::SharedDown, &hidden_values, cache)?; let (_, _, _, scalar_weights) = cache.mtp_matrix(binding, context, MtpRole::SharedScalar)?; let shared = upload(context, &shared)?; let mut scalar = allocate(context, 1)?; - context - .moe_shared_scalar_f32_bf16(x, scalar_weights, &mut scalar) - .map_err(moe_driver_error)?; + context.moe_shared_scalar_f32_bf16(x, scalar_weights, &mut scalar).map_err(moe_driver_error)?; let scalar_value = download(&scalar, 1)?; if !(0.0..=1.0).contains(&scalar_value[0]) { return Err(Error::NonFinite); } let mut scaled = allocate(context, N)?; let result: Result> = (|| { - context - .moe_shared_scale_f32(&shared, &scalar, &mut scaled) - .map_err(moe_driver_error)?; + context.moe_shared_scale_f32(&shared, &scalar, &mut scaled).map_err(moe_driver_error)?; download(&scaled, N) })(); let cleanup = release([shared, scalar, scaled]); @@ -326,10 +289,7 @@ fn gate_up_tile(gate: &[u8], up: &[u8]) -> Result { if gate.len() != 16 * 40 * 18 || up.len() != gate.len() { return Err(Error::InvalidDimension); } - let mut tile = S2Tile { - codes: reserve(32 * 40 * 16)?, - scales: reserve(32 * 40 * 2)?, - }; + let mut tile = S2Tile { codes: reserve(32 * 40 * 16)?, scales: reserve(32 * 40 * 2)? }; for row in 0..16 { for source in [gate, up] { append_row(&mut tile, &source[row * 40 * 18..(row + 1) * 40 * 18])?; @@ -341,10 +301,7 @@ fn down_tile(rows: &[u8]) -> Result { if rows.len() != 64 * 10 * 18 { return Err(Error::InvalidDimension); } - let mut tile = S2Tile { - codes: reserve(64 * 10 * 16)?, - scales: reserve(64 * 10 * 2)?, - }; + let mut tile = S2Tile { codes: reserve(64 * 10 * 16)?, scales: reserve(64 * 10 * 2)? }; for row in rows.as_chunks::<{ 10 * 18 }>().0 { append_row(&mut tile, row)?; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/tests.rs index 5b4faaec..d03edf53 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_experts/tests.rs @@ -10,9 +10,7 @@ fn fixture(rows: usize, blocks: usize, salt: u8) -> Vec { let half = [0x8000u16, 0x0001, 0x3c00, 0xbc00][block % 4]; bytes[at..at + 2].copy_from_slice(&half.to_le_bytes()); for lane in 0..16 { - bytes[at + 2 + lane] = salt - .wrapping_add(row as u8) - .wrapping_add((block * 3 + lane) as u8); + bytes[at + 2 + lane] = salt.wrapping_add(row as u8).wrapping_add((block * 3 + lane) as u8); } } } @@ -29,14 +27,8 @@ fn mtp_experts_new_gate_up_tiles_preserve_every_label() { for block in 0..40 { let input = (row * 40 + block) * 18; let packed = (2 * row + kind) * 40 + block; - assert_eq!( - &tile.scales[packed * 2..packed * 2 + 2], - &source[input..input + 2] - ); - assert_eq!( - &tile.codes[packed * 16..packed * 16 + 16], - &source[input + 2..input + 18] - ); + assert_eq!(&tile.scales[packed * 2..packed * 2 + 2], &source[input..input + 2]); + assert_eq!(&tile.codes[packed * 16..packed * 16 + 16], &source[input + 2..input + 18]); } } } @@ -47,23 +39,14 @@ fn mtp_experts_new_down_tiles_preserve_every_label() { let tile = down_tile(&rows).unwrap(); assert_eq!((tile.codes.len(), tile.scales.len()), (10240, 1280)); for block in 0..640 { - assert_eq!( - &tile.scales[block * 2..block * 2 + 2], - &rows[block * 18..block * 18 + 2] - ); - assert_eq!( - &tile.codes[block * 16..block * 16 + 16], - &rows[block * 18 + 2..block * 18 + 18] - ); + assert_eq!(&tile.scales[block * 2..block * 2 + 2], &rows[block * 18..block * 18 + 2]); + assert_eq!(&tile.codes[block * 16..block * 16 + 16], &rows[block * 18 + 2..block * 18 + 18]); } } #[test] fn mtp_experts_new_adapter_refuses_shape_and_nonfinite_scales() { let gate = fixture(16, 40, 3); - assert!(matches!( - gate_up_tile(&gate[..gate.len() - 1], &gate), - Err(Error::InvalidDimension) - )); + assert!(matches!(gate_up_tile(&gate[..gate.len() - 1], &gate), Err(Error::InvalidDimension))); assert!(matches!(down_tile(&[0; 1]), Err(Error::InvalidDimension))); for raw in [0x7c00u16, 0xfc00, 0x7e00] { let mut bad = gate.clone(); @@ -76,10 +59,7 @@ fn mtp_experts_new_adapter_refuses_shape_and_nonfinite_scales() { fn mtp_experts_new_route_refuses_duplicate_range_and_weights() { let ids = [511, 0, 31, 7, 9, 255, 256, 3, 4, 5]; let weights = [0.1; K]; - assert_eq!( - validate_route(ids, &weights).unwrap(), - ids.map(|id| id as u32) - ); + assert_eq!(validate_route(ids, &weights).unwrap(), ids.map(|id| id as u32)); for (slot, value) in [(9, -1), (9, 512), (9, 511)] { let mut bad = ids; bad[slot] = value; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport.rs index 6b11105a..9cdbc305 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport.rs @@ -88,10 +88,7 @@ impl<'ctx> Transport<'ctx> { if self.buffers[slot].is_some() { return Err(Error::IdentityMismatch); } - let result = self - .context - .allocate(role.count() * 4) - .map_err(driver_error); + let result = self.context.allocate(role.count() * 4).map_err(driver_error); self.note(&result); self.buffers[slot] = Some(result?); Ok(()) @@ -102,9 +99,7 @@ impl<'ctx> Transport<'ctx> { } validate_values(values, role.count())?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(role.count() * 4) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(role.count() * 4).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } @@ -131,12 +126,7 @@ impl<'ctx> Transport<'ctx> { self.allocate(role)?; let (inputs, output) = self.buffers.split_at_mut(role as usize); let result = operation(inputs, output[0].as_mut().ok_or(Error::IdentityMismatch)?) - .and_then(|()| { - download( - output[0].as_ref().ok_or(Error::IdentityMismatch)?, - role.count(), - ) - }); + .and_then(|()| download(output[0].as_ref().ok_or(Error::IdentityMismatch)?, role.count())); self.note(&result); let values = result?; self.finite(role, values) @@ -145,20 +135,13 @@ impl<'ctx> Transport<'ctx> { validate_values(&values, role.count())?; #[cfg(test)] if let Some(observations) = &mut self.observations { - observations - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + observations.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut copy = Vec::new(); - copy.try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; + copy.try_reserve_exact(values.len()).map_err(|_| Error::InputAllocation)?; copy.extend_from_slice(&values); observations.push((role, copy.into_boxed_slice())); } - Ok(Finite { - role, - values, - invocation: Rc::clone(&self.invocation), - }) + Ok(Finite { role, values, invocation: Rc::clone(&self.invocation) }) } fn validate(&self, finite: &Finite, role: Role) -> Result<()> { if finite.role != role || !Rc::ptr_eq(&finite.invocation, &self.invocation) { @@ -171,9 +154,7 @@ impl<'ctx> Transport<'ctx> { Ok(()) } fn release(&mut self, role: Role) -> Result<()> { - let result = self.buffers[role as usize] - .take() - .map_or(Ok(()), |buffer| buffer.release().map_err(driver_error)); + let result = self.buffers[role as usize].take().map_or(Ok(()), |buffer| buffer.release().map_err(driver_error)); if result.is_err() { self.failed.set(true); } @@ -213,14 +194,8 @@ impl Drop for Transport<'_> { let _ = self.close(); } } -fn at<'a, 'ctx>( - buffers: &'a [Option>], - role: Role, -) -> Result<&'a DeviceBuffer<'ctx>> { - buffers - .get(role as usize) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) +fn at<'a, 'ctx>(buffers: &'a [Option>], role: Role) -> Result<&'a DeviceBuffer<'ctx>> { + buffers.get(role as usize).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } pub(super) fn compose( @@ -264,9 +239,7 @@ fn compose_inner( // Same host-gamma finite gate, after original injected-residual readback. validate_values(gamma, STREAMS)?; let normalized = transport.produce(Role::Normalized, |values, out| { - context - .gr_norm_f32(at(values, Role::Residual)?, matrices[0], 1e-6, out) - .map_err(driver_error) + context.gr_norm_f32(at(values, Role::Residual)?, matrices[0], 1e-6, out).map_err(driver_error) }); let cleanup = transport.release(Role::Residual); let normalized = normalized?; @@ -278,18 +251,13 @@ fn compose_inner( matrices[1], at(values, Role::Normalized)?, out, - Bf16ProjectionShape { - rows: H, - columns: STREAMS, - }, + Bf16ProjectionShape { rows: H, columns: STREAMS }, ) .map_err(driver_error) })?; transport.validate(&down, Role::Down)?; let activated = transport.produce(Role::Activated, |values, out| { - context - .gr_down_silu_hc_f32(at(values, Role::Down)?, out) - .map_err(driver_error) + context.gr_down_silu_hc_f32(at(values, Role::Down)?, out).map_err(driver_error) }); let cleanup = transport.release(Role::Down); let activated = activated?; @@ -297,15 +265,7 @@ fn compose_inner( transport.validate(&activated, Role::Activated)?; let gates = transport.produce(Role::Gates, |values, out| { context - .bf16_f32( - matrices[2], - at(values, Role::Activated)?, - out, - Bf16ProjectionShape { - rows: STREAMS, - columns: H, - }, - ) + .bf16_f32(matrices[2], at(values, Role::Activated)?, out, Bf16ProjectionShape { rows: STREAMS, columns: H }) .map_err(driver_error) }); let cleanup = transport.release(Role::Activated); @@ -325,10 +285,7 @@ fn compose_inner( ) .map_err(driver_error) .and_then(|()| { - let products = download( - products[0].as_ref().ok_or(Error::IdentityMismatch)?, - STREAMS, - )?; + let products = download(products[0].as_ref().ok_or(Error::IdentityMismatch)?, STREAMS)?; let mixed = download(mixed[0].as_ref().ok_or(Error::IdentityMismatch)?, N)?; Ok((products, mixed)) }); @@ -338,10 +295,7 @@ fn compose_inner( let mixed = transport.finite(Role::Mixed, mixed)?; transport.validate(&products, Role::Products)?; transport.validate(&mixed, Role::Mixed)?; - Ok(Candidate { - streams: residual.values, - mixed: mixed.values, - }) + Ok(Candidate { streams: residual.values, mixed: mixed.values }) } #[cfg(test)] @@ -358,10 +312,7 @@ fn compose_observed( let mut transport = Transport::new(context, failed)?; transport.observations = Some(Vec::new()); let result = compose_inner(&mut transport, matrices, gamma, inputs); - let observations = transport - .observations - .take() - .ok_or(Error::IdentityMismatch)?; + let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?; let values = transport.finish(result)?; Ok((values, observations)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport_gpu.rs index 9237f5fb..26dfabf6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_final_transport_gpu.rs @@ -16,13 +16,15 @@ fn bf16(rows: usize, columns: usize, seed: usize) -> Vec { } fn source(n: usize, modulus: usize, center: f32, divisor: f32, zero: bool) -> Vec { (0..n) - .map(|i| { - if zero { - if i.is_multiple_of(2) { -0. } else { 0. } - } else { - ((i % modulus) as f32 - center) / divisor - } - }) + .map( + |i| { + if zero { + if i.is_multiple_of(2) { -0. } else { 0. } + } else { + ((i % modulus) as f32 - center) / divisor + } + }, + ) .collect() } fn exact(a: &[f32], b: &[f32]) { @@ -32,43 +34,28 @@ fn exact(a: &[f32], b: &[f32]) { assert_eq!(a.to_bits(), b.to_bits(), "word {i}"); } } -fn original( - ctx: &Context<'_>, - matrices: [&DeviceBuffer<'_>; 3], - inputs: Inputs<'_>, -) -> Vec> { +fn original(ctx: &Context<'_>, matrices: [&DeviceBuffer<'_>; 3], inputs: Inputs<'_>) -> Vec> { // Qualified original kernels with the original host readback/re-upload at // every boundary. This never calls the candidate transport or host math. let streams = upload(ctx, inputs.streams).unwrap(); let block = upload(ctx, inputs.block).unwrap(); let inject = upload(ctx, inputs.inject).unwrap(); let mut residual = ctx.allocate(40960).unwrap(); - ctx.gr_inject_residual_f32(&streams, &block, &inject, &mut residual) - .unwrap(); + ctx.gr_inject_residual_f32(&streams, &block, &inject, &mut residual).unwrap(); let mut trace = vec![download(&residual, 10240).unwrap()]; for b in [residual, inject, block, streams] { b.release().unwrap(); } let residual = upload(ctx, &trace[0]).unwrap(); let mut normalized = ctx.allocate(40960).unwrap(); - ctx.gr_norm_f32(&residual, matrices[0], 1e-6, &mut normalized) - .unwrap(); + ctx.gr_norm_f32(&residual, matrices[0], 1e-6, &mut normalized).unwrap(); trace.push(download(&normalized, 10240).unwrap()); for b in [normalized, residual] { b.release().unwrap(); } let normalized = upload(ctx, &trace[1]).unwrap(); let mut down = ctx.allocate(1280).unwrap(); - ctx.bf16_f32( - matrices[1], - &normalized, - &mut down, - Bf16ProjectionShape { - rows: 320, - columns: 10240, - }, - ) - .unwrap(); + ctx.bf16_f32(matrices[1], &normalized, &mut down, Bf16ProjectionShape { rows: 320, columns: 10240 }).unwrap(); trace.push(download(&down, 320).unwrap()); for b in [down, normalized] { b.release().unwrap(); @@ -82,16 +69,7 @@ fn original( } let activated = upload(ctx, &trace[3]).unwrap(); let mut gates = ctx.allocate(40960).unwrap(); - ctx.bf16_f32( - matrices[2], - &activated, - &mut gates, - Bf16ProjectionShape { - rows: 10240, - columns: 320, - }, - ) - .unwrap(); + ctx.bf16_f32(matrices[2], &activated, &mut gates, Bf16ProjectionShape { rows: 10240, columns: 320 }).unwrap(); trace.push(download(&gates, 10240).unwrap()); for b in [gates, activated] { b.release().unwrap(); @@ -100,8 +78,7 @@ fn original( let gates = upload(ctx, &trace[4]).unwrap(); let mut products = ctx.allocate(40960).unwrap(); let mut mixed = ctx.allocate(10240).unwrap(); - ctx.gr_gate_mean_final_unfused_f32(&normalized, &gates, &mut products, &mut mixed) - .unwrap(); + ctx.gr_gate_mean_final_unfused_f32(&normalized, &gates, &mut products, &mut mixed).unwrap(); trace.push(download(&products, 10240).unwrap()); trace.push(download(&mixed, 2560).unwrap()); for b in [mixed, products, gates, normalized] { @@ -116,13 +93,8 @@ fn owned_residual(transport: &mut Transport<'_>) -> Finite { let ctx = transport.context; transport .produce(Role::Residual, |v, out| { - ctx.gr_inject_residual_f32( - at(v, Role::Streams)?, - at(v, Role::Block)?, - at(v, Role::Inject)?, - out, - ) - .map_err(driver_error) + ctx.gr_inject_residual_f32(at(v, Role::Streams)?, at(v, Role::Block)?, at(v, Role::Inject)?, out) + .map_err(driver_error) }) .unwrap() } @@ -145,61 +117,29 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { let streams = source(10240, 19, 9., 64., zero); let block = source(2560, 13, 6., 128., zero); let inject = [0.25, -0.5, 0.75, 1.]; - let snapshot: Vec<_> = streams - .iter() - .chain(&block) - .chain(&inject) - .map(|x| x.to_bits()) - .collect(); - let expected = original( - &ctx, - [&norm, &down, &up], - Inputs { - streams: &streams, - block: &block, - inject: &inject, - }, - ); + let snapshot: Vec<_> = streams.iter().chain(&block).chain(&inject).map(|x| x.to_bits()).collect(); + let expected = + original(&ctx, [&norm, &down, &up], Inputs { streams: &streams, block: &block, inject: &inject }); assert_eq!(ctx.allocated_bytes(), charged); let failed = Rc::new(Cell::new(false)); let (actual, trace) = compose_observed( &ctx, [&norm, &down, &up], &gamma, - Inputs { - streams: &streams, - block: &block, - inject: &inject, - }, + Inputs { streams: &streams, block: &block, inject: &inject }, failed.clone(), ) .unwrap(); assert_eq!(trace.len(), 7); - let roles = [ - Role::Residual, - Role::Normalized, - Role::Down, - Role::Activated, - Role::Gates, - Role::Products, - Role::Mixed, - ]; - for ((role, values), (wanted_role, wanted)) in trace.iter().zip(roles.iter().zip(&expected)) - { + let roles = + [Role::Residual, Role::Normalized, Role::Down, Role::Activated, Role::Gates, Role::Products, Role::Mixed]; + for ((role, values), (wanted_role, wanted)) in trace.iter().zip(roles.iter().zip(&expected)) { assert_eq!(role, wanted_role); exact(values, wanted); } exact(&actual.streams, &expected[0]); exact(&actual.mixed, &expected[6]); - assert_eq!( - streams - .iter() - .chain(&block) - .chain(&inject) - .map(|x| x.to_bits()) - .collect::>(), - snapshot - ); + assert_eq!(streams.iter().chain(&block).chain(&inject).map(|x| x.to_bits()).collect::>(), snapshot); assert!(!failed.get()); assert_eq!(ctx.allocated_bytes(), charged); println!("MTP_FINAL zero={zero} trace_words=44160 returned_words=12800 exact=true"); @@ -213,11 +153,7 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { [&norm, &down, &up], if short == 3 { &gamma[..10239] } else { &gamma }, Inputs { - streams: if short == 0 { - &streams[..10239] - } else { - &streams - }, + streams: if short == 0 { &streams[..10239] } else { &streams }, block: if short == 1 { &block[..2559] } else { &block }, inject: if short == 2 { &inject[..3] } else { &inject }, }, @@ -234,11 +170,7 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { &ctx, [&norm, &down, &up], &gamma, - Inputs { - streams: &malformed, - block: &block, - inject: &inject - }, + Inputs { streams: &malformed, block: &block, inject: &inject }, Rc::new(Cell::new(false)) ), Err(Error::NonFinite) @@ -255,11 +187,7 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { &ctx, [&norm, &down, &up], &gamma, - Inputs { - streams: &streams, - block: &block, - inject: &inject - }, + Inputs { streams: &streams, block: &block, inject: &inject }, Rc::new(Cell::new(false)) ), Err(Error::NonFinite) @@ -274,11 +202,7 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { &ctx, [&foreign_norm, &down, &up], &gamma, - Inputs { - streams: &streams, - block: &block, - inject: &inject - }, + Inputs { streams: &streams, block: &block, inject: &inject }, Rc::new(Cell::new(false)) ), Err(Error::IdentityMismatch) @@ -289,33 +213,15 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { foreign.close().unwrap(); let mut first = Transport::new(&ctx, Rc::new(Cell::new(false))).unwrap(); let finite = owned_residual(&mut first); - assert_eq!( - first.validate(&finite, Role::Normalized), - Err(Error::IdentityMismatch) - ); + assert_eq!(first.validate(&finite, Role::Normalized), Err(Error::IdentityMismatch)); let second = Transport::new(&ctx, Rc::new(Cell::new(false))).unwrap(); - assert_eq!( - second.validate(&finite, Role::Residual), - Err(Error::IdentityMismatch) - ); + assert_eq!(second.validate(&finite, Role::Residual), Err(Error::IdentityMismatch)); second.finish(Ok(())).unwrap(); - assert_eq!( - first.upload(Role::Residual, &[0.; 10240]), - Err(Error::IdentityMismatch) - ); - assert_eq!( - first.upload(Role::Streams, &streams), - Err(Error::IdentityMismatch) - ); + assert_eq!(first.upload(Role::Residual, &[0.; 10240]), Err(Error::IdentityMismatch)); + assert_eq!(first.upload(Role::Streams, &streams), Err(Error::IdentityMismatch)); first.release(Role::Residual).unwrap(); - assert_eq!( - first.validate(&finite, Role::Residual), - Err(Error::IdentityMismatch) - ); - assert_eq!( - first.finish::<()>(Err(Error::NonFinite)), - Err(Error::NonFinite) - ); + assert_eq!(first.validate(&finite, Role::Residual), Err(Error::IdentityMismatch)); + assert_eq!(first.finish::<()>(Err(Error::NonFinite)), Err(Error::NonFinite)); assert_eq!(ctx.allocated_bytes(), charged); // Drop with a real allocated input is a genuine abort cleanup; manual // sticky state tests policy only and never simulates a driver fault. @@ -325,16 +231,10 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { } assert_eq!(ctx.allocated_bytes(), charged); let sticky = Rc::new(Cell::new(true)); - assert!(matches!( - Transport::new(&ctx, sticky.clone()), - Err(Error::CudaExecution) - )); + assert!(matches!(Transport::new(&ctx, sticky.clone()), Err(Error::CudaExecution))); assert!(sticky.get()); let tiny = device.create_context(FINAL_PEAK - 1).unwrap(); - assert!(matches!( - Transport::new(&tiny, Rc::new(Cell::new(false))), - Err(Error::InputAllocation) - )); + assert!(matches!(Transport::new(&tiny, Rc::new(Cell::new(false))), Err(Error::InputAllocation))); assert_eq!(tiny.allocated_bytes(), 0); tiny.close().unwrap(); let mut copy = vec![0; down_bytes.len()]; @@ -349,7 +249,5 @@ fn retained_final_matches_original_reuploads_and_fences_invocation_abort() { } assert_eq!(ctx.allocated_bytes(), 0); ctx.close().unwrap(); - println!( - "MTP_FINAL total_exact_words=113920 guards=16 aborts=2 cleanup=0 sticky_policy_only=true" - ); + println!("MTP_FINAL total_exact_words=113920 guards=16 aborts=2 cleanup=0 sticky_policy_only=true"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr.rs index 7337358f..619b1560 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr.rs @@ -9,8 +9,7 @@ use super::{ mtp_attention::MtpAttentionReady, mtp_experts::MtpBlock, qsa_index::{ - allocate, binding_error, download, driver_error as shared_driver_error, release, upload, - validate_values, + allocate, binding_error, download, driver_error as shared_driver_error, release, upload, validate_values, }, session::QwenSession, }; @@ -61,23 +60,23 @@ struct Candidate { mod driver_error_fn; #[allow(unused_imports)] -use driver_error_fn::driver_error; +use driver_error_fn::admit_role; #[allow(unused_imports)] pub(super) use driver_error_fn::attention_read; #[allow(unused_imports)] -pub(super) use driver_error_fn::mlp_read; -#[allow(unused_imports)] -use driver_error_fn::admit_role; +use driver_error_fn::driver_error; #[allow(unused_imports)] use driver_error_fn::fused; +#[allow(unused_imports)] +pub(super) use driver_error_fn::mlp_read; mod finalize_fn; #[allow(unused_imports)] +use finalize_fn::down_silu; +#[allow(unused_imports)] +use finalize_fn::final_gate; +#[allow(unused_imports)] pub(super) use finalize_fn::finalize; #[allow(unused_imports)] use finalize_fn::finalize_legacy; #[allow(unused_imports)] use finalize_fn::inject_residual; -#[allow(unused_imports)] -use finalize_fn::down_silu; -#[allow(unused_imports)] -use finalize_fn::final_gate; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/driver_error_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/driver_error_fn.rs index bfa759d5..57f22ac7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/driver_error_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/driver_error_fn.rs @@ -3,9 +3,10 @@ #[allow(unused_imports)] use super::*; - pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } match shared_driver_error(error) { Error::Unsupported(_) => Error::Unsupported(Stage::Gr), other => other, @@ -59,13 +60,7 @@ pub(in super::super) fn attention_read( ) -> Result { input.frame().validate(binding, session)?; validate_values(input.streams(), STREAMS)?; - let candidate = fused( - session.mtp_context()?, - binding, - input.streams(), - Read::Attention, - cache, - )?; + let candidate = fused(session.mtp_context()?, binding, input.streams(), Read::Attention, cache)?; input.frame().validate(binding, session)?; Ok(MtpAttentionRead { frame: input.frame().clone(), @@ -89,10 +84,7 @@ pub(in super::super) fn mlp_read( session.mtp_context()?, binding, input.streams(), - Read::Mlp { - block: input.output(), - inject: input.inject(), - }, + Read::Mlp { block: input.output(), inject: input.inject() }, cache, )?; input.frame().validate(binding, session)?; @@ -104,18 +96,8 @@ pub(in super::super) fn mlp_read( }) } -pub(super) fn admit_role( - binding: &ModelBinding, - role: MtpRole, - expected: (MtpKind, usize, usize), -) -> Result<()> { - if binding - .mtp_weights() - .map_err(binding_error)? - .dense_shape(binding, role) - .map_err(binding_error)? - != expected - { +pub(super) fn admit_role(binding: &ModelBinding, role: MtpRole, expected: (MtpKind, usize, usize)) -> Result<()> { + if binding.mtp_weights().map_err(binding_error)?.dense_shape(binding, role).map_err(binding_error)? != expected { return Err(Error::InvalidDimension); } Ok(()) @@ -129,23 +111,14 @@ pub(super) fn fused( cache: &MoeWeightCache<'_>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); validate_values(streams, STREAMS)?; let roles = match read { - Read::Attention => [ - MtpRole::AttentionNorm, - MtpRole::AttentionDown, - MtpRole::AttentionUp, - MtpRole::AttentionInject, - ], - Read::Mlp { .. } => [ - MtpRole::FfnNorm, - MtpRole::FfnDown, - MtpRole::FfnUp, - MtpRole::FfnInject, - ], + Read::Attention => { + [MtpRole::AttentionNorm, MtpRole::AttentionDown, MtpRole::AttentionUp, MtpRole::AttentionInject] + } + Read::Mlp { .. } => [MtpRole::FfnNorm, MtpRole::FfnDown, MtpRole::FfnUp, MtpRole::FfnInject], }; for (role, shape) in roles.into_iter().zip([ (MtpKind::F32, 1, STREAMS), @@ -174,16 +147,10 @@ pub(super) fn fused( let _ = download(&lo, H)?; let _ = download(&rs, 4)?; let inject = download(&injection, 4)?; - context - .mtp_gr_attention_up(&r, norm, up, &lo, &rs, &mut mixed) - .map_err(driver_error)?; + context.mtp_gr_attention_up(&r, norm, up, &lo, &rs, &mut mixed).map_err(driver_error)?; let mut retained = reserve(STREAMS)?; retained.extend_from_slice(streams); - Ok(Candidate { - streams: retained.into_boxed_slice(), - mixed: download(&mixed, N)?, - inject, - }) + Ok(Candidate { streams: retained.into_boxed_slice(), mixed: download(&mixed, N)?, inject }) })(), Read::Mlp { block, inject } => { let bo = upload(context, block)?; @@ -191,17 +158,7 @@ pub(super) fn fused( let mut out = allocate(context, STREAMS)?; let result = (|| { context - .mtp_gr_mlp_down( - &r, - &bo, - &previous, - norm, - down, - weights, - &mut lo, - &mut rs, - &mut injection, - ) + .mtp_gr_mlp_down(&r, &bo, &previous, norm, down, weights, &mut lo, &mut rs, &mut injection) .map_err(driver_error)?; let _ = download(&lo, H)?; let _ = download(&rs, 4)?; @@ -209,11 +166,7 @@ pub(super) fn fused( context .mtp_gr_mlp_up(&r, &bo, &previous, norm, up, &lo, &rs, &mut out, &mut mixed) .map_err(driver_error)?; - Ok(Candidate { - streams: download(&out, STREAMS)?, - mixed: download(&mixed, N)?, - inject, - }) + Ok(Candidate { streams: download(&out, STREAMS)?, mixed: download(&mixed, N)?, inject }) })(); let cleanup = release([bo, previous, out]); result.and_then(|value| cleanup.map(|()| value)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/finalize_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/finalize_fn.rs index 70bd9c7d..dfdf57c9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/finalize_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_gr/finalize_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(in super::super) fn finalize( binding: &ModelBinding, block: &MtpBlock, @@ -12,9 +11,8 @@ pub(in super::super) fn finalize( cache: &MoeWeightCache<'_>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Gr, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Gr); let failed = Rc::new(Cell::new(false)); let result = (|| { let frame = input.frame().clone(); @@ -52,11 +50,7 @@ pub(in super::super) fn finalize( context, matrices, &gamma, - mtp_final_transport::Inputs { - streams: input.streams(), - block: block.output(), - inject: input.inject(), - }, + mtp_final_transport::Inputs { streams: input.streams(), block: block.output(), inject: input.inject() }, Rc::clone(&failed), )?; frame.validate(binding, session)?; @@ -111,9 +105,7 @@ pub(super) fn finalize_legacy( let (_, _, _, w) = cache.mtp_matrix(binding, context, MtpRole::FinalNorm)?; let mut xn = allocate(context, STREAMS)?; let normalized = (|| { - context - .gr_norm_f32(&r, w, 1e-6, &mut xn) - .map_err(driver_error)?; + context.gr_norm_f32(&r, w, 1e-6, &mut xn).map_err(driver_error)?; download(&xn, STREAMS) })(); let cleanup = release([r, xn]); @@ -124,10 +116,7 @@ pub(super) fn finalize_legacy( let gates = project(context, binding, MtpRole::FinalUp, &activated, cache)?; let result = final_gate(context, &normalized, &gates)?; input.frame().validate(binding, session)?; - Ok(MtpDraftFinal { - mixed: MtpFinalMixed::from_native_mixer(input.frame().clone(), result)?, - streams, - }) + Ok(MtpDraftFinal { mixed: MtpFinalMixed::from_native_mixer(input.frame().clone(), result)?, streams }) } pub(super) fn inject_residual( @@ -141,9 +130,7 @@ pub(super) fn inject_residual( let i = upload(context, inject)?; let mut out = allocate(context, STREAMS)?; let result = (|| { - context - .gr_inject_residual_f32(&r, &b, &i, &mut out) - .map_err(driver_error)?; + context.gr_inject_residual_f32(&r, &b, &i, &mut out).map_err(driver_error)?; download(&out, STREAMS) })(); let cleanup = release([r, b, i, out]); @@ -153,9 +140,7 @@ pub(super) fn down_silu(context: &Context<'_>, down: &[f32]) -> Result, normalized: &[f32], gates: &[f32 let mut products = allocate(context, STREAMS)?; let mut out = allocate(context, N)?; let result = (|| { - context - .gr_gate_mean_final_unfused_f32(&x, &g, &mut products, &mut out) - .map_err(driver_error)?; + context.gr_gate_mean_final_unfused_f32(&x, &g, &mut products, &mut out).map_err(driver_error)?; let _ = download(&products, STREAMS)?; download(&out, N) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs index d4ed44c1..f23b2438 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_only.rs @@ -43,15 +43,10 @@ pub(in crate::qwen_forward) fn produce_chunk_kv_only( let result = (|| { let input = MtpInput::compute(binding, target, frame.clone(), streams, cache)?; let read = super::super::mtp_gr::attention_read(binding, &input, target, cache)?; - let (key, value) = - super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?; + let (key, value) = super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?; target.finish_mtp_device()?; frame.validate(binding, target)?; - product = Some(MtpKvOnlyProduct { - frame: frame.clone(), - key, - value, - }); + product = Some(MtpKvOnlyProduct { frame: frame.clone(), key, value }); Ok(()) })(); if let Err(error) = &result { @@ -86,8 +81,7 @@ pub(in crate::qwen_forward) fn compare_kv_cell_on_loaded_input( )?; let (expected_k, expected_v) = reference.pending_kv().ring_last(input.frame())?; let read = super::super::mtp_gr::attention_read(binding, input, target, cache)?; - let (actual_k, actual_v) = - super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?; + let (actual_k, actual_v) = super::super::mtp_attention::produce_kv_cell(binding, &read, target, cache)?; target.finish_mtp_device()?; input.frame().validate(binding, target)?; if actual_k.as_ref() != expected_k || actual_v.as_ref() != expected_v { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs index 5f293875..bd0f5a5d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_kv_resident.rs @@ -27,13 +27,7 @@ impl<'ctx> MtpKvResident<'ctx> { if ring.allocated_bytes() != RING_BYTES { return Err(Error::IdentityMismatch); } - Ok(Self { - binding, - context, - owner, - ring, - prior: None, - }) + Ok(Self { binding, context, owner, ring, prior: None }) } pub(super) fn prepare( &mut self, @@ -51,29 +45,16 @@ impl<'ctx> MtpKvResident<'ctx> { } next.ring_validate(frame)?; let position = u32::try_from(frame.position().get()).map_err(|_| Error::Overflow)?; - if self - .prior - .as_ref() - .map(|old| next.ring_same(old, frame)) - .transpose()? - .unwrap_or(false) - { + if self.prior.as_ref().map(|old| next.ring_same(old, frame)).transpose()?.unwrap_or(false) { return Ok(()); } - let append = self - .prior - .as_ref() - .map(|old| next.ring_append(old, frame)) - .transpose()? - .unwrap_or(false); + let append = self.prior.as_ref().map(|old| next.ring_append(old, frame)).transpose()?.unwrap_or(false); let result = if append { let (key, value) = next.ring_last(frame)?; self.ring.append(position, key, value).map_err(driver_error) } else { let (keys, values) = next.window(frame)?; - self.ring - .reload(position, &keys, &values) - .map_err(driver_error) + self.ring.reload(position, &keys, &values).map_err(driver_error) }; // Do not advertise a partial transport or retain a stale proof after it. self.prior = None; @@ -87,10 +68,7 @@ impl<'ctx> MtpKvResident<'ctx> { output: &mut DeviceBuffer<'_>, position: u32, ) -> Result<()> { - let result = self - .ring - .attend(query, output, position) - .map_err(driver_error); + let result = self.ring.attend(query, output, position).map_err(driver_error); if result.is_err() { self.prior = None; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs index 0d7bb9be..14aac754 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state.rs @@ -1,7 +1,7 @@ //! Immutable dense draft K/V and complete bounded draft checkpoints. use super::{ - BindingIdentity, Cell, Dimension, Error, ModelBinding, MtpFrame, Position, Rc, Result, - TargetStepOrigin, TokenId, reserve, + BindingIdentity, Cell, Dimension, Error, ModelBinding, MtpFrame, Position, Rc, Result, TargetStepOrigin, TokenId, + reserve, }; use std::rc::Weak; const WINDOW: usize = 32768; @@ -11,10 +11,10 @@ type HalfWindow = (Box<[u8]>, Box<[u8]>); mod chunk; #[path = "mtp_state_warming.rs"] mod warming; -pub(in crate::qwen_forward) use warming::{MtpKvPrefill, ReadyMtpKvPrefill}; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) use chunk::MtpChunkNumericSnapshot; pub(in crate::qwen_forward) use chunk::MtpChunkStage; +pub(in crate::qwen_forward) use warming::{MtpKvPrefill, ReadyMtpKvPrefill}; struct CellPair { key: Box<[u8]>, value: Box<[u8]>, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_densekv.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_densekv.rs index 44f35192..522e8de0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_densekv.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_densekv.rs @@ -5,21 +5,9 @@ use super::*; impl DenseKv { pub(super) fn empty(binding: BindingIdentity, owner: Rc>) -> Self { - Self { - binding, - owner, - next_position: 0, - cells: Rc::new(Vec::new()), - produced: None, - parent: Weak::new(), - } + Self { binding, owner, next_position: 0, cells: Rc::new(Vec::new()), produced: None, parent: Weak::new() } } - pub(in crate::qwen_forward) fn append( - &self, - frame: &MtpFrame, - key: Box<[u8]>, - value: Box<[u8]>, - ) -> Result { + pub(in crate::qwen_forward) fn append(&self, frame: &MtpFrame, key: Box<[u8]>, value: Box<[u8]>) -> Result { if !self.binding.matches(&frame.binding) || !Rc::ptr_eq(&self.owner, &frame.epoch) || frame.generation != frame.epoch.get() @@ -50,14 +38,8 @@ impl DenseKv { || !Rc::ptr_eq(&self.owner, &frame.epoch) || frame.generation != frame.epoch.get() || self.next_position != frame.position.get() + 1 - || self.cells.len() - != usize::try_from(self.next_position) - .map_err(|_| Error::Overflow)? - .min(WINDOW) - || self - .produced - .as_ref() - .is_none_or(|source| !source.same(frame)) + || self.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW) + || self.produced.as_ref().is_none_or(|source| !source.same(frame)) { return Err(Error::IdentityMismatch); } @@ -72,22 +54,16 @@ impl DenseKv { pub(super) fn ring_lineage(&self, old: &Self, frame: &MtpFrame) -> bool { self.binding.matches(&old.binding) && Rc::ptr_eq(&self.owner, &old.owner) - && old.produced.as_ref().is_some_and(|prior| { - prior.generation == frame.generation && prior.origin.same_branch(&frame.origin) - }) + && old + .produced + .as_ref() + .is_some_and(|prior| prior.generation == frame.generation && prior.origin.same_branch(&frame.origin)) } - pub(in crate::qwen_forward) fn ring_append( - &self, - old: &Self, - frame: &MtpFrame, - ) -> Result { + pub(in crate::qwen_forward) fn ring_append(&self, old: &Self, frame: &MtpFrame) -> Result { self.ring_validate(frame)?; Ok(self.ring_lineage(old, frame) && old.next_position.checked_add(1) == Some(self.next_position) - && self - .parent - .upgrade() - .is_some_and(|p| Rc::ptr_eq(&p, &old.cells))) + && self.parent.upgrade().is_some_and(|p| Rc::ptr_eq(&p, &old.cells))) } pub(in crate::qwen_forward) fn ring_last(&self, frame: &MtpFrame) -> Result<(&[u8], &[u8])> { self.ring_validate(frame)?; @@ -101,22 +77,12 @@ impl DenseKv { || !Rc::ptr_eq(&self.owner, &frame.epoch) || frame.generation != frame.epoch.get() || self.next_position != frame.position.get() + 1 - || self.cells.len() - != usize::try_from(self.next_position) - .map_err(|_| Error::Overflow)? - .min(WINDOW) - || self - .produced - .as_ref() - .is_none_or(|source| !source.same(frame)) + || self.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW) + || self.produced.as_ref().is_none_or(|source| !source.same(frame)) { return Err(Error::IdentityMismatch); } - let bytes = self - .cells - .len() - .checked_mul(HALF_ROW) - .ok_or(Error::Overflow)?; + let bytes = self.cells.len().checked_mul(HALF_ROW).ok_or(Error::Overflow)?; let mut keys = reserve(bytes)?; let mut values = reserve(bytes)?; for cell in self.cells.iter() { @@ -132,12 +98,7 @@ pub(super) fn validate_half(bytes: &[u8]) -> Result<()> { if bytes.len() != HALF_ROW { return Err(Error::InvalidDimension); } - if bytes - .as_chunks::<2>() - .0 - .iter() - .any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) - { + if bytes.as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { return Err(Error::NonFinite); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs index 6855b2cd..cdcc88b4 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_mtpsession.rs @@ -31,10 +31,7 @@ impl MtpSession { ) -> Result { if !self.binding.matches(&binding.identity()) || position.get() != self.next_position - || self - .target_owner - .as_ref() - .is_some_and(|old| !old.same_session(&origin)) + || self.target_owner.as_ref().is_some_and(|old| !old.same_session(&origin)) || token != TokenId::new(u64::from(token.get()), Dimension::new(248320)?)? { return Err(Error::IdentityMismatch); @@ -58,10 +55,7 @@ impl MtpSession { || !Rc::ptr_eq(&self.epoch, &frame.epoch) || self.epoch.get() != frame.generation || self.next_position != frame.position.get() - || self - .target_owner - .as_ref() - .is_some_and(|old| !old.same_session(&frame.origin)) + || self.target_owner.as_ref().is_some_and(|old| !old.same_session(&frame.origin)) { Err(Error::IdentityMismatch) } else { @@ -80,10 +74,7 @@ impl MtpSession { if !self.binding.matches(&pending.binding) || !Rc::ptr_eq(&self.epoch, &pending.owner) || pending.next_position != self.next_position + 1 - || pending - .produced - .as_ref() - .is_none_or(|source| !source.same(frame)) + || pending.produced.as_ref().is_none_or(|source| !source.same(frame)) { return Err(Error::IdentityMismatch); } @@ -118,10 +109,7 @@ impl MtpSession { first_seed_retained_charge(cells) } - pub(in crate::qwen_forward) fn checkpoint_first_seed( - &self, - admitted: usize, - ) -> Result { + pub(in crate::qwen_forward) fn checkpoint_first_seed(&self, admitted: usize) -> Result { // try_reserve_exact may receive greater allocator capacity. Admit its // actual live pointer vector before retaining it across later drafts. if first_seed_retained_charge(self.kv.cells.capacity())? > admitted { @@ -164,8 +152,8 @@ impl MtpSession { || checkpoint.generation != generation || checkpoint.kv.next_position != checkpoint.next_position || checkpoint.next_position > self.next_position - || checkpoint.kv.cells.len() != usize::try_from(checkpoint.next_position) - .map_err(|_| Error::Overflow)?.min(WINDOW) + || checkpoint.kv.cells.len() + != usize::try_from(checkpoint.next_position).map_err(|_| Error::Overflow)?.min(WINDOW) { return Err(Error::IdentityMismatch); } @@ -179,8 +167,7 @@ impl MtpSession { || !self.binding.matches(&self.kv.binding) || !Rc::ptr_eq(&self.epoch, &self.kv.owner) || self.kv.next_position != self.next_position - || self.kv.cells.len() != usize::try_from(self.next_position) - .map_err(|_| Error::Overflow)?.min(WINDOW) + || self.kv.cells.len() != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(WINDOW) || !self.binding.matches(¤t.binding) || !Rc::ptr_eq(&self.epoch, ¤t.epoch) || current.generation != generation @@ -199,7 +186,10 @@ impl MtpSession { if self.next_position == seed_end { if !Rc::ptr_eq(&self.kv.cells, &seed.kv.cells) || !current.same(expected) - || self.residual.as_ref().zip(seed.residual.as_ref()) + || self + .residual + .as_ref() + .zip(seed.residual.as_ref()) .is_none_or(|(active, saved)| !Rc::ptr_eq(active, saved)) { return Err(Error::IdentityMismatch); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_prefixdraftsnapshot.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_prefixdraftsnapshot.rs index b6d9e242..53a74357 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_prefixdraftsnapshot.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/impl_prefixdraftsnapshot.rs @@ -42,10 +42,7 @@ impl MtpSession { || self.kv.next_position != self.next_position || self.next_position == 0 || self.next_position > crate::qwen_forward::contract::serving_cells() - || self - .target_owner - .as_ref() - .is_none_or(|old| !old.same_session(¤t.origin)) + || self.target_owner.as_ref().is_none_or(|old| !old.same_session(¤t.origin)) { return Err(Error::IdentityMismatch); } @@ -77,7 +74,8 @@ impl MtpSession { } pub(super) fn first_seed_retained_charge(cells: usize) -> Result { - cells.checked_mul(std::mem::size_of::>()) + cells + .checked_mul(std::mem::size_of::>()) .and_then(|n| n.checked_add(10240 * 4 + 2 * HALF_ROW)) .and_then(|n| n.checked_add(std::mem::size_of::())) .and_then(|n| n.checked_add(std::mem::size_of::() + 1024)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/tests.rs index 84828581..8c1d003a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state/tests.rs @@ -27,14 +27,7 @@ fn draft() -> (MtpSession, MtpFrame) { (draft, frame) } fn pending(draft: &MtpSession, frame: &MtpFrame) -> DenseKv { - draft - .kv - .append( - frame, - vec![0; HALF_ROW].into_boxed_slice(), - vec![0; HALF_ROW].into_boxed_slice(), - ) - .unwrap() + draft.kv.append(frame, vec![0; HALF_ROW].into_boxed_slice(), vec![0; HALF_ROW].into_boxed_slice()).unwrap() } // Metadata/lineage tests only: these synthetic sessions do not certify a // real target producer, CUDA completion or numerical model equivalence. @@ -101,11 +94,18 @@ fn first_seed_coupled_refusal_never_remints_or_mutates() { 4 => original.binding = BindingIdentity::test_identity(), 5 => seed.next_position = 2, 6 => { - let unrelated = pending(&MtpSession { - binding: draft.binding.clone(), epoch: Rc::clone(&draft.epoch), - next_position: 0, kv: original.kv.clone(), residual: None, - target_owner: None, retained: Rc::clone(&draft.retained), - }, &frame); + let unrelated = pending( + &MtpSession { + binding: draft.binding.clone(), + epoch: Rc::clone(&draft.epoch), + next_position: 0, + kv: original.kv.clone(), + residual: None, + target_owner: None, + retained: Rc::clone(&draft.retained), + }, + &frame, + ); draft.kv = unrelated; } 7 => { @@ -157,7 +157,9 @@ fn first_seed_actual_capacity_and_existing_five_checkpoint_cap() { assert!(matches!(draft.checkpoint_first_seed(actual - 1), Err(Error::InputAllocation))); assert_eq!(draft.retained.get(), 0); let mut retained = Vec::new(); - for _ in 0..5 { retained.push(draft.checkpoint_first_seed(actual).unwrap()); } + for _ in 0..5 { + retained.push(draft.checkpoint_first_seed(actual).unwrap()); + } assert!(matches!(draft.checkpoint_first_seed(actual), Err(Error::InputAllocation))); assert_eq!(draft.retained.get(), 5); drop(retained); @@ -170,9 +172,7 @@ fn ring_requires_exact_parent_epoch_and_branch() { let (mut draft, frame) = draft(); let first = pending(&draft, &frame); assert!(first.ring_same(&first.clone(), &frame).unwrap()); - draft - .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) - .unwrap(); + draft.commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()).unwrap(); let mut next_frame = frame.clone(); next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); let next = pending(&draft, &next_frame); @@ -184,30 +184,20 @@ fn ring_requires_exact_parent_epoch_and_branch() { unrelated.owner = Rc::new(Cell::new(0)); assert!(!next.ring_append(&unrelated, &next_frame).unwrap()); draft.epoch.set(1); - assert_eq!( - next.ring_validate(&next_frame), - Err(Error::IdentityMismatch) - ); + assert_eq!(next.ring_validate(&next_frame), Err(Error::IdentityMismatch)); next_frame.generation = 1; - assert_eq!( - next.ring_validate(&next_frame), - Err(Error::IdentityMismatch) - ); + assert_eq!(next.ring_validate(&next_frame), Err(Error::IdentityMismatch)); } #[test] fn ring_restore_requires_reload_for_old_numerical_mirror() { let (mut draft, frame) = draft(); let first = pending(&draft, &frame); - draft - .commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()) - .unwrap(); + draft.commit(&frame, first.clone(), vec![0.0; 10240].into_boxed_slice()).unwrap(); let checkpoint = draft.checkpoint().unwrap(); let mut next_frame = frame.clone(); next_frame.position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(); let second = pending(&draft, &next_frame); - draft - .commit(&next_frame, second, vec![0.0; 10240].into_boxed_slice()) - .unwrap(); + draft.commit(&next_frame, second, vec![0.0; 10240].into_boxed_slice()).unwrap(); draft.restore(&checkpoint).unwrap(); next_frame.generation = draft.epoch.get(); let restored = pending(&draft, &next_frame); @@ -234,30 +224,19 @@ fn mtp_new_pending_token_epoch_and_residual_refuse_atomically() { let stale = pending(&draft, &frame); let mut wrong = frame.clone(); wrong.token = TokenId::new(2, Dimension::new(248320).unwrap()).unwrap(); - assert_eq!( - draft.commit(&wrong, stale.clone(), vec![0.0; 10240].into_boxed_slice()), - Err(Error::IdentityMismatch) - ); + assert_eq!(draft.commit(&wrong, stale.clone(), vec![0.0; 10240].into_boxed_slice()), Err(Error::IdentityMismatch)); assert_eq!(draft.next_position, 0); let initial = draft.checkpoint().unwrap(); draft.restore(&initial).unwrap(); wrong.generation = 1; - assert_eq!( - draft.commit(&wrong, stale, vec![0.0; 10240].into_boxed_slice()), - Err(Error::IdentityMismatch) - ); + assert_eq!(draft.commit(&wrong, stale, vec![0.0; 10240].into_boxed_slice()), Err(Error::IdentityMismatch)); let fresh = pending(&draft, &wrong); let mut invalid = vec![0.0; 10240]; invalid[10239] = f32::NAN; - assert_eq!( - draft.commit(&wrong, fresh.clone(), invalid.into_boxed_slice()), - Err(Error::NonFinite) - ); + assert_eq!(draft.commit(&wrong, fresh.clone(), invalid.into_boxed_slice()), Err(Error::NonFinite)); assert_eq!(draft.next_position, 0); assert!(draft.residual.is_none()); - draft - .commit(&wrong, fresh, vec![0.0; 10240].into_boxed_slice()) - .unwrap(); + draft.commit(&wrong, fresh, vec![0.0; 10240].into_boxed_slice()).unwrap(); assert_eq!(draft.next_position, 1); assert_eq!(draft.residual.as_ref().unwrap().len(), 10240); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk.rs index 0244b04b..a5014c77 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk.rs @@ -50,28 +50,16 @@ mod tests { #[test] fn exact_transaction_row_bounds_preserve_native64_and_admit_outer256() { assert_eq!(checked_chunk_end(170000, 64, 64), Ok(170064)); - assert_eq!( - checked_chunk_end(170000, 65, 64), - Err(Error::IdentityMismatch) - ); + assert_eq!(checked_chunk_end(170000, 65, 64), Err(Error::IdentityMismatch)); for rows in [64, 65, 256] { - assert_eq!( - checked_chunk_end(190000, rows, 256), - Ok(190000 + rows as u64) - ); + assert_eq!(checked_chunk_end(190000, rows, 256), Ok(190000 + rows as u64)); } - assert_eq!( - checked_chunk_end(190000, 257, 256), - Err(Error::IdentityMismatch) - ); + assert_eq!(checked_chunk_end(190000, 257, 256), Err(Error::IdentityMismatch)); assert_eq!(checked_chunk_end(0, 0, 64), Err(Error::IdentityMismatch)); assert_eq!(checked_chunk_end(0, 65, 65), Err(Error::IdentityMismatch)); assert_eq!(checked_chunk_end(u64::MAX, 1, 64), Err(Error::Overflow)); assert_eq!(checked_chunk_end(262080, 64, 64), Ok(262144)); - assert_eq!( - checked_chunk_end(262081, 64, 64), - Err(Error::InvalidPosition) - ); + assert_eq!(checked_chunk_end(262081, 64, 64), Err(Error::InvalidPosition)); } #[test] @@ -123,25 +111,16 @@ mod tests { let pending = stage .candidate .kv - .append( - &frame, - vec![0; 1024].into_boxed_slice(), - vec![0; 1024].into_boxed_slice(), - ) + .append(&frame, vec![0; 1024].into_boxed_slice(), vec![0; 1024].into_boxed_slice()) .unwrap(); let mut invalid = vec![0.0; 10240]; invalid[10239] = f32::NAN; assert_eq!( - stage - .candidate - .commit(&frame, pending.clone(), invalid.into_boxed_slice()), + stage.candidate.commit(&frame, pending.clone(), invalid.into_boxed_slice()), Err(Error::NonFinite) ); assert_eq!(stage.candidate.next_position, 0); - stage - .candidate - .commit(&frame, pending, vec![0.0; 10240].into_boxed_slice()) - .unwrap(); + stage.candidate.commit(&frame, pending, vec![0.0; 10240].into_boxed_slice()).unwrap(); assert_eq!(stage.candidate.next_position, 1); assert_eq!(stage.original.next_position, 0); assert!(stage.original.residual.is_none()); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/checked_chunk_end_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/checked_chunk_end_fn.rs index 2b33a60b..1e0767ff 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/checked_chunk_end_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/checked_chunk_end_fn.rs @@ -7,9 +7,7 @@ pub(super) fn checked_chunk_end(start: u64, rows: usize, limit: usize) -> Result if !matches!(limit, 64 | 256) || rows == 0 || rows > limit { return Err(Error::IdentityMismatch); } - let end = start - .checked_add(u64::try_from(rows).map_err(|_| Error::Overflow)?) - .ok_or(Error::Overflow)?; + let end = start.checked_add(u64::try_from(rows).map_err(|_| Error::Overflow)?).ok_or(Error::Overflow)?; if end > crate::qwen_forward::contract::serving_cells() { return Err(Error::InvalidPosition); } @@ -85,13 +83,8 @@ impl MtpSession { || !self.binding.matches(&self.kv.binding) || !Rc::ptr_eq(&self.epoch, &self.kv.owner) || self.kv.cells.len() - != usize::try_from(self.next_position) - .map_err(|_| Error::Overflow)? - .min(super::super::WINDOW) - || self - .target_owner - .as_ref() - .is_some_and(|old| !old.same_branch(&anchor)) + != usize::try_from(self.next_position).map_err(|_| Error::Overflow)?.min(super::super::WINDOW) + || self.target_owner.as_ref().is_some_and(|old| !old.same_branch(&anchor)) { return Err(Error::IdentityMismatch); } @@ -174,37 +167,23 @@ impl MtpChunkStage<'_> { || self.candidate.next_position != end || self.candidate.kv.next_position != end || self.candidate.kv.cells.len() - != usize::try_from(end) - .map_err(|_| Error::Overflow)? - .min(super::super::WINDOW) + != usize::try_from(end).map_err(|_| Error::Overflow)?.min(super::super::WINDOW) || !Rc::ptr_eq(&self.candidate.kv.owner, &self.candidate.epoch) || !self.candidate.kv.binding.matches(&self.original.binding) { return Err(Error::IdentityMismatch); } if end > self.start_position { - let frame = self - .candidate - .kv - .produced - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let frame = self.candidate.kv.produced.as_ref().ok_or(Error::IdentityMismatch)?; frame.validate(binding, target)?; if frame.position.get().checked_add(1) != Some(end) || !frame.origin.same_prefix(&self.anchor) - || self - .candidate - .target_owner - .as_ref() - .is_none_or(|owner| !owner.same_prefix(&self.anchor)) + || self.candidate.target_owner.as_ref().is_none_or(|owner| !owner.same_prefix(&self.anchor)) { return Err(Error::IdentityMismatch); } super::super::super::validate_values( - self.candidate - .residual - .as_ref() - .ok_or(Error::IdentityMismatch)?, + self.candidate.residual.as_ref().ok_or(Error::IdentityMismatch)?, 10240, )?; } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/impl_mtpsession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/impl_mtpsession.rs index 49166bfb..01234f1b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/impl_mtpsession.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_chunk/impl_mtpsession.rs @@ -13,27 +13,16 @@ impl MtpSession { residual: self.residual.clone(), } } - pub(in crate::qwen_forward) fn test_chunk_eq( - &self, - expected: &MtpChunkNumericSnapshot, - ) -> bool { + pub(in crate::qwen_forward) fn test_chunk_eq(&self, expected: &MtpChunkNumericSnapshot) -> bool { self.binding.matches(&expected.binding) && self.next_position == expected.next_position && self.kv.next_position == expected.next_position && self.kv.cells.len() == expected.cells.len() - && self - .kv - .cells - .iter() - .zip(expected.cells.iter()) - .all(|(a, b)| a.key == b.key && a.value == b.value) + && self.kv.cells.iter().zip(expected.cells.iter()).all(|(a, b)| a.key == b.key && a.value == b.value) && match (&self.residual, &expected.residual) { (None, None) => true, (Some(a), Some(b)) => { - a.len() == b.len() - && a.iter() - .zip(b.iter()) - .all(|(x, y)| x.to_bits() == y.to_bits()) + a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| x.to_bits() == y.to_bits()) } _ => false, } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming.rs index c140efa2..df1b0d9b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_state_warming.rs @@ -43,17 +43,11 @@ impl MtpKvPrefill { return Err(Error::InvalidToken); } } - binding - .mtp_weights() - .map_err(mtp::binding_error)? - .validate_binding(binding) - .map_err(mtp::binding_error)?; + binding.mtp_weights().map_err(mtp::binding_error)?.validate_binding(binding).map_err(mtp::binding_error)?; let anchor = target.target_origin()?; anchor.validate(target)?; let mut cells = VecDeque::new(); - cells - .try_reserve_exact(WINDOW) - .map_err(|_| Error::InputAllocation)?; + cells.try_reserve_exact(WINDOW).map_err(|_| Error::InputAllocation)?; let mut retained_tokens = mtp::reserve(tokens.len())?; retained_tokens.extend_from_slice(tokens); let owner = Self { @@ -73,12 +67,7 @@ impl MtpKvPrefill { owner.validate_original(binding, original, target)?; Ok(owner) } - fn validate_original( - &self, - binding: &ModelBinding, - original: &MtpSession, - target: &QwenSession<'_>, - ) -> Result<()> { + fn validate_original(&self, binding: &ModelBinding, original: &MtpSession, target: &QwenSession<'_>) -> Result<()> { let origin = target.target_origin()?; origin.validate(target)?; if self.complete @@ -111,16 +100,11 @@ impl MtpKvPrefill { source: &crate::qwen_forward::executor::TargetStepProduct, ) -> Result<()> { let (token, position, _, origin) = source.mtp_source(binding, target)?; - if position.get().checked_add(1) != Some(self.tokens.len() as u64) - || self.tokens.last().copied() != Some(token) + if position.get().checked_add(1) != Some(self.tokens.len() as u64) || self.tokens.last().copied() != Some(token) { return Err(Error::IdentityMismatch); } - let expected = self - .tokens - .len() - .checked_sub(1) - .ok_or(Error::InvalidDimension)?; + let expected = self.tokens.len().checked_sub(1).ok_or(Error::InvalidDimension)?; if !self.complete || self.covered < expected || !self.binding.matches(&binding.identity()) @@ -131,32 +115,19 @@ impl MtpKvPrefill { || original.next_position != expected as u64 || original.kv.next_position != expected as u64 || original.kv.cells.len() != expected.min(WINDOW) - || self - .completed_cells - .as_ref() - .is_none_or(|cells| !Rc::ptr_eq(cells, &original.kv.cells)) + || self.completed_cells.as_ref().is_none_or(|cells| !Rc::ptr_eq(cells, &original.kv.cells)) { return Err(Error::IdentityMismatch); } - let frame = original - .kv - .produced - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let frame = original.kv.produced.as_ref().ok_or(Error::IdentityMismatch)?; original.kv.ring_validate(frame)?; if frame.position.get() + 1 != expected as u64 || !frame.origin.same_branch(&origin) - || original - .target_owner - .as_ref() - .is_none_or(|owner| !owner.same_prefix(&frame.origin)) + || original.target_owner.as_ref().is_none_or(|owner| !owner.same_prefix(&frame.origin)) { return Err(Error::IdentityMismatch); } - mtp::validate_values( - original.residual.as_ref().ok_or(Error::IdentityMismatch)?, - 10240, - ) + mtp::validate_values(original.residual.as_ref().ok_or(Error::IdentityMismatch)?, 10240) } pub(in crate::qwen_forward) fn stage_chunk<'owner, 'binding>( &'owner mut self, @@ -178,9 +149,7 @@ impl MtpKvPrefill { return Err(Error::IdentityMismatch); } let mut cells = VecDeque::new(); - cells - .try_reserve_exact(WINDOW) - .map_err(|_| Error::InputAllocation)?; + cells.try_reserve_exact(WINDOW).map_err(|_| Error::InputAllocation)?; cells.extend(self.cells.iter().cloned()); let mut last = self.last.clone(); let mut full = None; @@ -215,10 +184,7 @@ impl MtpKvPrefill { // reaches every cell required by the ordinary prior window. let expected = global.min(WINDOW); if cells.len() != expected - || (global > 0 - && last - .as_ref() - .is_none_or(|f| f.position.get() + 1 != global as u64)) + || (global > 0 && last.as_ref().is_none_or(|f| f.position.get() + 1 != global as u64)) { return Err(Error::IdentityMismatch); } @@ -241,25 +207,20 @@ impl MtpKvPrefill { target_owner: last.as_ref().map(|f| f.origin.clone()), retained: Rc::clone(&original.retained), }; - txn.with_mtp_row( - row, - |target, actual_position, actual_next, streams, anchor| { - if actual_position != frame.position - || actual_next != frame.token - || !anchor.same_prefix(&frame.origin) - { - return Err(Error::IdentityMismatch); - } - let input = - MtpInput::compute(binding, target, frame.clone(), streams, cache)?; - mtp::warm_step(binding, target, &mut candidate, input, cache) - }, - )?; + txn.with_mtp_row(row, |target, actual_position, actual_next, streams, anchor| { + if actual_position != frame.position + || actual_next != frame.token + || !anchor.same_prefix(&frame.origin) + { + return Err(Error::IdentityMismatch); + } + let input = MtpInput::compute(binding, target, frame.clone(), streams, cache)?; + mtp::warm_step(binding, target, &mut candidate, input, cache) + })?; full = Some(candidate); } else if global >= self.first_needed { let product = mtp::produce_chunk_kv_only(binding, txn, row, &frame, cache)?; - let (produced, key, value) = - product.consume(binding, txn.original_session()?, &frame)?; + let (produced, key, value) = product.consume(binding, txn.original_session()?, &frame)?; super::validate_half(&key)?; super::validate_half(&value)?; if cells.len() == WINDOW { @@ -273,16 +234,7 @@ impl MtpKvPrefill { return Err(Error::Unsupported(Stage::Executor)); } } - let ready = ReadyMtpKvPrefill { - owner: self, - original, - binding, - start, - end, - cells, - last, - full, - }; + let ready = ReadyMtpKvPrefill { owner: self, original, binding, start, end, cells, last, full }; ready.validate(txn)?; Ok(ready) } @@ -302,8 +254,7 @@ pub(in crate::qwen_forward) struct ReadyMtpKvPrefill<'owner, 'binding> { } impl ChunkDraftPublication for ReadyMtpKvPrefill<'_, '_> { fn validate(&self, txn: &QwenChunkTxn<'_, '_>) -> Result<()> { - self.owner - .validate_original(self.binding, self.original, txn.original_session()?)?; + self.owner.validate_original(self.binding, self.original, txn.original_session()?)?; if self.start != self.owner.covered || txn.start_position() != self.start as u64 || txn.end_position() != self.end as u64 @@ -335,28 +286,16 @@ impl ChunkDraftPublication for ReadyMtpKvPrefill<'_, '_> { { return Err(Error::IdentityMismatch); } - let frame = candidate - .kv - .produced - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let frame = candidate.kv.produced.as_ref().ok_or(Error::IdentityMismatch)?; frame.validate(self.binding, txn.original_session()?)?; candidate.kv.ring_validate(frame)?; if frame.position.get() + 1 != expected - || !frame - .origin - .same_prefix(&txn.original_session()?.target_origin()?) - || candidate - .target_owner - .as_ref() - .is_none_or(|o| !o.same_prefix(&frame.origin)) + || !frame.origin.same_prefix(&txn.original_session()?.target_origin()?) + || candidate.target_owner.as_ref().is_none_or(|o| !o.same_prefix(&frame.origin)) { return Err(Error::IdentityMismatch); } - mtp::validate_values( - candidate.residual.as_ref().ok_or(Error::IdentityMismatch)?, - 10240, - )?; + mtp::validate_values(candidate.residual.as_ref().ok_or(Error::IdentityMismatch)?, 10240)?; } _ => return Err(Error::IdentityMismatch), } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs index 3c5f1842..cb408150 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/oracle_capture.rs @@ -32,20 +32,10 @@ fn error(_: impl std::fmt::Debug) -> Error { Error::InputAllocation } fn with(f: impl FnOnce(&mut Capture) -> Result) -> Result { - ACTIVE.with(|cell| { - f(cell - .try_borrow_mut() - .map_err(error)? - .as_mut() - .ok_or(Error::IdentityMismatch)?) - }) + ACTIVE.with(|cell| f(cell.try_borrow_mut().map_err(error)?.as_mut().ok_or(Error::IdentityMismatch)?)) } fn write(c: &mut Capture, name: &str, bytes: &[u8]) -> Result<()> { - if bytes.len() > OUTPUT_CAP - || c.emitted - .checked_add(bytes.len()) - .is_none_or(|x| x > OUTPUT_CAP) - { + if bytes.len() > OUTPUT_CAP || c.emitted.checked_add(bytes.len()).is_none_or(|x| x > OUTPUT_CAP) { return Err(Error::InvalidDimension); } let mut options = OpenOptions::new(); @@ -73,13 +63,7 @@ pub(super) fn initialize(directory: PathBuf) -> Result<()> { if active.is_some() { return Err(Error::IdentityMismatch); } - *active = Some(Capture { - directory, - position: 0, - layer: -1, - emitted: 0, - descriptors: BTreeMap::new(), - }); + *active = Some(Capture { directory, position: 0, layer: -1, emitted: 0, descriptors: BTreeMap::new() }); Ok(()) }) } @@ -100,9 +84,7 @@ pub(super) fn enabled() -> bool { ACTIVE.with(|cell| cell.borrow().is_some()) } fn f32_bytes(values: &[f32]) -> Result> { - if values.len().checked_mul(4).is_none_or(|n| n > OUTPUT_CAP) - || values.iter().any(|v| !v.is_finite()) - { + if values.len().checked_mul(4).is_none_or(|n| n > OUTPUT_CAP) || values.iter().any(|v| !v.is_finite()) { return Err(Error::NonFinite); } let mut bytes = Vec::new(); @@ -118,17 +100,10 @@ pub(super) fn stage_f32(layer: i32, role: &'static str, values: &[f32]) -> Resul return Err(Error::InvalidDimension); } with(|c| { - if !(-1..48).contains(&layer) - || c.descriptors.len() >= 1024 - || c.descriptors.contains_key(&(layer, role)) - { + if !(-1..48).contains(&layer) || c.descriptors.len() >= 1024 || c.descriptors.contains_key(&(layer, role)) { return Err(Error::IdentityMismatch); } - write( - c, - &format!("p{}.layer{layer}.{role}.f32", c.position), - &bytes, - )?; + write(c, &format!("p{}.layer{layer}.{role}.f32", c.position), &bytes)?; c.descriptors.insert((layer, role), (1, bytes.len())); Ok(()) }) @@ -143,11 +118,7 @@ pub(super) fn stage_i32(layer: i32, role: &'static str, values: &[i32]) -> Resul if c.descriptors.contains_key(&(layer, role)) { return Err(Error::IdentityMismatch); } - write( - c, - &format!("p{}.layer{layer}.{role}.i32", c.position), - &bytes, - )?; + write(c, &format!("p{}.layer{layer}.{role}.i32", c.position), &bytes)?; c.descriptors.insert((layer, role), (2, bytes.len())); Ok(()) }) @@ -259,13 +230,7 @@ pub(crate) fn check_on_loaded( finish_position()?; } output.test_reset_replay_record(false)?; - with(|c| { - write( - c, - "CAPTURE-COMPLETE.txt", - b"candidate_capture_complete=2\ncomparison_performed=false\n", - ) - })?; + with(|c| write(c, "CAPTURE-COMPLETE.txt", b"candidate_capture_complete=2\ncomparison_performed=false\n"))?; ACTIVE.with(|cell| { cell.borrow_mut().take(); }); @@ -298,16 +263,10 @@ fn pinned_candidate_full_forward_capture_two_public_tokens() { .expect("shard1"); let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact"); let binding = if let Some(fd) = std::env::var_os("LELEKA_STRA169_KAR_FD") { - let fd = fd - .to_str() - .expect("fd utf8") - .parse::() - .expect("operator fd"); - let source = - crate::backend::InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) - .expect("sealed source"); - ModelBinding::from_artifact_with_inherited_kar_ple(artifact, &source) - .expect("sealed pinned KAR") + let fd = fd.to_str().expect("fd utf8").parse::().expect("operator fd"); + let source = crate::backend::InheritedKarArchive::open(fd, path("LELEKA_STRA169_KAR_PROVENANCE")) + .expect("sealed source"); + ModelBinding::from_artifact_with_inherited_kar_ple(artifact, &source).expect("sealed pinned KAR") } else { ModelBinding::from_artifact_with_pinned_kar_ple( artifact, @@ -318,17 +277,10 @@ fn pinned_candidate_full_forward_capture_two_public_tokens() { }; let driver = Driver::load().expect("CUDA driver"); let device = driver.device(0).expect("device0"); - let context = Rc::new( - device - .create_context(28 * 1024 * 1024 * 1024) - .expect("Context"), - ); + let context = Rc::new(device.create_context(28 * 1024 * 1024 * 1024).expect("Context")); let output = OutputStage::load(&binding, context.as_ref()).expect("head"); - let mut cache = KarPleCache::new( - context.as_ref(), - binding.kar_ple_binding().expect("KAR provider"), - ) - .expect("KAR cache"); + let mut cache = + KarPleCache::new(context.as_ref(), binding.kar_ple_binding().expect("KAR provider")).expect("KAR cache"); let mut moe_cache = MoeWeightCache::new(&binding, context.as_ref()).expect("MoE cache"); let dense_cache = DenseWeightCache::new(&binding, context.as_ref()).expect("dense cache"); let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context)); @@ -348,13 +300,8 @@ fn pinned_candidate_full_forward_capture_two_public_tokens() { drop(output); let synchronized = context.synchronize(); let allocated = context.allocated_bytes(); - let closed = Rc::try_unwrap(context) - .unwrap_or_else(|_| panic!("borrowed Context")) - .close(); + let closed = Rc::try_unwrap(context).unwrap_or_else(|_| panic!("borrowed Context")).close(); assert!(captured.is_ok(), "capture failed"); - assert!( - moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok() && closed.is_ok(), - "cleanup failed" - ); + assert!(moe_closed.is_ok() && dense_closed.is_ok() && synchronized.is_ok() && closed.is_ok(), "cleanup failed"); assert_eq!(allocated, 0, "live allocations remain"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_cache_startup.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_cache_startup.rs index 6c2747e5..513010c8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_cache_startup.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_cache_startup.rs @@ -1,190 +1,308 @@ //! Literal generate.cpp expert-cache sizing/retry and STRP profile reader. //! Counts are planning metadata; only the returned physical cache owns slots. -use super::contract::{Error,Result}; -use crate::model_binding::qwen4exp_input::{ModelBinding,MoeMatrixRole}; -use leleka_cuda_driver::{Context,OriginalExpertCache}; -use std::{fs::File,io::Read,path::Path}; +use super::contract::{Error, Result}; +use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use leleka_cuda_driver::{Context, OriginalExpertCache}; +use std::{fs::File, io::Read, path::Path}; pub(crate) struct OriginalRankedExperts { - pairs:Vec<(u16,u16)>,requested_slots:u32, + pairs: Vec<(u16, u16)>, + requested_slots: u32, } impl OriginalRankedExperts { /// Original ignores the version and trailing bytes, and preserves order /// and duplicate pairs. A different topology is refused before any fill. - pub(crate) fn read(path:&Path,binding:&ModelBinding)->Result{ - let mut file=File::open(path).map_err(|_|Error::InputRead)?; - let mut header=[0u8;24];file.read_exact(&mut header).map_err(|_|Error::InputRead)?; - if &header[..4]!=b"STRP"{return Err(Error::IdentityMismatch);} - let word=|at|u32::from_le_bytes(header[at..at+4].try_into().unwrap()); - let (layers,experts,want,count)=(word(8),word(12),word(16),word(20)); - if layers!=binding.layer_count()||experts!=512||count>want{return Err(Error::InvalidDimension);} - let mut pairs=Vec::new();pairs.try_reserve_exact(count as usize).map_err(|_|Error::InputAllocation)?; - for _ in 0..count{ - let mut raw=[0u8;4];file.read_exact(&mut raw).map_err(|_|Error::InputRead)?; - let pair=(u16::from_le_bytes([raw[0],raw[1]]),u16::from_le_bytes([raw[2],raw[3]])); - if u32::from(pair.0)>=layers||u32::from(pair.1)>=experts{return Err(Error::InvalidDimension);} + pub(crate) fn read(path: &Path, binding: &ModelBinding) -> Result { + let mut file = File::open(path).map_err(|_| Error::InputRead)?; + let mut header = [0u8; 24]; + file.read_exact(&mut header).map_err(|_| Error::InputRead)?; + if &header[..4] != b"STRP" { + return Err(Error::IdentityMismatch); + } + let word = |at| u32::from_le_bytes(header[at..at + 4].try_into().unwrap()); + let (layers, experts, want, count) = (word(8), word(12), word(16), word(20)); + if layers != binding.layer_count() || experts != 512 || count > want { + return Err(Error::InvalidDimension); + } + let mut pairs = Vec::new(); + pairs.try_reserve_exact(count as usize).map_err(|_| Error::InputAllocation)?; + for _ in 0..count { + let mut raw = [0u8; 4]; + file.read_exact(&mut raw).map_err(|_| Error::InputRead)?; + let pair = (u16::from_le_bytes([raw[0], raw[1]]), u16::from_le_bytes([raw[2], raw[3]])); + if u32::from(pair.0) >= layers || u32::from(pair.1) >= experts { + return Err(Error::InvalidDimension); + } pairs.push(pair); } - Ok(Self{pairs,requested_slots:want}) + Ok(Self { pairs, requested_slots: want }) + } + pub(crate) fn pairs(&self) -> &[(u16, u16)] { + &self.pairs + } + pub(crate) fn requested_slots(&self) -> u32 { + self.requested_slots + } + pub(crate) fn is_empty(&self) -> bool { + self.pairs.is_empty() } - pub(crate) fn pairs(&self)->&[(u16,u16)]{&self.pairs} - pub(crate) fn requested_slots(&self)->u32{self.requested_slots} - pub(crate) fn is_empty(&self)->bool{self.pairs.is_empty()} } -#[derive(Clone,Copy)] +#[derive(Clone, Copy)] pub(crate) struct OriginalCacheOptions { /// -1=auto, 0=off, positive=explicit slots, as in Original. - pub slots:i32,pub reserve_mib:usize,pub prefill_capacity:usize, - pub prefill_borrow:bool,pub per_layer:bool, + pub slots: i32, + pub reserve_mib: usize, + pub prefill_capacity: usize, + pub prefill_borrow: bool, + pub per_layer: bool, +} +struct Geometry { + layer_bytes: [usize; 48], + max_blob: usize, } -struct Geometry{layer_bytes:[usize;48],max_blob:usize} impl Geometry { - fn from_binding(binding:&ModelBinding)->Result{ - if binding.layer_count()!=48{return Err(Error::InvalidDimension);} - let mut layer_bytes=[0usize;48]; - for (layer,total) in layer_bytes.iter_mut().enumerate(){ - for role in [MoeMatrixRole::Gate,MoeMatrixRole::Up,MoeMatrixRole::Down]{ - let d=binding.moe_preload_descriptor(layer as u32,0,role).map_err(|_|Error::IdentityMismatch)?; - if d.layer!=layer as u32||d.expert!=Some(0){return Err(Error::IdentityMismatch);} - *total=total.checked_add(d.bytes).ok_or(Error::Overflow)?; + fn from_binding(binding: &ModelBinding) -> Result { + if binding.layer_count() != 48 { + return Err(Error::InvalidDimension); + } + let mut layer_bytes = [0usize; 48]; + for (layer, total) in layer_bytes.iter_mut().enumerate() { + for role in [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down] { + let d = binding.moe_preload_descriptor(layer as u32, 0, role).map_err(|_| Error::IdentityMismatch)?; + if d.layer != layer as u32 || d.expert != Some(0) { + return Err(Error::IdentityMismatch); + } + *total = total.checked_add(d.bytes).ok_or(Error::Overflow)?; } } - let max_blob=*layer_bytes.iter().max().ok_or(Error::InvalidDimension)?; - if max_blob==0{return Err(Error::InvalidDimension);} - Ok(Self{layer_bytes,max_blob}) + let max_blob = *layer_bytes.iter().max().ok_or(Error::InvalidDimension)?; + if max_blob == 0 { + return Err(Error::InvalidDimension); + } + Ok(Self { layer_bytes, max_blob }) } } /// `layers`: the per-layer plan (`--expert-cache-per-layer` on a native pack, generate.cpp ~6333): `quota` slots of EACH layer's own blob /// size, in layer order (layer l owns slots l * quota .. (l + 1) * quota, the table's ranges), instead of `slots` slots of the largest blob. /// Per-arm override of `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED` for paired passes in one process (-1: none, 0: uniform slots, 1: each layer's own blob size). -static SIZED_OVERRIDE:std::sync::atomic::AtomicI8=std::sync::atomic::AtomicI8::new(-1); -pub(crate) fn set_sized_override(value:i8){SIZED_OVERRIDE.store(value,std::sync::atomic::Ordering::Relaxed);} -fn sized_per_layer()->bool{ - match SIZED_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed){ - 0=>false, - 1=>true, - _=>crate::settings::process().memory.per_layer_sized, +static SIZED_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1); +pub(crate) fn set_sized_override(value: i8) { + SIZED_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed); +} +fn sized_per_layer() -> bool { + match SIZED_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => false, + 1 => true, + _ => crate::settings::process().memory.per_layer_sized, } } -struct Plan{slots:usize,sizes:Vec,blob:usize,layers:Option<(usize,[usize;48])>} +struct Plan { + slots: usize, + sizes: Vec, + blob: usize, + layers: Option<(usize, [usize; 48])>, +} impl Plan { - fn bytes(&self)->Result{ - if self.sizes.is_empty(){self.slots.checked_mul(self.blob).ok_or(Error::Overflow)} - else{self.sizes.iter().try_fold(0usize,|n,&s|n.checked_add(align(s)?).ok_or(Error::Overflow))} + fn bytes(&self) -> Result { + if self.sizes.is_empty() { + self.slots.checked_mul(self.blob).ok_or(Error::Overflow) + } else { + self.sizes.iter().try_fold(0usize, |n, &s| n.checked_add(align(s)?).ok_or(Error::Overflow)) + } } /// The per-layer list for `quota` slots per layer. - fn per_layer_sizes(quota:usize,layer_bytes:&[usize;48])->Result>{ - let mut sizes=Vec::new(); - sizes.try_reserve_exact(quota.checked_mul(48).ok_or(Error::Overflow)?).map_err(|_|Error::InputAllocation)?; - for &b in layer_bytes{for _ in 0..quota{sizes.push(b);}} + fn per_layer_sizes(quota: usize, layer_bytes: &[usize; 48]) -> Result> { + let mut sizes = Vec::new(); + sizes.try_reserve_exact(quota.checked_mul(48).ok_or(Error::Overflow)?).map_err(|_| Error::InputAllocation)?; + for &b in layer_bytes { + for _ in 0..quota { + sizes.push(b); + } + } Ok(sizes) } - fn shrink_to(&mut self,keep:usize)->Result{ - if keep==0{self.slots=0;self.sizes.clear();return Ok(false);} - if let Some((quota,layer_bytes))=&mut self.layers{ + fn shrink_to(&mut self, keep: usize) -> Result { + if keep == 0 { + self.slots = 0; + self.sizes.clear(); + return Ok(false); + } + if let Some((quota, layer_bytes)) = &mut self.layers { // the same quota of every layer that fits `keep` (a truncated list would shift the layers' slot ranges) - let sum=layer_bytes.iter().try_fold(0usize,|n,&b|n.checked_add(align(b)?).ok_or(Error::Overflow))?; - *quota=(keep/sum).min(512); - if *quota==0{self.slots=0;self.sizes.clear();return Ok(false);} - self.sizes=Self::per_layer_sizes(*quota,layer_bytes)?;self.slots=self.sizes.len(); + let sum = layer_bytes.iter().try_fold(0usize, |n, &b| n.checked_add(align(b)?).ok_or(Error::Overflow))?; + *quota = (keep / sum).min(512); + if *quota == 0 { + self.slots = 0; + self.sizes.clear(); + return Ok(false); + } + self.sizes = Self::per_layer_sizes(*quota, layer_bytes)?; + self.slots = self.sizes.len(); return Ok(true); } - if self.sizes.is_empty(){self.slots=keep/self.blob;} - else{ - let (mut used,mut count)=(0usize,0usize); - while countkeep{break;}used=next;count+=1;} - self.sizes.truncate(count);self.slots=count; + if self.sizes.is_empty() { + self.slots = keep / self.blob; + } else { + let (mut used, mut count) = (0usize, 0usize); + while count < self.sizes.len() { + let next = used.checked_add(align(self.sizes[count])?).ok_or(Error::Overflow)?; + if next > keep { + break; + } + used = next; + count += 1; + } + self.sizes.truncate(count); + self.slots = count; } - Ok(self.slots>0) + Ok(self.slots > 0) + } +} +fn align(bytes: usize) -> Result { + Ok(bytes.checked_add(255).ok_or(Error::Overflow)? & !255) +} +fn driver(error: leleka_cuda_driver::Error) -> Error { + match error { + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + _ => Error::CudaExecution, } } -fn align(bytes:usize)->Result{Ok(bytes.checked_add(255).ok_or(Error::Overflow)?&!255)} -fn driver(error:leleka_cuda_driver::Error)->Error{match error{ - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - _=>Error::CudaExecution, -}} /// Bytes the cache may be sized against: the card's free VRAM, but never more than the Context budget still allows. The Context charges /// every allocation (`allocated_bytes`) against `budget_bytes` and refuses past it with `BudgetExceeded`; the owners that allocate after /// the cache (the QSA/prefill buffers of the first chunk, the per-request verifier) need the reserve under the BUDGET as well as on the card. /// Sized from the card alone, a build that saved physical memory without saving accounted bytes (the dense slabs: the driver's rounding is /// not charged) grew the cache to 305 MiB under a 30 GiB budget and the first 8192-token chunk died in layer 27 with `BudgetExceeded`. -pub(crate) fn usable_room(card_free:usize,budget:usize,allocated:usize)->usize{card_free.min(budget.saturating_sub(allocated))} +pub(crate) fn usable_room(card_free: usize, budget: usize, allocated: usize) -> usize { + card_free.min(budget.saturating_sub(allocated)) +} /// Real card readings and original sized-prefix / 3/4 retry policy. The caller /// supplies the actual not-yet-bound MTP head charge, never a guessed reserve. -pub(crate) fn open<'ctx>(binding:&ModelBinding,context:&'ctx Context<'ctx>,options:OriginalCacheOptions, - profile:Option<&OriginalRankedExperts>,pending_mtp_bind_bytes:usize, -)->Result>>{ - if options.slots< -1{return Err(Error::InvalidDimension);} - if options.slots==0{return Ok(None);} - let geometry=Geometry::from_binding(binding)?; - let auto=options.slots<0; - let reserve=options.reserve_mib.checked_mul(1<<20).ok_or(Error::Overflow)?; - let free=usable_room(context.memory_info().map_err(driver)?.0,context.budget_bytes(),context.allocated_bytes()); - let mut slots=if auto{ - let prefill_mib=if options.prefill_capacity>0&&!options.prefill_borrow{ - 160usize.checked_add(options.prefill_capacity.checked_mul(680).ok_or(Error::Overflow)?/1024).ok_or(Error::Overflow)? - }else{0}; - let reserved=reserve.checked_add(prefill_mib.checked_mul(1<<20).ok_or(Error::Overflow)?) - .and_then(|n|n.checked_add(pending_mtp_bind_bytes)).ok_or(Error::Overflow)?; - free.saturating_sub(reserved)/geometry.max_blob - }else{options.slots as usize}; - if auto{if let Some(profile)=profile.filter(|p|!p.is_empty()){slots=slots.min(profile.pairs.len());}} - let mut plan=Plan{slots,sizes:Vec::new(),blob:geometry.max_blob,layers:None}; +pub(crate) fn open<'ctx>( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + options: OriginalCacheOptions, + profile: Option<&OriginalRankedExperts>, + pending_mtp_bind_bytes: usize, +) -> Result>> { + if options.slots < -1 { + return Err(Error::InvalidDimension); + } + if options.slots == 0 { + return Ok(None); + } + let geometry = Geometry::from_binding(binding)?; + let auto = options.slots < 0; + let reserve = options.reserve_mib.checked_mul(1 << 20).ok_or(Error::Overflow)?; + let free = usable_room(context.memory_info().map_err(driver)?.0, context.budget_bytes(), context.allocated_bytes()); + let mut slots = if auto { + let prefill_mib = if options.prefill_capacity > 0 && !options.prefill_borrow { + 160usize + .checked_add(options.prefill_capacity.checked_mul(680).ok_or(Error::Overflow)? / 1024) + .ok_or(Error::Overflow)? + } else { + 0 + }; + let reserved = reserve + .checked_add(prefill_mib.checked_mul(1 << 20).ok_or(Error::Overflow)?) + .and_then(|n| n.checked_add(pending_mtp_bind_bytes)) + .ok_or(Error::Overflow)?; + free.saturating_sub(reserved) / geometry.max_blob + } else { + options.slots as usize + }; + if auto { + if let Some(profile) = profile.filter(|p| !p.is_empty()) { + slots = slots.min(profile.pairs.len()); + } + } + let mut plan = Plan { slots, sizes: Vec::new(), blob: geometry.max_blob, layers: None }; // Row "5090 gap to vanilla": the per-layer cache took `slots` slots of the LARGEST layer blob (2.54 MiB; 8,702 slots in 21.6 GiB) where the Original // (and vanilla Strata) give each layer slots of its own blob size (about 1.94 MiB on average; 12,575 slots in 23.9 GiB with the profile). Same VRAM, // 30 % more resident experts. LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED=0 keeps the uniform slots (the A/B arm). - if options.per_layer&&slots>0&&sized_per_layer(){ - let free=usable_room(context.memory_info().map_err(driver)?.0,context.budget_bytes(),context.allocated_bytes()); - let cap=slots.checked_mul(geometry.max_blob).ok_or(Error::Overflow)?.min(free.saturating_sub(reserve)); - let sum=geometry.layer_bytes.iter().try_fold(0usize,|n,&b|n.checked_add(align(b)?).ok_or(Error::Overflow))?; - let quota=(cap/sum).min(512); - if quota>0{ - plan.sizes=Plan::per_layer_sizes(quota,&geometry.layer_bytes)?;plan.slots=plan.sizes.len(); - plan.layers=Some((quota,geometry.layer_bytes)); + if options.per_layer && slots > 0 && sized_per_layer() { + let free = + usable_room(context.memory_info().map_err(driver)?.0, context.budget_bytes(), context.allocated_bytes()); + let cap = slots.checked_mul(geometry.max_blob).ok_or(Error::Overflow)?.min(free.saturating_sub(reserve)); + let sum = + geometry.layer_bytes.iter().try_fold(0usize, |n, &b| n.checked_add(align(b)?).ok_or(Error::Overflow))?; + let quota = (cap / sum).min(512); + if quota > 0 { + plan.sizes = Plan::per_layer_sizes(quota, &geometry.layer_bytes)?; + plan.slots = plan.sizes.len(); + plan.layers = Some((quota, geometry.layer_bytes)); } } - if let Some(profile)=profile.filter(|p|!p.is_empty()&&!options.per_layer&&slots>0){ + if let Some(profile) = profile.filter(|p| !p.is_empty() && !options.per_layer && slots > 0) { // Original rereads the card before sizing variable slots. - let free=usable_room(context.memory_info().map_err(driver)?.0,context.budget_bytes(),context.allocated_bytes()); - let cap=slots.checked_mul(geometry.max_blob).ok_or(Error::Overflow)?.min(free.saturating_sub(reserve)); - plan.sizes.try_reserve_exact(profile.pairs.len()).map_err(|_|Error::InputAllocation)?; - let mut used=0usize; - for &(layer,_) in &profile.pairs{ - let bytes=geometry.layer_bytes[usize::from(layer)]; - let next=used.checked_add(align(bytes)?).ok_or(Error::Overflow)?; - if next>cap{break;}used=next;plan.sizes.push(bytes); + let free = + usable_room(context.memory_info().map_err(driver)?.0, context.budget_bytes(), context.allocated_bytes()); + let cap = slots.checked_mul(geometry.max_blob).ok_or(Error::Overflow)?.min(free.saturating_sub(reserve)); + plan.sizes.try_reserve_exact(profile.pairs.len()).map_err(|_| Error::InputAllocation)?; + let mut used = 0usize; + for &(layer, _) in &profile.pairs { + let bytes = geometry.layer_bytes[usize::from(layer)]; + let next = used.checked_add(align(bytes)?).ok_or(Error::Overflow)?; + if next > cap { + break; + } + used = next; + plan.sizes.push(bytes); } - plan.slots=plan.sizes.len(); + plan.slots = plan.sizes.len(); } - if plan.slots==0{return Ok(None);} - let (mut failed,mut zero_reads)=(0usize,0usize); + if plan.slots == 0 { + return Ok(None); + } + let (mut failed, mut zero_reads) = (0usize, 0usize); // Same optional fault-injection knob; no execution is done by this source port. - let mut fake_fails=crate::settings::process().memory.test_cache_fail; - for attempt in 0usize..{ - let opened=if fake_fails>0{fake_fails-=1;Err(leleka_cuda_driver::Error::BudgetExceeded)} - else if plan.sizes.is_empty(){context.original_expert_cache_uniform(plan.slots,48,512,geometry.max_blob)} - else{context.original_expert_cache_sized(&plan.sizes,48,512)}; - let mut cache=match opened{ - Ok(cache)=>cache, - Err(primary)=>{ - if auto&&failed<8&&plan.shrink_to(plan.bytes()?/4*3)?{failed+=1;continue;} - return Err(driver(primary)); - }, + let mut fake_fails = crate::settings::process().memory.test_cache_fail; + for attempt in 0usize.. { + let opened = if fake_fails > 0 { + fake_fails -= 1; + Err(leleka_cuda_driver::Error::BudgetExceeded) + } else if plan.sizes.is_empty() { + context.original_expert_cache_uniform(plan.slots, 48, 512, geometry.max_blob) + } else { + context.original_expert_cache_sized(&plan.sizes, 48, 512) }; - if !auto||attempt-failed>=6{cache.set_per_layer_admission(options.per_layer);return Ok(Some(cache));} + let mut cache = match opened { + Ok(cache) => cache, + Err(primary) => { + if auto && failed < 8 && plan.shrink_to(plan.bytes()? / 4 * 3)? { + failed += 1; + continue; + } + return Err(driver(primary)); + } + }; + if !auto || attempt - failed >= 6 { + cache.set_per_layer_admission(options.per_layer); + return Ok(Some(cache)); + } // the card's free bytes, and what the Context budget still lets the lazily allocated owners take - let free=usable_room(cache.zero_written_free_info().map_err(driver)?,context.budget_bytes(),context.allocated_bytes()); - if free>=reserve.saturating_sub(64<<20){cache.set_per_layer_admission(options.per_layer);return Ok(Some(cache));} - let mut give=reserve.saturating_sub(free).checked_add(64<<20).ok_or(Error::Overflow)?; - if free<16<<20{zero_reads+=1;give=give.max(if zero_reads<=2{1<<30}else{cache.bytes()/4});} - let keep=cache.bytes().saturating_sub(give); + let free = usable_room( + cache.zero_written_free_info().map_err(driver)?, + context.budget_bytes(), + context.allocated_bytes(), + ); + if free >= reserve.saturating_sub(64 << 20) { + cache.set_per_layer_admission(options.per_layer); + return Ok(Some(cache)); + } + let mut give = reserve.saturating_sub(free).checked_add(64 << 20).ok_or(Error::Overflow)?; + if free < 16 << 20 { + zero_reads += 1; + give = give.max(if zero_reads <= 2 { 1 << 30 } else { cache.bytes() / 4 }); + } + let keep = cache.bytes().saturating_sub(give); cache.close().map_err(driver)?; - if !plan.shrink_to(keep)?{return Ok(None);} + if !plan.shrink_to(keep)? { + return Ok(None); + } } unreachable!() } @@ -198,7 +316,11 @@ mod budget_room_tests { fn the_cache_is_sized_against_the_smaller_of_the_card_and_the_context_budget() { assert_eq!(usable_room(23_000 * MIB, 30_720 * MIB, 7_000 * MIB), 23_000 * MIB, "the card binds"); assert_eq!(usable_room(23_633 * MIB, 30_720 * MIB, 7_650 * MIB), 23_070 * MIB, "the budget binds"); - assert_eq!(usable_room(23_633 * MIB, 30_720 * MIB, 31_000 * MIB), 0, "an exhausted budget leaves nothing, never wraps"); + assert_eq!( + usable_room(23_633 * MIB, 30_720 * MIB, 31_000 * MIB), + 0, + "an exhausted budget leaves nothing, never wraps" + ); } /// The failed 5090 run (slots-noseed-r2): 23,633 MiB free on the card, 7,650 MiB already charged, a 30 GiB budget, reserves 700 + 130. @@ -211,7 +333,11 @@ mod budget_room_tests { assert!(budget - charged - cap >= reserve); assert!(free - cap >= reserve); let old_cap = free.saturating_sub(reserve); - assert!(budget - charged - old_cap < 400 * MIB, "the card-only sizing left {} MiB", (budget - charged - old_cap) / MIB); + assert!( + budget - charged - old_cap < 400 * MIB, + "the card-only sizing left {} MiB", + (budget - charged - old_cap) / MIB + ); } } @@ -230,7 +356,10 @@ mod per_layer_plan_tests { let sizes = Plan::per_layer_sizes(5, &lb).unwrap(); assert_eq!(sizes.len(), 5 * 48); for layer in 0..48 { - assert!(sizes[layer * 5..(layer + 1) * 5].iter().all(|&s| s == lb[layer]), "layer {layer} owns slots layer * quota .."); + assert!( + sizes[layer * 5..(layer + 1) * 5].iter().all(|&s| s == lb[layer]), + "layer {layer} owns slots layer * quota .." + ); } } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_file_cache_source.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_file_cache_source.rs index e1c9eebd..e4ff2eb5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_file_cache_source.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_file_cache_source.rs @@ -1,84 +1,153 @@ //! Actual Original file-source/cache startup and lent-slot refill seams. //! Unselected source: no binding, source bytes or cache indices certify a model. -use super::{contract::{Error,Result},original_cache_startup::OriginalRankedExperts}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,ModelBinding}; -use leleka_cuda_driver::{Context,OriginalExpertCache,OriginalExpertStager,OriginalStagerOptions,OriginalFileExpertBlob}; +use super::{ + contract::{Error, Result}, + original_cache_startup::OriginalRankedExperts, +}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; +use leleka_cuda_driver::{ + Context, OriginalExpertCache, OriginalExpertStager, OriginalFileExpertBlob, OriginalStagerOptions, +}; -pub(crate) struct OriginalFileCacheSource<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,stager:Option>, +pub(crate) struct OriginalFileCacheSource<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + stager: Option>, } -impl<'ctx> OriginalFileCacheSource<'ctx>{ - pub(crate) fn open(binding:&ModelBinding,context:&'ctx Context<'ctx>,options:OriginalStagerOptions, - remaining_host_allowance:usize)->Result{ - let lease=binding.original_file_expert_source().map_err(|_|Error::IdentityMismatch)?; - binding.validate_original_file_expert_source(&lease).map_err(|_|Error::IdentityMismatch)?; - let stager=context.original_file_expert_stager(lease,options,remaining_host_allowance).map_err(driver)?; - let owner=Self{binding:binding.identity(),context,stager:Some(stager)}; - owner.validate(binding,context)?;Ok(owner) +impl<'ctx> OriginalFileCacheSource<'ctx> { + pub(crate) fn open( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + options: OriginalStagerOptions, + remaining_host_allowance: usize, + ) -> Result { + let lease = binding.original_file_expert_source().map_err(|_| Error::IdentityMismatch)?; + binding.validate_original_file_expert_source(&lease).map_err(|_| Error::IdentityMismatch)?; + let stager = context.original_file_expert_stager(lease, options, remaining_host_allowance).map_err(driver)?; + let owner = Self { binding: binding.identity(), context, stager: Some(stager) }; + owner.validate(binding, context)?; + Ok(owner) } - pub(crate) fn validate(&self,binding:&ModelBinding,context:&Context<'_>)->Result<()>{ - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch);} - let source=self.stager.as_ref().ok_or(Error::IdentityMismatch)?.retained_file_source().map_err(driver)?; - binding.validate_original_file_expert_source(source).map_err(|_|Error::IdentityMismatch) + pub(crate) fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + let source = self.stager.as_ref().ok_or(Error::IdentityMismatch)?.retained_file_source().map_err(driver)?; + binding.validate_original_file_expert_source(source).map_err(|_| Error::IdentityMismatch) } - pub(crate) fn stager(&mut self,binding:&ModelBinding,context:&Context<'_>)->Result<&mut OriginalExpertStager<'ctx>>{ - self.validate(binding,context)?;self.stager.as_mut().ok_or(Error::IdentityMismatch) + pub(crate) fn stager( + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + ) -> Result<&mut OriginalExpertStager<'ctx>> { + self.validate(binding, context)?; + self.stager.as_mut().ok_or(Error::IdentityMismatch) } - fn blob(&self,binding:&ModelBinding,layer:usize,expert:usize,allowance:usize)->Result>{ - self.validate(binding,self.context)?; - let layer=u8::try_from(layer).map_err(|_|Error::InvalidLayer)?; - let expert=u32::try_from(expert).map_err(|_|Error::InvalidExpert)?; - let blob=self.stager.as_ref().ok_or(Error::IdentityMismatch)?.file_blob(layer,expert,allowance).map_err(driver)?; - self.validate(binding,self.context)?;Ok(blob) + fn blob( + &self, + binding: &ModelBinding, + layer: usize, + expert: usize, + allowance: usize, + ) -> Result> { + self.validate(binding, self.context)?; + let layer = u8::try_from(layer).map_err(|_| Error::InvalidLayer)?; + let expert = u32::try_from(expert).map_err(|_| Error::InvalidExpert)?; + let blob = + self.stager.as_ref().ok_or(Error::IdentityMismatch)?.file_blob(layer, expert, allowance).map_err(driver)?; + self.validate(binding, self.context)?; + Ok(blob) } /// generate.cpp2949..2985: ranked order, per-layer skips, blocking copy /// per admitted pair, then the real first-slot byte readback. - pub(crate) fn fill_profile(&self,binding:&ModelBinding,cache:&mut OriginalExpertCache<'ctx>, - profile:&OriginalRankedExperts,remaining_host_allowance:usize)->Result{ - self.validate(binding,self.context)?; - let per_layer=cache.per_layer_admission(); - let want=if per_layer{profile.pairs().len()}else{profile.pairs().len().min(cache.slots())}; - let mut filled=0usize; - for &(layer,expert) in &profile.pairs()[..want]{ - let slot=cache.admit(usize::from(layer),usize::from(expert)).map_err(driver)?; - if slot<0{if per_layer{continue;}break;} - let allowance=remaining_host_allowance.checked_sub(cache.pending_file_host_bytes().map_err(driver)?).ok_or(Error::InputAllocation)?; - let blob=self.blob(binding,usize::from(layer),usize::from(expert),allowance)?; - cache.fill_file_slot_blocking(slot as usize,blob).map_err(driver)?;filled+=1; + pub(crate) fn fill_profile( + &self, + binding: &ModelBinding, + cache: &mut OriginalExpertCache<'ctx>, + profile: &OriginalRankedExperts, + remaining_host_allowance: usize, + ) -> Result { + self.validate(binding, self.context)?; + let per_layer = cache.per_layer_admission(); + let want = if per_layer { profile.pairs().len() } else { profile.pairs().len().min(cache.slots()) }; + let mut filled = 0usize; + for &(layer, expert) in &profile.pairs()[..want] { + let slot = cache.admit(usize::from(layer), usize::from(expert)).map_err(driver)?; + if slot < 0 { + if per_layer { + continue; + } + break; + } + let allowance = remaining_host_allowance + .checked_sub(cache.pending_file_host_bytes().map_err(driver)?) + .ok_or(Error::InputAllocation)?; + let blob = self.blob(binding, usize::from(layer), usize::from(expert), allowance)?; + cache.fill_file_slot_blocking(slot as usize, blob).map_err(driver)?; + filled += 1; } - if filled>0{ - let &(layer,expert)=profile.pairs().first().ok_or(Error::IdentityMismatch)?; - let slot=usize::try_from(cache.slot_of(usize::from(layer),usize::from(expert))).map_err(|_|Error::IdentityMismatch)?; - let blob=self.blob(binding,usize::from(layer),usize::from(expert),remaining_host_allowance)?; - cache.verify_file_slot(slot,&blob).map_err(driver)?; + if filled > 0 { + let &(layer, expert) = profile.pairs().first().ok_or(Error::IdentityMismatch)?; + let slot = usize::try_from(cache.slot_of(usize::from(layer), usize::from(expert))) + .map_err(|_| Error::IdentityMismatch)?; + let blob = self.blob(binding, usize::from(layer), usize::from(expert), remaining_host_allowance)?; + cache.verify_file_slot(slot, &blob).map_err(driver)?; } - self.validate(binding,self.context)?;Ok(filled) + self.validate(binding, self.context)?; + Ok(filled) } /// Original lent entries are visited in logical layer/expert order; their /// actual slot owners remain unchanged. Queued default is one final wait. /// This is issue-only so multi-card callers can issue every card first. - pub(crate) fn refill_issue(&self,binding:&ModelBinding,cache:&mut OriginalExpertCache<'ctx>, - remaining_host_allowance:usize,blocking:bool)->Result{ - self.validate(binding,self.context)?;let mut filled=0usize; - for layer in 0..48{for expert in 0..512{ - let slot=cache.slot_of(layer,expert);if slot<0{continue;} - if cache.needs_refill(slot as usize).map_err(driver)?!=Some((layer,expert)){continue;} - let allowance=remaining_host_allowance.checked_sub(cache.pending_file_host_bytes().map_err(driver)?).ok_or(Error::InputAllocation)?; - let blob=self.blob(binding,layer,expert,allowance)?; - if blocking{cache.fill_file_slot_blocking(slot as usize,blob).map_err(driver)?;} - else{cache.fill_file_slot_queued(slot as usize,blob).map_err(driver)?;} - filled+=1; - }} - self.validate(binding,self.context)?;Ok(filled) + pub(crate) fn refill_issue( + &self, + binding: &ModelBinding, + cache: &mut OriginalExpertCache<'ctx>, + remaining_host_allowance: usize, + blocking: bool, + ) -> Result { + self.validate(binding, self.context)?; + let mut filled = 0usize; + for layer in 0..48 { + for expert in 0..512 { + let slot = cache.slot_of(layer, expert); + if slot < 0 { + continue; + } + if cache.needs_refill(slot as usize).map_err(driver)? != Some((layer, expert)) { + continue; + } + let allowance = remaining_host_allowance + .checked_sub(cache.pending_file_host_bytes().map_err(driver)?) + .ok_or(Error::InputAllocation)?; + let blob = self.blob(binding, layer, expert, allowance)?; + if blocking { + cache.fill_file_slot_blocking(slot as usize, blob).map_err(driver)?; + } else { + cache.fill_file_slot_queued(slot as usize, blob).map_err(driver)?; + } + filled += 1; + } + } + self.validate(binding, self.context)?; + Ok(filled) } - pub(crate) fn refill_wait(&self,binding:&ModelBinding,cache:&mut OriginalExpertCache<'ctx>)->Result<()>{ - self.validate(binding,self.context)?;cache.sync_queued().map_err(driver)?;self.validate(binding,self.context) + pub(crate) fn refill_wait(&self, binding: &ModelBinding, cache: &mut OriginalExpertCache<'ctx>) -> Result<()> { + self.validate(binding, self.context)?; + cache.sync_queued().map_err(driver)?; + self.validate(binding, self.context) + } + pub(crate) fn host_charge_bytes(&self) -> Result { + Ok(self.stager.as_ref().ok_or(Error::IdentityMismatch)?.host_charge_bytes()) + } + pub(crate) fn close(mut self) -> Result<()> { + self.stager.take().ok_or(Error::IdentityMismatch)?.close().map_err(driver) + } +} +fn driver(error: leleka_cuda_driver::Error) -> Error { + match error { + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + _ => Error::CudaExecution, } - pub(crate) fn host_charge_bytes(&self)->Result{Ok(self.stager.as_ref().ok_or(Error::IdentityMismatch)?.host_charge_bytes())} - pub(crate) fn close(mut self)->Result<()>{self.stager.take().ok_or(Error::IdentityMismatch)?.close().map_err(driver)} } -fn driver(error:leleka_cuda_driver::Error)->Error{match error{ - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - _=>Error::CudaExecution, -}} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs index 4c4e8a51..56e33554 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_full_owner.rs @@ -7,63 +7,90 @@ //! launch and does not manufacture a verifier receipt; the serving adapter //! supplies those at a later boundary. -use super::{contract::{Error,Result,Stage},executor::original_prompt::embedding::OriginalPromptEmbedding, - moe_weight_cache::{MoeWeightCache,RetainedOriginalMtpWeights},output_native::OriginalNativeOutput, - session::{QwenSession,original_prompt::draft::OriginalDraftSession}}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,ModelBinding}; -use leleka_cuda_driver::{Context,OriginalMtpActor,OriginalMtpCapture,OriginalMtpDraftHead,OriginalMtpDrafter, - OriginalMtpKvStartup,OriginalMtpLoadFailure,OriginalMtpLoadMeter,OriginalMtpLoadPlan,OriginalMtpPlanError, - OriginalMtpRetainedPrefix}; -use std::{path::Path,rc::Rc}; +use super::{ + contract::{Error, Result, Stage}, + executor::original_prompt::embedding::OriginalPromptEmbedding, + moe_weight_cache::{MoeWeightCache, RetainedOriginalMtpWeights}, + output_native::OriginalNativeOutput, + session::{QwenSession, original_prompt::draft::OriginalDraftSession}, +}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; +use leleka_cuda_driver::{ + Context, OriginalMtpActor, OriginalMtpCapture, OriginalMtpDraftHead, OriginalMtpDrafter, OriginalMtpKvStartup, + OriginalMtpLoadFailure, OriginalMtpLoadMeter, OriginalMtpLoadPlan, OriginalMtpPlanError, OriginalMtpRetainedPrefix, +}; +use std::{path::Path, rc::Rc}; /// Everything `MtpDrafter::load(rt_dir, g, ss, max_t, err, window)` receives /// besides geometry (which comes from the binding) and the RT directory. -#[derive(Clone,Copy,Debug)] -pub(in crate::qwen_forward) struct OriginalMtpRequest{ - pub(in crate::qwen_forward) max_t:usize, +#[derive(Clone, Copy, Debug)] +pub(in crate::qwen_forward) struct OriginalMtpRequest { + pub(in crate::qwen_forward) max_t: usize, /// Prompt chunk capacity of the scalar-prefill records. - pub(in crate::qwen_forward) prompt_capacity:usize, + pub(in crate::qwen_forward) prompt_capacity: usize, /// `coupled_draft_env()`: a preference, resolved against the real subset /// width into the actual layout by the load plan. - pub(in crate::qwen_forward) coupled:bool, + pub(in crate::qwen_forward) coupled: bool, /// `load(..., window)`; Original default 32768. - pub(in crate::qwen_forward) window:i64, - pub(in crate::qwen_forward) kv:OriginalMtpKvStartup, + pub(in crate::qwen_forward) window: i64, + pub(in crate::qwen_forward) kv: OriginalMtpKvStartup, } -impl OriginalMtpRequest{ +impl OriginalMtpRequest { /// Original defaults: window 32768 and the INT8 window-ring draft state. - pub(in crate::qwen_forward) fn ring_int8(max_t:usize,prompt_capacity:usize,coupled:bool,resident_cells:u64)->Self{ - Self{max_t,prompt_capacity,coupled,window:leleka_cuda_driver::MTP_ORIGINAL_WINDOW as i64, - kv:OriginalMtpKvStartup::ring_int8(resident_cells)} + pub(in crate::qwen_forward) fn ring_int8( + max_t: usize, + prompt_capacity: usize, + coupled: bool, + resident_cells: u64, + ) -> Self { + Self { + max_t, + prompt_capacity, + coupled, + window: leleka_cuda_driver::MTP_ORIGINAL_WINDOW as i64, + kv: OriginalMtpKvStartup::ring_int8(resident_cells), + } } } /// A load refusal: the fixed runtime error plus, when the driver produced one, /// the Original `mtp: ...` text the caller may print as `strata generate: ...`. -#[derive(Clone,Debug,Eq,PartialEq)] -pub(in crate::qwen_forward) struct OriginalMtpLoadError{pub(in crate::qwen_forward) error:Error,pub(in crate::qwen_forward) message:Option} -impl From for OriginalMtpLoadError{fn from(error:Error)->Self{Self{error,message:None}}} -impl From for OriginalMtpLoadError{ - fn from(failure:OriginalMtpLoadFailure)->Self{ - let error=match failure.cause(){ - Some(leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation)=>Error::InputAllocation, - Some(leleka_cuda_driver::Error::ContextMismatch)=>Error::IdentityMismatch, - Some(leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize - |leleka_cuda_driver::Error::ShapeMismatch{..})=>Error::InvalidDimension, - Some(leleka_cuda_driver::Error::UnsupportedQwenOperation)=>Error::Unsupported(Stage::Session), - Some(_)=>Error::CudaExecution, - None=>Error::InputRead, - }; - Self{error,message:Some(failure.message().to_owned())} +#[derive(Clone, Debug, Eq, PartialEq)] +pub(in crate::qwen_forward) struct OriginalMtpLoadError { + pub(in crate::qwen_forward) error: Error, + pub(in crate::qwen_forward) message: Option, +} +impl From for OriginalMtpLoadError { + fn from(error: Error) -> Self { + Self { error, message: None } } } -fn plan_error(error:OriginalMtpPlanError)->OriginalMtpLoadError{ - let kind=match error{ - OriginalMtpPlanError::ClosedProfile(_)=>Error::Unsupported(Stage::Session), - OriginalMtpPlanError::Overflow=>Error::Overflow, - _=>Error::InvalidDimension, +impl From for OriginalMtpLoadError { + fn from(failure: OriginalMtpLoadFailure) -> Self { + let error = match failure.cause() { + Some(leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation) => { + Error::InputAllocation + } + Some(leleka_cuda_driver::Error::ContextMismatch) => Error::IdentityMismatch, + Some( + leleka_cuda_driver::Error::InvalidQwenShape + | leleka_cuda_driver::Error::InvalidSize + | leleka_cuda_driver::Error::ShapeMismatch { .. }, + ) => Error::InvalidDimension, + Some(leleka_cuda_driver::Error::UnsupportedQwenOperation) => Error::Unsupported(Stage::Session), + Some(_) => Error::CudaExecution, + None => Error::InputRead, + }; + Self { error, message: Some(failure.message().to_owned()) } + } +} +fn plan_error(error: OriginalMtpPlanError) -> OriginalMtpLoadError { + let kind = match error { + OriginalMtpPlanError::ClosedProfile(_) => Error::Unsupported(Stage::Session), + OriginalMtpPlanError::Overflow => Error::Overflow, + _ => Error::InvalidDimension, }; - OriginalMtpLoadError{error:kind,message:Some(error.message())} + OriginalMtpLoadError { error: kind, message: Some(error.message()) } } /// Model-affine full MTP graphs, their immutable role bank and the loaded @@ -71,42 +98,63 @@ fn plan_error(error:OriginalMtpPlanError)->OriginalMtpLoadError{ /// by the same driver shared-layout allocation; it is deliberately kept outside /// this owner so the genuine prompt/verification transaction remains its sole /// mutator. -pub(in crate::qwen_forward) struct OriginalMtpFullOwner<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>, - actor:Option>,max_t:usize,failed:bool, +pub(in crate::qwen_forward) struct OriginalMtpFullOwner<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + actor: Option>, + max_t: usize, + failed: bool, } /// The only construction output accepted by the runtime. The graph owner and /// draft session are born from the identical original physical layout; callers /// cannot join an arbitrary standalone MTP ring to the full-forward graphs. -pub(in crate::qwen_forward) struct OriginalMtpFullAssembly<'ctx>{ - pub(in crate::qwen_forward) draft:OriginalDraftSession<'ctx>, - pub(in crate::qwen_forward) owner:OriginalMtpFullOwner<'ctx>, +pub(in crate::qwen_forward) struct OriginalMtpFullAssembly<'ctx> { + pub(in crate::qwen_forward) draft: OriginalDraftSession<'ctx>, + pub(in crate::qwen_forward) owner: OriginalMtpFullOwner<'ctx>, } -fn capture_of(binding:&ModelBinding,context:&Context<'_>,request:&OriginalMtpRequest,vocabulary:usize)->OriginalMtpCapture{ - OriginalMtpCapture{ +fn capture_of( + binding: &ModelBinding, + context: &Context<'_>, + request: &OriginalMtpRequest, + vocabulary: usize, +) -> OriginalMtpCapture { + OriginalMtpCapture { // `cudaGetDevice` at load, `g.n_expert`, `ss.k`, `max_cells` of the primary QSA state. - device:context.device_ordinal(),n_expert:u64::from(binding.expert_count()), - top_k:u64::from(binding.expert_used_count()), - max_cells:u64::from(binding.input_constants().context_length()), - max_t:request.max_t as u64,window:request.window,vocabulary:vocabulary as u64, - kv:request.kv,coupled_requested:request.coupled, + device: context.device_ordinal(), + n_expert: u64::from(binding.expert_count()), + top_k: u64::from(binding.expert_used_count()), + max_cells: u64::from(binding.input_constants().context_length()), + max_t: request.max_t as u64, + window: request.window, + vocabulary: vocabulary as u64, + kv: request.kv, + coupled_requested: request.coupled, } } -impl<'ctx> OriginalMtpFullOwner<'ctx>{ +impl<'ctx> OriginalMtpFullOwner<'ctx> { /// `bind_bytes` for the startup reserve (generate.cpp `mtp.bind_bytes(...)`): /// computed from the real native head and the RT directory, before any /// device bank exists. - pub(in crate::qwen_forward) fn bind_reserve(binding:&ModelBinding,context:&Context<'_>, - output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:&Path)->Result { - let head=output.mtp_head(binding)?; - let capture=capture_of(binding,context,request,head.vocabulary()); - let row_bytes=leleka_cuda_driver::native_head_row_bytes(head.kind(),head.columns()).map_err(|_|Error::InvalidDimension)?; - leleka_cuda_driver::original_mtp_bind_reserve(&capture, - leleka_cuda_driver::original_mtp_draft_vocab_bytes(rt_directory),row_bytes as u64) - .map_err(|e|plan_error(e).error) + pub(in crate::qwen_forward) fn bind_reserve( + binding: &ModelBinding, + context: &Context<'_>, + output: &OriginalNativeOutput<'ctx>, + request: &OriginalMtpRequest, + rt_directory: &Path, + ) -> Result { + let head = output.mtp_head(binding)?; + let capture = capture_of(binding, context, request, head.vocabulary()); + let row_bytes = leleka_cuda_driver::native_head_row_bytes(head.kind(), head.columns()) + .map_err(|_| Error::InvalidDimension)?; + leleka_cuda_driver::original_mtp_bind_reserve( + &capture, + leleka_cuda_driver::original_mtp_draft_vocab_bytes(rt_directory), + row_bytes as u64, + ) + .map_err(|e| plan_error(e).error) } /// Literal `MtpDrafter::load` + `bind` from an RT directory. The caller @@ -115,148 +163,228 @@ impl<'ctx> OriginalMtpFullOwner<'ctx>{ /// again here only for the optional `draft_vocab.bin`, exactly where /// `bind` reads it. #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn assemble_rt(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>,retained:&RetainedOriginalMtpWeights<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:&Path) - ->std::result::Result,OriginalMtpLoadError>{ - Self::assemble_core(binding,session,context,retained,embedding,output,request,Some(rt_directory)) + pub(in crate::qwen_forward) fn assemble_rt( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + retained: &RetainedOriginalMtpWeights<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + output: &OriginalNativeOutput<'ctx>, + request: &OriginalMtpRequest, + rt_directory: &Path, + ) -> std::result::Result, OriginalMtpLoadError> { + Self::assemble_core(binding, session, context, retained, embedding, output, request, Some(rt_directory)) } /// Same assembly over the digest-pinned pack held by the MoE cache (no RT /// directory, hence no draft-vocab subset). #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn assemble(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>,moe:&MoeWeightCache<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest) - ->std::result::Result,OriginalMtpLoadError>{ + pub(in crate::qwen_forward) fn assemble( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + moe: &MoeWeightCache<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + output: &OriginalNativeOutput<'ctx>, + request: &OriginalMtpRequest, + ) -> std::result::Result, OriginalMtpLoadError> { // Source keeps all MTP roles immutable for the life of cached graphs. - let retained=moe.retain_original_mtp_weights(binding,context)?; - Self::assemble_core(binding,session,context,&retained,embedding,output,request,None) + let retained = moe.retain_original_mtp_weights(binding, context)?; + Self::assemble_core(binding, session, context, &retained, embedding, output, request, None) } #[allow(clippy::too_many_arguments)] - fn assemble_core(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>,retained:&RetainedOriginalMtpWeights<'ctx>,embedding:&OriginalPromptEmbedding<'ctx>, - output:&OriginalNativeOutput<'ctx>,request:&OriginalMtpRequest,rt_directory:Option<&Path>) - ->std::result::Result,OriginalMtpLoadError>{ - let(max_t,prompt_capacity)=(request.max_t,request.prompt_capacity); - if binding.layer_count()!=48||!(1..=8).contains(&max_t)||!(1..=8192).contains(&prompt_capacity) - ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch.into());} + fn assemble_core( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + retained: &RetainedOriginalMtpWeights<'ctx>, + embedding: &OriginalPromptEmbedding<'ctx>, + output: &OriginalNativeOutput<'ctx>, + request: &OriginalMtpRequest, + rt_directory: Option<&Path>, + ) -> std::result::Result, OriginalMtpLoadError> { + let (max_t, prompt_capacity) = (request.max_t, request.prompt_capacity); + if binding.layer_count() != 48 + || !(1..=8).contains(&max_t) + || !(1..=8192).contains(&prompt_capacity) + || !std::ptr::eq(context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch.into()); + } // Fresh ledger window: the bank's own bytes are added by `finish`. - let meter=OriginalMtpLoadMeter::start(context); - let head=output.mtp_head(binding)?; + let meter = OriginalMtpLoadMeter::start(context); + let head = output.mtp_head(binding)?; // geometry/session/device capture -> checked plan (refuses what the // retained owners cannot represent instead of planning around it) - let plan=OriginalMtpLoadPlan::new(capture_of(binding,context,request,head.vocabulary()),retained.dense_file_bytes()) - .map_err(plan_error)?; + let plan = OriginalMtpLoadPlan::new( + capture_of(binding, context, request, head.vocabulary()), + retained.dense_file_bytes(), + ) + .map_err(plan_error)?; // ---- bind: optional draft head (needs the main head's weights) - let draft_head:Option>=match rt_directory{ - Some(directory)=>{ - let weights=head.weights(); - context.original_mtp_draft_head(directory,&weights,head.kind(),head.columns(),head.vocabulary())? - }, - None=>None, + let draft_head: Option> = match rt_directory { + Some(directory) => { + let weights = head.weights(); + context.original_mtp_draft_head(directory, &weights, head.kind(), head.columns(), head.vocabulary())? + } + None => None, }; - let subset=draft_head.as_ref().map(|h|h.count() as u64); - let coupled_layout=plan.coupled_layout(subset).map_err(plan_error)?; - let scalar=retained.scalar_prefill_weights(binding,context,embedding)?; - let prefix=Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?); - let weights=retained.full_forward_weights(binding,context,prefix,&head,head.vocabulary(),draft_head.as_ref())?; + let subset = draft_head.as_ref().map(|h| h.count() as u64); + let coupled_layout = plan.coupled_layout(subset).map_err(plan_error)?; + let scalar = retained.scalar_prefill_weights(binding, context, embedding)?; + let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?); + let weights = + retained.full_forward_weights(binding, context, prefix, &head, head.vocabulary(), draft_head.as_ref())?; // This returns exactly one main arena and mapped records shared by // scalar prefill and full forward, plus the matching physical KV ring. - let(ring,scalar,full)=context.original_mtp_shared_layout_with_ring( - Rc::clone(&weights),max_t,prompt_capacity,coupled_layout).map_err(driver_error)?; - let drafter=match OriginalMtpDrafter::new(full,scalar){ - Ok(value)=>value, - Err(primary)=>{let close=ring.close().map_err(driver_error);return Err(match close {Err(cleanup)=>cleanup,Ok(())=>driver_error(primary)}.into());} + let (ring, scalar, full) = context + .original_mtp_shared_layout_with_ring(Rc::clone(&weights), max_t, prompt_capacity, coupled_layout) + .map_err(driver_error)?; + let drafter = match OriginalMtpDrafter::new(full, scalar) { + Ok(value) => value, + Err(primary) => { + let close = ring.close().map_err(driver_error); + return Err(match close { + Err(cleanup) => cleanup, + Ok(()) => driver_error(primary), + } + .into()); + } }; - let evidence=match meter.finish(context,draft_head.as_ref(),retained.loaded_bytes()){ - Ok(value)=>value, - Err(primary)=>{let _=drafter.close();let _=ring.close();return Err(primary.into());} + let evidence = match meter.finish(context, draft_head.as_ref(), retained.loaded_bytes()) { + Ok(value) => value, + Err(primary) => { + let _ = drafter.close(); + let _ = ring.close(); + return Err(primary.into()); + } }; - let actor=match OriginalMtpActor::adopt(context,plan,drafter,&ring,weights,evidence){ - Ok(value)=>value, - Err(primary)=>{let _=ring.close();return Err(primary.into());} + let actor = match OriginalMtpActor::adopt(context, plan, drafter, &ring, weights, evidence) { + Ok(value) => value, + Err(primary) => { + let _ = ring.close(); + return Err(primary.into()); + } }; - let draft=match OriginalDraftSession::from_original_ring(binding,session,context,ring){ - Ok(value)=>value, - Err(primary)=>{let _=actor.close();return Err(primary.into());} + let draft = match OriginalDraftSession::from_original_ring(binding, session, context, ring) { + Ok(value) => value, + Err(primary) => { + let _ = actor.close(); + return Err(primary.into()); + } }; - Ok(OriginalMtpFullAssembly{draft,owner:Self{binding:binding.identity(),context,actor:Some(actor),max_t,failed:false}}) + Ok(OriginalMtpFullAssembly { + draft, + owner: Self { binding: binding.identity(), context, actor: Some(actor), max_t, failed: false }, + }) } - pub(in crate::qwen_forward) fn validate(&self,binding:&ModelBinding,context:&Context<'ctx>, - max_t:usize)->Result<()> { - if self.failed||self.max_t!=max_t||!self.binding.matches(&binding.identity()) - ||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch);} + pub(in crate::qwen_forward) fn validate( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + max_t: usize, + ) -> Result<()> { + if self.failed + || self.max_t != max_t + || !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, context) + { + return Err(Error::IdentityMismatch); + } self.actor.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver_error) } /// The verified-session adapter loans the canonical ring from /// `OriginalDraftSession::with_pending_ring` and invokes this exact actor. /// No public mutable ring reference escapes this module. - pub(in crate::qwen_forward) fn actor_mut(&mut self,binding:&ModelBinding, - context:&Context<'ctx>,max_t:usize)->Result<&mut OriginalMtpActor<'ctx>>{ - self.validate(binding,context,max_t)?; + pub(in crate::qwen_forward) fn actor_mut( + &mut self, + binding: &ModelBinding, + context: &Context<'ctx>, + max_t: usize, + ) -> Result<&mut OriginalMtpActor<'ctx>> { + self.validate(binding, context, max_t)?; self.actor.as_mut().ok_or(Error::IdentityMismatch) } /// Read-only view for `device()`, `vram_bytes()`, `first_needed()`, plans. - pub(in crate::qwen_forward) fn actor(&self)->Result<&OriginalMtpActor<'ctx>>{ + pub(in crate::qwen_forward) fn actor(&self) -> Result<&OriginalMtpActor<'ctx>> { self.actor.as_ref().ok_or(Error::IdentityMismatch) } - pub(in crate::qwen_forward) fn close(mut self)->Result<()> {self.close_inner()} - fn close_inner(&mut self)->Result<()> { - self.failed=true; + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; // The actor drains its stream and closes the drafter before the retained // weights it holds are released, the same order as the source. - self.actor.take().map_or(Ok(()),|owner|owner.close().map_err(driver_error)) + self.actor.take().map_or(Ok(()), |owner| owner.close().map_err(driver_error)) + } +} +impl Drop for OriginalMtpFullOwner<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); } } -impl Drop for OriginalMtpFullOwner<'_>{fn drop(&mut self){let _=self.close_inner();}} -fn driver_error(error:leleka_cuda_driver::Error)->Error{ - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} - match error{ - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize - |leleka_cuda_driver::Error::InvalidProjectionShape=>Error::InvalidDimension, - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::UnsupportedQwenOperation=>Error::Unsupported(Stage::Session), - _=>Error::CudaExecution, +fn driver_error(error: leleka_cuda_driver::Error) -> Error { + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } + match error { + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + leleka_cuda_driver::Error::InvalidQwenShape + | leleka_cuda_driver::Error::InvalidSize + | leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension, + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(Stage::Session), + _ => Error::CudaExecution, } } #[cfg(test)] -mod tests{ +mod tests { use super::*; #[test] - fn plan_refusals_map_to_fixed_errors_and_keep_the_original_text(){ - let cases=[ - (OriginalMtpPlanError::MaxTOutOfRange,Error::InvalidDimension,"mtp: max_t out of range"), - (OriginalMtpPlanError::Geometry,Error::InvalidDimension,"mtp: invalid geometry"), - (OriginalMtpPlanError::Overflow,Error::Overflow,"mtp: resource size overflow"), - (OriginalMtpPlanError::RingMode,Error::InvalidDimension,"mtp: the draft K/V ring does not match the planned KV mode"), - (OriginalMtpPlanError::ClosedProfile("draft attention window"),Error::Unsupported(Stage::Session), - "mtp: unsupported draft attention window for the retained Original owners"), + fn plan_refusals_map_to_fixed_errors_and_keep_the_original_text() { + let cases = [ + (OriginalMtpPlanError::MaxTOutOfRange, Error::InvalidDimension, "mtp: max_t out of range"), + (OriginalMtpPlanError::Geometry, Error::InvalidDimension, "mtp: invalid geometry"), + (OriginalMtpPlanError::Overflow, Error::Overflow, "mtp: resource size overflow"), + ( + OriginalMtpPlanError::RingMode, + Error::InvalidDimension, + "mtp: the draft K/V ring does not match the planned KV mode", + ), + ( + OriginalMtpPlanError::ClosedProfile("draft attention window"), + Error::Unsupported(Stage::Session), + "mtp: unsupported draft attention window for the retained Original owners", + ), ]; - for(plan,error,text) in cases{ - let mapped=plan_error(plan); - assert_eq!(mapped.error,error); - assert_eq!(mapped.message.as_deref(),Some(text)); + for (plan, error, text) in cases { + let mapped = plan_error(plan); + assert_eq!(mapped.error, error); + assert_eq!(mapped.message.as_deref(), Some(text)); } // a runtime-only error carries no driver text - assert_eq!(OriginalMtpLoadError::from(Error::IdentityMismatch), - OriginalMtpLoadError{error:Error::IdentityMismatch,message:None}); + assert_eq!( + OriginalMtpLoadError::from(Error::IdentityMismatch), + OriginalMtpLoadError { error: Error::IdentityMismatch, message: None } + ); } #[test] - fn default_request_is_the_original_window_over_the_int8_ring(){ - let request=OriginalMtpRequest::ring_int8(4,512,true,20480); - assert_eq!((request.max_t,request.prompt_capacity,request.coupled),(4,512,true)); - assert_eq!(request.window,32768); - assert_eq!(request.kv,OriginalMtpKvStartup::ring_int8(20480)); - assert!(request.kv.int8&&!request.kv.q4&&!request.kv.hybrid&&!request.kv.ring_off&&!request.kv.main_off); + fn default_request_is_the_original_window_over_the_int8_ring() { + let request = OriginalMtpRequest::ring_int8(4, 512, true, 20480); + assert_eq!((request.max_t, request.prompt_capacity, request.coupled), (4, 512, true)); + assert_eq!(request.window, 32768); + assert_eq!(request.kv, OriginalMtpKvStartup::ring_int8(20480)); + assert!( + request.kv.int8 && !request.kv.q4 && !request.kv.hybrid && !request.kv.ring_off && !request.kv.main_off + ); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs index 8735ce60..11f85228 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_prefill.rs @@ -2,108 +2,188 @@ //! remain authoritative. Original Prefill conditions draft KV on the next known //! prompt token; preceding next-IDs come from the same pending input owners. //! The final prompt seed and sampled ID belong to the separate Verifier path. -use super::*; use super::super::moe_weight_cache::MoeWeightCache; -use crate::model_binding::qwen4exp_input::{MtpKind,MtpRole}; -use leleka_cuda_driver::{OriginalMtpPrefill,OriginalMtpPrefillWeights,OriginalMtpEmbedding, - DraftKvPolicy,DraftKvOutcome,CompletedDraftKv,MtpOriginalInt8,MtpInt8Snapshot,NativeBatchWorkspace}; +use super::*; +use crate::model_binding::qwen4exp_input::{MtpKind, MtpRole}; +use leleka_cuda_driver::{ + CompletedDraftKv, DraftKvOutcome, DraftKvPolicy, MtpInt8Snapshot, MtpOriginalInt8, NativeBatchWorkspace, + OriginalMtpEmbedding, OriginalMtpPrefill, OriginalMtpPrefillWeights, +}; /// Affine runtime handoff. Does not publish either canonical target or draft. /// Joint publication/rollback belongs to the real owning pending transaction. pub(in crate::qwen_forward) struct OriginalDraftKvPending { - binding:BindingIdentity,phase:Rc,first:u64,end:u64,last_next:TokenId, - completed:CompletedDraftKv, + binding: BindingIdentity, + phase: Rc, + first: u64, + end: u64, + last_next: TokenId, + completed: CompletedDraftKv, } impl OriginalDraftKvPending { - pub(in crate::qwen_forward) fn validate(&self,binding:&ModelBinding, - txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal)->Result<()> { - txn.validate_final(preview)?;preview.validate_conditioning(self.last_next)?; - if !self.binding.matches(&binding.identity())||!self.phase.same(&txn.phase()) - ||self.first!=txn.start_position()||self.end!=txn.end_position() - ||self.completed.next_position() as u64!=self.end {return Err(Error::IdentityMismatch)} + pub(in crate::qwen_forward) fn validate( + &self, + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + ) -> Result<()> { + txn.validate_final(preview)?; + preview.validate_conditioning(self.last_next)?; + if !self.binding.matches(&binding.identity()) + || !self.phase.same(&txn.phase()) + || self.first != txn.start_position() + || self.end != txn.end_position() + || self.completed.next_position() as u64 != self.end + { + return Err(Error::IdentityMismatch); + } Ok(()) } - pub(in crate::qwen_forward) fn validate_current(&self,binding:&ModelBinding, - txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal,ring:&MtpOriginalInt8<'_>)->Result<()>{ - self.validate(binding,txn,preview)?; + pub(in crate::qwen_forward) fn validate_current( + &self, + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + ring: &MtpOriginalInt8<'_>, + ) -> Result<()> { + self.validate(binding, txn, preview)?; self.completed.validate_current(ring).map_err(micro_driver_error) } - pub(in crate::qwen_forward) fn last_next(&self,binding:&ModelBinding, - txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal)->Result{ - self.validate(binding,txn,preview)?;Ok(self.last_next) + pub(in crate::qwen_forward) fn last_next( + &self, + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + ) -> Result { + self.validate(binding, txn, preview)?; + Ok(self.last_next) + } + pub(in crate::qwen_forward) fn completed(&self) -> &CompletedDraftKv { + &self.completed } - pub(in crate::qwen_forward) fn completed(&self)->&CompletedDraftKv{&self.completed} } pub(in crate::qwen_forward) enum OriginalPromptDraftOutcome { - Fallback(leleka_cuda_driver::DraftKvFallback),Skipped,Cancelled, + Fallback(leleka_cuda_driver::DraftKvFallback), + Skipped, + Cancelled, Completed(OriginalDraftKvPending), } -impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx> { +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { /// Called after the genuine all-row conditioning phase while its physical R /// loan survives. `last_next` must match that phase's known next prompt ID. /// Original Prefill neither invokes the output head nor samples this ID. #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn record_original_draft_kv( - &mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,mtp:&MoeWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal,last_next:TokenId, - producer:&mut OriginalMtpPrefill<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>, - ring:&mut MtpOriginalInt8<'ctx>,prior:&MtpInt8Snapshot, - embedding:OriginalMtpEmbedding<'_, '_>,first_needed:usize,policy:&DraftKvPolicy, - cancelled:impl FnMut()->bool, - )->Result { - self.sources.validate(binding,dense)?;txn.validate_final(preview)?; + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + mtp: &MoeWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + last_next: TokenId, + producer: &mut OriginalMtpPrefill<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + embedding: OriginalMtpEmbedding<'_, '_>, + first_needed: usize, + policy: &DraftKvPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.sources.validate(binding, dense)?; + txn.validate_final(preview)?; preview.validate_conditioning(last_next)?; - let phase=self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len() - ||!phase.same(&txn.phase())||!self.device.context_matches(self.sources.context) - ||!std::ptr::eq(txn.context()?,self.sources.context){return Err(Error::IdentityMismatch)} - let vocab=Dimension::new(248320)?; - if last_next!=TokenId::new(u64::from(last_next.get()),vocab)?{return Err(Error::InvalidToken)} - let mut next=Vec::new();next.try_reserve_exact(txn.len()).map_err(|_|Error::InputAllocation)?; - for index in 1..txn.len(){let actual=txn.input(index)?; - if !Rc::ptr_eq(&actual,&match &self.sources.rows[index].input{ - SourceInput::Owned(actual)=>Rc::clone(actual),SourceInput::Borrowed(_)=>return Err(Error::IdentityMismatch)}){ - return Err(Error::IdentityMismatch)} + let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; + if self.sources.role != GrRole::Final + || self.sources.rows.len() != txn.len() + || !phase.same(&txn.phase()) + || !self.device.context_matches(self.sources.context) + || !std::ptr::eq(txn.context()?, self.sources.context) + { + return Err(Error::IdentityMismatch); + } + let vocab = Dimension::new(248320)?; + if last_next != TokenId::new(u64::from(last_next.get()), vocab)? { + return Err(Error::InvalidToken); + } + let mut next = Vec::new(); + next.try_reserve_exact(txn.len()).map_err(|_| Error::InputAllocation)?; + for index in 1..txn.len() { + let actual = txn.input(index)?; + if !Rc::ptr_eq( + &actual, + &match &self.sources.rows[index].input { + SourceInput::Owned(actual) => Rc::clone(actual), + SourceInput::Borrowed(_) => return Err(Error::IdentityMismatch), + }, + ) { + return Err(Error::IdentityMismatch); + } next.push(actual.token().get() as i32); } next.push(last_next.get() as i32); - let context=self.sources.context; + let context = self.sources.context; // Exact Original acquisition order, authentic pack descriptor checks. - let matrix=|role,expected|->Result<&leleka_cuda_driver::DeviceBuffer<'ctx>>{ - let(kind,rows,columns,buffer)=mtp.mtp_matrix(binding,context,role)?; - if (kind,rows,columns)!=expected{return Err(Error::InvalidDimension)}Ok(buffer) + let matrix = |role, expected| -> Result<&leleka_cuda_driver::DeviceBuffer<'ctx>> { + let (kind, rows, columns, buffer) = mtp.mtp_matrix(binding, context, role)?; + if (kind, rows, columns) != expected { + return Err(Error::InvalidDimension); + } + Ok(buffer) }; - let weights=OriginalMtpPrefillWeights{ - embedding_norm:matrix(MtpRole::EmbeddingNorm,(MtpKind::F32,1,2560))?, - embedding_fc:matrix(MtpRole::FcEmbedding,(MtpKind::Q8_0,2560,2560))?, - hidden_norm:matrix(MtpRole::HiddenNorm,(MtpKind::F32,1,10240))?, - hidden_fc:matrix(MtpRole::FcHidden,(MtpKind::Q8_0,2560,2560))?, - gr_norm:matrix(MtpRole::AttentionNorm,(MtpKind::F32,1,10240))?, - gr_down:matrix(MtpRole::AttentionDown,(MtpKind::Bf16,320,10240))?, - gr_up:matrix(MtpRole::AttentionUp,(MtpKind::Bf16,10240,320))?, - key:matrix(MtpRole::KeyProjection,(MtpKind::Q8_0,512,2560))?, - value:matrix(MtpRole::ValueProjection,(MtpKind::Q8_0,512,2560))?, - key_norm:matrix(MtpRole::KeyNorm,(MtpKind::F32,1,256))?, + let weights = OriginalMtpPrefillWeights { + embedding_norm: matrix(MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560))?, + embedding_fc: matrix(MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560))?, + hidden_norm: matrix(MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240))?, + hidden_fc: matrix(MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560))?, + gr_norm: matrix(MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240))?, + gr_down: matrix(MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240))?, + gr_up: matrix(MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320))?, + key: matrix(MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560))?, + value: matrix(MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560))?, + key_norm: matrix(MtpRole::KeyNorm, (MtpKind::F32, 1, 256))?, }; // Input/draft host policy and all ten immutable device loans are live // throughout drain; never mint scalar committed products for prior rows. - let result=producer.record(&mut self.device,workspace,ring,prior,&next, - usize::try_from(txn.start_position()).map_err(|_|Error::Overflow)?,first_needed, - weights,embedding,policy,cancelled).map_err(micro_driver_error)?; - self.sources.validate(binding,dense)?;txn.validate_final(preview)?; - if !phase.same(&txn.phase()){return Err(Error::IdentityMismatch)} - Ok(match result{ - DraftKvOutcome::Fallback(reason)=>OriginalPromptDraftOutcome::Fallback(reason), - DraftKvOutcome::Skipped=>OriginalPromptDraftOutcome::Skipped, - DraftKvOutcome::Cancelled=>OriginalPromptDraftOutcome::Cancelled, - DraftKvOutcome::Completed(completed)=>{ - let pending=OriginalDraftKvPending{binding:binding.identity(),phase, - first:txn.start_position(),end:txn.end_position(),last_next,completed}; - pending.validate_current(binding,txn,preview,ring)?; + let result = producer + .record( + &mut self.device, + workspace, + ring, + prior, + &next, + usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?, + first_needed, + weights, + embedding, + policy, + cancelled, + ) + .map_err(micro_driver_error)?; + self.sources.validate(binding, dense)?; + txn.validate_final(preview)?; + if !phase.same(&txn.phase()) { + return Err(Error::IdentityMismatch); + } + Ok(match result { + DraftKvOutcome::Fallback(reason) => OriginalPromptDraftOutcome::Fallback(reason), + DraftKvOutcome::Skipped => OriginalPromptDraftOutcome::Skipped, + DraftKvOutcome::Cancelled => OriginalPromptDraftOutcome::Cancelled, + DraftKvOutcome::Completed(completed) => { + let pending = OriginalDraftKvPending { + binding: binding.identity(), + phase, + first: txn.start_position(), + end: txn.end_position(), + last_next, + completed, + }; + pending.validate_current(binding, txn, preview, ring)?; OriginalPromptDraftOutcome::Completed(pending) } }) } } -#[path="original_mtp_scalar_prefill.rs"]mod scalar; +#[path = "original_mtp_scalar_prefill.rs"] +mod scalar; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs index b3e9a4c7..36055d6e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_scalar_prefill.rs @@ -1,77 +1,148 @@ //! Private child of genuine original_mtp_prefill runtime adapter. Same Final //! phase, shifted actual IDs and current ring receipt, literal scalar producer. use super::*; -use leleka_cuda_driver::{OriginalMtpActor,OriginalMtpRetainedScalarWeights,OriginalMtpScalarPolicy}; use crate::qwen_forward::moe_weight_cache::RetainedOriginalMtpWeights; -impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx> { +use leleka_cuda_driver::{OriginalMtpActor, OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy}; +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { /// Original Prefill uses only known-next conditioning with no head/D2H. /// The genuine all-row R and immutable input owners survive through drain. #[allow(clippy::too_many_arguments)] pub(in crate::qwen_forward) fn record_original_scalar_draft_kv( - &mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,mtp:&RetainedOriginalMtpWeights<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,preview:&PromptDeviceFinal,last_next:TokenId, - producer:&mut OriginalMtpActor<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>, - ring:&mut MtpOriginalInt8<'ctx>,prior:&MtpInt8Snapshot, - retained:Rc>,first_needed:usize,policy:&OriginalMtpScalarPolicy, - cancelled:impl FnMut()->bool, - )->Result { - self.sources.validate(binding,dense)?;txn.validate_final(preview)?; + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + mtp: &RetainedOriginalMtpWeights<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + preview: &PromptDeviceFinal, + last_next: TokenId, + producer: &mut OriginalMtpActor<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + retained: Rc>, + first_needed: usize, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + self.sources.validate(binding, dense)?; + txn.validate_final(preview)?; preview.validate_conditioning(last_next)?; - let phase=self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len() - ||!phase.same(&txn.phase())||!preview.lease_identity.same_lease(&self.device.lease_identity()) - ||!self.device.context_matches(self.sources.context) - ||!std::ptr::eq(txn.context()?,self.sources.context){return Err(Error::IdentityMismatch)} - if txn.known_prompt_next()?.is_some_and(|known|known!=last_next){return Err(Error::IdentityMismatch)} - let vocab=Dimension::new(248320)?; - if last_next!=TokenId::new(u64::from(last_next.get()),vocab)?{return Err(Error::InvalidToken)} - let mut next=Vec::new();next.try_reserve_exact(txn.len()).map_err(|_|Error::InputAllocation)?; - for index in 1..txn.len(){let actual=txn.input(index)?; - if !Rc::ptr_eq(&actual,&match &self.sources.rows[index].input{ - SourceInput::Owned(actual)=>Rc::clone(actual),SourceInput::Borrowed(_)=>return Err(Error::IdentityMismatch)}){ - return Err(Error::IdentityMismatch)} + let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; + if self.sources.role != GrRole::Final + || self.sources.rows.len() != txn.len() + || !phase.same(&txn.phase()) + || !preview.lease_identity.same_lease(&self.device.lease_identity()) + || !self.device.context_matches(self.sources.context) + || !std::ptr::eq(txn.context()?, self.sources.context) + { + return Err(Error::IdentityMismatch); + } + if txn.known_prompt_next()?.is_some_and(|known| known != last_next) { + return Err(Error::IdentityMismatch); + } + let vocab = Dimension::new(248320)?; + if last_next != TokenId::new(u64::from(last_next.get()), vocab)? { + return Err(Error::InvalidToken); + } + let mut next = Vec::new(); + next.try_reserve_exact(txn.len()).map_err(|_| Error::InputAllocation)?; + for index in 1..txn.len() { + let actual = txn.input(index)?; + if !Rc::ptr_eq( + &actual, + &match &self.sources.rows[index].input { + SourceInput::Owned(actual) => Rc::clone(actual), + SourceInput::Borrowed(_) => return Err(Error::IdentityMismatch), + }, + ) { + return Err(Error::IdentityMismatch); + } next.push(actual.token().get() as i32); } next.push(last_next.get() as i32); - let context=self.sources.context; + let context = self.sources.context; // Exact Original acquisition order, authentic pack descriptor checks. // The retained scalar weights come from the same owner the drafter was built with: the pinned pack's cache, or with an RT // directory (--mtp-rt-dir) its own bank, whose buffers are not the MoE cache's. Check against that owner. - let matrix=|role,expected|->Result>>{ - let(kind,rows,columns,buffer)=mtp.matrix(binding,context,role)?; - if (kind,rows,columns)!=expected{crate::bringup_trace!("DBG scalar draft-kv matrix {role:?}: pack has {:?} {rows}x{columns}, expected {:?}",kind,expected);return Err(Error::InvalidDimension)}Ok(buffer) + let matrix = |role, expected| -> Result>> { + let (kind, rows, columns, buffer) = mtp.matrix(binding, context, role)?; + if (kind, rows, columns) != expected { + crate::bringup_trace!( + "DBG scalar draft-kv matrix {role:?}: pack has {:?} {rows}x{columns}, expected {:?}", + kind, + expected + ); + return Err(Error::InvalidDimension); + } + Ok(buffer) }; - retained.with_whole_loans(context,|weights,_|{ - for(buffer,role,shape)in [ - (weights.input.embedding_norm,MtpRole::EmbeddingNorm,(MtpKind::F32,1,2560)), - (weights.input.embedding_fc,MtpRole::FcEmbedding,(MtpKind::Q8_0,2560,2560)), - (weights.input.hidden_norm,MtpRole::HiddenNorm,(MtpKind::F32,1,10240)), - (weights.input.hidden_fc,MtpRole::FcHidden,(MtpKind::Q8_0,2560,2560)), - (weights.input.gr_norm,MtpRole::AttentionNorm,(MtpKind::F32,1,10240)), - (weights.input.gr_down,MtpRole::AttentionDown,(MtpKind::Bf16,320,10240)), - (weights.input.gr_up,MtpRole::AttentionUp,(MtpKind::Bf16,10240,320)), - (weights.input.key,MtpRole::KeyProjection,(MtpKind::Q8_0,512,2560)), - (weights.input.value,MtpRole::ValueProjection,(MtpKind::Q8_0,512,2560)), - (weights.input.key_norm,MtpRole::KeyNorm,(MtpKind::F32,1,256)), - (weights.gr_inject,MtpRole::AttentionInject,(MtpKind::Bf16,4,10240)), - ]{match matrix(role,shape){Ok(b) if std::ptr::eq(buffer,&*b)=>{},Ok(_)=>{crate::bringup_trace!("DBG scalar draft-kv matrix {role:?}: buffer is not the retained one");return Err(leleka_cuda_driver::Error::InvalidProjectionShape)},Err(e)=>{crate::bringup_trace!("DBG scalar draft-kv matrix {role:?} err {e:?}");return Err(leleka_cuda_driver::Error::InvalidProjectionShape)}}} - Ok(()) - }).map_err(micro_driver_error)?; + retained + .with_whole_loans(context, |weights, _| { + for (buffer, role, shape) in [ + (weights.input.embedding_norm, MtpRole::EmbeddingNorm, (MtpKind::F32, 1, 2560)), + (weights.input.embedding_fc, MtpRole::FcEmbedding, (MtpKind::Q8_0, 2560, 2560)), + (weights.input.hidden_norm, MtpRole::HiddenNorm, (MtpKind::F32, 1, 10240)), + (weights.input.hidden_fc, MtpRole::FcHidden, (MtpKind::Q8_0, 2560, 2560)), + (weights.input.gr_norm, MtpRole::AttentionNorm, (MtpKind::F32, 1, 10240)), + (weights.input.gr_down, MtpRole::AttentionDown, (MtpKind::Bf16, 320, 10240)), + (weights.input.gr_up, MtpRole::AttentionUp, (MtpKind::Bf16, 10240, 320)), + (weights.input.key, MtpRole::KeyProjection, (MtpKind::Q8_0, 512, 2560)), + (weights.input.value, MtpRole::ValueProjection, (MtpKind::Q8_0, 512, 2560)), + (weights.input.key_norm, MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), + (weights.gr_inject, MtpRole::AttentionInject, (MtpKind::Bf16, 4, 10240)), + ] { + match matrix(role, shape) { + Ok(b) if std::ptr::eq(buffer, &*b) => {} + Ok(_) => { + crate::bringup_trace!( + "DBG scalar draft-kv matrix {role:?}: buffer is not the retained one" + ); + return Err(leleka_cuda_driver::Error::InvalidProjectionShape); + } + Err(e) => { + crate::bringup_trace!("DBG scalar draft-kv matrix {role:?} err {e:?}"); + return Err(leleka_cuda_driver::Error::InvalidProjectionShape); + } + } + } + Ok(()) + }) + .map_err(micro_driver_error)?; // Input/draft host policy and all eleven immutable device owners are live // throughout drain; never mint scalar committed products for prior rows. - let result=producer.record_scalar_prefill(&mut self.device,workspace,ring,prior,&next, - usize::try_from(txn.start_position()).map_err(|_|Error::Overflow)?,first_needed, - retained,policy,cancelled).map_err(micro_driver_error)?; - self.sources.validate(binding,dense)?;txn.validate_final(preview)?; - if !phase.same(&txn.phase()){return Err(Error::IdentityMismatch)} - Ok(match result{ - DraftKvOutcome::Fallback(reason)=>OriginalPromptDraftOutcome::Fallback(reason), - DraftKvOutcome::Skipped=>OriginalPromptDraftOutcome::Skipped, - DraftKvOutcome::Cancelled=>OriginalPromptDraftOutcome::Cancelled, - DraftKvOutcome::Completed(completed)=>{ - let pending=OriginalDraftKvPending{binding:binding.identity(),phase, - first:txn.start_position(),end:txn.end_position(),last_next,completed}; - pending.validate_current(binding,txn,preview,ring)?; + let result = producer + .record_scalar_prefill( + &mut self.device, + workspace, + ring, + prior, + &next, + usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?, + first_needed, + retained, + policy, + cancelled, + ) + .map_err(micro_driver_error)?; + self.sources.validate(binding, dense)?; + txn.validate_final(preview)?; + if !phase.same(&txn.phase()) { + return Err(Error::IdentityMismatch); + } + Ok(match result { + DraftKvOutcome::Fallback(reason) => OriginalPromptDraftOutcome::Fallback(reason), + DraftKvOutcome::Skipped => OriginalPromptDraftOutcome::Skipped, + DraftKvOutcome::Cancelled => OriginalPromptDraftOutcome::Cancelled, + DraftKvOutcome::Completed(completed) => { + let pending = OriginalDraftKvPending { + binding: binding.identity(), + phase, + first: txn.start_position(), + end: txn.end_position(), + last_next, + completed, + }; + pending.validate_current(binding, txn, preview, ring)?; OriginalPromptDraftOutcome::Completed(pending) } }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs index b2398936..1ea40455 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_mtp_verified_adapter.rs @@ -3,87 +3,145 @@ //! again. These receipts encode that order, so a pre-commit verifier window //! cannot accidentally launch a draft against an unpublished target branch. -use super::{contract::{Error,Result},executor::{TargetStepProduct,original_prompt::OriginalPromptExecutor}, - session::{QwenSession,TargetStepOrigin,original_prompt::draft::OriginalDraftSession}}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,ModelBinding}; -use leleka_cuda_driver::{Context,CompletedOriginalMtpDraft,NativeHeadSelection,OriginalGpuEvent,OriginalMtpFullPolicy, - OriginalVerifyWindow,SamplerParams}; +use super::{ + contract::{Error, Result}, + executor::{TargetStepProduct, original_prompt::OriginalPromptExecutor}, + session::{QwenSession, TargetStepOrigin, original_prompt::draft::OriginalDraftSession}, +}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding}; +use leleka_cuda_driver::{ + CompletedOriginalMtpDraft, Context, NativeHeadSelection, OriginalGpuEvent, OriginalMtpFullPolicy, + OriginalVerifyWindow, SamplerParams, +}; /// One completed `Verifier::run` receipt, before the target commit. It owns /// the actual residual window and sampled target rows; the caller may only /// transform it into `OriginalCommittedMtpReceipt` after verifier commit has /// advanced the real target session. -pub(in crate::qwen_forward) struct OriginalVerifiedMtpReceipt<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,window:OriginalVerifyWindow<'ctx>, - selection:NativeHeadSelection,before:TargetStepOrigin,first:usize,accepted_row:usize, +pub(in crate::qwen_forward) struct OriginalVerifiedMtpReceipt<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + before: TargetStepOrigin, + first: usize, + accepted_row: usize, } /// The same physical verifier window after its target `commit(a + 1)`. /// Target publication belongs to the verifier owner; this is a validation /// receipt, not a target-state mutator. -pub(in crate::qwen_forward) struct OriginalCommittedMtpReceipt<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,window:OriginalVerifyWindow<'ctx>, - selection:NativeHeadSelection,before:TargetStepOrigin,committed:TargetStepOrigin, - accepted_row:usize, +pub(in crate::qwen_forward) struct OriginalCommittedMtpReceipt<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + before: TargetStepOrigin, + committed: TargetStepOrigin, + accepted_row: usize, } /// Completed source draft kept as one opaque receipt. Prediction IDs, /// probabilities, physical MTP snapshot, and the exact committed target /// branch remain inseparable until the next target verifier consumes it. -pub(in crate::qwen_forward) struct OriginalMtpDraftReceipt<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,origin:TargetStepOrigin, - completed:CompletedOriginalMtpDraft<'ctx>, +pub(in crate::qwen_forward) struct OriginalMtpDraftReceipt<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + origin: TargetStepOrigin, + completed: CompletedOriginalMtpDraft<'ctx>, } -impl<'ctx> OriginalMtpDraftReceipt<'ctx>{ - pub(in crate::qwen_forward) fn ids(&self)->&[i32]{self.completed.ids()} - pub(in crate::qwen_forward) fn probabilities(&self)->&[f32]{self.completed.probabilities()} - pub(in crate::qwen_forward) fn count(&self)->usize{self.completed.count()} - pub(in crate::qwen_forward) fn first_position(&self)->usize{self.completed.first_position()} - pub(in crate::qwen_forward) fn accepted_row(&self)->usize{self.completed.accepted_row()} +impl<'ctx> OriginalMtpDraftReceipt<'ctx> { + pub(in crate::qwen_forward) fn ids(&self) -> &[i32] { + self.completed.ids() + } + pub(in crate::qwen_forward) fn probabilities(&self) -> &[f32] { + self.completed.probabilities() + } + pub(in crate::qwen_forward) fn count(&self) -> usize { + self.completed.count() + } + pub(in crate::qwen_forward) fn first_position(&self) -> usize { + self.completed.first_position() + } + pub(in crate::qwen_forward) fn accepted_row(&self) -> usize { + self.completed.accepted_row() + } /// The next verifier may read these predictions only while the real target /// prefix still equals the commit that produced this draft. The MTP ring /// intentionally contains provisional catch-up cells past target position. - pub(in crate::qwen_forward) fn validate_current(&self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>)->Result<()> { - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - draft.with_mtp_current_ring(binding,session,&self.origin,|ring,_|self.completed.validate_current(ring).map_err(driver_error)) + pub(in crate::qwen_forward) fn validate_current( + &self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + ) -> Result<()> { + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, session.mtp_context()?) { + return Err(Error::IdentityMismatch); + } + draft.with_mtp_current_ring(binding, session, &self.origin, |ring, _| { + self.completed.validate_current(ring).map_err(driver_error) + }) } } -impl<'ctx> OriginalVerifiedMtpReceipt<'ctx>{ - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection, - accepted_row:usize)->Result{ - let before=session.target_origin()?; +impl<'ctx> OriginalVerifiedMtpReceipt<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + accepted_row: usize, + ) -> Result { + let before = session.target_origin()?; window.validate_context(context).map_err(driver_error)?; window.validate_selection(&selection).map_err(driver_error)?; - let first=window.first_position(); - if !std::ptr::eq(context,session.mtp_context()?)||first!=usize::try_from(before.next_position()).map_err(|_|Error::Overflow)? - ||accepted_row>=window.rows(){return Err(Error::IdentityMismatch);} - Ok(Self{binding:binding.identity(),context,window,selection,before,first,accepted_row}) + let first = window.first_position(); + if !std::ptr::eq(context, session.mtp_context()?) + || first != usize::try_from(before.next_position()).map_err(|_| Error::Overflow)? + || accepted_row >= window.rows() + { + return Err(Error::IdentityMismatch); + } + Ok(Self { binding: binding.identity(), context, window, selection, before, first, accepted_row }) } /// Must be called after the genuine verifier has committed exactly the /// source accept count through `QwenChunkTxn::publish_verified_joint`. /// The resulting `TargetStepProduct` rejects skipped, extra, manually /// advanced, or cross-branch target publication before MTP capture. - pub(in crate::qwen_forward) fn after_target_commit(self,binding:&ModelBinding, - session:&QwenSession<'ctx>,committed_source:&TargetStepProduct)->Result>{ - let committed=session.target_origin()?; - let (_,source_position,_,source_origin)=committed_source.mtp_source(binding,session)?; + pub(in crate::qwen_forward) fn after_target_commit( + self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + committed_source: &TargetStepProduct, + ) -> Result> { + let committed = session.target_origin()?; + let (_, source_position, _, source_origin) = committed_source.mtp_source(binding, session)?; self.before.validate_projection_branch(session)?; - let expected=self.first.checked_add(self.accepted_row).and_then(|n|n.checked_add(1)).ok_or(Error::Overflow)?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?) - ||!self.before.same_session(&committed)||!source_origin.same_prefix(&committed) - ||source_position.get().checked_add(1).ok_or(Error::Overflow)?!=committed.next_position() - ||usize::try_from(committed.next_position()).map_err(|_|Error::Overflow)?!=expected{ + let expected = + self.first.checked_add(self.accepted_row).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, session.mtp_context()?) + || !self.before.same_session(&committed) + || !source_origin.same_prefix(&committed) + || source_position.get().checked_add(1).ok_or(Error::Overflow)? != committed.next_position() + || usize::try_from(committed.next_position()).map_err(|_| Error::Overflow)? != expected + { return Err(Error::IdentityMismatch); } - Ok(OriginalCommittedMtpReceipt{binding:self.binding,context:self.context,window:self.window, - selection:self.selection,before:self.before,committed,accepted_row:self.accepted_row}) + Ok(OriginalCommittedMtpReceipt { + binding: self.binding, + context: self.context, + window: self.window, + selection: self.selection, + before: self.before, + committed, + accepted_row: self.accepted_row, + }) } } -impl<'ctx> OriginalCommittedMtpReceipt<'ctx>{ +impl<'ctx> OriginalCommittedMtpReceipt<'ctx> { /// The receipt of a completed verifier window whose accepted prefix the session ALREADY holds. /// The serve path publishes the session when the commit event completes (the accepted state is read /// back from the verifier then), so the draft is requested with the pre-window origin captured at @@ -91,31 +149,51 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx>{ /// same acceptance rules as `after_target_commit`, without a `TargetStepProduct` (the native verifier /// has none): same session and branch, the window started where the session stood, and the session now /// stands exactly `accepted_row + 1` rows later. - pub(in crate::qwen_forward) fn for_published_window(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection, - before:TargetStepOrigin,accepted_row:usize)->Result{ - let committed=session.target_origin()?; + pub(in crate::qwen_forward) fn for_published_window( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + before: TargetStepOrigin, + accepted_row: usize, + ) -> Result { + let committed = session.target_origin()?; window.validate_context(context).map_err(driver_error)?; window.validate_selection(&selection).map_err(driver_error)?; - let first=u64::try_from(window.first_position()).map_err(|_|Error::Overflow)?; - let expected=first.checked_add(accepted_row as u64).and_then(|n|n.checked_add(1)).ok_or(Error::Overflow)?; - if !std::ptr::eq(context,session.mtp_context()?)||accepted_row>=window.rows() - ||!before.same_session(&committed)||before.next_position()!=first||committed.next_position()!=expected{ + let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?; + let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?; + if !std::ptr::eq(context, session.mtp_context()?) + || accepted_row >= window.rows() + || !before.same_session(&committed) + || before.next_position() != first + || committed.next_position() != expected + { return Err(Error::IdentityMismatch); } before.validate_projection_branch(session)?; - Ok(Self{binding:binding.identity(),context,window,selection,before,committed,accepted_row}) + Ok(Self { binding: binding.identity(), context, window, selection, before, committed, accepted_row }) } - fn validate(&self,binding:&ModelBinding,session:&QwenSession<'ctx>,context:&Context<'ctx>)->Result<()> { + fn validate(&self, binding: &ModelBinding, session: &QwenSession<'ctx>, context: &Context<'ctx>) -> Result<()> { self.window.validate_context(context).map_err(driver_error)?; self.window.validate_selection(&self.selection).map_err(driver_error)?; - let expected=self.window.first_position().checked_add(self.accepted_row).and_then(|n|n.checked_add(1)).ok_or(Error::Overflow)?; + let expected = self + .window + .first_position() + .checked_add(self.accepted_row) + .and_then(|n| n.checked_add(1)) + .ok_or(Error::Overflow)?; self.before.validate_projection_branch(session)?; self.committed.validate(session)?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context) - ||!std::ptr::eq(context,session.mtp_context()?)||!self.before.same_session(&self.committed) - ||usize::try_from(self.committed.next_position()).map_err(|_|Error::Overflow)?!=expected - ||self.accepted_row>=self.window.rows(){return Err(Error::IdentityMismatch);} + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, context) + || !std::ptr::eq(context, session.mtp_context()?) + || !self.before.same_session(&self.committed) + || usize::try_from(self.committed.next_position()).map_err(|_| Error::Overflow)? != expected + || self.accepted_row >= self.window.rows() + { + return Err(Error::IdentityMismatch); + } Ok(()) } } @@ -123,55 +201,80 @@ impl<'ctx> OriginalCommittedMtpReceipt<'ctx>{ /// A draft launched behind an enqueued, not yet published commit (`launch_committing_mtp`). It names the branch the /// session stood on and the one the commit publishes; `finish_committing_mtp` completes it only once the session /// holds exactly that second origin. -pub(in crate::qwen_forward) struct OriginalLaunchedMtpDraft{ - binding:BindingIdentity,before:TargetStepOrigin,prospective:TargetStepOrigin, +pub(in crate::qwen_forward) struct OriginalLaunchedMtpDraft { + binding: BindingIdentity, + before: TargetStepOrigin, + prospective: TargetStepOrigin, } -impl<'ctx> OriginalPromptExecutor<'ctx>{ +impl<'ctx> OriginalPromptExecutor<'ctx> { /// generate.cpp's order without the host wait between them: the verifier commit of `accepted_row + 1` rows is /// enqueued (`after` is its completion event, which the draft stream waits on the device) and the full MTP draft /// of the same completed window is enqueued behind it, while the session still stands at `before`. The same /// acceptance rules as `OriginalCommittedMtpReceipt::for_published_window`, with the published origin replaced by /// the one the commit will publish. #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn launch_committing_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,window:OriginalVerifyWindow<'ctx>, - selection:NativeHeadSelection,before:TargetStepOrigin,accepted_row:usize,min_p:f32, - policy:&OriginalMtpFullPolicy,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result{ + pub(in crate::qwen_forward) fn launch_committing_mtp( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + before: TargetStepOrigin, + accepted_row: usize, + min_p: f32, + policy: &OriginalMtpFullPolicy, + after: Option<&mut OriginalGpuEvent<'ctx>>, + ) -> Result { window.validate_context(self.context).map_err(driver_error)?; window.validate_selection(&selection).map_err(driver_error)?; - if !min_p.is_finite(){return Err(Error::InvalidDimension);} - let first=u64::try_from(window.first_position()).map_err(|_|Error::Overflow)?; - let prospective=session.original_origin_after(accepted_row.checked_add(1).ok_or(Error::Overflow)?)?; - let expected=first.checked_add(accepted_row as u64).and_then(|n|n.checked_add(1)).ok_or(Error::Overflow)?; - if !std::ptr::eq(self.context,session.mtp_context()?)||accepted_row>=window.rows() - ||before.next_position()!=first||prospective.next_position()!=expected{ + if !min_p.is_finite() { + return Err(Error::InvalidDimension); + } + let first = u64::try_from(window.first_position()).map_err(|_| Error::Overflow)?; + let prospective = session.original_origin_after(accepted_row.checked_add(1).ok_or(Error::Overflow)?)?; + let expected = first.checked_add(accepted_row as u64).and_then(|n| n.checked_add(1)).ok_or(Error::Overflow)?; + if !std::ptr::eq(self.context, session.mtp_context()?) + || accepted_row >= window.rows() + || before.next_position() != first + || prospective.next_position() != expected + { return Err(Error::IdentityMismatch); } before.validate(session)?; - let actor=self.mtp_actor(binding)?; - if actor.settings().max_drafts()<0{return Err(Error::InvalidDimension);} - draft.with_mtp_launch_ring(binding,session,&before,&prospective,|ring,prior|{ - actor.launch_draft_from_verifier(ring,prior,window,selection,accepted_row,min_p,policy,after) + let actor = self.mtp_actor(binding)?; + if actor.settings().max_drafts() < 0 { + return Err(Error::InvalidDimension); + } + draft.with_mtp_launch_ring(binding, session, &before, &prospective, |ring, prior| { + actor + .launch_draft_from_verifier(ring, prior, window, selection, accepted_row, min_p, policy, after) .map_err(driver_error) })?; - Ok(OriginalLaunchedMtpDraft{binding:binding.identity(),before,prospective}) + Ok(OriginalLaunchedMtpDraft { binding: binding.identity(), before, prospective }) } /// The second half of `launch_committing_mtp`, after the commit was published: the session must hold exactly the /// launched draft's prospective origin. Then the completion is published to the ring as `draft_committed_mtp` does. - pub(in crate::qwen_forward) fn finish_committing_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>,launched:OriginalLaunchedMtpDraft, - policy:&OriginalMtpFullPolicy)->Result>{ - let committed=session.target_origin()?; - if !launched.binding.matches(&binding.identity())||!launched.prospective.same_prefix(&committed){ + pub(in crate::qwen_forward) fn finish_committing_mtp( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + launched: OriginalLaunchedMtpDraft, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + let committed = session.target_origin()?; + if !launched.binding.matches(&binding.identity()) || !launched.prospective.same_prefix(&committed) { return Err(Error::IdentityMismatch); } - let actor=self.mtp_actor(binding)?; - let completed=draft.with_mtp_transition_ring(binding,session,&launched.before,&committed,|ring,prior|{ - actor.finish_draft_from_verifier(ring,prior,policy).map_err(driver_error) - })?; - draft.publish_mtp_completion(binding,session,&launched.before,&committed,&completed)?; - Ok(OriginalMtpDraftReceipt{binding:binding.identity(),context:self.context,origin:committed,completed}) + let actor = self.mtp_actor(binding)?; + let completed = + draft.with_mtp_transition_ring(binding, session, &launched.before, &committed, |ring, prior| { + actor.finish_draft_from_verifier(ring, prior, policy).map_err(driver_error) + })?; + draft.publish_mtp_completion(binding, session, &launched.before, &committed, &completed)?; + Ok(OriginalMtpDraftReceipt { binding: binding.identity(), context: self.context, origin: committed, completed }) } /// Literal source order: verifier completion -> target commit -> full MTP /// draft. This neither commits target state nor accepts tokens; both are @@ -179,62 +282,114 @@ impl<'ctx> OriginalPromptExecutor<'ctx>{ /// the coupled request/history come from the loaded actor (`set_max_drafts`, /// `set_draft_sampling`, `set_draft_history`), as in `MtpDrafter::draft`. #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn draft_committed_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>, - receipt:OriginalCommittedMtpReceipt<'ctx>,min_p:f32,policy:&OriginalMtpFullPolicy) - ->Result>{ - receipt.validate(binding,session,self.context)?; - if !min_p.is_finite(){return Err(Error::InvalidDimension);} - let actor=self.mtp_actor(binding)?; - if actor.settings().max_drafts()<0{return Err(Error::InvalidDimension);} - let completed=draft.with_mtp_transition_ring(binding,session,&receipt.before,&receipt.committed,|ring,prior|{ - actor.draft_from_verifier(ring,prior,receipt.window,receipt.selection, - receipt.accepted_row,min_p,policy).map_err(driver_error) - })?; - draft.publish_mtp_completion(binding,session,&receipt.before,&receipt.committed,&completed)?; - Ok(OriginalMtpDraftReceipt{binding:binding.identity(),context:self.context,origin:receipt.committed,completed}) + pub(in crate::qwen_forward) fn draft_committed_mtp( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + receipt: OriginalCommittedMtpReceipt<'ctx>, + min_p: f32, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + receipt.validate(binding, session, self.context)?; + if !min_p.is_finite() { + return Err(Error::InvalidDimension); + } + let actor = self.mtp_actor(binding)?; + if actor.settings().max_drafts() < 0 { + return Err(Error::InvalidDimension); + } + let completed = + draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { + actor + .draft_from_verifier( + ring, + prior, + receipt.window, + receipt.selection, + receipt.accepted_row, + min_p, + policy, + ) + .map_err(driver_error) + })?; + draft.publish_mtp_completion(binding, session, &receipt.before, &receipt.committed, &completed)?; + Ok(OriginalMtpDraftReceipt { + binding: binding.identity(), + context: self.context, + origin: receipt.committed, + completed, + }) } /// generate.cpp `mtp.draft_first(o.spec, ss.R, x, p - 1, drafts, ...)`: the /// first round after the prompt, from the single-row verifier window of the /// final prompt seed (the Original repeat-row path), not `draft`'s catch-up. /// Same order and receipts as `draft_committed_mtp`; `rows` is `T`. #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn draft_first_committed_mtp(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,draft:&mut OriginalDraftSession<'ctx>, - receipt:OriginalCommittedMtpReceipt<'ctx>,rows:usize,min_p:f32,policy:&OriginalMtpFullPolicy) - ->Result>{ - receipt.validate(binding,session,self.context)?; - if !min_p.is_finite()||receipt.accepted_row!=0||receipt.window.rows()!=1{return Err(Error::InvalidDimension);} - let actor=self.mtp_actor(binding)?; - if actor.settings().max_drafts()<0{return Err(Error::InvalidDimension);} - let completed=draft.with_mtp_transition_ring(binding,session,&receipt.before,&receipt.committed,|ring,prior|{ - actor.draft_first_from_verifier(ring,prior,receipt.window,receipt.selection,rows,min_p,policy) - .map_err(driver_error) - })?; - draft.publish_mtp_completion(binding,session,&receipt.before,&receipt.committed,&completed)?; - Ok(OriginalMtpDraftReceipt{binding:binding.identity(),context:self.context,origin:receipt.committed,completed}) + pub(in crate::qwen_forward) fn draft_first_committed_mtp( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + draft: &mut OriginalDraftSession<'ctx>, + receipt: OriginalCommittedMtpReceipt<'ctx>, + rows: usize, + min_p: f32, + policy: &OriginalMtpFullPolicy, + ) -> Result> { + receipt.validate(binding, session, self.context)?; + if !min_p.is_finite() || receipt.accepted_row != 0 || receipt.window.rows() != 1 { + return Err(Error::InvalidDimension); + } + let actor = self.mtp_actor(binding)?; + if actor.settings().max_drafts() < 0 { + return Err(Error::InvalidDimension); + } + let completed = + draft.with_mtp_transition_ring(binding, session, &receipt.before, &receipt.committed, |ring, prior| { + actor + .draft_first_from_verifier(ring, prior, receipt.window, receipt.selection, rows, min_p, policy) + .map_err(driver_error) + })?; + draft.publish_mtp_completion(binding, session, &receipt.before, &receipt.committed, &completed)?; + Ok(OriginalMtpDraftReceipt { + binding: binding.identity(), + context: self.context, + origin: receipt.committed, + completed, + }) } /// `mtp.set_draft_sampling(req_sp)` (a no-op unless coupled setup succeeded). - pub(in crate::qwen_forward) fn set_mtp_draft_sampling(&mut self,binding:&ModelBinding, - params:&SamplerParams)->Result<()> { - self.mtp_actor(binding)?.set_draft_sampling(params);Ok(()) + pub(in crate::qwen_forward) fn set_mtp_draft_sampling( + &mut self, + binding: &ModelBinding, + params: &SamplerParams, + ) -> Result<()> { + self.mtp_actor(binding)?.set_draft_sampling(params); + Ok(()) } /// `mtp.set_draft_history(consumed, n, next)` before the next draft. - pub(in crate::qwen_forward) fn set_mtp_draft_history(&mut self,binding:&ModelBinding, - tail:&[i32],next:i32)->Result<()> { - self.mtp_actor(binding)?.set_draft_history(tail,next).map_err(driver_error) + pub(in crate::qwen_forward) fn set_mtp_draft_history( + &mut self, + binding: &ModelBinding, + tail: &[i32], + next: i32, + ) -> Result<()> { + self.mtp_actor(binding)?.set_draft_history(tail, next).map_err(driver_error) } } -fn driver_error(error:leleka_cuda_driver::Error)->Error{ - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} - match error{ - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize - |leleka_cuda_driver::Error::InvalidProjectionShape=>Error::InvalidDimension, - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::UnsupportedQwenOperation=>Error::Unsupported(super::contract::Stage::Session), - leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite, - _=>Error::CudaExecution, +fn driver_error(error: leleka_cuda_driver::Error) -> Error { + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } + match error { + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + leleka_cuda_driver::Error::InvalidQwenShape + | leleka_cuda_driver::Error::InvalidSize + | leleka_cuda_driver::Error::InvalidProjectionShape => Error::InvalidDimension, + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(super::contract::Stage::Session), + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + _ => Error::CudaExecution, } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_prompt_embedding.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_prompt_embedding.rs index 64bdae1a..18eca93b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_prompt_embedding.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_prompt_embedding.rs @@ -1,79 +1,154 @@ //! Genuine native token table owner loaded before the expert cache budget is //! planned. It is tied to one admitted model and the actual CUDA context. use super::*; -use leleka_cuda_driver::{Context,DeviceBuffer,OriginalMtpEmbedding}; -pub(in crate::qwen_forward) struct OriginalPromptEmbedding<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,table:Option>>, - kind:i32,row_bytes:usize,vocabulary:usize,failed:bool, +use leleka_cuda_driver::{Context, DeviceBuffer, OriginalMtpEmbedding}; +pub(in crate::qwen_forward) struct OriginalPromptEmbedding<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + table: Option>>, + kind: i32, + row_bytes: usize, + vocabulary: usize, + failed: bool, } -impl<'ctx> OriginalPromptEmbedding<'ctx>{ - pub(in crate::qwen_forward) fn load(binding:&ModelBinding,context:&'ctx Context<'ctx>)->Result{ - let(kind,row_bytes,vocabulary,bytes)=binding.native_embedding_layout().map_err(|_|Error::InputRead)?; - let kind=i32::try_from(kind).map_err(|_|Error::InvalidDimension)?; - let mut table=context.allocate(bytes).map_err(driver_error)?; +impl<'ctx> OriginalPromptEmbedding<'ctx> { + pub(in crate::qwen_forward) fn load(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { + let (kind, row_bytes, vocabulary, bytes) = binding.native_embedding_layout().map_err(|_| Error::InputRead)?; + let kind = i32::try_from(kind).map_err(|_| Error::InvalidDimension)?; + let mut table = context.allocate(bytes).map_err(driver_error)?; // Admit the genuine gather shape before reading any source bytes. - OriginalMtpEmbedding::native(&table,kind,row_bytes,vocabulary).map_err(driver_error)?; - let mut source=Vec::new();source.try_reserve_exact(bytes).map_err(|_|Error::InputAllocation)?; - let read=binding.stream_native_embedding(|chunk|{ - source.len().checked_add(chunk.len()).filter(|end|*end<=bytes) - .ok_or_else(||std::io::Error::from(std::io::ErrorKind::InvalidData))?; - source.extend_from_slice(chunk);Ok(()) + OriginalMtpEmbedding::native(&table, kind, row_bytes, vocabulary).map_err(driver_error)?; + let mut source = Vec::new(); + source.try_reserve_exact(bytes).map_err(|_| Error::InputAllocation)?; + let read = binding.stream_native_embedding(|chunk| { + source + .len() + .checked_add(chunk.len()) + .filter(|end| *end <= bytes) + .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidData))?; + source.extend_from_slice(chunk); + Ok(()) }); - read.map_err(|_|Error::InputRead)?; - if source.len()!=bytes{return Err(Error::InputRead);} + read.map_err(|_| Error::InputRead)?; + if source.len() != bytes { + return Err(Error::InputRead); + } // One whole native table upload; file read chunks do not create new // CUDA copies or synchronization boundaries. table.copy_from_owned(source).map_err(driver_error)?; - Ok(Self{binding:binding.identity(),context,table:Some(std::rc::Rc::new(table)),kind,row_bytes,vocabulary,failed:false}) + Ok(Self { + binding: binding.identity(), + context, + table: Some(std::rc::Rc::new(table)), + kind, + row_bytes, + vocabulary, + failed: false, + }) } /// `LELEKA_PROMPT_EMBED_ALIAS=1` (EXPERIMENTAL, off by default): the prompt path reads the same token table through the mapped /// host copy the native embedding already holds, instead of a second 324 MiB copy in VRAM (and a second 322 MiB read at load). /// Prefill gathers 8192 rows of 1,360 B per chunk (11 MB over PCIe); the MTP drafter's per-round row is one more. - pub(in crate::qwen_forward) fn alias_enabled()->bool{ + pub(in crate::qwen_forward) fn alias_enabled() -> bool { crate::settings::process().kv.prompt_embed_alias } /// The same table, aliased onto `native` (its mapped host copy or device fallback). Identity is checked against the binding's own /// layout so a different tensor can never be aliased. `native` must outlive every use: close this owner first. - pub(in crate::qwen_forward) fn alias_native(binding:&ModelBinding,context:&'ctx Context<'ctx>,native:&leleka_cuda_driver::OriginalNativeEmbed<'ctx>)->Result{ - let(kind,row_bytes,vocabulary,bytes)=binding.native_embedding_layout().map_err(|_|Error::InputRead)?; - let kind=i32::try_from(kind).map_err(|_|Error::InvalidDimension)?; - if i64::from(native.kind())!=i64::from(kind)||native.bytes()!=bytes{return Err(Error::IdentityMismatch);} - let table=native.table_alias().map_err(driver_error)?; - OriginalMtpEmbedding::native(&table,kind,row_bytes,vocabulary).map_err(driver_error)?; - Ok(Self{binding:binding.identity(),context,table:Some(std::rc::Rc::new(table)),kind,row_bytes,vocabulary,failed:false}) + pub(in crate::qwen_forward) fn alias_native( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + native: &leleka_cuda_driver::OriginalNativeEmbed<'ctx>, + ) -> Result { + let (kind, row_bytes, vocabulary, bytes) = binding.native_embedding_layout().map_err(|_| Error::InputRead)?; + let kind = i32::try_from(kind).map_err(|_| Error::InvalidDimension)?; + if i64::from(native.kind()) != i64::from(kind) || native.bytes() != bytes { + return Err(Error::IdentityMismatch); + } + let table = native.table_alias().map_err(driver_error)?; + OriginalMtpEmbedding::native(&table, kind, row_bytes, vocabulary).map_err(driver_error)?; + Ok(Self { + binding: binding.identity(), + context, + table: Some(std::rc::Rc::new(table)), + kind, + row_bytes, + vocabulary, + failed: false, + }) } - pub(in crate::qwen_forward) fn borrow(&self,binding:&ModelBinding,context:&Context<'ctx>)->Result>{ - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch);} - OriginalMtpEmbedding::native(self.table.as_ref().ok_or(Error::IdentityMismatch)?,self.kind,self.row_bytes,self.vocabulary) - .map_err(driver_error) + pub(in crate::qwen_forward) fn borrow( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + ) -> Result> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(context, self.context) { + return Err(Error::IdentityMismatch); + } + OriginalMtpEmbedding::native( + self.table.as_ref().ok_or(Error::IdentityMismatch)?, + self.kind, + self.row_bytes, + self.vocabulary, + ) + .map_err(driver_error) + } + pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { + self.table.as_ref().map_or(0, |table| table.len()) } - pub(in crate::qwen_forward) fn allocated_bytes(&self)->usize{self.table.as_ref().map_or(0,|table|table.len())} /// Graph resources retain the exact allocation admitted above; neither an /// integer address nor a short-lived embedding descriptor owns the table. - pub(in crate::qwen_forward) fn retain(&self,binding:&ModelBinding,context:&Context<'ctx>) - ->Result<(std::rc::Rc>,i32,usize,usize)>{ - self.borrow(binding,context)?; - Ok((std::rc::Rc::clone(self.table.as_ref().ok_or(Error::IdentityMismatch)?),self.kind,self.row_bytes,self.vocabulary)) + pub(in crate::qwen_forward) fn retain( + &self, + binding: &ModelBinding, + context: &Context<'ctx>, + ) -> Result<(std::rc::Rc>, i32, usize, usize)> { + self.borrow(binding, context)?; + Ok(( + std::rc::Rc::clone(self.table.as_ref().ok_or(Error::IdentityMismatch)?), + self.kind, + self.row_bytes, + self.vocabulary, + )) + } + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + match self.table.take() { + Some(table) => match std::rc::Rc::try_unwrap(table) { + Ok(table) => table.release().map_err(driver_error), + Err(_) => Ok(()), + }, + None => Ok(()), + } + } +} +impl Drop for OriginalPromptEmbedding<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); } - pub(in crate::qwen_forward) fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{self.failed=true;match self.table.take(){ - Some(table)=>match std::rc::Rc::try_unwrap(table){Ok(table)=>table.release().map_err(driver_error),Err(_)=>Ok(())},None=>Ok(())}} } -impl Drop for OriginalPromptEmbedding<'_>{fn drop(&mut self){let _=self.close_inner();}} /// The switch's reading: only an explicit yes turns the alias on. #[cfg(test)] -fn alias_requested(value:Option<&str>)->bool{ - crate::settings::text_is_one_of(value,&crate::settings::PROMPT_EMBED_ALIAS_ON) +fn alias_requested(value: Option<&str>) -> bool { + crate::settings::text_is_one_of(value, &crate::settings::PROMPT_EMBED_ALIAS_ON) } #[cfg(test)] -mod tests{ +mod tests { use super::alias_requested; #[test] - fn the_token_table_alias_is_opt_in(){ + fn the_token_table_alias_is_opt_in() { assert!(!alias_requested(None)); - for off in ["","0","off","no","true","2"]{assert!(!alias_requested(Some(off)),"{off}");} - for on in ["1","on","yes"]{assert!(alias_requested(Some(on)),"{on}");} + for off in ["", "0", "off", "no", "true", "2"] { + assert!(!alias_requested(Some(off)), "{off}"); + } + for on in ["1", "on", "yes"] { + assert!(alias_requested(Some(on)), "{on}"); + } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_sampled_serve.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_sampled_serve.rs index 11d773c9..b065617e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_sampled_serve.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_sampled_serve.rs @@ -112,7 +112,9 @@ impl SampledServe { #[cfg(test)] mod tests { - use super::super::original_sampler::{PENALTY_WINDOW_CAP, coupled_hist_base, penalty_rows, request_params, target_params}; + use super::super::original_sampler::{ + PENALTY_WINDOW_CAP, coupled_hist_base, penalty_rows, request_params, target_params, + }; use super::*; fn request() -> SamplerParams { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_sampler.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_sampler.rs index 95eac7e4..465e6630 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_sampler.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_sampler.rs @@ -1,59 +1,80 @@ //! Literal Original sampler host histories and absolute coupled draw positions. //! These are metadata helpers, never model/session/commit capabilities. The //! caller must pass the actual consumed tail and genuine current verify window. -use leleka_cuda_driver::SamplerParams; use super::contract::{Error, Result}; +use leleka_cuda_driver::SamplerParams; pub(crate) const PENALTY_WINDOW_CAP: usize = 4096; /// Original serve's seed==0 fallback takes the actual steady clock tick supplied /// by the operator adapter. It is resolved once, never per draft or GPU row. -pub(crate) fn request_params(params: SamplerParams, steady_clock_tick:u64)->Result { - let mut p=params.for_request().map_err(|_|Error::InvalidDimension)?; - if p.seed==0{p.seed=steady_clock_tick;}p.counter=0;Ok(p) +pub(crate) fn request_params(params: SamplerParams, steady_clock_tick: u64) -> Result { + let mut p = params.for_request().map_err(|_| Error::InvalidDimension)?; + if p.seed == 0 { + p.seed = steady_clock_tick; + } + p.counter = 0; + Ok(p) } /// Target verifier counter is pos0 + t. One immutable parameter record per call. -pub(crate) fn target_params(mut p:SamplerParams,pos0:usize,rows:usize)->Result { - if rows==0||rows>64{return Err(Error::InvalidDimension);} - pos0.checked_add(rows-1).ok_or(Error::Overflow)?; - p.counter=u64::try_from(pos0).map_err(|_|Error::Overflow)?;Ok(p) +pub(crate) fn target_params(mut p: SamplerParams, pos0: usize, rows: usize) -> Result { + if rows == 0 || rows > 64 { + return Err(Error::InvalidDimension); + } + pos0.checked_add(rows - 1).ok_or(Error::Overflow)?; + p.counter = u64::try_from(pos0).map_err(|_| Error::Overflow)?; + Ok(p) } -pub(crate) fn penalty_rows(tail:&[i32],window:&[i32],h:usize)->Result> { - if window.is_empty()||window.len()>64||h>PENALTY_WINDOW_CAP{return Err(Error::InvalidDimension);} - let count=window.len().checked_mul(h).ok_or(Error::Overflow)?; - let mut out=Vec::new();out.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?;out.resize(count,-1); - for t in 0..window.len(){ - let avail=tail.len().checked_add(t+1).ok_or(Error::Overflow)?; - let take=h.min(avail); +pub(crate) fn penalty_rows(tail: &[i32], window: &[i32], h: usize) -> Result> { + if window.is_empty() || window.len() > 64 || h > PENALTY_WINDOW_CAP { + return Err(Error::InvalidDimension); + } + let count = window.len().checked_mul(h).ok_or(Error::Overflow)?; + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + out.resize(count, -1); + for t in 0..window.len() { + let avail = tail.len().checked_add(t + 1).ok_or(Error::Overflow)?; + let take = h.min(avail); for j in 0..take { - let i=avail-take+j; - out[t*h+h-take+j]=if iusize { - if penalty_last_n<=0{0}else{(penalty_last_n as usize).min(PENALTY_WINDOW_CAP)} +pub(crate) fn coupled_hist_len(penalty_last_n: i32) -> usize { + if penalty_last_n <= 0 { 0 } else { (penalty_last_n as usize).min(PENALTY_WINDOW_CAP) } } -pub(crate) fn coupled_hist_base(tail:&[i32],next:i32,penalty_last_n:i32)->Result<[i32;PENALTY_WINDOW_CAP]> { - let h=coupled_hist_len(penalty_last_n);let mut base=[-1;PENALTY_WINDOW_CAP]; - if h>0{let rows=penalty_rows(tail,&[next],h)?;base[PENALTY_WINDOW_CAP-h..].copy_from_slice(&rows);}Ok(base) +pub(crate) fn coupled_hist_base(tail: &[i32], next: i32, penalty_last_n: i32) -> Result<[i32; PENALTY_WINDOW_CAP]> { + let h = coupled_hist_len(penalty_last_n); + let mut base = [-1; PENALTY_WINDOW_CAP]; + if h > 0 { + let rows = penalty_rows(tail, &[next], h)?; + base[PENALTY_WINDOW_CAP - h..].copy_from_slice(&rows); + } + Ok(base) } /// The original cell pairs residual c with token c+1; it predicts c+2. /// The verifying target draw for that draft is exactly counter c+1. -pub(crate) fn coupled_draft_cell(p:usize,accepted:usize,j:usize)->Result { - p.checked_add(accepted).and_then(|n|n.checked_add(j)).and_then(|n|i32::try_from(n).ok()).ok_or(Error::Overflow) +pub(crate) fn coupled_draft_cell(p: usize, accepted: usize, j: usize) -> Result { + p.checked_add(accepted).and_then(|n| n.checked_add(j)).and_then(|n| i32::try_from(n).ok()).ok_or(Error::Overflow) } /// `(uint64_t)(cell + 1)`. Cell -1 is real: `draft_first` for a window at p = 0 drafts from /// cell p - 1, whose verifying row draws counter 0. Anything below -1 has no Original meaning. -pub(crate) fn coupled_draft_counter(cell:i32)->Result { - if cell< -1{return Err(Error::InvalidDimension);}Ok((i64::from(cell)+1) as u64) +pub(crate) fn coupled_draft_counter(cell: i32) -> Result { + if cell < -1 { + return Err(Error::InvalidDimension); + } + Ok((i64::from(cell) + 1) as u64) } -pub(crate) fn coupled_hist_start(j:usize,h:usize)->Result { - if j>=8||h>PENALTY_WINDOW_CAP{return Err(Error::InvalidDimension);} - PENALTY_WINDOW_CAP.checked_add(j).and_then(|n|n.checked_sub(h)).ok_or(Error::Overflow) +pub(crate) fn coupled_hist_start(j: usize, h: usize) -> Result { + if j >= 8 || h > PENALTY_WINDOW_CAP { + return Err(Error::InvalidDimension); + } + PENALTY_WINDOW_CAP.checked_add(j).and_then(|n| n.checked_sub(h)).ok_or(Error::Overflow) } #[cfg(test)] @@ -61,50 +82,93 @@ mod tests { use super::*; #[test] fn original_history_first_coupled_absolute_counter_and_request_boundary() { - let tail=[3,7,3,11];let window=[19,7,23];let h=7; + let tail = [3, 7, 3, 11]; + let window = [19, 7, 23]; + let h = 7; // Independent concatenate/take-last specification before candidate. - let mut expected=Vec::new(); - for t in 0..window.len(){let mut consumed=tail.to_vec();consumed.extend_from_slice(&window[..=t]);let start=consumed.len().saturating_sub(h);expected.extend(std::iter::repeat_n(-1,h-(consumed.len()-start)));expected.extend_from_slice(&consumed[start..]);} - assert_eq!(&*penalty_rows(&tail,&window,h).expect("rows"),expected); - let base=coupled_hist_base(&tail,19,h as i32).expect("base");assert_eq!(&base[PENALTY_WINDOW_CAP-h..],&expected[..h]); - for accepted in 0..=8 {for j in 0..8 {let cell=coupled_draft_cell(123,accepted,j).expect("cell");assert_eq!(coupled_draft_counter(cell).expect("counter"),124+accepted as u64+j as u64);}} - assert_eq!(&*penalty_rows(&[],&[5,9],3).expect("front pad"),&[-1,-1,5,-1,5,9]); - assert!(penalty_rows(&[],&[],1).is_err());assert!(penalty_rows(&[],&[1],4097).is_err());assert!(coupled_draft_cell(usize::MAX,1,0).is_err());assert_eq!(coupled_draft_counter(-1).expect("draft_first at p=0"),0);assert!(coupled_draft_counter(-2).is_err()); - let mut params=SamplerParams::default();params.temperature=0.0;let p=request_params(params,77).expect("request");assert!(p.greedy);assert_eq!(p.seed,77);assert_eq!(target_params(p,44,3).expect("counter").counter,44); + let mut expected = Vec::new(); + for t in 0..window.len() { + let mut consumed = tail.to_vec(); + consumed.extend_from_slice(&window[..=t]); + let start = consumed.len().saturating_sub(h); + expected.extend(std::iter::repeat_n(-1, h - (consumed.len() - start))); + expected.extend_from_slice(&consumed[start..]); + } + assert_eq!(&*penalty_rows(&tail, &window, h).expect("rows"), expected); + let base = coupled_hist_base(&tail, 19, h as i32).expect("base"); + assert_eq!(&base[PENALTY_WINDOW_CAP - h..], &expected[..h]); + for accepted in 0..=8 { + for j in 0..8 { + let cell = coupled_draft_cell(123, accepted, j).expect("cell"); + assert_eq!(coupled_draft_counter(cell).expect("counter"), 124 + accepted as u64 + j as u64); + } + } + assert_eq!(&*penalty_rows(&[], &[5, 9], 3).expect("front pad"), &[-1, -1, 5, -1, 5, 9]); + assert!(penalty_rows(&[], &[], 1).is_err()); + assert!(penalty_rows(&[], &[1], 4097).is_err()); + assert!(coupled_draft_cell(usize::MAX, 1, 0).is_err()); + assert_eq!(coupled_draft_counter(-1).expect("draft_first at p=0"), 0); + assert!(coupled_draft_counter(-2).is_err()); + let mut params = SamplerParams::default(); + params.temperature = 0.0; + let p = request_params(params, 77).expect("request"); + assert!(p.greedy); + assert_eq!(p.seed, 77); + assert_eq!(target_params(p, 44, 3).expect("counter").counter, 44); } - fn fixture()->serde_json::Value{ - serde_json::from_str(include_str!("../../../sampler-ref/tests/fixtures/sampler_oracle.json")).expect("oracle fixture") + fn fixture() -> serde_json::Value { + serde_json::from_str(include_str!("../../../sampler-ref/tests/fixtures/sampler_oracle.json")) + .expect("oracle fixture") + } + fn ints(v: &serde_json::Value) -> Vec { + v.as_array().expect("array").iter().map(|x| x.as_i64().expect("int") as i32).collect() } - fn ints(v:&serde_json::Value)->Vec{v.as_array().expect("array").iter().map(|x|x.as_i64().expect("int") as i32).collect()} /// The existing host helpers against the Original's own headers (`penalty_rows`, /// `coupled_hist_base`, `coupled_hist_len/start`, `coupled_draft_cell/counter`). #[test] fn host_helpers_match_the_original_headers_fixture() { - let f=fixture(); - let rows=f["penalty_rows"].as_array().expect("rows");assert!(rows.len()>=50); + let f = fixture(); + let rows = f["penalty_rows"].as_array().expect("rows"); + assert!(rows.len() >= 50); for c in rows { - let tail=ints(&c["tail"]);let window=ints(&c["window"]);let h=c["h"].as_u64().expect("h") as usize; - assert_eq!(&*penalty_rows(&tail,&window,h).expect("rows"),&ints(&c["rows"])[..]); - let next=c["next"].as_i64().expect("next") as i32; - let base=coupled_hist_base(&tail,next,h as i32).expect("base"); - assert_eq!(&base[PENALTY_WINDOW_CAP-h..],&ints(&c["base"])[..]); - assert!(base[..PENALTY_WINDOW_CAP-h].iter().all(|&v|v==-1)); + let tail = ints(&c["tail"]); + let window = ints(&c["window"]); + let h = c["h"].as_u64().expect("h") as usize; + assert_eq!(&*penalty_rows(&tail, &window, h).expect("rows"), &ints(&c["rows"])[..]); + let next = c["next"].as_i64().expect("next") as i32; + let base = coupled_hist_base(&tail, next, h as i32).expect("base"); + assert_eq!(&base[PENALTY_WINDOW_CAP - h..], &ints(&c["base"])[..]); + assert!(base[..PENALTY_WINDOW_CAP - h].iter().all(|&v| v == -1)); } - let counters=&f["counters"]; + let counters = &f["counters"]; for r in counters["cells"].as_array().expect("cells") { - let (p,a,j,cell,counter)=(r[0].as_i64().expect("p"),r[1].as_u64().expect("a") as usize,r[2].as_u64().expect("j") as usize,r[3].as_i64().expect("cell"),r[4].as_u64().expect("c")); - if p>i64::from(i32::MAX)/2{assert!(coupled_draft_cell(p as usize,a,j).is_err()||cell<=i64::from(i32::MAX));continue;} - let got=coupled_draft_cell(p as usize,a,j).expect("cell"); - assert_eq!(i64::from(got),cell);assert_eq!(coupled_draft_counter(got).expect("counter"),counter); + let (p, a, j, cell, counter) = ( + r[0].as_i64().expect("p"), + r[1].as_u64().expect("a") as usize, + r[2].as_u64().expect("j") as usize, + r[3].as_i64().expect("cell"), + r[4].as_u64().expect("c"), + ); + if p > i64::from(i32::MAX) / 2 { + assert!(coupled_draft_cell(p as usize, a, j).is_err() || cell <= i64::from(i32::MAX)); + continue; + } + let got = coupled_draft_cell(p as usize, a, j).expect("cell"); + assert_eq!(i64::from(got), cell); + assert_eq!(coupled_draft_counter(got).expect("counter"), counter); } for r in counters["hist_len"].as_array().expect("hist_len") { - let v=ints(r); - if v[1]==PENALTY_WINDOW_CAP as i32{assert_eq!(coupled_hist_len(v[0]) as i32,v[2],"{v:?}");} + let v = ints(r); + if v[1] == PENALTY_WINDOW_CAP as i32 { + assert_eq!(coupled_hist_len(v[0]) as i32, v[2], "{v:?}"); + } } for r in counters["hist_start"].as_array().expect("hist_start") { - let v=ints(r); - if v[0]==PENALTY_WINDOW_CAP as i32&&v[1]<8{assert_eq!(coupled_hist_start(v[1] as usize,v[2] as usize).expect("start") as i32,v[3]);} + let v = ints(r); + if v[0] == PENALTY_WINDOW_CAP as i32 && v[1] < 8 { + assert_eq!(coupled_hist_start(v[1] as usize, v[2] as usize).expect("start") as i32, v[3]); + } } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs index 54dad170..cf5fbfbb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config.rs @@ -2,8 +2,8 @@ //! context. Everything here is configuration, never a certificate: each value names the line of the //! Original it mirrors, so a hardware run can diff them against the CLI it is compared with. use super::contract::{Error, Result}; -use crate::settings::EnvSource; use crate::model_binding::qwen4exp_input::{ModelBinding, MoeMatrixRole}; +use crate::settings::EnvSource; use leleka_cuda_driver::{ DraftKvPolicy, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpScalarPolicy, OriginalVerifyExpertLayout, OriginalVerifyGeometry, OriginalVerifyRope, PrefillKvStage, PrefillLayoutOptions, SamplerParams, SamplerPath, @@ -44,7 +44,11 @@ pub(in crate::qwen_forward) struct ExpertBlobSizes { max_blob: usize, } impl ExpertBlobSizes { - pub(in crate::qwen_forward) fn from_layer_bytes(gate: [usize; 48], up: [usize; 48], down: [usize; 48]) -> Result { + pub(in crate::qwen_forward) fn from_layer_bytes( + gate: [usize; 48], + up: [usize; 48], + down: [usize; 48], + ) -> Result { let mut blob = [0usize; 48]; let roles = std::array::from_fn(|layer| [gate[layer], up[layer], down[layer]]); let (mut gate_up_max, mut down_max) = (0usize, 0usize); @@ -104,14 +108,17 @@ impl ExpertBlobSizes { } /// Every layer's gate/up/down lengths are whole 16-byte words summing to its blob (the copy kernel's precondition). pub(in crate::qwen_forward) fn spans_tile_blobs(&self) -> bool { - (0..48).all(|l| self.roles[l].iter().all(|b| b % 16 == 0) && self.roles[l].iter().sum::() == self.blob[l]) + (0..48) + .all(|l| self.roles[l].iter().all(|b| b % 16 == 0) && self.roles[l].iter().sum::() == self.blob[l]) } } /// The routed experts' ggml types per layer (`expert_layout().fmt[l]`), from the binding's own expert /// descriptors (expert 0 of each layer; every expert of a layer has the same shape and type). Gate and up /// share one type, as the verifier's grouped expert kernels require. -pub(in crate::qwen_forward) fn expert_formats(binding: &ModelBinding) -> Result { +pub(in crate::qwen_forward) fn expert_formats( + binding: &ModelBinding, +) -> Result { if binding.layer_count() != 48 { return Err(Error::InvalidDimension); } @@ -130,7 +137,8 @@ pub(in crate::qwen_forward) fn expert_formats(binding: &ModelBinding) -> Result< } formats[layer as usize] = (gate, down); } - leleka_cuda_driver::OriginalVerifyExpertFormats::new(formats, 2560, 640).map_err(|_| Error::Unsupported(super::contract::Stage::Executor)) + leleka_cuda_driver::OriginalVerifyExpertFormats::new(formats, 2560, 640) + .map_err(|_| Error::Unsupported(super::contract::Stage::Executor)) } /// The RoPE constants of the draft K/V append and the verifier's QSA indexer append: the analytic form @@ -152,7 +160,10 @@ impl RopeConstants { let serving = leleka_cuda_driver::serving_context(); Self::from_parts(serving.rope.freq_base, serving.rope_args) } - pub(in crate::qwen_forward) fn from_parts(freq_base: f64, args: leleka_context::rope_scaling::RopeKernelArgs) -> Self { + pub(in crate::qwen_forward) fn from_parts( + freq_base: f64, + args: leleka_context::rope_scaling::RopeKernelArgs, + ) -> Self { Self { theta_scale: (freq_base as f32).powf(-2.0f32 / N_ROT), freq_scale: args.freq_scale, @@ -263,7 +274,11 @@ pub(in crate::qwen_forward) fn greedy_params(seed: u64) -> SamplerParams { /// Verifier bank geometry (`Verifier::init`): the model-fixed shape constants of `OriginalVerifyLayout`, /// the window width, the serving cell count and the staging blob bound of the expert layout. -pub(in crate::qwen_forward) fn verify_geometry(max_t: usize, max_cells: usize, blobs: &ExpertBlobSizes) -> Result { +pub(in crate::qwen_forward) fn verify_geometry( + max_t: usize, + max_cells: usize, + blobs: &ExpertBlobSizes, +) -> Result { let geometry = OriginalVerifyGeometry { max_t, n: 2560, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs index 2bf077a0..7b5b6075 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_config/tests.rs @@ -23,7 +23,8 @@ fn the_legacy_footprint_switch_is_off_unless_asked_for() { use leleka_context::rope_scaling::RopeKernelArgs; fn blobs() -> ExpertBlobSizes { - ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap() + ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]) + .unwrap() } #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation.rs index ec6c1191..7bb68b87 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation.rs @@ -191,7 +191,9 @@ impl SessionEngine for Engine<'_, D> { Some(index) => { let saved = &self.saved[index]; if saved.ids.len() != resume { - return Err(ConvError("restoring the draft ring: the restored checkpoint is not the resume point".into())); + return Err(ConvError( + "restoring the draft ring: the restored checkpoint is not the resume point".into(), + )); } self.device.restore_draft(&saved.point, resume).map_err(|e| conv("restoring the draft ring", e)) } @@ -268,7 +270,11 @@ impl

ServeConversation

{ impl

ServeConversation

{ /// generate.cpp at the head of a request: decide where `prompt` starts reading and put the owners there. /// An error leaves the owners in an unknown place; the caller drops the cache and resets. - pub(super) fn begin>(&mut self, device: &mut D, prompt: &[i32]) -> ConvResult { + pub(super) fn begin>( + &mut self, + device: &mut D, + prompt: &[i32], + ) -> ConvResult { self.start = None; self.live = None; let mut engine = Engine { device, saved: &mut self.saved, restored: None }; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs index 2080d6c7..4d815e23 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_conversation/tests.rs @@ -61,11 +61,18 @@ fn config() -> ConversationConfig { /// One request against the fake: begin, read the plan's batched chunks (the device then holds them), /// and finish as a decode that committed `reply` (live only when `live`). -fn serve(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], reply: &[i32], live: bool) -> RequestStart { +fn serve( + c: &mut ServeConversation<(Vec, usize)>, + d: &mut Fake, + prompt: &[i32], + reply: &[i32], + live: bool, +) -> RequestStart { let start = c.begin(d, prompt).unwrap(); assert_eq!(d.held.len(), start.read_from); let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let options = + c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); for action in plan { if action.path == PromptPath::FinalSeed { @@ -140,9 +147,16 @@ fn a_settled_in_step_session_continues_live_without_a_restore() { } /// Read the first `chunks` batched chunks of the plan of `prompt` after `begin` (the device then holds them, the ring in step). -fn read_chunks(c: &mut ServeConversation<(Vec, usize)>, d: &mut Fake, prompt: &[i32], start: &RequestStart, chunks: usize) { +fn read_chunks( + c: &mut ServeConversation<(Vec, usize)>, + d: &mut Fake, + prompt: &[i32], + start: &RequestStart, + chunks: usize, +) { let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let options = + c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); let plan = PromptPlan::new(&tokens, start.resume, start.reread_to, None, options, 256).unwrap(); for action in plan.take(chunks) { assert_eq!(d.held.len(), action.first); @@ -244,7 +258,8 @@ fn a_one_token_prompt_starts_empty_reads_nothing_and_checkpoints_nothing() { assert_eq!(d.held.len(), 0); // the plan of a 1-token prompt is the final seed alone: no chunk, no checkpoint let tokens = [first[0] as u32]; - let options = c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); + let options = + c.config().plan_options(PromptOptions { force_batched: true, ..PromptOptions::original_mode17(1 << 16) }); let plan = PromptPlan::new(&tokens, 0, None, None, options, 256).unwrap(); assert!(plan.into_iter().all(|a| a.path == PromptPath::FinalSeed)); c.finish(true); @@ -327,11 +342,19 @@ fn reread_mode_reads_the_checkpoint_again_instead_of_restoring_it() { #[test] fn the_config_follows_the_original_defaults_and_refuses_nonsense() { let o = ConversationConfig::original(); - assert_eq!((o.prompt_cache, o.prompt_cache_every, o.prompt_cache_root, o.turn_token), (6, 16_384, 2048, Some(248_045))); + assert_eq!( + (o.prompt_cache, o.prompt_cache_every, o.prompt_cache_root, o.turn_token), + (6, 16_384, 2048, Some(248_045)) + ); assert!(o.validate().is_ok()); assert!(ConversationConfig { prompt_cache: 0, ..o.clone() }.validate().is_err()); assert!(ConversationConfig { turn_token: Some(248_320), ..o.clone() }.validate().is_err()); - let plan = o.plan_options(PromptOptions { prompt_cache: false, turn_token: None, root_min: 0, ..PromptOptions::original_mode17(4096) }); + let plan = o.plan_options(PromptOptions { + prompt_cache: false, + turn_token: None, + root_min: 0, + ..PromptOptions::original_mode17(4096) + }); assert!(plan.prompt_cache && plan.turn_token == Some(248_045) && plan.root_min == 2048); assert_eq!(o.options().conversation_cache_bytes, 0, "parking stays off"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs index 275cdc93..1d32589f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine.rs @@ -7,21 +7,23 @@ //! implementation must bind the genuine verifier window, session publication and //! `OriginalMtpDrafter::draft_from_verifier` owners. No default port exists: //! a missing owner is `Error::Unsupported`, never a synthesized result. -use super::contract::{Error,Result}; -use super::original_spec_controller::{NanGuard,OriginalSpecController,OriginalSpecEngine,SpecConfig,SpecError}; -use super::original_spec_draft::{DraftPick,OriginalDraftEngine,OriginalFirstDraftEngine}; +use super::contract::{Error, Result}; use super::original_spec_adaptive::AdaptiveConfig; +use super::original_spec_controller::{NanGuard, OriginalSpecController, OriginalSpecEngine, SpecConfig, SpecError}; +use super::original_spec_draft::{DraftPick, OriginalDraftEngine, OriginalFirstDraftEngine}; use super::original_spec_policy::MAX_T; use crate::settings::EnvSource; use std::rc::Rc; /// One completed one-shot MTP draft (all-T residual catch-up, ring/full seed and /// chain), exactly the picks `MtpDrafter::draft` would produce. -#[derive(Clone,Debug,PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct DraftCompletion { - pub(crate) ids:Vec,pub(crate) probabilities:Vec, + pub(crate) ids: Vec, + pub(crate) probabilities: Vec, /// Cell of the seed (`p + accepted_row`); the chain continues at `first_cell + j`. - pub(crate) first_cell:i64,pub(crate) accepted_row:usize, + pub(crate) first_cell: i64, + pub(crate) accepted_row: usize, } /// The genuine physical owners behind the serve loop. Every method that touches @@ -37,90 +39,144 @@ pub(crate) trait OriginalServePort { type DraftCheckpoint; type Adaptive; /// The committed target prefix is exactly `consumed + input` at `position`. - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()>; /// Reads session state: the engine has already waited the commit event. - fn checkpoint_target(&self)->Result; - fn checkpoint_draft(&self)->Result; - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; - fn apply_pending(&mut self)->Result<()>; + fn checkpoint_target(&self) -> Result; + fn checkpoint_draft(&self) -> Result; + fn restore_target(&mut self, checkpoint: &Self::TargetCheckpoint) -> Result<()>; + fn restore_draft(&mut self, checkpoint: &Self::DraftCheckpoint) -> Result<()>; + fn apply_pending(&mut self) -> Result<()>; /// Stage the literal per-row penalty histories (sampler counter is the cell, /// preserved across rollback) and run the genuine verifier window. - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result; - fn validate_window(&self,window:&Self::Window,position:i64,inputs:&[i32])->Result<()>; - fn window_outputs<'a>(&self,window:&'a Self::Window)->&'a[i32]; + fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result; + fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()>; + fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32]; /// Enqueue the asynchronous commit of the first `keep` input rows (replays the /// accepted prefix, publishes QSA/PLE/GDN state). The completion event is /// observed only by `wait_commit`. - fn commit_window(&mut self,window:&mut Self::Window,keep:usize)->Result<()>; + fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()>; /// Wait the commit event and publish the session. Idempotent when nothing is pending. - fn wait_commit(&mut self)->Result<()>; - fn drain_window(&mut self,window:Self::Window)->Result<()>; + fn wait_commit(&mut self) -> Result<()>; + fn drain_window(&mut self, window: Self::Window) -> Result<()>; /// Take back the physical effects of a window nothing was committed for (it was drained, both checkpoints restored): afterwards /// `run_window` can stage rows at the same position again. Nothing outstanding is not an error. The NaN guard's retry needs it. - fn discard_window(&mut self)->Result<()>; - fn begin_adaptation(&mut self,next_round:u64)->Result; - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; + fn discard_window(&mut self) -> Result<()>; + fn begin_adaptation(&mut self, next_round: u64) -> Result; + fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()>; /// Stage the coupled draft sampler's history (`set_draft_history`). - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()>; /// Literal `draft_from_verifier`: needs the committed window (commit already /// enqueued, event dependency honored by the owner) and all T real rows. #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self,window:&Self::Window,position:i64,accepted_row:usize,outputs:&[i32], - max_drafts:usize,min_p:f32,coupled:bool)->Result; - fn drain_draft(&mut self)->Result<()>; + fn draft_committed( + &mut self, + window: &Self::Window, + position: i64, + accepted_row: usize, + outputs: &[i32], + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result; + fn drain_draft(&mut self) -> Result<()>; #[allow(clippy::too_many_arguments)] - fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; - fn drain_first(&mut self)->Result<()>; + fn draft_first( + &mut self, + seed: &Self::Seed, + t: usize, + cell: i64, + token: i32, + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result; + fn drain_first(&mut self) -> Result<()>; } /// The window receipt handed to the controller. It owns the port's window and /// the host copies the controller needs; only this engine can drain it. pub(crate) struct ServedWindow { - window:W,owner:Rc<()>,serial:u64,position:i64,inputs:[i32;MAX_T],outputs:[i32;MAX_T],t:usize,committed:Option, + window: W, + owner: Rc<()>, + serial: u64, + position: i64, + inputs: [i32; MAX_T], + outputs: [i32; MAX_T], + t: usize, + committed: Option, } -enum DraftStage {Idle,Replayed{serial:u64},Seeded{completion:DraftCompletion,next:usize},} -enum FirstStage {Idle,Seeded{completion:DraftCompletion,next:usize,cell:i64},} +enum DraftStage { + Idle, + Replayed { serial: u64 }, + Seeded { completion: DraftCompletion, next: usize }, +} +enum FirstStage { + Idle, + Seeded { completion: DraftCompletion, next: usize, cell: i64 }, +} -pub(crate) struct OriginalServeEngine { - port:P,owner:Rc<()>,vocabulary:u32,max_t:usize,max_drafts:usize,min_p:f32, +pub(crate) struct OriginalServeEngine { + port: P, + owner: Rc<()>, + vocabulary: u32, + max_t: usize, + max_drafts: usize, + min_p: f32, /// The chain length of the NEXT draft stage (<= `max_drafts`, the cap); equal to the cap unless an adaptive plan lowers it. - plan_drafts:usize, - serial:u64,live_windows:usize,commit_pending:bool,adaptive_pending:bool, - history_staged:Option,draft:DraftStage,first:FirstStage,poisoned:bool, + plan_drafts: usize, + serial: u64, + live_windows: usize, + commit_pending: bool, + adaptive_pending: bool, + history_staged: Option, + draft: DraftStage, + first: FirstStage, + poisoned: bool, } /// Whether the adaptive speculative window is the default of the serve stack (docs/adaptive-spec.md). -pub(crate) const ADAPTIVE_DEFAULT:bool=true; +pub(crate) const ADAPTIVE_DEFAULT: bool = true; /// Original `generate` serve settings for mode17: `--spec 4` verify width, prompt lookup on /// (`--suffix-draft 3`), which makes the MTP keep 4-wide windows (`mtp_max_t = spec`) and the /// verifier take windows up to `spec + 2` (`kVerifyMaxT` 8), coupled draft sampling per env. -#[derive(Clone,Copy,Debug,PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct OriginalServeSettings { - pub(crate) max_t:usize,pub(crate) mtp_max_t:usize,pub(crate) max_context:i64,pub(crate) vocabulary:u32, - pub(crate) suffix_min_match:usize,pub(crate) coupled:bool, + pub(crate) max_t: usize, + pub(crate) mtp_max_t: usize, + pub(crate) max_context: i64, + pub(crate) vocabulary: u32, + pub(crate) suffix_min_match: usize, + pub(crate) coupled: bool, /// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy (`original_spec_adaptive.rs`). - pub(crate) adaptive:Option, + pub(crate) adaptive: Option, /// Re-run a verify window with non-finite output from its round's checkpoint (`NanGuard`); off in mode17 itself. - pub(crate) nan_guard:NanGuard, + pub(crate) nan_guard: NanGuard, /// An arm's own `spec_min_p` for the requests it serves (`fixed4@0`), overriding the harness default; `None` = the harness's. - pub(crate) request_min_p:Option, + pub(crate) request_min_p: Option, } -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) enum ServeStop {Eos,Length,Context} -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) struct ServeOutcome {pub(crate) stop:ServeStop,pub(crate) produced:usize,pub(crate) rounds:usize} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ServeStop { + Eos, + Length, + Context, +} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct ServeOutcome { + pub(crate) stop: ServeStop, + pub(crate) produced: usize, + pub(crate) rounds: usize, +} /// Bring-up diagnostic: logs every port call and its outcome. Remove together with the DBG lines. pub(crate) struct TracePort

(pub P); -#[cfg(test)] -mod tests; #[cfg(test)] mod env_tests; +#[cfg(test)] +mod tests; mod impl_draftcompletion; mod impl_originalfirstdraftengine_for_originalservee; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs index 10be7dd9..b0a9626d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/env_tests.rs @@ -15,34 +15,18 @@ fn engine(pairs: &[(&str, &str)]) -> OriginalServeSettings { #[test] fn nothing_set_selects_the_adaptive_window_at_full_width() { let s = engine(&[]); - assert_eq!( - (s.max_t, s.mtp_max_t, s.suffix_min_match), - (MAX_T, MAX_T, 3) - ); + assert_eq!((s.max_t, s.mtp_max_t, s.suffix_min_match), (MAX_T, MAX_T, 3)); assert_eq!(s.adaptive, Some(AdaptiveConfig::new(MAX_T, MAX_T - 1))); - assert_eq!( - (s.max_context, s.vocabulary, s.coupled), - (4096, VOCAB, false) - ); + assert_eq!((s.max_context, s.vocabulary, s.coupled), (4096, VOCAB, false)); } #[test] fn a_fixed_spec_is_clamped_and_turns_the_default_adaptive_window_off() { - for (value, max_t, mtp) in [ - ("3", 5, 3), - ("4", 6, 4), - ("8", 8, 8), - ("99", 8, 8), - ("1", 4, 2), - ("0", 4, 2), - (" 3 ", 5, 3), - ] { + for (value, max_t, mtp) in + [("3", 5, 3), ("4", 6, 4), ("8", 8, 8), ("99", 8, 8), ("1", 4, 2), ("0", 4, 2), (" 3 ", 5, 3)] + { let s = engine(&[("LELEKA_SPEC", value)]); - assert_eq!( - (s.max_t, s.mtp_max_t, s.adaptive), - (max_t, mtp, None), - "LELEKA_SPEC={value:?}" - ); + assert_eq!((s.max_t, s.mtp_max_t, s.adaptive), (max_t, mtp, None), "LELEKA_SPEC={value:?}"); } } @@ -51,11 +35,7 @@ fn a_malformed_spec_is_ignored_as_a_number_but_still_counts_as_set() { // the numeric reading ignores it (mode17 widths stay), the set-ness reading keeps the default adaptive window off for value in ["x", "", "-1", "4.5"] { let s = engine(&[("LELEKA_SPEC", value)]); - assert_eq!( - (s.max_t, s.mtp_max_t, s.adaptive), - (6, 4, None), - "LELEKA_SPEC={value:?}" - ); + assert_eq!((s.max_t, s.mtp_max_t, s.adaptive), (6, 4, None), "LELEKA_SPEC={value:?}"); } } @@ -63,18 +43,10 @@ fn a_malformed_spec_is_ignored_as_a_number_but_still_counts_as_set() { fn the_mtp_cap_and_the_suffix_floor_follow_their_own_words() { let spec4 = |key: &str, value: &str| engine(&[("LELEKA_SPEC", "4"), (key, value)]); for (value, want) in [("0", 4), ("3", 3), ("9", 6), (" 5 ", 5), ("x", 4)] { - assert_eq!( - spec4("LELEKA_SPEC_MTP_MAX_T", value).mtp_max_t, - want, - "MTP_MAX_T={value:?}" - ); + assert_eq!(spec4("LELEKA_SPEC_MTP_MAX_T", value).mtp_max_t, want, "MTP_MAX_T={value:?}"); } for (value, want) in [("0", 0), ("5", 5), (" 2 ", 2), ("x", 3), ("-1", 3)] { - assert_eq!( - spec4("LELEKA_SPEC_SUFFIX", value).suffix_min_match, - want, - "SUFFIX={value:?}" - ); + assert_eq!(spec4("LELEKA_SPEC_SUFFIX", value).suffix_min_match, want, "SUFFIX={value:?}"); } } @@ -94,24 +66,10 @@ fn the_adaptive_switch_wins_over_a_fixed_spec() { #[test] fn the_adaptive_window_width_is_clamped_and_sets_both_widths() { - for (value, width) in [ - ("5", 5), - ("2", 2), - ("1", 2), - ("99", 8), - (" 6 ", 6), - ("x", 8), - ] { + for (value, width) in [("5", 5), ("2", 2), ("1", 2), ("99", 8), (" 6 ", 6), ("x", 8)] { let s = engine(&[("LELEKA_SPEC_ADAPTIVE_MAX_T", value)]); - assert_eq!( - (s.max_t, s.mtp_max_t), - (width, width), - "ADAPTIVE_MAX_T={value:?}" - ); - assert_eq!( - s.adaptive.map(|a| (a.max_t, a.max_drafts)), - Some((width, width - 1)) - ); + assert_eq!((s.max_t, s.mtp_max_t), (width, width), "ADAPTIVE_MAX_T={value:?}"); + assert_eq!(s.adaptive.map(|a| (a.max_t, a.max_drafts)), Some((width, width - 1))); } } @@ -183,29 +141,11 @@ fn the_nan_guard_reads_its_three_words_and_keeps_its_default_on_a_malformed_one( let read = |pairs: &[(&str, &str)]| NanGuard::from_environment(&MapEnv::of(pairs)); let default = NanGuard::parse(None, None, None).unwrap(); assert_eq!(read(&[]), default); - assert_eq!( - read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on")]), - NanGuard::with_retries(2) - ); - let retries = [ - ("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on"), - ("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES", "5"), - ]; + assert_eq!(read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on")]), NanGuard::with_retries(2)); + let retries = [("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on"), ("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES", "5")]; assert_eq!(read(&retries), NanGuard::with_retries(5)); - let inject = [ - ("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on"), - ("LELEKA_ORIGINAL_SERVE_NAN_INJECT", "4x2"), - ]; - assert_eq!( - read(&inject), - NanGuard::with_retries(2).with_injection(4, 2) - ); - assert_eq!( - read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "maybe")]), - default - ); - assert_eq!( - read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES", "9")]), - default - ); + let inject = [("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "on"), ("LELEKA_ORIGINAL_SERVE_NAN_INJECT", "4x2")]; + assert_eq!(read(&inject), NanGuard::with_retries(2).with_injection(4, 2)); + assert_eq!(read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD", "maybe")]), default); + assert_eq!(read(&[("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES", "9")]), default); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion.rs index 50cd22ee..556b6d7d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion.rs @@ -3,230 +3,5 @@ #[allow(unused_imports)] use super::*; -impl DraftCompletion { - pub(super) fn validate(&self,vocabulary:u32,max_picks:usize,cell:i64,row:usize)->Result<()> { - let n=self.ids.len(); - if n==0||n>max_picks||n!=self.probabilities.len()||self.first_cell!=cell||self.accepted_row!=row {return Err(Error::IdentityMismatch);} - if self.ids.iter().any(|&v|v<0||v as u32>=vocabulary) {return Err(Error::InvalidToken);} - if self.probabilities.iter().any(|p|!p.is_finite()||!(0.0..=1.0).contains(p)) {return Err(Error::NonFinite);} - Ok(()) - } -} -impl ServedWindow { - pub(crate) fn rows(&self)->usize {self.t} - pub(crate) fn committed_rows(&self)->Option {self.committed} -} -impl OriginalServeEngine

{ - pub(crate) fn new(port:P,vocabulary:u32,max_t:usize,max_drafts:usize)->Result { - if vocabulary==0||vocabulary>262144||!(1..=MAX_T).contains(&max_t)||max_drafts>max_t-1 {return Err(Error::InvalidDimension);} - Ok(Self{port,owner:Rc::new(()),vocabulary,max_t,max_drafts,min_p:0.0,plan_drafts:max_drafts,serial:0,live_windows:0,commit_pending:false, - adaptive_pending:false,history_staged:None,draft:DraftStage::Idle,first:FirstStage::Idle,poisoned:false}) - } - /// The request's draft confidence floor; the controller uses the same value - /// when it stops the chain, and `drain_draft` cross-checks the two. - pub(crate) fn set_min_p(&mut self,min_p:f32)->Result<()> { - if !min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} - if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} - self.min_p=min_p;Ok(()) - } - pub(crate) fn port(&self)->&P {&self.port} - pub(crate) fn port_mut(&mut self)->&mut P {&mut self.port} - pub(crate) fn is_poisoned(&self)->bool {self.poisoned} - pub(crate) fn commit_pending(&self)->bool {self.commit_pending} - pub(crate) fn into_port(self)->P {self.port} - pub(super) fn usable(&self)->Result<()> {if self.poisoned {Err(Error::IdentityMismatch)} else {Ok(())}} - pub(super) fn window_ok(&self,w:&ServedWindow)->Result<()> { - if !Rc::ptr_eq(&self.owner,&w.owner)||w.serial!=self.serial {return Err(Error::IdentityMismatch);}Ok(()) - } - /// Session reads (checkpoint, validate) require the previous commit's event. - pub(super) fn settle_commit(&mut self)->Result<()> { - if self.commit_pending { - self.commit_pending=false; - if let Err(e)=self.port.wait_commit() {self.poisoned=true;return Err(e);} - }Ok(()) - } - pub(super) fn after_restore(&mut self) { - self.draft=DraftStage::Idle;self.first=FirstStage::Idle;self.history_staged=None; - } - pub(super) fn cached_pick(&self,completion:&DraftCompletion,index:usize)->DraftPick { - DraftPick{token:completion.ids[index],probability:completion.probabilities[index]} - } -} - -impl OriginalDraftEngine> for OriginalServeEngine

{ - fn replay_target_kv(&mut self,verified:&ServedWindow,p:i64,outputs:&[i32])->Result<()> { - self.usable()?;self.window_ok(verified)?; - // Literal order: commit is enqueued BEFORE any draft reads the branch. - if verified.committed.is_none()||!matches!(self.draft,DraftStage::Idle)||p!=verified.position - ||outputs!=&verified.outputs[..verified.t] {return Err(Error::IdentityMismatch);} - self.draft=DraftStage::Replayed{serial:verified.serial};Ok(()) - } - fn full_target_seed(&mut self,verified:&ServedWindow,row:usize,cell:i64,token:i32,coupled:bool)->Result { - self.usable()?;self.window_ok(verified)?; - let keep=verified.committed.ok_or(Error::IdentityMismatch)?; - match self.draft {DraftStage::Replayed{serial} if serial==verified.serial=>{},_=>return Err(Error::IdentityMismatch)} - if row+1!=keep||row>=verified.t||cell!=verified.position.checked_add(row as i64).ok_or(Error::Overflow)? - ||token!=verified.outputs[row] {return Err(Error::IdentityMismatch);} - // A coupled draft is sampled with the staged history of THIS window. - if coupled&&self.history_staged!=Some(verified.serial) {return Err(Error::IdentityMismatch);} - let max_picks=self.plan_drafts.max(1); - let completion=self.port.draft_committed(&verified.window,verified.position,row,&verified.outputs[..verified.t], - self.plan_drafts,self.min_p,coupled)?; - completion.validate(self.vocabulary,max_picks,cell,row)?; - let pick=self.cached_pick(&completion,0); - self.draft=DraftStage::Seeded{completion,next:1};Ok(pick) - } - fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.usable()?; - let DraftStage::Seeded{completion,next}=&self.draft else {return Err(Error::IdentityMismatch)}; - if j!=*next||j>=completion.ids.len()||cell!=completion.first_cell.checked_add(j as i64).ok_or(Error::Overflow)? - ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} - let pick=self.cached_pick(completion,j); - if let DraftStage::Seeded{next,..}=&mut self.draft {*next+=1;}Ok(pick) - } - fn stage_coupled_history(&mut self,consumed:&[i32],next:i32)->Result<()> { - self.usable()?; - if next<0||next as u32>=self.vocabulary||consumed.iter().any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} - self.port.stage_draft_history(consumed,next)?; - // The sampled history belongs to the window just verified (serial stays - // valid until the next verify bumps it). - self.history_staged=Some(self.serial);Ok(()) - } - fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> { - self.usable()?; - if max_drafts==0||max_drafts>self.max_drafts||!min_p.is_finite()||min_p<0.0 {return Err(Error::InvalidDimension);} - if !matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} - self.plan_drafts=max_drafts;self.min_p=min_p;Ok(()) - } - fn drain_draft(&mut self)->Result<()> { - // Always drain the real owner; then cross-check the controller's chain - // length against the one-shot completion. - let drained=self.port.drain_draft(); - let stage=std::mem::replace(&mut self.draft,DraftStage::Idle); - if drained.is_err() {self.poisoned=true;} - drained?; - if let DraftStage::Seeded{completion,next}=stage { - let n=completion.ids.len(); - if next=self.plan_drafts.min(self.max_t-1); - if !stopped {return Err(Error::IdentityMismatch);} - } - } - Ok(()) - } -} - -impl OriginalSpecEngine for OriginalServeEngine

{ - type Verified=ServedWindow; - type TargetCheckpoint=P::TargetCheckpoint; - type DraftCheckpoint=P::DraftCheckpoint; - type AdaptiveWork=P::Adaptive; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - self.usable()?; - if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.validate_current(consumed,input,position) - } - fn checkpoint_target(&self)->Result { - self.usable()?; - // The controller checkpoints right after validate_current; the previous - // commit event must already have been waited (see `apply_pending`). - if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.checkpoint_target() - } - fn checkpoint_draft(&self)->Result { - self.usable()?;if self.commit_pending {return Err(Error::IdentityMismatch);} - self.port.checkpoint_draft() - } - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { - // A rollback never depends on engine health: it fences, then restores. - let settled=if self.commit_pending {self.commit_pending=false;self.port.wait_commit()} else {Ok(())}; - let restored=self.port.restore_target(checkpoint); - self.after_restore(); - if settled.is_err()||restored.is_err() {self.poisoned=true;} - settled.and(restored) - } - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { - let restored=self.port.restore_draft(checkpoint); - self.after_restore(); - if restored.is_err() {self.poisoned=true;} - restored - } - fn apply_pending(&mut self)->Result<()> { - self.usable()?; - // Round-start session reads (and the adaptive refill) need the prior commit. - self.settle_commit()?; - self.port.apply_pending() - } - fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.usable()?; - if inputs.is_empty()||inputs.len()>self.max_t||self.live_windows!=0||self.commit_pending - ||!matches!(self.draft,DraftStage::Idle) {return Err(Error::IdentityMismatch);} - if inputs.iter().chain(consumed).any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);} - let window=self.port.run_window(position,inputs,consumed)?; - // From here a window exists: any refusal below still has to drain it. - let t=inputs.len(); - let admission=(||{ - self.port.validate_window(&window,position,inputs)?; - let out=self.port.window_outputs(&window); - if out.len()!=t {return Err(Error::IdentityMismatch);} - let mut copy=[0;MAX_T];copy[..t].copy_from_slice(out);Ok(copy) - })(); - let outputs=match admission {Ok(o)=>o,Err(e)=>{ - if self.port.drain_window(window).is_err() {self.poisoned=true;} - return Err(e); - }}; - self.serial=self.serial.checked_add(1).ok_or(Error::Overflow)?; - self.live_windows+=1;self.history_staged=None; - let mut copy_in=[0;MAX_T];copy_in[..t].copy_from_slice(inputs); - Ok(ServedWindow{window,owner:Rc::clone(&self.owner),serial:self.serial,position,inputs:copy_in,outputs,t,committed:None}) - } - fn validate_verified(&self,verified:&Self::Verified,position:i64,inputs:&[i32])->Result<()> { - self.usable()?;self.window_ok(verified)?; - if verified.position!=position||inputs!=&verified.inputs[..verified.t] {return Err(Error::IdentityMismatch);} - self.port.validate_window(&verified.window,position,inputs) - } - fn outputs<'a>(&self,verified:&'a Self::Verified)->&'a[i32] {&verified.outputs[..verified.t]} - fn commit_verified(&mut self,verified:&mut Self::Verified,input_rows:usize)->Result<()> { - self.usable()?;self.window_ok(verified)?; - if verified.committed.is_some()||self.commit_pending||input_rows==0||input_rows>verified.t {return Err(Error::IdentityMismatch);} - // Only the accepted prefix is publishable: row k+1's input must equal output k. - if (1..input_rows).any(|k|verified.inputs[k]!=verified.outputs[k-1]) {return Err(Error::IdentityMismatch);} - // The commit event is outstanding from the moment it is enqueued, even if - // the enqueue itself reports uncertainty. - self.commit_pending=true; - if let Err(e)=self.port.commit_window(&mut verified.window,input_rows) {self.poisoned=true;return Err(e);} - verified.committed=Some(input_rows);Ok(()) - } - fn discard_window(&mut self)->Result<()> { - // after the drain of the refused window, before the checkpoints' round starts again: no window may be alive, no commit outstanding - if self.live_windows!=0||self.commit_pending {return Err(Error::IdentityMismatch);} - let discarded=self.port.discard_window(); - if discarded.is_err() {self.poisoned=true;} - discarded - } - fn drain_verified(&mut self,verified:Self::Verified)->Result<()> { - if !Rc::ptr_eq(&self.owner,&verified.owner) {return Err(Error::IdentityMismatch);} - self.live_windows=self.live_windows.saturating_sub(1); - // The draft that depended on the commit event has finished by now: wait - // the event (publishing the session) and release the window's resources. - // Both are always attempted; the first failure is the one reported. - let settled=self.settle_commit(); - let drained=self.port.drain_window(verified.window); - if drained.is_err() {self.poisoned=true;} - settled.and(drained) - } - fn begin_adaptation(&mut self,next_round:u64)->Result { - self.usable()?;if self.adaptive_pending {return Err(Error::IdentityMismatch);} - let work=self.port.begin_adaptation(next_round)?;self.adaptive_pending=true;Ok(work) - } - fn join_adaptation(&mut self,work:Self::AdaptiveWork)->Result<()> { - self.adaptive_pending=false; - let joined=self.port.join_adaptation(work); - if joined.is_err() {self.poisoned=true;}joined - } - fn wait_commit(&mut self)->Result<()> { - if self.commit_pending {self.settle_commit()} else {Ok(())} - } -} +mod impl_draftcompletion_2; +mod impl_originalspecengine_for_originalserveengine; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs new file mode 100644 index 00000000..89ee58fa --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_draftcompletion_2.rs @@ -0,0 +1,233 @@ +//! Moved out of the parent module by STRA-338: impl DraftCompletion, impl ServedWindow, impl OriginalServeEngine, impl OriginalDraftEngine_for_OriginalServeEngine. + +#[allow(unused_imports)] +use super::*; + +impl DraftCompletion { + pub(in super::super) fn validate(&self, vocabulary: u32, max_picks: usize, cell: i64, row: usize) -> Result<()> { + let n = self.ids.len(); + if n == 0 + || n > max_picks + || n != self.probabilities.len() + || self.first_cell != cell + || self.accepted_row != row + { + return Err(Error::IdentityMismatch); + } + if self.ids.iter().any(|&v| v < 0 || v as u32 >= vocabulary) { + return Err(Error::InvalidToken); + } + if self.probabilities.iter().any(|p| !p.is_finite() || !(0.0..=1.0).contains(p)) { + return Err(Error::NonFinite); + } + Ok(()) + } +} +impl ServedWindow { + pub(crate) fn rows(&self) -> usize { + self.t + } + pub(crate) fn committed_rows(&self) -> Option { + self.committed + } +} +impl OriginalServeEngine

{ + pub(crate) fn new(port: P, vocabulary: u32, max_t: usize, max_drafts: usize) -> Result { + if vocabulary == 0 || vocabulary > 262144 || !(1..=MAX_T).contains(&max_t) || max_drafts > max_t - 1 { + return Err(Error::InvalidDimension); + } + Ok(Self { + port, + owner: Rc::new(()), + vocabulary, + max_t, + max_drafts, + min_p: 0.0, + plan_drafts: max_drafts, + serial: 0, + live_windows: 0, + commit_pending: false, + adaptive_pending: false, + history_staged: None, + draft: DraftStage::Idle, + first: FirstStage::Idle, + poisoned: false, + }) + } + /// The request's draft confidence floor; the controller uses the same value + /// when it stops the chain, and `drain_draft` cross-checks the two. + pub(crate) fn set_min_p(&mut self, min_p: f32) -> Result<()> { + if !min_p.is_finite() || min_p < 0.0 { + return Err(Error::InvalidDimension); + } + if self.live_windows != 0 || self.commit_pending { + return Err(Error::IdentityMismatch); + } + self.min_p = min_p; + Ok(()) + } + pub(crate) fn port(&self) -> &P { + &self.port + } + pub(crate) fn port_mut(&mut self) -> &mut P { + &mut self.port + } + pub(crate) fn is_poisoned(&self) -> bool { + self.poisoned + } + pub(crate) fn commit_pending(&self) -> bool { + self.commit_pending + } + pub(crate) fn into_port(self) -> P { + self.port + } + pub(in super::super) fn usable(&self) -> Result<()> { + if self.poisoned { Err(Error::IdentityMismatch) } else { Ok(()) } + } + pub(in super::super) fn window_ok(&self, w: &ServedWindow) -> Result<()> { + if !Rc::ptr_eq(&self.owner, &w.owner) || w.serial != self.serial { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + /// Session reads (checkpoint, validate) require the previous commit's event. + pub(in super::super) fn settle_commit(&mut self) -> Result<()> { + if self.commit_pending { + self.commit_pending = false; + if let Err(e) = self.port.wait_commit() { + self.poisoned = true; + return Err(e); + } + } + Ok(()) + } + pub(in super::super) fn after_restore(&mut self) { + self.draft = DraftStage::Idle; + self.first = FirstStage::Idle; + self.history_staged = None; + } + pub(in super::super) fn cached_pick(&self, completion: &DraftCompletion, index: usize) -> DraftPick { + DraftPick { token: completion.ids[index], probability: completion.probabilities[index] } + } +} + +impl OriginalDraftEngine> for OriginalServeEngine

{ + fn replay_target_kv(&mut self, verified: &ServedWindow, p: i64, outputs: &[i32]) -> Result<()> { + self.usable()?; + self.window_ok(verified)?; + // Literal order: commit is enqueued BEFORE any draft reads the branch. + if verified.committed.is_none() + || !matches!(self.draft, DraftStage::Idle) + || p != verified.position + || outputs != &verified.outputs[..verified.t] + { + return Err(Error::IdentityMismatch); + } + self.draft = DraftStage::Replayed { serial: verified.serial }; + Ok(()) + } + fn full_target_seed( + &mut self, + verified: &ServedWindow, + row: usize, + cell: i64, + token: i32, + coupled: bool, + ) -> Result { + self.usable()?; + self.window_ok(verified)?; + let keep = verified.committed.ok_or(Error::IdentityMismatch)?; + match self.draft { + DraftStage::Replayed { serial } if serial == verified.serial => {} + _ => return Err(Error::IdentityMismatch), + } + if row + 1 != keep + || row >= verified.t + || cell != verified.position.checked_add(row as i64).ok_or(Error::Overflow)? + || token != verified.outputs[row] + { + return Err(Error::IdentityMismatch); + } + // A coupled draft is sampled with the staged history of THIS window. + if coupled && self.history_staged != Some(verified.serial) { + return Err(Error::IdentityMismatch); + } + let max_picks = self.plan_drafts.max(1); + let completion = self.port.draft_committed( + &verified.window, + verified.position, + row, + &verified.outputs[..verified.t], + self.plan_drafts, + self.min_p, + coupled, + )?; + completion.validate(self.vocabulary, max_picks, cell, row)?; + let pick = self.cached_pick(&completion, 0); + self.draft = DraftStage::Seeded { completion, next: 1 }; + Ok(pick) + } + fn full_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, _coupled: bool) -> Result { + self.usable()?; + let DraftStage::Seeded { completion, next } = &self.draft else { return Err(Error::IdentityMismatch) }; + if j != *next + || j >= completion.ids.len() + || cell != completion.first_cell.checked_add(j as i64).ok_or(Error::Overflow)? + || previous_token != completion.ids[j - 1] + { + return Err(Error::IdentityMismatch); + } + let pick = self.cached_pick(completion, j); + if let DraftStage::Seeded { next, .. } = &mut self.draft { + *next += 1; + } + Ok(pick) + } + fn stage_coupled_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + self.usable()?; + if next < 0 || next as u32 >= self.vocabulary || consumed.iter().any(|&v| v < 0 || v as u32 >= self.vocabulary) + { + return Err(Error::InvalidToken); + } + self.port.stage_draft_history(consumed, next)?; + // The sampled history belongs to the window just verified (serial stays + // valid until the next verify bumps it). + self.history_staged = Some(self.serial); + Ok(()) + } + fn set_draft_plan(&mut self, max_drafts: usize, min_p: f32) -> Result<()> { + self.usable()?; + if max_drafts == 0 || max_drafts > self.max_drafts || !min_p.is_finite() || min_p < 0.0 { + return Err(Error::InvalidDimension); + } + if !matches!(self.draft, DraftStage::Idle) { + return Err(Error::IdentityMismatch); + } + self.plan_drafts = max_drafts; + self.min_p = min_p; + Ok(()) + } + fn drain_draft(&mut self) -> Result<()> { + // Always drain the real owner; then cross-check the controller's chain + // length against the one-shot completion. + let drained = self.port.drain_draft(); + let stage = std::mem::replace(&mut self.draft, DraftStage::Idle); + if drained.is_err() { + self.poisoned = true; + } + drained?; + if let DraftStage::Seeded { completion, next } = stage { + let n = completion.ids.len(); + if next < n { + // The controller stopped early: only legal when the literal stop + // rule fires (confidence below the floor or the draft cap). + let stopped = + completion.probabilities[next - 1] < self.min_p || next >= self.plan_drafts.min(self.max_t - 1); + if !stopped { + return Err(Error::IdentityMismatch); + } + } + } + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_originalspecengine_for_originalserveengine.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_originalspecengine_for_originalserveengine.rs new file mode 100644 index 00000000..eaf483df --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_draftcompletion/impl_originalspecengine_for_originalserveengine.rs @@ -0,0 +1,191 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSpecEngine_for_OriginalServeEngine. + +#[allow(unused_imports)] +use super::*; + +impl OriginalSpecEngine for OriginalServeEngine

{ + type Verified = ServedWindow; + type TargetCheckpoint = P::TargetCheckpoint; + type DraftCheckpoint = P::DraftCheckpoint; + type AdaptiveWork = P::Adaptive; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + self.usable()?; + if self.commit_pending { + return Err(Error::IdentityMismatch); + } + self.port.validate_current(consumed, input, position) + } + fn checkpoint_target(&self) -> Result { + self.usable()?; + // The controller checkpoints right after validate_current; the previous + // commit event must already have been waited (see `apply_pending`). + if self.commit_pending { + return Err(Error::IdentityMismatch); + } + self.port.checkpoint_target() + } + fn checkpoint_draft(&self) -> Result { + self.usable()?; + if self.commit_pending { + return Err(Error::IdentityMismatch); + } + self.port.checkpoint_draft() + } + fn restore_target(&mut self, checkpoint: &Self::TargetCheckpoint) -> Result<()> { + // A rollback never depends on engine health: it fences, then restores. + let settled = if self.commit_pending { + self.commit_pending = false; + self.port.wait_commit() + } else { + Ok(()) + }; + let restored = self.port.restore_target(checkpoint); + self.after_restore(); + if settled.is_err() || restored.is_err() { + self.poisoned = true; + } + settled.and(restored) + } + fn restore_draft(&mut self, checkpoint: &Self::DraftCheckpoint) -> Result<()> { + let restored = self.port.restore_draft(checkpoint); + self.after_restore(); + if restored.is_err() { + self.poisoned = true; + } + restored + } + fn apply_pending(&mut self) -> Result<()> { + self.usable()?; + // Round-start session reads (and the adaptive refill) need the prior commit. + self.settle_commit()?; + self.port.apply_pending() + } + fn verify(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { + self.usable()?; + if inputs.is_empty() + || inputs.len() > self.max_t + || self.live_windows != 0 + || self.commit_pending + || !matches!(self.draft, DraftStage::Idle) + { + return Err(Error::IdentityMismatch); + } + if inputs.iter().chain(consumed).any(|&v| v < 0 || v as u32 >= self.vocabulary) { + return Err(Error::InvalidToken); + } + let window = self.port.run_window(position, inputs, consumed)?; + // From here a window exists: any refusal below still has to drain it. + let t = inputs.len(); + let admission = (|| { + self.port.validate_window(&window, position, inputs)?; + let out = self.port.window_outputs(&window); + if out.len() != t { + return Err(Error::IdentityMismatch); + } + let mut copy = [0; MAX_T]; + copy[..t].copy_from_slice(out); + Ok(copy) + })(); + let outputs = match admission { + Ok(o) => o, + Err(e) => { + if self.port.drain_window(window).is_err() { + self.poisoned = true; + } + return Err(e); + } + }; + self.serial = self.serial.checked_add(1).ok_or(Error::Overflow)?; + self.live_windows += 1; + self.history_staged = None; + let mut copy_in = [0; MAX_T]; + copy_in[..t].copy_from_slice(inputs); + Ok(ServedWindow { + window, + owner: Rc::clone(&self.owner), + serial: self.serial, + position, + inputs: copy_in, + outputs, + t, + committed: None, + }) + } + fn validate_verified(&self, verified: &Self::Verified, position: i64, inputs: &[i32]) -> Result<()> { + self.usable()?; + self.window_ok(verified)?; + if verified.position != position || inputs != &verified.inputs[..verified.t] { + return Err(Error::IdentityMismatch); + } + self.port.validate_window(&verified.window, position, inputs) + } + fn outputs<'a>(&self, verified: &'a Self::Verified) -> &'a [i32] { + &verified.outputs[..verified.t] + } + fn commit_verified(&mut self, verified: &mut Self::Verified, input_rows: usize) -> Result<()> { + self.usable()?; + self.window_ok(verified)?; + if verified.committed.is_some() || self.commit_pending || input_rows == 0 || input_rows > verified.t { + return Err(Error::IdentityMismatch); + } + // Only the accepted prefix is publishable: row k+1's input must equal output k. + if (1..input_rows).any(|k| verified.inputs[k] != verified.outputs[k - 1]) { + return Err(Error::IdentityMismatch); + } + // The commit event is outstanding from the moment it is enqueued, even if + // the enqueue itself reports uncertainty. + self.commit_pending = true; + if let Err(e) = self.port.commit_window(&mut verified.window, input_rows) { + self.poisoned = true; + return Err(e); + } + verified.committed = Some(input_rows); + Ok(()) + } + fn discard_window(&mut self) -> Result<()> { + // after the drain of the refused window, before the checkpoints' round starts again: no window may be alive, no commit outstanding + if self.live_windows != 0 || self.commit_pending { + return Err(Error::IdentityMismatch); + } + let discarded = self.port.discard_window(); + if discarded.is_err() { + self.poisoned = true; + } + discarded + } + fn drain_verified(&mut self, verified: Self::Verified) -> Result<()> { + if !Rc::ptr_eq(&self.owner, &verified.owner) { + return Err(Error::IdentityMismatch); + } + self.live_windows = self.live_windows.saturating_sub(1); + // The draft that depended on the commit event has finished by now: wait + // the event (publishing the session) and release the window's resources. + // Both are always attempted; the first failure is the one reported. + let settled = self.settle_commit(); + let drained = self.port.drain_window(verified.window); + if drained.is_err() { + self.poisoned = true; + } + settled.and(drained) + } + fn begin_adaptation(&mut self, next_round: u64) -> Result { + self.usable()?; + if self.adaptive_pending { + return Err(Error::IdentityMismatch); + } + let work = self.port.begin_adaptation(next_round)?; + self.adaptive_pending = true; + Ok(work) + } + fn join_adaptation(&mut self, work: Self::AdaptiveWork) -> Result<()> { + self.adaptive_pending = false; + let joined = self.port.join_adaptation(work); + if joined.is_err() { + self.poisoned = true; + } + joined + } + fn wait_commit(&mut self) -> Result<()> { + if self.commit_pending { self.settle_commit() } else { Ok(()) } + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs index e5fc930b..eae32e56 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/impl_originalfirstdraftengine_for_originalservee.rs @@ -3,174 +3,272 @@ #[allow(unused_imports)] use super::*; - /// Seed receipt for the CLI `draft_first` path; same one-shot caching. -impl OriginalFirstDraftEngine for OriginalServeEngine

{ - fn replay_first_seed_kv(&mut self,_seed:&P::Seed,t:usize,cell:i64,token:i32)->Result<()> { +impl OriginalFirstDraftEngine for OriginalServeEngine

{ + fn replay_first_seed_kv(&mut self, _seed: &P::Seed, t: usize, cell: i64, token: i32) -> Result<()> { self.usable()?; - if t!=self.max_t||cell<0||token<0||token as u32>=self.vocabulary||self.commit_pending - ||!matches!(self.first,FirstStage::Idle)||!matches!(self.draft,DraftStage::Idle)||self.live_windows!=0 { + if t != self.max_t + || cell < 0 + || token < 0 + || token as u32 >= self.vocabulary + || self.commit_pending + || !matches!(self.first, FirstStage::Idle) + || !matches!(self.draft, DraftStage::Idle) + || self.live_windows != 0 + { return Err(Error::IdentityMismatch); } Ok(()) } - fn full_first_seed(&mut self,seed:&P::Seed,cell:i64,token:i32,coupled:bool)->Result { + fn full_first_seed(&mut self, seed: &P::Seed, cell: i64, token: i32, coupled: bool) -> Result { self.usable()?; - if !matches!(self.first,FirstStage::Idle) {return Err(Error::IdentityMismatch);} - let completion=self.port.draft_first(seed,self.max_t,cell,token,self.max_drafts,self.min_p,coupled)?; - completion.validate(self.vocabulary,self.max_drafts.max(1),cell,0)?; - let pick=self.cached_pick(&completion,0); - self.first=FirstStage::Seeded{completion,next:1,cell};Ok(pick) + if !matches!(self.first, FirstStage::Idle) { + return Err(Error::IdentityMismatch); + } + let completion = self.port.draft_first(seed, self.max_t, cell, token, self.max_drafts, self.min_p, coupled)?; + completion.validate(self.vocabulary, self.max_drafts.max(1), cell, 0)?; + let pick = self.cached_pick(&completion, 0); + self.first = FirstStage::Seeded { completion, next: 1, cell }; + Ok(pick) } - fn first_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { + fn first_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, _coupled: bool) -> Result { self.usable()?; - let FirstStage::Seeded{completion,next,cell:first}=&self.first else {return Err(Error::IdentityMismatch)}; - if j!=*next||j>=completion.ids.len()||cell!=first.checked_add(j as i64).ok_or(Error::Overflow)? - ||previous_token!=completion.ids[j-1] {return Err(Error::IdentityMismatch);} - let pick=self.cached_pick(completion,j); - if let FirstStage::Seeded{next,..}=&mut self.first {*next+=1;}Ok(pick) + let FirstStage::Seeded { completion, next, cell: first } = &self.first else { + return Err(Error::IdentityMismatch); + }; + if j != *next + || j >= completion.ids.len() + || cell != first.checked_add(j as i64).ok_or(Error::Overflow)? + || previous_token != completion.ids[j - 1] + { + return Err(Error::IdentityMismatch); + } + let pick = self.cached_pick(completion, j); + if let FirstStage::Seeded { next, .. } = &mut self.first { + *next += 1; + } + Ok(pick) } - fn drain_first_seed(&mut self)->Result<()> { - let drained=self.port.drain_first();self.first=FirstStage::Idle; - if drained.is_err() {self.poisoned=true;}drained + fn drain_first_seed(&mut self) -> Result<()> { + let drained = self.port.drain_first(); + self.first = FirstStage::Idle; + if drained.is_err() { + self.poisoned = true; + } + drained } } impl OriginalServeSettings { - pub(crate) fn mode17(max_context:i64,vocabulary:u32,coupled:bool)->Self { - const SPEC:usize=4;const SUFFIX:usize=3; - Self{max_t:(SPEC+2).min(MAX_T),mtp_max_t:SPEC,max_context,vocabulary,suffix_min_match:SUFFIX,coupled,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None} + pub(crate) fn mode17(max_context: i64, vocabulary: u32, coupled: bool) -> Self { + const SPEC: usize = 4; + const SUFFIX: usize = 3; + Self { + max_t: (SPEC + 2).min(MAX_T), + mtp_max_t: SPEC, + max_context, + vocabulary, + suffix_min_match: SUFFIX, + coupled, + adaptive: None, + nan_guard: NanGuard::off(), + request_min_p: None, + } } /// Mode17 with the operator's overrides from the environment (read once per stack): /// `LELEKA_SPEC` (the Original's `--spec`: MTP window, verify windows up to `spec + 2`, at most 8), /// `LELEKA_SPEC_MTP_MAX_T` (`--mtp-max-t`, 0 = spec), `LELEKA_SPEC_SUFFIX` (`--suffix-draft`, 0 = off), and /// `LELEKA_SPEC_ADAPTIVE=on` (adaptive window; widest window `LELEKA_SPEC_ADAPTIVE_MAX_T`, default 8 rows, MTP chain up /// to `max_t - 1` drafts). Unset = mode17 exactly. - pub(crate) fn from_environment(max_context:i64,vocabulary:u32,coupled:bool,env:&impl EnvSource)->Self { - let num=|name:&str|env.get(name).and_then(|v|v.trim().parse::().ok()); - let mut s=Self::mode17(max_context,vocabulary,coupled); - s.nan_guard=NanGuard::from_environment(env); - if let Some(spec)=num("LELEKA_SPEC") { - let spec=spec.clamp(2,MAX_T);s.max_t=(spec+2).min(MAX_T);s.mtp_max_t=spec; + pub(crate) fn from_environment(max_context: i64, vocabulary: u32, coupled: bool, env: &impl EnvSource) -> Self { + let num = |name: &str| env.get(name).and_then(|v| v.trim().parse::().ok()); + let mut s = Self::mode17(max_context, vocabulary, coupled); + s.nan_guard = NanGuard::from_environment(env); + if let Some(spec) = num("LELEKA_SPEC") { + let spec = spec.clamp(2, MAX_T); + s.max_t = (spec + 2).min(MAX_T); + s.mtp_max_t = spec; } - if let Some(m)=num("LELEKA_SPEC_MTP_MAX_T") {s.mtp_max_t=if m==0 {s.max_t.min(s.mtp_max_t)} else {m.min(s.max_t)};} - if let Some(n)=num("LELEKA_SPEC_SUFFIX") {s.suffix_min_match=n;} - let explicit=env.get("LELEKA_SPEC_ADAPTIVE"); - if Self::adaptive_wanted(explicit.as_deref(),env.is_set("LELEKA_SPEC")) { - let max_t=num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2,MAX_T); - s.max_t=max_t;s.mtp_max_t=max_t; - s.adaptive=Some(super::super::original_spec_adaptive_env::from_environment(AdaptiveConfig::new(max_t,max_t-1),env)); + if let Some(m) = num("LELEKA_SPEC_MTP_MAX_T") { + s.mtp_max_t = if m == 0 { s.max_t.min(s.mtp_max_t) } else { m.min(s.max_t) }; + } + if let Some(n) = num("LELEKA_SPEC_SUFFIX") { + s.suffix_min_match = n; + } + let explicit = env.get("LELEKA_SPEC_ADAPTIVE"); + if Self::adaptive_wanted(explicit.as_deref(), env.is_set("LELEKA_SPEC")) { + let max_t = num("LELEKA_SPEC_ADAPTIVE_MAX_T").unwrap_or(MAX_T).clamp(2, MAX_T); + s.max_t = max_t; + s.mtp_max_t = max_t; + s.adaptive = Some(super::super::original_spec_adaptive_env::from_environment( + AdaptiveConfig::new(max_t, max_t - 1), + env, + )); } s } /// Adaptive window or the fixed mode17 window: an explicit `LELEKA_SPEC_ADAPTIVE` (`on`/`1`/`yes` or `off`/`0`/`no`) decides; otherwise /// a fixed `LELEKA_SPEC=N` means the fixed window and nothing set means [`ADAPTIVE_DEFAULT`]. - pub(crate) fn adaptive_wanted(explicit:Option<&str>,fixed_spec_set:bool)->bool { + pub(crate) fn adaptive_wanted(explicit: Option<&str>, fixed_spec_set: bool) -> bool { match explicit { - Some("on"|"1"|"yes")=>true, - Some("off"|"0"|"no")=>false, - _=>!fixed_spec_set&&ADAPTIVE_DEFAULT, + Some("on" | "1" | "yes") => true, + Some("off" | "0" | "no") => false, + _ => !fixed_spec_set && ADAPTIVE_DEFAULT, } } /// `LELEKA_SPEC_ARMS=fixed3,fixed4,fixed6,adaptive`: named window policies one process can switch between per request (an /// A/B inside one model load, same tier and caches). `fixedN` is the Original's `--spec N` (suffix 3), `adaptive` the /// adaptive window; the verifier is built for the widest arm. Empty when unset. pub(crate) fn arms_from_environment( - max_context:i64,vocabulary:u32,coupled:bool,env:&impl EnvSource, - )->Vec<(String,Self)> { - let Some(list)=env.get("LELEKA_SPEC_ARMS") else {return Vec::new()}; - let base=Self::from_environment(max_context,vocabulary,coupled,env); - let mut arms=Vec::new(); - for entry in list.split(',').map(str::trim).filter(|l|!l.is_empty()) { + max_context: i64, + vocabulary: u32, + coupled: bool, + env: &impl EnvSource, + ) -> Vec<(String, Self)> { + let Some(list) = env.get("LELEKA_SPEC_ARMS") else { return Vec::new() }; + let base = Self::from_environment(max_context, vocabulary, coupled, env); + let mut arms = Vec::new(); + for entry in list.split(',').map(str::trim).filter(|l| !l.is_empty()) { // `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay harness's, the label keeps them - let main=entry.split_once('+').map_or(entry,|(m,_)|m); + let main = entry.split_once('+').map_or(entry, |(m, _)| m); // `~key=value` suffixes set constants of the adaptive policy for this arm alone (`adaptive@0~step=0.3~explore=0`, // `AdaptiveConfig::set_option`); an unknown key drops the arm - let mut options=main.split('~'); - let main=options.next().unwrap_or(main); - let (label,min_p)=match main.split_once('@') { - Some((l,p))=>(l,p.parse::().ok()), - None=>(main,None), + let mut options = main.split('~'); + let main = options.next().unwrap_or(main); + let (label, min_p) = match main.split_once('@') { + Some((l, p)) => (l, p.parse::().ok()), + None => (main, None), }; - let mut s=base;s.adaptive=None;s.request_min_p=min_p; - if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::().ok()) { - let n=n.clamp(2,MAX_T);s.max_t=(n+2).min(MAX_T);s.mtp_max_t=n;s.suffix_min_match=3; - } else if label=="adaptive" { - s.max_t=MAX_T;s.mtp_max_t=MAX_T;s.suffix_min_match=3; - let mut cfg=super::super::original_spec_adaptive_env::from_environment(AdaptiveConfig::new(MAX_T,MAX_T-1),env); - if !options.all(|o|o.split_once('=').is_some_and(|(k,v)|cfg.set_option(k,v))) {continue;} - s.adaptive=Some(cfg); - } else {continue;} - arms.push((entry.to_owned(),s)); + let mut s = base; + s.adaptive = None; + s.request_min_p = min_p; + if let Some(n) = label.strip_prefix("fixed").and_then(|n| n.parse::().ok()) { + let n = n.clamp(2, MAX_T); + s.max_t = (n + 2).min(MAX_T); + s.mtp_max_t = n; + s.suffix_min_match = 3; + } else if label == "adaptive" { + s.max_t = MAX_T; + s.mtp_max_t = MAX_T; + s.suffix_min_match = 3; + let mut cfg = super::super::original_spec_adaptive_env::from_environment( + AdaptiveConfig::new(MAX_T, MAX_T - 1), + env, + ); + if !options.all(|o| o.split_once('=').is_some_and(|(k, v)| cfg.set_option(k, v))) { + continue; + } + s.adaptive = Some(cfg); + } else { + continue; + } + arms.push((entry.to_owned(), s)); } arms } /// The same policy for a verifier that records windows only up to `cap` rows (a window graph did not fit in device memory): the /// widest window, the MTP chain and the adaptive policy's bounds are cut to it, everything else is unchanged. - pub(crate) fn with_window_cap(mut self,cap:usize)->Self { - let cap=cap.clamp(1,MAX_T); - self.max_t=self.max_t.min(cap);self.mtp_max_t=self.mtp_max_t.min(self.max_t); - if let Some(a)=self.adaptive.as_mut() {a.max_t=a.max_t.min(self.max_t);a.max_drafts=a.max_drafts.min(a.max_t.saturating_sub(1));} + pub(crate) fn with_window_cap(mut self, cap: usize) -> Self { + let cap = cap.clamp(1, MAX_T); + self.max_t = self.max_t.min(cap); + self.mtp_max_t = self.mtp_max_t.min(self.max_t); + if let Some(a) = self.adaptive.as_mut() { + a.max_t = a.max_t.min(self.max_t); + a.max_drafts = a.max_drafts.min(a.max_t.saturating_sub(1)); + } self } /// Draft cap the engine shares with the controller's `DraftPreparation`. - pub(crate) fn max_drafts(&self)->usize {self.mtp_max_t.min(self.max_t).saturating_sub(1)} + pub(crate) fn max_drafts(&self) -> usize { + self.mtp_max_t.min(self.max_t).saturating_sub(1) + } /// The width the MTP drafter is LOADED with: generate.cpp rewrites `o.spec` to the verify width (`min(spec+2, 8)`, line 1537) /// before `mtp.load(..., o.spec, ...)` (line 2610), so the drafter accepts every window the verifier runs (suffix drafts go up to /// `max_t`) while its own chain stays capped by `max_drafts()` (`set_max_drafts(S_mtp - 1)`). Loading it at `mtp_max_t` made every /// window wider than that fail `draft` (`T > max_t_`) with InvalidQwenShape. - pub(crate) fn mtp_load_t(&self)->usize {self.max_t} + pub(crate) fn mtp_load_t(&self) -> usize { + self.max_t + } /// The one production call of `OriginalSpecController::new`. - pub(crate) fn controller(&self)->Result { - OriginalSpecController::new(SpecConfig::new(self.max_t,self.mtp_max_t,self.max_context,self.vocabulary, - self.suffix_min_match,self.coupled)?.with_adaptive(self.adaptive).with_nan_guard(self.nan_guard)) + pub(crate) fn controller(&self) -> Result { + OriginalSpecController::new( + SpecConfig::new( + self.max_t, + self.mtp_max_t, + self.max_context, + self.vocabulary, + self.suffix_min_match, + self.coupled, + )? + .with_adaptive(self.adaptive) + .with_nan_guard(self.nan_guard), + ) } } /// generate.cpp's serve loop for one request: begin, then verify/commit, emit the committed /// tokens, finish the round (draft + adaptive join + drain), repeat; `finish_request` waits the /// last commit before anything reads the session. `emit` runs only AFTER the commit succeeded. -pub(crate) fn serve_request(controller:&mut OriginalSpecController,engine:&mut E, - prompt:&[i32],max_new:usize,min_p:f32,eos:&[i32],mut emit:impl FnMut(&[i32])->Result<()>, - mut cancel:impl FnMut()->bool,mut clock_ms:impl FnMut()->f64)->std::result::Result { - let begin_span=super::super::original_serve_profile::span("ctrl.begin_request"); - controller.begin_request(prompt,max_new,min_p,eos)?; +pub(crate) fn serve_request( + controller: &mut OriginalSpecController, + engine: &mut E, + prompt: &[i32], + max_new: usize, + min_p: f32, + eos: &[i32], + mut emit: impl FnMut(&[i32]) -> Result<()>, + mut cancel: impl FnMut() -> bool, + mut clock_ms: impl FnMut() -> f64, +) -> std::result::Result { + let begin_span = super::super::original_serve_profile::span("ctrl.begin_request"); + controller.begin_request(prompt, max_new, min_p, eos)?; drop(begin_span); - let (mut produced,mut rounds,mut stop)=(0usize,0usize,None); - let looped=(||->std::result::Result<(),SpecError> { + let (mut produced, mut rounds, mut stop) = (0usize, 0usize, None); + let looped = (|| -> std::result::Result<(), SpecError> { while !controller.finished() { - let started=clock_ms(); - let vc_span=super::super::original_serve_profile::span("round.verify_commit"); - let Some(round)=controller.verify_commit(engine,&mut cancel)? else {break}; + let started = clock_ms(); + let vc_span = super::super::original_serve_profile::span("round.verify_commit"); + let Some(round) = controller.verify_commit(engine, &mut cancel)? else { break }; drop(vc_span); - let emit_span=super::super::original_serve_profile::span("round.emit"); - let emitted=emit(round.tokens()); + let emit_span = super::super::original_serve_profile::span("round.emit"); + let emitted = emit(round.tokens()); drop(emit_span); - produced+=round.tokens().len();rounds+=1; - if round.stopped_on_eos() {stop=Some(ServeStop::Eos);} + produced += round.tokens().len(); + rounds += 1; + if round.stopped_on_eos() { + stop = Some(ServeStop::Eos); + } // A failed emit still finishes the round (drain + join) before reporting. - let fr_span=super::super::original_serve_profile::span("round.finish"); - let finished=controller.finish_round(engine,round,||clock_ms()-started,&mut cancel); + let fr_span = super::super::original_serve_profile::span("round.finish"); + let finished = controller.finish_round(engine, round, || clock_ms() - started, &mut cancel); drop(fr_span); - emitted?;finished?; + emitted?; + finished?; } Ok(()) })(); - if let Err(e)=looped { + if let Err(e) = looped { // Close the request best-effort (waits the last commit) so the controller is reusable // unless a restore/finish failure already marked it failed. - let _=controller.finish_request(engine);return Err(e); + let _ = controller.finish_request(engine); + return Err(e); } controller.finish_request(engine)?; - let stop=stop.unwrap_or(if produced>=max_new {ServeStop::Length} else {ServeStop::Context}); - Ok(ServeOutcome{stop,produced,rounds}) + let stop = stop.unwrap_or(if produced >= max_new { ServeStop::Length } else { ServeStop::Context }); + Ok(ServeOutcome { stop, produced, rounds }) } pub(super) fn tr_port(name: &str, f: impl FnOnce() -> Result) -> Result { let started = std::time::Instant::now(); let r = f(); if crate::bringup_trace_enabled() { - let state = match &r { Ok(_) => "ok".to_string(), Err(e) => format!("ERR {e:?}") }; - eprintln!("DBG[{:.0}s] port.{name} {:.3}ms -> {state}", crate::qwen_forward::original_serve_stack::dbg_el(), - started.elapsed().as_secs_f64() * 1e3); + let state = match &r { + Ok(_) => "ok".to_string(), + Err(e) => format!("ERR {e:?}"), + }; + eprintln!( + "DBG[{:.0}s] port.{name} {:.3}ms -> {state}", + crate::qwen_forward::original_serve_stack::dbg_el(), + started.elapsed().as_secs_f64() * 1e3 + ); } r } @@ -180,33 +278,90 @@ impl OriginalServePort for TracePort

{ type TargetCheckpoint = P::TargetCheckpoint; type DraftCheckpoint = P::DraftCheckpoint; type Adaptive = P::Adaptive; - fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { tr_port("validate_current", || self.0.validate_current(consumed, input, position)) } - fn checkpoint_target(&self) -> Result { tr_port("checkpoint_target", || self.0.checkpoint_target()) } - fn checkpoint_draft(&self) -> Result { tr_port("checkpoint_draft", || self.0.checkpoint_draft()) } - fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> { tr_port("restore_target", || self.0.restore_target(c)) } - fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> { tr_port("restore_draft", || self.0.restore_draft(c)) } - fn apply_pending(&mut self) -> Result<()> { tr_port("apply_pending", || self.0.apply_pending()) } + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + tr_port("validate_current", || self.0.validate_current(consumed, input, position)) + } + fn checkpoint_target(&self) -> Result { + tr_port("checkpoint_target", || self.0.checkpoint_target()) + } + fn checkpoint_draft(&self) -> Result { + tr_port("checkpoint_draft", || self.0.checkpoint_draft()) + } + fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> { + tr_port("restore_target", || self.0.restore_target(c)) + } + fn restore_draft(&mut self, c: &Self::DraftCheckpoint) -> Result<()> { + tr_port("restore_draft", || self.0.restore_draft(c)) + } + fn apply_pending(&mut self) -> Result<()> { + tr_port("apply_pending", || self.0.apply_pending()) + } fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { - crate::bringup_trace!("DBG port.run_window position={position} inputs={inputs:?} consumed_len={}", consumed.len()); + crate::bringup_trace!( + "DBG port.run_window position={position} inputs={inputs:?} consumed_len={}", + consumed.len() + ); tr_port("run_window", || self.0.run_window(position, inputs, consumed)) } - fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> { tr_port("validate_window", || self.0.validate_window(window, position, inputs)) } - fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] { self.0.window_outputs(window) } - fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> { tr_port("commit_window", || self.0.commit_window(window, keep)) } - fn wait_commit(&mut self) -> Result<()> { tr_port("wait_commit", || self.0.wait_commit()) } - fn drain_window(&mut self, window: Self::Window) -> Result<()> { tr_port("drain_window", || self.0.drain_window(window)) } - fn discard_window(&mut self) -> Result<()> { tr_port("discard_window", || self.0.discard_window()) } - fn begin_adaptation(&mut self, next_round: u64) -> Result { tr_port("begin_adaptation", || self.0.begin_adaptation(next_round)) } - fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> { tr_port("join_adaptation", || self.0.join_adaptation(work)) } - fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next)) } - #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self, window: &Self::Window, position: i64, accepted_row: usize, outputs: &[i32], max_drafts: usize, min_p: f32, coupled: bool) -> Result { - tr_port("draft_committed", || self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled)) + fn validate_window(&self, window: &Self::Window, position: i64, inputs: &[i32]) -> Result<()> { + tr_port("validate_window", || self.0.validate_window(window, position, inputs)) + } + fn window_outputs<'a>(&self, window: &'a Self::Window) -> &'a [i32] { + self.0.window_outputs(window) + } + fn commit_window(&mut self, window: &mut Self::Window, keep: usize) -> Result<()> { + tr_port("commit_window", || self.0.commit_window(window, keep)) + } + fn wait_commit(&mut self) -> Result<()> { + tr_port("wait_commit", || self.0.wait_commit()) + } + fn drain_window(&mut self, window: Self::Window) -> Result<()> { + tr_port("drain_window", || self.0.drain_window(window)) + } + fn discard_window(&mut self) -> Result<()> { + tr_port("discard_window", || self.0.discard_window()) + } + fn begin_adaptation(&mut self, next_round: u64) -> Result { + tr_port("begin_adaptation", || self.0.begin_adaptation(next_round)) + } + fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> { + tr_port("join_adaptation", || self.0.join_adaptation(work)) + } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + tr_port("stage_draft_history", || self.0.stage_draft_history(consumed, next)) } - fn drain_draft(&mut self) -> Result<()> { tr_port("drain_draft", || self.0.drain_draft()) } #[allow(clippy::too_many_arguments)] - fn draft_first(&mut self, seed: &Self::Seed, t: usize, cell: i64, token: i32, max_drafts: usize, min_p: f32, coupled: bool) -> Result { + fn draft_committed( + &mut self, + window: &Self::Window, + position: i64, + accepted_row: usize, + outputs: &[i32], + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result { + tr_port("draft_committed", || { + self.0.draft_committed(window, position, accepted_row, outputs, max_drafts, min_p, coupled) + }) + } + fn drain_draft(&mut self) -> Result<()> { + tr_port("drain_draft", || self.0.drain_draft()) + } + #[allow(clippy::too_many_arguments)] + fn draft_first( + &mut self, + seed: &Self::Seed, + t: usize, + cell: i64, + token: i32, + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result { tr_port("draft_first", || self.0.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)) } - fn drain_first(&mut self) -> Result<()> { tr_port("drain_first", || self.0.drain_first()) } + fn drain_first(&mut self) -> Result<()> { + tr_port("drain_first", || self.0.drain_first()) + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs index 47b1feb1..e5d8f8b6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests.rs @@ -1,166 +1,347 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). -use super::*; -use super::super::original_spec_controller::{NanGuard,OriginalSpecController,SpecConfig,SpecError}; +use super::super::original_spec_controller::{NanGuard, OriginalSpecController, SpecConfig, SpecError}; use super::super::original_spec_draft::DraftPreparation; +use super::*; use std::cell::RefCell; -const VOCAB:u32=1000; -fn model(x:i32)->i32 {(x*5+1)%997} +const VOCAB: u32 = 1000; +fn model(x: i32) -> i32 { + (x * 5 + 1) % 997 +} #[derive(Default)] struct World { /// committed target tokens (the session prefix), including the current input. - committed:Vec,events:Vec,commit_waits:usize, - fail:Option<&'static str>,fail_restore:Option<&'static str>, + committed: Vec, + events: Vec, + commit_waits: usize, + fail: Option<&'static str>, + fail_restore: Option<&'static str>, /// tokens the "MTP" drafts: chain of the model, shifted by `skew` to force rejections - skew:i32,sampler_cell:i64, + skew: i32, + sampler_cell: i64, /// the highest cell (+1) a verify window row or a draft touched - max_end:i64, + max_end: i64, +} +struct Win { + inputs: Vec, + outputs: Vec, + position: i64, +} +struct Fake { + w: Rc>, + pending_commit: Option, + pending_position: i64, } -struct Win {inputs:Vec,outputs:Vec,position:i64} -struct Fake {w:Rc>,pending_commit:Option,pending_position:i64} impl Fake { - fn new(prompt:&[i32])->(Self,Rc>) { - let w=Rc::new(RefCell::new(World{committed:prompt.to_vec(),..Default::default()})); - (Self{w:Rc::clone(&w),pending_commit:None,pending_position:0},w) + fn new(prompt: &[i32]) -> (Self, Rc>) { + let w = Rc::new(RefCell::new(World { committed: prompt.to_vec(), ..Default::default() })); + (Self { w: Rc::clone(&w), pending_commit: None, pending_position: 0 }, w) + } + fn log(&self, s: impl Into) { + self.w.borrow_mut().events.push(s.into()); + } + fn fails(&self, what: &str) -> bool { + self.w.borrow().fail == Some(what) } - fn log(&self,s:impl Into) {self.w.borrow_mut().events.push(s.into());} - fn fails(&self,what:&str)->bool {self.w.borrow().fail==Some(what)} } impl OriginalServePort for Fake { - type Window=Win;type Seed=i32;type TargetCheckpoint=(Vec,i64);type DraftCheckpoint=i64;type Adaptive=u64; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - let w=self.w.borrow(); - if w.committed.len() as i64!=position+1||&w.committed[..consumed.len()]!=consumed||w.committed[position as usize]!=input {return Err(Error::IdentityMismatch);} + type Window = Win; + type Seed = i32; + type TargetCheckpoint = (Vec, i64); + type DraftCheckpoint = i64; + type Adaptive = u64; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + let w = self.w.borrow(); + if w.committed.len() as i64 != position + 1 + || &w.committed[..consumed.len()] != consumed + || w.committed[position as usize] != input + { + return Err(Error::IdentityMismatch); + } Ok(()) } - fn checkpoint_target(&self)->Result { - if self.pending_commit.is_some() {return Err(Error::CudaExecution);} - let w=self.w.borrow();Ok((w.committed.clone(),w.sampler_cell)) + fn checkpoint_target(&self) -> Result { + if self.pending_commit.is_some() { + return Err(Error::CudaExecution); + } + let w = self.w.borrow(); + Ok((w.committed.clone(), w.sampler_cell)) } - fn checkpoint_draft(&self)->Result {self.log("ckpt-draft");Ok(self.w.borrow().committed.len() as i64)} - fn restore_target(&mut self,c:&Self::TargetCheckpoint)->Result<()> { + fn checkpoint_draft(&self) -> Result { + self.log("ckpt-draft"); + Ok(self.w.borrow().committed.len() as i64) + } + fn restore_target(&mut self, c: &Self::TargetCheckpoint) -> Result<()> { self.log("restore-target"); - if self.w.borrow().fail_restore==Some("target") {return Err(Error::CudaExecution);} - let mut w=self.w.borrow_mut();w.committed=c.0.clone();w.sampler_cell=c.1;Ok(()) + if self.w.borrow().fail_restore == Some("target") { + return Err(Error::CudaExecution); + } + let mut w = self.w.borrow_mut(); + w.committed = c.0.clone(); + w.sampler_cell = c.1; + Ok(()) } - fn restore_draft(&mut self,_:&i64)->Result<()> { + fn restore_draft(&mut self, _: &i64) -> Result<()> { self.log("restore-draft"); - if self.w.borrow().fail_restore==Some("draft") {return Err(Error::CudaExecution);}Ok(()) + if self.w.borrow().fail_restore == Some("draft") { + return Err(Error::CudaExecution); + } + Ok(()) } - fn apply_pending(&mut self)->Result<()> {self.log("apply-pending");Ok(())} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.log(format!("run t={} consumed={}",inputs.len(),consumed.len())); - if self.fails("run") {return Err(Error::CudaExecution);} + fn apply_pending(&mut self) -> Result<()> { + self.log("apply-pending"); + Ok(()) + } + fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { + self.log(format!("run t={} consumed={}", inputs.len(), consumed.len())); + if self.fails("run") { + return Err(Error::CudaExecution); + } // the window must see the committed branch (async commit already published) - let outputs:Vec=inputs.iter().map(|&x|model(x)).collect(); - self.w.borrow_mut().sampler_cell=position+inputs.len() as i64; - {let mut w=self.w.borrow_mut();w.max_end=w.max_end.max(position+inputs.len() as i64);} - Ok(Win{inputs:inputs.to_vec(),outputs,position}) + let outputs: Vec = inputs.iter().map(|&x| model(x)).collect(); + self.w.borrow_mut().sampler_cell = position + inputs.len() as i64; + { + let mut w = self.w.borrow_mut(); + w.max_end = w.max_end.max(position + inputs.len() as i64); + } + Ok(Win { inputs: inputs.to_vec(), outputs, position }) } - fn validate_window(&self,w:&Win,position:i64,inputs:&[i32])->Result<()> { - if self.fails("validate") {return Err(Error::NonFinite);} - if w.position!=position||w.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) + fn validate_window(&self, w: &Win, position: i64, inputs: &[i32]) -> Result<()> { + if self.fails("validate") { + return Err(Error::NonFinite); + } + if w.position != position || w.inputs != inputs { + return Err(Error::IdentityMismatch); + } + Ok(()) } - fn window_outputs<'a>(&self,w:&'a Win)->&'a[i32] {if self.fails("short") {&w.outputs[..1]} else {&w.outputs}} - fn commit_window(&mut self,w:&mut Win,keep:usize)->Result<()> { + fn window_outputs<'a>(&self, w: &'a Win) -> &'a [i32] { + if self.fails("short") { &w.outputs[..1] } else { &w.outputs } + } + fn commit_window(&mut self, w: &mut Win, keep: usize) -> Result<()> { self.log(format!("commit keep={keep}")); - if self.fails("commit") {return Err(Error::CudaExecution);} - self.pending_commit=Some(keep);self.pending_position=w.position; + if self.fails("commit") { + return Err(Error::CudaExecution); + } + self.pending_commit = Some(keep); + self.pending_position = w.position; // the published prefix is visible only after wait_commit Ok(()) } - fn wait_commit(&mut self)->Result<()> { + fn wait_commit(&mut self) -> Result<()> { if self.pending_commit.take().is_some() { - self.log("wait-commit");self.w.borrow_mut().commit_waits+=1; - if self.fails("wait") {return Err(Error::CudaExecution);} - } + self.log("wait-commit"); + self.w.borrow_mut().commit_waits += 1; + if self.fails("wait") { + return Err(Error::CudaExecution); + } + } Ok(()) } - fn drain_window(&mut self,_:Win)->Result<()> {self.log("drain-window");if self.fails("drain") {Err(Error::CudaExecution)} else {Ok(())}} - fn discard_window(&mut self)->Result<()> {self.log("discard-window");if self.fails("discard") {Err(Error::CudaExecution)} else {Ok(())}} - fn begin_adaptation(&mut self,r:u64)->Result {self.log(format!("begin-adapt {r}"));if self.fails("begin") {Err(Error::CudaExecution)} else {Ok(r)}} - fn join_adaptation(&mut self,r:u64)->Result<()> {self.log(format!("join-adapt {r}"));if self.fails("join") {Err(Error::CudaExecution)} else {Ok(())}} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.log(format!("history {} {next}",consumed.len()));Ok(())} - fn draft_committed(&mut self,w:&Win,position:i64,a:usize,outputs:&[i32],max_drafts:usize,min_p:f32,_coupled:bool)->Result { + fn drain_window(&mut self, _: Win) -> Result<()> { + self.log("drain-window"); + if self.fails("drain") { Err(Error::CudaExecution) } else { Ok(()) } + } + fn discard_window(&mut self) -> Result<()> { + self.log("discard-window"); + if self.fails("discard") { Err(Error::CudaExecution) } else { Ok(()) } + } + fn begin_adaptation(&mut self, r: u64) -> Result { + self.log(format!("begin-adapt {r}")); + if self.fails("begin") { Err(Error::CudaExecution) } else { Ok(r) } + } + fn join_adaptation(&mut self, r: u64) -> Result<()> { + self.log(format!("join-adapt {r}")); + if self.fails("join") { Err(Error::CudaExecution) } else { Ok(()) } + } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + self.log(format!("history {} {next}", consumed.len())); + Ok(()) + } + fn draft_committed( + &mut self, + w: &Win, + position: i64, + a: usize, + outputs: &[i32], + max_drafts: usize, + min_p: f32, + _coupled: bool, + ) -> Result { self.log(format!("draft a={a}")); - if self.fails("draft") {return Err(Error::CudaExecution);} - let skew=self.w.borrow().skew; - let mut ids=vec![(model(outputs[a])+skew).rem_euclid(997)];let mut probs=vec![0.9f32]; - while ids.len()=min_p { - let last=*ids.last().unwrap();ids.push(model(last));probs.push(0.9); + if self.fails("draft") { + return Err(Error::CudaExecution); } - let _=w; - {let mut wd=self.w.borrow_mut();wd.max_end=wd.max_end.max(position+a as i64+ids.len() as i64);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:position+a as i64,accepted_row:a}) + let skew = self.w.borrow().skew; + let mut ids = vec![(model(outputs[a]) + skew).rem_euclid(997)]; + let mut probs = vec![0.9f32]; + while ids.len() < max_drafts.max(1) && probs[ids.len() - 1] >= min_p { + let last = *ids.last().unwrap(); + ids.push(model(last)); + probs.push(0.9); + } + let _ = w; + { + let mut wd = self.w.borrow_mut(); + wd.max_end = wd.max_end.max(position + a as i64 + ids.len() as i64); + } + Ok(DraftCompletion { ids, probabilities: probs, first_cell: position + a as i64, accepted_row: a }) } - fn drain_draft(&mut self)->Result<()> {self.log("drain-draft");Ok(())} - fn draft_first(&mut self,_:&i32,_t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,_c:bool)->Result { + fn drain_draft(&mut self) -> Result<()> { + self.log("drain-draft"); + Ok(()) + } + fn draft_first( + &mut self, + _: &i32, + _t: usize, + cell: i64, + token: i32, + max_drafts: usize, + min_p: f32, + _c: bool, + ) -> Result { self.log("draft-first"); - let mut ids=vec![model(token)];let mut probs=vec![0.9f32]; - while ids.len()=min_p {let l=*ids.last().unwrap();ids.push(model(l));probs.push(0.9);} - Ok(DraftCompletion{ids,probabilities:probs,first_cell:cell,accepted_row:0}) + let mut ids = vec![model(token)]; + let mut probs = vec![0.9f32]; + while ids.len() < max_drafts.max(1) && probs[ids.len() - 1] >= min_p { + let l = *ids.last().unwrap(); + ids.push(model(l)); + probs.push(0.9); + } + Ok(DraftCompletion { ids, probabilities: probs, first_cell: cell, accepted_row: 0 }) + } + fn drain_first(&mut self) -> Result<()> { + self.log("drain-first"); + Ok(()) } - fn drain_first(&mut self)->Result<()> {self.log("drain-first");Ok(())} } -fn engine(prompt:&[i32],max_t:usize)->(OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(prompt); - (OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(),w) +fn engine(prompt: &[i32], max_t: usize) -> (OriginalServeEngine, Rc>) { + let (f, w) = Fake::new(prompt); + (OriginalServeEngine::new(f, VOCAB, max_t, max_t - 1).unwrap(), w) +} +fn events(w: &Rc>) -> Vec { + w.borrow().events.clone() +} +fn idx(e: &[String], needle: &str) -> usize { + e.iter().position(|s| s.starts_with(needle)).unwrap_or_else(|| panic!("missing {needle} in {e:?}")) +} +fn prompt() -> Vec { + vec![11, model(11), model(model(11))] } -fn events(w:&Rc>)->Vec {w.borrow().events.clone()} -fn idx(e:&[String],needle:&str)->usize {e.iter().position(|s|s.starts_with(needle)).unwrap_or_else(||panic!("missing {needle} in {e:?}"))} -fn prompt() -> Vec {vec![11,model(11),model(model(11))]} /// Drive one window by hand the way the controller does (verify, commit). -fn verify_commit(e:&mut OriginalServeEngine,p:i64,inputs:&[i32],consumed:&[i32],keep:usize)->ServedWindow { +fn verify_commit( + e: &mut OriginalServeEngine, + p: i64, + inputs: &[i32], + consumed: &[i32], + keep: usize, +) -> ServedWindow { e.apply_pending().unwrap(); - let mut v=e.verify(p,inputs,consumed).unwrap(); - e.commit_verified(&mut v,keep).unwrap();v + let mut v = e.verify(p, inputs, consumed).unwrap(); + e.commit_verified(&mut v, keep).unwrap(); + v } // ---- end to end: the real controller over this engine ---- -fn run_request(skew:i32,max_t:usize,max_new:usize)->(Vec,Vec) { - let p=prompt_long(); - let (f,w)=Fake::new(&p[..p.len()-1]); +fn run_request(skew: i32, max_t: usize, max_new: usize) -> (Vec, Vec) { + let p = prompt_long(); + let (f, w) = Fake::new(&p[..p.len() - 1]); // Fake's committed prefix tracks tokens through the current input - w.borrow_mut().committed=p.clone();w.borrow_mut().skew=skew; - let mut e=OriginalServeEngine::new(f,VOCAB,max_t,max_t-1).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(max_t,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,max_new,0.0,&[]).unwrap(); + w.borrow_mut().committed = p.clone(); + w.borrow_mut().skew = skew; + let mut e = OriginalServeEngine::new(f, VOCAB, max_t, max_t - 1).unwrap(); + let mut c = OriginalSpecController::new(SpecConfig::new(max_t, 0, 4096, VOCAB, 0, false).unwrap()).unwrap(); + c.begin_request(&p, max_new, 0.0, &[]).unwrap(); e.set_min_p(0.0).unwrap(); - let mut out=Vec::new(); + let mut out = Vec::new(); while !c.finished() { // the fake's committed list must follow what the controller commits - let round=match c.verify_commit(&mut e,||false) {Ok(Some(r))=>r,Ok(None)=>break,Err(err)=>panic!("{err:?}")}; + let round = match c.verify_commit(&mut e, || false) { + Ok(Some(r)) => r, + Ok(None) => break, + Err(err) => panic!("{err:?}"), + }; out.extend_from_slice(round.tokens()); w.borrow_mut().committed.extend_from_slice(round.tokens()); - c.finish_round(&mut e,round,||1.0,||false).unwrap(); + c.finish_round(&mut e, round, || 1.0, || false).unwrap(); } c.finish_request(&mut e).unwrap(); - let ev=events(&w);(out,ev) + let ev = events(&w); + (out, ev) +} +fn prompt_long() -> Vec { + let mut v = vec![11]; + for i in 1..40 { + v.push(model(v[i - 1])); + } + v } -fn prompt_long()->Vec {let mut v=vec![11];for i in 1..40 {v.push(model(v[i-1]));}v} -fn serve(p:&[i32],max_new:usize,eos:&[i32],cancel:impl FnMut()->bool,fail_emit_after:Option) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine) { - let (r,out,c,e,_)=serve_in(p,max_new,eos,cancel,fail_emit_after,4096);(r,out,c,e) +fn serve( + p: &[i32], + max_new: usize, + eos: &[i32], + cancel: impl FnMut() -> bool, + fail_emit_after: Option, +) -> (std::result::Result, Vec, OriginalSpecController, OriginalServeEngine) { + let (r, out, c, e, _) = serve_in(p, max_new, eos, cancel, fail_emit_after, 4096); + (r, out, c, e) } -fn serve_in(p:&[i32],max_new:usize,eos:&[i32],mut cancel:impl FnMut()->bool,fail_emit_after:Option,max_context:i64) - ->(std::result::Result,Vec,OriginalSpecController,OriginalServeEngine,Rc>) { - let (f,w)=Fake::new(p); - let s=OriginalServeSettings{max_t:4,mtp_max_t:0,max_context,vocabulary:VOCAB,suffix_min_match:0,coupled:false,adaptive:None,nan_guard:NanGuard::off(),request_min_p:None}; - let mut e=OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_t-1).unwrap(); - let mut c=s.controller().unwrap(); - let mut out=Vec::new(); - let wc=Rc::clone(&w); - let r=serve_request(&mut c,&mut e,p,max_new,0.0,eos,|t|{ - if fail_emit_after.is_some_and(|n|out.len()>=n) {return Err(Error::InputRead);} - out.extend_from_slice(t);wc.borrow_mut().committed.extend_from_slice(t);Ok(()) - },&mut cancel,||0.0); - (r,out,c,e,w) +fn serve_in( + p: &[i32], + max_new: usize, + eos: &[i32], + mut cancel: impl FnMut() -> bool, + fail_emit_after: Option, + max_context: i64, +) -> ( + std::result::Result, + Vec, + OriginalSpecController, + OriginalServeEngine, + Rc>, +) { + let (f, w) = Fake::new(p); + let s = OriginalServeSettings { + max_t: 4, + mtp_max_t: 0, + max_context, + vocabulary: VOCAB, + suffix_min_match: 0, + coupled: false, + adaptive: None, + nan_guard: NanGuard::off(), + request_min_p: None, + }; + let mut e = OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_t - 1).unwrap(); + let mut c = s.controller().unwrap(); + let mut out = Vec::new(); + let wc = Rc::clone(&w); + let r = serve_request( + &mut c, + &mut e, + p, + max_new, + 0.0, + eos, + |t| { + if fail_emit_after.is_some_and(|n| out.len() >= n) { + return Err(Error::InputRead); + } + out.extend_from_slice(t); + wc.borrow_mut().committed.extend_from_slice(t); + Ok(()) + }, + &mut cancel, + || 0.0, + ); + (r, out, c, e, w) } #[path = "tests/constructor_validates_dimensions.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs index d6a50ed2..e592f11d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_engine/tests/constructor_validates_dimensions.rs @@ -3,272 +3,307 @@ #[allow(unused_imports)] use super::*; - #[test] fn constructor_validates_dimensions() { - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,0,4,3).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,0,0).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,4).is_err()); - let (f,_)=Fake::new(&prompt()); - assert!(OriginalServeEngine::new(f,VOCAB,4,3).is_ok()); + let (f, _) = Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f, 0, 4, 3).is_err()); + let (f, _) = Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f, VOCAB, 0, 0).is_err()); + let (f, _) = Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f, VOCAB, 4, 4).is_err()); + let (f, _) = Fake::new(&prompt()); + assert!(OriginalServeEngine::new(f, VOCAB, 4, 3).is_ok()); } #[test] fn verify_returns_all_t_outputs_and_requires_a_drained_window() { - let p=prompt();let (mut e,w)=engine(&p,4); - let consumed=&p[..2];let input=p[2]; - let mut v=e.verify(2,&[input],consumed).unwrap(); - assert_eq!(e.outputs(&v),&[model(input)]); - e.validate_verified(&v,2,&[input]).unwrap(); - assert_eq!(e.validate_verified(&v,3,&[input]),Err(Error::IdentityMismatch)); - assert_eq!(e.validate_verified(&v,2,&[input+1]),Err(Error::IdentityMismatch)); + let p = prompt(); + let (mut e, w) = engine(&p, 4); + let consumed = &p[..2]; + let input = p[2]; + let mut v = e.verify(2, &[input], consumed).unwrap(); + assert_eq!(e.outputs(&v), &[model(input)]); + e.validate_verified(&v, 2, &[input]).unwrap(); + assert_eq!(e.validate_verified(&v, 3, &[input]), Err(Error::IdentityMismatch)); + assert_eq!(e.validate_verified(&v, 2, &[input + 1]), Err(Error::IdentityMismatch)); // a second window while one is live is refused before anything runs - let runs=events(&w).iter().filter(|s|s.starts_with("run")).count(); - assert_eq!(e.verify(2,&[input],consumed).err(),Some(Error::IdentityMismatch)); - assert_eq!(events(&w).iter().filter(|s|s.starts_with("run")).count(),runs); - e.commit_verified(&mut v,1).unwrap(); - assert_eq!(v.committed_rows(),Some(1)); + let runs = events(&w).iter().filter(|s| s.starts_with("run")).count(); + assert_eq!(e.verify(2, &[input], consumed).err(), Some(Error::IdentityMismatch)); + assert_eq!(events(&w).iter().filter(|s| s.starts_with("run")).count(), runs); + e.commit_verified(&mut v, 1).unwrap(); + assert_eq!(v.committed_rows(), Some(1)); e.drain_verified(v).unwrap(); e.wait_commit().unwrap(); } #[test] fn out_of_range_tokens_never_reach_the_port() { - let p=prompt();let (mut e,w)=engine(&p,4); - assert_eq!(e.verify(2,&[VOCAB as i32],&p[..2]).err(),Some(Error::InvalidToken)); - assert_eq!(e.verify(2,&[5],&[-1]).err(),Some(Error::InvalidToken)); - assert!(!events(&w).iter().any(|s|s.starts_with("run"))); - assert_eq!(e.verify(2,&[],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert_eq!(e.verify(2,&[1,2,3,4,5],&p[..2]).err(),Some(Error::IdentityMismatch)); + let p = prompt(); + let (mut e, w) = engine(&p, 4); + assert_eq!(e.verify(2, &[VOCAB as i32], &p[..2]).err(), Some(Error::InvalidToken)); + assert_eq!(e.verify(2, &[5], &[-1]).err(), Some(Error::InvalidToken)); + assert!(!events(&w).iter().any(|s| s.starts_with("run"))); + assert_eq!(e.verify(2, &[], &p[..2]).err(), Some(Error::IdentityMismatch)); + assert_eq!(e.verify(2, &[1, 2, 3, 4, 5], &p[..2]).err(), Some(Error::IdentityMismatch)); } #[test] fn a_short_or_invalid_window_is_drained_not_leaked() { - let p=prompt();let (mut e,w)=engine(&p,4); - w.borrow_mut().fail=Some("short"); - assert_eq!(e.verify(2,&[p[2],model(p[2])],&p[..2]).err(),Some(Error::IdentityMismatch)); - assert!(events(&w).iter().any(|s|s=="drain-window")); - w.borrow_mut().fail=Some("validate"); - assert_eq!(e.verify(2,&[p[2]],&p[..2]).err(),Some(Error::NonFinite)); - w.borrow_mut().fail=None; + let p = prompt(); + let (mut e, w) = engine(&p, 4); + w.borrow_mut().fail = Some("short"); + assert_eq!(e.verify(2, &[p[2], model(p[2])], &p[..2]).err(), Some(Error::IdentityMismatch)); + assert!(events(&w).iter().any(|s| s == "drain-window")); + w.borrow_mut().fail = Some("validate"); + assert_eq!(e.verify(2, &[p[2]], &p[..2]).err(), Some(Error::NonFinite)); + w.borrow_mut().fail = None; // nothing left live: a clean window works again - let v=e.verify(2,&[p[2]],&p[..2]).unwrap();e.drain_verified(v).unwrap(); + let v = e.verify(2, &[p[2]], &p[..2]).unwrap(); + e.drain_verified(v).unwrap(); assert!(!e.is_poisoned()); } #[test] fn commit_checks_the_accepted_prefix_and_only_once() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2];let good=model(a); - let mut v=e.verify(2,&[a,good,good+1],&p[..2]).unwrap(); + let p = prompt(); + let (mut e, _) = engine(&p, 4); + let a = p[2]; + let good = model(a); + let mut v = e.verify(2, &[a, good, good + 1], &p[..2]).unwrap(); // row 2's input (good+1) != output 1 (model(good)) so keep=3 is not a legal prefix - assert_eq!(e.commit_verified(&mut v,3),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,0),Err(Error::IdentityMismatch)); - assert_eq!(e.commit_verified(&mut v,4),Err(Error::IdentityMismatch)); - e.commit_verified(&mut v,2).unwrap(); - assert_eq!(e.commit_verified(&mut v,2),Err(Error::IdentityMismatch)); - e.drain_verified(v).unwrap();e.wait_commit().unwrap(); + assert_eq!(e.commit_verified(&mut v, 3), Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v, 0), Err(Error::IdentityMismatch)); + assert_eq!(e.commit_verified(&mut v, 4), Err(Error::IdentityMismatch)); + e.commit_verified(&mut v, 2).unwrap(); + assert_eq!(e.commit_verified(&mut v, 2), Err(Error::IdentityMismatch)); + e.drain_verified(v).unwrap(); + e.wait_commit().unwrap(); } #[test] fn commit_is_asynchronous_and_the_window_drain_waits_for_its_event() { - let p=prompt();let (mut e,w)=engine(&p,4); - let v=verify_commit(&mut e,2,&[p[2]],&p[..2],1); + let p = prompt(); + let (mut e, w) = engine(&p, 4); + let v = verify_commit(&mut e, 2, &[p[2]], &p[..2], 1); assert!(e.commit_pending()); // checkpoints and validation refuse to read the session mid-commit - assert_eq!(e.checkpoint_target().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.checkpoint_draft().err(),Some(Error::IdentityMismatch)); - assert_eq!(e.validate_current(&p[..2],p[2],2),Err(Error::IdentityMismatch)); - assert_eq!(w.borrow().commit_waits,0); + assert_eq!(e.checkpoint_target().err(), Some(Error::IdentityMismatch)); + assert_eq!(e.checkpoint_draft().err(), Some(Error::IdentityMismatch)); + assert_eq!(e.validate_current(&p[..2], p[2], 2), Err(Error::IdentityMismatch)); + assert_eq!(w.borrow().commit_waits, 0); // the draft (event-dependent) runs before the drain; the drain waits + publishes e.drain_verified(v).unwrap(); - assert_eq!(w.borrow().commit_waits,1); + assert_eq!(w.borrow().commit_waits, 1); assert!(!e.commit_pending()); - let ev=events(&w); - assert!(idx(&ev,"wait-commit")=20); + let (out, ev) = run_request(0, 4, 20); + let mut expect = Vec::new(); + let mut x = *prompt_long().last().unwrap(); + for _ in 0..out.len() { + x = model(x); + expect.push(x); + } + assert_eq!(out, expect); + assert!(out.len() >= 20); // every verify was followed by a commit, a drain, and (while unfinished) a draft - assert!(ev.iter().filter(|s|s.starts_with("commit keep=")).count()>=4); - assert_eq!(ev.iter().filter(|s|s.starts_with("run ")).count(),ev.iter().filter(|s|s.starts_with("commit keep=")).count()); - assert_eq!(ev.iter().filter(|s|*s=="drain-window").count(),ev.iter().filter(|s|s.starts_with("run ")).count()); + assert!(ev.iter().filter(|s| s.starts_with("commit keep=")).count() >= 4); + assert_eq!( + ev.iter().filter(|s| s.starts_with("run ")).count(), + ev.iter().filter(|s| s.starts_with("commit keep=")).count() + ); + assert_eq!(ev.iter().filter(|s| *s == "drain-window").count(), ev.iter().filter(|s| s.starts_with("run ")).count()); } #[test] fn controller_over_the_engine_survives_rejected_drafts() { - let (out,ev)=run_request(3,4,12); - let mut expect=Vec::new();let mut x=*prompt_long().last().unwrap(); - for _ in 0..out.len() {x=model(x);expect.push(x);} - assert_eq!(out,expect,"rejected drafts must never change the greedy text"); - assert!(ev.iter().any(|s|s=="commit keep=1")); + let (out, ev) = run_request(3, 4, 12); + let mut expect = Vec::new(); + let mut x = *prompt_long().last().unwrap(); + for _ in 0..out.len() { + x = model(x); + expect.push(x); + } + assert_eq!(out, expect, "rejected drafts must never change the greedy text"); + assert!(ev.iter().any(|s| s == "commit keep=1")); } #[test] fn controller_both_restores_run_when_the_verifier_fails() { - let p=prompt_long(); - let (f,w)=Fake::new(&p); - let mut e=OriginalServeEngine::new(f,VOCAB,4,3).unwrap(); - let mut c=OriginalSpecController::new(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap()).unwrap(); - c.begin_request(&p,8,0.0,&[]).unwrap(); - w.borrow_mut().fail=Some("run"); - let err=c.verify_commit(&mut e,||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - let ev=events(&w); - assert!(ev.iter().any(|s|s=="restore-target")&&ev.iter().any(|s|s=="restore-draft")); + let p = prompt_long(); + let (f, w) = Fake::new(&p); + let mut e = OriginalServeEngine::new(f, VOCAB, 4, 3).unwrap(); + let mut c = OriginalSpecController::new(SpecConfig::new(4, 0, 4096, VOCAB, 0, false).unwrap()).unwrap(); + c.begin_request(&p, 8, 0.0, &[]).unwrap(); + w.borrow_mut().fail = Some("run"); + let err = c.verify_commit(&mut e, || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::CudaExecution)); + let ev = events(&w); + assert!(ev.iter().any(|s| s == "restore-target") && ev.iter().any(|s| s == "restore-draft")); assert!(!c.is_failed()); } #[test] fn preparation_drives_the_engine_through_after_verified() { - let p=prompt();let (mut e,_)=engine(&p,4); - let a=p[2]; - let mut v=e.verify(2,&[a],&p[..2]).unwrap(); - let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap(); - let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); - let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap(); - assert_eq!(batch.produced(),3); - assert_eq!(batch.ids()[0],model(outs[0])); + let p = prompt(); + let (mut e, _) = engine(&p, 4); + let a = p[2]; + let mut v = e.verify(2, &[a], &p[..2]).unwrap(); + let outs = e.outputs(&v).to_vec(); + e.commit_verified(&mut v, 1).unwrap(); + let prep = DraftPreparation::new(4, 3, VOCAB).unwrap(); + let batch = prep + .after_verified( + &mut e, + &v, + 2, + 0, + &outs, + &p[..3], + &mut crate::qwen_forward::token_memo::PrefixMemo::new(), + 0.0, + false, + ) + .unwrap(); + assert_eq!(batch.produced(), 3); + assert_eq!(batch.ids()[0], model(outs[0])); e.drain_verified(v).unwrap(); } #[test] fn the_adaptive_window_is_selected_by_the_explicit_switch_then_by_a_fixed_spec_then_by_the_default() { - let w=OriginalServeSettings::adaptive_wanted; - assert!(w(Some("on"),false)&&w(Some("1"),true)&&w(Some("yes"),true)); - assert!(!w(Some("off"),false)&&!w(Some("0"),false)&&!w(Some("no"),false)); - assert_eq!(w(None,false),ADAPTIVE_DEFAULT); - assert!(!w(None,true),"a fixed LELEKA_SPEC keeps the fixed window"); + let w = OriginalServeSettings::adaptive_wanted; + assert!(w(Some("on"), false) && w(Some("1"), true) && w(Some("yes"), true)); + assert!(!w(Some("off"), false) && !w(Some("0"), false) && !w(Some("no"), false)); + assert_eq!(w(None, false), ADAPTIVE_DEFAULT); + assert!(!w(None, true), "a fixed LELEKA_SPEC keeps the fixed window"); } #[test] fn a_window_cap_narrows_every_bound_and_leaves_the_rest() { - let mut wide=OriginalServeSettings::mode17(4096,VOCAB,true); - wide.max_t=8;wide.mtp_max_t=8; - wide.adaptive=Some(AdaptiveConfig::new(8,7)); + let mut wide = OriginalServeSettings::mode17(4096, VOCAB, true); + wide.max_t = 8; + wide.mtp_max_t = 8; + wide.adaptive = Some(AdaptiveConfig::new(8, 7)); for cap in 2..=8 { - let s=wide.with_window_cap(cap); - assert_eq!((s.max_t,s.mtp_max_t),(cap,cap),"cap {cap}"); - assert_eq!(s.max_drafts(),cap-1); - let a=s.adaptive.unwrap(); - assert_eq!((a.max_t,a.max_drafts),(cap,cap-1)); + let s = wide.with_window_cap(cap); + assert_eq!((s.max_t, s.mtp_max_t), (cap, cap), "cap {cap}"); + assert_eq!(s.max_drafts(), cap - 1); + let a = s.adaptive.unwrap(); + assert_eq!((a.max_t, a.max_drafts), (cap, cap - 1)); // unchanged: everything that is not a width - assert_eq!((s.max_context,s.vocabulary,s.suffix_min_match,s.coupled),(wide.max_context,wide.vocabulary,wide.suffix_min_match,wide.coupled)); - assert_eq!(s.nan_guard,wide.nan_guard); + assert_eq!( + (s.max_context, s.vocabulary, s.suffix_min_match, s.coupled), + (wide.max_context, wide.vocabulary, wide.suffix_min_match, wide.coupled) + ); + assert_eq!(s.nan_guard, wide.nan_guard); // the controller and the engine accept it - let c=s.controller().unwrap(); - assert!(c.finished()&&!c.is_failed()); - let (f,_)=Fake::new(&prompt_long()); - assert!(OriginalServeEngine::new(f,VOCAB,s.max_t,s.max_drafts()).is_ok(),"cap {cap}"); + let c = s.controller().unwrap(); + assert!(c.finished() && !c.is_failed()); + let (f, _) = Fake::new(&prompt_long()); + assert!(OriginalServeEngine::new(f, VOCAB, s.max_t, s.max_drafts()).is_ok(), "cap {cap}"); } // a cap above the settings changes nothing; a fixed window narrower than the cap keeps its own width - assert_eq!(wide.with_window_cap(8),wide); - let fixed=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!(fixed.with_window_cap(8),fixed); - let narrow=fixed.with_window_cap(3); - assert_eq!((narrow.max_t,narrow.mtp_max_t,narrow.max_drafts()),(3,3,2)); + assert_eq!(wide.with_window_cap(8), wide); + let fixed = OriginalServeSettings::mode17(4096, VOCAB, false); + assert_eq!(fixed.with_window_cap(8), fixed); + let narrow = fixed.with_window_cap(3); + assert_eq!((narrow.max_t, narrow.mtp_max_t, narrow.max_drafts()), (3, 3, 2)); assert!(narrow.adaptive.is_none()); } #[test] fn mode17_settings_follow_generate_defaults() { - let s=OriginalServeSettings::mode17(4096,VOCAB,false); - assert_eq!((s.max_t,s.mtp_max_t,s.suffix_min_match),(6,4,3)); - assert_eq!(s.max_drafts(),3); + let s = OriginalServeSettings::mode17(4096, VOCAB, false); + assert_eq!((s.max_t, s.mtp_max_t, s.suffix_min_match), (6, 4, 3)); + assert_eq!(s.max_drafts(), 3); // the drafter is loaded at the verify width (6), not at its own window width (4): suffix windows are 6 rows wide - assert_eq!(s.mtp_load_t(),6); - assert!(s.mtp_load_t()>=s.max_t&&s.max_drafts()= s.max_t && s.max_drafts() < s.mtp_load_t()); + let c = s.controller().unwrap(); + assert!(c.finished() && !c.is_failed()); + assert!(OriginalServeSettings { max_context: 0, ..s }.controller().is_err()); + assert!(OriginalServeSettings { vocabulary: 0, ..s }.controller().is_err()); } /// Upstream 41cf05a0 `e85567b6`: through the real engine (plan, cap and cross-check of the chain), a request that runs to the /// context's end never touches a cell past it, whatever the distance of the last windows to it. #[test] fn serve_request_to_the_context_end_stays_inside_the_cells_and_ends_as_context() { - let p=prompt_long(); + let p = prompt_long(); for k in 1..=9i64 { - let max_context=p.len() as i64-1+k; - let (r,out,c,e,w)=serve_in(&p,1000,&[],||false,None,max_context); - let r=r.unwrap_or_else(|err|panic!("k {k}: {err:?}")); - assert_eq!(r.stop,ServeStop::Context,"k {k}"); - assert_eq!(out.len() as i64,k,"k {k}: one token per row that fits"); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(w.borrow().max_end<=max_context,"k {k}: touched cell {} of {max_context}",w.borrow().max_end); - assert!(c.finished()&&!c.is_failed()&&!e.is_poisoned()&&!e.commit_pending(),"k {k}"); + let max_context = p.len() as i64 - 1 + k; + let (r, out, c, e, w) = serve_in(&p, 1000, &[], || false, None, max_context); + let r = r.unwrap_or_else(|err| panic!("k {k}: {err:?}")); + assert_eq!(r.stop, ServeStop::Context, "k {k}"); + assert_eq!(out.len() as i64, k, "k {k}: one token per row that fits"); + let mut x = *p.last().unwrap(); + for &t in &out { + x = model(x); + assert_eq!(t, x); + } + assert!(w.borrow().max_end <= max_context, "k {k}: touched cell {} of {max_context}", w.borrow().max_end); + assert!(c.finished() && !c.is_failed() && !e.is_poisoned() && !e.commit_pending(), "k {k}"); } } #[test] fn serve_request_emits_the_greedy_text_and_reports_the_stop() { - let p=prompt_long(); - let (r,out,mut c,_e)=serve(&p,10,&[],||false,None); - let r=r.unwrap(); - assert_eq!(r.stop,ServeStop::Length); - assert!(r.produced>=10&&r.rounds>=1); - assert_eq!(out.len(),r.produced); - let mut x=*p.last().unwrap();for &t in &out {x=model(x);assert_eq!(t,x);} + let p = prompt_long(); + let (r, out, mut c, _e) = serve(&p, 10, &[], || false, None); + let r = r.unwrap(); + assert_eq!(r.stop, ServeStop::Length); + assert!(r.produced >= 10 && r.rounds >= 1); + assert_eq!(out.len(), r.produced); + let mut x = *p.last().unwrap(); + for &t in &out { + x = model(x); + assert_eq!(t, x); + } // the controller is reusable for the next request - assert!(c.begin_request(&p,1,0.0,&[]).is_ok()); + assert!(c.begin_request(&p, 1, 0.0, &[]).is_ok()); } /// Upstream 41cf05a0 `aece46db`: a 1-token prompt (position 0 is the first verify input) speculates like any other. #[test] fn serve_request_with_a_one_token_prompt_speculates() { - let p=vec![11]; - let (r,out,_c,e)=serve(&p,30,&[],||false,None); - let r=r.unwrap(); - assert_eq!((r.stop,r.produced),(ServeStop::Length,out.len())); - assert!(out.len()>=30); - let mut x=11;for &t in &out {x=model(x);assert_eq!(t,x);} - assert!(r.rounds= 30); + let mut x = 11; + for &t in &out { + x = model(x); + assert_eq!(t, x); + } + assert!(r.rounds < out.len(), "speculation accepted drafts: {} rounds for {} tokens", r.rounds, out.len()); + assert!(!e.is_poisoned() && !e.commit_pending()); } #[test] fn serve_request_stops_on_eos() { - let p=prompt_long(); - let third={let mut x=*p.last().unwrap();for _ in 0..3 {x=model(x);}x}; - let (r,out,_c,_e)=serve(&p,50,&[third],||false,None); - assert_eq!(r.unwrap().stop,ServeStop::Eos); - assert_eq!(out.last(),Some(&third)); + let p = prompt_long(); + let third = { + let mut x = *p.last().unwrap(); + for _ in 0..3 { + x = model(x); + } + x + }; + let (r, out, _c, _e) = serve(&p, 50, &[third], || false, None); + assert_eq!(r.unwrap().stop, ServeStop::Eos); + assert_eq!(out.last(), Some(&third)); } #[test] fn serve_request_cancellation_rolls_back_and_closes_the_request() { - let p=prompt_long(); - let mut calls=0; - let (r,_out,c,e)=serve(&p,50,&[],move||{calls+=1;calls>3},None); - assert_eq!(r.err(),Some(SpecError::Cancelled)); - assert!(c.finished(),"a cancelled request is closed"); + let p = prompt_long(); + let mut calls = 0; + let (r, _out, c, e) = serve( + &p, + 50, + &[], + move || { + calls += 1; + calls > 3 + }, + None, + ); + assert_eq!(r.err(), Some(SpecError::Cancelled)); + assert!(c.finished(), "a cancelled request is closed"); assert!(!e.commit_pending()); } #[test] fn serve_request_a_failed_emit_still_finishes_the_round_and_closes_the_request() { - let p=prompt_long(); - let (r,out,c,e)=serve(&p,50,&[],||false,Some(1)); - assert_eq!(r.err(),Some(SpecError::Forward(Error::InputRead))); + let p = prompt_long(); + let (r, out, c, e) = serve(&p, 50, &[], || false, Some(1)); + assert_eq!(r.err(), Some(SpecError::Forward(Error::InputRead))); assert!(!out.is_empty()); - assert!(c.finished()&&!e.commit_pending()); + assert!(c.finished() && !e.commit_pending()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs index 1c23a990..db53ca03 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host.rs @@ -28,18 +28,18 @@ use super::{ original_serve_native::NativeServeHost, original_serve_pool::OriginalServePool, original_serve_profile as profile, - original_serve_verifier::{driver_error, read_ple_history, ServeFailure}, + original_serve_verifier::{ServeFailure, driver_error, read_ple_history}, output_native::OriginalNativePenaltyHistory, session::{ - original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, QwenSession, TargetStepOrigin, + original_prompt::draft::{OriginalDraftCheckpoint, OriginalDraftSession}, }, }; use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalMtpFullPolicy, - OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, OriginalVerifyWindow, - OriginalVerifyWindowResult, SamplerParams, SamplerPath, + Context, DeviceBuffer, NativeHeadSelection, OriginalGpuEvent, OriginalMtpFullPolicy, + OriginalNativeHeadGraphResources, OriginalVerifier, OriginalVerifyGraphResources, OriginalVerifyQsaJournal, + OriginalVerifyWindow, OriginalVerifyWindowResult, SamplerParams, SamplerPath, }; use std::rc::Rc; @@ -113,9 +113,9 @@ mod tests; mod impl_requestsampling; #[allow(unused_imports)] -use impl_requestsampling::serial_publish; +use impl_requestsampling::adapt_defer; #[allow(unused_imports)] use impl_requestsampling::operator_line; #[allow(unused_imports)] -use impl_requestsampling::adapt_defer; +use impl_requestsampling::serial_publish; mod impl_nativeservehost_for_originalservehost; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs index 75daa605..cf8f4fc7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_nativeservehost_for_originalservehost.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { type TargetCheckpoint = LedgerCheckpoint; type DraftCheckpoint = OriginalDraftCheckpoint; @@ -54,7 +53,13 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { let ple_span = profile::span("window.ple"); let ple = if self.session.original_ple_required() { let predecessors = self.session.original_predecessors()?; - Some(InputStage::original_window_ple(self.binding, self.kar.as_deref_mut(), self.context, predecessors, inputs)?) + Some(InputStage::original_window_ple( + self.binding, + self.kar.as_deref_mut(), + self.context, + predecessors, + inputs, + )?) } else { None }; @@ -81,28 +86,31 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { history_span.stop(); let _p = profile::span("window.verifier"); let verifier_clock = super::super::original_serve_pool::window_trace::now(); - let ran = verifier - .run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { - let group_clock = super::super::original_serve_pool::window_trace::now(); - let ran = pool.run_group(rows, sink, copy).map_err(|error| { - pool_error = Some(error); - leleka_cuda_driver::Error::InvalidDriverValue("Original serve expert pool refused a layer group") - }); - if let Some(c) = group_clock { - super::super::original_serve_pool::window_trace::add(super::super::original_serve_pool::window_trace::POOL, c.elapsed().as_secs_f64() * 1e3); - } - ran + let ran = verifier.run(inputs, first, ple.as_deref(), sampling, |rows, sink, copy| { + let group_clock = super::super::original_serve_pool::window_trace::now(); + let ran = pool.run_group(rows, sink, copy).map_err(|error| { + pool_error = Some(error); + leleka_cuda_driver::Error::InvalidDriverValue( + "Original serve expert pool refused a layer group", + ) }); + if let Some(c) = group_clock { + super::super::original_serve_pool::window_trace::add( + super::super::original_serve_pool::window_trace::POOL, + c.elapsed().as_secs_f64() * 1e3, + ); + } + ran + }); if let Some(c) = verifier_clock { verifier_ms = c.elapsed().as_secs_f64() * 1e3; } - ran - .map_err(|error| { - let failure = ServeFailure::from(error); - let class = failure.error; - driver_failure = Some(failure); - class - }) + ran.map_err(|error| { + let failure = ServeFailure::from(error); + let class = failure.error; + driver_failure = Some(failure); + class + }) }, ); if let (Some(c), Some(ple_ms)) = (window_clock, ple_ms) { @@ -140,7 +148,12 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { self.ledger.commit_enqueued(keep) } - fn publish_committed(&mut self, verifier: &mut OriginalVerifier<'ctx, R>, position: i64, committed: &[i32]) -> Result<()> + fn publish_committed( + &mut self, + verifier: &mut OriginalVerifier<'ctx, R>, + position: i64, + committed: &[i32], + ) -> Result<()> where R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, { @@ -151,7 +164,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { let mut next: [Option<_>; 48] = std::array::from_fn(|_| None); { let p = profile::span("publish.workspace"); - let mut workspace = self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = + self.dense.native_batch_workspace(self.binding, self.context)?.ok_or(Error::IdentityMismatch)?; drop(p); // The twelve index checkpoints in one batch after the commit event (one stream drain, pooled buffers), // or one by one with a context synchronize each (LELEKA_SERVE_PUBLISH=serial, the earlier path). @@ -246,7 +260,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { )?; drop(p); let _p = profile::span("draft.drafter"); - let drafted = self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; + let drafted = + self.executor.draft_committed_mtp(self.binding, self.session, self.draft, receipt, min_p, self.policy)?; let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; Ok(DraftCompletion { @@ -293,7 +308,8 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> { } fn finish_draft(&mut self) -> Result { let launched = self.launched.take().ok_or(Error::IdentityMismatch)?; - let drafted = self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; + let drafted = + self.executor.finish_committing_mtp(self.binding, self.session, self.draft, launched, self.policy)?; let first_cell = i64::try_from(drafted.first_position()).map_err(|_| Error::Overflow)? + i64::try_from(drafted.accepted_row()).map_err(|_| Error::Overflow)?; Ok(DraftCompletion { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs index 30ce2e36..57e3f259 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_host/impl_requestsampling.rs @@ -35,8 +35,21 @@ impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { limit: u64, sampling: RequestSampling, ) -> Result { - let HostOwners { binding, dense, context, session, draft, executor, kar, history, pool, qsa, slots, ple_history, policy } = - owners; + let HostOwners { + binding, + dense, + context, + session, + draft, + executor, + kar, + history, + pool, + qsa, + slots, + ple_history, + policy, + } = owners; let position = session.target_origin()?.next_position(); if session.original_state_lag().is_some() || committed.len() as u64 != position @@ -81,7 +94,8 @@ impl<'a, 'ctx> OriginalServeHost<'a, 'ctx> { { let Some(from) = self.session.original_state_lag() else { return Ok(()) }; let position = self.position()?; - let rows = usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; + let rows = + usize::try_from(position.checked_sub(from).ok_or(Error::InvalidPosition)?).map_err(|_| Error::Overflow)?; let base = self.session.original_verified_base()?; let mut gdn: [Option; 48] = std::array::from_fn(|_| None); let mut ordinal = 0usize; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs index c5c21536..e6f5c04f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_ledger.rs @@ -23,9 +23,16 @@ pub(in crate::qwen_forward) struct LedgerCheckpoint { enum Window { Idle, /// `run` started at `position` with `rows` inputs; nothing is published yet. - Open { position: u64, rows: usize }, + Open { + position: u64, + rows: usize, + }, /// `commit` was enqueued for `keep` rows; the session is published when the event completes. - Committing { position: u64, rows: usize, keep: usize }, + Committing { + position: u64, + rows: usize, + keep: usize, + }, } pub(in crate::qwen_forward) struct ServeLedger { @@ -50,7 +57,14 @@ impl ServeLedger { if committed.len() as u64 > limit { return Err(Error::InvalidPosition); } - Ok(Self { committed, limit, window: Window::Idle, dirty: false, failed: false, agreed: Cell::new(PrefixMemo::new()) }) + Ok(Self { + committed, + limit, + window: Window::Idle, + dirty: false, + failed: false, + agreed: Cell::new(PrefixMemo::new()), + }) } /// `committed == consumed`, examining only the tokens appended since the last successful comparison of the same buffer. pub(in crate::qwen_forward) fn agrees_with(&self, consumed: &[i32]) -> bool { @@ -75,11 +89,7 @@ impl ServeLedger { self.failed = true; } fn live(&self) -> Result<()> { - if self.failed { - Err(Error::IdentityMismatch) - } else { - Ok(()) - } + if self.failed { Err(Error::IdentityMismatch) } else { Ok(()) } } /// The controller's view must be the session's: `consumed` is exactly the committed sequence, the @@ -179,7 +189,11 @@ impl ServeLedger { /// The controller asked to undo back to `checkpoint`. Possible only while the session never advanced /// past it (a window that did not publish); the owners are then repaired by the host at the end of /// the decode. A publication in between cannot be undone and poisons the ledger. - pub(in crate::qwen_forward) fn restore(&mut self, checkpoint: &LedgerCheckpoint, session_position: u64) -> Result<()> { + pub(in crate::qwen_forward) fn restore( + &mut self, + checkpoint: &LedgerCheckpoint, + session_position: u64, + ) -> Result<()> { if session_position != checkpoint.position || self.committed.len() != checkpoint.committed_len || matches!(self.window, Window::Committing { .. }) @@ -234,7 +248,10 @@ mod tests { l.committed.extend_from_slice(&t); consumed.extend_from_slice(&t); assert!(l.agrees_with(&consumed), "round {round}"); - assert!(l.validate_current(&consumed, 7, consumed.len() as i64, consumed.len() as u64).is_ok(), "round {round}"); + assert!( + l.validate_current(&consumed, 7, consumed.len() as i64, consumed.len() as u64).is_ok(), + "round {round}" + ); } // the controller's newest token differs from the ledger's, or its length does let n = consumed.len(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_lookahead.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_lookahead.rs index 4d93e1f1..c3f64ce5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_lookahead.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_lookahead.rs @@ -5,7 +5,10 @@ //! (`MADV_WILLNEED`), so they are on the way while layer `l` computes. A prediction only warms pages: it //! never changes which experts are computed or how. `submit` never waits: a prediction still running for an //! earlier layer makes this one skip. -use std::sync::{Arc, Condvar, Mutex, atomic::{AtomicU64, Ordering}}; +use std::sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicU64, Ordering}, +}; use std::thread::JoinHandle; const HIDDEN: usize = 2560; @@ -136,7 +139,9 @@ fn run(shared: &(Mutex, Condvar), stats: &LookaheadStats, routers: &[Box<[ let started = std::time::Instant::now(); if let (Some(router), Some(layout)) = (routers.get(layer), layouts.get(layer)) { let out = &mut logits[..rows * EXPERTS]; - if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &x[..rows * HIDDEN], rows, out).is_ok() { + if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &x[..rows * HIDDEN], rows, out) + .is_ok() + { want.clear(); for t in 0..rows { let lt = &out[t * EXPERTS..(t + 1) * EXPERTS]; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs index be300d5c..bb1f6625 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native.rs @@ -9,11 +9,13 @@ //! (PLE rows, request penalty history/sampler, the CPU expert pool and PCIe plan //! callbacks, target/draft lineage checkpoints, the MTP ring and drafter, and the //! verified-window session publication; see `original_serve_host.rs`). Nothing here fabricates one of them. -use super::contract::{Error,Result}; +use super::contract::{Error, Result}; +use super::original_serve_engine::{DraftCompletion, OriginalServePort}; use super::original_serve_profile as profile; -use super::original_serve_engine::{DraftCompletion,OriginalServePort}; -use leleka_cuda_driver::{NativeHeadSelection,OriginalGpuEvent,OriginalNativeHeadGraphResources,OriginalVerifier, - OriginalVerifyGraphResources,OriginalVerifyWindow,OriginalVerifyWindowResult}; +use leleka_cuda_driver::{ + NativeHeadSelection, OriginalGpuEvent, OriginalNativeHeadGraphResources, OriginalVerifier, + OriginalVerifyGraphResources, OriginalVerifyWindow, OriginalVerifyWindowResult, +}; use std::cell::RefCell; /// What the serving owner must supply for the verified-window serve path. @@ -22,293 +24,104 @@ pub(in crate::qwen_forward) trait NativeServeHost<'ctx> { type DraftCheckpoint; type Adaptive; type Seed; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; - fn checkpoint_target(&self)->Result; - fn checkpoint_draft(&self)->Result; - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; - fn apply_pending(&mut self)->Result<()>; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()>; + fn checkpoint_target(&self) -> Result; + fn checkpoint_draft(&self) -> Result; + fn restore_target(&mut self, checkpoint: &Self::TargetCheckpoint) -> Result<()>; + fn restore_draft(&mut self, checkpoint: &Self::DraftCheckpoint) -> Result<()>; + fn apply_pending(&mut self) -> Result<()>; /// Stage literal per-row penalty histories (counter = cell), the PLE rows and the CPU /// pool/PCIe callbacks, and call `verifier.run` on the authenticated window. - fn run_window+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,inputs:&[i32],consumed:&[i32], - )->Result; + fn run_window + OriginalNativeHeadGraphResources<'ctx>>( + &mut self, + verifier: &mut OriginalVerifier<'ctx, R>, + position: i64, + inputs: &[i32], + consumed: &[i32], + ) -> Result; /// The driver commit for `keep` rows is about to be enqueued (called BEFORE `verifier.commit`, so /// that an uncertain enqueue is already on the books as a commit that may have changed the verifier). - fn commit_enqueued(&mut self,keep:usize)->Result<()>; + fn commit_enqueued(&mut self, keep: usize) -> Result<()>; /// Publish the accepted prefix (target position, predecessors and QSA witnesses; the recurrent /// GDN/PLE state follows lazily) AFTER the driver commit event completed. `committed` are the /// accepted input tokens exactly as the driver staged them. - fn publish_committed+OriginalNativeHeadGraphResources<'ctx>>( - &mut self,verifier:&mut OriginalVerifier<'ctx,R>,position:i64,committed:&[i32], - )->Result<()>; - fn begin_adaptation(&mut self,next_round:u64)->Result; + fn publish_committed + OriginalNativeHeadGraphResources<'ctx>>( + &mut self, + verifier: &mut OriginalVerifier<'ctx, R>, + position: i64, + committed: &[i32], + ) -> Result<()>; + fn begin_adaptation(&mut self, next_round: u64) -> Result; /// Adaptive work a host deferred at `begin_adaptation`: run it now (the draft is launched, the GPU is busy). A host that does its work /// at `begin_adaptation` has nothing to run. `join_adaptation` must run whatever is still deferred. - fn run_deferred_adaptation(&mut self)->Result<()> {Ok(())} - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()>; - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + fn run_deferred_adaptation(&mut self) -> Result<()> { + Ok(()) + } + fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()>; + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()>; /// Literal `OriginalMtpDrafter::draft_from_verifier` over the same ring/snapshot lineage. #[allow(clippy::too_many_arguments)] - fn draft_committed(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,coupled:bool)->Result; + fn draft_committed( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result; /// `draft_committed` in generate.cpp's order: launched while the commit is enqueued and NOT yet published (the /// draft stream waits `after`, the commit event, on the device), BEFORE `publish_committed`... #[allow(clippy::too_many_arguments)] - fn launch_draft(&mut self,window:OriginalVerifyWindow<'ctx>,selection:NativeHeadSelection,position:i64, - accepted_row:usize,max_drafts:usize,min_p:f32,after:Option<&mut OriginalGpuEvent<'ctx>>)->Result<()>; + fn launch_draft( + &mut self, + window: OriginalVerifyWindow<'ctx>, + selection: NativeHeadSelection, + position: i64, + accepted_row: usize, + max_drafts: usize, + min_p: f32, + after: Option<&mut OriginalGpuEvent<'ctx>>, + ) -> Result<()>; /// ...and completed AFTER it, over the published branch. - fn finish_draft(&mut self)->Result; - fn drain_draft(&mut self)->Result<()>; + fn finish_draft(&mut self) -> Result; + fn drain_draft(&mut self) -> Result<()>; #[allow(clippy::too_many_arguments)] - fn draft_first(&mut self,seed:&Self::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result; - fn drain_first(&mut self)->Result<()>; + fn draft_first( + &mut self, + seed: &Self::Seed, + t: usize, + cell: i64, + token: i32, + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result; + fn drain_first(&mut self) -> Result<()>; } /// Receipt of one completed driver window. The head selection is single-use: the /// draft consumes it exactly once, mirroring `draft_from_verifier`'s by-value argument. pub(in crate::qwen_forward) struct NativeWindow { - generation:u64,position:i64,rows:usize,ids:Vec,inputs:Vec, - selection:RefCell>,keep:Option, -} -impl NativeWindow { - pub(in crate::qwen_forward) fn generation(&self)->u64 {self.generation} + generation: u64, + position: i64, + rows: usize, + ids: Vec, + inputs: Vec, + selection: RefCell>, + keep: Option, } -pub(in crate::qwen_forward) struct NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - verifier:OriginalVerifier<'ctx,R>,host:H,pending_publish:Option<(i64,Vec)>,failed:bool, -} -impl<'ctx,R,H> NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - pub(in crate::qwen_forward) fn new(verifier:OriginalVerifier<'ctx,R>,host:H)->Self { - Self{verifier,host,pending_publish:None,failed:false} - } - pub(in crate::qwen_forward) fn verifier(&self)->&OriginalVerifier<'ctx,R> {&self.verifier} - pub(in crate::qwen_forward) fn verifier_mut(&mut self)->&mut OriginalVerifier<'ctx,R> {&mut self.verifier} - pub(in crate::qwen_forward) fn host(&self)->&H {&self.host} - pub(in crate::qwen_forward) fn into_parts(self)->(OriginalVerifier<'ctx,R>,H) {(self.verifier,self.host)} - fn live(&self)->Result<()> {if self.failed {Err(Error::IdentityMismatch)} else {Ok(())}} - /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with - /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target - /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). - fn settle_commit(&mut self)->Result<()> { - let Some((position,expected))=self.pending_publish.take() else { - return match self.verifier.wait_commit() {Ok(())=>Ok(()),Err(_)=>{self.failed=true;Err(Error::CudaExecution)}}; - }; - let waited={let _p=profile::span("commit.wait");self.verifier.wait_commit()}; - if waited.is_err() {self.failed=true;return Err(Error::CudaExecution);} - // The driver staged the commit tokens itself; they must be exactly the accepted prefix. - let staged=match self.verifier.accepted_tokens() {Ok(t)=>t.to_vec(),Err(_)=>{self.failed=true;return Err(Error::CudaExecution);}}; - if staged!=expected {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("commit.publish"); - let published=self.host.publish_committed(&mut self.verifier,position,&expected); - if published.is_err() {self.failed=true;}published - } -} - -/// The two bring-up window traces, read once (they sat on the per-window path). -fn trace_logprobs()->Option { - crate::settings::process().decode.trace_logprobs -} -/// `LELEKA_TRACE_DRAFT=1`: one line per completed draft (position, accepted row, the draft ids and the IEEE bits of their probabilities). The draft's numerics -/// are bit-compared across builds and settings by diffing these lines (draft-round identity gate); nothing reads them in production. -fn trace_draft()->bool { - crate::settings::process().decode.trace_draft -} -fn trace_draft_line(position:i64,accepted_row:usize,c:&DraftCompletion) { - if !trace_draft() {return;} - let bits:Vec=c.probabilities.iter().map(|p|format!("{:08x}",p.to_bits())).collect(); - eprintln!("DRAFT position={position} accepted_row={accepted_row} cell={} ids={:?} pbits=[{}]",c.first_cell,c.ids,bits.join(",")); -} -fn trace_residual()->Option<&'static std::ffi::OsString> { - crate::settings::process().decode.trace_residual.as_ref() -} - -/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized -/// order; A/B control). Default: the draft is enqueued while the commit runs (`draft_waits_for_commit` says whether it also waits for -/// the commit event on the device), and the host publishes the session while the draft's first graph runs. -fn overlap()->bool { - crate::settings::process().decode.overlap -} - -/// Whether the draft stream waits for the verifier's commit event on the device before its first command. -/// Upstream's serve loop does not: `Verifier::commit` (core/verify.cpp, `set_commit_async`) enqueues the commit graph on the verifier's -/// stream and returns, and `MtpDrafter::draft` launches the round graph on the drafter's own stream with no dependency on it ("the drafter -/// (its own stream) reads only this window's final rows and its own K/V"), so the two graphs run side by side. The earlier port enqueued -/// the draft behind the commit event, which put the commit graph (~0.36 ms: 36 GDN layers, 12 QSA appends, the PLE history) in front of -/// every draft on the critical path. `LELEKA_SERVE_DRAFT_AFTER_COMMIT=on` restores that order (A/B control). -fn draft_waits_for_commit()->bool { - crate::settings::process().decode.draft_after_commit -} -#[cfg(test)] -fn draft_waits_for_commit_from(value:Option<&str>)->bool { - crate::settings::text_is_one_of(value,&crate::settings::DRAFT_AFTER_COMMIT_ON) -} - -impl<'ctx,R,H> OriginalServePort for NativeServePort<'ctx,R,H> -where R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<'ctx>,H:NativeServeHost<'ctx> { - type Window=NativeWindow; - type Seed=H::Seed; - type TargetCheckpoint=H::TargetCheckpoint; - type DraftCheckpoint=H::DraftCheckpoint; - type Adaptive=H::Adaptive; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()> { - self.live()?;self.host.validate_current(consumed,input,position) - } - fn checkpoint_target(&self)->Result {self.live()?;self.host.checkpoint_target()} - fn checkpoint_draft(&self)->Result {self.live()?;self.host.checkpoint_draft()} - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()> { - // Whatever was in flight is dead: the window state is discarded by the driver (the - // uncommitted window never touched GDN state, and a committed one is fenced first). - self.pending_publish=None; - let restored=self.host.restore_target(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()> { - let restored=self.host.restore_draft(checkpoint); - if restored.is_err() {self.failed=true;}restored - } - fn apply_pending(&mut self)->Result<()> {self.live()?;let _p=profile::span("round.apply_pending");self.host.apply_pending()} - fn run_window(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.live()?; - let first=usize::try_from(position).map_err(|_|Error::InvalidPosition)?; - let result={let _p=profile::span("round.run_window");self.host.run_window(&mut self.verifier,position,inputs,consumed)?}; - // The driver's own receipt is authoritative: it must describe exactly this window. - let t=inputs.len(); - let ok=result.rows==t&&result.first_position==first&&result.selection.ids().len()==t - &&result.selection.position()==position as u64; - if !ok {self.failed=true;return Err(Error::IdentityMismatch);} - let mut ids=result.selection.ids().to_vec(); - // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks - // the controller verifies drafts against and commits next are the forced text's tokens. - let forced_differ=super::quality_force::apply(position,&mut ids); - if forced_differ>0 {crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}");} - // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. - if let Some(k)=trace_logprobs() { - let mut line:Vec=Vec::new(); - crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}"); - match self.verifier.window_logprobs_topk(&ids,-1,k,&mut line) { - Ok(())=>eprintln!("{}",String::from_utf8_lossy(&line).trim_end()), - Err(e)=>crate::bringup_trace!("DBG logprobs err {e:?}"), - } - } - // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=

): the final residual R of every row of the completed window, - // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. - if let Some(dir)=trace_residual() { - match self.verifier.window_residual_rows() { - Ok((rows,start,values))=>{ - let bytes:Vec=values.iter().flat_map(|v|v.to_le_bytes()).collect(); - static WINDOW_SEQ:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); - let seq=WINDOW_SEQ.fetch_add(1,std::sync::atomic::Ordering::Relaxed); - let path=std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); - eprintln!("DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}",values.len(),path.display()); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG residual write err {e:?}"); } - if let Ok(Some(ladder))=self.verifier.window_ladder_rows() { - let bytes:Vec=ladder.iter().flat_map(|v|v.to_le_bytes()).collect(); - let path=std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); - if let Err(e)=std::fs::write(&path,bytes) { eprintln!("DBG ladder write err {e:?}"); } - } - } - Err(e)=>eprintln!("DBG residual err {e:?}"), - } - } - Ok(NativeWindow{generation:result.generation,position,rows:t,ids,inputs:inputs.to_vec(), - selection:RefCell::new(Some(result.selection)),keep:None}) - } - fn validate_window(&self,window:&NativeWindow,position:i64,inputs:&[i32])->Result<()> { - self.live()?; - if window.position!=position||window.inputs!=inputs {return Err(Error::IdentityMismatch);} - // A capture-only or already-superseded window cannot pass: the driver mints - // `completed_window` only for the genuinely completed current generation. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch)?; - if completed.generation()!=window.generation||completed.rows()!=window.rows - ||completed.first_position()!=usize::try_from(position).map_err(|_|Error::InvalidPosition)? { - return Err(Error::IdentityMismatch); - } - if let Some(selection)=window.selection.borrow().as_ref() { - completed.validate_selection(selection).map_err(|_|Error::IdentityMismatch)?; - } - Ok(()) - } - fn window_outputs<'a>(&self,window:&'a NativeWindow)->&'a[i32] {&window.ids} - fn commit_window(&mut self,window:&mut NativeWindow,keep:usize)->Result<()> { - self.live()?; - if keep==0||keep>window.rows||window.keep.is_some()||self.pending_publish.is_some() {return Err(Error::IdentityMismatch);} - let _p=profile::span("round.commit"); - if let Err(e)=self.host.commit_enqueued(keep) {self.failed=true;return Err(e);} - if let Err(_e)=self.verifier.commit(keep,true) {self.failed=true;return Err(Error::CudaExecution);} - window.keep=Some(keep); - self.pending_publish=Some((window.position,window.inputs[..keep].to_vec()));Ok(()) - } - fn wait_commit(&mut self)->Result<()> {self.settle_commit()} - fn drain_window(&mut self,_window:NativeWindow)->Result<()> { - // The retained residuals belong to the driver bank; they stay alive until the next - // window (the bank, not this receipt, owns them), so draining releases only the receipt. - Ok(()) - } - fn discard_window(&mut self)->Result<()> { - // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) - if self.pending_publish.is_some() {self.failed=true;return Err(Error::IdentityMismatch);} - let _p=profile::span("round.discard_window"); - if let Err(e)=self.verifier.discard_window() { - eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); - self.failed=true;return Err(super::original_serve_verifier::driver_error(&e)); - } - Ok(()) - } - fn begin_adaptation(&mut self,next_round:u64)->Result {self.live()?;let _p=profile::span("round.adapt");self.host.begin_adaptation(next_round)} - fn join_adaptation(&mut self,work:Self::Adaptive)->Result<()> {self.host.join_adaptation(work)} - fn stage_draft_history(&mut self,consumed:&[i32],next:i32)->Result<()> {self.live()?;self.host.stage_draft_history(consumed,next)} - fn draft_committed(&mut self,window:&NativeWindow,position:i64,accepted_row:usize,outputs:&[i32], - max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?; - let _p=profile::span("round.draft_committed"); - // Literal order: commit enqueued first, draft depends on its event on the same stream. - if window.keep!=Some(accepted_row+1)||window.position!=position||outputs!=window.ids.as_slice() { - return Err(Error::IdentityMismatch); - } - if overlap() && self.pending_publish.is_some() { - // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is - // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and - // the draft completes only over that published branch. - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let launched={let _p=profile::span("draft.launch"); - let after=if draft_waits_for_commit() {self.verifier.pending_commit_event()} else {None}; - self.host.launch_draft(completed,selection,position,accepted_row,max_drafts,min_p,after)}; - if let Err(e)=launched {self.failed=true;return Err(e);} - // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow - if let Err(e)={let _p=profile::span("round.adapt_deferred");self.host.run_deferred_adaptation()} {self.failed=true;return Err(e);} - self.settle_commit()?; - let finished={let _p=profile::span("draft.finish");self.host.finish_draft()}; - if finished.is_err() {self.failed=true;} - if let Ok(c)=&finished {trace_draft_line(position,accepted_row,c);} - return finished; - } - // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is - // published before the draft launches. - self.settle_commit()?; - let completed=self.verifier.completed_window().map_err(|_|Error::IdentityMismatch); - let selection=window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); - let (completed,selection)=match (completed,selection) {(Ok(c),Ok(s))=>(c,s),(Err(e),_)|(_,Err(e))=>return Err(e)}; - let draft={let _p=profile::span("draft.mtp");self.host.draft_committed(completed,selection,position,accepted_row,max_drafts,min_p,coupled)}; - if draft.is_err() {self.failed=true;} - if let Ok(c)=&draft {trace_draft_line(position,accepted_row,c);} - draft - } - fn drain_draft(&mut self)->Result<()> { - let drained=self.host.drain_draft(); - if drained.is_err() {self.failed=true;}drained - } - fn draft_first(&mut self,seed:&H::Seed,t:usize,cell:i64,token:i32,max_drafts:usize,min_p:f32,coupled:bool)->Result { - self.live()?; - let c=self.host.draft_first(seed,t,cell,token,max_drafts,min_p,coupled)?; - trace_draft_line(cell,0,&c); - Ok(c) - } - fn drain_first(&mut self)->Result<()> {self.host.drain_first()} +pub(in crate::qwen_forward) struct NativeServePort<'ctx, R, H> +where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + H: NativeServeHost<'ctx>, +{ + verifier: OriginalVerifier<'ctx, R>, + host: H, + pending_publish: Option<(i64, Vec)>, + failed: bool, } #[cfg(test)] @@ -328,3 +141,21 @@ mod tests { assert!(draft_waits_for_commit_from(Some("1"))); } } + +mod impl_nativewindow; +#[allow(unused_imports)] +use impl_nativewindow::draft_waits_for_commit; +#[cfg(test)] +#[allow(unused_imports)] +use impl_nativewindow::draft_waits_for_commit_from; +#[allow(unused_imports)] +use impl_nativewindow::overlap; +#[allow(unused_imports)] +use impl_nativewindow::trace_draft; +#[allow(unused_imports)] +use impl_nativewindow::trace_draft_line; +#[allow(unused_imports)] +use impl_nativewindow::trace_logprobs; +#[allow(unused_imports)] +use impl_nativewindow::trace_residual; +mod impl_originalserveport_for_nativeserveport; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs new file mode 100644 index 00000000..a8f864ec --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_nativewindow.rs @@ -0,0 +1,120 @@ +//! Moved out of the parent module by STRA-338: impl NativeWindow, impl NativeServePort, fn trace_logprobs, fn trace_draft, fn trace_draft_line, fn trace_residual .... + +#[allow(unused_imports)] +use super::*; + +impl NativeWindow { + pub(in crate::qwen_forward) fn generation(&self) -> u64 { + self.generation + } +} +impl<'ctx, R, H> NativeServePort<'ctx, R, H> +where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + H: NativeServeHost<'ctx>, +{ + pub(in crate::qwen_forward) fn new(verifier: OriginalVerifier<'ctx, R>, host: H) -> Self { + Self { verifier, host, pending_publish: None, failed: false } + } + pub(in crate::qwen_forward) fn verifier(&self) -> &OriginalVerifier<'ctx, R> { + &self.verifier + } + pub(in crate::qwen_forward) fn verifier_mut(&mut self) -> &mut OriginalVerifier<'ctx, R> { + &mut self.verifier + } + pub(in crate::qwen_forward) fn host(&self) -> &H { + &self.host + } + pub(in crate::qwen_forward) fn into_parts(self) -> (OriginalVerifier<'ctx, R>, H) { + (self.verifier, self.host) + } + pub(super) fn live(&self) -> Result<()> { + if self.failed { Err(Error::IdentityMismatch) } else { Ok(()) } + } + /// Wait the driver commit event and publish the accepted prefix to the session. Idempotent: with + /// nothing outstanding on our side the driver event must agree. The draft needs the PUBLISHED target + /// branch, so `draft_committed` settles through here too (the engine's later settle is then a no-op). + pub(super) fn settle_commit(&mut self) -> Result<()> { + let Some((position, expected)) = self.pending_publish.take() else { + return match self.verifier.wait_commit() { + Ok(()) => Ok(()), + Err(_) => { + self.failed = true; + Err(Error::CudaExecution) + } + }; + }; + let waited = { + let _p = profile::span("commit.wait"); + self.verifier.wait_commit() + }; + if waited.is_err() { + self.failed = true; + return Err(Error::CudaExecution); + } + // The driver staged the commit tokens itself; they must be exactly the accepted prefix. + let staged = match self.verifier.accepted_tokens() { + Ok(t) => t.to_vec(), + Err(_) => { + self.failed = true; + return Err(Error::CudaExecution); + } + }; + if staged != expected { + self.failed = true; + return Err(Error::IdentityMismatch); + } + let _p = profile::span("commit.publish"); + let published = self.host.publish_committed(&mut self.verifier, position, &expected); + if published.is_err() { + self.failed = true; + } + published + } +} + +/// The two bring-up window traces, read once (they sat on the per-window path). +pub(super) fn trace_logprobs() -> Option { + crate::settings::process().decode.trace_logprobs +} +/// `LELEKA_TRACE_DRAFT=1`: one line per completed draft (position, accepted row, the draft ids and the IEEE bits of their probabilities). The draft's numerics +/// are bit-compared across builds and settings by diffing these lines (draft-round identity gate); nothing reads them in production. +pub(super) fn trace_draft() -> bool { + crate::settings::process().decode.trace_draft +} +pub(super) fn trace_draft_line(position: i64, accepted_row: usize, c: &DraftCompletion) { + if !trace_draft() { + return; + } + let bits: Vec = c.probabilities.iter().map(|p| format!("{:08x}", p.to_bits())).collect(); + eprintln!( + "DRAFT position={position} accepted_row={accepted_row} cell={} ids={:?} pbits=[{}]", + c.first_cell, + c.ids, + bits.join(",") + ); +} +pub(super) fn trace_residual() -> Option<&'static std::ffi::OsString> { + crate::settings::process().decode.trace_residual.as_ref() +} + +/// `LELEKA_SERVE_OVERLAP=off`: settle the commit (wait + publish) before the draft launches (the earlier, serialized +/// order; A/B control). Default: the draft is enqueued while the commit runs (`draft_waits_for_commit` says whether it also waits for +/// the commit event on the device), and the host publishes the session while the draft's first graph runs. +pub(super) fn overlap() -> bool { + crate::settings::process().decode.overlap +} + +/// Whether the draft stream waits for the verifier's commit event on the device before its first command. +/// Upstream's serve loop does not: `Verifier::commit` (core/verify.cpp, `set_commit_async`) enqueues the commit graph on the verifier's +/// stream and returns, and `MtpDrafter::draft` launches the round graph on the drafter's own stream with no dependency on it ("the drafter +/// (its own stream) reads only this window's final rows and its own K/V"), so the two graphs run side by side. The earlier port enqueued +/// the draft behind the commit event, which put the commit graph (~0.36 ms: 36 GDN layers, 12 QSA appends, the PLE history) in front of +/// every draft on the critical path. `LELEKA_SERVE_DRAFT_AFTER_COMMIT=on` restores that order (A/B control). +pub(super) fn draft_waits_for_commit() -> bool { + crate::settings::process().decode.draft_after_commit +} +#[cfg(test)] +pub(super) fn draft_waits_for_commit_from(value: Option<&str>) -> bool { + crate::settings::text_is_one_of(value, &crate::settings::DRAFT_AFTER_COMMIT_ON) +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs new file mode 100644 index 00000000..042983d2 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_native/impl_originalserveport_for_nativeserveport.rs @@ -0,0 +1,297 @@ +//! Moved out of the parent module by STRA-338: impl OriginalServePort_for_NativeServePort. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx, R, H> OriginalServePort for NativeServePort<'ctx, R, H> +where + R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>, + H: NativeServeHost<'ctx>, +{ + type Window = NativeWindow; + type Seed = H::Seed; + type TargetCheckpoint = H::TargetCheckpoint; + type DraftCheckpoint = H::DraftCheckpoint; + type Adaptive = H::Adaptive; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()> { + self.live()?; + self.host.validate_current(consumed, input, position) + } + fn checkpoint_target(&self) -> Result { + self.live()?; + self.host.checkpoint_target() + } + fn checkpoint_draft(&self) -> Result { + self.live()?; + self.host.checkpoint_draft() + } + fn restore_target(&mut self, checkpoint: &Self::TargetCheckpoint) -> Result<()> { + // Whatever was in flight is dead: the window state is discarded by the driver (the + // uncommitted window never touched GDN state, and a committed one is fenced first). + self.pending_publish = None; + let restored = self.host.restore_target(checkpoint); + if restored.is_err() { + self.failed = true; + } + restored + } + fn restore_draft(&mut self, checkpoint: &Self::DraftCheckpoint) -> Result<()> { + let restored = self.host.restore_draft(checkpoint); + if restored.is_err() { + self.failed = true; + } + restored + } + fn apply_pending(&mut self) -> Result<()> { + self.live()?; + let _p = profile::span("round.apply_pending"); + self.host.apply_pending() + } + fn run_window(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { + self.live()?; + let first = usize::try_from(position).map_err(|_| Error::InvalidPosition)?; + let result = { + let _p = profile::span("round.run_window"); + self.host.run_window(&mut self.verifier, position, inputs, consumed)? + }; + // The driver's own receipt is authoritative: it must describe exactly this window. + let t = inputs.len(); + let ok = result.rows == t + && result.first_position == first + && result.selection.ids().len() == t + && result.selection.position() == position as u64; + if !ok { + self.failed = true; + return Err(Error::IdentityMismatch); + } + let mut ids = result.selection.ids().to_vec(); + // Quality gate only (an installed `quality_force` sequence; nothing installs one in production): the picks + // the controller verifies drafts against and commits next are the forced text's tokens. + let forced_differ = super::super::quality_force::apply(position, &mut ids); + if forced_differ > 0 { + crate::bringup_trace!("DBG forced window position={position} picks_replaced={forced_differ}"); + } + // Bring-up diagnostic (LELEKA_TRACE_LOGPROBS=): top-k head logprobs of every row of the completed window. + if let Some(k) = trace_logprobs() { + let mut line: Vec = Vec::new(); + crate::bringup_trace!("DBG logprobs window position={position} inputs={inputs:?} argmax_ids={ids:?}"); + match self.verifier.window_logprobs_topk(&ids, -1, k, &mut line) { + Ok(()) => eprintln!("{}", String::from_utf8_lossy(&line).trim_end()), + Err(e) => crate::bringup_trace!("DBG logprobs err {e:?}"), + } + } + // Bring-up diagnostic (LELEKA_TRACE_RESIDUAL=): the final residual R of every row of the completed window, + // raw little-endian f32 (rows, hc*n_embd), file `r_win_pos.f32`. + if let Some(dir) = trace_residual() { + match self.verifier.window_residual_rows() { + Ok((rows, start, values)) => { + let bytes: Vec = values.iter().flat_map(|v| v.to_le_bytes()).collect(); + static WINDOW_SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let seq = WINDOW_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::path::Path::new(&dir).join(format!("r_win{seq:05}_pos{start}.f32")); + eprintln!( + "DBG residual window seq={seq} first={start} rows={rows} inputs={inputs:?} floats={} -> {}", + values.len(), + path.display() + ); + if let Err(e) = std::fs::write(&path, bytes) { + eprintln!("DBG residual write err {e:?}"); + } + if let Ok(Some(ladder)) = self.verifier.window_ladder_rows() { + let bytes: Vec = ladder.iter().flat_map(|v| v.to_le_bytes()).collect(); + let path = std::path::Path::new(&dir).join(format!("l_win{seq:05}_pos{start}.f32")); + if let Err(e) = std::fs::write(&path, bytes) { + eprintln!("DBG ladder write err {e:?}"); + } + } + } + Err(e) => eprintln!("DBG residual err {e:?}"), + } + } + Ok(NativeWindow { + generation: result.generation, + position, + rows: t, + ids, + inputs: inputs.to_vec(), + selection: RefCell::new(Some(result.selection)), + keep: None, + }) + } + fn validate_window(&self, window: &NativeWindow, position: i64, inputs: &[i32]) -> Result<()> { + self.live()?; + if window.position != position || window.inputs != inputs { + return Err(Error::IdentityMismatch); + } + // A capture-only or already-superseded window cannot pass: the driver mints + // `completed_window` only for the genuinely completed current generation. + let completed = self.verifier.completed_window().map_err(|_| Error::IdentityMismatch)?; + if completed.generation() != window.generation + || completed.rows() != window.rows + || completed.first_position() != usize::try_from(position).map_err(|_| Error::InvalidPosition)? + { + return Err(Error::IdentityMismatch); + } + if let Some(selection) = window.selection.borrow().as_ref() { + completed.validate_selection(selection).map_err(|_| Error::IdentityMismatch)?; + } + Ok(()) + } + fn window_outputs<'a>(&self, window: &'a NativeWindow) -> &'a [i32] { + &window.ids + } + fn commit_window(&mut self, window: &mut NativeWindow, keep: usize) -> Result<()> { + self.live()?; + if keep == 0 || keep > window.rows || window.keep.is_some() || self.pending_publish.is_some() { + return Err(Error::IdentityMismatch); + } + let _p = profile::span("round.commit"); + if let Err(e) = self.host.commit_enqueued(keep) { + self.failed = true; + return Err(e); + } + if let Err(_e) = self.verifier.commit(keep, true) { + self.failed = true; + return Err(Error::CudaExecution); + } + window.keep = Some(keep); + self.pending_publish = Some((window.position, window.inputs[..keep].to_vec())); + Ok(()) + } + fn wait_commit(&mut self) -> Result<()> { + self.settle_commit() + } + fn drain_window(&mut self, _window: NativeWindow) -> Result<()> { + // The retained residuals belong to the driver bank; they stay alive until the next + // window (the bank, not this receipt, owns them), so draining releases only the receipt. + Ok(()) + } + fn discard_window(&mut self) -> Result<()> { + // an enqueued commit cannot be undone; the controller restores the checkpoints first (which clears `pending_publish`) + if self.pending_publish.is_some() { + self.failed = true; + return Err(Error::IdentityMismatch); + } + let _p = profile::span("round.discard_window"); + if let Err(e) = self.verifier.discard_window() { + eprintln!("leleka-serve nan-guard: the verifier could not take the refused window back ({e:?})"); + self.failed = true; + return Err(super::super::original_serve_verifier::driver_error(&e)); + } + Ok(()) + } + fn begin_adaptation(&mut self, next_round: u64) -> Result { + self.live()?; + let _p = profile::span("round.adapt"); + self.host.begin_adaptation(next_round) + } + fn join_adaptation(&mut self, work: Self::Adaptive) -> Result<()> { + self.host.join_adaptation(work) + } + fn stage_draft_history(&mut self, consumed: &[i32], next: i32) -> Result<()> { + self.live()?; + self.host.stage_draft_history(consumed, next) + } + fn draft_committed( + &mut self, + window: &NativeWindow, + position: i64, + accepted_row: usize, + outputs: &[i32], + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result { + self.live()?; + let _p = profile::span("round.draft_committed"); + // Literal order: commit enqueued first, draft depends on its event on the same stream. + if window.keep != Some(accepted_row + 1) || window.position != position || outputs != window.ids.as_slice() { + return Err(Error::IdentityMismatch); + } + if overlap() && self.pending_publish.is_some() { + // generate.cpp: commit -> draft on one stream, the host waits only for the draft's tokens. The draft is + // enqueued behind the commit event; the session is published (commit wait, witnesses) while it runs, and + // the draft completes only over that published branch. + let completed = self.verifier.completed_window().map_err(|_| Error::IdentityMismatch); + let selection = window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed, selection) = match (completed, selection) { + (Ok(c), Ok(s)) => (c, s), + (Err(e), _) | (_, Err(e)) => return Err(e), + }; + let launched = { + let _p = profile::span("draft.launch"); + let after = if draft_waits_for_commit() { self.verifier.pending_commit_event() } else { None }; + self.host.launch_draft(completed, selection, position, accepted_row, max_drafts, min_p, after) + }; + if let Err(e) = launched { + self.failed = true; + return Err(e); + } + // the GPU is on the draft now: the adaptive planning/queueing the host deferred runs in its shadow + if let Err(e) = { + let _p = profile::span("round.adapt_deferred"); + self.host.run_deferred_adaptation() + } { + self.failed = true; + return Err(e); + } + self.settle_commit()?; + let finished = { + let _p = profile::span("draft.finish"); + self.host.finish_draft() + }; + if finished.is_err() { + self.failed = true; + } + if let Ok(c) = &finished { + trace_draft_line(position, accepted_row, c); + } + return finished; + } + // Serialized: the MTP receipt names the PUBLISHED branch, the commit event completes and the session is + // published before the draft launches. + self.settle_commit()?; + let completed = self.verifier.completed_window().map_err(|_| Error::IdentityMismatch); + let selection = window.selection.borrow_mut().take().ok_or(Error::IdentityMismatch); + let (completed, selection) = match (completed, selection) { + (Ok(c), Ok(s)) => (c, s), + (Err(e), _) | (_, Err(e)) => return Err(e), + }; + let draft = { + let _p = profile::span("draft.mtp"); + self.host.draft_committed(completed, selection, position, accepted_row, max_drafts, min_p, coupled) + }; + if draft.is_err() { + self.failed = true; + } + if let Ok(c) = &draft { + trace_draft_line(position, accepted_row, c); + } + draft + } + fn drain_draft(&mut self) -> Result<()> { + let drained = self.host.drain_draft(); + if drained.is_err() { + self.failed = true; + } + drained + } + fn draft_first( + &mut self, + seed: &H::Seed, + t: usize, + cell: i64, + token: i32, + max_drafts: usize, + min_p: f32, + coupled: bool, + ) -> Result { + self.live()?; + let c = self.host.draft_first(seed, t, cell, token, max_drafts, min_p, coupled)?; + trace_draft_line(cell, 0, &c); + Ok(c) + } + fn drain_first(&mut self) -> Result<()> { + self.host.drain_first() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs index 0bb13755..10733c98 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool.rs @@ -12,15 +12,15 @@ //! so no expert is a GPU hit or a PCIe copy and the copy-from-mapped kernel takes every slot from here. //! A GPU slot cache with a non-empty plan is a different pool implementation behind the same trait //! (`original_serve_residency::GpuExpertPool`), which hands this pool only the entries it must compute. +use super::original_serve_lookahead::{LayerLayout, RouterLookahead}; use super::{ contract::{Error, Result}, - cpu_expert_miss::{runtime_error, validate_triplet, CpuMissWorkspace}, + cpu_expert_miss::{CpuMissWorkspace, runtime_error, validate_triplet}, input::binding_error, }; use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeMatrixRole, MoeRoutedSourceScope}; use leleka_cuda_driver::{OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink}; use leleka_model_format::qwen4exp::ResidentExpertBankSpan; -use super::original_serve_lookahead::{LayerLayout, RouterLookahead}; use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat}; const HIDDEN: usize = 2560; @@ -36,8 +36,21 @@ const BATCH_ALLOWANCE: usize = 48 << 20; pub(in crate::qwen_forward) mod window_trace { use std::cell::Cell; use std::time::Instant; - pub(in crate::qwen_forward) const NAMES: [&str; 13] = - ["pool", "gpu_split", "plan", "prepare", "start", "join", "validate", "scatter", "experts", "entries", "fetch", "pcie_spans", "pcie_experts"]; + pub(in crate::qwen_forward) const NAMES: [&str; 13] = [ + "pool", + "gpu_split", + "plan", + "prepare", + "start", + "join", + "validate", + "scatter", + "experts", + "entries", + "fetch", + "pcie_spans", + "pcie_experts", + ]; pub(in crate::qwen_forward) const POOL: usize = 0; pub(in crate::qwen_forward) const GPU_SPLIT: usize = 1; pub(in crate::qwen_forward) const PLAN: usize = 2; @@ -167,30 +180,30 @@ mod tests; mod prefetch_off_file_exists_fn; #[allow(unused_imports)] -use prefetch_off_file_exists_fn::prefetch_off_file_exists; +use prefetch_off_file_exists_fn::admit_job; +#[allow(unused_imports)] +use prefetch_off_file_exists_fn::open_job; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::output_offset; #[cfg(test)] #[allow(unused_imports)] pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::plan_experts; #[allow(unused_imports)] pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::plan_experts_where; #[allow(unused_imports)] -pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::output_offset; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::scatter; -#[allow(unused_imports)] -use prefetch_off_file_exists_fn::open_job; -#[allow(unused_imports)] -use prefetch_off_file_exists_fn::admit_job; +use prefetch_off_file_exists_fn::prefetch_off_file_exists; #[allow(unused_imports)] use prefetch_off_file_exists_fn::same_spans; -mod impl_directtier; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use prefetch_off_file_exists_fn::scatter; mod impl_cpuexpertpool; +mod impl_directtier; mod impl_drop_for_directtier; #[allow(unused_imports)] use impl_drop_for_directtier::admit_eager; #[allow(unused_imports)] -use impl_drop_for_directtier::sink_result; -#[allow(unused_imports)] use impl_drop_for_directtier::native_cpu_error; #[allow(unused_imports)] use impl_drop_for_directtier::selection; +#[allow(unused_imports)] +use impl_drop_for_directtier::sink_result; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs index a93ecaa7..bfd3192b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_cpuexpertpool.rs @@ -100,7 +100,12 @@ impl CpuExpertPool<'_> { let mut refs: Vec> = Vec::new(); refs.try_reserve_exact(opened.len()).map_err(|_| Error::InputAllocation)?; for (spans, _, _) in opened { - refs.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &[] }); + refs.push(BorrowedExpert { + gate: spans[0].bytes(), + up: spans[1].bytes(), + down: spans[2].bytes(), + pairs: &[], + }); } for chunk in refs.chunks(leleka_native_cpu_expert::MAX_JOBS) { pool.prefetch(gu, down, chunk).map_err(|e| runtime_error(native_cpu_error(e)))?; @@ -110,12 +115,17 @@ impl CpuExpertPool<'_> { Ok(()) })?; drop(open_span); - if tier.lookahead_enabled && tier.lookahead.is_none() && opened.iter().any(|(s, _, _)| s.iter().any(ResidentExpertBankSpan::file_mapped)) { + if tier.lookahead_enabled + && tier.lookahead.is_none() + && opened.iter().any(|(s, _, _)| s.iter().any(ResidentExpertBankSpan::file_mapped)) + { // Once: the routers' BF16 host copies and the bank layout of every layer, then the thread. tier.lookahead_enabled = false; match tier.start_lookahead(binding) { Ok(lookahead) => { - eprintln!("leleka-serve cpu expert pool: router lookahead on (mapped experts, LELEKA_CPU_POOL_LOOKAHEAD=on)"); + eprintln!( + "leleka-serve cpu expert pool: router lookahead on (mapped experts, LELEKA_CPU_POOL_LOOKAHEAD=on)" + ); tier.lookahead = Some(lookahead); } Err(e) => eprintln!("leleka-serve cpu expert pool: WARNING: router lookahead not started ({e:?})"), @@ -130,7 +140,12 @@ impl CpuExpertPool<'_> { let mut experts: Vec> = Vec::new(); experts.try_reserve_exact(plan.len()).map_err(|_| Error::InputAllocation)?; for (job, (spans, _, _)) in plan.iter().zip(&opened) { - experts.push(BorrowedExpert { gate: spans[0].bytes(), up: spans[1].bytes(), down: spans[2].bytes(), pairs: &job.pairs }); + experts.push(BorrowedExpert { + gate: spans[0].bytes(), + up: spans[1].bytes(), + down: spans[2].bytes(), + pairs: &job.pairs, + }); } window_trace::lap(window_trace::PREPARE, clock); window_trace::add(window_trace::PREPARE, -fetch_ms); @@ -193,10 +208,17 @@ impl CpuExpertPool<'_> { /// The PCIe tier's (or an adaptive swap's) source spans of `experts` of `layer`, through the same /// per-job validation and one-time row admission as the CPU's own experts, under one source fence; /// `None` on the legacy path (the caller keeps its per-expert full scan). - pub(in crate::qwen_forward) fn admitted_spans(&mut self, layer: u32, experts: &[u32]) -> Option>> { + pub(in crate::qwen_forward) fn admitted_spans( + &mut self, + layer: u32, + experts: &[u32], + ) -> Option>> { let binding = self.binding; let tier = self.direct.as_mut()?; - Some(tier.open_group(binding, layer, experts, |_, _| Ok(())).map(|opened| opened.into_iter().map(|(spans, _, _)| spans).collect())) + Some( + tier.open_group(binding, layer, experts, |_, _| Ok(())) + .map(|opened| opened.into_iter().map(|(spans, _, _)| spans).collect()), + ) } /// The legacy path's results: owned copies, batches of `JOBS_PER_BATCH` joined in turn, every result @@ -246,7 +268,8 @@ impl CpuExpertPool<'_> { // Re-open the source and require the finished rows to belong to exactly this expert's // gate/up/down descriptors before they may reach the window. let (first_row, first_slot) = job.pairs[0]; - let weights = binding.moe_expert_weights(layer, selection(rows.ids, first_row)?).map_err(binding_error)?; + let weights = + binding.moe_expert_weights(layer, selection(rows.ids, first_row)?).map_err(binding_error)?; let members = [(&weights, first_slot)]; binding.with_moe_routed_source(&members, binding_error, |source| { let keys = [ @@ -268,7 +291,12 @@ impl CpuExpertPool<'_> { } /// Crosscheck: the direct rows already in the destination against the legacy rows, bit for bit. - pub(super) fn compare(&mut self, sink: &mut OriginalVerifyCpuSink<'_, '_>, plan: &[ExpertJob], results: &[(usize, Box<[f32]>)]) -> Result<()> { + pub(super) fn compare( + &mut self, + sink: &mut OriginalVerifyCpuSink<'_, '_>, + plan: &[ExpertJob], + results: &[(usize, Box<[f32]>)], + ) -> Result<()> { let mut differing = 0usize; let mut compared = 0usize; let mut failure = None; @@ -282,7 +310,11 @@ impl CpuExpertPool<'_> { for (i, &(row, slot)) in job.pairs.iter().enumerate() { let at = output_offset(row, slot); let direct = out.get(at..at + HIDDEN).ok_or(leleka_cuda_driver::Error::InvalidQwenShape)?; - differing += direct.iter().zip(&values[i * HIDDEN..(i + 1) * HIDDEN]).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + differing += direct + .iter() + .zip(&values[i * HIDDEN..(i + 1) * HIDDEN]) + .filter(|(a, b)| a.to_bits() != b.to_bits()) + .count(); compared += 1; } } @@ -296,7 +328,10 @@ impl CpuExpertPool<'_> { return Err(Error::IdentityMismatch); } if self.crosscheck.groups % 48 == 0 { - eprintln!("CROSSCHECK cpu pool: {} groups, {} expert rows bit-identical (direct vs legacy)", self.crosscheck.groups, self.crosscheck.rows); + eprintln!( + "CROSSCHECK cpu pool: {} groups, {} expert rows bit-identical (direct vs legacy)", + self.crosscheck.groups, self.crosscheck.rows + ); } Ok(()) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs index 66f406c0..e6f7253e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_directtier.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl DirectTier { /// Admit every routed expert of every layer now (stack open), through the same `open_group` admission the decode runs at an /// expert's first CPU or PCIe use (source scope, descriptor checks, the full FP16-scale scan of `mapped_span`): the checks are @@ -14,7 +13,11 @@ impl DirectTier { let mut admitted = 0usize; for layer in 0..48u32 { for chunk in all.chunks(64) { - admitted += self.open_group(binding, layer, chunk, |_, _| Ok(()))?.iter().filter(|(_, _, ready)| !*ready).count(); + admitted += self + .open_group(binding, layer, chunk, |_, _| Ok(()))? + .iter() + .filter(|(_, _, ready)| !*ready) + .count(); } } Ok(admitted) @@ -78,7 +81,8 @@ impl DirectTier { let mut opened: Vec = Vec::new(); opened.try_reserve_exact(experts.len()).map_err(|_| Error::InputAllocation)?; for &expert in experts { - let (spans, format) = self.opened_cache[Self::index(layer, expert)?].as_ref().ok_or(Error::IdentityMismatch)?; + let (spans, format) = + self.opened_cache[Self::index(layer, expert)?].as_ref().ok_or(Error::IdentityMismatch)?; opened.push((spans.clone(), *format, true)); } between(&mut self.pool, &opened)?; @@ -149,7 +153,9 @@ impl DirectTier { for (i, &expert) in experts.iter().enumerate() { let at = Self::index(layer, expert)?; // admitted now (first use) or before: both leave `held` equal to the opened spans - if self.held[at].as_ref().is_some_and(|h| same_spans(h, &opened[i].0)) && self.opened_cache[at].is_none() { + if self.held[at].as_ref().is_some_and(|h| same_spans(h, &opened[i].0)) + && self.opened_cache[at].is_none() + { self.opened_cache[at] = Some((opened[i].0.clone(), opened[i].1)); } } @@ -190,19 +196,34 @@ impl<'a> CpuExpertPool<'a> { let open_cache_on = pool_settings.open_cache; let prefetch_text = pool_settings.prefetch.as_deref(); let prefetch_mode = super::super::prefetch_policy::Mode::from_value(prefetch_text, cfg!(windows)); - let mut tier = DirectTier { pool, held, routes, group_fence, lookahead_enabled, lookahead: None, next_resident: vec![false; EXPERTS as usize], opened_cache, open_cache_on, - prefetch: super::super::prefetch_policy::PrefetchPolicy::new(prefetch_mode) }; + let mut tier = DirectTier { + pool, + held, + routes, + group_fence, + lookahead_enabled, + lookahead: None, + next_resident: vec![false; EXPERTS as usize], + opened_cache, + open_cache_on, + prefetch: super::super::prefetch_policy::PrefetchPolicy::new(prefetch_mode), + }; if admit_eager() { let started = std::time::Instant::now(); let n = tier.admit_all(binding)?; - eprintln!("leleka-serve cpu expert pool: {n} routed experts admitted at open in {:.2} s (LELEKA_CPU_ADMIT_EAGER=off admits at first use)", started.elapsed().as_secs_f64()); + eprintln!( + "leleka-serve cpu expert pool: {n} routed experts admitted at open in {:.2} s (LELEKA_CPU_ADMIT_EAGER=off admits at first use)", + started.elapsed().as_secs_f64() + ); } Some(tier) } }; let legacy = match path { PoolPath::Direct => None, - PoolPath::Legacy | PoolPath::Crosscheck => Some(CpuMissWorkspace::new(binding, workers).map_err(runtime_error)?), + PoolPath::Legacy | PoolPath::Crosscheck => { + Some(CpuMissWorkspace::new(binding, workers).map_err(runtime_error)?) + } }; if path != PoolPath::Direct { eprintln!("leleka-serve cpu expert pool: {path:?} path (LELEKA_CPU_POOL)"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs index f24ac453..0ce4eb0e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/impl_drop_for_directtier.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Drop for DirectTier { fn drop(&mut self) { if let Some(lookahead) = &self.lookahead { @@ -11,7 +10,10 @@ impl Drop for DirectTier { use std::sync::atomic::Ordering::Relaxed; eprintln!( "leleka-serve router lookahead: {} layers submitted, {} skipped, {} experts warmed, {:.1} ms busy", - s.submitted.load(Relaxed), s.skipped.load(Relaxed), s.predicted.load(Relaxed), s.busy_us.load(Relaxed) as f64 / 1e3 + s.submitted.load(Relaxed), + s.skipped.load(Relaxed), + s.predicted.load(Relaxed), + s.busy_us.load(Relaxed) as f64 / 1e3 ); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs index f105224f..72a79d43 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_pool/prefetch_off_file_exists_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// A bring-up file (`LELEKA_CPU_PREFETCH_OFF_FILE`, A/B inside one engine): while it exists the page-touch pass is skipped, whatever the policy says. pub(super) fn prefetch_off_file_exists() -> bool { let file = crate::settings::process().memory.pool.prefetch_off_file.as_ref(); @@ -19,7 +18,11 @@ pub(in crate::qwen_forward) fn plan_experts(ids: &[i32], rows: usize) -> Result< /// `plan_experts` over the entries `include[row * 10 + slot]` selects (all when `None`); every id is still /// validated. The GPU tier's entries are left out: the CPU only writes their rows as zeros. -pub(in crate::qwen_forward) fn plan_experts_where(ids: &[i32], rows: usize, include: Option<&[bool]>) -> Result> { +pub(in crate::qwen_forward) fn plan_experts_where( + ids: &[i32], + rows: usize, + include: Option<&[bool]>, +) -> Result> { if rows == 0 || rows > 8 || ids.len() != rows * TOP_K || include.is_some_and(|m| m.len() != ids.len()) { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs index 91490daa..b574490b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix.rs @@ -19,7 +19,8 @@ //! cancelled or failed request never claims cells it did not finish writing. use super::super::contract::Error; use crate::prefix_cache::{ - budget, fingerprint, ByteSize, Consider, PolicyParams, PrefixMatch, PrefixStore, PrefixSummary, Reject, Stats, StoreConfig, + ByteSize, Consider, PolicyParams, PrefixMatch, PrefixStore, PrefixSummary, Reject, Stats, StoreConfig, budget, + fingerprint, }; use leleka_obs::time::{AnyClock, Clock, Stopwatch}; @@ -116,7 +117,12 @@ pub(super) enum ChunkOutcome { Rejected(Reject), /// The host is short of memory: nothing was built. LowMemory, - Admitted { tokens: usize, new_blocks: usize, bytes: usize, park_ms: f64 }, + Admitted { + tokens: usize, + new_blocks: usize, + bytes: usize, + park_ms: f64, + }, } struct Req { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/clock_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/clock_tests.rs index 8bc78baa..0574c43a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/clock_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/clock_tests.rs @@ -8,61 +8,38 @@ use leleka_obs::time::ManualClock; #[test] fn idle_checkpoints_expire_when_the_clock_passes_the_retention_and_not_before() { let clock = ManualClock::new(); - let mut s = - PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); + let mut s = PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); let retention = cfg().policy.retention_ms; - assert!( - retention > 0, - "the default policy retains sessions for a finite time" - ); + assert!(retention > 0, "the default policy retains sessions for a finite time"); let mut d = Fake::new(); let prompt: Vec = (0..(3 * G + 10) as i32).collect(); request(&mut s, &mut d, &prompt, None); let nodes = s.store().node_count(); assert!(nodes > 0, "the request left checkpoints"); clock.advance_ms(retention); - assert_eq!( - s.expire_idle(), - 0, - "at exactly the retention the session is still kept" - ); + assert_eq!(s.expire_idle(), 0, "at exactly the retention the session is still kept"); assert_eq!(s.store().node_count(), nodes); clock.advance_ms(1); - assert_eq!( - s.expire_idle(), - nodes, - "one millisecond past it every idle node goes" - ); + assert_eq!(s.expire_idle(), nodes, "one millisecond past it every idle node goes"); assert_eq!(s.store().node_count(), 0); } #[test] fn a_request_renews_the_retention_of_the_checkpoints_it_used() { let clock = ManualClock::new(); - let mut s = - PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); + let mut s = PrefixServe::new(cfg(), 1024, 1 << 30, "test").with_clock(AnyClock::from(clock.clone())); let retention = cfg().policy.retention_ms; let mut d = Fake::new(); let prompt: Vec = (0..(3 * G + 10) as i32).collect(); request(&mut s, &mut d, &prompt, None); clock.advance_ms(retention - 1); let (start, _) = request(&mut s, &mut d, &prompt, None); - assert!( - start.is_some(), - "the second request resumed from a checkpoint" - ); + assert!(start.is_some(), "the second request resumed from a checkpoint"); // the first request's other nodes are now older than the retention, the ones the second request used are not clock.advance_ms(retention - 1); s.expire_idle(); let kept = s.store().node_count(); - assert!( - kept > 0, - "the checkpoints the second request used outlive the first request's retention" - ); + assert!(kept > 0, "the checkpoints the second request used outlive the first request's retention"); clock.advance_ms(2); - assert_eq!( - s.expire_idle(), - kept, - "and go when their own retention is over" - ); + assert_eq!(s.expire_idle(), kept, "and go when their own retention is over"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs index c5e29d25..a1bf8746 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2.rs @@ -3,14 +3,13 @@ #[allow(unused_imports)] use super::*; - - impl PrefixServe { /// `identity`: whatever makes two runtimes' caches interchangeable (model digest, KV format...), hashed with the /// block size into the summary's namespace. pub(in super::super::super) fn new(cfg: PrefixConfig, capacity: usize, budget_bytes: u64, identity: &str) -> Self { let block_tokens = cfg.resolved_block(capacity); - let namespace = fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); + let namespace = + fingerprint(&format!("{identity}|block={block_tokens}|chain={}", crate::prefix_cache::CHAIN_VERSION)); let store = PrefixStore::new(StoreConfig { block_tokens, budget_bytes: usize::try_from(budget_bytes).unwrap_or(usize::MAX), @@ -52,7 +51,11 @@ impl PrefixServe { /// Apply the memory governor's shed directive (`Governor::directive`): `Some(bytes)` evicts down to that budget (lowest /// expected-value-per-byte first), `None` restores the configured one after a shed. Returns the bytes evicted. - pub(in super::super::super) fn apply_shed(&mut self, target: Option, governor: &leleka_memory::Governor) -> usize { + pub(in super::super::super) fn apply_shed( + &mut self, + target: Option, + governor: &leleka_memory::Governor, + ) -> usize { match target { Some(bytes) => { let bytes = usize::try_from(bytes).unwrap_or(usize::MAX).min(self.configured_budget); @@ -80,7 +83,6 @@ impl PrefixServe { } } - /// (import, draft re-anchoring) milliseconds of the last hit. pub(in super::super::super) fn last_import_split(&self) -> (f64, f64) { self.last_import_split @@ -185,7 +187,11 @@ impl PrefixServe { let started = self.clock.now(); let full = hit.tokens / g; let first_block = (common / g).min(full); - let mut blocks = if copy { self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? } else { Vec::new() }; + let mut blocks = if copy { + self.store.blocks_from(hit.key, first_block).ok_or(Error::IdentityMismatch)? + } else { + Vec::new() + }; if copy { // a request-end checkpoint also carries the cells after its last full block if let Some((tail, _, _)) = self.store.tail_of(hit.key) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs index 10b80ccb..cb1ba8ed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/impl_prefixserve/impl_prefixserve_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl PrefixServe { - /// A chunk ending at `end` was published: the cells below `end` are this prompt's; maybe checkpoint there. /// An error means the checkpoint could not be built (the caller drops the cache, the request goes on). pub(in super::super::super) fn after_chunk>( @@ -40,7 +37,11 @@ impl PrefixServe { let candidate = match verdict { Consider::Exists => return Ok(ChunkOutcome::Exists), Consider::Rejected(why) => { - self.note = Some(format!("grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)", self.store.bytes() >> 20, self.configured_budget >> 20)); + self.note = Some(format!( + "grid point {end} rejected by the policy: {why:?} (store {} MiB of {} MiB)", + self.store.bytes() >> 20, + self.configured_budget >> 20 + )); return Ok(ChunkOutcome::Rejected(why)); } Consider::Admit(candidate) => candidate, @@ -81,10 +82,19 @@ impl PrefixServe { /// The end of the prompt's prefill: the session stands at `prompt.len() - 1`. With `TailMode::Prompt` or `Reply`, checkpoint /// there (a request-end checkpoint), unless that is a grid point. - pub(in super::super::super) fn after_prefill>(&mut self, device: &mut D, prompt: &[i32]) -> Result { + pub(in super::super::super) fn after_prefill>( + &mut self, + device: &mut D, + prompt: &[i32], + ) -> Result { self.note = None; if self.cfg.tail == TailMode::Off || self.bypass || self.req.is_none() { - self.note = Some(format!("no tail checkpoint: tail {:?}, bypass {}, request {}", self.cfg.tail, self.bypass, self.req.is_some())); + self.note = Some(format!( + "no tail checkpoint: tail {:?}, bypass {}, request {}", + self.cfg.tail, + self.bypass, + self.req.is_some() + )); return Ok(ChunkOutcome::Nothing); } let end = prompt.len().saturating_sub(1); @@ -98,7 +108,11 @@ impl PrefixServe { self.note.take() } - pub(in super::super::super) fn after_decode>(&mut self, device: &mut D, consumed: &[i32]) -> Result { + pub(in super::super::super) fn after_decode>( + &mut self, + device: &mut D, + consumed: &[i32], + ) -> Result { self.note = None; if self.cfg.tail != TailMode::Reply || self.bypass || self.req.is_none() { return Ok(ChunkOutcome::Nothing); @@ -115,12 +129,20 @@ impl PrefixServe { Ok(outcome) } - pub(in super::super) fn admit_tail>(&mut self, device: &mut D, tokens: &[i32], keep_end: Option) -> Result { + pub(in super::super) fn admit_tail>( + &mut self, + device: &mut D, + tokens: &[i32], + keep_end: Option, + ) -> Result { let g = self.block_tokens; // a grid point is a pure checkpoint of its own (and a node below one block has no blocks to hang on) let position = device.position()?; if tokens.len() <= g || tokens.len() % g == 0 || position != tokens.len() as u64 { - self.note = Some(format!("not a tail position: {} tokens, grid {g}, the session stands at {position}", tokens.len())); + self.note = Some(format!( + "not a tail position: {} tokens, grid {g}, the session stands at {position}", + tokens.len() + )); return Ok(ChunkOutcome::Nothing); } let (est_state, est_block) = device.estimate(g); @@ -135,7 +157,12 @@ impl PrefixServe { return Ok(ChunkOutcome::Exists); } Consider::Rejected(why) => { - self.note = Some(format!("rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)", tokens.len(), self.store.bytes() >> 20, self.configured_budget >> 20)); + self.note = Some(format!( + "rejected by the policy at {} tokens: {why:?} (store {} MiB of {} MiB)", + tokens.len(), + self.store.bytes() >> 20, + self.configured_budget >> 20 + )); return Ok(ChunkOutcome::Rejected(why)); } Consider::Admit(candidate) => candidate, @@ -172,7 +199,9 @@ impl PrefixServe { let new_blocks = blocks.len(); let bytes = state.byte_size() + tail.byte_size() + blocks.iter().map(|(_, b)| b.byte_size()).sum::(); let park_ms = self.clock.since(started).as_secs_f64() * 1e3; - self.store.commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end).map_err(|_| Error::IdentityMismatch)?; + self.store + .commit_tail_keeping(candidate, tokens, state, blocks, tail, keep_end) + .map_err(|_| Error::IdentityMismatch)?; self.park_ms_request += park_ms; self.admitted_request += 1; Ok(ChunkOutcome::Admitted { tokens: tokens.len(), new_blocks, bytes, park_ms }) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs index 3f457501..6d8b34e6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests.rs @@ -43,7 +43,14 @@ pub(super) struct Fake { } impl Fake { pub(super) fn new() -> Self { - Self { cells: vec![-1; 1 << 16], position: 0, digest: 0, log: Vec::new(), fail_import: false, available: Some(1 << 40) } + Self { + cells: vec![-1; 1 << 16], + position: 0, + digest: 0, + log: Vec::new(), + fail_import: false, + available: Some(1 << 40), + } } fn read(&mut self, tokens: &[i32], first: usize) { assert_eq!(first as u64, self.position, "chunks are contiguous"); @@ -104,7 +111,12 @@ fn serve() -> PrefixServe { /// One request against the fake: begin, read the plan's chunks on the grid, finish. Returns (start, digest the /// session holds at the end of the prefill = a function of all tokens read). -pub(super) fn request(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], stop_after_chunks: Option) -> (Option, u64) { +pub(super) fn request( + s: &mut PrefixServe, + d: &mut Fake, + prompt: &[i32], + stop_after_chunks: Option, +) -> (Option, u64) { let start = s.begin(d, prompt).unwrap(); let resume = match &start { Some(st) => st.resume, @@ -118,7 +130,14 @@ pub(super) fn request(s: &mut PrefixServe, d: &mut Fake, prompt: & let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); // like the stack: a request that resumed between two grid points reads the way a full read of its own would let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; + let options = PromptOptions { + grid, + prompt_cache: false, + turn_token: None, + root_min: 0, + force_batched: true, + ..PromptOptions::original_mode17(1 << 16) + }; let mut chunks = 0; for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { if action.path == PromptPath::FinalSeed { @@ -146,7 +165,12 @@ pub(super) fn request(s: &mut PrefixServe, d: &mut Fake, prompt: & /// An agent turn: `request`, then the decode of `reply` (the session consumes the last prompt token and every reply token but the /// last, which is the pending input) and the request-end checkpoint of `TailMode::Reply`. Returns (start, digest after the /// prefill, the consumed tokens). -fn turn(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], reply: &[i32]) -> (Option, u64, Vec) { +fn turn( + s: &mut PrefixServe, + d: &mut Fake, + prompt: &[i32], + reply: &[i32], +) -> (Option, u64, Vec) { let start = s.begin(d, prompt).unwrap(); let resume = match &start { Some(st) => st.resume, @@ -158,7 +182,14 @@ fn turn(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], reply: }; let tokens: Vec = prompt.iter().map(|&t| t as u32).collect(); let grid = if resume % s.block_tokens() == 0 { s.block_tokens() } else { 0 }; - let options = PromptOptions { grid, prompt_cache: false, turn_token: None, root_min: 0, force_batched: true, ..PromptOptions::original_mode17(1 << 16) }; + let options = PromptOptions { + grid, + prompt_cache: false, + turn_token: None, + root_min: 0, + force_batched: true, + ..PromptOptions::original_mode17(1 << 16) + }; for action in PromptPlan::new(&tokens, resume, None, None, options, 1024).unwrap() { if action.path == PromptPath::FinalSeed { break; @@ -170,7 +201,8 @@ fn turn(s: &mut PrefixServe, d: &mut Fake, prompt: &[i32], reply: s.after_prefill(d, prompt).unwrap(); let digest = d.digest; let mut consumed = prompt[..prompt.len() - 1].to_vec(); - let decoded: Vec = std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect(); + let decoded: Vec = + std::iter::once(prompt[prompt.len() - 1]).chain(reply[..reply.len() - 1].iter().copied()).collect(); d.read(&decoded, consumed.len()); consumed.extend_from_slice(&decoded); s.after_decode(d, &consumed).unwrap(); @@ -207,7 +239,7 @@ fn governor() -> leleka_memory::Governor { leleka_memory::Governor::new(cfg, std::sync::Arc::new(leleka_memory::FakeProc::default())) } -#[path = "tests/second_session.rs"] -mod second_session; #[path = "tests/one_token_prompt_reads.rs"] mod one_token_prompt_reads; +#[path = "tests/second_session.rs"] +mod second_session; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs index 0ac7b07e..fd1fb0df 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/one_token_prompt_reads.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Upstream 41cf05a0 `aece46db` (a 1-token prompt with `--spec`): the prompt has no token to read (the single token is the first /// verify input), so nothing is looked up, read or checkpointed and no claim is made on the buffer. #[test] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs index a636e86a..139cacb1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_prefix/tests/second_session.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_and_ends_in_the_full_reads_state() { let mut s = serve(); @@ -21,7 +20,10 @@ fn a_second_session_with_the_same_system_prompt_resumes_from_the_shared_blocks_a let (start, digest) = request(&mut s, &mut d, &b, None); let start = start.unwrap(); assert_eq!((start.resume, start.switched, start.branch), (4 * G, true, true)); - assert_eq!(start.copied_tokens, 0, "the buffer held A, whose first four blocks are the shared prompt: nothing to write back"); + assert_eq!( + start.copied_tokens, 0, + "the buffer held A, whose first four blocks are the shared prompt: nothing to write back" + ); assert_eq!(digest, full_digest(&b), "the resumed read ends in exactly the full read's state"); assert_eq!(s.stats().hits, 1); assert_eq!(s.stats().shared_hits, 1); @@ -262,7 +264,8 @@ fn a_full_store_evicts_the_session_idle_longest_so_the_newest_request_is_cached( assert!(s.bytes() <= s.budget_bytes(), "{} > {}", s.bytes(), s.budget_bytes()); } assert!(s.stats().evicted > 0, "the store was full, so something went"); - let deepest = |p: &[i32], s: &PrefixServe| s.store().longest_match(p, p.len() - 1).map_or(0, |m| m.tokens); + let deepest = + |p: &[i32], s: &PrefixServe| s.store().longest_match(p, p.len() - 1).map_or(0, |m| m.tokens); assert_eq!(deepest(&c, &s), 4 * G, "the newest request's deepest checkpoint is cached, not dropped"); assert!(deepest(&a, &s) < 4 * G, "the session idle longest gave way"); // whatever was evicted, every session resumes to exactly the full read's state diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs index 24c0b068..047de9a9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request.rs @@ -7,15 +7,11 @@ //! before any work; the prompt is read through token n-2 and token n-1 is the first verify input. With the //! conversation cache (`RequestOwners::resume`) a request starts reading where an earlier one left a reusable //! prefix; without it every request starts from the empty prompt. -use super::{ - contract::Error, - original_serve_engine::ServeOutcome, - original_spec_controller::SpecError, -}; +use super::{contract::Error, original_serve_engine::ServeOutcome, original_spec_controller::SpecError}; use leleka_cuda_driver::{SamplerParams, SamplerPath}; -pub(crate) use leleka_engine_core::request::{original_stop_tokens, Admission, ENDOFTEXT_TOKEN}; pub(in crate::qwen_forward) use leleka_engine_core::request::CONTEXT_SLACK; +pub(crate) use leleka_engine_core::request::{Admission, ENDOFTEXT_TOKEN, original_stop_tokens}; /// How a request ended when it did not complete, over this stack's forward error. pub(crate) type ServeError = leleka_engine_core::request::ServeError; @@ -48,7 +44,14 @@ impl ServeRequest { Some(params) => super::original_serve_config::driver_sampler_params(params), None => super::original_serve_config::greedy_params(entropy), }; - Self { prompt, max_new, params, path: super::original_serve_config::sampler_path_from_environment(), spec_min_p, eos } + Self { + prompt, + max_new, + params, + path: super::original_serve_config::sampler_path_from_environment(), + spec_min_p, + eos, + } } } @@ -72,7 +75,12 @@ pub(in crate::qwen_forward) trait RequestOwners { } /// Condition `prompt[resume..n-1]` into the session and the draft ring (they stand at `resume`). /// `Err(Cancelled)` only when the caller's flag fired. - fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError>; + fn prefill( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> Result<(), SpecError>; /// Run the verified-window decode of the request; `emit` receives each committed round. fn decode( &mut self, @@ -138,7 +146,12 @@ impl leleka_engine_core::request::Lifecycle for Owners<'_, O> fn resume(&mut self, request: &ServeRequest) -> Option { self.0.resume(request) } - fn prefill bool>(&mut self, request: &ServeRequest, resume: usize, cancel: &mut C) -> Result<(), SpecError> { + fn prefill bool>( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut C, + ) -> Result<(), SpecError> { self.0.prefill(request, resume, cancel) } fn decode Result<(), Error>, C: FnMut() -> bool>( @@ -169,202 +182,4 @@ pub(in crate::qwen_forward) fn run_request( } #[cfg(test)] -mod tests { - use super::super::original_serve_engine::ServeStop; - use super::*; - use leleka_cuda_driver::SamplerPath; - - fn request(prompt: usize, max_new: usize) -> ServeRequest { - ServeRequest { - prompt: (0..prompt as i32).collect(), - max_new, - params: super::super::original_serve_config::greedy_params(1), - path: SamplerPath::Split, - spec_min_p: 0.0, - eos: vec![7], - } - } - - #[test] - fn the_stop_set_is_the_originals_endoftext_and_im_end() { - assert_eq!(original_stop_tokens(248_046), vec![248_046, 248_044]); - assert_eq!(original_stop_tokens(248_044), vec![248_044]); - assert!(original_stop_tokens(248_046).contains(&ENDOFTEXT_TOKEN), "generate.cpp stops on <|endoftext|> as well"); - } - - #[derive(Default)] - struct Fake { - fresh: bool, - log: Vec<&'static str>, - fail_reset: bool, - reset_leaves_state: bool, - prefill: Option, - decode: Option, - emitted: Vec, - resume_at: Option, - prefilled_from: Option, - ended: Option>, - } - impl RequestOwners for Fake { - fn is_fresh(&self) -> bool { - self.fresh - } - fn reset(&mut self) -> Result<(), Error> { - self.log.push("reset"); - if self.fail_reset { - return Err(Error::CudaExecution); - } - self.fresh = !self.reset_leaves_state; - Ok(()) - } - fn resume(&mut self, request: &ServeRequest) -> Option { - let resume = self.resume_at.map(|r| r.min(request.prompt.len()))?; - self.log.push("resume"); - self.fresh = false; - Some(resume) - } - fn prefill(&mut self, _: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError> { - self.log.push("prefill"); - self.prefilled_from = Some(resume); - self.fresh = false; - if let Some(error) = self.prefill { - return Err(error); - } - if cancel() { - return Err(SpecError::Cancelled); - } - Ok(()) - } - fn decode( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>, - _: &mut dyn FnMut() -> bool, - ) -> Result { - self.log.push("decode"); - if let Some(error) = self.decode { - return Err(error); - } - emit(&[3, 4]).map_err(SpecError::Forward)?; - self.emitted.extend([3, 4]); - Ok(ServeOutcome { stop: ServeStop::Length, produced: 2.min(request.max_new), rounds: 1 }) - } - fn finish(&mut self, ended: Result<(), ServeError>) { - self.log.push("finish"); - self.ended = Some(ended); - } - } - - #[test] - fn a_resumed_request_skips_the_reset_reads_from_the_resume_point_and_always_finishes() { - let mut owners = Fake { resume_at: Some(5), ..Default::default() }; - run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); - assert_eq!(owners.log, ["resume", "prefill", "decode", "finish"]); - assert_eq!((owners.prefilled_from, owners.ended), (Some(5), Some(Ok(())))); - // a resume that would swallow the last prompt token is refused as broken, and still finished - let mut owners = Fake { resume_at: Some(8), ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Broken(Error::InvalidPosition)); - assert_eq!(owners.log, ["resume", "finish"]); - // the outcome of a failed request reaches finish - let mut owners = Fake { resume_at: Some(0), decode: Some(SpecError::Forward(Error::NonFinite)), ..Default::default() }; - run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(owners.ended, Some(Err(ServeError::Failed(Error::NonFinite)))); - // without a cache the reset path runs and the prompt is read from 0 - let mut owners = Fake::default(); - run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); - assert_eq!(owners.log, ["reset", "prefill", "decode", "finish"]); - assert_eq!(owners.prefilled_from, Some(0)); - } - - #[test] - fn admission_follows_generate_cpp() { - assert_eq!(admit(&request(10, 20), 38), Ok(())); - assert_eq!(admit(&request(10, 21), 38), Err(Admission::Context)); - assert_eq!(admit(&request(0, 5), 100), Err(Admission::EmptyPrompt)); - assert_eq!(admit(&request(5, 0), 100), Err(Admission::NoOutput)); - let mut bad = request(5, 5); - bad.prompt[2] = 248_320; - assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); - let mut bad = request(5, 5); - bad.eos = vec![-1]; - assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); - let mut bad = request(5, 5); - bad.spec_min_p = 1.5; - assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); - let mut huge = request(5, 5); - huge.max_new = usize::MAX; - assert_eq!(admit(&huge, i64::MAX), Err(Admission::Context)); - } - - #[test] - fn a_fresh_stack_skips_the_reset_and_a_used_one_resets_first() { - let mut fresh = Fake { fresh: true, ..Default::default() }; - let out = run_request(&mut fresh, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); - assert_eq!(fresh.log, ["prefill", "decode", "finish"]); - assert_eq!(out.produced, 2); - let mut used = Fake::default(); - run_request(&mut used, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); - assert_eq!(used.log, ["reset", "prefill", "decode", "finish"]); - } - - #[test] - fn a_refused_request_touches_no_owner() { - let mut owners = Fake::default(); - let error = run_request(&mut owners, &request(8, 400), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Refused(Admission::Context)); - assert!(owners.log.is_empty()); - // cancelled before the first owner call - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || true).unwrap_err(); - assert_eq!(error, ServeError::Cancelled); - assert!(owners.log.is_empty()); - } - - #[test] - fn an_unrecoverable_reset_is_broken_not_failed() { - let mut owners = Fake { fail_reset: true, ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Broken(Error::CudaExecution)); - assert_eq!(owners.log, ["reset"]); - // a reset that reports success but leaves state behind is a broken stack as well - let mut owners = Fake { reset_leaves_state: true, ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Broken(Error::IdentityMismatch)); - assert_eq!(owners.log, ["reset"]); - } - - #[test] - fn prefill_and_decode_errors_keep_their_class() { - let mut owners = Fake { fresh: true, prefill: Some(SpecError::Cancelled), ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Cancelled); - assert_eq!(owners.log, ["prefill", "finish"], "no decode after a failed prefill"); - let mut owners = Fake { fresh: true, prefill: Some(SpecError::Forward(Error::NonFinite)), ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Failed(Error::NonFinite)); - let mut owners = Fake { fresh: true, decode: Some(SpecError::Forward(Error::IdentityMismatch)), ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Failed(Error::IdentityMismatch)); - // a cancel that fires during the prompt surfaces from the prefill - let mut owners = Fake { fresh: true, ..Default::default() }; - let mut calls = 0; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || { - calls += 1; - calls > 1 - }) - .unwrap_err(); - assert_eq!(error, ServeError::Cancelled); - assert_eq!(owners.log, ["prefill", "finish"]); - } - - #[test] - fn emitted_rounds_reach_the_caller_and_an_emit_failure_fails_the_request() { - let mut owners = Fake { fresh: true, ..Default::default() }; - let mut seen = Vec::new(); - run_request(&mut owners, &request(8, 4), 100, &mut |t| { seen.extend_from_slice(t); Ok(()) }, &mut || false).unwrap(); - assert_eq!(seen, [3, 4]); - let mut owners = Fake { fresh: true, ..Default::default() }; - let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Err(Error::InputRead), &mut || false).unwrap_err(); - assert_eq!(error, ServeError::Failed(Error::InputRead)); - } -} +mod tests; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request/tests.rs new file mode 100644 index 00000000..f03769ef --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_request/tests.rs @@ -0,0 +1,212 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::super::original_serve_engine::ServeStop; +use super::*; +use leleka_cuda_driver::SamplerPath; + +fn request(prompt: usize, max_new: usize) -> ServeRequest { + ServeRequest { + prompt: (0..prompt as i32).collect(), + max_new, + params: super::super::original_serve_config::greedy_params(1), + path: SamplerPath::Split, + spec_min_p: 0.0, + eos: vec![7], + } +} + +#[test] +fn the_stop_set_is_the_originals_endoftext_and_im_end() { + assert_eq!(original_stop_tokens(248_046), vec![248_046, 248_044]); + assert_eq!(original_stop_tokens(248_044), vec![248_044]); + assert!(original_stop_tokens(248_046).contains(&ENDOFTEXT_TOKEN), "generate.cpp stops on <|endoftext|> as well"); +} + +#[derive(Default)] +struct Fake { + fresh: bool, + log: Vec<&'static str>, + fail_reset: bool, + reset_leaves_state: bool, + prefill: Option, + decode: Option, + emitted: Vec, + resume_at: Option, + prefilled_from: Option, + ended: Option>, +} +impl RequestOwners for Fake { + fn is_fresh(&self) -> bool { + self.fresh + } + fn reset(&mut self) -> Result<(), Error> { + self.log.push("reset"); + if self.fail_reset { + return Err(Error::CudaExecution); + } + self.fresh = !self.reset_leaves_state; + Ok(()) + } + fn resume(&mut self, request: &ServeRequest) -> Option { + let resume = self.resume_at.map(|r| r.min(request.prompt.len()))?; + self.log.push("resume"); + self.fresh = false; + Some(resume) + } + fn prefill(&mut self, _: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> Result<(), SpecError> { + self.log.push("prefill"); + self.prefilled_from = Some(resume); + self.fresh = false; + if let Some(error) = self.prefill { + return Err(error); + } + if cancel() { + return Err(SpecError::Cancelled); + } + Ok(()) + } + fn decode( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<(), Error>, + _: &mut dyn FnMut() -> bool, + ) -> Result { + self.log.push("decode"); + if let Some(error) = self.decode { + return Err(error); + } + emit(&[3, 4]).map_err(SpecError::Forward)?; + self.emitted.extend([3, 4]); + Ok(ServeOutcome { stop: ServeStop::Length, produced: 2.min(request.max_new), rounds: 1 }) + } + fn finish(&mut self, ended: Result<(), ServeError>) { + self.log.push("finish"); + self.ended = Some(ended); + } +} + +#[test] +fn a_resumed_request_skips_the_reset_reads_from_the_resume_point_and_always_finishes() { + let mut owners = Fake { resume_at: Some(5), ..Default::default() }; + run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); + assert_eq!(owners.log, ["resume", "prefill", "decode", "finish"]); + assert_eq!((owners.prefilled_from, owners.ended), (Some(5), Some(Ok(())))); + // a resume that would swallow the last prompt token is refused as broken, and still finished + let mut owners = Fake { resume_at: Some(8), ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Broken(Error::InvalidPosition)); + assert_eq!(owners.log, ["resume", "finish"]); + // the outcome of a failed request reaches finish + let mut owners = + Fake { resume_at: Some(0), decode: Some(SpecError::Forward(Error::NonFinite)), ..Default::default() }; + run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(owners.ended, Some(Err(ServeError::Failed(Error::NonFinite)))); + // without a cache the reset path runs and the prompt is read from 0 + let mut owners = Fake::default(); + run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); + assert_eq!(owners.log, ["reset", "prefill", "decode", "finish"]); + assert_eq!(owners.prefilled_from, Some(0)); +} + +#[test] +fn admission_follows_generate_cpp() { + assert_eq!(admit(&request(10, 20), 38), Ok(())); + assert_eq!(admit(&request(10, 21), 38), Err(Admission::Context)); + assert_eq!(admit(&request(0, 5), 100), Err(Admission::EmptyPrompt)); + assert_eq!(admit(&request(5, 0), 100), Err(Admission::NoOutput)); + let mut bad = request(5, 5); + bad.prompt[2] = 248_320; + assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); + let mut bad = request(5, 5); + bad.eos = vec![-1]; + assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); + let mut bad = request(5, 5); + bad.spec_min_p = 1.5; + assert_eq!(admit(&bad, 100), Err(Admission::BadToken)); + let mut huge = request(5, 5); + huge.max_new = usize::MAX; + assert_eq!(admit(&huge, i64::MAX), Err(Admission::Context)); +} + +#[test] +fn a_fresh_stack_skips_the_reset_and_a_used_one_resets_first() { + let mut fresh = Fake { fresh: true, ..Default::default() }; + let out = run_request(&mut fresh, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); + assert_eq!(fresh.log, ["prefill", "decode", "finish"]); + assert_eq!(out.produced, 2); + let mut used = Fake::default(); + run_request(&mut used, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap(); + assert_eq!(used.log, ["reset", "prefill", "decode", "finish"]); +} + +#[test] +fn a_refused_request_touches_no_owner() { + let mut owners = Fake::default(); + let error = run_request(&mut owners, &request(8, 400), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Refused(Admission::Context)); + assert!(owners.log.is_empty()); + // cancelled before the first owner call + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || true).unwrap_err(); + assert_eq!(error, ServeError::Cancelled); + assert!(owners.log.is_empty()); +} + +#[test] +fn an_unrecoverable_reset_is_broken_not_failed() { + let mut owners = Fake { fail_reset: true, ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Broken(Error::CudaExecution)); + assert_eq!(owners.log, ["reset"]); + // a reset that reports success but leaves state behind is a broken stack as well + let mut owners = Fake { reset_leaves_state: true, ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Broken(Error::IdentityMismatch)); + assert_eq!(owners.log, ["reset"]); +} + +#[test] +fn prefill_and_decode_errors_keep_their_class() { + let mut owners = Fake { fresh: true, prefill: Some(SpecError::Cancelled), ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Cancelled); + assert_eq!(owners.log, ["prefill", "finish"], "no decode after a failed prefill"); + let mut owners = Fake { fresh: true, prefill: Some(SpecError::Forward(Error::NonFinite)), ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Failed(Error::NonFinite)); + let mut owners = + Fake { fresh: true, decode: Some(SpecError::Forward(Error::IdentityMismatch)), ..Default::default() }; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Failed(Error::IdentityMismatch)); + // a cancel that fires during the prompt surfaces from the prefill + let mut owners = Fake { fresh: true, ..Default::default() }; + let mut calls = 0; + let error = run_request(&mut owners, &request(8, 4), 100, &mut |_| Ok(()), &mut || { + calls += 1; + calls > 1 + }) + .unwrap_err(); + assert_eq!(error, ServeError::Cancelled); + assert_eq!(owners.log, ["prefill", "finish"]); +} + +#[test] +fn emitted_rounds_reach_the_caller_and_an_emit_failure_fails_the_request() { + let mut owners = Fake { fresh: true, ..Default::default() }; + let mut seen = Vec::new(); + run_request( + &mut owners, + &request(8, 4), + 100, + &mut |t| { + seen.extend_from_slice(t); + Ok(()) + }, + &mut || false, + ) + .unwrap(); + assert_eq!(seen, [3, 4]); + let mut owners = Fake { fresh: true, ..Default::default() }; + let error = + run_request(&mut owners, &request(8, 4), 100, &mut |_| Err(Error::InputRead), &mut || false).unwrap_err(); + assert_eq!(error, ServeError::Failed(Error::InputRead)); +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs index b8bb328f..b9c194dd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency.rs @@ -30,11 +30,11 @@ use super::{ }; use crate::model_binding::qwen4exp_input::ModelBinding; use crate::settings::EnvSource; -use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use leleka_cuda_driver::{ Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource, }; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; use std::{ path::PathBuf, rc::Rc, @@ -247,30 +247,30 @@ mod tier_env_tests; mod tail_skip_rank_fn; #[allow(unused_imports)] -pub(crate) use tail_skip_rank_fn::tail_skip_rank; +pub(crate) use tail_skip_rank_fn::effective_tail_rank; #[allow(unused_imports)] pub(crate) use tail_skip_rank_fn::set_tail_skip_arm; -#[allow(unused_imports)] -pub(crate) use tail_skip_rank_fn::effective_tail_rank; #[cfg(test)] #[allow(unused_imports)] pub(in crate::qwen_forward) use tail_skip_rank_fn::split_group; #[allow(unused_imports)] pub(in crate::qwen_forward) use tail_skip_rank_fn::split_group_tail; +#[allow(unused_imports)] +pub(crate) use tail_skip_rank_fn::tail_skip_rank; mod split_group_pcie_fn; #[allow(unused_imports)] -pub(in crate::qwen_forward) use split_group_pcie_fn::split_group_pcie; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use split_group_pcie_fn::pcie_locked_only; +use split_group_pcie_fn::adapt_decay; #[allow(unused_imports)] use split_group_pcie_fn::adapt_tuning; #[allow(unused_imports)] -use split_group_pcie_fn::adapt_decay; -#[allow(unused_imports)] pub(in crate::qwen_forward) use split_group_pcie_fn::choose_swaps; #[cfg(test)] #[allow(unused_imports)] use split_group_pcie_fn::choose_swaps_reference; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use split_group_pcie_fn::pcie_locked_only; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use split_group_pcie_fn::split_group_pcie; mod impl_std_fmt_debug; #[allow(unused_imports)] use impl_std_fmt_debug::span_cache_enabled; @@ -281,14 +281,14 @@ pub(super) use source_spans_fn::source_spans; use source_spans_fn::swap_wait; mod open_tier_fn; #[allow(unused_imports)] +pub(in crate::qwen_forward) use open_tier_fn::loan_slots; +#[allow(unused_imports)] pub(in crate::qwen_forward) use open_tier_fn::open_tier; #[allow(unused_imports)] use open_tier_fn::pin_resident_complement; #[allow(unused_imports)] -pub(in crate::qwen_forward) use open_tier_fn::loan_slots; +pub(in crate::qwen_forward) use open_tier_fn::refill_defer_enabled; #[allow(unused_imports)] pub(in crate::qwen_forward) use open_tier_fn::refill_lent; #[allow(unused_imports)] pub(in crate::qwen_forward) use open_tier_fn::settle_refill; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use open_tier_fn::refill_defer_enabled; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs index 9201f1b1..596051aa 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/impl_std_fmt_debug.rs @@ -33,7 +33,13 @@ impl PcieLag { if !crate::settings::process().memory.pcie_auto_lag || start_num == 0 { return None; } - Some(Self { num: start_num.clamp(Self::MIN, Self::MAX), lag_us: 0.0, groups: 0, ema_us: None, rounds_since_up: 0 }) + Some(Self { + num: start_num.clamp(Self::MIN, Self::MAX), + lag_us: 0.0, + groups: 0, + ema_us: None, + rounds_since_up: 0, + }) } pub(crate) fn pcie_num(&self) -> u32 { self.num @@ -159,7 +165,10 @@ impl ResidencyState { } /// Cumulative (vram, pcie, cpu) entries after each round of the last request, from the request's own start. pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { - self.marks.iter().map(|m| [m[0] - self.mark_base[0], m[1] - self.mark_base[1], m[2] - self.mark_base[2]]).collect() + self.marks + .iter() + .map(|m| [m[0] - self.mark_base[0], m[1] - self.mark_base[1], m[2] - self.mark_base[2]]) + .collect() } /// The adaptive tier's routed counts (`layer * 512 + expert`; empty when the tier is off). pub(crate) fn usage(&self) -> &[f32] { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs index b6ebf00c..9fc5536b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/open_tier_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// generate.cpp startup of the tier for the serve stack: size and open the cache after every other owner, /// fill it from the profile through the registered bank (blocking, rank order; per-layer skips a full /// layer's pairs, global stops at the first refusal) and read slot 0 back. `None`: the tier is off or no @@ -27,7 +26,11 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>( if config.slots < 0 && config.decode_headroom_mib() < VANILLA_FREE_FLOOR_MIB as isize { eprintln!( "leleka-serve: WARNING: the VRAM reserves ({} + {} MiB) leave {} MiB free at decode after the {} MiB verifier assembly, below the {} MiB vanilla Strata runs with; the first request may not fit", - config.reserve_mib, config.decode_reserve_mib, config.decode_headroom_mib(), VERIFIER_ASSEMBLY_MIB, VANILLA_FREE_FLOOR_MIB + config.reserve_mib, + config.decode_reserve_mib, + config.decode_headroom_mib(), + VERIFIER_ASSEMBLY_MIB, + VANILLA_FREE_FLOOR_MIB ); } let options = OriginalCacheOptions { @@ -59,7 +62,8 @@ pub(in crate::qwen_forward) fn open_tier<'ctx>( } if filled > 0 { let (layer, expert) = profile.pairs()[0]; - let slot = usize::try_from(cache.slot_of(usize::from(layer), usize::from(expert))).map_err(|_| Error::IdentityMismatch)?; + let slot = usize::try_from(cache.slot_of(usize::from(layer), usize::from(expert))) + .map_err(|_| Error::IdentityMismatch)?; let spans = moe.original_expert_spans(binding, u32::from(layer), u32::from(expert))?; cache.verify_slot(slot, &bank, &spans).map_err(|e| driver_error(&e))?; } @@ -116,7 +120,9 @@ pub(super) fn pin_resident_complement( started.elapsed().as_secs_f64() ), // #403: a budget that cannot be kept is a warning; every miss is read from the file pages instead - Err(e) => eprintln!("leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file"), + Err(e) => eprintln!( + "leleka-serve: WARNING: the resident RAM budget cannot be kept ({e:?}); experts are read from the file" + ), } Ok(()) } @@ -124,7 +130,10 @@ pub(super) fn pin_resident_complement( /// The serve stack's loan test (generate.cpp `fits_one`, fixed chunk): the prompt path's buffers for the /// configured chunk come from the cache's last `k` slots when `0 < k` and `k + 128 <= slots`. Unlike the /// Original the chunk is not halved to fit: the prompt executor is built for exactly this capacity. -pub(in crate::qwen_forward) fn loan_slots(cache: &OriginalExpertCache<'_>, bytes_needed: usize) -> Result> { +pub(in crate::qwen_forward) fn loan_slots( + cache: &OriginalExpertCache<'_>, + bytes_needed: usize, +) -> Result> { let k = cache.lend_slots(bytes_needed).map_err(|e| driver_error(&e))?; Ok((k > 0 && k.checked_add(LOAN_FLOOR).is_some_and(|n| n <= cache.slots())).then_some(k)) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans_fn.rs index bec11a03..4e2e123d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/source_spans_fn.rs @@ -84,7 +84,12 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { TOP_K, sink.plan_capacity(), |e| cache.resident_slot(layer, e as usize), - self.state.pcie_lag.as_ref().map(PcieLag::pcie_num).or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num)).unwrap_or(self.pcie_num), + self.state + .pcie_lag + .as_ref() + .map(PcieLag::pcie_num) + .or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num)) + .unwrap_or(self.pcie_num), sink.staging_capacity(), self.tail_rank, |e| locked.is_empty() || locked.get(layer * EXPERTS + e as usize).copied().unwrap_or(false), @@ -92,12 +97,29 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { if let Some(auto) = self.state.pcie_auto.as_mut() { auto.add_misses(split.kinds.iter().filter(|&&k| k == -1 || k == 1).count()); } - super::super::original_serve_pool::window_trace::lap(super::super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); + super::super::original_serve_pool::window_trace::lap( + super::super::original_serve_pool::window_trace::GPU_SPLIT, + &mut clock, + ); drop(profile_split); let profile_spans = super::super::original_serve_profile::span("pool.spans"); - let spans = source_spans(&mut *self.cpu, &self.bank, self.moe, self.binding, &mut self.state.spans, layer, &split.pcie_experts)?; - super::super::original_serve_pool::window_trace::lap(super::super::original_serve_pool::window_trace::PCIE_SPANS, &mut clock); - super::super::original_serve_pool::window_trace::add(super::super::original_serve_pool::window_trace::PCIE_EXPERTS, split.pcie_experts.len() as f64); + let spans = source_spans( + &mut *self.cpu, + &self.bank, + self.moe, + self.binding, + &mut self.state.spans, + layer, + &split.pcie_experts, + )?; + super::super::original_serve_pool::window_trace::lap( + super::super::original_serve_pool::window_trace::PCIE_SPANS, + &mut clock, + ); + super::super::original_serve_pool::window_trace::add( + super::super::original_serve_pool::window_trace::PCIE_EXPERTS, + split.pcie_experts.len() as f64, + ); drop(profile_spans); let profile_publish = super::super::original_serve_profile::span("pool.publish_plan"); let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans }); @@ -121,7 +143,10 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> { let next = layer + 1; self.cpu.set_next_resident(|e| cache.resident_slot(next, e).is_some()); } - super::super::original_serve_pool::window_trace::lap(super::super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock); + super::super::original_serve_pool::window_trace::lap( + super::super::original_serve_pool::window_trace::GPU_SPLIT, + &mut clock, + ); let _p = super::super::original_serve_profile::span("pool.cpu"); let ran = self.cpu.run_entries(rows, sink, Some(&include)); if ran.is_ok() && !split.pcie_experts.is_empty() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs index e055a19b..c5d3179e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/split_group_pcie_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// `split_group_tail` with a say in which misses may take the PCIe share: only an expert `pcie_ok` accepts is staged, the share /// is still `nmiss * pcie_num >> 8` of ALL the misses but capped by the number that are eligible, and it is the last eligible /// misses in routing order. `|_| true` is the unrestricted split. The pageable file-mapped bank uses it to keep PCIe to experts @@ -56,7 +55,10 @@ pub(in crate::qwen_forward) fn split_group_pcie( } let mut m = if pcie_num > 0 { (nmiss * pcie_num as usize) >> 8 } else { 0 }; // the misses that may be staged (all of them unless the caller restricts the share) - let eligible = distinct.iter().filter(|&&i0| !skip[i0] && valid(ids[i0]) && resident(ids[i0] as u32).is_none() && pcie_ok(ids[i0] as u32)).count(); + let eligible = distinct + .iter() + .filter(|&&i0| !skip[i0] && valid(ids[i0]) && resident(ids[i0] as u32).is_none() && pcie_ok(ids[i0] as u32)) + .count(); m = m.min(eligible); let mut eligible_rank = 0usize; let mut kinds = vec![-1i8; n]; @@ -77,7 +79,10 @@ pub(in crate::qwen_forward) fn split_group_pcie( } None => { if pcie_ok(e as u32) { - if eligible_rank >= eligible - m && pcie_groups.len() < staging && pcie_groups.len() < ORIGINAL_VERIFY_MAX_PCIE_FETCHES { + if eligible_rank >= eligible - m + && pcie_groups.len() < staging + && pcie_groups.len() < ORIGINAL_VERIFY_MAX_PCIE_FETCHES + { kind = 1; } eligible_rank += 1; @@ -143,7 +148,11 @@ pub(super) fn adapt_decay(raw: Option<&str>) -> (f32, Option) { /// least twice (most first) against the resident ones (least first), pairwise while /// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer /// order (`std::sort` leaves tie order unspecified). -pub(in crate::qwen_forward) fn choose_swaps(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { +pub(in crate::qwen_forward) fn choose_swaps( + usage: &[f32], + resident: impl Fn(usize, usize) -> bool, + max_swaps: usize, +) -> Vec { let (min_count, margin, _) = adapt_tuning(); let mut swaps = Vec::new(); if usage.len() != LAYERS * EXPERTS { @@ -191,7 +200,11 @@ pub(in crate::qwen_forward) fn choose_swaps(usage: &[f32], resident: impl Fn(usi /// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same order. #[cfg(test)] -pub(super) fn choose_swaps_reference(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec { +pub(super) fn choose_swaps_reference( + usage: &[f32], + resident: impl Fn(usize, usize) -> bool, + max_swaps: usize, +) -> Vec { let (min_count, margin, _) = adapt_tuning(); let mut swaps = Vec::new(); if usage.len() != LAYERS * EXPERTS { @@ -229,7 +242,11 @@ pub(super) fn choose_swaps_reference(usage: &[f32], resident: impl Fn(usize, usi impl ResidencyStats { pub(crate) fn describe(&self) -> String { let all = (self.vram_entries + self.pcie_entries + self.cpu_entries).max(1) as f64; - let tail = if self.tail_entries > 0 { format!(", route tail skip {} entries / {} experts", self.tail_entries, self.tail_experts) } else { String::new() }; + let tail = if self.tail_entries > 0 { + format!(", route tail skip {} entries / {} experts", self.tail_entries, self.tail_experts) + } else { + String::new() + }; format!( "expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps{}", self.groups, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs index f11895d3..004fac5e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tail_skip_rank_fn.rs @@ -15,7 +15,8 @@ pub(crate) fn tail_skip_rank() -> u32 { } /// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to the environment. pub(crate) fn set_tail_skip_arm(rank: Option) { - TAIL_SKIP_RANK.store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed); + TAIL_SKIP_RANK + .store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed); } /// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all experts. pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 { @@ -23,16 +24,21 @@ pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 { if rank == 0 { return 0; } - let cached: usize = (0..LAYERS).map(|l| (0..EXPERTS).filter(|&e| cache.resident_slot(l, e).is_some()).count()).sum(); + let cached: usize = + (0..LAYERS).map(|l| (0..EXPERTS).filter(|&e| cache.resident_slot(l, e).is_some()).count()).sum(); let percent = 100.0 * cached as f64 / (LAYERS * EXPERTS) as f64; let limit = crate::settings::process().memory.route_tail_skip_max_cached; let effective = if percent >= limit { 0 } else { rank }; static ANNOUNCED: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED); if ANNOUNCED.swap(effective, Ordering::Relaxed) != effective { if effective == 0 { - eprintln!("leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)"); + eprintln!( + "leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)" + ); } else { - eprintln!("leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES"); + eprintln!( + "leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES" + ); } } effective @@ -92,10 +98,18 @@ impl ExpertTierConfig { if self.slots == 0 && self.profile.is_some() { -1 } else { self.slots } } pub(crate) fn validate(&self) -> Result<()> { - if self.slots < -1 || !self.pcie_frac.is_finite() || !(0.0..=1.0).contains(&self.pcie_frac) || self.adapt_swaps > 4096 - || !self.resident_budget_gib.is_finite() || self.resident_budget_gib < 0.0 - || !self.seed_keep.is_finite() || self.seed_keep < 0.0 || !self.seed_usage.is_finite() || self.seed_usage < 0.0 - || !(0.0..=1.0).contains(&self.seed_decay) || self.seed_swaps > LAYERS * EXPERTS + if self.slots < -1 + || !self.pcie_frac.is_finite() + || !(0.0..=1.0).contains(&self.pcie_frac) + || self.adapt_swaps > 4096 + || !self.resident_budget_gib.is_finite() + || self.resident_budget_gib < 0.0 + || !self.seed_keep.is_finite() + || self.seed_keep < 0.0 + || !self.seed_usage.is_finite() + || self.seed_usage < 0.0 + || !(0.0..=1.0).contains(&self.seed_decay) + || self.seed_swaps > LAYERS * EXPERTS { return Err(Error::InvalidDimension); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs index cb143e1d..b1375c23 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tests.rs @@ -58,7 +58,9 @@ fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { }; for case in 0..40 { let skew = 1 + case % 7; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect(); + let usage: Vec = (0..LAYERS * EXPERTS) + .map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }) + .collect(); let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect(); let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; for max_swaps in [1usize, 5, 96, 4096] { @@ -66,7 +68,11 @@ fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() { let slow = choose_swaps_reference(&usage, resident, max_swaps); assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}"); for (a, b) in fast.iter().zip(&slow) { - assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}"); + assert_eq!( + (a.layer, a.incoming, a.outgoing, a.gain.to_bits()), + (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), + "case {case} max {max_swaps}" + ); } } } @@ -82,7 +88,8 @@ fn choose_swaps_timing() { x ^= x << 17; x }; - let usage: Vec = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); + let usage: Vec = + (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect(); let resident_bits: Vec = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect(); let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e]; let time = |f: &dyn Fn() -> usize| { @@ -190,7 +197,10 @@ fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() // 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17); // 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18) assert_eq!(on.skipped_experts, 3); - assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), vec![7, 8, 17, 19]); + assert_eq!( + on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::>(), + vec![7, 8, 17, 19] + ); assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1)); assert_eq!(on.kinds[9], 0, "a resident expert is never skipped"); // everything else is exactly what the skip-off split produced diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs index 7435d640..0460268b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency/tier_env_tests.rs @@ -7,17 +7,12 @@ const P: &str = "LELEKA_ORIGINAL_SERVE_"; fn read(pairs: &[(&str, &str)]) -> Result { let pairs: Vec<(String, &str)> = pairs.iter().map(|(k, v)| (format!("{P}{k}"), *v)).collect(); - let env = pairs - .iter() - .fold(MapEnv::new(), |env, (k, v)| env.with(k, v)); + let env = pairs.iter().fold(MapEnv::new(), |env, (k, v)| env.with(k, v)); ExpertTierConfig::from_source(&env) } fn defaults() -> ExpertTierConfig { - ExpertTierConfig { - seed_swaps: super::super::original_serve_seed::DEFAULT_SEED_SWAPS, - ..ExpertTierConfig::off() - } + ExpertTierConfig { seed_swaps: super::super::original_serve_seed::DEFAULT_SEED_SWAPS, ..ExpertTierConfig::off() } } #[test] @@ -27,18 +22,8 @@ fn an_empty_environment_is_off_with_the_seed_on() { #[test] fn slots_are_auto_or_a_number_not_below_minus_one() { - for (value, want) in [ - ("auto", Some(-1)), - ("64", Some(64)), - ("0", Some(0)), - ("-1", Some(-1)), - ("+5", Some(5)), - ] { - assert_eq!( - read(&[("EXPERT_SLOTS", value)]).map(|c| c.slots).ok(), - want, - "{value:?}" - ); + for (value, want) in [("auto", Some(-1)), ("64", Some(64)), ("0", Some(0)), ("-1", Some(-1)), ("+5", Some(5))] { + assert_eq!(read(&[("EXPERT_SLOTS", value)]).map(|c| c.slots).ok(), want, "{value:?}"); } for value in ["-2", "x", "", "1.5", " 5", "AUTO"] { assert!(read(&[("EXPERT_SLOTS", value)]).is_err(), "{value:?}"); @@ -60,34 +45,16 @@ fn per_layer_and_prefill_borrow_never_fail() { #[test] fn the_reserves_and_adapt_counts_are_untrimmed_unsigned_numbers() { - assert_eq!( - read(&[("VRAM_RESERVE_MIB", "512")]).map(|c| c.reserve_mib), - Ok(512) - ); - assert_eq!( - read(&[("DECODE_RESERVE_MIB", "130")]).map(|c| c.decode_reserve_mib), - Ok(130) - ); + assert_eq!(read(&[("VRAM_RESERVE_MIB", "512")]).map(|c| c.reserve_mib), Ok(512)); + assert_eq!(read(&[("DECODE_RESERVE_MIB", "130")]).map(|c| c.decode_reserve_mib), Ok(130)); assert_eq!(read(&[("ADAPT_EVERY", "8")]).map(|c| c.adapt_every), Ok(8)); - assert_eq!( - read(&[("ADAPT_SWAPS", "4096")]).map(|c| c.adapt_swaps), - Ok(4096) - ); - for key in [ - "VRAM_RESERVE_MIB", - "DECODE_RESERVE_MIB", - "ADAPT_EVERY", - "ADAPT_SWAPS", - "SEED_MAX_ROWS", - ] { + assert_eq!(read(&[("ADAPT_SWAPS", "4096")]).map(|c| c.adapt_swaps), Ok(4096)); + for key in ["VRAM_RESERVE_MIB", "DECODE_RESERVE_MIB", "ADAPT_EVERY", "ADAPT_SWAPS", "SEED_MAX_ROWS"] { for value in ["-1", "x", "", " 5", "1.5"] { assert!(read(&[(key, value)]).is_err(), "{key}={value:?}"); } } - assert!( - read(&[("ADAPT_SWAPS", "4097")]).is_err(), - "validate refuses more than 4096 swaps" - ); + assert!(read(&[("ADAPT_SWAPS", "4097")]).is_err(), "validate refuses more than 4096 swaps"); } #[test] @@ -98,16 +65,8 @@ fn the_pcie_share_is_a_fraction_and_marks_itself_as_set() { for value in ["1.5", "-0.1", "NaN", "inf", "x", ""] { assert!(read(&[("PCIE_FRAC", value)]).is_err(), "{value:?}"); } - for (value, want) in [ - ("auto", PcieMode::Auto), - ("dma", PcieMode::Dma), - ("kernel", PcieMode::Kernel), - ] { - assert_eq!( - read(&[("PCIE_MODE", value)]).map(|c| c.pcie_mode), - Ok(want), - "{value:?}" - ); + for (value, want) in [("auto", PcieMode::Auto), ("dma", PcieMode::Dma), ("kernel", PcieMode::Kernel)] { + assert_eq!(read(&[("PCIE_MODE", value)]).map(|c| c.pcie_mode), Ok(want), "{value:?}"); } for value in ["Dma", "", "copy"] { assert!(read(&[("PCIE_MODE", value)]).is_err(), "{value:?}"); @@ -117,20 +76,8 @@ fn the_pcie_share_is_a_fraction_and_marks_itself_as_set() { #[test] fn the_seed_is_a_word_or_a_swap_count_inside_the_bank() { let on = super::super::original_serve_seed::DEFAULT_SEED_SWAPS; - for (value, want) in [ - ("off", 0), - ("no", 0), - ("0", 0), - ("on", on), - ("yes", on), - ("100", 100), - ("24576", 24576), - ] { - assert_eq!( - read(&[("SEED", value)]).map(|c| c.seed_swaps), - Ok(want), - "{value:?}" - ); + for (value, want) in [("off", 0), ("no", 0), ("0", 0), ("on", on), ("yes", on), ("100", 100), ("24576", 24576)] { + assert_eq!(read(&[("SEED", value)]).map(|c| c.seed_swaps), Ok(want), "{value:?}"); } for value in ["x", "", "24577", "-1", "Off"] { assert!(read(&[("SEED", value)]).is_err(), "{value:?}"); @@ -139,20 +86,11 @@ fn the_seed_is_a_word_or_a_swap_count_inside_the_bank() { #[test] fn the_seed_weights_and_the_resident_budget_are_non_negative_numbers() { - let config = read(&[ - ("SEED_KEEP", "2.5"), - ("SEED_USAGE", "0.5"), - ("SEED_DECAY", "0.25"), - ("RESIDENT_BUDGET_GIB", "12.5"), - ]) - .unwrap(); + let config = + read(&[("SEED_KEEP", "2.5"), ("SEED_USAGE", "0.5"), ("SEED_DECAY", "0.25"), ("RESIDENT_BUDGET_GIB", "12.5")]) + .unwrap(); assert_eq!( - ( - config.seed_keep, - config.seed_usage, - config.seed_decay, - config.resident_budget_gib - ), + (config.seed_keep, config.seed_usage, config.seed_decay, config.resident_budget_gib), (2.5, 0.5, 0.25, 12.5) ); for (key, value) in [ @@ -170,12 +108,6 @@ fn the_seed_weights_and_the_resident_budget_are_non_negative_numbers() { #[test] fn the_profile_path_is_kept_as_set_without_a_check() { assert_eq!(read(&[]).unwrap().profile, None); - assert_eq!( - read(&[("EXPERT_PROFILE", "/p/x.strp")]).unwrap().profile, - Some(PathBuf::from("/p/x.strp")) - ); - assert_eq!( - read(&[("EXPERT_PROFILE", "")]).unwrap().profile, - Some(PathBuf::from("")) - ); + assert_eq!(read(&[("EXPERT_PROFILE", "/p/x.strp")]).unwrap().profile, Some(PathBuf::from("/p/x.strp"))); + assert_eq!(read(&[("EXPERT_PROFILE", "")]).unwrap().profile, Some(PathBuf::from(""))); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency_gpu.rs index d0ef4969..d5f3d88f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_residency_gpu.rs @@ -63,7 +63,13 @@ fn expert_blob(seed: u64) -> Vec { } /// The native CPU path for the entries `include` selects; every other entry's row is zeros. -fn cpu_rows(pool: &mut CpuPool, blobs: &dyn Fn(i32) -> Vec, ids: &[i32], activation: &[f32], include: &[bool]) -> Vec { +fn cpu_rows( + pool: &mut CpuPool, + blobs: &dyn Fn(i32) -> Vec, + ids: &[i32], + activation: &[f32], + include: &[bool], +) -> Vec { let mut out = vec![0.0f32; ids.len() * H]; let mut experts: Vec = Vec::new(); for (i, &e) in ids.iter().enumerate() { @@ -146,21 +152,33 @@ fn the_vram_tier_computes_the_resident_experts_and_leaves_the_misses_bit_identic // all-CPU reference: no plan, the run loop's empty plan let reference = probe - .run_group(LAYER, &activation, &ids, |rows: OriginalVerifyCpuRows<'_>, sink: &mut OriginalVerifyCpuSink<'_, '_>, _copy| { - let values = cpu_rows(&mut cpu, &blobs, rows.ids, rows.activation, &vec![true; rows.ids.len()]); - sink.with_output(|out| { - out.copy_from_slice(&values); - Ok(()) - }) - }) + .run_group( + LAYER, + &activation, + &ids, + |rows: OriginalVerifyCpuRows<'_>, sink: &mut OriginalVerifyCpuSink<'_, '_>, _copy| { + let values = cpu_rows(&mut cpu, &blobs, rows.ids, rows.activation, &vec![true; rows.ids.len()]); + sink.with_output(|out| { + out.copy_from_slice(&values); + Ok(()) + }) + }, + ) .expect("all-CPU group"); // the tier's split let mut placed = None; let tier = probe .run_group(LAYER, &activation, &ids, |rows, sink, copy| { - let split = split_group(rows.ids, K, sink.plan_capacity(), |e| cache.resident_slot(LAYER, e as usize), 0, sink.staging_capacity()) - .map_err(|_| leleka_cuda_driver::Error::InvalidQwenShape)?; + let split = split_group( + rows.ids, + K, + sink.plan_capacity(), + |e| cache.resident_slot(LAYER, e as usize), + 0, + sink.staging_capacity(), + ) + .map_err(|_| leleka_cuda_driver::Error::InvalidQwenShape)?; sink.publish_gpu_plan(&split.plan, &cache, None, copy)?; let include: Vec = split.kinds.iter().map(|&k| k < 0).collect(); let values = cpu_rows(&mut cpu, &blobs, rows.ids, rows.activation, &include); @@ -183,7 +201,10 @@ fn the_vram_tier_computes_the_resident_experts_and_leaves_the_misses_bit_identic let (t, r) = (&tier[i * H..(i + 1) * H], &reference[i * H..(i + 1) * H]); assert!(t.iter().all(|x| x.is_finite()), "entry {i} not finite"); if split.kinds[i] < 0 { - assert!(t.iter().zip(r).all(|(a, b)| a.to_bits() == b.to_bits()), "CPU entry {i} differs from the all-CPU run"); + assert!( + t.iter().zip(r).all(|(a, b)| a.to_bits() == b.to_bits()), + "CPU entry {i} differs from the all-CPU run" + ); } else { let e = rel(t, r); assert!(r.iter().any(|x| *x != 0.0) && t.iter().any(|x| *x != 0.0), "entry {i} is zero"); @@ -191,7 +212,9 @@ fn the_vram_tier_computes_the_resident_experts_and_leaves_the_misses_bit_identic worst = worst.max(e); } } - eprintln!("expert tier probe: 7 GPU entries, worst GPU-vs-CPU relative L1 {worst:.3e} (gate 3e-2); 23 CPU entries bit-identical"); + eprintln!( + "expert tier probe: 7 GPU entries, worst GPU-vs-CPU relative L1 {worst:.3e} (gate 3e-2); 23 CPU entries bit-identical" + ); // integrity: a plan naming the slot of expert 41 for an entry routed to expert 7 is refused before any read let refused = probe.run_group(LAYER, &activation, &ids, |_rows, sink, copy| { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs index cf7fd135..e8595e73 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_seed.rs @@ -15,7 +15,7 @@ use super::{ contract::{Error, Result}, moe_weight_cache::MoeWeightCache, original_serve_pool::CpuExpertPool, - original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap}, + original_serve_residency::{SpanCache, Swap, choose_swaps, source_spans}, original_serve_verifier::driver_error, }; use crate::model_binding::qwen4exp_input::ModelBinding; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs index 8277d0df..ab5df9db 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack.rs @@ -21,28 +21,32 @@ use super::{ contract::{Error, Result}, dense_weight_cache::DenseWeightCache, - executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor}, + executor::original_prompt::{OriginalPromptExecutor, embedding::OriginalPromptEmbedding}, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache, original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, - original_serve_config::{expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants}, - original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome}, + original_serve_config::{ + ExpertBlobSizes, RopeConstants, expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, + }, + original_serve_engine::{OriginalServeEngine, OriginalServeSettings, ServeOutcome, serve_request}, original_serve_host::{HostOwners, OriginalServeHost, RequestSampling}, original_serve_native::NativeServePort, original_serve_pool::{CpuExpertPool, OriginalServePool}, original_serve_profile as profile, + original_serve_request::{RequestOwners, ServeDevice, ServeError, ServeRequest, run_request}, original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState}, original_serve_seed::{self, SeedReport}, - original_serve_request::{run_request, RequestOwners, ServeDevice, ServeError, ServeRequest}, original_serve_verifier::{ - assemble, assemble_with_window_fallback, disassemble, seed_ple_history, AssembleFailure, DecodeResources, ServeFailure, VerifyWeights, - PLE_HISTORY_BYTES, + AssembleFailure, DecodeResources, PLE_HISTORY_BYTES, ServeFailure, VerifyWeights, assemble, + assemble_with_window_fallback, disassemble, seed_ple_history, }, original_spec_controller::{OriginalSpecController, SpecError}, output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, session::{ - original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, QwenSession, + original_prompt::{ + OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession, draft::OriginalDraftCheckpoint, + }, }, }; use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; @@ -71,10 +75,10 @@ use conversation::{ResumeDevice, ServeConversation}; #[path = "original_serve_prefix.rs"] mod prefix; -pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; +use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; use leleka_obs::time::{AnyClock, Clock}; use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; -use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; +pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; /// Stage marks of one request's time to first token (milliseconds since `serve` was entered). #[derive(Clone, Copy, Debug)] @@ -266,27 +270,27 @@ pub(crate) mod lifecycle_fake; mod impl_default_for_ttftmarks; #[allow(unused_imports)] -use impl_default_for_ttftmarks::prefill_bytes; -#[allow(unused_imports)] -use impl_default_for_ttftmarks::tier_for; -#[allow(unused_imports)] -use impl_default_for_ttftmarks::plan_error; +use impl_default_for_ttftmarks::at; #[allow(unused_imports)] use impl_default_for_ttftmarks::failure; #[allow(unused_imports)] -use impl_default_for_ttftmarks::at; +use impl_default_for_ttftmarks::plan_error; +#[allow(unused_imports)] +use impl_default_for_ttftmarks::prefill_bytes; +#[allow(unused_imports)] +use impl_default_for_ttftmarks::tier_for; mod impl_originalservestack; mod impl_promptchunk; #[allow(unused_imports)] -use impl_promptchunk::vram_note; -#[allow(unused_imports)] pub(crate) use impl_promptchunk::dbg_el; #[allow(unused_imports)] -use impl_promptchunk::report_kernel_selection; -#[allow(unused_imports)] -use impl_promptchunk::operator_note; -#[allow(unused_imports)] use impl_promptchunk::operator_line; #[allow(unused_imports)] +use impl_promptchunk::operator_note; +#[allow(unused_imports)] use impl_promptchunk::operator_text; +#[allow(unused_imports)] +use impl_promptchunk::report_kernel_selection; +#[allow(unused_imports)] +use impl_promptchunk::vram_note; mod impl_prefixdevice_for_originalservestack; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs index f9a75c7f..99696ae1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP @@ -21,7 +19,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { error: Error::InvalidDimension, - detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), + detail: Some(format!( + "--kv-resident {}: the process already serves another resident KV window", + config.kv_resident + )), })?; if let Some(footprint) = config.kv_footprint() { operator_note(&footprint.to_string()); @@ -30,19 +31,29 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { return Err(failure(Error::IdentityMismatch)); } if binding.layer_count() != 48 { - return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); + return Err(ServeFailure { + error: Error::IdentityMismatch, + detail: Some("the Original serve stack serves the 48-layer model only".to_owned()), + }); } if !binding.has_mtp() { return Err(ServeFailure { error: Error::Unsupported(super::super::super::contract::Stage::Session), - detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), + detail: Some( + "the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned(), + ), }); } - let max_cells = usize::try_from(super::super::super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; + let max_cells = + usize::try_from(super::super::super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; let env = crate::settings::process().env(); let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled, env); let mut arm_label = String::from("env"); - let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled, env).into_iter().map(|(l, _)| l).collect(); + let arm_order: Vec = + OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled, env) + .into_iter() + .map(|(l, _)| l) + .collect(); let mut parked = Vec::new(); let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled, env); let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); @@ -62,36 +73,91 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { vram_note(context, "open begin"); // The native head + embedding come first: with LELEKA_PROMPT_EMBED_ALIAS=1 the prompt path's token table aliases the mapped host copy // of the native embedding instead of a second copy in VRAM (the two are the same GGUF tensor). - let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); - let embedding = staged!("embedding table", context, if OriginalPromptEmbedding::alias_enabled() { - OriginalPromptEmbedding::alias_native(binding, context, output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?).map_err(at("OriginalPromptEmbedding::alias_native"))? - } else { - OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))? - }); - let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { - Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), - None => None, - }); - let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); - let mut moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout, super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some())).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); + let output = staged!( + "native head + embedding", + context, + OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true) + .map_err(at("OriginalNativeOutput::load"))? + ); + let embedding = staged!( + "embedding table", + context, + if OriginalPromptEmbedding::alias_enabled() { + OriginalPromptEmbedding::alias_native( + binding, + context, + output.embedding(binding).map_err(at("OriginalNativeOutput::embedding"))?, + ) + .map_err(at("OriginalPromptEmbedding::alias_native"))? + } else { + OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))? + } + ); + let kar = staged!( + "KAR PLE cache", + context, + match binding.kar_ple_binding() { + Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), + None => None, + } + ); + let dense = staged!( + "dense weights", + context, + DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity) + .map_err(at("DenseWeightCache::new_original_prompt_capacity"))? + ); + let mut moe = staged!( + "MoE arena cache", + context, + MoeWeightCache::new_original_prompt_arena( + binding, + context, + layout, + super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) + ) + .map_err(at("MoeWeightCache::new_original_prompt_arena"))? + ); if !super::super::super::original_serve_config::mtp_pack_experts_needed(config.rt_directory.is_some()) { - operator_note("footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)"); + operator_note( + "footprint: the pinned MTP pack's expert bank (675 MiB) is not uploaded: the draft layer is loaded from the RT directory and never reads it (LELEKA_FOOTPRINT_LEGACY=1 keeps it)", + ); } vram_note(context, "after embedding, output, kar, dense, moe arena"); let mut session = QwenSession::for_binding_on_shared_device(binding, shared); - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); + let request = + OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); let (executor, draft) = match &config.rt_directory { Some(directory) => OriginalPromptExecutor::select_rt_mtp( - binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, + binding, + &dense, + &mut session, + context, + &embedding, + &output, + directory, + config.capacity, + true, + &request, ) .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, None => { let mut executor = OriginalPromptExecutor::new( - binding, &dense, &mut session, context, &moe, &embedding, config.capacity, verifier_max_t, true, - ).map_err(at("OriginalPromptExecutor::new"))?; - let assembly = OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; + binding, + &dense, + &mut session, + context, + &moe, + &embedding, + config.capacity, + verifier_max_t, + true, + ) + .map_err(at("OriginalPromptExecutor::new"))?; + let assembly = + OriginalMtpFullOwner::assemble(binding, &session, context, &moe, &embedding, &output, &request) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?; let draft = executor.install_full_mtp(binding, &session, assembly).map_err(at("install_full_mtp"))?; (executor, draft) } @@ -102,7 +168,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let share = moe.share_rt_mtp_dense(retained).map_err(at("share_rt_mtp_dense"))?; operator_note(&format!( "footprint: MTP dense roles shared with the RT bank (byte-equal): {} shared, {} kept ({} differing), {:.1} MiB released", - share.shared, share.kept, share.differing, share.released_bytes as f64 / f64::from(1u32 << 20) + share.shared, + share.kept, + share.differing, + share.released_bytes as f64 / f64::from(1u32 << 20) )); } } @@ -112,21 +181,46 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers // after the cache when it cannot borrow them; without the tier the order is unchanged. let tier = config.expert_tier.enabled(); - let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); + let mut arena = staged!( + "prefill arena", + context, + if tier { + None + } else { + Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) + } + ); vram_note(context, "before cache"); - let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); + let history = staged!( + "penalty history", + context, + OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))? + ); let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; - let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); - let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); - let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); + let pool = staged!( + "CPU expert pool", + context, + CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))? + ); + let empty_session = staged!( + "empty-prompt session checkpoint", + context, + executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))? + ); + let empty_draft = staged!( + "empty-prompt draft checkpoint", + context, + draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))? + ); let prefix = match &config.prefix { Some(prefix_config) => { let available = crate::conversation::memory::available_memory(); // the budget comes from the memory governor (what is left above the floors), not from an independent default let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); + let bytes = + crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)); let mut prefix_config = prefix_config.clone(); if let Some(g) = leleka_memory::Governor::global() { // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) @@ -141,9 +235,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { )); None } else { - let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let identity = + format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); let clock = config.clock.clone(); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock); + let serve = + PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock); operator_note(&format!( "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", serve.block_tokens(), @@ -158,17 +254,26 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } None => None, }; - let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; + let conversation = + if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; let residency = ResidencyState::new(&config.expert_tier); report_kernel_selection(); vram_note(context, "before expert tier"); let mut loan = None; - let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); + let tier_open = staged!( + "expert tier (VRAM slots + profile fill)", + context, + original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity) + .map_err(at("expert tier"))? + ); let expert_cache = match tier_open { Some((cache, filled)) => { if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { - loan = original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?) - .map_err(at("expert-cache loan"))?; + loan = original_serve_residency::loan_slots( + &cache, + prefill_bytes(layout).map_err(at("prefill bytes"))?, + ) + .map_err(at("expert-cache loan"))?; } operator_note(&format!( "expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)", @@ -189,7 +294,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; - let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; + let slots = original_serve_residency::loan_slots( + cache, + prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?, + ) + .map_err(at("expert-cache loan (tier)"))?; if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); } @@ -197,7 +306,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if !loan_tiers.is_empty() { operator_note(&format!( "prompt loan ladder: {}, up to {} rows {full} slots", - loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), + loan_tiers + .iter() + .map(|t| format!("up to {} rows {} slots", t.rows, t.slots)) + .collect::>() + .join(", "), config.capacity )); } @@ -207,7 +320,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) .unwrap_or_default(); if arena.is_none() && loan.is_none() { - arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); + arena = Some(staged!( + "prefill arena (after the expert tier)", + context, + context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))? + )); } let this = Self { binding, @@ -262,10 +379,16 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { this.register_memory_classes(); crate::memory_governor::post_open(); if let Some(governor) = leleka_memory::Governor::global() { - governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): -{}", governor.inventory().table())); - governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): -{}", governor.ledger().table())); + governor.log(&format!( + "stack open; inventory of allocation classes (accounted by their owners): +{}", + governor.inventory().table() + )); + governor.log(&format!( + "load ledger (measured: kernel and driver deltas per opening step): +{}", + governor.ledger().table() + )); governor.publish(); } Ok(this) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs index 222a6e6e..3cf09dd3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. pub(crate) fn health(&self) -> Option { self.broken @@ -68,7 +65,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } } if let Some(conversation) = self.conversation.as_ref() { - crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); + crate::memory_governor::set_bytes( + "conversation.checkpoints", + conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES, + ); } } @@ -78,9 +78,30 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let Some(governor) = leleka_memory::Governor::global() else { return }; let _ = governor; if let Some(f) = self.config.kv_footprint() { - crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); - crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); - crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); + crate::memory_governor::account( + "kv", + "host_pinned", + Space::HostPinned, + When::Startup, + "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", + f.pinned_host_bytes as u64, + ); + crate::memory_governor::account( + "kv", + "vram_window", + Space::Device, + When::Startup, + "12 layers x resident pages x 4244 B (+ page table + resolver state)", + f.vram_bytes as u64, + ); + crate::memory_governor::account( + "kv", + "prompt_stage", + Space::Device, + When::Startup, + "one INT8 staging pool of the prompt path (identity layout)", + f.stage_bytes as u64, + ); } if let Ok(bytes) = prefill_bytes(self.layout) { crate::memory_governor::account( @@ -88,15 +109,40 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if self.loan.is_some() { "arena_borrowed" } else { "arena" }, Space::Device, When::Startup, - if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, + if self.loan.is_some() { + "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" + } else { + "carve of the prefill arena at the chunk capacity" + }, if self.loan.is_some() { 0 } else { bytes as u64 }, ); } if let Some(cache) = self.expert_cache.as_ref() { - crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); + crate::memory_governor::account( + "expert_cache", + "slots", + Space::Device, + When::Startup, + "slots x slot bytes (VRAM expert tier)", + cache.bytes() as u64, + ); } - crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); - crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); + crate::memory_governor::account( + "ple", + "history_and_scratch", + Space::Device, + When::Startup, + "PLE history image + scratch", + (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64, + ); + crate::memory_governor::account( + "context", + "accounted_total", + Space::Device, + When::Lazy, + "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", + 0, + ); if let Some(prefix) = self.prefix.as_ref() { crate::memory_governor::account( "prefix", @@ -201,7 +247,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { self.residency.clear_usage(); self.controller = self.settings.controller()?; match self.expert_cache.as_mut() { - Some(cache) => original_serve_seed::restore_placement(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &self.initial_owners), + Some(cache) => original_serve_seed::restore_placement( + self.binding, + &self.moe, + cache, + &mut self.pool, + &mut self.residency.spans, + &self.initial_owners, + ), None => Ok(0), } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs index 3dcd0284..115efb89 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// The prefix cache's metrics line (`None` when the cache is off). #[allow(dead_code)] pub(crate) fn prefix_metrics(&self) -> Option { @@ -28,8 +25,23 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// Close every owner in dependency order; the first failure is reported after all were attempted. pub(crate) fn close(self) -> Result<()> { let Self { - conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, - moe, dense, output, embedding, .. + conversation, + residency, + history, + ple_history, + ple_scratch, + arena, + expert_cache, + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + embedding, + .. } = self; drop(conversation); // the span cache retains registered-source spans of the bank `moe` closes below diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs index 3693375c..7eb7b3ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_4.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. pub(in super::super) fn decode_phase( &mut self, @@ -66,11 +63,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { } // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { - (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { - config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( - super::super::super::contract::Stage::Session, - ))? - } + (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => config + .expert_tier + .pcie_mode + .graph_mode(bank.pageable(), blobs.spans_tile_blobs()) + .ok_or(Error::Unsupported(super::super::super::contract::Stage::Session))?, _ => 0, }; let p = profile::span("decode.seed_ple"); @@ -83,7 +80,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); let owners = executor.take_qsa_owners()?; let ple_history: &DeviceBuffer<'ctx> = &*ple_history; - let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; + let weights = VerifyWeights { + dense: &*dense, + moe: &*moe, + shared: &shared, + formats: &*formats, + ple_scratch: &*ple_scratch, + }; let p = profile::span("decode.assemble"); // queued after assembly's own uploads (canonical GDN image), before the graph capture let mut queue_refill = || -> Result<()> { @@ -104,10 +107,24 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { *verifier_max_t, |max_t| { let Some(owners) = owners_slot.take() else { - return Err((AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, None)); + return Err(( + AssembleFailure { failure: Error::IdentityMismatch.into(), owners: None, window_cap: None }, + None, + )); }; assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, max_t, *max_cells, pcie_mode, + binding, + &weights, + context, + &*output, + &base, + owners, + ple_history, + rope, + blobs, + max_t, + *max_cells, + pcie_mode, &mut queue_refill, ) .map_err(|mut lost| { @@ -133,14 +150,19 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { if let Err(error) = original_serve_residency::settle_refill(cache) { broken.get_or_insert(error); if let Ok(resources) = assembled { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + let _ = disassemble(resources) + .map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); } return Err(SpecError::Forward(error)); } } } vram_note(context, "decode after assemble"); - crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); + crate::bringup_trace!( + "DBG[{:.0}s] decode: assemble -> {}", + dbg_el(), + if assembled.is_ok() { "ok" } else { "ERR" } + ); let resources = match assembled { Ok(resources) => resources, Err(lost) => { @@ -173,7 +195,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { executor.set_mtp_max_drafts(binding, i32::try_from(settings.max_drafts()).map_err(|_| Error::Overflow)?) })(); if let Err(error) = narrowed { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + let _ = disassemble(resources) + .map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); broken.get_or_insert(error); return Err(SpecError::Forward(error)); } @@ -188,7 +211,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { (Some(cache), Some(bank)) => { let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); let tail_rank = original_serve_residency::effective_tail_rank(&*cache); - let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; + let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { + bank.locked_experts() + } else { + Vec::new() + }; gpu_pool = GpuExpertPool { binding, moe: &*moe, @@ -268,7 +295,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); } } - if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } + if let Err(e) = &result { + crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); + } let (mut verifier, mut host) = engine.into_port().0.into_parts(); // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) let gpu_profile = verifier.profile_report(); @@ -283,7 +312,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); if want_tail && result.is_ok() && !tail { - operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); + operator_text( + "prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode", + ); } if (result.is_ok() && config.settle_state) || live || tail { match host.settle_state(&mut verifier) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs index 033b8a7f..53e7cca1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_5.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache @@ -25,7 +22,9 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { self.seed_report = None; if let Some(cache) = self.expert_cache.as_mut() { let _p = profile::span("prefill.wait_swaps"); - cache.wait_swaps().map_err(|e| SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e)))?; + cache + .wait_swaps() + .map_err(|e| SpecError::Forward(super::super::super::original_serve_verifier::driver_error(&e)))?; } // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); @@ -39,10 +38,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the // decode phase's host-side assembly // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) - let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); + let defer = read.is_ok() + && !seeding + && original_serve_residency::refill_defer_enabled() + && self.loan.is_some() + && self.expert_cache.is_some(); let refilled = match (self.loan, self.expert_cache.as_mut()) { (Some(_), Some(cache)) if !defer => { - original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) + original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) + .map(|_| ()) } _ => Ok(()), }; @@ -83,7 +87,14 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let swaps = original_serve_seed::plan(counts, cache, max, keep); let planned = self.config.clock.since(started); let mut report = original_serve_seed::summarize(counts, &swaps); - original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; + original_serve_seed::queue_swaps( + self.binding, + &self.moe, + cache, + &mut self.pool, + &mut self.residency.spans, + &swaps, + )?; report.plan_ms = planned.as_secs_f64() * 1e3; report.queue_ms = (self.config.clock.since(started) - planned).as_secs_f64() * 1e3; self.residency.add_usage(counts, usage); @@ -128,7 +139,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let mut best: Vec = usage[range.clone()].to_vec(); best.sort_by(|a, b| b.total_cmp(a)); oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); - by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); + by_initial += + (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); } // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. eprintln!( @@ -152,7 +164,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // sampling parameters configure the actor for the whole request. let mtp_setup_span = profile::span("prefill.mtp_setup"); self.executor.set_mtp_prompt_len(binding, n as i64)?; - self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; + self.executor + .set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; self.executor.set_mtp_draft_sampling(binding, &request.params)?; drop(mtp_setup_span); if n < 2 { @@ -178,16 +191,40 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the // capacity allows: its states are not grid-canonical anyway) - (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), + (Some(prefix), _) => ( + PromptOptions { + grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, + ..options + }, + None, + ), (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), (None, None) => (options, None), }; let capacity = self.config.capacity; - let plan = PromptPlan::new_in_context(crate::qwen_forward::contract::serving_cells(), &tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; + let plan = PromptPlan::new_in_context( + crate::qwen_forward::contract::serving_cells(), + &tokens, + resume, + reread_to, + None, + options, + capacity, + ) + .map_err(|e| { + crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); + plan_error(e) + })?; crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); drop(setup_span); for action in plan { - crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); + crate::bringup_trace!( + "DBG[{:.0}s] prompt action path={:?} first={} count={}", + dbg_el(), + action.path, + action.first, + action.count + ); if action.path == PromptPath::FinalSeed { // the last prompt token is the first verify input of the decode phase break; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs index 192de8fd..631a104c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_originalservestack/impl_originalservestack_6.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. @@ -17,8 +14,21 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { cancel: &mut dyn FnMut() -> bool, ) -> std::result::Result<(), SpecError> { let Self { - binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, - scalar_policy, .. + binding, + moe, + arena, + layout, + expert_cache, + loan, + loan_tiers, + executor, + draft, + session, + kar, + dense, + embedding, + scalar_policy, + .. } = self; let mut chunk = PromptChunk { binding: *binding, @@ -36,7 +46,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { super::super::super::prefill_profile::begin_chunk(); let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { (Some(slots), Some(cache), _) => match { - let _span = super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None); + let _span = + super::super::super::prefill_profile::span(super::super::super::prefill_profile::Stage::Lend, None); // the smallest rung of the ladder that holds the chunk let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); cache.lend_prefill_tail(slots, options) @@ -60,10 +71,18 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let _span = profile::span("prefix.after_prefill"); match prefix.after_prefill(self, prompt) { Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + operator_text(&format!( + "prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", + bytes >> 20 + )); + } + Ok(other) => operator_text(&format!( + "prefix tail (prompt end) not taken: {other:?}: {}", + prefix.take_note().unwrap_or_default() + )), + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")) } - Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), } self.prefix = Some(prefix); } @@ -75,10 +94,18 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { let _span = profile::span("prefix.after_decode"); match prefix.after_decode(self, consumed) { Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + operator_text(&format!( + "prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", + bytes >> 20 + )); + } + Ok(other) => operator_text(&format!( + "prefix tail (decode end) not taken: {other:?}: {}", + prefix.take_note().unwrap_or_default() + )), + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")) } - Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), } self.prefix = Some(prefix); } @@ -91,12 +118,18 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { match prefix.after_chunk(self, prompt, end) { Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { if crate::settings::process().diagnostics.prefix_trace { - operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + operator_text(&format!( + "prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", + bytes >> 20 + )); } } Ok(other) => { if crate::settings::process().diagnostics.prefix_trace && !matches!(other, ChunkOutcome::Nothing) { - operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); + operator_text(&format!( + "prefix admit (grid point {end}) not taken: {other:?}: {}", + prefix.take_note().unwrap_or_default() + )); } } Err(error) => { @@ -123,7 +156,11 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs /// the cache, never the request: the cache is dropped and the request goes on. - pub(in super::super) fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { + pub(in super::super) fn after_prompt_action( + &mut self, + prompt: &[i32], + action: &crate::backend::original_prompt::PromptAction, + ) { let Some(mut conversation) = self.conversation.take() else { return }; let _span = profile::span("conv.after_action"); if let Err(error) = conversation.after_action(self, prompt, action) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs index 04cc06f9..78f6b06d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_prefixdevice_for_originalservestack.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The prefix cache's device side over the stack's own owners. impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { type State = StackState; @@ -44,7 +43,8 @@ impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); let _p = profile::span("prefix.import_session"); // a refused import touches nothing; a failed physical one poisons the executor - let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); + let imported = + self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); if let Err(error) = imported { self.mark_broken(error); } @@ -120,7 +120,12 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { self.conversation = Some(conversation); resume } - fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { + fn prefill( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { let started = self.config.clock.now(); self.timing = (0.0, 0.0); self.marks.resumed = self.marks.since(&self.config.clock); @@ -148,7 +153,13 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { // an exit before the decode phase queued the refill still refills now; one before it waited still waits if std::mem::take(&mut self.refill_due) { if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) { + if let Err(error) = original_serve_residency::refill_lent( + self.binding, + &self.moe, + cache, + &mut self.residency.spans, + false, + ) { self.mark_broken(error); } } @@ -164,14 +175,27 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { profile::add("decode.phase", self.timing.1); if profile::enabled() { let t1 = self.residency.stats; - let (v, p, c) = (t1.vram_entries - tier0.vram_entries, t1.pcie_entries - tier0.pcie_entries, t1.cpu_entries - tier0.cpu_entries); + let (v, p, c) = ( + t1.vram_entries - tier0.vram_entries, + t1.pcie_entries - tier0.pcie_entries, + t1.cpu_entries - tier0.cpu_entries, + ); let all = (v + p + c).max(1) as f64; // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) eprintln!( "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", - 100.0 * v as f64 / all, 100.0 * p as f64 / all, 100.0 * c as f64 / all, - 100.0 * v as f64 / ((v + c).max(1) as f64), t1.adaptations - tier0.adaptations, t1.swaps - tier0.swaps, - self.residency.pcie_lag.as_ref().map(|l| l.pcie_num()).or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())).unwrap_or(self.config.expert_tier.pcie_num()) + 100.0 * v as f64 / all, + 100.0 * p as f64 / all, + 100.0 * c as f64 / all, + 100.0 * v as f64 / ((v + c).max(1) as f64), + t1.adaptations - tier0.adaptations, + t1.swaps - tier0.swaps, + self.residency + .pcie_lag + .as_ref() + .map(|l| l.pcie_num()) + .or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())) + .unwrap_or(self.config.expert_tier.pcie_num()) ); } // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts @@ -192,7 +216,10 @@ impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { if let Some(prefix) = self.prefix.as_mut() { prefix.finish(completed); let (admitted, park_ms, consider_ms) = prefix.request_parking(); - operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); + operator_text(&format!( + "prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", + prefix.describe() + )); } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs index 6708410c..f88583bd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/impl_promptchunk.rs @@ -24,7 +24,9 @@ impl<'ctx> PromptChunk<'_, 'ctx> { self.scalar_policy, || cancel(), ); - if let Err(e) = &pending { crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); } + if let Err(e) = &pending { + crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); + } let pending = match pending { Ok(pending) => pending, Err(error) if cancel() => { @@ -50,7 +52,12 @@ pub(super) fn vram_note(context: &Context<'_>, label: &str) { // the low-water mark of the card's free VRAM over every note of this process: the number the reserve must cover static LOWEST_FREE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX); let lowest = LOWEST_FREE.fetch_min(free, std::sync::atomic::Ordering::Relaxed).min(free); - eprintln!("DBG vram {label}: free {} MiB of {} MiB (lowest note so far {} MiB)", free >> 20, total >> 20, lowest >> 20); + eprintln!( + "DBG vram {label}: free {} MiB of {} MiB (lowest note so far {} MiB)", + free >> 20, + total >> 20, + lowest >> 20 + ); } } } @@ -169,7 +176,10 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { Some(start.resume) } Ok(None) => { - operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); + operator_text(&format!( + "prefix request: n={n} hit=no resume=0 match_us={:.0}", + prefix.last_match_us() + )); None } Err(error) => { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs index 97dce55f..14f151ae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake.rs @@ -51,9 +51,7 @@ pub(crate) fn wrong(x: i32) -> i32 { /// The `count` tokens the model generates after `last`. pub(crate) fn greedy_continuation(last: i32, count: usize) -> Vec { - std::iter::successors(Some(model(last)), |&t| Some(model(t))) - .take(count) - .collect() + std::iter::successors(Some(model(last)), |&t| Some(model(t))).take(count).collect() } /// What the device does, per request. Failures fire once. @@ -149,13 +147,7 @@ impl FakeDevice { /// The log lines that start with `prefix`. pub(crate) fn lines(&self, prefix: &str) -> Vec { - self.0 - .borrow() - .log - .iter() - .filter(|l| l.starts_with(prefix)) - .cloned() - .collect() + self.0.borrow().log.iter().filter(|l| l.starts_with(prefix)).cloned().collect() } /// Prompt tokens the session holds. @@ -187,8 +179,7 @@ impl FakeDevice { s.clock.advance_ms(s.script.chunk_ms); let index = s.chunks; s.chunks += 1; - s.log - .push(format!("chunk first={first} count={}", tokens.len())); + s.log.push(format!("chunk first={first} count={}", tokens.len())); if first as u64 != s.position { return Err(Error::IdentityMismatch); } @@ -241,23 +232,14 @@ impl FakeDevice { } /// The picks of one draft call: a chain of the model from `start`, correct for the first `accept` picks. - pub(crate) fn draft_chain( - &self, - start: i32, - max_drafts: usize, - min_p: f32, - ) -> (Vec, Vec) { + pub(crate) fn draft_chain(&self, start: i32, max_drafts: usize, min_p: f32) -> (Vec, Vec) { let mut s = self.0.borrow_mut(); let accept = s.script.accepted(s.drafts); s.drafts += 1; let (mut ids, mut probabilities) = (Vec::new(), Vec::new()); let mut right = model(start); while ids.len() < max_drafts.max(1) && probabilities.last().is_none_or(|&p| p >= min_p) { - ids.push(if ids.len() < accept { - right - } else { - wrong(right) - }); + ids.push(if ids.len() < accept { right } else { wrong(right) }); probabilities.push(0.9); right = model(right); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs index c17d3f99..95afec51 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/port.rs @@ -58,11 +58,7 @@ impl OriginalServePort for FakeDevice { self.log(format!("run t={}", inputs.len())); self.begin_round()?; let outputs = inputs.iter().map(|&x| model(x)).collect(); - Ok(Window { - inputs: inputs.to_vec(), - outputs, - position, - }) + Ok(Window { inputs: inputs.to_vec(), outputs, position }) } fn validate_window(&self, window: &Window, position: i64, inputs: &[i32]) -> Result<()> { @@ -77,11 +73,7 @@ impl OriginalServePort for FakeDevice { fn commit_window(&mut self, window: &mut Window, keep: usize) -> Result<()> { self.log(format!("commit keep={keep}")); let (inputs, outputs) = (window.inputs.clone(), window.outputs.clone()); - self.state().pending = Some(super::Pending { - keep, - inputs, - outputs, - }); + self.state().pending = Some(super::Pending { keep, inputs, outputs }); Ok(()) } @@ -92,8 +84,7 @@ impl OriginalServePort for FakeDevice { }; self.log("wait-commit"); let mut s = self.state(); - s.committed - .extend_from_slice(&pending.inputs[1..pending.keep]); + s.committed.extend_from_slice(&pending.inputs[1..pending.keep]); s.committed.push(pending.outputs[pending.keep - 1]); s.sampler_cell += pending.keep as i64; Ok(()) @@ -133,12 +124,7 @@ impl OriginalServePort for FakeDevice { ) -> Result { self.log(format!("draft a={accepted_row}")); let (ids, probabilities) = self.draft_chain(outputs[accepted_row], max_drafts, min_p); - Ok(DraftCompletion { - ids, - probabilities, - first_cell: position + accepted_row as i64, - accepted_row, - }) + Ok(DraftCompletion { ids, probabilities, first_cell: position + accepted_row as i64, accepted_row }) } fn drain_draft(&mut self) -> Result<()> { @@ -157,12 +143,7 @@ impl OriginalServePort for FakeDevice { ) -> Result { self.log("draft-first"); let (ids, probabilities) = self.draft_chain(token, max_drafts, min_p); - Ok(DraftCompletion { - ids, - probabilities, - first_cell: cell, - accepted_row: 0, - }) + Ok(DraftCompletion { ids, probabilities, first_cell: cell, accepted_row: 0 }) } fn drain_first(&mut self) -> Result<()> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/prefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/prefix.rs index 4ab6c715..7416acdd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/prefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/prefix.rs @@ -41,9 +41,7 @@ impl FakeDevice { if (first + tokens) as u64 > s.position { return Err(Error::IdentityMismatch); } - Ok(FakeBlock { - cells: s.cells[first..first + tokens].to_vec(), - }) + Ok(FakeBlock { cells: s.cells[first..first + tokens].to_vec() }) } } @@ -61,10 +59,7 @@ impl PrefixDevice for FakeDevice { fn park_state(&mut self) -> Result { let s = self.state(); - Ok(FakeState { - position: s.position, - digest: s.digest, - }) + Ok(FakeState { position: s.position, digest: s.digest }) } fn park_block(&mut self, first: usize, tokens: usize) -> Result { @@ -80,8 +75,7 @@ impl PrefixDevice for FakeDevice { for (index, block) in blocks { s.cells[index * GRID..index * GRID + block.cells.len()].copy_from_slice(&block.cells); } - s.log - .push(format!("import {} blocks={}", state.position, blocks.len())); + s.log.push(format!("import {} blocks={}", state.position, blocks.len())); s.position = state.position; s.digest = state.digest; Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs index a3ae7ec5..2a81171d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/lifecycle_fake/stack.rs @@ -1,7 +1,7 @@ //! `FakeStack`: the request-level seams of the stack over the scripted device. use super::super::{ - PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ServeDevice, - ServeError, ServeRequest, original_serve_residency, plan_error, run_request, + PrefixConfig, PrefixServe, PromptOptions, PromptPath, PromptPlan, RequestOwners, ServeDevice, ServeError, + ServeRequest, original_serve_residency, plan_error, run_request, }; use super::{FakeBlock, FakeDevice, FakeState, GRID, VOCAB}; use crate::backend::original_prompt::PromptAction; @@ -29,15 +29,10 @@ pub(crate) struct FakeStack { impl FakeStack { /// A stack over `dev`, with the cross-session prefix cache on a `GRID` grid when `prefix` is set. pub(crate) fn new(dev: FakeDevice, clock: ManualClock, prefix: bool) -> Self { - let settings = OriginalServeSettings { - suffix_min_match: 0, - ..OriginalServeSettings::mode17(4096, VOCAB, false) - }; + let settings = + OriginalServeSettings { suffix_min_match: 0, ..OriginalServeSettings::mode17(4096, VOCAB, false) }; let cache = prefix.then(|| { - let cfg = PrefixConfig { - block_tokens: GRID, - ..PrefixConfig::auto() - }; + let cfg = PrefixConfig { block_tokens: GRID, ..PrefixConfig::auto() }; PrefixServe::new(cfg, 1024, 1 << 30, "fake").with_clock(clock.clone().into()) }); Self { @@ -109,7 +104,15 @@ impl FakeStack { fn plan<'t>(&self, tokens: &'t [u32], resume: usize) -> Result, SpecError> { let options = self.plan_options(resume); - let plan = PromptPlan::new_in_context(crate::qwen_forward::contract::serving_cells(), tokens, resume, None, None, options, self.capacity); + let plan = PromptPlan::new_in_context( + crate::qwen_forward::contract::serving_cells(), + tokens, + resume, + None, + None, + options, + self.capacity, + ); plan.map_err(plan_error).map_err(SpecError::Forward) } @@ -131,10 +134,7 @@ impl FakeStack { if let Some(prefix) = self.prefix.as_mut() { prefix.before_chunk(action.first); } - self.dev.read_chunk( - &prompt[action.first..action.first + action.count], - action.first, - )?; + self.dev.read_chunk(&prompt[action.first..action.first + action.count], action.first)?; self.after_chunk(prompt, action.first + action.count); Ok(()) } @@ -165,12 +165,8 @@ impl FakeStack { if self.controller.is_failed() { self.controller = self.settings.controller()?; } - let mut engine = OriginalServeEngine::new( - self.dev.clone(), - VOCAB, - self.settings.max_t, - self.settings.max_drafts(), - )?; + let mut engine = + OriginalServeEngine::new(self.dev.clone(), VOCAB, self.settings.max_t, self.settings.max_drafts())?; engine.set_min_p(request.spec_min_p)?; let (clock, started) = (self.clock.clone(), self.clock.now()); serve_request( @@ -255,12 +251,7 @@ impl RequestOwners for FakeStack { } impl ServeDevice for FakeStack { - fn serve( - &mut self, - request: &ServeRequest, - emit: &mut E, - cancel: &mut C, - ) -> Result + fn serve(&mut self, request: &ServeRequest, emit: &mut E, cancel: &mut C) -> Result where E: FnMut(&[i32]) -> Result<(), Error>, C: FnMut() -> bool, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs index 57b81916..5c184765 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_stack/tests.rs @@ -4,7 +4,9 @@ use super::*; #[test] fn a_chunk_borrows_the_smallest_rung_that_holds_it() { - let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); + let blobs = + ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]) + .unwrap(); let layout = prefill_layout_options(8192, 262_144, &blobs); let tiers: Vec = [(512usize, 600usize), (2048, 900)] .into_iter() @@ -41,7 +43,10 @@ fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_ fn the_conversation_cache_is_on_by_default_with_the_original_settings() { let config = StackConfig::new(4096); let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); - assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); + assert_eq!( + (conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), + (6, 16_384, 2048) + ); assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); assert!(config.validate().is_ok()); assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier.rs index 1200c138..e9edc6bf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier.rs @@ -20,8 +20,9 @@ use super::{ }; use crate::model_binding::qwen4exp_input::{BoundLayerKind, ModelBinding}; use leleka_cuda_driver::{ - Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, OriginalVerifyExpertFormats, - OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, OriginalVerifyWindowResources, + Context, DeviceBuffer, OriginalQsaMappedJournal, OriginalQsaResidentIndex, OriginalVerifier, + OriginalVerifyExpertFormats, OriginalVerifyQsaJournal, OriginalVerifyResources, OriginalVerifyWindowPolicy, + OriginalVerifyWindowResources, }; use std::rc::Rc; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/tests.rs index ba6355a2..ac7adc95 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_serve_verifier/tests.rs @@ -17,7 +17,12 @@ fn a_graph_out_of_memory_names_the_widest_window_worth_recording() { assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 0 }, 2), None); assert_eq!(window_cap_after(&D::GraphOutOfMemory { window: 9 }, 4), Some(3)); // every other failure, including a plain out-of-memory the driver did not classify, is not retried - for other in [D::HostAllocation, D::ContextPoisoned, D::InvalidQwenShape, D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }] { + for other in [ + D::HostAllocation, + D::ContextPoisoned, + D::InvalidQwenShape, + D::Driver { operation: "cuGraphInstantiateWithFlags", code: 2 }, + ] { assert_eq!(window_cap_after(&other, 8), None, "{other:?}"); } assert!(ServeFailure::from(D::GraphOutOfMemory { window: 6 }).describe().contains("T=6")); @@ -45,7 +50,14 @@ fn the_assembly_is_repeated_with_narrower_windows_until_one_fits() { assert_eq!(notes, [(8, 6), (6, 5)]); // it fits at once: one attempt, nothing noted let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<_, &str>(8, |t| { calls += 1; Ok(t) }, |_, _| panic!("no retry")); + let (used, outcome) = assemble_with_window_fallback::<_, &str>( + 8, + |t| { + calls += 1; + Ok(t) + }, + |_, _| panic!("no retry"), + ); assert_eq!((used, outcome, calls), (8, Ok(8), 1)); } @@ -60,10 +72,18 @@ fn the_fallback_stops_at_the_floor_on_any_other_failure_and_never_loops() { assert_eq!((used, outcome), (2, Err("oom at 2".to_string()))); // a failure that is not an out-of-memory is returned at once, with no retry let mut calls = 0; - let (used, outcome) = assemble_with_window_fallback::<(), _>(8, |_| { calls += 1; Err(("broken", None)) }, |_, _| panic!("no retry")); + let (used, outcome) = assemble_with_window_fallback::<(), _>( + 8, + |_| { + calls += 1; + Err(("broken", None)) + }, + |_, _| panic!("no retry"), + ); assert_eq!((used, outcome, calls), (8, Err("broken"), 1)); // a cap that does not narrow the window (a bug somewhere) is not followed - let (used, outcome) = assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); + let (used, outcome) = + assemble_with_window_fallback::<(), _>(4, |_| Err(("same", Some(4))), |_, _| panic!("no retry")); assert_eq!((used, outcome), (4, Err("same"))); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs index e9f0e188..63d8a013 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_adaptive_env.rs @@ -10,13 +10,29 @@ pub(crate) fn from_environment(mut config: AdaptiveConfig, env: &impl crate::set env.get(name).and_then(|v| v.trim().parse().ok()) } config = config.with_policy(env.get("LELEKA_SPEC_POLICY").as_deref()); - if let Some(v) = num(env, "LELEKA_SPEC_FLOOR_CEILING") { config.min_p_hi = v; } - if let Some(v) = num(env, "LELEKA_SPEC_EXPLORE") { config.explore_period = v; } - if let Some(v) = num(env, "LELEKA_SPEC_MARGIN") { config.margin = v; } - if let Some(v) = num(env, "LELEKA_SPEC_MIN_P_LO") { config.min_p_lo = v; } - if let Some(v) = num(env, "LELEKA_SPEC_DRAFT_STEP_MS") { config.draft_step_ms = v; } - if let Some(v) = num(env, "LELEKA_SPEC_COST_ALPHA") { config.cost_alpha = v; } - if let Some(v) = num(env, "LELEKA_SPEC_DECAY") { config.decay = v; } - if let Some(v) = num(env, "LELEKA_SPEC_BIAS_RATE") { config.bias_rate = v; } + if let Some(v) = num(env, "LELEKA_SPEC_FLOOR_CEILING") { + config.min_p_hi = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_EXPLORE") { + config.explore_period = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_MARGIN") { + config.margin = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_MIN_P_LO") { + config.min_p_lo = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_DRAFT_STEP_MS") { + config.draft_step_ms = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_COST_ALPHA") { + config.cost_alpha = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_DECAY") { + config.decay = v; + } + if let Some(v) = num(env, "LELEKA_SPEC_BIAS_RATE") { + config.bias_rate = v; + } config } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs index 2be9c00c..f2d5cd73 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller.rs @@ -1,16 +1,19 @@ //! Original generate.cpp serve verification loop. The engine adapter owns all //! actual target/draft capabilities; scheduling metadata never certifies math. -use super::contract::{Error,Result}; -use std::rc::Rc; -use super::original_spec_draft::{DraftBatch,DraftPreparation,OriginalDraftEngine}; -use super::original_spec_adaptive::{AdaptiveConfig,AdaptivePolicy,Choice,DraftPlan,Offer,Origin,SpecStats}; -use super::original_spec_policy::{DraftPolicy,MAX_T}; +use super::contract::{Error, Result}; +use super::original_spec_adaptive::{AdaptiveConfig, AdaptivePolicy, Choice, DraftPlan, Offer, Origin, SpecStats}; +use super::original_spec_draft::{DraftBatch, DraftPreparation, OriginalDraftEngine}; +use super::original_spec_policy::{DraftPolicy, MAX_T}; use super::original_spec_suffix::SuffixDrafter; use super::token_memo::PrefixMemo; +use std::rc::Rc; -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) enum SpecError {Cancelled,Forward(Error)} -type SpecResult=std::result::Result; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum SpecError { + Cancelled, + Forward(Error), +} +type SpecResult = std::result::Result; /// Root's sole actual session/executor implementation supplies these receipts. /// No implementation accepts arbitrary floats/position-only checkpoints. @@ -18,34 +21,34 @@ type SpecResult=std::result::Result; /// real residual even when that suffix is rejected; commit keeps exactly n /// input rows. A sampled pick is verified by equality, exactly like a greedy /// pick: the sampler owns the real Philox/penalty chain (not this controller). -pub(crate) trait OriginalSpecEngine:OriginalDraftEngine { +pub(crate) trait OriginalSpecEngine: OriginalDraftEngine { type Verified; type TargetCheckpoint; type DraftCheckpoint; - fn validate_current(&self,consumed:&[i32],input:i32,position:i64)->Result<()>; - fn checkpoint_target(&self)->Result; - fn checkpoint_draft(&self)->Result; - fn restore_target(&mut self,checkpoint:&Self::TargetCheckpoint)->Result<()>; - fn restore_draft(&mut self,checkpoint:&Self::DraftCheckpoint)->Result<()>; + fn validate_current(&self, consumed: &[i32], input: i32, position: i64) -> Result<()>; + fn checkpoint_target(&self) -> Result; + fn checkpoint_draft(&self) -> Result; + fn restore_target(&mut self, checkpoint: &Self::TargetCheckpoint) -> Result<()>; + fn restore_draft(&mut self, checkpoint: &Self::DraftCheckpoint) -> Result<()>; /// Applies genuinely completed adaptive transfers before verification; /// does not infer residency from pending copy submission. - fn apply_pending(&mut self)->Result<()>; + fn apply_pending(&mut self) -> Result<()>; /// Stages literal per-row penalty histories, then all actual verify rows. - fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result; - fn validate_verified(&self,verified:&Self::Verified,position:i64,inputs:&[i32])->Result<()>; - fn outputs<'a>(&self,verified:&'a Self::Verified)->&'a[i32]; + fn verify(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result; + fn validate_verified(&self, verified: &Self::Verified, position: i64, inputs: &[i32]) -> Result<()>; + fn outputs<'a>(&self, verified: &'a Self::Verified) -> &'a [i32]; /// Real verified-prefix replay/publication; no position-only truncation. - fn commit_verified(&mut self,verified:&mut Self::Verified,input_rows:usize)->Result<()>; - fn drain_verified(&mut self,verified:Self::Verified)->Result<()>; + fn commit_verified(&mut self, verified: &mut Self::Verified, input_rows: usize) -> Result<()>; + fn drain_verified(&mut self, verified: Self::Verified) -> Result<()>; /// Take back the physical effects of a window that was drained without a commit (and whose checkpoints were restored), so that /// `verify` accepts the same position again. Nothing outstanding is not an error. Only the NaN guard's retry calls it. - fn discard_window(&mut self)->Result<()>; + fn discard_window(&mut self) -> Result<()>; /// Starts host adaptive work beside commit/draft at actual completed-round /// cadence. Return a real pending owner even for an empty/no-work round. type AdaptiveWork; - fn begin_adaptation(&mut self,next_round:u64)->Result; - fn join_adaptation(&mut self,work:Self::AdaptiveWork)->Result<()>; - fn wait_commit(&mut self)->Result<()>; + fn begin_adaptation(&mut self, next_round: u64) -> Result; + fn join_adaptation(&mut self, work: Self::AdaptiveWork) -> Result<()>; + fn wait_commit(&mut self) -> Result<()>; } /// Upstream's NaN guard with self-healing (`STRATA_NAN_GUARD`, f332a855 / 894f133b): how many times a verify window whose logits or stage @@ -53,41 +56,78 @@ pub(crate) trait OriginalSpecEngine:OriginalDraftEngine { /// and lets its gateway send it again from token 0; here the window itself is repeated, which costs one window and keeps the request. /// `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on|off` (a profile `engine_env` key), `..._NAN_GUARD_RETRIES=N` (default 2), /// `..._NAN_INJECT=n[xK]` (debug: the n-th checked window reads as non-finite K times, default 1, to exercise the path). -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub(crate) struct NanGuard {pub(crate) retries:u32,inject_at:u64,inject_times:u32} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) struct NanGuard { + pub(crate) retries: u32, + inject_at: u64, + inject_times: u32, +} pub(crate) struct SpecConfig { - max_t:usize,mtp_t:usize,max_context:i64,vocabulary:u32, - suffix_min_match:usize,coupled:bool, + max_t: usize, + mtp_t: usize, + max_context: i64, + vocabulary: u32, + suffix_min_match: usize, + coupled: bool, /// `LELEKA_SPEC_ADAPTIVE`: the adaptive window policy replaces the fixed `mtp_t` / min_p / DraftPolicy choice. - adaptive:Option, + adaptive: Option, /// See [`NanGuard`]; off unless the caller asks (the controller's own tests rely on the first failure aborting). - nan_guard:NanGuard, + nan_guard: NanGuard, } struct Request { - consumed:Vec,input:i32,position:i64,first_window:bool, - produced:usize,max_new:usize,min_p:f32,eos:Vec,drafts:DraftBatch, - pending_draft:bool,finished:bool, + consumed: Vec, + input: i32, + position: i64, + first_window: bool, + produced: usize, + max_new: usize, + min_p: f32, + eos: Vec, + drafts: DraftBatch, + pending_draft: bool, + finished: bool, /// The part of `consumed` the draft stage already range-checked (`consumed` only grows within a request; see `token_memo`). - vetted:PrefixMemo, + vetted: PrefixMemo, } pub(crate) struct OriginalSpecController { - config:SpecConfig,policy:DraftPolicy,suffix:SuffixDrafter,request:Option,rounds:u64,failed:bool,owner:Rc<()>, + config: SpecConfig, + policy: DraftPolicy, + suffix: SuffixDrafter, + request: Option, + rounds: u64, + failed: bool, + owner: Rc<()>, /// Draft the window after the LAST round too (generate.cpp skips it on EOS/length), so the draft ring stands at the session's /// position when the request ends and a checkpoint of both can be taken there. Off unless the caller asks, per request. - final_draft:bool, - adaptive:Option,plan:Option,stats:SpecStats, + final_draft: bool, + adaptive: Option, + plan: Option, + stats: SpecStats, /// The last draft stage ran a chain shortened by the context's end: the next stage restores the full chain in the engine's plan. - chain_clamped:bool, + chain_clamped: bool, /// Verify windows checked by the NaN guard so far (the injection counts them). - windows_checked:u64, + windows_checked: u64, } /// Holds the authentic complete verification receipt until MTP catch-up has /// consumed all T residuals. It cannot be cloned or used as a state checkpoint. /// The caller emits only tokens() AFTER verify_commit returned successfully. -pub(crate) struct CommittedRound { - verified:V,outputs:[i32;MAX_T],emitted:usize,t:usize,accepted:usize, - position:i64,from_lookup:bool,matched:usize,timed:bool,eos:bool,choice:Option, - next_position:i64,round_number:u64,work:Option,owner:Rc<()>,bookkeeping_error:Option, +pub(crate) struct CommittedRound { + verified: V, + outputs: [i32; MAX_T], + emitted: usize, + t: usize, + accepted: usize, + position: i64, + from_lookup: bool, + matched: usize, + timed: bool, + eos: bool, + choice: Option, + next_position: i64, + round_number: u64, + work: Option, + owner: Rc<()>, + bookkeeping_error: Option, } #[cfg(test)] @@ -95,8 +135,8 @@ mod tests; mod trace_enabled_fn; #[allow(unused_imports)] -pub(crate) use trace_enabled_fn::trace_enabled; -#[allow(unused_imports)] pub(crate) use trace_enabled_fn::stats_enabled; +#[allow(unused_imports)] +pub(crate) use trace_enabled_fn::trace_enabled; mod impl_originalspeccontroller; mod impl_originalspeccontroller_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller.rs index b4edd5d5..a49398eb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller.rs @@ -3,217 +3,5 @@ #[allow(unused_imports)] use super::*; -impl OriginalSpecController { - /// Conservative preallocation ledger for Root before construction. Actual - /// allocator capacities are checked by host_bytes() before publication. - pub(crate) fn planned_host_bytes(config:&SpecConfig,prompt_len:usize,max_new:usize,eos_count:usize)->Result { - if prompt_len==0||prompt_len>config.max_context as usize {return Err(Error::InvalidDimension);} - let h=(config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?; - let table=h.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?; - let history=prompt_len.checked_add(max_new).and_then(|n|n.checked_add(config.max_t)).ok_or(Error::Overflow)? - .min(config.max_context as usize+MAX_T); - table.checked_mul(32).and_then(|n|n.checked_add(h.checked_mul(4)?)) - .and_then(|n|n.checked_add(history.checked_mul(4)?)) - .and_then(|n|n.checked_add(eos_count.checked_mul(4)?)) - .and_then(|n|n.checked_add(std::mem::size_of::()+256)).ok_or(Error::Overflow) - } - pub(crate) fn new(config:SpecConfig)->Result { - let cap=(config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?; - let suffix=SuffixDrafter::new(config.suffix_min_match.max(1),64,cap)?; - let policy=DraftPolicy::new(config.max_t,0.03)?; - let adaptive=config.adaptive.map(AdaptivePolicy::new); - Ok(Self{config,policy,suffix,request:None,rounds:0,failed:false,owner:Rc::new(()),final_draft:false,adaptive,plan:None,stats:SpecStats::default(),chain_clamped:false,windows_checked:0}) - } - /// See `final_draft`; set before `begin_request`. - pub(crate) fn set_final_draft(&mut self,on:bool) {self.final_draft=on;} - /// Policy and adaptive round cadence survive requests, exactly like serve. - /// Prompt suffix/history is reset for each request, including resumed ones. - /// Root reads the prompt only through n-2; row n-1 is first verify input. - pub(crate) fn begin_request(&mut self,prompt:&[i32],max_new:usize,min_p:f32,eos_ids:&[i32])->Result<()> { - if self.failed {return Err(Error::IdentityMismatch);} - if self.request.as_ref().is_some_and(|r|!r.finished||r.pending_draft) {return Err(Error::IdentityMismatch);} - if prompt.is_empty()||prompt.len()>self.config.max_context as usize||!min_p.is_finite() {return Err(Error::InvalidDimension);} - let valid=|v:i32|v>=0&&(v as u32)0 {self.suffix.append(prompt)?;} - self.plan=None; - if let Some(pol)=self.adaptive.as_mut() { - pol.begin_request(min_p); - self.plan=Some(pol.draft_plan()); - } - self.request=Some(Request{consumed,input:prompt[prompt.len()-1],position:prompt.len() as i64-1, - first_window:true,produced:0,max_new,min_p,eos,drafts:DraftBatch::empty(),pending_draft:false,finished:max_new==0,vetted:PrefixMemo::new()}); - Ok(()) - } - pub(crate) fn host_bytes(&self)->Result { - let mut bytes=self.suffix.metadata_bytes()?.checked_add(std::mem::size_of::()+64).ok_or(Error::Overflow)?; - if let Some(r)=&self.request { - bytes=bytes.checked_add(r.consumed.capacity().checked_mul(4).ok_or(Error::Overflow)?).ok_or(Error::Overflow)?; - bytes=bytes.checked_add(r.eos.capacity().checked_mul(4).ok_or(Error::Overflow)?).ok_or(Error::Overflow)?; - }Ok(bytes) - } - pub(crate) fn consumed(&self)->Result<&[i32]> {Ok(&self.request.as_ref().ok_or(Error::IdentityMismatch)?.consumed)} - pub(crate) fn finished(&self)->bool {self.request.as_ref().is_none_or(|r|r.finished)} - pub(crate) fn policy(&self)->&DraftPolicy {&self.policy} - pub(crate) fn adaptive(&self)->Option<&AdaptivePolicy> {self.adaptive.as_ref()} - /// The round counters since the last call (per request in the serve loop), for every window policy. - pub(crate) fn take_stats(&mut self)->SpecStats {std::mem::take(&mut self.stats)} - pub(crate) fn is_failed(&self)->bool {self.failed} - - pub(super) fn abort(&mut self,engine:&mut E,target:&E::TargetCheckpoint,draft:&E::DraftCheckpoint,primary:SpecError)->SpecError { - // Always attempt BOTH. Actual adapters fence poison and retain unknown - // completion even if the callback primary remains the returned error. - let target_restore=engine.restore_target(target);let draft_restore=engine.restore_draft(draft); - self.failed|=target_restore.is_err()||draft_restore.is_err(); - if let Some(r)=self.request.as_mut() {r.finished=true;}primary - } - pub(crate) fn verify_commit(&mut self,engine:&mut E,mut cancel:impl FnMut()->bool)->SpecResult>> { - if self.failed {return Err(Error::IdentityMismatch.into());} - let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?; - if r.finished {return Ok(None);}if r.pending_draft {return Err(Error::IdentityMismatch.into());} - if cancel() {return Err(SpecError::Cancelled);} - engine.validate_current(&r.consumed,r.input,r.position)?; - let mut t=self.config.mtp_t; - if r.min_p>0.0 {t=1;while t=r.min_p {t+=1;}} - if r.first_window {t=1;} - let mut suffix_tokens=[0;MAX_T];let(mut lookup,mut matched)=(false,0); - let mut choice=None; - if let Some(pol)=self.adaptive.as_mut() { - // Adaptive window: every offered row (MTP chain up to its plan, suffix continuation of any agreement) is a - // candidate; the policy verifies the prefix with the best expected tokens per ms. - t=1; - if !r.first_window { - let (mut k,mut agrees)=(0,false); - if self.config.suffix_min_match>0 { - k=self.suffix.propose(&mut suffix_tokens[..self.config.max_t-1]);matched=self.suffix.last_match(); - agrees=k>0&&r.drafts.produced()>0&&suffix_tokens[0]==r.drafts.ids()[0]; - } - let n=r.drafts.produced().min(self.config.max_t-1); - let c=pol.choose(&Offer{mtp_probs:&r.drafts.probabilities()[..n],suffix_k:k,suffix_match:matched,suffix_agrees:agrees}); - t=c.t;lookup=c.origin==Origin::Suffix&&t>1;choice=Some(c); - } - } else if self.config.suffix_min_match>0&&!r.first_window { - let k=self.suffix.propose(&mut suffix_tokens[..self.config.max_t-1]);matched=self.suffix.last_match(); - if k>0&&suffix_tokens[0]==r.drafts.ids()[0] { - let pick=self.policy.choose(t,k,matched);if pick.lookup {t=pick.t;lookup=true;} - } - } - let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?; - let p=r.position; - // Rows p .. p+t-1 each need a cell: past `max_context` there is none. Upstream 41cf05a0 (`e85567b6`, generate.cpp - // `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, `max_new` - // and 8 cells of margin, which a full window of up to 8 rows can overrun). No room at all ends the request as length. - let room=self.config.max_context.checked_sub(p).ok_or(Error::Overflow)?; - if room<1 { - self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished=true;return Ok(None); - } - if (t as i64)>room { - // A shrunk window is not the policy's offer: its observation would teach the wrong width. - t=room as usize;choice=None;if t==1 {lookup=false;} - } - if r.consumed.len().checked_add(t).ok_or(Error::Overflow)?>r.consumed.capacity() {return Err(Error::InputAllocation.into());} - if self.config.suffix_min_match>0 {self.suffix.reserve_append(t)?;} - let mut inputs=[0;MAX_T];inputs[0]=r.input; - for i in 1..t {inputs[i]=if lookup {suffix_tokens[i-1]} else {r.drafts.ids()[i-1]};} - let next_round=self.rounds.checked_add(1).ok_or(Error::Overflow)?; - let target=engine.checkpoint_target()?;let draft=engine.checkpoint_draft()?; - // NaN guard (upstream STRATA_NAN_GUARD, f332a855 / 894f133b): a window whose logits or stage outputs are not finite is run again from - // this round's checkpoints instead of failing the request. Nothing of the window is committed or emitted before it passed, and the - // restore is the one `abort` does. Off: the first failure aborts, exactly as before. - let guard=self.config.nan_guard; - self.windows_checked=self.windows_checked.saturating_add(1); - let mut attempt=0u32; - let mut verified=loop { - let prepared=(||{engine.apply_pending()?;engine.verify(p,&inputs[..t],&r.consumed)})(); - let judged=match prepared { - Err(e)=>Err((e,None)), - Ok(v)=>{ - let admission=(|| { - engine.validate_verified(&v,p,&inputs[..t])?; - let out=engine.outputs(&v); - if out.len()!=t {return Err(Error::IdentityMismatch);} - if out.iter().any(|&x|x<0||x as u32>=self.config.vocabulary) {return Err(Error::InvalidToken);}Ok(()) - })(); - match admission { - Err(e)=>Err((e,Some(v))), - // the debug injection of upstream's STRATA_NAN_INJECT: the n-th checked window (first `times` attempts) reads as non-finite - Ok(())=>if guard.injects(self.windows_checked,attempt) {Err((Error::NonFinite,Some(v)))} else {Ok(v)}, - } - } - }; - match judged { - Ok(v)=>break v, - Err((e,leftover))=>{ - if let Some(v)=leftover {let _=engine.drain_verified(v);} - let what=format!("position {p}, {t} rows, attempt {} of {}: {e:?}",attempt+1,guard.retries); - if guard.retries>attempt&&matches!(e,Error::NonFinite)&&!cancel() { - // The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back, taking the - // window back lets the verifier stage the same rows again (a completed, uncommitted window refuses the next one). - let restored=(engine.restore_target(&target),engine.restore_draft(&draft)); - let taken_back=if restored.0.is_ok()&&restored.1.is_ok() {engine.discard_window()} else {Ok(())}; - if restored.0.is_ok()&&restored.1.is_ok()&&taken_back.is_ok() { - attempt+=1; - eprintln!("leleka-serve nan-guard: a non-finite window ({what}); the round restarts from its checkpoint"); - continue; - } - // the checkpoint could not be restored or the window not taken back: the state is unknown, nothing to retry on - self.failed=true; - if let Some(rq)=self.request.as_mut() {rq.finished=true;} - leleka_memory::telemetry::nan_guard_unhealed(&format!("{what}; the round could not be undone")); - eprintln!("leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone (restore target {:?}, restore draft {:?}, take back {:?})",restored.0,restored.1,taken_back); - return Err(e.into()); - } - if guard.retries>0&&matches!(e,Error::NonFinite) { - leleka_memory::telemetry::nan_guard_unhealed(&what); - eprintln!("leleka-serve nan-guard: a non-finite window ({what}) was not healed; the request fails"); - } - return Err(self.abort(engine,&target,&draft,e.into())); - } - } - }; - if attempt>0 { - self.stats.healed+=1; - leleka_memory::telemetry::nan_guard_healed(&format!("position {p}, {t} rows, after {attempt} restart(s)")); - eprintln!("leleka-serve nan-guard: healed the window at position {p} ({t} rows) after {attempt} restart(s)"); - } - if cancel() {let _=engine.drain_verified(verified);return Err(self.abort(engine,&target,&draft,SpecError::Cancelled));} - let mut outputs=[0;MAX_T];outputs[..t].copy_from_slice(engine.outputs(&verified)); - let mut accepted=0;while acceptedv,Err(e)=>{let _=engine.drain_verified(verified);return Err(self.abort(engine,&target,&draft,e.into()));} - }; - if let Err(e)=engine.commit_verified(&mut verified,accepted+1) { - let _=engine.join_adaptation(work);let _=engine.drain_verified(verified); - return Err(self.abort(engine,&target,&draft,e.into())); - } - // Actual prefix commit is now authoritative. Adaptation remains beside - // draft via a receipt owned by the engine; finish_round joins it. No - // borrowed stack worker or unobserved async boolean cert is retained. - let r=self.request.as_mut().ok_or(Error::IdentityMismatch)?; - let timed=!r.first_window; - r.consumed.extend_from_slice(&inputs[..accepted+1]);r.first_window=false; - let mut emitted=0;let mut eos=false; - while emitted<=accepted&&r.produced0 {self.suffix.append(&outputs[..emitted]).err()} else {None}; - r.input=outputs[accepted];r.position=next;r.pending_draft=true;r.finished=eos||r.produced>=r.max_new; - self.rounds=next_round; - // Store the actual pending adaptive owner with the committed receipt. - Ok(Some(CommittedRound{verified,outputs,emitted,t,accepted,position:p,from_lookup:lookup,matched,timed,eos,choice, - next_position:next,round_number:next_round,work:Some(work),owner:Rc::clone(&self.owner),bookkeeping_error})) - } -} +mod impl_originalspeccontroller_2; +mod impl_originalspeccontroller_2_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs new file mode 100644 index 00000000..de4d296b --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2.rs @@ -0,0 +1,165 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSpecController. + +#[allow(unused_imports)] +use super::*; + +impl OriginalSpecController { + /// Conservative preallocation ledger for Root before construction. Actual + /// allocator capacities are checked by host_bytes() before publication. + pub(crate) fn planned_host_bytes( + config: &SpecConfig, + prompt_len: usize, + max_new: usize, + eos_count: usize, + ) -> Result { + if prompt_len == 0 || prompt_len > config.max_context as usize { + return Err(Error::InvalidDimension); + } + let h = (config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?; + let table = h.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?; + let history = prompt_len + .checked_add(max_new) + .and_then(|n| n.checked_add(config.max_t)) + .ok_or(Error::Overflow)? + .min(config.max_context as usize + MAX_T); + table + .checked_mul(32) + .and_then(|n| n.checked_add(h.checked_mul(4)?)) + .and_then(|n| n.checked_add(history.checked_mul(4)?)) + .and_then(|n| n.checked_add(eos_count.checked_mul(4)?)) + .and_then(|n| n.checked_add(std::mem::size_of::() + 256)) + .ok_or(Error::Overflow) + } + pub(crate) fn new(config: SpecConfig) -> Result { + let cap = (config.max_context as usize).checked_add(4096).ok_or(Error::Overflow)?; + let suffix = SuffixDrafter::new(config.suffix_min_match.max(1), 64, cap)?; + let policy = DraftPolicy::new(config.max_t, 0.03)?; + let adaptive = config.adaptive.map(AdaptivePolicy::new); + Ok(Self { + config, + policy, + suffix, + request: None, + rounds: 0, + failed: false, + owner: Rc::new(()), + final_draft: false, + adaptive, + plan: None, + stats: SpecStats::default(), + chain_clamped: false, + windows_checked: 0, + }) + } + /// See `final_draft`; set before `begin_request`. + pub(crate) fn set_final_draft(&mut self, on: bool) { + self.final_draft = on; + } + /// Policy and adaptive round cadence survive requests, exactly like serve. + /// Prompt suffix/history is reset for each request, including resumed ones. + /// Root reads the prompt only through n-2; row n-1 is first verify input. + pub(crate) fn begin_request(&mut self, prompt: &[i32], max_new: usize, min_p: f32, eos_ids: &[i32]) -> Result<()> { + if self.failed { + return Err(Error::IdentityMismatch); + } + if self.request.as_ref().is_some_and(|r| !r.finished || r.pending_draft) { + return Err(Error::IdentityMismatch); + } + if prompt.is_empty() || prompt.len() > self.config.max_context as usize || !min_p.is_finite() { + return Err(Error::InvalidDimension); + } + let valid = |v: i32| v >= 0 && (v as u32) < self.config.vocabulary; + if prompt.iter().chain(eos_ids).any(|&v| !valid(v)) { + return Err(Error::InvalidToken); + } + // Precharge all append capacity BEFORE actual inference. Original + // reserves n+max_new+S; max-context+S also bounds accepted overshoot. + let cap = prompt + .len() + .checked_add(max_new) + .and_then(|n| n.checked_add(self.config.max_t)) + .ok_or(Error::Overflow)? + .min((self.config.max_context as usize).checked_add(MAX_T).ok_or(Error::Overflow)?); + let mut consumed = Vec::new(); + consumed.try_reserve_exact(cap).map_err(|_| Error::InputAllocation)?; + consumed.extend_from_slice(&prompt[..prompt.len() - 1]); + let mut eos = Vec::new(); + eos.try_reserve_exact(eos_ids.len()).map_err(|_| Error::InputAllocation)?; + eos.extend_from_slice(eos_ids); + // Reserve/admit before resetting the previous suffix state. + self.suffix.reserve_reset(prompt.len())?; + self.suffix.reset(); + if self.config.suffix_min_match > 0 { + self.suffix.append(prompt)?; + } + self.plan = None; + if let Some(pol) = self.adaptive.as_mut() { + pol.begin_request(min_p); + self.plan = Some(pol.draft_plan()); + } + self.request = Some(Request { + consumed, + input: prompt[prompt.len() - 1], + position: prompt.len() as i64 - 1, + first_window: true, + produced: 0, + max_new, + min_p, + eos, + drafts: DraftBatch::empty(), + pending_draft: false, + finished: max_new == 0, + vetted: PrefixMemo::new(), + }); + Ok(()) + } + pub(crate) fn host_bytes(&self) -> Result { + let mut bytes = + self.suffix.metadata_bytes()?.checked_add(std::mem::size_of::() + 64).ok_or(Error::Overflow)?; + if let Some(r) = &self.request { + bytes = bytes + .checked_add(r.consumed.capacity().checked_mul(4).ok_or(Error::Overflow)?) + .ok_or(Error::Overflow)?; + bytes = + bytes.checked_add(r.eos.capacity().checked_mul(4).ok_or(Error::Overflow)?).ok_or(Error::Overflow)?; + } + Ok(bytes) + } + pub(crate) fn consumed(&self) -> Result<&[i32]> { + Ok(&self.request.as_ref().ok_or(Error::IdentityMismatch)?.consumed) + } + pub(crate) fn finished(&self) -> bool { + self.request.as_ref().is_none_or(|r| r.finished) + } + pub(crate) fn policy(&self) -> &DraftPolicy { + &self.policy + } + pub(crate) fn adaptive(&self) -> Option<&AdaptivePolicy> { + self.adaptive.as_ref() + } + /// The round counters since the last call (per request in the serve loop), for every window policy. + pub(crate) fn take_stats(&mut self) -> SpecStats { + std::mem::take(&mut self.stats) + } + pub(crate) fn is_failed(&self) -> bool { + self.failed + } + + pub(in super::super) fn abort( + &mut self, + engine: &mut E, + target: &E::TargetCheckpoint, + draft: &E::DraftCheckpoint, + primary: SpecError, + ) -> SpecError { + // Always attempt BOTH. Actual adapters fence poison and retain unknown + // completion even if the callback primary remains the returned error. + let target_restore = engine.restore_target(target); + let draft_restore = engine.restore_draft(draft); + self.failed |= target_restore.is_err() || draft_restore.is_err(); + if let Some(r) = self.request.as_mut() { + r.finished = true; + } + primary + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2_2.rs new file mode 100644 index 00000000..327e6c61 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller/impl_originalspeccontroller_2_2.rs @@ -0,0 +1,260 @@ +//! Moved out of the parent module by STRA-338: impl OriginalSpecController (2). + +#[allow(unused_imports)] +use super::*; + +impl OriginalSpecController { + pub(crate) fn verify_commit( + &mut self, + engine: &mut E, + mut cancel: impl FnMut() -> bool, + ) -> SpecResult>> { + if self.failed { + return Err(Error::IdentityMismatch.into()); + } + let r = self.request.as_ref().ok_or(Error::IdentityMismatch)?; + if r.finished { + return Ok(None); + } + if r.pending_draft { + return Err(Error::IdentityMismatch.into()); + } + if cancel() { + return Err(SpecError::Cancelled); + } + engine.validate_current(&r.consumed, r.input, r.position)?; + let mut t = self.config.mtp_t; + if r.min_p > 0.0 { + t = 1; + while t < self.config.mtp_t && r.drafts.probabilities()[t - 1] >= r.min_p { + t += 1; + } + } + if r.first_window { + t = 1; + } + let mut suffix_tokens = [0; MAX_T]; + let (mut lookup, mut matched) = (false, 0); + let mut choice = None; + if let Some(pol) = self.adaptive.as_mut() { + // Adaptive window: every offered row (MTP chain up to its plan, suffix continuation of any agreement) is a + // candidate; the policy verifies the prefix with the best expected tokens per ms. + t = 1; + if !r.first_window { + let (mut k, mut agrees) = (0, false); + if self.config.suffix_min_match > 0 { + k = self.suffix.propose(&mut suffix_tokens[..self.config.max_t - 1]); + matched = self.suffix.last_match(); + agrees = k > 0 && r.drafts.produced() > 0 && suffix_tokens[0] == r.drafts.ids()[0]; + } + let n = r.drafts.produced().min(self.config.max_t - 1); + let c = pol.choose(&Offer { + mtp_probs: &r.drafts.probabilities()[..n], + suffix_k: k, + suffix_match: matched, + suffix_agrees: agrees, + }); + t = c.t; + lookup = c.origin == Origin::Suffix && t > 1; + choice = Some(c); + } + } else if self.config.suffix_min_match > 0 && !r.first_window { + let k = self.suffix.propose(&mut suffix_tokens[..self.config.max_t - 1]); + matched = self.suffix.last_match(); + if k > 0 && suffix_tokens[0] == r.drafts.ids()[0] { + let pick = self.policy.choose(t, k, matched); + if pick.lookup { + t = pick.t; + lookup = true; + } + } + } + let r = self.request.as_ref().ok_or(Error::IdentityMismatch)?; + let p = r.position; + // Rows p .. p+t-1 each need a cell: past `max_context` there is none. Upstream 41cf05a0 (`e85567b6`, generate.cpp + // `room`): near the context's end the window takes only the rows that fit (the admission checked the prompt, `max_new` + // and 8 cells of margin, which a full window of up to 8 rows can overrun). No room at all ends the request as length. + let room = self.config.max_context.checked_sub(p).ok_or(Error::Overflow)?; + if room < 1 { + self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished = true; + return Ok(None); + } + if (t as i64) > room { + // A shrunk window is not the policy's offer: its observation would teach the wrong width. + t = room as usize; + choice = None; + if t == 1 { + lookup = false; + } + } + if r.consumed.len().checked_add(t).ok_or(Error::Overflow)? > r.consumed.capacity() { + return Err(Error::InputAllocation.into()); + } + if self.config.suffix_min_match > 0 { + self.suffix.reserve_append(t)?; + } + let mut inputs = [0; MAX_T]; + inputs[0] = r.input; + for i in 1..t { + inputs[i] = if lookup { suffix_tokens[i - 1] } else { r.drafts.ids()[i - 1] }; + } + let next_round = self.rounds.checked_add(1).ok_or(Error::Overflow)?; + let target = engine.checkpoint_target()?; + let draft = engine.checkpoint_draft()?; + // NaN guard (upstream STRATA_NAN_GUARD, f332a855 / 894f133b): a window whose logits or stage outputs are not finite is run again from + // this round's checkpoints instead of failing the request. Nothing of the window is committed or emitted before it passed, and the + // restore is the one `abort` does. Off: the first failure aborts, exactly as before. + let guard = self.config.nan_guard; + self.windows_checked = self.windows_checked.saturating_add(1); + let mut attempt = 0u32; + let mut verified = loop { + let prepared = (|| { + engine.apply_pending()?; + engine.verify(p, &inputs[..t], &r.consumed) + })(); + let judged = match prepared { + Err(e) => Err((e, None)), + Ok(v) => { + let admission = (|| { + engine.validate_verified(&v, p, &inputs[..t])?; + let out = engine.outputs(&v); + if out.len() != t { + return Err(Error::IdentityMismatch); + } + if out.iter().any(|&x| x < 0 || x as u32 >= self.config.vocabulary) { + return Err(Error::InvalidToken); + } + Ok(()) + })(); + match admission { + Err(e) => Err((e, Some(v))), + // the debug injection of upstream's STRATA_NAN_INJECT: the n-th checked window (first `times` attempts) reads as non-finite + Ok(()) => { + if guard.injects(self.windows_checked, attempt) { + Err((Error::NonFinite, Some(v))) + } else { + Ok(v) + } + } + } + } + }; + match judged { + Ok(v) => break v, + Err((e, leftover)) => { + if let Some(v) = leftover { + let _ = engine.drain_verified(v); + } + let what = format!("position {p}, {t} rows, attempt {} of {}: {e:?}", attempt + 1, guard.retries); + if guard.retries > attempt && matches!(e, Error::NonFinite) && !cancel() { + // The window ran on the device and nothing was committed: restoring the checkpoints puts the lineage back, taking the + // window back lets the verifier stage the same rows again (a completed, uncommitted window refuses the next one). + let restored = (engine.restore_target(&target), engine.restore_draft(&draft)); + let taken_back = + if restored.0.is_ok() && restored.1.is_ok() { engine.discard_window() } else { Ok(()) }; + if restored.0.is_ok() && restored.1.is_ok() && taken_back.is_ok() { + attempt += 1; + eprintln!( + "leleka-serve nan-guard: a non-finite window ({what}); the round restarts from its checkpoint" + ); + continue; + } + // the checkpoint could not be restored or the window not taken back: the state is unknown, nothing to retry on + self.failed = true; + if let Some(rq) = self.request.as_mut() { + rq.finished = true; + } + leleka_memory::telemetry::nan_guard_unhealed(&format!("{what}; the round could not be undone")); + eprintln!( + "leleka-serve nan-guard: a non-finite window ({what}) and the round could not be undone (restore target {:?}, restore draft {:?}, take back {:?})", + restored.0, restored.1, taken_back + ); + return Err(e.into()); + } + if guard.retries > 0 && matches!(e, Error::NonFinite) { + leleka_memory::telemetry::nan_guard_unhealed(&what); + eprintln!( + "leleka-serve nan-guard: a non-finite window ({what}) was not healed; the request fails" + ); + } + return Err(self.abort(engine, &target, &draft, e.into())); + } + } + }; + if attempt > 0 { + self.stats.healed += 1; + leleka_memory::telemetry::nan_guard_healed(&format!("position {p}, {t} rows, after {attempt} restart(s)")); + eprintln!( + "leleka-serve nan-guard: healed the window at position {p} ({t} rows) after {attempt} restart(s)" + ); + } + if cancel() { + let _ = engine.drain_verified(verified); + return Err(self.abort(engine, &target, &draft, SpecError::Cancelled)); + } + let mut outputs = [0; MAX_T]; + outputs[..t].copy_from_slice(engine.outputs(&verified)); + let mut accepted = 0; + while accepted < t - 1 && inputs[accepted + 1] == outputs[accepted] { + accepted += 1; + } + let next = p.checked_add(accepted as i64 + 1).ok_or(Error::Overflow)?; + super::super::super::original_serve_profile::add("round.T", t as f64); + super::super::super::original_serve_profile::add("round.acc", accepted as f64); + if lookup { + super::super::super::original_serve_profile::add("round.lookupT", t as f64); + } + let work = match engine.begin_adaptation(next_round) { + Ok(v) => v, + Err(e) => { + let _ = engine.drain_verified(verified); + return Err(self.abort(engine, &target, &draft, e.into())); + } + }; + if let Err(e) = engine.commit_verified(&mut verified, accepted + 1) { + let _ = engine.join_adaptation(work); + let _ = engine.drain_verified(verified); + return Err(self.abort(engine, &target, &draft, e.into())); + } + // Actual prefix commit is now authoritative. Adaptation remains beside + // draft via a receipt owned by the engine; finish_round joins it. No + // borrowed stack worker or unobserved async boolean cert is retained. + let r = self.request.as_mut().ok_or(Error::IdentityMismatch)?; + let timed = !r.first_window; + r.consumed.extend_from_slice(&inputs[..accepted + 1]); + r.first_window = false; + let mut emitted = 0; + let mut eos = false; + while emitted <= accepted && r.produced < r.max_new && !eos { + eos = r.eos.contains(&outputs[emitted]); + emitted += 1; + r.produced += 1; + } + let bookkeeping_error = + if self.config.suffix_min_match > 0 { self.suffix.append(&outputs[..emitted]).err() } else { None }; + r.input = outputs[accepted]; + r.position = next; + r.pending_draft = true; + r.finished = eos || r.produced >= r.max_new; + self.rounds = next_round; + // Store the actual pending adaptive owner with the committed receipt. + Ok(Some(CommittedRound { + verified, + outputs, + emitted, + t, + accepted, + position: p, + from_lookup: lookup, + matched, + timed, + eos, + choice, + next_position: next, + round_number: next_round, + work: Some(work), + owner: Rc::clone(&self.owner), + bookkeeping_error, + })) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller_2.rs index d673741f..1711b0cd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/impl_originalspeccontroller_2.rs @@ -9,98 +9,184 @@ impl OriginalSpecController { /// committed/emitted prefix disappeared. Pending work always joins and the /// complete verified owner always drains, including error/cancel paths. /// round_ms is measured by Root across verify+commit+emit+draft+adaptive join. - pub(crate) fn finish_round(&mut self,engine:&mut E, - mut round:CommittedRound,round_ms:impl FnOnce()->f64, - mut cancel:impl FnMut()->bool)->SpecResult<()> { - let admission=(|| { - let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?; - if !Rc::ptr_eq(&self.owner,&round.owner)||!r.pending_draft||self.rounds!=round.round_number||r.position!=round.next_position||r.input!=round.outputs[round.accepted] { + pub(crate) fn finish_round( + &mut self, + engine: &mut E, + mut round: CommittedRound, + round_ms: impl FnOnce() -> f64, + mut cancel: impl FnMut() -> bool, + ) -> SpecResult<()> { + let admission = (|| { + let r = self.request.as_ref().ok_or(Error::IdentityMismatch)?; + if !Rc::ptr_eq(&self.owner, &round.owner) + || !r.pending_draft + || self.rounds != round.round_number + || r.position != round.next_position + || r.input != round.outputs[round.accepted] + { return Err(Error::IdentityMismatch); - }Ok(()) + } + Ok(()) })(); // Original serve checks the completed adaptive refill before drafted. // Earlier authority/bookkeeping refusals still preserve their primary. - let draft_stage_admitted=admission.is_ok()&&round.bookkeeping_error.is_none(); - let result:SpecResult>=match admission { - Err(e)=>Err(e.into()), - Ok(())=> { - let r=self.request.as_mut().ok_or(Error::IdentityMismatch)?; - if let Some(e)=round.bookkeeping_error {Err(e.into())} - else if r.finished&&!self.final_draft {Ok(None)} - else { + let draft_stage_admitted = admission.is_ok() && round.bookkeeping_error.is_none(); + let result: SpecResult> = match admission { + Err(e) => Err(e.into()), + Ok(()) => { + let r = self.request.as_mut().ok_or(Error::IdentityMismatch)?; + if let Some(e) = round.bookkeeping_error { + Err(e.into()) + } else if r.finished && !self.final_draft { + Ok(None) + } else { // the chain of this round: the request's (`mtp_t - 1` drafts down to `min_p`) or the adaptive plan - let (chain,floor)=match self.plan {Some(p)=>(p.max_drafts,p.min_p),None=>(self.config.mtp_t-1,r.min_p)}; + let (chain, floor) = match self.plan { + Some(p) => (p.max_drafts, p.min_p), + None => (self.config.mtp_t - 1, r.min_p), + }; // Draft j writes its K/V at the cell p+a+j, and cells end at `max_context`: near the context's end the // round drafts only the cells that exist (upstream `max_steps = min(.., max_cells - (p + a))`, mtp.cpp). // Draft 0 always fits: the window's rows did, and a < t. - let cell=round.position.saturating_add(round.accepted as i64); - let room=usize::try_from(self.config.max_context.saturating_sub(cell)).unwrap_or(0).max(1); - let clamped=chain>room; - let chain=chain.min(room); + let cell = round.position.saturating_add(round.accepted as i64); + let room = usize::try_from(self.config.max_context.saturating_sub(cell)).unwrap_or(0).max(1); + let clamped = chain > room; + let chain = chain.min(room); // A fixed chain never needed a plan; a clamped one does (and restores the full chain on the next round). - let planned=if self.plan.is_some()||clamped||self.chain_clamped {engine.set_draft_plan(chain,floor)} else {Ok(())}; - self.chain_clamped=clamped; - let preparation=DraftPreparation::new(self.config.max_t,chain,self.config.vocabulary); - match (planned,preparation) { - (Err(e),_)|(_,Err(e))=>Err(e.into()), - (Ok(()),Ok(preparation))=>preparation.after_verified(engine,&round.verified,round.position,round.accepted, - &round.outputs[..round.t],&r.consumed,&mut r.vetted,floor,self.config.coupled).map(Some).map_err(Into::into), + let planned = if self.plan.is_some() || clamped || self.chain_clamped { + engine.set_draft_plan(chain, floor) + } else { + Ok(()) + }; + self.chain_clamped = clamped; + let preparation = DraftPreparation::new(self.config.max_t, chain, self.config.vocabulary); + match (planned, preparation) { + (Err(e), _) | (_, Err(e)) => Err(e.into()), + (Ok(()), Ok(preparation)) => preparation + .after_verified( + engine, + &round.verified, + round.position, + round.accepted, + &round.outputs[..round.t], + &r.consumed, + &mut r.vetted, + floor, + self.config.coupled, + ) + .map(Some) + .map_err(Into::into), } } } }; - let join=match round.work.take() {Some(work)=>engine.join_adaptation(work),None=>Err(Error::IdentityMismatch)}; - let drain=engine.drain_verified(round.verified); - let result=match (result,join) { - (_,Err(e)) if draft_stage_admitted=>Err(e.into()), - (Err(e),_)=>Err(e), - (Ok(_),Err(e))=>Err(e.into()), - (Ok(next),Ok(()))=>match drain {Err(e)=>Err(e.into()),Ok(())=>Ok(next)}, + let join = match round.work.take() { + Some(work) => engine.join_adaptation(work), + None => Err(Error::IdentityMismatch), + }; + let drain = engine.drain_verified(round.verified); + let result = match (result, join) { + (_, Err(e)) if draft_stage_admitted => Err(e.into()), + (Err(e), _) => Err(e), + (Ok(_), Err(e)) => Err(e.into()), + (Ok(next), Ok(())) => match drain { + Err(e) => Err(e.into()), + Ok(()) => Ok(next), + }, }; match result { - Err(e)=> { + Err(e) => { // Commit remains real, but this failed request cannot continue // with stale draft logits or an unknown completed source. - self.failed=true;if let Some(r)=self.request.as_mut() {r.pending_draft=false;r.finished=true;}Err(e) + self.failed = true; + if let Some(r) = self.request.as_mut() { + r.pending_draft = false; + r.finished = true; + } + Err(e) } - Ok(next)=> { - let r=self.request.as_mut().ok_or(Error::IdentityMismatch)?; - let drafts_after=next.as_ref().map_or(0,|b|b.produced()); - if let Some(batch)=next {r.drafts=batch;} - r.pending_draft=false; - let ms=round_ms(); - if round.timed&&!round.eos { - match (self.adaptive.as_mut(),round.choice.as_ref()) { - (Some(pol),Some(c))=>{ - pol.observe(c,round.accepted,ms,drafts_after); - self.plan=Some(pol.draft_plan()); + Ok(next) => { + let r = self.request.as_mut().ok_or(Error::IdentityMismatch)?; + let drafts_after = next.as_ref().map_or(0, |b| b.produced()); + if let Some(batch) = next { + r.drafts = batch; + } + r.pending_draft = false; + let ms = round_ms(); + if round.timed && !round.eos { + match (self.adaptive.as_mut(), round.choice.as_ref()) { + (Some(pol), Some(c)) => { + pol.observe(c, round.accepted, ms, drafts_after); + self.plan = Some(pol.draft_plan()); if trace_enabled() { - let plan=self.plan.unwrap_or(DraftPlan{max_drafts:0,min_p:0.0}); - eprintln!("DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2} bar={:.3} slope={:.2}", - round.round_number,round.t,c.origin,round.accepted,ms,c.expected,c.rate,c.explored as u8,drafts_after,plan.max_drafts,plan.min_p,pol.bar(),pol.row_slope_ms()); + let plan = self.plan.unwrap_or(DraftPlan { max_drafts: 0, min_p: 0.0 }); + eprintln!( + "DBG spec-trace r={} t={} src={:?} acc={} ms={:.2} E={:.2} rate={:.4} explored={} drafts={} next_plan={}/{:.2} bar={:.3} slope={:.2}", + round.round_number, + round.t, + c.origin, + round.accepted, + ms, + c.expected, + c.rate, + c.explored as u8, + drafts_after, + plan.max_drafts, + plan.min_p, + pol.bar(), + pol.row_slope_ms() + ); } } - _=>{ + _ => { if self.adaptive.is_none() { - if let Err(e)=self.policy.observe(round.from_lookup,round.t,round.accepted,round.matched,ms) {r.finished=true;return Err(crate::qwen_forward::contract::Error::from(e).into());} + if let Err(e) = + self.policy.observe(round.from_lookup, round.t, round.accepted, round.matched, ms) + { + r.finished = true; + return Err(crate::qwen_forward::contract::Error::from(e).into()); + } } if trace_enabled() { - eprintln!("DBG spec-trace r={} t={} src={} acc={} ms={:.2} drafts={}",round.round_number,round.t,if round.from_lookup {"Lookup"} else {"Mtp"},round.accepted,ms,drafts_after); + eprintln!( + "DBG spec-trace r={} t={} src={} acc={} ms={:.2} drafts={}", + round.round_number, + round.t, + if round.from_lookup { "Lookup" } else { "Mtp" }, + round.accepted, + ms, + drafts_after + ); } } } - self.stats.record(round.t,round.accepted,round.from_lookup,round.choice.is_some_and(|c|c.explored),ms); + self.stats.record( + round.t, + round.accepted, + round.from_lookup, + round.choice.is_some_and(|c| c.explored), + ms, + ); + } + if cancel() { + r.finished = true; + return Err(SpecError::Cancelled); } - if cancel() {r.finished=true;return Err(SpecError::Cancelled);} Ok(()) } } } /// Original wait_commit occurs before any session checkpoint/reuse reads. - pub(crate) fn finish_request(&mut self,engine:&mut E)->Result<()> { - let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?; - if r.pending_draft {return Err(Error::IdentityMismatch);} - if let Err(e)=engine.wait_commit() {self.failed=true;return Err(e);} - self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished=true;Ok(()) + pub(crate) fn finish_request(&mut self, engine: &mut E) -> Result<()> { + let r = self.request.as_ref().ok_or(Error::IdentityMismatch)?; + if r.pending_draft { + return Err(Error::IdentityMismatch); + } + if let Err(e) = engine.wait_commit() { + self.failed = true; + return Err(e); + } + self.request.as_mut().ok_or(Error::IdentityMismatch)?.finished = true; + Ok(()) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs index 91b5131b..2f7eebac 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests.rs @@ -1,135 +1,265 @@ //! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged). +use super::super::original_spec_draft::{DraftPick, OriginalFirstDraftEngine}; use super::*; -use super::super::original_spec_draft::{DraftPick,OriginalFirstDraftEngine}; mod golden; -const VOCAB:u32=1000; +const VOCAB: u32 = 1000; /// The fake target model: greedy continuation depends only on the last token. -fn next(x:i32)->i32 {(x*5+1)%997} +fn next(x: i32) -> i32 { + (x * 5 + 1) % 997 +} #[derive(Debug)] -struct Verif {inputs:Vec,outputs:Vec,position:i64} +struct Verif { + inputs: Vec, + outputs: Vec, + position: i64, +} #[derive(Default)] struct Fake { - log:Vec,committed:Vec,fail:Option<(&'static str,Error)>, - bad_draft:Option,probs:Vec,drafted:usize, - bad_output:Option<(usize,i32)>,cancel_after_verify:bool, + log: Vec, + committed: Vec, + fail: Option<(&'static str, Error)>, + bad_draft: Option, + probs: Vec, + drafted: usize, + bad_output: Option<(usize, i32)>, + cancel_after_verify: bool, /// the highest cell a window row or a draft touched (+1), and the chain lengths the controller asked for - max_end:i64,plans:Vec<(usize,f32)>, + max_end: i64, + plans: Vec<(usize, f32)>, /// how many times the named failure repeats (0 = once) - fail_n:u32, + fail_n: u32, /// every restore of the target fails (the checkpoint cannot be reached) - fail_restore_target:bool, + fail_restore_target: bool, /// a window completed and nothing was committed for it yet: like the driver's `window_ready`, it refuses the next window until /// the commit or `discard_window` takes it back (the live stack answered `InvalidDimension`) - open:bool, + open: bool, } impl Fake { - fn new(prompt_prefix:&[i32])->Self {Self{committed:prompt_prefix.to_vec(),probs:vec![0.9;8],..Default::default()}} - fn trip(&mut self,op:&'static str)->Result<()> { + fn new(prompt_prefix: &[i32]) -> Self { + Self { committed: prompt_prefix.to_vec(), probs: vec![0.9; 8], ..Default::default() } + } + fn trip(&mut self, op: &'static str) -> Result<()> { self.log.push(op.to_string()); - if let Some((name,e))=self.fail {if name==op {if self.fail_n>1 {self.fail_n-=1;} else {self.fail=None;}return Err(e);}} + if let Some((name, e)) = self.fail { + if name == op { + if self.fail_n > 1 { + self.fail_n -= 1; + } else { + self.fail = None; + } + return Err(e); + } + } Ok(()) } - fn count(&self,op:&str)->usize {self.log.iter().filter(|l|l.as_str()==op).count()} - fn pick(&mut self,j:usize,token:i32)->DraftPick { - self.drafted+=1; - let t=if self.bad_draft==Some(j) {token+1} else {token}; - DraftPick{token:t,probability:self.probs[j]} + fn count(&self, op: &str) -> usize { + self.log.iter().filter(|l| l.as_str() == op).count() + } + fn pick(&mut self, j: usize, token: i32) -> DraftPick { + self.drafted += 1; + let t = if self.bad_draft == Some(j) { token + 1 } else { token }; + DraftPick { token: t, probability: self.probs[j] } } } impl OriginalDraftEngine for Fake { - fn replay_target_kv(&mut self,v:&Verif,p:i64,outputs:&[i32])->Result<()> { - self.trip("replay")?;assert_eq!(v.position,p);assert_eq!(v.outputs,outputs);Ok(()) + fn replay_target_kv(&mut self, v: &Verif, p: i64, outputs: &[i32]) -> Result<()> { + self.trip("replay")?; + assert_eq!(v.position, p); + assert_eq!(v.outputs, outputs); + Ok(()) } - fn set_draft_plan(&mut self,max_drafts:usize,min_p:f32)->Result<()> {self.plans.push((max_drafts,min_p));Ok(())} - fn full_target_seed(&mut self,v:&Verif,row:usize,cell:i64,token:i32,_coupled:bool)->Result { - self.trip("seed")?;assert_eq!(cell,v.position+row as i64);assert_eq!(token,v.outputs[row]); - self.max_end=self.max_end.max(cell+1); - Ok(self.pick(0,next(token))) + fn set_draft_plan(&mut self, max_drafts: usize, min_p: f32) -> Result<()> { + self.plans.push((max_drafts, min_p)); + Ok(()) } - fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,_coupled:bool)->Result { - self.trip("chain")?;assert!(cell>0);self.max_end=self.max_end.max(cell+1);Ok(self.pick(j,next(previous_token))) + fn full_target_seed(&mut self, v: &Verif, row: usize, cell: i64, token: i32, _coupled: bool) -> Result { + self.trip("seed")?; + assert_eq!(cell, v.position + row as i64); + assert_eq!(token, v.outputs[row]); + self.max_end = self.max_end.max(cell + 1); + Ok(self.pick(0, next(token))) + } + fn full_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, _coupled: bool) -> Result { + self.trip("chain")?; + assert!(cell > 0); + self.max_end = self.max_end.max(cell + 1); + Ok(self.pick(j, next(previous_token))) + } + fn stage_coupled_history(&mut self, _: &[i32], _: i32) -> Result<()> { + self.trip("stage_history") + } + fn drain_draft(&mut self) -> Result<()> { + self.trip("drain_draft") } - fn stage_coupled_history(&mut self,_:&[i32],_:i32)->Result<()> {self.trip("stage_history")} - fn drain_draft(&mut self)->Result<()> {self.trip("drain_draft")} } impl OriginalSpecEngine for Fake { - type Verified=Verif;type TargetCheckpoint=usize;type DraftCheckpoint=u8;type AdaptiveWork=u64; - fn validate_current(&self,consumed:&[i32],_input:i32,position:i64)->Result<()> { - if consumed!=self.committed.as_slice()||position!=self.committed.len() as i64 {return Err(Error::IdentityMismatch);}Ok(()) + type Verified = Verif; + type TargetCheckpoint = usize; + type DraftCheckpoint = u8; + type AdaptiveWork = u64; + fn validate_current(&self, consumed: &[i32], _input: i32, position: i64) -> Result<()> { + if consumed != self.committed.as_slice() || position != self.committed.len() as i64 { + return Err(Error::IdentityMismatch); + } + Ok(()) } - fn checkpoint_target(&self)->Result {Ok(self.committed.len())} - fn checkpoint_draft(&self)->Result {Ok(7)} - fn restore_target(&mut self,c:&usize)->Result<()> {self.trip("restore_target")?;if self.fail_restore_target {return Err(Error::CudaExecution);}self.committed.truncate(*c);Ok(())} - fn restore_draft(&mut self,c:&u8)->Result<()> {assert_eq!(*c,7);self.trip("restore_draft")} - fn apply_pending(&mut self)->Result<()> {self.trip("apply_pending")} - fn verify(&mut self,position:i64,inputs:&[i32],consumed:&[i32])->Result { - self.trip("verify")?;assert_eq!(consumed,self.committed.as_slice()); - if self.open {return Err(Error::InvalidDimension);}self.open=true; - self.max_end=self.max_end.max(position+inputs.len() as i64); - let mut outputs:Vec=inputs.iter().map(|&x|next(x)).collect(); - if let Some((i,v))=self.bad_output {if i Result { + Ok(self.committed.len()) } - fn validate_verified(&self,v:&Verif,position:i64,inputs:&[i32])->Result<()> { - self.log_len();if v.position!=position||v.inputs!=inputs {return Err(Error::IdentityMismatch);}Ok(()) + fn checkpoint_draft(&self) -> Result { + Ok(7) } - fn outputs<'a>(&self,v:&'a Verif)->&'a[i32] {&v.outputs} - fn commit_verified(&mut self,v:&mut Verif,rows:usize)->Result<()> { - self.trip("commit")?;self.committed.extend_from_slice(&v.inputs[..rows]);self.open=false;Ok(()) + fn restore_target(&mut self, c: &usize) -> Result<()> { + self.trip("restore_target")?; + if self.fail_restore_target { + return Err(Error::CudaExecution); + } + self.committed.truncate(*c); + Ok(()) + } + fn restore_draft(&mut self, c: &u8) -> Result<()> { + assert_eq!(*c, 7); + self.trip("restore_draft") + } + fn apply_pending(&mut self) -> Result<()> { + self.trip("apply_pending") + } + fn verify(&mut self, position: i64, inputs: &[i32], consumed: &[i32]) -> Result { + self.trip("verify")?; + assert_eq!(consumed, self.committed.as_slice()); + if self.open { + return Err(Error::InvalidDimension); + } + self.open = true; + self.max_end = self.max_end.max(position + inputs.len() as i64); + let mut outputs: Vec = inputs.iter().map(|&x| next(x)).collect(); + if let Some((i, v)) = self.bad_output { + if i < outputs.len() { + outputs[i] = v; + } + } + Ok(Verif { inputs: inputs.to_vec(), outputs, position }) + } + fn validate_verified(&self, v: &Verif, position: i64, inputs: &[i32]) -> Result<()> { + self.log_len(); + if v.position != position || v.inputs != inputs { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + fn outputs<'a>(&self, v: &'a Verif) -> &'a [i32] { + &v.outputs + } + fn commit_verified(&mut self, v: &mut Verif, rows: usize) -> Result<()> { + self.trip("commit")?; + self.committed.extend_from_slice(&v.inputs[..rows]); + self.open = false; + Ok(()) + } + fn drain_verified(&mut self, _v: Verif) -> Result<()> { + self.trip("drain_verified") + } + fn discard_window(&mut self) -> Result<()> { + self.trip("discard_window")?; + self.open = false; + Ok(()) + } + fn begin_adaptation(&mut self, round: u64) -> Result { + self.trip("begin_adaptation")?; + Ok(round) + } + fn join_adaptation(&mut self, work: u64) -> Result<()> { + self.trip("join_adaptation")?; + assert!(work > 0); + Ok(()) + } + fn wait_commit(&mut self) -> Result<()> { + self.trip("wait_commit") } - fn drain_verified(&mut self,_v:Verif)->Result<()> {self.trip("drain_verified")} - fn discard_window(&mut self)->Result<()> {self.trip("discard_window")?;self.open=false;Ok(())} - fn begin_adaptation(&mut self,round:u64)->Result {self.trip("begin_adaptation")?;Ok(round)} - fn join_adaptation(&mut self,work:u64)->Result<()> {self.trip("join_adaptation")?;assert!(work>0);Ok(())} - fn wait_commit(&mut self)->Result<()> {self.trip("wait_commit")} } -impl Fake {fn log_len(&self){}} +impl Fake { + fn log_len(&self) {} +} -fn config(max_t:usize,mtp:usize,suffix:usize)->SpecConfig {SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()} -fn prompt(n:usize)->Vec {let mut v=vec![11];for i in 1..n {v.push(next(v[i-1]));}v} +fn config(max_t: usize, mtp: usize, suffix: usize) -> SpecConfig { + SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap() +} +fn prompt(n: usize) -> Vec { + let mut v = vec![11]; + for i in 1..n { + v.push(next(v[i - 1])); + } + v +} /// Whole request: verify+commit, emit, finish_round until the controller stops. -fn drive(c:&mut OriginalSpecController,e:&mut Fake,cancel:&mut dyn FnMut()->bool)->std::result::Result,SpecError> { - let mut out=Vec::new(); - while let Some(round)=c.verify_commit(e,&mut *cancel)? { +fn drive( + c: &mut OriginalSpecController, + e: &mut Fake, + cancel: &mut dyn FnMut() -> bool, +) -> std::result::Result, SpecError> { + let mut out = Vec::new(); + while let Some(round) = c.verify_commit(e, &mut *cancel)? { out.extend_from_slice(round.tokens()); - c.finish_round(e,round,||1.0,&mut *cancel)?; + c.finish_round(e, round, || 1.0, &mut *cancel)?; } Ok(out) } -fn expected(prompt:&[i32],n:usize)->Vec { - let mut x=*prompt.last().unwrap();let mut v=Vec::new();for _ in 0..n {x=next(x);v.push(x);}v +fn expected(prompt: &[i32], n: usize) -> Vec { + let mut x = *prompt.last().unwrap(); + let mut v = Vec::new(); + for _ in 0..n { + x = next(x); + v.push(x); + } + v +} +fn begin(c: &mut OriginalSpecController, p: &[i32], max_new: usize, eos: &[i32]) { + c.begin_request(p, max_new, 0.0, eos).unwrap(); } -fn begin(c:&mut OriginalSpecController,p:&[i32],max_new:usize,eos:&[i32]) {c.begin_request(p,max_new,0.0,eos).unwrap();} /// Upstream 41cf05a0 `e85567b6`: the window and the MTP chain near the context's end must stay inside `max_context` cells /// (before: the whole request died with "ran out of context", or the draft wrote cells that do not exist). -fn run_to_the_end(max_context:i64,prompt_len:usize,max_new:usize,max_t:usize,mtp:usize,suffix:usize,min_p:f32,adaptive:bool)->(Fake,Vec,OriginalSpecController) { +fn run_to_the_end( + max_context: i64, + prompt_len: usize, + max_new: usize, + max_t: usize, + mtp: usize, + suffix: usize, + min_p: f32, + adaptive: bool, +) -> (Fake, Vec, OriginalSpecController) { use super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(prompt_len);let mut e=Fake::new(&p[..prompt_len-1]); - let mut cfg=SpecConfig::new(max_t,mtp,64,VOCAB,suffix,false).unwrap();cfg.max_context=max_context; - if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(max_t,max_t-1)));} - let mut c=OriginalSpecController::new(cfg).unwrap(); - c.begin_request(&p,max_new,min_p,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); + let p = prompt(prompt_len); + let mut e = Fake::new(&p[..prompt_len - 1]); + let mut cfg = SpecConfig::new(max_t, mtp, 64, VOCAB, suffix, false).unwrap(); + cfg.max_context = max_context; + if adaptive { + cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(max_t, max_t - 1))); + } + let mut c = OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p, max_new, min_p, &[]).unwrap(); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - (e,out,c) + (e, out, c) } /// Upstream 41cf05a0 `f332a855` / `894f133b` (STRATA_NAN_GUARD, #879): a window whose output is not finite is not emitted; upstream ends the /// request and its gateway repeats it. Here the window itself is run again from its round's checkpoint. -fn guarded(guard:NanGuard,max_new:usize)->(Fake,OriginalSpecController,Vec) { - let p=prompt(6);let e=Fake::new(&p[..5]); - let c=OriginalSpecController::new(config(4,4,0).with_nan_guard(guard)).unwrap(); - let _=max_new; - (e,c,p) +fn guarded(guard: NanGuard, max_new: usize) -> (Fake, OriginalSpecController, Vec) { + let p = prompt(6); + let e = Fake::new(&p[..5]); + let c = OriginalSpecController::new(config(4, 4, 0).with_nan_guard(guard)).unwrap(); + let _ = max_new; + (e, c, p) } +#[path = "tests/adaptation_join_failure_is_reported.rs"] +mod adaptation_join_failure_is_reported; #[path = "tests/config_rejects_out_of_range.rs"] mod config_rejects_out_of_range; #[path = "tests/non_finite_window.rs"] mod non_finite_window; -#[path = "tests/adaptation_join_failure_is_reported.rs"] -mod adaptation_join_failure_is_reported; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs index f5195554..870db28d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/adaptation_join_failure_is_reported.rs @@ -3,80 +3,101 @@ #[allow(unused_imports)] use super::*; - #[test] fn adaptation_join_failure_is_reported_even_after_a_good_draft() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - e.fail=Some(("join_adaptation",Error::CudaExecution)); - assert_eq!(c.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); - assert_eq!(e.count("drain_verified"),1); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let round = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + e.fail = Some(("join_adaptation", Error::CudaExecution)); + assert_eq!( + c.finish_round(&mut e, round, || 1.0, &mut || false).err(), + Some(SpecError::Forward(Error::CudaExecution)) + ); + assert_eq!(e.count("drain_verified"), 1); assert!(c.is_failed()); } #[test] fn finish_round_refuses_a_receipt_from_another_controller() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut a=OriginalSpecController::new(config(4,4,0)).unwrap(); - let mut b=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut a,&p,8,&[]);begin(&mut b,&p,8,&[]); - let round=a.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!(b.finish_round(&mut e,round,||1.0,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut a = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + let mut b = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut a, &p, 8, &[]); + begin(&mut b, &p, 8, &[]); + let round = a.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + assert_eq!( + b.finish_round(&mut e, round, || 1.0, &mut || false).err(), + Some(SpecError::Forward(Error::IdentityMismatch)) + ); // the receipt was still drained and joined - assert_eq!((e.count("join_adaptation"),e.count("drain_verified")),(1,1)); + assert_eq!((e.count("join_adaptation"), e.count("drain_verified")), (1, 1)); } #[test] fn a_request_cannot_restart_while_a_draft_is_pending() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); - assert_eq!(c.finish_request(&mut e),Err(Error::IdentityMismatch)); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let round = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + assert_eq!(c.verify_commit(&mut e, &mut || false).err(), Some(SpecError::Forward(Error::IdentityMismatch))); + assert_eq!(c.finish_request(&mut e), Err(Error::IdentityMismatch)); + c.finish_round(&mut e, round, || 1.0, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); } #[test] fn policy_and_adaptive_cadence_survive_across_requests() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,6,&[]); - drive(&mut c,&mut e,&mut||false).unwrap(); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 6, &[]); + drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - let rounds_first=e.count("begin_adaptation"); - let mut e2=Fake::new(&p[..4]); - begin(&mut c,&p,6,&[]); - drive(&mut c,&mut e2,&mut||false).unwrap(); + let rounds_first = e.count("begin_adaptation"); + let mut e2 = Fake::new(&p[..4]); + begin(&mut c, &p, 6, &[]); + drive(&mut c, &mut e2, &mut || false).unwrap(); // the adaptive round numbers keep counting (Original `rounds`), the engine sees them - assert!(rounds_first>0&&e2.count("begin_adaptation")>0); + assert!(rounds_first > 0 && e2.count("begin_adaptation") > 0); // the first window of a new request is again T=1: one input row committed - assert_eq!(e2.committed.len(),4+1+4+4,"windows of 1, 4, 4 input rows for max_new=6"); + assert_eq!(e2.committed.len(), 4 + 1 + 4 + 4, "windows of 1, 4, 4 input rows for max_new=6"); } #[test] fn suffix_lookup_takes_a_longer_window_when_it_agrees_with_the_first_draft() { // the fake model's orbit is a cycle: the suffix index proposes the continuation the MTP also drafts - let mut x=11;let mut seq=vec![x]; - let mut seen=std::collections::HashMap::new(); - let cycle=loop {if let Some(&at)=seen.get(&x) {break seq[at..seq.len()-1].to_vec();}seen.insert(x,seq.len()-1);x=next(x);seq.push(x);}; - assert!(cycle.len()>=3); - let mut seq=Vec::new();while seq.len()<1200 {seq.extend_from_slice(&cycle);} - let prompt=seq; - let mut e=Fake::new(&prompt[..prompt.len()-1]); - let mut c=OriginalSpecController::new(config(8,2,3)).unwrap(); - begin(&mut c,&prompt,40,&[]); - let mut windows=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - windows.push((round.offered()+1,round.used_lookup())); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + let mut x = 11; + let mut seq = vec![x]; + let mut seen = std::collections::HashMap::new(); + let cycle = loop { + if let Some(&at) = seen.get(&x) { + break seq[at..seq.len() - 1].to_vec(); + } + seen.insert(x, seq.len() - 1); + x = next(x); + seq.push(x); + }; + assert!(cycle.len() >= 3); + let mut seq = Vec::new(); + while seq.len() < 1200 { + seq.extend_from_slice(&cycle); + } + let prompt = seq; + let mut e = Fake::new(&prompt[..prompt.len() - 1]); + let mut c = OriginalSpecController::new(config(8, 2, 3)).unwrap(); + begin(&mut c, &prompt, 40, &[]); + let mut windows = Vec::new(); + while let Some(round) = c.verify_commit(&mut e, &mut || false).unwrap() { + windows.push((round.offered() + 1, round.used_lookup())); + c.finish_round(&mut e, round, || 1.0, &mut || false).unwrap(); } // first window T=1; a lookup then widens the window beyond the MTP's T=2 - assert_eq!(windows[0],(1,false)); - assert!(windows.iter().skip(1).any(|&(t,lookup)|lookup&&t>2),"{windows:?}"); + assert_eq!(windows[0], (1, false)); + assert!(windows.iter().skip(1).any(|&(t, lookup)| lookup && t > 2), "{windows:?}"); } #[test] @@ -84,54 +105,89 @@ fn output_is_the_greedy_text_for_every_window_shape_noise_and_stop_rule() { // Output invariance: whatever the window sizes, the draft noise, the confidence floor, the suffix // lookup, EOS and max_new do, the emitted tokens are the greedy continuation (cut at the first EOS or // max_new) and the session ends up holding exactly the consumed tokens. - let p=prompt(40); - let full=expected(&p,64); - let noisy=[None,Some(0),Some(1),Some(2),Some(5)]; - let probs:[[f32;8];3]=[[0.9;8],[0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9],[0.02;8]]; - for max_t in 1..=8usize { for mtp in [0usize,1,2,max_t,9] { for suffix in [0usize,3] { - for bad in noisy { for pr in probs { for min_p in [0.0f32,0.5] { for max_new in [0usize,1,3,17] { - for eos_at in [None,Some(2usize),Some(9)] { - let eos:Vec=eos_at.map(|i|full[i]).into_iter().collect(); - let mut e=Fake::new(&p[..p.len()-1]);e.bad_draft=bad;e.probs=pr.to_vec(); - let mut c=OriginalSpecController::new(SpecConfig::new(max_t,mtp,4096,VOCAB,suffix,false).unwrap()).unwrap(); - c.begin_request(&p,max_new,min_p,&eos).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - c.finish_request(&mut e).unwrap(); - let mut want=full[..max_new].to_vec(); - if let Some(i)=eos_at {if i = eos_at.map(|i| full[i]).into_iter().collect(); + let mut e = Fake::new(&p[..p.len() - 1]); + e.bad_draft = bad; + e.probs = pr.to_vec(); + let mut c = OriginalSpecController::new( + SpecConfig::new(max_t, mtp, 4096, VOCAB, suffix, false).unwrap(), + ) + .unwrap(); + c.begin_request(&p, max_new, min_p, &eos).unwrap(); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + c.finish_request(&mut e).unwrap(); + let mut want = full[..max_new].to_vec(); + if let Some(i) = eos_at { + if i < max_new { + want.truncate(i + 1); + } + } + let ctx = format!( + "max_t {max_t} mtp {mtp} suffix {suffix} bad {bad:?} probs {:?} min_p {min_p} max_new {max_new} eos {eos_at:?}", + &pr[..3] + ); + assert_eq!(out, want, "{ctx}"); + assert_eq!(c.consumed().unwrap(), e.committed.as_slice(), "{ctx}"); + assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation"), "{ctx}"); + assert_eq!(e.count("drain_verified"), e.count("verify"), "{ctx}"); + assert_eq!(e.count("drain_draft"), e.count("seed"), "{ctx}"); + assert_eq!(e.count("restore_target") + e.count("restore_draft"), 0, "{ctx}"); + } + } + } + } + } } - }}}}}} + } } } #[test] fn draft_first_entry_is_a_separate_literal_path_and_drains() { - struct First{log:Vec<&'static str>,fail:bool} - impl OriginalFirstDraftEngine for First { - fn replay_first_seed_kv(&mut self,_:&u8,t:usize,cell:i64,token:i32)->Result<()> { - self.log.push("replay");assert_eq!((t,cell,token),(4,9,5));Ok(()) - } - fn full_first_seed(&mut self,_:&u8,_cell:i64,token:i32,_c:bool)->Result { - self.log.push("seed");if self.fail {return Err(Error::CudaExecution);}Ok(DraftPick{token:next(token),probability:0.9}) - } - fn first_chain_step(&mut self,_cell:i64,_j:usize,prev:i32,_c:bool)->Result { - self.log.push("chain");Ok(DraftPick{token:next(prev),probability:0.9}) - } - fn drain_first_seed(&mut self)->Result<()> {self.log.push("drain");Ok(())} + struct First { + log: Vec<&'static str>, + fail: bool, } - let prep=DraftPreparation::new(4,3,VOCAB).unwrap(); - let mut f=First{log:Vec::new(),fail:false}; - let b=prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).unwrap(); - assert_eq!(b.produced(),3); - assert_eq!(f.log,["replay","seed","chain","chain","drain"]); - let mut f=First{log:Vec::new(),fail:true}; - assert_eq!(prep.from_committed_seed(&mut f,&0u8,9,5,0.0,false).err(),Some(Error::CudaExecution)); - assert_eq!(f.log.last(),Some(&"drain")); + impl OriginalFirstDraftEngine for First { + fn replay_first_seed_kv(&mut self, _: &u8, t: usize, cell: i64, token: i32) -> Result<()> { + self.log.push("replay"); + assert_eq!((t, cell, token), (4, 9, 5)); + Ok(()) + } + fn full_first_seed(&mut self, _: &u8, _cell: i64, token: i32, _c: bool) -> Result { + self.log.push("seed"); + if self.fail { + return Err(Error::CudaExecution); + } + Ok(DraftPick { token: next(token), probability: 0.9 }) + } + fn first_chain_step(&mut self, _cell: i64, _j: usize, prev: i32, _c: bool) -> Result { + self.log.push("chain"); + Ok(DraftPick { token: next(prev), probability: 0.9 }) + } + fn drain_first_seed(&mut self) -> Result<()> { + self.log.push("drain"); + Ok(()) + } + } + let prep = DraftPreparation::new(4, 3, VOCAB).unwrap(); + let mut f = First { log: Vec::new(), fail: false }; + let b = prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).unwrap(); + assert_eq!(b.produced(), 3); + assert_eq!(f.log, ["replay", "seed", "chain", "chain", "drain"]); + let mut f = First { log: Vec::new(), fail: true }; + assert_eq!(prep.from_committed_seed(&mut f, &0u8, 9, 5, 0.0, false).err(), Some(Error::CudaExecution)); + assert_eq!(f.log.last(), Some(&"drain")); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs index d636f919..ac800c27 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/config_rejects_out_of_range.rs @@ -3,59 +3,62 @@ #[allow(unused_imports)] use super::*; - #[test] fn config_rejects_out_of_range_and_mtp_zero_means_max_t() { - assert!(SpecConfig::new(0,0,4096,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(9,0,4096,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,0,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,262145,VOCAB,0,false).is_err()); - assert!(SpecConfig::new(4,0,4096,0,0,false).is_err()); - assert_eq!(SpecConfig::new(4,0,4096,VOCAB,0,false).unwrap().mtp_t,4); - assert_eq!(SpecConfig::new(4,9,4096,VOCAB,0,false).unwrap().mtp_t,4); - assert_eq!(SpecConfig::new(4,2,4096,VOCAB,0,false).unwrap().mtp_t,2); + assert!(SpecConfig::new(0, 0, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(9, 0, 4096, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(4, 0, 0, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(4, 0, 262145, VOCAB, 0, false).is_err()); + assert!(SpecConfig::new(4, 0, 4096, 0, 0, false).is_err()); + assert_eq!(SpecConfig::new(4, 0, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new(4, 9, 4096, VOCAB, 0, false).unwrap().mtp_t, 4); + assert_eq!(SpecConfig::new(4, 2, 4096, VOCAB, 0, false).unwrap().mtp_t, 2); } #[test] fn host_budget_is_checked_and_grows_with_the_request() { - let c=config(4,4,0); - let a=OriginalSpecController::planned_host_bytes(&c,10,10,1).unwrap(); - let b=OriginalSpecController::planned_host_bytes(&c,100,10,1).unwrap(); - assert!(b>a); - assert!(OriginalSpecController::planned_host_bytes(&c,0,10,1).is_err()); - assert!(OriginalSpecController::planned_host_bytes(&c,5000,10,1).is_err()); - assert!(OriginalSpecController::planned_host_bytes(&c,10,usize::MAX,1).is_err()); + let c = config(4, 4, 0); + let a = OriginalSpecController::planned_host_bytes(&c, 10, 10, 1).unwrap(); + let b = OriginalSpecController::planned_host_bytes(&c, 100, 10, 1).unwrap(); + assert!(b > a); + assert!(OriginalSpecController::planned_host_bytes(&c, 0, 10, 1).is_err()); + assert!(OriginalSpecController::planned_host_bytes(&c, 5000, 10, 1).is_err()); + assert!(OriginalSpecController::planned_host_bytes(&c, 10, usize::MAX, 1).is_err()); } #[test] fn begin_request_validates_tokens_and_rejects_a_live_request() { - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - assert_eq!(c.begin_request(&[],4,0.0,&[]),Err(Error::InvalidDimension)); - assert_eq!(c.begin_request(&[1,2000],4,0.0,&[]),Err(Error::InvalidToken)); - assert_eq!(c.begin_request(&[1,2],4,f32::NAN,&[]),Err(Error::InvalidDimension)); - assert_eq!(c.begin_request(&[1,2],4,0.0,&[VOCAB as i32]),Err(Error::InvalidToken)); - begin(&mut c,&[1,2,3],4,&[]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + assert_eq!(c.begin_request(&[], 4, 0.0, &[]), Err(Error::InvalidDimension)); + assert_eq!(c.begin_request(&[1, 2000], 4, 0.0, &[]), Err(Error::InvalidToken)); + assert_eq!(c.begin_request(&[1, 2], 4, f32::NAN, &[]), Err(Error::InvalidDimension)); + assert_eq!(c.begin_request(&[1, 2], 4, 0.0, &[VOCAB as i32]), Err(Error::InvalidToken)); + begin(&mut c, &[1, 2, 3], 4, &[]); // the final prompt token is the first verify input, not yet consumed - assert_eq!(c.consumed().unwrap(),&[1,2]); - assert_eq!(c.begin_request(&[1],4,0.0,&[]),Err(Error::IdentityMismatch)); + assert_eq!(c.consumed().unwrap(), &[1, 2]); + assert_eq!(c.begin_request(&[1], 4, 0.0, &[]), Err(Error::IdentityMismatch)); } #[test] fn the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter() { use super::super::super::original_spec_adaptive::AdaptiveConfig; - for bad in [None,Some(0),Some(1),Some(3)] { - for probs in [vec![0.95;8],vec![0.3;8],vec![0.9,0.8,0.6,0.5,0.4,0.9,0.9,0.9]] { - for suffix in [0usize,3] { - let p=prompt(6);let mut e=Fake::new(&p[..5]); - e.bad_draft=bad;e.probs=probs.clone(); - let mut c=OriginalSpecController::new(config(6,6,suffix).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); - begin(&mut c,&p,70,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); + for bad in [None, Some(0), Some(1), Some(3)] { + for probs in [vec![0.95; 8], vec![0.3; 8], vec![0.9, 0.8, 0.6, 0.5, 0.4, 0.9, 0.9, 0.9]] { + for suffix in [0usize, 3] { + let p = prompt(6); + let mut e = Fake::new(&p[..5]); + e.bad_draft = bad; + e.probs = probs.clone(); + let mut c = + OriginalSpecController::new(config(6, 6, suffix).with_adaptive(Some(AdaptiveConfig::new(6, 5)))) + .unwrap(); + begin(&mut c, &p, 70, &[]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - assert_eq!(out,expected(&p,70),"bad {bad:?} probs {probs:?} suffix {suffix}"); - let stats=c.take_stats(); - assert!(stats.rounds>=2&&stats.tokens as usize>=stats.rounds as usize,"{}",stats.line()); - assert!(c.adaptive().is_some_and(|a|a.rounds()>=stats.rounds-1)); + assert_eq!(out, expected(&p, 70), "bad {bad:?} probs {probs:?} suffix {suffix}"); + let stats = c.take_stats(); + assert!(stats.rounds >= 2 && stats.tokens as usize >= stats.rounds as usize, "{}", stats.line()); + assert!(c.adaptive().is_some_and(|a| a.rounds() >= stats.rounds - 1)); } } } @@ -64,138 +67,148 @@ fn the_adaptive_window_emits_the_same_text_as_a_fixed_one_under_any_drafter() { #[test] fn the_adaptive_window_learns_to_verify_wide_when_the_drafter_is_perfect() { use super::super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(6);let mut e=Fake::new(&p[..5]); - let mut c=OriginalSpecController::new(config(6,6,0).with_adaptive(Some(AdaptiveConfig::new(6,5)))).unwrap(); - begin(&mut c,&p,200,&[]); - let mut widths=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - widths.push(round.offered()+1); + let p = prompt(6); + let mut e = Fake::new(&p[..5]); + let mut c = OriginalSpecController::new(config(6, 6, 0).with_adaptive(Some(AdaptiveConfig::new(6, 5)))).unwrap(); + begin(&mut c, &p, 200, &[]); + let mut widths = Vec::new(); + while let Some(round) = c.verify_commit(&mut e, &mut || false).unwrap() { + widths.push(round.offered() + 1); // a wider window costs a little more in this fake clock - let ms=30.0+1.0*(round.offered() as f64); - c.finish_round(&mut e,round,move||ms,&mut||false).unwrap(); + let ms = 30.0 + 1.0 * (round.offered() as f64); + c.finish_round(&mut e, round, move || ms, &mut || false).unwrap(); } c.finish_request(&mut e).unwrap(); - let tail=&widths[widths.len()-8..]; - assert!(tail.iter().all(|&t|t>=5),"{widths:?}"); + let tail = &widths[widths.len() - 8..]; + assert!(tail.iter().all(|&t| t >= 5), "{widths:?}"); } #[test] fn perfect_drafter_accepts_whole_windows_and_emits_greedy_text() { - let p=prompt(6);let mut e=Fake::new(&p[..5]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,12,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); + let p = prompt(6); + let mut e = Fake::new(&p[..5]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 12, &[]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - assert_eq!(out,expected(&p,12)); + assert_eq!(out, expected(&p, 12)); assert!(c.finished()); // first window is T=1 (nothing drafted yet); later windows verify 3 drafts + the input - assert_eq!(e.committed.len(),5+1+4+4+4,"windows commit input rows: 1 then 4 each"); - assert_eq!(e.count("verify"),1+(12-1+3)/4); - assert_eq!(e.count("wait_commit"),1); + assert_eq!(e.committed.len(), 5 + 1 + 4 + 4 + 4, "windows commit input rows: 1 then 4 each"); + assert_eq!(e.count("verify"), 1 + (12 - 1 + 3) / 4); + assert_eq!(e.count("wait_commit"), 1); // each committed round took a target AND a draft checkpoint restore-free path - assert_eq!(e.count("restore_target")+e.count("restore_draft"),0); - assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation")); - assert_eq!(e.count("drain_verified"),e.count("verify")); - assert_eq!(e.count("drain_draft"),e.count("seed")); + assert_eq!(e.count("restore_target") + e.count("restore_draft"), 0); + assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation")); + assert_eq!(e.count("drain_verified"), e.count("verify")); + assert_eq!(e.count("drain_draft"), e.count("seed")); } #[test] fn rejected_draft_commits_only_the_accepted_prefix() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.bad_draft=Some(1); // the second draft token is wrong - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,9,&[]); - let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert_eq!((r1.offered(),r1.accepted(),r1.committed_input_rows()),(0,0,1)); - c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); - let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.bad_draft = Some(1); // the second draft token is wrong + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 9, &[]); + let r1 = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + assert_eq!((r1.offered(), r1.accepted(), r1.committed_input_rows()), (0, 0, 1)); + c.finish_round(&mut e, r1, || 1.0, &mut || false).unwrap(); + let r2 = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); // inputs: x, d0 (right), d1 (wrong), d2 -> one draft accepted - assert_eq!((r2.offered(),r2.accepted(),r2.committed_input_rows()),(3,1,2)); - assert_eq!(r2.tokens().len(),2); + assert_eq!((r2.offered(), r2.accepted(), r2.committed_input_rows()), (3, 1, 2)); + assert_eq!(r2.tokens().len(), 2); assert!(!r2.used_lookup()); - c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); + c.finish_round(&mut e, r2, || 1.0, &mut || false).unwrap(); // after any prefix the session holds exactly the consumed tokens - assert_eq!(c.consumed().unwrap(),e.committed.as_slice()); + assert_eq!(c.consumed().unwrap(), e.committed.as_slice()); } #[test] fn min_p_shrinks_the_window_and_the_draft_chain() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.probs=vec![0.9,0.1,0.9,0.9,0.9,0.9,0.9,0.9]; - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - c.begin_request(&p,20,0.5,&[]).unwrap(); - let r1=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - c.finish_round(&mut e,r1,||1.0,&mut||false).unwrap(); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.probs = vec![0.9, 0.1, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9]; + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + c.begin_request(&p, 20, 0.5, &[]).unwrap(); + let r1 = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + c.finish_round(&mut e, r1, || 1.0, &mut || false).unwrap(); // the chain stopped after draft 1 (0.1 < min_p): seed + one chain step only - assert_eq!(e.drafted,2); - let r2=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); + assert_eq!(e.drafted, 2); + let r2 = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); // draft 0 passes min_p, draft 1 does not: T = 2 - assert_eq!(r2.offered(),1); - c.finish_round(&mut e,r2,||1.0,&mut||false).unwrap(); + assert_eq!(r2.offered(), 1); + c.finish_round(&mut e, r2, || 1.0, &mut || false).unwrap(); } #[test] fn eos_stops_emission_skips_drafting_and_keeps_the_commit() { - let p=prompt(5);let want=expected(&p,12); - let eos=want[5]; - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,30,&[eos]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,want[..6].to_vec()); + let p = prompt(5); + let want = expected(&p, 12); + let eos = want[5]; + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 30, &[eos]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + assert_eq!(out, want[..6].to_vec()); assert!(c.finished()); - let before=e.count("seed"); + let before = e.count("seed"); // last round hit EOS: no draft was prepared for it - assert!(e.count("verify")>=2&&before= 2 && before < e.count("verify")); + assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation")); + assert_eq!(e.count("drain_verified"), e.count("verify")); } #[test] fn max_new_ends_inside_a_window_without_overshooting_output() { - let p=prompt(4);let mut e=Fake::new(&p[..3]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,2,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out.len(),2); + let p = prompt(4); + let mut e = Fake::new(&p[..3]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 2, &[]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + assert_eq!(out.len(), 2); // zero new tokens means no work at all - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,0,&[]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 0, &[]); assert!(c.finished()); - assert!(c.verify_commit(&mut e,&mut||false).unwrap().is_none()); + assert!(c.verify_commit(&mut e, &mut || false).unwrap().is_none()); } #[test] fn a_window_near_the_context_end_takes_only_the_rows_that_fit() { - let p=prompt(4);let mut e=Fake::new(&p[..3]); - let mut cfg=SpecConfig::new(4,4,6,VOCAB,0,false).unwrap();cfg.max_context=6; - let mut c=OriginalSpecController::new(cfg).unwrap(); - begin(&mut c,&p,100,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); + let p = prompt(4); + let mut e = Fake::new(&p[..3]); + let mut cfg = SpecConfig::new(4, 4, 6, VOCAB, 0, false).unwrap(); + cfg.max_context = 6; + let mut c = OriginalSpecController::new(cfg).unwrap(); + begin(&mut c, &p, 100, &[]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); // position 3: T=1; position 4: T=4 does not fit (4 + 4 > 6), so the window shrinks to the 2 rows left, not to "length" assert!(c.finished()); - assert_eq!(e.committed.len(),6,"every cell of the context is used"); - assert_eq!(out,expected(&p,3),"the tokens of rows 3, 4 and 5 are all emitted"); - assert!(e.max_end<=6,"no row or draft past the context: {}",e.max_end); + assert_eq!(e.committed.len(), 6, "every cell of the context is used"); + assert_eq!(out, expected(&p, 3), "the tokens of rows 3, 4 and 5 are all emitted"); + assert!(e.max_end <= 6, "no row or draft past the context: {}", e.max_end); } #[test] fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() { // every distance k of the first window from the end, every window shape: fixed, min_p, suffix lookup, adaptive - for max_t in [2usize,4,6,8] { - for k in 1..=(max_t as i64+3) { - for (suffix,min_p,adaptive) in [(0usize,0.0f32,false),(3,0.0,false),(0,0.5,false),(3,0.5,true),(0,0.0,true)] { - let prompt_len=10usize; - let max_context=prompt_len as i64-1+k; - let (e,out,c)=run_to_the_end(max_context,prompt_len,1000,max_t,max_t,suffix,min_p,adaptive); - let tag=format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); - assert!(e.max_end<=max_context,"{tag}: touched cell {} of {max_context}",e.max_end); + for max_t in [2usize, 4, 6, 8] { + for k in 1..=(max_t as i64 + 3) { + for (suffix, min_p, adaptive) in + [(0usize, 0.0f32, false), (3, 0.0, false), (0, 0.5, false), (3, 0.5, true), (0, 0.0, true)] + { + let prompt_len = 10usize; + let max_context = prompt_len as i64 - 1 + k; + let (e, out, c) = run_to_the_end(max_context, prompt_len, 1000, max_t, max_t, suffix, min_p, adaptive); + let tag = format!("max_t {max_t} k {k} suffix {suffix} min_p {min_p} adaptive {adaptive}"); + assert!(e.max_end <= max_context, "{tag}: touched cell {} of {max_context}", e.max_end); // the request ended because the context is full, with the greedy text of every row that fits - assert_eq!(e.committed.len() as i64,max_context,"{tag}"); - assert_eq!(out,expected(&prompt(prompt_len),k as usize),"{tag}"); - assert!(c.finished()&&!c.is_failed(),"{tag}"); - assert_eq!(e.count("begin_adaptation"),e.count("join_adaptation"),"{tag}"); - assert_eq!(e.count("drain_verified"),e.count("verify"),"{tag}"); + assert_eq!(e.committed.len() as i64, max_context, "{tag}"); + assert_eq!(out, expected(&prompt(prompt_len), k as usize), "{tag}"); + assert!(c.finished() && !c.is_failed(), "{tag}"); + assert_eq!(e.count("begin_adaptation"), e.count("join_adaptation"), "{tag}"); + assert_eq!(e.count("drain_verified"), e.count("verify"), "{tag}"); } } } @@ -204,79 +217,101 @@ fn spec_windows_and_drafts_never_pass_max_context_at_any_distance_from_the_end() #[test] fn the_chain_is_shortened_near_the_end_and_restored_after_it() { // fixed window, perfect drafter: 4-wide windows, 3 drafts. The last round before the end drafts only the cells left. - let (e,_,_)=run_to_the_end(30,10,1000,4,4,0,0.0,false); - assert!(e.max_end<=30); + let (e, _, _) = run_to_the_end(30, 10, 1000, 4, 4, 0, 0.0, false); + assert!(e.max_end <= 30); // plans: a clamped chain is asked for explicitly, never longer than the cells left - assert!(e.plans.iter().all(|&(n,_)|(1..=3).contains(&n)),"{:?}",e.plans); - assert!(e.plans.iter().any(|&(n,_)|n<3),"the last rounds draft fewer than the full chain: {:?}",e.plans); + assert!(e.plans.iter().all(|&(n, _)| (1..=3).contains(&n)), "{:?}", e.plans); + assert!(e.plans.iter().any(|&(n, _)| n < 3), "the last rounds draft fewer than the full chain: {:?}", e.plans); // a request that never gets near the end never sets a plan (the fixed chain needs none) - let (e,_,_)=run_to_the_end(4096,10,40,4,4,0,0.0,false); - assert!(e.plans.is_empty(),"{:?}",e.plans); + let (e, _, _) = run_to_the_end(4096, 10, 40, 4, 4, 0, 0.0, false); + assert!(e.plans.is_empty(), "{:?}", e.plans); } #[test] fn a_chain_clamped_by_one_request_is_restored_for_the_next() { - let p=prompt(10); - let mut e=Fake::new(&p[..9]); - let mut cfg=SpecConfig::new(4,4,64,VOCAB,0,false).unwrap();cfg.max_context=20; - let mut c=OriginalSpecController::new(cfg).unwrap(); - c.begin_request(&p,1000,0.0,&[]).unwrap(); - drive(&mut c,&mut e,&mut||false).unwrap();c.finish_request(&mut e).unwrap(); - assert!(e.plans.last().is_some_and(|&(n,_)|n<3),"the request ended on a clamped chain: {:?}",e.plans); + let p = prompt(10); + let mut e = Fake::new(&p[..9]); + let mut cfg = SpecConfig::new(4, 4, 64, VOCAB, 0, false).unwrap(); + cfg.max_context = 20; + let mut c = OriginalSpecController::new(cfg).unwrap(); + c.begin_request(&p, 1000, 0.0, &[]).unwrap(); + drive(&mut c, &mut e, &mut || false).unwrap(); + c.finish_request(&mut e).unwrap(); + assert!(e.plans.last().is_some_and(|&(n, _)| n < 3), "the request ended on a clamped chain: {:?}", e.plans); // a short request on the same controller: its first drafting round puts the full chain back - let mut e2=Fake::new(&p[..9]); - c.begin_request(&p,3,0.0,&[]).unwrap(); - drive(&mut c,&mut e2,&mut||false).unwrap(); - assert_eq!(e2.plans.first().map(|x|x.0),Some(3),"{:?}",e2.plans); + let mut e2 = Fake::new(&p[..9]); + c.begin_request(&p, 3, 0.0, &[]).unwrap(); + drive(&mut c, &mut e2, &mut || false).unwrap(); + assert_eq!(e2.plans.first().map(|x| x.0), Some(3), "{:?}", e2.plans); } /// Upstream 41cf05a0 `aece46db`: position 0 was the CLI's "speculation not started" value, so a 1-token prompt on a native pack /// (its only token is the first verify input, at position 0) never speculated. Here position 0 is a real start. #[test] fn a_one_token_prompt_speculates_from_position_zero() { - for (suffix,adaptive) in [(0usize,false),(3,false),(0,true)] { + for (suffix, adaptive) in [(0usize, false), (3, false), (0, true)] { use super::super::super::original_spec_adaptive::AdaptiveConfig; - let p=prompt(1); - let mut e=Fake::new(&[]); - let mut cfg=config(4,4,suffix); - if adaptive {cfg=cfg.with_adaptive(Some(AdaptiveConfig::new(4,3)));} - let mut c=OriginalSpecController::new(cfg).unwrap(); - begin(&mut c,&p,40,&[]); - assert_eq!(c.consumed().unwrap().len(),0); - let mut widths=Vec::new(); - while let Some(round)=c.verify_commit(&mut e,&mut||false).unwrap() { - widths.push(round.offered()+1); - c.finish_round(&mut e,round,||1.0,&mut||false).unwrap(); + let p = prompt(1); + let mut e = Fake::new(&[]); + let mut cfg = config(4, 4, suffix); + if adaptive { + cfg = cfg.with_adaptive(Some(AdaptiveConfig::new(4, 3))); + } + let mut c = OriginalSpecController::new(cfg).unwrap(); + begin(&mut c, &p, 40, &[]); + assert_eq!(c.consumed().unwrap().len(), 0); + let mut widths = Vec::new(); + while let Some(round) = c.verify_commit(&mut e, &mut || false).unwrap() { + widths.push(round.offered() + 1); + c.finish_round(&mut e, round, || 1.0, &mut || false).unwrap(); } c.finish_request(&mut e).unwrap(); - assert_eq!(widths[0],1,"the first window has nothing drafted yet"); - assert!(widths[1..].iter().any(|&t|t>1),"suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}"); - assert!(e.count("verify")<40,"suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}"); - assert_eq!(e.committed.len(),widths.iter().sum::(),"every round committed its accepted rows only: windows {widths:?}"); + assert_eq!(widths[0], 1, "the first window has nothing drafted yet"); + assert!( + widths[1..].iter().any(|&t| t > 1), + "suffix {suffix} adaptive {adaptive}: no window ever speculated: {widths:?}" + ); + assert!(e.count("verify") < 40, "suffix {suffix} adaptive {adaptive}: one window per token: {widths:?}"); + assert_eq!( + e.committed.len(), + widths.iter().sum::(), + "every round committed its accepted rows only: windows {widths:?}" + ); } - let p=prompt(1);let mut e=Fake::new(&[]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,40,&[]); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&p,40)); + let p = prompt(1); + let mut e = Fake::new(&[]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 40, &[]); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + assert_eq!(out, expected(&p, 40)); } #[test] fn the_guard_reads_its_three_switches_and_refuses_a_malformed_one() { - assert_eq!(NanGuard::parse(None,None,None),Ok(if NanGuard::DEFAULT_ON {NanGuard::with_retries(NanGuard::DEFAULT_RETRIES)} else {NanGuard::off()})); - assert_eq!(NanGuard::parse(Some("on"),None,None),Ok(NanGuard::with_retries(2))); - assert_eq!(NanGuard::parse(Some(" ON "),Some("5"),None),Ok(NanGuard::with_retries(5))); - assert_eq!(NanGuard::parse(Some("off"),Some("5"),None),Ok(NanGuard::off())); - assert_eq!(NanGuard::parse(Some("1"),Some("0"),None),Ok(NanGuard::with_retries(0))); - assert_eq!(NanGuard::parse(Some("on"),None,Some("3")),Ok(NanGuard::with_retries(2).with_injection(3,1))); - assert_eq!(NanGuard::parse(Some("on"),None,Some("4x2")),Ok(NanGuard::with_retries(2).with_injection(4,2))); - for bad in [(Some("maybe"),None,None),(Some("on"),Some("9"),None),(Some("on"),Some("x"),None),(Some("on"),None,Some("0")),(Some("on"),None,Some("2x0")),(Some("on"),None,Some("a"))] { - assert!(NanGuard::parse(bad.0,bad.1,bad.2).is_err(),"{bad:?}"); + assert_eq!( + NanGuard::parse(None, None, None), + Ok(if NanGuard::DEFAULT_ON { NanGuard::with_retries(NanGuard::DEFAULT_RETRIES) } else { NanGuard::off() }) + ); + assert_eq!(NanGuard::parse(Some("on"), None, None), Ok(NanGuard::with_retries(2))); + assert_eq!(NanGuard::parse(Some(" ON "), Some("5"), None), Ok(NanGuard::with_retries(5))); + assert_eq!(NanGuard::parse(Some("off"), Some("5"), None), Ok(NanGuard::off())); + assert_eq!(NanGuard::parse(Some("1"), Some("0"), None), Ok(NanGuard::with_retries(0))); + assert_eq!(NanGuard::parse(Some("on"), None, Some("3")), Ok(NanGuard::with_retries(2).with_injection(3, 1))); + assert_eq!(NanGuard::parse(Some("on"), None, Some("4x2")), Ok(NanGuard::with_retries(2).with_injection(4, 2))); + for bad in [ + (Some("maybe"), None, None), + (Some("on"), Some("9"), None), + (Some("on"), Some("x"), None), + (Some("on"), None, Some("0")), + (Some("on"), None, Some("2x0")), + (Some("on"), None, Some("a")), + ] { + assert!(NanGuard::parse(bad.0, bad.1, bad.2).is_err(), "{bad:?}"); } // an injection under a guard that is off does nothing: the guard has to be on to heal what it injects - let off=NanGuard::parse(Some("off"),None,Some("2")).unwrap(); - assert!(!off.injects(2,0)); - assert!(NanGuard::with_retries(2).with_injection(2,1).injects(2,0)); - assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(2,1),"only the first attempt"); - assert!(!NanGuard::with_retries(2).with_injection(2,1).injects(3,0)); + let off = NanGuard::parse(Some("off"), None, Some("2")).unwrap(); + assert!(!off.injects(2, 0)); + assert!(NanGuard::with_retries(2).with_injection(2, 1).injects(2, 0)); + assert!(!NanGuard::with_retries(2).with_injection(2, 1).injects(2, 1), "only the first attempt"); + assert!(!NanGuard::with_retries(2).with_injection(2, 1).injects(3, 0)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs index 86a05e7a..2a856449 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/golden.rs @@ -6,12 +6,14 @@ //! arguments of the port calls fails here before it reaches the 5090. //! Re-record after an intended change with `LELEKA_UPDATE_GOLDEN=1 cargo test -p leleka-engine-qwen35-cuda --lib golden` and review the diff. -use super::*; use super::super::super::original_spec_adaptive::AdaptiveConfig; +use super::*; use std::path::PathBuf; fn golden_path(name: &str) -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/qwen_forward/original_spec_controller/golden").join(format!("{name}.txt")) + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src/qwen_forward/original_spec_controller/golden") + .join(format!("{name}.txt")) } /// One operation per line, then the draft plans (window rows, min_p) and the emitted tokens. @@ -53,7 +55,17 @@ struct Scenario { impl Scenario { fn new(max_new: usize, max_t: usize, mtp: usize) -> Self { - Self { prompt_len: 8, max_new, max_t, mtp, min_p: 0.0, adaptive: false, eos: vec![], max_context: 4096, bad_draft: None } + Self { + prompt_len: 8, + max_new, + max_t, + mtp, + min_p: 0.0, + adaptive: false, + eos: vec![], + max_context: 4096, + bad_draft: None, + } } fn run(&self) -> String { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/non_finite_window.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/non_finite_window.rs index 46f8e64b..b18e2918 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/non_finite_window.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/tests/non_finite_window.rs @@ -3,281 +3,300 @@ #[allow(unused_imports)] use super::*; - #[test] fn a_non_finite_window_is_run_again_from_its_checkpoint_and_the_request_completes() { - let want=expected(&prompt(6),20); - for retries in [1u32,2,5] { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); + let want = expected(&prompt(6), 20); + for retries in [1u32, 2, 5] { + let (mut e, mut c, p) = guarded(NanGuard::with_retries(retries), 20); + e.fail = Some(("verify", Error::NonFinite)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - assert_eq!(out,want,"retries {retries}: the text is the greedy one, nothing lost or repeated"); - assert!(!c.is_failed()&&c.finished()); + assert_eq!(out, want, "retries {retries}: the text is the greedy one, nothing lost or repeated"); + assert!(!c.is_failed() && c.finished()); // one restore of each checkpoint, and the window was run twice: one more verify than a clean run - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(retries),20); - cc.begin_request(&p2,20,0.0,&[]).unwrap(); - drive(&mut cc,&mut clean,&mut||false).unwrap(); - assert_eq!(e.count("verify"),clean.count("verify")+1); - assert_eq!(c.take_stats().healed,1); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); + let (mut clean, mut cc, p2) = guarded(NanGuard::with_retries(retries), 20); + cc.begin_request(&p2, 20, 0.0, &[]).unwrap(); + drive(&mut cc, &mut clean, &mut || false).unwrap(); + assert_eq!(e.count("verify"), clean.count("verify") + 1); + assert_eq!(c.take_stats().healed, 1); // what the session committed is exactly what the clean run committed - assert_eq!(e.committed,clean.committed); + assert_eq!(e.committed, clean.committed); } } #[test] fn the_guard_costs_nothing_when_nothing_is_wrong() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2),30); - c.begin_request(&p,30,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&prompt(6),30)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(0,0)); - assert_eq!(c.take_stats().healed,0); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2), 30); + c.begin_request(&p, 30, 0.0, &[]).unwrap(); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + assert_eq!(out, expected(&prompt(6), 30)); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (0, 0)); + assert_eq!(c.take_stats().healed, 0); // and the same request with the guard off runs the identical sequence of engine calls - let mut off=Fake::new(&prompt(6)[..5]); - let mut co=OriginalSpecController::new(config(4,4,0)).unwrap(); - co.begin_request(&prompt(6),30,0.0,&[]).unwrap(); - drive(&mut co,&mut off,&mut||false).unwrap(); - assert_eq!(e.log,off.log); + let mut off = Fake::new(&prompt(6)[..5]); + let mut co = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + co.begin_request(&prompt(6), 30, 0.0, &[]).unwrap(); + drive(&mut co, &mut off, &mut || false).unwrap(); + assert_eq!(e.log, off.log); } #[test] fn a_window_that_stays_non_finite_fails_the_request_after_the_retries() { - for retries in [1u32,2] { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(retries),20); - e.fail=Some(("verify",Error::NonFinite));e.fail_n=retries+1; - c.begin_request(&p,20,0.0,&[]).unwrap(); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite)); - assert!(c.finished()&&!c.is_failed(),"the request ends, the controller stays usable (the checkpoints were restored)"); + for retries in [1u32, 2] { + let (mut e, mut c, p) = guarded(NanGuard::with_retries(retries), 20); + e.fail = Some(("verify", Error::NonFinite)); + e.fail_n = retries + 1; + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::NonFinite)); + assert!( + c.finished() && !c.is_failed(), + "the request ends, the controller stays usable (the checkpoints were restored)" + ); // retries restores for the retries, one more for the abort that gives up - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(retries as usize+1,retries as usize+1)); - assert_eq!(e.count("verify"),retries as usize+1); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (retries as usize + 1, retries as usize + 1)); + assert_eq!(e.count("verify"), retries as usize + 1); } } #[test] fn only_a_non_finite_failure_is_retried_and_a_guard_that_is_off_retries_nothing() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("verify",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::CudaExecution))); - assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"not retried"); - let (mut e,mut c,p)=guarded(NanGuard::off(),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); - assert_eq!((e.count("verify"),e.count("restore_target")),(1,1),"guard off: the first failure aborts as before"); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(3), 20); + e.fail = Some(("verify", Error::CudaExecution)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert_eq!(c.verify_commit(&mut e, &mut || false).err(), Some(SpecError::Forward(Error::CudaExecution))); + assert_eq!((e.count("verify"), e.count("restore_target")), (1, 1), "not retried"); + let (mut e, mut c, p) = guarded(NanGuard::off(), 20); + e.fail = Some(("verify", Error::NonFinite)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert_eq!(c.verify_commit(&mut e, &mut || false).err(), Some(SpecError::Forward(Error::NonFinite))); + assert_eq!((e.count("verify"), e.count("restore_target")), (1, 1), "guard off: the first failure aborts as before"); // a failed apply_pending of the adaptive tier is not a window either - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("apply_pending",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert!(c.verify_commit(&mut e,&mut||false).is_err()); - assert_eq!(e.count("verify"),0); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(3), 20); + e.fail = Some(("apply_pending", Error::CudaExecution)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert!(c.verify_commit(&mut e, &mut || false).is_err()); + assert_eq!(e.count("verify"), 0); } #[test] fn a_checkpoint_that_cannot_be_restored_ends_the_healing_with_the_original_error() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3),20); - e.fail=Some(("verify",Error::NonFinite)); - c.begin_request(&p,20,0.0,&[]).unwrap(); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(3), 20); + e.fail = Some(("verify", Error::NonFinite)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); // the restore the guard asks for fails: the state is unknown - e.fail_restore_target=true; - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); - assert!(c.is_failed()&&c.finished(),"the controller is unusable: its state is unknown"); - assert_eq!(e.count("verify"),1); + e.fail_restore_target = true; + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::NonFinite), "the primary error is kept"); + assert!(c.is_failed() && c.finished(), "the controller is unusable: its state is unknown"); + assert_eq!(e.count("verify"), 1); } #[test] fn the_injection_exercises_the_same_path_on_a_good_window_and_counts_windows_across_requests() { // the 3rd checked window fails once: healed, text unchanged - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(3,1),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let out=drive(&mut c,&mut e,&mut||false).unwrap(); - assert_eq!(out,expected(&prompt(6),20)); - assert_eq!(c.take_stats().healed,1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.count("discard_window"),1,"the injected window was taken back once"); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(3, 1), 20); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + let out = drive(&mut c, &mut e, &mut || false).unwrap(); + assert_eq!(out, expected(&prompt(6), 20)); + assert_eq!(c.take_stats().healed, 1); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); + assert_eq!(e.count("discard_window"), 1, "the injected window was taken back once"); // the window that was injected was a real, good one: it was drained before the retry - assert_eq!(e.count("drain_verified"),e.count("verify")); + assert_eq!(e.count("drain_verified"), e.count("verify")); // two failures in a row on one window, two retries: healed after two restarts - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,2),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e,&mut||false).unwrap(),expected(&prompt(6),20)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(2,2)); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(2, 2), 20); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert_eq!(drive(&mut c, &mut e, &mut || false).unwrap(), expected(&prompt(6), 20)); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (2, 2)); // three failures, two retries: the request fails and says why - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(2,3),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e,&mut||false).err(),Some(SpecError::Forward(Error::NonFinite))); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(2, 3), 20); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert_eq!(drive(&mut c, &mut e, &mut || false).err(), Some(SpecError::Forward(Error::NonFinite))); // windows are counted across the requests of one controller - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(4,1),6); - c.begin_request(&p,6,0.0,&[]).unwrap(); - drive(&mut c,&mut e,&mut||false).unwrap(); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(4, 1), 6); + c.begin_request(&p, 6, 0.0, &[]).unwrap(); + drive(&mut c, &mut e, &mut || false).unwrap(); c.finish_request(&mut e).unwrap(); - let first_request_windows=e.count("verify"); - assert!(first_request_windows<4,"{first_request_windows}"); - let mut e2=Fake::new(&p[..5]); - c.begin_request(&p,20,0.0,&[]).unwrap(); - assert_eq!(drive(&mut c,&mut e2,&mut||false).unwrap(),expected(&p,20)); - assert_eq!(e2.count("restore_target"),1,"the injected window was one of the second request's"); + let first_request_windows = e.count("verify"); + assert!(first_request_windows < 4, "{first_request_windows}"); + let mut e2 = Fake::new(&p[..5]); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + assert_eq!(drive(&mut c, &mut e2, &mut || false).unwrap(), expected(&p, 20)); + assert_eq!(e2.count("restore_target"), 1, "the injected window was one of the second request's"); } #[test] fn the_retry_takes_the_refused_window_back_before_it_stages_the_rows_again() { // the live stack's first failure: a completed window that nothing was committed for refuses the next one (InvalidDimension) - let (mut e,mut c,p)=guarded(NanGuard::with_retries(2).with_injection(1,1),20); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let _first=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - assert!(!e.open,"the retried window was committed"); - assert_eq!(c.take_stats().healed,1); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(2).with_injection(1, 1), 20); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + let _first = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + assert!(!e.open, "the retried window was committed"); + assert_eq!(c.take_stats().healed, 1); // drain, restore both checkpoints, take the window back, then the same rows again - let at=e.log.iter().position(|l|l=="drain_verified").unwrap(); - let order:Vec<&str>=e.log[at..at+6].iter().map(String::as_str).collect(); - assert_eq!(order,["drain_verified","restore_target","restore_draft","discard_window","apply_pending","verify"]); - assert_eq!(e.count("discard_window"),1); + let at = e.log.iter().position(|l| l == "drain_verified").unwrap(); + let order: Vec<&str> = e.log[at..at + 6].iter().map(String::as_str).collect(); + assert_eq!( + order, + ["drain_verified", "restore_target", "restore_draft", "discard_window", "apply_pending", "verify"] + ); + assert_eq!(e.count("discard_window"), 1); // a clean request never takes anything back - let (mut clean,mut cc,p2)=guarded(NanGuard::with_retries(2),20); - cc.begin_request(&p2,20,0.0,&[]).unwrap(); - drive(&mut cc,&mut clean,&mut||false).unwrap(); - assert_eq!(clean.count("discard_window"),0); + let (mut clean, mut cc, p2) = guarded(NanGuard::with_retries(2), 20); + cc.begin_request(&p2, 20, 0.0, &[]).unwrap(); + drive(&mut cc, &mut clean, &mut || false).unwrap(); + assert_eq!(clean.count("discard_window"), 0); } #[test] fn a_window_that_cannot_be_taken_back_ends_the_healing_with_the_original_error() { - let (mut e,mut c,p)=guarded(NanGuard::with_retries(3).with_injection(1,1),20); - e.fail=Some(("discard_window",Error::CudaExecution)); - c.begin_request(&p,20,0.0,&[]).unwrap(); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::NonFinite),"the primary error is kept"); - assert!(c.is_failed()&&c.finished(),"the controller is unusable: the verifier still holds the window"); - assert_eq!((e.count("verify"),e.count("discard_window")),(1,1),"no second attempt on a verifier that still holds the window"); + let (mut e, mut c, p) = guarded(NanGuard::with_retries(3).with_injection(1, 1), 20); + e.fail = Some(("discard_window", Error::CudaExecution)); + c.begin_request(&p, 20, 0.0, &[]).unwrap(); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::NonFinite), "the primary error is kept"); + assert!(c.is_failed() && c.finished(), "the controller is unusable: the verifier still holds the window"); + assert_eq!( + (e.count("verify"), e.count("discard_window")), + (1, 1), + "no second attempt on a verifier that still holds the window" + ); } #[test] fn verify_failure_restores_both_checkpoints_and_poisons_nothing_else() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("verify",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert!(c.finished()&&!c.is_failed()); - assert_eq!(e.committed.len(),4); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.fail = Some(("verify", Error::CudaExecution)); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::CudaExecution)); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); + assert!(c.finished() && !c.is_failed()); + assert_eq!(e.committed.len(), 4); } #[test] fn a_failed_window_preparation_also_restores_both_checkpoints() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - e.fail=Some(("apply_pending",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!(e.count("verify"),0); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.fail = Some(("apply_pending", Error::CudaExecution)); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::CudaExecution)); + assert_eq!(e.count("verify"), 0); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); assert!(!c.is_failed()); } #[test] fn restore_failure_makes_the_controller_unusable_but_keeps_the_primary_error() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let target=e.checkpoint_target().unwrap();let draft=e.checkpoint_draft().unwrap(); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let target = e.checkpoint_target().unwrap(); + let draft = e.checkpoint_draft().unwrap(); // the target restore fails: the draft restore must still be attempted - e.fail=Some(("restore_target",Error::CudaExecution)); - let primary=c.abort(&mut e,&target,&draft,SpecError::Forward(Error::InputRead)); - assert_eq!(primary,SpecError::Forward(Error::InputRead)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + e.fail = Some(("restore_target", Error::CudaExecution)); + let primary = c.abort(&mut e, &target, &draft, SpecError::Forward(Error::InputRead)); + assert_eq!(primary, SpecError::Forward(Error::InputRead)); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); assert!(c.is_failed()); - assert_eq!(c.verify_commit(&mut e,&mut||false).err(),Some(SpecError::Forward(Error::IdentityMismatch))); + assert_eq!(c.verify_commit(&mut e, &mut || false).err(), Some(SpecError::Forward(Error::IdentityMismatch))); // and a failing draft restore is equally fatal - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - e.fail=Some(("restore_draft",Error::CudaExecution)); - let _=c.abort(&mut e,&target,&draft,SpecError::Cancelled); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + e.fail = Some(("restore_draft", Error::CudaExecution)); + let _ = c.abort(&mut e, &target, &draft, SpecError::Cancelled); assert!(c.is_failed()); } #[test] fn commit_failure_joins_adaptation_drains_and_restores() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("commit",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); - assert_eq!((e.count("begin_adaptation"),e.count("join_adaptation")),(1,1)); - assert_eq!(e.count("drain_verified"),1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.committed.len(),4); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.fail = Some(("commit", Error::CudaExecution)); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::CudaExecution)); + assert_eq!((e.count("begin_adaptation"), e.count("join_adaptation")), (1, 1)); + assert_eq!(e.count("drain_verified"), 1); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); + assert_eq!(e.committed.len(), 4); } #[test] fn begin_adaptation_failure_drains_and_restores_without_committing() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - e.fail=Some(("begin_adaptation",Error::CudaExecution)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - assert!(c.verify_commit(&mut e,&mut||false).is_err()); - assert_eq!(e.count("commit"),0); - assert_eq!(e.count("join_adaptation"),0); - assert_eq!(e.count("drain_verified"),1); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.fail = Some(("begin_adaptation", Error::CudaExecution)); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + assert!(c.verify_commit(&mut e, &mut || false).is_err()); + assert_eq!(e.count("commit"), 0); + assert_eq!(e.count("join_adaptation"), 0); + assert_eq!(e.count("drain_verified"), 1); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); } #[test] fn invalid_verified_output_is_refused_before_anything_commits() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]);e.bad_output=Some((0,VOCAB as i32+5)); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let err=c.verify_commit(&mut e,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::InvalidToken)); - assert_eq!((e.count("commit"),e.count("drain_verified"),e.count("restore_target")),(0,1,1)); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + e.bad_output = Some((0, VOCAB as i32 + 5)); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let err = c.verify_commit(&mut e, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::InvalidToken)); + assert_eq!((e.count("commit"), e.count("drain_verified"), e.count("restore_target")), (0, 1, 1)); } #[test] fn cancellation_before_verify_touches_nothing_and_after_verify_rolls_back() { - let p=prompt(5); - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - assert_eq!(c.verify_commit(&mut e,&mut||true).err(),Some(SpecError::Cancelled)); - assert_eq!(e.count("verify"),0); - assert_eq!(e.count("restore_target"),0); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + assert_eq!(c.verify_commit(&mut e, &mut || true).err(), Some(SpecError::Cancelled)); + assert_eq!(e.count("verify"), 0); + assert_eq!(e.count("restore_target"), 0); // cancelled after the window ran: drained, both restored, no commit - let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let mut calls=0; - let r=c.verify_commit(&mut e,&mut||{calls+=1;calls==2}); - assert_eq!(r.err(),Some(SpecError::Cancelled)); - assert_eq!((e.count("verify"),e.count("commit"),e.count("drain_verified")),(1,0,1)); - assert_eq!((e.count("restore_target"),e.count("restore_draft")),(1,1)); - assert_eq!(e.committed.len(),4); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let mut calls = 0; + let r = c.verify_commit(&mut e, &mut || { + calls += 1; + calls == 2 + }); + assert_eq!(r.err(), Some(SpecError::Cancelled)); + assert_eq!((e.count("verify"), e.count("commit"), e.count("drain_verified")), (1, 0, 1)); + assert_eq!((e.count("restore_target"), e.count("restore_draft")), (1, 1)); + assert_eq!(e.committed.len(), 4); } #[test] fn draft_failure_after_commit_keeps_the_commit_joins_and_fails_the_request() { - let p=prompt(5);let mut e=Fake::new(&p[..4]); - let mut c=OriginalSpecController::new(config(4,4,0)).unwrap(); - begin(&mut c,&p,8,&[]); - let round=c.verify_commit(&mut e,&mut||false).unwrap().unwrap(); - let tokens=round.tokens().to_vec(); - e.fail=Some(("seed",Error::CudaExecution)); - let err=c.finish_round(&mut e,round,||1.0,&mut||false).err().unwrap(); - assert_eq!(err,SpecError::Forward(Error::CudaExecution)); + let p = prompt(5); + let mut e = Fake::new(&p[..4]); + let mut c = OriginalSpecController::new(config(4, 4, 0)).unwrap(); + begin(&mut c, &p, 8, &[]); + let round = c.verify_commit(&mut e, &mut || false).unwrap().unwrap(); + let tokens = round.tokens().to_vec(); + e.fail = Some(("seed", Error::CudaExecution)); + let err = c.finish_round(&mut e, round, || 1.0, &mut || false).err().unwrap(); + assert_eq!(err, SpecError::Forward(Error::CudaExecution)); // the emitted prefix is real; pending adaptation was joined and the receipt drained - assert_eq!(tokens.len(),1); - assert_eq!(e.committed.len(),5); - assert_eq!((e.count("join_adaptation"),e.count("drain_verified"),e.count("drain_draft")),(1,1,1)); - assert!(c.is_failed()&&c.finished()); + assert_eq!(tokens.len(), 1); + assert_eq!(e.committed.len(), 5); + assert_eq!((e.count("join_adaptation"), e.count("drain_verified"), e.count("drain_draft")), (1, 1, 1)); + assert!(c.is_failed() && c.finished()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs index 4b1cf499..5f414dfe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_controller/trace_enabled_fn.rs @@ -3,74 +3,152 @@ #[allow(unused_imports)] use super::*; - /// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's expectation). -pub(crate) fn trace_enabled()->bool { +pub(crate) fn trace_enabled() -> bool { crate::settings::process().decode.spec_trace } /// `LELEKA_SPEC_STATS`: one `DBG spec-stats` line per request (rounds, tokens per round, T and accepted histograms, ms per T). -pub(crate) fn stats_enabled()->bool { +pub(crate) fn stats_enabled() -> bool { crate::settings::process().decode.spec_stats } -impl From for SpecError {fn from(e:Error)->Self {Self::Forward(e)}} +impl From for SpecError { + fn from(e: Error) -> Self { + Self::Forward(e) + } +} impl NanGuard { /// Whether an unset switch means on. Off until the replay with the guard on showed no change of normal output. - pub(crate) const DEFAULT_ON:bool=false; - pub(crate) const DEFAULT_RETRIES:u32=2; - pub(crate) const fn off()->Self {Self{retries:0,inject_at:0,inject_times:0}} - pub(crate) const fn with_retries(retries:u32)->Self {Self{retries,inject_at:0,inject_times:0}} + pub(crate) const DEFAULT_ON: bool = false; + pub(crate) const DEFAULT_RETRIES: u32 = 2; + pub(crate) const fn off() -> Self { + Self { retries: 0, inject_at: 0, inject_times: 0 } + } + pub(crate) const fn with_retries(retries: u32) -> Self { + Self { retries, inject_at: 0, inject_times: 0 } + } /// The injection (tests and the live proof): the `at`-th checked window fails `times` times in a row. - pub(crate) const fn with_injection(mut self,at:u64,times:u32)->Self {self.inject_at=at;self.inject_times=times;self} + pub(crate) const fn with_injection(mut self, at: u64, times: u32) -> Self { + self.inject_at = at; + self.inject_times = times; + self + } /// From the three values; a malformed one is refused with its name (a guard that silently differs from what the operator wrote is worse than none). - pub(crate) fn parse(switch:Option<&str>,retries:Option<&str>,inject:Option<&str>)->std::result::Result { - let on=match switch.map(|v|v.trim().to_ascii_lowercase()).as_deref() { - None|Some("")=>Self::DEFAULT_ON, - Some("on"|"1"|"yes"|"true")=>true, - Some("off"|"0"|"no"|"false")=>false, - Some(other)=>return Err(format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD={other}: expected on or off")), + pub(crate) fn parse( + switch: Option<&str>, + retries: Option<&str>, + inject: Option<&str>, + ) -> std::result::Result { + let on = match switch.map(|v| v.trim().to_ascii_lowercase()).as_deref() { + None | Some("") => Self::DEFAULT_ON, + Some("on" | "1" | "yes" | "true") => true, + Some("off" | "0" | "no" | "false") => false, + Some(other) => return Err(format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD={other}: expected on or off")), }; - let retries=match retries.map(str::trim).filter(|v|!v.is_empty()) { - None=>Self::DEFAULT_RETRIES, - Some(v)=>v.parse::().ok().filter(|&n|n<=8).ok_or_else(||format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES={v}: expected 0..=8"))?, + let retries = match retries.map(str::trim).filter(|v| !v.is_empty()) { + None => Self::DEFAULT_RETRIES, + Some(v) => v + .parse::() + .ok() + .filter(|&n| n <= 8) + .ok_or_else(|| format!("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES={v}: expected 0..=8"))?, }; - let mut guard=if on {Self::with_retries(retries)} else {Self::off()}; - if let Some(v)=inject.map(str::trim).filter(|v|!v.is_empty()) { - let (at,times)=match v.split_once('x') {Some((a,k))=>(a,k),None=>(v,"1")}; - let bad=||format!("LELEKA_ORIGINAL_SERVE_NAN_INJECT={v}: expected n or nxK"); - let (at,times)=(at.parse::().ok().filter(|&n|n>0).ok_or_else(bad)?,times.parse::().ok().filter(|&n|n>0).ok_or_else(bad)?); - guard=guard.with_injection(at,times); + let mut guard = if on { Self::with_retries(retries) } else { Self::off() }; + if let Some(v) = inject.map(str::trim).filter(|v| !v.is_empty()) { + let (at, times) = match v.split_once('x') { + Some((a, k)) => (a, k), + None => (v, "1"), + }; + let bad = || format!("LELEKA_ORIGINAL_SERVE_NAN_INJECT={v}: expected n or nxK"); + let (at, times) = ( + at.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, + times.parse::().ok().filter(|&n| n > 0).ok_or_else(bad)?, + ); + guard = guard.with_injection(at, times); } Ok(guard) } /// Read once per stack from the captured environment; a malformed value is reported, the guard keeps its default. - pub(crate) fn from_environment(env:&impl crate::settings::EnvSource)->Self { - let get=|k:&str|env.get(k); - Self::parse(get("LELEKA_ORIGINAL_SERVE_NAN_GUARD").as_deref(),get("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES").as_deref(),get("LELEKA_ORIGINAL_SERVE_NAN_INJECT").as_deref()) - .unwrap_or_else(|why|{eprintln!("leleka-serve nan-guard: {why}; the guard keeps its default");if Self::DEFAULT_ON {Self::with_retries(Self::DEFAULT_RETRIES)} else {Self::off()}}) + pub(crate) fn from_environment(env: &impl crate::settings::EnvSource) -> Self { + let get = |k: &str| env.get(k); + Self::parse( + get("LELEKA_ORIGINAL_SERVE_NAN_GUARD").as_deref(), + get("LELEKA_ORIGINAL_SERVE_NAN_GUARD_RETRIES").as_deref(), + get("LELEKA_ORIGINAL_SERVE_NAN_INJECT").as_deref(), + ) + .unwrap_or_else(|why| { + eprintln!("leleka-serve nan-guard: {why}; the guard keeps its default"); + if Self::DEFAULT_ON { Self::with_retries(Self::DEFAULT_RETRIES) } else { Self::off() } + }) } /// The injected failure applies to window number `window` (1-based, per controller) on attempt `attempt` (0-based). - pub(super) fn injects(&self,window:u64,attempt:u32)->bool {self.retries>0&&self.inject_at==window&&attempt bool { + self.retries > 0 && self.inject_at == window && attempt < self.inject_times + } } impl SpecConfig { - pub(crate) fn new(max_t:usize,mtp_max_t:usize,max_context:i64,vocabulary:u32,suffix_min_match:usize,coupled:bool)->Result { - if !(1..=MAX_T).contains(&max_t)||max_context<1||max_context>crate::qwen_forward::contract::serving_cells() as i64||vocabulary==0||vocabulary>262144 {return Err(Error::InvalidDimension);} + pub(crate) fn new( + max_t: usize, + mtp_max_t: usize, + max_context: i64, + vocabulary: u32, + suffix_min_match: usize, + coupled: bool, + ) -> Result { + if !(1..=MAX_T).contains(&max_t) + || max_context < 1 + || max_context > crate::qwen_forward::contract::serving_cells() as i64 + || vocabulary == 0 + || vocabulary > 262144 + { + return Err(Error::InvalidDimension); + } // Original --mtp-max-t<=0 means S; public usize zero carries that case. - let mtp_t=if mtp_max_t==0 {max_t} else {mtp_max_t.min(max_t)}; - Ok(Self{max_t,mtp_t,max_context,vocabulary,suffix_min_match,coupled,adaptive:None,nan_guard:NanGuard::off()}) + let mtp_t = if mtp_max_t == 0 { max_t } else { mtp_max_t.min(max_t) }; + Ok(Self { + max_t, + mtp_t, + max_context, + vocabulary, + suffix_min_match, + coupled, + adaptive: None, + nan_guard: NanGuard::off(), + }) + } + pub(crate) fn with_nan_guard(mut self, guard: NanGuard) -> Self { + self.nan_guard = guard; + self } - pub(crate) fn with_nan_guard(mut self,guard:NanGuard)->Self {self.nan_guard=guard;self} /// Select the adaptive window policy (`max_t` is the widest verify window, `mtp_t - 1` the longest MTP chain). - pub(crate) fn with_adaptive(mut self,adaptive:Option)->Self { - self.adaptive=adaptive.map(|mut a|{a.max_t=a.max_t.min(self.max_t);a.max_drafts=a.max_drafts.min(self.mtp_t.saturating_sub(1)).min(a.max_t.saturating_sub(1));a}); + pub(crate) fn with_adaptive(mut self, adaptive: Option) -> Self { + self.adaptive = adaptive.map(|mut a| { + a.max_t = a.max_t.min(self.max_t); + a.max_drafts = a.max_drafts.min(self.mtp_t.saturating_sub(1)).min(a.max_t.saturating_sub(1)); + a + }); self } } -impl CommittedRound { - pub(crate) fn tokens(&self)->&[i32] {&self.outputs[..self.emitted]} - pub(crate) fn offered(&self)->usize {self.t-1} - pub(crate) fn accepted(&self)->usize {self.accepted} - pub(crate) fn committed_input_rows(&self)->usize {self.accepted+1} - pub(crate) fn used_lookup(&self)->bool {self.from_lookup} - pub(crate) fn stopped_on_eos(&self)->bool {self.eos} - pub(crate) fn position(&self)->i64 {self.position} +impl CommittedRound { + pub(crate) fn tokens(&self) -> &[i32] { + &self.outputs[..self.emitted] + } + pub(crate) fn offered(&self) -> usize { + self.t - 1 + } + pub(crate) fn accepted(&self) -> usize { + self.accepted + } + pub(crate) fn committed_input_rows(&self) -> usize { + self.accepted + 1 + } + pub(crate) fn used_lookup(&self) -> bool { + self.from_lookup + } + pub(crate) fn stopped_on_eos(&self) -> bool { + self.eos + } + pub(crate) fn position(&self) -> i64 { + self.position + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs index 30849cef..3d4c4fdb 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_draft.rs @@ -1,22 +1,46 @@ //! Original MtpDrafter::capture_round/draft scheduling. No target residual is invented here. -use super::contract::{Error,Result}; +use super::contract::{Error, Result}; use super::original_spec_policy::MAX_T; use super::token_memo::PrefixMemo; -#[derive(Clone,Copy,Debug)] -pub(crate) struct DraftPick {pub(crate) token:i32,pub(crate) probability:f32} -#[derive(Clone,Copy)] -pub(crate) struct DraftBatch {ids:[i32;MAX_T],probabilities:[f32;MAX_T],n:usize} +#[derive(Clone, Copy, Debug)] +pub(crate) struct DraftPick { + pub(crate) token: i32, + pub(crate) probability: f32, +} +#[derive(Clone, Copy)] +pub(crate) struct DraftBatch { + ids: [i32; MAX_T], + probabilities: [f32; MAX_T], + n: usize, +} impl DraftBatch { - pub(crate) fn empty()->Self {Self{ids:[0;MAX_T],probabilities:[0.0;MAX_T],n:0}} - pub(crate) fn ids(&self)->&[i32] {&self.ids} - pub(crate) fn probabilities(&self)->&[f32] {&self.probabilities} - pub(crate) fn produced(&self)->usize {self.n} - fn push(&mut self,p:DraftPick,vocabulary:u32)->Result<()> { - if p.token<0 || p.token as u32>=vocabulary {return Err(Error::InvalidToken);} - if !p.probability.is_finite() || !(0.0..=1.0).contains(&p.probability) {return Err(Error::NonFinite);} - if self.n==MAX_T {return Err(Error::InvalidDimension);} - self.ids[self.n]=p.token;self.probabilities[self.n]=p.probability;self.n+=1;Ok(()) + pub(crate) fn empty() -> Self { + Self { ids: [0; MAX_T], probabilities: [0.0; MAX_T], n: 0 } + } + pub(crate) fn ids(&self) -> &[i32] { + &self.ids + } + pub(crate) fn probabilities(&self) -> &[f32] { + &self.probabilities + } + pub(crate) fn produced(&self) -> usize { + self.n + } + fn push(&mut self, p: DraftPick, vocabulary: u32) -> Result<()> { + if p.token < 0 || p.token as u32 >= vocabulary { + return Err(Error::InvalidToken); + } + if !p.probability.is_finite() || !(0.0..=1.0).contains(&p.probability) { + return Err(Error::NonFinite); + } + if self.n == MAX_T { + return Err(Error::InvalidDimension); + } + self.ids[self.n] = p.token; + self.probabilities[self.n] = p.probability; + self.n += 1; + Ok(()) } } @@ -29,95 +53,185 @@ pub(crate) trait OriginalDraftEngine { /// Same-stream all-T K/V-only catch-up, paired with verified target outputs, /// INCLUDING rejected suffix rows. These cells are provisional overwrite, /// never published as the committed target/draft checkpoint prefix. - fn replay_target_kv(&mut self,verified:&Verified,p:i64,outputs:&[i32])->Result<()>; + fn replay_target_kv(&mut self, verified: &Verified, p: i64, outputs: &[i32]) -> Result<()>; /// Select the real residual row a and target output a at cell p+a, run full /// draft layer, overwrite that KV cell identically, retain resulting R/token. - fn full_target_seed(&mut self,verified:&Verified,row:usize,cell:i64,token:i32,coupled:bool)->Result; + fn full_target_seed( + &mut self, + verified: &Verified, + row: usize, + cell: i64, + token: i32, + coupled: bool, + ) -> Result; /// Consume the previous ACTUAL draft R/token held by this adapter. Cell is /// p+a+j; sampler counter is cell+1, not the current target window row. - fn full_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,coupled:bool)->Result; + fn full_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, coupled: bool) -> Result; /// Stage exact request sampling params/history; no-op for uncoupled mode. - fn stage_coupled_history(&mut self,consumed:&[i32],next:i32)->Result<()>; + fn stage_coupled_history(&mut self, consumed: &[i32], next: i32) -> Result<()>; /// All actual commands/events/ABI/registered resources must be drained even /// after callback failure. Transport uncertainty fences real owner/Context. - fn drain_draft(&mut self)->Result<()>; + fn drain_draft(&mut self) -> Result<()>; /// Adaptive speculative window: the chain length cap and the confidence floor of the NEXT draft stage (before /// `full_target_seed`). Engines with a fixed chain keep the default (nothing to apply). - fn set_draft_plan(&mut self,_max_drafts:usize,_min_p:f32)->Result<()> {Ok(())} + fn set_draft_plan(&mut self, _max_drafts: usize, _min_p: f32) -> Result<()> { + Ok(()) + } } -pub(crate) struct DraftPreparation {max_t:usize,max_drafts:usize,vocabulary:u32} +pub(crate) struct DraftPreparation { + max_t: usize, + max_drafts: usize, + vocabulary: u32, +} impl DraftPreparation { - pub(crate) fn new(max_t:usize,max_drafts:usize,vocabulary:u32)->Result { - if !(1..=MAX_T).contains(&max_t)||max_drafts>max_t-1||vocabulary==0||vocabulary>262144 {return Err(Error::InvalidDimension);} - Ok(Self{max_t,max_drafts,vocabulary}) + pub(crate) fn new(max_t: usize, max_drafts: usize, vocabulary: u32) -> Result { + if !(1..=MAX_T).contains(&max_t) || max_drafts > max_t - 1 || vocabulary == 0 || vocabulary > 262144 { + return Err(Error::InvalidDimension); + } + Ok(Self { max_t, max_drafts, vocabulary }) } /// Target receipts stay borrowed until catch-up, selection, chain and drain /// complete. Ordinary confidence truncation leaves the rest of IDs/probs 0. - pub(crate) fn after_verified>(&self,engine:&mut E,verified:&V, - p:i64,a:usize,outputs:&[i32],consumed:&[i32],vetted:&mut PrefixMemo,min_p:f32,coupled:bool)->Result { - if outputs.is_empty()||outputs.len()>self.max_t||a>=outputs.len()||p<0||p.checked_add(outputs.len() as i64).is_none_or(|end|end>(crate::qwen_forward::contract::serving_cells() as i64))||!min_p.is_finite() { + pub(crate) fn after_verified>( + &self, + engine: &mut E, + verified: &V, + p: i64, + a: usize, + outputs: &[i32], + consumed: &[i32], + vetted: &mut PrefixMemo, + min_p: f32, + coupled: bool, + ) -> Result { + if outputs.is_empty() + || outputs.len() > self.max_t + || a >= outputs.len() + || p < 0 + || p.checked_add(outputs.len() as i64) + .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || !min_p.is_finite() + { return Err(Error::InvalidDimension); } // `consumed` only grows within a request: `vetted` remembers the part already range-checked (`token_memo`) - if outputs.iter().any(|&v|v<0||v as u32>=self.vocabulary)||!vetted.in_range(consumed,self.vocabulary as i32) {return Err(Error::InvalidToken);} - let result=(|| { - if coupled {engine.stage_coupled_history(consumed,outputs[a])?;} - engine.replay_target_kv(verified,p,outputs)?; - let cell=p.checked_add(a as i64).ok_or(Error::Overflow)?; - let mut batch=DraftBatch::empty(); - batch.push(engine.full_target_seed(verified,a,cell,outputs[a],coupled)?,self.vocabulary)?; - let mut j=1; - while j<(self.max_t-1).min(self.max_drafts) && batch.probabilities[j-1]>=min_p { - let next_cell=cell.checked_add(j as i64).ok_or(Error::Overflow)?; - batch.push(engine.full_chain_step(next_cell,j,batch.ids[j-1],coupled)?,self.vocabulary)?;j+=1; + if outputs.iter().any(|&v| v < 0 || v as u32 >= self.vocabulary) + || !vetted.in_range(consumed, self.vocabulary as i32) + { + return Err(Error::InvalidToken); + } + let result = (|| { + if coupled { + engine.stage_coupled_history(consumed, outputs[a])?; + } + engine.replay_target_kv(verified, p, outputs)?; + let cell = p.checked_add(a as i64).ok_or(Error::Overflow)?; + let mut batch = DraftBatch::empty(); + batch.push(engine.full_target_seed(verified, a, cell, outputs[a], coupled)?, self.vocabulary)?; + let mut j = 1; + while j < (self.max_t - 1).min(self.max_drafts) && batch.probabilities[j - 1] >= min_p { + let next_cell = cell.checked_add(j as i64).ok_or(Error::Overflow)?; + batch.push(engine.full_chain_step(next_cell, j, batch.ids[j - 1], coupled)?, self.vocabulary)?; + j += 1; } Ok(batch) })(); - let drain=engine.drain_draft(); + let drain = engine.drain_draft(); // Preserves stage primary; adapter must retain/poison uncertainty even // when an earlier finite/admission error is returned to the caller. - match result {Err(e)=>Err(e),Ok(b)=>{drain?;Ok(b)}} + match result { + Err(e) => Err(e), + Ok(b) => { + drain?; + Ok(b) + } + } } } /// Exact Original record geometry: token + step[4] + head positions[24]. /// These are scheduling inputs only; no typed readiness capability is created. -pub(crate) struct PrefillRecords {records:Box<[i32]>,rows:usize,cell0:i64} +pub(crate) struct PrefillRecords { + records: Box<[i32]>, + rows: usize, + cell0: i64, +} impl PrefillRecords { - pub(crate) fn new(next_tokens:&[i32],cell0:i64,vocabulary:u32)->Result { - let n=next_tokens.len(); - if n==0||(n as i64)>(crate::qwen_forward::contract::serving_cells() as i64)||cell0<0||cell0.checked_add(n as i64).is_none_or(|end|end>(crate::qwen_forward::contract::serving_cells() as i64))||vocabulary==0||vocabulary>262144 {return Err(Error::InvalidDimension);} - if next_tokens.iter().any(|&v|v<0||v as u32>=vocabulary) {return Err(Error::InvalidToken);} - let count=n.checked_mul(29).ok_or(Error::Overflow)?; - let mut rec=Vec::new();rec.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?;rec.resize(count,0); + pub(crate) fn new(next_tokens: &[i32], cell0: i64, vocabulary: u32) -> Result { + let n = next_tokens.len(); + if n == 0 + || (n as i64) > (crate::qwen_forward::contract::serving_cells() as i64) + || cell0 < 0 + || cell0 + .checked_add(n as i64) + .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || vocabulary == 0 + || vocabulary > 262144 + { + return Err(Error::InvalidDimension); + } + if next_tokens.iter().any(|&v| v < 0 || v as u32 >= vocabulary) { + return Err(Error::InvalidToken); + } + let count = n.checked_mul(29).ok_or(Error::Overflow)?; + let mut rec = Vec::new(); + rec.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; + rec.resize(count, 0); rec[..n].copy_from_slice(next_tokens); for i in 0..n { - let cell=i32::try_from(cell0.checked_add(i as i64).ok_or(Error::Overflow)?).map_err(|_|Error::InvalidPosition)?; - let next=cell.checked_add(1).ok_or(Error::Overflow)?; - rec[n+i*4..n+(i+1)*4].copy_from_slice(&[cell,next,next/4,next]); - rec[5*n+i*24..5*n+(i+1)*24].fill(cell); + let cell = i32::try_from(cell0.checked_add(i as i64).ok_or(Error::Overflow)?) + .map_err(|_| Error::InvalidPosition)?; + let next = cell.checked_add(1).ok_or(Error::Overflow)?; + rec[n + i * 4..n + (i + 1) * 4].copy_from_slice(&[cell, next, next / 4, next]); + rec[5 * n + i * 24..5 * n + (i + 1) * 24].fill(cell); } - Ok(Self{records:rec.into_boxed_slice(),rows:n,cell0}) + Ok(Self { records: rec.into_boxed_slice(), rows: n, cell0 }) } - pub(crate) fn tokens(&self)->&[i32] {&self.records[..self.rows]} - pub(crate) fn steps(&self)->&[i32] {&self.records[self.rows..5*self.rows]} - pub(crate) fn positions(&self)->&[i32] {&self.records[5*self.rows..]} - pub(crate) fn bytes(&self)->usize {self.records.len()*4} - pub(crate) fn groups(&self,max_t:usize,cell0:i64,window:i64,prompt_len:i64)->Result { - if !(1..=MAX_T).contains(&max_t)||cell0!=self.cell0||!(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&window)||!(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&prompt_len) {return Err(Error::InvalidDimension);} - let first_needed=if window>0&&prompt_len>0 {prompt_len-window-64} else {0}; - Ok(PrefillGroups{next:0,rows:self.rows,max_t,cell0,first_needed}) + pub(crate) fn tokens(&self) -> &[i32] { + &self.records[..self.rows] + } + pub(crate) fn steps(&self) -> &[i32] { + &self.records[self.rows..5 * self.rows] + } + pub(crate) fn positions(&self) -> &[i32] { + &self.records[5 * self.rows..] + } + pub(crate) fn bytes(&self) -> usize { + self.records.len() * 4 + } + pub(crate) fn groups(&self, max_t: usize, cell0: i64, window: i64, prompt_len: i64) -> Result { + if !(1..=MAX_T).contains(&max_t) + || cell0 != self.cell0 + || !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&window) + || !(0..=(crate::qwen_forward::contract::serving_cells() as i64)).contains(&prompt_len) + { + return Err(Error::InvalidDimension); + } + let first_needed = if window > 0 && prompt_len > 0 { prompt_len - window - 64 } else { 0 }; + Ok(PrefillGroups { next: 0, rows: self.rows, max_t, cell0, first_needed }) } } -pub(crate) struct PrefillGroups {next:usize,rows:usize,max_t:usize,cell0:i64,first_needed:i64} +pub(crate) struct PrefillGroups { + next: usize, + rows: usize, + max_t: usize, + cell0: i64, + first_needed: i64, +} impl Iterator for PrefillGroups { - type Item=(usize,usize); - fn next(&mut self)->Option { - while self.next Option { + while self.next < self.rows { + let c = self.next; + let t = self.max_t.min(self.rows - c); + self.next += t; + if self.cell0 + c as i64 + t as i64 <= self.first_needed { + continue; + } + return Some((c, t)); + } + None } } @@ -127,25 +241,51 @@ impl Iterator for PrefillGroups { pub(crate) trait OriginalFirstDraftEngine { /// Retain the authentic current target seed and stage it T times exactly /// like draft_first; repeated rows write only cells the next round replaces. - fn replay_first_seed_kv(&mut self,seed:&Seed,t:usize,cell:i64,token:i32)->Result<()>; - fn full_first_seed(&mut self,seed:&Seed,cell:i64,token:i32,coupled:bool)->Result; - fn first_chain_step(&mut self,cell:i64,j:usize,previous_token:i32,coupled:bool)->Result; - fn drain_first_seed(&mut self)->Result<()>; + fn replay_first_seed_kv(&mut self, seed: &Seed, t: usize, cell: i64, token: i32) -> Result<()>; + fn full_first_seed(&mut self, seed: &Seed, cell: i64, token: i32, coupled: bool) -> Result; + fn first_chain_step(&mut self, cell: i64, j: usize, previous_token: i32, coupled: bool) -> Result; + fn drain_first_seed(&mut self) -> Result<()>; } impl DraftPreparation { - pub(crate) fn from_committed_seed>(&self,engine:&mut E,seed:&S, - cell:i64,token:i32,min_p:f32,coupled:bool)->Result { - if cell<0||cell.checked_add(self.max_t as i64).is_none_or(|end|end>(crate::qwen_forward::contract::serving_cells() as i64))||token<0||token as u32>=self.vocabulary||!min_p.is_finite() {return Err(Error::InvalidDimension);} - let result=(|| { - engine.replay_first_seed_kv(seed,self.max_t,cell,token)?; - let mut batch=DraftBatch::empty();batch.push(engine.full_first_seed(seed,cell,token,coupled)?,self.vocabulary)?; - let mut j=1; - while j<(self.max_t-1).min(self.max_drafts)&&batch.probabilities[j-1]>=min_p { - let next=cell.checked_add(j as i64).ok_or(Error::Overflow)?; - batch.push(engine.first_chain_step(next,j,batch.ids[j-1],coupled)?,self.vocabulary)?;j+=1; - }Ok(batch) + pub(crate) fn from_committed_seed>( + &self, + engine: &mut E, + seed: &S, + cell: i64, + token: i32, + min_p: f32, + coupled: bool, + ) -> Result { + if cell < 0 + || cell + .checked_add(self.max_t as i64) + .is_none_or(|end| end > (crate::qwen_forward::contract::serving_cells() as i64)) + || token < 0 + || token as u32 >= self.vocabulary + || !min_p.is_finite() + { + return Err(Error::InvalidDimension); + } + let result = (|| { + engine.replay_first_seed_kv(seed, self.max_t, cell, token)?; + let mut batch = DraftBatch::empty(); + batch.push(engine.full_first_seed(seed, cell, token, coupled)?, self.vocabulary)?; + let mut j = 1; + while j < (self.max_t - 1).min(self.max_drafts) && batch.probabilities[j - 1] >= min_p { + let next = cell.checked_add(j as i64).ok_or(Error::Overflow)?; + batch.push(engine.first_chain_step(next, j, batch.ids[j - 1], coupled)?, self.vocabulary)?; + j += 1; + } + Ok(batch) })(); - let drain=engine.drain_first_seed();match result {Err(e)=>Err(e),Ok(batch)=>{drain?;Ok(batch)}} + let drain = engine.drain_first_seed(); + match result { + Err(e) => Err(e), + Ok(batch) => { + drain?; + Ok(batch) + } + } } } @@ -154,14 +294,36 @@ impl DraftPreparation { /// The adapter loans genuine whole prompt residuals and validated next tokens; /// this scheduler cannot mint or advance target/session causal metadata. pub(crate) trait OriginalPrefillDraftEngine { - fn upload_prefill_records(&mut self,prompt:&Prompt,records:&PrefillRecords)->Result<()>; - fn append_prefill_group(&mut self,prompt:&Prompt,records:&PrefillRecords,first:usize,rows:usize)->Result<()>; - fn drain_prefill(&mut self)->Result<()>; + fn upload_prefill_records(&mut self, prompt: &Prompt, records: &PrefillRecords) -> Result<()>; + fn append_prefill_group( + &mut self, + prompt: &Prompt, + records: &PrefillRecords, + first: usize, + rows: usize, + ) -> Result<()>; + fn drain_prefill(&mut self) -> Result<()>; } -pub(crate) fn prefill_draft>(engine:&mut E,prompt:&P,records:&PrefillRecords, - max_t:usize,cell0:i64,window:i64,prompt_len:i64)->Result<()> { - let groups=records.groups(max_t,cell0,window,prompt_len)?; - let result=(||{engine.upload_prefill_records(prompt,records)?; - for (first,rows) in groups {engine.append_prefill_group(prompt,records,first,rows)?;}Ok(())})(); - let drain=engine.drain_prefill();match result {Err(e)=>Err(e),Ok(())=>drain} +pub(crate) fn prefill_draft>( + engine: &mut E, + prompt: &P, + records: &PrefillRecords, + max_t: usize, + cell0: i64, + window: i64, + prompt_len: i64, +) -> Result<()> { + let groups = records.groups(max_t, cell0, window, prompt_len)?; + let result = (|| { + engine.upload_prefill_records(prompt, records)?; + for (first, rows) in groups { + engine.append_prefill_group(prompt, records, first, rows)?; + } + Ok(()) + })(); + let drain = engine.drain_prefill(); + match result { + Err(e) => Err(e), + Ok(()) => drain, + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs index ed3140c3..1a045654 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/original_spec_suffix.rs @@ -1,88 +1,180 @@ //! Original four-way trigram suffix index. It is a drafter, never target authority. use super::contract::{Error, Result}; -#[derive(Clone,Copy,Default)] -struct Slot { key:u64,pos:[u32;4],n:u8 } +#[derive(Clone, Copy, Default)] +struct Slot { + key: u64, + pos: [u32; 4], + n: u8, +} pub(crate) struct SuffixDrafter { - min_match:usize,max_match:usize,history:Vec,table:Box<[Slot]>,mask:usize,last_match:usize, + min_match: usize, + max_match: usize, + history: Vec, + table: Box<[Slot]>, + mask: usize, + last_match: usize, /// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is /// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots). - touched:Vec, + touched: Vec, } /// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control). -fn sparse_reset()->bool { +fn sparse_reset() -> bool { crate::settings::process().decode.suffix_reset_sparse } -fn mix(mut x:u64)->u64 { - x^=x>>33;x=x.wrapping_mul(0xff51afd7ed558ccd);x^=x>>33; - x=x.wrapping_mul(0xc4ceb9fe1a85ec53);x^(x>>33) +fn mix(mut x: u64) -> u64 { + x ^= x >> 33; + x = x.wrapping_mul(0xff51afd7ed558ccd); + x ^= x >> 33; + x = x.wrapping_mul(0xc4ceb9fe1a85ec53); + x ^ (x >> 33) } impl SuffixDrafter { - pub(crate) fn new(min_match:usize,max_match:usize,capacity_tokens:usize)->Result { - if capacity_tokens==0 || capacity_tokens>i32::MAX as usize {return Err(Error::InvalidDimension);} - let cap=capacity_tokens.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?; - let mut table=Vec::new();table.try_reserve_exact(cap).map_err(|_|Error::InputAllocation)?; - table.resize(cap,Slot::default()); - let mut history=Vec::new();history.try_reserve_exact(capacity_tokens).map_err(|_|Error::InputAllocation)?; - Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0,touched:Vec::new()}) + pub(crate) fn new(min_match: usize, max_match: usize, capacity_tokens: usize) -> Result { + if capacity_tokens == 0 || capacity_tokens > i32::MAX as usize { + return Err(Error::InvalidDimension); + } + let cap = capacity_tokens.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?; + let mut table = Vec::new(); + table.try_reserve_exact(cap).map_err(|_| Error::InputAllocation)?; + table.resize(cap, Slot::default()); + let mut history = Vec::new(); + history.try_reserve_exact(capacity_tokens).map_err(|_| Error::InputAllocation)?; + Ok(Self { + min_match: min_match.max(3), + max_match: min_match.max(max_match), + history, + table: table.into_boxed_slice(), + mask: cap - 1, + last_match: 0, + touched: Vec::new(), + }) } - pub(crate) fn metadata_bytes(&self)->Result { - self.history.capacity().checked_mul(std::mem::size_of::()) - .and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::())?)) - .and_then(|n|n.checked_add(std::mem::size_of::())).ok_or(Error::Overflow) + pub(crate) fn metadata_bytes(&self) -> Result { + self.history + .capacity() + .checked_mul(std::mem::size_of::()) + .and_then(|n| n.checked_add(self.table.len().checked_mul(std::mem::size_of::())?)) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .ok_or(Error::Overflow) } pub(crate) fn reset(&mut self) { - self.history.clear();self.last_match=0; + self.history.clear(); + self.last_match = 0; // Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill. - if sparse_reset()&&self.touched.len()<=self.table.len()/4 { - for &i in &self.touched {self.table[i as usize]=Slot::default();} + if sparse_reset() && self.touched.len() <= self.table.len() / 4 { + for &i in &self.touched { + self.table[i as usize] = Slot::default(); + } } else { self.table.fill(Slot::default()); } self.touched.clear(); } - pub(crate) fn reserve_reset(&self,n:usize)->Result<()> { - if n>self.history.capacity() {return Err(Error::InputAllocation);}Ok(()) + pub(crate) fn reserve_reset(&self, n: usize) -> Result<()> { + if n > self.history.capacity() { + return Err(Error::InputAllocation); + } + Ok(()) } - pub(crate) fn reserve_append(&self,n:usize)->Result<()> { - if self.history.len().checked_add(n).ok_or(Error::Overflow)?>self.history.capacity() {return Err(Error::InputAllocation);}Ok(()) + pub(crate) fn reserve_append(&self, n: usize) -> Result<()> { + if self.history.len().checked_add(n).ok_or(Error::Overflow)? > self.history.capacity() { + return Err(Error::InputAllocation); + } + Ok(()) } - fn key_at(&self,end:usize)->u64 { - let a=self.history[end-2] as u32 as u64;let b=self.history[end-1] as u32 as u64;let c=self.history[end] as u32 as u64; - mix(a.wrapping_mul(0x9E3779B97F4A7C15)^mix(b.wrapping_add(0x632BE59BD9B4E019))^(c<<1))|1 + fn key_at(&self, end: usize) -> u64 { + let a = self.history[end - 2] as u32 as u64; + let b = self.history[end - 1] as u32 as u64; + let c = self.history[end] as u32 as u64; + mix(a.wrapping_mul(0x9E3779B97F4A7C15) ^ mix(b.wrapping_add(0x632BE59BD9B4E019)) ^ (c << 1)) | 1 } - fn find_slot(&mut self,key:u64,insert:bool)->Option { - let mut i=key as usize & self.mask; + fn find_slot(&mut self, key: u64, insert: bool) -> Option { + let mut i = key as usize & self.mask; for _ in 0..=self.mask { - if self.table[i].key==key {return Some(i);} - if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;self.touched.push(i as u32);return Some(i);} - i=(i+1)&self.mask; - }None + if self.table[i].key == key { + return Some(i); + } + if self.table[i].key == 0 { + if !insert { + return None; + } + self.table[i].key = key; + self.touched.push(i as u32); + return Some(i); + } + i = (i + 1) & self.mask; + } + None } - pub(crate) fn append(&mut self,tokens:&[i32])->Result<()> { + pub(crate) fn append(&mut self, tokens: &[i32]) -> Result<()> { self.reserve_append(tokens.len())?; for &token in tokens { - self.history.push(token);let end=self.history.len()-1;if end<2 {continue;} - let key=self.key_at(end); - if let Some(i)=self.find_slot(key,true) { - let s=&mut self.table[i];for w in (1..4).rev() {s.pos[w]=s.pos[w-1];} - s.pos[0]=end as u32;if s.n<4 {s.n+=1;} + self.history.push(token); + let end = self.history.len() - 1; + if end < 2 { + continue; + } + let key = self.key_at(end); + if let Some(i) = self.find_slot(key, true) { + let s = &mut self.table[i]; + for w in (1..4).rev() { + s.pos[w] = s.pos[w - 1]; + } + s.pos[0] = end as u32; + if s.n < 4 { + s.n += 1; + } } - }Ok(()) - } - pub(crate) fn propose(&mut self,out:&mut[i32])->usize { - self.last_match=0;let n=self.history.len();if n<4||out.is_empty() {return 0;} - let cur=n-1;let key=self.key_at(cur);let Some(i)=self.find_slot(key,false) else {return 0;}; - let slot=self.table[i];let(mut best_end,mut best_len)=(0,0); - for w in 0..slot.n as usize { - let p=slot.pos[w] as usize;if p>=cur {continue;} - let mut len=0;while lenbest_len {best_len=len;best_end=p;} } - if best_len usize { + self.last_match = 0; + let n = self.history.len(); + if n < 4 || out.is_empty() { + return 0; + } + let cur = n - 1; + let key = self.key_at(cur); + let Some(i) = self.find_slot(key, false) else { + return 0; + }; + let slot = self.table[i]; + let (mut best_end, mut best_len) = (0, 0); + for w in 0..slot.n as usize { + let p = slot.pos[w] as usize; + if p >= cur { + continue; + } + let mut len = 0; + while len < self.max_match && len <= p && self.history[p - len] == self.history[cur - len] { + len += 1; + } + if len > best_len { + best_len = len; + best_end = p; + } + } + if best_len < self.min_match { + return 0; + } + self.last_match = best_len; + let mut k = 0; + for q in best_end + 1..=cur { + if k == out.len() { + break; + } + out[k] = self.history[q]; + k += 1; + } + k + } + pub(crate) fn last_match(&self) -> usize { + self.last_match + } + pub(crate) fn len(&self) -> usize { + self.history.len() } - pub(crate) fn last_match(&self)->usize {self.last_match} - pub(crate) fn len(&self)->usize {self.history.len()} } #[cfg(test)] @@ -91,19 +183,23 @@ mod tests { #[test] fn a_sparse_reset_leaves_the_same_empty_table_as_a_full_clear() { - let mut drafter=SuffixDrafter::new(3,64,4096).unwrap(); - let tokens:Vec=(0..300).map(|i|(i*7+i/3)%97).collect(); + let mut drafter = SuffixDrafter::new(3, 64, 4096).unwrap(); + let tokens: Vec = (0..300).map(|i| (i * 7 + i / 3) % 97).collect(); drafter.append(&tokens).unwrap(); assert!(!drafter.touched.is_empty()); drafter.reset(); - assert!(drafter.table.iter().all(|s|s.key==0&&s.n==0&&s.pos==[0;4]),"every claimed slot is cleared"); - assert!(drafter.touched.is_empty()&&drafter.len()==0); + assert!( + drafter.table.iter().all(|s| s.key == 0 && s.n == 0 && s.pos == [0; 4]), + "every claimed slot is cleared" + ); + assert!(drafter.touched.is_empty() && drafter.len() == 0); // the same tokens give the same proposals after the reset as on a fresh drafter - let mut fresh=SuffixDrafter::new(3,64,4096).unwrap(); - drafter.append(&tokens).unwrap();fresh.append(&tokens).unwrap(); - let (mut a,mut b)=([0;7],[0;7]); - assert_eq!(drafter.propose(&mut a),fresh.propose(&mut b)); - assert_eq!(a,b); - assert_eq!(drafter.last_match(),fresh.last_match()); + let mut fresh = SuffixDrafter::new(3, 64, 4096).unwrap(); + drafter.append(&tokens).unwrap(); + fresh.append(&tokens).unwrap(); + let (mut a, mut b) = ([0; 7], [0; 7]); + assert_eq!(drafter.propose(&mut a), fresh.propose(&mut b)); + assert_eq!(a, b); + assert_eq!(drafter.last_match(), fresh.last_match()); } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output.rs index 4780dcde..bc2ddc4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output.rs @@ -4,12 +4,9 @@ use super::contract::{Dimension, Error, FiniteF32, LayerId, Position, Result, Stage, TokenId}; use super::gr::{GrStage, InjectedResidual}; use super::session::QwenStepTxn; -use crate::model_binding::qwen4exp_input::{ - BindingIdentity, ModelBinding, OutputBindingError, OutputWeights, -}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, OutputBindingError, OutputWeights}; use leleka_cuda_driver::{ - Context, DeviceBuffer, HeadGreedySelection, HeadGreedyWorkspace, Q6KProjectionShape, - HEAD_GREEDY_WORKSPACE_BYTES, + Context, DeviceBuffer, HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace, Q6KProjectionShape, }; const VOCABULARY: usize = 248_320; @@ -53,12 +50,14 @@ pub(super) struct FiniteLogits { /// Authentic selected head result for one real pending final row. The private /// constructor below consumes a completed vocabulary witness; callers cannot /// substitute an arbitrary token as the MTP shifted final input. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) struct OriginalPromptSample { - binding:BindingIdentity, - phase:std::rc::Rc, - token:TokenId,position:Position,next:TokenId, - conditioning:bool, + binding: BindingIdentity, + phase: std::rc::Rc, + token: TokenId, + position: Position, + next: TokenId, + conditioning: bool, } // Both alternatives are completed provider products. Compact never stands in @@ -77,18 +76,18 @@ mod impl_originalpromptsample; mod impl_outputstage; mod impl_outputstage_2; #[allow(unused_imports)] +use impl_outputstage_2::binding_error; +#[allow(unused_imports)] +use impl_outputstage_2::combine; +#[allow(unused_imports)] +use impl_outputstage_2::decode_logits; +#[allow(unused_imports)] +use impl_outputstage_2::driver_error; +#[allow(unused_imports)] +use impl_outputstage_2::encode_activation; +#[allow(unused_imports)] pub(super) use impl_outputstage_2::greedy; #[allow(unused_imports)] use impl_outputstage_2::selected_token; #[allow(unused_imports)] use impl_outputstage_2::validate_weight_owner; -#[allow(unused_imports)] -use impl_outputstage_2::encode_activation; -#[allow(unused_imports)] -use impl_outputstage_2::decode_logits; -#[allow(unused_imports)] -use impl_outputstage_2::binding_error; -#[allow(unused_imports)] -use impl_outputstage_2::driver_error; -#[allow(unused_imports)] -use impl_outputstage_2::combine; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs index d0c08a56..9ca3c774 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_originalpromptsample.rs @@ -3,35 +3,77 @@ #[allow(unused_imports)] use super::*; -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl OriginalPromptSample { - pub(in crate::qwen_forward) fn greedy(binding:&ModelBinding,completed:&super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>,logits:FiniteLogits)->Result{ + pub(in crate::qwen_forward) fn greedy( + binding: &ModelBinding, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + logits: FiniteLogits, + ) -> Result { txn.validate_final(completed)?; - logits.validate_for(&binding.identity(),completed.token(),completed.position())?; - let next=greedy(logits)?; + logits.validate_for(&binding.identity(), completed.token(), completed.position())?; + let next = greedy(logits)?; txn.validate_final(completed)?; - if txn.known_prompt_next()?.is_some(){return Err(Error::IdentityMismatch);} - Ok(Self{binding:binding.identity(),phase:txn.phase(),token:completed.token(),position:completed.position(),next,conditioning:false}) + if txn.known_prompt_next()?.is_some() { + return Err(Error::IdentityMismatch); + } + Ok(Self { + binding: binding.identity(), + phase: txn.phase(), + token: completed.token(), + position: completed.position(), + next, + conditioning: false, + }) } - pub(in crate::qwen_forward) fn conditioning(binding:&ModelBinding,completed:&super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>)->Result{ + pub(in crate::qwen_forward) fn conditioning( + binding: &ModelBinding, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + ) -> Result { txn.validate_final(completed)?; - let next=txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; + let next = txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; completed.validate_conditioning(next)?; - Ok(Self{binding:binding.identity(),phase:txn.phase(),token:completed.token(),position:completed.position(),next,conditioning:true}) + Ok(Self { + binding: binding.identity(), + phase: txn.phase(), + token: completed.token(), + position: completed.position(), + next, + conditioning: true, + }) } - pub(in crate::qwen_forward) fn validate(&self,binding:&ModelBinding,completed:&super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::session::original_prompt::OriginalPromptTxn<'_, '_>)->Result<()> { + pub(in crate::qwen_forward) fn validate( + &self, + binding: &ModelBinding, + completed: &super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + ) -> Result<()> { txn.validate_final(completed)?; - if !self.binding.matches(&binding.identity())||!self.phase.same(&txn.phase()) - ||self.token!=completed.token()||self.position!=completed.position(){return Err(Error::IdentityMismatch);} - if self.conditioning {if txn.known_prompt_next()!=Ok(Some(self.next)){return Err(Error::IdentityMismatch);}completed.validate_conditioning(self.next)?;} - else if txn.known_prompt_next()?.is_some(){return Err(Error::IdentityMismatch);} + if !self.binding.matches(&binding.identity()) + || !self.phase.same(&txn.phase()) + || self.token != completed.token() + || self.position != completed.position() + { + return Err(Error::IdentityMismatch); + } + if self.conditioning { + if txn.known_prompt_next() != Ok(Some(self.next)) { + return Err(Error::IdentityMismatch); + } + completed.validate_conditioning(self.next)?; + } else if txn.known_prompt_next()?.is_some() { + return Err(Error::IdentityMismatch); + } Ok(()) } - pub(in crate::qwen_forward) fn next(&self)->TokenId{self.next} - pub(in crate::qwen_forward) fn emitted(&self)->Option{if self.conditioning{None}else{Some(self.next)}} + pub(in crate::qwen_forward) fn next(&self) -> TokenId { + self.next + } + pub(in crate::qwen_forward) fn emitted(&self) -> Option { + if self.conditioning { None } else { Some(self.next) } + } } impl FiniteLogits { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs index d36d5c60..0da466ed 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2.rs @@ -3,46 +3,48 @@ #[allow(unused_imports)] use super::*; - - impl<'context, 'driver> OutputStage<'context, 'driver> { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn logits_original_prompt( - &self,binding:&ModelBinding,completed:&super::super::super::prompt_device_rows::PromptDeviceFinal, - txn:&super::super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, - cache:&super::super::super::dense_weight_cache::DenseWeightCache<'_>, - )->Result{ + &self, + binding: &ModelBinding, + completed: &super::super::super::prompt_device_rows::PromptDeviceFinal, + txn: &super::super::super::session::original_prompt::OriginalPromptTxn<'_, '_>, + cache: &super::super::super::dense_weight_cache::DenseWeightCache<'_>, + ) -> Result { txn.validate_final(completed)?; - let context=txn.context()?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context){return Err(Error::IdentityMismatch)} - let mixed=GrStage::final_mix_original_prompt(binding,completed,txn,cache)?; - if mixed.len()!=EMBEDDING||mixed.iter().any(|value|!value.is_finite()){return Err(Error::NonFinite)} - if self.sampler_wants(completed.position())? {return Err(Error::Unsupported(Stage::Output));} - let logits=self.project_mixed(binding.identity(),completed.token(),completed.position(),&mixed,context,false)?; - txn.validate_final(completed)?;logits.validate_for(&binding.identity(),completed.token(),completed.position())?; - if matches!(&logits.values,LogitValues::Compact(_)){self.record_compact_completion()?;} + let context = txn.context()?; + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + let mixed = GrStage::final_mix_original_prompt(binding, completed, txn, cache)?; + if mixed.len() != EMBEDDING || mixed.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + if self.sampler_wants(completed.position())? { + return Err(Error::Unsupported(Stage::Output)); + } + let logits = + self.project_mixed(binding.identity(), completed.token(), completed.position(), &mixed, context, false)?; + txn.validate_final(completed)?; + logits.validate_for(&binding.identity(), completed.token(), completed.position())?; + if matches!(&logits.values, LogitValues::Compact(_)) { + self.record_compact_completion()?; + } Ok(logits) } /// Validate and upload the one fixed output tensor once for this context. /// The caller retains this stage for subsequent tokens; no per-token head /// re-read or matrix transfer occurs. - pub(crate) fn load( - binding: &ModelBinding, - context: &'context Context<'driver>, - ) -> Result { - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET) - .ok_or(Error::Overflow)?; + pub(crate) fn load(binding: &ModelBinding, context: &'context Context<'driver>) -> Result { + let required = context.allocated_bytes().checked_add(OUTPUT_STAGE_BUDGET).ok_or(Error::Overflow)?; if required > context.budget_bytes() { return Err(Error::InputAllocation); } let weights = binding.output_weights().map_err(binding_error)?; validate_weight_owner(&weights, &binding.identity())?; - let mut device_weights = context - .allocate(OUTPUT_WEIGHT_BYTES) - .map_err(driver_error)?; + let mut device_weights = context.allocate(OUTPUT_WEIGHT_BYTES).map_err(driver_error)?; if let Err(error) = device_weights.copy_from(weights.bytes()) { let primary = driver_error(error); return combine(Err(primary), device_weights.release().map_err(driver_error)); @@ -66,18 +68,13 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { // Explicit private qualification factory only. The fixed owner is charged // before the existing head load and before the caller's profile preload. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(crate) fn load_compact( - binding: &ModelBinding, - context: &'context Context<'driver>, - ) -> Result { + pub(crate) fn load_compact(binding: &ModelBinding, context: &'context Context<'driver>) -> Result { let required = context .allocated_bytes() .checked_add(OUTPUT_STAGE_BUDGET) .and_then(|bytes| bytes.checked_add(HEAD_GREEDY_WORKSPACE_BYTES)) .ok_or(Error::Overflow)?; - let physical = HEAD_GREEDY_WORKSPACE_BYTES - .checked_add(128 * 1024 * 1024) - .ok_or(Error::Overflow)?; + let physical = HEAD_GREEDY_WORKSPACE_BYTES.checked_add(128 * 1024 * 1024).ok_or(Error::Overflow)?; if required > context.budget_bytes() { return Err(Error::InputAllocation); } @@ -135,14 +132,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { let token = txn.token(); let position = txn.position(); - let final_layer = binding - .layer_count() - .checked_sub(1) - .ok_or(Error::InvalidLayer)?; - let layer = LayerId::new( - u64::from(final_layer), - Dimension::new(u64::from(binding.layer_count()))?, - )?; + let final_layer = binding.layer_count().checked_sub(1).ok_or(Error::InvalidLayer)?; + let layer = LayerId::new(u64::from(final_layer), Dimension::new(u64::from(binding.layer_count()))?)?; residual.identity().validate(token, position, layer)?; txn.validate_input(token, position)?; @@ -162,14 +153,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { } // A request sampler needs the complete vector, never the compact device argmax. let sampled = self.sampler_wants(position)?; - let mut logits = self.project_mixed( - identity, - token, - position, - &mixed, - txn.cuda_context()?, - sampled, - )?; + let mut logits = self.project_mixed(identity, token, position, &mixed, txn.cuda_context()?, sampled)?; if sampled { logits = self.sample_complete(logits)?; } @@ -224,11 +208,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if current.is_poisoned() { return Err(Error::CudaExecution); } - logits.validate_for( - &binding.identity(), - mixed.frame().token(), - mixed.frame().position(), - )?; + logits.validate_for(&binding.identity(), mixed.frame().token(), mixed.frame().position())?; self.record_compact_completion()?; } greedy(logits) @@ -236,10 +216,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { /// Arm the per-request sampler for the plain decode path. One request at a time. pub(crate) fn arm_sampler(&self, sampler: super::super::super::step_sampler::StepSampler) -> Result<()> { - let mut slot = self - .sampler - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut slot = self.sampler.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; if slot.is_some() { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs index 6c2c05d1..45b5da4a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage/impl_outputstage_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'context, 'driver> OutputStage<'context, 'driver> { - pub(in super::super) fn sampler_wants(&self, position: Position) -> Result { Ok(self .sampler @@ -30,10 +27,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { .ok_or(Error::IdentityMismatch)? .pick(&floats, logits.position.get())?; let token = TokenId::new(u64::from(token), Dimension::new(VOCABULARY as u64)?)?; - Ok(FiniteLogits { - values: LogitValues::Selected(token), - ..logits - }) + Ok(FiniteLogits { values: LogitValues::Selected(token), ..logits }) } pub(in super::super) fn project_mixed( @@ -46,14 +40,9 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { force_full: bool, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Head, - ); - if self - .compact - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .is_some() + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Head); + if self.compact.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_some() && !force_full && !self.full_head_observer_active() { @@ -68,10 +57,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if mixed.iter().any(|v| !v.is_finite()) { return Err(Error::NonFinite); } - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) - .ok_or(Error::Overflow)?; + let required = + context.allocated_bytes().checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES).ok_or(Error::Overflow)?; if required > context.budget_bytes() { return Err(Error::InputAllocation); } @@ -96,10 +83,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { &self.weights, &activation, &mut candidate, - Q6KProjectionShape { - rows: VOCABULARY, - columns: EMBEDDING, - }, + Q6KProjectionShape { rows: VOCABULARY, columns: EMBEDDING }, ); let mut result = projection.map_err(driver_error); let mut decoded_logits = None; @@ -141,12 +125,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { // draft frame has been revalidated. An attempted selection is not counted. pub(in super::super) fn record_compact_completion(&self) -> Result<()> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - self.compact_completions.set( - self.compact_completions - .get() - .checked_add(1) - .ok_or(Error::Overflow)?, - ); + self.compact_completions.set(self.compact_completions.get().checked_add(1).ok_or(Error::Overflow)?); Ok(()) } @@ -180,10 +159,8 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { if mixed.iter().any(|v| !v.is_finite()) { return Err(Error::NonFinite); } - let required = context - .allocated_bytes() - .checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES) - .ok_or(Error::Overflow)?; + let required = + context.allocated_bytes().checked_add(OUTPUT_STAGE_BUDGET - OUTPUT_WEIGHT_BYTES).ok_or(Error::Overflow)?; if required > context.budget_bytes() { return Err(Error::InputAllocation); } @@ -208,10 +185,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { &self.weights, &activation, &mut candidate, - Q6KProjectionShape { - rows: VOCABULARY, - columns: EMBEDDING, - }, + Q6KProjectionShape { rows: VOCABULARY, columns: EMBEDDING }, ); let mut selection = None; let mut result = projection.map_err(driver_error); @@ -219,10 +193,7 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { result = (|| { // The exclusive loan ends before either source buffer is // released. No immutable weight/cache callback is reentered. - let mut owner = self - .compact - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut owner = self.compact.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; let workspace = owner.as_mut().ok_or(Error::IdentityMismatch)?; if workspace.allocated_bytes() != HEAD_GREEDY_WORKSPACE_BYTES { return Err(Error::InvalidDimension); @@ -247,11 +218,6 @@ impl<'context, 'driver> OutputStage<'context, 'driver> { } let selection = selection.ok_or(Error::NonFinite)?; selected_token(&selection)?; - Ok(FiniteLogits { - binding: identity, - token, - position, - values: LogitValues::Compact(selection), - }) + Ok(FiniteLogits { binding: identity, token, position, values: LogitValues::Compact(selection) }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs index 95be8394..65990f47 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/impl_outputstage_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // The real ignored reset test opts in explicitly. Other test callers retain // no extra values; production builds have neither this storage nor a reader. #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -12,21 +11,13 @@ impl OutputStage<'_, '_> { // actual target step. Existing executor reset/replay observers stay one-shot. pub(crate) fn test_prefix_begin_target(&self) -> Result<()> { if self.reset_replay_record.get() { - self.reset_replay_logits - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)? - .take(); + self.reset_replay_logits.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.take(); } Ok(()) } pub(crate) fn test_reset_replay_record(&self, enabled: bool) -> Result<()> { - if self - .reset_replay_logits - .try_borrow() - .map_err(|_| Error::IdentityMismatch)? - .is_some() - { + if self.reset_replay_logits.try_borrow().map_err(|_| Error::IdentityMismatch)?.is_some() { return Err(Error::IdentityMismatch); } self.reset_replay_record.set(enabled); @@ -38,11 +29,7 @@ impl OutputStage<'_, '_> { LogitValues::Full(values) => values, LogitValues::Selected(_) => return Err(Error::IdentityMismatch), LogitValues::Compact(_) => { - return if self.full_head_observer_active() { - Err(Error::IdentityMismatch) - } else { - Ok(()) - }; + return if self.full_head_observer_active() { Err(Error::IdentityMismatch) } else { Ok(()) }; } }; // Separate bounded observer; the old single-slot observer stays exact. @@ -57,17 +44,12 @@ impl OutputStage<'_, '_> { if !self.binding.matches(&logits.binding) || values.len() != VOCABULARY { return Err(Error::IdentityMismatch); } - let mut destination = self - .reset_replay_logits - .try_borrow_mut() - .map_err(|_| Error::IdentityMismatch)?; + let mut destination = self.reset_replay_logits.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; if destination.is_some() { return Err(Error::IdentityMismatch); } let mut words = Vec::new(); - words - .try_reserve_exact(VOCABULARY) - .map_err(|_| Error::InputAllocation)?; + words.try_reserve_exact(VOCABULARY).map_err(|_| Error::InputAllocation)?; words.extend(values.iter().map(|v| v.get().to_bits())); *destination = Some(words.into_boxed_slice()); Ok(()) @@ -128,10 +110,7 @@ pub(super) fn validate_weight_owner(weights: &OutputWeights, binding: &BindingId if weights.kind() != 14 { return Err(Error::Unsupported(Stage::Binding)); } - if weights.rows() != VOCABULARY - || weights.columns() != EMBEDDING - || weights.bytes().len() != OUTPUT_WEIGHT_BYTES - { + if weights.rows() != VOCABULARY || weights.columns() != EMBEDDING || weights.bytes().len() != OUTPUT_WEIGHT_BYTES { return Err(Error::InvalidDimension); } Ok(()) @@ -142,9 +121,7 @@ pub(super) fn encode_activation(values: &[f32]) -> Result> { return Err(Error::InvalidDimension); } let mut bytes = Vec::new(); - bytes - .try_reserve_exact(ACTIVATION_BYTES) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(ACTIVATION_BYTES).map_err(|_| Error::InputAllocation)?; for value in values { if !value.is_finite() { return Err(Error::NonFinite); @@ -166,9 +143,7 @@ pub(super) fn decode_logits(bytes: &[u8]) -> Result> { return Err(Error::InvalidDimension); } let mut values = Vec::new(); - values - .try_reserve_exact(VOCABULARY) - .map_err(|_| Error::InputAllocation)?; + values.try_reserve_exact(VOCABULARY).map_err(|_| Error::InputAllocation)?; for word in words { let value = f32::from_bits(u32::from_le_bytes(*word)); values.push(FiniteF32::new(value)?); @@ -188,7 +163,9 @@ pub(super) fn binding_error(error: OutputBindingError) -> Error { } pub(super) fn driver_error(error: leleka_cuda_driver::Error) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {error:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {error:?}"); + } use leleka_cuda_driver::Error as DriverError; match error { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output/tests.rs index 61d82188..9fbb3ed7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output/tests.rs @@ -20,14 +20,8 @@ fn logits(values: Vec) -> FiniteLogits { fn output_weights_refuse_cross_binding_before_invalid_extent() { let owner = BindingIdentity::test_identity(); let weights = OutputWeights::test_empty(owner.clone()); - assert_eq!( - validate_weight_owner(&weights, &owner), - Err(Error::InvalidDimension) - ); - assert_eq!( - validate_weight_owner(&weights, &BindingIdentity::test_identity()), - Err(Error::IdentityMismatch) - ); + assert_eq!(validate_weight_owner(&weights, &owner), Err(Error::InvalidDimension)); + assert_eq!(validate_weight_owner(&weights, &BindingIdentity::test_identity()), Err(Error::IdentityMismatch)); assert!(weights.bytes().is_empty()); assert!(weights.matches(&owner)); } @@ -44,10 +38,7 @@ fn greedy_ties_choose_the_lowest_vocabulary_id() { fn greedy_selects_a_strictly_greater_late_logit() { let mut values = finite_values(0.0); values[VOCABULARY - 1] = FiniteF32::new(1.0).expect("finite max"); - assert_eq!( - greedy(logits(values)).map(TokenId::get), - Ok((VOCABULARY - 1) as u32) - ); + assert_eq!(greedy(logits(values)).map(TokenId::get), Ok((VOCABULARY - 1) as u32)); } #[test] @@ -63,28 +54,18 @@ fn greedy_refuses_an_incomplete_vector() { #[test] fn decoding_requires_the_full_finite_vocabulary_before_publication() { let mut bytes = vec![0; LOGIT_BYTES]; - assert_eq!( - decode_logits(&bytes).map(|values| values.len()), - Ok(VOCABULARY) - ); + assert_eq!(decode_logits(&bytes).map(|values| values.len()), Ok(VOCABULARY)); bytes.truncate(LOGIT_BYTES - 1); assert_eq!(decode_logits(&bytes), Err(Error::InvalidDimension)); bytes.resize(LOGIT_BYTES, 0); - bytes[(VOCABULARY - 1) * 4..VOCABULARY * 4] - .copy_from_slice(&f32::INFINITY.to_bits().to_le_bytes()); + bytes[(VOCABULARY - 1) * 4..VOCABULARY * 4].copy_from_slice(&f32::INFINITY.to_bits().to_le_bytes()); assert_eq!(decode_logits(&bytes), Err(Error::NonFinite)); } #[test] fn cleanup_failure_takes_precedence_over_a_host_validation_error() { - assert_eq!( - combine::<()>(Err(Error::NonFinite), Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert_eq!( - combine::<()>(Err(Error::NonFinite), Ok(())), - Err(Error::NonFinite) - ); + assert_eq!(combine::<()>(Err(Error::NonFinite), Err(Error::CudaExecution)), Err(Error::CudaExecution)); + assert_eq!(combine::<()>(Err(Error::NonFinite), Ok(())), Err(Error::NonFinite)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs index 45f0e126..52c8033f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native.rs @@ -1,56 +1,178 @@ //! Model-affine literal NativeHead bank. Actual row/epoch/accepted-prefix authority //! stays with the existing actor transaction; this module never mints it. -use crate::model_binding::qwen4exp_input::{BindingIdentity,ModelBinding,NativeOutputRole}; -use leleka_cuda_driver::{Context,OriginalNativeHead,OriginalNativeEmbed,OriginalNativeHeadRows, - OriginalGpuStream,OriginalGpuGraph,NativeHeadDispatch,NativeHeadSelection,NativeHeadSampling,OriginalNativeHeadGraphResources,DeviceBuffer}; +use super::contract::{Error, Result, Stage}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, NativeOutputRole}; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeHeadDispatch, NativeHeadSampling, NativeHeadSelection, OriginalGpuGraph, + OriginalGpuStream, OriginalNativeEmbed, OriginalNativeHead, OriginalNativeHeadGraphResources, + OriginalNativeHeadRows, +}; use std::rc::Rc; -use super::contract::{Error,Result,Stage}; -#[path="output_native_history.rs"] +#[path = "output_native_history.rs"] mod history; pub(in crate::qwen_forward) use history::OriginalNativePenaltyHistory; /// The exact `NativeHead::weights()` allocation borrowed by the original MTP /// drafter. This carries no host copy, row staging buffer, or replacement /// dispatch setting; `OriginalNativeOutput` remains the model-affine source. -pub(in crate::qwen_forward) struct OriginalMtpNativeHead<'ctx>{weights:Rc>,kind:u32,columns:usize,vocabulary:usize,dispatch:NativeHeadDispatch} -impl<'ctx> OriginalMtpNativeHead<'ctx>{ - pub(in crate::qwen_forward) fn weights(&self)->Rc>{Rc::clone(&self.weights)} - pub(in crate::qwen_forward) fn kind(&self)->u32{self.kind} - pub(in crate::qwen_forward) fn columns(&self)->usize{self.columns} - pub(in crate::qwen_forward) fn vocabulary(&self)->usize{self.vocabulary} - pub(in crate::qwen_forward) fn dispatch(&self)->NativeHeadDispatch{self.dispatch} +pub(in crate::qwen_forward) struct OriginalMtpNativeHead<'ctx> { + weights: Rc>, + kind: u32, + columns: usize, + vocabulary: usize, + dispatch: NativeHeadDispatch, } -pub(in crate::qwen_forward) struct OriginalNativeOutput<'ctx>{binding:BindingIdentity,context:&'ctx Context<'ctx>,head:Option>,embed:Option>} -fn driver(e:leleka_cuda_driver::Error)->Error{use leleka_cuda_driver::Error as D;match e{D::UnsupportedQwenOperation=>Error::Unsupported(Stage::Output),D::HostAllocation|D::BudgetExceeded=>Error::InputAllocation,D::InvalidQwenShape|D::InvalidQ6KProjectionShape|D::InvalidQ8Activation|D::InvalidSize|D::ShapeMismatch{..}=>Error::InvalidDimension,D::ContextMismatch|D::UnexpectedContext=>Error::IdentityMismatch,_=>Error::CudaExecution}} -impl<'ctx> OriginalNativeOutput<'ctx>{ - pub(in crate::qwen_forward) fn load(binding:&ModelBinding,context:&'ctx Context<'ctx>,dispatch:NativeHeadDispatch,with_embedding:bool)->Result{ - // A refusal here is reported with its cause on stderr: the class alone (InvalidDimension) hides which of the - // binding, the weight block or the driver refused. - let weights=binding.native_output_block(NativeOutputRole::Head).map_err(|e|{eprintln!("OriginalNativeOutput::load: head block refused: {e:?}");Error::InvalidDimension})?; - if !weights.matches(&binding.identity()){return Err(Error::IdentityMismatch);} - let head=context.original_native_head(weights.kind(),weights.columns(),weights.vocabulary(),weights.bytes(),dispatch).map_err(|e|{eprintln!("OriginalNativeOutput::load: native head refused: {e:?}");driver(e)})?; - let mut owner=Self{binding:binding.identity(),context,head:Some(head),embed:None}; - let operation=(||{if with_embedding{let embedding=binding.native_output_block(NativeOutputRole::Embedding).map_err(|e|{eprintln!("OriginalNativeOutput::load: embedding block refused: {e:?}");Error::InvalidDimension})?;if !embedding.matches(&binding.identity()){return Err(Error::IdentityMismatch);}owner.embed=Some(context.original_native_embed(embedding.kind(),embedding.columns(),embedding.vocabulary(),embedding.bytes()).map_err(|e|{eprintln!("OriginalNativeOutput::load: native embedding refused: {e:?}");driver(e)})?);}Ok(())})(); - if let Err(primary)=operation{let _=owner.close();return Err(primary);}Ok(owner) - } - fn validate(&self,binding:&ModelBinding,context:&Context<'_>)->Result<()>{if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch);}self.head.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver)} - /// Literal MtpDrafter::bind dependency: lend the native output matrix itself. - /// The direct port cannot call this against another model identity or context. - pub(in crate::qwen_forward) fn mtp_head(&self,binding:&ModelBinding)->Result>{self.validate(binding,self.context)?;let head=self.head.as_ref().ok_or(Error::IdentityMismatch)?;Ok(OriginalMtpNativeHead{weights:head.retain_weights().map_err(driver)?,kind:head.kind(),columns:head.columns(),vocabulary:head.vocabulary(),dispatch:head.dispatch()})} - pub(in crate::qwen_forward) fn rows(&self,binding:&ModelBinding,t:usize)->Result>{self.validate(binding,self.context)?;self.head.as_ref().ok_or(Error::IdentityMismatch)?.rows(t).map_err(driver)} - pub(in crate::qwen_forward) fn embedding(&self,binding:&ModelBinding)->Result<&OriginalNativeEmbed<'ctx>>{self.validate(binding,self.context)?;self.embed.as_ref().ok_or(Error::IdentityMismatch)} - /// The graph is made with the REAL head row resource by the actor. `authenticate` - /// validates genuine current target rows before any wait/resample and after ALL - /// actual sampled IDs are complete. It is not a host-float readiness constructor. - pub(in crate::qwen_forward) fn finish_verification>( - &self,binding:&ModelBinding,graph:&mut OriginalGpuGraph<'ctx,R>, - stream:&mut OriginalGpuStream<'ctx>,sampling:NativeHeadSampling<'_,'ctx>, - mut authenticate:impl FnMut()->Result<()>, - )->Result{ - self.validate(binding,self.context)?;authenticate()?; - graph.validate_native_head(self.head.as_ref().ok_or(Error::IdentityMismatch)?).map_err(driver)?; - let selected=graph.native_head_after_launch(stream,sampling).map_err(driver)?; - self.validate(binding,self.context)?;authenticate()?; - if selected.position()!=sampling.position||selected.vocabulary()!=self.head.as_ref().ok_or(Error::IdentityMismatch)?.vocabulary(){return Err(Error::IdentityMismatch);}Ok(selected) - } - pub(in crate::qwen_forward) fn close(mut self)->Result<()>{let embed=self.embed.take().map_or(Ok(()),|e|e.close().map_err(driver));let head=self.head.take().map_or(Ok(()),|h|h.close().map_err(driver));match (embed,head){(Err(primary),_)=>Err(primary),(Ok(()),other)=>other}} +impl<'ctx> OriginalMtpNativeHead<'ctx> { + pub(in crate::qwen_forward) fn weights(&self) -> Rc> { + Rc::clone(&self.weights) + } + pub(in crate::qwen_forward) fn kind(&self) -> u32 { + self.kind + } + pub(in crate::qwen_forward) fn columns(&self) -> usize { + self.columns + } + pub(in crate::qwen_forward) fn vocabulary(&self) -> usize { + self.vocabulary + } + pub(in crate::qwen_forward) fn dispatch(&self) -> NativeHeadDispatch { + self.dispatch + } +} +pub(in crate::qwen_forward) struct OriginalNativeOutput<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + head: Option>, + embed: Option>, +} +fn driver(e: leleka_cuda_driver::Error) -> Error { + use leleka_cuda_driver::Error as D; + match e { + D::UnsupportedQwenOperation => Error::Unsupported(Stage::Output), + D::HostAllocation | D::BudgetExceeded => Error::InputAllocation, + D::InvalidQwenShape + | D::InvalidQ6KProjectionShape + | D::InvalidQ8Activation + | D::InvalidSize + | D::ShapeMismatch { .. } => Error::InvalidDimension, + D::ContextMismatch | D::UnexpectedContext => Error::IdentityMismatch, + _ => Error::CudaExecution, + } +} +impl<'ctx> OriginalNativeOutput<'ctx> { + pub(in crate::qwen_forward) fn load( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + dispatch: NativeHeadDispatch, + with_embedding: bool, + ) -> Result { + // A refusal here is reported with its cause on stderr: the class alone (InvalidDimension) hides which of the + // binding, the weight block or the driver refused. + let weights = binding.native_output_block(NativeOutputRole::Head).map_err(|e| { + eprintln!("OriginalNativeOutput::load: head block refused: {e:?}"); + Error::InvalidDimension + })?; + if !weights.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + let head = context + .original_native_head(weights.kind(), weights.columns(), weights.vocabulary(), weights.bytes(), dispatch) + .map_err(|e| { + eprintln!("OriginalNativeOutput::load: native head refused: {e:?}"); + driver(e) + })?; + let mut owner = Self { binding: binding.identity(), context, head: Some(head), embed: None }; + let operation = (|| { + if with_embedding { + let embedding = binding.native_output_block(NativeOutputRole::Embedding).map_err(|e| { + eprintln!("OriginalNativeOutput::load: embedding block refused: {e:?}"); + Error::InvalidDimension + })?; + if !embedding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + owner.embed = Some( + context + .original_native_embed( + embedding.kind(), + embedding.columns(), + embedding.vocabulary(), + embedding.bytes(), + ) + .map_err(|e| { + eprintln!("OriginalNativeOutput::load: native embedding refused: {e:?}"); + driver(e) + })?, + ); + } + Ok(()) + })(); + if let Err(primary) = operation { + let _ = owner.close(); + return Err(primary); + } + Ok(owner) + } + fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { + if !self.binding.matches(&binding.identity()) || !std::ptr::eq(context, self.context) { + return Err(Error::IdentityMismatch); + } + self.head.as_ref().ok_or(Error::IdentityMismatch)?.validate_context(context).map_err(driver) + } + /// Literal MtpDrafter::bind dependency: lend the native output matrix itself. + /// The direct port cannot call this against another model identity or context. + pub(in crate::qwen_forward) fn mtp_head(&self, binding: &ModelBinding) -> Result> { + self.validate(binding, self.context)?; + let head = self.head.as_ref().ok_or(Error::IdentityMismatch)?; + Ok(OriginalMtpNativeHead { + weights: head.retain_weights().map_err(driver)?, + kind: head.kind(), + columns: head.columns(), + vocabulary: head.vocabulary(), + dispatch: head.dispatch(), + }) + } + pub(in crate::qwen_forward) fn rows( + &self, + binding: &ModelBinding, + t: usize, + ) -> Result> { + self.validate(binding, self.context)?; + self.head.as_ref().ok_or(Error::IdentityMismatch)?.rows(t).map_err(driver) + } + pub(in crate::qwen_forward) fn embedding(&self, binding: &ModelBinding) -> Result<&OriginalNativeEmbed<'ctx>> { + self.validate(binding, self.context)?; + self.embed.as_ref().ok_or(Error::IdentityMismatch) + } + /// The graph is made with the REAL head row resource by the actor. `authenticate` + /// validates genuine current target rows before any wait/resample and after ALL + /// actual sampled IDs are complete. It is not a host-float readiness constructor. + pub(in crate::qwen_forward) fn finish_verification>( + &self, + binding: &ModelBinding, + graph: &mut OriginalGpuGraph<'ctx, R>, + stream: &mut OriginalGpuStream<'ctx>, + sampling: NativeHeadSampling<'_, 'ctx>, + mut authenticate: impl FnMut() -> Result<()>, + ) -> Result { + self.validate(binding, self.context)?; + authenticate()?; + graph.validate_native_head(self.head.as_ref().ok_or(Error::IdentityMismatch)?).map_err(driver)?; + let selected = graph.native_head_after_launch(stream, sampling).map_err(driver)?; + self.validate(binding, self.context)?; + authenticate()?; + if selected.position() != sampling.position + || selected.vocabulary() != self.head.as_ref().ok_or(Error::IdentityMismatch)?.vocabulary() + { + return Err(Error::IdentityMismatch); + } + Ok(selected) + } + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + let embed = self.embed.take().map_or(Ok(()), |e| e.close().map_err(driver)); + let head = self.head.take().map_or(Ok(()), |h| h.close().map_err(driver)); + match (embed, head) { + (Err(primary), _) => Err(primary), + (Ok(()), other) => other, + } + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs b/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs index 02a1262c..d7055845 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/output_native_history.rs @@ -2,81 +2,146 @@ //! allocation and one T*h upload per penalized window; disabled penalties lend //! no buffer. Token history is input data, never numerical/commit authority. use super::*; +use crate::qwen_forward::session::{QwenSession, TargetStepOrigin}; use crate::qwen_forward::token_memo::PrefixMemo; -use crate::qwen_forward::session::{QwenSession,TargetStepOrigin}; -use leleka_cuda_driver::{DeviceBuffer,SamplerParams,SamplerPath}; -const HISTORY:usize=4096; -const ROWS:usize=8; -const BYTES:usize=HISTORY*ROWS*4; +use leleka_cuda_driver::{DeviceBuffer, SamplerParams, SamplerPath}; +const HISTORY: usize = 4096; +const ROWS: usize = 8; +const BYTES: usize = HISTORY * ROWS * 4; -pub(in crate::qwen_forward) struct OriginalNativePenaltyHistory<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,device:Option>, - staging:Box<[u8]>,failed:bool, +pub(in crate::qwen_forward) struct OriginalNativePenaltyHistory<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + device: Option>, + staging: Box<[u8]>, + failed: bool, /// The part of the controller's `consumed` already range-checked (it only grows within a request): each window checks the tokens /// appended since, not the whole history again (`token_memo`). - tail_checked:PrefixMemo, + tail_checked: PrefixMemo, } -impl<'ctx> OriginalNativePenaltyHistory<'ctx>{ - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,context:&'ctx Context<'ctx>)->Result{ - if binding.layer_count()!=48{return Err(Error::IdentityMismatch);} - let mut staging=Vec::new();staging.try_reserve_exact(BYTES).map_err(|_|Error::InputAllocation)?; - staging.resize(BYTES,0xff); - let device=context.allocate(BYTES).map_err(driver)?; - Ok(Self{binding:binding.identity(),context,device:Some(device),staging:staging.into_boxed_slice(),failed:false,tail_checked:PrefixMemo::new()}) +impl<'ctx> OriginalNativePenaltyHistory<'ctx> { + pub(in crate::qwen_forward) fn new(binding: &ModelBinding, context: &'ctx Context<'ctx>) -> Result { + if binding.layer_count() != 48 { + return Err(Error::IdentityMismatch); + } + let mut staging = Vec::new(); + staging.try_reserve_exact(BYTES).map_err(|_| Error::InputAllocation)?; + staging.resize(BYTES, 0xff); + let device = context.allocate(BYTES).map_err(driver)?; + Ok(Self { + binding: binding.identity(), + context, + device: Some(device), + staging: staging.into_boxed_slice(), + failed: false, + tail_checked: PrefixMemo::new(), + }) + } + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + self.staging.len() + std::mem::size_of::() } - pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.staging.len()+std::mem::size_of::()} /// The closed caller authenticates its actual controller-consumed tail and /// verification inputs before upload and after sampling. This check is not /// replaced by matching lengths, positions, or bounded token IDs below. /// The exclusive owner loan lasts through the real sampler drain; no next /// window can overwrite the borrowed history while the consumer runs. pub(in crate::qwen_forward) fn with_sampling( - &mut self,binding:&ModelBinding,session:&QwenSession<'ctx>,origin:&TargetStepOrigin, - tail:&[i32],window:&[i32],params:SamplerParams,path:SamplerPath,enabled:bool, - mut authenticate:impl FnMut()->Result<()>, - consume:impl FnOnce(NativeHeadSampling<'_,'ctx>)->Result, - )->Result{ - origin.validate(session)?;authenticate()?; - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,session.mtp_context()?) - ||!(1..=ROWS).contains(&window.len())||tail.len()as u64!=origin.next_position(){return Err(Error::IdentityMismatch);} + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + origin: &TargetStepOrigin, + tail: &[i32], + window: &[i32], + params: SamplerParams, + path: SamplerPath, + enabled: bool, + mut authenticate: impl FnMut() -> Result<()>, + consume: impl FnOnce(NativeHeadSampling<'_, 'ctx>) -> Result, + ) -> Result { + origin.validate(session)?; + authenticate()?; + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, session.mtp_context()?) + || !(1..=ROWS).contains(&window.len()) + || tail.len() as u64 != origin.next_position() + { + return Err(Error::IdentityMismatch); + } params.validate().map_err(driver)?; - let vocabulary=248320; - if window.iter().any(|&id|id<0||id>=vocabulary)||!self.tail_checked.in_range(tail,vocabulary){return Err(Error::InvalidToken);} - origin.next_position().checked_add(window.len()as u64).ok_or(Error::Overflow)?; - let h=if params.penalty_last_n<=0{0}else{(params.penalty_last_n as usize).min(HISTORY)}; - if h>0{ + let vocabulary = 248320; + if window.iter().any(|&id| id < 0 || id >= vocabulary) || !self.tail_checked.in_range(tail, vocabulary) { + return Err(Error::InvalidToken); + } + origin.next_position().checked_add(window.len() as u64).ok_or(Error::Overflow)?; + let h = if params.penalty_last_n <= 0 { 0 } else { (params.penalty_last_n as usize).min(HISTORY) }; + if h > 0 { // Literal penalty_rows: row t sees tail plus window[0..=t], most // recent token last and the unavailable prefix padded with -1. - for t in 0..window.len(){ - let available=tail.len().checked_add(t+1).ok_or(Error::Overflow)?; - let take=h.min(available); - for j in 0..h{ - let value=if jErr(primary),Ok(value)=>{checked?;Ok(value)}} + let checked = (|| { + origin.validate(session)?; + authenticate() + })(); + if operation.is_err() || checked.is_err() || self.context.is_poisoned() { + self.failed = true; + } + match operation { + Err(primary) => Err(primary), + Ok(value) => { + checked?; + Ok(value) + } + } } - pub(in crate::qwen_forward) fn close(mut self)->Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{ - self.failed=true; - self.device.take().map_or(Ok(()),|device|device.release().map_err(driver)) + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.device.take().map_or(Ok(()), |device| device.release().map_err(driver)) + } +} +impl Drop for OriginalNativePenaltyHistory<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); } } -impl Drop for OriginalNativePenaltyHistory<'_>{fn drop(&mut self){let _=self.close_inner();}} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs index 31a4bad3..5969cd71 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/owner_wall_profile.rs @@ -59,10 +59,7 @@ pub(crate) fn arm() -> Result<(), &'static str> { if state.active || state.in_flight != 0 { return Err("profile already armed"); } - let generation = state - .generation - .checked_add(1) - .ok_or("profile generation overflow")?; + let generation = state.generation.checked_add(1).ok_or("profile generation overflow")?; state.generation = generation; state.totals = [Totals::default(); 6]; state.invalid = false; @@ -85,12 +82,7 @@ pub(crate) fn drain() -> Result<[Sample; 6], &'static str> { } Ok(std::array::from_fn(|index| { let totals = state.totals[index]; - Sample { - label: LABELS[index], - count: totals.count, - total_ns: totals.total_ns, - max_ns: totals.max_ns, - } + Sample { label: LABELS[index], count: totals.count, total_ns: totals.total_ns, max_ns: totals.max_ns } })) }) } @@ -124,11 +116,7 @@ impl Scope { state.in_flight = in_flight; Some((Instant::now(), state.generation)) }); - Self { - stage, - started, - _owner_thread: PhantomData, - } + Self { stage, started, _owner_thread: PhantomData } } } @@ -153,10 +141,7 @@ impl Drop for Scope { return; }; let totals = &mut state.totals[self.stage as usize]; - let update = totals - .count - .checked_add(1) - .zip(totals.total_ns.checked_add(elapsed)); + let update = totals.count.checked_add(1).zip(totals.total_ns.checked_add(elapsed)); if let Some((count, total_ns)) = update { totals.count = count; totals.total_ns = total_ns; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs index ad086dcc..e26a7e88 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu.rs @@ -22,12 +22,7 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { let embedding = source(2560, 17, 8., 64., zero); let streams = source(10240, 19, 9., 64., zero); let history = source(92160, 23, 11., 128., zero); - let snapshot: Vec<_> = embedding - .iter() - .chain(&streams) - .chain(&history) - .map(|x| x.to_bits()) - .collect(); + let snapshot: Vec<_> = embedding.iter().chain(&streams).chain(&history).map(|x| x.to_bits()).collect(); let expected = original(&ctx, &matrices, &embedding, &streams, &history); assert_eq!(ctx.allocated_bytes(), charged); let failed = Rc::new(Cell::new(false)); @@ -50,20 +45,10 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { } exact(&actual.streams, &expected[9].1); exact(&actual.history, &expected[8].1); - assert_eq!( - embedding - .iter() - .chain(&streams) - .chain(&history) - .map(|x| x.to_bits()) - .collect::>(), - snapshot - ); + assert_eq!(embedding.iter().chain(&streams).chain(&history).map(|x| x.to_bits()).collect::>(), snapshot); assert!(!failed.get()); assert_eq!(ctx.allocated_bytes(), charged); - println!( - "PLE_KEY_RETAINED zero={zero} trace_words=166404 returned_words=102400 exact=true" - ); + println!("PLE_KEY_RETAINED zero={zero} trace_words=166404 returned_words=102400 exact=true"); } let embedding = vec![0.125; 2560]; let streams = vec![0.125; 10240]; @@ -75,21 +60,9 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { &matrices.key, &matrices.value, matrices.aux(), - if short == 0 { - &embedding[..2559] - } else { - &embedding - }, - if short == 1 { - &streams[..10239] - } else { - &streams - }, - if short == 2 { - &history[..92159] - } else { - &history - }, + if short == 0 { &embedding[..2559] } else { &embedding }, + if short == 1 { &streams[..10239] } else { &streams }, + if short == 2 { &history[..92159] } else { &history }, Rc::new(Cell::new(false)) ), Err(Error::InvalidDimension) @@ -131,16 +104,7 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { short_value.release().unwrap(); let wrong = ctx.allocate(4).unwrap(); assert!(matches!( - compose( - &ctx, - &matrices.key, - &wrong, - matrices.aux(), - &embedding, - &streams, - &history, - Rc::new(Cell::new(false)) - ), + compose(&ctx, &matrices.key, &wrong, matrices.aux(), &embedding, &streams, &history, Rc::new(Cell::new(false))), Err(Error::InvalidDimension) )); assert!(matches!( @@ -239,34 +203,16 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { matrices.aux[3].copy_from(&conv_bytes).unwrap(); let mut first = Transport::new(&ctx, Rc::new(Cell::new(false))).unwrap(); let finite = owned_key(&mut first, &matrices); - assert_eq!( - first.validate(&finite, Role::KeyNorm), - Err(Error::IdentityMismatch) - ); + assert_eq!(first.validate(&finite, Role::KeyNorm), Err(Error::IdentityMismatch)); let second = Transport::new(&ctx, Rc::new(Cell::new(false))).unwrap(); - assert_eq!( - second.validate(&finite, Role::Key), - Err(Error::IdentityMismatch) - ); + assert_eq!(second.validate(&finite, Role::Key), Err(Error::IdentityMismatch)); second.finish(Ok(())).unwrap(); let bad = first.allocate(4).unwrap(); - assert!(matches!( - first.certify(bad, Role::Key), - Err(Error::InvalidDimension) - )); - assert!(matches!( - first.certify(usize::MAX, Role::Value), - Err(Error::IdentityMismatch) - )); + assert!(matches!(first.certify(bad, Role::Key), Err(Error::InvalidDimension))); + assert!(matches!(first.certify(usize::MAX, Role::Value), Err(Error::IdentityMismatch))); first.release(finite.index).unwrap(); - assert_eq!( - first.validate(&finite, Role::Key), - Err(Error::IdentityMismatch) - ); - assert_eq!( - first.finish::<()>(Err(Error::NonFinite)), - Err(Error::NonFinite) - ); + assert_eq!(first.validate(&finite, Role::Key), Err(Error::IdentityMismatch)); + assert_eq!(first.finish::<()>(Err(Error::NonFinite)), Err(Error::NonFinite)); assert_eq!(ctx.allocated_bytes(), charged); { let mut t = Transport::new(&ctx, Rc::new(Cell::new(false))).unwrap(); @@ -274,27 +220,17 @@ fn retained_key_and_whole_value_match_original_40_tiles_and_fence_abort() { } assert_eq!(ctx.allocated_bytes(), charged); let sticky = Rc::new(Cell::new(true)); - assert!(matches!( - Transport::new(&ctx, sticky.clone()), - Err(Error::CudaExecution) - )); + assert!(matches!(Transport::new(&ctx, sticky.clone()), Err(Error::CudaExecution))); assert!(sticky.get()); - let tiny = device - .create_context(super::super::PLE_DEVICE_PEAK - 1) - .unwrap(); - assert!(matches!( - Transport::new(&tiny, Rc::new(Cell::new(false))), - Err(Error::InputAllocation) - )); + let tiny = device.create_context(super::super::PLE_DEVICE_PEAK - 1).unwrap(); + assert!(matches!(Transport::new(&tiny, Rc::new(Cell::new(false))), Err(Error::InputAllocation))); assert_eq!(tiny.allocated_bytes(), 0); tiny.close().unwrap(); matrices.unchanged(); matrices.close(); assert_eq!(ctx.allocated_bytes(), 0); ctx.close().unwrap(); - println!( - "PLE_KEY_RETAINED total_exact_words=537608 guards=20 aborts=2 cleanup=0 sticky_policy_only=true" - ); + println!("PLE_KEY_RETAINED total_exact_words=537608 guards=20 aborts=2 cleanup=0 sticky_policy_only=true"); } #[path = "ple_key_retained_gpu/bf16_fn.rs"] @@ -302,14 +238,14 @@ mod bf16_fn; #[allow(unused_imports)] use bf16_fn::bf16; #[allow(unused_imports)] -use bf16_fn::source; -#[allow(unused_imports)] use bf16_fn::exact; #[allow(unused_imports)] -use bf16_fn::value_bytes; -#[allow(unused_imports)] -use bf16_fn::run; -#[allow(unused_imports)] use bf16_fn::original; #[allow(unused_imports)] use bf16_fn::owned_key; +#[allow(unused_imports)] +use bf16_fn::run; +#[allow(unused_imports)] +use bf16_fn::source; +#[allow(unused_imports)] +use bf16_fn::value_bytes; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu/bf16_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu/bf16_fn.rs index 82b76691..f855adfe 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu/bf16_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_key_retained_gpu/bf16_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn bf16(rows: usize, columns: usize, seed: usize) -> Vec { (0..rows) .flat_map(|r| { @@ -16,13 +15,15 @@ pub(super) fn bf16(rows: usize, columns: usize, seed: usize) -> Vec { } pub(super) fn source(n: usize, modulus: usize, center: f32, divisor: f32, zero: bool) -> Vec { (0..n) - .map(|i| { - if zero { - if i.is_multiple_of(2) { -0. } else { 0. } - } else { - ((i % modulus) as f32 - center) / divisor - } - }) + .map( + |i| { + if zero { + if i.is_multiple_of(2) { -0. } else { 0. } + } else { + ((i % modulus) as f32 - center) / divisor + } + }, + ) .collect() } pub(super) fn exact(a: &[f32], b: &[f32]) { @@ -91,16 +92,7 @@ pub(super) fn original( // full readback, as in the previous production chain. let emb = ple_upload_f32(ctx, embedding).unwrap(); let key = run(ctx, 10240, |out| { - ctx.bf16_f32( - &matrices.key, - &emb, - out, - Bf16ProjectionShape { - rows: 10240, - columns: 2560, - }, - ) - .unwrap() + ctx.bf16_f32(&matrices.key, &emb, out, Bf16ProjectionShape { rows: 10240, columns: 2560 }).unwrap() }); let mut trace = vec![(Role::Key, key)]; let mut value = Vec::with_capacity(2560); @@ -108,59 +100,43 @@ pub(super) fn original( // One ephemeral literal legacy tile at a time. The new whole matrix // has exactly these bytes, checked after the candidate comparisons. let matrix = ple_upload(ctx, &bf16(64, 2560, tile + 3)).unwrap(); - let output = run(ctx, 64, |out| { - ctx.ple_value_bf16_f32(&emb, &matrix, out).unwrap() - }); + let output = run(ctx, 64, |out| ctx.ple_value_bf16_f32(&emb, &matrix, out).unwrap()); value.extend_from_slice(&output); matrix.release().unwrap(); } trace.push((Role::Value, value.clone().into_boxed_slice())); emb.release().unwrap(); let raw_key = ple_upload_f32(ctx, &trace[0].1).unwrap(); - let key = run(ctx, 10240, |out| { - ctx.ple_grouped_norm_f32(&raw_key, &matrices.aux[0], out) - .unwrap() - }); + let key = run(ctx, 10240, |out| ctx.ple_grouped_norm_f32(&raw_key, &matrices.aux[0], out).unwrap()); raw_key.release().unwrap(); trace.push((Role::KeyNorm, key)); let residual = ple_upload_f32(ctx, streams).unwrap(); - let query = run(ctx, 10240, |out| { - ctx.ple_grouped_norm_f32(&residual, &matrices.aux[1], out) - .unwrap() - }); + let query = run(ctx, 10240, |out| ctx.ple_grouped_norm_f32(&residual, &matrices.aux[1], out).unwrap()); residual.release().unwrap(); trace.push((Role::QueryNorm, query)); let key = ple_upload_f32(ctx, &trace[2].1).unwrap(); let query = ple_upload_f32(ctx, &trace[3].1).unwrap(); - let gate = run(ctx, 4, |out| { - ctx.ple_signed_gate_f32(&key, &query, out).unwrap() - }); + let gate = run(ctx, 4, |out| ctx.ple_signed_gate_f32(&key, &query, out).unwrap()); for b in [query, key] { b.release().unwrap(); } trace.push((Role::Gate, gate)); let value = ple_upload_f32(ctx, &value).unwrap(); let gate = ple_upload_f32(ctx, &trace[4].1).unwrap(); - let gated = run(ctx, 10240, |out| { - ctx.ple_broadcast_f32(&value, &gate, out).unwrap() - }); + let gated = run(ctx, 10240, |out| ctx.ple_broadcast_f32(&value, &gate, out).unwrap()); for b in [gate, value] { b.release().unwrap(); } trace.push((Role::Gated, gated)); let gated = ple_upload_f32(ctx, &trace[5].1).unwrap(); - let normalized = run(ctx, 10240, |out| { - ctx.ple_grouped_norm_f32(&gated, &matrices.aux[2], out) - .unwrap() - }); + let normalized = run(ctx, 10240, |out| ctx.ple_grouped_norm_f32(&gated, &matrices.aux[2], out).unwrap()); gated.release().unwrap(); trace.push((Role::Normalized, normalized)); let prior = ple_upload_f32(ctx, history).unwrap(); let normalized = ple_upload_f32(ctx, &trace[6].1).unwrap(); let mut conv = ctx.allocate(40960).unwrap(); let mut next = ctx.allocate(368640).unwrap(); - ctx.ple_conv_history_f32(&prior, &normalized, &matrices.aux[3], &mut conv, &mut next) - .unwrap(); + ctx.ple_conv_history_f32(&prior, &normalized, &matrices.aux[3], &mut conv, &mut next).unwrap(); trace.push((Role::Conv, ple_download(&conv, 10240).unwrap())); trace.push((Role::History, ple_download(&next, 92160).unwrap())); for b in [next, conv, normalized, prior] { @@ -169,9 +145,7 @@ pub(super) fn original( let residual = ple_upload_f32(ctx, streams).unwrap(); let gated = ple_upload_f32(ctx, &trace[5].1).unwrap(); let conv = ple_upload_f32(ctx, &trace[7].1).unwrap(); - let result = run(ctx, 10240, |out| { - ctx.ple_residual_f32(&residual, &gated, &conv, out).unwrap() - }); + let result = run(ctx, 10240, |out| ctx.ple_residual_f32(&residual, &gated, &conv, out).unwrap()); for b in [conv, gated, residual] { b.release().unwrap(); } @@ -183,16 +157,8 @@ pub(super) fn owned_key(transport: &mut Transport<'_>, matrices: &Matrices<'_>) let ctx = transport.context; transport .produce(Role::Key, |v, out| { - ctx.bf16_f32( - &matrices.key, - at(v, input)?, - out, - Bf16ProjectionShape { - rows: 10240, - columns: 2560, - }, - ) - .map_err(ple_driver_error) + ctx.bf16_f32(&matrices.key, at(v, input)?, out, Bf16ProjectionShape { rows: 10240, columns: 2560 }) + .map_err(ple_driver_error) }) .unwrap() } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs index 58468941..f43412e3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport.rs @@ -1,7 +1,7 @@ //! Invocation-local PLE transport. Key and Value use selected native F32-input MMVF. use super::{ - Bf16ProjectionShape, Context, DeviceBuffer, Error, PLE_HC, PLE_HISTORY, PleCandidate, Result, - ple_budget, ple_download, ple_driver_error, ple_values, + Bf16ProjectionShape, Context, DeviceBuffer, Error, PLE_HC, PLE_HISTORY, PleCandidate, Result, ple_budget, + ple_download, ple_driver_error, ple_values, }; use std::{cell::Cell, rc::Rc}; @@ -46,11 +46,11 @@ mod ple_key_retained_gpu; #[path = "ple_transport/impl_role.rs"] mod impl_role; #[allow(unused_imports)] +use impl_role::admit; +#[allow(unused_imports)] use impl_role::at; #[allow(unused_imports)] pub(super) use impl_role::compose; -#[allow(unused_imports)] -use impl_role::admit; #[path = "ple_transport/compose_inner_fn.rs"] mod compose_inner_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs index c8a0d405..2143d695 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/compose_inner_fn.rs @@ -17,28 +17,12 @@ pub(super) fn compose_inner( let emb = transport.upload(embedding)?; let raw_key = transport.produce(Role::Key, |inputs, output| { context - .bf16_f32( - key_matrix, - at(inputs, emb)?, - output, - Bf16ProjectionShape { - rows: PLE_HC, - columns: 2560, - }, - ) + .bf16_f32(key_matrix, at(inputs, emb)?, output, Bf16ProjectionShape { rows: PLE_HC, columns: 2560 }) .map_err(ple_driver_error) })?; let value = transport.produce(Role::Value, |inputs, output| { context - .bf16_f32( - value_matrix, - at(inputs, emb)?, - output, - Bf16ProjectionShape { - rows: 2560, - columns: 2560, - }, - ) + .bf16_f32(value_matrix, at(inputs, emb)?, output, Bf16ProjectionShape { rows: 2560, columns: 2560 }) .map_err(ple_driver_error) })?; let value_index = transport.validate(&value, Role::Value)?; @@ -47,33 +31,23 @@ pub(super) fn compose_inner( let prior = transport.upload(history)?; let raw_key_index = transport.validate(&raw_key, Role::Key)?; let key = transport.produce(Role::KeyNorm, |inputs, output| { - context - .ple_grouped_norm_f32(at(inputs, raw_key_index)?, aux[0], output) - .map_err(ple_driver_error) + context.ple_grouped_norm_f32(at(inputs, raw_key_index)?, aux[0], output).map_err(ple_driver_error) })?; let query = transport.produce(Role::QueryNorm, |inputs, output| { - context - .ple_grouped_norm_f32(at(inputs, residual)?, aux[1], output) - .map_err(ple_driver_error) + context.ple_grouped_norm_f32(at(inputs, residual)?, aux[1], output).map_err(ple_driver_error) })?; let key_index = transport.validate(&key, Role::KeyNorm)?; let query_index = transport.validate(&query, Role::QueryNorm)?; let gate = transport.produce(Role::Gate, |inputs, output| { - context - .ple_signed_gate_f32(at(inputs, key_index)?, at(inputs, query_index)?, output) - .map_err(ple_driver_error) + context.ple_signed_gate_f32(at(inputs, key_index)?, at(inputs, query_index)?, output).map_err(ple_driver_error) })?; let gate_index = transport.validate(&gate, Role::Gate)?; let gated = transport.produce(Role::Gated, |inputs, output| { - context - .ple_broadcast_f32(at(inputs, value_index)?, at(inputs, gate_index)?, output) - .map_err(ple_driver_error) + context.ple_broadcast_f32(at(inputs, value_index)?, at(inputs, gate_index)?, output).map_err(ple_driver_error) })?; let gated_index = transport.validate(&gated, Role::Gated)?; let normalized = transport.produce(Role::Normalized, |inputs, output| { - context - .ple_grouped_norm_f32(at(inputs, gated_index)?, aux[2], output) - .map_err(ple_driver_error) + context.ple_grouped_norm_f32(at(inputs, gated_index)?, aux[2], output).map_err(ple_driver_error) })?; let normalized_index = transport.validate(&normalized, Role::Normalized)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -102,20 +76,12 @@ pub(super) fn compose_inner( let conv_index = transport.validate(&conv, Role::Conv)?; let result = transport.produce(Role::Streams, |inputs, output| { context - .ple_residual_f32( - at(inputs, residual)?, - at(inputs, gated_index)?, - at(inputs, conv_index)?, - output, - ) + .ple_residual_f32(at(inputs, residual)?, at(inputs, gated_index)?, at(inputs, conv_index)?, output) .map_err(ple_driver_error) })?; transport.validate(&next, Role::History)?; transport.validate(&result, Role::Streams)?; - Ok(PleCandidate { - streams: result.values, - history: next.values, - }) + Ok(PleCandidate { streams: result.values, history: next.values }) } #[cfg(test)] @@ -133,19 +99,8 @@ pub(super) fn compose_observed( admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; let mut transport = Transport::new(context, failed)?; transport.observations = Some(Vec::new()); - let result = compose_inner( - &mut transport, - key_matrix, - value_matrix, - aux, - embedding, - streams, - history, - ); - let observations = transport - .observations - .take() - .ok_or(Error::IdentityMismatch)?; + let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history); + let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?; let output = transport.finish(result)?; Ok((output, observations)) } @@ -165,17 +120,26 @@ pub(in super::super) fn compose_queued( failed: Rc>, ) -> Result { admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; - if failed.get() { return Err(Error::CudaExecution); } + if failed.get() { + return Err(Error::CudaExecution); + } let result = (|| { queue.validate_context(context).map_err(ple_driver_error)?; - let completion = queue.compose(leleka_cuda_driver::PleClosedWeights { - key: key_matrix, value: value_matrix, aux, - }, embedding, streams, history).map_err(ple_driver_error)?; + let completion = queue + .compose( + leleka_cuda_driver::PleClosedWeights { key: key_matrix, value: value_matrix, aux }, + embedding, + streams, + history, + ) + .map_err(ple_driver_error)?; let (streams, history) = completion.into_parts().map_err(|_| Error::NonFinite)?; ple_values(&streams, PLE_HC)?; ple_values(&history, PLE_HISTORY)?; Ok(PleCandidate { streams, history }) })(); - if matches!(result, Err(Error::CudaExecution)) || queue.is_failed() { failed.set(true); } + if matches!(result, Err(Error::CudaExecution)) || queue.is_failed() { + failed.set(true); + } result } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs index 24cb5c76..41d16f09 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/ple_transport/impl_role.rs @@ -37,9 +37,7 @@ impl<'ctx> Transport<'ctx> { if self.failed.get() { return Err(Error::CudaExecution); } - self.buffers - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.buffers.try_reserve(1).map_err(|_| Error::InputAllocation)?; let result = self.context.allocate(bytes).map_err(ple_driver_error); self.note(&result); let index = self.buffers.len(); @@ -62,11 +60,8 @@ impl<'ctx> Transport<'ctx> { bytes.extend_from_slice(&value.to_le_bytes()); } let index = self.allocate(bytes.len())?; - let result = self.buffers[index] - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from(&bytes) - .map_err(ple_driver_error); + let result = + self.buffers[index].as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&bytes).map_err(ple_driver_error); self.note(&result); result?; Ok(index) @@ -81,12 +76,7 @@ impl<'ctx> Transport<'ctx> { let values = result?; #[cfg(test)] self.observe(role, &values)?; - Ok(Finite { - index, - values, - role, - invocation: Rc::clone(&self.invocation), - }) + Ok(Finite { index, values, role, invocation: Rc::clone(&self.invocation) }) } pub(super) fn produce( &mut self, @@ -113,23 +103,16 @@ impl<'ctx> Transport<'ctx> { #[cfg(test)] pub(super) fn observe(&mut self, role: Role, values: &[f32]) -> Result<()> { if let Some(observations) = &mut self.observations { - observations - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + observations.try_reserve(1).map_err(|_| Error::InputAllocation)?; let mut copy = Vec::new(); - copy.try_reserve_exact(values.len()) - .map_err(|_| Error::InputAllocation)?; + copy.try_reserve_exact(values.len()).map_err(|_| Error::InputAllocation)?; copy.extend_from_slice(values); observations.push((role, copy.into_boxed_slice())); } Ok(()) } pub(super) fn release(&mut self, index: usize) -> Result<()> { - let buffer = self - .buffers - .get_mut(index) - .ok_or(Error::IdentityMismatch)? - .take(); + let buffer = self.buffers.get_mut(index).ok_or(Error::IdentityMismatch)?.take(); let result = buffer.map_or(Ok(()), |buffer| buffer.release().map_err(ple_driver_error)); if result.is_err() { self.failed.set(true); @@ -158,14 +141,8 @@ impl Drop for Transport<'_> { let _ = self.close(); } } -pub(super) fn at<'a, 'ctx>( - buffers: &'a [Option>], - index: usize, -) -> Result<&'a DeviceBuffer<'ctx>> { - buffers - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch) +pub(super) fn at<'a, 'ctx>(buffers: &'a [Option>], index: usize) -> Result<&'a DeviceBuffer<'ctx>> { + buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch) } #[allow(clippy::too_many_arguments)] @@ -181,15 +158,7 @@ pub(in super::super) fn compose( ) -> Result { admit(key_matrix, value_matrix, &aux, embedding, streams, history)?; let mut transport = Transport::new(context, failed)?; - let result = compose_inner( - &mut transport, - key_matrix, - value_matrix, - aux, - embedding, - streams, - history, - ); + let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history); transport.finish(result) } pub(super) fn admit( diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs index 3af0a6a0..09ab04e8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prefill_profile.rs @@ -65,10 +65,32 @@ pub(crate) enum Stage { Lend, } const STAGES: [Stage; 26] = [ - Stage::Input, Stage::InputEmbedding, Stage::InputPle, Stage::Initialize, Stage::InitSources, Stage::InitUpload, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::GdnStateIn, - Stage::GdnCompute, Stage::GdnStateOut, Stage::Qsa, - Stage::FfnRead, Stage::Moe, Stage::MoePrepare, Stage::MoeSpans, Stage::MoeRing, Stage::MoeFinish, Stage::Inject, - Stage::Final, Stage::DraftKv, Stage::FinishPreview, Stage::Publish, Stage::Lend, + Stage::Input, + Stage::InputEmbedding, + Stage::InputPle, + Stage::Initialize, + Stage::InitSources, + Stage::InitUpload, + Stage::Ple, + Stage::Validate, + Stage::AttnRead, + Stage::Gdn, + Stage::GdnStateIn, + Stage::GdnCompute, + Stage::GdnStateOut, + Stage::Qsa, + Stage::FfnRead, + Stage::Moe, + Stage::MoePrepare, + Stage::MoeSpans, + Stage::MoeRing, + Stage::MoeFinish, + Stage::Inject, + Stage::Final, + Stage::DraftKv, + Stage::FinishPreview, + Stage::Publish, + Stage::Lend, ]; impl Stage { fn name(self) -> &'static str { @@ -185,8 +207,20 @@ pub(crate) fn end_chunk(first: u64, tokens: usize) { } // Time of the chunk outside every top-level span (the nested moe.* and inject spans are excluded). let top = [ - Stage::Input, Stage::Initialize, Stage::Ple, Stage::Validate, Stage::AttnRead, Stage::Gdn, Stage::Qsa, - Stage::FfnRead, Stage::Moe, Stage::Final, Stage::DraftKv, Stage::FinishPreview, Stage::Publish, Stage::Lend, + Stage::Input, + Stage::Initialize, + Stage::Ple, + Stage::Validate, + Stage::AttnRead, + Stage::Gdn, + Stage::Qsa, + Stage::FfnRead, + Stage::Moe, + Stage::Final, + Stage::DraftKv, + Stage::FinishPreview, + Stage::Publish, + Stage::Lend, ]; let covered: Duration = top.iter().map(|s| acc[s.index()]).sum(); line.push_str(&format!(" other={:.1}", ms(total.saturating_sub(covered)))); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs index cd9a46bf..8e6625b1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows.rs @@ -2,45 +2,82 @@ //! Does not manufacture scalar ResidualReady/PleReady or intermediate history. //! Root's chronological chunk journal authenticates each current row before //! consuming a phase and publishes only the completed whole prompt state. -use super::{contract::{Dimension,Error,LayerId,Result,TokenLayer}, - dense_weight_cache::DenseWeightCache,input::{InputReady,PlePrior}, - session::QwenStepTxn}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,GrRole,ModelBinding}; -use super::session::original_prompt::{OriginalPromptTxn,OriginalPromptPhase,OriginalPromptRowKey}; +use super::contract::{Position, TokenId}; +use super::session::original_prompt::{OriginalPromptPhase, OriginalPromptRowKey, OriginalPromptTxn}; +use super::{ + contract::{Dimension, Error, LayerId, Result, TokenLayer}, + dense_weight_cache::DenseWeightCache, + input::{InputReady, PlePrior}, + session::QwenStepTxn, +}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding}; +use leleka_cuda_driver::{ + Context, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual, OriginalDeviceResidual, + OriginalPleHistory, OriginalPromptDevice, OriginalPromptRows, +}; use std::rc::Rc; -use super::contract::{TokenId,Position}; -use leleka_cuda_driver::{Context,OriginalPromptRows,OriginalPromptDevice, - OriginalDeviceResidual,OriginalDeviceNormedResidual,OriginalDeviceGrRead,OriginalDeviceBlock,OriginalPleHistory}; -pub(in crate::qwen_forward) struct PromptDeviceSource<'source,'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>, - input:SourceInput<'source>,original:Option, +pub(in crate::qwen_forward) struct PromptDeviceSource<'source, 'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + input: SourceInput<'source>, + original: Option, +} +enum SourceInput<'source> { + Borrowed(&'source InputReady), + Owned(Rc), +} +struct Sources<'source, 'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + rows: Vec>, + role: GrRole, + validated: usize, +} +pub(in crate::qwen_forward) struct PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { + sources: Sources<'source, 'ctx>, + device: OriginalDeviceResidual<'arena, 'loan, 'ctx>, +} +pub(in crate::qwen_forward) struct PromptDeviceNormedRows<'weight, 'source, 'arena, 'loan, 'ctx> { + sources: Sources<'source, 'ctx>, + device: OriginalDeviceNormedResidual<'weight, 'arena, 'loan, 'ctx>, +} +pub(in crate::qwen_forward) struct PromptDeviceRead<'source, 'arena, 'loan, 'ctx> { + sources: Sources<'source, 'ctx>, + device: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, } -enum SourceInput<'source>{Borrowed(&'source InputReady),Owned(Rc)} -struct Sources<'source,'ctx>{binding:BindingIdentity,context:&'ctx Context<'ctx>,rows:Vec>,role:GrRole,validated:usize} -pub(in crate::qwen_forward) struct PromptDeviceRows<'source,'arena,'loan,'ctx>{sources:Sources<'source,'ctx>,device:OriginalDeviceResidual<'arena,'loan,'ctx>} -pub(in crate::qwen_forward) struct PromptDeviceNormedRows<'weight,'source,'arena,'loan,'ctx>{sources:Sources<'source,'ctx>,device:OriginalDeviceNormedResidual<'weight,'arena,'loan,'ctx>} -pub(in crate::qwen_forward) struct PromptDeviceRead<'source,'arena,'loan,'ctx>{sources:Sources<'source,'ctx>,device:OriginalDeviceGrRead<'arena,'loan,'ctx>} /// Actual last-row product of the complete physical 48-layer prompt. Sole /// construction below consumes the arena product and the authenticated phase. -pub(in crate::qwen_forward) struct PromptDeviceFinal{ - binding:BindingIdentity,phase:Rc,token:TokenId,position:Position,product:FinalProduct, - lease_identity:leleka_cuda_driver::OriginalPromptLeaseIdentity, +pub(in crate::qwen_forward) struct PromptDeviceFinal { + binding: BindingIdentity, + phase: Rc, + token: TokenId, + position: Position, + product: FinalProduct, + lease_identity: leleka_cuda_driver::OriginalPromptLeaseIdentity, } // Conditioning prefill retains the actual all-row device R. It has no output // head and does not download its final row. This variant is an affine physical // phase descriptor, never a certificate for host float values. -enum FinalProduct{Host(Box<[f32]>),DeviceConditioning{known_next:TokenId}} +enum FinalProduct { + Host(Box<[f32]>), + DeviceConditioning { known_next: TokenId }, +} /// One actual layer-one prior and end-only history owner. This cannot construct /// a PlePending for an earlier row or impersonate a scalar host PleReady. -pub(in crate::qwen_forward) struct PromptPleHistory<'ctx>{binding:BindingIdentity,prior:PlePrior,device:OriginalPleHistory<'ctx>,completed_rows:Option} +pub(in crate::qwen_forward) struct PromptPleHistory<'ctx> { + binding: BindingIdentity, + prior: PlePrior, + device: OriginalPleHistory<'ctx>, + completed_rows: Option, +} -#[path="original_mtp_prefill.rs"] +#[path = "original_mtp_prefill.rs"] mod mtp_prefill; -pub(in crate::qwen_forward) use mtp_prefill::{OriginalDraftKvPending,OriginalPromptDraftOutcome}; +pub(in crate::qwen_forward) use mtp_prefill::{OriginalDraftKvPending, OriginalPromptDraftOutcome}; -mod impl_std_ops_deref; mod impl_promptdeviceread; +mod impl_std_ops_deref; #[allow(unused_imports)] use impl_promptdeviceread::produce_original_gdn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs index 8db89fce..a3e96a2a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread.rs @@ -3,237 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'source,'arena,'loan,'ctx> PromptDeviceRead<'source,'arena,'loan,'ctx>{ - pub(in crate::qwen_forward) fn validate_original_rows(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>)->Result<()>{ - self.sources.original_all(binding,cache,true) - } - pub(in crate::qwen_forward) fn validate_row(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>,index:usize,role:GrRole)->Result{if index!=self.sources.validated{return Err(Error::IdentityMismatch)}let id=self.sources.current(binding,cache,txn,index,role)?;self.sources.validated+=1;Ok(id)} - pub(in crate::qwen_forward) fn device(&self)->&OriginalDeviceGrRead<'arena,'loan,'ctx>{&self.device} - /// Full prompt GDN projections/conv/recurrence/Out consume the real Read. - /// Only its genuine completed end recurrence/history enters the journal. - pub(in crate::qwen_forward) fn complete_original_gdn( - self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,txn:&OriginalPromptTxn<'_, '_>, - producer:&mut OriginalPromptDevice<'ctx>,gdn:&mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Attention(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let layer=LayerId::new(layer as u64,Dimension::new(48)?)?; - let context=self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase|!phase.same(&txn.phase())){return Err(Error::IdentityMismatch)} - self.complete_with(binding,dense,producer,GrRole::Ffn(layer.get()),|read|{ - let prior=txn.gdn_prior(layer)?; - let(start,rows)=super::super::session::chunk::GdnChunkStart::from_original_prompt(txn,layer,&prior)?; - let mut owner=super::super::gdn::chunk_device::GdnChunkDevice::new(binding,context,dense,start.clone())?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let(block,edges)=super::super::gdn::GdnStage::produce_prompt_device(binding,layer,dense,context, - &mut owner,rows,read,gdn,&mut workspace)?; - drop(workspace); - let seal=super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn,&start,edges)?; - let next=owner.finish(seal,binding,dense)?; - txn.stage_gdn(&prior,next)?;Ok(block) - }) - } - pub(in crate::qwen_forward) fn complete_original_gdn_normed<'weight>( - self,binding:&ModelBinding,dense:&'weight DenseWeightCache<'ctx>,txn:&OriginalPromptTxn<'_, '_>, - producer:&mut OriginalPromptDevice<'ctx>,gdn:&mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Attention(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let layer=LayerId::new(layer as u64,Dimension::new(48)?)?;let context=self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase|!phase.same(&txn.phase())){return Err(Error::IdentityMismatch)} - self.complete_with_normed(binding,dense,producer,GrRole::Ffn(layer.get()),|read|{ - produce_original_gdn(binding,dense,txn,context,layer,read,gdn) - }) - } - pub(in crate::qwen_forward) fn complete_original_qsa( - self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>,txn:&OriginalPromptTxn<'_, 'ctx>, - producer:&mut OriginalPromptDevice<'ctx>,layer_owner:&mut super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa:&mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - transport:&mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>,attention:&mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Attention(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let layer=LayerId::new(layer as u64,Dimension::new(48)?)?;let context=self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase|!phase.same(&txn.phase())){return Err(Error::IdentityMismatch)} - self.complete_with(binding,dense,producer,GrRole::Ffn(layer.get()),|read|{ - produce_original_qsa(binding,dense,txn,context,layer,read,layer_owner,qsa,transport,attention) - }) - } - pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>( - self,binding:&ModelBinding,dense:&'weight DenseWeightCache<'ctx>,txn:&OriginalPromptTxn<'_, 'ctx>, - producer:&mut OriginalPromptDevice<'ctx>,layer_owner:&mut super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa:&mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, - transport:&mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>,attention:&mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Attention(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let layer=LayerId::new(layer as u64,Dimension::new(48)?)?;let context=self.sources.context; - if self.sources.original_phase()?.is_none_or(|phase|!phase.same(&txn.phase())){return Err(Error::IdentityMismatch)} - self.complete_with_normed(binding,dense,producer,GrRole::Ffn(layer.get()),|read|{ - produce_original_qsa(binding,dense,txn,context,layer,read,layer_owner,qsa,transport,attention) - }) - } - /// Complete actual FFN arithmetic on the same physical arena, then the - /// actual following GR injection. Every current row must have passed the - /// chronological session validation, exactly as for attention consumers. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in crate::qwen_forward) fn complete_original_moe( - self, binding:&ModelBinding, dense:&DenseWeightCache<'ctx>, - cache:&mut super::super::moe_weight_cache::MoeWeightCache<'ctx>, - producer:&mut OriginalPromptDevice<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Ffn(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let id=LayerId::new(u64::from(layer),Dimension::new(u64::from(binding.layer_count()))?)?; - let next=layer.checked_add(1).ok_or(Error::Overflow)?; - let role=if next==binding.layer_count(){GrRole::Final}else{GrRole::Attention(next)}; - let context=self.sources.context; - self.complete_with(binding,dense,producer,role,|read|{ - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - cache.original_prompt_moe(binding,dense,id,read,&mut workspace) - }) - } - /// Original fused injection carries the next gamma norm on device. PLE - /// layer-one and final-head boundaries use the plain variant above. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in crate::qwen_forward) fn complete_original_moe_normed<'weight>( - self, binding:&ModelBinding, dense:&'weight DenseWeightCache<'ctx>, - cache:&mut super::super::moe_weight_cache::MoeWeightCache<'ctx>, - producer:&mut OriginalPromptDevice<'ctx>, - )->Result>{ - let layer=match self.sources.role{GrRole::Ffn(layer)=>layer,_=>return Err(Error::IdentityMismatch)}; - let id=LayerId::new(u64::from(layer),Dimension::new(u64::from(binding.layer_count()))?)?; - let next=layer.checked_add(1).ok_or(Error::Overflow)?; - let context=self.sources.context; - self.complete_with_normed(binding,dense,producer,GrRole::Attention(next),|read|{ - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - cache.original_prompt_moe(binding,dense,id,read,&mut workspace) - }) - } - /// Actual producer must consume `device` and return its affine completed - /// Block. Root retains chronological source proof and all causal journals. - pub(in crate::qwen_forward) fn complete_with(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,producer:&mut OriginalPromptDevice<'ctx>,next_role:GrRole,produce:impl FnOnce(OriginalDeviceGrRead<'arena,'loan,'ctx>)->Result>)->Result>{ - self.sources.validate(binding,cache)?; - if self.sources.validated!=self.sources.rows.len(){return Err(Error::IdentityMismatch)} - let expected=match self.sources.role{GrRole::Attention(l)=>GrRole::Ffn(l),GrRole::Ffn(l)=>{ - let next=l.checked_add(1).ok_or(Error::Overflow)?; - if next==binding.layer_count(){GrRole::Final}else{GrRole::Attention(next)} - },GrRole::Final=>return Err(Error::IdentityMismatch)}; - if next_role!=expected{return Err(Error::IdentityMismatch)} - let identity=self.device.lease_identity(); - let block=produce(self.device)?; - if !identity.same_lease(&block.lease_identity()){return Err(Error::IdentityMismatch)} - self.sources.validate(binding,cache)?; - let context=self.sources.context; - let inject_span=super::super::prefill_profile::span(super::super::prefill_profile::Stage::Inject,Some(context as &dyn super::super::prefill_profile::Drain)); - let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?;producer.inject_gr(block,&mut workspace).map_err(micro_driver_error)})(); - drop(inject_span); - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - let device=result?;self.sources.validate(binding,cache)?; - if let Some(phase)=self.sources.original_phase()?{phase.inject(self.sources.role,next_role)?;} - let mut sources=self.sources;sources.role=next_role;sources.validated=0; - Ok(PromptDeviceRows{sources,device}) - } -} -/// End-state is staged only from the same completed whole-layer producer. -pub(super) fn produce_original_gdn<'arena,'loan,'ctx>(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,context:&'ctx Context<'ctx>,layer:LayerId, - read:OriginalDeviceGrRead<'arena,'loan,'ctx>,gdn:&mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, -)->Result>{ - use super::super::prefill_profile::{span,Stage as P,Drain}; - let drain=Some(context as &dyn Drain); - let timed=leleka_cuda_driver::command_profile::enabled();let mut mark=std::time::Instant::now(); - let mut lap=|index:usize,label:&'static str|{if timed{leleka_cuda_driver::command_profile::record("gdn-host",index,label,mark.elapsed());mark=std::time::Instant::now();}}; - let state_in=span(P::GdnStateIn,drain); - let prior=txn.gdn_prior(layer)?; - lap(1,"in: gdn_prior"); - let(start,rows)=super::super::session::chunk::GdnChunkStart::from_original_prompt(txn,layer,&prior)?; - lap(2,"in: chunk start + row keys"); - let mut owner=super::super::gdn::chunk_device::GdnChunkDevice::new(binding,context,dense,start.clone())?; - lap(3,"in: chunk device (state upload, alloc)"); - drop(state_in); - let compute=span(P::GdnCompute,drain); - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let(block,edges)=super::super::gdn::GdnStage::produce_prompt_device(binding,layer,dense,context, - &mut owner,rows,read,gdn,&mut workspace)?; - drop(workspace); - drop(compute); - lap(4,"compute: produce_prompt_device"); - let _state_out=span(P::GdnStateOut,drain); - let seal=super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn,&start,edges)?; - lap(5,"out: seal (row edges)"); - let next=owner.finish(seal,binding,dense)?;lap(6,"out: owner.finish (download, mirror)");txn.stage_gdn(&prior,next)?;lap(7,"out: stage_gdn");Ok(block) -} -#[allow(clippy::too_many_arguments)] -pub(super) fn produce_original_qsa<'arena,'loan,'ctx>(binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, 'ctx>,context:&'ctx Context<'ctx>,layer:LayerId,read:OriginalDeviceGrRead<'arena,'loan,'ctx>, - layer_owner:&mut super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, - qsa:&mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>,transport:&mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, - attention:&mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, -)->Result>{ - let timed=leleka_cuda_driver::command_profile::enabled();let mut mark=std::time::Instant::now(); - let mut lap=|index:usize,label:&'static str|{if timed{leleka_cuda_driver::command_profile::record("qsa-host",index,label,mark.elapsed());mark=std::time::Instant::now();}}; - txn.validate_phase(GrRole::Attention(layer.get()),true)?; - let inputs=txn.input_references()?;let prior=txn.qsa_prior(binding,layer)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - lap(1,"host setup"); - // the layer's prior-KV prefix copy starts on a side stream now and overlaps the projections and the indexer (a no-op unless LELEKA_PREFILL_QSA_PREFETCH) - layer_owner.begin_prefix(&mut workspace,transport,&prior,&read)?; - let selected=match layer_owner.prepare(binding,dense,txn.original_session(),&inputs,&prior,qsa,read,&mut workspace){ - Ok(selected)=>selected, - Err(error)=>{let _=transport.cancel_prefix();return Err(error)} - }; - lap(2,"prepare (index, projections)"); - let(block,completed)=selected.complete(binding,dense,txn.original_session(),&mut workspace,transport,attention)?; - lap(3,"complete (kv, attention, out)"); - completed.validate_rows(binding,dense,txn.original_session(),&inputs)?; - lap(4,"validate_rows"); - let seal=completed.seal_prefix(binding,dense,txn.original_session(),&inputs,qsa,&mut workspace,txn.len())?; - lap(5,"seal_prefix"); - drop(workspace);txn.stage_qsa(binding,dense,seal)?;lap(6,"stage_qsa");Ok(block) -} -impl<'weight,'source,'arena,'loan,'ctx> PromptDeviceNormedRows<'weight,'source,'arena,'loan,'ctx>{ - pub(in crate::qwen_forward) fn validate_original_rows(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>)->Result<()>{ - self.sources.original_all(binding,cache,false) - } - pub(in crate::qwen_forward) fn validate_row(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>,index:usize,role:GrRole)->Result{ - if index!=self.sources.validated{return Err(Error::IdentityMismatch)} - let id=self.sources.current(binding,cache,txn,index,role)?;self.sources.validated+=1;Ok(id) - } - pub(in crate::qwen_forward) fn read(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,producer:&mut OriginalPromptDevice<'ctx>)->Result>{ - self.sources.validate(binding,cache)?;if self.sources.validated!=self.sources.rows.len(){return Err(Error::IdentityMismatch)} - if let Some(phase)=self.sources.original_phase()?{phase.prepare_read(self.sources.role)?;} - let context=self.sources.context;let resident=cache.gr(binding,self.sources.role)?; - if !resident.weights.matches(&binding.identity(),self.sources.role){return Err(Error::IdentityMismatch)} - let [gamma,down,up,inject]=cache.gr_buffers(resident)?.map(|w|w.ok_or(Error::IdentityMismatch)); - let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.read_gr_normed(self.device,&mut workspace,[gamma?,down?,up?,inject?],resident.weights.epsilon()).map_err(micro_driver_error)})(); - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - let device=result?;self.sources.validate(binding,cache)?; - if let Some(phase)=self.sources.original_phase()?{phase.read(self.sources.role)?;} - let mut sources=self.sources;sources.validated=0;Ok(PromptDeviceRead{sources,device}) - } -} -impl<'source,'arena,'loan,'ctx> PromptDeviceRead<'source,'arena,'loan,'ctx>{ - /// Original caller eligibility additionally excludes cvec/unfused modes. - /// This selected native path cannot carry a norm across the actual PLE - /// boundary or final layer. Those use complete_with and plain next read. - pub(in crate::qwen_forward) fn complete_with_normed<'weight>(self,binding:&ModelBinding,cache:&'weight DenseWeightCache<'ctx>,producer:&mut OriginalPromptDevice<'ctx>,next_role:GrRole,produce:impl FnOnce(OriginalDeviceGrRead<'arena,'loan,'ctx>)->Result>)->Result>{ - self.sources.validate(binding,cache)?; - if self.sources.validated!=self.sources.rows.len(){return Err(Error::IdentityMismatch)} - let expected=match self.sources.role{GrRole::Attention(l)=>GrRole::Ffn(l),GrRole::Ffn(l)=>GrRole::Attention(l.checked_add(1).ok_or(Error::Overflow)?),GrRole::Final=>return Err(Error::IdentityMismatch)}; - let layer=match next_role{GrRole::Attention(l)|GrRole::Ffn(l)=>l,GrRole::Final=>return Err(Error::IdentityMismatch)}; - if next_role!=expected||next_role==GrRole::Attention(1)||layer>=binding.layer_count(){return Err(Error::IdentityMismatch)} - let resident=cache.gr(binding,next_role)?; - if !resident.weights.matches(&binding.identity(),next_role){return Err(Error::IdentityMismatch)} - let gamma=cache.gr_buffers(resident)?[0].ok_or(Error::IdentityMismatch)?; - let identity=self.device.lease_identity(); - let block=produce(self.device)?; - if !identity.same_lease(&block.lease_identity()){return Err(Error::IdentityMismatch)} - self.sources.validate(binding,cache)?;let context=self.sources.context; - let inject_span=super::super::prefill_profile::span(super::super::prefill_profile::Stage::Inject,Some(context as &dyn super::super::prefill_profile::Drain)); - let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.inject_gr_fused(block,&mut workspace,gamma,resident.weights.epsilon()).map_err(micro_driver_error)})(); - drop(inject_span); - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - let device=result?;self.sources.validate(binding,cache)?; - if let Some(phase)=self.sources.original_phase()?{phase.inject(self.sources.role,next_role)?;} - let mut sources=self.sources;sources.role=next_role;sources.validated=0; - Ok(PromptDeviceNormedRows{sources,device}) - } -} +mod impl_promptdeviceread_2; +mod produce_original_gdn_fn; +#[allow(unused_imports)] +pub(super) use produce_original_gdn_fn::produce_original_gdn; +#[allow(unused_imports)] +pub(super) use produce_original_gdn_fn::produce_original_qsa; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs new file mode 100644 index 00000000..7565a110 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/impl_promptdeviceread_2.rs @@ -0,0 +1,245 @@ +//! Moved out of the parent module by STRA-338: impl PromptDeviceRead. + +#[allow(unused_imports)] +use super::*; + +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx> { + pub(in crate::qwen_forward) fn validate_original_rows( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + ) -> Result<()> { + self.sources.original_all(binding, cache, true) + } + pub(in crate::qwen_forward) fn validate_row( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + index: usize, + role: GrRole, + ) -> Result { + if index != self.sources.validated { + return Err(Error::IdentityMismatch); + } + let id = self.sources.current(binding, cache, txn, index, role)?; + self.sources.validated += 1; + Ok(id) + } + pub(in crate::qwen_forward) fn device(&self) -> &OriginalDeviceGrRead<'arena, 'loan, 'ctx> { + &self.device + } + /// Full prompt GDN projections/conv/recurrence/Out consume the real Read. + /// Only its genuine completed end recurrence/history enters the journal. + pub(in crate::qwen_forward) fn complete_original_gdn( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + producer: &mut OriginalPromptDevice<'ctx>, + gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Attention(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; + let context = self.sources.context; + if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { + return Err(Error::IdentityMismatch); + } + self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { + let prior = txn.gdn_prior(layer)?; + let (start, rows) = + super::super::super::session::chunk::GdnChunkStart::from_original_prompt(txn, layer, &prior)?; + let mut owner = + super::super::super::gdn::chunk_device::GdnChunkDevice::new(binding, context, dense, start.clone())?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let (block, edges) = super::super::super::gdn::GdnStage::produce_prompt_device( + binding, + layer, + dense, + context, + &mut owner, + rows, + read, + gdn, + &mut workspace, + )?; + drop(workspace); + let seal = super::super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn, &start, edges)?; + let next = owner.finish(seal, binding, dense)?; + txn.stage_gdn(&prior, next)?; + Ok(block) + }) + } + pub(in crate::qwen_forward) fn complete_original_gdn_normed<'weight>( + self, + binding: &ModelBinding, + dense: &'weight DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + producer: &mut OriginalPromptDevice<'ctx>, + gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Attention(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; + let context = self.sources.context; + if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { + return Err(Error::IdentityMismatch); + } + self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { + produce_original_gdn(binding, dense, txn, context, layer, read, gdn) + }) + } + pub(in crate::qwen_forward) fn complete_original_qsa( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, 'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, + qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Attention(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; + let context = self.sources.context; + if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { + return Err(Error::IdentityMismatch); + } + self.complete_with(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { + produce_original_qsa(binding, dense, txn, context, layer, read, layer_owner, qsa, transport, attention) + }) + } + pub(in crate::qwen_forward) fn complete_original_qsa_normed<'weight>( + self, + binding: &ModelBinding, + dense: &'weight DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, 'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, + qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Attention(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(layer as u64, Dimension::new(48)?)?; + let context = self.sources.context; + if self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) { + return Err(Error::IdentityMismatch); + } + self.complete_with_normed(binding, dense, producer, GrRole::Ffn(layer.get()), |read| { + produce_original_qsa(binding, dense, txn, context, layer, read, layer_owner, qsa, transport, attention) + }) + } + /// Complete actual FFN arithmetic on the same physical arena, then the + /// actual following GR injection. Every current row must have passed the + /// chronological session validation, exactly as for attention consumers. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn complete_original_moe( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + cache: &mut super::super::super::moe_weight_cache::MoeWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Ffn(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let id = LayerId::new(u64::from(layer), Dimension::new(u64::from(binding.layer_count()))?)?; + let next = layer.checked_add(1).ok_or(Error::Overflow)?; + let role = if next == binding.layer_count() { GrRole::Final } else { GrRole::Attention(next) }; + let context = self.sources.context; + self.complete_with(binding, dense, producer, role, |read| { + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + cache.original_prompt_moe(binding, dense, id, read, &mut workspace) + }) + } + /// Original fused injection carries the next gamma norm on device. PLE + /// layer-one and final-head boundaries use the plain variant above. + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn complete_original_moe_normed<'weight>( + self, + binding: &ModelBinding, + dense: &'weight DenseWeightCache<'ctx>, + cache: &mut super::super::super::moe_weight_cache::MoeWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + ) -> Result> { + let layer = match self.sources.role { + GrRole::Ffn(layer) => layer, + _ => return Err(Error::IdentityMismatch), + }; + let id = LayerId::new(u64::from(layer), Dimension::new(u64::from(binding.layer_count()))?)?; + let next = layer.checked_add(1).ok_or(Error::Overflow)?; + let context = self.sources.context; + self.complete_with_normed(binding, dense, producer, GrRole::Attention(next), |read| { + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + cache.original_prompt_moe(binding, dense, id, read, &mut workspace) + }) + } + /// Actual producer must consume `device` and return its affine completed + /// Block. Root retains chronological source proof and all causal journals. + pub(in crate::qwen_forward) fn complete_with( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + next_role: GrRole, + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, + ) -> Result> { + self.sources.validate(binding, cache)?; + if self.sources.validated != self.sources.rows.len() { + return Err(Error::IdentityMismatch); + } + let expected = match self.sources.role { + GrRole::Attention(l) => GrRole::Ffn(l), + GrRole::Ffn(l) => { + let next = l.checked_add(1).ok_or(Error::Overflow)?; + if next == binding.layer_count() { GrRole::Final } else { GrRole::Attention(next) } + } + GrRole::Final => return Err(Error::IdentityMismatch), + }; + if next_role != expected { + return Err(Error::IdentityMismatch); + } + let identity = self.device.lease_identity(); + let block = produce(self.device)?; + if !identity.same_lease(&block.lease_identity()) { + return Err(Error::IdentityMismatch); + } + self.sources.validate(binding, cache)?; + let context = self.sources.context; + let inject_span = super::super::super::prefill_profile::span( + super::super::super::prefill_profile::Stage::Inject, + Some(context as &dyn super::super::super::prefill_profile::Drain), + ); + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer.inject_gr(block, &mut workspace).map_err(micro_driver_error) + })(); + drop(inject_span); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + let device = result?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.inject(self.sources.role, next_role)?; + } + let mut sources = self.sources; + sources.role = next_role; + sources.validated = 0; + Ok(PromptDeviceRows { sources, device }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs new file mode 100644 index 00000000..fb8a9e9c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptdeviceread/produce_original_gdn_fn.rs @@ -0,0 +1,235 @@ +//! Moved out of the parent module by STRA-338: fn produce_original_gdn, fn produce_original_qsa, impl PromptDeviceNormedRows, impl PromptDeviceRead. + +#[allow(unused_imports)] +use super::*; + +/// End-state is staged only from the same completed whole-layer producer. +pub(in super::super) fn produce_original_gdn<'arena, 'loan, 'ctx>( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + context: &'ctx Context<'ctx>, + layer: LayerId, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + gdn: &mut leleka_cuda_driver::OriginalGdnPromptDevice<'ctx>, +) -> Result> { + use super::super::super::prefill_profile::{Drain, Stage as P, span}; + let drain = Some(context as &dyn Drain); + let timed = leleka_cuda_driver::command_profile::enabled(); + let mut mark = std::time::Instant::now(); + let mut lap = |index: usize, label: &'static str| { + if timed { + leleka_cuda_driver::command_profile::record("gdn-host", index, label, mark.elapsed()); + mark = std::time::Instant::now(); + } + }; + let state_in = span(P::GdnStateIn, drain); + let prior = txn.gdn_prior(layer)?; + lap(1, "in: gdn_prior"); + let (start, rows) = super::super::super::session::chunk::GdnChunkStart::from_original_prompt(txn, layer, &prior)?; + lap(2, "in: chunk start + row keys"); + let mut owner = + super::super::super::gdn::chunk_device::GdnChunkDevice::new(binding, context, dense, start.clone())?; + lap(3, "in: chunk device (state upload, alloc)"); + drop(state_in); + let compute = span(P::GdnCompute, drain); + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let (block, edges) = super::super::super::gdn::GdnStage::produce_prompt_device( + binding, + layer, + dense, + context, + &mut owner, + rows, + read, + gdn, + &mut workspace, + )?; + drop(workspace); + drop(compute); + lap(4, "compute: produce_prompt_device"); + let _state_out = span(P::GdnStateOut, drain); + let seal = super::super::super::session::chunk::GdnChunkSeal::from_original_prompt(txn, &start, edges)?; + lap(5, "out: seal (row edges)"); + let next = owner.finish(seal, binding, dense)?; + lap(6, "out: owner.finish (download, mirror)"); + txn.stage_gdn(&prior, next)?; + lap(7, "out: stage_gdn"); + Ok(block) +} +#[allow(clippy::too_many_arguments)] +pub(in super::super) fn produce_original_qsa<'arena, 'loan, 'ctx>( + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, 'ctx>, + context: &'ctx Context<'ctx>, + layer: LayerId, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + layer_owner: &mut super::super::super::qsa_index::prompt_device::resident_device::ResidentQsaLayer<'ctx>, + qsa: &mut leleka_cuda_driver::OriginalQsaResidentPromptDevice<'ctx>, + transport: &mut leleka_cuda_driver::OriginalQsaResidentTransport<'ctx>, + attention: &mut leleka_cuda_driver::OriginalQsaResidentAttention<'ctx>, +) -> Result> { + let timed = leleka_cuda_driver::command_profile::enabled(); + let mut mark = std::time::Instant::now(); + let mut lap = |index: usize, label: &'static str| { + if timed { + leleka_cuda_driver::command_profile::record("qsa-host", index, label, mark.elapsed()); + mark = std::time::Instant::now(); + } + }; + txn.validate_phase(GrRole::Attention(layer.get()), true)?; + let inputs = txn.input_references()?; + let prior = txn.qsa_prior(binding, layer)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + lap(1, "host setup"); + // the layer's prior-KV prefix copy starts on a side stream now and overlaps the projections and the indexer (a no-op unless LELEKA_PREFILL_QSA_PREFETCH) + layer_owner.begin_prefix(&mut workspace, transport, &prior, &read)?; + let selected = + match layer_owner.prepare(binding, dense, txn.original_session(), &inputs, &prior, qsa, read, &mut workspace) { + Ok(selected) => selected, + Err(error) => { + let _ = transport.cancel_prefix(); + return Err(error); + } + }; + lap(2, "prepare (index, projections)"); + let (block, completed) = + selected.complete(binding, dense, txn.original_session(), &mut workspace, transport, attention)?; + lap(3, "complete (kv, attention, out)"); + completed.validate_rows(binding, dense, txn.original_session(), &inputs)?; + lap(4, "validate_rows"); + let seal = + completed.seal_prefix(binding, dense, txn.original_session(), &inputs, qsa, &mut workspace, txn.len())?; + lap(5, "seal_prefix"); + drop(workspace); + txn.stage_qsa(binding, dense, seal)?; + lap(6, "stage_qsa"); + Ok(block) +} +impl<'weight, 'source, 'arena, 'loan, 'ctx> PromptDeviceNormedRows<'weight, 'source, 'arena, 'loan, 'ctx> { + pub(in crate::qwen_forward) fn validate_original_rows( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + ) -> Result<()> { + self.sources.original_all(binding, cache, false) + } + pub(in crate::qwen_forward) fn validate_row( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + index: usize, + role: GrRole, + ) -> Result { + if index != self.sources.validated { + return Err(Error::IdentityMismatch); + } + let id = self.sources.current(binding, cache, txn, index, role)?; + self.sources.validated += 1; + Ok(id) + } + pub(in crate::qwen_forward) fn read( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + ) -> Result> { + self.sources.validate(binding, cache)?; + if self.sources.validated != self.sources.rows.len() { + return Err(Error::IdentityMismatch); + } + if let Some(phase) = self.sources.original_phase()? { + phase.prepare_read(self.sources.role)?; + } + let context = self.sources.context; + let resident = cache.gr(binding, self.sources.role)?; + if !resident.weights.matches(&binding.identity(), self.sources.role) { + return Err(Error::IdentityMismatch); + } + let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer + .read_gr_normed(self.device, &mut workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) + .map_err(micro_driver_error) + })(); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + let device = result?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.read(self.sources.role)?; + } + let mut sources = self.sources; + sources.validated = 0; + Ok(PromptDeviceRead { sources, device }) + } +} +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRead<'source, 'arena, 'loan, 'ctx> { + /// Original caller eligibility additionally excludes cvec/unfused modes. + /// This selected native path cannot carry a norm across the actual PLE + /// boundary or final layer. Those use complete_with and plain next read. + pub(in crate::qwen_forward) fn complete_with_normed<'weight>( + self, + binding: &ModelBinding, + cache: &'weight DenseWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + next_role: GrRole, + produce: impl FnOnce(OriginalDeviceGrRead<'arena, 'loan, 'ctx>) -> Result>, + ) -> Result> { + self.sources.validate(binding, cache)?; + if self.sources.validated != self.sources.rows.len() { + return Err(Error::IdentityMismatch); + } + let expected = match self.sources.role { + GrRole::Attention(l) => GrRole::Ffn(l), + GrRole::Ffn(l) => GrRole::Attention(l.checked_add(1).ok_or(Error::Overflow)?), + GrRole::Final => return Err(Error::IdentityMismatch), + }; + let layer = match next_role { + GrRole::Attention(l) | GrRole::Ffn(l) => l, + GrRole::Final => return Err(Error::IdentityMismatch), + }; + if next_role != expected || next_role == GrRole::Attention(1) || layer >= binding.layer_count() { + return Err(Error::IdentityMismatch); + } + let resident = cache.gr(binding, next_role)?; + if !resident.weights.matches(&binding.identity(), next_role) { + return Err(Error::IdentityMismatch); + } + let gamma = cache.gr_buffers(resident)?[0].ok_or(Error::IdentityMismatch)?; + let identity = self.device.lease_identity(); + let block = produce(self.device)?; + if !identity.same_lease(&block.lease_identity()) { + return Err(Error::IdentityMismatch); + } + self.sources.validate(binding, cache)?; + let context = self.sources.context; + let inject_span = super::super::super::prefill_profile::span( + super::super::super::prefill_profile::Stage::Inject, + Some(context as &dyn super::super::super::prefill_profile::Drain), + ); + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer + .inject_gr_fused(block, &mut workspace, gamma, resident.weights.epsilon()) + .map_err(micro_driver_error) + })(); + drop(inject_span); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + let device = result?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.inject(self.sources.role, next_role)?; + } + let mut sources = self.sources; + sources.role = next_role; + sources.validated = 0; + Ok(PromptDeviceNormedRows { sources, device }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs index e8906c0d..9b82d22b 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_promptplehistory.rs @@ -3,28 +3,53 @@ #[allow(unused_imports)] use super::*; -impl<'ctx> PromptPleHistory<'ctx>{ - pub(in super::super) fn from_prior(binding:BindingIdentity,prior:PlePrior,device:OriginalPleHistory<'ctx>)->Self{Self{binding,prior,device,completed_rows:None}} - pub(in super::super) fn into_completed(self,binding:&ModelBinding,prior:&PlePrior)->Result<(PlePrior,usize,Box<[f32]>)>{ - if !self.binding.matches(&binding.identity())||!self.prior.same_state(prior){return Err(Error::IdentityMismatch)} - let count=self.completed_rows.ok_or(Error::IdentityMismatch)?; - let result=self.device.final_values().map_err(micro_driver_error); - let close=self.device.close().map_err(micro_driver_error); - let values=match result{Err(e)=>return Err(e),Ok(v)=>{close?;v}};Ok((self.prior,count,values)) +impl<'ctx> PromptPleHistory<'ctx> { + pub(in super::super) fn from_prior( + binding: BindingIdentity, + prior: PlePrior, + device: OriginalPleHistory<'ctx>, + ) -> Self { + Self { binding, prior, device, completed_rows: None } + } + pub(in super::super) fn into_completed( + self, + binding: &ModelBinding, + prior: &PlePrior, + ) -> Result<(PlePrior, usize, Box<[f32]>)> { + if !self.binding.matches(&binding.identity()) || !self.prior.same_state(prior) { + return Err(Error::IdentityMismatch); + } + let count = self.completed_rows.ok_or(Error::IdentityMismatch)?; + let result = self.device.final_values().map_err(micro_driver_error); + let close = self.device.close().map_err(micro_driver_error); + let values = match result { + Err(e) => return Err(e), + Ok(v) => { + close?; + v + } + }; + Ok((self.prior, count, values)) + } + pub(in crate::qwen_forward) fn close(self) -> Result<()> { + self.device.close().map_err(micro_driver_error) } - pub(in crate::qwen_forward) fn close(self)->Result<()>{self.device.close().map_err(micro_driver_error)} } // Same closed GR transport classification; numeric flags remain NonFinite. -pub(super) fn micro_driver_error(error:leleka_cuda_driver::Error)->Error{ +pub(super) fn micro_driver_error(error: leleka_cuda_driver::Error) -> Error { use leleka_cuda_driver::Error as E; crate::bringup_trace!("DBG micro_driver_error(prompt_device_rows): {error:?}"); - match error{ - E::NonFiniteMmqOutput(_)=>Error::NonFinite, - E::UnsupportedQwenOperation|E::Disabled|E::UnsupportedPlatform|E::LibraryUnavailable=>Error::Unsupported(super::super::contract::Stage::Gr), - E::BudgetExceeded|E::HostAllocation=>Error::InputAllocation, - E::ContextMismatch=>Error::IdentityMismatch, - E::InvalidQwenShape|E::InvalidBf16ProjectionShape|E::ShapeMismatch{..}|E::InvalidSize=>Error::InvalidDimension, - _=>Error::CudaExecution, + match error { + E::NonFiniteMmqOutput(_) => Error::NonFinite, + E::UnsupportedQwenOperation | E::Disabled | E::UnsupportedPlatform | E::LibraryUnavailable => { + Error::Unsupported(super::super::contract::Stage::Gr) + } + E::BudgetExceeded | E::HostAllocation => Error::InputAllocation, + E::ContextMismatch => Error::IdentityMismatch, + E::InvalidQwenShape | E::InvalidBf16ProjectionShape | E::ShapeMismatch { .. } | E::InvalidSize => { + Error::InvalidDimension + } + _ => Error::CudaExecution, } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref.rs index fe5a871d..54e2c0e3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref.rs @@ -3,219 +3,6 @@ #[allow(unused_imports)] use super::*; -impl std::ops::Deref for SourceInput<'_>{type Target=InputReady;fn deref(&self)->&InputReady{match self{Self::Borrowed(input)=>input,Self::Owned(input)=>input.as_ref()}}} -impl<'source,'ctx> PromptDeviceSource<'source,'ctx>{ - pub(in super::super) fn from_current(binding:&ModelBinding,context:&'ctx Context<'ctx>,input:&'source InputReady,txn:&QwenStepTxn<'_, '_>)->Result{ - txn.validate_binding(&binding.identity())?; - txn.validate_binding(input.binding_identity())?; - txn.validate_input(input.token(),input.position())?; - if !std::ptr::eq(context,txn.cuda_context()?)||!std::ptr::eq(txn.input()?.as_ref(),input){return Err(Error::IdentityMismatch)} - if input.streams().values().len()!=10240||input.ple_embedding().len()!=2560{return Err(Error::InvalidDimension)} - if input.streams().values().iter().chain(input.ple_embedding()).any(|x|!x.is_finite()){return Err(Error::NonFinite)} - Ok(Self{binding:binding.identity(),context,input:SourceInput::Borrowed(input),original:None}) - } - pub(in crate::qwen_forward) fn from_original(binding:&ModelBinding,context:&'ctx Context<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,index:usize)->Result>{ - let input=txn.input(index)?;let key=txn.source_key(index,&input,context)?; - // A deferred input (the batched KAR prompt path) keeps its values on the device; the driver checks them there. - if !input.is_deferred(){ - if input.streams().values().len()!=10240||input.ple_embedding().len()!=2560{return Err(Error::InvalidDimension)} - if input.streams().values().iter().chain(input.ple_embedding()).any(|x|!x.is_finite()){return Err(Error::NonFinite)} - } - key.validate_initial(&binding.identity(),&input)?; - Ok(PromptDeviceSource{binding:binding.identity(),context,input:SourceInput::Owned(input),original:Some(key)}) - } -} -impl PromptDeviceFinal{ - pub(in crate::qwen_forward) fn validate(&self,phase:&OriginalPromptPhase,binding:&BindingIdentity)->Result<()>{ - if !self.binding.matches(binding)||!self.phase.same(phase){return Err(Error::IdentityMismatch)} - if let FinalProduct::Host(streams)=&self.product{ - if streams.len()!=10240{return Err(Error::IdentityMismatch)} - if streams.iter().any(|value|!value.is_finite()){return Err(Error::NonFinite)} - }Ok(()) - } - pub(in crate::qwen_forward) fn token(&self)->TokenId{self.token} - pub(in crate::qwen_forward) fn position(&self)->Position{self.position} - pub(in crate::qwen_forward) fn streams(&self)->Result<&[f32]>{ - match &self.product{FinalProduct::Host(streams)=>Ok(streams),FinalProduct::DeviceConditioning{..}=>Err(Error::IdentityMismatch)} - } - pub(in crate::qwen_forward) fn validate_conditioning(&self,next:TokenId)->Result<()>{ - match &self.product{FinalProduct::DeviceConditioning{known_next}if *known_next==next=>Ok(()),_=>Err(Error::IdentityMismatch)} - } -} -impl Sources<'_, '_>{ - pub(super) fn original_phase(&self)->Result>>{ - let first=self.rows.first().ok_or(Error::IdentityMismatch)?.original.as_ref().map(OriginalPromptRowKey::phase); - for row in &self.rows{match(&first,&row.original){(Some(first),Some(row))if first.same(&row.phase())=>{},(None,None)=>{},_=>return Err(Error::IdentityMismatch)}} - Ok(first) - } - /// Every row's chronological key against the current phase. The whole-set checks (binding, Context, dense - /// cache, consecutive positions) do not depend on the row, so they run once for the set, not once per row: - /// the per-row form was quadratic in the chunk and re-checked the dense sources for every row. - pub(super) fn original_all(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,read:bool)->Result<()>{ - if self.validated!=0{return Err(Error::IdentityMismatch)} - if self.rows.is_empty(){return Ok(())} - self.validate(binding,cache)?; - for index in 0..self.rows.len(){self.original_row(index,read)?;self.validated+=1;} - Ok(()) - } - pub(super) fn original_row(&self,index:usize,read:bool)->Result{ - let row=self.rows.get(index).ok_or(Error::IdentityMismatch)?; - let key=row.original.as_ref().ok_or(Error::IdentityMismatch)?; - if key.ordinal()!=index{return Err(Error::IdentityMismatch)} - key.validate(&self.binding,&row.input,self.role,read) - } - pub(super) fn validate(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>)->Result<()>{ - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,cache.retained_context(binding,self.context)?){return Err(Error::IdentityMismatch)} - cache.validate(binding)?; - for(row,s)in self.rows.iter().enumerate(){ - if !s.binding.matches(&self.binding)||!std::ptr::eq(s.context,self.context) - || s.input.position().get()!=self.rows[0].input.position().get().checked_add(row as u64).ok_or(Error::Overflow)?{return Err(Error::IdentityMismatch)} - }Ok(()) - } - pub(super) fn current(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>,index:usize,role:GrRole)->Result{ - self.validate(binding,cache)?; - if self.role!=role||!std::ptr::eq(self.context,txn.cuda_context()?){return Err(Error::IdentityMismatch)} - txn.validate_binding(&self.binding)?;let s=self.rows.get(index).ok_or(Error::IdentityMismatch)?; - txn.validate_input(s.input.token(),s.input.position())?; - let layer=match role{GrRole::Attention(l)|GrRole::Ffn(l)=>l,GrRole::Final=>return Err(Error::IdentityMismatch)}; - let layer=LayerId::new(u64::from(layer),Dimension::new(u64::from(binding.layer_count()))?)?; - let identity=TokenLayer::new(s.input.token(),s.input.position(),layer); - identity.validate(txn.token(),txn.position(),layer)?;Ok(identity) - } -} -impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{ - /// Original Prefill consumes only the known-next conditioning prefix. - /// Keep the genuine all-row residual on device for the shifted MTP input; - /// the final seed is handled by Verifier, not by this prefill producer. - pub(in crate::qwen_forward) fn preview_conditioning(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>)->Result{ - self.sources.validate(binding,cache)?;txn.validate_phase(GrRole::Final,false)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len(){return Err(Error::IdentityMismatch)} - let phase=self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if !phase.same(&txn.phase()){return Err(Error::IdentityMismatch)} - let last=self.sources.rows.last().ok_or(Error::IdentityMismatch)?; - if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)} - let known_next=txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; - let lease_identity=self.device.lease_identity(); - self.device.resolve_guards().map_err(micro_driver_error)?; - phase.seal_final()?; - Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(), - product:FinalProduct::DeviceConditioning{known_next},lease_identity}) - } - /// Read the real head row while retaining all physical R rows for MTP. - /// The resulting final product is tied to this actual arena lease. - pub(in crate::qwen_forward) fn preview_final(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>)->Result{ - self.sources.validate(binding,cache)?;txn.validate_phase(GrRole::Final,false)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len(){return Err(Error::IdentityMismatch)} - let phase=self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if !phase.same(&txn.phase()){return Err(Error::IdentityMismatch)} - let last=self.sources.rows.last().ok_or(Error::IdentityMismatch)?; - if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)} - let lease_identity=self.device.lease_identity(); - let streams=self.device.read_prompt_row(txn.len()-1).map_err(micro_driver_error)?; - self.sources.validate(binding,cache)?; - if !lease_identity.same_lease(&self.device.lease_identity()){return Err(Error::IdentityMismatch)} - phase.seal_final()?; - Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(),product:FinalProduct::Host(streams),lease_identity}) - } - /// Only the actual final-phase owner can lend the retained all-row R to - /// the genuine MTP producer. No host reconstruction substitutes for it. - pub(in crate::qwen_forward) fn with_final_residual(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,completed:&PromptDeviceFinal, - execute:impl FnOnce(&mut OriginalDeviceResidual<'arena,'loan,'ctx>)->Result)->Result{ - self.validate_preview(binding,cache,txn,completed)?; - let value=execute(&mut self.device)?; - self.validate_preview(binding,cache,txn,completed)?;Ok(value) - } - pub(super) fn validate_preview(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,txn:&OriginalPromptTxn<'_, '_>, - completed:&PromptDeviceFinal)->Result<()>{ - self.sources.validate(binding,cache)?;txn.validate_final(completed)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len() - ||!completed.lease_identity.same_lease(&self.device.lease_identity()) - ||self.sources.original_phase()?.is_none_or(|phase|!phase.same(&txn.phase())){return Err(Error::IdentityMismatch)} - Ok(()) - } - pub(in crate::qwen_forward) fn finish_after_preview(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,completed:&PromptDeviceFinal)->Result<()>{ - self.validate_preview(binding,cache,txn,completed)?; - self.device.finish_after_preview().map_err(micro_driver_error)?; - txn.validate_final(completed) - } - pub(in crate::qwen_forward) fn finish_after_preview_rows(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>,completed:&PromptDeviceFinal)->Result>{ - self.validate_preview(binding,cache,txn,completed)?; - let rows=self.device.into_rows_after_preview().map_err(micro_driver_error)?; - txn.validate_final(completed)?; - Ok(rows) - } - pub(in crate::qwen_forward) fn finish(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - txn:&OriginalPromptTxn<'_, '_>)->Result{ - self.sources.validate(binding,cache)?;txn.validate_phase(GrRole::Final,false)?; - if self.sources.role!=GrRole::Final||self.sources.rows.len()!=txn.len(){return Err(Error::IdentityMismatch)} - let phase=self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; - if !phase.same(&txn.phase()){return Err(Error::IdentityMismatch)} - let last=self.sources.rows.last().ok_or(Error::IdentityMismatch)?; - if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)} - let lease_identity=self.device.lease_identity(); - let streams=self.device.finish_prompt_row(txn.len()-1).map_err(micro_driver_error)?; - self.sources.validate(binding,cache)?;phase.seal_final()?; - Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(),product:FinalProduct::Host(streams),lease_identity}) - } - pub(in crate::qwen_forward) fn initialize(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,context:&Context<'_>,producer:&mut OriginalPromptDevice<'ctx>,lease:OriginalPromptRows<'arena,'loan,'ctx>,rows:Vec>, - stage:Option>)->Result{ - let context=cache.retained_context(binding,context)?; - if rows.is_empty()||rows.len()!=lease.rows(){return Err(Error::InvalidDimension)} - let sources=Sources{binding:binding.identity(),context,rows,role:GrRole::Attention(0),validated:0};sources.validate(binding,cache)?; - // Only initial real source staging: Original also uploads initial R - // and PLE embeddings. Later layer phases retain this same device R. - // The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals). - let deferred=sources.rows.iter().filter(|s|s.input.is_deferred()).count(); - if deferred!=0&&(deferred!=sources.rows.len()||stage.is_none())||deferred==0&&stage.is_some(){return Err(Error::IdentityMismatch)} - let result=if let Some(stage)=stage{ - (||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.initialize_staged(lease,&mut workspace,stage).map_err(micro_driver_error)})() - }else{ - let mut slices=Vec::new();slices.try_reserve_exact(sources.rows.len()).map_err(|_|Error::InputAllocation)?; - for s in &sources.rows{slices.push((s.input.streams().values(),s.input.ple_embedding()));} - (||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.initialize_rows(lease,&mut workspace,&slices).map_err(micro_driver_error)})() - }; - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - let device=result?;sources.validate(binding,cache)?; - if let Some(phase)=sources.original_phase()?{phase.initialize(sources.rows.len())?;} - Ok(Self{sources,device}) - } - pub(in crate::qwen_forward) fn validate_original_rows(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>)->Result<()>{ - self.sources.original_all(binding,cache,false) - } - pub(in crate::qwen_forward) fn validate_row(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>,index:usize,role:GrRole)->Result{if index!=self.sources.validated{return Err(Error::IdentityMismatch)}let id=self.sources.current(binding,cache,txn,index,role)?;self.sources.validated+=1;Ok(id)} - pub(in crate::qwen_forward) fn apply_ple(mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,producer:&mut OriginalPromptDevice<'ctx>,history:&mut PromptPleHistory<'ctx>)->Result{ - self.sources.validate(binding,cache)?; - if self.sources.validated!=self.sources.rows.len()||self.sources.role!=GrRole::Attention(1)||!history.binding.matches(&binding.identity()) - ||history.completed_rows.is_some()||history.prior.next_position()!=self.sources.rows[0].input.position().get(){return Err(Error::IdentityMismatch)} - let context=self.sources.context;let entry=cache.ple(binding,context)?; - if !entry.weights.matches(&binding.identity()){return Err(Error::IdentityMismatch)} - let weights=leleka_cuda_driver::PleClosedWeights{key:cache.ple_key(entry)?,value:cache.ple_value(entry)?,aux:cache.ple_aux(entry)?}; - let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.apply_ple(self.device,&mut workspace,weights,&mut history.device).map_err(micro_driver_error)})(); - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - self.device=result?;self.sources.validate(binding,cache)?;history.completed_rows=Some(self.sources.rows.len()); - if let Some(phase)=self.sources.original_phase()?{phase.ple_complete()?;} - self.sources.validated=0;Ok(self) - } - pub(in crate::qwen_forward) fn read(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,producer:&mut OriginalPromptDevice<'ctx>,role:GrRole)->Result>{ - self.sources.validate(binding,cache)?;if self.sources.validated!=self.sources.rows.len()||self.sources.role!=role{return Err(Error::IdentityMismatch)} - if let Some(phase)=self.sources.original_phase()?{phase.prepare_read(role)?;} - let context=self.sources.context;let resident=cache.gr(binding,role)?; - if !resident.weights.matches(&binding.identity(),role){return Err(Error::IdentityMismatch)} - let [gamma,down,up,inject]=cache.gr_buffers(resident)?.map(|w|w.ok_or(Error::IdentityMismatch)); - let result=(||{let mut workspace=cache.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - producer.read_gr(self.device,&mut workspace,[gamma?,down?,up?,inject?],resident.weights.epsilon()).map_err(micro_driver_error)})(); - if producer.is_failed(){cache.transport_failure_flag(binding,context)?.set(true)} - let device=result?;self.sources.validate(binding,cache)?; - if let Some(phase)=self.sources.original_phase()?{phase.read(role)?;} - let mut sources=self.sources;sources.validated=0;Ok(PromptDeviceRead{sources,device}) - } -} +mod impl_promptdevicerows; +mod impl_promptdevicerows_2; +mod impl_std_ops_deref_2; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs new file mode 100644 index 00000000..72f2e445 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows.rs @@ -0,0 +1,237 @@ +//! Moved out of the parent module by STRA-338: impl PromptDeviceRows. + +#[allow(unused_imports)] +use super::*; + +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { + /// Original Prefill consumes only the known-next conditioning prefix. + /// Keep the genuine all-row residual on device for the shifted MTP input; + /// the final seed is handled by Verifier, not by this prefill producer. + pub(in crate::qwen_forward) fn preview_conditioning( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + ) -> Result { + self.sources.validate(binding, cache)?; + txn.validate_phase(GrRole::Final, false)?; + if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { + return Err(Error::IdentityMismatch); + } + let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; + if !phase.same(&txn.phase()) { + return Err(Error::IdentityMismatch); + } + let last = self.sources.rows.last().ok_or(Error::IdentityMismatch)?; + if last.input.position().get().checked_add(1) != Some(txn.end_position()) { + return Err(Error::IdentityMismatch); + } + let known_next = txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?; + let lease_identity = self.device.lease_identity(); + self.device.resolve_guards().map_err(micro_driver_error)?; + phase.seal_final()?; + Ok(PromptDeviceFinal { + binding: binding.identity(), + phase, + token: last.input.token(), + position: last.input.position(), + product: FinalProduct::DeviceConditioning { known_next }, + lease_identity, + }) + } + /// Read the real head row while retaining all physical R rows for MTP. + /// The resulting final product is tied to this actual arena lease. + pub(in crate::qwen_forward) fn preview_final( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + ) -> Result { + self.sources.validate(binding, cache)?; + txn.validate_phase(GrRole::Final, false)?; + if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { + return Err(Error::IdentityMismatch); + } + let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; + if !phase.same(&txn.phase()) { + return Err(Error::IdentityMismatch); + } + let last = self.sources.rows.last().ok_or(Error::IdentityMismatch)?; + if last.input.position().get().checked_add(1) != Some(txn.end_position()) { + return Err(Error::IdentityMismatch); + } + let lease_identity = self.device.lease_identity(); + let streams = self.device.read_prompt_row(txn.len() - 1).map_err(micro_driver_error)?; + self.sources.validate(binding, cache)?; + if !lease_identity.same_lease(&self.device.lease_identity()) { + return Err(Error::IdentityMismatch); + } + phase.seal_final()?; + Ok(PromptDeviceFinal { + binding: binding.identity(), + phase, + token: last.input.token(), + position: last.input.position(), + product: FinalProduct::Host(streams), + lease_identity, + }) + } + /// Only the actual final-phase owner can lend the retained all-row R to + /// the genuine MTP producer. No host reconstruction substitutes for it. + pub(in crate::qwen_forward) fn with_final_residual( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + completed: &PromptDeviceFinal, + execute: impl FnOnce(&mut OriginalDeviceResidual<'arena, 'loan, 'ctx>) -> Result, + ) -> Result { + self.validate_preview(binding, cache, txn, completed)?; + let value = execute(&mut self.device)?; + self.validate_preview(binding, cache, txn, completed)?; + Ok(value) + } + pub(in super::super) fn validate_preview( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + completed: &PromptDeviceFinal, + ) -> Result<()> { + self.sources.validate(binding, cache)?; + txn.validate_final(completed)?; + if self.sources.role != GrRole::Final + || self.sources.rows.len() != txn.len() + || !completed.lease_identity.same_lease(&self.device.lease_identity()) + || self.sources.original_phase()?.is_none_or(|phase| !phase.same(&txn.phase())) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn finish_after_preview( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + completed: &PromptDeviceFinal, + ) -> Result<()> { + self.validate_preview(binding, cache, txn, completed)?; + self.device.finish_after_preview().map_err(micro_driver_error)?; + txn.validate_final(completed) + } + pub(in crate::qwen_forward) fn finish_after_preview_rows( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + completed: &PromptDeviceFinal, + ) -> Result> { + self.validate_preview(binding, cache, txn, completed)?; + let rows = self.device.into_rows_after_preview().map_err(micro_driver_error)?; + txn.validate_final(completed)?; + Ok(rows) + } + pub(in crate::qwen_forward) fn finish( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + ) -> Result { + self.sources.validate(binding, cache)?; + txn.validate_phase(GrRole::Final, false)?; + if self.sources.role != GrRole::Final || self.sources.rows.len() != txn.len() { + return Err(Error::IdentityMismatch); + } + let phase = self.sources.original_phase()?.ok_or(Error::IdentityMismatch)?; + if !phase.same(&txn.phase()) { + return Err(Error::IdentityMismatch); + } + let last = self.sources.rows.last().ok_or(Error::IdentityMismatch)?; + if last.input.position().get().checked_add(1) != Some(txn.end_position()) { + return Err(Error::IdentityMismatch); + } + let lease_identity = self.device.lease_identity(); + let streams = self.device.finish_prompt_row(txn.len() - 1).map_err(micro_driver_error)?; + self.sources.validate(binding, cache)?; + phase.seal_final()?; + Ok(PromptDeviceFinal { + binding: binding.identity(), + phase, + token: last.input.token(), + position: last.input.position(), + product: FinalProduct::Host(streams), + lease_identity, + }) + } + pub(in crate::qwen_forward) fn initialize( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + context: &Context<'_>, + producer: &mut OriginalPromptDevice<'ctx>, + lease: OriginalPromptRows<'arena, 'loan, 'ctx>, + rows: Vec>, + stage: Option>, + ) -> Result { + let context = cache.retained_context(binding, context)?; + if rows.is_empty() || rows.len() != lease.rows() { + return Err(Error::InvalidDimension); + } + let sources = Sources { binding: binding.identity(), context, rows, role: GrRole::Attention(0), validated: 0 }; + sources.validate(binding, cache)?; + // Only initial real source staging: Original also uploads initial R + // and PLE embeddings. Later layer phases retain this same device R. + // The driver stages every row's streams and PLE embedding in place (one pass, same bytes and refusals). + let deferred = sources.rows.iter().filter(|s| s.input.is_deferred()).count(); + if deferred != 0 && (deferred != sources.rows.len() || stage.is_none()) || deferred == 0 && stage.is_some() { + return Err(Error::IdentityMismatch); + } + let result = if let Some(stage) = stage { + (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer.initialize_staged(lease, &mut workspace, stage).map_err(micro_driver_error) + })() + } else { + let mut slices = Vec::new(); + slices.try_reserve_exact(sources.rows.len()).map_err(|_| Error::InputAllocation)?; + for s in &sources.rows { + slices.push((s.input.streams().values(), s.input.ple_embedding())); + } + (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer.initialize_rows(lease, &mut workspace, &slices).map_err(micro_driver_error) + })() + }; + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + let device = result?; + sources.validate(binding, cache)?; + if let Some(phase) = sources.original_phase()? { + phase.initialize(sources.rows.len())?; + } + Ok(Self { sources, device }) + } + pub(in crate::qwen_forward) fn validate_original_rows( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + ) -> Result<()> { + self.sources.original_all(binding, cache, false) + } + pub(in crate::qwen_forward) fn validate_row( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + index: usize, + role: GrRole, + ) -> Result { + if index != self.sources.validated { + return Err(Error::IdentityMismatch); + } + let id = self.sources.current(binding, cache, txn, index, role)?; + self.sources.validated += 1; + Ok(id) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs new file mode 100644 index 00000000..289b2dfa --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_promptdevicerows_2.rs @@ -0,0 +1,87 @@ +//! Moved out of the parent module by STRA-338: impl PromptDeviceRows (2). + +#[allow(unused_imports)] +use super::*; + +impl<'source, 'arena, 'loan, 'ctx> PromptDeviceRows<'source, 'arena, 'loan, 'ctx> { + pub(in crate::qwen_forward) fn apply_ple( + mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + history: &mut PromptPleHistory<'ctx>, + ) -> Result { + self.sources.validate(binding, cache)?; + if self.sources.validated != self.sources.rows.len() + || self.sources.role != GrRole::Attention(1) + || !history.binding.matches(&binding.identity()) + || history.completed_rows.is_some() + || history.prior.next_position() != self.sources.rows[0].input.position().get() + { + return Err(Error::IdentityMismatch); + } + let context = self.sources.context; + let entry = cache.ple(binding, context)?; + if !entry.weights.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + let weights = leleka_cuda_driver::PleClosedWeights { + key: cache.ple_key(entry)?, + value: cache.ple_value(entry)?, + aux: cache.ple_aux(entry)?, + }; + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer.apply_ple(self.device, &mut workspace, weights, &mut history.device).map_err(micro_driver_error) + })(); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + self.device = result?; + self.sources.validate(binding, cache)?; + history.completed_rows = Some(self.sources.rows.len()); + if let Some(phase) = self.sources.original_phase()? { + phase.ple_complete()?; + } + self.sources.validated = 0; + Ok(self) + } + pub(in crate::qwen_forward) fn read( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + producer: &mut OriginalPromptDevice<'ctx>, + role: GrRole, + ) -> Result> { + self.sources.validate(binding, cache)?; + if self.sources.validated != self.sources.rows.len() || self.sources.role != role { + return Err(Error::IdentityMismatch); + } + if let Some(phase) = self.sources.original_phase()? { + phase.prepare_read(role)?; + } + let context = self.sources.context; + let resident = cache.gr(binding, role)?; + if !resident.weights.matches(&binding.identity(), role) { + return Err(Error::IdentityMismatch); + } + let [gamma, down, up, inject] = cache.gr_buffers(resident)?.map(|w| w.ok_or(Error::IdentityMismatch)); + let result = (|| { + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + producer + .read_gr(self.device, &mut workspace, [gamma?, down?, up?, inject?], resident.weights.epsilon()) + .map_err(micro_driver_error) + })(); + if producer.is_failed() { + cache.transport_failure_flag(binding, context)?.set(true) + } + let device = result?; + self.sources.validate(binding, cache)?; + if let Some(phase) = self.sources.original_phase()? { + phase.read(role)?; + } + let mut sources = self.sources; + sources.validated = 0; + Ok(PromptDeviceRead { sources, device }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs new file mode 100644 index 00000000..419d5ad7 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/prompt_device_rows/impl_std_ops_deref/impl_std_ops_deref_2.rs @@ -0,0 +1,185 @@ +//! Moved out of the parent module by STRA-338: impl std_ops_Deref, impl PromptDeviceSource, impl PromptDeviceFinal, impl Sources. + +#[allow(unused_imports)] +use super::*; + +impl std::ops::Deref for SourceInput<'_> { + type Target = InputReady; + fn deref(&self) -> &InputReady { + match self { + Self::Borrowed(input) => input, + Self::Owned(input) => input.as_ref(), + } + } +} +impl<'source, 'ctx> PromptDeviceSource<'source, 'ctx> { + pub(in super::super::super) fn from_current( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + input: &'source InputReady, + txn: &QwenStepTxn<'_, '_>, + ) -> Result { + txn.validate_binding(&binding.identity())?; + txn.validate_binding(input.binding_identity())?; + txn.validate_input(input.token(), input.position())?; + if !std::ptr::eq(context, txn.cuda_context()?) || !std::ptr::eq(txn.input()?.as_ref(), input) { + return Err(Error::IdentityMismatch); + } + if input.streams().values().len() != 10240 || input.ple_embedding().len() != 2560 { + return Err(Error::InvalidDimension); + } + if input.streams().values().iter().chain(input.ple_embedding()).any(|x| !x.is_finite()) { + return Err(Error::NonFinite); + } + Ok(Self { binding: binding.identity(), context, input: SourceInput::Borrowed(input), original: None }) + } + pub(in crate::qwen_forward) fn from_original( + binding: &ModelBinding, + context: &'ctx Context<'ctx>, + txn: &OriginalPromptTxn<'_, '_>, + index: usize, + ) -> Result> { + let input = txn.input(index)?; + let key = txn.source_key(index, &input, context)?; + // A deferred input (the batched KAR prompt path) keeps its values on the device; the driver checks them there. + if !input.is_deferred() { + if input.streams().values().len() != 10240 || input.ple_embedding().len() != 2560 { + return Err(Error::InvalidDimension); + } + if input.streams().values().iter().chain(input.ple_embedding()).any(|x| !x.is_finite()) { + return Err(Error::NonFinite); + } + } + key.validate_initial(&binding.identity(), &input)?; + Ok(PromptDeviceSource { + binding: binding.identity(), + context, + input: SourceInput::Owned(input), + original: Some(key), + }) + } +} +impl PromptDeviceFinal { + pub(in crate::qwen_forward) fn validate( + &self, + phase: &OriginalPromptPhase, + binding: &BindingIdentity, + ) -> Result<()> { + if !self.binding.matches(binding) || !self.phase.same(phase) { + return Err(Error::IdentityMismatch); + } + if let FinalProduct::Host(streams) = &self.product { + if streams.len() != 10240 { + return Err(Error::IdentityMismatch); + } + if streams.iter().any(|value| !value.is_finite()) { + return Err(Error::NonFinite); + } + } + Ok(()) + } + pub(in crate::qwen_forward) fn token(&self) -> TokenId { + self.token + } + pub(in crate::qwen_forward) fn position(&self) -> Position { + self.position + } + pub(in crate::qwen_forward) fn streams(&self) -> Result<&[f32]> { + match &self.product { + FinalProduct::Host(streams) => Ok(streams), + FinalProduct::DeviceConditioning { .. } => Err(Error::IdentityMismatch), + } + } + pub(in crate::qwen_forward) fn validate_conditioning(&self, next: TokenId) -> Result<()> { + match &self.product { + FinalProduct::DeviceConditioning { known_next } if *known_next == next => Ok(()), + _ => Err(Error::IdentityMismatch), + } + } +} +impl Sources<'_, '_> { + pub(in super::super) fn original_phase(&self) -> Result>> { + let first = + self.rows.first().ok_or(Error::IdentityMismatch)?.original.as_ref().map(OriginalPromptRowKey::phase); + for row in &self.rows { + match (&first, &row.original) { + (Some(first), Some(row)) if first.same(&row.phase()) => {} + (None, None) => {} + _ => return Err(Error::IdentityMismatch), + } + } + Ok(first) + } + /// Every row's chronological key against the current phase. The whole-set checks (binding, Context, dense + /// cache, consecutive positions) do not depend on the row, so they run once for the set, not once per row: + /// the per-row form was quadratic in the chunk and re-checked the dense sources for every row. + pub(in super::super) fn original_all( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + read: bool, + ) -> Result<()> { + if self.validated != 0 { + return Err(Error::IdentityMismatch); + } + if self.rows.is_empty() { + return Ok(()); + } + self.validate(binding, cache)?; + for index in 0..self.rows.len() { + self.original_row(index, read)?; + self.validated += 1; + } + Ok(()) + } + pub(in super::super) fn original_row(&self, index: usize, read: bool) -> Result { + let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + let key = row.original.as_ref().ok_or(Error::IdentityMismatch)?; + if key.ordinal() != index { + return Err(Error::IdentityMismatch); + } + key.validate(&self.binding, &row.input, self.role, read) + } + pub(in super::super) fn validate(&self, binding: &ModelBinding, cache: &DenseWeightCache<'_>) -> Result<()> { + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, cache.retained_context(binding, self.context)?) + { + return Err(Error::IdentityMismatch); + } + cache.validate(binding)?; + for (row, s) in self.rows.iter().enumerate() { + if !s.binding.matches(&self.binding) + || !std::ptr::eq(s.context, self.context) + || s.input.position().get() + != self.rows[0].input.position().get().checked_add(row as u64).ok_or(Error::Overflow)? + { + return Err(Error::IdentityMismatch); + } + } + Ok(()) + } + pub(in super::super) fn current( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + index: usize, + role: GrRole, + ) -> Result { + self.validate(binding, cache)?; + if self.role != role || !std::ptr::eq(self.context, txn.cuda_context()?) { + return Err(Error::IdentityMismatch); + } + txn.validate_binding(&self.binding)?; + let s = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + txn.validate_input(s.input.token(), s.input.position())?; + let layer = match role { + GrRole::Attention(l) | GrRole::Ffn(l) => l, + GrRole::Final => return Err(Error::IdentityMismatch), + }; + let layer = LayerId::new(u64::from(layer), Dimension::new(u64::from(binding.layer_count()))?)?; + let identity = TokenLayer::new(s.input.token(), s.input.position(), layer); + identity.validate(txn.token(), txn.position(), layer)?; + Ok(identity) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns.rs b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns.rs index f8a848f9..2e887202 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns.rs @@ -12,8 +12,8 @@ use super::{ session::{QwenStepTxn, TargetStepOrigin, chunk::QwenChunkTxn}, }; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, ModelBinding, QsaMatrixKind, - QsaMatrixRole, QsaWeights, + BindingIdentity, GdnMatrixKind, GdnMatrixRole, GdnWeights, GrRole, ModelBinding, QsaMatrixKind, QsaMatrixRole, + QsaWeights, }; use leleka_cuda_driver::{Context, DeviceBuffer}; use std::{cell::Cell, rc::Rc}; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs index baa33250..a1592c83 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/numeric_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn numeric<'ctx>( context: &'ctx Context<'ctx>, matrix: &DeviceBuffer<'_>, @@ -26,11 +25,7 @@ pub(super) fn numeric<'ctx>( ); return Err(Error::CudaExecution); } - if context - .allocated_bytes() - .checked_add(128 * 1024 * 1024) - .is_none_or(|value| value > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|value| value > context.budget_bytes()) { return Err(Error::InputAllocation); } let batch = modules.q6(context)?; @@ -47,12 +42,7 @@ pub(super) fn numeric<'ctx>( } y = Some( context - .allocate( - tokens - .checked_mul(rows) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::Overflow)?, - ) + .allocate(tokens.checked_mul(rows).and_then(|n| n.checked_mul(4)).ok_or(Error::Overflow)?) .map_err(driver_error)?, ); let engine = &*batch; @@ -61,34 +51,20 @@ pub(super) fn numeric<'ctx>( driver_stage = "q6-quantize"; } q = Some( - engine - .prepare( - x.as_ref().ok_or(Error::IdentityMismatch)?, - rows, - 2560, - tokens, - ) - .map_err(driver_error)?, + engine.prepare(x.as_ref().ok_or(Error::IdentityMismatch)?, rows, 2560, tokens).map_err(driver_error)?, ); #[cfg(test)] { driver_stage = "q6-project"; } engine - .project( - matrix, - q.as_ref().ok_or(Error::IdentityMismatch)?, - y.as_mut().ok_or(Error::IdentityMismatch)?, - ) + .project(matrix, q.as_ref().ok_or(Error::IdentityMismatch)?, y.as_mut().ok_or(Error::IdentityMismatch)?) .map_err(driver_error)?; #[cfg(test)] { driver_stage = "q6-output-download"; } - download( - y.as_ref().ok_or(Error::IdentityMismatch)?, - tokens.checked_mul(rows).ok_or(Error::Overflow)?, - ) + download(y.as_ref().ok_or(Error::IdentityMismatch)?, tokens.checked_mul(rows).ok_or(Error::Overflow)?) })(); #[cfg(test)] if let Err(error) = &operation { @@ -107,9 +83,7 @@ pub(super) fn numeric<'ctx>( for buffer in [y.take(), x.take()].into_iter().flatten() { if let Err(error) = buffer.release() { #[cfg(test)] - eprintln!( - "PUBLIC CUDA stage=q6-buffer-release rows={rows} columns={tokens} error={error:?}" - ); + eprintln!("PUBLIC CUDA stage=q6-buffer-release rows={rows} columns={tokens} error={error:?}"); failed.set(true); if cleanup.is_ok() { cleanup = Err(driver_error(error)); @@ -120,9 +94,7 @@ pub(super) fn numeric<'ctx>( && let Err(error) = prepared.close() { #[cfg(test)] - eprintln!( - "PUBLIC CUDA stage=q6-prepared-close rows={rows} columns={tokens} error={error:?}" - ); + eprintln!("PUBLIC CUDA stage=q6-prepared-close rows={rows} columns={tokens} error={error:?}"); failed.set(true); if cleanup.is_ok() { cleanup = Err(driver_error(error)); @@ -156,11 +128,7 @@ pub(super) fn numeric_retained<'ctx>( if failed.get() { return Err(Error::CudaExecution); } - if context - .allocated_bytes() - .checked_add(128 * 1024 * 1024) - .is_none_or(|value| value > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|value| value > context.budget_bytes()) { return Err(Error::InputAllocation); } let batch = modules.q6(context)?; @@ -171,31 +139,15 @@ pub(super) fn numeric_retained<'ctx>( x = Some(super::super::qsa_index::upload(context, columns)?); y = Some( context - .allocate( - tokens - .checked_mul(rows) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::Overflow)?, - ) + .allocate(tokens.checked_mul(rows).and_then(|n| n.checked_mul(4)).ok_or(Error::Overflow)?) .map_err(driver_error)?, ); let engine = &*batch; q = Some( - engine - .prepare( - x.as_ref().ok_or(Error::IdentityMismatch)?, - rows, - 2560, - tokens, - ) - .map_err(driver_error)?, + engine.prepare(x.as_ref().ok_or(Error::IdentityMismatch)?, rows, 2560, tokens).map_err(driver_error)?, ); engine - .project( - matrix, - q.as_ref().ok_or(Error::IdentityMismatch)?, - y.as_mut().ok_or(Error::IdentityMismatch)?, - ) + .project(matrix, q.as_ref().ok_or(Error::IdentityMismatch)?, y.as_mut().ok_or(Error::IdentityMismatch)?) .map_err(driver_error) })(); if matches!(operation, Err(Error::CudaExecution)) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/project_impl_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/project_impl_fn.rs index 0dadfdde..32261267 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/project_impl_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/q6_attention_columns/project_impl_fn.rs @@ -14,13 +14,11 @@ pub(super) fn project_impl<'source, 'ctx>( retain: bool, ) -> Result>> { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - if role == Role::GdnQkv { - crate::qwen_forward::owner_wall_profile::Stage::Gdn - } else { - crate::qwen_forward::owner_wall_profile::Stage::Qsa - }, - ); + let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(if role == Role::GdnQkv { + crate::qwen_forward::owner_wall_profile::Stage::Gdn + } else { + crate::qwen_forward::owner_wall_profile::Stage::Qsa + }); if retain && role != Role::GdnQkv { return Err(Error::IdentityMismatch); } @@ -42,15 +40,10 @@ pub(super) fn project_impl<'source, 'ctx>( validate_values(input.mixed(), 2560)?; if local > 0 { let previous = inputs[local - 1]; - if previous.identity().position().get().checked_add(1) - != Some(input.identity().position().get()) - { + if previous.identity().position().get().checked_add(1) != Some(input.identity().position().get()) { return Err(Error::InvalidPosition); } - if inputs[..local] - .iter() - .any(|prior| std::ptr::eq(*prior, *input)) - { + if inputs[..local].iter().any(|prior| std::ptr::eq(*prior, *input)) { return Err(Error::IdentityMismatch); } } @@ -84,24 +77,16 @@ pub(super) fn project_impl<'source, 'ctx>( // No device output is retained across scalar recurrence's128MiB preflight. let elements = tokens.checked_mul(2560).ok_or(Error::Overflow)?; let mut columns = Vec::new(); - columns - .try_reserve_exact(elements) - .map_err(|_| Error::InputAllocation)?; + columns.try_reserve_exact(elements).map_err(|_| Error::InputAllocation)?; for input in inputs { columns.extend_from_slice(input.mixed()); } if retain { let modules = cache.chunk_modules(binding, context)?; let output = numeric_retained(context, matrix, &columns, role.rows(), tokens, modules)?; - let shared = Rc::new(RetainedColumns { - failed: modules.failure_flag().clone(), - tokens, - buffer: Some(output), - }); + let shared = Rc::new(RetainedColumns { failed: modules.failure_flag().clone(), tokens, buffer: Some(output) }); let mut result = Vec::new(); - result - .try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; + result.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; for (local, source) in inputs.iter().enumerate() { result.push(ProjectionRow { binding: binding.identity(), @@ -117,27 +102,13 @@ pub(super) fn project_impl<'source, 'ctx>( } return Ok(result); } - let outputs = numeric( - context, - matrix, - &columns, - role.rows(), - tokens, - cache.chunk_modules(binding, context)?, - )?; - validate_values( - &outputs, - tokens.checked_mul(role.rows()).ok_or(Error::Overflow)?, - )?; + let outputs = numeric(context, matrix, &columns, role.rows(), tokens, cache.chunk_modules(binding, context)?)?; + validate_values(&outputs, tokens.checked_mul(role.rows()).ok_or(Error::Overflow)?)?; let mut result = Vec::new(); - result - .try_reserve_exact(tokens) - .map_err(|_| Error::InputAllocation)?; + result.try_reserve_exact(tokens).map_err(|_| Error::InputAllocation)?; for (source, values) in inputs.iter().zip(outputs.chunks_exact(role.rows())) { let mut owned = Vec::new(); - owned - .try_reserve_exact(role.rows()) - .map_err(|_| Error::InputAllocation)?; + owned.try_reserve_exact(role.rows()).map_err(|_| Error::InputAllocation)?; owned.extend_from_slice(values); result.push(ProjectionRow { binding: binding.identity(), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs index 92ca85f6..4cbd29a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs @@ -3,8 +3,8 @@ use super::contract::{Error, LayerId, Result, Stage, TokenLayer}; use super::dense_weight_cache::DenseWeightCache; use super::qsa_index::{ - QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project, - project_cached_out, release, upload, upload_bytes, validate_values, + QsaPrepared, QsaSelectedCache, admit_budget, allocate, download, driver_error, project, project_cached_out, + release, upload, upload_bytes, validate_values, }; use super::session::QwenStepTxn; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, QsaMatrixRole}; @@ -63,18 +63,9 @@ mod tests { assert_eq!(validate_values(&[f32::NAN], 1), Err(Error::NonFinite)); assert_eq!(validate_values(&[f32::INFINITY], 1), Err(Error::NonFinite)); assert_eq!(validate_values(&[], Q), Err(Error::InvalidDimension)); - assert_eq!( - super::super::qsa_index::validate_ids(&[], 1), - Err(Error::InvalidDimension) - ); - assert_eq!( - super::super::qsa_index::validate_ids(&[1, 0], 2), - Err(Error::InvalidPosition) - ); - assert_eq!( - super::super::qsa_index::validate_ids(&[0, 0], 2), - Err(Error::InvalidPosition) - ); + assert_eq!(super::super::qsa_index::validate_ids(&[], 1), Err(Error::InvalidDimension)); + assert_eq!(super::super::qsa_index::validate_ids(&[1, 0], 2), Err(Error::InvalidPosition)); + assert_eq!(super::super::qsa_index::validate_ids(&[0, 0], 2), Err(Error::InvalidPosition)); } } @@ -116,17 +107,17 @@ mod impl_qsaready; use impl_qsaready::decode_cached; mod decode_selected_cached_fn; #[allow(unused_imports)] -use decode_selected_cached_fn::decode_selected_cached; -#[allow(unused_imports)] use decode_selected_cached_fn::attend_retained; #[allow(unused_imports)] +use decode_selected_cached_fn::attention_driver_error; +#[allow(unused_imports)] +use decode_selected_cached_fn::decode_selected_cached; +#[allow(unused_imports)] use decode_selected_cached_fn::gate_retained; #[allow(unused_imports)] +use decode_selected_cached_fn::release_retained; +#[allow(unused_imports)] use decode_selected_cached_fn::upload_retained_bytes; #[allow(unused_imports)] use decode_selected_cached_fn::upload_retained_f32; -#[allow(unused_imports)] -use decode_selected_cached_fn::release_retained; -#[allow(unused_imports)] -use decode_selected_cached_fn::attention_driver_error; mod impl_nativeattended; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs index c6c61625..7f28200d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/decode_selected_cached_fn.rs @@ -30,10 +30,7 @@ pub(super) fn decode_selected_cached( let cleanup = release_retained([q]); if result.is_err() || cleanup.is_err() { let y_cleanup = release_retained([y]); - if cleanup.is_err() - || y_cleanup.is_err() - || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) - { + if cleanup.is_err() || y_cleanup.is_err() || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { failed.set(true); } let _ = result?; @@ -41,23 +38,14 @@ pub(super) fn decode_selected_cached( y_cleanup?; return Err(Error::CudaExecution); } - let attended = QsaAttended { - context, - buffer: y, - values: result?, - failed, - }; + let attended = QsaAttended { context, buffer: y, values: result?, failed }; let gated = gate_retained(context, attended, prepared.gate())?; let result = project_cached_out(context, binding, prepared.weights(), &gated, cache); let cleanup = gated.close(); let output = result?; cleanup?; validate_values(&output, 2560)?; - Ok(QsaReady { - identity: prepared.identity(), - binding: binding.identity(), - output, - }) + Ok(QsaReady { identity: prepared.identity(), binding: binding.identity(), output }) } pub(super) fn attend_retained<'ctx>( context: &'ctx Context<'ctx>, @@ -74,21 +62,13 @@ pub(super) fn attend_retained<'ctx>( if width == 0 || width > 2051 { return Err(Error::InvalidDimension); } - let bytes = usize::try_from(width) - .map_err(|_| Error::Overflow)? - .checked_mul(1024) - .ok_or(Error::Overflow)?; + let bytes = usize::try_from(width).map_err(|_| Error::Overflow)?.checked_mul(1024).ok_or(Error::Overflow)?; if keys.len() != bytes || values.len() != bytes { return Err(Error::InvalidDimension); } // These canonical FP16 words are already checked by selected_kv in serving. // Repeat the same domain guard for this closed component seam before upload. - for word in keys - .as_chunks::<2>() - .0 - .iter() - .chain(values.as_chunks::<2>().0) - { + for word in keys.as_chunks::<2>().0.iter().chain(values.as_chunks::<2>().0) { if u16::from_le_bytes(*word) & 0x7c00 == 0x7c00 { return Err(Error::NonFinite); } @@ -114,10 +94,7 @@ pub(super) fn attend_retained<'ctx>( let cleanup = release_retained([q, k, v]); if result.is_err() || cleanup.is_err() { let y_cleanup = release_retained([y]); - if cleanup.is_err() - || y_cleanup.is_err() - || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) - { + if cleanup.is_err() || y_cleanup.is_err() || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { failed.set(true); } let _ = result?; @@ -125,12 +102,7 @@ pub(super) fn attend_retained<'ctx>( y_cleanup?; return Err(Error::CudaExecution); } - Ok(QsaAttended { - context, - buffer: y, - values: result?, - failed, - }) + Ok(QsaAttended { context, buffer: y, values: result?, failed }) } pub(super) fn gate_retained<'ctx>( context: &'ctx Context<'ctx>, @@ -165,10 +137,7 @@ pub(super) fn gate_retained<'ctx>( let cleanup = release_retained([attended.buffer.take(), gate]); if result.is_err() || cleanup.is_err() { let gated_cleanup = release_retained([gated]); - if cleanup.is_err() - || gated_cleanup.is_err() - || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) - { + if cleanup.is_err() || gated_cleanup.is_err() || result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { attended.failed.set(true); } let _ = result?; @@ -176,21 +145,14 @@ pub(super) fn gate_retained<'ctx>( gated_cleanup?; return Err(Error::CudaExecution); } - Ok(QsaGated { - context, - buffer: gated, - values: result?, - failed: attended.failed, - }) + Ok(QsaGated { context, buffer: gated, values: result?, failed: attended.failed }) } pub(super) fn upload_retained_bytes<'ctx>( context: &'ctx Context<'ctx>, bytes: &[u8], failed: &Cell, ) -> Result> { - let mut buffer = context - .allocate(bytes.len()) - .map_err(attention_driver_error)?; + let mut buffer = context.allocate(bytes.len()).map_err(attention_driver_error)?; if let Err(primary) = buffer.copy_from(bytes).map_err(attention_driver_error) { failed.set(true); let _ = buffer.release(); @@ -206,9 +168,7 @@ pub(super) fn upload_retained_f32<'ctx>( validate_values(values, values.len())?; let count = values.len().checked_mul(4).ok_or(Error::Overflow)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(count) - .map_err(|_| Error::InputAllocation)?; + bytes.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs index d961398a..b601f8a1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_nativeattended.rs @@ -25,8 +25,7 @@ impl NativeAttended<'_, '_> { context: &Context<'_>, proof: &super::super::session::chunk::PreparedLayerRow, ) -> Result<()> { - self.origin - .validate_projection_branch(chunk.original_session()?)?; + self.origin.validate_projection_branch(chunk.original_session()?)?; chunk.validate_prepared_attention_input(proof, self.source)?; cache.retained_context(binding, context)?; let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; @@ -76,11 +75,7 @@ impl NativeAttended<'_, '_> { return Err(Error::IdentityMismatch); } let output = output.take(&binding.identity(), self.identity, self.context)?; - Ok(QsaReady { - identity: self.identity, - binding: binding.identity(), - output, - }) + Ok(QsaReady { identity: self.identity, binding: binding.identity(), output }) } } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -103,41 +98,33 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { chunk.validate_prompt_qsa_prior(layer, prior)?; let snapshot = prior.native_snapshot(kv)?.clone(); let t = index.rows(); - let append = - index.with_completed_before_causal(binding, cache, chunk, |k, v, _, _, _| { - let inputs = leleka_cuda_driver::QsaKvInputs::new(k, v, t) - .map_err(attention_driver_error)?; - if t>64 {kv.append_for_prompt(workspace, stage, &snapshot, &inputs)}else{kv.append(workspace, stage, &snapshot, &inputs)} - .map_err(attention_driver_error) - })?; + let append = index.with_completed_before_causal(binding, cache, chunk, |k, v, _, _, _| { + let inputs = leleka_cuda_driver::QsaKvInputs::new(k, v, t).map_err(attention_driver_error)?; + if t > 64 { + kv.append_for_prompt(workspace, stage, &snapshot, &inputs) + } else { + kv.append(workspace, stage, &snapshot, &inputs) + } + .map_err(attention_driver_error) + })?; if append.rows() != t { return Err(Error::IdentityMismatch); } - let values = - index.with_completed_before_causal(binding, cache, chunk, |_, _, q, ids, steps| { - let inputs = leleka_cuda_driver::QsaAttentionInputs::new(q, ids, steps, t) - .map_err(attention_driver_error)?; - let completed = attention - .attend(workspace, stage, kv, append.final_snapshot(), &inputs) - .map_err(attention_driver_error)?; - if completed.rows() != t { - return Err(Error::IdentityMismatch); - } - completed.into_values().map_err(attention_driver_error) - })?; + let values = index.with_completed_before_causal(binding, cache, chunk, |_, _, q, ids, steps| { + let inputs = + leleka_cuda_driver::QsaAttentionInputs::new(q, ids, steps, t).map_err(attention_driver_error)?; + let completed = attention + .attend(workspace, stage, kv, append.final_snapshot(), &inputs) + .map_err(attention_driver_error)?; + if completed.rows() != t { + return Err(Error::IdentityMismatch); + } + completed.into_values().map_err(attention_driver_error) + })?; validate_values(&values, t * Q)?; chunk.validate_prompt_qsa_prior(layer, prior)?; let provider = cache.qsa(binding, layer.get())?.weights.clone(); - Ok(Self { - index, - append, - values, - binding: binding.identity(), - layer, - context, - origin, - provider, - }) + Ok(Self { index, append, values, binding: binding.identity(), layer, context, origin, provider }) } /// This is the genuine causal row callback, never a batch-final relabel. pub(in super::super) fn publish_row( @@ -167,17 +154,10 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { { return Err(Error::IdentityMismatch); } - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; let prior = txn.qsa_prior(layer)?; - let prefix = self - .index - .prefix_for_txn(binding, cache, txn, layer, input, &prior)?; - let snapshot = self - .append - .snapshot_after(local) - .map_err(attention_driver_error)?; + let prefix = self.index.prefix_for_txn(binding, cache, txn, layer, input, &prior)?; + let snapshot = self.append.snapshot_after(local).map_err(attention_driver_error)?; let pending = super::super::qsa_index::QsaPending::from_prompt_completion( &prior, input.identity(), @@ -187,16 +167,9 @@ impl<'source, 'lease, 'ctx> NativePromptAttentionBatch<'source, 'lease, 'ctx> { )?; let mut values = Vec::new(); let mut gate = Vec::new(); - values - .try_reserve_exact(Q) - .map_err(|_| Error::InputAllocation)?; - gate.try_reserve_exact(Q) - .map_err(|_| Error::InputAllocation)?; - values.extend_from_slice( - self.values - .get(local * Q..(local + 1) * Q) - .ok_or(Error::InvalidPosition)?, - ); + values.try_reserve_exact(Q).map_err(|_| Error::InputAllocation)?; + gate.try_reserve_exact(Q).map_err(|_| Error::InputAllocation)?; + values.extend_from_slice(self.values.get(local * Q..(local + 1) * Q).ok_or(Error::InvalidPosition)?); gate.extend_from_slice(self.index.gate(local)?); validate_values(&values, Q)?; validate_values(&gate, Q)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs index 4fd7a2df..6026c4d3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention/impl_qsaready.rs @@ -28,18 +28,10 @@ impl QsaAttentionStage { ) -> Result { let context = cache.retained_context(binding, txn.cuda_context()?)?; let mut resources = cache.native_qsa(binding, context)?; - let mut workspace = cache - .native_batch_workspace(binding, context)? - .ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; let slot = super::super::qsa_native_resources::NativeQsaResources::layer_slot(layer.get())?; - let super::super::qsa_native_resources::NativeQsaResources { - index, - stage, - decode, - gate, - kv, - .. - } = &mut *resources; + let super::super::qsa_native_resources::NativeQsaResources { index, stage, decode, gate, kv, .. } = + &mut *resources; let kv = kv.get_mut(slot).ok_or(Error::InvalidLayer)?; let prior = txn.native_qsa_prior(layer, kv)?; let selected = super::super::qsa_decode_index::QsaDecodeIndex::prepare( @@ -66,16 +58,11 @@ impl QsaAttentionStage { gate.as_mut().ok_or(Error::IdentityMismatch)?, &mut workspace, )?; - let (identity, output, pending) = - completed.into_parts(binding, cache, txn, layer, input)?; + let (identity, output, pending) = completed.into_parts(binding, cache, txn, layer, input)?; // Only the actual native completion can reach the canonical pending // journal. The ordinary joint transaction still owns publication. txn.stage_qsa(&prior, pending)?; - Ok(QsaReady { - identity, - binding: binding.identity(), - output, - }) + Ok(QsaReady { identity, binding: binding.identity(), output }) } pub(in super::super) fn decode( binding: &ModelBinding, @@ -85,9 +72,8 @@ impl QsaAttentionStage { cache: Option<&DenseWeightCache<'_>>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Qsa, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); txn.validate_binding(&binding.identity())?; prepared.validate_binding(&binding.identity())?; prepared.validate_for(txn.token(), txn.position(), layer)?; @@ -119,34 +105,19 @@ impl QsaAttentionStage { let k = upload_bytes(context, &k)?; let v = upload_bytes(context, &v)?; let mut y = allocate(context, Q)?; - context - .qsa_attend(&q, &k, &v, &mut y, width) - .map_err(attention_driver_error)?; + context.qsa_attend(&q, &k, &v, &mut y, width).map_err(attention_driver_error)?; // Refuse failure-only NaN before a following gate could mask it. let attended = download(&y, Q)?; release([q, k, v, y])?; let a = upload(context, &attended)?; let gate = upload(context, prepared.gate())?; let mut gated = allocate(context, Q)?; - context - .qsa_gate_f32(&a, &gate, &mut gated) - .map_err(attention_driver_error)?; + context.qsa_gate_f32(&a, &gate, &mut gated).map_err(attention_driver_error)?; let activation = download(&gated, Q)?; release([a, gate, gated])?; - let output = project( - context, - binding, - prepared.weights(), - QsaMatrixRole::Out, - &activation, - cache, - )?; + let output = project(context, binding, prepared.weights(), QsaMatrixRole::Out, &activation, cache)?; validate_values(&output, 2560)?; - Ok(QsaReady { - identity: prepared.identity(), - binding: binding.identity(), - output, - }) + Ok(QsaReady { identity: prepared.identity(), binding: binding.identity(), output }) } } impl<'ctx> QsaGated<'ctx> { @@ -168,10 +139,7 @@ impl<'ctx> QsaGated<'ctx> { } pub(super) fn close(mut self) -> Result<()> { let primary = self.failed.get().then_some(Error::CudaExecution); - let cleanup = self - .buffer - .take() - .map_or(Ok(()), |v| v.release().map_err(attention_driver_error)); + let cleanup = self.buffer.take().map_or(Ok(()), |v| v.release().map_err(attention_driver_error)); if cleanup.is_err() { self.failed.set(true); } @@ -196,9 +164,5 @@ pub(super) fn decode_cached( let output = result?; cleanup?; validate_values(&output, 2560)?; - Ok(QsaReady { - identity: prepared.identity(), - binding: binding.identity(), - output, - }) + Ok(QsaReady { identity: prepared.identity(), binding: binding.identity(), output }) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs index 8ad76c31..5968e9cf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_reuse_gpu.rs @@ -27,16 +27,10 @@ fn half_kv(width: usize, zero: bool) -> (Vec, Vec) { // Original qsa.cu selected layout: ((cell*2+head)*256+dimension). const KEY: [u16; 6] = [0x0000, 0x3400, 0xb800, 0x3a00, 0xbc00, 0x3800]; const VALUE: [u16; 6] = [0x3c00, 0xbc00, 0x4000, 0xb800, 0x3400, 0x4200]; - let keys = (0..width * 512) - .flat_map(|i| KEY[(i * 7 + i / 256) % 6].to_le_bytes()) - .collect(); + let keys = (0..width * 512).flat_map(|i| KEY[(i * 7 + i / 256) % 6].to_le_bytes()).collect(); let values = (0..width * 512) .flat_map(|i| { - let word = if zero { - if i % 2 == 0 { 0x8000u16 } else { 0 } - } else { - VALUE[(i * 11 + i / 512) % 6] - }; + let word = if zero { if i % 2 == 0 { 0x8000u16 } else { 0 } } else { VALUE[(i * 11 + i / 512) % 6] }; word.to_le_bytes() }) .collect(); @@ -68,17 +62,7 @@ fn original_transfer_chain( release([a, g, y]).unwrap(); let a = upload(context, &gated).unwrap(); let mut y = allocate(context, 2560).unwrap(); - context - .bf16_f32( - matrix, - &a, - &mut y, - Bf16ProjectionShape { - rows: 2560, - columns: Q, - }, - ) - .unwrap(); + context.bf16_f32(matrix, &a, &mut y, Bf16ProjectionShape { rows: 2560, columns: Q }).unwrap(); let out = download(&y, 2560).unwrap(); release([a, y]).unwrap(); (attended, gated, out) @@ -95,69 +79,33 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { let matrix = upload_bytes(&context, &weights).unwrap(); for (width, zero) in [(1u32, false), (65, true)] { let query: Vec = (0..Q) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - (i % 17) as f32 / 64. - 8. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 17) as f32 / 64. - 8. / 64. }) .collect(); let gate: Vec = (0..Q) - .map(|i| { - if zero { - if i % 2 == 0 { -0. } else { 0. } - } else { - (i % 13) as f32 / 8. - 6. / 8. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } else { (i % 13) as f32 / 8. - 6. / 8. }) .collect(); let query_bits: Vec = query.iter().map(|v| v.to_bits()).collect(); let gate_bits: Vec = gate.iter().map(|v| v.to_bits()).collect(); let (keys, values) = half_kv(width as usize, zero); - let legacy = - original_transfer_chain(&context, &query, &keys, &values, &gate, width, &matrix); + let legacy = original_transfer_chain(&context, &query, &keys, &values, &gate, width, &matrix); let charged = context.allocated_bytes(); - let attended = - attend_retained(&context, &query, &keys, &values, width, failed.clone()).unwrap(); + let attended = attend_retained(&context, &query, &keys, &values, width, failed.clone()).unwrap(); exact(&attended.values, &legacy.0); assert_eq!(context.allocated_bytes(), charged + Q * 4); let gated = gate_retained(&context, attended, &gate).unwrap(); exact(gated.values(), &legacy.1); assert_eq!(context.allocated_bytes(), charged + Q * 4); let mut actual_bytes = vec![0; Q * 4]; - gated - .buffer(&context) - .unwrap() - .copy_to(&mut actual_bytes) - .unwrap(); - assert_eq!( - actual_bytes, - legacy - .1 - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); - let actual = super::super::qsa_index::project_out_numeric( - &context, - &matrix, - QsaMatrixKind::Bf16, - &gated, - &failed, - ) - .unwrap(); + gated.buffer(&context).unwrap().copy_to(&mut actual_bytes).unwrap(); + assert_eq!(actual_bytes, legacy.1.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let actual = + super::super::qsa_index::project_out_numeric(&context, &matrix, QsaMatrixKind::Bf16, &gated, &failed) + .unwrap(); exact(&actual, &legacy.2); gated.close().unwrap(); assert_eq!(context.allocated_bytes(), charged); - assert_eq!( - query.iter().map(|v| v.to_bits()).collect::>(), - query_bits - ); - assert_eq!( - gate.iter().map(|v| v.to_bits()).collect::>(), - gate_bits - ); + assert_eq!(query.iter().map(|v| v.to_bits()).collect::>(), query_bits); + assert_eq!(gate.iter().map(|v| v.to_bits()).collect::>(), gate_bits); println!("QSA_RETAINED PAIR width={width} zero={zero} exact_words=14848"); } let mut unchanged = vec![0; weights.len()]; @@ -181,38 +129,22 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { ); let mut bad_query = query.clone(); bad_query[Q - 1] = f32::from_bits(0x7fc00001); - assert_eq!( - attend_retained(&context, &bad_query, &keys, &values, 1, failed.clone()).err(), - Some(Error::NonFinite) - ); + assert_eq!(attend_retained(&context, &bad_query, &keys, &values, 1, failed.clone()).err(), Some(Error::NonFinite)); assert_eq!( attend_retained(&context, &query, &keys[..1022], &values, 1, failed.clone()).err(), Some(Error::InvalidDimension) ); let mut bad_keys = keys.clone(); bad_keys[1022..].copy_from_slice(&0x7c00u16.to_le_bytes()); - assert_eq!( - attend_retained(&context, &query, &bad_keys, &values, 1, failed.clone()).err(), - Some(Error::NonFinite) - ); + assert_eq!(attend_retained(&context, &query, &bad_keys, &values, 1, failed.clone()).err(), Some(Error::NonFinite)); let mut bad_values = values.clone(); bad_values[1022..].copy_from_slice(&0x7e01u16.to_le_bytes()); - assert_eq!( - attend_retained(&context, &query, &keys, &bad_values, 1, failed.clone()).err(), - Some(Error::NonFinite) - ); + assert_eq!(attend_retained(&context, &query, &keys, &bad_values, 1, failed.clone()).err(), Some(Error::NonFinite)); // All operands are finite, but the original F32 dot overflows. The actual // retained attention's full D2H rejects before a gate can mask the failure. assert_eq!( - attend_retained( - &context, - &vec![f32::MAX; Q], - &0x7bffu16.to_le_bytes().repeat(512), - &values, - 1, - failed.clone() - ) - .err(), + attend_retained(&context, &vec![f32::MAX; Q], &0x7bffu16.to_le_bytes().repeat(512), &values, 1, failed.clone()) + .err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), 0); @@ -222,24 +154,13 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { let mut bad_gate = gate.clone(); bad_gate[Q - 1] = f32::NAN; for malformed in [&bad_gate[..], &gate[..Q - 1]] { - let expected = if malformed.len() == Q { - Error::NonFinite - } else { - Error::InvalidDimension - }; - let attended = - attend_retained(&context, &query, &keys, &values, 1, failed.clone()).unwrap(); - assert_eq!( - gate_retained(&context, attended, malformed).err(), - Some(expected) - ); + let expected = if malformed.len() == Q { Error::NonFinite } else { Error::InvalidDimension }; + let attended = attend_retained(&context, &query, &keys, &values, 1, failed.clone()).unwrap(); + assert_eq!(gate_retained(&context, attended, malformed).err(), Some(expected)); assert_eq!(context.allocated_bytes(), 0); } let attended = attend_retained(&context, &query, &keys, &values, 1, failed.clone()).unwrap(); - assert_eq!( - gate_retained(&foreign, attended, &gate).err(), - Some(Error::IdentityMismatch) - ); + assert_eq!(gate_retained(&foreign, attended, &gate).err(), Some(Error::IdentityMismatch)); assert_eq!(context.allocated_bytes(), 0); assert_eq!(foreign.allocated_bytes(), 0); @@ -249,14 +170,7 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { let malformed = upload_bytes(&context, &[0; 2]).unwrap(); let charged = context.allocated_bytes(); assert_eq!( - super::super::qsa_index::project_out_numeric( - &context, - &malformed, - QsaMatrixKind::Bf16, - &gated, - &failed - ) - .err(), + super::super::qsa_index::project_out_numeric(&context, &malformed, QsaMatrixKind::Bf16, &gated, &failed).err(), Some(Error::InvalidDimension) ); assert_eq!(context.allocated_bytes(), charged); @@ -267,14 +181,7 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { let matrix = upload_bytes(&context, &bad_weights).unwrap(); let charged = context.allocated_bytes(); assert_eq!( - super::super::qsa_index::project_out_numeric( - &context, - &matrix, - QsaMatrixKind::Bf16, - &gated, - &failed - ) - .err(), + super::super::qsa_index::project_out_numeric(&context, &matrix, QsaMatrixKind::Bf16, &gated, &failed).err(), Some(Error::NonFinite) ); assert_eq!(context.allocated_bytes(), charged); @@ -282,20 +189,10 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { // Explicit shared-policy flag, not injected device failure. No operation // may clear it; teardown still frees the actual successful owner and matrix. failed.set(true); - assert_eq!( - attend_retained(&context, &query, &keys, &values, 1, failed.clone()).err(), - Some(Error::CudaExecution) - ); + assert_eq!(attend_retained(&context, &query, &keys, &values, 1, failed.clone()).err(), Some(Error::CudaExecution)); assert_eq!(gated.buffer(&context).err(), Some(Error::CudaExecution)); assert_eq!( - super::super::qsa_index::project_out_numeric( - &context, - &matrix, - QsaMatrixKind::Bf16, - &gated, - &failed - ) - .err(), + super::super::qsa_index::project_out_numeric(&context, &matrix, QsaMatrixKind::Bf16, &gated, &failed).err(), Some(Error::CudaExecution) ); assert_eq!(context.allocated_bytes(), charged); @@ -306,7 +203,5 @@ fn retained_attention_gate_out_matches_legacy_transfers_and_cleans_refusals() { context.synchronize().unwrap(); context.close().unwrap(); foreign.close().unwrap(); - println!( - "QSA_RETAINED COMPLETE exact_words=29696 finite_cases=2 guard_refusals=17 allocated=0" - ); + println!("QSA_RETAINED COMPLETE exact_words=29696 finite_cases=2 guard_refusals=17 allocated=0"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs index 6b52d4fb..0890ac25 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch.rs @@ -29,20 +29,28 @@ impl<'ctx> QsaAttentionScratch<'ctx> { context: &'ctx Context<'ctx>, failed: Rc>, ) -> Result { - Ok(Self { binding: binding.identity(), + Ok(Self { + binding: binding.identity(), #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] completed_rows: Cell::new(0), - buffers: ScratchBuffers::new(context, failed)? }) + buffers: ScratchBuffers::new(context, failed)?, + }) } pub(in crate::qwen_forward) fn allocated_bytes(&self) -> usize { self.buffers.roles.iter().flatten().map(DeviceBuffer::len).sum() } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(in crate::qwen_forward) fn completed_rows(&self) -> u64 { self.completed_rows.get() } - pub(in crate::qwen_forward) fn close(self) -> Result<()> { self.buffers.close() } + pub(in crate::qwen_forward) fn completed_rows(&self) -> u64 { + self.completed_rows.get() + } + pub(in crate::qwen_forward) fn close(self) -> Result<()> { + self.buffers.close() + } fn lease<'slot, 'prepared>( - mut slot: RefMut<'slot, Self>, binding: &ModelBinding, - context: &Context<'_>, prepared: &'prepared QsaPrepared, + mut slot: RefMut<'slot, Self>, + binding: &ModelBinding, + context: &Context<'_>, + prepared: &'prepared QsaPrepared, ) -> Result> { prepared.validate_binding(&binding.identity())?; if !slot.binding.matches(&binding.identity()) || !std::ptr::eq(slot.buffers.context, context) { @@ -55,13 +63,17 @@ impl<'ctx> QsaAttentionScratch<'ctx> { } impl<'ctx> ScratchBuffers<'ctx> { fn new(context: &'ctx Context<'ctx>, failed: Rc>) -> Result { - if failed.get() || context.is_poisoned() { return Err(Error::CudaExecution); } + if failed.get() || context.is_poisoned() { + return Err(Error::CudaExecution); + } let required = SCRATCH_BYTES.checked_add(128 * 1024 * 1024).ok_or(Error::Overflow)?; if context.allocated_bytes().checked_add(required).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } let (free, _) = context.memory_info().map_err(attention_driver_error)?; - if free < required { return Err(Error::InputAllocation); } + if free < required { + return Err(Error::InputAllocation); + } let mut buffers = Self { context, failed, roles: std::array::from_fn(|_| None), attended: None, gated: None }; let result: Result<()> = (|| { for (index, size) in SIZES.into_iter().enumerate() { @@ -84,21 +96,30 @@ impl<'ctx> ScratchBuffers<'ctx> { Ok(buffers) } fn validate(&self) -> Result<()> { - if self.failed.get() || self.context.is_poisoned() { return Err(Error::CudaExecution); } + if self.failed.get() || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } if self.roles.iter().zip(SIZES).any(|(b, n)| b.as_ref().is_none_or(|v| v.len() != n)) { return Err(Error::InvalidDimension); } Ok(()) } - fn reset(&mut self) { self.attended = None; self.gated = None; } + fn reset(&mut self) { + self.attended = None; + self.gated = None; + } fn note(&self, error: Error) { - if error == Error::CudaExecution || self.context.is_poisoned() { self.failed.set(true); } + if error == Error::CudaExecution || self.context.is_poisoned() { + self.failed.set(true); + } } fn put_f32(&mut self, index: usize, values: &[f32]) -> Result<()> { validate_values(values, Q)?; let mut bytes = Vec::new(); bytes.try_reserve_exact(Q * 4).map_err(|_| Error::InputAllocation)?; - for value in values { bytes.extend_from_slice(&value.to_le_bytes()); } + for value in values { + bytes.extend_from_slice(&value.to_le_bytes()); + } if let Err(error) = self.roles[index].as_mut().ok_or(Error::CudaExecution)?.copy_from(&bytes) { // Exact original upload_retained_bytes sticky-copy policy. self.failed.set(true); @@ -107,10 +128,16 @@ impl<'ctx> ScratchBuffers<'ctx> { Ok(()) } // Runtime closure is ONLY the actual selected cache's checked attend call. - fn attend_by(&mut self, query: &[f32], attend: impl FnOnce(&DeviceBuffer<'ctx>, &mut DeviceBuffer<'ctx>) -> Result<()>) -> Result<()> { + fn attend_by( + &mut self, + query: &[f32], + attend: impl FnOnce(&DeviceBuffer<'ctx>, &mut DeviceBuffer<'ctx>) -> Result<()>, + ) -> Result<()> { let result = (|| { self.validate()?; - if self.attended.is_some() || self.gated.is_some() { return Err(Error::IdentityMismatch); } + if self.attended.is_some() || self.gated.is_some() { + return Err(Error::IdentityMismatch); + } self.put_f32(0, query)?; let (q, rest) = self.roles.split_at_mut(1); attend(q[0].as_ref().ok_or(Error::CudaExecution)?, rest[0].as_mut().ok_or(Error::CudaExecution)?)?; @@ -118,52 +145,72 @@ impl<'ctx> ScratchBuffers<'ctx> { self.attended = Some(download(self.roles[1].as_ref().ok_or(Error::CudaExecution)?, Q)?); Ok(()) })(); - if let Err(error) = result { self.note(error); } + if let Err(error) = result { + self.note(error); + } result } fn gate(&mut self, values: &[f32]) -> Result<()> { let result = (|| { self.validate()?; validate_values(self.attended.as_deref().ok_or(Error::IdentityMismatch)?, Q)?; - if self.gated.is_some() { return Err(Error::IdentityMismatch); } + if self.gated.is_some() { + return Err(Error::IdentityMismatch); + } validate_values(values, Q)?; self.put_f32(2, values)?; let (inputs, outputs) = self.roles.split_at_mut(3); - self.context.qsa_gate_f32( - inputs[1].as_ref().ok_or(Error::CudaExecution)?, - inputs[2].as_ref().ok_or(Error::CudaExecution)?, - outputs[0].as_mut().ok_or(Error::CudaExecution)?, - ).map_err(attention_driver_error)?; + self.context + .qsa_gate_f32( + inputs[1].as_ref().ok_or(Error::CudaExecution)?, + inputs[2].as_ref().ok_or(Error::CudaExecution)?, + outputs[0].as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(attention_driver_error)?; self.gated = Some(download(outputs[0].as_ref().ok_or(Error::CudaExecution)?, Q)?); Ok(()) })(); - if let Err(error) = result { self.note(error); } + if let Err(error) = result { + self.note(error); + } result } fn close(mut self) -> Result<()> { let primary = (self.failed.get() || self.context.is_poisoned()).then_some(Error::CudaExecution); self.reset(); let cleanup = release_retained(std::mem::replace(&mut self.roles, std::array::from_fn(|_| None))); - if cleanup.is_err() { self.failed.set(true); } + if cleanup.is_err() { + self.failed.set(true); + } primary.map_or(cleanup, Err) } } impl<'ctx> QsaAttentionLease<'_, '_, 'ctx> { fn validate(&self, binding: &ModelBinding, context: &Context<'_>) -> Result<()> { - if !self.slot.binding.matches(&binding.identity()) || !std::ptr::eq(self.slot.buffers.context, context) - || self.identity != self.prepared.identity() { return Err(Error::IdentityMismatch); } + if !self.slot.binding.matches(&binding.identity()) + || !std::ptr::eq(self.slot.buffers.context, context) + || self.identity != self.prepared.identity() + { + return Err(Error::IdentityMismatch); + } self.prepared.validate_binding(&binding.identity())?; self.slot.buffers.validate() } pub(super) fn project_out( - &mut self, binding: &ModelBinding, context: &Context<'_>, cache: &DenseWeightCache<'_>, + &mut self, + binding: &ModelBinding, + context: &Context<'_>, + cache: &DenseWeightCache<'_>, ) -> Result> { self.validate(binding, context)?; let prepared = self.prepared; super::super::qsa_index::project_cached_out_scratch(context, binding, prepared.weights(), self, cache) } pub(in crate::qwen_forward) fn gated_parts<'a>( - &'a mut self, binding: &ModelBinding, context: &Context<'_>, weights: &crate::model_binding::qwen4exp_input::QsaWeights, + &'a mut self, + binding: &ModelBinding, + context: &Context<'_>, + weights: &crate::model_binding::qwen4exp_input::QsaWeights, ) -> Result<(&'a DeviceBuffer<'ctx>, &'a mut DeviceBuffer<'ctx>)> { self.validate(binding, context)?; if !std::ptr::eq(weights, self.prepared.weights()) || weights.layer() != self.identity.layer().get() { @@ -174,7 +221,9 @@ impl<'ctx> QsaAttentionLease<'_, '_, 'ctx> { Ok((inputs[3].as_ref().ok_or(Error::CudaExecution)?, outputs[0].as_mut().ok_or(Error::CudaExecution)?)) } pub(in crate::qwen_forward) fn note_result(&self, result: &Result>) { - if let Err(error) = result { self.slot.buffers.note(*error); } + if let Err(error) = result { + self.slot.buffers.note(*error); + } } } impl Drop for QsaAttentionLease<'_, '_, '_> { @@ -187,16 +236,22 @@ impl Drop for QsaAttentionLease<'_, '_, '_> { // New explicit seam only. None/non-selected delegates the entire original body. impl QsaAttentionStage { pub(in crate::qwen_forward) fn decode_with_scratch( - binding: &ModelBinding, layer: LayerId, prepared: QsaPrepared, - txn: &mut QwenStepTxn, cache: Option<&DenseWeightCache<'_>>, + binding: &ModelBinding, + layer: LayerId, + prepared: QsaPrepared, + txn: &mut QwenStepTxn, + cache: Option<&DenseWeightCache<'_>>, scratch: Option<&RefCell>>, ) -> Result { let (Some(scratch), Some(cache)) = (scratch, cache) else { return Self::decode(binding, layer, prepared, txn, cache); }; - if !cache.has_qsa_selected() { return Self::decode(binding, layer, prepared, txn, Some(cache)); } + if !cache.has_qsa_selected() { + return Self::decode(binding, layer, prepared, txn, Some(cache)); + } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); txn.validate_binding(&binding.identity())?; prepared.validate_binding(&binding.identity())?; prepared.validate_for(txn.token(), txn.position(), layer)?; @@ -204,7 +259,9 @@ impl QsaAttentionStage { validate_values(prepared.q(), Q)?; validate_values(prepared.gate(), Q)?; let width = u32::try_from(prepared.ids().len()).map_err(|_| Error::Overflow)?; - if width == 0 || width > 2051 { return Err(Error::InvalidDimension); } + if width == 0 || width > 2051 { + return Err(Error::InvalidDimension); + } let context = txn.cuda_context()?; admit_budget(context)?; let Some(mut selected) = cache.qsa_selected(binding, layer.get(), context)? else { @@ -213,9 +270,13 @@ impl QsaAttentionStage { let context = cache.retained_context(binding, context)?; let failed = cache.transport_failure_flag(binding, context)?; let slot = scratch.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?; - if !Rc::ptr_eq(&slot.buffers.failed, &failed) { return Err(Error::IdentityMismatch); } + if !Rc::ptr_eq(&slot.buffers.failed, &failed) { + return Err(Error::IdentityMismatch); + } let mut loan = QsaAttentionScratch::lease(slot, binding, context, &prepared)?; - loan.slot.buffers.attend_by(prepared.q(), |q, y| selected.attend(&binding.identity(), context, &prepared, q, y))?; + loan.slot + .buffers + .attend_by(prepared.q(), |q, y| selected.attend(&binding.identity(), context, &prepared, q, y))?; loan.slot.buffers.gate(prepared.gate())?; // Out source/cache acquisition is deliberately AFTER both finite boundaries. let output = loan.project_out(binding, context, cache)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs index 632836a6..245c3dae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention_scratch_gpu.rs @@ -6,18 +6,29 @@ use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; fn bits(a: &[f32], b: &[f32]) { assert_eq!(a.len(), b.len()); - for (a, b) in a.iter().zip(b) { assert_eq!(a.to_bits(), b.to_bits()); } + for (a, b) in a.iter().zip(b) { + assert_eq!(a.to_bits(), b.to_bits()); + } } type Products = (Box<[f32]>, Box<[f32]>, Box<[f32]>); #[allow(clippy::too_many_arguments)] // Literal original-first component input tuple. -fn original(context: &Context<'_>, query: &[f32], keys: &[u8], values: &[u8], gate: &[f32], width: u32, matrix: &DeviceBuffer<'_>) -> Result { +fn original( + context: &Context<'_>, + query: &[f32], + keys: &[u8], + values: &[u8], + gate: &[f32], + width: u32, + matrix: &DeviceBuffer<'_>, +) -> Result { // Exact pre-existing retained producer FIRST, including original finite boundaries. let failed = Rc::new(Cell::new(false)); let attended = attend_retained(context, query, keys, values, width, failed.clone())?; let a = attended.values.clone(); let gated = gate_retained(context, attended, gate)?; let g = gated.values().to_vec().into_boxed_slice(); - let result = super::super::super::qsa_index::project_out_numeric(context, matrix, QsaMatrixKind::Bf16, &gated, &failed); + let result = + super::super::super::qsa_index::project_out_numeric(context, matrix, QsaMatrixKind::Bf16, &gated, &failed); let cleanup = gated.close(); let out = result?; cleanup?; @@ -28,8 +39,11 @@ fn project(buffers: &mut ScratchBuffers<'_>, matrix: &DeviceBuffer<'_>) -> Resul validate_values(buffers.gated.as_deref().ok_or(Error::IdentityMismatch)?, Q)?; let (inputs, outputs) = buffers.roles.split_at_mut(4); super::super::super::qsa_index::project_scratch_out_numeric( - buffers.context, matrix, inputs[3].as_ref().ok_or(Error::CudaExecution)?, - outputs[0].as_mut().ok_or(Error::CudaExecution)?, QsaMatrixKind::Bf16, + buffers.context, + matrix, + inputs[3].as_ref().ok_or(Error::CudaExecution)?, + outputs[0].as_mut().ok_or(Error::CudaExecution)?, + QsaMatrixKind::Bf16, ) } @@ -61,21 +75,43 @@ fn original_first_five_role_qsa_scratch_repeat_finite_refusal_and_cleanup() { drop(loan); } for (width, zero, changed) in [(1u32, false, false), (65, false, true), (65, true, false), (1, false, false)] { - let query: Vec = (0..Q).map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } - else { ((i + usize::from(changed)) % 17) as f32 / 64. - 8. / 64. }).collect(); - let gate: Vec = (0..Q).map(|i| if zero { if i % 2 == 0 { -0. } else { 0. } } - else { ((i + usize::from(changed)) % 13) as f32 / 8. - 6. / 8. }).collect(); - let keys: Vec = (0..width as usize * 512).flat_map(|i| [0u16,0x3400,0xb800,0x3a00][i % 4].to_le_bytes()).collect(); - let values: Vec = (0..width as usize * 512).flat_map(|i| { - (if zero { if i % 2 == 0 { 0x8000u16 } else { 0 } } - else { [0x3c00u16,0xbc00,0x4000,0xb800][(i + usize::from(changed)) % 4] }).to_le_bytes() - }).collect(); + let query: Vec = (0..Q) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + ((i + usize::from(changed)) % 17) as f32 / 64. - 8. / 64. + } + }) + .collect(); + let gate: Vec = (0..Q) + .map(|i| { + if zero { + if i % 2 == 0 { -0. } else { 0. } + } else { + ((i + usize::from(changed)) % 13) as f32 / 8. - 6. / 8. + } + }) + .collect(); + let keys: Vec = + (0..width as usize * 512).flat_map(|i| [0u16, 0x3400, 0xb800, 0x3a00][i % 4].to_le_bytes()).collect(); + let values: Vec = (0..width as usize * 512) + .flat_map(|i| { + (if zero { + if i % 2 == 0 { 0x8000u16 } else { 0 } + } else { + [0x3c00u16, 0xbc00, 0x4000, 0xb800][(i + usize::from(changed)) % 4] + }) + .to_le_bytes() + }) + .collect(); let old = original(&context, &query, &keys, &values, &gate, width, &matrix).unwrap(); let k = upload_bytes(&context, &keys).unwrap(); let v = upload_bytes(&context, &values).unwrap(); let mut slot = buffers.borrow_mut(); slot.reset(); - slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)).unwrap(); + slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)) + .unwrap(); bits(slot.attended.as_deref().unwrap(), &old.0); slot.gate(&gate).unwrap(); bits(slot.gated.as_deref().unwrap(), &old.1); @@ -83,31 +119,55 @@ fn original_first_five_role_qsa_scratch_repeat_finite_refusal_and_cleanup() { word_count += 2 * Q + 2560; slot.reset(); for invalid in [f32::NAN, f32::INFINITY] { - let mut bad_query = query.clone(); bad_query[Q - 1] = invalid; - assert!(matches!(original(&context, &bad_query, &keys, &values, &gate, width, &matrix), Err(Error::NonFinite))); - assert!(matches!(slot.attend_by(&bad_query, |_, _| panic!("query must refuse before CUDA callback")), Err(Error::NonFinite))); + let mut bad_query = query.clone(); + bad_query[Q - 1] = invalid; + assert!(matches!( + original(&context, &bad_query, &keys, &values, &gate, width, &matrix), + Err(Error::NonFinite) + )); + assert!(matches!( + slot.attend_by(&bad_query, |_, _| panic!("query must refuse before CUDA callback")), + Err(Error::NonFinite) + )); slot.reset(); // Inject an actual whole output owner, not a synthetic finite capability. - let mut raw = vec![0u8; Q * 4]; raw[(Q - 1) * 4..].copy_from_slice(&invalid.to_le_bytes()); - assert!(matches!(slot.attend_by(&query, |_, y| y.copy_from(&raw).map_err(attention_driver_error)), Err(Error::NonFinite))); + let mut raw = vec![0u8; Q * 4]; + raw[(Q - 1) * 4..].copy_from_slice(&invalid.to_le_bytes()); + assert!(matches!( + slot.attend_by(&query, |_, y| y.copy_from(&raw).map_err(attention_driver_error)), + Err(Error::NonFinite) + )); slot.reset(); - slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)).unwrap(); - let mut bad_gate = gate.clone(); bad_gate[Q - 1] = invalid; - assert!(matches!(original(&context, &query, &keys, &values, &bad_gate, width, &matrix), Err(Error::NonFinite))); + slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)) + .unwrap(); + let mut bad_gate = gate.clone(); + bad_gate[Q - 1] = invalid; + assert!(matches!( + original(&context, &query, &keys, &values, &bad_gate, width, &matrix), + Err(Error::NonFinite) + )); assert!(matches!(slot.gate(&bad_gate), Err(Error::NonFinite))); slot.reset(); } - assert!(matches!(slot.attend_by(&query[..Q-1], |_, _| panic!("extent must refuse first")), Err(Error::InvalidDimension))); + assert!(matches!( + slot.attend_by(&query[..Q - 1], |_, _| panic!("extent must refuse first")), + Err(Error::InvalidDimension) + )); slot.reset(); - assert!(matches!(slot.attend_by(&query, |q, y| foreign.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)), Err(Error::IdentityMismatch))); + assert!(matches!( + slot.attend_by(&query, |q, y| foreign.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)), + Err(Error::IdentityMismatch) + )); slot.reset(); - slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)).unwrap(); + slot.attend_by(&query, |q, y| context.qsa_attend(q, &k, &v, y, width).map_err(attention_driver_error)) + .unwrap(); slot.gate(&gate).unwrap(); bits(&project(&mut slot, &matrix).unwrap(), &old.2); word_count += 2560; assert!(!failed.get()); - slot.reset(); drop(slot); - release([k,v]).unwrap(); + slot.reset(); + drop(slot); + release([k, v]).unwrap(); assert_eq!(context.allocated_bytes(), baseline_charge); } })); @@ -117,8 +177,12 @@ fn original_first_five_role_qsa_scratch_repeat_finite_refusal_and_cleanup() { let allocated = context.allocated_bytes(); let foreign_close = foreign.close(); let context_close = context.close(); - if let Err(primary) = checks { resume_unwind(primary); } - assert!(scratch_close.is_ok() && matrix_close.is_ok() && sync.is_ok() && foreign_close.is_ok() && context_close.is_ok()); + if let Err(primary) = checks { + resume_unwind(primary); + } + assert!( + scratch_close.is_ok() && matrix_close.is_ok() && sync.is_ok() && foreign_close.is_ok() && context_close.is_ok() + ); assert_eq!(allocated, 0); assert_eq!(word_count, 69_632); // Exact typed boundary refuses before any allocation or physical query. diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs index 48e5846d..931f440d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_attention.rs @@ -6,8 +6,7 @@ use super::{ gr::ResidualReady, qsa_decode_index::QsaDecodeIndex, qsa_index::{ - QsaPending, QsaPrior, allocate, download, driver_error, project_scratch_out_numeric, - upload, validate_values, + QsaPending, QsaPrior, allocate, download, driver_error, project_scratch_out_numeric, upload, validate_values, }, session::QwenStepTxn, }; @@ -15,8 +14,8 @@ use crate::model_binding::qwen4exp_input::{ BindingIdentity, GrRole, ModelBinding, QsaMatrixKind, QsaMatrixRole, QsaWeights, }; use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeBatchWorkspace, QsaAttentionInputs, QsaKvInputs, QsaNativeDecode, - QsaNativeGate, QsaPromptKv, QsaPromptStage, + Context, DeviceBuffer, NativeBatchWorkspace, QsaAttentionInputs, QsaKvInputs, QsaNativeDecode, QsaNativeGate, + QsaPromptKv, QsaPromptStage, }; use std::{cell::Cell, rc::Rc}; @@ -88,9 +87,7 @@ pub(super) fn complete<'source, 'lease, 'ctx>( let operation = (|| { index.validate(binding, cache, txn, layer, input)?; txn.validate_qsa_prior(prior, layer)?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; if !std::ptr::eq(index.source(), input) || index.identity() != input.identity() { return Err(Error::IdentityMismatch); @@ -106,17 +103,14 @@ pub(super) fn complete<'source, 'lease, 'ctx>( let snapshot = prior.native_snapshot(kv)?; let append = index.with_completed_kv(binding, cache, txn, |k, v| { let inputs = QsaKvInputs::new(k, v, 1).map_err(driver)?; - kv.append(workspace, stage, snapshot, &inputs) - .map_err(driver) + kv.append(workspace, stage, snapshot, &inputs).map_err(driver) })?; if append.rows() != 1 { return Err(Error::IdentityMismatch); } let attended = index.with_completed_buffers(binding, cache, txn, |q, ids, steps| { let inputs = QsaAttentionInputs::new(q, ids, steps, 1).map_err(driver)?; - let actual = attention - .attend(workspace, kv, append.final_snapshot(), &inputs) - .map_err(driver)?; + let actual = attention.attend(workspace, kv, append.final_snapshot(), &inputs).map_err(driver)?; if actual.rows() != 1 { return Err(Error::IdentityMismatch); } @@ -145,8 +139,7 @@ pub(super) fn complete<'source, 'lease, 'ctx>( } let prefix = index.prefix_for_txn(binding, cache, txn)?; let next = append.snapshot_after(0).map_err(driver)?; - let pending = - QsaPending::from_prompt_completion(prior, input.identity(), next, prefix, kv)?; + let pending = QsaPending::from_prompt_completion(prior, input.identity(), next, prefix, kv)?; pending.validate(prior, input.identity())?; validate_values(&values, 2560)?; Ok(NativeDecodeAttentionRow { @@ -210,9 +203,7 @@ fn gate_and_out<'ctx>( let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?; validate_values(&gated, 6144)?; let entry = cache.qsa(binding, weights.layer())?; - if !std::ptr::eq(entry.weights.as_ref(), weights) - || weights.shape(QsaMatrixRole::Out) != (6144, 2560) - { + if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) { return Err(Error::IdentityMismatch); } let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; @@ -239,8 +230,7 @@ fn gate_and_out<'ctx>( } } } - if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() - { + if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() { failed.set(true); } match operation { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs index 77531014..ed97ea6d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_decode_index.rs @@ -7,12 +7,9 @@ use super::{ qsa_index::{QsaPrior, driver_error, project, validate_values}, session::QwenStepTxn, }; -use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights, -}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights}; use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeBatchWorkspace, QsaPromptIndexPrefix, QsaPromptIndexWorkspace, - QsaPromptSelection, + Context, DeviceBuffer, NativeBatchWorkspace, QsaPromptIndexPrefix, QsaPromptIndexWorkspace, QsaPromptSelection, }; use std::rc::Rc; fn driver(error: leleka_cuda_driver::Error) -> Error { @@ -46,9 +43,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { ) -> Result { txn.validate_binding(&binding.identity())?; txn.validate_input(input.identity().token(), input.identity().position())?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; txn.validate_qsa_prior(prior, layer)?; // Only the actual empty position-zero prior may start a native cache. @@ -76,58 +71,16 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { let txn_owner = txn.residual_handoff_owner()?; // Each result is from the actual closed scalar CUDA projection producer. // No caller supplies bytes/floats as a completed role certificate. - let raw = project( - context, - binding, - &entry.weights, - QsaMatrixRole::IndexK, - input.mixed(), - Some(cache), - )?; - let k = project( - context, - binding, - &entry.weights, - QsaMatrixRole::K, - input.mixed(), - Some(cache), - )?; - let v = project( - context, - binding, - &entry.weights, - QsaMatrixRole::V, - input.mixed(), - Some(cache), - )?; - let qfull = project( - context, - binding, - &entry.weights, - QsaMatrixRole::Q, - input.mixed(), - Some(cache), - )?; - let iq = project( - context, - binding, - &entry.weights, - QsaMatrixRole::IndexQ, - input.mixed(), - Some(cache), - )?; - for (values, n) in [ - (&raw, 128), - (&k, 512), - (&v, 512), - (&qfull, 12288), - (&iq, 512), - ] { + let raw = project(context, binding, &entry.weights, QsaMatrixRole::IndexK, input.mixed(), Some(cache))?; + let k = project(context, binding, &entry.weights, QsaMatrixRole::K, input.mixed(), Some(cache))?; + let v = project(context, binding, &entry.weights, QsaMatrixRole::V, input.mixed(), Some(cache))?; + let qfull = project(context, binding, &entry.weights, QsaMatrixRole::Q, input.mixed(), Some(cache))?; + let iq = project(context, binding, &entry.weights, QsaMatrixRole::IndexQ, input.mixed(), Some(cache))?; + for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] { validate_values(values, n)?; } let mut gate = Vec::new(); - gate.try_reserve_exact(6144) - .map_err(|_| Error::InputAllocation)?; + gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?; for head in 0..24 { gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]); } @@ -136,9 +89,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { let p = u32::try_from(txn.position().get()).map_err(|_| Error::InvalidPosition)?; let gamma = cache.qsa_norms(entry)?; let selected = owner - .append_select_decode( - p, &pooled, &tail, &dead, &raw, &k, &v, &qfull, &iq, gamma, workspace, - ) + .append_select_decode(p, &pooled, &tail, &dead, &raw, &k, &v, &qfull, &iq, gamma, workspace) .map_err(driver)?; let result = Self { binding: binding.identity(), @@ -167,9 +118,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { ) -> Result<()> { txn.validate_binding(&binding.identity())?; txn.validate_input(input.identity().token(), input.identity().position())?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; txn.validate_qsa_prior(&self.prior, layer)?; let context = cache.retained_context(binding, txn.cuda_context()?)?; @@ -207,10 +156,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { f: impl FnOnce(&DeviceBuffer<'_>, &DeviceBuffer<'_>) -> Result, ) -> Result { self.validate(binding, cache, txn, self.layer, self.source)?; - let result = self - .selected - .with_completed_kv(|k, v| Ok(f(k, v))) - .map_err(driver)?; + let result = self.selected.with_completed_kv(|k, v| Ok(f(k, v))).map_err(driver)?; let health = self.validate(binding, cache, txn, self.layer, self.source); match result { Err(primary) => Err(primary), @@ -228,10 +174,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { f: impl FnOnce(&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>) -> Result, ) -> Result { self.validate(binding, cache, txn, self.layer, self.source)?; - let result = self - .selected - .with_completed_buffers(|q, ids, steps| Ok(f(q, ids, steps))) - .map_err(driver)?; + let result = self.selected.with_completed_buffers(|q, ids, steps| Ok(f(q, ids, steps))).map_err(driver)?; let health = self.validate(binding, cache, txn, self.layer, self.source); match result { Err(primary) => Err(primary), @@ -248,10 +191,7 @@ impl<'source, 'lease, 'ctx> QsaDecodeIndex<'source, 'lease, 'ctx> { txn: &QwenStepTxn<'_, '_>, ) -> Result> { self.validate(binding, cache, txn, self.layer, self.source)?; - self.selected - .final_index() - .completed_prefix(1) - .map_err(driver) + self.selected.final_index().completed_prefix(1).map_err(driver) } pub(super) fn close(self) -> Result<()> { self.selected.close().map_err(driver) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory.rs index c4ed640d..35ba6681 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory.rs @@ -14,10 +14,7 @@ pub(super) struct Directory { } impl Clone for Directory { fn clone(&self) -> Self { - Self { - root: self.root.clone(), - len: self.len, - } + Self { root: self.root.clone(), len: self.len } } } impl Directory { @@ -51,18 +48,12 @@ impl Directory { return Err(Error::InvalidDimension); } let root = edit(self.root.as_ref(), LEVEL, self.len, value)?; - Ok(Self { - root: Some(root), - len: self.len + 1, - }) + Ok(Self { root: Some(root), len: self.len + 1 }) } pub(super) fn replace_last(&self, value: Rc) -> Result { let index = self.len.checked_sub(1).ok_or(Error::InvalidDimension)?; let root = edit(self.root.as_ref(), LEVEL, index, value)?; - Ok(Self { - root: Some(root), - len: self.len, - }) + Ok(Self { root: Some(root), len: self.len }) } #[cfg(test)] pub(super) fn from_entries(entries: Vec>) -> Result { @@ -76,10 +67,7 @@ impl Directory { Ok(directory) } pub(super) fn iter(&self) -> DirectoryIter<'_, T> { - DirectoryIter { - directory: self, - index: 0, - } + DirectoryIter { directory: self, index: 0 } } } // Only the bounded path's metadata storage is allocated fallibly. Standard @@ -89,17 +77,11 @@ fn copy_entries(entries: &[Rc]) -> Result>> { return Err(Error::InvalidDimension); } let mut copy = Vec::new(); - copy.try_reserve_exact(RADIX) - .map_err(|_| Error::InputAllocation)?; + copy.try_reserve_exact(RADIX).map_err(|_| Error::InputAllocation)?; copy.extend(entries.iter().cloned()); Ok(copy) } -fn edit( - node: Option<&Rc>>, - level: usize, - index: usize, - value: Rc, -) -> Result>> { +fn edit(node: Option<&Rc>>, level: usize, index: usize, value: Rc) -> Result>> { let slot = (index >> (6 * level)) & (RADIX - 1); if level == 0 { let values = match node.map(Rc::as_ref) { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory_sdet.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory_sdet.rs index 2048e8bd..4890e5e6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory_sdet.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_directory_sdet.rs @@ -7,10 +7,7 @@ fn persistent_directory_boundaries_preserve_retained_roots_and_payload_identity( assert!(empty.is_empty()); assert_eq!(empty.iter().len(), 0); assert!(empty.get(0).is_none()); - assert!(matches!( - empty.replace_last(Rc::new(9)), - Err(Error::InvalidDimension) - )); + assert!(matches!(empty.replace_last(Rc::new(9)), Err(Error::InvalidDimension))); let payloads: Vec<_> = (0..65536u32).map(Rc::new).collect(); let mut directory = empty.clone(); @@ -34,10 +31,7 @@ fn persistent_directory_boundaries_preserve_retained_roots_and_payload_identity( let clone = directory.clone(); assert!(Rc::ptr_eq(root, clone.root.as_ref().unwrap())); assert_eq!(Rc::strong_count(&payloads[65535]), payload_refs); - assert!(matches!( - directory.appended(Rc::new(7)), - Err(Error::InvalidDimension) - )); + assert!(matches!(directory.appended(Rc::new(7)), Err(Error::InvalidDimension))); assert!(Rc::ptr_eq(root, directory.root.as_ref().unwrap())); for prior in &retained { @@ -56,14 +50,8 @@ fn persistent_directory_boundaries_preserve_retained_roots_and_payload_identity( let replacement = Rc::new(900000u32); let replaced = prior.replace_last(Rc::clone(&replacement)).unwrap(); assert_eq!(replaced.len(), prior.len()); - assert!(Rc::ptr_eq( - replaced.get(prior.len() - 1).unwrap(), - &replacement - )); - assert!(Rc::ptr_eq( - prior.get(prior.len() - 1).unwrap(), - &payloads[prior.len() - 1] - )); + assert!(Rc::ptr_eq(replaced.get(prior.len() - 1).unwrap(), &replacement)); + assert!(Rc::ptr_eq(prior.get(prior.len() - 1).unwrap(), &payloads[prior.len() - 1])); for (actual, expected) in replaced.iter().take(prior.len() - 1).zip(&payloads) { assert!(Rc::ptr_eq(actual, expected)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs index 97683369..3deba676 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs @@ -6,12 +6,11 @@ use super::gr::ResidualReady; use super::qsa_attention::QsaGated; use super::session::QwenStepTxn; use crate::model_binding::qwen4exp_input::{ - BindingIdentity, GrRole, InputBindingError, ModelBinding, QsaMatrixKind, QsaMatrixRole, - QsaWeights, + BindingIdentity, GrRole, InputBindingError, ModelBinding, QsaMatrixKind, QsaMatrixRole, QsaWeights, }; use leleka_cuda_driver::{ - Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, - ProjectionSpec, Q5KProjectionShape, Q6KProjectionShape, + Bf16ProjectionShape, Context, DenseFormat, DeviceBuffer, Error as DriverError, ProjectionKind, ProjectionSpec, + Q5KProjectionShape, Q6KProjectionShape, }; use std::{cell::Cell, rc::Rc}; #[path = "qsa_index_resident.rs"] @@ -47,7 +46,7 @@ struct State { pooled: Directory<[f32; 128]>, tail: [f32; 384], dead: [f32; 128], - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native_kv: Option, } #[derive(Clone)] @@ -111,14 +110,8 @@ mod tests { let mut prior = empty.clone(); let mut first = None; for p in 0..4 { - let pending = QsaPending::new( - &prior, - identity(p), - &halves(0x3c00 + p as u16), - &halves(0x8000), - &index(), - ) - .unwrap(); + let pending = + QsaPending::new(&prior, identity(p), &halves(0x3c00 + p as u16), &halves(0x8000), &index()).unwrap(); assert_eq!(prior.next_position(), p); pending.validate(&prior, identity(p)).unwrap(); let next = pending.into_prior(); @@ -150,17 +143,10 @@ mod tests { let b = BindingIdentity::test_identity(); let o = QsaOwner::new(); let prior = QsaPrior::empty(b.clone(), &o, layer()).unwrap(); - let pending = - QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &index()).unwrap(); + let pending = QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &index()).unwrap(); let other = QsaPrior::empty(b.clone(), &o, layer()).unwrap(); - assert_eq!( - pending.validate(&other, identity(0)), - Err(Error::IdentityMismatch) - ); - assert_eq!( - prior.validate(&b, &QsaOwner::new(), layer(), identity(0).position()), - Err(Error::IdentityMismatch) - ); + assert_eq!(pending.validate(&other, identity(0)), Err(Error::IdentityMismatch)); + assert_eq!(prior.validate(&b, &QsaOwner::new(), layer(), identity(0).position()), Err(Error::IdentityMismatch)); drop(pending); assert_eq!(prior.next_position(), 0); assert!(prior.0.pages.is_empty()); @@ -170,19 +156,14 @@ mod tests { )); let mut bad = index(); bad[639] = f32::NAN; - assert!(matches!( - QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &bad), - Err(Error::NonFinite) - )); + assert!(matches!(QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &bad), Err(Error::NonFinite))); assert_eq!(prior.next_position(), 0); } #[test] fn immutable_spare_and_causal_ascending_ids_are_refusal_boundaries() { let o = QsaOwner::new(); let prior = QsaPrior::empty(BindingIdentity::test_identity(), &o, layer()).unwrap(); - let first = QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &index()) - .unwrap() - .into_prior(); + let first = QsaPending::new(&prior, identity(0), &halves(0), &halves(0), &index()).unwrap().into_prior(); let mut changed = index(); changed[384] = f32::from_bits(0x80000000); assert!(matches!( @@ -194,10 +175,7 @@ mod tests { assert_eq!(validate_ids(&[0, 0], 2), Err(Error::InvalidPosition)); assert_eq!(validate_ids(&[-1], 1), Err(Error::InvalidPosition)); assert_eq!(validate_ids(&[], 0), Err(Error::InvalidDimension)); - assert_eq!( - validate_ids(&[], context() as u64 + 1), - Err(Error::InvalidDimension) - ); + assert_eq!(validate_ids(&[], context() as u64 + 1), Err(Error::InvalidDimension)); let last: Vec = (context() - 2051..context()).map(|x| x as i32).collect(); assert_eq!(validate_ids(&last, context() as u64), Ok(())); } @@ -217,11 +195,7 @@ pub(crate) mod combined_qsa_observer { pub(super) fn selected(resident: bool) { COUNTS.with(|c| { let (legacy, cached) = c.get(); - c.set(if resident { - (legacy, cached + 1) - } else { - (legacy + 1, cached) - }); + c.set(if resident { (legacy, cached + 1) } else { (legacy + 1, cached) }); }); } pub(super) fn action(kind: u8) { @@ -258,8 +232,8 @@ pub(crate) mod combined_qsa_observer { } // Selected mode17 canonical INT8 state; default halfword state stays separate. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] -#[path="qsa_native_state.rs"] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +#[path = "qsa_native_state.rs"] mod native_state; // Genuine device prompt producer; old scalar/default/reference paths unchanged. @@ -272,49 +246,59 @@ mod context_fn; use context_fn::context; #[allow(unused_imports)] use context_fn::device_peak; -mod impl_qsapending; mod impl_qsaindexstage; +mod impl_qsapending; mod norm_fn; #[allow(unused_imports)] +use norm_fn::append; +#[allow(unused_imports)] use norm_fn::norm; #[allow(unused_imports)] -use norm_fn::rope; -#[allow(unused_imports)] -use norm_fn::split; -#[allow(unused_imports)] use norm_fn::pack; #[allow(unused_imports)] -use norm_fn::append; +pub(super) use norm_fn::project; +#[allow(unused_imports)] +use norm_fn::rope; #[allow(unused_imports)] use norm_fn::select; #[allow(unused_imports)] use norm_fn::select_with_keys; #[allow(unused_imports)] -pub(super) use norm_fn::project; +use norm_fn::split; mod dispatch_projection_fn; #[allow(unused_imports)] +pub(super) use dispatch_projection_fn::admit_budget; +#[allow(unused_imports)] use dispatch_projection_fn::dispatch_projection; #[allow(unused_imports)] -use dispatch_projection_fn::project_input_columns; -#[allow(unused_imports)] -use dispatch_projection_fn::project_input; -#[allow(unused_imports)] -use dispatch_projection_fn::project_input_numeric; -#[allow(unused_imports)] pub(super) use dispatch_projection_fn::project_cached_out; #[allow(unused_imports)] -pub(super) use dispatch_projection_fn::project_out_numeric; -#[allow(unused_imports)] use dispatch_projection_fn::project_device; #[allow(unused_imports)] -pub(super) use dispatch_projection_fn::admit_budget; +use dispatch_projection_fn::project_input; +#[allow(unused_imports)] +use dispatch_projection_fn::project_input_columns; +#[allow(unused_imports)] +use dispatch_projection_fn::project_input_numeric; +#[allow(unused_imports)] +pub(super) use dispatch_projection_fn::project_out_numeric; mod validate_ids_fn; #[allow(unused_imports)] -pub(super) use validate_ids_fn::validate_ids; +pub(super) use validate_ids_fn::allocate; #[allow(unused_imports)] -use validate_ids_fn::validate_half; +pub(super) use validate_ids_fn::binding_error; #[allow(unused_imports)] -pub(super) use validate_ids_fn::validate_values; +pub(super) use validate_ids_fn::download; +#[allow(unused_imports)] +pub(super) use validate_ids_fn::download_bytes; +#[allow(unused_imports)] +pub(super) use validate_ids_fn::driver_error; +#[allow(unused_imports)] +pub(in crate::qwen_forward) use validate_ids_fn::project_cached_out_scratch; +#[allow(unused_imports)] +pub(super) use validate_ids_fn::project_scratch_out_numeric; +#[allow(unused_imports)] +pub(super) use validate_ids_fn::release; #[allow(unused_imports)] use validate_ids_fn::reserve; #[allow(unused_imports)] @@ -322,18 +306,8 @@ pub(super) use validate_ids_fn::upload; #[allow(unused_imports)] pub(super) use validate_ids_fn::upload_bytes; #[allow(unused_imports)] -pub(super) use validate_ids_fn::allocate; +use validate_ids_fn::validate_half; #[allow(unused_imports)] -pub(super) use validate_ids_fn::download_bytes; +pub(super) use validate_ids_fn::validate_ids; #[allow(unused_imports)] -pub(super) use validate_ids_fn::download; -#[allow(unused_imports)] -pub(super) use validate_ids_fn::release; -#[allow(unused_imports)] -pub(super) use validate_ids_fn::binding_error; -#[allow(unused_imports)] -pub(super) use validate_ids_fn::driver_error; -#[allow(unused_imports)] -pub(in crate::qwen_forward) use validate_ids_fn::project_cached_out_scratch; -#[allow(unused_imports)] -pub(super) use validate_ids_fn::project_scratch_out_numeric; +pub(super) use validate_ids_fn::validate_values; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs index 1c3d14dd..b299a320 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/context_fn.rs @@ -60,23 +60,9 @@ impl QsaPrior { .pooled .iter() .zip(other.0.pooled.iter()) - .all(|(a, b)| { - a.iter() - .zip(b.iter()) - .all(|(x, y)| x.to_bits() == y.to_bits()) - }) - && self - .0 - .tail - .iter() - .zip(other.0.tail.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) - && self - .0 - .dead - .iter() - .zip(other.0.dead.iter()) - .all(|(a, b)| a.to_bits() == b.to_bits()) + .all(|(a, b)| a.iter().zip(b.iter()).all(|(x, y)| x.to_bits() == y.to_bits())) + && self.0.tail.iter().zip(other.0.tail.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) + && self.0.dead.iter().zip(other.0.dead.iter()).all(|(a, b)| a.to_bits() == b.to_bits()) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -85,21 +71,11 @@ impl QsaPrior { Some(snapshot) => snapshot.encoded_bytes(), None => self.0.pages.len().checked_mul(2 * PAGE * 2)?, }; - let index = self - .0 - .pooled - .len() - .checked_mul(128)? - .checked_add(384 + 128)? - .checked_mul(4)?; + let index = self.0.pooled.len().checked_mul(128)?.checked_add(384 + 128)?.checked_mul(4)?; kv.checked_add(index) } - pub(in super::super) fn empty( - binding: BindingIdentity, - owner: &QsaOwner, - layer: LayerId, - ) -> Result { + pub(in super::super) fn empty(binding: BindingIdentity, owner: &QsaOwner, layer: LayerId) -> Result { if layer.get() >= 48 || layer.get() % 4 != 3 { return Err(Error::InvalidLayer); } @@ -113,7 +89,7 @@ impl QsaPrior { pooled: Directory::new(), tail: [0.0; 384], dead: [0.0; 128], - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native_kv: None, }))) } @@ -135,10 +111,15 @@ impl QsaPrior { } pub(super) fn validate_extent(&self) -> Result<()> { let n = usize::try_from(self.0.next_position).map_err(|_| Error::Overflow)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] if let Some(snapshot) = &self.0.native_kv { - if n > context() || snapshot.next_position() != n || !self.0.pages.is_empty() - || self.0.pooled.len() != n / 4 { return Err(Error::InvalidDimension); } + if n > context() + || snapshot.next_position() != n + || !self.0.pages.is_empty() + || self.0.pooled.len() != n / 4 + { + return Err(Error::InvalidDimension); + } return Ok(()); } if n > context() || self.0.pages.len() != n.div_ceil(4) || self.0.pooled.len() != n / 4 { @@ -156,13 +137,16 @@ impl QsaPrior { self.0.next_position } // Genuine immutable index image only; no current-row or native INT8 certificate. - pub(in super::super) fn native_index_image(&self) -> Result<(Box<[f32]>, [f32;384], [f32;128])> { + pub(in super::super) fn native_index_image(&self) -> Result<(Box<[f32]>, [f32; 384], [f32; 128])> { self.validate_extent()?; - let mut values=reserve(self.0.pooled.len()*128)?; - for key in &self.0.pooled { values.extend_from_slice(key.as_ref()); } - validate_values(&values,self.0.pooled.len()*128)?; - validate_values(&self.0.tail,384)?;validate_values(&self.0.dead,128)?; - Ok((values.into_boxed_slice(),self.0.tail,self.0.dead)) + let mut values = reserve(self.0.pooled.len() * 128)?; + for key in &self.0.pooled { + values.extend_from_slice(key.as_ref()); + } + validate_values(&values, self.0.pooled.len() * 128)?; + validate_values(&self.0.tail, 384)?; + validate_values(&self.0.dead, 128)?; + Ok((values.into_boxed_slice(), self.0.tail, self.0.dead)) } pub(super) fn raw_prior(&self) -> Result> { let mut v = reserve(512)?; @@ -172,13 +156,7 @@ impl QsaPrior { } pub(super) fn score_keys(&self) -> Result> { self.validate_extent()?; - let count = self - .0 - .pooled - .len() - .checked_add(1) - .and_then(|n| n.checked_mul(128)) - .ok_or(Error::Overflow)?; + let count = self.0.pooled.len().checked_add(1).and_then(|n| n.checked_mul(128)).ok_or(Error::Overflow)?; let mut v = reserve(count)?; for key in &self.0.pooled { v.extend_from_slice(key.as_ref()); @@ -189,8 +167,10 @@ impl QsaPrior { } pub(super) fn gather(&self, ids: &[i32]) -> Result { self.validate_extent()?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.0.native_kv.is_some() { return Err(Error::Unsupported(Stage::QsaIndex)); } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.0.native_kv.is_some() { + return Err(Error::Unsupported(Stage::QsaIndex)); + } validate_ids(ids, self.0.next_position)?; let bytes = ids.len().checked_mul(KV * 2).ok_or(Error::Overflow)?; let mut k = reserve(bytes)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs index f1a8b8a6..67ebcb8d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/dispatch_projection_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn dispatch_projection( context: &Context<'_>, matrix: &DeviceBuffer<'_>, @@ -14,33 +13,9 @@ pub(super) fn dispatch_projection( r: usize, ) -> std::result::Result<(), DriverError> { match kind { - QsaMatrixKind::Bf16 => context.bf16_f32( - matrix, - a, - y, - Bf16ProjectionShape { - rows: r, - columns: c, - }, - ), - QsaMatrixKind::Q5K => context.q5_k_q8_1( - matrix, - a, - y, - Q5KProjectionShape { - rows: r, - columns: c, - }, - ), - QsaMatrixKind::Q6K => context.q6_k_q8_1( - matrix, - a, - y, - Q6KProjectionShape { - rows: r, - columns: c, - }, - ), + QsaMatrixKind::Bf16 => context.bf16_f32(matrix, a, y, Bf16ProjectionShape { rows: r, columns: c }), + QsaMatrixKind::Q5K => context.q5_k_q8_1(matrix, a, y, Q5KProjectionShape { rows: r, columns: c }), + QsaMatrixKind::Q6K => context.q6_k_q8_1(matrix, a, y, Q6KProjectionShape { rows: r, columns: c }), kind => context.project_q8_1( matrix, a, @@ -83,24 +58,9 @@ pub(super) fn project_input_columns( if !std::ptr::eq(entry.weights.as_ref(), weights) { return Err(Error::IdentityMismatch); } - return row.take( - binding, - cache, - txn, - input.identity().layer(), - input, - expected, - ); + return row.take(binding, cache, txn, input.identity().layer(), input, expected); } - project_input( - context, - binding, - weights, - role, - input.mixed(), - cache, - source, - ) + project_input(context, binding, weights, role, input.mixed(), cache, source) } pub(super) fn project_input( @@ -120,9 +80,7 @@ pub(super) fn project_input( source.buffer(&binding.identity(), context, weights.layer(), role, x)?; let cache = cache.ok_or(Error::IdentityMismatch)?; let entry = cache.qsa(binding, weights.layer())?; - if !weights.matches(&binding.identity(), weights.layer()) - || !std::ptr::eq(entry.weights.as_ref(), weights) - { + if !weights.matches(&binding.identity(), weights.layer()) || !std::ptr::eq(entry.weights.as_ref(), weights) { return Err(Error::IdentityMismatch); } let (matrix, kind) = cache.qsa_matrix(entry, role)?; @@ -138,15 +96,7 @@ pub(super) fn project_input_numeric( source: &QsaInputLease<'_, '_, '_>, ) -> Result> { let activation = source.activation(context, columns)?; - project_device( - context, - matrix, - activation, - kind, - columns, - rows, - source.failure_flag(), - ) + project_device(context, matrix, activation, kind, columns, rows, source.failure_flag()) } pub(in super::super) fn project_cached_out( @@ -203,16 +153,7 @@ pub(super) fn project_device( } }; let operation = (|| { - dispatch_projection( - context, - matrix, - activation, - &mut output, - kind, - columns, - rows, - ) - .map_err(driver_error)?; + dispatch_projection(context, matrix, activation, &mut output, kind, columns, rows).map_err(driver_error)?; download(&output, rows) })(); let cleanup = output.release().map_err(driver_error); @@ -225,11 +166,7 @@ pub(super) fn project_device( } pub(in super::super) fn admit_budget(context: &Context<'_>) -> Result<()> { - if context - .allocated_bytes() - .checked_add(device_peak()) - .is_none_or(|n| n > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(device_peak()).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs index 0c6b6a67..56efb457 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsaindexstage.rs @@ -31,24 +31,13 @@ impl QsaIndexStage { } for (index, row) in columns.iter().enumerate() { if row.role() == super::super::q6_attention_columns::Role::GdnQkv - || columns[..index] - .iter() - .any(|prior| prior.role() == row.role()) + || columns[..index].iter().any(|prior| prior.role() == row.role()) { return Err(Error::IdentityMismatch); } row.validate(binding, cache, txn, layer, input, row.role())?; } - Self::prepare_impl( - binding, - layer, - input, - pos, - prior, - txn, - Some(cache), - Some(columns), - ) + Self::prepare_impl(binding, layer, input, pos, prior, txn, Some(cache), Some(columns)) } #[allow(clippy::too_many_arguments)] // Additional private certified projection rows only. pub(super) fn prepare_impl( @@ -62,14 +51,11 @@ impl QsaIndexStage { mut columns: Option<&mut [super::super::q6_attention_columns::ProjectionRow<'_, '_>]>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Qsa, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); txn.validate_binding(&binding.identity())?; txn.validate_input(input.identity().token(), pos)?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; txn.validate_qsa_prior(prior, layer)?; let p = u32::try_from(pos.get()).map_err(|_| Error::InvalidPosition)?; @@ -88,13 +74,8 @@ impl QsaIndexStage { if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } - let norms = cache - .zip(resident) - .map(|(c, r)| c.qsa_norms(r)) - .transpose()?; - let input_lease = cache - .map(|c| c.qsa_input(binding, layer.get(), context, input.mixed())) - .transpose()?; + let norms = cache.zip(resident).map(|(c, r)| c.qsa_norms(r)).transpose()?; + let input_lease = cache.map(|c| c.qsa_input(binding, layer.get(), context, input.mixed())).transpose()?; let raw = project_input( context, binding, @@ -129,14 +110,7 @@ impl QsaIndexStage { let k = norm(context, &k, weights.k_norm(), Norm::K, norms.map(|v| v[1]))?; let k = rope(context, &k, p, Norm::K)?; let (kh, vh) = pack(context, &k, &v)?; - let index = append( - context, - &raw, - weights.index_k_norm(), - &prior.raw_prior()?, - p, - norms.map(|v| v[3]), - )?; + let index = append(context, &raw, weights.index_k_norm(), &prior.raw_prior()?, p, norms.map(|v| v[3]))?; let pending = QsaPending::new(prior, input.identity(), &kh, &vh, &index)?; let candidate = pending.next.clone(); let full = project_input_columns( @@ -162,20 +136,10 @@ impl QsaIndexStage { cache, input_lease.as_ref(), )?; - let iq = norm( - context, - &iq, - weights.index_q_norm(), - Norm::Index, - norms.map(|v| v[2]), - )?; + let iq = norm(context, &iq, weights.index_q_norm(), Norm::Index, norms.map(|v| v[2]))?; let iq = rope(context, &iq, p, Norm::Index)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let cache = if combined_qsa_observer::bypass() { - None - } else { - cache - }; + let cache = if combined_qsa_observer::bypass() { None } else { cache }; let ids = if let Some(cache) = cache { cache.qsa_select(binding, context, &candidate, &iq, p)? } else { @@ -197,7 +161,7 @@ impl QsaIndexStage { }) } #[allow(clippy::too_many_arguments)] // Closed native prompt product; old prepare_impl remains exact. - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in super::super) fn prepare_native( binding: &ModelBinding, layer: LayerId, @@ -209,16 +173,13 @@ impl QsaIndexStage { native: &mut super::super::qsa_prefill_batch::NativeProjectionRow<'_, '_>, ) -> Result { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let _owner_wall_scope = crate::qwen_forward::owner_wall_profile::Scope::begin( - crate::qwen_forward::owner_wall_profile::Stage::Qsa, - ); + let _owner_wall_scope = + crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Qsa); native.validate_fresh(binding, cache, txn, layer, input)?; let cache = Some(cache); txn.validate_binding(&binding.identity())?; txn.validate_input(input.identity().token(), pos)?; - input - .identity() - .validate(txn.token(), txn.position(), layer)?; + input.identity().validate(txn.token(), txn.position(), layer)?; input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; txn.validate_qsa_prior(prior, layer)?; let p = u32::try_from(pos.get()).map_err(|_| Error::InvalidPosition)?; @@ -237,45 +198,27 @@ impl QsaIndexStage { if !weights.matches(&binding.identity(), layer.get()) { return Err(Error::IdentityMismatch); } - let norms = cache - .zip(resident) - .map(|(c, r)| c.qsa_norms(r)) - .transpose()?; - let raw = native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::IndexK)?; + let norms = cache.zip(resident).map(|(c, r)| c.qsa_norms(r)).transpose()?; + let raw = + native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::IndexK)?; let k = native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::K)?; let v = native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::V)?; let k = norm(context, &k, weights.k_norm(), Norm::K, norms.map(|v| v[1]))?; let k = rope(context, &k, p, Norm::K)?; let (kh, vh) = pack(context, &k, &v)?; - let index = append( - context, - &raw, - weights.index_k_norm(), - &prior.raw_prior()?, - p, - norms.map(|v| v[3]), - )?; + let index = append(context, &raw, weights.index_k_norm(), &prior.raw_prior()?, p, norms.map(|v| v[3]))?; let pending = QsaPending::new(prior, input.identity(), &kh, &vh, &index)?; let candidate = pending.next.clone(); let full = native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::Q)?; let (q, gate) = split(context, &full)?; let q = norm(context, &q, weights.q_norm(), Norm::Q, norms.map(|v| v[0]))?; let q = rope(context, &q, p, Norm::Q)?; - let iq = native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::IndexQ)?; - let iq = norm( - context, - &iq, - weights.index_q_norm(), - Norm::Index, - norms.map(|v| v[2]), - )?; + let iq = + native.take(binding, cache.ok_or(Error::IdentityMismatch)?, txn, layer, input, QsaMatrixRole::IndexQ)?; + let iq = norm(context, &iq, weights.index_q_norm(), Norm::Index, norms.map(|v| v[2]))?; let iq = rope(context, &iq, p, Norm::Index)?; #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - let cache = if combined_qsa_observer::bypass() { - None - } else { - cache - }; + let cache = if combined_qsa_observer::bypass() { None } else { cache }; let ids = if let Some(cache) = cache { cache.qsa_select(binding, context, &candidate, &iq, p)? } else { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs index 6fa3b4c9..629e06a0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/impl_qsapending.rs @@ -4,16 +4,12 @@ use super::*; impl QsaPending { - pub(super) fn new( - prior: &QsaPrior, - identity: TokenLayer, - k: &[u8], - v: &[u8], - index: &[f32], - ) -> Result { + pub(super) fn new(prior: &QsaPrior, identity: TokenLayer, k: &[u8], v: &[u8], index: &[f32]) -> Result { prior.validate_extent()?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if prior.0.native_kv.is_some() { return Err(Error::Unsupported(Stage::QsaIndex)); } + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if prior.0.native_kv.is_some() { + return Err(Error::Unsupported(Stage::QsaIndex)); + } if prior.layer() != identity.layer() || prior.next_position() != identity.position().get() { return Err(Error::IdentityMismatch); } @@ -26,42 +22,21 @@ impl QsaPending { return Err(Error::InvalidPosition); } let mut page = if pos % 4 == 0 { - KvPage { - k: Box::new([0; PAGE]), - v: Box::new([0; PAGE]), - } + KvPage { k: Box::new([0; PAGE]), v: Box::new([0; PAGE]) } } else { let old = prior .0 .pages - .get( - prior - .0 - .pages - .len() - .checked_sub(1) - .ok_or(Error::InvalidPosition)?, - ) + .get(prior.0.pages.len().checked_sub(1).ok_or(Error::InvalidPosition)?) .ok_or(Error::InvalidPosition)?; - KvPage { - k: old.k.clone(), - v: old.v.clone(), - } + KvPage { k: old.k.clone(), v: old.v.clone() } }; for h in 0..2 { for d in 0..256 { let src = (h * 256 + d) * 2; let dst = (h * 4 + pos % 4) * 256 + d; - let kh = u16::from_le_bytes( - k[src..src + 2] - .try_into() - .map_err(|_| Error::InvalidDimension)?, - ); - let vh = u16::from_le_bytes( - v[src..src + 2] - .try_into() - .map_err(|_| Error::InvalidDimension)?, - ); + let kh = u16::from_le_bytes(k[src..src + 2].try_into().map_err(|_| Error::InvalidDimension)?); + let vh = u16::from_le_bytes(v[src..src + 2].try_into().map_err(|_| Error::InvalidDimension)?); validate_half(kh)?; validate_half(vh)?; page.k[dst] = kh; @@ -69,33 +44,16 @@ impl QsaPending { } } let page = Rc::new(page); - let pages = if pos % 4 == 0 { - prior.0.pages.appended(page)? - } else { - prior.0.pages.replace_last(page)? - }; + let pages = if pos % 4 == 0 { prior.0.pages.appended(page)? } else { prior.0.pages.replace_last(page)? }; let pooled = if pos % 4 == 3 { - prior.0.pooled.appended(Rc::new( - index[512..640] - .try_into() - .map_err(|_| Error::InvalidDimension)?, - ))? + prior.0.pooled.appended(Rc::new(index[512..640].try_into().map_err(|_| Error::InvalidDimension)?))? } else { prior.0.pooled.clone() }; - let tail: [f32; 384] = index[..384] - .try_into() - .map_err(|_| Error::InvalidDimension)?; - let dead: [f32; 128] = index[384..512] - .try_into() - .map_err(|_| Error::InvalidDimension)?; + let tail: [f32; 384] = index[..384].try_into().map_err(|_| Error::InvalidDimension)?; + let dead: [f32; 128] = index[384..512].try_into().map_err(|_| Error::InvalidDimension)?; // The position-zero spare remains byte-identical on every later append. - if pos != 0 - && dead - .iter() - .zip(prior.0.dead.iter()) - .any(|(a, b)| a.to_bits() != b.to_bits()) - { + if pos != 0 && dead.iter().zip(prior.0.dead.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) { return Err(Error::IdentityMismatch); } let next = QsaPrior(Rc::new(State { @@ -103,23 +61,16 @@ impl QsaPending { binding: prior.0.binding.clone(), owner: prior.0.owner.clone(), layer: prior.layer(), - next_position: prior - .next_position() - .checked_add(1) - .ok_or(Error::Overflow)?, + next_position: prior.next_position().checked_add(1).ok_or(Error::Overflow)?, pages, pooled, tail, dead, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native_kv: None, })); next.validate_extent()?; - Ok(Self { - prior: prior.clone(), - next, - identity, - }) + Ok(Self { prior: prior.clone(), next, identity }) } pub(in super::super) fn validate(&self, prior: &QsaPrior, identity: TokenLayer) -> Result<()> { if !self.prior.same_state(prior) || self.identity != identity { @@ -174,7 +125,9 @@ impl QsaPrepared { pub(in super::super) fn weights(&self) -> &QsaWeights { &self.weights } - pub(in super::super) fn native_pending_taken(&self) -> bool { self.pending.is_none() } + pub(in super::super) fn native_pending_taken(&self) -> bool { + self.pending.is_none() + } pub(in super::super) fn selected_kv(&self) -> Result { self.candidate.gather(&self.ids) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs index c8371d88..41400bdd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/norm_fn.rs @@ -11,11 +11,7 @@ pub(super) fn norm( resident: Option<&DeviceBuffer<'_>>, ) -> Result> { let a = upload(context, x)?; - let owned = if resident.is_none() { - Some(upload(context, gamma)?) - } else { - None - }; + let owned = if resident.is_none() { Some(upload(context, gamma)?) } else { None }; let g = resident.or(owned.as_ref()).ok_or(Error::IdentityMismatch)?; let mut y = allocate(context, x.len())?; match which { @@ -49,9 +45,7 @@ pub(super) fn split(context: &Context<'_>, full: &[f32]) -> Result { let x = upload(context, full)?; let mut q = allocate(context, Q)?; let mut g = allocate(context, Q)?; - context - .qsa_split_q_gate(&x, &mut q, &mut g) - .map_err(driver_error)?; + context.qsa_split_q_gate(&x, &mut q, &mut g).map_err(driver_error)?; let out = (download(&q, Q)?, download(&g, Q)?); release([x, q, g])?; Ok(out) @@ -63,9 +57,7 @@ pub(super) fn pack(context: &Context<'_>, k: &[f32], v: &[f32]) -> Result, - pooled: &[f32], - dead: &[f32], - iq: &[f32], - p: u32, -) -> Result> { +pub(super) fn select(context: &Context<'_>, pooled: &[f32], dead: &[f32], iq: &[f32], p: u32) -> Result> { let blocks = (p as usize + 1) / 4 + 1; validate_values(pooled, blocks * 128)?; validate_values(dead, 128)?; @@ -142,9 +122,7 @@ pub(super) fn select_with_keys( let _checked = download(&scores, blocks)?; let mut ids = context.allocate(2051 * 4).map_err(driver_error)?; ids.copy_from(&[0xff; 2051 * 4]).map_err(driver_error)?; - context - .qsa_block_topk(&scores, &mut ids, p) - .map_err(driver_error)?; + context.qsa_block_topk(&scores, &mut ids, p).map_err(driver_error)?; let bytes = download_bytes(&ids, 2051 * 4)?; let width = (p as usize + 1).min(2051); let mut out = reserve(width)?; @@ -171,12 +149,8 @@ pub(in super::super) fn project( let entry = cache.qsa(binding, w.layer())?; cache.qsa_matrix(entry, role)? } else { - let block = binding - .qsa_matrix_block(w, role, 0, r) - .map_err(binding_error)?; - let mut buffer = context - .allocate(block.bytes().len()) - .map_err(driver_error)?; + let block = binding.qsa_matrix_block(w, role, 0, r).map_err(binding_error)?; + let mut buffer = context.allocate(block.bytes().len()).map_err(driver_error)?; buffer.copy_from(block.bytes()).map_err(driver_error)?; let kind = block.kind(); owned = Some(buffer); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids_fn.rs index edda3fea..4092363f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index/validate_ids_fn.rs @@ -4,10 +4,7 @@ use super::*; pub(in super::super) fn validate_ids(ids: &[i32], n: u64) -> Result<()> { - if n == 0 - || n > context() as u64 - || ids.len() != usize::try_from(n).map_err(|_| Error::Overflow)?.min(2051) - { + if n == 0 || n > context() as u64 || ids.len() != usize::try_from(n).map_err(|_| Error::Overflow)?.min(2051) { return Err(Error::InvalidDimension); } let mut prev = -1; @@ -47,18 +44,13 @@ pub(in super::super) fn upload<'a, 'd>(context: &'a Context<'d>, v: &[f32]) -> R } upload_bytes(context, &bytes) } -pub(in super::super) fn upload_bytes<'a, 'd>( - context: &'a Context<'d>, - bytes: &[u8], -) -> Result> { +pub(in super::super) fn upload_bytes<'a, 'd>(context: &'a Context<'d>, bytes: &[u8]) -> Result> { let mut b = context.allocate(bytes.len()).map_err(driver_error)?; b.copy_from(bytes).map_err(driver_error)?; Ok(b) } pub(in super::super) fn allocate<'a, 'd>(context: &'a Context<'d>, n: usize) -> Result> { - context - .allocate(n.checked_mul(4).ok_or(Error::Overflow)?) - .map_err(driver_error) + context.allocate(n.checked_mul(4).ok_or(Error::Overflow)?).map_err(driver_error) } pub(in super::super) fn download_bytes(b: &DeviceBuffer<'_>, n: usize) -> Result> { let mut bytes = reserve(n)?; @@ -94,7 +86,9 @@ pub(in super::super) fn binding_error(e: InputBindingError) -> Error { } } pub(in super::super) fn driver_error(e: DriverError) -> Error { - if crate::driver_errors_traced(){eprintln!("driver error: {e:?}");} + if crate::driver_errors_traced() { + eprintln!("driver error: {e:?}"); + } #[cfg(test)] eprintln!("PUBLIC CUDA raw adapter=qsa error={e:?}"); match e { @@ -119,7 +113,9 @@ pub(in super::super) fn driver_error(e: DriverError) -> Error { // Closed current-row gated loan; cannot pair arbitrary host values with a buffer. pub(in crate::qwen_forward) fn project_cached_out_scratch( - context: &Context<'_>, binding: &ModelBinding, weights: &QsaWeights, + context: &Context<'_>, + binding: &ModelBinding, + weights: &QsaWeights, gated: &mut super::super::qsa_attention::attention_scratch::QsaAttentionLease<'_, '_, '_>, cache: &DenseWeightCache<'_>, ) -> Result> { @@ -128,10 +124,14 @@ pub(in crate::qwen_forward) fn project_cached_out_scratch( if !weights.matches(&binding.identity(), weights.layer()) || !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; let result = (|| { - if failed.get() { return Err(Error::CudaExecution); } + if failed.get() { + return Err(Error::CudaExecution); + } let (activation, output) = gated.gated_parts(binding, context, weights)?; project_scratch_out_numeric(context, matrix, activation, output, kind) })(); @@ -141,13 +141,15 @@ pub(in crate::qwen_forward) fn project_cached_out_scratch( // Fixed whole Out role only; same original dispatch/full finite readback. pub(in super::super) fn project_scratch_out_numeric( - context: &Context<'_>, matrix: &DeviceBuffer<'_>, activation: &DeviceBuffer<'_>, - output: &mut DeviceBuffer<'_>, kind: QsaMatrixKind, + context: &Context<'_>, + matrix: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + output: &mut DeviceBuffer<'_>, + kind: QsaMatrixKind, ) -> Result> { if activation.len() != 6144 * 4 || output.len() != 2560 * 4 { return Err(Error::InvalidDimension); } - dispatch_projection(context, matrix, activation, output, kind, 6144, 2560) - .map_err(driver_error)?; + dispatch_projection(context, matrix, activation, output, kind, 6144, 2560).map_err(driver_error)?; download(output, 2560) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs index 938667b9..9c928dae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident.rs @@ -34,9 +34,7 @@ mod tests { Position::new(p, crate::qwen_forward::contract::position_dimension()).unwrap(), prior.layer(), ); - QsaPending::new(prior, identity, &[0; KV * 2], &[0; KV * 2], &index) - .unwrap() - .into_prior() + QsaPending::new(prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior() } #[test] fn resident_plan_exact_bytes_across_append_reuse_branch_reset() { @@ -52,11 +50,7 @@ mod tests { let mut transferred = 0; for p in 0..20 { let next = pending(&prior, p); - let action = if p == 0 { - Update::Reload - } else { - update(&prior, &next).unwrap() - }; + let action = if p == 0 { Update::Reload } else { update(&prior, &next).unwrap() }; match action { Update::Reload => { bytes = upload_words(&next.score_keys().unwrap()).unwrap(); @@ -126,9 +120,7 @@ mod late_cpu { Position::new(190003, crate::qwen_forward::contract::position_dimension()).unwrap(), prior.layer(), ); - let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index) - .unwrap() - .into_prior(); + let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior(); assert_eq!(update(&prior, &next).unwrap(), Update::Append(47500)); let patch = delta(&next, 47500).unwrap(); assert_eq!(patch.len(), 1024); @@ -138,10 +130,7 @@ mod late_cpu { assert_eq!(bytes, upload_words(&next.score_keys().unwrap()).unwrap()); drop(prior); assert!(next.0.parent.upgrade().is_none()); - assert_eq!( - update(&synthetic_late_prior(190003), &next).unwrap(), - Update::Reload - ); + assert_eq!(update(&synthetic_late_prior(190003), &next).unwrap(), Update::Reload); } } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -153,11 +142,7 @@ mod gpu { #[ignore = "Root-only serial installed-driver QSA transport proof, no model inference"] fn resident_index_transport_matches_uncached_at_190k_and_reset() { let driver = Driver::load().unwrap(); - let context = driver - .device(0) - .unwrap() - .create_context(1024 * 1024 * 1024) - .unwrap(); + let context = driver.device(0).unwrap().create_context(1024 * 1024 * 1024).unwrap(); let binding = BindingIdentity::test_identity(); let failed = Rc::new(Cell::new(false)); // the legacy footprint (LELEKA_FOOTPRINT_LEGACY=1) allocates all twelve mirrors at construction @@ -182,20 +167,9 @@ mod gpu { Position::new(p, crate::qwen_forward::contract::position_dimension()).unwrap(), prior.layer(), ); - let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index) - .unwrap() - .into_prior(); - let expected = select( - &context, - &next.score_keys().unwrap(), - &next.0.dead, - &iq, - p as u32, - ) - .unwrap(); - let actual = cache - .select(&binding, &context, &next, &iq, p as u32) - .unwrap(); + let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior(); + let expected = select(&context, &next.score_keys().unwrap(), &next.0.dead, &iq, p as u32).unwrap(); + let actual = cache.select(&binding, &context, &next, &iq, p as u32).unwrap(); assert_eq!(actual.as_ref(), expected.as_ref()); total += actual.len(); prior = next; @@ -205,41 +179,18 @@ mod gpu { assert_eq!(cache.allocated_layers(), 1); assert_eq!(context.allocated_bytes(), 402659328 / 12); let replacement = synthetic_late_prior_for(binding.clone(), 190004); - let expected = select( - &context, - &replacement.score_keys().unwrap(), - &replacement.0.dead, - &iq, - 190003, - ) - .unwrap(); - let actual = cache - .select(&binding, &context, &replacement, &iq, 190003) - .unwrap(); + let expected = select(&context, &replacement.score_keys().unwrap(), &replacement.0.dead, &iq, 190003).unwrap(); + let actual = cache.select(&binding, &context, &replacement, &iq, 190003).unwrap(); assert_eq!(actual.as_ref(), expected.as_ref()); let uploads = cache.uploads; - assert_eq!( - cache - .select(&binding, &context, &replacement, &iq, 190003) - .unwrap() - .as_ref(), - expected.as_ref() - ); + assert_eq!(cache.select(&binding, &context, &replacement, &iq, 190003).unwrap().as_ref(), expected.as_ref()); assert_eq!(cache.uploads, uploads); let wrong = BindingIdentity::test_identity(); // Bound position and malformed source must refuse before any transfer. - assert!( - cache - .select(&wrong, &context, &replacement, &iq, 190002) - .is_err() - ); + assert!(cache.select(&wrong, &context, &replacement, &iq, 190002).is_err()); let mut bad = iq; bad[511] = f32::NAN; - assert!( - cache - .select(&binding, &context, &replacement, &bad, 190003) - .is_err() - ); + assert!(cache.select(&binding, &context, &replacement, &bad, 190003).is_err()); assert_eq!(cache.uploads, uploads); assert!(!failed.get()); cache.close().unwrap(); @@ -255,15 +206,15 @@ mod gpu { #[path = "qsa_index_resident/max_rows_fn.rs"] mod max_rows_fn; #[allow(unused_imports)] +use max_rows_fn::capacity; +#[allow(unused_imports)] +use max_rows_fn::delta; +#[allow(unused_imports)] use max_rows_fn::max_rows; #[allow(unused_imports)] use max_rows_fn::update; #[allow(unused_imports)] -use max_rows_fn::capacity; -#[allow(unused_imports)] use max_rows_fn::upload_words; -#[allow(unused_imports)] -use max_rows_fn::delta; #[path = "qsa_index_resident/synthetic_late_prior_fn.rs"] mod synthetic_late_prior_fn; #[cfg(test)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs index 599f8af3..b93e11ad 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/max_rows_fn.rs @@ -15,12 +15,7 @@ pub(super) fn update(old: &QsaPrior, next: &QsaPrior) -> Result { } // Reset/replay, speculative branches and unrelated sessions are misses. // Weak parent does not retain an unbounded chain of prior state versions. - if !next - .0 - .parent - .upgrade() - .is_some_and(|parent| Rc::ptr_eq(&parent, &old.0)) - { + if !next.0.parent.upgrade().is_some_and(|parent| Rc::ptr_eq(&parent, &old.0)) { return Ok(Update::Reload); } if !old.0.binding.matches(&next.0.binding) @@ -32,13 +27,7 @@ pub(super) fn update(old: &QsaPrior, next: &QsaPrior) -> Result { } if old.0.pooled.len() == next.0.pooled.len() { // QsaPending has proved spare row invariant for positions after zero. - if old - .0 - .dead - .iter() - .zip(&next.0.dead) - .all(|(a, b)| a.to_bits() == b.to_bits()) - { + if old.0.dead.iter().zip(&next.0.dead).all(|(a, b)| a.to_bits() == b.to_bits()) { Ok(Update::Reuse) } else { Ok(Update::Append(old.0.pooled.len())) @@ -172,29 +161,17 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { #[cfg(test)] let needed = rows.checked_mul(ROW_BYTES).ok_or(Error::Overflow)?; let entry = self.ensure(slot)?; - if entry.buffer.len() - != capacity(rows)? - .checked_mul(ROW_BYTES) - .ok_or(Error::Overflow)? - { + if entry.buffer.len() != capacity(rows)?.checked_mul(ROW_BYTES).ok_or(Error::Overflow)? { return Err(Error::InvalidDimension); } - let action = entry - .prior - .as_ref() - .map(|old| update(old, next)) - .transpose()? - .unwrap_or(Update::Reload); + let action = entry.prior.as_ref().map(|old| update(old, next)).transpose()?.unwrap_or(Update::Reload); let result = (|| -> Result> { match action { Update::Reload => { let values = next.score_keys()?; let bytes = upload_words(&values)?; let entry = self.entries[slot].as_mut().ok_or(Error::IdentityMismatch)?; - entry - .buffer - .copy_from_range(0, &bytes) - .map_err(driver_error)?; + entry.buffer.copy_from_range(0, &bytes).map_err(driver_error)?; entry.prior = Some(next.clone()); #[cfg(test)] { @@ -215,10 +192,7 @@ impl<'ctx> QsaIndexKeyCache<'ctx> { } } Update::Reuse => { - self.entries[slot] - .as_mut() - .ok_or(Error::IdentityMismatch)? - .prior = Some(next.clone()); + self.entries[slot].as_mut().ok_or(Error::IdentityMismatch)?.prior = Some(next.clone()); } } let entry = self.entries[slot].as_ref().ok_or(Error::IdentityMismatch)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/synthetic_late_prior_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/synthetic_late_prior_fn.rs index dab12dc7..637eadd1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/synthetic_late_prior_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_index_resident/synthetic_late_prior_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(test)] pub(super) fn synthetic_late_prior(position: u64) -> QsaPrior { synthetic_late_prior_for(BindingIdentity::test_identity(), position) @@ -13,10 +12,7 @@ pub(super) fn synthetic_late_prior(position: u64) -> QsaPrior { pub(super) fn synthetic_late_prior_for(binding: BindingIdentity, position: u64) -> QsaPrior { use crate::qwen_forward::contract::Dimension; let owner = QsaOwner::new(); - let page = Rc::new(KvPage { - k: Box::new([0; PAGE]), - v: Box::new([0; PAGE]), - }); + let page = Rc::new(KvPage { k: Box::new([0; PAGE]), v: Box::new([0; PAGE]) }); let row = Rc::new([0.5; 128]); QsaPrior(Rc::new(State { parent: std::rc::Weak::new(), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs index 1e7fb3a5..8ba8964c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_reuse_gpu.rs @@ -41,22 +41,14 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() let context = device.create_context(208 * 1024 * 1024).unwrap(); let binding = BindingIdentity::test_identity(); // Tag only, no artifact capability. let failed = Rc::new(Cell::new(false)); - let scratch = - RefCell::new(QsaInputScratch::new(binding.clone(), &context, failed.clone()).unwrap()); + let scratch = RefCell::new(QsaInputScratch::new(binding.clone(), &context, failed.clone()).unwrap()); assert_eq!(context.allocated_bytes(), INPUT_BYTES); for zero in [false, true] { let input: Vec = (0..2560) - .map(|i| { - if zero { - if i % 2 == 0 { -0.0 } else { 0.0 } - } else { - (i % 17) as f32 / 64. - 8. / 64. - } - }) + .map(|i| if zero { if i % 2 == 0 { -0.0 } else { 0.0 } } else { (i % 17) as f32 / 64. - 8. / 64. }) .collect(); let source_bits: Vec = input.iter().map(|v| v.to_bits()).collect(); - let lease = - QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 3, &input).unwrap(); + let lease = QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 3, &input).unwrap(); if !zero { assert!(scratch.try_borrow_mut().is_err()); } // Actual exclusive RefCell lease. @@ -71,16 +63,7 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() let matrix = bytes_upload(&context, &bytes); let fresh = upload(&context, &input).unwrap(); let mut output = allocate(&context, rows).unwrap(); - dispatch_projection( - &context, - &matrix, - &fresh, - &mut output, - QsaMatrixKind::Bf16, - 2560, - rows, - ) - .unwrap(); + dispatch_projection(&context, &matrix, &fresh, &mut output, QsaMatrixKind::Bf16, 2560, rows).unwrap(); let expected = download(&output, rows).unwrap(); output.release().unwrap(); fresh.release().unwrap(); @@ -88,16 +71,8 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() let admitted = lease.buffer(&binding, &context, 3, role, &input).unwrap(); let mut retained_input = vec![0; INPUT_BYTES]; admitted.copy_to(&mut retained_input).unwrap(); - assert_eq!( - retained_input, - input - .iter() - .flat_map(|v| v.to_le_bytes()) - .collect::>() - ); - let actual = - project_input_numeric(&context, &matrix, QsaMatrixKind::Bf16, 2560, rows, &lease) - .unwrap(); + assert_eq!(retained_input, input.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let actual = project_input_numeric(&context, &matrix, QsaMatrixKind::Bf16, 2560, rows, &lease).unwrap(); exact(&actual, &expected); assert_eq!(context.allocated_bytes(), charged); let mut unchanged = vec![0; bytes.len()]; @@ -106,10 +81,7 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() matrix.release().unwrap(); println!("QSA_INPUT PAIR role={role:?} zero={zero} exact_words={rows}"); } - assert_eq!( - input.iter().map(|v| v.to_bits()).collect::>(), - source_bits - ); + assert_eq!(input.iter().map(|v| v.to_bits()).collect::>(), source_bits); drop(lease); assert_eq!(scratch.borrow().uploads, if zero { 2 } else { 1 }); assert_eq!(context.allocated_bytes(), INPUT_BYTES); @@ -124,14 +96,7 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() (&binding, &context, 0, Error::InvalidLayer), ] { assert_eq!( - QsaInputScratch::lease( - scratch.borrow_mut(), - candidate_binding, - candidate_context, - layer, - &input - ) - .err(), + QsaInputScratch::lease(scratch.borrow_mut(), candidate_binding, candidate_context, layer, &input).err(), Some(expected) ); } @@ -146,62 +111,18 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() Some(Error::InvalidDimension) ); assert_eq!(scratch.borrow().uploads, 2); - let lease = - QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 3, &input).unwrap(); + let lease = QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 3, &input).unwrap(); let copy = input.clone(); for (candidate_binding, candidate_context, layer, role, source, expected) in [ - ( - &rival, - &context, - 3, - QsaMatrixRole::IndexK, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &foreign, - 3, - QsaMatrixRole::IndexK, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 7, - QsaMatrixRole::IndexK, - input.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 3, - QsaMatrixRole::IndexK, - copy.as_slice(), - Error::IdentityMismatch, - ), - ( - &binding, - &context, - 3, - QsaMatrixRole::Out, - input.as_slice(), - Error::InvalidDimension, - ), + (&rival, &context, 3, QsaMatrixRole::IndexK, input.as_slice(), Error::IdentityMismatch), + (&binding, &foreign, 3, QsaMatrixRole::IndexK, input.as_slice(), Error::IdentityMismatch), + (&binding, &context, 7, QsaMatrixRole::IndexK, input.as_slice(), Error::IdentityMismatch), + (&binding, &context, 3, QsaMatrixRole::IndexK, copy.as_slice(), Error::IdentityMismatch), + (&binding, &context, 3, QsaMatrixRole::Out, input.as_slice(), Error::InvalidDimension), ] { - assert_eq!( - lease - .buffer(candidate_binding, candidate_context, layer, role, source) - .err(), - Some(expected) - ); + assert_eq!(lease.buffer(candidate_binding, candidate_context, layer, role, source).err(), Some(expected)); } - assert_eq!( - lease.activation(&context, 6144).err(), - Some(Error::InvalidDimension) - ); + assert_eq!(lease.activation(&context, 6144).err(), Some(Error::InvalidDimension)); // A completed late NaN is withheld and output freed, while the finite // original input slot remains valid. No simulated numerical provider. let mut bytes = matrix_bytes(128, 5); @@ -227,25 +148,13 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() drop(lease); // Abort releases exclusive ownership without releasing actor slot. assert_eq!(scratch.borrow().uploads, 3); let replacement = vec![-0.0625; 2560]; - let lease = - QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 7, &replacement).unwrap(); - assert!( - lease - .buffer(&binding, &context, 7, QsaMatrixRole::IndexQ, &replacement) - .is_ok() - ); + let lease = QsaInputScratch::lease(scratch.borrow_mut(), &binding, &context, 7, &replacement).unwrap(); + assert!(lease.buffer(&binding, &context, 7, QsaMatrixRole::IndexQ, &replacement).is_ok()); let mut overwritten = vec![0; INPUT_BYTES]; - lease - .activation(&context, 2560) - .unwrap() - .copy_to(&mut overwritten) - .unwrap(); + lease.activation(&context, 2560).unwrap().copy_to(&mut overwritten).unwrap(); assert_eq!(overwritten, (-0.0625_f32).to_le_bytes().repeat(2560)); lease.failure_flag().set(true); // Exercise explicit sticky policy, not an injected CUDA fault. - assert_eq!( - lease.activation(&context, 2560).err(), - Some(Error::CudaExecution) - ); + assert_eq!(lease.activation(&context, 2560).err(), Some(Error::CudaExecution)); drop(lease); assert_eq!(scratch.borrow().uploads, 4); assert_eq!( @@ -260,16 +169,9 @@ fn one_input_upload_matches_five_legacy_projections_and_preserves_lease_guards() context.close().unwrap(); assert_eq!(foreign.allocated_bytes(), 0); foreign.close().unwrap(); - let small = device - .create_context(128 * 1024 * 1024 + INPUT_BYTES - 1) - .unwrap(); - assert_eq!( - QsaInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), - Some(Error::InputAllocation) - ); + let small = device.create_context(128 * 1024 * 1024 + INPUT_BYTES - 1).unwrap(); + assert_eq!(QsaInputScratch::new(binding, &small, Rc::new(Cell::new(false))).err(), Some(Error::InputAllocation)); assert_eq!(small.allocated_bytes(), 0); small.close().unwrap(); - println!( - "QSA_INPUT COMPLETE exact_words=27904 finite_leases=2 guard_refusals=18 uploads=4 allocated=0" - ); + println!("QSA_INPUT COMPLETE exact_words=27904 finite_leases=2 guard_refusals=18 uploads=4 allocated=0"); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs index 5b0b248b..d5ff5764 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_input_scratch.rs @@ -1,7 +1,6 @@ //! One current-source slot; no recurrent or cross-token cache identity. use super::{ - BindingIdentity, Context, DeviceBuffer, Error, QsaMatrixRole, Result, admit_budget, - driver_error, validate_values, + BindingIdentity, Context, DeviceBuffer, Error, QsaMatrixRole, Result, admit_budget, driver_error, validate_values, }; use std::{ cell::{Cell, RefMut}, @@ -31,14 +30,8 @@ impl<'ctx> QsaInputScratch<'ctx> { if failed.get() { return Err(Error::CudaExecution); } - let charged = context - .allocated_bytes() - .checked_add(INPUT_BYTES) - .ok_or(Error::Overflow)?; - if charged - .checked_add(128 * 1024 * 1024) - .is_none_or(|peak| peak > context.budget_bytes()) - { + let charged = context.allocated_bytes().checked_add(INPUT_BYTES).ok_or(Error::Overflow)?; + if charged.checked_add(128 * 1024 * 1024).is_none_or(|peak| peak > context.budget_bytes()) { return Err(Error::InputAllocation); } let buffer = context.allocate(INPUT_BYTES).map_err(driver_error)?; @@ -84,11 +77,7 @@ impl<'ctx> QsaInputScratch<'ctx> { { slot.uploads += 1; } - Ok(QsaInputLease { - slot, - source, - layer, - }) + Ok(QsaInputLease { slot, source, layer }) } pub(in crate::qwen_forward) fn close(self) -> Result<()> { let primary = self.failed.get().then_some(Error::CudaExecution); @@ -117,21 +106,13 @@ impl<'ctx> QsaInputLease<'_, '_, 'ctx> { } if !matches!( role, - QsaMatrixRole::Q - | QsaMatrixRole::K - | QsaMatrixRole::V - | QsaMatrixRole::IndexQ - | QsaMatrixRole::IndexK + QsaMatrixRole::Q | QsaMatrixRole::K | QsaMatrixRole::V | QsaMatrixRole::IndexQ | QsaMatrixRole::IndexK ) { return Err(Error::InvalidDimension); } self.activation(context, 2560) } - pub(super) fn activation( - &self, - context: &Context<'_>, - columns: usize, - ) -> Result<&DeviceBuffer<'ctx>> { + pub(super) fn activation(&self, context: &Context<'_>, columns: usize) -> Result<&DeviceBuffer<'ctx>> { if self.slot.failed.get() { return Err(Error::CudaExecution); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs index 81abe973..b97790e7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_resources.rs @@ -5,8 +5,7 @@ use super::{ qsa_index::driver_error, }; use leleka_cuda_driver::{ - Context, QsaNativeDecode, QsaNativeGate, QsaPromptAttention, QsaPromptIndexWorkspace, - QsaPromptKv, QsaPromptStage, + Context, QsaNativeDecode, QsaNativeGate, QsaPromptAttention, QsaPromptIndexWorkspace, QsaPromptKv, QsaPromptStage, }; #[cfg_attr(target_os = "windows", allow(unused_imports))] use std::{cell::Cell, fs::File, io::Read, rc::Rc}; @@ -45,21 +44,23 @@ pub(super) struct NativeQsaResources<'ctx> { } impl<'ctx> NativeQsaResources<'ctx> { pub(super) fn new(context: &'ctx Context<'ctx>, failed: Rc>) -> Result { - Self::new_for_prompt(context,failed,64) + Self::new_for_prompt(context, failed, 64) } - pub(super) fn new_for_prompt(context:&'ctx Context<'ctx>,failed:Rc>,capacity:usize)->Result { - if !(1..=8192).contains(&capacity) {return Err(Error::InvalidDimension);} + pub(super) fn new_for_prompt( + context: &'ctx Context<'ctx>, + failed: Rc>, + capacity: usize, + ) -> Result { + if !(1..=8192).contains(&capacity) { + return Err(Error::InvalidDimension); + } let sizes = sizes()?; let host_canonical_limit = LAYERS * (sizes.payload + sizes.metadata + sizes.index_image); // Every real mapped bank has four16-aligned runs plus1024B allocation // slack from the literal Original pool layout. Canonical rollback bytes // remain independently charged: mapped storage is mutable, not a snapshot. let mapped = LAYERS * (sizes.payload + 1024); - admit_host( - mapped - .checked_add(host_canonical_limit) - .ok_or(Error::Overflow)?, - )?; + admit_host(mapped.checked_add(host_canonical_limit).ok_or(Error::Overflow)?)?; let mut owner = Self { context, failed, @@ -72,14 +73,25 @@ impl<'ctx> NativeQsaResources<'ctx> { host_pinned_bytes: 0, host_canonical_limit, }; - owner - .kv - .try_reserve_exact(LAYERS) - .map_err(|_| Error::InputAllocation)?; + owner.kv.try_reserve_exact(LAYERS).map_err(|_| Error::InputAllocation)?; let operation = (|| { - owner.index = Some(if capacity==64 {context.qsa_prompt_index_workspace()}else{context.qsa_prompt_index_workspace_for_capacity(capacity)}.map_err(driver_error)?); + owner.index = Some( + if capacity == 64 { + context.qsa_prompt_index_workspace() + } else { + context.qsa_prompt_index_workspace_for_capacity(capacity) + } + .map_err(driver_error)?, + ); owner.stage = Some(context.qsa_prompt_stage().map_err(driver_error)?); - owner.attention = Some(if capacity==64 {context.qsa_prompt_attention()}else{context.qsa_prompt_attention_for_capacity(capacity)}.map_err(driver_error)?); + owner.attention = Some( + if capacity == 64 { + context.qsa_prompt_attention() + } else { + context.qsa_prompt_attention_for_capacity(capacity) + } + .map_err(driver_error)?, + ); owner.decode = Some(context.qsa_native_decode().map_err(driver_error)?); owner.gate = Some(context.qsa_native_gate().map_err(driver_error)?); for _ in 0..LAYERS { @@ -89,10 +101,7 @@ impl<'ctx> NativeQsaResources<'ctx> { let _ = kv.close(); return Err(Error::InvalidDimension); } - owner.host_pinned_bytes = owner - .host_pinned_bytes - .checked_add(bytes) - .ok_or(Error::Overflow)?; + owner.host_pinned_bytes = owner.host_pinned_bytes.checked_add(bytes).ok_or(Error::Overflow)?; owner.kv.push(kv); } if owner.host_pinned_bytes != mapped { @@ -113,15 +122,9 @@ impl<'ctx> NativeQsaResources<'ctx> { if self.failed.get() || self.kv.len() != LAYERS || self.kv.iter().any(QsaPromptKv::is_failed) - || self - .index - .as_ref() - .is_none_or(QsaPromptIndexWorkspace::is_failed) + || self.index.as_ref().is_none_or(QsaPromptIndexWorkspace::is_failed) || self.stage.as_ref().is_none_or(QsaPromptStage::is_failed) - || self - .attention - .as_ref() - .is_none_or(QsaPromptAttention::is_failed) + || self.attention.as_ref().is_none_or(QsaPromptAttention::is_failed) || self.decode.as_ref().is_none_or(QsaNativeDecode::is_failed) || self.gate.as_ref().is_none_or(QsaNativeGate::is_failed) { @@ -198,10 +201,8 @@ impl<'ctx> NativeQsaResources<'ctx> { // closed actor owns the typed capacity and actual allocations; every later // native request retains its own separate transient admission. fn admit_host(bytes: usize) -> Result<()> { - let needed = u64::try_from(bytes) - .map_err(|_| Error::Overflow)? - .checked_add(FUTURE_HEADROOM) - .ok_or(Error::Overflow)?; + let needed = + u64::try_from(bytes).map_err(|_| Error::Overflow)?.checked_add(FUTURE_HEADROOM).ok_or(Error::Overflow)?; let mut text = String::new(); #[cfg(not(target_os = "windows"))] File::open("/proc/meminfo") @@ -230,11 +231,7 @@ fn admit_host(bytes: usize) -> Result<()> { if out.is_some() { return Err(Error::InputAllocation); } - let value = parts - .next() - .ok_or(Error::InputAllocation)? - .parse::() - .map_err(|_| Error::InputAllocation)?; + let value = parts.next().ok_or(Error::InputAllocation)?.parse::().map_err(|_| Error::InputAllocation)?; if parts.next() != Some("kB") || parts.next().is_some() { return Err(Error::InputAllocation); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs index 2d8b355f..48cde9a8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_native_state.rs @@ -1,57 +1,95 @@ //! Canonical mode17 state is the real completed INT8 owner, never decoded FP16. //! Chronological candidates are published by the existing genuine session journal. use super::*; -use leleka_cuda_driver::{QsaKvSnapshot,QsaPromptKv,QsaPromptIndexPrefix}; +use leleka_cuda_driver::{QsaKvSnapshot, QsaPromptIndexPrefix, QsaPromptKv}; impl QsaPrior { - pub(in crate::qwen_forward) fn empty_native(binding:BindingIdentity,owner:&QsaOwner,layer:LayerId,kv:&QsaPromptKv<'_>)->Result { - let snapshot=kv.empty_snapshot().map_err(driver_error)?; + pub(in crate::qwen_forward) fn empty_native( + binding: BindingIdentity, + owner: &QsaOwner, + layer: LayerId, + kv: &QsaPromptKv<'_>, + ) -> Result { + let snapshot = kv.empty_snapshot().map_err(driver_error)?; kv.validate_snapshot(&snapshot).map_err(driver_error)?; - if snapshot.next_position()!=0 {return Err(Error::InvalidPosition);} - let mut prior=Self::empty(binding,owner,layer)?; - Rc::get_mut(&mut prior.0).ok_or(Error::IdentityMismatch)?.native_kv=Some(snapshot); - prior.validate_extent()?;Ok(prior) + if snapshot.next_position() != 0 { + return Err(Error::InvalidPosition); + } + let mut prior = Self::empty(binding, owner, layer)?; + Rc::get_mut(&mut prior.0).ok_or(Error::IdentityMismatch)?.native_kv = Some(snapshot); + prior.validate_extent()?; + Ok(prior) } - pub(in crate::qwen_forward) fn native_snapshot(&self,kv:&QsaPromptKv<'_>)->Result<&QsaKvSnapshot> { + pub(in crate::qwen_forward) fn native_snapshot(&self, kv: &QsaPromptKv<'_>) -> Result<&QsaKvSnapshot> { self.validate_extent()?; - let snapshot=self.0.native_kv.as_ref().ok_or(Error::IdentityMismatch)?; + let snapshot = self.0.native_kv.as_ref().ok_or(Error::IdentityMismatch)?; kv.validate_snapshot(snapshot).map_err(driver_error)?; Ok(snapshot) } - pub(in crate::qwen_forward) fn has_native_kv(&self)->bool {self.0.native_kv.is_some()} - pub(in crate::qwen_forward) fn native_host_payload_bytes(&self)->Result { - self.validate_extent()?;let snapshot=self.0.native_kv.as_ref().ok_or(Error::IdentityMismatch)?; + pub(in crate::qwen_forward) fn has_native_kv(&self) -> bool { + self.0.native_kv.is_some() + } + pub(in crate::qwen_forward) fn native_host_payload_bytes(&self) -> Result { + self.validate_extent()?; + let snapshot = self.0.native_kv.as_ref().ok_or(Error::IdentityMismatch)?; snapshot.encoded_bytes().checked_add(snapshot.metadata_bytes()).ok_or(Error::Overflow) } } impl QsaPending { /// Called only after the authenticated PromptIndexBatch producer has derived /// this prefix from its actual transaction, and completed append named its row. - pub(in crate::qwen_forward) fn from_prompt_completion(prior:&QsaPrior,identity:TokenLayer, - snapshot:QsaKvSnapshot,index:QsaPromptIndexPrefix<'_>,kv:&QsaPromptKv<'_>)->Result { - let old=prior.native_snapshot(kv)?; - let pos=usize::try_from(prior.next_position()).map_err(|_|Error::Overflow)?; - let end=pos.checked_add(1).ok_or(Error::Overflow)?; - if end>context()||identity.layer()!=prior.layer()||identity.position().get()!=pos as u64 - ||snapshot.next_position()!=end||index.end_position()as usize!=end - ||!old.owner_id().same_owner(&snapshot.owner_id()) {return Err(Error::IdentityMismatch);} + pub(in crate::qwen_forward) fn from_prompt_completion( + prior: &QsaPrior, + identity: TokenLayer, + snapshot: QsaKvSnapshot, + index: QsaPromptIndexPrefix<'_>, + kv: &QsaPromptKv<'_>, + ) -> Result { + let old = prior.native_snapshot(kv)?; + let pos = usize::try_from(prior.next_position()).map_err(|_| Error::Overflow)?; + let end = pos.checked_add(1).ok_or(Error::Overflow)?; + if end > context() + || identity.layer() != prior.layer() + || identity.position().get() != pos as u64 + || snapshot.next_position() != end + || index.end_position() as usize != end + || !old.owner_id().same_owner(&snapshot.owner_id()) + { + return Err(Error::IdentityMismatch); + } kv.validate_snapshot(&snapshot).map_err(driver_error)?; - validate_values(index.pooled(),(end/4)*128)?; - validate_values(index.tail(),384)?;validate_values(index.dead(),128)?; - if pos!=0&&index.dead().iter().zip(prior.0.dead.iter()).any(|(a,b)|a.to_bits()!=b.to_bits()) { + validate_values(index.pooled(), (end / 4) * 128)?; + validate_values(index.tail(), 384)?; + validate_values(index.dead(), 128)?; + if pos != 0 && index.dead().iter().zip(prior.0.dead.iter()).any(|(a, b)| a.to_bits() != b.to_bits()) { return Err(Error::IdentityMismatch); } // Preserve the persistent predecessor directory. A completed block adds // one genuine key; future batch keys are never inserted in this prefix. - let pooled=if end/4==prior.0.pooled.len(){prior.0.pooled.clone()} - else if end/4==prior.0.pooled.len()+1 { - let first=(end/4-1)*128; - prior.0.pooled.appended(Rc::new(index.pooled()[first..first+128].try_into().map_err(|_|Error::InvalidDimension)?))? - } else {return Err(Error::InvalidPosition);}; - let tail=index.tail().try_into().map_err(|_|Error::InvalidDimension)?; - let dead=index.dead().try_into().map_err(|_|Error::InvalidDimension)?; - let next=QsaPrior(Rc::new(State{parent:Rc::downgrade(&prior.0),binding:prior.0.binding.clone(), - owner:prior.0.owner.clone(),layer:prior.layer(),next_position:end as u64,pages:Directory::new(), - pooled,tail,dead,native_kv:Some(snapshot)})); - next.validate_extent()?;Ok(Self{prior:prior.clone(),next,identity}) + let pooled = if end / 4 == prior.0.pooled.len() { + prior.0.pooled.clone() + } else if end / 4 == prior.0.pooled.len() + 1 { + let first = (end / 4 - 1) * 128; + prior.0.pooled.appended(Rc::new( + index.pooled()[first..first + 128].try_into().map_err(|_| Error::InvalidDimension)?, + ))? + } else { + return Err(Error::InvalidPosition); + }; + let tail = index.tail().try_into().map_err(|_| Error::InvalidDimension)?; + let dead = index.dead().try_into().map_err(|_| Error::InvalidDimension)?; + let next = QsaPrior(Rc::new(State { + parent: Rc::downgrade(&prior.0), + binding: prior.0.binding.clone(), + owner: prior.0.owner.clone(), + layer: prior.layer(), + next_position: end as u64, + pages: Directory::new(), + pooled, + tail, + dead, + native_kv: Some(snapshot), + })); + next.validate_extent()?; + Ok(Self { prior: prior.clone(), next, identity }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs index 9744e53b..ff77ae07 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prefill_batch.rs @@ -1,149 +1,299 @@ //! Literal Original prompt projection boundary. Only actual GR rows construct products. //! Root supplies the admitted model-lifetime native owners; no decode factory switch here. #![allow(dead_code)] -use super::{contract::{Error,LayerId,Result,Stage},dense_weight_cache::DenseWeightCache, - gr::ResidualReady,qsa_index::validate_values, - session::{QwenStepTxn,TargetStepOrigin,chunk::QwenChunkTxn}}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,GrRole,ModelBinding,QsaMatrixKind,QsaMatrixRole,QsaWeights}; -use leleka_cuda_driver::{Context,NativeBatchWorkspace,QsaNativeBatchWorkspace,QsaNativeKind}; +use super::{ + contract::{Error, LayerId, Result, Stage}, + dense_weight_cache::DenseWeightCache, + gr::ResidualReady, + qsa_index::validate_values, + session::{QwenStepTxn, TargetStepOrigin, chunk::QwenChunkTxn}, +}; +use crate::model_binding::qwen4exp_input::{ + BindingIdentity, GrRole, ModelBinding, QsaMatrixKind, QsaMatrixRole, QsaWeights, +}; +use leleka_cuda_driver::{Context, NativeBatchWorkspace, QsaNativeBatchWorkspace, QsaNativeKind}; use std::rc::Rc; -const ROLES:[QsaMatrixRole;5]=[QsaMatrixRole::K,QsaMatrixRole::V,QsaMatrixRole::Q,QsaMatrixRole::IndexK,QsaMatrixRole::IndexQ]; -const WIDTHS:[usize;5]=[512,512,12288,128,512]; -fn native_error(error:leleka_cuda_driver::Error)->Error { +const ROLES: [QsaMatrixRole; 5] = + [QsaMatrixRole::K, QsaMatrixRole::V, QsaMatrixRole::Q, QsaMatrixRole::IndexK, QsaMatrixRole::IndexQ]; +const WIDTHS: [usize; 5] = [512, 512, 12288, 128, 512]; +fn native_error(error: leleka_cuda_driver::Error) -> Error { match error { - leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite, - other=>super::qsa_index::driver_error(other), + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + other => super::qsa_index::driver_error(other), } } -fn native(kind:QsaMatrixKind)->Result { - Ok(match kind {QsaMatrixKind::Q4K=>QsaNativeKind::Q4K,QsaMatrixKind::Q5K=>QsaNativeKind::Q5K, - QsaMatrixKind::Q6K=>QsaNativeKind::Q6K,QsaMatrixKind::Iq4Xs=>QsaNativeKind::Iq4Xs, - QsaMatrixKind::Bf16=>return Err(Error::Unsupported(Stage::QsaIndex))}) +fn native(kind: QsaMatrixKind) -> Result { + Ok(match kind { + QsaMatrixKind::Q4K => QsaNativeKind::Q4K, + QsaMatrixKind::Q5K => QsaNativeKind::Q5K, + QsaMatrixKind::Q6K => QsaNativeKind::Q6K, + QsaMatrixKind::Iq4Xs => QsaNativeKind::Iq4Xs, + QsaMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::QsaIndex)), + }) } -pub(super) struct NativeProjectionRow<'source,'ctx> { - binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId, - source:&'source ResidualReady,provider:Rc,values:[Option>;5], +pub(super) struct NativeProjectionRow<'source, 'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + source: &'source ResidualReady, + provider: Rc, + values: [Option>; 5], } impl<'source> NativeProjectionRow<'source, '_> { - pub(super) fn validate(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>, - layer:LayerId,input:&ResidualReady)->Result<()> { + pub(super) fn validate( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + ) -> Result<()> { txn.validate_projection_branch(&self.origin)?; - txn.validate_input(input.identity().token(),input.identity().position())?; - let context=txn.cuda_context()?;cache.retained_context(binding,context)?; - let entry=cache.qsa(binding,layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(self.context,context)||self.layer!=layer - ||!std::ptr::eq(self.source,input)||self.source.identity()!=input.identity() - ||!Rc::ptr_eq(&self.provider,&entry.weights) {return Err(Error::IdentityMismatch);} - input.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?; - for (values,n) in self.values.iter().zip(WIDTHS) {if let Some(values)=values {validate_values(values,n)?;}} + txn.validate_input(input.identity().token(), input.identity().position())?; + let context = txn.cuda_context()?; + cache.retained_context(binding, context)?; + let entry = cache.qsa(binding, layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(self.context, context) + || self.layer != layer + || !std::ptr::eq(self.source, input) + || self.source.identity() != input.identity() + || !Rc::ptr_eq(&self.provider, &entry.weights) + { + return Err(Error::IdentityMismatch); + } + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + for (values, n) in self.values.iter().zip(WIDTHS) { + if let Some(values) = values { + validate_values(values, n)?; + } + } Ok(()) } - pub(super) fn validate_fresh(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>, - txn:&QwenStepTxn<'_, '_>,layer:LayerId,input:&ResidualReady)->Result<()> { - self.validate(binding,cache,txn,layer,input)?; - if self.values.iter().any(Option::is_none) {return Err(Error::IdentityMismatch);} + pub(super) fn validate_fresh( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + ) -> Result<()> { + self.validate(binding, cache, txn, layer, input)?; + if self.values.iter().any(Option::is_none) { + return Err(Error::IdentityMismatch); + } Ok(()) } - pub(super) fn source(&self)->&'source ResidualReady {self.source} - pub(super) fn attend_origin(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>, - txn:&QwenStepTxn<'_, '_>,layer:LayerId,identity:super::contract::TokenLayer)->Result { - self.validate(binding,cache,txn,layer,self.source)?; - if identity!=self.source.identity() {return Err(Error::IdentityMismatch);} + pub(super) fn source(&self) -> &'source ResidualReady { + self.source + } + pub(super) fn attend_origin( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + identity: super::contract::TokenLayer, + ) -> Result { + self.validate(binding, cache, txn, layer, self.source)?; + if identity != self.source.identity() { + return Err(Error::IdentityMismatch); + } Ok(self.origin.clone()) } - pub(super) fn take_prompt(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,chunk:&QwenChunkTxn<'_, '_>, - layer:LayerId,local:usize,role:QsaMatrixRole)->Result> { + pub(super) fn take_prompt( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + local: usize, + role: QsaMatrixRole, + ) -> Result> { self.origin.validate(chunk.original_session()?)?; - let context=cache.retained_context(binding,chunk.context()?)?; - let entry=cache.qsa(binding,layer.get())?; - let index=chunk.micro_row_index(local)?;chunk.validate_attention_input(index,layer,self.source)?; - let(token,pos)=chunk.row_ids(index)?;self.source.identity().validate(token,pos,layer)?; - self.source.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?; - if !self.binding.matches(&binding.identity())||self.layer!=layer||!std::ptr::eq(context,self.context) - ||!Rc::ptr_eq(&entry.weights,&self.provider){return Err(Error::IdentityMismatch);} - let i=ROLES.iter().position(|r|*r==role).ok_or(Error::IdentityMismatch)?; - let values=self.values[i].as_ref().ok_or(Error::IdentityMismatch)?;validate_values(values,WIDTHS[i])?; + let context = cache.retained_context(binding, chunk.context()?)?; + let entry = cache.qsa(binding, layer.get())?; + let index = chunk.micro_row_index(local)?; + chunk.validate_attention_input(index, layer, self.source)?; + let (token, pos) = chunk.row_ids(index)?; + self.source.identity().validate(token, pos, layer)?; + self.source.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + if !self.binding.matches(&binding.identity()) + || self.layer != layer + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + { + return Err(Error::IdentityMismatch); + } + let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; + let values = self.values[i].as_ref().ok_or(Error::IdentityMismatch)?; + validate_values(values, WIDTHS[i])?; self.values[i].take().ok_or(Error::IdentityMismatch) } - pub(super) fn take(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&QwenStepTxn<'_, '_>, - layer:LayerId,input:&ResidualReady,role:QsaMatrixRole)->Result> { - self.validate(binding,cache,txn,layer,input)?; - let i=ROLES.iter().position(|r|*r==role).ok_or(Error::IdentityMismatch)?; + pub(super) fn take( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + role: QsaMatrixRole, + ) -> Result> { + self.validate(binding, cache, txn, layer, input)?; + let i = ROLES.iter().position(|r| *r == role).ok_or(Error::IdentityMismatch)?; self.values[i].take().ok_or(Error::IdentityMismatch) } } #[allow(clippy::too_many_arguments)] // Genuine chunk and separately admitted fixed native owners. -pub(super) fn project<'source,'ctx>(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>, - chunk:&QwenChunkTxn<'_, '_>,layer:LayerId,inputs:&[&'source ResidualReady], - owner:&mut QsaNativeBatchWorkspace<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>) - ->Result>> { - let context=cache.retained_context(binding,chunk.context()?)?; - let origin=chunk.original_session()?.target_origin()?; - let t=inputs.len();if t==0||t>owner.capacity()||t!=chunk.micro_len()? {return Err(Error::InvalidDimension);} - for (local,input) in inputs.iter().enumerate() { - let index=chunk.micro_row_index(local)?;chunk.validate_attention_input(index,layer,input)?; - let (token,pos)=chunk.row_ids(index)?;input.identity().validate(token,pos,layer)?; - input.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?;validate_values(input.mixed(),2560)?; - if inputs[..local].iter().any(|prior|std::ptr::eq(*prior,*input)) {return Err(Error::IdentityMismatch);} - if local>0&&inputs[local-1].identity().position().get().checked_add(1)!=Some(pos.get()) {return Err(Error::InvalidPosition);} +pub(super) fn project<'source, 'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + inputs: &[&'source ResidualReady], + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result>> { + let context = cache.retained_context(binding, chunk.context()?)?; + let origin = chunk.original_session()?.target_origin()?; + let t = inputs.len(); + if t == 0 || t > owner.capacity() || t != chunk.micro_len()? { + return Err(Error::InvalidDimension); + } + for (local, input) in inputs.iter().enumerate() { + let index = chunk.micro_row_index(local)?; + chunk.validate_attention_input(index, layer, input)?; + let (token, pos) = chunk.row_ids(index)?; + input.identity().validate(token, pos, layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + validate_values(input.mixed(), 2560)?; + if inputs[..local].iter().any(|prior| std::ptr::eq(*prior, *input)) { + return Err(Error::IdentityMismatch); + } + if local > 0 && inputs[local - 1].identity().position().get().checked_add(1) != Some(pos.get()) { + return Err(Error::InvalidPosition); + } + } + let entry = cache.qsa(binding, layer.get())?; + for (role, n) in ROLES.into_iter().zip(WIDTHS) { + if entry.weights.shape(role) != (2560, n) { + return Err(Error::InvalidDimension); + } } - let entry=cache.qsa(binding,layer.get())?; - for (role,n) in ROLES.into_iter().zip(WIDTHS) {if entry.weights.shape(role)!=(2560,n){return Err(Error::InvalidDimension);}} // All Original need() weights are genuine retained whole matrices. - let (k,kk)=cache.qsa_matrix(entry,QsaMatrixRole::K)?; - let (v,vk)=cache.qsa_matrix(entry,QsaMatrixRole::V)?; - let (q,qk)=cache.qsa_matrix(entry,QsaMatrixRole::Q)?; - let (ik,ikk)=cache.qsa_matrix(entry,QsaMatrixRole::IndexK)?; - let (iq,iqk)=cache.qsa_matrix(entry,QsaMatrixRole::IndexQ)?; - if ikk!=QsaMatrixKind::Bf16||iqk!=QsaMatrixKind::Bf16 {return Err(Error::Unsupported(Stage::QsaIndex));} - let mut mixed=Vec::new();mixed.try_reserve_exact(t*2560).map_err(|_|Error::InputAllocation)?; - for input in inputs {mixed.extend_from_slice(input.mixed());} - let output=owner.project_inputs(t,&mixed,[k,v,q,ik,iq],[native(kk)?,native(vk)?,native(qk)?],workspace).map_err(native_error)?; - let batches=[output.k,output.v,output.q,output.index_k,output.index_q]; - for (values,n) in batches.iter().zip(WIDTHS) {validate_values(values,t*n)?;} + let (k, kk) = cache.qsa_matrix(entry, QsaMatrixRole::K)?; + let (v, vk) = cache.qsa_matrix(entry, QsaMatrixRole::V)?; + let (q, qk) = cache.qsa_matrix(entry, QsaMatrixRole::Q)?; + let (ik, ikk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexK)?; + let (iq, iqk) = cache.qsa_matrix(entry, QsaMatrixRole::IndexQ)?; + if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::QsaIndex)); + } + let mut mixed = Vec::new(); + mixed.try_reserve_exact(t * 2560).map_err(|_| Error::InputAllocation)?; + for input in inputs { + mixed.extend_from_slice(input.mixed()); + } + let output = owner + .project_inputs(t, &mixed, [k, v, q, ik, iq], [native(kk)?, native(vk)?, native(qk)?], workspace) + .map_err(native_error)?; + let batches = [output.k, output.v, output.q, output.index_k, output.index_q]; + for (values, n) in batches.iter().zip(WIDTHS) { + validate_values(values, t * n)?; + } // Full whole-batch finite checks precede every row capability allocation. - let mut result=Vec::new();result.try_reserve_exact(t).map_err(|_|Error::InputAllocation)?; - for (local,source) in inputs.iter().enumerate() { - let mut values:[Option>;5]=std::array::from_fn(|_|None); - for i in 0..5 {let n=WIDTHS[i];let mut row=Vec::new();row.try_reserve_exact(n).map_err(|_|Error::InputAllocation)?; - row.extend_from_slice(&batches[i][local*n..(local+1)*n]);values[i]=Some(row.into_boxed_slice());} - result.push(NativeProjectionRow{binding:binding.identity(),origin:origin.clone(),context,layer,source, - provider:entry.weights.clone(),values}); - } Ok(result) + let mut result = Vec::new(); + result.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + for (local, source) in inputs.iter().enumerate() { + let mut values: [Option>; 5] = std::array::from_fn(|_| None); + for i in 0..5 { + let n = WIDTHS[i]; + let mut row = Vec::new(); + row.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + row.extend_from_slice(&batches[i][local * n..(local + 1) * n]); + values[i] = Some(row.into_boxed_slice()); + } + result.push(NativeProjectionRow { + binding: binding.identity(), + origin: origin.clone(), + context, + layer, + source, + provider: entry.weights.clone(), + values, + }); + } + Ok(result) } pub(super) struct NativeOutRow<'ctx> { - binding:BindingIdentity,identity:super::contract::TokenLayer,context:&'ctx Context<'ctx>,values:Box<[f32]>, + binding: BindingIdentity, + identity: super::contract::TokenLayer, + context: &'ctx Context<'ctx>, + values: Box<[f32]>, } impl NativeOutRow<'_> { - pub(super) fn take(self,binding:&BindingIdentity,identity:super::contract::TokenLayer,context:&Context<'_>)->Result> { - if !self.binding.matches(binding)||self.identity!=identity||!std::ptr::eq(self.context,context) {return Err(Error::IdentityMismatch);} - validate_values(&self.values,2560)?;Ok(self.values) + pub(super) fn take( + self, + binding: &BindingIdentity, + identity: super::contract::TokenLayer, + context: &Context<'_>, + ) -> Result> { + if !self.binding.matches(binding) || self.identity != identity || !std::ptr::eq(self.context, context) { + return Err(Error::IdentityMismatch); + } + validate_values(&self.values, 2560)?; + Ok(self.values) } } #[allow(clippy::too_many_arguments)] // Actual attention producers and current chunk fence. -pub(super) fn project_out<'ctx>(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,chunk:&QwenChunkTxn<'_, '_>, - layer:LayerId,rows:&[super::qsa_attention::NativeAttended<'_,'ctx>], - proofs:&[super::session::chunk::PreparedLayerRow],owner:&mut QsaNativeBatchWorkspace<'ctx>, - workspace:&mut NativeBatchWorkspace<'ctx>)->Result> { - let context=cache.retained_context(binding,chunk.context()?)?; - let t=rows.len();if t==0||t>owner.capacity()||t!=chunk.micro_len()?||proofs.len()!=t {return Err(Error::InvalidDimension);} - let entry=cache.qsa(binding,layer.get())?; - let mut attended=Vec::new();let mut gates=Vec::new(); - attended.try_reserve_exact(t*6144).map_err(|_|Error::InputAllocation)?; - gates.try_reserve_exact(t*6144).map_err(|_|Error::InputAllocation)?; - for (local,row) in rows.iter().enumerate() { - row.validate(binding,cache,chunk,layer,local,context,&proofs[local])?; - attended.extend_from_slice(row.values());gates.extend_from_slice(row.gate()); +pub(super) fn project_out<'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + rows: &[super::qsa_attention::NativeAttended<'_, 'ctx>], + proofs: &[super::session::chunk::PreparedLayerRow], + owner: &mut QsaNativeBatchWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let context = cache.retained_context(binding, chunk.context()?)?; + let t = rows.len(); + if t == 0 || t > owner.capacity() || t != chunk.micro_len()? || proofs.len() != t { + return Err(Error::InvalidDimension); } - if entry.weights.shape(QsaMatrixRole::Out)!=(6144,2560) {return Err(Error::InvalidDimension);} - let (weight,kind)=cache.qsa_matrix(entry,QsaMatrixRole::Out)?; - let output=owner.project_out(t,&attended,&gates,weight,native(kind)?,workspace).map_err(native_error)?; - validate_values(&output,t*2560)?; - let mut ready=Vec::new();ready.try_reserve_exact(t).map_err(|_|Error::InputAllocation)?; - for (local,row) in rows.iter().enumerate() { - row.validate(binding,cache,chunk,layer,local,context,&proofs[local])?; - let mut values=Vec::new();values.try_reserve_exact(2560).map_err(|_|Error::InputAllocation)?; - values.extend_from_slice(&output[local*2560..(local+1)*2560]); - ready.push(row.ready(binding,NativeOutRow{binding:binding.identity(),identity:row.identity(),context,values:values.into_boxed_slice()})?); - } Ok(ready) + let entry = cache.qsa(binding, layer.get())?; + let mut attended = Vec::new(); + let mut gates = Vec::new(); + attended.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; + gates.try_reserve_exact(t * 6144).map_err(|_| Error::InputAllocation)?; + for (local, row) in rows.iter().enumerate() { + row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; + attended.extend_from_slice(row.values()); + gates.extend_from_slice(row.gate()); + } + if entry.weights.shape(QsaMatrixRole::Out) != (6144, 2560) { + return Err(Error::InvalidDimension); + } + let (weight, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; + let output = owner.project_out(t, &attended, &gates, weight, native(kind)?, workspace).map_err(native_error)?; + validate_values(&output, t * 2560)?; + let mut ready = Vec::new(); + ready.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + for (local, row) in rows.iter().enumerate() { + row.validate(binding, cache, chunk, layer, local, context, &proofs[local])?; + let mut values = Vec::new(); + values.try_reserve_exact(2560).map_err(|_| Error::InputAllocation)?; + values.extend_from_slice(&output[local * 2560..(local + 1) * 2560]); + ready.push(row.ready( + binding, + NativeOutRow { + binding: binding.identity(), + identity: row.identity(), + context, + values: values.into_boxed_slice(), + }, + )?); + } + Ok(ready) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs index a2cb2781..01bcb0bf 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_device.rs @@ -1,62 +1,231 @@ //! Genuine current prompt QSA over one affine physical arena. Canonical INT8 //! snapshots/index prefixes are the actual completed driver products; no host //! residual or query/selection certificate is fabricated. +use super::super::session::{TargetStepOrigin, chunk::QwenChunkTxn}; use super::*; -use super::super::session::{TargetStepOrigin,chunk::QwenChunkTxn}; -use leleka_cuda_driver::{OriginalDeviceGrRead,OriginalDeviceBlock,OriginalQsaPromptDevice,OriginalQsaDeviceSelection,OriginalQsaPromptWeights,QsaNativeKind,NativeBatchWorkspace,QsaPromptKv,QsaPromptStage,QsaPromptAttention,QsaPromptIndexState,CompletedQsaKvAppend}; -const ROLES:[QsaMatrixRole;6]=[QsaMatrixRole::K,QsaMatrixRole::V,QsaMatrixRole::Q,QsaMatrixRole::IndexK,QsaMatrixRole::IndexQ,QsaMatrixRole::Out]; -fn native(kind:QsaMatrixKind)->Result{Ok(match kind{QsaMatrixKind::Q4K=>QsaNativeKind::Q4K,QsaMatrixKind::Q5K=>QsaNativeKind::Q5K,QsaMatrixKind::Q6K=>QsaNativeKind::Q6K,QsaMatrixKind::Iq4Xs=>QsaNativeKind::Iq4Xs,QsaMatrixKind::Bf16=>return Err(Error::Unsupported(Stage::QsaIndex))})} -fn device_error(e:DriverError)->Error{match e{DriverError::NonFiniteMmqOutput(_)=>Error::NonFinite,other=>driver_error(other)}} -pub(in crate::qwen_forward) struct PromptDeviceQsaSelection<'lease,'arena,'loan,'ctx>{binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId,prior:QsaPrior,provider:Rc,identities:Vec,selected:OriginalQsaDeviceSelection<'lease,'arena,'loan,'ctx>} -pub(in crate::qwen_forward) struct PromptDeviceQsaState<'ctx>{binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId,prior:QsaPrior,provider:Rc,identities:Vec,index:QsaPromptIndexState,kv:CompletedQsaKvAppend} -#[allow(clippy::too_many_arguments)] -pub(in crate::qwen_forward) fn prepare_prompt_device<'lease,'arena,'loan,'ctx>(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,chunk:&QwenChunkTxn<'_, '_>,layer:LayerId,prior:&QsaPrior,producer:&'lease mut OriginalQsaPromptDevice<'ctx>,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>)->Result>{ - let context=cache.retained_context(binding,chunk.context()?)?;cache.validate(binding)?;chunk.validate_prompt_qsa_prior(layer,prior)?; - let t=read.rows();if t==0||t!=chunk.micro_len()?||!read.context_matches(context){return Err(Error::IdentityMismatch)} - let entry=cache.qsa(binding,layer.get())?;let origin=chunk.original_session()?.target_origin()?; - let mut identities=Vec::new();identities.try_reserve_exact(t).map_err(|_|Error::InputAllocation)?; - let first=prior.next_position(); - for local in 0..t{let index=chunk.micro_row_index(local)?;let(token,pos)=chunk.row_ids(index)?; - if pos.get()!=first.checked_add(local as u64).ok_or(Error::Overflow)?{return Err(Error::InvalidPosition)}identities.push(TokenLayer::new(token,pos,layer));} - for(role,n,k)in[(QsaMatrixRole::K,512,2560),(QsaMatrixRole::V,512,2560),(QsaMatrixRole::Q,12288,2560),(QsaMatrixRole::IndexK,128,2560),(QsaMatrixRole::IndexQ,512,2560),(QsaMatrixRole::Out,2560,6144)]{if entry.weights.shape(role)!=(k,n){return Err(Error::InvalidDimension)}} - let(k,kk)=cache.qsa_matrix(entry,ROLES[0])?;let(v,vk)=cache.qsa_matrix(entry,ROLES[1])?;let(q,qk)=cache.qsa_matrix(entry,ROLES[2])?; - let(ik,ikk)=cache.qsa_matrix(entry,ROLES[3])?;let(iq,iqk)=cache.qsa_matrix(entry,ROLES[4])?;let(out,ok)=cache.qsa_matrix(entry,ROLES[5])?; - if ikk!=QsaMatrixKind::Bf16||iqk!=QsaMatrixKind::Bf16{return Err(Error::Unsupported(Stage::QsaIndex))} - let(pooled,tail,dead)=prior.native_index_image()?;let norms=cache.qsa_norms(entry)?; - let selected=producer.prepare(read,workspace,u32::try_from(first).map_err(|_|Error::InvalidPosition)?,&pooled,&tail,&dead,OriginalQsaPromptWeights{projections:[k,v,q,ik,iq,out],kinds:[native(kk)?,native(vk)?,native(qk)?,native(ok)?],norms}).map_err(device_error)?; - chunk.validate_prompt_qsa_prior(layer,prior)?;cache.validate(binding)?;origin.validate(chunk.original_session()?)?; - Ok(PromptDeviceQsaSelection{binding:binding.identity(),origin,context,layer,prior:prior.clone(),provider:entry.weights.clone(),identities,selected}) +use leleka_cuda_driver::{ + CompletedQsaKvAppend, NativeBatchWorkspace, OriginalDeviceBlock, OriginalDeviceGrRead, OriginalQsaDeviceSelection, + OriginalQsaPromptDevice, OriginalQsaPromptWeights, QsaNativeKind, QsaPromptAttention, QsaPromptIndexState, + QsaPromptKv, QsaPromptStage, +}; +const ROLES: [QsaMatrixRole; 6] = [ + QsaMatrixRole::K, + QsaMatrixRole::V, + QsaMatrixRole::Q, + QsaMatrixRole::IndexK, + QsaMatrixRole::IndexQ, + QsaMatrixRole::Out, +]; +fn native(kind: QsaMatrixKind) -> Result { + Ok(match kind { + QsaMatrixKind::Q4K => QsaNativeKind::Q4K, + QsaMatrixKind::Q5K => QsaNativeKind::Q5K, + QsaMatrixKind::Q6K => QsaNativeKind::Q6K, + QsaMatrixKind::Iq4Xs => QsaNativeKind::Iq4Xs, + QsaMatrixKind::Bf16 => return Err(Error::Unsupported(Stage::QsaIndex)), + }) } -impl<'lease,'arena,'loan,'ctx> PromptDeviceQsaSelection<'lease,'arena,'loan,'ctx>{ - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn complete(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,chunk:&QwenChunkTxn<'_, '_>,workspace:&mut NativeBatchWorkspace<'ctx>,kv:&mut QsaPromptKv<'ctx>,stage:&mut QsaPromptStage<'ctx>,attention:&mut QsaPromptAttention<'ctx>)->Result<(OriginalDeviceBlock<'arena,'loan,'ctx>,PromptDeviceQsaState<'ctx>)>{ - self.origin.validate(chunk.original_session()?)?;chunk.validate_prompt_qsa_prior(self.layer,&self.prior)?;cache.validate(binding)?; - let context=cache.retained_context(binding,chunk.context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider)||self.selected.rows()!=self.identities.len(){return Err(Error::IdentityMismatch)} - for(local,id)in self.identities.iter().enumerate(){let(token,pos)=chunk.row_ids(chunk.micro_row_index(local)?)?;id.validate(token,pos,self.layer)?;} - let(out,kind)=cache.qsa_matrix(entry,QsaMatrixRole::Out)?; - let snapshot=self.prior.native_snapshot(kv)?; - let(block,index,appended)=self.selected.complete(workspace,kv,stage,snapshot,attention,out,native(kind)?).map_err(device_error)?; - cache.validate(binding)?;cache.retained_context(binding,context)?;self.origin.validate(chunk.original_session()?)?;chunk.validate_prompt_qsa_prior(self.layer,&self.prior)?; - for(local,id)in self.identities.iter().enumerate(){let(token,pos)=chunk.row_ids(chunk.micro_row_index(local)?)?;id.validate(token,pos,self.layer)?;} - Ok((block,PromptDeviceQsaState{binding:self.binding,origin:self.origin,context:self.context,layer:self.layer,prior:self.prior,provider:self.provider,identities:self.identities,index,kv:appended})) +fn device_error(e: DriverError) -> Error { + match e { + DriverError::NonFiniteMmqOutput(_) => Error::NonFinite, + other => driver_error(other), } } -impl PromptDeviceQsaState<'_>{ +pub(in crate::qwen_forward) struct PromptDeviceQsaSelection<'lease, 'arena, 'loan, 'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: QsaPrior, + provider: Rc, + identities: Vec, + selected: OriginalQsaDeviceSelection<'lease, 'arena, 'loan, 'ctx>, +} +pub(in crate::qwen_forward) struct PromptDeviceQsaState<'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: QsaPrior, + provider: Rc, + identities: Vec, + index: QsaPromptIndexState, + kv: CompletedQsaKvAppend, +} +#[allow(clippy::too_many_arguments)] +pub(in crate::qwen_forward) fn prepare_prompt_device<'lease, 'arena, 'loan, 'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + prior: &QsaPrior, + producer: &'lease mut OriginalQsaPromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let context = cache.retained_context(binding, chunk.context()?)?; + cache.validate(binding)?; + chunk.validate_prompt_qsa_prior(layer, prior)?; + let t = read.rows(); + if t == 0 || t != chunk.micro_len()? || !read.context_matches(context) { + return Err(Error::IdentityMismatch); + } + let entry = cache.qsa(binding, layer.get())?; + let origin = chunk.original_session()?.target_origin()?; + let mut identities = Vec::new(); + identities.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + let first = prior.next_position(); + for local in 0..t { + let index = chunk.micro_row_index(local)?; + let (token, pos) = chunk.row_ids(index)?; + if pos.get() != first.checked_add(local as u64).ok_or(Error::Overflow)? { + return Err(Error::InvalidPosition); + } + identities.push(TokenLayer::new(token, pos, layer)); + } + for (role, n, k) in [ + (QsaMatrixRole::K, 512, 2560), + (QsaMatrixRole::V, 512, 2560), + (QsaMatrixRole::Q, 12288, 2560), + (QsaMatrixRole::IndexK, 128, 2560), + (QsaMatrixRole::IndexQ, 512, 2560), + (QsaMatrixRole::Out, 2560, 6144), + ] { + if entry.weights.shape(role) != (k, n) { + return Err(Error::InvalidDimension); + } + } + let (k, kk) = cache.qsa_matrix(entry, ROLES[0])?; + let (v, vk) = cache.qsa_matrix(entry, ROLES[1])?; + let (q, qk) = cache.qsa_matrix(entry, ROLES[2])?; + let (ik, ikk) = cache.qsa_matrix(entry, ROLES[3])?; + let (iq, iqk) = cache.qsa_matrix(entry, ROLES[4])?; + let (out, ok) = cache.qsa_matrix(entry, ROLES[5])?; + if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::QsaIndex)); + } + let (pooled, tail, dead) = prior.native_index_image()?; + let norms = cache.qsa_norms(entry)?; + let selected = producer + .prepare( + read, + workspace, + u32::try_from(first).map_err(|_| Error::InvalidPosition)?, + &pooled, + &tail, + &dead, + OriginalQsaPromptWeights { + projections: [k, v, q, ik, iq, out], + kinds: [native(kk)?, native(vk)?, native(qk)?, native(ok)?], + norms, + }, + ) + .map_err(device_error)?; + chunk.validate_prompt_qsa_prior(layer, prior)?; + cache.validate(binding)?; + origin.validate(chunk.original_session()?)?; + Ok(PromptDeviceQsaSelection { + binding: binding.identity(), + origin, + context, + layer, + prior: prior.clone(), + provider: entry.weights.clone(), + identities, + selected, + }) +} +impl<'lease, 'arena, 'loan, 'ctx> PromptDeviceQsaSelection<'lease, 'arena, 'loan, 'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn complete( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + kv: &mut QsaPromptKv<'ctx>, + stage: &mut QsaPromptStage<'ctx>, + attention: &mut QsaPromptAttention<'ctx>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, PromptDeviceQsaState<'ctx>)> { + self.origin.validate(chunk.original_session()?)?; + chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; + cache.validate(binding)?; + let context = cache.retained_context(binding, chunk.context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + || self.selected.rows() != self.identities.len() + { + return Err(Error::IdentityMismatch); + } + for (local, id) in self.identities.iter().enumerate() { + let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; + id.validate(token, pos, self.layer)?; + } + let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; + let snapshot = self.prior.native_snapshot(kv)?; + let (block, index, appended) = self + .selected + .complete(workspace, kv, stage, snapshot, attention, out, native(kind)?) + .map_err(device_error)?; + cache.validate(binding)?; + cache.retained_context(binding, context)?; + self.origin.validate(chunk.original_session()?)?; + chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; + for (local, id) in self.identities.iter().enumerate() { + let (token, pos) = chunk.row_ids(chunk.micro_row_index(local)?)?; + id.validate(token, pos, self.layer)?; + } + Ok(( + block, + PromptDeviceQsaState { + binding: self.binding, + origin: self.origin, + context: self.context, + layer: self.layer, + prior: self.prior, + provider: self.provider, + identities: self.identities, + index, + kv: appended, + }, + )) + } +} +impl PromptDeviceQsaState<'_> { /// Genuine chronological current transaction, true previous native prior, /// actual prefix after this row and actual completed INT8 snapshot. The /// whole final state is never relabelled as an earlier row's state. - pub(in crate::qwen_forward) fn pending_for_txn(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&super::super::session::QwenStepTxn<'_, '_>,prior:&QsaPrior,kv:&QsaPromptKv<'_>)->Result{ - txn.validate_binding(&binding.identity())?;txn.validate_projection_branch(&self.origin)?;txn.validate_qsa_prior(prior,self.layer)?; - let context=cache.retained_context(binding,txn.cuda_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider){return Err(Error::IdentityMismatch)} - let local=txn.position().get().checked_sub(self.prior.next_position()).ok_or(Error::InvalidPosition)?; - let local=usize::try_from(local).map_err(|_|Error::InvalidPosition)?;let id=*self.identities.get(local).ok_or(Error::InvalidPosition)?; - id.validate(txn.token(),txn.position(),self.layer)?;txn.validate_input(id.token(),id.position())?; - let snapshot=self.kv.snapshot_after(local).map_err(device_error)?;let prefix=self.index.completed_prefix((local+1)as u32).map_err(device_error)?; - QsaPending::from_prompt_completion(prior,id,snapshot,prefix,kv) + pub(in crate::qwen_forward) fn pending_for_txn( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &super::super::session::QwenStepTxn<'_, '_>, + prior: &QsaPrior, + kv: &QsaPromptKv<'_>, + ) -> Result { + txn.validate_binding(&binding.identity())?; + txn.validate_projection_branch(&self.origin)?; + txn.validate_qsa_prior(prior, self.layer)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + { + return Err(Error::IdentityMismatch); + } + let local = txn.position().get().checked_sub(self.prior.next_position()).ok_or(Error::InvalidPosition)?; + let local = usize::try_from(local).map_err(|_| Error::InvalidPosition)?; + let id = *self.identities.get(local).ok_or(Error::InvalidPosition)?; + id.validate(txn.token(), txn.position(), self.layer)?; + txn.validate_input(id.token(), id.position())?; + let snapshot = self.kv.snapshot_after(local).map_err(device_error)?; + let prefix = self.index.completed_prefix((local + 1) as u32).map_err(device_error)?; + QsaPending::from_prompt_completion(prior, id, snapshot, prefix, kv) } } -#[path="qsa_resident_device.rs"] +#[path = "qsa_resident_device.rs"] pub(in crate::qwen_forward) mod resident_device; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs index 307c4661..d9cefae2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_prompt_index.rs @@ -1,94 +1,286 @@ //! Literal prompt index producer. Root owns causal native KV/prefix publication. //! Whole index final state is an end-only product, never a manufactured per-row prior. #![allow(dead_code)] -use super::{contract::{Error,LayerId,Result},dense_weight_cache::DenseWeightCache, - gr::ResidualReady,qsa_index::{QsaPrior,validate_values},qsa_prefill_batch::NativeProjectionRow, - session::{TargetStepOrigin,chunk::{QwenChunkTxn,PreparedLayerRow}}}; -use crate::model_binding::qwen4exp_input::{BindingIdentity,GrRole,ModelBinding,QsaMatrixRole,QsaWeights}; -use leleka_cuda_driver::{Context,DeviceBuffer,NativeBatchWorkspace,QsaPromptIndexWorkspace,QsaPromptSelection,QsaPromptIndexState,QsaPromptIndexPrefix}; +use super::{ + contract::{Error, LayerId, Result}, + dense_weight_cache::DenseWeightCache, + gr::ResidualReady, + qsa_index::{QsaPrior, validate_values}, + qsa_prefill_batch::NativeProjectionRow, + session::{ + TargetStepOrigin, + chunk::{PreparedLayerRow, QwenChunkTxn}, + }, +}; +use crate::model_binding::qwen4exp_input::{BindingIdentity, GrRole, ModelBinding, QsaMatrixRole, QsaWeights}; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeBatchWorkspace, QsaPromptIndexPrefix, QsaPromptIndexState, QsaPromptIndexWorkspace, + QsaPromptSelection, +}; use std::rc::Rc; -fn driver(e:leleka_cuda_driver::Error)->Error{match e{leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite,other=>super::qsa_index::driver_error(other)}} -pub(super) struct PromptIndexBatch<'source,'lease,'ctx>{ - binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId, - prior:QsaPrior,provider:Rc,sources:Vec<&'source ResidualReady>,gate:Box<[f32]>, - selected:QsaPromptSelection<'lease,'ctx>, +fn driver(e: leleka_cuda_driver::Error) -> Error { + match e { + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + other => super::qsa_index::driver_error(other), + } +} +pub(super) struct PromptIndexBatch<'source, 'lease, 'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: QsaPrior, + provider: Rc, + sources: Vec<&'source ResidualReady>, + gate: Box<[f32]>, + selected: QsaPromptSelection<'lease, 'ctx>, } #[allow(clippy::too_many_arguments)] // Actual whole chunk/current prior and admitted fixed owners. -pub(super) fn prepare<'source,'lease,'ctx>(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,chunk:&QwenChunkTxn<'_, '_>, - layer:LayerId,prior:&QsaPrior,rows:&mut[NativeProjectionRow<'source,'ctx>], - owner:&'lease mut QsaPromptIndexWorkspace<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>) - ->Result>{ - let t=rows.len();if t==0||t>owner.capacity()||t!=chunk.micro_len()?{return Err(Error::InvalidDimension);} - let context=cache.retained_context(binding,chunk.context()?)?; +pub(super) fn prepare<'source, 'lease, 'ctx>( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + chunk: &QwenChunkTxn<'_, '_>, + layer: LayerId, + prior: &QsaPrior, + rows: &mut [NativeProjectionRow<'source, 'ctx>], + owner: &'lease mut QsaPromptIndexWorkspace<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, +) -> Result> { + let t = rows.len(); + if t == 0 || t > owner.capacity() || t != chunk.micro_len()? { + return Err(Error::InvalidDimension); + } + let context = cache.retained_context(binding, chunk.context()?)?; // Root's authentic current next_qsa/source-owner fence. No arbitrary prior acceptance. - chunk.validate_prompt_qsa_prior(layer,prior)?; - let entry=cache.qsa(binding,layer.get())?;let origin=chunk.original_session()?.target_origin()?; - let first=rows[0].source().identity().position().get();if prior.next_position()!=first{return Err(Error::InvalidPosition);} - let mut sources:Vec<&'source ResidualReady>=Vec::new();sources.try_reserve_exact(t).map_err(|_|Error::InputAllocation)?; - let mut raw=Vec::new();let mut k=Vec::new();let mut v=Vec::new();let mut qfull=Vec::new();let mut iq=Vec::new();let mut gate=Vec::new(); - for(x,n)in [(&mut raw,t*128),(&mut k,t*512),(&mut v,t*512),(&mut qfull,t*12288),(&mut iq,t*512),(&mut gate,t*6144)]{x.try_reserve_exact(n).map_err(|_|Error::InputAllocation)?;} + chunk.validate_prompt_qsa_prior(layer, prior)?; + let entry = cache.qsa(binding, layer.get())?; + let origin = chunk.original_session()?.target_origin()?; + let first = rows[0].source().identity().position().get(); + if prior.next_position() != first { + return Err(Error::InvalidPosition); + } + let mut sources: Vec<&'source ResidualReady> = Vec::new(); + sources.try_reserve_exact(t).map_err(|_| Error::InputAllocation)?; + let mut raw = Vec::new(); + let mut k = Vec::new(); + let mut v = Vec::new(); + let mut qfull = Vec::new(); + let mut iq = Vec::new(); + let mut gate = Vec::new(); + for (x, n) in [ + (&mut raw, t * 128), + (&mut k, t * 512), + (&mut v, t * 512), + (&mut qfull, t * 12288), + (&mut iq, t * 512), + (&mut gate, t * 6144), + ] { + x.try_reserve_exact(n).map_err(|_| Error::InputAllocation)?; + } // All original producer/row guards precede role consumption or CUDA writes. - for(local,row)in rows.iter().enumerate(){let source=row.source();let index=chunk.micro_row_index(local)?;chunk.validate_attention_input(index,layer,source)?; - let(token,pos)=chunk.row_ids(index)?;source.identity().validate(token,pos,layer)?;source.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?; - if pos.get()!=first+local as u64||sources.iter().any(|old|std::ptr::eq(*old,source)){return Err(Error::IdentityMismatch);} - validate_values(source.mixed(),2560)?;sources.push(source); + for (local, row) in rows.iter().enumerate() { + let source = row.source(); + let index = chunk.micro_row_index(local)?; + chunk.validate_attention_input(index, layer, source)?; + let (token, pos) = chunk.row_ids(index)?; + source.identity().validate(token, pos, layer)?; + source.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + if pos.get() != first + local as u64 || sources.iter().any(|old| std::ptr::eq(*old, source)) { + return Err(Error::IdentityMismatch); + } + validate_values(source.mixed(), 2560)?; + sources.push(source); } - for(local,row)in rows.iter_mut().enumerate(){ - k.extend_from_slice(&row.take_prompt(binding,cache,chunk,layer,local,QsaMatrixRole::K)?); - v.extend_from_slice(&row.take_prompt(binding,cache,chunk,layer,local,QsaMatrixRole::V)?); - let q=row.take_prompt(binding,cache,chunk,layer,local,QsaMatrixRole::Q)?; - for h in 0..24{gate.extend_from_slice(&q[h*512+256..h*512+512]);}qfull.extend_from_slice(&q); - raw.extend_from_slice(&row.take_prompt(binding,cache,chunk,layer,local,QsaMatrixRole::IndexK)?); - iq.extend_from_slice(&row.take_prompt(binding,cache,chunk,layer,local,QsaMatrixRole::IndexQ)?); + for (local, row) in rows.iter_mut().enumerate() { + k.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::K)?); + v.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::V)?); + let q = row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::Q)?; + for h in 0..24 { + gate.extend_from_slice(&q[h * 512 + 256..h * 512 + 512]); + } + qfull.extend_from_slice(&q); + raw.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexK)?); + iq.extend_from_slice(&row.take_prompt(binding, cache, chunk, layer, local, QsaMatrixRole::IndexQ)?); } - for(x,n)in [(&raw,t*128),(&k,t*512),(&v,t*512),(&qfull,t*12288),(&iq,t*512),(&gate,t*6144)]{validate_values(x,n)?;} - let(pooled,tail,dead)=prior.native_index_image()?;let gamma=cache.qsa_norms(entry)?; - let selected=owner.append_select(u32::try_from(first).map_err(|_|Error::InvalidPosition)?,t as u32,&pooled,&tail,&dead, - &raw,&k,&v,&qfull,&iq,gamma,workspace).map_err(driver)?; - chunk.validate_prompt_qsa_prior(layer,prior)?;cache.retained_context(binding,context)?;origin.validate(chunk.original_session()?)?; - for(local,source)in sources.iter().enumerate(){chunk.validate_attention_input(chunk.micro_row_index(local)?,layer,source)?;} - Ok(PromptIndexBatch{binding:binding.identity(),origin,context,layer,prior:prior.clone(),provider:entry.weights.clone(),sources,gate:gate.into_boxed_slice(),selected}) + for (x, n) in + [(&raw, t * 128), (&k, t * 512), (&v, t * 512), (&qfull, t * 12288), (&iq, t * 512), (&gate, t * 6144)] + { + validate_values(x, n)?; + } + let (pooled, tail, dead) = prior.native_index_image()?; + let gamma = cache.qsa_norms(entry)?; + let selected = owner + .append_select( + u32::try_from(first).map_err(|_| Error::InvalidPosition)?, + t as u32, + &pooled, + &tail, + &dead, + &raw, + &k, + &v, + &qfull, + &iq, + gamma, + workspace, + ) + .map_err(driver)?; + chunk.validate_prompt_qsa_prior(layer, prior)?; + cache.retained_context(binding, context)?; + origin.validate(chunk.original_session()?)?; + for (local, source) in sources.iter().enumerate() { + chunk.validate_attention_input(chunk.micro_row_index(local)?, layer, source)?; + } + Ok(PromptIndexBatch { + binding: binding.identity(), + origin, + context, + layer, + prior: prior.clone(), + provider: entry.weights.clone(), + sources, + gate: gate.into_boxed_slice(), + selected, + }) } -impl<'source,'lease,'ctx> PromptIndexBatch<'source,'lease,'ctx>{ - fn validate(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,chunk:&QwenChunkTxn<'_, '_>)->Result<()>{ - self.origin.validate(chunk.original_session()?)?;let context=cache.retained_context(binding,chunk.context()?)?; - let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider) - ||self.selected.rows()as usize!=self.sources.len()||self.selected.first_position()as u64!=self.prior.next_position() - ||self.selected.final_index().end_position()as u64!=self.prior.next_position()+self.sources.len()as u64{return Err(Error::IdentityMismatch);} - validate_values(&self.gate,self.sources.len()*6144)?;Ok(()) +impl<'source, 'lease, 'ctx> PromptIndexBatch<'source, 'lease, 'ctx> { + fn validate( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + ) -> Result<()> { + self.origin.validate(chunk.original_session()?)?; + let context = cache.retained_context(binding, chunk.context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + || self.selected.rows() as usize != self.sources.len() + || self.selected.first_position() as u64 != self.prior.next_position() + || self.selected.final_index().end_position() as u64 + != self.prior.next_position() + self.sources.len() as u64 + { + return Err(Error::IdentityMismatch); + } + validate_values(&self.gate, self.sources.len() * 6144)?; + Ok(()) } - pub(super) fn rows(&self)->usize{self.sources.len()} - pub(super) fn source(&self,local:usize)->Result<&'source ResidualReady>{self.sources.get(local).copied().ok_or(Error::InvalidPosition)} - pub(super) fn gate(&self,local:usize)->Result<&[f32]>{if local>=self.rows(){return Err(Error::InvalidPosition);}Ok(&self.gate[local*6144..(local+1)*6144])} - pub(super) fn with_completed_before_causal(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,chunk:&QwenChunkTxn<'_, '_>, - f:impl FnOnce(&DeviceBuffer<'_>,&DeviceBuffer<'_>,&DeviceBuffer<'_>,&DeviceBuffer<'_>,&DeviceBuffer<'_>)->Result)->Result{ - self.validate(binding,cache,chunk)?;chunk.validate_prompt_qsa_prior(self.layer,&self.prior)?; - for(local,source)in self.sources.iter().enumerate(){chunk.validate_attention_input(chunk.micro_row_index(local)?,self.layer,source)?;} - let result=self.selected.with_completed_kv(|k,v|self.selected.with_completed_buffers(|q,ids,steps|Ok(f(k,v,q,ids,steps)))).map_err(driver)?; - let health=self.validate(binding,cache,chunk);match result{Err(primary)=>Err(primary),Ok(value)=>{health?;Ok(value)}} + pub(super) fn rows(&self) -> usize { + self.sources.len() } - pub(super) fn with_completed_after_causal(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,chunk:&QwenChunkTxn<'_, '_>,proofs:&[PreparedLayerRow], - f:impl FnOnce(&DeviceBuffer<'_>,&DeviceBuffer<'_>,&DeviceBuffer<'_>)->Result)->Result{ - self.validate(binding,cache,chunk)?;if proofs.len()!=self.rows(){return Err(Error::InvalidDimension);} - for(proof,source)in proofs.iter().zip(&self.sources){chunk.validate_prepared_attention_input(proof,source)?;} - let result=self.selected.with_completed_buffers(|q,ids,steps|Ok(f(q,ids,steps))).map_err(driver)?; - let health:Result<()>=(||{self.validate(binding,cache,chunk)?;for(proof,source)in proofs.iter().zip(&self.sources){chunk.validate_prepared_attention_input(proof,source)?;}Ok(())})();match result{Err(primary)=>Err(primary),Ok(value)=>{health?;Ok(value)}} + pub(super) fn source(&self, local: usize) -> Result<&'source ResidualReady> { + self.sources.get(local).copied().ok_or(Error::InvalidPosition) } - pub(super) fn prefix_for_txn<'a>(&'a self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,txn:&super::session::QwenStepTxn<'_, '_>, - layer:LayerId,input:&ResidualReady,prior:&QsaPrior)->Result> { - txn.validate_binding(&binding.identity())?;txn.validate_projection_branch(&self.origin)?; - txn.validate_input(input.identity().token(),input.identity().position())?;txn.validate_qsa_prior(prior,layer)?; - let context=cache.retained_context(binding,txn.cuda_context()?)?; - let entry=cache.qsa(binding,layer.get())?; - if !self.binding.matches(&binding.identity())||self.layer!=layer||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider){return Err(Error::IdentityMismatch);} - let local=txn.position().get().checked_sub(self.prior.next_position()).ok_or(Error::InvalidPosition)?; - let local=usize::try_from(local).map_err(|_|Error::InvalidPosition)?; - if local>=self.sources.len()||!std::ptr::eq(self.sources[local],input){return Err(Error::IdentityMismatch);} - input.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?; - self.selected.final_index().completed_prefix((local+1)as u32).map_err(driver) + pub(super) fn gate(&self, local: usize) -> Result<&[f32]> { + if local >= self.rows() { + return Err(Error::InvalidPosition); + } + Ok(&self.gate[local * 6144..(local + 1) * 6144]) + } + pub(super) fn with_completed_before_causal( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + f: impl FnOnce( + &DeviceBuffer<'_>, + &DeviceBuffer<'_>, + &DeviceBuffer<'_>, + &DeviceBuffer<'_>, + &DeviceBuffer<'_>, + ) -> Result, + ) -> Result { + self.validate(binding, cache, chunk)?; + chunk.validate_prompt_qsa_prior(self.layer, &self.prior)?; + for (local, source) in self.sources.iter().enumerate() { + chunk.validate_attention_input(chunk.micro_row_index(local)?, self.layer, source)?; + } + let result = self + .selected + .with_completed_kv(|k, v| self.selected.with_completed_buffers(|q, ids, steps| Ok(f(k, v, q, ids, steps)))) + .map_err(driver)?; + let health = self.validate(binding, cache, chunk); + match result { + Err(primary) => Err(primary), + Ok(value) => { + health?; + Ok(value) + } + } + } + pub(super) fn with_completed_after_causal( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + proofs: &[PreparedLayerRow], + f: impl FnOnce(&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>) -> Result, + ) -> Result { + self.validate(binding, cache, chunk)?; + if proofs.len() != self.rows() { + return Err(Error::InvalidDimension); + } + for (proof, source) in proofs.iter().zip(&self.sources) { + chunk.validate_prepared_attention_input(proof, source)?; + } + let result = self.selected.with_completed_buffers(|q, ids, steps| Ok(f(q, ids, steps))).map_err(driver)?; + let health: Result<()> = (|| { + self.validate(binding, cache, chunk)?; + for (proof, source) in proofs.iter().zip(&self.sources) { + chunk.validate_prepared_attention_input(proof, source)?; + } + Ok(()) + })(); + match result { + Err(primary) => Err(primary), + Ok(value) => { + health?; + Ok(value) + } + } + } + pub(super) fn prefix_for_txn<'a>( + &'a self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + txn: &super::session::QwenStepTxn<'_, '_>, + layer: LayerId, + input: &ResidualReady, + prior: &QsaPrior, + ) -> Result> { + txn.validate_binding(&binding.identity())?; + txn.validate_projection_branch(&self.origin)?; + txn.validate_input(input.identity().token(), input.identity().position())?; + txn.validate_qsa_prior(prior, layer)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + let entry = cache.qsa(binding, layer.get())?; + if !self.binding.matches(&binding.identity()) + || self.layer != layer + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + { + return Err(Error::IdentityMismatch); + } + let local = txn.position().get().checked_sub(self.prior.next_position()).ok_or(Error::InvalidPosition)?; + let local = usize::try_from(local).map_err(|_| Error::InvalidPosition)?; + if local >= self.sources.len() || !std::ptr::eq(self.sources[local], input) { + return Err(Error::IdentityMismatch); + } + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + self.selected.final_index().completed_prefix((local + 1) as u32).map_err(driver) + } + pub(super) fn close(self) -> Result<()> { + self.selected.close().map_err(driver) } - pub(super) fn close(self)->Result<()>{self.selected.close().map_err(driver)} // End-only actual complete state; Root must authenticate its native prefix proof, not fabricate earlier rows. - pub(super) fn final_index(&self,binding:&ModelBinding,cache:&DenseWeightCache<'_>,chunk:&QwenChunkTxn<'_, '_>)->Result<&QsaPromptIndexState>{self.validate(binding,cache,chunk)?;Ok(self.selected.final_index())} + pub(super) fn final_index( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'_>, + chunk: &QwenChunkTxn<'_, '_>, + ) -> Result<&QsaPromptIndexState> { + self.validate(binding, cache, chunk)?; + Ok(self.selected.final_index()) + } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs index 6be78ba5..feeb70ca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device.rs @@ -2,248 +2,91 @@ //! provenance, not a host image or an intermediate canonical index snapshot. //! Root session adapter validates the actual Attention(layer) physical read and //! stores all twelve actual seals before joint target/draft publication. +use super::super::super::{input::InputReady, session::QwenSession}; use super::*; -use super::super::super::{input::InputReady,session::QwenSession}; -use leleka_cuda_driver::{OriginalQsaResidentIndex,OriginalQsaIndexCheckpoint,OriginalQsaIndexBatch}; -use leleka_cuda_driver::{OriginalQsaResidentPromptDevice,OriginalQsaResidentSelection,OriginalQsaResidentAttention}; -use leleka_cuda_driver::{OriginalQsaMappedJournal,OriginalQsaMappedPrefix,OriginalQsaMappedAppend,OriginalQsaResidentTransport}; -struct Prior<'ctx>{ - binding:BindingIdentity,owner:QsaOwner,origin:TargetStepOrigin,layer:LayerId,provider:Rc, - index:OriginalQsaIndexCheckpoint<'ctx>, - kv:OriginalQsaMappedPrefix, +use leleka_cuda_driver::{OriginalQsaIndexBatch, OriginalQsaIndexCheckpoint, OriginalQsaResidentIndex}; +use leleka_cuda_driver::{ + OriginalQsaMappedAppend, OriginalQsaMappedJournal, OriginalQsaMappedPrefix, OriginalQsaResidentTransport, +}; +use leleka_cuda_driver::{OriginalQsaResidentAttention, OriginalQsaResidentPromptDevice, OriginalQsaResidentSelection}; +struct Prior<'ctx> { + binding: BindingIdentity, + owner: QsaOwner, + origin: TargetStepOrigin, + layer: LayerId, + provider: Rc, + index: OriginalQsaIndexCheckpoint<'ctx>, + kv: OriginalQsaMappedPrefix, } #[derive(Clone)] pub(in crate::qwen_forward) struct ResidentQsaPrior<'ctx>(Rc>); -impl ResidentQsaPrior<'_>{ - pub(in crate::qwen_forward) fn next_position(&self)->u64{self.0.index.next_position() as u64} - pub(in crate::qwen_forward) fn layer(&self)->LayerId{self.0.layer} - pub(in crate::qwen_forward) fn same_prior(&self,other:&Self)->bool{Rc::ptr_eq(&self.0,&other.0)} - pub(in crate::qwen_forward) fn validate_for_session(&self,binding:&ModelBinding,session:&QwenSession<'_>,layer:LayerId,end:u64)->Result<()>{ - self.validate_for_identity(&binding.identity(),session,layer,end) - } - /// Same check from the model identity alone (the session carries it), for callers without a `ModelBinding`. - pub(in crate::qwen_forward) fn validate_for_identity(&self,identity:&BindingIdentity,session:&QwenSession<'_>,layer:LayerId,end:u64)->Result<()>{ - self.0.origin.validate_projection_branch(session)?;session.validate_resident_qsa_owner(&self.0.owner)?; - let context=session.mtp_context()?; - if !self.0.binding.matches(identity)||!self.0.provider.matches(identity,layer.get())||layer!=self.layer()||end!=self.next_position()||self.0.index.next_position()!=self.0.kv.next_position(){return Err(Error::IdentityMismatch)} - self.0.index.validate_retained(context).map_err(device_error)?;self.0.kv.validate_retained().map_err(device_error)?; - if context.is_poisoned(){return Err(Error::CudaExecution)}Ok(()) - } - -} -impl<'ctx> ResidentQsaPrior<'ctx>{ - /// The same layer's lineage after the native verifier committed more rows. The verifier owns the physical - /// index image and mapped K/V for the whole decode phase; after each commit event the runtime records where - /// both now end (an index checkpoint and a mapped prefix of the verifier's own journal) as the session's - /// resident witness. Binding, owner and weight provider are inherited, never re-derived. - /// The EMPTY lineage (index image and mapped K/V both at position 0) re-stamped onto another branch - /// generation of the same session. The empty state is content-independent by construction (no cell is - /// reachable), so a position-0 prior taken at load remains the exact reset target after any number of - /// restores; any later position is refused. - pub(in crate::qwen_forward) fn rebased_empty(&self,origin:TargetStepOrigin)->Result{ - if self.0.index.next_position()!=0||self.0.kv.next_position()!=0||origin.next_position()!=0||self.0.origin.next_position()!=0 - ||!self.0.origin.same_session(&origin){return Err(Error::IdentityMismatch)} - Ok(Self(Rc::new(Prior{binding:self.0.binding.clone(),owner:self.0.owner.clone(),origin,layer:self.0.layer,provider:self.0.provider.clone(),index:self.0.index.clone(),kv:self.0.kv.clone()}))) - } - /// The same lineage (index checkpoint and mapped prefix unchanged) stamped with the session's CURRENT branch - /// generation, for a conversation checkpoint resumed after a restore bumped the generation. Only the logical - /// fence moves: whether the physical index image and mapped K/V still hold this prefix is decided by their own - /// epoch/coverage when the layer is restored to it (`ResidentQsaLayer::restore`), and the conversation policy - /// keeps only checkpoints whose tokens are a prefix of what the session holds. - pub(in crate::qwen_forward) fn restamped(&self,origin:TargetStepOrigin)->Result{ - if origin.next_position()!=self.next_position()||!self.0.origin.same_session(&origin){return Err(Error::IdentityMismatch)} - Ok(Self(Rc::new(Prior{binding:self.0.binding.clone(),owner:self.0.owner.clone(),origin,layer:self.0.layer,provider:self.0.provider.clone(),index:self.0.index.clone(),kv:self.0.kv.clone()}))) - } - pub(in crate::qwen_forward) fn advanced(&self,origin:TargetStepOrigin,index:OriginalQsaIndexCheckpoint<'ctx>,kv:OriginalQsaMappedPrefix)->Result{ - if index.next_position()!=kv.next_position()||(index.next_position() as u64),pub(in crate::qwen_forward) index:Vec} -impl ParkedLayerSpan{pub(in crate::qwen_forward) fn bytes(&self)->usize{self.kv.len()+self.index.len()}} -pub(in crate::qwen_forward) struct ResidentQsaLayer<'ctx>{context:&'ctx Context<'ctx>,index:OriginalQsaResidentIndex<'ctx>,kv:OriginalQsaMappedJournal<'ctx>,current:ResidentQsaPrior<'ctx>} -impl<'ctx> ResidentQsaLayer<'ctx>{ - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,empty:&QsaPrior,index:OriginalQsaResidentIndex<'ctx>,kv:OriginalQsaMappedJournal<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>)->Result{ - empty.validate_extent()?;let origin=session.target_origin()?; - let context=cache.retained_context(binding,session.mtp_context()?)?;cache.validate(binding)?; - if !empty.0.binding.matches(&binding.identity())||empty.next_position()!=0||index.next_position()!=0||kv.next_position()!=0{return Err(Error::IdentityMismatch)} - index.validate_context(context).map_err(device_error)?;kv.validate_context(context).map_err(device_error)?;let entry=cache.qsa(binding,empty.layer().get())?; - let mut index=index;let saved=index.checkpoint(ws).map_err(device_error)?;let prefix=kv.empty_prefix().map_err(device_error)?; - let current=ResidentQsaPrior(Rc::new(Prior{binding:binding.identity(),owner:empty.0.owner.clone(),origin,layer:empty.layer(),provider:entry.weights.clone(),index:saved,kv:prefix})); - Ok(Self{context,index,kv,current}) - } - pub(in crate::qwen_forward) fn current(&self)->ResidentQsaPrior<'ctx>{self.current.clone()} - fn validate(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,prior:&ResidentQsaPrior<'ctx>)->Result<()>{ - cache.validate(binding)?;let context=cache.retained_context(binding,session.mtp_context()?)?;let entry=cache.qsa(binding,prior.layer().get())?; - prior.0.origin.validate_projection_branch(session)?; - if !self.current.same_prior(prior)||!prior.0.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&prior.0.provider)||!prior.0.owner.matches(&self.current.0.owner)||prior.0.index.next_position()!=prior.0.kv.next_position(){return Err(Error::IdentityMismatch)} - self.index.validate_context(context).map_err(device_error)?;self.index.validate_checkpoint(&prior.0.index).map_err(device_error)?;self.kv.validate_prefix(&prior.0.kv).map_err(device_error)?;Ok(()) - } - #[allow(clippy::too_many_arguments)] - /// Start the layer's KV prefix copy on a side stream before `prepare` runs (LELEKA_PREFILL_QSA_PREFETCH; a no-op with the switch off). - pub(in crate::qwen_forward) fn begin_prefix(&mut self,ws:&mut NativeBatchWorkspace<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,prior:&ResidentQsaPrior<'ctx>,read:&OriginalDeviceGrRead<'_,'_,'ctx>)->Result<()>{ - self.kv.begin_stage_prefix(ws,stage,&prior.0.kv,read).map_err(device_error) - } - pub(in crate::qwen_forward) fn prepare<'lease,'index,'weights,'arena,'loan>(&'index mut self,binding:&ModelBinding,cache:&'weights DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,inputs:&[&InputReady],prior:&ResidentQsaPrior<'ctx>,producer:&'lease mut OriginalQsaResidentPromptDevice<'ctx>,read:OriginalDeviceGrRead<'arena,'loan,'ctx>,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{ - self.validate(binding,cache,session,prior)?;let origin=session.target_origin()?;let layer=prior.layer(); - if inputs.is_empty()||inputs.len()>8192||read.rows()!=inputs.len()||!read.context_matches(self.context){return Err(Error::IdentityMismatch)} - let mut identities=Vec::new();identities.try_reserve_exact(inputs.len()).map_err(|_|Error::InputAllocation)?; - for(local,input)in inputs.iter().enumerate(){if !input.binding_identity().matches(&binding.identity())||input.position().get()!=prior.next_position().checked_add(local as u64).ok_or(Error::Overflow)?{return Err(Error::IdentityMismatch)}identities.push(TokenLayer::new(input.token(),input.position(),layer));} - let entry=cache.qsa(binding,layer.get())?; - for(role,n,k)in[(QsaMatrixRole::K,512,2560),(QsaMatrixRole::V,512,2560),(QsaMatrixRole::Q,12288,2560),(QsaMatrixRole::IndexK,128,2560),(QsaMatrixRole::IndexQ,512,2560),(QsaMatrixRole::Out,2560,6144)]{if entry.weights.shape(role)!=(k,n){return Err(Error::InvalidDimension)}} - let(k,kk)=cache.qsa_matrix(entry,ROLES[0])?;let(v,vk)=cache.qsa_matrix(entry,ROLES[1])?;let(q,qk)=cache.qsa_matrix(entry,ROLES[2])?; - let(ik,ikk)=cache.qsa_matrix(entry,ROLES[3])?;let(iq,iqk)=cache.qsa_matrix(entry,ROLES[4])?;let(out,ok)=cache.qsa_matrix(entry,ROLES[5])?; - if ikk!=QsaMatrixKind::Bf16||iqk!=QsaMatrixKind::Bf16{return Err(Error::Unsupported(Stage::QsaIndex))} - let selected=producer.prepare(read,ws,&mut self.index,&prior.0.index,OriginalQsaPromptWeights{projections:[k,v,q,ik,iq,out],kinds:[native(kk)?,native(vk)?,native(qk)?,native(ok)?],norms:cache.qsa_norms(entry)?}).map_err(device_error)?; - origin.validate(session)?;cache.validate(binding)?; - Ok(ResidentQsaSelection{binding:binding.identity(),origin,context:self.context,layer,prior:prior.clone(),provider:entry.weights.clone(),identities,selected,kv:&mut self.kv}) - } - /// Publish only an actual drained replay seal. Root must complete all twelve - /// seals and all genuine joint guards before this actual canonical assignment. - pub(in crate::qwen_forward) fn prepare_publication<'layer>(&'layer mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,seal:ResidentQsaSeal<'ctx>)->Result>{ - cache.validate(binding)?;seal.next.validate_for_session(binding,session,seal.next.layer(),seal.end())?; - let context=cache.retained_context(binding,session.mtp_context()?)?;let entry=cache.qsa(binding,seal.next.layer().get())?; - if !self.current.same_prior(&seal.previous)||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&seal.next.0.provider)||!seal.next.0.owner.matches(&self.current.0.owner){return Err(Error::IdentityMismatch)} - self.index.validate_checkpoint(&seal.next.0.index).map_err(device_error)?;self.kv.validate_prefix(&seal.next.0.kv).map_err(device_error)?; - if self.index.next_position()!=seal.next.0.index.next_position()||self.kv.next_position()!=seal.next.0.kv.next_position(){return Err(Error::IdentityMismatch)} - Ok(ResidentQsaPublication{layer:self,seal}) - } - pub(in crate::qwen_forward) fn publish(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,seal:ResidentQsaSeal<'ctx>)->Result>{Ok(self.prepare_publication(binding,cache,session,seal)?.publish_validated())} - - /// Real session-checkpoint rollback, including branch invalidation. No prior - /// capability can address overwritten future bytes after this completion. - pub(in crate::qwen_forward) fn restore(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,prior:&ResidentQsaPrior<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{ - cache.validate(binding)?;let origin=session.target_origin()?;let context=cache.retained_context(binding,session.mtp_context()?)?; - if !prior.0.origin.same_session(&origin)||!prior.0.binding.matches(&binding.identity())||!prior.0.owner.matches(&self.current.0.owner)||prior.layer()!=self.current.layer()||!std::ptr::eq(context,self.context){return Err(Error::IdentityMismatch)} - // Attempt both real restorations; preserve the first failure. - let index=self.index.restore(ws,&prior.0.index).map_err(device_error);let kv=self.kv.rollback(ws,&prior.0.kv).map_err(device_error);index?;kv?; - self.current=ResidentQsaPrior(Rc::new(Prior{binding:prior.0.binding.clone(),owner:prior.0.owner.clone(),origin,layer:prior.layer(),provider:prior.0.provider.clone(),index:prior.0.index.clone(),kv:prior.0.kv.clone()}));Ok(self.current.clone()) - } - /// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index - /// rows). `first` and `tokens` are multiples of four and lie below the layer's end. - pub(in crate::qwen_forward) fn export_span(&self,first:usize,tokens:usize)->Result{ - // `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover its cells, and only the - // complete 4-cell rows of the index image are copied (the checkpoint's tail carries the partial one) - if first%4!=0||tokens==0||first+tokens>self.current.next_position() as usize{return Err(Error::InvalidPosition)} - let(mut kv,mut index)=(Vec::new(),Vec::new()); - {let _p=crate::qwen_forward::original_serve_profile::span("prefix.export_kv");self.kv.export_pages(first/4,(first+tokens).div_ceil(4)-first/4,&mut kv).map_err(device_error)?;} - let rows=(first+tokens)/4-first/4; - if rows>0 {let _p=crate::qwen_forward::original_serve_profile::span("prefix.export_index");self.index.export_rows(first/4,rows,&mut index).map_err(device_error)?;} - Ok(ParkedLayerSpan{first_token:first,tokens,kv,index}) - } - /// The tail of the layer's index checkpoint at its current end (what `import` needs besides the spans). - pub(in crate::qwen_forward) fn export_tail(&self)->Result>{ - self.index.export_tail(&self.current.0.index).map_err(device_error) - } - /// Install a parked prefix ending at `end`: write the spans, then re-mint the layer's index checkpoint and mapped - /// prefix from this layer's own lineage. Both physical halves are attempted; the first failure is returned. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn import(&mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>, - tail:&[u8],spans:&[&ParkedLayerSpan],end:usize,ws:&mut NativeBatchWorkspace<'ctx>)->Result>{ - cache.validate(binding)?;let origin=session.target_origin()?;let context=cache.retained_context(binding,session.mtp_context()?)?; - if !std::ptr::eq(context,self.context)||!self.current.0.binding.matches(&binding.identity()){return Err(Error::IdentityMismatch)} - let index_spans:Vec<(usize,&[u8])>=spans.iter().filter(|s|!s.index.is_empty()).map(|s|(s.first_token/4,&s.index[..])).collect(); - let kv_spans:Vec<(usize,&[u8])>=spans.iter().map(|s|(s.first_token/4,&s.kv[..])).collect(); - let index={let _p=crate::qwen_forward::original_serve_profile::span("prefix.layer_index");self.index.import(ws,&index_spans,tail,end).map_err(device_error)}; - let kv={let _p=crate::qwen_forward::original_serve_profile::span("prefix.layer_kv");self.kv.import_pages(ws,&kv_spans,end).map_err(device_error)}; - let(index,kv)=(index?,kv?); - self.current=ResidentQsaPrior(Rc::new(Prior{binding:self.current.0.binding.clone(),owner:self.current.0.owner.clone(),origin,layer:self.current.layer(),provider:self.current.0.provider.clone(),index,kv})); - Ok(self.current.clone()) - } - /// One-way handoff into the native verifier. It moves the same resident - /// index and mapped K/V owners used by the prompt executor; it never clones - /// a checkpoint or recreates state from a final image. The returned prior - /// remains the session lineage witness for the exact transferred prefix. - pub(in crate::qwen_forward) fn check_handoff(&self)->Result<()>{ - self.index.validate_context(self.context).map_err(device_error)?; - self.index.validate_checkpoint(&self.current.0.index).map_err(device_error)?; - self.kv.validate_prefix(&self.current.0.kv).map_err(device_error)?; - if self.index.next_position()!=self.current.0.index.next_position()||self.kv.next_position()!=self.current.0.kv.next_position()||self.index.next_position()!=self.kv.next_position(){return Err(Error::IdentityMismatch)} - Ok(()) - } - pub(in crate::qwen_forward) fn into_verifier_owners(self)->Result<(OriginalQsaResidentIndex<'ctx>,OriginalQsaMappedJournal<'ctx>,ResidentQsaPrior<'ctx>)>{ - self.check_handoff()?; - Ok((self.index,self.kv,self.current)) - } - /// The reverse of `into_verifier_owners`, after the verifier graphs have all been closed and the journal's - /// owners recovered: the prompt executor takes the SAME physical index and mapped K/V back at the session's - /// current lineage `current`. The physical owners are always rolled back to `current` (a no-op copy when the - /// last window committed; the repair when a window was abandoned mid-flight), so a layer never re-enters - /// the prompt path at a position the session does not hold. - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn from_verifier_owners(binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,index:OriginalQsaResidentIndex<'ctx>,kv:OriginalQsaMappedJournal<'ctx>,current:ResidentQsaPrior<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>)->Result{ - cache.validate(binding)?;let origin=session.target_origin()?;let context=cache.retained_context(binding,session.mtp_context()?)?; - current.validate_for_session(binding,session,current.layer(),origin.next_position())?; - index.validate_context(context).map_err(device_error)?;kv.validate_context(context).map_err(device_error)?; - let mut layer=Self{context,index,kv,current:current.clone()}; - layer.restore(binding,cache,session,¤t,ws)?; - Ok(layer) - } - pub(in crate::qwen_forward) fn close(self)->Result<()>{let index=self.index.close().map_err(device_error);let kv=self.kv.close().map_err(device_error);index?;kv} +pub(in crate::qwen_forward) struct ParkedLayerSpan { + pub(in crate::qwen_forward) first_token: usize, + pub(in crate::qwen_forward) tokens: usize, + pub(in crate::qwen_forward) kv: Vec, + pub(in crate::qwen_forward) index: Vec, +} +pub(in crate::qwen_forward) struct ResidentQsaLayer<'ctx> { + context: &'ctx Context<'ctx>, + index: OriginalQsaResidentIndex<'ctx>, + kv: OriginalQsaMappedJournal<'ctx>, + current: ResidentQsaPrior<'ctx>, +} +pub(in crate::qwen_forward) struct ResidentQsaSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: ResidentQsaPrior<'ctx>, + provider: Rc, + identities: Vec, + selected: OriginalQsaResidentSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx>, + kv: &'index mut OriginalQsaMappedJournal<'ctx>, +} +pub(in crate::qwen_forward) struct ResidentQsaCompleted<'index, 'weights, 'ctx> { + binding: BindingIdentity, + origin: TargetStepOrigin, + context: &'ctx Context<'ctx>, + layer: LayerId, + prior: ResidentQsaPrior<'ctx>, + provider: Rc, + identities: Vec, + index: OriginalQsaIndexBatch<'index, 'weights, 'ctx>, + kv: &'index mut OriginalQsaMappedJournal<'ctx>, + appended: OriginalQsaMappedAppend, } -pub(in crate::qwen_forward) struct ResidentQsaSelection<'lease,'index,'weights,'arena,'loan,'ctx>{binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId,prior:ResidentQsaPrior<'ctx>,provider:Rc,identities:Vec,selected:OriginalQsaResidentSelection<'lease,'index,'weights,'arena,'loan,'ctx>,kv:&'index mut OriginalQsaMappedJournal<'ctx>} -pub(in crate::qwen_forward) struct ResidentQsaCompleted<'index,'weights,'ctx>{binding:BindingIdentity,origin:TargetStepOrigin,context:&'ctx Context<'ctx>,layer:LayerId,prior:ResidentQsaPrior<'ctx>,provider:Rc,identities:Vec,index:OriginalQsaIndexBatch<'index,'weights,'ctx>,kv:&'index mut OriginalQsaMappedJournal<'ctx>,appended:OriginalQsaMappedAppend} /// Affine permit retains the actual mutable layer and validated consuming seal. /// Gathering all twelve permits precedes every infallible assignment. -pub(in crate::qwen_forward) struct ResidentQsaPublication<'layer,'ctx>{layer:&'layer mut ResidentQsaLayer<'ctx>,seal:ResidentQsaSeal<'ctx>} -impl<'ctx> ResidentQsaPublication<'_,'ctx>{pub(in crate::qwen_forward) fn publish_validated(self)->ResidentQsaPrior<'ctx>{self.layer.current=self.seal.next;self.layer.current.clone()}} -pub(in crate::qwen_forward) struct ResidentQsaSeal<'ctx>{context:&'ctx Context<'ctx>,previous:ResidentQsaPrior<'ctx>,next:ResidentQsaPrior<'ctx>,accepted:usize} -impl<'ctx> ResidentQsaSeal<'ctx>{ - pub(in crate::qwen_forward) fn next_prior(&self)->ResidentQsaPrior<'ctx>{self.next.clone()} - pub(in crate::qwen_forward) fn previous_matches(&self,prior:&ResidentQsaPrior<'ctx>)->bool{self.previous.same_prior(prior)} - - pub(in crate::qwen_forward) fn validate_for(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,layer:LayerId,first:u64,accepted:usize)->Result<()>{ - self.next.0.origin.validate_projection_branch(session)?;cache.validate(binding)?;let context=cache.retained_context(binding,session.mtp_context()?)?;let entry=cache.qsa(binding,layer.get())?; - if !self.next.0.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.next.0.provider)||layer!=self.next.layer()||first!=self.previous.next_position()||accepted!=self.accepted||first.checked_add(accepted as u64)!=Some(self.end())||self.next.0.index.next_position()!=self.next.0.kv.next_position(){return Err(Error::IdentityMismatch)}Ok(()) - } -pub(in crate::qwen_forward) fn end(&self)->u64{self.next.next_position()}pub(in crate::qwen_forward) fn accepted(&self)->usize{self.accepted}pub(in crate::qwen_forward) fn layer(&self)->LayerId{self.next.layer()}} -impl<'lease,'index,'weights,'arena,'loan,'ctx> ResidentQsaSelection<'lease,'index,'weights,'arena,'loan,'ctx>{ - pub(in crate::qwen_forward) fn abort(self,ws:&mut NativeBatchWorkspace<'ctx>)->Result<()>{self.selected.abort(ws,self.kv,&self.prior.0.kv).map_err(device_error)} - pub(in crate::qwen_forward) fn complete(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,attention:&mut OriginalQsaResidentAttention<'ctx>)->Result<(OriginalDeviceBlock<'arena,'loan,'ctx>,ResidentQsaCompleted<'index,'weights,'ctx>)>{ - self.origin.validate(session)?;cache.validate(binding)?;let context=cache.retained_context(binding,session.mtp_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider){return Err(Error::IdentityMismatch)} - let(out,kind)=cache.qsa_matrix(entry,QsaMatrixRole::Out)?; - let(block,index,appended)=self.selected.complete(ws,self.kv,stage,&self.prior.0.kv,attention,out,native(kind)?).map_err(device_error)?; - self.origin.validate(session)?;cache.validate(binding)?;cache.retained_context(binding,context)?; - Ok((block,ResidentQsaCompleted{binding:self.binding,origin:self.origin,context:self.context,layer:self.layer,prior:self.prior,provider:self.provider,identities:self.identities,index,kv:self.kv,appended})) - } +pub(in crate::qwen_forward) struct ResidentQsaPublication<'layer, 'ctx> { + layer: &'layer mut ResidentQsaLayer<'ctx>, + seal: ResidentQsaSeal<'ctx>, +} +pub(in crate::qwen_forward) struct ResidentQsaSeal<'ctx> { + context: &'ctx Context<'ctx>, + previous: ResidentQsaPrior<'ctx>, + next: ResidentQsaPrior<'ctx>, + accepted: usize, } /// A provisional bounded row borrows the actual completed whole-layer owner; /// no caller position or final index image can create an earlier state. -pub(in crate::qwen_forward) struct ResidentQsaRow<'row,'ctx>{_prior:&'row ResidentQsaPrior<'ctx>,identity:TokenLayer,kv:OriginalQsaMappedPrefix} -impl ResidentQsaRow<'_, '_>{pub(in crate::qwen_forward) fn identity(&self)->TokenLayer{self.identity}pub(in crate::qwen_forward) fn end(&self)->usize{self.kv.next_position()}} -impl<'index,'weights,'ctx> ResidentQsaCompleted<'index,'weights,'ctx>{ - pub(in crate::qwen_forward) fn first(&self)->u64{self.prior.next_position()}pub(in crate::qwen_forward) fn rows(&self)->usize{self.identities.len()}pub(in crate::qwen_forward) fn layer(&self)->LayerId{self.layer} - pub(in crate::qwen_forward) fn validate_rows(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,inputs:&[&InputReady])->Result<()>{ - self.origin.validate_projection_branch(session)?;cache.validate(binding)?;let context=cache.retained_context(binding,session.mtp_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider)||inputs.len()!=self.identities.len()||self.index.rows()!=inputs.len()||self.index.first_position()as u64!=self.first()||self.appended.rows()!=inputs.len(){return Err(Error::IdentityMismatch)} - for(input,id)in inputs.iter().zip(&self.identities){if !input.binding_identity().matches(&binding.identity()){return Err(Error::IdentityMismatch)}id.validate(input.token(),input.position(),self.layer)?;} - self.kv.validate_prefix(self.appended.final_prefix()).map_err(device_error) - } - pub(in crate::qwen_forward) fn row_for_txn(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,txn:&QwenStepTxn<'_, '_>)->Result>{ - txn.validate_binding(&binding.identity())?;txn.validate_projection_branch(&self.origin)?;let context=cache.retained_context(binding,txn.cuda_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&self.provider){return Err(Error::IdentityMismatch)} - let local=usize::try_from(txn.position().get().checked_sub(self.first()).ok_or(Error::InvalidPosition)?).map_err(|_|Error::InvalidPosition)?;let id=*self.identities.get(local).ok_or(Error::InvalidPosition)?;id.validate(txn.token(),txn.position(),self.layer)?;txn.validate_input(id.token(),id.position())?; - let kv=self.appended.prefix_after(local).map_err(device_error)?;self.kv.validate_prefix(&kv).map_err(device_error)?;Ok(ResidentQsaRow{_prior:&self.prior,identity:id,kv}) - } - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn seal_prefix(mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,session:&QwenSession<'ctx>,inputs:&[&InputReady],producer:&mut OriginalQsaResidentPromptDevice<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>,accepted:usize)->Result>{ - self.validate_rows(binding,cache,session,inputs)?;if accepted>self.rows(){return Err(Error::InvalidPosition)} - let index=producer.commit_prefix(ws,&mut self.index,accepted).map_err(device_error); - let kv=self.kv.accept_prefix(ws,&self.appended,accepted).map_err(device_error);let index=index?;let kv=kv?; - cache.validate(binding)?;cache.retained_context(binding,self.context)?;self.origin.validate_projection_branch(session)?; - let next=ResidentQsaPrior(Rc::new(Prior{binding:self.binding,owner:self.prior.0.owner.clone(),origin:self.origin,layer:self.layer,provider:self.provider,index,kv})); - Ok(ResidentQsaSeal{context:self.context,previous:self.prior,next,accepted}) - } - pub(in crate::qwen_forward) fn abort(mut self,producer:&mut OriginalQsaResidentPromptDevice<'ctx>,ws:&mut NativeBatchWorkspace<'ctx>)->Result<()>{ - let index=producer.commit_prefix(ws,&mut self.index,0).map_err(device_error);let kv=self.kv.rollback(ws,&self.prior.0.kv).map_err(device_error);index?;kv - } +pub(in crate::qwen_forward) struct ResidentQsaRow<'row, 'ctx> { + _prior: &'row ResidentQsaPrior<'ctx>, + identity: TokenLayer, + kv: OriginalQsaMappedPrefix, } -#[path="qsa_resident_scalar.rs"] +#[path = "qsa_resident_scalar.rs"] mod scalar; -pub(in crate::qwen_forward) use scalar::{ResidentQsaScalar,ResidentQsaScalarReady}; +pub(in crate::qwen_forward) use scalar::{ResidentQsaScalar, ResidentQsaScalarReady}; + +#[path = "qsa_resident_device/impl_residentqsacompleted.rs"] +mod impl_residentqsacompleted; +#[path = "qsa_resident_device/impl_residentqsalayer.rs"] +mod impl_residentqsalayer; +#[path = "qsa_resident_device/impl_residentqsalayer_2.rs"] +mod impl_residentqsalayer_2; +#[path = "qsa_resident_device/impl_residentqsaprior.rs"] +mod impl_residentqsaprior; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs new file mode 100644 index 00000000..fff6083a --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsacompleted.rs @@ -0,0 +1,113 @@ +//! Moved out of the parent module by STRA-338: impl ResidentQsaCompleted. + +#[allow(unused_imports)] +use super::*; + +impl<'index, 'weights, 'ctx> ResidentQsaCompleted<'index, 'weights, 'ctx> { + pub(in crate::qwen_forward) fn first(&self) -> u64 { + self.prior.next_position() + } + pub(in crate::qwen_forward) fn rows(&self) -> usize { + self.identities.len() + } + pub(in crate::qwen_forward) fn layer(&self) -> LayerId { + self.layer + } + pub(in crate::qwen_forward) fn validate_rows( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + inputs: &[&InputReady], + ) -> Result<()> { + self.origin.validate_projection_branch(session)?; + cache.validate(binding)?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + || inputs.len() != self.identities.len() + || self.index.rows() != inputs.len() + || self.index.first_position() as u64 != self.first() + || self.appended.rows() != inputs.len() + { + return Err(Error::IdentityMismatch); + } + for (input, id) in inputs.iter().zip(&self.identities) { + if !input.binding_identity().matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + id.validate(input.token(), input.position(), self.layer)?; + } + self.kv.validate_prefix(self.appended.final_prefix()).map_err(device_error) + } + pub(in crate::qwen_forward) fn row_for_txn( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + ) -> Result> { + txn.validate_binding(&binding.identity())?; + txn.validate_projection_branch(&self.origin)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + { + return Err(Error::IdentityMismatch); + } + let local = usize::try_from(txn.position().get().checked_sub(self.first()).ok_or(Error::InvalidPosition)?) + .map_err(|_| Error::InvalidPosition)?; + let id = *self.identities.get(local).ok_or(Error::InvalidPosition)?; + id.validate(txn.token(), txn.position(), self.layer)?; + txn.validate_input(id.token(), id.position())?; + let kv = self.appended.prefix_after(local).map_err(device_error)?; + self.kv.validate_prefix(&kv).map_err(device_error)?; + Ok(ResidentQsaRow { _prior: &self.prior, identity: id, kv }) + } + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn seal_prefix( + mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + inputs: &[&InputReady], + producer: &mut OriginalQsaResidentPromptDevice<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + accepted: usize, + ) -> Result> { + self.validate_rows(binding, cache, session, inputs)?; + if accepted > self.rows() { + return Err(Error::InvalidPosition); + } + let index = producer.commit_prefix(ws, &mut self.index, accepted).map_err(device_error); + let kv = self.kv.accept_prefix(ws, &self.appended, accepted).map_err(device_error); + let index = index?; + let kv = kv?; + cache.validate(binding)?; + cache.retained_context(binding, self.context)?; + self.origin.validate_projection_branch(session)?; + let next = ResidentQsaPrior(Rc::new(Prior { + binding: self.binding, + owner: self.prior.0.owner.clone(), + origin: self.origin, + layer: self.layer, + provider: self.provider, + index, + kv, + })); + Ok(ResidentQsaSeal { context: self.context, previous: self.prior, next, accepted }) + } + pub(in crate::qwen_forward) fn abort( + mut self, + producer: &mut OriginalQsaResidentPromptDevice<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + let index = producer.commit_prefix(ws, &mut self.index, 0).map_err(device_error); + let kv = self.kv.rollback(ws, &self.prior.0.kv).map_err(device_error); + index?; + kv + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs new file mode 100644 index 00000000..95c58197 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer.rs @@ -0,0 +1,240 @@ +//! Moved out of the parent module by STRA-338: impl ResidentQsaLayer. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> ResidentQsaLayer<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + empty: &QsaPrior, + index: OriginalQsaResidentIndex<'ctx>, + kv: OriginalQsaMappedJournal<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result { + empty.validate_extent()?; + let origin = session.target_origin()?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + cache.validate(binding)?; + if !empty.0.binding.matches(&binding.identity()) + || empty.next_position() != 0 + || index.next_position() != 0 + || kv.next_position() != 0 + { + return Err(Error::IdentityMismatch); + } + index.validate_context(context).map_err(device_error)?; + kv.validate_context(context).map_err(device_error)?; + let entry = cache.qsa(binding, empty.layer().get())?; + let mut index = index; + let saved = index.checkpoint(ws).map_err(device_error)?; + let prefix = kv.empty_prefix().map_err(device_error)?; + let current = ResidentQsaPrior(Rc::new(Prior { + binding: binding.identity(), + owner: empty.0.owner.clone(), + origin, + layer: empty.layer(), + provider: entry.weights.clone(), + index: saved, + kv: prefix, + })); + Ok(Self { context, index, kv, current }) + } + pub(in crate::qwen_forward) fn current(&self) -> ResidentQsaPrior<'ctx> { + self.current.clone() + } + pub(super) fn validate( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + prior: &ResidentQsaPrior<'ctx>, + ) -> Result<()> { + cache.validate(binding)?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + let entry = cache.qsa(binding, prior.layer().get())?; + prior.0.origin.validate_projection_branch(session)?; + if !self.current.same_prior(prior) + || !prior.0.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &prior.0.provider) + || !prior.0.owner.matches(&self.current.0.owner) + || prior.0.index.next_position() != prior.0.kv.next_position() + { + return Err(Error::IdentityMismatch); + } + self.index.validate_context(context).map_err(device_error)?; + self.index.validate_checkpoint(&prior.0.index).map_err(device_error)?; + self.kv.validate_prefix(&prior.0.kv).map_err(device_error)?; + Ok(()) + } + #[allow(clippy::too_many_arguments)] + /// Start the layer's KV prefix copy on a side stream before `prepare` runs (LELEKA_PREFILL_QSA_PREFETCH; a no-op with the switch off). + pub(in crate::qwen_forward) fn begin_prefix( + &mut self, + ws: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + prior: &ResidentQsaPrior<'ctx>, + read: &OriginalDeviceGrRead<'_, '_, 'ctx>, + ) -> Result<()> { + self.kv.begin_stage_prefix(ws, stage, &prior.0.kv, read).map_err(device_error) + } + pub(in crate::qwen_forward) fn prepare<'lease, 'index, 'weights, 'arena, 'loan>( + &'index mut self, + binding: &ModelBinding, + cache: &'weights DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + inputs: &[&InputReady], + prior: &ResidentQsaPrior<'ctx>, + producer: &'lease mut OriginalQsaResidentPromptDevice<'ctx>, + read: OriginalDeviceGrRead<'arena, 'loan, 'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + self.validate(binding, cache, session, prior)?; + let origin = session.target_origin()?; + let layer = prior.layer(); + if inputs.is_empty() + || inputs.len() > 8192 + || read.rows() != inputs.len() + || !read.context_matches(self.context) + { + return Err(Error::IdentityMismatch); + } + let mut identities = Vec::new(); + identities.try_reserve_exact(inputs.len()).map_err(|_| Error::InputAllocation)?; + for (local, input) in inputs.iter().enumerate() { + if !input.binding_identity().matches(&binding.identity()) + || input.position().get() != prior.next_position().checked_add(local as u64).ok_or(Error::Overflow)? + { + return Err(Error::IdentityMismatch); + } + identities.push(TokenLayer::new(input.token(), input.position(), layer)); + } + let entry = cache.qsa(binding, layer.get())?; + for (role, n, k) in [ + (QsaMatrixRole::K, 512, 2560), + (QsaMatrixRole::V, 512, 2560), + (QsaMatrixRole::Q, 12288, 2560), + (QsaMatrixRole::IndexK, 128, 2560), + (QsaMatrixRole::IndexQ, 512, 2560), + (QsaMatrixRole::Out, 2560, 6144), + ] { + if entry.weights.shape(role) != (k, n) { + return Err(Error::InvalidDimension); + } + } + let (k, kk) = cache.qsa_matrix(entry, ROLES[0])?; + let (v, vk) = cache.qsa_matrix(entry, ROLES[1])?; + let (q, qk) = cache.qsa_matrix(entry, ROLES[2])?; + let (ik, ikk) = cache.qsa_matrix(entry, ROLES[3])?; + let (iq, iqk) = cache.qsa_matrix(entry, ROLES[4])?; + let (out, ok) = cache.qsa_matrix(entry, ROLES[5])?; + if ikk != QsaMatrixKind::Bf16 || iqk != QsaMatrixKind::Bf16 { + return Err(Error::Unsupported(Stage::QsaIndex)); + } + let selected = producer + .prepare( + read, + ws, + &mut self.index, + &prior.0.index, + OriginalQsaPromptWeights { + projections: [k, v, q, ik, iq, out], + kinds: [native(kk)?, native(vk)?, native(qk)?, native(ok)?], + norms: cache.qsa_norms(entry)?, + }, + ) + .map_err(device_error)?; + origin.validate(session)?; + cache.validate(binding)?; + Ok(ResidentQsaSelection { + binding: binding.identity(), + origin, + context: self.context, + layer, + prior: prior.clone(), + provider: entry.weights.clone(), + identities, + selected, + kv: &mut self.kv, + }) + } + /// Publish only an actual drained replay seal. Root must complete all twelve + /// seals and all genuine joint guards before this actual canonical assignment. + pub(in crate::qwen_forward) fn prepare_publication<'layer>( + &'layer mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + seal: ResidentQsaSeal<'ctx>, + ) -> Result> { + cache.validate(binding)?; + seal.next.validate_for_session(binding, session, seal.next.layer(), seal.end())?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + let entry = cache.qsa(binding, seal.next.layer().get())?; + if !self.current.same_prior(&seal.previous) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &seal.next.0.provider) + || !seal.next.0.owner.matches(&self.current.0.owner) + { + return Err(Error::IdentityMismatch); + } + self.index.validate_checkpoint(&seal.next.0.index).map_err(device_error)?; + self.kv.validate_prefix(&seal.next.0.kv).map_err(device_error)?; + if self.index.next_position() != seal.next.0.index.next_position() + || self.kv.next_position() != seal.next.0.kv.next_position() + { + return Err(Error::IdentityMismatch); + } + Ok(ResidentQsaPublication { layer: self, seal }) + } + pub(in crate::qwen_forward) fn publish( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + seal: ResidentQsaSeal<'ctx>, + ) -> Result> { + Ok(self.prepare_publication(binding, cache, session, seal)?.publish_validated()) + } + + /// Real session-checkpoint rollback, including branch invalidation. No prior + /// capability can address overwritten future bytes after this completion. + pub(in crate::qwen_forward) fn restore( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + prior: &ResidentQsaPrior<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + cache.validate(binding)?; + let origin = session.target_origin()?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + if !prior.0.origin.same_session(&origin) + || !prior.0.binding.matches(&binding.identity()) + || !prior.0.owner.matches(&self.current.0.owner) + || prior.layer() != self.current.layer() + || !std::ptr::eq(context, self.context) + { + return Err(Error::IdentityMismatch); + } + // Attempt both real restorations; preserve the first failure. + let index = self.index.restore(ws, &prior.0.index).map_err(device_error); + let kv = self.kv.rollback(ws, &prior.0.kv).map_err(device_error); + index?; + kv?; + self.current = ResidentQsaPrior(Rc::new(Prior { + binding: prior.0.binding.clone(), + owner: prior.0.owner.clone(), + origin, + layer: prior.layer(), + provider: prior.0.provider.clone(), + index: prior.0.index.clone(), + kv: prior.0.kv.clone(), + })); + Ok(self.current.clone()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs new file mode 100644 index 00000000..d9e2b9aa --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsalayer_2.rs @@ -0,0 +1,234 @@ +//! Moved out of the parent module by STRA-338: impl ResidentQsaLayer (2), impl ResidentQsaPublication, impl ResidentQsaSeal, impl ResidentQsaSelection, impl ResidentQsaRow. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> ResidentQsaLayer<'ctx> { + /// Bytes of the cells `first..first + tokens` of this layer as a prefix-cache span (host K/V pages and pooled index + /// rows). `first` and `tokens` are multiples of four and lie below the layer's end. + pub(in crate::qwen_forward) fn export_span(&self, first: usize, tokens: usize) -> Result { + // `tokens` is a multiple of four for a grid block; a request-end checkpoint ends anywhere: whole pages cover its cells, and only the + // complete 4-cell rows of the index image are copied (the checkpoint's tail carries the partial one) + if first % 4 != 0 || tokens == 0 || first + tokens > self.current.next_position() as usize { + return Err(Error::InvalidPosition); + } + let (mut kv, mut index) = (Vec::new(), Vec::new()); + { + let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_kv"); + self.kv.export_pages(first / 4, (first + tokens).div_ceil(4) - first / 4, &mut kv).map_err(device_error)?; + } + let rows = (first + tokens) / 4 - first / 4; + if rows > 0 { + let _p = crate::qwen_forward::original_serve_profile::span("prefix.export_index"); + self.index.export_rows(first / 4, rows, &mut index).map_err(device_error)?; + } + Ok(ParkedLayerSpan { first_token: first, tokens, kv, index }) + } + /// The tail of the layer's index checkpoint at its current end (what `import` needs besides the spans). + pub(in crate::qwen_forward) fn export_tail(&self) -> Result> { + self.index.export_tail(&self.current.0.index).map_err(device_error) + } + /// Install a parked prefix ending at `end`: write the spans, then re-mint the layer's index checkpoint and mapped + /// prefix from this layer's own lineage. Both physical halves are attempted; the first failure is returned. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn import( + &mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + tail: &[u8], + spans: &[&ParkedLayerSpan], + end: usize, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + cache.validate(binding)?; + let origin = session.target_origin()?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + if !std::ptr::eq(context, self.context) || !self.current.0.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + let index_spans: Vec<(usize, &[u8])> = + spans.iter().filter(|s| !s.index.is_empty()).map(|s| (s.first_token / 4, &s.index[..])).collect(); + let kv_spans: Vec<(usize, &[u8])> = spans.iter().map(|s| (s.first_token / 4, &s.kv[..])).collect(); + let index = { + let _p = crate::qwen_forward::original_serve_profile::span("prefix.layer_index"); + self.index.import(ws, &index_spans, tail, end).map_err(device_error) + }; + let kv = { + let _p = crate::qwen_forward::original_serve_profile::span("prefix.layer_kv"); + self.kv.import_pages(ws, &kv_spans, end).map_err(device_error) + }; + let (index, kv) = (index?, kv?); + self.current = ResidentQsaPrior(Rc::new(Prior { + binding: self.current.0.binding.clone(), + owner: self.current.0.owner.clone(), + origin, + layer: self.current.layer(), + provider: self.current.0.provider.clone(), + index, + kv, + })); + Ok(self.current.clone()) + } + /// One-way handoff into the native verifier. It moves the same resident + /// index and mapped K/V owners used by the prompt executor; it never clones + /// a checkpoint or recreates state from a final image. The returned prior + /// remains the session lineage witness for the exact transferred prefix. + pub(in crate::qwen_forward) fn check_handoff(&self) -> Result<()> { + self.index.validate_context(self.context).map_err(device_error)?; + self.index.validate_checkpoint(&self.current.0.index).map_err(device_error)?; + self.kv.validate_prefix(&self.current.0.kv).map_err(device_error)?; + if self.index.next_position() != self.current.0.index.next_position() + || self.kv.next_position() != self.current.0.kv.next_position() + || self.index.next_position() != self.kv.next_position() + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn into_verifier_owners( + self, + ) -> Result<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>, ResidentQsaPrior<'ctx>)> { + self.check_handoff()?; + Ok((self.index, self.kv, self.current)) + } + /// The reverse of `into_verifier_owners`, after the verifier graphs have all been closed and the journal's + /// owners recovered: the prompt executor takes the SAME physical index and mapped K/V back at the session's + /// current lineage `current`. The physical owners are always rolled back to `current` (a no-op copy when the + /// last window committed; the repair when a window was abandoned mid-flight), so a layer never re-enters + /// the prompt path at a position the session does not hold. + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn from_verifier_owners( + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + index: OriginalQsaResidentIndex<'ctx>, + kv: OriginalQsaMappedJournal<'ctx>, + current: ResidentQsaPrior<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result { + cache.validate(binding)?; + let origin = session.target_origin()?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + current.validate_for_session(binding, session, current.layer(), origin.next_position())?; + index.validate_context(context).map_err(device_error)?; + kv.validate_context(context).map_err(device_error)?; + let mut layer = Self { context, index, kv, current: current.clone() }; + layer.restore(binding, cache, session, ¤t, ws)?; + Ok(layer) + } + pub(in crate::qwen_forward) fn close(self) -> Result<()> { + let index = self.index.close().map_err(device_error); + let kv = self.kv.close().map_err(device_error); + index?; + kv + } +} +impl<'ctx> ResidentQsaPublication<'_, 'ctx> { + pub(in crate::qwen_forward) fn publish_validated(self) -> ResidentQsaPrior<'ctx> { + self.layer.current = self.seal.next; + self.layer.current.clone() + } +} +impl<'ctx> ResidentQsaSeal<'ctx> { + pub(in crate::qwen_forward) fn next_prior(&self) -> ResidentQsaPrior<'ctx> { + self.next.clone() + } + pub(in crate::qwen_forward) fn previous_matches(&self, prior: &ResidentQsaPrior<'ctx>) -> bool { + self.previous.same_prior(prior) + } + + pub(in crate::qwen_forward) fn validate_for( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + layer: LayerId, + first: u64, + accepted: usize, + ) -> Result<()> { + self.next.0.origin.validate_projection_branch(session)?; + cache.validate(binding)?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + let entry = cache.qsa(binding, layer.get())?; + if !self.next.0.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.next.0.provider) + || layer != self.next.layer() + || first != self.previous.next_position() + || accepted != self.accepted + || first.checked_add(accepted as u64) != Some(self.end()) + || self.next.0.index.next_position() != self.next.0.kv.next_position() + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } + pub(in crate::qwen_forward) fn end(&self) -> u64 { + self.next.next_position() + } + pub(in crate::qwen_forward) fn accepted(&self) -> usize { + self.accepted + } + pub(in crate::qwen_forward) fn layer(&self) -> LayerId { + self.next.layer() + } +} +impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> + ResidentQsaSelection<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> +{ + pub(in crate::qwen_forward) fn abort(self, ws: &mut NativeBatchWorkspace<'ctx>) -> Result<()> { + self.selected.abort(ws, self.kv, &self.prior.0.kv).map_err(device_error) + } + pub(in crate::qwen_forward) fn complete( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + ws: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + attention: &mut OriginalQsaResidentAttention<'ctx>, + ) -> Result<(OriginalDeviceBlock<'arena, 'loan, 'ctx>, ResidentQsaCompleted<'index, 'weights, 'ctx>)> { + self.origin.validate(session)?; + cache.validate(binding)?; + let context = cache.retained_context(binding, session.mtp_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &self.provider) + { + return Err(Error::IdentityMismatch); + } + let (out, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; + let (block, index, appended) = self + .selected + .complete(ws, self.kv, stage, &self.prior.0.kv, attention, out, native(kind)?) + .map_err(device_error)?; + self.origin.validate(session)?; + cache.validate(binding)?; + cache.retained_context(binding, context)?; + Ok(( + block, + ResidentQsaCompleted { + binding: self.binding, + origin: self.origin, + context: self.context, + layer: self.layer, + prior: self.prior, + provider: self.provider, + identities: self.identities, + index, + kv: self.kv, + appended, + }, + )) + } +} +impl ResidentQsaRow<'_, '_> { + pub(in crate::qwen_forward) fn identity(&self) -> TokenLayer { + self.identity + } + pub(in crate::qwen_forward) fn end(&self) -> usize { + self.kv.next_position() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsaprior.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsaprior.rs new file mode 100644 index 00000000..5dff173d --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/impl_residentqsaprior.rs @@ -0,0 +1,123 @@ +//! Moved out of the parent module by STRA-338: impl ResidentQsaPrior, impl ResidentQsaPrior, impl ParkedLayerSpan. + +#[allow(unused_imports)] +use super::*; + +impl ResidentQsaPrior<'_> { + pub(in crate::qwen_forward) fn next_position(&self) -> u64 { + self.0.index.next_position() as u64 + } + pub(in crate::qwen_forward) fn layer(&self) -> LayerId { + self.0.layer + } + pub(in crate::qwen_forward) fn same_prior(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } + pub(in crate::qwen_forward) fn validate_for_session( + &self, + binding: &ModelBinding, + session: &QwenSession<'_>, + layer: LayerId, + end: u64, + ) -> Result<()> { + self.validate_for_identity(&binding.identity(), session, layer, end) + } + /// Same check from the model identity alone (the session carries it), for callers without a `ModelBinding`. + pub(in crate::qwen_forward) fn validate_for_identity( + &self, + identity: &BindingIdentity, + session: &QwenSession<'_>, + layer: LayerId, + end: u64, + ) -> Result<()> { + self.0.origin.validate_projection_branch(session)?; + session.validate_resident_qsa_owner(&self.0.owner)?; + let context = session.mtp_context()?; + if !self.0.binding.matches(identity) + || !self.0.provider.matches(identity, layer.get()) + || layer != self.layer() + || end != self.next_position() + || self.0.index.next_position() != self.0.kv.next_position() + { + return Err(Error::IdentityMismatch); + } + self.0.index.validate_retained(context).map_err(device_error)?; + self.0.kv.validate_retained().map_err(device_error)?; + if context.is_poisoned() { + return Err(Error::CudaExecution); + } + Ok(()) + } +} +impl<'ctx> ResidentQsaPrior<'ctx> { + /// The same layer's lineage after the native verifier committed more rows. The verifier owns the physical + /// index image and mapped K/V for the whole decode phase; after each commit event the runtime records where + /// both now end (an index checkpoint and a mapped prefix of the verifier's own journal) as the session's + /// resident witness. Binding, owner and weight provider are inherited, never re-derived. + /// The EMPTY lineage (index image and mapped K/V both at position 0) re-stamped onto another branch + /// generation of the same session. The empty state is content-independent by construction (no cell is + /// reachable), so a position-0 prior taken at load remains the exact reset target after any number of + /// restores; any later position is refused. + pub(in crate::qwen_forward) fn rebased_empty(&self, origin: TargetStepOrigin) -> Result { + if self.0.index.next_position() != 0 + || self.0.kv.next_position() != 0 + || origin.next_position() != 0 + || self.0.origin.next_position() != 0 + || !self.0.origin.same_session(&origin) + { + return Err(Error::IdentityMismatch); + } + Ok(Self(Rc::new(Prior { + binding: self.0.binding.clone(), + owner: self.0.owner.clone(), + origin, + layer: self.0.layer, + provider: self.0.provider.clone(), + index: self.0.index.clone(), + kv: self.0.kv.clone(), + }))) + } + /// The same lineage (index checkpoint and mapped prefix unchanged) stamped with the session's CURRENT branch + /// generation, for a conversation checkpoint resumed after a restore bumped the generation. Only the logical + /// fence moves: whether the physical index image and mapped K/V still hold this prefix is decided by their own + /// epoch/coverage when the layer is restored to it (`ResidentQsaLayer::restore`), and the conversation policy + /// keeps only checkpoints whose tokens are a prefix of what the session holds. + pub(in crate::qwen_forward) fn restamped(&self, origin: TargetStepOrigin) -> Result { + if origin.next_position() != self.next_position() || !self.0.origin.same_session(&origin) { + return Err(Error::IdentityMismatch); + } + Ok(Self(Rc::new(Prior { + binding: self.0.binding.clone(), + owner: self.0.owner.clone(), + origin, + layer: self.0.layer, + provider: self.0.provider.clone(), + index: self.0.index.clone(), + kv: self.0.kv.clone(), + }))) + } + pub(in crate::qwen_forward) fn advanced( + &self, + origin: TargetStepOrigin, + index: OriginalQsaIndexCheckpoint<'ctx>, + kv: OriginalQsaMappedPrefix, + ) -> Result { + if index.next_position() != kv.next_position() || (index.next_position() as u64) < self.next_position() { + return Err(Error::IdentityMismatch); + } + Ok(Self(Rc::new(Prior { + binding: self.0.binding.clone(), + owner: self.0.owner.clone(), + origin, + layer: self.0.layer, + provider: self.0.provider.clone(), + index, + kv, + }))) + } +} +impl ParkedLayerSpan { + pub(in crate::qwen_forward) fn bytes(&self) -> usize { + self.kv.len() + self.index.len() + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs index 10f213ff..958dc2a2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_scalar.rs @@ -1,117 +1,251 @@ //! Genuine current scalar target/MTP continuation of the same live resident //! layer. Old scalar projection/gate/Out math is retained; no index/page image. use super::*; -use leleka_cuda_driver::{OriginalQsaResidentScalarIndex,OriginalQsaResidentScalarSelection,QsaNativeDecode,QsaNativeGate,QsaAttentionInputs}; +use leleka_cuda_driver::{ + OriginalQsaResidentScalarIndex, OriginalQsaResidentScalarSelection, QsaAttentionInputs, QsaNativeDecode, + QsaNativeGate, +}; use std::cell::Cell; -fn driver(e:leleka_cuda_driver::Error)->Error{device_error(e)} -pub(in crate::qwen_forward) struct ResidentQsaScalar<'source,'lease,'index,'weights,'ctx>{binding:BindingIdentity,context:&'ctx Context<'ctx>,layer:LayerId,source:&'source ResidualReady,prior:ResidentQsaPrior<'ctx>,provider:Rc,transaction:Rc<()>,gate:Box<[f32]>,selected:OriginalQsaResidentScalarSelection<'lease,'index,'weights,'ctx>,kv:&'index mut OriginalQsaMappedJournal<'ctx>} -pub(in crate::qwen_forward) struct ResidentQsaScalarReady<'source,'ctx>{binding:BindingIdentity,context:&'ctx Context<'ctx>,layer:LayerId,source:&'source ResidualReady,provider:Rc,transaction:Rc<()>,values:Box<[f32]>,seal:ResidentQsaSeal<'ctx>} -impl<'ctx> ResidentQsaLayer<'ctx>{ - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn prepare_scalar<'source,'lease,'index,'weights>(&'index mut self,binding:&ModelBinding,cache:&'weights DenseWeightCache<'ctx>,txn:&QwenStepTxn<'_, '_>,layer:LayerId,input:&'source ResidualReady,prior:&ResidentQsaPrior<'ctx>,owner:&'lease mut OriginalQsaResidentScalarIndex<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>)->Result>{ - txn.validate_binding(&binding.identity())?;txn.validate_input(input.identity().token(),input.identity().position())?;input.identity().validate(txn.token(),txn.position(),layer)?;input.validate_origin(&binding.identity(),GrRole::Attention(layer.get()))?;txn.validate_projection_branch(&prior.0.origin)?; - let context=cache.retained_context(binding,txn.cuda_context()?)?;cache.validate(binding)?;let entry=cache.qsa(binding,layer.get())?; - if !self.current.same_prior(prior)||layer!=prior.layer()||prior.next_position()!=txn.position().get()||!prior.0.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!Rc::ptr_eq(&entry.weights,&prior.0.provider){return Err(Error::IdentityMismatch)} - self.index.validate_context(context).map_err(driver)?;self.index.validate_checkpoint(&prior.0.index).map_err(driver)?;self.kv.validate_prefix(&prior.0.kv).map_err(driver)?;validate_values(input.mixed(),2560)?; - for(role,width)in[(QsaMatrixRole::IndexK,128),(QsaMatrixRole::K,512),(QsaMatrixRole::V,512),(QsaMatrixRole::Q,12288),(QsaMatrixRole::IndexQ,512)]{if entry.weights.shape(role)!=(2560,width){return Err(Error::InvalidDimension)}} - let transaction=txn.residual_handoff_owner()?; - let raw = project( - context, - binding, - &entry.weights, - QsaMatrixRole::IndexK, - input.mixed(), - Some(cache), - )?; - let k = project( - context, - binding, - &entry.weights, - QsaMatrixRole::K, - input.mixed(), - Some(cache), - )?; - let v = project( - context, - binding, - &entry.weights, - QsaMatrixRole::V, - input.mixed(), - Some(cache), - )?; - let qfull = project( - context, - binding, - &entry.weights, - QsaMatrixRole::Q, - input.mixed(), - Some(cache), - )?; - let iq = project( - context, - binding, - &entry.weights, - QsaMatrixRole::IndexQ, - input.mixed(), - Some(cache), - )?; - for (values, n) in [ - (&raw, 128), - (&k, 512), - (&v, 512), - (&qfull, 12288), - (&iq, 512), +fn driver(e: leleka_cuda_driver::Error) -> Error { + device_error(e) +} +pub(in crate::qwen_forward) struct ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + layer: LayerId, + source: &'source ResidualReady, + prior: ResidentQsaPrior<'ctx>, + provider: Rc, + transaction: Rc<()>, + gate: Box<[f32]>, + selected: OriginalQsaResidentScalarSelection<'lease, 'index, 'weights, 'ctx>, + kv: &'index mut OriginalQsaMappedJournal<'ctx>, +} +pub(in crate::qwen_forward) struct ResidentQsaScalarReady<'source, 'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + layer: LayerId, + source: &'source ResidualReady, + provider: Rc, + transaction: Rc<()>, + values: Box<[f32]>, + seal: ResidentQsaSeal<'ctx>, +} +impl<'ctx> ResidentQsaLayer<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn prepare_scalar<'source, 'lease, 'index, 'weights>( + &'index mut self, + binding: &ModelBinding, + cache: &'weights DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + layer: LayerId, + input: &'source ResidualReady, + prior: &ResidentQsaPrior<'ctx>, + owner: &'lease mut OriginalQsaResidentScalarIndex<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + txn.validate_binding(&binding.identity())?; + txn.validate_input(input.identity().token(), input.identity().position())?; + input.identity().validate(txn.token(), txn.position(), layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?; + txn.validate_projection_branch(&prior.0.origin)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + cache.validate(binding)?; + let entry = cache.qsa(binding, layer.get())?; + if !self.current.same_prior(prior) + || layer != prior.layer() + || prior.next_position() != txn.position().get() + || !prior.0.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !Rc::ptr_eq(&entry.weights, &prior.0.provider) + { + return Err(Error::IdentityMismatch); + } + self.index.validate_context(context).map_err(driver)?; + self.index.validate_checkpoint(&prior.0.index).map_err(driver)?; + self.kv.validate_prefix(&prior.0.kv).map_err(driver)?; + validate_values(input.mixed(), 2560)?; + for (role, width) in [ + (QsaMatrixRole::IndexK, 128), + (QsaMatrixRole::K, 512), + (QsaMatrixRole::V, 512), + (QsaMatrixRole::Q, 12288), + (QsaMatrixRole::IndexQ, 512), ] { + if entry.weights.shape(role) != (2560, width) { + return Err(Error::InvalidDimension); + } + } + let transaction = txn.residual_handoff_owner()?; + let raw = project(context, binding, &entry.weights, QsaMatrixRole::IndexK, input.mixed(), Some(cache))?; + let k = project(context, binding, &entry.weights, QsaMatrixRole::K, input.mixed(), Some(cache))?; + let v = project(context, binding, &entry.weights, QsaMatrixRole::V, input.mixed(), Some(cache))?; + let qfull = project(context, binding, &entry.weights, QsaMatrixRole::Q, input.mixed(), Some(cache))?; + let iq = project(context, binding, &entry.weights, QsaMatrixRole::IndexQ, input.mixed(), Some(cache))?; + for (values, n) in [(&raw, 128), (&k, 512), (&v, 512), (&qfull, 12288), (&iq, 512)] { validate_values(values, n)?; } let mut gate = Vec::new(); - gate.try_reserve_exact(6144) - .map_err(|_| Error::InputAllocation)?; + gate.try_reserve_exact(6144).map_err(|_| Error::InputAllocation)?; for head in 0..24 { gate.extend_from_slice(&qfull[head * 512 + 256..head * 512 + 512]); } validate_values(&gate, 6144)?; - let selected=owner.prepare(&mut self.index,&prior.0.index,&raw,&k,&v,&qfull,&iq,cache.qsa_norms(entry)?,workspace).map_err(driver)?; - txn.validate_binding(&binding.identity())?;txn.validate_input(input.identity().token(),input.identity().position())?;cache.validate(binding)?; - Ok(ResidentQsaScalar{binding:binding.identity(),context,layer,source:input,prior:prior.clone(),provider:entry.weights.clone(),transaction,gate:gate.into_boxed_slice(),selected,kv:&mut self.kv}) - } + let selected = owner + .prepare(&mut self.index, &prior.0.index, &raw, &k, &v, &qfull, &iq, cache.qsa_norms(entry)?, workspace) + .map_err(driver)?; + txn.validate_binding(&binding.identity())?; + txn.validate_input(input.identity().token(), input.identity().position())?; + cache.validate(binding)?; + Ok(ResidentQsaScalar { + binding: binding.identity(), + context, + layer, + source: input, + prior: prior.clone(), + provider: entry.weights.clone(), + transaction, + gate: gate.into_boxed_slice(), + selected, + kv: &mut self.kv, + }) + } } -impl<'source,'lease,'index,'weights,'ctx> ResidentQsaScalar<'source,'lease,'index,'weights,'ctx>{ - fn validate(&self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,txn:&QwenStepTxn<'_, '_>,input:&ResidualReady)->Result<()>{ - txn.validate_binding(&binding.identity())?;txn.validate_input(input.identity().token(),input.identity().position())?;input.identity().validate(txn.token(),txn.position(),self.layer)?;input.validate_origin(&binding.identity(),GrRole::Attention(self.layer.get()))?;txn.validate_projection_branch(&self.prior.0.origin)?; - let context=cache.retained_context(binding,txn.cuda_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!std::ptr::eq(input,self.source)||!Rc::ptr_eq(&self.provider,&entry.weights)||!Rc::ptr_eq(&self.transaction,&txn.residual_handoff_owner()?)||self.prior.next_position()!=txn.position().get()||self.selected.first_position()as u64!=txn.position().get(){return Err(Error::IdentityMismatch)}validate_values(&self.gate,6144) - } - #[allow(clippy::too_many_arguments)] - pub(in crate::qwen_forward) fn complete(mut self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,txn:&QwenStepTxn<'_, '_>,input:&ResidualReady,attention:&mut QsaNativeDecode<'ctx>,stage:&mut OriginalQsaResidentTransport<'ctx>,gate_owner:&mut QsaNativeGate<'ctx>,workspace:&mut NativeBatchWorkspace<'ctx>)->Result>{ - let operation=(||->Result<(Box<[f32]>,OriginalQsaMappedAppend)>{ - self.validate(binding,cache,txn,input)?;super::super::admit_budget(self.context)?; - let append=self.kv.append_resident_decode(workspace,stage,&self.prior.0.kv,&self.selected).map_err(driver)?; - let attended=self.selected.with_completed_buffers(|q,ids,steps|{ - let inputs=QsaAttentionInputs::new(q,ids,steps,1)?;let actual=attention.attend_resident(workspace,self.kv,append.final_prefix(),&inputs)?;actual.into_values() - }).map_err(driver)?;validate_values(&attended,6144)?; - let failed=cache.transport_failure_flag(binding,self.context)?; - let values=gate_and_out(binding,cache,self.context,self.provider.as_ref(),&attended,&self.gate,gate_owner,workspace,&failed)?; - self.validate(binding,cache,txn,input)?;validate_values(&values,2560)?;Ok((values,append)) - })(); - match operation{ - Err(primary)=>{let index=self.selected.abort(workspace).map_err(driver);let kv=self.kv.rollback(workspace,&self.prior.0.kv).map_err(driver);let _=(index,kv);Err(primary)}, - Ok((values,append))=>{let index=self.selected.seal(workspace,1).map_err(driver);let kv=self.kv.accept_prefix(workspace,&append,1).map_err(driver);let index=index?;let kv=kv?; - cache.validate(binding)?;cache.retained_context(binding,self.context)?;txn.validate_projection_branch(&self.prior.0.origin)?; - let next=ResidentQsaPrior(Rc::new(Prior{binding:self.binding.clone(),owner:self.prior.0.owner.clone(),origin:self.prior.0.origin.clone(),layer:self.layer,provider:self.provider.clone(),index,kv})); - let seal=ResidentQsaSeal{context:self.context,previous:self.prior,next,accepted:1}; - Ok(ResidentQsaScalarReady{binding:self.binding,context:self.context,layer:self.layer,source:self.source,provider:self.provider,transaction:self.transaction,values,seal}) - } - } - } +impl<'source, 'lease, 'index, 'weights, 'ctx> ResidentQsaScalar<'source, 'lease, 'index, 'weights, 'ctx> { + fn validate( + &self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + input: &ResidualReady, + ) -> Result<()> { + txn.validate_binding(&binding.identity())?; + txn.validate_input(input.identity().token(), input.identity().position())?; + input.identity().validate(txn.token(), txn.position(), self.layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?; + txn.validate_projection_branch(&self.prior.0.origin)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !std::ptr::eq(input, self.source) + || !Rc::ptr_eq(&self.provider, &entry.weights) + || !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?) + || self.prior.next_position() != txn.position().get() + || self.selected.first_position() as u64 != txn.position().get() + { + return Err(Error::IdentityMismatch); + } + validate_values(&self.gate, 6144) + } + #[allow(clippy::too_many_arguments)] + pub(in crate::qwen_forward) fn complete( + mut self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + input: &ResidualReady, + attention: &mut QsaNativeDecode<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + gate_owner: &mut QsaNativeGate<'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ) -> Result> { + let operation = (|| -> Result<(Box<[f32]>, OriginalQsaMappedAppend)> { + self.validate(binding, cache, txn, input)?; + super::super::admit_budget(self.context)?; + let append = + self.kv.append_resident_decode(workspace, stage, &self.prior.0.kv, &self.selected).map_err(driver)?; + let attended = self + .selected + .with_completed_buffers(|q, ids, steps| { + let inputs = QsaAttentionInputs::new(q, ids, steps, 1)?; + let actual = attention.attend_resident(workspace, self.kv, append.final_prefix(), &inputs)?; + actual.into_values() + }) + .map_err(driver)?; + validate_values(&attended, 6144)?; + let failed = cache.transport_failure_flag(binding, self.context)?; + let values = gate_and_out( + binding, + cache, + self.context, + self.provider.as_ref(), + &attended, + &self.gate, + gate_owner, + workspace, + &failed, + )?; + self.validate(binding, cache, txn, input)?; + validate_values(&values, 2560)?; + Ok((values, append)) + })(); + match operation { + Err(primary) => { + let index = self.selected.abort(workspace).map_err(driver); + let kv = self.kv.rollback(workspace, &self.prior.0.kv).map_err(driver); + let _ = (index, kv); + Err(primary) + } + Ok((values, append)) => { + let index = self.selected.seal(workspace, 1).map_err(driver); + let kv = self.kv.accept_prefix(workspace, &append, 1).map_err(driver); + let index = index?; + let kv = kv?; + cache.validate(binding)?; + cache.retained_context(binding, self.context)?; + txn.validate_projection_branch(&self.prior.0.origin)?; + let next = ResidentQsaPrior(Rc::new(Prior { + binding: self.binding.clone(), + owner: self.prior.0.owner.clone(), + origin: self.prior.0.origin.clone(), + layer: self.layer, + provider: self.provider.clone(), + index, + kv, + })); + let seal = ResidentQsaSeal { context: self.context, previous: self.prior, next, accepted: 1 }; + Ok(ResidentQsaScalarReady { + binding: self.binding, + context: self.context, + layer: self.layer, + source: self.source, + provider: self.provider, + transaction: self.transaction, + values, + seal, + }) + } + } + } } -impl<'source,'ctx> ResidentQsaScalarReady<'source,'ctx>{ - pub(in crate::qwen_forward) fn into_parts(self,binding:&ModelBinding,cache:&DenseWeightCache<'ctx>,txn:&QwenStepTxn<'_, '_>,input:&ResidualReady)->Result<(TokenLayer,Box<[f32]>,ResidentQsaSeal<'ctx>)>{ - txn.validate_binding(&binding.identity())?;txn.validate_input(input.identity().token(),input.identity().position())?;input.identity().validate(txn.token(),txn.position(),self.layer)?;input.validate_origin(&binding.identity(),GrRole::Attention(self.layer.get()))?;txn.validate_projection_branch(&self.seal.next.0.origin)?; - let context=cache.retained_context(binding,txn.cuda_context()?)?;let entry=cache.qsa(binding,self.layer.get())?; - if !self.binding.matches(&binding.identity())||!std::ptr::eq(context,self.context)||!std::ptr::eq(input,self.source)||!Rc::ptr_eq(&self.provider,&entry.weights)||!Rc::ptr_eq(&self.transaction,&txn.residual_handoff_owner()?){return Err(Error::IdentityMismatch)}validate_values(&self.values,2560)?;Ok((input.identity(),self.values,self.seal)) - } +impl<'source, 'ctx> ResidentQsaScalarReady<'source, 'ctx> { + pub(in crate::qwen_forward) fn into_parts( + self, + binding: &ModelBinding, + cache: &DenseWeightCache<'ctx>, + txn: &QwenStepTxn<'_, '_>, + input: &ResidualReady, + ) -> Result<(TokenLayer, Box<[f32]>, ResidentQsaSeal<'ctx>)> { + txn.validate_binding(&binding.identity())?; + txn.validate_input(input.identity().token(), input.identity().position())?; + input.identity().validate(txn.token(), txn.position(), self.layer)?; + input.validate_origin(&binding.identity(), GrRole::Attention(self.layer.get()))?; + txn.validate_projection_branch(&self.seal.next.0.origin)?; + let context = cache.retained_context(binding, txn.cuda_context()?)?; + let entry = cache.qsa(binding, self.layer.get())?; + if !self.binding.matches(&binding.identity()) + || !std::ptr::eq(context, self.context) + || !std::ptr::eq(input, self.source) + || !Rc::ptr_eq(&self.provider, &entry.weights) + || !Rc::ptr_eq(&self.transaction, &txn.residual_handoff_owner()?) + { + return Err(Error::IdentityMismatch); + } + validate_values(&self.values, 2560)?; + Ok((input.identity(), self.values, self.seal)) + } } #[allow(clippy::too_many_arguments)] // Actual role-specific weights and closed current finite inputs. fn gate_and_out<'ctx>( @@ -151,9 +285,7 @@ fn gate_and_out<'ctx>( let gated = download(buffers[2].as_ref().ok_or(Error::IdentityMismatch)?, 6144)?; validate_values(&gated, 6144)?; let entry = cache.qsa(binding, weights.layer())?; - if !std::ptr::eq(entry.weights.as_ref(), weights) - || weights.shape(QsaMatrixRole::Out) != (6144, 2560) - { + if !std::ptr::eq(entry.weights.as_ref(), weights) || weights.shape(QsaMatrixRole::Out) != (6144, 2560) { return Err(Error::IdentityMismatch); } let (matrix, kind) = cache.qsa_matrix(entry, QsaMatrixRole::Out)?; @@ -180,8 +312,7 @@ fn gate_and_out<'ctx>( } } } - if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() - { + if matches!(&operation, Err(Error::CudaExecution)) || cleanup.is_err() || context.is_poisoned() { failed.set(true); } match operation { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs index 5c964a3b..3bc42001 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/qsa_selected_cache.rs @@ -16,11 +16,7 @@ struct CachedCell { } impl CachedCell { fn matches(&self, page: &Rc, offset: u8) -> bool { - self.offset == offset - && self - .page - .upgrade() - .is_some_and(|old| Rc::ptr_eq(&old, page)) + self.offset == offset && self.page.upgrade().is_some_and(|old| Rc::ptr_eq(&old, page)) } fn key(&self) -> CellKey { (self.page.as_ptr() as usize, self.offset) @@ -37,23 +33,15 @@ impl LayerDirectory { let mut cells = reserve(SLOTS)?; cells.resize_with(SLOTS, || None); let mut index = HashMap::new(); - index - .try_reserve(SLOTS) - .map_err(|_| Error::InputAllocation)?; - Ok(Self { - owner: None, - cells, - index, - cursor: 0, - }) + index.try_reserve(SLOTS).map_err(|_| Error::InputAllocation)?; + Ok(Self { owner: None, cells, index, cursor: 0 }) } fn copy_for(&self, owner: &QsaOwner) -> Result { let mut next = Self::empty()?; next.owner = Some(owner.clone()); if self.owner.as_ref().is_some_and(|old| old.matches(owner)) { next.cells.clone_from_slice(&self.cells); - next.index - .extend(self.index.iter().map(|(key, slot)| (*key, *slot))); + next.index.extend(self.index.iter().map(|(key, slot)| (*key, *slot))); next.cursor = self.cursor; } Ok(next) @@ -86,9 +74,7 @@ fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { for (row, (page, offset)) in sources.iter().enumerate() { let key = (Rc::as_ptr(page) as usize, *offset); if let Some(&slot) = next.index.get(&key) - && next.cells[slot] - .as_ref() - .is_some_and(|old| old.matches(page, *offset)) + && next.cells[slot].as_ref().is_some_and(|old| old.matches(page, *offset)) { protected[slot] = true; selected[row] = slot as u32; @@ -123,23 +109,14 @@ fn plan(old: &LayerDirectory, prior: &QsaPrior, ids: &[i32]) -> Result { } } let key = (Rc::as_ptr(page) as usize, *offset); - next.cells[slot] = Some(CachedCell { - page: Rc::downgrade(page), - offset: *offset, - }); + next.cells[slot] = Some(CachedCell { page: Rc::downgrade(page), offset: *offset }); next.index.insert(key, slot); next.cursor = (slot + 1) % SLOTS; protected[slot] = true; selected[row] = slot as u32; misses.push(slot as u32); } - Ok(Plan { - next, - misses, - k, - v, - selected, - }) + Ok(Plan { next, misses, k, v, selected }) } pub(in crate::qwen_forward) struct QsaSelectedCache<'ctx> { @@ -158,14 +135,8 @@ impl<'ctx> QsaSelectedCache<'ctx> { if failed.get() || context.is_poisoned() { return Err(Error::CudaExecution); } - let required = WORKSPACE_BYTES - .checked_add(device_peak()) - .ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|bytes| bytes > context.budget_bytes()) - { + let required = WORKSPACE_BYTES.checked_add(device_peak()).ok_or(Error::Overflow)?; + if context.allocated_bytes().checked_add(required).is_none_or(|bytes| bytes > context.budget_bytes()) { return Err(Error::InputAllocation); } let (free, _) = context.memory_info().map_err(|error| { @@ -194,13 +165,7 @@ impl<'ctx> QsaSelectedCache<'ctx> { } return Err(Error::InvalidDimension); } - Ok(Self { - binding, - context, - failed, - layers, - workspace: Some(workspace), - }) + Ok(Self { binding, context, failed, layers, workspace: Some(workspace) }) } pub(in crate::qwen_forward) fn attend( @@ -213,10 +178,7 @@ impl<'ctx> QsaSelectedCache<'ctx> { ) -> Result<()> { if self.failed.get() || self.context.is_poisoned() - || self - .workspace - .as_ref() - .is_none_or(|workspace| workspace.is_failed()) + || self.workspace.as_ref().is_none_or(|workspace| workspace.is_failed()) { self.failed.set(true); return Err(Error::CudaExecution); @@ -238,9 +200,8 @@ impl<'ctx> QsaSelectedCache<'ctx> { let plan = plan(&self.layers[slot], candidate, &prepared.ids)?; let workspace = self.workspace.as_mut().ok_or(Error::CudaExecution)?; let operation = (|| { - let products = workspace - .prepare(layer / 4, &plan.misses, &plan.k, &plan.v, &plan.selected) - .map_err(driver_error)?; + let products = + workspace.prepare(layer / 4, &plan.misses, &plan.k, &plan.v, &plan.selected).map_err(driver_error)?; if products.width() as usize != plan.selected.len() { self.failed.set(true); return Err(Error::InvalidDimension); @@ -258,10 +219,7 @@ impl<'ctx> QsaSelectedCache<'ctx> { pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { let primary = self.failed.get().then_some(Error::CudaExecution); - let cleanup = self - .workspace - .take() - .map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); + let cleanup = self.workspace.take().map_or(Ok(()), |workspace| workspace.close().map_err(driver_error)); if cleanup.is_err() || self.context.is_poisoned() { self.failed.set(true); } @@ -295,14 +253,8 @@ mod tests { let mut index = [0.0; 640]; index[384..512].fill(0.25); index[512..].fill(-0.5); - QsaPending::new( - prior, - identity, - &word.to_le_bytes().repeat(KV), - &0x8000u16.to_le_bytes().repeat(KV), - &index, - ) - .map(QsaPending::into_prior) + QsaPending::new(prior, identity, &word.to_le_bytes().repeat(KV), &0x8000u16.to_le_bytes().repeat(KV), &index) + .map(QsaPending::into_prior) } // Pure planning fixture; it never claims a device upload or invents a ModelBinding. @@ -344,21 +296,10 @@ mod tests { let reset = append(&reset, 0x3c00).unwrap(); let reset_plan = plan(&checkpoint.next, &reset, &[0]).unwrap(); assert_eq!(reset_plan.misses.len(), 1); - assert!(matches!( - plan(&checkpoint.next, &five, &[0, 1, 3, 2, 4]), - Err(Error::InvalidPosition) - )); - assert!(matches!( - plan(&checkpoint.next, &five, &[0, 1, 2, 3, 5]), - Err(Error::InvalidPosition) - )); + assert!(matches!(plan(&checkpoint.next, &five, &[0, 1, 3, 2, 4]), Err(Error::InvalidPosition))); + assert!(matches!(plan(&checkpoint.next, &five, &[0, 1, 2, 3, 5]), Err(Error::InvalidPosition))); assert!(matches!(append(&five, 0x7c00), Err(Error::NonFinite))); - assert!( - plan(&checkpoint.next, &five, &[0, 1, 2, 3, 4]) - .unwrap() - .misses - .is_empty() - ); + assert!(plan(&checkpoint.next, &five, &[0, 1, 2, 3, 4]).unwrap().misses.is_empty()); // Weak entries retain neither reset pages nor speculative branch host payloads. let retired = Rc::downgrade(&six.0.pages[1]); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs index 0c423c0b..472b2957 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch.rs @@ -30,11 +30,7 @@ impl<'ctx> RouterBuffers<'ctx> { return Err(Error::CudaExecution); } let needed = ROUTER_BYTES.checked_add(RESERVE).ok_or(Error::Overflow)?; - if context - .allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(needed).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } let (free, _) = context.memory_info().map_err(|error| { @@ -44,11 +40,7 @@ impl<'ctx> RouterBuffers<'ctx> { if free < needed { return Err(Error::InputAllocation); } - let mut result = Self { - context, - slots: std::array::from_fn(|_| None), - failed, - }; + let mut result = Self { context, slots: std::array::from_fn(|_| None), failed }; for (index, bytes) in EXTENTS.into_iter().enumerate() { match context.allocate(bytes) { Ok(buffer) => result.slots[index] = Some(buffer), @@ -68,12 +60,7 @@ impl<'ctx> RouterBuffers<'ctx> { if self.failed.get() || self.context.is_poisoned() { return Err(Error::CudaExecution); } - if self - .slots - .iter() - .zip(EXTENTS) - .any(|(b, n)| b.as_ref().is_none_or(|b| b.len() != n)) - { + if self.slots.iter().zip(EXTENTS).any(|(b, n)| b.as_ref().is_none_or(|b| b.len() != n)) { return Err(Error::InvalidDimension); } Ok(()) @@ -85,12 +72,7 @@ impl<'ctx> RouterBuffers<'ctx> { return Err(Error::InvalidDimension); } let mut input_bytes = [0u8; 10240]; - for (bytes, value) in input_bytes - .as_chunks_mut::<4>() - .0 - .iter_mut() - .zip(activation) - { + for (bytes, value) in input_bytes.as_chunks_mut::<4>().0.iter_mut().zip(activation) { *bytes = value.to_bits().to_le_bytes(); } let operation = (|| -> Result<[f32; 512]> { @@ -99,24 +81,12 @@ impl<'ctx> RouterBuffers<'ctx> { let output = output.as_mut().ok_or(Error::IdentityMismatch)?; input.copy_from(&input_bytes).map_err(map_driver_error)?; self.context - .bf16_f32( - matrix, - input, - output, - Bf16ProjectionShape { - rows: 512, - columns: 2560, - }, - ) + .bf16_f32(matrix, input, output, Bf16ProjectionShape { rows: 512, columns: 2560 }) .map_err(map_driver_error)?; let mut bytes = [0u8; 2048]; output.copy_to(&mut bytes).map_err(map_driver_error)?; Ok(std::array::from_fn(|i| { - f32::from_le_bytes( - bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed router output"), - ) + f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("fixed router output")) })) })(); if operation.as_ref().err() == Some(&Error::CudaExecution) || self.context.is_poisoned() { @@ -141,29 +111,17 @@ impl<'ctx> RouterBuffers<'ctx> { let ids = ids.as_mut().ok_or(Error::IdentityMismatch)?; let weights = weights.as_mut().ok_or(Error::IdentityMismatch)?; input.copy_from(&logits_bytes).map_err(map_driver_error)?; - self.context - .qwen_route_top10(input, ids, weights) - .map_err(map_driver_error)?; + self.context.qwen_route_top10(input, ids, weights).map_err(map_driver_error)?; let mut ids_bytes = [0u8; 40]; let mut weights_bytes = [0u8; 40]; ids.copy_to(&mut ids_bytes).map_err(map_driver_error)?; - weights - .copy_to(&mut weights_bytes) - .map_err(map_driver_error)?; + weights.copy_to(&mut weights_bytes).map_err(map_driver_error)?; Ok(( std::array::from_fn(|i| { - i32::from_ne_bytes( - ids_bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed ID extent"), - ) + i32::from_ne_bytes(ids_bytes[i * 4..i * 4 + 4].try_into().expect("fixed ID extent")) }), std::array::from_fn(|i| { - f32::from_ne_bytes( - weights_bytes[i * 4..i * 4 + 4] - .try_into() - .expect("fixed weight extent"), - ) + f32::from_ne_bytes(weights_bytes[i * 4..i * 4 + 4].try_into().expect("fixed weight extent")) }), )) })(); @@ -212,17 +170,8 @@ pub(super) struct RouterLease<'loan, 'ctx> { } impl<'ctx> RouterScratch<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn new( - binding: BindingIdentity, - context: &'ctx Context<'ctx>, - failed: Rc>, - ) -> Result { - Ok(Self { - binding, - buffers: RouterBuffers::new(context, failed)?, - generation: 0, - completed: 0, - }) + pub(super) fn new(binding: BindingIdentity, context: &'ctx Context<'ctx>, failed: Rc>) -> Result { + Ok(Self { binding, buffers: RouterBuffers::new(context, failed)?, generation: 0, completed: 0 }) } pub(super) fn lease<'loan>( mut slot: RefMut<'loan, Self>, @@ -247,16 +196,7 @@ impl<'ctx> RouterScratch<'ctx> { let generation = slot.generation.checked_add(1).ok_or(Error::Overflow)?; let next_completed = slot.completed.checked_add(1).ok_or(Error::Overflow)?; slot.generation = generation; - Ok(RouterLease { - slot, - matrix, - source, - identity, - generation, - next_completed, - projected: None, - routed: false, - }) + Ok(RouterLease { slot, matrix, source, identity, generation, next_completed, projected: None, routed: false }) } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(super) fn completed(&self) -> u64 { @@ -272,29 +212,21 @@ impl RouterLease<'_, '_> { if self.slot.generation != self.generation || self.source.identity() != self.identity { return Err(Error::IdentityMismatch); } - self.source - .validate_origin(&self.slot.binding, GrRole::Ffn(self.identity.layer().get())) + self.source.validate_origin(&self.slot.binding, GrRole::Ffn(self.identity.layer().get())) } pub(super) fn project(&mut self) -> Result<[f32; 512]> { self.check()?; if self.projected.is_some() || self.routed { return Err(Error::IdentityMismatch); } - let values = self - .slot - .buffers - .project(self.matrix, self.source.mixed())?; + let values = self.slot.buffers.project(self.matrix, self.source.mixed())?; self.projected = Some(values); Ok(values) } pub(super) fn route(&mut self, values: &[f32; 512]) -> Result<([i32; 10], [f32; 10])> { self.check()?; if self.routed - || self.projected.as_ref().is_none_or(|old| { - old.iter() - .zip(values) - .any(|(a, b)| a.to_bits() != b.to_bits()) - }) + || self.projected.as_ref().is_none_or(|old| old.iter().zip(values).any(|(a, b)| a.to_bits() != b.to_bits())) { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs index 7f824c54..3fe04666 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu.rs @@ -30,12 +30,8 @@ fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { let driver = Driver::load().expect("actual CUDA driver"); let device = driver.device(0).expect("actual CUDA device"); let context = device.create_context(BUDGET).expect("main numeric context"); - let foreign_context = device - .create_context(16 * 1024 * 1024) - .expect("foreign numeric context"); - let small_context = device - .create_context(RESERVE + ROUTER_BYTES - 1) - .expect("budget refusal context"); + let foreign_context = device.create_context(16 * 1024 * 1024).expect("foreign numeric context"); + let small_context = device.create_context(RESERVE + ROUTER_BYTES - 1).expect("budget refusal context"); let mut report = Report::default(); let small_before = small_context.allocated_bytes(); let small = RouterBuffers::new(&small_context, Rc::new(Cell::new(false))); @@ -45,9 +41,7 @@ fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { let small_sync = small_context.synchronize(); let small_allocated = small_context.allocated_bytes(); let small_close = small_context.close(); - let operation = catch_unwind(AssertUnwindSafe(|| { - numeric(&context, &foreign_context, &mut report) - })); + let operation = catch_unwind(AssertUnwindSafe(|| numeric(&context, &foreign_context, &mut report))); let main_sync = context.synchronize(); let foreign_sync = foreign_context.synchronize(); let main_allocated = context.allocated_bytes(); @@ -67,10 +61,7 @@ fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { && main_close.is_ok() && foreign_close.is_ok() ); - assert_eq!( - (small_allocated, main_allocated, foreign_allocated), - (0, 0, 0) - ); + assert_eq!((small_allocated, main_allocated, foreign_allocated), (0, 0, 0)); println!( "ROUTER_SCRATCH_COMPLETE cases={} logits_words={} ids={} weights={} differences={} guards={} failed_guards={} resets={} ties={} allocated=0 component_only=true", report.cases, @@ -93,32 +84,32 @@ fn original_first_fixed_router_all_logits_routes_repeat_reset_and_cleanup() { #[path = "router_scratch_gpu/impl_report.rs"] mod impl_report; #[allow(unused_imports)] -use impl_report::valid_product; +use impl_report::activation; #[allow(unused_imports)] -use impl_report::float_bytes; +use impl_report::candidate; #[allow(unused_imports)] use impl_report::close_all; #[allow(unused_imports)] use impl_report::finish; #[allow(unused_imports)] +use impl_report::float_bytes; +#[allow(unused_imports)] +use impl_report::healthy; +#[allow(unused_imports)] +use impl_report::matrix_bytes; +#[allow(unused_imports)] +use impl_report::original; +#[allow(unused_imports)] use impl_report::original_project; #[allow(unused_imports)] use impl_report::original_route; #[allow(unused_imports)] -use impl_report::original; -#[allow(unused_imports)] -use impl_report::candidate; -#[allow(unused_imports)] use impl_report::snapshot; #[allow(unused_imports)] -use impl_report::matrix_bytes; -#[allow(unused_imports)] -use impl_report::activation; -#[allow(unused_imports)] -use impl_report::healthy; +use impl_report::valid_product; #[path = "router_scratch_gpu/valid_reset_fn.rs"] mod valid_reset_fn; #[allow(unused_imports)] -use valid_reset_fn::valid_reset; -#[allow(unused_imports)] use valid_reset_fn::numeric; +#[allow(unused_imports)] +use valid_reset_fn::valid_reset; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/impl_report.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/impl_report.rs index f2f14062..3df0b8d1 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/impl_report.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/impl_report.rs @@ -19,24 +19,9 @@ impl Report { self.logits_words += 512; self.ids += 10; self.weight_words += 10; - self.differences += expected - .0 - .iter() - .zip(actual.0) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); - self.differences += expected - .1 - .iter() - .zip(actual.1) - .filter(|(a, b)| **a != *b) - .count(); - self.differences += expected - .2 - .iter() - .zip(actual.2) - .filter(|(a, b)| a.to_bits() != b.to_bits()) - .count(); + self.differences += expected.0.iter().zip(actual.0).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); + self.differences += expected.1.iter().zip(actual.1).filter(|(a, b)| **a != *b).count(); + self.differences += expected.2.iter().zip(actual.2).filter(|(a, b)| a.to_bits() != b.to_bits()).count(); } } @@ -79,11 +64,7 @@ pub(super) fn finish(operation: Result, cleanup: Result<()>) -> Result // Original cached-matrix numerical path, independent per-call transport owners. // SAME original bf16_f32, full512 D2H, releases, finite validation before routing. -pub(super) fn original_project( - context: &Context<'_>, - matrix: &DeviceBuffer<'_>, - values: &[f32], -) -> Result<[f32; 512]> { +pub(super) fn original_project(context: &Context<'_>, matrix: &DeviceBuffer<'_>, values: &[f32]) -> Result<[f32; 512]> { validate_activation(values)?; if matrix.len() != MATRIX_BYTES { return Err(Error::InvalidDimension); @@ -95,29 +76,13 @@ pub(super) fn original_project( let [input, output] = &mut buffers; let input = input.as_mut().ok_or(Error::IdentityMismatch)?; let output = output.as_mut().ok_or(Error::IdentityMismatch)?; - input - .copy_from(&float_bytes(values)) - .map_err(map_driver_error)?; + input.copy_from(&float_bytes(values)).map_err(map_driver_error)?; context - .bf16_f32( - matrix, - input, - output, - Bf16ProjectionShape { - rows: 512, - columns: 2560, - }, - ) + .bf16_f32(matrix, input, output, Bf16ProjectionShape { rows: 512, columns: 2560 }) .map_err(map_driver_error)?; let mut bytes = [0u8; 2048]; output.copy_to(&mut bytes).map_err(map_driver_error)?; - Ok(std::array::from_fn(|i| { - f32::from_le_bytes( - bytes[i * 4..i * 4 + 4] - .try_into() - .expect("whole router word"), - ) - })) + Ok(std::array::from_fn(|i| f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().expect("whole router word")))) })(); let cleanup = close_all(&mut buffers); let values = finish(operation, cleanup)?; @@ -137,33 +102,16 @@ pub(super) fn original_route(context: &Context<'_>, values: &[f32; 512]) -> Resu let input = input.as_mut().ok_or(Error::IdentityMismatch)?; let ids = ids.as_mut().ok_or(Error::IdentityMismatch)?; let weights = weights.as_mut().ok_or(Error::IdentityMismatch)?; - input - .copy_from( - &values - .iter() - .flat_map(|v| v.to_ne_bytes()) - .collect::>(), - ) - .map_err(map_driver_error)?; - context - .qwen_route_top10(input, ids, weights) - .map_err(map_driver_error)?; + input.copy_from(&values.iter().flat_map(|v| v.to_ne_bytes()).collect::>()).map_err(map_driver_error)?; + context.qwen_route_top10(input, ids, weights).map_err(map_driver_error)?; let mut id_bytes = [0u8; 40]; let mut weight_bytes = [0u8; 40]; ids.copy_to(&mut id_bytes).map_err(map_driver_error)?; - weights - .copy_to(&mut weight_bytes) - .map_err(map_driver_error)?; + weights.copy_to(&mut weight_bytes).map_err(map_driver_error)?; Ok(( + std::array::from_fn(|i| i32::from_ne_bytes(id_bytes[i * 4..i * 4 + 4].try_into().expect("whole ID"))), std::array::from_fn(|i| { - i32::from_ne_bytes(id_bytes[i * 4..i * 4 + 4].try_into().expect("whole ID")) - }), - std::array::from_fn(|i| { - f32::from_ne_bytes( - weight_bytes[i * 4..i * 4 + 4] - .try_into() - .expect("whole weight"), - ) + f32::from_ne_bytes(weight_bytes[i * 4..i * 4 + 4].try_into().expect("whole weight")) }), )) })(); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs index 72c787b9..3d1a6258 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/router_scratch_gpu/valid_reset_fn.rs @@ -28,26 +28,14 @@ pub(super) fn numeric<'ctx>( let mut workspace = None; let operation: Result<()> = (|| { buffers[0] = Some(context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); - buffers[1] = Some( - context - .allocate(MATRIX_BYTES - 2) - .map_err(map_driver_error)?, - ); - foreign = Some( - foreign_context - .allocate(MATRIX_BYTES) - .map_err(map_driver_error)?, - ); + buffers[1] = Some(context.allocate(MATRIX_BYTES - 2).map_err(map_driver_error)?); + foreign = Some(foreign_context.allocate(MATRIX_BYTES).map_err(map_driver_error)?); let baseline = matrix_bytes(); let [matrix, short] = &mut buffers; let matrix = matrix.as_mut().ok_or(Error::IdentityMismatch)?; let short = short.as_ref().ok_or(Error::IdentityMismatch)?; matrix.copy_from(&baseline).map_err(map_driver_error)?; - foreign - .as_mut() - .ok_or(Error::IdentityMismatch)? - .copy_from(&baseline) - .map_err(map_driver_error)?; + foreign.as_mut().ok_or(Error::IdentityMismatch)?.copy_from(&baseline).map_err(map_driver_error)?; let before = context.allocated_bytes(); workspace = Some(RouterBuffers::new(context, Rc::new(Cell::new(false)))?); report.guard(context.allocated_bytes() == before + ROUTER_BYTES); @@ -71,11 +59,7 @@ pub(super) fn numeric<'ctx>( } // Change the last matrix row, independently capture it, then restore and repeat. let mut changed = baseline.clone(); - for half in changed[MATRIX_BYTES - 5120..] - .as_chunks_mut::<2>() - .0 - .iter_mut() - { + for half in changed[MATRIX_BYTES - 5120..].as_chunks_mut::<2>().0.iter_mut() { *half = 0x3f80u16.to_le_bytes(); } matrix.copy_from(&changed).map_err(map_driver_error)?; @@ -94,36 +78,26 @@ pub(super) fn numeric<'ctx>( let old = original_project(context, matrix, &values).err(); let before = snapshot(workspace)?; let actual = workspace.project(matrix, &values).err(); - report.guard( - old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before, - ); + report.guard(old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before); valid_reset(workspace, matrix, &inputs[0], context, report)?; let mut logits = expected[0].0; logits[511] = bad; let old = original_route(context, &logits).err(); let before = snapshot(workspace)?; let actual = workspace.route(&logits).err(); - report.guard( - old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before, - ); + report.guard(old == Some(Error::NonFinite) && actual == old && snapshot(workspace)? == before); valid_reset(workspace, matrix, &inputs[0], context, report)?; } for values in [&inputs[0][..2559], &inputs[0][..0]] { let old = original_project(context, matrix, values).err(); let before = snapshot(workspace)?; let actual = workspace.project(matrix, values).err(); - report.guard( - old == Some(Error::InvalidDimension) - && actual == old - && snapshot(workspace)? == before, - ); + report.guard(old == Some(Error::InvalidDimension) && actual == old && snapshot(workspace)? == before); } let old = original_project(context, short, &inputs[0]).err(); let before = snapshot(workspace)?; let actual = workspace.project(short, &inputs[0]).err(); - report.guard( - old == Some(Error::InvalidDimension) && actual == old && snapshot(workspace)? == before, - ); + report.guard(old == Some(Error::InvalidDimension) && actual == old && snapshot(workspace)? == before); // Actual late projection NaN/Inf is detected by full512 readback, then reset. for half in [0x7fc1u16, 0x7f80u16, 0xff80u16] { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session.rs index 4bc4f113..d07688df 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session.rs @@ -79,8 +79,9 @@ pub(crate) struct QwenSession<'driver> { /// PLE host priors then stay at this position until `publish_original_resident_state` reads the /// verifier's canonical image back once; `None` means they are in step with `next_position`. state_lag: Option, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - resident_qsa_states: [Option>; STATE_CAPACITY], + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + resident_qsa_states: + [Option>; STATE_CAPACITY], } /// Test-only retained immutable numerical content, not a restore capability. @@ -102,6 +103,6 @@ pub(crate) struct ResetReplaySnapshot { #[cfg(test)] mod tests; +mod impl_qwensession; mod impl_qwensteptxn; mod impl_resetreplaysnapshot; -mod impl_qwensession; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensession.rs index 753c8a42..7fefd8dc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensession.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensession.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl<'driver> QwenSession<'driver> { pub(in crate::qwen_forward) fn note_mtp_failure(&mut self, error: &Error) { if *error == Error::CudaExecution { @@ -36,10 +35,7 @@ impl<'driver> QwenSession<'driver> { checkpoint_generation: 0, cuda_failed: false, layer_count: binding.layer_count(), - ple_required: binding - .ordered_layers() - .get(1) - .is_some_and(|d| d.index() == 1), + ple_required: binding.ordered_layers().get(1).is_some_and(|d| d.index() == 1), ple_owner: PleOwner::new(), ple_state: None, gdn_layers: std::array::from_fn(|index| { @@ -59,8 +55,8 @@ impl<'driver> QwenSession<'driver> { qsa_owner: QsaOwner::new(), qsa_states: std::array::from_fn(|_| None), state_lag: None, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - resident_qsa_states: std::array::from_fn(|_|None), + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + resident_qsa_states: std::array::from_fn(|_| None), } } @@ -71,9 +67,7 @@ impl<'driver> QwenSession<'driver> { if self.cuda_failed { return Err(Error::CudaExecution); } - self.cuda - .as_deref() - .ok_or(Error::Unsupported(Stage::Session)) + self.cuda.as_deref().ok_or(Error::Unsupported(Stage::Session)) } /// Retain one real Context; its Driver borrow must outlive the session. /// This does not qualify any provider or make a full forward available. @@ -81,10 +75,7 @@ impl<'driver> QwenSession<'driver> { Self::for_binding_on_shared_device(binding, Rc::new(context)) } - pub(crate) fn for_binding_on_shared_device( - binding: &ModelBinding, - context: Rc>, - ) -> Self { + pub(crate) fn for_binding_on_shared_device(binding: &ModelBinding, context: Rc>) -> Self { let mut session = Self::for_binding(binding); session.cuda = Some(context); session @@ -133,8 +124,7 @@ impl<'driver> QwenSession<'driver> { binding: &BindingIdentity, execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, ) -> Result { - self.transact_completion(token, position, binding, |txn| execute(txn).map(Some))? - .ok_or(Error::IdentityMismatch) + self.transact_completion(token, position, binding, |txn| execute(txn).map(Some))?.ok_or(Error::IdentityMismatch) } /// Private completion seam; None requires a genuine finish_prefill producer. @@ -191,8 +181,10 @@ impl<'driver> QwenSession<'driver> { self.qsa_owner = QsaOwner::new(); self.qsa_states = std::array::from_fn(|_| None); self.state_lag = None; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - {self.resident_qsa_states=std::array::from_fn(|_|None);} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + { + self.resident_qsa_states = std::array::from_fn(|_| None); + } self.cuda_failed = false; Ok(()) } @@ -221,8 +213,8 @@ impl QwenSession<'_> { qsa_owner: QsaOwner::new(), qsa_states: std::array::from_fn(|_| None), state_lag: None, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - resident_qsa_states: std::array::from_fn(|_|None), + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + resident_qsa_states: std::array::from_fn(|_| None), } } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs index 93682eb0..afa0d2ae 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'driver> QwenStepTxn<'_, 'driver> { pub(in super::super::super) fn token(&self) -> TokenId { self.token @@ -42,10 +40,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { if self.session.cuda_failed { return Err(Error::CudaExecution); } - self.session - .cuda - .as_deref() - .ok_or(Error::Unsupported(Stage::Session)) + self.session.cuda.as_deref().ok_or(Error::Unsupported(Stage::Session)) } /// Validate the complete bounded identities before any input artifact row @@ -84,10 +79,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { pub(in super::super::super) fn input(&self) -> Result> { self.check_owner()?; - self.input - .as_ref() - .map(Rc::clone) - .ok_or(Error::Unsupported(Stage::Input)) + self.input.as_ref().map(Rc::clone).ok_or(Error::Unsupported(Stage::Input)) } pub(in super::super) fn ple_layer(&self) -> Result { @@ -107,9 +99,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { if self.ple_prior.is_none() { let prior = match &self.session.ple_state { Some(prior) => prior.clone(), - None if self.position.get() == 0 => { - PlePrior::zero(self.binding.clone(), &self.session.ple_owner)? - } + None if self.position.get() == 0 => PlePrior::zero(self.binding.clone(), &self.session.ple_owner)?, None => return Err(Error::IdentityMismatch), }; prior.validate(&self.binding, &self.session.ple_owner, self.position)?; @@ -123,11 +113,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { self.validate_binding(&self.session.binding)?; self.validate_input(self.token, self.position)?; prior.validate(&self.binding, &self.session.ple_owner, self.position)?; - if !self - .ple_prior - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { + if !self.ple_prior.as_ref().is_some_and(|current| current.same_state(prior)) { return Err(Error::IdentityMismatch); } Ok(()) @@ -135,10 +121,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { pub(in super::super::super) fn stage_ple(&mut self, prior: &PlePrior, pending: PlePending) -> Result<()> { self.validate_ple_prior(prior)?; - pending.validate( - prior, - TokenLayer::new(self.token, self.position, self.ple_layer()?), - )?; + pending.validate(prior, TokenLayer::new(self.token, self.position, self.ple_layer()?))?; if self.ple_pending.is_some() { return Err(Error::IdentityMismatch); } @@ -148,10 +131,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { pub(in super::super) fn gdn_slot(&self, layer: LayerId) -> Result { self.check_owner()?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(self.session.layer_count))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(self.session.layer_count))?)?; let index = layer.get() as usize; if expected != layer || index >= STATE_CAPACITY || !self.session.gdn_layers[index] { return Err(Error::InvalidLayer); @@ -174,20 +154,14 @@ impl<'driver> QwenStepTxn<'_, 'driver> { prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; self.gdn_priors[index] = Some(prior); } - Ok(self.gdn_priors[index] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .clone()) + Ok(self.gdn_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone()) } pub(in super::super::super) fn validate_gdn_prior(&self, prior: &GdnPrior, layer: LayerId) -> Result<()> { let index = self.gdn_slot(layer)?; self.validate_binding(&self.session.binding)?; prior.validate(&self.binding, &self.session.gdn_owner, layer, self.position)?; - if !self.gdn_priors[index] - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { + if !self.gdn_priors[index].as_ref().is_some_and(|current| current.same_state(prior)) { return Err(Error::IdentityMismatch); } Ok(()) @@ -207,10 +181,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { pub(in super::super) fn qsa_slot(&self, layer: LayerId) -> Result { self.check_owner()?; - let expected = LayerId::new( - u64::from(layer.get()), - Dimension::new(u64::from(self.session.layer_count))?, - )?; + let expected = LayerId::new(u64::from(layer.get()), Dimension::new(u64::from(self.session.layer_count))?)?; let index = layer.get() as usize; if expected != layer || index >= STATE_CAPACITY || !self.session.qsa_layers[index] { return Err(Error::InvalidLayer); @@ -218,23 +189,31 @@ impl<'driver> QwenStepTxn<'_, 'driver> { Ok(index) } - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in super::super::super) fn native_qsa_prior(&mut self,layer:LayerId, - kv:&leleka_cuda_driver::QsaPromptKv<'_>)->Result { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in super::super::super) fn native_qsa_prior( + &mut self, + layer: LayerId, + kv: &leleka_cuda_driver::QsaPromptKv<'_>, + ) -> Result { kv.validate_context(self.cuda_context()?).map_err(super::super::super::qsa_index::driver_error)?; - let index=self.qsa_slot(layer)?; - let prior=self.qsa_prior(layer)?; + let index = self.qsa_slot(layer)?; + let prior = self.qsa_prior(layer)?; if !prior.has_native_kv() { // Only the genuine empty current session can create its initial // snapshot from this real KV owner. Existing FP16 state never migrates. - if self.position.get()!=0 || prior.next_position()!=0 - || self.session.qsa_states[index].is_some() || self.qsa_pending[index].is_some() - {return Err(Error::IdentityMismatch);} - self.qsa_priors[index]=Some(QsaIndexPrior::empty_native(self.binding.clone(), - &self.session.qsa_owner,layer,kv)?); + if self.position.get() != 0 + || prior.next_position() != 0 + || self.session.qsa_states[index].is_some() + || self.qsa_pending[index].is_some() + { + return Err(Error::IdentityMismatch); + } + self.qsa_priors[index] = + Some(QsaIndexPrior::empty_native(self.binding.clone(), &self.session.qsa_owner, layer, kv)?); } - let prior=self.qsa_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone(); - self.validate_qsa_prior(&prior,layer)?; - prior.native_snapshot(kv)?;Ok(prior) + let prior = self.qsa_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone(); + self.validate_qsa_prior(&prior, layer)?; + prior.native_snapshot(kv)?; + Ok(prior) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs index 3a522bf7..caee65c8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_qwensteptxn/impl_qwensteptxn_2_2.rs @@ -3,14 +3,13 @@ #[allow(unused_imports)] use super::*; - - impl<'driver> QwenStepTxn<'_, 'driver> { - pub(in super::super::super) fn qsa_prior(&mut self, layer: LayerId) -> Result { let index = self.qsa_slot(layer)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.session.resident_qsa_states[index].is_some() { + return Err(Error::Unsupported(Stage::QsaIndex)); + } self.validate_binding(&self.session.binding)?; self.validate_input(self.token, self.position)?; if self.qsa_priors[index].is_none() { @@ -24,23 +23,19 @@ impl<'driver> QwenStepTxn<'_, 'driver> { prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; self.qsa_priors[index] = Some(prior); } - Ok(self.qsa_priors[index] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .clone()) + Ok(self.qsa_priors[index].as_ref().ok_or(Error::IdentityMismatch)?.clone()) } pub(in super::super::super) fn validate_qsa_prior(&self, prior: &QsaIndexPrior, layer: LayerId) -> Result<()> { let index = self.qsa_slot(layer)?; - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.session.resident_qsa_states[index].is_some(){return Err(Error::Unsupported(Stage::QsaIndex));} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.session.resident_qsa_states[index].is_some() { + return Err(Error::Unsupported(Stage::QsaIndex)); + } self.validate_binding(&self.session.binding)?; self.validate_input(self.token, self.position)?; prior.validate(&self.binding, &self.session.qsa_owner, layer, self.position)?; - if !self.qsa_priors[index] - .as_ref() - .is_some_and(|current| current.same_state(prior)) - { + if !self.qsa_priors[index].as_ref().is_some_and(|current| current.same_state(prior)) { return Err(Error::IdentityMismatch); } Ok(()) @@ -64,10 +59,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { let identity = residual.identity(); residual.validate_origin(&self.binding, GrRole::Ffn(identity.layer().get()))?; self.validate_layer_completion(identity)?; - self.completed_layers = self - .completed_layers - .checked_add(1) - .ok_or(Error::Overflow)?; + self.completed_layers = self.completed_layers.checked_add(1).ok_or(Error::Overflow)?; Ok(()) } @@ -76,10 +68,8 @@ impl<'driver> QwenStepTxn<'_, 'driver> { if self.forward_output.is_some() || identity.layer().get() != self.completed_layers { return Err(Error::IdentityMismatch); } - let layer = LayerId::new( - u64::from(self.completed_layers), - Dimension::new(u64::from(self.session.layer_count))?, - )?; + let layer = + LayerId::new(u64::from(self.completed_layers), Dimension::new(u64::from(self.session.layer_count))?)?; if layer != identity.layer() { return Err(Error::IdentityMismatch); } @@ -115,9 +105,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { residual.validate_origin(&self.binding, GrRole::Ffn(self.session.layer_count - 1))?; let identity = residual.identity(); self.validate_input(identity.token(), identity.position())?; - if identity.layer().get() != self.session.layer_count - 1 - || residual.streams().len() != 10240 - { + if identity.layer().get() != self.session.layer_count - 1 || residual.streams().len() != 10240 { return Err(Error::IdentityMismatch); } if residual.streams().iter().any(|value| !value.is_finite()) { @@ -141,10 +129,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { let next_position = self.position.get().checked_add(1).ok_or(Error::Overflow)?; let token = i32::try_from(self.token.get()).map_err(|_| Error::InvalidToken)?; let next_ple = if self.session.ple_required { - let next = self - .ple_pending - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); + let next = self.ple_pending.ok_or(Error::Unsupported(Stage::Input))?.into_prior(); if next.next_position() != next_position { return Err(Error::IdentityMismatch); } @@ -170,9 +155,7 @@ impl<'driver> QwenStepTxn<'_, 'driver> { let mut next_qsa = self.session.qsa_states.clone(); for (index, pending) in self.qsa_pending.into_iter().enumerate() { if self.session.qsa_layers[index] { - let next = pending - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .into_prior(); + let next = pending.ok_or(Error::Unsupported(Stage::QsaIndex))?.into_prior(); if next.layer().get() as usize != index || next.next_position() != next_position { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_resetreplaysnapshot.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_resetreplaysnapshot.rs index 5264d4d1..7f85d1c3 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_resetreplaysnapshot.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/impl_resetreplaysnapshot.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl ResetReplaySnapshot { pub(crate) fn has_prefix(&self, next_position: u64, predecessors: [i32; 2]) -> bool { @@ -24,24 +23,16 @@ impl ResetReplaySnapshot { && self.gdn_layers == other.gdn_layers && self.qsa_layers == other.qsa_layers && ple_equal - && self - .gdn - .iter() - .zip(other.gdn.iter()) - .all(|(a, b)| match (a, b) { - (None, None) => true, - (Some(a), Some(b)) => a.test_reset_replay_numeric_eq(b), - _ => false, - }) - && self - .qsa - .iter() - .zip(other.qsa.iter()) - .all(|(a, b)| match (a, b) { - (None, None) => true, - (Some(a), Some(b)) => a.test_reset_replay_numeric_eq(b), - _ => false, - }) + && self.gdn.iter().zip(other.gdn.iter()).all(|(a, b)| match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.test_reset_replay_numeric_eq(b), + _ => false, + }) + && self.qsa.iter().zip(other.qsa.iter()).all(|(a, b)| match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.test_reset_replay_numeric_eq(b), + _ => false, + }) } // Charge complete arrays even where immutable pages are physically shared. @@ -62,23 +53,14 @@ impl ResetReplaySnapshot { #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl QwenSession<'_> { - pub(in super::super) fn oracle_capture_committed( - &self, - binding: &ModelBinding, - position: u64, - ) -> Result<()> { + pub(in super::super) fn oracle_capture_committed(&self, binding: &ModelBinding, position: u64) -> Result<()> { let s = self.test_reset_replay_snapshot(binding)?; let prior = if position == 0 { [-1, 0] } else { [0, 1] }; - if position > 1 - || !s.has_prefix(position + 1, prior) - || s.layer_count != 48 - || !s.ple_required - { + if position > 1 || !s.has_prefix(position + 1, prior) || s.layer_count != 48 || !s.ple_required { return Err(Error::IdentityMismatch); } let mut gdn = Vec::new(); - gdn.try_reserve_exact(36 * (786432 + 30720)) - .map_err(|_| Error::InputAllocation)?; + gdn.try_reserve_exact(36 * (786432 + 30720)).map_err(|_| Error::InputAllocation)?; let mut tails = Vec::new(); let mut dead = Vec::new(); let mut blocks = Vec::new(); @@ -119,10 +101,7 @@ impl QwenSession<'_> { super::super::oracle_capture::file_f32("gdn_recurrence_conv.f32", &gdn)?; super::super::oracle_capture::file_f32( "ple_history.f32", - s.ple - .as_ref() - .ok_or(Error::IdentityMismatch)? - .oracle_history(), + s.ple.as_ref().ok_or(Error::IdentityMismatch)?.oracle_history(), )?; super::super::oracle_capture::file_f32("qsa_tail.f32", &tails)?; super::super::oracle_capture::file_f32("qsa_dead.f32", &dead)?; @@ -131,24 +110,15 @@ impl QwenSession<'_> { let tokens: [i32; 2] = [0, 1]; super::super::oracle_capture::file_bytes( "tokens.i32", - &tokens[..(position + 1) as usize] - .iter() - .flat_map(|x| x.to_le_bytes()) - .collect::>(), + &tokens[..(position + 1) as usize].iter().flat_map(|x| x.to_le_bytes()).collect::>(), )?; super::super::oracle_capture::file_bytes( "ple_prev.i32", - &s.predecessors - .iter() - .flat_map(|x| x.to_le_bytes()) - .collect::>(), + &s.predecessors.iter().flat_map(|x| x.to_le_bytes()).collect::>(), )?; Ok(()) } - pub(crate) fn test_reset_replay_snapshot( - &self, - binding: &ModelBinding, - ) -> Result { + pub(crate) fn test_reset_replay_snapshot(&self, binding: &ModelBinding) -> Result { if self.owner_thread != std::thread::current().id() || !self.binding.matches(&binding.identity()) || self.layer_count != binding.layer_count() @@ -158,10 +128,8 @@ impl QwenSession<'_> { if self.cuda_failed { return Err(Error::CudaExecution); } - let position = Position::new( - self.next_position, - Dimension::new(u64::from(binding.input_constants().context_length()))?, - )?; + let position = + Position::new(self.next_position, Dimension::new(u64::from(binding.input_constants().context_length()))?)?; let layers = Dimension::new(u64::from(self.layer_count))?; match &self.ple_state { Some(state) if self.ple_required && self.next_position > 0 => { @@ -173,24 +141,14 @@ impl QwenSession<'_> { for index in 0..STATE_CAPACITY { match &self.gdn_states[index] { Some(state) if self.gdn_layers[index] && self.next_position > 0 => { - state.validate( - &self.binding, - &self.gdn_owner, - LayerId::new(index as u64, layers)?, - position, - )?; + state.validate(&self.binding, &self.gdn_owner, LayerId::new(index as u64, layers)?, position)?; } None if self.next_position == 0 || !self.gdn_layers[index] => {} _ => return Err(Error::IdentityMismatch), } match &self.qsa_states[index] { Some(state) if self.qsa_layers[index] && self.next_position > 0 => { - state.validate( - &self.binding, - &self.qsa_owner, - LayerId::new(index as u64, layers)?, - position, - )?; + state.validate(&self.binding, &self.qsa_owner, LayerId::new(index as u64, layers)?, position)?; } None if self.next_position == 0 || !self.qsa_layers[index] => {} _ => return Err(Error::IdentityMismatch), diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs index 35c4490a..d3837504 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests.rs @@ -12,7 +12,7 @@ fn position(value: u64) -> Position { Position::new(value, crate::qwen_forward::contract::position_dimension()).unwrap() } -#[path = "tests/retained_gr_handoff_identity.rs"] -mod retained_gr_handoff_identity; #[path = "tests/gdn_session_commit_advances_all.rs"] mod gdn_session_commit_advances_all; +#[path = "tests/retained_gr_handoff_identity.rs"] +mod retained_gr_handoff_identity; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/gdn_session_commit_advances_all.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/gdn_session_commit_advances_all.rs index c859d930..74334d65 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/gdn_session_commit_advances_all.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/gdn_session_commit_advances_all.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner() { let binding = BindingIdentity::test_identity(); @@ -13,14 +12,9 @@ fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner() let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); session .transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; let prior = txn.gdn_prior(layer)?; - let pending = - GdnPending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?; + let pending = GdnPending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?; txn.stage_gdn(&prior, pending)?; // Synthetic completion markers isolate recurrent publication; // this test does not execute layers or produce model logits. @@ -31,27 +25,13 @@ fn gdn_session_commit_advances_all_state_once_and_failed_reset_preserves_owner() .unwrap(); let committed = session.gdn_states[0].as_ref().unwrap().clone(); assert_eq!((session.next_position, committed.next_position()), (1, 1)); - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); - assert!( - session.gdn_states[0] - .as_ref() - .unwrap() - .same_state(&committed) - ); - assert_eq!( - committed.validate(&binding, &session.gdn_owner, layer, position(1)), - Ok(()) - ); + assert_eq!(session.reset_after_completion(Err(Error::CudaExecution)), Err(Error::CudaExecution)); + assert!(session.gdn_states[0].as_ref().unwrap().same_state(&committed)); + assert_eq!(committed.validate(&binding, &session.gdn_owner, layer, position(1)), Ok(())); session.reset().unwrap(); assert!(session.gdn_states[0].is_none()); assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - committed.validate(&binding, &session.gdn_owner, layer, position(1)), - Err(Error::IdentityMismatch) - ); + assert_eq!(committed.validate(&binding, &session.gdn_owner, layer, position(1)), Err(Error::IdentityMismatch)); } #[test] @@ -66,11 +46,7 @@ fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_t session.layer_count = 1; assert_eq!( session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; txn.completed_layers = completed; txn.forward_output = proved_output; Ok(token(4)) @@ -83,33 +59,20 @@ fn full_forward_guard_refuses_skipped_layers_missing_logits_and_wrong_callback_t session.layer_count = 2; let mut txn = session.begin(token(3), position(0)).unwrap(); let bound = Dimension::new(2).unwrap(); - let identity = - |layer| TokenLayer::new(token(3), position(0), LayerId::new(layer, bound).unwrap()); - assert_eq!( - txn.validate_layer_completion(identity(1)), - Err(Error::IdentityMismatch) - ); + let identity = |layer| TokenLayer::new(token(3), position(0), LayerId::new(layer, bound).unwrap()); + assert_eq!(txn.validate_layer_completion(identity(1)), Err(Error::IdentityMismatch)); assert_eq!(txn.validate_layer_completion(identity(0)), Ok(())); txn.completed_layers = 1; - assert_eq!( - txn.validate_layer_completion(identity(0)), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_layer_completion(identity(0)), Err(Error::IdentityMismatch)); txn.forward_output = Some(token(4)); - assert_eq!( - txn.validate_layer_completion(identity(1)), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_layer_completion(identity(1)), Err(Error::IdentityMismatch)); } #[test] fn context_seam_missing_owner_refuses_after_identity_checks() { let mut session = QwenSession::test_session(BindingIdentity::test_identity()); let mut txn = session.begin(token(1), position(0)).unwrap(); - assert_eq!( - txn.cuda_context().err(), - Some(Error::Unsupported(Stage::Session)) - ); + assert_eq!(txn.cuda_context().err(), Some(Error::Unsupported(Stage::Session))); txn.binding = BindingIdentity::test_identity(); assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); } @@ -118,9 +81,7 @@ fn context_seam_missing_owner_refuses_after_identity_checks() { fn context_seam_wrong_thread_refuses_before_backend_access() { let mut session = QwenSession::test_session(BindingIdentity::test_identity()); let mut txn = session.begin(token(1), position(0)).unwrap(); - txn.owner_thread = std::thread::spawn(|| std::thread::current().id()) - .join() - .unwrap(); + txn.owner_thread = std::thread::spawn(|| std::thread::current().id()).join().unwrap(); assert_eq!(txn.cuda_context().err(), Some(Error::IdentityMismatch)); } @@ -131,10 +92,7 @@ fn context_seam_failed_reset_keeps_committed_snapshot() { session.next_position = 2; session.cuda_failed = true; let owner = Rc::clone(&session.owner); - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); + assert_eq!(session.reset_after_completion(Err(Error::CudaExecution)), Err(Error::CudaExecution)); assert_eq!(session.predecessors, [17, 21]); assert_eq!(session.next_position, 2); assert!(Rc::ptr_eq(&owner, &session.owner)); @@ -151,17 +109,12 @@ fn context_seam_cuda_failure_blocks_new_steps_without_committing() { let identity = BindingIdentity::test_identity(); let mut session = QwenSession::test_session(identity.clone()); assert_eq!( - session.transact(token(1), position(0), &identity, |_| Err( - Error::CudaExecution - )), + session.transact(token(1), position(0), &identity, |_| Err(Error::CudaExecution)), Err(Error::CudaExecution) ); assert_eq!(session.predecessors, [-1, -1]); assert_eq!(session.next_position, 0); - assert_eq!( - session.begin(token(1), position(0)).err(), - Some(Error::CudaExecution) - ); + assert_eq!(session.begin(token(1), position(0)).err(), Some(Error::CudaExecution)); // Contextless fixtures exercise only the local state guard. A real // device-backed reset additionally requires Context::synchronize. session.reset().unwrap(); @@ -176,11 +129,7 @@ fn committed_predecessors_advance_oldest_first_and_reset() { let output = session .transact(token(17), position(0), &identity, |txn| { assert_eq!(txn.input_predecessors()?, [-1, -1]); - txn.stage_input(InputReady::test_fixture( - token(17), - position(0), - identity.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(17), position(0), identity.clone()))?; Ok(token(18)) }) .unwrap(); @@ -189,11 +138,7 @@ fn committed_predecessors_advance_oldest_first_and_reset() { session .transact(token(21), position(1), &identity, |txn| { assert_eq!(txn.input_predecessors()?, [-1, 17]); - txn.stage_input(InputReady::test_fixture( - token(21), - position(1), - identity.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(21), position(1), identity.clone()))?; Ok(token(22)) }) .unwrap(); @@ -213,10 +158,7 @@ fn failed_or_dropped_transaction_does_not_advance_committed_state() { let other = BindingIdentity::test_identity(); let mut session = QwenSession::test_session(identity.clone()); - assert_eq!( - session.transact(token(3), position(0), &other, |_| Ok(token(8))), - Err(Error::IdentityMismatch) - ); + assert_eq!(session.transact(token(3), position(0), &other, |_| Ok(token(8))), Err(Error::IdentityMismatch)); assert_eq!( session.transact(token(3), position(0), &identity, |txn| { assert_eq!(txn.input_predecessors()?, [-1, -1]); @@ -226,9 +168,7 @@ fn failed_or_dropped_transaction_does_not_advance_committed_state() { Err(Error::IdentityMismatch) ); assert_eq!( - session.transact(token(3), position(0), &identity, |_txn| { - Err(Error::Unsupported(Stage::Input)) - }), + session.transact(token(3), position(0), &identity, |_txn| { Err(Error::Unsupported(Stage::Input)) }), Err(Error::Unsupported(Stage::Input)) ); @@ -240,27 +180,14 @@ fn failed_or_dropped_transaction_does_not_advance_committed_state() { #[test] fn begin_rejects_skips_and_repeats_before_mutation() { let mut session = QwenSession::test_session(BindingIdentity::test_identity()); - assert_eq!( - session.begin(token(1), position(1)).err(), - Some(Error::InvalidPosition) - ); + assert_eq!(session.begin(token(1), position(1)).err(), Some(Error::InvalidPosition)); let binding = session.binding.clone(); session .transact(token(1), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(1), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(1), position(0), binding.clone()))?; Ok(token(2)) }) .unwrap(); - assert_eq!( - session.begin(token(1), position(0)).err(), - Some(Error::InvalidPosition) - ); - assert_eq!( - session.begin(token(2), position(1)).unwrap().token(), - token(2) - ); + assert_eq!(session.begin(token(1), position(0)).err(), Some(Error::InvalidPosition)); + assert_eq!(session.begin(token(2), position(1)).unwrap().token(), token(2)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/retained_gr_handoff_identity.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/retained_gr_handoff_identity.rs index 6a63c46f..3872ed07 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/retained_gr_handoff_identity.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session/tests/retained_gr_handoff_identity.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin() { // Actual contextless begin/abort state; no fabricated device producer. @@ -19,10 +18,7 @@ fn retained_gr_handoff_identity_is_lazy_and_refuses_same_position_rebegin() { assert!(Rc::ptr_eq(&session_owner, &session.owner)); let second = session.begin(token(1), position(0)).unwrap(); assert!(second.residual_handoff.get().is_none()); - assert!(!Rc::ptr_eq( - &first_owner, - &second.residual_handoff_owner().unwrap() - )); + assert!(!Rc::ptr_eq(&first_owner, &second.residual_handoff_owner().unwrap())); } #[test] @@ -31,11 +27,7 @@ fn headfree_prefill_refuses_metadata_completion_without_actual_final_producer() let mut session = QwenSession::test_session(binding.clone()); session.layer_count = 48; let result = session.transact_completion(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; // Synthetic count is only a refusal fixture; it cannot certify prefill. txn.completed_layers = 48; Ok(None) @@ -49,11 +41,7 @@ fn headfree_prefill_refuses_zero_layer_fixture_and_preserves_history() { let binding = BindingIdentity::test_identity(); let mut session = QwenSession::test_session(binding.clone()); let result = session.transact_completion(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; Ok(None) }); assert_eq!(result, Err(Error::Unsupported(Stage::Executor))); @@ -72,10 +60,7 @@ fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() { let prior = txn.qsa_prior(layer).unwrap(); assert!(txn.qsa_prior(layer).unwrap().same_state(&prior)); let foreign = QsaIndexPrior::empty(binding.clone(), &QsaOwner::new(), layer).unwrap(); - assert_eq!( - txn.validate_qsa_prior(&foreign, layer), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_qsa_prior(&foreign, layer), Err(Error::IdentityMismatch)); assert_eq!(txn.validate_qsa_prior(&prior, layer), Ok(())); let gdn_layer = LayerId::new(0, Dimension::new(4).unwrap()).unwrap(); assert!(matches!(txn.qsa_prior(gdn_layer), Err(Error::InvalidLayer))); @@ -84,11 +69,7 @@ fn qsa_session_prior_is_private_and_required_state_cannot_be_skipped() { assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); assert_eq!( session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; // Completion markers isolate the state gate, not model math. txn.completed_layers = 4; txn.forward_output = Some(token(4)); @@ -107,19 +88,12 @@ fn qsa_session_reset_invalidates_old_generation_even_at_position_zero() { session.layer_count = 4; session.qsa_layers[3] = true; let layer = LayerId::new(3, Dimension::new(4).unwrap()).unwrap(); - let prior = session - .begin(token(3), position(0)) - .unwrap() - .qsa_prior(layer) - .unwrap(); + let prior = session.begin(token(3), position(0)).unwrap().qsa_prior(layer).unwrap(); session.reset().unwrap(); let mut txn = session.begin(token(3), position(0)).unwrap(); let fresh = txn.qsa_prior(layer).unwrap(); assert!(!fresh.same_state(&prior)); - assert_eq!( - txn.validate_qsa_prior(&prior, layer), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_qsa_prior(&prior, layer), Err(Error::IdentityMismatch)); assert_eq!(txn.validate_qsa_prior(&fresh, layer), Ok(())); } @@ -132,23 +106,13 @@ fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() { let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); let identity = TokenLayer::new(token(3), position(0), layer); let result = session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; let prior = txn.ple_prior()?; let foreign = PlePrior::zero(binding.clone(), &PleOwner::new())?; - assert_eq!( - txn.validate_ple_prior(&foreign), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_ple_prior(&foreign), Err(Error::IdentityMismatch)); let pending = PlePending::test_next(&prior, &identity)?; txn.stage_ple(&prior, pending)?; - assert_eq!( - txn.stage_ple(&prior, PlePending::test_next(&prior, &identity)?), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.stage_ple(&prior, PlePending::test_next(&prior, &identity)?), Err(Error::IdentityMismatch)); Err(Error::NonFinite) }); assert_eq!(result, Err(Error::NonFinite)); @@ -156,11 +120,7 @@ fn ple_session_candidate_is_not_published_on_late_failure_or_missing_history() { assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); assert_eq!( session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; // Isolate the required PLE publication gate from full-model math. txn.completed_layers = 2; txn.forward_output = Some(token(4)); @@ -181,16 +141,9 @@ fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() { let layer = LayerId::new(1, Dimension::new(2).unwrap()).unwrap(); session .transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; let prior = txn.ple_prior()?; - txn.stage_ple( - &prior, - PlePending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?, - )?; + txn.stage_ple(&prior, PlePending::test_next(&prior, &TokenLayer::new(token(3), position(0), layer))?)?; // Synthetic markers test state publication, not actual model logits. txn.completed_layers = 2; txn.forward_output = Some(token(4)); @@ -203,22 +156,13 @@ fn ple_session_commit_and_reset_preserve_exact_owner_and_prior_identity() { let mut txn = session.begin(token(4), position(1)).unwrap(); assert!(txn.ple_prior().unwrap().same_state(&committed)); } - assert_eq!( - session.reset_after_completion(Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); + assert_eq!(session.reset_after_completion(Err(Error::CudaExecution)), Err(Error::CudaExecution)); assert!(session.ple_state.as_ref().unwrap().same_state(&committed)); - assert_eq!( - committed.validate(&binding, &session.ple_owner, position(1)), - Ok(()) - ); + assert_eq!(committed.validate(&binding, &session.ple_owner, position(1)), Ok(())); session.reset().unwrap(); assert!(session.ple_state.is_none()); assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert_eq!( - committed.validate(&binding, &session.ple_owner, position(1)), - Err(Error::IdentityMismatch) - ); + assert_eq!(committed.validate(&binding, &session.ple_owner, position(1)), Err(Error::IdentityMismatch)); } #[test] @@ -230,24 +174,14 @@ fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_ski let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); let identity = TokenLayer::new(token(3), position(0), layer); let result = session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; let prior = txn.gdn_prior(layer)?; let foreign = GdnPrior::zero(binding.clone(), &GdnOwner::new(), layer)?; - assert_eq!( - txn.validate_gdn_prior(&foreign, layer), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.validate_gdn_prior(&foreign, layer), Err(Error::IdentityMismatch)); let pending = GdnPending::test_next(&prior, &identity)?; txn.stage_gdn(&prior, pending)?; let duplicate = GdnPending::test_next(&prior, &identity)?; - assert_eq!( - txn.stage_gdn(&prior, duplicate), - Err(Error::IdentityMismatch) - ); + assert_eq!(txn.stage_gdn(&prior, duplicate), Err(Error::IdentityMismatch)); Err(Error::NonFinite) }); assert_eq!(result, Err(Error::NonFinite)); @@ -255,11 +189,7 @@ fn gdn_session_late_failure_discards_candidates_and_required_state_cannot_be_ski assert!(session.gdn_states[0].is_none()); assert_eq!( session.transact(token(3), position(0), &binding, |txn| { - txn.stage_input(InputReady::test_fixture( - token(3), - position(0), - binding.clone(), - ))?; + txn.stage_input(InputReady::test_fixture(token(3), position(0), binding.clone()))?; Ok(token(4)) }), Err(Error::Unsupported(Stage::Gdn)) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_checkpoint.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_checkpoint.rs index 837af77a..1aa87178 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_checkpoint.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_checkpoint.rs @@ -14,11 +14,11 @@ pub(in crate::qwen_forward) struct TargetStepOrigin { next_position: u64, } impl TargetStepOrigin { - pub(in crate::qwen_forward) fn next_position(&self) -> u64 { self.next_position } + pub(in crate::qwen_forward) fn next_position(&self) -> u64 { + self.next_position + } pub(in crate::qwen_forward) fn same_prefix(&self, other: &Self) -> bool { - self.same_session(other) - && self.generation == other.generation - && self.next_position == other.next_position + self.same_session(other) && self.generation == other.generation && self.next_position == other.next_position } pub(in crate::qwen_forward) fn same_session(&self, other: &Self) -> bool { self.binding.matches(&other.binding) && Rc::ptr_eq(&self.owner, &other.owner) @@ -110,8 +110,10 @@ impl QwenSession<'_> { /// recurrence, complete QSA pages/index pool/tail/dead block, and PLE. /// Callers retain at most the accepted prefix plus four draft checkpoints. pub(in crate::qwen_forward) fn checkpoint(&mut self) -> Result { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.resident_qsa_states.iter().any(Option::is_some){return Err(Error::Unsupported(super::Stage::Session));} + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.resident_qsa_states.iter().any(Option::is_some) { + return Err(Error::Unsupported(super::Stage::Session)); + } if self.owner_thread != std::thread::current().id() { return Err(Error::IdentityMismatch); } @@ -133,12 +135,11 @@ impl QwenSession<'_> { /// Restore the entire accepted target prefix only after device completion. /// Device failure is sticky even when the checkpoint predates the failure. - pub(in crate::qwen_forward) fn restore_checkpoint( - &mut self, - prior: &SessionCheckpoint, - ) -> Result<()> { - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - if self.resident_qsa_states.iter().any(Option::is_some){return Err(Error::Unsupported(super::Stage::Session));} + pub(in crate::qwen_forward) fn restore_checkpoint(&mut self, prior: &SessionCheckpoint) -> Result<()> { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + if self.resident_qsa_states.iter().any(Option::is_some) { + return Err(Error::Unsupported(super::Stage::Session)); + } if self.owner_thread != std::thread::current().id() || !self.binding.matches(&prior.binding) || !Rc::ptr_eq(&self.owner, &prior.owner) @@ -150,10 +151,7 @@ impl QwenSession<'_> { if self.cuda_failed { return Err(Error::CudaExecution); } - let generation = self - .checkpoint_generation - .checked_add(1) - .ok_or(Error::Overflow)?; + let generation = self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; self.complete_cuda()?; // Fence every capability from the rejected branch before publication. // The next window must snapshot the restored accepted prefix anew. @@ -179,10 +177,8 @@ mod tests { let gdn_layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); let qsa_layer = LayerId::new(3, Dimension::new(48).unwrap()).unwrap(); session.ple_state = Some(PlePrior::zero(identity.clone(), &session.ple_owner).unwrap()); - session.gdn_states[0] = - Some(GdnPrior::zero(identity.clone(), &session.gdn_owner, gdn_layer).unwrap()); - session.qsa_states[3] = - Some(QsaIndexPrior::empty(identity, &session.qsa_owner, qsa_layer).unwrap()); + session.gdn_states[0] = Some(GdnPrior::zero(identity.clone(), &session.gdn_owner, gdn_layer).unwrap()); + session.qsa_states[3] = Some(QsaIndexPrior::empty(identity, &session.qsa_owner, qsa_layer).unwrap()); let snapshot = session.checkpoint().unwrap(); // This mutates actual session fields, not a duplicate checkpoint model. // Numerical stage candidates themselves are covered by their own tests. @@ -193,25 +189,9 @@ mod tests { session.qsa_states[3] = None; session.restore_checkpoint(&snapshot).unwrap(); assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); - assert!( - session - .ple_state - .as_ref() - .unwrap() - .same_state(snapshot.ple.as_ref().unwrap()) - ); - assert!( - session.gdn_states[0] - .as_ref() - .unwrap() - .same_state(snapshot.gdn[0].as_ref().unwrap()) - ); - assert!( - session.qsa_states[3] - .as_ref() - .unwrap() - .same_state(snapshot.qsa[3].as_ref().unwrap()) - ); + assert!(session.ple_state.as_ref().unwrap().same_state(snapshot.ple.as_ref().unwrap())); + assert!(session.gdn_states[0].as_ref().unwrap().same_state(snapshot.gdn[0].as_ref().unwrap())); + assert!(session.qsa_states[3].as_ref().unwrap().same_state(snapshot.qsa[3].as_ref().unwrap())); } #[test] @@ -220,22 +200,13 @@ mod tests { let mut session = QwenSession::test_session(identity.clone()); let snapshot = session.checkpoint().unwrap(); session.cuda_failed = true; - assert_eq!( - session.restore_checkpoint(&snapshot), - Err(Error::CudaExecution) - ); + assert_eq!(session.restore_checkpoint(&snapshot), Err(Error::CudaExecution)); assert!(session.cuda_failed); session.cuda_failed = false; // synthetic test repair, never production recovery session.reset().unwrap(); - assert_eq!( - session.restore_checkpoint(&snapshot), - Err(Error::IdentityMismatch) - ); + assert_eq!(session.restore_checkpoint(&snapshot), Err(Error::IdentityMismatch)); let mut other = QwenSession::test_session(identity); - assert_eq!( - other.restore_checkpoint(&snapshot), - Err(Error::IdentityMismatch) - ); + assert_eq!(other.restore_checkpoint(&snapshot), Err(Error::IdentityMismatch)); } #[test] @@ -250,10 +221,7 @@ mod tests { let new_prefix = session.checkpoint().unwrap(); session.next_position = 4; session.predecessors = [12, 13]; - assert_eq!( - session.restore_checkpoint(&rejected_tail), - Err(Error::IdentityMismatch) - ); + assert_eq!(session.restore_checkpoint(&rejected_tail), Err(Error::IdentityMismatch)); assert_eq!((session.next_position, session.predecessors), (4, [12, 13])); session.restore_checkpoint(&new_prefix).unwrap(); assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk.rs index 75d05032..9bb8f7d5 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk.rs @@ -191,13 +191,7 @@ mod refusal_tests { session, origin, chunk: Rc::new(()), - rows: vec![Row { - token: token(3), - position, - predecessors: [-1, -1], - input: None, - completed: 0, - }], + rows: vec![Row { token: token(3), position, predecessors: [-1, -1], input: None, completed: 0 }], witnesses: Vec::new(), next_layer: 0, next_row: 0, @@ -266,10 +260,7 @@ mod refusal_tests { // producer or numerical warm witness is fabricated by this fixture. txn.rows[0].completed = 48; txn.next_layer = 48; - assert_eq!( - txn.finish(&[None], |_, _| panic!("head must not run")), - Err(Error::Unsupported(Stage::Executor)) - ); + assert_eq!(txn.finish(&[None], |_, _| panic!("head must not run")), Err(Error::Unsupported(Stage::Executor))); assert!(txn.rows().is_empty()); assert_eq!(txn.check(), Err(Error::Unsupported(Stage::Session))); struct UnreachableDraft; @@ -281,10 +272,7 @@ mod refusal_tests { panic!("draft must not publish") } } - assert!(matches!( - txn.publish_joint(UnreachableDraft), - Err(Error::Unsupported(Stage::Session)) - )); + assert!(matches!(txn.publish_joint(UnreachableDraft), Err(Error::Unsupported(Stage::Session)))); assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); } #[test] @@ -293,14 +281,8 @@ mod refusal_tests { { let mut txn = fixture(&mut session); let wrong = LayerId::new(1, Dimension::new(48).unwrap()).unwrap(); - assert!(matches!( - txn.layer(0, wrong, |_| panic!("wrong layer executed")), - Err(Error::IdentityMismatch) - )); - assert_eq!( - txn.input(0, |_| Err(Error::CudaExecution)), - Err(Error::CudaExecution) - ); + assert!(matches!(txn.layer(0, wrong, |_| panic!("wrong layer executed")), Err(Error::IdentityMismatch))); + assert_eq!(txn.input(0, |_| Err(Error::CudaExecution)), Err(Error::CudaExecution)); assert_eq!(txn.check(), Err(Error::CudaExecution)); } assert_eq!((session.next_position, session.predecessors), (0, [-1, -1])); @@ -314,9 +296,7 @@ mod refusal_tests { let mut txn = fixture(&mut session); let layer = LayerId::new(0, Dimension::new(48).unwrap()).unwrap(); assert!(matches!( - txn.prepare_layer_batch(1, layer, |_| -> Result<()> { - panic!("wrong row executes") - }), + txn.prepare_layer_batch(1, layer, |_| -> Result<()> { panic!("wrong row executes") }), Err(Error::IdentityMismatch) )); assert!(matches!( @@ -326,10 +306,7 @@ mod refusal_tests { // A synthetic phase flag is a negative challenge only, never a // fabricated actual pending producer or completed residual. txn.batch_layer = Some(layer); - assert!(matches!( - txn.layer(0, layer, |_| panic!("mixed scalar completes")), - Err(Error::IdentityMismatch) - )); + assert!(matches!(txn.layer(0, layer, |_| panic!("mixed scalar completes")), Err(Error::IdentityMismatch))); txn.next_row = 1; txn.batch_rows = vec![None]; assert!(matches!( @@ -353,11 +330,11 @@ pub(in crate::qwen_forward) struct TestGdnComponentRows { #[path = "session_chunk/impl_gdnchunkstart.rs"] mod impl_gdnchunkstart; +#[allow(unused_imports)] +use impl_gdnchunkstart::host_charge; #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[allow(unused_imports)] use impl_gdnchunkstart::same_window_proof; -#[allow(unused_imports)] -use impl_gdnchunkstart::host_charge; #[path = "session_chunk/host_charge_bounded_fn.rs"] mod host_charge_bounded_fn; #[allow(unused_imports)] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/host_charge_bounded_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/host_charge_bounded_fn.rs index dc5a1d92..72f3370d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/host_charge_bounded_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/host_charge_bounded_fn.rs @@ -10,13 +10,10 @@ pub(super) fn host_charge_bounded(tokens: usize, end: u64, limit: usize) -> Resu let rolling: usize = 36 * (786432 + 30720) * 4 + 9 * 10240 * 4; // Actual detached GR host rows plus conservative simultaneous Q6 // output/readback/copy and input packing admission, separate from FFN. - let attention = tokens - .checked_mul((10240 + 2560 + 4 + 3 * (12288 + 512 + 512) + 2560) * 4 + 2048) - .ok_or(Error::Overflow)?; + let attention = + tokens.checked_mul((10240 + 2560 + 4 + 3 * (12288 + 512 + 512) + 2560) * 4 + 2048).ok_or(Error::Overflow)?; let columns = tokens - .checked_mul( - (10240 * 4 * 3) + 16 * 2560 * 4 + 8192 + (10240 + 2560 + 4) * 4 + 10 * 640 * 4 * 3, - ) + .checked_mul((10240 * 4 * 3) + 16 * 2560 * 4 + 8192 + (10240 + 2560 + 4) * 4 + 10 * 640 * 4 * 3) .ok_or(Error::Overflow)?; let metadata = usize::try_from(end) .map_err(|_| Error::Overflow)? diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_gdnchunkstart.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_gdnchunkstart.rs index 05724027..85f8c9c2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_gdnchunkstart.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_gdnchunkstart.rs @@ -7,14 +7,13 @@ impl GdnChunkStart { pub(in crate::qwen_forward) fn prior(&self) -> &GdnPrior { &self.0.prior } - pub(in crate::qwen_forward) fn count(&self) -> usize { self.0.count } + pub(in crate::qwen_forward) fn count(&self) -> usize { + self.0.count + } pub(in crate::qwen_forward) fn binding(&self) -> BindingIdentity { self.0.binding.clone() } - pub(in crate::qwen_forward) fn validate_binding( - &self, - binding: &BindingIdentity, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate_binding(&self, binding: &BindingIdentity) -> Result<()> { if !self.0.binding.matches(binding) || !(1..=8192).contains(&self.0.count) || self.0.prior.next_position() != self.0.first.get() @@ -27,18 +26,16 @@ impl GdnChunkStart { } } impl GdnChunkRow { - pub(in crate::qwen_forward) fn ordinal(&self) -> usize { self.index } + pub(in crate::qwen_forward) fn ordinal(&self) -> usize { + self.index + } pub(in crate::qwen_forward) fn identity(&self) -> TokenLayer { self.identity } pub(in crate::qwen_forward) fn readout_key(&self) -> Rc<()> { self.key.clone() } - pub(in crate::qwen_forward) fn matches_readout( - &self, - key: &Rc<()>, - identity: TokenLayer, - ) -> bool { + pub(in crate::qwen_forward) fn matches_readout(&self, key: &Rc<()>, identity: TokenLayer) -> bool { Rc::ptr_eq(&self.key, key) && self.identity == identity } pub(in crate::qwen_forward) fn validate( @@ -52,8 +49,7 @@ impl GdnChunkRow { || self.index != cursor || cursor >= start.0.count || self.identity.layer() != start.0.layer - || start.0.first.get().checked_add(cursor as u64) - != Some(self.identity.position().get()) + || start.0.first.get().checked_add(cursor as u64) != Some(self.identity.position().get()) { return Err(Error::IdentityMismatch); } @@ -62,18 +58,23 @@ impl GdnChunkRow { } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl GdnChunkMicro { - pub(in crate::qwen_forward) fn len(&self) -> usize { self.rows.len() } - pub(in crate::qwen_forward) fn first(&self) -> usize { self.first } + pub(in crate::qwen_forward) fn len(&self) -> usize { + self.rows.len() + } + pub(in crate::qwen_forward) fn first(&self) -> usize { + self.first + } pub(in crate::qwen_forward) fn row(&self, local: usize) -> Result<&GdnChunkRow> { self.rows.get(local).ok_or(Error::IdentityMismatch) } - pub(in crate::qwen_forward) fn input( - &self, local: usize, - ) -> Result<&super::super::super::gr::ResidualReady> { + pub(in crate::qwen_forward) fn input(&self, local: usize) -> Result<&super::super::super::gr::ResidualReady> { self.reads.get(local).map(|read| read.ready()).ok_or(Error::IdentityMismatch) } pub(in crate::qwen_forward) fn validate( - &self, start: &GdnChunkStart, cursor: usize, binding: &BindingIdentity, + &self, + start: &GdnChunkStart, + cursor: usize, + binding: &BindingIdentity, ) -> Result<()> { start.validate_binding(binding)?; if !Rc::ptr_eq(&self.start.0, &start.0) @@ -86,8 +87,7 @@ impl GdnChunkMicro { } for (local, (row, read)) in self.rows.iter().zip(&self.reads).enumerate() { row.validate(start, cursor + local, binding)?; - if !Rc::ptr_eq(&row.start.0.chunk, &start.0.chunk) - || !same_window_proof(&row.window, &self.rows[0].window) + if !Rc::ptr_eq(&row.start.0.chunk, &start.0.chunk) || !same_window_proof(&row.window, &self.rows[0].window) { return Err(Error::IdentityMismatch); } @@ -108,11 +108,7 @@ pub(super) fn same_window_proof(a: &Option>, b: &Option>) -> bool } } impl GdnChunkSeal { - pub(in crate::qwen_forward) fn validate( - &self, - start: &GdnChunkStart, - cursor: usize, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate(&self, start: &GdnChunkStart, cursor: usize) -> Result<()> { start.validate_binding(&self.start.binding())?; if !Rc::ptr_eq(&self.start.0, &start.0) || cursor != start.0.count { return Err(Error::IdentityMismatch); @@ -130,47 +126,79 @@ impl GdnChunkSeal { // Physical Original prompt adapter. Legacy begin/begin_windowed limits and // scalar completion paths remain unchanged; these rows have a real GPU phase. -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl GdnChunkStart { pub(in crate::qwen_forward) fn from_original_prompt( - txn:&super::super::original_prompt::OriginalPromptTxn<'_, '_>,layer:LayerId,prior:&GdnPrior, - )->Result<(Self,Vec)>{ - txn.validate_phase(GrRole::Attention(layer.get()),true)?; - let actual=txn.gdn_prior(layer)?; - if !actual.same_state(prior){return Err(Error::IdentityMismatch)} - let phase=txn.phase();let owner=phase.journal_owner(); - let start=Self(Rc::new(GdnChunkAnchor{binding:txn.original_session().binding.clone(), - chunk:Rc::clone(&owner),prior:prior.clone(),layer, - first:Position::new(txn.start_position(),crate::qwen_forward::contract::position_dimension())?, - end:txn.end_position(),count:txn.len()})); - start.validate_binding(&txn.original_session().binding)?; - let mut rows=Vec::new();rows.try_reserve_exact(txn.len()).map_err(|_|Error::InputAllocation)?; - for index in 0..txn.len(){let input=txn.input(index)?; - let key=txn.row_key(index)?; - let identity=key.validate(&txn.original_session().binding,&input,GrRole::Attention(layer.get()),true)?; - rows.push(GdnChunkRow{start:start.clone(),index,identity,proof:Rc::clone(&owner),window:None,key:Rc::new(())}); + txn: &super::super::original_prompt::OriginalPromptTxn<'_, '_>, + layer: LayerId, + prior: &GdnPrior, + ) -> Result<(Self, Vec)> { + txn.validate_phase(GrRole::Attention(layer.get()), true)?; + let actual = txn.gdn_prior(layer)?; + if !actual.same_state(prior) { + return Err(Error::IdentityMismatch); } - Ok((start,rows)) + let phase = txn.phase(); + let owner = phase.journal_owner(); + let start = Self(Rc::new(GdnChunkAnchor { + binding: txn.original_session().binding.clone(), + chunk: Rc::clone(&owner), + prior: prior.clone(), + layer, + first: Position::new(txn.start_position(), crate::qwen_forward::contract::position_dimension())?, + end: txn.end_position(), + count: txn.len(), + })); + start.validate_binding(&txn.original_session().binding)?; + let mut rows = Vec::new(); + rows.try_reserve_exact(txn.len()).map_err(|_| Error::InputAllocation)?; + for index in 0..txn.len() { + let input = txn.input(index)?; + let key = txn.row_key(index)?; + let identity = + key.validate(&txn.original_session().binding, &input, GrRole::Attention(layer.get()), true)?; + rows.push(GdnChunkRow { + start: start.clone(), + index, + identity, + proof: Rc::clone(&owner), + window: None, + key: Rc::new(()), + }); + } + Ok((start, rows)) } } -#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] impl GdnChunkSeal { pub(in crate::qwen_forward) fn from_original_prompt( - txn:&super::super::original_prompt::OriginalPromptTxn<'_, '_>,start:&GdnChunkStart, - edges:Vec, - )->Result{ - txn.validate_phase(GrRole::Attention(start.0.layer.get()),true)?; - let owner=txn.phase().journal_owner(); - if edges.len()!=txn.len()||!Rc::ptr_eq(&owner,&start.0.chunk) - || start.0.count!=txn.len()||start.0.first.get()!=txn.start_position() - || start.0.end!=txn.end_position(){return Err(Error::IdentityMismatch)} - for(index,edge)in edges.into_iter().enumerate(){let(row,verified)=edge.into_parts(); - row.validate(start,index,&txn.original_session().binding)?; - let input=txn.input(index)?; - if verified.is_some()||!Rc::ptr_eq(&row.proof,&owner)||row.identity.token()!=input.token() - ||row.identity.position()!=input.position(){return Err(Error::IdentityMismatch)} + txn: &super::super::original_prompt::OriginalPromptTxn<'_, '_>, + start: &GdnChunkStart, + edges: Vec, + ) -> Result { + txn.validate_phase(GrRole::Attention(start.0.layer.get()), true)?; + let owner = txn.phase().journal_owner(); + if edges.len() != txn.len() + || !Rc::ptr_eq(&owner, &start.0.chunk) + || start.0.count != txn.len() + || start.0.first.get() != txn.start_position() + || start.0.end != txn.end_position() + { + return Err(Error::IdentityMismatch); } - Ok(Self{start:start.clone()}) + for (index, edge) in edges.into_iter().enumerate() { + let (row, verified) = edge.into_parts(); + row.validate(start, index, &txn.original_session().binding)?; + let input = txn.input(index)?; + if verified.is_some() + || !Rc::ptr_eq(&row.proof, &owner) + || row.identity.token() != input.token() + || row.identity.position() != input.position() + { + return Err(Error::IdentityMismatch); + } + } + Ok(Self { start: start.clone() }) } } impl ChunkFfnRow { @@ -191,22 +219,8 @@ impl ChunkCommit { } pub(in crate::qwen_forward) fn into_parts( self, - ) -> ( - BindingIdentity, - TokenId, - Position, - Option, - Box<[f32]>, - TargetStepOrigin, - ) { - ( - self.binding, - self.token, - self.position, - self.output, - self.streams, - self.origin, - ) + ) -> (BindingIdentity, TokenId, Position, Option, Box<[f32]>, TargetStepOrigin) { + (self.binding, self.token, self.position, self.output, self.streams, self.origin) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs index ff5843fb..95a76c12 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2.rs @@ -3,16 +3,18 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// Actual extra simultaneous owners of the selected native prompt PLE /// batch. Caller reserves this before begin; default and verification /// admission retain their existing exact charge and 512 MiB ceiling. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn native_prefill_host_charge(tokens: usize) -> Result { - if !(1..=256).contains(&tokens) { return Err(Error::InvalidDimension); } - tokens.min(64).checked_mul(409600 + 51200) + if !(1..=256).contains(&tokens) { + return Err(Error::InvalidDimension); + } + tokens + .min(64) + .checked_mul(409600 + 51200) .and_then(|bytes| bytes.checked_add(3_645_440 + 819_200 + 8192)) // Genuine pooled flatten + end readback bytes/F32 + driver upload // staging may coexist; persistent canonical pages stay separately @@ -41,14 +43,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { known_next: Option, host_remaining: usize, ) -> Result { - Self::begin_bounded( - session, - binding, - tokens, - known_next, - host_remaining.min(512 * 1024 * 1024), - true, - ) + Self::begin_bounded(session, binding, tokens, known_next, host_remaining.min(512 * 1024 * 1024), true) } pub(in super::super) fn begin_bounded( session: &'session mut QwenSession<'driver>, @@ -67,10 +62,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::InvalidDimension); } - let end = session - .next_position - .checked_add(tokens.len() as u64) - .ok_or(Error::Overflow)?; + let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; let context_bound = Dimension::new(u64::from(binding.input_constants().context_length()))?; if end >= u64::from(context_bound.get()) || end >= crate::qwen_forward::contract::serving_cells() { return Err(Error::InvalidPosition); @@ -81,43 +73,24 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::InvalidToken); } } - let charge = if windowed { - host_charge_bounded(tokens.len(), end, 256)? - } else { - host_charge(tokens.len(), end)? - }; + let charge = + if windowed { host_charge_bounded(tokens.len(), end, 256)? } else { host_charge(tokens.len(), end)? }; if charge > host_remaining { return Err(Error::InputAllocation); } let context = session.mtp_context()?; - if context - .allocated_bytes() - .checked_add(128 * 1024 * 1024) - .is_none_or(|n| n > context.budget_bytes()) - { + if context.allocated_bytes().checked_add(128 * 1024 * 1024).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation); } let mut rows = Vec::new(); - rows.try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; + rows.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; let mut witnesses = Vec::new(); - witnesses - .try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; + witnesses.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; let mut predecessors = session.predecessors; for (index, token) in tokens.iter().copied().enumerate() { let position = Position::new(session.next_position + index as u64, context_bound)?; - rows.push(Row { - token, - position, - predecessors, - input: None, - completed: 0, - }); - predecessors = [ - predecessors[1], - i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?, - ]; + rows.push(Row { token, position, predecessors, input: None, completed: 0 }); + predecessors = [predecessors[1], i32::try_from(token.get()).map_err(|_| Error::InvalidToken)?]; } Ok(Self { verification: None, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs index 9cba3af9..bb15e431 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs @@ -3,19 +3,10 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - pub(in crate::qwen_forward) fn open_micro_window( - &mut self, - layer: LayerId, - ) -> Result { + pub(in crate::qwen_forward) fn open_micro_window(&mut self, layer: LayerId) -> Result { self.check()?; - if self - .gdn_chunk - .as_ref() - .is_some_and(|journal| journal.start.0.layer != layer) - { + if self.gdn_chunk.as_ref().is_some_and(|journal| journal.start.0.layer != layer) { return Err(Error::IdentityMismatch); } if !self.windowed @@ -42,36 +33,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if !(1..=64).contains(&width) { return Err(Error::IdentityMismatch); } - let end = first - .checked_add(width) - .ok_or(Error::Overflow)? - .min(self.rows.len()); - if self.rows[first..end] - .iter() - .any(|r| r.completed != layer.get()) - { + let end = first.checked_add(width).ok_or(Error::Overflow)?.min(self.rows.len()); + if self.rows[first..end].iter().any(|r| r.completed != layer.get()) { return Err(Error::IdentityMismatch); } let proof = Rc::new(()); - self.active_micro = Some(ActiveMicroWindow { - proof: Rc::clone(&proof), - layer, - first, - end, - }); - Ok(ChunkMicroWindow { - chunk: Rc::clone(&self.chunk), - proof, - layer, - first, - end, - }) + self.active_micro = Some(ActiveMicroWindow { proof: Rc::clone(&proof), layer, first, end }); + Ok(ChunkMicroWindow { chunk: Rc::clone(&self.chunk), proof, layer, first, end }) } /// Consumes the exact minted capability; no next range can open early. - pub(in crate::qwen_forward) fn close_micro_window( - &mut self, - window: ChunkMicroWindow, - ) -> Result<()> { + pub(in crate::qwen_forward) fn close_micro_window(&mut self, window: ChunkMicroWindow) -> Result<()> { let (first, end) = self.phase_span()?; let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(&self.chunk, &window.chunk) @@ -86,9 +57,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { || !self.batch_rows.is_empty() || !self.attention_sources.is_empty() || self.attention_authorized.is_some() - || self.rows[first..end] - .iter() - .any(|r| r.completed != self.next_layer + 1) + || self.rows[first..end].iter().any(|r| r.completed != self.next_layer + 1) { return Err(Error::IdentityMismatch); } @@ -105,9 +74,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] { - self.test_window_journal - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.test_window_journal.try_reserve(1).map_err(|_| Error::InputAllocation)?; // The tuple is observed only after genuine finite completion and // all capability checks, before the infallible cursor transition. self.test_window_journal.push((self.next_layer, first, end)); @@ -165,26 +132,26 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { residual.validate_origin(&self.session.binding, GrRole::Ffn(0))?; let (token, position) = self.row_ids(index)?; residual.identity().validate(token, position, layer)?; - if residual.streams().len() != 10240 - || residual.streams().iter().any(|v| !v.is_finite()) - { + if residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite()) { return Err(Error::NonFinite); } - words = words - .checked_add(residual.streams().len()) - .ok_or(Error::Overflow)?; + words = words.checked_add(residual.streams().len()).ok_or(Error::Overflow)?; } let end = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; if self.session.gdn_layers[0] { - self.next_gdn[0] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + self.next_gdn[0].as_ref().ok_or(Error::IdentityMismatch)?.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + end, + )?; } else if self.session.qsa_layers[0] { - self.next_qsa[0] - .as_ref() - .ok_or(Error::IdentityMismatch)? - .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; + self.next_qsa[0].as_ref().ok_or(Error::IdentityMismatch)?.validate( + &self.session.binding, + &self.session.qsa_owner, + layer, + end, + )?; } else { return Err(Error::InvalidLayer); } @@ -197,10 +164,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn test_publication_preflight_refused(&self) -> bool { - matches!( - self.validate_publish(), - Err(Error::Unsupported(Stage::Executor)) - ) + matches!(self.validate_publish(), Err(Error::Unsupported(Stage::Executor))) } pub(in crate::qwen_forward) fn context(&self) -> Result<&Context<'driver>> { self.check()?; @@ -213,17 +177,24 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn prompt_qsa_prior(&mut self, layer: LayerId) -> Result { let (first, end) = self.phase_span()?; let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() - { return Err(Error::IdentityMismatch); } + if slot >= STATE_CAPACITY + || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() + || self.next_row != first + || self.attention_layer != Some(layer) + || self.attention_next != end + || self.batch_layer.is_some() + || self.attention_authorized.is_some() + { + return Err(Error::IdentityMismatch); + } let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; if self.next_qsa[slot].is_none() { - if position.get() != 0 { return Err(Error::IdentityMismatch); } - self.next_qsa[slot] = Some(QsaIndexPrior::empty( - self.session.binding.clone(), &self.session.qsa_owner, layer, - )?); + if position.get() != 0 { + return Err(Error::IdentityMismatch); + } + self.next_qsa[slot] = + Some(QsaIndexPrior::empty(self.session.binding.clone(), &self.session.qsa_owner, layer)?); } let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; @@ -233,22 +204,32 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// Existing FP16 state cannot be relabeled after a mode switch. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn prompt_native_qsa_prior( - &mut self, layer: LayerId, kv: &leleka_cuda_driver::QsaPromptKv<'_>, + &mut self, + layer: LayerId, + kv: &leleka_cuda_driver::QsaPromptKv<'_>, ) -> Result { let (first, end) = self.phase_span()?; let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() - { return Err(Error::IdentityMismatch); } - kv.validate_context(self.session.mtp_context()?).map_err(super::super::super::super::qsa_index::driver_error)?; + if slot >= STATE_CAPACITY + || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() + || self.next_row != first + || self.attention_layer != Some(layer) + || self.attention_next != end + || self.batch_layer.is_some() + || self.attention_authorized.is_some() + { + return Err(Error::IdentityMismatch); + } + kv.validate_context(self.session.mtp_context()?) + .map_err(super::super::super::super::qsa_index::driver_error)?; let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; if self.next_qsa[slot].is_none() { - if position.get() != 0 { return Err(Error::IdentityMismatch); } - self.next_qsa[slot] = Some(QsaIndexPrior::empty_native( - self.session.binding.clone(), &self.session.qsa_owner, layer, kv, - )?); + if position.get() != 0 { + return Err(Error::IdentityMismatch); + } + self.next_qsa[slot] = + Some(QsaIndexPrior::empty_native(self.session.binding.clone(), &self.session.qsa_owner, layer, kv)?); } let prior = self.next_qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs index 7495935e..b291f9fc 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_3.rs @@ -3,21 +3,27 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn validate_prompt_qsa_prior( - &self, layer: LayerId, prior: &QsaIndexPrior, + &self, + layer: LayerId, + prior: &QsaIndexPrior, ) -> Result<()> { let (first, end) = self.phase_span()?; let slot = layer.get() as usize; - if slot >= STATE_CAPACITY || !self.session.qsa_layers[slot] - || self.next_layer != layer.get() || self.next_row != first - || self.attention_layer != Some(layer) || self.attention_next != end - || self.batch_layer.is_some() || self.attention_authorized.is_some() + if slot >= STATE_CAPACITY + || !self.session.qsa_layers[slot] + || self.next_layer != layer.get() + || self.next_row != first + || self.attention_layer != Some(layer) + || self.attention_next != end + || self.batch_layer.is_some() + || self.attention_authorized.is_some() || self.next_qsa[slot].as_ref().is_none_or(|actual| !actual.same_state(prior)) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let position = self.rows.get(first).ok_or(Error::InvalidPosition)?.position; prior.validate(&self.session.binding, &self.session.qsa_owner, layer, position) } @@ -37,13 +43,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn with_mtp_row( &mut self, witness: &ChunkRowResidual, - execute: impl FnOnce( - &mut QwenSession<'driver>, - Position, - TokenId, - &[f32], - TargetStepOrigin, - ) -> Result<()>, + execute: impl FnOnce(&mut QwenSession<'driver>, Position, TokenId, &[f32], TargetStepOrigin) -> Result<()>, ) -> Result<()> { let (_, position, next, streams) = self.validate_row(witness)?; let next = next.ok_or(Error::Unsupported(Stage::Executor))?; @@ -72,19 +72,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } witness.origin.validate(self.session)?; let index = usize::try_from( - witness - .position - .get() - .checked_sub(self.session.next_position) - .ok_or(Error::InvalidPosition)?, + witness.position.get().checked_sub(self.session.next_position).ok_or(Error::InvalidPosition)?, ) .map_err(|_| Error::Overflow)?; let row = self.rows.get(index).ok_or(Error::InvalidPosition)?; - let expected_next = self - .rows - .get(index + 1) - .map(|r| r.token) - .or(self.known_next); + let expected_next = self.rows.get(index + 1).map(|r| r.token).or(self.known_next); if row.token != witness.token || row.position != witness.position || row.completed != 48 @@ -94,12 +86,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::IdentityMismatch); } - Ok(( - witness.token, - witness.position, - witness.known_next, - witness.streams.as_ref(), - )) + Ok((witness.token, witness.position, witness.known_next, witness.streams.as_ref())) } pub(in crate::qwen_forward) fn row_ids(&self, index: usize) -> Result<(TokenId, Position)> { self.check()?; @@ -110,10 +97,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.rows.len() } - pub(in crate::qwen_forward) fn begin_gdn_chunk( - &mut self, - layer: LayerId, - ) -> Result { + pub(in crate::qwen_forward) fn begin_gdn_chunk(&mut self, layer: LayerId) -> Result { self.check()?; let slot = layer.get() as usize; if !self.windowed @@ -131,9 +115,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { let first = self.rows.first().ok_or(Error::InvalidPosition)?.position; let prior = match &self.next_gdn[slot] { Some(prior) => prior.clone(), - None if first.get() == 0 => { - GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)? - } + None if first.get() == 0 => GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)?, None => return Err(Error::IdentityMismatch), }; prior.validate(&self.session.binding, &self.session.gdn_owner, layer, first)?; @@ -147,10 +129,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { count: self.rows.len(), })); start.validate_binding(&self.session.binding)?; - self.gdn_chunk = Some(GdnChunkJournal { - start: start.clone(), - accepted: 0, - }); + self.gdn_chunk = Some(GdnChunkJournal { start: start.clone(), accepted: 0 }); Ok(start) } pub(in crate::qwen_forward) fn finish_gdn_chunk<'ctx>( @@ -176,13 +155,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.aborted = true; return Err(Error::IdentityMismatch); } - let seal = GdnChunkSeal { - start: journal.start.clone(), - }; + let seal = GdnChunkSeal { start: journal.start.clone() }; if owner.is_verification() { - let result=owner.finish_verification(seal,binding,cache); - if let Err(error)=&result{self.session.note_mtp_failure(error);self.aborted=true;} - result?;self.gdn_chunk=None;return Ok(()); + let result = owner.finish_verification(seal, binding, cache); + if let Err(error) = &result { + self.session.note_mtp_failure(error); + self.aborted = true; + } + result?; + self.gdn_chunk = None; + return Ok(()); } let result = owner.finish(seal, binding, cache).and_then(|prior| { prior.validate( @@ -232,8 +214,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { qsa_owner: self.session.qsa_owner.clone(), qsa_states: self.next_qsa.clone(), state_lag: None, - #[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - resident_qsa_states:self.session.resident_qsa_states.clone(), + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + resident_qsa_states: self.session.resident_qsa_states.clone(), }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs index 2e89b3f5..00cd3452 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_4.rs @@ -3,18 +3,13 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn input( &mut self, index: usize, execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, ) -> Result<()> { - if self.next_layer != 0 - || self.next_row != 0 - || self.rows.get(index).is_none_or(|r| r.input.is_some()) - { + if self.next_layer != 0 || self.next_row != 0 || self.rows.get(index).is_none_or(|r| r.input.is_some()) { return Err(Error::IdentityMismatch); } let mut view = self.stage_view(index)?; @@ -44,9 +39,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { mut prepare: impl FnMut(usize, &QwenStepTxn<'_, 'driver>) -> Result, ) -> Result<(PlePrior, Vec)> { let (first, end) = self.phase_span()?; - if layer.get() != 1 || self.next_layer != 1 - || self.next_row != first || self.attention_next != first - || self.batch_layer.is_some() || self.attention_layer.is_some() + if layer.get() != 1 + || self.next_layer != 1 + || self.next_row != first + || self.attention_next != first + || self.batch_layer.is_some() + || self.attention_layer.is_some() || self.device_gdn_lease()?.is_some() || !(1..=64).contains(&(end - first)) || self.rows[first..end].iter().any(|row| row.completed != 1) @@ -59,14 +57,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } let mut inputs = Vec::new(); - inputs.try_reserve_exact(end-first).map_err(|_| Error::InputAllocation)?; + inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?; for index in first..end { let mut view = self.stage_view(index)?; let row = &self.rows[index]; let mut step = view.begin(row.token, row.position)?; step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); step.completed_layers = row.completed; - if index == first { step.validate_ple_prior(&prior)?; } + if index == first { + step.validate_ple_prior(&prior)?; + } inputs.push(prepare(index, &step)?); } Ok((prior, inputs)) @@ -101,17 +101,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { || self.batch_layer.is_some() || self.attention_layer.is_some_and(|old| old != layer) || !(1..=64).contains(&(end - first)) - || self.rows[first..end] - .iter() - .any(|row| row.completed != layer.get()) + || self.rows[first..end].iter().any(|row| row.completed != layer.get()) { return Err(Error::IdentityMismatch); } let result = (|| { if self.attention_layer.is_none() { - self.attention_sources - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; + self.attention_sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; self.attention_sources.resize_with(self.rows.len(), || None); self.attention_layer = Some(layer); } @@ -121,9 +117,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } let mut inputs = Vec::new(); - inputs - .try_reserve_exact(end - first) - .map_err(|_| Error::InputAllocation)?; + inputs.try_reserve_exact(end - first).map_err(|_| Error::InputAllocation)?; for index in first..end { if self.attention_next != index { return Err(Error::IdentityMismatch); @@ -139,11 +133,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { input.validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; input.identity().validate(token, position, layer)?; if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); + let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior(); if next.next_position() != position.get() + 1 { return Err(Error::IdentityMismatch); } @@ -152,9 +142,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } else if step.ple_pending.is_some() { return Err(Error::IdentityMismatch); } - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { + if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) { return Err(Error::IdentityMismatch); } inputs.push(input); @@ -167,21 +155,16 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { // Validate every completed producer before publishing even the // first row. Token/position/role come from this actual transaction. for (row, read) in self.rows[first..end].iter().zip(&reads) { - read.ready() - .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + read.ready().validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; read.ready().identity().validate(row.token, row.position, layer)?; } let mut completed = Vec::new(); - completed - .try_reserve_exact(reads.len()) - .map_err(|_| Error::InputAllocation)?; + completed.try_reserve_exact(reads.len()).map_err(|_| Error::InputAllocation)?; for (index, read) in (first..end).zip(reads) { let proof = Rc::new(()); let read = Rc::new(read); - self.attention_sources[index] = Some(AttentionSource { - proof: Rc::clone(&proof), - read: Rc::clone(&read), - }); + self.attention_sources[index] = + Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) }); completed.push(ChunkAttentionRow { chunk: Rc::clone(&self.chunk), proof, diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs index 44efe093..5d8ad978 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_5.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn read_attention_column( &mut self, @@ -21,17 +19,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { || self.batch_layer.is_some() || index != self.attention_next || self.attention_layer.is_some_and(|old| old != layer) - || self - .rows - .get(index) - .is_none_or(|row| row.completed != layer.get()) + || self.rows.get(index).is_none_or(|row| row.completed != layer.get()) { return Err(Error::IdentityMismatch); } if self.attention_layer.is_none() { - self.attention_sources - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; + self.attention_sources.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; self.attention_sources.resize_with(self.rows.len(), || None); self.attention_layer = Some(layer); } @@ -42,17 +35,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { step.input = Some(row.input.clone().ok_or(Error::Unsupported(Stage::Input))?); step.completed_layers = row.completed; let result = execute(&mut step).and_then(|read| { - read.ready() - .validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; - read.ready() - .identity() - .validate(step.token(), position, layer)?; + read.ready().validate_origin(&self.session.binding, GrRole::Attention(layer.get()))?; + read.ready().identity().validate(step.token(), position, layer)?; if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); + let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior(); if next.next_position() != position.get() + 1 { return Err(Error::IdentityMismatch); } @@ -61,9 +47,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } else if step.ple_pending.is_some() { return Err(Error::IdentityMismatch); } - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { + if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) { return Err(Error::IdentityMismatch); } Ok(read) @@ -72,10 +56,8 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { Ok(read) => { let proof = Rc::new(()); let read = Rc::new(read); - self.attention_sources[index] = Some(AttentionSource { - proof: Rc::clone(&proof), - read: Rc::clone(&read), - }); + self.attention_sources[index] = + Some(AttentionSource { proof: Rc::clone(&proof), read: Rc::clone(&read) }); self.attention_next += 1; Ok(ChunkAttentionRow { chunk: Rc::clone(&self.chunk), @@ -100,18 +82,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ready: &super::super::super::super::gr::ResidualReady, ) -> Result<()> { let (first, end) = self.phase_span()?; - if index < first - || index >= end - || self.attention_layer != Some(layer) - || self.attention_next != end - { + if index < first || index >= end || self.attention_layer != Some(layer) || self.attention_next != end { return Err(Error::IdentityMismatch); } - let source = self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?; if !std::ptr::eq(source.read.ready(), ready) { return Err(Error::IdentityMismatch); } @@ -127,9 +101,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result<()> { self.validate_attention_input(index, layer, read.ready())?; self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(&self.chunk, &read.chunk) || !Rc::ptr_eq(&source.proof, &read.proof) || !Rc::ptr_eq(&source.read, &read.read) @@ -145,16 +117,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { index: usize, layer: LayerId, read: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, - &super::super::super::super::gr::DetachedGrRead, - ) -> Result, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead) -> Result, ) -> Result<(T, PreparedLayerRow)> { self.validate_attention_input(index, layer, read.ready())?; self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(&self.chunk, &read.chunk) || !Rc::ptr_eq(&source.proof, &read.proof) || !Rc::ptr_eq(&source.read, &read.read) @@ -183,12 +150,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result, ) -> Result { let (row, proof) = self.prepare_attention_layer_batch(index, layer, read, execute)?; - row.validate( - &self.session.binding, - self.rows[index].token, - self.rows[index].position, - layer, - )?; + row.validate(&self.session.binding, self.rows[index].token, self.rows[index].position, layer)?; Ok(ChunkFfnRow { proof, row }) } pub(in crate::qwen_forward) fn prepare_attention_ffn_device_gdn( @@ -207,9 +169,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result { self.validate_attention_input(index, layer, read.ready())?; self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?; let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(&self.chunk, &read.chunk) || !Rc::ptr_eq(&source.proof, &read.proof) @@ -238,12 +198,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.attention_authorized = None; let (row, proof) = result?; self.attention_sources[index] = None; - row.validate( - &self.session.binding, - self.rows[index].token, - self.rows[index].position, - layer, - )?; + row.validate(&self.session.binding, self.rows[index].token, self.rows[index].position, layer)?; Ok(ChunkFfnRow { proof, row }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs index d09d02ff..023c8a14 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_6.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// The device attention edge is genuine, but independent FFN GR reads may /// be completed after collecting all causal attention rows of this window. @@ -22,9 +20,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { ) -> Result<(T, PreparedLayerRow)> { self.validate_attention_input(index, layer, read.ready())?; self.validate_window_proof(&read.window)?; - let source = self.attention_sources[index] - .as_ref() - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources[index].as_ref().ok_or(Error::IdentityMismatch)?; let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; if !Rc::ptr_eq(&self.chunk, &read.chunk) || !Rc::ptr_eq(&source.proof, &read.proof) @@ -67,8 +63,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { attention: &[ChunkAttentionRow], execute: impl FnOnce(&GdnChunkMicro, &Context<'driver>) -> Result>, mut consume: impl FnMut( - usize, &mut QwenStepTxn<'_, 'driver>, - &super::super::super::super::gr::DetachedGrRead, R, + usize, + &mut QwenStepTxn<'_, 'driver>, + &super::super::super::super::gr::DetachedGrRead, + R, ) -> Result<(T, super::super::super::super::gdn::chunk_device::ChunkEdge)>, ) -> Result> { let (first, end) = self.phase_span()?; @@ -86,9 +84,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::IdentityMismatch); } - let mut micro = GdnChunkMicro { - start: journal.start.clone(), first, rows: Vec::new(), reads: Vec::new(), - }; + let mut micro = GdnChunkMicro { start: journal.start.clone(), first, rows: Vec::new(), reads: Vec::new() }; micro.rows.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; micro.reads.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?; for (local, read) in attention.iter().enumerate() { @@ -96,9 +92,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.validate_attention_column(index, layer, read)?; let actual = &self.rows[index]; micro.rows.push(GdnChunkRow { - start: micro.start.clone(), index, + start: micro.start.clone(), + index, identity: TokenLayer::new(actual.token, actual.position, layer), - proof: Rc::clone(&read.proof), window: read.window.clone(), key: Rc::new(()), + proof: Rc::clone(&read.proof), + window: read.window.clone(), + key: Rc::new(()), }); micro.reads.push(Rc::clone(&read.read)); } @@ -118,8 +117,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } self.attention_authorized = Some(index); let prepared = self.prepare_layer_batch_internal(index, layer, |step| { - consume(local, step, &read.read, product) - .map(|(value, edge)| (value, Some(edge))) + consume(local, step, &read.read, product).map(|(value, edge)| (value, Some(edge))) }); self.attention_authorized = None; completed.push(prepared?); @@ -139,25 +137,35 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// prepared-row proof carries its original Rc into the later Out batch. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn validate_prepared_attention_input( - &self, proof: &PreparedLayerRow, + &self, + proof: &PreparedLayerRow, input: &super::super::super::super::gr::ResidualReady, ) -> Result<()> { let (first, end) = self.phase_span()?; self.validate_window_proof(&proof.window)?; - if proof.index < first || proof.index >= end + if proof.index < first + || proof.index >= end || self.batch_layer != Some(proof.layer) - || self.next_layer != proof.layer.get() || self.next_row != end + || self.next_layer != proof.layer.get() + || self.next_row != end || self.batch_completed != first || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) + || self + .batch_rows + .get(proof.index) + .and_then(Option::as_ref) .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let source = proof.attention_source.as_ref().ok_or(Error::IdentityMismatch)?; if !std::ptr::eq(source.ready(), input) { return Err(Error::IdentityMismatch); } let actual = self.rows.get(proof.index).ok_or(Error::IdentityMismatch)?; - if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } + if actual.completed != proof.layer.get() { + return Err(Error::IdentityMismatch); + } input.validate_origin(&self.session.binding, GrRole::Attention(proof.layer.get()))?; input.identity().validate(actual.token, actual.position, proof.layer) } @@ -166,18 +174,20 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// and current transaction, without advancing attention a second time. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn prepare_attention_output_after_causal( - &mut self, proof: &PreparedLayerRow, source: &ChunkAttentionRow, - execute: impl FnOnce( - &mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead, - ) -> Result, + &mut self, + proof: &PreparedLayerRow, + source: &ChunkAttentionRow, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>, &super::super::super::super::gr::DetachedGrRead) -> Result, ) -> Result { self.validate_prepared_attention_input(proof, source.ready())?; self.validate_window_proof(&source.window)?; - if source.index != proof.index || source.layer != proof.layer + if source.index != proof.index + || source.layer != proof.layer || !Rc::ptr_eq(&self.chunk, &source.chunk) - || proof.attention_source.as_ref() - .is_none_or(|actual| !Rc::ptr_eq(actual, &source.read)) - { return Err(Error::IdentityMismatch); } + || proof.attention_source.as_ref().is_none_or(|actual| !Rc::ptr_eq(actual, &source.read)) + { + return Err(Error::IdentityMismatch); + } let actual = &self.rows[proof.index]; let token = actual.token; let position = actual.position; @@ -190,11 +200,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if step.ple_pending.is_some() || step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } Ok(output) })(); if let Err(error) = &result { - self.session.note_mtp_failure(error); self.aborted = true; + self.session.note_mtp_failure(error); + self.aborted = true; } result } @@ -203,19 +216,31 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { /// reopening a row for routing cannot advance its causal attention twice. #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn validate_prepared_ffn_read( - &self, proof: &PreparedLayerRow, read: &super::super::super::super::gr::DetachedGrRead, + &self, + proof: &PreparedLayerRow, + read: &super::super::super::super::gr::DetachedGrRead, ) -> Result { let (first, end) = self.phase_span()?; self.validate_window_proof(&proof.window)?; - if proof.index < first || proof.index >= end + if proof.index < first + || proof.index >= end || self.batch_layer != Some(proof.layer) - || self.next_layer != proof.layer.get() || self.next_row != end - || self.batch_completed != first || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) + || self.next_layer != proof.layer.get() + || self.next_row != end + || self.batch_completed != first + || !Rc::ptr_eq(&self.chunk, &proof.chunk) + || self + .batch_rows + .get(proof.index) + .and_then(Option::as_ref) .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) - { return Err(Error::IdentityMismatch); } + { + return Err(Error::IdentityMismatch); + } let actual = &self.rows[proof.index]; - if actual.completed != proof.layer.get() { return Err(Error::IdentityMismatch); } + if actual.completed != proof.layer.get() { + return Err(Error::IdentityMismatch); + } read.ready().validate_origin(&self.session.binding, GrRole::Ffn(proof.layer.get()))?; let identity = read.ready().identity(); identity.validate(actual.token, actual.position, proof.layer)?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs index f64c618f..6bb1c4d8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_7.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] pub(in crate::qwen_forward) fn prepare_ffn_after_attention( &mut self, @@ -26,7 +23,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { || self.next_row != end || self.batch_completed != first || !Rc::ptr_eq(&self.chunk, &proof.chunk) - || self.batch_rows.get(proof.index).and_then(Option::as_ref) + || self + .batch_rows + .get(proof.index) + .and_then(Option::as_ref) .is_none_or(|stored| !Rc::ptr_eq(stored, &proof.proof)) { return Err(Error::IdentityMismatch); @@ -74,16 +74,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::IdentityMismatch); } - let (row,verified) = edge.into_parts(); + let (row, verified) = edge.into_parts(); self.validate_window_proof(&row.window)?; let journal = self.gdn_chunk.as_ref().ok_or(Error::IdentityMismatch)?; row.validate(&journal.start, journal.accepted, &self.session.binding)?; let actual = self.rows.get(index).ok_or(Error::IdentityMismatch)?; - let source = self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; + let source = self.attention_sources.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?; if row.index != index || row.identity != TokenLayer::new(actual.token, actual.position, layer) || !Rc::ptr_eq(&source.proof, &row.proof) @@ -91,12 +87,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::IdentityMismatch); } - if let Some(proof)=verified {self.record_device_gdn(index,layer,proof)?;} - else if self.device_gdn_lease()?.is_some(){return Err(Error::IdentityMismatch);} - self.gdn_chunk - .as_mut() - .ok_or(Error::IdentityMismatch)? - .accepted += 1; + if let Some(proof) = verified { + self.record_device_gdn(index, layer, proof)?; + } else if self.device_gdn_lease()?.is_some() { + return Err(Error::IdentityMismatch); + } + self.gdn_chunk.as_mut().ok_or(Error::IdentityMismatch)?.accepted += 1; Ok(()) } pub(in crate::qwen_forward) fn validate_ffn_row( @@ -108,11 +104,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { let (first, end) = self.phase_span()?; let proof = &row.proof; self.validate_window_proof(&proof.window)?; - let stored = self - .batch_rows - .get(index) - .and_then(Option::as_ref) - .ok_or(Error::IdentityMismatch)?; + let stored = self.batch_rows.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)?; if self.batch_layer != Some(layer) || index < first || index >= end @@ -126,8 +118,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } let (token, position) = self.row_ids(index)?; - row.row - .validate(&self.session.binding, token, position, layer) + row.row.validate(&self.session.binding, token, position, layer) } pub(in crate::qwen_forward) fn prepare_ffn_injection( &mut self, @@ -143,12 +134,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { expert.identity().validate(token, position, layer)?; let mut view = self.stage_view(index)?; let mut step = view.begin(token, position)?; - step.input = Some( - self.rows[index] - .input - .clone() - .ok_or(Error::Unsupported(Stage::Input))?, - ); + step.input = Some(self.rows[index].input.clone().ok_or(Error::Unsupported(Stage::Input))?); step.completed_layers = self.rows[index].completed; let result = super::super::super::super::gr::GrStage::prepare_detached_batch_injection( binding, @@ -175,22 +161,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { let next_position = position.get().checked_add(1).ok_or(Error::Overflow)?; if self.attention_layer == Some(layer) { let index = self.attention_authorized.ok_or(Error::IdentityMismatch)?; - if self - .attention_sources - .get(index) - .and_then(Option::as_ref) - .is_none() - || step.ple_pending.is_some() - { + if self.attention_sources.get(index).and_then(Option::as_ref).is_none() || step.ple_pending.is_some() { return Err(Error::IdentityMismatch); } } else { if layer.get() == 1 && self.session.ple_required { - let next = step - .ple_pending - .take() - .ok_or(Error::Unsupported(Stage::Input))? - .into_prior(); + let next = step.ple_pending.take().ok_or(Error::Unsupported(Stage::Input))?.into_prior(); if next.next_position() != next_position { return Err(Error::IdentityMismatch); } @@ -201,19 +177,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } } if self.session.gdn_layers[slot] { - let next = step.gdn_pending[slot] - .take() - .ok_or(Error::Unsupported(Stage::Gdn))? - .into_prior(); + let next = step.gdn_pending[slot].take().ok_or(Error::Unsupported(Stage::Gdn))?.into_prior(); if next.layer() != layer || next.next_position() != next_position { return Err(Error::IdentityMismatch); } self.next_gdn[slot] = Some(next); } else if self.session.qsa_layers[slot] { - let next = step.qsa_pending[slot] - .take() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .into_prior(); + let next = step.qsa_pending[slot].take().ok_or(Error::Unsupported(Stage::QsaIndex))?.into_prior(); if next.layer() != layer || next.next_position() != next_position { return Err(Error::IdentityMismatch); } @@ -223,9 +193,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } self.record_verification_prior(self.next_row, layer, position)?; // No hidden noncurrent-layer candidate is admitted. - if step.gdn_pending.iter().any(Option::is_some) - || step.qsa_pending.iter().any(Option::is_some) - { + if step.gdn_pending.iter().any(Option::is_some) || step.qsa_pending.iter().any(Option::is_some) { return Err(Error::IdentityMismatch); } Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs index 6aa6ad61..aef0ceca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_8.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn layer( &mut self, @@ -19,10 +17,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if layer.get() != self.next_layer || index != self.next_row || layer.get() >= 48 - || self - .rows - .get(index) - .is_none_or(|r| r.completed != layer.get()) + || self.rows.get(index).is_none_or(|r| r.completed != layer.get()) { return Err(Error::IdentityMismatch); } @@ -60,9 +55,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { layer: LayerId, execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, ) -> Result<(T, PreparedLayerRow)> { - self.prepare_layer_batch_internal(index, layer, |step| { - execute(step).map(|prepared| (prepared, None)) - }) + self.prepare_layer_batch_internal(index, layer, |step| execute(step).map(|prepared| (prepared, None))) } pub(in super::super) fn prepare_layer_batch_internal( &mut self, @@ -84,10 +77,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if layer.get() != self.next_layer || index != self.next_row || layer.get() >= 48 - || self - .rows - .get(index) - .is_none_or(|r| r.completed != layer.get()) + || self.rows.get(index).is_none_or(|r| r.completed != layer.get()) || self.batch_layer.is_some_and(|current| current != layer) { return Err(Error::IdentityMismatch); @@ -96,9 +86,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if index != first { return Err(Error::IdentityMismatch); } - self.batch_rows - .try_reserve_exact(self.rows.len()) - .map_err(|_| Error::InputAllocation)?; + self.batch_rows.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?; self.batch_rows.resize_with(self.rows.len(), || None); self.batch_layer = Some(layer); self.batch_completed = first; @@ -133,8 +121,11 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { index, layer, window: self.window_proof(), - attention_source: self.attention_sources.get(index) - .and_then(Option::as_ref).map(|source| Rc::clone(&source.read)), + attention_source: self + .attention_sources + .get(index) + .and_then(Option::as_ref) + .map(|source| Rc::clone(&source.read)), }, )) } @@ -152,10 +143,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { let (first, end) = self.phase_span()?; if self.batch_layer.is_none() || self.next_row != end - || self - .batch_rows - .get(first..end) - .is_none_or(|rows| rows.iter().any(Option::is_none)) + || self.batch_rows.get(first..end).is_none_or(|rows| rows.iter().any(Option::is_none)) { return Err(Error::IdentityMismatch); } @@ -205,11 +193,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { || !Rc::ptr_eq(&self.chunk, &proof.chunk) || proof.index != self.batch_completed || self.next_row != end - || self - .batch_rows - .get(proof.index) - .and_then(Option::as_ref) - .is_none_or(|p| !Rc::ptr_eq(p, &proof.proof)) + || self.batch_rows.get(proof.index).and_then(Option::as_ref).is_none_or(|p| !Rc::ptr_eq(p, &proof.proof)) { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs index 85bc021d..b0de5489 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_qwenchunktxn/impl_qwenchunktxn_9.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - pub(in crate::qwen_forward) fn finish( &mut self, residuals: &[Option], @@ -36,15 +33,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } for (index, residual) in residuals.iter().enumerate() { let row = &self.rows[index]; - let residual = residual - .as_ref() - .ok_or(Error::Unsupported(Stage::Executor))?; + let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?; residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; - residual.identity().validate( - row.token, - row.position, - LayerId::new(47, Dimension::new(48)?)?, - )?; + residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?; if row.completed != 48 || residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite()) @@ -52,9 +43,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::NonFinite); } let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; streams.extend_from_slice(residual.streams()); self.witnesses.push(ChunkRowResidual { binding: self.session.binding.clone(), @@ -62,11 +51,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { origin: self.origin.clone(), token: row.token, position: row.position, - known_next: self - .rows - .get(index + 1) - .map(|r| r.token) - .or(self.known_next), + known_next: self.rows.get(index + 1).map(|r| r.token).or(self.known_next), streams: Rc::new(streams.into_boxed_slice()), }); } @@ -77,10 +62,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { let mut step = view.begin(row.token, row.position)?; step.input = row.input.clone(); step.completed_layers = 48; - match execute_head( - &mut step, - residuals[index].as_ref().ok_or(Error::IdentityMismatch)?, - ) { + match execute_head(&mut step, residuals[index].as_ref().ok_or(Error::IdentityMismatch)?) { Ok(output) if step.forward_output == Some(output) && !step.prefill_finished => { self.output = Some(output) } @@ -111,21 +93,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } let end_position = Position::new(self.end, crate::qwen_forward::contract::position_dimension())?; if self.session.ple_required { - self.next_ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))? - .validate(&self.session.binding, &self.session.ple_owner, end_position)?; + self.next_ple.as_ref().ok_or(Error::Unsupported(Stage::Input))?.validate( + &self.session.binding, + &self.session.ple_owner, + end_position, + )?; } for slot in 0..STATE_CAPACITY { let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; if self.session.gdn_layers[slot] { if self.device_gdn_lease()?.is_some() { - self.validate_verification_state(self.rows.len()-1)?; + self.validate_verification_state(self.rows.len() - 1)?; } else { - self.next_gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))? - .validate( + self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate( &self.session.binding, &self.session.gdn_owner, layer, @@ -136,25 +116,19 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { return Err(Error::IdentityMismatch); } if self.session.qsa_layers[slot] { - self.next_qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .validate( - &self.session.binding, - &self.session.qsa_owner, - layer, - end_position, - )?; + self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate( + &self.session.binding, + &self.session.qsa_owner, + layer, + end_position, + )?; } else if self.next_qsa[slot].is_some() { return Err(Error::IdentityMismatch); } } Ok(()) } - pub(in crate::qwen_forward) fn publish_joint( - self, - draft: impl ChunkDraftPublication, - ) -> Result { + pub(in crate::qwen_forward) fn publish_joint(self, draft: impl ChunkDraftPublication) -> Result { if self.verification.is_some() { return Err(Error::IdentityMismatch); } @@ -162,18 +136,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { draft.validate(&self)?; self.session.complete_cuda()?; let last = self.rows.last().ok_or(Error::InvalidPosition)?; - let predecessors = [ - last.predecessors[1], - i32::try_from(last.token.get()).map_err(|_| Error::InvalidToken)?, - ]; + let predecessors = [last.predecessors[1], i32::try_from(last.token.get()).map_err(|_| Error::InvalidToken)?]; let source = self.witnesses.last().ok_or(Error::IdentityMismatch)?; let token = source.token; let position = source.position; let binding = source.binding.clone(); let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; streams.extend_from_slice(source.streams.as_ref()); let streams = streams.into_boxed_slice(); // Every fallible operation above. Neither target nor draft is exposed @@ -185,13 +154,6 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.session.next_position = self.end; draft.publish(); let origin = super::super::super::checkpoint::committed_origin(self.session); - Ok(ChunkCommit { - binding, - token, - position, - output: self.output, - streams, - origin, - }) + Ok(ChunkCommit { binding, token, position, output: self.output, streams, origin }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_testgdncomponentrows.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_testgdncomponentrows.rs index 376ff207..18e2b54d 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_testgdncomponentrows.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk/impl_testgdncomponentrows.rs @@ -18,10 +18,7 @@ impl TestGdnComponentRows { count: 65, })); start.validate_binding(&start.binding())?; - Ok(Self { - start, - windows: [Rc::new(()), Rc::new(())], - }) + Ok(Self { start, windows: [Rc::new(()), Rc::new(())] }) } pub(in crate::qwen_forward) fn start(&self) -> GdnChunkStart { self.start.clone() @@ -36,12 +33,7 @@ impl TestGdnComponentRows { identity: TokenLayer::new( TokenId::new(index as u64, Dimension::new(248320)?)?, Position::new( - self.start - .0 - .first - .get() - .checked_add(index as u64) - .ok_or(Error::Overflow)?, + self.start.0.first.get().checked_add(index as u64).ok_or(Error::Overflow)?, crate::qwen_forward::contract::position_dimension(), )?, self.start.0.layer, @@ -55,9 +47,7 @@ impl TestGdnComponentRows { if cursor != 65 { return Err(Error::IdentityMismatch); } - let seal = GdnChunkSeal { - start: self.start.clone(), - }; + let seal = GdnChunkSeal { start: self.start.clone() }; seal.validate(&self.start, cursor)?; Ok(seal) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify.rs index b75df03f..ce2567dd 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify.rs @@ -37,8 +37,8 @@ mod tests; #[path = "session_chunk_verify/impl_verifiedtargetprefix.rs"] mod impl_verifiedtargetprefix; #[allow(unused_imports)] -use impl_verifiedtargetprefix::verification_extra_charge; -#[allow(unused_imports)] use impl_verifiedtargetprefix::greedy_prefix; +#[allow(unused_imports)] +use impl_verifiedtargetprefix::verification_extra_charge; #[path = "session_chunk_verify/impl_qwenchunktxn.rs"] mod impl_qwenchunktxn; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs index f1f586f2..73cb5f57 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn validate_verification_source( binding: &ModelBinding, @@ -33,15 +31,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { if !session.binding.matches(&binding.identity()) || session.layer_count != 48 { return Err(Error::IdentityMismatch); } - let end = session - .next_position - .checked_add(tokens as u64) - .ok_or(Error::Overflow)?; + let end = session.next_position.checked_add(tokens as u64).ok_or(Error::Overflow)?; let extra = verification_extra_charge(tokens, end)?; - let total = host_charge_bounded(tokens, end, 256)? - .checked_add(extra) - .ok_or(Error::Overflow)?; - if end >= u64::from(binding.input_constants().context_length()) || end >= crate::qwen_forward::contract::serving_cells() { + let total = host_charge_bounded(tokens, end, 256)?.checked_add(extra).ok_or(Error::Overflow)?; + if end >= u64::from(binding.input_constants().context_length()) + || end >= crate::qwen_forward::contract::serving_cells() + { return Err(Error::InvalidPosition); } if total > host_remaining.min(HOST_LIMIT) { @@ -57,22 +52,14 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { host_remaining: usize, ) -> Result { Self::preflight_mtp_verification(session, binding, tokens.len(), host_remaining)?; - let end = session - .next_position - .checked_add(tokens.len() as u64) - .ok_or(Error::Overflow)?; + let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; let extra = verification_extra_charge(tokens.len(), end)?; - let available = host_remaining - .min(HOST_LIMIT) - .checked_sub(extra) - .ok_or(Error::InputAllocation)?; + let available = host_remaining.min(HOST_LIMIT).checked_sub(extra).ok_or(Error::InputAllocation)?; // Both charges are admitted before rows, pointer journals or numeric // producers allocate. This preserves the old admission and VRAM cap. let mut txn = Self::begin_windowed256(session, binding, tokens, None, available)?; let mut states = Vec::new(); - states - .try_reserve_exact(tokens.len()) - .map_err(|_| Error::InputAllocation)?; + states.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; states.resize_with(tokens.len(), || PrefixState { ple: None, gdn: std::array::from_fn(|_| None), @@ -84,71 +71,158 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { Ok(txn) } - pub(in crate::qwen_forward) fn enable_device_gdn_verification(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,host_remaining:usize)->Result<()> { - self.check()?;self.origin.validate(self.session)?; - let context=self.session.mtp_context()?; - let Some(workspace)=cache.gdn_verification_workspace(binding,context)? else{return Ok(());}; - let metadata=workspace.try_borrow().map_err(|_|Error::IdentityMismatch)?.metadata_bytes()?; - let charged=host_charge_bounded(self.rows.len(),self.end,256)? - .checked_add(verification_extra_charge(self.rows.len(),self.end)?).and_then(|n|n.checked_add(metadata)).ok_or(Error::Overflow)?; - if charged>host_remaining.min(HOST_LIMIT){return Err(Error::InputAllocation);} - let journal=self.verification.as_mut().ok_or(Error::IdentityMismatch)?; - if journal.device_lease.is_some() || self.rows.len()>3 || self.next_layer!=0 || self.next_row!=0 {return Err(Error::IdentityMismatch);} - let lease=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.begin(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?; - journal.device_lease=Some(lease);Ok(()) + pub(in crate::qwen_forward) fn enable_device_gdn_verification( + &mut self, + binding: &ModelBinding, + cache: &crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>, + host_remaining: usize, + ) -> Result<()> { + self.check()?; + self.origin.validate(self.session)?; + let context = self.session.mtp_context()?; + let Some(workspace) = cache.gdn_verification_workspace(binding, context)? else { + return Ok(()); + }; + let metadata = workspace.try_borrow().map_err(|_| Error::IdentityMismatch)?.metadata_bytes()?; + let charged = host_charge_bounded(self.rows.len(), self.end, 256)? + .checked_add(verification_extra_charge(self.rows.len(), self.end)?) + .and_then(|n| n.checked_add(metadata)) + .ok_or(Error::Overflow)?; + if charged > host_remaining.min(HOST_LIMIT) { + return Err(Error::InputAllocation); + } + let journal = self.verification.as_mut().ok_or(Error::IdentityMismatch)?; + if journal.device_lease.is_some() || self.rows.len() > 3 || self.next_layer != 0 || self.next_row != 0 { + return Err(Error::IdentityMismatch); + } + let lease = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.begin( + &self.session.binding, + &self.origin, + &self.chunk, + self.rows.len(), + )?; + journal.device_lease = Some(lease); + Ok(()) } - pub(in crate::qwen_forward) fn device_gdn_lease(&self)->Result>>{ - let lease=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()); - if lease.is_none(){return Ok(None);} - self.check()?;self.origin.validate(self.session)?; - if let Some(lease)=lease{lease.validate(&self.session.binding,&self.origin,&self.chunk,self.rows.len())?;} + pub(in crate::qwen_forward) fn device_gdn_lease( + &self, + ) -> Result>> { + let lease = self.verification.as_ref().and_then(|j| j.device_lease.as_ref()); + if lease.is_none() { + return Ok(None); + } + self.check()?; + self.origin.validate(self.session)?; + if let Some(lease) = lease { + lease.validate(&self.session.binding, &self.origin, &self.chunk, self.rows.len())?; + } Ok(lease.cloned()) } - pub(in super::super::super) fn record_device_gdn(&mut self,index:usize,layer:LayerId,proof:Rc)->Result<()> { - let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; - let row=self.rows.get(index).ok_or(Error::IdentityMismatch)?; - proof.validate(&lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; - let state=self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states.get_mut(index).ok_or(Error::IdentityMismatch)?; - if state.gdn[layer.get() as usize].is_some() || state.device_gdn[layer.get() as usize].is_some(){return Err(Error::IdentityMismatch);} - state.device_gdn[layer.get() as usize]=Some(proof);Ok(()) + pub(in super::super::super) fn record_device_gdn( + &mut self, + index: usize, + layer: LayerId, + proof: Rc, + ) -> Result<()> { + let lease = self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; + let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?; + proof.validate(&lease, layer, index, TokenLayer::new(row.token, row.position, layer))?; + let state = self + .verification + .as_mut() + .ok_or(Error::IdentityMismatch)? + .states + .get_mut(index) + .ok_or(Error::IdentityMismatch)?; + if state.gdn[layer.get() as usize].is_some() || state.device_gdn[layer.get() as usize].is_some() { + return Err(Error::IdentityMismatch); + } + state.device_gdn[layer.get() as usize] = Some(proof); + Ok(()) } - pub(in super::super) fn replay_device_prefix(&self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,count:usize,mut cancelled:impl FnMut()->bool)->Result<[Option;STATE_CAPACITY]>{ - let lease=self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; - if count==0 || count>self.rows.len(){return Err(Error::IdentityMismatch);} - let workspace=cache.gdn_verification_workspace(binding,self.session.mtp_context()?)?.ok_or(Error::IdentityMismatch)?; - let mut sealed=std::array::from_fn(|_|None); - for (slot,output) in sealed.iter_mut().enumerate(){ - if !self.session.gdn_layers[slot]{continue;} - if cancelled(){return Err(Error::Unsupported(Stage::Executor));} + pub(in super::super) fn replay_device_prefix( + &self, + binding: &ModelBinding, + cache: &crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>, + count: usize, + mut cancelled: impl FnMut() -> bool, + ) -> Result<[Option; STATE_CAPACITY]> { + let lease = self.device_gdn_lease()?.ok_or(Error::IdentityMismatch)?; + if count == 0 || count > self.rows.len() { + return Err(Error::IdentityMismatch); + } + let workspace = + cache.gdn_verification_workspace(binding, self.session.mtp_context()?)?.ok_or(Error::IdentityMismatch)?; + let mut sealed = std::array::from_fn(|_| None); + for (slot, output) in sealed.iter_mut().enumerate() { + if !self.session.gdn_layers[slot] { + continue; + } + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } self.origin.validate(self.session)?; - let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - let mut proofs=Vec::new();proofs.try_reserve_exact(count).map_err(|_|Error::InputAllocation)?; + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + let mut proofs = Vec::new(); + proofs.try_reserve_exact(count).map_err(|_| Error::InputAllocation)?; for index in 0..count { - let state=self.validate_verification_state(index)?; - let proof=state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; - let actual=&self.rows[index];proof.validate(&lease,layer,index,TokenLayer::new(actual.token,actual.position,layer))?; + let state = self.validate_verification_state(index)?; + let proof = state.device_gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?; + let actual = &self.rows[index]; + proof.validate(&lease, layer, index, TokenLayer::new(actual.token, actual.position, layer))?; proofs.push(proof.clone()); } - let prior=workspace.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?.replay(&lease,&proofs,&mut cancelled)?; - prior.validate(&self.session.binding,&self.session.gdn_owner,layer,Position::new(self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?,crate::qwen_forward::contract::position_dimension())?)?; - *output=Some(prior); + let prior = workspace.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.replay( + &lease, + &proofs, + &mut cancelled, + )?; + prior.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + Position::new( + self.start_position().checked_add(count as u64).ok_or(Error::Overflow)?, + crate::qwen_forward::contract::position_dimension(), + )?, + )?; + *output = Some(prior); } - if cancelled(){return Err(Error::Unsupported(Stage::Executor));} - self.origin.validate(self.session)?;Ok(sealed) + if cancelled() { + return Err(Error::Unsupported(Stage::Executor)); + } + self.origin.validate(self.session)?; + Ok(sealed) } - pub(in crate::qwen_forward) fn seal_device_gdn_prefix(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,prefix:&VerifiedTargetPrefix,cancelled:impl FnMut()->bool)->Result<()> { + pub(in crate::qwen_forward) fn seal_device_gdn_prefix( + &mut self, + binding: &ModelBinding, + cache: &crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>, + prefix: &VerifiedTargetPrefix, + cancelled: impl FnMut() -> bool, + ) -> Result<()> { self.validate_verified_prefix(prefix)?; - if self.device_gdn_lease()?.is_none(){return Ok(());} + if self.device_gdn_lease()?.is_none() { + return Ok(()); + } // Stage ALL36 actual replayed canonical priors before either owner mutation. - let sealed=self.replay_device_prefix(binding,cache,prefix.count,cancelled)?; - self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[prefix.count-1].gdn=sealed;Ok(()) + let sealed = self.replay_device_prefix(binding, cache, prefix.count, cancelled)?; + self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[prefix.count - 1].gdn = sealed; + Ok(()) } - #[cfg(all(test,any(target_os="linux",target_os="windows"),target_arch="x86_64"))] - pub(in crate::qwen_forward) fn materialize_device_gdn_observer(&mut self,binding:&ModelBinding,cache:&crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>,mut cancelled:impl FnMut()->bool)->Result<()> { - if self.device_gdn_lease()?.is_none() || !crate::qwen_forward::mtp_decode::batch_gpu::collecting(){return Ok(());} - for count in 1..=self.rows.len(){ - let sealed=self.replay_device_prefix(binding,cache,count,&mut cancelled)?; - self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[count-1].gdn=sealed; + #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + pub(in crate::qwen_forward) fn materialize_device_gdn_observer( + &mut self, + binding: &ModelBinding, + cache: &crate::qwen_forward::dense_weight_cache::DenseWeightCache<'_>, + mut cancelled: impl FnMut() -> bool, + ) -> Result<()> { + if self.device_gdn_lease()?.is_none() || !crate::qwen_forward::mtp_decode::batch_gpu::collecting() { + return Ok(()); + } + for count in 1..=self.rows.len() { + let sealed = self.replay_device_prefix(binding, cache, count, &mut cancelled)?; + self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[count - 1].gdn = sealed; } Ok(()) } @@ -193,30 +267,21 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { { return Err(Error::IdentityMismatch); } - start.prior.validate(&self.session.binding, &self.session.gdn_owner, - start.layer, start.first)?; - Position::new(position.get().checked_add(1).ok_or(Error::Overflow)?, - crate::qwen_forward::contract::position_dimension()) + start.prior.validate(&self.session.binding, &self.session.gdn_owner, start.layer, start.first)?; + Position::new( + position.get().checked_add(1).ok_or(Error::Overflow)?, + crate::qwen_forward::contract::position_dimension(), + ) } - pub(in super::super::super) fn record_verification_ple( - &mut self, - index: usize, - position: Position, - ) -> Result<()> { + pub(in super::super::super) fn record_verification_ple(&mut self, index: usize, position: Position) -> Result<()> { if self.verification.is_none() { return Ok(()); } let end = self.verification_ple_row_position(index, position)?; - let prior = self - .next_ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))?; + let prior = self.next_ple.as_ref().ok_or(Error::Unsupported(Stage::Input))?; prior.validate(&self.session.binding, &self.session.ple_owner, end)?; let journal = self.verification.as_mut().ok_or(Error::IdentityMismatch)?; - let state = journal - .states - .get_mut(index) - .ok_or(Error::IdentityMismatch)?; + let state = journal.states.get_mut(index).ok_or(Error::IdentityMismatch)?; if state.ple.is_some() { return Err(Error::IdentityMismatch); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs index 4476bf1b..51cf6842 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_2_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in super::super::super) fn record_verification_prior( &mut self, @@ -23,9 +21,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { // Only the consumed producer prior is cloned; no numeric constructor, // stale initial state or advanced metadata is used for a prefix. if self.session.gdn_layers[slot] { - let prior = self.next_gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))?; + let prior = self.next_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?; prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; let state = self .verification @@ -39,9 +35,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } state.gdn[slot] = Some(prior.clone()); } else if self.session.qsa_layers[slot] { - let prior = self.next_qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))?; + let prior = self.next_qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?; prior.validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; let state = self .verification @@ -77,35 +71,45 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { .get(index) .ok_or(Error::IdentityMismatch)?; if self.session.ple_required { - state - .ple - .as_ref() - .ok_or(Error::Unsupported(Stage::Input))? - .validate(&self.session.binding, &self.session.ple_owner, end)?; + state.ple.as_ref().ok_or(Error::Unsupported(Stage::Input))?.validate( + &self.session.binding, + &self.session.ple_owner, + end, + )?; } else if state.ple.is_some() { return Err(Error::IdentityMismatch); } for slot in 0..STATE_CAPACITY { let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; if self.session.gdn_layers[slot] { - if let Some(lease)=self.verification.as_ref().and_then(|j|j.device_lease.as_ref()) { - state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? - .validate(lease,layer,index,TokenLayer::new(row.token,row.position,layer))?; - if let Some(prior)=&state.gdn[slot] {prior.validate(&self.session.binding,&self.session.gdn_owner,layer,end)?;} + if let Some(lease) = self.verification.as_ref().and_then(|j| j.device_lease.as_ref()) { + state.device_gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate( + lease, + layer, + index, + TokenLayer::new(row.token, row.position, layer), + )?; + if let Some(prior) = &state.gdn[slot] { + prior.validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + } } else { - state.gdn[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::Gdn))? - .validate(&self.session.binding, &self.session.gdn_owner, layer, end)?; + state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + end, + )?; } } else if state.gdn[slot].is_some() || state.device_gdn[slot].is_some() { return Err(Error::IdentityMismatch); } if self.session.qsa_layers[slot] { - state.qsa[slot] - .as_ref() - .ok_or(Error::Unsupported(Stage::QsaIndex))? - .validate(&self.session.binding, &self.session.qsa_owner, layer, end)?; + state.qsa[slot].as_ref().ok_or(Error::Unsupported(Stage::QsaIndex))?.validate( + &self.session.binding, + &self.session.qsa_owner, + layer, + end, + )?; } else if state.qsa[slot].is_some() { return Err(Error::IdentityMismatch); } @@ -116,10 +120,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in crate::qwen_forward) fn finish_mtp_verification( &mut self, residuals: &[Option], - mut execute_head: impl FnMut( - &mut QwenStepTxn<'_, 'driver>, - &InjectedResidual, - ) -> Result, + mut execute_head: impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, ) -> Result<()> { let result = self.finish_mtp_verification_inner(residuals, &mut execute_head); if let Err(error) = &result { @@ -131,18 +132,12 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { pub(in super::super) fn finish_mtp_verification_inner( &mut self, residuals: &[Option], - execute_head: &mut impl FnMut( - &mut QwenStepTxn<'_, 'driver>, - &InjectedResidual, - ) -> Result, + execute_head: &mut impl FnMut(&mut QwenStepTxn<'_, 'driver>, &InjectedResidual) -> Result, ) -> Result<()> { self.check()?; if self.finished || self.known_next.is_some() - || self - .verification - .as_ref() - .is_none_or(|j| j.states.len() != self.rows.len()) + || self.verification.as_ref().is_none_or(|j| j.states.len() != self.rows.len()) || self.next_layer != 48 || self.next_row != 0 || self.active_micro.is_some() @@ -154,18 +149,10 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } for (index, residual) in residuals.iter().enumerate() { let row = &self.rows[index]; - let residual = residual - .as_ref() - .ok_or(Error::Unsupported(Stage::Executor))?; + let residual = residual.as_ref().ok_or(Error::Unsupported(Stage::Executor))?; residual.validate_origin(&self.session.binding, GrRole::Ffn(47))?; - residual.identity().validate( - row.token, - row.position, - LayerId::new(47, Dimension::new(48)?)?, - )?; - if residual.streams().len() != 10240 - || residual.streams().iter().any(|v| !v.is_finite()) - { + residual.identity().validate(row.token, row.position, LayerId::new(47, Dimension::new(48)?)?)?; + if residual.streams().len() != 10240 || residual.streams().iter().any(|v| !v.is_finite()) { return Err(Error::NonFinite); } let state = self.validate_verification_state(index)?; @@ -215,9 +202,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { )?; } let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; streams.extend_from_slice(residual.streams()); self.witnesses.push(ChunkRowResidual { binding: self.session.binding.clone(), @@ -228,17 +213,9 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { known_next: self.rows.get(index + 1).map(|r| r.token), streams: Rc::new(streams.into_boxed_slice()), }); - self.verification - .as_mut() - .ok_or(Error::IdentityMismatch)? - .states[index] - .head = Some(head); + self.verification.as_mut().ok_or(Error::IdentityMismatch)?.states[index].head = Some(head); } - self.output = self - .verification - .as_ref() - .and_then(|j| j.states.last()) - .and_then(|s| s.head); + self.output = self.verification.as_ref().and_then(|j| j.states.last()).and_then(|s| s.head); self.finished = true; self.validate_publish()?; Ok(()) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs index 83258f80..4b5df541 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_qwenchunktxn/impl_qwenchunktxn_3.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { - pub(in crate::qwen_forward) fn select_verified_prefix( &self, binding: &ModelBinding, @@ -30,29 +27,13 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { // Every row is genuine and complete, including a rejected tail. for index in 0..self.rows.len() { tokens[index] = self.rows[index].token; - heads[index] = self - .validate_verification_state(index)? - .head - .ok_or(Error::Unsupported(Stage::Output))?; + heads[index] = self.validate_verification_state(index)?.head.ok_or(Error::Unsupported(Stage::Output))?; } - let (count, expected) = greedy_prefix( - seed, - eos, - &tokens[..self.rows.len()], - &heads[..self.rows.len()], - )?; - Ok(VerifiedTargetPrefix { - chunk: self.chunk.clone(), - origin: self.origin.clone(), - count, - next: expected, - }) + let (count, expected) = greedy_prefix(seed, eos, &tokens[..self.rows.len()], &heads[..self.rows.len()])?; + Ok(VerifiedTargetPrefix { chunk: self.chunk.clone(), origin: self.origin.clone(), count, next: expected }) } - pub(in crate::qwen_forward) fn validate_verified_prefix( - &self, - prefix: &VerifiedTargetPrefix, - ) -> Result<()> { + pub(in crate::qwen_forward) fn validate_verified_prefix(&self, prefix: &VerifiedTargetPrefix) -> Result<()> { self.validate_publish()?; if !Rc::ptr_eq(&prefix.chunk, &self.chunk) || !prefix.origin.same_prefix(&self.origin) @@ -63,9 +44,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { } prefix.origin.validate(self.session)?; for index in 0..self.rows.len() { - self.validate_verification_state(index)? - .head - .ok_or(Error::Unsupported(Stage::Output))?; + self.validate_verification_state(index)?.head.ok_or(Error::Unsupported(Stage::Output))?; } if self.validate_verification_state(prefix.count - 1)?.head != Some(prefix.next) { return Err(Error::IdentityMismatch); @@ -83,32 +62,29 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.session.complete_cuda()?; let row = &self.rows[prefix.count - 1]; let source = &self.witnesses[prefix.count - 1]; - let predecessors = [ - row.predecessors[1], - i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?, - ]; + let predecessors = [row.predecessors[1], i32::try_from(row.token.get()).map_err(|_| Error::InvalidToken)?]; let end = row.position.get().checked_add(1).ok_or(Error::Overflow)?; let mut streams = Vec::new(); - streams - .try_reserve_exact(10240) - .map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(10240).map_err(|_| Error::InputAllocation)?; streams.extend_from_slice(source.streams.as_ref()); let streams = streams.into_boxed_slice(); let binding = source.binding.clone(); let token = row.token; let position = row.position; let journal = self.verification.take().ok_or(Error::IdentityMismatch)?; - let state = journal - .states - .into_iter() - .nth(prefix.count - 1) - .ok_or(Error::IdentityMismatch)?; + let state = journal.states.into_iter().nth(prefix.count - 1).ok_or(Error::IdentityMismatch)?; if journal.device_lease.is_some() { - let end_position=Position::new(end,crate::qwen_forward::contract::position_dimension())?; - for slot in 0..STATE_CAPACITY {if self.session.gdn_layers[slot] { - state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))? - .validate(&self.session.binding,&self.session.gdn_owner,LayerId::new(slot as u64,Dimension::new(48)?)?,end_position)?; - }} + let end_position = Position::new(end, crate::qwen_forward::contract::position_dimension())?; + for slot in 0..STATE_CAPACITY { + if self.session.gdn_layers[slot] { + state.gdn[slot].as_ref().ok_or(Error::Unsupported(Stage::Gdn))?.validate( + &self.session.binding, + &self.session.gdn_owner, + LayerId::new(slot as u64, Dimension::new(48)?)?, + end_position, + )?; + } + } } // All fallible work precedes either owner mutation. Rejected tail // states and row witnesses are dropped; no epoch or position rewind. @@ -119,13 +95,6 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> { self.session.next_position = end; draft.publish(); let origin = super::super::super::super::checkpoint::committed_origin(self.session); - Ok(ChunkCommit { - binding, - token, - position, - output: Some(prefix.next), - streams, - origin, - }) + Ok(ChunkCommit { binding, token, position, output: Some(prefix.next), streams, origin }) } } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_verifiedtargetprefix.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_verifiedtargetprefix.rs index da9a4bbe..ce74e3f2 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_verifiedtargetprefix.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/impl_verifiedtargetprefix.rs @@ -20,9 +20,7 @@ pub(super) fn verification_extra_charge(tokens: usize, end: u64) -> Result>()) .ok_or(Error::Overflow)?; - let state = (36usize * (786432 + 30720) * 4 + 9 * 10240 * 4) - .checked_add(qsa) - .ok_or(Error::Overflow)?; + let state = (36usize * (786432 + 30720) * 4 + 9 * 10240 * 4).checked_add(qsa).ok_or(Error::Overflow)?; extra .checked_mul(state) .and_then(|n| n.checked_add(tokens * std::mem::size_of::())) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/tests.rs index 309ed105..aa681ad9 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_chunk_verify/tests.rs @@ -10,71 +10,32 @@ fn real_head_decision_stops_at_first_rejection_or_eos() { let heads = [token(11), token(12), token(13)]; let eos_token = token(2); let eos = Some(eos_token); + assert_eq!(greedy_prefix(ids[0], None, &ids, &heads), Ok((3, token(13)))); assert_eq!( - greedy_prefix(ids[0], None, &ids, &heads), - Ok((3, token(13))) - ); - assert_eq!( - greedy_prefix( - ids[0], - None, - &[ids[0], ids[1], eos_token], - &[ids[1], eos_token, token(13)] - ), + greedy_prefix(ids[0], None, &[ids[0], ids[1], eos_token], &[ids[1], eos_token, token(13)]), Ok((3, token(13))) ); assert_eq!(greedy_prefix(ids[0], eos, &ids, &heads), Ok((3, token(13)))); - assert_eq!( - greedy_prefix(ids[0], eos, &[ids[0], token(99), ids[2]], &heads), - Ok((1, token(11))) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &[ids[0], ids[1], token(99)], &heads), - Ok((2, token(12))) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &ids, &[eos_token, ids[2], token(13)]), - Ok((1, eos_token)) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &[token(99)], &heads[..1]), - Err(Error::IdentityMismatch) - ); - assert_eq!( - greedy_prefix(eos_token, eos, &ids, &heads), - Err(Error::IdentityMismatch) - ); - assert_eq!( - greedy_prefix(ids[0], eos, &ids, &heads[..2]), - Err(Error::IdentityMismatch) - ); + assert_eq!(greedy_prefix(ids[0], eos, &[ids[0], token(99), ids[2]], &heads), Ok((1, token(11)))); + assert_eq!(greedy_prefix(ids[0], eos, &[ids[0], ids[1], token(99)], &heads), Ok((2, token(12)))); + assert_eq!(greedy_prefix(ids[0], eos, &ids, &[eos_token, ids[2], token(13)]), Ok((1, eos_token))); + assert_eq!(greedy_prefix(ids[0], eos, &[token(99)], &heads[..1]), Err(Error::IdentityMismatch)); + assert_eq!(greedy_prefix(eos_token, eos, &ids, &heads), Err(Error::IdentityMismatch)); + assert_eq!(greedy_prefix(ids[0], eos, &ids, &heads[..2]), Err(Error::IdentityMismatch)); } #[test] fn complete_journal_charge_preserves_512_mib_refusal() { - assert_eq!( - verification_extra_charge(0, 1), - Err(Error::InvalidDimension) - ); - assert_eq!( - verification_extra_charge(5, 5), - Err(Error::InvalidDimension) - ); - assert_eq!( - verification_extra_charge(2, 262145), - Err(Error::InvalidDimension) - ); + assert_eq!(verification_extra_charge(0, 1), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(5, 5), Err(Error::InvalidDimension)); + assert_eq!(verification_extra_charge(2, 262145), Err(Error::InvalidDimension)); for rows in [2, 3] { let charge = host_charge_bounded(rows, rows as u64, 256).unwrap() + verification_extra_charge(rows, rows as u64).unwrap(); assert!(charge < HOST_LIMIT); } - let four = - host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); + let four = host_charge_bounded(4, 4, 256).unwrap() + verification_extra_charge(4, 4).unwrap(); assert!(four > HOST_LIMIT); - assert!( - verification_extra_charge(3, 190000).unwrap() - > verification_extra_charge(3, 3).unwrap() - ); + assert!(verification_extra_charge(3, 190000).unwrap() > verification_extra_charge(3, 3).unwrap()); } // This tests private session/phase admission, NOT a ModelBinding, CUDA @@ -89,19 +50,47 @@ fn ple_gdn_fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a let input = crate::qwen_forward::input::InputReady::test_fixture(token(3), position, binding); QwenChunkTxn { verification: Some(VerificationJournal { - states: vec![PrefixState { ple: None, gdn: std::array::from_fn(|_| None), + states: vec![PrefixState { + ple: None, + gdn: std::array::from_fn(|_| None), device_gdn: std::array::from_fn(|_| None), - qsa: std::array::from_fn(|_| None), head: None }], device_lease: None, + qsa: std::array::from_fn(|_| None), + head: None, + }], + device_lease: None, }), - next_ple: None, next_gdn: std::array::from_fn(|_| None), gdn_chunk: None, - next_qsa: std::array::from_fn(|_| None), session, origin, chunk: Rc::new(()), - rows: vec![Row { token: token(3), position, predecessors: [-1, -1], - input: Some(Rc::new(input)), completed: 1 }], - witnesses: Vec::new(), next_layer: 1, next_row: 0, batch_layer: None, - batch_rows: Vec::new(), batch_completed: 0, attention_layer: None, - attention_next: 0, attention_sources: Vec::new(), attention_authorized: None, - known_next: None, output: None, finished: false, aborted: false, end: 1, - windowed: true, micro_cursor: 0, active_micro: None, + next_ple: None, + next_gdn: std::array::from_fn(|_| None), + gdn_chunk: None, + next_qsa: std::array::from_fn(|_| None), + session, + origin, + chunk: Rc::new(()), + rows: vec![Row { + token: token(3), + position, + predecessors: [-1, -1], + input: Some(Rc::new(input)), + completed: 1, + }], + witnesses: Vec::new(), + next_layer: 1, + next_row: 0, + batch_layer: None, + batch_rows: Vec::new(), + batch_completed: 0, + attention_layer: None, + attention_next: 0, + attention_sources: Vec::new(), + attention_authorized: None, + known_next: None, + output: None, + finished: false, + aborted: false, + end: 1, + windowed: true, + micro_cursor: 0, + active_micro: None, #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] test_micro_width: 64, #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] @@ -124,8 +113,7 @@ fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { let window = txn.open_micro_window(layer).unwrap(); txn.attention_layer = Some(layer); let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); - let pending = PlePending::test_next(&prior, - &TokenLayer::new(token(3), position, layer)).unwrap(); + let pending = PlePending::test_next(&prior, &TokenLayer::new(token(3), position, layer)).unwrap(); pending.validate(&prior, TokenLayer::new(token(3), position, layer)).unwrap(); let next = pending.into_prior(); txn.next_ple = Some(next.clone()); @@ -143,9 +131,16 @@ fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { 1 | 2 | 3 => { let anchor = &start.0; txn.gdn_chunk.as_mut().unwrap().start = GdnChunkStart(Rc::new(GdnChunkAnchor { - binding: anchor.binding.clone(), chunk: anchor.chunk.clone(), prior: anchor.prior.clone(), - layer: if refusal == 1 { LayerId::new(0, Dimension::new(48).unwrap()).unwrap() } else { anchor.layer }, - first: anchor.first, end: if refusal == 2 { 2 } else { anchor.end }, + binding: anchor.binding.clone(), + chunk: anchor.chunk.clone(), + prior: anchor.prior.clone(), + layer: if refusal == 1 { + LayerId::new(0, Dimension::new(48).unwrap()).unwrap() + } else { + anchor.layer + }, + first: anchor.first, + end: if refusal == 2 { 2 } else { anchor.end }, count: if refusal == 3 { 2 } else { anchor.count }, })); } @@ -157,8 +152,9 @@ fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { 9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(), 10 => { let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap(); - txn.next_ple = Some(PlePending::test_next(&foreign, - &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); + txn.next_ple = Some( + PlePending::test_next(&foreign, &TokenLayer::new(token(3), position, layer)).unwrap().into_prior(), + ); } 11 => txn.aborted = true, 12 => txn.session.reset().unwrap(), @@ -177,8 +173,8 @@ fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() { let mut session = QwenSession::test_session(BindingIdentity::test_identity()); let mut txn = ple_gdn_fixture(&mut session); let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap(); - txn.next_ple = Some(PlePending::test_next(&prior, - &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); + txn.next_ple = + Some(PlePending::test_next(&prior, &TokenLayer::new(token(3), position, layer)).unwrap().into_prior()); assert_eq!(txn.record_verification_ple(0, position), Ok(())); assert_eq!(txn.record_verification_ple(0, position), Err(Error::IdentityMismatch)); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs index bbaf245d..b94bd5ca 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft.rs @@ -1,332 +1,85 @@ //! Canonical Original INT8 draft owner. Actual immutable driver snapshots are //! bound to the real target branch; end metadata never invents older KV cells. use super::*; -use leleka_cuda_driver::{Context,MtpOriginalInt8,MtpInt8Snapshot,CompletedDraftKv,CompletedOriginalMtpDraft}; +use leleka_cuda_driver::{CompletedDraftKv, CompletedOriginalMtpDraft, Context, MtpInt8Snapshot, MtpOriginalInt8}; -pub(in crate::qwen_forward) struct OriginalDraftSession<'ctx>{ - binding:BindingIdentity,context:&'ctx Context<'ctx>,origin:TargetStepOrigin, - ring:Option>,snapshot:MtpInt8Snapshot, - first_materialized:usize,failed:bool, +pub(in crate::qwen_forward) struct OriginalDraftSession<'ctx> { + binding: BindingIdentity, + context: &'ctx Context<'ctx>, + origin: TargetStepOrigin, + ring: Option>, + snapshot: MtpInt8Snapshot, + first_materialized: usize, + failed: bool, } -pub(in crate::qwen_forward) struct OriginalDraftCheckpoint{ - binding:BindingIdentity,origin:TargetStepOrigin,snapshot:MtpInt8Snapshot,first_materialized:usize, -} -impl OriginalDraftCheckpoint{ - /// Host bytes of the ring image (prefix-cache accounting; pages shared with neighbouring points are counted in full). - pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.snapshot.encoded_bytes()} +pub(in crate::qwen_forward) struct OriginalDraftCheckpoint { + binding: BindingIdentity, + origin: TargetStepOrigin, + snapshot: MtpInt8Snapshot, + first_materialized: usize, } /// Exclusive canonical loan is held until all target permits are prepared and /// CUDA has completed. Publication below is only infallible assignment. -pub(super) struct OriginalDraftPublication<'a,'ctx>{ - owner:&'a mut OriginalDraftSession<'ctx>,snapshot:MtpInt8Snapshot,first_materialized:usize, -} -impl<'ctx> OriginalDraftSession<'ctx>{ - pub(in crate::qwen_forward) fn new(binding:&ModelBinding,session:&QwenSession<'ctx>, - context:&'ctx Context<'ctx>)->Result{ - let origin=session.target_origin()?; - if origin.next_position()!=0||!binding.identity().matches(&session.binding) - ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - let ring=context.mtp_original_int8(8).map_err(draft_driver_error)?; - let snapshot=ring.empty_snapshot().map_err(draft_driver_error)?; - Ok(Self{binding:binding.identity(),context,origin,ring:Some(ring),snapshot, - first_materialized:0,failed:false}) - } - /// Literal MtpDrafter::init handoff. The shared-layout constructor owns - /// the physical INT8 state before it creates the scalar/full graph pair; - /// this constructor preserves that owner instead of allocating a second - /// independent ring for the same session. - pub(in crate::qwen_forward) fn from_original_ring(binding:&ModelBinding, - session:&QwenSession<'ctx>,context:&'ctx Context<'ctx>,ring:MtpOriginalInt8<'ctx>) - ->Result{ - let origin=session.target_origin()?; - if origin.next_position()!=0||!binding.identity().matches(&session.binding) - ||!std::ptr::eq(context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - ring.validate_context(context).map_err(draft_driver_error)?; - let snapshot=ring.empty_snapshot().map_err(draft_driver_error)?; - Ok(Self{binding:binding.identity(),context,origin,ring:Some(ring),snapshot, - first_materialized:0,failed:false}) - } - fn validate(&self,binding:&ModelBinding,origin:&TargetStepOrigin)->Result<()> { - if self.failed||self.context.is_poisoned(){return Err(Error::CudaExecution);} - if !self.binding.matches(&binding.identity())||!self.origin.same_prefix(origin) - ||(self.snapshot.next_position() as u64)self.snapshot.next_position(){ - crate::bringup_trace!("DBG draft.validate mismatch: binding_ok={} same_prefix={} snapshot_next={} target_next={} draft_origin_next={} first_materialized={}", - self.binding.matches(&binding.identity()), self.origin.same_prefix(origin), self.snapshot.next_position(), - origin.next_position(), self.origin.next_position(), self.first_materialized); - return Err(Error::IdentityMismatch);} - let ring=self.ring.as_ref().ok_or(Error::IdentityMismatch)?; - ring.validate_context(self.context).map_err(draft_driver_error)?; - ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error) - } - pub(in crate::qwen_forward) fn checkpoint(&self,binding:&ModelBinding,session:&QwenSession<'ctx>)->Result{ - let origin=session.target_origin()?;self.validate(binding,&origin)?; - Ok(OriginalDraftCheckpoint{binding:self.binding.clone(),origin,snapshot:self.snapshot.clone(), - first_materialized:self.first_materialized}) - } - /// Only the authentic target transaction can lend this canonical snapshot - /// and its actual device owner to the draft producer. - pub(in crate::qwen_forward) fn with_pending_ring(&mut self,binding:&ModelBinding, - txn:&OriginalPromptTxn<'_, 'ctx>,execute:impl FnOnce(&mut MtpOriginalInt8<'ctx>,&MtpInt8Snapshot,usize)->Result)->Result{ - txn.check()?;self.validate(binding,&txn.phase.origin)?; - let first_needed=usize::try_from(txn.end_position()).map_err(|_|Error::Overflow)? - .saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW); - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - let result=execute(ring,&self.snapshot,first_needed); - if ring.is_failed()||self.context.is_poisoned(){self.failed=true;} - result - } - /// Verified serve rounds have no prompt transaction: their authoritative - /// proof is the current target origin plus a completed verifier window. - /// This lends the same canonical ring only while its physical snapshot - /// exactly matches that target origin; an older or future draft cannot be - /// presented as the current verification branch. - pub(in crate::qwen_forward) fn with_current_ring(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,execute:impl FnOnce(&mut MtpOriginalInt8<'ctx>,&MtpInt8Snapshot)->Result)->Result{ - let origin=session.target_origin()?; - self.validate(binding,&origin)?; - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - let result=execute(ring,&self.snapshot); - if ring.is_failed()||self.context.is_poisoned(){self.failed=true;} - result - } - /// Literal generate.cpp ordering for a verified serve window: the target - /// owner has already committed `a + 1` rows, while this independent MTP - /// ring is still anchored at the pre-window snapshot. A normal prompt - /// loan cannot express that intentional position skew, so this transition - /// requires both real origins explicitly. It never advances target state. - pub(in crate::qwen_forward) fn with_mtp_transition_ring(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,before:&TargetStepOrigin,committed:&TargetStepOrigin, - execute:impl FnOnce(&mut MtpOriginalInt8<'ctx>,&MtpInt8Snapshot)->Result)->Result{ - if self.failed||!self.binding.matches(&binding.identity())||!self.origin.same_prefix(before) - ||!before.same_session(committed)||!std::ptr::eq(self.context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - // `before` belongs to the same surviving branch, whereas `committed` - // is the only current target origin. The prior position intentionally - // differs after the verifier has published its accepted prefix. - before.validate_projection_branch(session)?; - committed.validate(session)?; - if committed.next_position()<=before.next_position(){return Err(Error::IdentityMismatch);} - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - ring.validate_context(self.context).map_err(draft_driver_error)?; - ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; - let result=execute(ring,&self.snapshot); - if ring.is_failed()||self.context.is_poisoned(){self.failed=true;} - result - } - /// `with_mtp_transition_ring` for a draft LAUNCHED while the verifier's commit of `prospective` is enqueued and - /// not yet published (generate.cpp enqueues the draft behind the commit): the session still stands exactly at - /// `before`; `prospective` must be the same branch, further on. The completion is published only through - /// `with_mtp_transition_ring` + `publish_mtp_completion` once the session holds `prospective`. - pub(in crate::qwen_forward) fn with_mtp_launch_ring(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,before:&TargetStepOrigin,prospective:&TargetStepOrigin, - execute:impl FnOnce(&mut MtpOriginalInt8<'ctx>,&MtpInt8Snapshot)->Result)->Result{ - if self.failed||!self.binding.matches(&binding.identity())||!self.origin.same_prefix(before) - ||!before.same_branch(prospective)||!std::ptr::eq(self.context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - before.validate(session)?; - if prospective.next_position()<=before.next_position(){return Err(Error::IdentityMismatch);} - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - ring.validate_context(self.context).map_err(draft_driver_error)?; - ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; - let result=execute(ring,&self.snapshot); - if ring.is_failed()||self.context.is_poisoned(){self.failed=true;} - result - } - /// Rebinds only the independent MTP ring after its fully drained source - /// draft. The target state was committed by the verifier beforehand; this - /// is deliberately incapable of minting or modifying a target origin. - pub(in crate::qwen_forward) fn publish_mtp_completion(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,before:&TargetStepOrigin,committed:&TargetStepOrigin, - completed:&CompletedOriginalMtpDraft<'ctx>)->Result<()>{ - // The preceding graph replaced `self.snapshot` with its completed - // speculative snapshot, so this publication must validate that new - // physical current state directly. Re-entering the pre-graph loan - // would incorrectly demand the old snapshot after a successful draft. - if self.failed||!self.binding.matches(&binding.identity())||!self.origin.same_prefix(before) - ||!before.same_session(committed)||!std::ptr::eq(self.context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - before.validate_projection_branch(session)?; - committed.validate(session)?; - if committed.next_position()<=before.next_position(){return Err(Error::IdentityMismatch);} - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - ring.validate_context(self.context).map_err(draft_driver_error)?; - completed.validate_current(ring).map_err(draft_driver_error)?; - self.origin=committed.clone(); - self.snapshot=completed.final_snapshot().clone(); - self.first_materialized=self.first_materialized.min(self.snapshot.next_position()); - Ok(()) - } - /// A completed MTP receipt is valid only for the exact committed target - /// branch that produced it. Its ring may extend beyond target position - /// with provisional catch-up cells, which is why `with_current_ring` is - /// intentionally not used here. - pub(in crate::qwen_forward) fn with_mtp_current_ring(&mut self,binding:&ModelBinding, - session:&QwenSession<'ctx>,origin:&TargetStepOrigin, - execute:impl FnOnce(&mut MtpOriginalInt8<'ctx>,&MtpInt8Snapshot)->Result)->Result{ - if self.failed||!self.binding.matches(&binding.identity())||!self.origin.same_prefix(origin) - ||!std::ptr::eq(self.context,session.mtp_context()?){return Err(Error::IdentityMismatch);} - origin.validate(session)?; - let ring=self.ring.as_mut().ok_or(Error::IdentityMismatch)?; - ring.validate_context(self.context).map_err(draft_driver_error)?; - ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; - let result=execute(ring,&self.snapshot); - if ring.is_failed()||self.context.is_poisoned(){self.failed=true;} - result - } - pub(super) fn prepare_publication<'a>(&'a mut self,binding:&ModelBinding,txn:&OriginalPromptTxn<'_, 'ctx>, - completed:&CompletedDraftKv)->Result>{ - self.validate(binding,&txn.phase.origin)?; - let ring=self.ring.as_ref().ok_or(Error::IdentityMismatch)?; - completed.validate_current(ring).map_err(draft_driver_error)?; - let end=usize::try_from(txn.end_position()).map_err(|_|Error::Overflow)?; - let start=usize::try_from(txn.start_position()).map_err(|_|Error::Overflow)?; - let first_materialized=published_first_materialized(self.first_materialized,self.snapshot.next_position(), - start,completed.first_materialized(),end); - if completed.next_position()!=end||end==0 - ||first_materialized>end.saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW) - ||!completed.owner_id().same_owner(&self.snapshot.owner_id()){ - crate::bringup_trace!("DBG draft.prepare_publication refused: start={start} end={end} completed_next={} completed_first={} prior_first={} prior_next={} lower={first_materialized} same_owner={}", - completed.next_position(),completed.first_materialized(),self.first_materialized,self.snapshot.next_position(), - completed.owner_id().same_owner(&self.snapshot.owner_id())); - return Err(Error::IdentityMismatch); - } - let snapshot=completed.snapshot_after(end-1).map_err(draft_driver_error)?; - ring.validate_snapshot(&snapshot).map_err(draft_driver_error)?; - Ok(OriginalDraftPublication{owner:self,snapshot,first_materialized}) - } - /// All physical restores are attempted by the coupled target owner. An - /// uncertain ring restore poisons this owner even when target rollback works. - pub(super) fn restore_physical(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - prior:&OriginalDraftCheckpoint)->Result<()> { - if self.failed||!self.binding.matches(&binding.identity())||!prior.binding.matches(&self.binding) - ||!self.origin.same_prefix(&prior.origin){return Err(Error::IdentityMismatch);} - let context=dense.retained_context(binding,self.context)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let result=self.ring.as_mut().ok_or(Error::IdentityMismatch)?.restore(&mut workspace,&prior.snapshot) - .map_err(draft_driver_error); - if result.is_err(){self.failed=true;} - result - } - /// Roll the MTP ring back to `prior` and rebind it to the (already restored) target branch. The - /// serve host calls this for a failed round after the target side was repaired: both physical - /// restores are attempted by the caller's order (target first, then this). - pub(in crate::qwen_forward) fn restore_current(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&QwenSession<'ctx>,prior:&OriginalDraftCheckpoint)->Result<()> { - self.restore_physical(binding,dense,prior)?; - let actual=session.target_origin()?; - self.rebind_restored(prior,&actual) - } - /// A new request starts from the empty prompt: roll the ring back to the empty snapshot taken at load - /// (`empty`, position 0) and rebind it to the session, which must stand at position 0 again. Unlike - /// `restore_current` the draft's current origin is NOT required to equal the checkpoint's: the whole - /// previous request lies between them, and the empty ring holds no history to disagree with. - pub(in crate::qwen_forward) fn reset_to_empty(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&QwenSession<'ctx>,empty:&OriginalDraftCheckpoint)->Result<()> { - let actual=session.target_origin()?; - if self.failed||!self.binding.matches(&binding.identity())||!empty.binding.matches(&self.binding) - ||empty.origin.next_position()!=0||empty.snapshot.next_position()!=0||empty.first_materialized!=0 - ||actual.next_position()!=0||!actual.same_session(&empty.origin)||!self.origin.same_session(&actual){ - return Err(Error::IdentityMismatch); - } - let context=dense.retained_context(binding,self.context)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let result=self.ring.as_mut().ok_or(Error::IdentityMismatch)?.restore(&mut workspace,&empty.snapshot) - .map_err(draft_driver_error); - if result.is_err(){self.failed=true;return result;} - self.origin=actual;self.snapshot=empty.snapshot.clone();self.first_materialized=0;Ok(()) - } - /// Conversation resume (generate.cpp `mtp.kv_restore(resume)` after a checkpoint restore): roll the ring - /// back to the snapshot `point` saved together with the target checkpoint the session was just restored to, - /// and rebind it to the session. As in `reset_to_empty` the draft's current origin is not required to equal - /// the checkpoint's (a later turn and a generation bump lie between them); the checkpoint must name the - /// session's position and its snapshot must cover it. The snapshot is an immutable host image, so the - /// restored ring holds exactly the cells it held when the checkpoint was taken. - pub(in crate::qwen_forward) fn resume_at(&mut self,binding:&ModelBinding,dense:&DenseWeightCache<'ctx>, - session:&QwenSession<'ctx>,point:&OriginalDraftCheckpoint)->Result<()> { - let actual=session.target_origin()?; - if self.failed||!self.binding.matches(&binding.identity())||!point.binding.matches(&self.binding) - ||!actual.same_session(&point.origin)||!self.origin.same_session(&actual) - ||point.origin.next_position()!=actual.next_position() - ||(point.snapshot.next_position() as u64)point.snapshot.next_position(){ - return Err(Error::IdentityMismatch); - } - let context=dense.retained_context(binding,self.context)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let result=self.ring.as_mut().ok_or(Error::IdentityMismatch)?.restore(&mut workspace,&point.snapshot) - .map_err(draft_driver_error); - if result.is_err(){self.failed=true;return result;} - self.origin=actual;self.snapshot=point.snapshot.clone();self.first_materialized=point.first_materialized;Ok(()) - } - /// Whether the ring stands at the session's current origin (a request can continue from it as is). - pub(in crate::qwen_forward) fn in_step(&self,binding:&ModelBinding,session:&QwenSession<'ctx>)->bool{ - session.target_origin().is_ok_and(|origin|self.validate(binding,&origin).is_ok()) - } - pub(super) fn rebind_restored(&mut self,prior:&OriginalDraftCheckpoint,actual:&TargetStepOrigin)->Result<()> { - if self.failed||!self.origin.same_prefix(&prior.origin)||!actual.same_session(&prior.origin) - ||actual.next_position()!=prior.origin.next_position() - ||(prior.snapshot.next_position() as u64)Result<()>{self.close_inner()} - fn close_inner(&mut self)->Result<()>{self.failed=true;self.ring.take().map_or(Ok(()),|ring|ring.close().map_err(draft_driver_error))} -} -impl OriginalDraftPublication<'_, '_>{ - pub(super) fn publish_validated(self,actual:TargetStepOrigin){ - self.owner.origin=actual;self.owner.snapshot=self.snapshot;self.owner.first_materialized=self.first_materialized; - } -} -impl Drop for OriginalDraftSession<'_>{fn drop(&mut self){let _=self.close_inner();}} -/// The ring's lower materialized bound after a prompt chunk `[start, end)` whose recording materialized -/// `[chunk_first, end)`. The driver reports the chunk's own bound (`cell0 + r0`); when the chunk starts where -/// the ring's materialized range already reaches (`prior_next >= start`) and recorded from its first row, the -/// range simply continues and keeps the earlier bound. A chunk that skipped its leading rows (the Original's -/// `first_needed` cut) starts a new range at its own bound. Taking the chunk's bound alone made every chunk -/// after the first look as if `[0, start)` had never been recorded, so the second chunk of every multi-chunk -/// prompt was refused (`first_materialized > end - MTP_ORIGINAL_WINDOW`). -fn published_first_materialized(prior_first:usize,prior_next:usize,start:usize,chunk_first:usize,end:usize)->usize{ - if chunk_first==start&&prior_next>=start&&prior_first<=start&&start { + owner: &'a mut OriginalDraftSession<'ctx>, + snapshot: MtpInt8Snapshot, + first_materialized: usize, } #[cfg(test)] -mod first_materialized_tests{ +mod first_materialized_tests { use super::published_first_materialized as lower; use leleka_cuda_driver::MTP_ORIGINAL_WINDOW as W; /// Walk a whole prompt in chunks the way `prefill_actions` does and check every publication's bound. - fn walk(prompt:usize,chunk:usize)->Vec<(usize,usize)>{ - let (mut first,mut next)=(0usize,0usize);let mut out=Vec::new(); - let mut start=0; - while start Vec<(usize, usize)> { + let (mut first, mut next) = (0usize, 0usize); + let mut out = Vec::new(); + let mut start = 0; + while start < prompt - 1 { + let end = (start + chunk).min(prompt - 1); // with_pending_ring: first_needed = end - window; the driver records from max(first_needed, start) - let chunk_first=end.saturating_sub(W).max(start); - first=lower(first,next,start,chunk_first,end);next=end;out.push((first,end));start=end;} + let chunk_first = end.saturating_sub(W).max(start); + first = lower(first, next, start, chunk_first, end); + next = end; + out.push((first, end)); + start = end; + } out } #[test] - fn contiguous_chunks_keep_the_rings_lower_bound(){ + fn contiguous_chunks_keep_the_rings_lower_bound() { // the 8000-token prompt of job 311: four 2048-row chunks - for (first,end) in walk(8000,2048) {assert_eq!(first,0);assert!(first<=end.saturating_sub(W));} + for (first, end) in walk(8000, 2048) { + assert_eq!(first, 0); + assert!(first <= end.saturating_sub(W)); + } // the 40000-token prompt of job 310: twenty chunks, past the 32768-cell window - for (first,end) in walk(40000,2048) {assert!(first<=end.saturating_sub(W),"{first} {end}");} - assert_eq!(lower(0,2048,2048,2048,4096),0); + for (first, end) in walk(40000, 2048) { + assert!(first <= end.saturating_sub(W), "{first} {end}"); + } + assert_eq!(lower(0, 2048, 2048, 2048, 4096), 0); } #[test] - fn a_chunk_that_skipped_rows_or_left_a_gap_starts_a_new_range(){ - assert_eq!(lower(0,2048,2048,2100,4096),2100); // leading rows skipped - assert_eq!(lower(0,1024,2048,2048,4096),2048); // the ring did not reach the chunk's start - assert_eq!(lower(0,0,0,0,2048),0); // first chunk + fn a_chunk_that_skipped_rows_or_left_a_gap_starts_a_new_range() { + assert_eq!(lower(0, 2048, 2048, 2100, 4096), 2100); // leading rows skipped + assert_eq!(lower(0, 1024, 2048, 2048, 4096), 2048); // the ring did not reach the chunk's start + assert_eq!(lower(0, 0, 0, 0, 2048), 0); // first chunk } #[test] - fn the_old_rule_refused_the_second_chunk(){ + fn the_old_rule_refused_the_second_chunk() { // what publication checked before: the chunk's own bound against the window - let (start,end)=(2048usize,4096usize); - assert!(start>end.saturating_sub(W)); - assert!(lower(0,start,start,start,end)<=end.saturating_sub(W)); + let (start, end) = (2048usize, 4096usize); + assert!(start > end.saturating_sub(W)); + assert!(lower(0, start, start, start, end) <= end.saturating_sub(W)); } } -fn draft_driver_error(error:leleka_cuda_driver::Error)->Error{match error{ - leleka_cuda_driver::Error::ContextMismatch=>Error::IdentityMismatch, - leleka_cuda_driver::Error::InvalidQwenShape|leleka_cuda_driver::Error::InvalidSize=>Error::InvalidDimension, - leleka_cuda_driver::Error::BudgetExceeded|leleka_cuda_driver::Error::HostAllocation=>Error::InputAllocation, - leleka_cuda_driver::Error::NonFiniteMmqOutput(_)=>Error::NonFinite, - leleka_cuda_driver::Error::UnsupportedQwenOperation=>Error::Unsupported(Stage::Session), - _=>Error::CudaExecution, -}} + +#[path = "session_original_draft/impl_originaldraftcheckpoint.rs"] +mod impl_originaldraftcheckpoint; +#[path = "session_original_draft/impl_originaldraftsession_2.rs"] +mod impl_originaldraftsession_2; +#[path = "session_original_draft/published_first_materialized_fn.rs"] +mod published_first_materialized_fn; +#[allow(unused_imports)] +use published_first_materialized_fn::draft_driver_error; +#[allow(unused_imports)] +use published_first_materialized_fn::published_first_materialized; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs new file mode 100644 index 00000000..437fe00c --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftcheckpoint.rs @@ -0,0 +1,251 @@ +//! Moved out of the parent module by STRA-338: impl OriginalDraftCheckpoint, impl OriginalDraftSession. + +#[allow(unused_imports)] +use super::*; + +impl OriginalDraftCheckpoint { + /// Host bytes of the ring image (prefix-cache accounting; pages shared with neighbouring points are counted in full). + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + self.snapshot.encoded_bytes() + } +} +impl<'ctx> OriginalDraftSession<'ctx> { + pub(in crate::qwen_forward) fn new( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + ) -> Result { + let origin = session.target_origin()?; + if origin.next_position() != 0 + || !binding.identity().matches(&session.binding) + || !std::ptr::eq(context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + let ring = context.mtp_original_int8(8).map_err(draft_driver_error)?; + let snapshot = ring.empty_snapshot().map_err(draft_driver_error)?; + Ok(Self { + binding: binding.identity(), + context, + origin, + ring: Some(ring), + snapshot, + first_materialized: 0, + failed: false, + }) + } + /// Literal MtpDrafter::init handoff. The shared-layout constructor owns + /// the physical INT8 state before it creates the scalar/full graph pair; + /// this constructor preserves that owner instead of allocating a second + /// independent ring for the same session. + pub(in crate::qwen_forward) fn from_original_ring( + binding: &ModelBinding, + session: &QwenSession<'ctx>, + context: &'ctx Context<'ctx>, + ring: MtpOriginalInt8<'ctx>, + ) -> Result { + let origin = session.target_origin()?; + if origin.next_position() != 0 + || !binding.identity().matches(&session.binding) + || !std::ptr::eq(context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + ring.validate_context(context).map_err(draft_driver_error)?; + let snapshot = ring.empty_snapshot().map_err(draft_driver_error)?; + Ok(Self { + binding: binding.identity(), + context, + origin, + ring: Some(ring), + snapshot, + first_materialized: 0, + failed: false, + }) + } + pub(super) fn validate(&self, binding: &ModelBinding, origin: &TargetStepOrigin) -> Result<()> { + if self.failed || self.context.is_poisoned() { + return Err(Error::CudaExecution); + } + if !self.binding.matches(&binding.identity()) + || !self.origin.same_prefix(origin) + || (self.snapshot.next_position() as u64) < origin.next_position() + || self.first_materialized > self.snapshot.next_position() + { + crate::bringup_trace!( + "DBG draft.validate mismatch: binding_ok={} same_prefix={} snapshot_next={} target_next={} draft_origin_next={} first_materialized={}", + self.binding.matches(&binding.identity()), + self.origin.same_prefix(origin), + self.snapshot.next_position(), + origin.next_position(), + self.origin.next_position(), + self.first_materialized + ); + return Err(Error::IdentityMismatch); + } + let ring = self.ring.as_ref().ok_or(Error::IdentityMismatch)?; + ring.validate_context(self.context).map_err(draft_driver_error)?; + ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error) + } + pub(in crate::qwen_forward) fn checkpoint( + &self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + ) -> Result { + let origin = session.target_origin()?; + self.validate(binding, &origin)?; + Ok(OriginalDraftCheckpoint { + binding: self.binding.clone(), + origin, + snapshot: self.snapshot.clone(), + first_materialized: self.first_materialized, + }) + } + /// Only the authentic target transaction can lend this canonical snapshot + /// and its actual device owner to the draft producer. + pub(in crate::qwen_forward) fn with_pending_ring( + &mut self, + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, 'ctx>, + execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot, usize) -> Result, + ) -> Result { + txn.check()?; + self.validate(binding, &txn.phase.origin)?; + let first_needed = usize::try_from(txn.end_position()) + .map_err(|_| Error::Overflow)? + .saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW); + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + let result = execute(ring, &self.snapshot, first_needed); + if ring.is_failed() || self.context.is_poisoned() { + self.failed = true; + } + result + } + /// Verified serve rounds have no prompt transaction: their authoritative + /// proof is the current target origin plus a completed verifier window. + /// This lends the same canonical ring only while its physical snapshot + /// exactly matches that target origin; an older or future draft cannot be + /// presented as the current verification branch. + pub(in crate::qwen_forward) fn with_current_ring( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, + ) -> Result { + let origin = session.target_origin()?; + self.validate(binding, &origin)?; + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + let result = execute(ring, &self.snapshot); + if ring.is_failed() || self.context.is_poisoned() { + self.failed = true; + } + result + } + /// Literal generate.cpp ordering for a verified serve window: the target + /// owner has already committed `a + 1` rows, while this independent MTP + /// ring is still anchored at the pre-window snapshot. A normal prompt + /// loan cannot express that intentional position skew, so this transition + /// requires both real origins explicitly. It never advances target state. + pub(in crate::qwen_forward) fn with_mtp_transition_ring( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + before: &TargetStepOrigin, + committed: &TargetStepOrigin, + execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, + ) -> Result { + if self.failed + || !self.binding.matches(&binding.identity()) + || !self.origin.same_prefix(before) + || !before.same_session(committed) + || !std::ptr::eq(self.context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + // `before` belongs to the same surviving branch, whereas `committed` + // is the only current target origin. The prior position intentionally + // differs after the verifier has published its accepted prefix. + before.validate_projection_branch(session)?; + committed.validate(session)?; + if committed.next_position() <= before.next_position() { + return Err(Error::IdentityMismatch); + } + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + ring.validate_context(self.context).map_err(draft_driver_error)?; + ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; + let result = execute(ring, &self.snapshot); + if ring.is_failed() || self.context.is_poisoned() { + self.failed = true; + } + result + } + /// `with_mtp_transition_ring` for a draft LAUNCHED while the verifier's commit of `prospective` is enqueued and + /// not yet published (generate.cpp enqueues the draft behind the commit): the session still stands exactly at + /// `before`; `prospective` must be the same branch, further on. The completion is published only through + /// `with_mtp_transition_ring` + `publish_mtp_completion` once the session holds `prospective`. + pub(in crate::qwen_forward) fn with_mtp_launch_ring( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + before: &TargetStepOrigin, + prospective: &TargetStepOrigin, + execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, + ) -> Result { + if self.failed + || !self.binding.matches(&binding.identity()) + || !self.origin.same_prefix(before) + || !before.same_branch(prospective) + || !std::ptr::eq(self.context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + before.validate(session)?; + if prospective.next_position() <= before.next_position() { + return Err(Error::IdentityMismatch); + } + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + ring.validate_context(self.context).map_err(draft_driver_error)?; + ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; + let result = execute(ring, &self.snapshot); + if ring.is_failed() || self.context.is_poisoned() { + self.failed = true; + } + result + } + /// Rebinds only the independent MTP ring after its fully drained source + /// draft. The target state was committed by the verifier beforehand; this + /// is deliberately incapable of minting or modifying a target origin. + pub(in crate::qwen_forward) fn publish_mtp_completion( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + before: &TargetStepOrigin, + committed: &TargetStepOrigin, + completed: &CompletedOriginalMtpDraft<'ctx>, + ) -> Result<()> { + // The preceding graph replaced `self.snapshot` with its completed + // speculative snapshot, so this publication must validate that new + // physical current state directly. Re-entering the pre-graph loan + // would incorrectly demand the old snapshot after a successful draft. + if self.failed + || !self.binding.matches(&binding.identity()) + || !self.origin.same_prefix(before) + || !before.same_session(committed) + || !std::ptr::eq(self.context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + before.validate_projection_branch(session)?; + committed.validate(session)?; + if committed.next_position() <= before.next_position() { + return Err(Error::IdentityMismatch); + } + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + ring.validate_context(self.context).map_err(draft_driver_error)?; + completed.validate_current(ring).map_err(draft_driver_error)?; + self.origin = committed.clone(); + self.snapshot = completed.final_snapshot().clone(); + self.first_materialized = self.first_materialized.min(self.snapshot.next_position()); + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftsession_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftsession_2.rs new file mode 100644 index 00000000..7f835ba0 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/impl_originaldraftsession_2.rs @@ -0,0 +1,242 @@ +//! Moved out of the parent module by STRA-338: impl OriginalDraftSession (2), impl OriginalDraftPublication, impl Drop_for_OriginalDraftSession. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalDraftSession<'ctx> { + /// A completed MTP receipt is valid only for the exact committed target + /// branch that produced it. Its ring may extend beyond target position + /// with provisional catch-up cells, which is why `with_current_ring` is + /// intentionally not used here. + pub(in crate::qwen_forward) fn with_mtp_current_ring( + &mut self, + binding: &ModelBinding, + session: &QwenSession<'ctx>, + origin: &TargetStepOrigin, + execute: impl FnOnce(&mut MtpOriginalInt8<'ctx>, &MtpInt8Snapshot) -> Result, + ) -> Result { + if self.failed + || !self.binding.matches(&binding.identity()) + || !self.origin.same_prefix(origin) + || !std::ptr::eq(self.context, session.mtp_context()?) + { + return Err(Error::IdentityMismatch); + } + origin.validate(session)?; + let ring = self.ring.as_mut().ok_or(Error::IdentityMismatch)?; + ring.validate_context(self.context).map_err(draft_driver_error)?; + ring.validate_snapshot(&self.snapshot).map_err(draft_driver_error)?; + let result = execute(ring, &self.snapshot); + if ring.is_failed() || self.context.is_poisoned() { + self.failed = true; + } + result + } + pub(in super::super) fn prepare_publication<'a>( + &'a mut self, + binding: &ModelBinding, + txn: &OriginalPromptTxn<'_, 'ctx>, + completed: &CompletedDraftKv, + ) -> Result> { + self.validate(binding, &txn.phase.origin)?; + let ring = self.ring.as_ref().ok_or(Error::IdentityMismatch)?; + completed.validate_current(ring).map_err(draft_driver_error)?; + let end = usize::try_from(txn.end_position()).map_err(|_| Error::Overflow)?; + let start = usize::try_from(txn.start_position()).map_err(|_| Error::Overflow)?; + let first_materialized = published_first_materialized( + self.first_materialized, + self.snapshot.next_position(), + start, + completed.first_materialized(), + end, + ); + if completed.next_position() != end + || end == 0 + || first_materialized > end.saturating_sub(leleka_cuda_driver::MTP_ORIGINAL_WINDOW) + || !completed.owner_id().same_owner(&self.snapshot.owner_id()) + { + crate::bringup_trace!( + "DBG draft.prepare_publication refused: start={start} end={end} completed_next={} completed_first={} prior_first={} prior_next={} lower={first_materialized} same_owner={}", + completed.next_position(), + completed.first_materialized(), + self.first_materialized, + self.snapshot.next_position(), + completed.owner_id().same_owner(&self.snapshot.owner_id()) + ); + return Err(Error::IdentityMismatch); + } + let snapshot = completed.snapshot_after(end - 1).map_err(draft_driver_error)?; + ring.validate_snapshot(&snapshot).map_err(draft_driver_error)?; + Ok(OriginalDraftPublication { owner: self, snapshot, first_materialized }) + } + /// All physical restores are attempted by the coupled target owner. An + /// uncertain ring restore poisons this owner even when target rollback works. + pub(in super::super) fn restore_physical( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + prior: &OriginalDraftCheckpoint, + ) -> Result<()> { + if self.failed + || !self.binding.matches(&binding.identity()) + || !prior.binding.matches(&self.binding) + || !self.origin.same_prefix(&prior.origin) + { + return Err(Error::IdentityMismatch); + } + let context = dense.retained_context(binding, self.context)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let result = self + .ring + .as_mut() + .ok_or(Error::IdentityMismatch)? + .restore(&mut workspace, &prior.snapshot) + .map_err(draft_driver_error); + if result.is_err() { + self.failed = true; + } + result + } + /// Roll the MTP ring back to `prior` and rebind it to the (already restored) target branch. The + /// serve host calls this for a failed round after the target side was repaired: both physical + /// restores are attempted by the caller's order (target first, then this). + pub(in crate::qwen_forward) fn restore_current( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + prior: &OriginalDraftCheckpoint, + ) -> Result<()> { + self.restore_physical(binding, dense, prior)?; + let actual = session.target_origin()?; + self.rebind_restored(prior, &actual) + } + /// A new request starts from the empty prompt: roll the ring back to the empty snapshot taken at load + /// (`empty`, position 0) and rebind it to the session, which must stand at position 0 again. Unlike + /// `restore_current` the draft's current origin is NOT required to equal the checkpoint's: the whole + /// previous request lies between them, and the empty ring holds no history to disagree with. + pub(in crate::qwen_forward) fn reset_to_empty( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + empty: &OriginalDraftCheckpoint, + ) -> Result<()> { + let actual = session.target_origin()?; + if self.failed + || !self.binding.matches(&binding.identity()) + || !empty.binding.matches(&self.binding) + || empty.origin.next_position() != 0 + || empty.snapshot.next_position() != 0 + || empty.first_materialized != 0 + || actual.next_position() != 0 + || !actual.same_session(&empty.origin) + || !self.origin.same_session(&actual) + { + return Err(Error::IdentityMismatch); + } + let context = dense.retained_context(binding, self.context)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let result = self + .ring + .as_mut() + .ok_or(Error::IdentityMismatch)? + .restore(&mut workspace, &empty.snapshot) + .map_err(draft_driver_error); + if result.is_err() { + self.failed = true; + return result; + } + self.origin = actual; + self.snapshot = empty.snapshot.clone(); + self.first_materialized = 0; + Ok(()) + } + /// Conversation resume (generate.cpp `mtp.kv_restore(resume)` after a checkpoint restore): roll the ring + /// back to the snapshot `point` saved together with the target checkpoint the session was just restored to, + /// and rebind it to the session. As in `reset_to_empty` the draft's current origin is not required to equal + /// the checkpoint's (a later turn and a generation bump lie between them); the checkpoint must name the + /// session's position and its snapshot must cover it. The snapshot is an immutable host image, so the + /// restored ring holds exactly the cells it held when the checkpoint was taken. + pub(in crate::qwen_forward) fn resume_at( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'ctx>, + session: &QwenSession<'ctx>, + point: &OriginalDraftCheckpoint, + ) -> Result<()> { + let actual = session.target_origin()?; + if self.failed + || !self.binding.matches(&binding.identity()) + || !point.binding.matches(&self.binding) + || !actual.same_session(&point.origin) + || !self.origin.same_session(&actual) + || point.origin.next_position() != actual.next_position() + || (point.snapshot.next_position() as u64) < actual.next_position() + || point.first_materialized > point.snapshot.next_position() + { + return Err(Error::IdentityMismatch); + } + let context = dense.retained_context(binding, self.context)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let result = self + .ring + .as_mut() + .ok_or(Error::IdentityMismatch)? + .restore(&mut workspace, &point.snapshot) + .map_err(draft_driver_error); + if result.is_err() { + self.failed = true; + return result; + } + self.origin = actual; + self.snapshot = point.snapshot.clone(); + self.first_materialized = point.first_materialized; + Ok(()) + } + /// Whether the ring stands at the session's current origin (a request can continue from it as is). + pub(in crate::qwen_forward) fn in_step(&self, binding: &ModelBinding, session: &QwenSession<'ctx>) -> bool { + session.target_origin().is_ok_and(|origin| self.validate(binding, &origin).is_ok()) + } + pub(in super::super) fn rebind_restored( + &mut self, + prior: &OriginalDraftCheckpoint, + actual: &TargetStepOrigin, + ) -> Result<()> { + if self.failed + || !self.origin.same_prefix(&prior.origin) + || !actual.same_session(&prior.origin) + || actual.next_position() != prior.origin.next_position() + || (prior.snapshot.next_position() as u64) < actual.next_position() + { + self.failed = true; + return Err(Error::IdentityMismatch); + } + self.origin = actual.clone(); + self.snapshot = prior.snapshot.clone(); + self.first_materialized = prior.first_materialized; + Ok(()) + } + pub(in super::super) fn mark_failed(&mut self) { + self.failed = true; + } + pub(in crate::qwen_forward) fn close(mut self) -> Result<()> { + self.close_inner() + } + pub(super) fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.ring.take().map_or(Ok(()), |ring| ring.close().map_err(draft_driver_error)) + } +} +impl OriginalDraftPublication<'_, '_> { + pub(in super::super) fn publish_validated(self, actual: TargetStepOrigin) { + self.owner.origin = actual; + self.owner.snapshot = self.snapshot; + self.owner.first_materialized = self.first_materialized; + } +} +impl Drop for OriginalDraftSession<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/published_first_materialized_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/published_first_materialized_fn.rs new file mode 100644 index 00000000..6cf3d55d --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_draft/published_first_materialized_fn.rs @@ -0,0 +1,35 @@ +//! Moved out of the parent module by STRA-338: fn published_first_materialized, fn draft_driver_error. + +#[allow(unused_imports)] +use super::*; + +/// The ring's lower materialized bound after a prompt chunk `[start, end)` whose recording materialized +/// `[chunk_first, end)`. The driver reports the chunk's own bound (`cell0 + r0`); when the chunk starts where +/// the ring's materialized range already reaches (`prior_next >= start`) and recorded from its first row, the +/// range simply continues and keeps the earlier bound. A chunk that skipped its leading rows (the Original's +/// `first_needed` cut) starts a new range at its own bound. Taking the chunk's bound alone made every chunk +/// after the first look as if `[0, start)` had never been recorded, so the second chunk of every multi-chunk +/// prompt was refused (`first_materialized > end - MTP_ORIGINAL_WINDOW`). +pub(super) fn published_first_materialized( + prior_first: usize, + prior_next: usize, + start: usize, + chunk_first: usize, + end: usize, +) -> usize { + if chunk_first == start && prior_next >= start && prior_first <= start && start < end { + prior_first + } else { + chunk_first + } +} +pub(super) fn draft_driver_error(error: leleka_cuda_driver::Error) -> Error { + match error { + leleka_cuda_driver::Error::ContextMismatch => Error::IdentityMismatch, + leleka_cuda_driver::Error::InvalidQwenShape | leleka_cuda_driver::Error::InvalidSize => Error::InvalidDimension, + leleka_cuda_driver::Error::BudgetExceeded | leleka_cuda_driver::Error::HostAllocation => Error::InputAllocation, + leleka_cuda_driver::Error::NonFiniteMmqOutput(_) => Error::NonFinite, + leleka_cuda_driver::Error::UnsupportedQwenOperation => Error::Unsupported(Stage::Session), + _ => Error::CudaExecution, + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs index 87f7efa9..84a62ed8 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt.rs @@ -1,46 +1,65 @@ //! Genuine layer-major Original prompt transaction. Initial embeddings are //! host inputs; the R payload then stays in one affine device arena. End-only //! state is never relabelled as an earlier causal row or scalar transaction. +use super::super::dense_weight_cache::DenseWeightCache; +use super::super::qsa_index::prompt_device::resident_device::{ + ParkedLayerSpan, ResidentQsaLayer, ResidentQsaPrior, ResidentQsaSeal, +}; use super::*; use std::cell::{Cell, RefCell}; -use super::super::qsa_index::prompt_device::resident_device::{ResidentQsaPrior,ResidentQsaSeal,ResidentQsaLayer,ParkedLayerSpan}; -use super::super::dense_weight_cache::DenseWeightCache; -#[path="session_original_draft.rs"] +#[path = "session_original_draft.rs"] pub(in crate::qwen_forward) mod draft; /// Actual tokenized request owner. Known-next conditioning IDs are read from /// this same immutable input, never from a sampled or caller-labelled token. -pub(in crate::qwen_forward) struct OriginalPromptInput{binding:BindingIdentity,tokens:Box<[TokenId]>} +pub(in crate::qwen_forward) struct OriginalPromptInput { + binding: BindingIdentity, + tokens: Box<[TokenId]>, +} /// Actual resident checkpoints are separate from legacy host QSA snapshots. /// The immutable index tail/dead checkpoint and mapped positional bounds keep /// their real owners; restoration must also touch all twelve physical layers. -pub(in crate::qwen_forward) struct OriginalSessionCheckpoint<'driver>{ - origin:TargetStepOrigin,predecessors:[i32;2],ple:Option, - gdn:[Option;STATE_CAPACITY],qsa:[Option>;STATE_CAPACITY], +pub(in crate::qwen_forward) struct OriginalSessionCheckpoint<'driver> { + origin: TargetStepOrigin, + predecessors: [i32; 2], + ple: Option, + gdn: [Option; STATE_CAPACITY], + qsa: [Option>; STATE_CAPACITY], } /// A session point that belongs to no lineage (prefix cache, `docs/prefix-cache.md`): the position, the recurrent /// and PLE host priors (immutable images, shared by reference) and, per resident QSA layer, the bytes of its index /// checkpoint tail. The K/V cells and pooled index rows below the position are parked separately as /// [`ParkedBlock`]s, because they are shared by every point of the same token prefix. -pub(in crate::qwen_forward) struct ParkedSession{ - position:u64,predecessors:[i32;2],ple:Option, - gdn:[Option;STATE_CAPACITY],tails:[Option>;STATE_CAPACITY], +pub(in crate::qwen_forward) struct ParkedSession { + position: u64, + predecessors: [i32; 2], + ple: Option, + gdn: [Option; STATE_CAPACITY], + tails: [Option>; STATE_CAPACITY], } /// The cells `first_token .. first_token + tokens` of every resident QSA layer, as plain bytes. -pub(in crate::qwen_forward) struct ParkedBlock{ - first_token:usize,tokens:usize,layers:[Option;STATE_CAPACITY], +pub(in crate::qwen_forward) struct ParkedBlock { + first_token: usize, + tokens: usize, + layers: [Option; STATE_CAPACITY], } #[derive(Clone, Copy, PartialEq, Eq)] -enum DevicePhase { Staging, Ready(GrRole), Read(GrRole), Final, Published } +enum DevicePhase { + Staging, + Ready(GrRole), + Read(GrRole), + Final, + Published, +} /// Shared only by authentic source rows and their physical producer products. /// Mutations are private and follow completed upload/read/injection boundaries. pub(in crate::qwen_forward) struct OriginalPromptPhase { binding: BindingIdentity, - source:Rc, + source: Rc, origin: TargetStepOrigin, owner: Rc<()>, phase: Cell, @@ -59,19 +78,19 @@ pub(in crate::qwen_forward) struct OriginalPromptRowKey { position: Position, } -pub(in crate::qwen_forward) struct OriginalPromptTxn<'session,'driver> { - session:&'session mut QwenSession<'driver>, - phase:Rc, - tokens:Vec, - inputs:Vec>, - predecessors:[i32;2], - next_ple:RefCell>, - ple_prior:RefCell>, - gdn_priors:RefCell<[Option;STATE_CAPACITY]>, - next_gdn:RefCell<[Option;STATE_CAPACITY]>, - next_qsa:RefCell<[Option>;STATE_CAPACITY]>, - gdn_completed:Cell, - qsa_completed:Cell, +pub(in crate::qwen_forward) struct OriginalPromptTxn<'session, 'driver> { + session: &'session mut QwenSession<'driver>, + phase: Rc, + tokens: Vec, + inputs: Vec>, + predecessors: [i32; 2], + next_ple: RefCell>, + ple_prior: RefCell>, + gdn_priors: RefCell<[Option; STATE_CAPACITY]>, + next_gdn: RefCell<[Option; STATE_CAPACITY]>, + next_qsa: RefCell<[Option>; STATE_CAPACITY]>, + gdn_completed: Cell, + qsa_completed: Cell, } #[path = "session_original_prompt/impl_originalpromptinput.rs"] diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput.rs index 69250968..749f88af 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput.rs @@ -3,220 +3,7 @@ #[allow(unused_imports)] use super::*; -impl OriginalPromptInput{ - pub(in crate::qwen_forward) fn from_tokenized(binding:&ModelBinding,tokens:&[u32])->Result>{ - if tokens.is_empty()||tokens.len()>=binding.input_constants().context_length() as usize{return Err(Error::InvalidPosition);} - let vocabulary=Dimension::new(248320)?; - let mut owned=Vec::new();owned.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; - for &token in tokens{owned.push(TokenId::new(u64::from(token),vocabulary)?);} - Ok(Rc::new(Self{binding:binding.identity(),tokens:owned.into_boxed_slice()})) - } - pub(in crate::qwen_forward) fn len(&self)->usize{self.tokens.len()} - pub(in crate::qwen_forward) fn window(&self,binding:&ModelBinding,first:u64,count:usize)->Result<&[TokenId]>{ - if !self.binding.matches(&binding.identity()){return Err(Error::IdentityMismatch);} - let first=usize::try_from(first).map_err(|_|Error::Overflow)?; - let end=first.checked_add(count).ok_or(Error::Overflow)?; - self.tokens.get(first..end).ok_or(Error::InvalidPosition) - } -} - -impl QwenSession<'_> { - /// Closed owner check for genuine resident QSA producers. Caller-supplied - /// layer/position metadata cannot substitute the session's actual owner. - pub(in crate::qwen_forward) fn validate_resident_qsa_owner(&self,owner:&QsaOwner)->Result<()> { - self.target_origin()?; - if !self.qsa_owner.matches(owner){return Err(Error::IdentityMismatch);} - Ok(()) - } -} - -impl<'driver> QwenSession<'driver> { - pub(in crate::qwen_forward) fn original_qsa_seed(&self,binding:&ModelBinding,layer:LayerId)->Result { - self.target_origin()?; - let slot=layer.get()as usize; - if !self.binding.matches(&binding.identity())||self.next_position!=0||slot>=48 - ||!self.qsa_layers[slot]||self.qsa_states[slot].is_some()||self.resident_qsa_states[slot].is_some(){return Err(Error::IdentityMismatch);} - QsaIndexPrior::empty(self.binding.clone(),&self.qsa_owner,layer) - } - pub(in crate::qwen_forward) fn install_original_qsa_seed(&mut self,binding:&ModelBinding,prior:ResidentQsaPrior<'driver>)->Result<()> { - let slot=prior.layer().get()as usize; - if self.next_position!=0||slot>=48||!self.qsa_layers[slot]||self.qsa_states[slot].is_some() - ||self.resident_qsa_states[slot].is_some(){return Err(Error::IdentityMismatch);} - prior.validate_for_session(binding,self,prior.layer(),0)?; - self.resident_qsa_states[slot]=Some(prior);Ok(()) - } - pub(in crate::qwen_forward) fn install_original_qsa_seed_set(&mut self,binding:&ModelBinding, - priors:[Option>;STATE_CAPACITY])->Result<()> { - self.target_origin()?; - if self.next_position!=0||self.layer_count!=48||!self.binding.matches(&binding.identity()) - ||self.qsa_states.iter().any(Option::is_some)||self.resident_qsa_states.iter().any(Option::is_some){return Err(Error::IdentityMismatch);} - for slot in 0..48 {if self.qsa_layers[slot]{let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - priors[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session(binding,self,layer,0)?; - }else if priors[slot].is_some(){return Err(Error::IdentityMismatch);}} - self.complete_cuda()?; - self.resident_qsa_states=priors;Ok(()) - } -} -impl<'driver> OriginalSessionCheckpoint<'driver>{ - /// The empty-prompt checkpoint taken at load, re-stamped onto the session's CURRENT branch generation - /// (every restore bumps it, which fences old checkpoints). Only the position-0 checkpoint can be - /// re-stamped: the empty lineage holds no history, so it names the same state on every branch. - pub(in crate::qwen_forward) fn rebased_empty(&self,session:&QwenSession<'driver>)->Result{ - let current=session.target_origin()?; - if self.origin.next_position()!=0||!self.origin.same_session(¤t)||self.ple.is_some() - ||self.gdn.iter().any(Option::is_some){return Err(Error::IdentityMismatch);} - let origin=super::super::checkpoint::origin_at(session,0); - let mut qsa:[Option>;STATE_CAPACITY]=std::array::from_fn(|_|None); - for slot in 0..STATE_CAPACITY{if let Some(prior)=&self.qsa[slot]{qsa[slot]=Some(prior.rebased_empty(origin.clone())?);}} - Ok(Self{origin,predecessors:[-1,-1],ple:None,gdn:std::array::from_fn(|_|None),qsa}) - } - /// The position this checkpoint restores to. - pub(in crate::qwen_forward) fn next_position(&self)->u64{self.origin.next_position()} - /// A conversation checkpoint (generate.cpp `checkpoint_at`) re-stamped onto the session's CURRENT branch - /// generation. Every restore bumps the generation, which fences all older checkpoints; the conversation - /// cache keeps a chain of checkpoints that are prefixes of the tokens the session holds, and a restore to - /// one of them leaves the positional cells below every other one untouched (generate.cpp: "a checkpoint is - /// only valid while the positional cells below it still hold ITS tokens"). That token-prefix invariant is - /// the conversation policy's to keep (`ConversationManager`); this only refuses another session and a - /// position the session has not reached. The GDN/PLE priors are immutable host images; the resident QSA - /// priors are re-stamped and their physical index/K-V coverage is checked again when restored. - pub(in crate::qwen_forward) fn rebased_onto_current(&self,session:&QwenSession<'driver>)->Result{ - let current=session.target_origin()?; - let position=self.origin.next_position(); - if !self.origin.same_session(¤t)||position>current.next_position(){return Err(Error::IdentityMismatch);} - let origin=super::super::checkpoint::origin_at(session,position); - let mut qsa:[Option>;STATE_CAPACITY]=std::array::from_fn(|_|None); - for slot in 0..STATE_CAPACITY{if let Some(prior)=&self.qsa[slot]{qsa[slot]=Some(prior.restamped(origin.clone())?);}} - Ok(Self{origin,predecessors:self.predecessors,ple:self.ple.clone(),gdn:self.gdn.clone(),qsa}) - } -} -impl<'driver> QwenSession<'driver> { - pub(in crate::qwen_forward) fn original_checkpoint(&mut self,binding:&ModelBinding)->Result>{ - let origin=self.target_origin()?; - // a checkpoint of lagging recurrent priors would name a state the session does not hold - if !self.binding.matches(&binding.identity())||self.layer_count!=48||self.state_lag.is_some(){return Err(Error::IdentityMismatch);} - for slot in 0..48{if self.qsa_layers[slot]{let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - self.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)? - .validate_for_session(binding,self,layer,self.next_position)?; - }else if self.resident_qsa_states[slot].is_some(){return Err(Error::IdentityMismatch);}} - self.complete_cuda()?; - Ok(OriginalSessionCheckpoint{origin,predecessors:self.predecessors,ple:self.ple_state.clone(), - gdn:self.gdn_states.clone(),qsa:self.resident_qsa_states.clone()}) - } - pub(in crate::qwen_forward) fn restore_original_checkpoint(&mut self,binding:&ModelBinding, - dense:&DenseWeightCache<'driver>,layers:&mut[Option>;STATE_CAPACITY], - prior:&OriginalSessionCheckpoint<'driver>)->Result<()> { - let origin=self.target_origin()?; - if !prior.origin.same_branch(&origin)||prior.origin.next_position()>self.next_position - ||!self.binding.matches(&binding.identity()){return Err(Error::IdentityMismatch);} - for slot in 0..48{if self.qsa_layers[slot]{let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - let saved=prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; - saved.validate_for_session(binding,self,layer,prior.origin.next_position())?; - let actual=layers[slot].as_ref().ok_or(Error::IdentityMismatch)?.current(); - if self.resident_qsa_states[slot].as_ref().is_none_or(|current|!current.same_prior(&actual)){return Err(Error::IdentityMismatch);} - }else if prior.qsa[slot].is_some()||layers[slot].is_some(){return Err(Error::IdentityMismatch);}} - let generation=self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; - self.complete_cuda()?; - // Fence the rejected branch before physical rollback. A failed rollback - // cannot leave an old capability addressing the partly restored image. - self.checkpoint_generation=generation; - let context=dense.retained_context(binding,self.mtp_context()?)?; - let mut workspace=dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?; - let mut restored=std::array::from_fn(|_|None);let mut first_error=None; - for(slot,layer)in layers.iter_mut().enumerate(){if let Some(layer)=layer{ - let saved=prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; - match layer.restore(binding,dense,self,saved,&mut workspace){Ok(current)=>restored[slot]=Some(current), - Err(error)=>{first_error.get_or_insert(error);}} - }} - drop(workspace); - if let Some(error)=first_error{self.note_mtp_failure(&error);return Err(error);} - self.complete_cuda()?; - self.next_position=prior.origin.next_position();self.predecessors=prior.predecessors; - self.ple_state=prior.ple.clone();self.gdn_states=prior.gdn.clone(); - // every recurrent prior was just replaced from the checkpoint: nothing lags any more - self.state_lag=None; - self.qsa_states=std::array::from_fn(|_|None);self.resident_qsa_states=restored;Ok(()) - } -} -impl ParkedSession{ - pub(in crate::qwen_forward) fn next_position(&self)->u64{self.position} - /// Host bytes this point pins (priors counted in full even where a neighbouring point shares an image). - pub(in crate::qwen_forward) fn host_bytes(&self)->usize{ - self.ple.as_ref().map_or(0,PlePrior::host_bytes)+self.gdn.iter().flatten().map(GdnPrior::host_bytes).sum::() - +self.tails.iter().flatten().map(Vec::len).sum::() - } -} -impl ParkedBlock{ - pub(in crate::qwen_forward) fn first_token(&self)->usize{self.first_token} - pub(in crate::qwen_forward) fn tokens(&self)->usize{self.tokens} - pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.layers.iter().flatten().map(ParkedLayerSpan::bytes).sum()} -} -impl<'driver> QwenSession<'driver> { - /// Park the point the session stands at. Same preconditions as `original_checkpoint` (recurrent priors current, - /// every resident witness valid), and the layers must stand where the session does. - pub(in crate::qwen_forward) fn park_original(&mut self,binding:&ModelBinding, - layers:&[Option>;STATE_CAPACITY])->Result{ - let checkpoint=self.original_checkpoint(binding)?; - let mut tails:[Option>;STATE_CAPACITY]=std::array::from_fn(|_|None); - for slot in 0..48{match(&layers[slot],self.qsa_layers[slot]){ - (Some(layer),true)=>{ - if self.resident_qsa_states[slot].as_ref().is_none_or(|current|!current.same_prior(&layer.current())){return Err(Error::IdentityMismatch);} - tails[slot]=Some(layer.export_tail()?); - } - (None,false)=>{} - _=>return Err(Error::IdentityMismatch), - }} - Ok(ParkedSession{position:checkpoint.origin.next_position(),predecessors:checkpoint.predecessors,ple:checkpoint.ple,gdn:checkpoint.gdn,tails}) - } - /// The cells `first..first + tokens` of every resident layer (the session stands at or beyond `first + tokens`). - pub(in crate::qwen_forward) fn park_block(&self,layers:&[Option>;STATE_CAPACITY], - first:usize,tokens:usize)->Result{ - if self.state_lag.is_some()||(first+tokens) as u64>self.next_position{return Err(Error::InvalidPosition);} - let mut out:[Option;STATE_CAPACITY]=std::array::from_fn(|_|None); - for slot in 0..48{match(&layers[slot],self.qsa_layers[slot]){ - (Some(layer),true)=>out[slot]=Some(layer.export_span(first,tokens)?), - (None,false)=>{} - _=>return Err(Error::IdentityMismatch), - }} - Ok(ParkedBlock{first_token:first,tokens,layers:out}) - } - /// Make the session and the twelve physical layers stand at `parked`, writing the cells of `blocks` (the layers' - /// cells below the position that no block names must already hold the parked prefix; the caller knows which). - /// Unlike `restore_original_checkpoint` this accepts a point of ANOTHER lineage, because everything a lineage - /// witness would vouch for is re-written or re-minted from this session's own owners. The branch generation - /// is bumped first, fencing every older checkpoint. - pub(in crate::qwen_forward) fn import_parked(&mut self,binding:&ModelBinding, - dense:&DenseWeightCache<'driver>,layers:&mut[Option>;STATE_CAPACITY], - parked:&ParkedSession,blocks:&[&ParkedBlock])->Result<()>{ - let origin=self.target_origin()?; - if !self.binding.matches(&binding.identity())||self.layer_count!=48||parked.position>=u64::from(binding.input_constants().context_length()){ - return Err(Error::IdentityMismatch); - } - let _=origin; - for slot in 0..48{ - let wanted=self.qsa_layers[slot]; - if wanted!=layers[slot].is_some()||wanted!=parked.tails[slot].is_some() - ||blocks.iter().any(|b|b.layers[slot].is_some()!=wanted){return Err(Error::IdentityMismatch);} - } - let generation=self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; - {let _p=super::super::super::original_serve_profile::span("prefix.import_sync");self.complete_cuda()?;} - self.checkpoint_generation=generation; - let context=dense.retained_context(binding,self.mtp_context()?)?; - let mut workspace={let _p=super::super::super::original_serve_profile::span("prefix.import_workspace");dense.native_batch_workspace(binding,context)?.ok_or(Error::IdentityMismatch)?}; - let mut restored=std::array::from_fn(|_|None);let mut first_error=None; - let end=usize::try_from(parked.position).map_err(|_|Error::Overflow)?; - for(slot,layer)in layers.iter_mut().enumerate(){if let Some(layer)=layer{ - let spans:Vec<&ParkedLayerSpan>=blocks.iter().filter_map(|b|b.layers[slot].as_ref()).collect(); - let tail=parked.tails[slot].as_deref().ok_or(Error::IdentityMismatch)?; - match layer.import(binding,dense,self,tail,&spans,end,&mut workspace){Ok(current)=>restored[slot]=Some(current), - Err(error)=>{first_error.get_or_insert(error);}} - }} - drop(workspace); - if let Some(error)=first_error{self.note_mtp_failure(&error);return Err(error);} - self.complete_cuda()?; - self.next_position=parked.position;self.predecessors=parked.predecessors; - self.ple_state=parked.ple.clone();self.gdn_states=parked.gdn.clone(); - self.state_lag=None; - self.qsa_states=std::array::from_fn(|_|None);self.resident_qsa_states=restored;Ok(()) - } -} +#[path = "impl_originalpromptinput/impl_originalpromptinput_2.rs"] +mod impl_originalpromptinput_2; +#[path = "impl_originalpromptinput/impl_qwensession.rs"] +mod impl_qwensession; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_originalpromptinput_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_originalpromptinput_2.rs new file mode 100644 index 00000000..1c8d0315 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_originalpromptinput_2.rs @@ -0,0 +1,162 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptInput, impl QwenSession, impl QwenSession, impl OriginalSessionCheckpoint. + +#[allow(unused_imports)] +use super::*; + +impl OriginalPromptInput { + pub(in crate::qwen_forward) fn from_tokenized(binding: &ModelBinding, tokens: &[u32]) -> Result> { + if tokens.is_empty() || tokens.len() >= binding.input_constants().context_length() as usize { + return Err(Error::InvalidPosition); + } + let vocabulary = Dimension::new(248320)?; + let mut owned = Vec::new(); + owned.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; + for &token in tokens { + owned.push(TokenId::new(u64::from(token), vocabulary)?); + } + Ok(Rc::new(Self { binding: binding.identity(), tokens: owned.into_boxed_slice() })) + } + pub(in crate::qwen_forward) fn len(&self) -> usize { + self.tokens.len() + } + pub(in crate::qwen_forward) fn window( + &self, + binding: &ModelBinding, + first: u64, + count: usize, + ) -> Result<&[TokenId]> { + if !self.binding.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + let first = usize::try_from(first).map_err(|_| Error::Overflow)?; + let end = first.checked_add(count).ok_or(Error::Overflow)?; + self.tokens.get(first..end).ok_or(Error::InvalidPosition) + } +} + +impl QwenSession<'_> { + /// Closed owner check for genuine resident QSA producers. Caller-supplied + /// layer/position metadata cannot substitute the session's actual owner. + pub(in crate::qwen_forward) fn validate_resident_qsa_owner(&self, owner: &QsaOwner) -> Result<()> { + self.target_origin()?; + if !self.qsa_owner.matches(owner) { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} + +impl<'driver> QwenSession<'driver> { + pub(in crate::qwen_forward) fn original_qsa_seed( + &self, + binding: &ModelBinding, + layer: LayerId, + ) -> Result { + self.target_origin()?; + let slot = layer.get() as usize; + if !self.binding.matches(&binding.identity()) + || self.next_position != 0 + || slot >= 48 + || !self.qsa_layers[slot] + || self.qsa_states[slot].is_some() + || self.resident_qsa_states[slot].is_some() + { + return Err(Error::IdentityMismatch); + } + QsaIndexPrior::empty(self.binding.clone(), &self.qsa_owner, layer) + } + pub(in crate::qwen_forward) fn install_original_qsa_seed( + &mut self, + binding: &ModelBinding, + prior: ResidentQsaPrior<'driver>, + ) -> Result<()> { + let slot = prior.layer().get() as usize; + if self.next_position != 0 + || slot >= 48 + || !self.qsa_layers[slot] + || self.qsa_states[slot].is_some() + || self.resident_qsa_states[slot].is_some() + { + return Err(Error::IdentityMismatch); + } + prior.validate_for_session(binding, self, prior.layer(), 0)?; + self.resident_qsa_states[slot] = Some(prior); + Ok(()) + } + pub(in crate::qwen_forward) fn install_original_qsa_seed_set( + &mut self, + binding: &ModelBinding, + priors: [Option>; STATE_CAPACITY], + ) -> Result<()> { + self.target_origin()?; + if self.next_position != 0 + || self.layer_count != 48 + || !self.binding.matches(&binding.identity()) + || self.qsa_states.iter().any(Option::is_some) + || self.resident_qsa_states.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + for slot in 0..48 { + if self.qsa_layers[slot] { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + priors[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session(binding, self, layer, 0)?; + } else if priors[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + self.complete_cuda()?; + self.resident_qsa_states = priors; + Ok(()) + } +} +impl<'driver> OriginalSessionCheckpoint<'driver> { + /// The empty-prompt checkpoint taken at load, re-stamped onto the session's CURRENT branch generation + /// (every restore bumps it, which fences old checkpoints). Only the position-0 checkpoint can be + /// re-stamped: the empty lineage holds no history, so it names the same state on every branch. + pub(in crate::qwen_forward) fn rebased_empty(&self, session: &QwenSession<'driver>) -> Result { + let current = session.target_origin()?; + if self.origin.next_position() != 0 + || !self.origin.same_session(¤t) + || self.ple.is_some() + || self.gdn.iter().any(Option::is_some) + { + return Err(Error::IdentityMismatch); + } + let origin = super::super::super::checkpoint::origin_at(session, 0); + let mut qsa: [Option>; STATE_CAPACITY] = std::array::from_fn(|_| None); + for slot in 0..STATE_CAPACITY { + if let Some(prior) = &self.qsa[slot] { + qsa[slot] = Some(prior.rebased_empty(origin.clone())?); + } + } + Ok(Self { origin, predecessors: [-1, -1], ple: None, gdn: std::array::from_fn(|_| None), qsa }) + } + /// The position this checkpoint restores to. + pub(in crate::qwen_forward) fn next_position(&self) -> u64 { + self.origin.next_position() + } + /// A conversation checkpoint (generate.cpp `checkpoint_at`) re-stamped onto the session's CURRENT branch + /// generation. Every restore bumps the generation, which fences all older checkpoints; the conversation + /// cache keeps a chain of checkpoints that are prefixes of the tokens the session holds, and a restore to + /// one of them leaves the positional cells below every other one untouched (generate.cpp: "a checkpoint is + /// only valid while the positional cells below it still hold ITS tokens"). That token-prefix invariant is + /// the conversation policy's to keep (`ConversationManager`); this only refuses another session and a + /// position the session has not reached. The GDN/PLE priors are immutable host images; the resident QSA + /// priors are re-stamped and their physical index/K-V coverage is checked again when restored. + pub(in crate::qwen_forward) fn rebased_onto_current(&self, session: &QwenSession<'driver>) -> Result { + let current = session.target_origin()?; + let position = self.origin.next_position(); + if !self.origin.same_session(¤t) || position > current.next_position() { + return Err(Error::IdentityMismatch); + } + let origin = super::super::super::checkpoint::origin_at(session, position); + let mut qsa: [Option>; STATE_CAPACITY] = std::array::from_fn(|_| None); + for slot in 0..STATE_CAPACITY { + if let Some(prior) = &self.qsa[slot] { + qsa[slot] = Some(prior.restamped(origin.clone())?); + } + } + Ok(Self { origin, predecessors: self.predecessors, ple: self.ple.clone(), gdn: self.gdn.clone(), qsa }) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs new file mode 100644 index 00000000..c37c9ffd --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptinput/impl_qwensession.rs @@ -0,0 +1,248 @@ +//! Moved out of the parent module by STRA-338: impl QwenSession, impl ParkedSession, impl ParkedBlock, impl QwenSession. + +#[allow(unused_imports)] +use super::*; + +impl<'driver> QwenSession<'driver> { + pub(in crate::qwen_forward) fn original_checkpoint( + &mut self, + binding: &ModelBinding, + ) -> Result> { + let origin = self.target_origin()?; + // a checkpoint of lagging recurrent priors would name a state the session does not hold + if !self.binding.matches(&binding.identity()) || self.layer_count != 48 || self.state_lag.is_some() { + return Err(Error::IdentityMismatch); + } + for slot in 0..48 { + if self.qsa_layers[slot] { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + self.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session( + binding, + self, + layer, + self.next_position, + )?; + } else if self.resident_qsa_states[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + self.complete_cuda()?; + Ok(OriginalSessionCheckpoint { + origin, + predecessors: self.predecessors, + ple: self.ple_state.clone(), + gdn: self.gdn_states.clone(), + qsa: self.resident_qsa_states.clone(), + }) + } + pub(in crate::qwen_forward) fn restore_original_checkpoint( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + layers: &mut [Option>; STATE_CAPACITY], + prior: &OriginalSessionCheckpoint<'driver>, + ) -> Result<()> { + let origin = self.target_origin()?; + if !prior.origin.same_branch(&origin) + || prior.origin.next_position() > self.next_position + || !self.binding.matches(&binding.identity()) + { + return Err(Error::IdentityMismatch); + } + for slot in 0..48 { + if self.qsa_layers[slot] { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; + saved.validate_for_session(binding, self, layer, prior.origin.next_position())?; + let actual = layers[slot].as_ref().ok_or(Error::IdentityMismatch)?.current(); + if self.resident_qsa_states[slot].as_ref().is_none_or(|current| !current.same_prior(&actual)) { + return Err(Error::IdentityMismatch); + } + } else if prior.qsa[slot].is_some() || layers[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + let generation = self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; + self.complete_cuda()?; + // Fence the rejected branch before physical rollback. A failed rollback + // cannot leave an old capability addressing the partly restored image. + self.checkpoint_generation = generation; + let context = dense.retained_context(binding, self.mtp_context()?)?; + let mut workspace = dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let mut restored = std::array::from_fn(|_| None); + let mut first_error = None; + for (slot, layer) in layers.iter_mut().enumerate() { + if let Some(layer) = layer { + let saved = prior.qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; + match layer.restore(binding, dense, self, saved, &mut workspace) { + Ok(current) => restored[slot] = Some(current), + Err(error) => { + first_error.get_or_insert(error); + } + } + } + } + drop(workspace); + if let Some(error) = first_error { + self.note_mtp_failure(&error); + return Err(error); + } + self.complete_cuda()?; + self.next_position = prior.origin.next_position(); + self.predecessors = prior.predecessors; + self.ple_state = prior.ple.clone(); + self.gdn_states = prior.gdn.clone(); + // every recurrent prior was just replaced from the checkpoint: nothing lags any more + self.state_lag = None; + self.qsa_states = std::array::from_fn(|_| None); + self.resident_qsa_states = restored; + Ok(()) + } +} +impl ParkedSession { + pub(in crate::qwen_forward) fn next_position(&self) -> u64 { + self.position + } + /// Host bytes this point pins (priors counted in full even where a neighbouring point shares an image). + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + self.ple.as_ref().map_or(0, PlePrior::host_bytes) + + self.gdn.iter().flatten().map(GdnPrior::host_bytes).sum::() + + self.tails.iter().flatten().map(Vec::len).sum::() + } +} +impl ParkedBlock { + pub(in crate::qwen_forward) fn first_token(&self) -> usize { + self.first_token + } + pub(in crate::qwen_forward) fn tokens(&self) -> usize { + self.tokens + } + pub(in crate::qwen_forward) fn host_bytes(&self) -> usize { + self.layers.iter().flatten().map(ParkedLayerSpan::bytes).sum() + } +} +impl<'driver> QwenSession<'driver> { + /// Park the point the session stands at. Same preconditions as `original_checkpoint` (recurrent priors current, + /// every resident witness valid), and the layers must stand where the session does. + pub(in crate::qwen_forward) fn park_original( + &mut self, + binding: &ModelBinding, + layers: &[Option>; STATE_CAPACITY], + ) -> Result { + let checkpoint = self.original_checkpoint(binding)?; + let mut tails: [Option>; STATE_CAPACITY] = std::array::from_fn(|_| None); + for slot in 0..48 { + match (&layers[slot], self.qsa_layers[slot]) { + (Some(layer), true) => { + if self.resident_qsa_states[slot] + .as_ref() + .is_none_or(|current| !current.same_prior(&layer.current())) + { + return Err(Error::IdentityMismatch); + } + tails[slot] = Some(layer.export_tail()?); + } + (None, false) => {} + _ => return Err(Error::IdentityMismatch), + } + } + Ok(ParkedSession { + position: checkpoint.origin.next_position(), + predecessors: checkpoint.predecessors, + ple: checkpoint.ple, + gdn: checkpoint.gdn, + tails, + }) + } + /// The cells `first..first + tokens` of every resident layer (the session stands at or beyond `first + tokens`). + pub(in crate::qwen_forward) fn park_block( + &self, + layers: &[Option>; STATE_CAPACITY], + first: usize, + tokens: usize, + ) -> Result { + if self.state_lag.is_some() || (first + tokens) as u64 > self.next_position { + return Err(Error::InvalidPosition); + } + let mut out: [Option; STATE_CAPACITY] = std::array::from_fn(|_| None); + for slot in 0..48 { + match (&layers[slot], self.qsa_layers[slot]) { + (Some(layer), true) => out[slot] = Some(layer.export_span(first, tokens)?), + (None, false) => {} + _ => return Err(Error::IdentityMismatch), + } + } + Ok(ParkedBlock { first_token: first, tokens, layers: out }) + } + /// Make the session and the twelve physical layers stand at `parked`, writing the cells of `blocks` (the layers' + /// cells below the position that no block names must already hold the parked prefix; the caller knows which). + /// Unlike `restore_original_checkpoint` this accepts a point of ANOTHER lineage, because everything a lineage + /// witness would vouch for is re-written or re-minted from this session's own owners. The branch generation + /// is bumped first, fencing every older checkpoint. + pub(in crate::qwen_forward) fn import_parked( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + layers: &mut [Option>; STATE_CAPACITY], + parked: &ParkedSession, + blocks: &[&ParkedBlock], + ) -> Result<()> { + let origin = self.target_origin()?; + if !self.binding.matches(&binding.identity()) + || self.layer_count != 48 + || parked.position >= u64::from(binding.input_constants().context_length()) + { + return Err(Error::IdentityMismatch); + } + let _ = origin; + for slot in 0..48 { + let wanted = self.qsa_layers[slot]; + if wanted != layers[slot].is_some() + || wanted != parked.tails[slot].is_some() + || blocks.iter().any(|b| b.layers[slot].is_some() != wanted) + { + return Err(Error::IdentityMismatch); + } + } + let generation = self.checkpoint_generation.checked_add(1).ok_or(Error::Overflow)?; + { + let _p = super::super::super::super::original_serve_profile::span("prefix.import_sync"); + self.complete_cuda()?; + } + self.checkpoint_generation = generation; + let context = dense.retained_context(binding, self.mtp_context()?)?; + let mut workspace = { + let _p = super::super::super::super::original_serve_profile::span("prefix.import_workspace"); + dense.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)? + }; + let mut restored = std::array::from_fn(|_| None); + let mut first_error = None; + let end = usize::try_from(parked.position).map_err(|_| Error::Overflow)?; + for (slot, layer) in layers.iter_mut().enumerate() { + if let Some(layer) = layer { + let spans: Vec<&ParkedLayerSpan> = blocks.iter().filter_map(|b| b.layers[slot].as_ref()).collect(); + let tail = parked.tails[slot].as_deref().ok_or(Error::IdentityMismatch)?; + match layer.import(binding, dense, self, tail, &spans, end, &mut workspace) { + Ok(current) => restored[slot] = Some(current), + Err(error) => { + first_error.get_or_insert(error); + } + } + } + } + drop(workspace); + if let Some(error) = first_error { + self.note_mtp_failure(&error); + return Err(error); + } + self.complete_cuda()?; + self.next_position = parked.position; + self.predecessors = parked.predecessors; + self.ple_state = parked.ple.clone(); + self.gdn_states = parked.gdn.clone(); + self.state_lag = None; + self.qsa_states = std::array::from_fn(|_| None); + self.resident_qsa_states = restored; + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptphase.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptphase.rs index b5252789..78c0213e 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptphase.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalpromptphase.rs @@ -4,79 +4,121 @@ use super::*; impl OriginalPromptPhase { - pub(in crate::qwen_forward) fn validate_role(&self, binding:&BindingIdentity, role:GrRole, read:bool)->Result<()> { + pub(in crate::qwen_forward) fn validate_role( + &self, + binding: &BindingIdentity, + role: GrRole, + read: bool, + ) -> Result<()> { if self.failed.get() || !self.binding.matches(binding) { return Err(Error::IdentityMismatch); } let expected = if read { DevicePhase::Read(role) } else { DevicePhase::Ready(role) }; - if self.phase.get()!=expected { return Err(Error::IdentityMismatch); } - Ok(()) - } - pub(in crate::qwen_forward) fn initialize(&self,rows:usize)->Result<()> { - if self.failed.get() || self.phase.get()!=DevicePhase::Staging || rows!=self.rows { + if self.phase.get() != expected { return Err(Error::IdentityMismatch); } - self.phase.set(DevicePhase::Ready(GrRole::Attention(0))); Ok(()) + Ok(()) } - pub(in crate::qwen_forward) fn read(&self,role:GrRole)->Result<()> { + pub(in crate::qwen_forward) fn initialize(&self, rows: usize) -> Result<()> { + if self.failed.get() || self.phase.get() != DevicePhase::Staging || rows != self.rows { + return Err(Error::IdentityMismatch); + } + self.phase.set(DevicePhase::Ready(GrRole::Attention(0))); + Ok(()) + } + pub(in crate::qwen_forward) fn read(&self, role: GrRole) -> Result<()> { self.prepare_read(role)?; - self.phase.set(DevicePhase::Read(role)); Ok(()) + self.phase.set(DevicePhase::Read(role)); + Ok(()) } - pub(in crate::qwen_forward) fn prepare_read(&self,role:GrRole)->Result<()> { - self.validate_role(&self.binding,role,false)?; - if role==GrRole::Attention(1) && self.ple_required && !self.ple_done.get() { + pub(in crate::qwen_forward) fn prepare_read(&self, role: GrRole) -> Result<()> { + self.validate_role(&self.binding, role, false)?; + if role == GrRole::Attention(1) && self.ple_required && !self.ple_done.get() { return Err(Error::IdentityMismatch); } Ok(()) } - pub(in crate::qwen_forward) fn inject(&self,from:GrRole,to:GrRole)->Result<()> { - self.validate_role(&self.binding,from,true)?; + pub(in crate::qwen_forward) fn inject(&self, from: GrRole, to: GrRole) -> Result<()> { + self.validate_role(&self.binding, from, true)?; let expected = match from { - GrRole::Attention(layer)=>GrRole::Ffn(layer), - GrRole::Ffn(47)=>GrRole::Final, - GrRole::Ffn(layer) if layer<47=>GrRole::Attention(layer+1), - _=>return Err(Error::IdentityMismatch), + GrRole::Attention(layer) => GrRole::Ffn(layer), + GrRole::Ffn(47) => GrRole::Final, + GrRole::Ffn(layer) if layer < 47 => GrRole::Attention(layer + 1), + _ => return Err(Error::IdentityMismatch), }; - if to!=expected { return Err(Error::IdentityMismatch); } - self.phase.set(DevicePhase::Ready(to)); Ok(()) - } - pub(in crate::qwen_forward) fn ple_complete(&self)->Result<()> { - self.validate_role(&self.binding,GrRole::Attention(1),false)?; - if !self.ple_required || self.ple_done.replace(true) { return Err(Error::IdentityMismatch); } + if to != expected { + return Err(Error::IdentityMismatch); + } + self.phase.set(DevicePhase::Ready(to)); Ok(()) } - pub(in crate::qwen_forward) fn seal_final(&self)->Result<()> { - self.validate_role(&self.binding,GrRole::Final,false)?; - if self.ple_required && !self.ple_done.get() {return Err(Error::IdentityMismatch);} - self.phase.set(DevicePhase::Final); Ok(()) + pub(in crate::qwen_forward) fn ple_complete(&self) -> Result<()> { + self.validate_role(&self.binding, GrRole::Attention(1), false)?; + if !self.ple_required || self.ple_done.replace(true) { + return Err(Error::IdentityMismatch); + } + Ok(()) } - pub(in crate::qwen_forward) fn same(&self,other:&Self)->bool { - Rc::ptr_eq(&self.owner,&other.owner) && self.origin.same_prefix(&other.origin) + pub(in crate::qwen_forward) fn seal_final(&self) -> Result<()> { + self.validate_role(&self.binding, GrRole::Final, false)?; + if self.ple_required && !self.ple_done.get() { + return Err(Error::IdentityMismatch); + } + self.phase.set(DevicePhase::Final); + Ok(()) + } + pub(in crate::qwen_forward) fn same(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.owner, &other.owner) && self.origin.same_prefix(&other.origin) + } + pub(in crate::qwen_forward) fn journal_owner(&self) -> Rc<()> { + Rc::clone(&self.owner) } - pub(in crate::qwen_forward) fn journal_owner(&self)->Rc<()>{Rc::clone(&self.owner)} } impl OriginalPromptRowKey { - pub(in crate::qwen_forward) fn validate_initial(&self,binding:&BindingIdentity,input:&InputReady)->Result<()> { - if self.phase.failed.get() || self.phase.phase.get()!=DevicePhase::Staging - || !self.phase.binding.matches(binding) || !input.binding_identity().matches(binding) - || self.index>=self.phase.rows || self.token!=input.token() || self.position!=input.position() - || self.phase.first.checked_add(self.index as u64)!=Some(self.position.get()) { + pub(in crate::qwen_forward) fn validate_initial( + &self, + binding: &BindingIdentity, + input: &InputReady, + ) -> Result<()> { + if self.phase.failed.get() + || self.phase.phase.get() != DevicePhase::Staging + || !self.phase.binding.matches(binding) + || !input.binding_identity().matches(binding) + || self.index >= self.phase.rows + || self.token != input.token() + || self.position != input.position() + || self.phase.first.checked_add(self.index as u64) != Some(self.position.get()) + { return Err(Error::IdentityMismatch); } Ok(()) } - pub(in crate::qwen_forward) fn validate(&self,binding:&BindingIdentity,input:&InputReady, - role:GrRole,read:bool)->Result { - self.phase.validate_role(binding,role,read)?; - if self.index>=self.phase.rows || self.token!=input.token() || self.position!=input.position() + pub(in crate::qwen_forward) fn validate( + &self, + binding: &BindingIdentity, + input: &InputReady, + role: GrRole, + read: bool, + ) -> Result { + self.phase.validate_role(binding, role, read)?; + if self.index >= self.phase.rows + || self.token != input.token() + || self.position != input.position() || !input.binding_identity().matches(binding) - || self.phase.first.checked_add(self.index as u64)!=Some(self.position.get()) { + || self.phase.first.checked_add(self.index as u64) != Some(self.position.get()) + { return Err(Error::IdentityMismatch); } - let layer=match role {GrRole::Attention(layer)|GrRole::Ffn(layer)=>layer, - GrRole::Final=>return Err(Error::IdentityMismatch)}; - Ok(TokenLayer::new(self.token,self.position,LayerId::new(layer as u64,Dimension::new(48)?)?)) + let layer = match role { + GrRole::Attention(layer) | GrRole::Ffn(layer) => layer, + GrRole::Final => return Err(Error::IdentityMismatch), + }; + Ok(TokenLayer::new(self.token, self.position, LayerId::new(layer as u64, Dimension::new(48)?)?)) + } + pub(in crate::qwen_forward) fn phase(&self) -> Rc { + Rc::clone(&self.phase) + } + pub(in crate::qwen_forward) fn ordinal(&self) -> usize { + self.index } - pub(in crate::qwen_forward) fn phase(&self)->Rc{Rc::clone(&self.phase)} - pub(in crate::qwen_forward) fn ordinal(&self)->usize{self.index} } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn.rs index 18a8cb38..a32de056 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn.rs @@ -3,244 +3,9 @@ #[allow(unused_imports)] use super::*; -impl<'session,'driver> OriginalPromptTxn<'session,'driver> { - pub(in crate::qwen_forward) fn begin(session:&'session mut QwenSession<'driver>, - binding:&ModelBinding,source:&Rc,count:usize)->Result { - let origin=session.target_origin()?; - if session.state_lag.is_some(){return Err(Error::IdentityMismatch);} - let tokens=source.window(binding,session.next_position,count)?; - for slot in 0..48 { - if session.qsa_layers[slot] { - let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)? - .validate_for_session(binding,session,layer,session.next_position)?; - if session.qsa_states[slot].is_some(){return Err(Error::IdentityMismatch);} - }else if session.resident_qsa_states[slot].is_some(){return Err(Error::IdentityMismatch);} - } - if !(1..=8192).contains(&tokens.len()) || binding.layer_count()!=48 - || !session.binding.matches(&binding.identity()) || session.layer_count!=48 - || session.cuda.is_none() {return Err(Error::IdentityMismatch);} - let end=session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; - let limit=u64::from(binding.input_constants().context_length()); - // A subsequent sampled token requires one remaining valid position. - if end>=limit {return Err(Error::InvalidPosition);} - let vocab=Dimension::new(248320)?; - for token in tokens {if *token!=TokenId::new(token.get() as u64,vocab)? {return Err(Error::InvalidToken);}} - let mut owned=Vec::new();owned.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; - owned.extend_from_slice(tokens); - let mut inputs=Vec::new();inputs.try_reserve_exact(tokens.len()).map_err(|_|Error::InputAllocation)?; - let phase=Rc::new(OriginalPromptPhase{binding:binding.identity(),source:Rc::clone(source),origin,owner:Rc::new(()), - phase:Cell::new(DevicePhase::Staging),ple_required:session.ple_required, - ple_done:Cell::new(false),failed:Cell::new(false),rows:tokens.len(),first:session.next_position,end}); - Ok(Self{predecessors:session.predecessors,next_ple:RefCell::new(None),ple_prior:RefCell::new(None), - gdn_priors:RefCell::new(std::array::from_fn(|_|None)), - next_gdn:RefCell::new(std::array::from_fn(|_|None)),next_qsa:RefCell::new(std::array::from_fn(|_|None)), - gdn_completed:Cell::new(0),qsa_completed:Cell::new(0),session,phase,tokens:owned,inputs}) - } - pub(super) fn check(&self)->Result<()> { - self.phase.origin.validate(self.session)?; - if self.phase.failed.get() {return Err(Error::IdentityMismatch);} - if self.session.mtp_context()?.is_poisoned() {return Err(Error::CudaExecution);} - Ok(()) - } - pub(in crate::qwen_forward) fn original_session(&self)->&QwenSession<'driver>{self.session} - pub(in crate::qwen_forward) fn origin(&self)->&TargetStepOrigin{&self.phase.origin} - pub(in crate::qwen_forward) fn len(&self)->usize{self.tokens.len()} - pub(in crate::qwen_forward) fn start_position(&self)->u64{self.phase.first} - pub(in crate::qwen_forward) fn end_position(&self)->u64{self.phase.end} - pub(in crate::qwen_forward) fn known_prompt_next(&self)->Result>{ - self.check()?; - let first=usize::try_from(self.phase.first).map_err(|_|Error::Overflow)?; - let end=usize::try_from(self.phase.end).map_err(|_|Error::Overflow)?; - if !self.phase.source.binding.matches(&self.session.binding) - ||self.phase.source.tokens.get(first..end)!=Some(self.tokens.as_slice()){return Err(Error::IdentityMismatch);} - Ok(self.phase.source.tokens.get(end).copied()) - } - /// Whole immutable request length, not the current prefill chunk end. - /// Original MTP cutoff depends on this authentic full prompt owner. - pub(in crate::qwen_forward) fn full_prompt_length(&self)->Result{ - self.known_prompt_next()?; - Ok(self.phase.source.tokens.len()) - } - pub(in crate::qwen_forward) fn phase(&self)->Rc{Rc::clone(&self.phase)} - pub(in crate::qwen_forward) fn context(&self)->Result<&Context<'driver>>{self.check()?;self.session.mtp_context()} - pub(in crate::qwen_forward) fn input(&self,index:usize)->Result>{ - self.check()?;self.inputs.get(index).map(Rc::clone).ok_or(Error::IdentityMismatch) - } - pub(in crate::qwen_forward) fn row_key(&self,index:usize)->Result{ - self.check()?;let input=self.inputs.get(index).ok_or(Error::IdentityMismatch)?; - Ok(OriginalPromptRowKey{phase:Rc::clone(&self.phase),index,token:input.token(),position:input.position()}) - } - pub(in crate::qwen_forward) fn source_key(&self,index:usize,input:&Rc,context:&Context<'_>)->Result{ - self.check()?; - if !std::ptr::eq(context,self.session.mtp_context()?) - || self.inputs.len()!=self.tokens.len() - || self.inputs.get(index).is_none_or(|actual|!Rc::ptr_eq(actual,input)) { - return Err(Error::IdentityMismatch); - } - let key=self.row_key(index)?;key.validate_initial(&self.session.binding,input)?;Ok(key) - } - /// Actual initial input transactions only. No intermediate layer/history - /// is constructed by this view; each next row uses true token predecessors. - pub(in crate::qwen_forward) fn stage_input(&mut self, - execute:impl FnOnce(&mut QwenStepTxn<'_, 'driver>)->Result)->Result<()> { - self.check()?; - if self.phase.phase.get()!=DevicePhase::Staging || self.inputs.len()>=self.tokens.len(){return Err(Error::IdentityMismatch);} - let index=self.inputs.len();let token=self.tokens[index]; - let position=Position::new(self.phase.first+index as u64,crate::qwen_forward::contract::position_dimension())?; - let mut view=QwenSession{binding:self.session.binding.clone(),owner:Rc::clone(&self.session.owner), - owner_thread:self.session.owner_thread,predecessors:self.predecessors,next_position:position.get(), - cuda:self.session.cuda.clone(),checkpoint_generation:self.session.checkpoint_generation,cuda_failed:false, - layer_count:48,ple_required:self.session.ple_required,ple_owner:self.session.ple_owner.clone(), - ple_state:self.session.ple_state.clone(),gdn_layers:self.session.gdn_layers, - gdn_owner:self.session.gdn_owner.clone(),gdn_states:self.session.gdn_states.clone(), - qsa_layers:self.session.qsa_layers,qsa_owner:self.session.qsa_owner.clone(),qsa_states:self.session.qsa_states.clone(),state_lag:None,resident_qsa_states:self.session.resident_qsa_states.clone()}; - let operation=(||{let mut step=view.begin(token,position)?; - let input=execute(&mut step)?;step.stage_input(input)})(); - match operation {Ok(input)=>{self.inputs.push(input);self.predecessors=[self.predecessors[1],token.get() as i32];Ok(())}, - Err(error)=>{self.phase.failed.set(true);self.session.note_mtp_failure(&error);Err(error)}} - } - pub(in crate::qwen_forward) fn validate_phase(&self,role:GrRole,read:bool)->Result<()> { - self.check()?;if self.inputs.len()!=self.tokens.len(){return Err(Error::IdentityMismatch);} - self.phase.validate_role(&self.session.binding,role,read) - } - pub(in crate::qwen_forward) fn validate_final(&self,completed:&super::super::super::prompt_device_rows::PromptDeviceFinal)->Result<()> { - self.check()?;completed.validate(self.phase.as_ref(),&self.session.binding)?; - if self.phase.phase.get()!=DevicePhase::Final - || self.tokens.last()!=Some(&completed.token()) - || completed.position().get().checked_add(1)!=Some(self.phase.end){return Err(Error::IdentityMismatch)} - Ok(()) - } - pub(in crate::qwen_forward) fn gdn_prior(&self,layer:LayerId)->Result{ - self.validate_phase(GrRole::Attention(layer.get()),true)?; - let slot=layer.get() as usize; - if slot>=48 || !self.session.gdn_layers[slot] || self.gdn_completed.get()&(1<prior.clone(),None if self.phase.first==0=> - GdnPrior::zero(self.session.binding.clone(),&self.session.gdn_owner,layer)?,None=>return Err(Error::IdentityMismatch)}; - prior.validate(&self.session.binding,&self.session.gdn_owner,layer,Position::new(self.phase.first,crate::qwen_forward::contract::position_dimension())?)?; - self.gdn_priors.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?[slot]=Some(prior.clone());Ok(prior) - } - pub(in crate::qwen_forward) fn stage_gdn(&self,prior:&GdnPrior,next:GdnPrior)->Result<()> { - let layer=prior.layer();let actual=self.gdn_prior(layer)?; - if !actual.same_state(prior){return Err(Error::IdentityMismatch);} - next.validate(&self.session.binding,&self.session.gdn_owner,layer,Position::new(self.phase.end,crate::qwen_forward::contract::position_dimension())?)?; - self.next_gdn.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?[layer.get() as usize]=Some(next); - self.gdn_completed.set(self.gdn_completed.get()|(1<Result{ - self.validate_phase(GrRole::Attention(1),false)?; - if !self.session.ple_required || self.next_ple.borrow().is_some(){return Err(Error::IdentityMismatch);} - if let Some(prior)=self.ple_prior.borrow().as_ref(){return Ok(prior.clone());} - let prior=match &self.session.ple_state{Some(prior)=>prior.clone(),None if self.phase.first==0=> - PlePrior::zero(self.session.binding.clone(),&self.session.ple_owner)?,None=>return Err(Error::IdentityMismatch)}; - prior.validate(&self.session.binding,&self.session.ple_owner,Position::new(self.phase.first,crate::qwen_forward::contract::position_dimension())?)?; - *self.ple_prior.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?=Some(prior.clone());Ok(prior) - } - pub(in crate::qwen_forward) fn stage_ple(&self,prior:&PlePrior,next:PlePrior)->Result<()> { - self.check()?; - if !self.phase.ple_done.get() || self.next_ple.borrow().is_some(){return Err(Error::IdentityMismatch);} - let actual=self.ple_prior.borrow().clone().ok_or(Error::IdentityMismatch)?; - // Initial zero prior must be retained by the authentic producer; its - // owner/range validation is authoritative even when no prior is stored. - prior.validate(&self.session.binding,&self.session.ple_owner,Position::new(self.phase.first,crate::qwen_forward::contract::position_dimension())?)?; - if !actual.same_state(prior){return Err(Error::IdentityMismatch);} - next.validate(&self.session.binding,&self.session.ple_owner,Position::new(self.phase.end,crate::qwen_forward::contract::position_dimension())?)?; - *self.next_ple.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?=Some(next);Ok(()) - } - pub(in crate::qwen_forward) fn qsa_prior(&self,binding:&ModelBinding,layer:LayerId)->Result> { - self.validate_phase(GrRole::Attention(layer.get()),true)?; - let slot=layer.get()as usize; - if slot>=48||!self.session.qsa_layers[slot]||self.qsa_completed.get()&(1<Result> { - self.check()?; - if self.inputs.len()!=self.tokens.len(){return Err(Error::IdentityMismatch);} - let mut rows=Vec::new();rows.try_reserve_exact(self.inputs.len()).map_err(|_|Error::InputAllocation)?; - rows.extend(self.inputs.iter().map(Rc::as_ref));Ok(rows) - } - pub(in crate::qwen_forward) fn abort(self,binding:&ModelBinding,dense:&DenseWeightCache<'driver>, - layers:&mut[Option>;STATE_CAPACITY],checkpoint:&OriginalSessionCheckpoint<'driver>)->Result<()> { - self.phase.failed.set(true); - self.session.restore_original_checkpoint(binding,dense,layers,checkpoint) - } - /// Attempt both physical restores even if one fails. The accepted target - /// branch is read back only after the real layer rollback; it is never - /// inferred from a requested position or the draft's end metadata. - pub(in crate::qwen_forward) fn abort_with_draft(self,binding:&ModelBinding,dense:&DenseWeightCache<'driver>, - layers:&mut[Option>;STATE_CAPACITY],checkpoint:&OriginalSessionCheckpoint<'driver>, - draft:&mut draft::OriginalDraftSession<'driver>,prior:&draft::OriginalDraftCheckpoint)->Result<()> { - self.phase.failed.set(true); - let mut first=draft.restore_physical(binding,dense,prior).err(); - if let Err(error)=self.session.restore_original_checkpoint(binding,dense,layers,checkpoint){first.get_or_insert(error);} - if first.is_none(){ - match self.session.target_origin(){ - Ok(actual)=>{if let Err(error)=draft.rebind_restored(prior,&actual){first.get_or_insert(error);}}, - Err(error)=>{first.get_or_insert(error);}, - } - } - if let Some(error)=first{draft.mark_failed();self.session.note_mtp_failure(&error);Err(error)}else{Ok(())} - } - pub(in crate::qwen_forward) fn stage_qsa(&self,binding:&ModelBinding,dense:&DenseWeightCache<'driver>,seal:ResidentQsaSeal<'driver>)->Result<()> { - let layer=seal.layer();let prior=self.qsa_prior(binding,layer)?; - seal.validate_for(binding,dense,self.session,layer,self.phase.first,self.len())?; - if !seal.previous_matches(&prior){return Err(Error::IdentityMismatch);} - seal.next_prior().validate_for_session(binding,self.session,layer,self.phase.end)?; - self.next_qsa.try_borrow_mut().map_err(|_|Error::IdentityMismatch)?[layer.get()as usize]=Some(seal); - self.qsa_completed.set(self.qsa_completed.get()|(1<, - layers:&mut[Option>;STATE_CAPACITY], - completed:&super::super::super::prompt_device_rows::PromptDeviceFinal, - draft:&mut draft::OriginalDraftSession<'driver>, - draft_kv:&super::super::super::prompt_device_rows::OriginalDraftKvPending, - sample:&super::super::super::output::OriginalPromptSample)->Result<(TargetStepOrigin,Option)> { - self.validate_final(completed)?; - sample.validate(binding,completed,self)?; - draft_kv.validate(binding,self,completed)?; - if draft_kv.last_next(binding,self,completed)?!=sample.next(){return Err(Error::IdentityMismatch);} - let draft_permit=draft.prepare_publication(binding,self,draft_kv.completed())?; - let end=Position::new(self.phase.end,crate::qwen_forward::contract::position_dimension())?; - let ple=self.next_ple.get_mut().clone();let gdn=self.next_gdn.get_mut().clone(); - let mut qsa=std::mem::replace(self.next_qsa.get_mut(),std::array::from_fn(|_|None)); - if self.session.ple_required {ple.as_ref().ok_or(Error::IdentityMismatch)?.validate(&self.session.binding,&self.session.ple_owner,end)?;} - let mut required_gdn=0u64;let mut required_qsa=0u64; - for slot in 0..48 {let layer=LayerId::new(slot as u64,Dimension::new(48)?)?; - if self.session.gdn_layers[slot] {required_gdn|=1< OriginalPromptTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn begin( + session: &'session mut QwenSession<'driver>, + binding: &ModelBinding, + source: &Rc, + count: usize, + ) -> Result { + let origin = session.target_origin()?; + if session.state_lag.is_some() { + return Err(Error::IdentityMismatch); + } + let tokens = source.window(binding, session.next_position, count)?; + for slot in 0..48 { + if session.qsa_layers[slot] { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate_for_session( + binding, + session, + layer, + session.next_position, + )?; + if session.qsa_states[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } else if session.resident_qsa_states[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + if !(1..=8192).contains(&tokens.len()) + || binding.layer_count() != 48 + || !session.binding.matches(&binding.identity()) + || session.layer_count != 48 + || session.cuda.is_none() + { + return Err(Error::IdentityMismatch); + } + let end = session.next_position.checked_add(tokens.len() as u64).ok_or(Error::Overflow)?; + let limit = u64::from(binding.input_constants().context_length()); + // A subsequent sampled token requires one remaining valid position. + if end >= limit { + return Err(Error::InvalidPosition); + } + let vocab = Dimension::new(248320)?; + for token in tokens { + if *token != TokenId::new(token.get() as u64, vocab)? { + return Err(Error::InvalidToken); + } + } + let mut owned = Vec::new(); + owned.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; + owned.extend_from_slice(tokens); + let mut inputs = Vec::new(); + inputs.try_reserve_exact(tokens.len()).map_err(|_| Error::InputAllocation)?; + let phase = Rc::new(OriginalPromptPhase { + binding: binding.identity(), + source: Rc::clone(source), + origin, + owner: Rc::new(()), + phase: Cell::new(DevicePhase::Staging), + ple_required: session.ple_required, + ple_done: Cell::new(false), + failed: Cell::new(false), + rows: tokens.len(), + first: session.next_position, + end, + }); + Ok(Self { + predecessors: session.predecessors, + next_ple: RefCell::new(None), + ple_prior: RefCell::new(None), + gdn_priors: RefCell::new(std::array::from_fn(|_| None)), + next_gdn: RefCell::new(std::array::from_fn(|_| None)), + next_qsa: RefCell::new(std::array::from_fn(|_| None)), + gdn_completed: Cell::new(0), + qsa_completed: Cell::new(0), + session, + phase, + tokens: owned, + inputs, + }) + } + pub(in super::super) fn check(&self) -> Result<()> { + self.phase.origin.validate(self.session)?; + if self.phase.failed.get() { + return Err(Error::IdentityMismatch); + } + if self.session.mtp_context()?.is_poisoned() { + return Err(Error::CudaExecution); + } + Ok(()) + } + pub(in crate::qwen_forward) fn original_session(&self) -> &QwenSession<'driver> { + self.session + } + pub(in crate::qwen_forward) fn origin(&self) -> &TargetStepOrigin { + &self.phase.origin + } + pub(in crate::qwen_forward) fn len(&self) -> usize { + self.tokens.len() + } + pub(in crate::qwen_forward) fn start_position(&self) -> u64 { + self.phase.first + } + pub(in crate::qwen_forward) fn end_position(&self) -> u64 { + self.phase.end + } + pub(in crate::qwen_forward) fn known_prompt_next(&self) -> Result> { + self.check()?; + let first = usize::try_from(self.phase.first).map_err(|_| Error::Overflow)?; + let end = usize::try_from(self.phase.end).map_err(|_| Error::Overflow)?; + if !self.phase.source.binding.matches(&self.session.binding) + || self.phase.source.tokens.get(first..end) != Some(self.tokens.as_slice()) + { + return Err(Error::IdentityMismatch); + } + Ok(self.phase.source.tokens.get(end).copied()) + } + /// Whole immutable request length, not the current prefill chunk end. + /// Original MTP cutoff depends on this authentic full prompt owner. + pub(in crate::qwen_forward) fn full_prompt_length(&self) -> Result { + self.known_prompt_next()?; + Ok(self.phase.source.tokens.len()) + } + pub(in crate::qwen_forward) fn phase(&self) -> Rc { + Rc::clone(&self.phase) + } + pub(in crate::qwen_forward) fn context(&self) -> Result<&Context<'driver>> { + self.check()?; + self.session.mtp_context() + } + pub(in crate::qwen_forward) fn input(&self, index: usize) -> Result> { + self.check()?; + self.inputs.get(index).map(Rc::clone).ok_or(Error::IdentityMismatch) + } + pub(in crate::qwen_forward) fn row_key(&self, index: usize) -> Result { + self.check()?; + let input = self.inputs.get(index).ok_or(Error::IdentityMismatch)?; + Ok(OriginalPromptRowKey { + phase: Rc::clone(&self.phase), + index, + token: input.token(), + position: input.position(), + }) + } + pub(in crate::qwen_forward) fn source_key( + &self, + index: usize, + input: &Rc, + context: &Context<'_>, + ) -> Result { + self.check()?; + if !std::ptr::eq(context, self.session.mtp_context()?) + || self.inputs.len() != self.tokens.len() + || self.inputs.get(index).is_none_or(|actual| !Rc::ptr_eq(actual, input)) + { + return Err(Error::IdentityMismatch); + } + let key = self.row_key(index)?; + key.validate_initial(&self.session.binding, input)?; + Ok(key) + } + /// Actual initial input transactions only. No intermediate layer/history + /// is constructed by this view; each next row uses true token predecessors. + pub(in crate::qwen_forward) fn stage_input( + &mut self, + execute: impl FnOnce(&mut QwenStepTxn<'_, 'driver>) -> Result, + ) -> Result<()> { + self.check()?; + if self.phase.phase.get() != DevicePhase::Staging || self.inputs.len() >= self.tokens.len() { + return Err(Error::IdentityMismatch); + } + let index = self.inputs.len(); + let token = self.tokens[index]; + let position = + Position::new(self.phase.first + index as u64, crate::qwen_forward::contract::position_dimension())?; + let mut view = QwenSession { + binding: self.session.binding.clone(), + owner: Rc::clone(&self.session.owner), + owner_thread: self.session.owner_thread, + predecessors: self.predecessors, + next_position: position.get(), + cuda: self.session.cuda.clone(), + checkpoint_generation: self.session.checkpoint_generation, + cuda_failed: false, + layer_count: 48, + ple_required: self.session.ple_required, + ple_owner: self.session.ple_owner.clone(), + ple_state: self.session.ple_state.clone(), + gdn_layers: self.session.gdn_layers, + gdn_owner: self.session.gdn_owner.clone(), + gdn_states: self.session.gdn_states.clone(), + qsa_layers: self.session.qsa_layers, + qsa_owner: self.session.qsa_owner.clone(), + qsa_states: self.session.qsa_states.clone(), + state_lag: None, + resident_qsa_states: self.session.resident_qsa_states.clone(), + }; + let operation = (|| { + let mut step = view.begin(token, position)?; + let input = execute(&mut step)?; + step.stage_input(input) + })(); + match operation { + Ok(input) => { + self.inputs.push(input); + self.predecessors = [self.predecessors[1], token.get() as i32]; + Ok(()) + } + Err(error) => { + self.phase.failed.set(true); + self.session.note_mtp_failure(&error); + Err(error) + } + } + } + pub(in crate::qwen_forward) fn validate_phase(&self, role: GrRole, read: bool) -> Result<()> { + self.check()?; + if self.inputs.len() != self.tokens.len() { + return Err(Error::IdentityMismatch); + } + self.phase.validate_role(&self.session.binding, role, read) + } + pub(in crate::qwen_forward) fn validate_final( + &self, + completed: &super::super::super::super::prompt_device_rows::PromptDeviceFinal, + ) -> Result<()> { + self.check()?; + completed.validate(self.phase.as_ref(), &self.session.binding)?; + if self.phase.phase.get() != DevicePhase::Final + || self.tokens.last() != Some(&completed.token()) + || completed.position().get().checked_add(1) != Some(self.phase.end) + { + return Err(Error::IdentityMismatch); + } + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs new file mode 100644 index 00000000..10797cc9 --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_2_2.rs @@ -0,0 +1,181 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptTxn (2). + +#[allow(unused_imports)] +use super::*; + +impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> { + pub(in crate::qwen_forward) fn gdn_prior(&self, layer: LayerId) -> Result { + self.validate_phase(GrRole::Attention(layer.get()), true)?; + let slot = layer.get() as usize; + if slot >= 48 || !self.session.gdn_layers[slot] || self.gdn_completed.get() & (1 << slot) != 0 { + return Err(Error::IdentityMismatch); + } + if let Some(prior) = self.gdn_priors.borrow()[slot].as_ref() { + return Ok(prior.clone()); + } + let prior = match &self.session.gdn_states[slot] { + Some(prior) => prior.clone(), + None if self.phase.first == 0 => { + GdnPrior::zero(self.session.binding.clone(), &self.session.gdn_owner, layer)? + } + None => return Err(Error::IdentityMismatch), + }; + prior.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + Position::new(self.phase.first, crate::qwen_forward::contract::position_dimension())?, + )?; + self.gdn_priors.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?[slot] = Some(prior.clone()); + Ok(prior) + } + pub(in crate::qwen_forward) fn stage_gdn(&self, prior: &GdnPrior, next: GdnPrior) -> Result<()> { + let layer = prior.layer(); + let actual = self.gdn_prior(layer)?; + if !actual.same_state(prior) { + return Err(Error::IdentityMismatch); + } + next.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?, + )?; + self.next_gdn.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?[layer.get() as usize] = Some(next); + self.gdn_completed.set(self.gdn_completed.get() | (1 << layer.get())); + Ok(()) + } + pub(in crate::qwen_forward) fn ple_prior(&self) -> Result { + self.validate_phase(GrRole::Attention(1), false)?; + if !self.session.ple_required || self.next_ple.borrow().is_some() { + return Err(Error::IdentityMismatch); + } + if let Some(prior) = self.ple_prior.borrow().as_ref() { + return Ok(prior.clone()); + } + let prior = match &self.session.ple_state { + Some(prior) => prior.clone(), + None if self.phase.first == 0 => PlePrior::zero(self.session.binding.clone(), &self.session.ple_owner)?, + None => return Err(Error::IdentityMismatch), + }; + prior.validate( + &self.session.binding, + &self.session.ple_owner, + Position::new(self.phase.first, crate::qwen_forward::contract::position_dimension())?, + )?; + *self.ple_prior.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? = Some(prior.clone()); + Ok(prior) + } + pub(in crate::qwen_forward) fn stage_ple(&self, prior: &PlePrior, next: PlePrior) -> Result<()> { + self.check()?; + if !self.phase.ple_done.get() || self.next_ple.borrow().is_some() { + return Err(Error::IdentityMismatch); + } + let actual = self.ple_prior.borrow().clone().ok_or(Error::IdentityMismatch)?; + // Initial zero prior must be retained by the authentic producer; its + // owner/range validation is authoritative even when no prior is stored. + prior.validate( + &self.session.binding, + &self.session.ple_owner, + Position::new(self.phase.first, crate::qwen_forward::contract::position_dimension())?, + )?; + if !actual.same_state(prior) { + return Err(Error::IdentityMismatch); + } + next.validate( + &self.session.binding, + &self.session.ple_owner, + Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?, + )?; + *self.next_ple.try_borrow_mut().map_err(|_| Error::IdentityMismatch)? = Some(next); + Ok(()) + } + pub(in crate::qwen_forward) fn qsa_prior( + &self, + binding: &ModelBinding, + layer: LayerId, + ) -> Result> { + self.validate_phase(GrRole::Attention(layer.get()), true)?; + let slot = layer.get() as usize; + if slot >= 48 || !self.session.qsa_layers[slot] || self.qsa_completed.get() & (1 << slot) != 0 { + return Err(Error::IdentityMismatch); + } + let prior = self.session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?.clone(); + prior.validate_for_session(binding, self.session, layer, self.phase.first)?; + Ok(prior) + } + pub(in crate::qwen_forward) fn input_references(&self) -> Result> { + self.check()?; + if self.inputs.len() != self.tokens.len() { + return Err(Error::IdentityMismatch); + } + let mut rows = Vec::new(); + rows.try_reserve_exact(self.inputs.len()).map_err(|_| Error::InputAllocation)?; + rows.extend(self.inputs.iter().map(Rc::as_ref)); + Ok(rows) + } + pub(in crate::qwen_forward) fn abort( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + layers: &mut [Option>; STATE_CAPACITY], + checkpoint: &OriginalSessionCheckpoint<'driver>, + ) -> Result<()> { + self.phase.failed.set(true); + self.session.restore_original_checkpoint(binding, dense, layers, checkpoint) + } + /// Attempt both physical restores even if one fails. The accepted target + /// branch is read back only after the real layer rollback; it is never + /// inferred from a requested position or the draft's end metadata. + pub(in crate::qwen_forward) fn abort_with_draft( + self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + layers: &mut [Option>; STATE_CAPACITY], + checkpoint: &OriginalSessionCheckpoint<'driver>, + draft: &mut draft::OriginalDraftSession<'driver>, + prior: &draft::OriginalDraftCheckpoint, + ) -> Result<()> { + self.phase.failed.set(true); + let mut first = draft.restore_physical(binding, dense, prior).err(); + if let Err(error) = self.session.restore_original_checkpoint(binding, dense, layers, checkpoint) { + first.get_or_insert(error); + } + if first.is_none() { + match self.session.target_origin() { + Ok(actual) => { + if let Err(error) = draft.rebind_restored(prior, &actual) { + first.get_or_insert(error); + } + } + Err(error) => { + first.get_or_insert(error); + } + } + } + if let Some(error) = first { + draft.mark_failed(); + self.session.note_mtp_failure(&error); + Err(error) + } else { + Ok(()) + } + } + pub(in crate::qwen_forward) fn stage_qsa( + &self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + seal: ResidentQsaSeal<'driver>, + ) -> Result<()> { + let layer = seal.layer(); + let prior = self.qsa_prior(binding, layer)?; + seal.validate_for(binding, dense, self.session, layer, self.phase.first, self.len())?; + if !seal.previous_matches(&prior) { + return Err(Error::IdentityMismatch); + } + seal.next_prior().validate_for_session(binding, self.session, layer, self.phase.end)?; + self.next_qsa.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?[layer.get() as usize] = Some(seal); + self.qsa_completed.set(self.qsa_completed.get() | (1 << layer.get())); + Ok(()) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs new file mode 100644 index 00000000..beca3a5d --- /dev/null +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_prompt/impl_originalprompttxn/impl_originalprompttxn_3.rs @@ -0,0 +1,101 @@ +//! Moved out of the parent module by STRA-338: impl OriginalPromptTxn (3). + +#[allow(unused_imports)] +use super::*; + +impl<'session, 'driver> OriginalPromptTxn<'session, 'driver> { + /// Validate every real layer seal before preparing any publication. All + /// twelve affine permits then perform only infallible state assignment. + /// No host QsaIndexPrior is fabricated from an end-only resident checkpoint. + pub(in crate::qwen_forward) fn publish( + &mut self, + binding: &ModelBinding, + dense: &DenseWeightCache<'driver>, + layers: &mut [Option>; STATE_CAPACITY], + completed: &super::super::super::super::prompt_device_rows::PromptDeviceFinal, + draft: &mut draft::OriginalDraftSession<'driver>, + draft_kv: &super::super::super::super::prompt_device_rows::OriginalDraftKvPending, + sample: &super::super::super::super::output::OriginalPromptSample, + ) -> Result<(TargetStepOrigin, Option)> { + self.validate_final(completed)?; + sample.validate(binding, completed, self)?; + draft_kv.validate(binding, self, completed)?; + if draft_kv.last_next(binding, self, completed)? != sample.next() { + return Err(Error::IdentityMismatch); + } + let draft_permit = draft.prepare_publication(binding, self, draft_kv.completed())?; + let end = Position::new(self.phase.end, crate::qwen_forward::contract::position_dimension())?; + let ple = self.next_ple.get_mut().clone(); + let gdn = self.next_gdn.get_mut().clone(); + let mut qsa = std::mem::replace(self.next_qsa.get_mut(), std::array::from_fn(|_| None)); + if self.session.ple_required { + ple.as_ref().ok_or(Error::IdentityMismatch)?.validate( + &self.session.binding, + &self.session.ple_owner, + end, + )?; + } + let mut required_gdn = 0u64; + let mut required_qsa = 0u64; + for slot in 0..48 { + let layer = LayerId::new(slot as u64, Dimension::new(48)?)?; + if self.session.gdn_layers[slot] { + required_gdn |= 1 << slot; + gdn[slot].as_ref().ok_or(Error::IdentityMismatch)?.validate( + &self.session.binding, + &self.session.gdn_owner, + layer, + end, + )?; + } else if gdn[slot].is_some() { + return Err(Error::IdentityMismatch); + } + if self.session.qsa_layers[slot] { + required_qsa |= 1 << slot; + let seal = qsa[slot].as_ref().ok_or(Error::IdentityMismatch)?; + seal.validate_for(binding, dense, self.session, layer, self.phase.first, self.tokens.len())?; + let prior = self.session.resident_qsa_states[slot].as_ref().ok_or(Error::IdentityMismatch)?; + if !seal.previous_matches(prior) { + return Err(Error::IdentityMismatch); + } + seal.next_prior().validate_for_session(binding, self.session, layer, self.phase.end)?; + if layers[slot].is_none() { + return Err(Error::IdentityMismatch); + } + } else if qsa[slot].is_some() || layers[slot].is_some() { + return Err(Error::IdentityMismatch); + } + } + if self.gdn_completed.get() != required_gdn || self.qsa_completed.get() != required_qsa { + return Err(Error::IdentityMismatch); + } + let output = sample.emitted(); + let mut permits = Vec::new(); + permits.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; + for (slot, layer) in layers.iter_mut().enumerate() { + if let Some(layer) = layer { + let seal = qsa[slot].take().ok_or(Error::IdentityMismatch)?; + permits.push((slot, layer.prepare_publication(binding, dense, self.session, seal)?)); + } + } + if permits.len() != 12 { + return Err(Error::IdentityMismatch); + } + self.session.complete_cuda()?; + let mut resident = std::array::from_fn(|_| None); + for (slot, permit) in permits { + resident[slot] = Some(permit.publish_validated()); + } + // No fallible operation after the first canonical assignment. + self.session.ple_state = ple; + self.session.gdn_states = gdn; + self.session.qsa_states = std::array::from_fn(|_| None); + self.session.resident_qsa_states = resident; + self.session.predecessors = self.predecessors; + self.session.next_position = self.phase.end; + self.phase.phase.set(DevicePhase::Published); + let actual = super::super::super::checkpoint::committed_origin(self.session); + draft_permit.publish_validated(actual.clone()); + Ok((actual, output)) + } +} diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified.rs index 464a27bd..55aa0767 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified.rs @@ -17,9 +17,9 @@ //! //! While the lag is open the session refuses prompt transactions and checkpoints (their priors would //! describe a position the session does not hold); a checkpoint restore replaces every prior and ends it. -use super::*; -use super::checkpoint::{committed_origin,origin_at}; use super::super::qsa_index::prompt_device::resident_device::ResidentQsaPrior; +use super::checkpoint::{committed_origin, origin_at}; +use super::*; /// Largest verified window (`kVerifyMaxT`). pub(in crate::qwen_forward) const MAX_WINDOW_ROWS: usize = 8; @@ -79,9 +79,11 @@ impl<'driver> QwenSession<'driver> { if self.gdn_layers[slot] { gdn[slot] = Some(match &self.gdn_states[slot] { Some(prior) => prior.clone(), - None if state_position == 0 => { - GdnPrior::zero(self.binding.clone(), &self.gdn_owner, LayerId::new(slot as u64, Dimension::new(48)?)?)? - } + None if state_position == 0 => GdnPrior::zero( + self.binding.clone(), + &self.gdn_owner, + LayerId::new(slot as u64, Dimension::new(48)?)?, + )?, None => return Err(Error::IdentityMismatch), }); } @@ -96,7 +98,9 @@ impl<'driver> QwenSession<'driver> { /// The twelve resident QSA witnesses at the session's position (the per-round publication replaces /// exactly these). Cheap: no recurrent prior is materialized. - pub(in crate::qwen_forward) fn original_qsa_witnesses(&self) -> Result<[Option>; STATE_CAPACITY]> { + pub(in crate::qwen_forward) fn original_qsa_witnesses( + &self, + ) -> Result<[Option>; STATE_CAPACITY]> { self.target_origin()?; if self.layer_count != 48 { return Err(Error::IdentityMismatch); @@ -183,7 +187,12 @@ impl<'driver> QwenSession<'driver> { } Ok(()) } - fn check_state(&self, gdn: &[Option; STATE_CAPACITY], ple: &Option, at: Position) -> Result<()> { + fn check_state( + &self, + gdn: &[Option; STATE_CAPACITY], + ple: &Option, + at: Position, + ) -> Result<()> { if self.ple_required { ple.as_ref().ok_or(Error::IdentityMismatch)?.validate(&self.binding, &self.ple_owner, at)?; } else if ple.is_some() { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified/tests.rs b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified/tests.rs index 63901d01..f1a6d7ee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified/tests.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/session_original_verified/tests.rs @@ -28,9 +28,10 @@ fn state_after(session: &QwenSession<'static>, rows: usize) -> OriginalVerifiedL for slot in 0..STATE_CAPACITY { lineage.gdn[slot] = base.gdn[slot].as_ref().map(|prior| gdn_after(prior, rows)); } - lineage.ple = base.ple.as_ref().map(|prior| { - PlePrior::from_original_verified(prior, rows, vec![0.125; 9 * 10240].into_boxed_slice()).unwrap() - }); + lineage.ple = base + .ple + .as_ref() + .map(|prior| PlePrior::from_original_verified(prior, rows, vec![0.125; 9 * 10240].into_boxed_slice()).unwrap()); lineage } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs b/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs index 31e6f9d9..ff431da7 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/shared_expert_workspace.rs @@ -3,8 +3,7 @@ use super::contract::{Error, Result, TokenLayer}; use super::qsa_index::driver_error; use crate::model_binding::qwen4exp_input::{BindingIdentity, ModelBinding, MoeWeightDescriptor}; use leleka_cuda_driver::{ - Context, DeviceBuffer, SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, - SharedGuKind, SharedTailRefusal, + Context, DeviceBuffer, SharedDownKind, SharedExpertWeights, SharedExpertWorkspace, SharedGuKind, SharedTailRefusal, }; use std::rc::Rc; @@ -41,12 +40,7 @@ fn down_kind(key: MoeWeightDescriptor) -> Result { 20 => (SharedDownKind::Iq4Nl, 921_600), _ => return Err(Error::InvalidDimension), }; - if key.expert.is_some() - || key.role != 2 - || key.rows != 2560 - || key.columns != 640 - || key.bytes != bytes - { + if key.expert.is_some() || key.role != 2 || key.rows != 2560 || key.columns != 640 || key.bytes != bytes { return Err(Error::InvalidDimension); } Ok(kind) @@ -72,22 +66,13 @@ pub(super) fn validate_descriptors(keys: &[MoeWeightDescriptor; 4]) -> Result<() } impl<'ctx> TargetSharedWorkspace<'ctx> { #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - pub(super) fn new( - binding: BindingIdentity, - owner: Rc<()>, - context: &'ctx Context<'ctx>, - ) -> Result { + pub(super) fn new(binding: BindingIdentity, owner: Rc<()>, context: &'ctx Context<'ctx>) -> Result { let workspace = context.shared_expert_workspace().map_err(driver_error)?; if workspace.allocated_bytes() != ALLOCATED_BYTES { let _ = workspace.close(); return Err(Error::IdentityMismatch); } - Ok(Self { - binding, - owner, - context, - workspace, - }) + Ok(Self { binding, owner, context, workspace }) } #[allow(clippy::too_many_arguments)] pub(super) fn compose( @@ -133,13 +118,11 @@ impl<'ctx> TargetSharedWorkspace<'ctx> { ) .map_err(driver_error)?; // All driver numeric refusals retain the original runtime NonFinite class. - completion - .into_final_values() - .map_err(|refusal| match refusal { - SharedTailRefusal::InvalidQ8Activation - | SharedTailRefusal::NonFinite - | SharedTailRefusal::InvalidScalar => Error::NonFinite, - }) + completion.into_final_values().map_err(|refusal| match refusal { + SharedTailRefusal::InvalidQ8Activation + | SharedTailRefusal::NonFinite + | SharedTailRefusal::InvalidScalar => Error::NonFinite, + }) } pub(super) fn close(self) -> Result<()> { self.workspace.close().map_err(driver_error) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/step_sampler.rs b/crates/engine-qwen35-cuda/src/qwen_forward/step_sampler.rs index 02151035..1c9e32e6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/step_sampler.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/step_sampler.rs @@ -29,11 +29,7 @@ impl StepSampler { if prompt.is_empty() || prompt.iter().any(|&t| t as usize >= VOCABULARY) { return Err(Error::InvalidToken); } - Ok(Self { - params, - prompt: prompt.iter().map(|&t| t as i32).collect(), - generated: Vec::new(), - }) + Ok(Self { params, prompt: prompt.iter().map(|&t| t as i32).collect(), generated: Vec::new() }) } /// The fed token at `position` is the first whose logits are sampled (the last prompt @@ -55,21 +51,14 @@ impl StepSampler { if position != self.fed_index() { return Err(Error::IdentityMismatch); } - let h = usize::try_from(self.params.penalty_last_n.max(0)) - .map_err(|_| Error::Overflow)? - .min(PENALTY_WINDOW_CAP); + let h = + usize::try_from(self.params.penalty_last_n.max(0)).map_err(|_| Error::Overflow)?.min(PENALTY_WINDOW_CAP); let total = self.prompt.len() + self.generated.len(); let take = h.min(total); let mut history = Vec::new(); - history - .try_reserve_exact(take) - .map_err(|_| Error::InputAllocation)?; + history.try_reserve_exact(take).map_err(|_| Error::InputAllocation)?; for i in total - take..total { - history.push(if i < self.prompt.len() { - self.prompt[i] - } else { - self.generated[i - self.prompt.len()] - }); + history.push(if i < self.prompt.len() { self.prompt[i] } else { self.generated[i - self.prompt.len()] }); } let mut params = self.params; params.counter = position; @@ -77,9 +66,7 @@ impl StepSampler { if token < 0 || token as usize >= VOCABULARY { return Err(Error::InvalidToken); } - self.generated - .try_reserve(1) - .map_err(|_| Error::InputAllocation)?; + self.generated.try_reserve(1).map_err(|_| Error::InputAllocation)?; self.generated.push(token); Ok(token as u32) } @@ -90,13 +77,7 @@ mod tests { use super::*; fn sampled(seed: u64) -> SamplerParams { - SamplerParams { - top_k: 8, - top_p: 0.9, - temperature: 0.8, - seed, - ..SamplerParams::default() - } + SamplerParams { top_k: 8, top_p: 0.9, temperature: 0.8, seed, ..SamplerParams::default() } } fn logits(salt: usize) -> Vec { diff --git a/crates/engine-qwen35-cuda/src/serve_meta.rs b/crates/engine-qwen35-cuda/src/serve_meta.rs index 3fb7196d..e51cdb01 100644 --- a/crates/engine-qwen35-cuda/src/serve_meta.rs +++ b/crates/engine-qwen35-cuda/src/serve_meta.rs @@ -25,7 +25,8 @@ pub(crate) const MODEL_DIGEST_MAPPING: &str = "pinned-constant:sha256(shard0.raw /// A value as one token: blanks, `=` and control characters become `_`; empty becomes `-`. fn token(value: &str) -> String { - let cleaned: String = value.chars().map(|c| if c.is_whitespace() || c == '=' || c.is_control() { '_' } else { c }).collect(); + let cleaned: String = + value.chars().map(|c| if c.is_whitespace() || c == '=' || c.is_control() { '_' } else { c }).collect(); if cleaned.is_empty() { "-".to_owned() } else { cleaned } } @@ -101,7 +102,10 @@ impl ModelFile { Self { name, bytes: meta.as_ref().map(|m| m.len()), - mtime_unix_s: meta.and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()), + mtime_unix_s: meta + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()), } } } @@ -189,7 +193,12 @@ pub(crate) struct CacheFacts { } /// The `build`, `model` and `config` lines (without the `leleka-serve ` prefix), in this order. -pub(crate) fn startup_lines(build: &BuildInfo, profile: &ProfileInfo, model: &ModelInfo, config: &ConfigFacts) -> Vec { +pub(crate) fn startup_lines( + build: &BuildInfo, + profile: &ProfileInfo, + model: &ModelInfo, + config: &ConfigFacts, +) -> Vec { let mut lines = Vec::with_capacity(3); lines.push(line( "build", @@ -204,11 +213,19 @@ pub(crate) fn startup_lines(build: &BuildInfo, profile: &ProfileInfo, model: &Mo ("values_sha256", config.values_sha256()), ], )); - let mut model_fields = vec![("digest", model.digest.clone()), ("mapping", MODEL_DIGEST_MAPPING.to_owned()), ("verify", "recorded-no-rehash".to_owned()), ("files", model.files.len().to_string())]; + let mut model_fields = vec![ + ("digest", model.digest.clone()), + ("mapping", MODEL_DIGEST_MAPPING.to_owned()), + ("verify", "recorded-no-rehash".to_owned()), + ("files", model.files.len().to_string()), + ]; let mut file_keys: Vec<(String, String)> = Vec::new(); for (index, file) in model.files.iter().enumerate() { let number = |v: Option| v.map_or_else(|| "-".to_owned(), |n| n.to_string()); - file_keys.push((format!("file{index}"), format!("{}:{}:{}", token(&file.name).replace(':', "_"), number(file.bytes), number(file.mtime_unix_s)))); + file_keys.push(( + format!("file{index}"), + format!("{}:{}:{}", token(&file.name).replace(':', "_"), number(file.bytes), number(file.mtime_unix_s)), + )); } let owned: Vec<(&str, String)> = file_keys.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); model_fields.extend(owned); diff --git a/crates/engine-qwen35-cuda/src/serve_meta/tests.rs b/crates/engine-qwen35-cuda/src/serve_meta/tests.rs index cfa374b9..7b92ba05 100644 --- a/crates/engine-qwen35-cuda/src/serve_meta/tests.rs +++ b/crates/engine-qwen35-cuda/src/serve_meta/tests.rs @@ -35,8 +35,16 @@ pub(super) fn model() -> ModelInfo { ModelInfo { digest: DIGEST.to_owned(), files: vec![ - ModelFile { name: "model-00001-of-00002.gguf".to_owned(), bytes: Some(54_817_524_224), mtime_unix_s: Some(1_790_000_000) }, - ModelFile { name: "model-00002-of-00002.gguf".to_owned(), bytes: Some(28_800_138_432), mtime_unix_s: Some(1_790_000_001) }, + ModelFile { + name: "model-00001-of-00002.gguf".to_owned(), + bytes: Some(54_817_524_224), + mtime_unix_s: Some(1_790_000_000), + }, + ModelFile { + name: "model-00002-of-00002.gguf".to_owned(), + bytes: Some(28_800_138_432), + mtime_unix_s: Some(1_790_000_001), + }, ], } } @@ -44,7 +52,13 @@ pub(super) fn profile() -> ProfileInfo { ProfileInfo::from_values(Some("rtx5090-32g"), Some(PROFILE_SHA)) } pub(super) fn cache() -> CacheFacts { - CacheFacts { prefix_on: true, prefix_entries: 0, prefix_blocks: 0, prefix_used_bytes: 0, prefix_budget_bytes: 5_713_000_000 } + CacheFacts { + prefix_on: true, + prefix_entries: 0, + prefix_blocks: 0, + prefix_used_bytes: 0, + prefix_budget_bytes: 5_713_000_000, + } } /// The golden sample is shared with `scripts/e2e/evidence` (capture.py parses the same file): this pins the format of every line. @@ -54,7 +68,8 @@ fn the_meta_lines_match_the_golden_sample_byte_for_byte() { lines.push(cache_line(&cache())); let produced: String = lines.iter().map(|l| format!("leleka-serve {l}\n")).collect(); let golden = include_str!("../../../../scripts/e2e/evidence/golden/engine_meta_sample.txt").replace("\r\n", "\n"); - let golden_meta: String = golden.lines().filter(|l| l.starts_with("leleka-serve meta: ")).map(|l| format!("{l}\n")).collect(); + let golden_meta: String = + golden.lines().filter(|l| l.starts_with("leleka-serve meta: ")).map(|l| format!("{l}\n")).collect(); assert_eq!(produced, golden_meta); } @@ -108,7 +123,10 @@ fn an_unset_profile_is_printed_as_none_and_unset_and_a_bad_hash_is_refused() { let lines = startup_lines(&build(), &ProfileInfo::from_values(None, None), &model(), &config()); assert!(lines[0].contains(" profile=none profile_sha256=unset values_sha256=")); assert_eq!(ProfileInfo::from_values(Some(" "), Some("not-a-hash")), ProfileInfo { name: None, sha256: None }); - assert_eq!(ProfileInfo::from_values(Some("x"), Some(&PROFILE_SHA.to_ascii_uppercase())).sha256.as_deref(), Some(PROFILE_SHA)); + assert_eq!( + ProfileInfo::from_values(Some("x"), Some(&PROFILE_SHA.to_ascii_uppercase())).sha256.as_deref(), + Some(PROFILE_SHA) + ); } #[test] @@ -129,7 +147,10 @@ fn values_sha256_follows_the_values_and_nothing_else() { #[test] fn values_with_blanks_or_equals_cannot_split_a_token() { - let odd = ModelInfo { digest: "sha256:a b=c".to_owned(), files: vec![ModelFile { name: "my model=1.gguf".to_owned(), bytes: None, mtime_unix_s: None }] }; + let odd = ModelInfo { + digest: "sha256:a b=c".to_owned(), + files: vec![ModelFile { name: "my model=1.gguf".to_owned(), bytes: None, mtime_unix_s: None }], + }; let lines = startup_lines(&build(), &profile(), &odd, &config()); assert!(lines[1].contains(" digest=sha256:a_b_c "), "{}", lines[1]); assert!(lines[1].ends_with(" file0=my_model_1.gguf:-:-"), "{}", lines[1]); diff --git a/crates/engine-qwen35-cuda/src/serve_tuning.rs b/crates/engine-qwen35-cuda/src/serve_tuning.rs index 77472900..e97716b1 100644 --- a/crates/engine-qwen35-cuda/src/serve_tuning.rs +++ b/crates/engine-qwen35-cuda/src/serve_tuning.rs @@ -43,7 +43,8 @@ pub struct Tuning { impl Tuning { pub fn parse(text: &str) -> Result { - let tuning: Tuning = serde_json::from_str(text).map_err(|error| format!("invalid settings document: {error}"))?; + let tuning: Tuning = + serde_json::from_str(text).map_err(|error| format!("invalid settings document: {error}"))?; if tuning == Tuning::default() { return Err("the settings document changes nothing (members: context_tokens, prefill_capacity, kv_resident, prefix_cache_mib, prefix_cache_tail, prefix_cache_block, prefix_retention_min, cpu_workers, spec_min_p)".into()); } @@ -51,7 +52,11 @@ impl Tuning { } /// Apply to the current options and context; returns the names of the members that changed value. Nothing is modified on error. - pub fn apply(&self, options: &mut OriginalServeOptions, context_tokens: &mut u32) -> Result, String> { + pub fn apply( + &self, + options: &mut OriginalServeOptions, + context_tokens: &mut u32, + ) -> Result, String> { let mut next = options.clone(); let mut context = *context_tokens; let mut changed = Vec::new(); @@ -79,7 +84,9 @@ impl Tuning { } let in_force = next.kv_resident.unwrap_or(DEFAULT_KV_RESIDENT); if cells != in_force { - return Err(format!("kv_resident is fixed for the life of the process (now {in_force}); change it with a restart (`leleka up --kv-resident`)")); + return Err(format!( + "kv_resident is fixed for the life of the process (now {in_force}); change it with a restart (`leleka up --kv-resident`)" + )); } } if let Some(workers) = self.cpu_workers { @@ -100,7 +107,10 @@ impl Tuning { } next.spec_min_p = p; } - let touches_prefix = self.prefix_cache_mib.is_some() || self.prefix_cache_tail.is_some() || self.prefix_cache_block.is_some() || self.prefix_retention_min.is_some(); + let touches_prefix = self.prefix_cache_mib.is_some() + || self.prefix_cache_tail.is_some() + || self.prefix_cache_block.is_some() + || self.prefix_retention_min.is_some(); if touches_prefix { let before = next.prefix_cache.clone(); let mut prefix = before.clone().unwrap_or_default(); @@ -108,7 +118,13 @@ impl Tuning { prefix.budget_bytes = match text.trim().to_ascii_lowercase().as_str() { "auto" => None, "off" | "0" => Some(0), - mib => Some(mib.parse::().ok().filter(|m| *m <= 1 << 30).ok_or("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB")? << 20), + mib => Some( + mib.parse::() + .ok() + .filter(|m| *m <= 1 << 30) + .ok_or("prefix_cache_mib must be \"auto\", \"off\" or a size in MiB")? + << 20, + ), }; } if let Some(tail) = &self.prefix_cache_tail { @@ -121,7 +137,9 @@ impl Tuning { } if let Some(block) = self.prefix_cache_block { if block % 256 != 0 || block > 8192 { - return Err("prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into()); + return Err( + "prefix_cache_block must be a multiple of 256, at most 8192 (0 = the prefill chunk)".into() + ); } prefix.block_tokens = block; } @@ -147,7 +165,10 @@ impl Tuning { let chunk = next.prefill_capacity.unwrap_or(2048); if let Some(prefix) = &next.prefix_cache { if prefix.block_tokens > chunk { - return Err(format!("prefix_cache_block {} is larger than the prefill chunk {chunk}", prefix.block_tokens)); + return Err(format!( + "prefix_cache_block {} is larger than the prefill chunk {chunk}", + prefix.block_tokens + )); } } next.validate_for_tuning()?; @@ -158,7 +179,12 @@ impl Tuning { } /// The settings an engine reports (`telemetry.settings`, the reply of a reconfigure). -pub fn describe(options: &OriginalServeOptions, context_tokens: u32, cpu_workers_effective: i32, prefix_budget_bytes: Option) -> Value { +pub fn describe( + options: &OriginalServeOptions, + context_tokens: u32, + cpu_workers_effective: i32, + prefix_budget_bytes: Option, +) -> Value { let prefix = options.prefix_cache.as_ref().map(|p: &PrefixCacheOptions| { json!({ "budget_mib": prefix_budget_bytes.map(|b| b >> 20), @@ -185,7 +211,12 @@ mod tests { fn base() -> (OriginalServeOptions, u32) { let options = OriginalServeOptions { - prefix_cache: Some(PrefixCacheOptions { tail: PrefixTail::Off, budget_bytes: None, block_tokens: 0, retention_s: None }), + prefix_cache: Some(PrefixCacheOptions { + tail: PrefixTail::Off, + budget_bytes: None, + block_tokens: 0, + retention_s: None, + }), ..OriginalServeOptions::default() }; (options, 262_144) @@ -208,8 +239,20 @@ mod tests { assert_eq!(options.cpu_workers, Some(8)); assert_eq!(options.spec_min_p, 0.5); let prefix = options.prefix_cache.as_ref().unwrap(); - assert_eq!((prefix.tail, prefix.budget_bytes, prefix.block_tokens, prefix.retention_s), (PrefixTail::Reply, Some(20_480 << 20), 8192, Some(1800))); - for name in ["context_tokens", "prefill_capacity", "cpu_workers", "spec_min_p", "prefix_cache_mib", "prefix_cache_tail", "prefix_cache_block", "prefix_retention_min"] { + assert_eq!( + (prefix.tail, prefix.budget_bytes, prefix.block_tokens, prefix.retention_s), + (PrefixTail::Reply, Some(20_480 << 20), 8192, Some(1800)) + ); + for name in [ + "context_tokens", + "prefill_capacity", + "cpu_workers", + "spec_min_p", + "prefix_cache_mib", + "prefix_cache_tail", + "prefix_cache_block", + "prefix_retention_min", + ] { assert!(changed.contains(&name), "{name} in {changed:?}"); } // the same document again changes nothing @@ -223,7 +266,7 @@ mod tests { r#"{"context_tokens":300000}"#, r#"{"prefill_capacity":5000}"#, r#"{"kv_resident":1000}"#, - r#"{"kv_resident":0}"#, // fixed per process: only the value in force is accepted + r#"{"kv_resident":0}"#, // fixed per process: only the value in force is accepted r#"{"cpu_workers":0}"#, r#"{"cpu_workers":16}"#, r#"{"spec_min_p":1.5}"#, @@ -243,11 +286,25 @@ mod tests { #[test] fn the_resident_kv_window_is_accepted_only_at_the_value_in_force() { let (mut options, mut context) = base(); - let changed = Tuning::parse(r#"{"kv_resident":32768,"context_tokens":100000}"#).unwrap().apply(&mut options, &mut context).unwrap(); + let changed = Tuning::parse(r#"{"kv_resident":32768,"context_tokens":100000}"#) + .unwrap() + .apply(&mut options, &mut context) + .unwrap(); assert_eq!(changed, vec!["context_tokens"]); options.kv_resident = Some(40_960); - assert!(Tuning::parse(r#"{"kv_resident":32768}"#).unwrap().apply(&mut options, &mut context).unwrap_err().contains("restart")); - assert!(Tuning::parse(r#"{"kv_resident":40960,"prefill_capacity":4096}"#).unwrap().apply(&mut options, &mut context).is_ok()); + assert!( + Tuning::parse(r#"{"kv_resident":32768}"#) + .unwrap() + .apply(&mut options, &mut context) + .unwrap_err() + .contains("restart") + ); + assert!( + Tuning::parse(r#"{"kv_resident":40960,"prefill_capacity":4096}"#) + .unwrap() + .apply(&mut options, &mut context) + .is_ok() + ); } #[test] @@ -255,7 +312,10 @@ mod tests { let (mut options, mut context) = base(); Tuning::parse(r#"{"prefix_cache_mib":"off"}"#).unwrap().apply(&mut options, &mut context).unwrap(); assert!(options.prefix_cache.is_none()); - let changed = Tuning::parse(r#"{"prefix_cache_mib":"auto","prefix_cache_tail":"prompt"}"#).unwrap().apply(&mut options, &mut context).unwrap(); + let changed = Tuning::parse(r#"{"prefix_cache_mib":"auto","prefix_cache_tail":"prompt"}"#) + .unwrap() + .apply(&mut options, &mut context) + .unwrap(); assert_eq!(options.prefix_cache.as_ref().unwrap().tail, PrefixTail::Prompt); assert!(changed.contains(&"prefix_cache_mib")); } diff --git a/crates/engine-qwen35-cuda/src/serving.rs b/crates/engine-qwen35-cuda/src/serving.rs index 471ac579..56f18465 100644 --- a/crates/engine-qwen35-cuda/src/serving.rs +++ b/crates/engine-qwen35-cuda/src/serving.rs @@ -24,7 +24,10 @@ pub enum ServingError { /// `context_policy::resolve_context` refused (rope rules, size ceiling or the memory planner). Policy(PolicyError), /// The process already serves a different context geometry; it is fixed once per process. - ProcessGeometry { configured: usize, requested: usize }, + ProcessGeometry { + configured: usize, + requested: usize, + }, Driver(DriverError), } @@ -34,10 +37,9 @@ impl std::fmt::Display for ServingError { Self::Slots(n) => write!(f, "the native runtime serves one slot, not {n}"), Self::KvFormat(k) => write!(f, "KV format {k} is not wired in the native runtime"), Self::Policy(e) => write!(f, "{e}"), - Self::ProcessGeometry { configured, requested } => write!( - f, - "the process already serves a {configured}-cell context and cannot serve {requested}" - ), + Self::ProcessGeometry { configured, requested } => { + write!(f, "the process already serves a {configured}-cell context and cannot serve {requested}") + } Self::Driver(e) => write!(f, "serving context rejected by the driver: {e:?}"), } } diff --git a/crates/engine-qwen35-cuda/src/settings.rs b/crates/engine-qwen35-cuda/src/settings.rs index 2e40dfcb..4e67dceb 100644 --- a/crates/engine-qwen35-cuda/src/settings.rs +++ b/crates/engine-qwen35-cuda/src/settings.rs @@ -77,9 +77,7 @@ fn capture(source: &impl EnvSource) -> MapEnv { source .entries_with_prefix(&NAMESPACES) .into_iter() - .fold(MapEnv::new(), |env, (name, value)| { - env.with_os(&name, value) - }) + .fold(MapEnv::new(), |env, (name, value)| env.with_os(&name, value)) } /// The settings of this process: captured from the real environment the first time anything asks, which the engine's diff --git a/crates/engine-qwen35-cuda/src/settings/capture_tests.rs b/crates/engine-qwen35-cuda/src/settings/capture_tests.rs index 0e546e59..bee15337 100644 --- a/crates/engine-qwen35-cuda/src/settings/capture_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/capture_tests.rs @@ -2,12 +2,7 @@ use super::*; #[test] fn only_the_operator_namespace_is_captured() { - let source = MapEnv::of(&[ - ("LELEKA_A", "1"), - ("STRATA_B", "2"), - ("HOME", "/root"), - ("OTHER_LELEKA_C", "3"), - ]); + let source = MapEnv::of(&[("LELEKA_A", "1"), ("STRATA_B", "2"), ("HOME", "/root"), ("OTHER_LELEKA_C", "3")]); let settings = Settings::from_source(&source); assert_eq!(settings.env().get("LELEKA_A").as_deref(), Some("1")); assert_eq!(settings.env().get("STRATA_B").as_deref(), Some("2")); @@ -30,15 +25,9 @@ fn an_empty_environment_gives_the_defaults_of_every_topic() { #[test] fn the_conversation_cache_policy_reads_its_two_knobs_from_the_capture() { use crate::conversation::resident::ResidentPolicy; - let read = |pairs: &[(&str, &str)]| { - ResidentPolicy::from_source(Settings::from_source(&MapEnv::of(pairs)).env()) - }; + let read = |pairs: &[(&str, &str)]| ResidentPolicy::from_source(Settings::from_source(&MapEnv::of(pairs)).env()); assert_eq!(read(&[]), Ok(ResidentPolicy::disabled())); - let both = read(&[ - ("LELEKA_CONVERSATION_CACHE_MIB", "64"), - ("LELEKA_CONVERSATION_CACHE_SLOTS", "2"), - ]) - .unwrap(); + let both = read(&[("LELEKA_CONVERSATION_CACHE_MIB", "64"), ("LELEKA_CONVERSATION_CACHE_SLOTS", "2")]).unwrap(); assert_eq!((both.budget_bytes, both.slots), (64 << 20, 2)); for (key, value) in [ ("LELEKA_CONVERSATION_CACHE_MIB", "x"), @@ -58,12 +47,8 @@ fn a_conversation_cache_value_that_is_not_unicode_is_refused() { use crate::conversation::resident::ResidentPolicy; use std::os::unix::ffi::OsStringExt; let raw = std::ffi::OsString::from_vec(vec![0x36, 0xff]); - let settings = - Settings::from_source(&MapEnv::new().with_os("LELEKA_CONVERSATION_CACHE_MIB", raw)); - assert_eq!( - ResidentPolicy::from_source(settings.env()), - Err("invalid conversation cache setting") - ); + let settings = Settings::from_source(&MapEnv::new().with_os("LELEKA_CONVERSATION_CACHE_MIB", raw)); + assert_eq!(ResidentPolicy::from_source(settings.env()), Err("invalid conversation cache setting")); } #[test] @@ -74,20 +59,10 @@ fn the_memory_governor_reads_its_keys_from_the_capture() { let settings = Settings::from_source(&MapEnv::of(pairs)); GovernorConfig::from_env(121 << 30, false, &|key| settings.env().get(key)) }; - let cfg = read(&[ - ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), - ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), - ]) - .unwrap(); - assert_eq!( - (cfg.policy.soft_floor, cfg.policy.hard_floor), - (19000 * MIB, 16000 * MIB) - ); + let cfg = read(&[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000")]).unwrap(); + assert_eq!((cfg.policy.soft_floor, cfg.policy.hard_floor), (19000 * MIB, 16000 * MIB)); assert!(read(&[]).is_ok()); - for (key, value) in [ - ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots"), - ("LELEKA_MEMORY_CACHE_SHARE_PERCENT", "0"), - ] { + for (key, value) in [("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots"), ("LELEKA_MEMORY_CACHE_SHARE_PERCENT", "0")] { assert!(read(&[(key, value)]).is_err(), "{key}={value:?}"); } } diff --git a/crates/engine-qwen35-cuda/src/settings/decode_tests.rs b/crates/engine-qwen35-cuda/src/settings/decode_tests.rs index 22514037..15dce7f7 100644 --- a/crates/engine-qwen35-cuda/src/settings/decode_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/decode_tests.rs @@ -15,14 +15,7 @@ fn rows(key: &str, field: fn(&DecodeSettings) -> bool, unset: bool, values: &[(& #[test] fn coupled_is_set_non_empty_and_not_zero() { - let spellings = [ - ("1", true), - ("yes", true), - ("00", true), - (" ", true), - ("0", false), - ("", false), - ]; + let spellings = [("1", true), ("yes", true), ("00", true), (" ", true), ("0", false), ("", false)]; rows("STRATA_SPEC_COUPLED", |d| d.coupled, false, &spellings); } @@ -35,70 +28,25 @@ fn the_trace_switches_are_set_non_empty_and_not_zero() { #[test] fn overlap_and_adapt_defer_are_on_unless_off_or_zero() { - let spellings = [ - ("off", false), - ("0", false), - ("on", true), - ("1", true), - ("OFF", true), - ("", true), - ("no", true), - ]; + let spellings = [("off", false), ("0", false), ("on", true), ("1", true), ("OFF", true), ("", true), ("no", true)]; rows("LELEKA_SERVE_OVERLAP", |d| d.overlap, true, &spellings); - rows( - "LELEKA_SERVE_ADAPT_DEFER", - |d| d.adapt_defer, - true, - &spellings, - ); + rows("LELEKA_SERVE_ADAPT_DEFER", |d| d.adapt_defer, true, &spellings); } #[test] fn the_draft_waits_for_the_commit_only_on_or_one() { - let spellings = [ - ("on", true), - ("1", true), - ("", false), - ("off", false), - ("0", false), - ("yes please", false), - ("ON", false), - ]; - rows( - "LELEKA_SERVE_DRAFT_AFTER_COMMIT", - |d| d.draft_after_commit, - false, - &spellings, - ); + let spellings = + [("on", true), ("1", true), ("", false), ("off", false), ("0", false), ("yes please", false), ("ON", false)]; + rows("LELEKA_SERVE_DRAFT_AFTER_COMMIT", |d| d.draft_after_commit, false, &spellings); } #[test] fn serial_publish_and_full_suffix_reset_are_exact_words() { - let serial = [ - ("serial", true), - ("Serial", false), - ("batched", false), - ("", false), - ]; + let serial = [("serial", true), ("Serial", false), ("batched", false), ("", false)]; rows("LELEKA_SERVE_PUBLISH", |d| d.publish_serial, false, &serial); - let reset = [ - ("full", false), - ("FULL", true), - ("sparse", true), - ("", true), - ]; - rows( - "LELEKA_SUFFIX_RESET", - |d| d.suffix_reset_sparse, - true, - &reset, - ); - rows( - "LELEKA_TRACE_DRAFT", - |d| d.trace_draft, - false, - &[("1", true), ("on", false), ("0", false), ("", false)], - ); + let reset = [("full", false), ("FULL", true), ("sparse", true), ("", true)]; + rows("LELEKA_SUFFIX_RESET", |d| d.suffix_reset_sparse, true, &reset); + rows("LELEKA_TRACE_DRAFT", |d| d.trace_draft, false, &[("1", true), ("on", false), ("0", false), ("", false)]); } #[test] @@ -114,23 +62,13 @@ fn logprob_trace_depth_is_an_untrimmed_usize_above_zero() { ("x", None), ("", None), ] { - assert_eq!( - decode(&[("LELEKA_TRACE_LOGPROBS", value)]).trace_logprobs, - want, - "{value:?}" - ); + assert_eq!(decode(&[("LELEKA_TRACE_LOGPROBS", value)]).trace_logprobs, want, "{value:?}"); } } #[test] fn the_residual_trace_directory_is_kept_as_set() { assert_eq!(decode(&[]).trace_residual, None); - assert_eq!( - decode(&[("LELEKA_TRACE_RESIDUAL", "")]).trace_residual, - Some(std::ffi::OsString::new()) - ); - assert_eq!( - decode(&[("LELEKA_TRACE_RESIDUAL", "/t")]).trace_residual, - Some(std::ffi::OsString::from("/t")) - ); + assert_eq!(decode(&[("LELEKA_TRACE_RESIDUAL", "")]).trace_residual, Some(std::ffi::OsString::new())); + assert_eq!(decode(&[("LELEKA_TRACE_RESIDUAL", "/t")]).trace_residual, Some(std::ffi::OsString::from("/t"))); } diff --git a/crates/engine-qwen35-cuda/src/settings/diagnostics_tests.rs b/crates/engine-qwen35-cuda/src/settings/diagnostics_tests.rs index 5156fe98..17c7406b 100644 --- a/crates/engine-qwen35-cuda/src/settings/diagnostics_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/diagnostics_tests.rs @@ -27,26 +27,15 @@ fn the_trace_switches_are_on_when_set_to_anything() { #[test] fn a_raw_os_value_counts_as_set() { let raw = std::ffi::OsString::from("x"); - let settings = - DiagnosticsSettings::from_source(&MapEnv::new().with_os("LELEKA_TRACE_PLE", raw)); + let settings = DiagnosticsSettings::from_source(&MapEnv::new().with_os("LELEKA_TRACE_PLE", raw)); assert!(settings.trace_ple); } #[test] fn the_serve_profile_is_set_non_empty_and_not_zero() { assert!(!diag(&[]).serve_profile); - for (value, want) in [ - ("1", true), - ("on", true), - ("00", true), - ("0", false), - ("", false), - ] { - assert_eq!( - diag(&[("LELEKA_SERVE_PROFILE", value)]).serve_profile, - want, - "{value:?}" - ); + for (value, want) in [("1", true), ("on", true), ("00", true), ("0", false), ("", false)] { + assert_eq!(diag(&[("LELEKA_SERVE_PROFILE", value)]).serve_profile, want, "{value:?}"); } } diff --git a/crates/engine-qwen35-cuda/src/settings/kv.rs b/crates/engine-qwen35-cuda/src/settings/kv.rs index aa9c1780..6473ef1f 100644 --- a/crates/engine-qwen35-cuda/src/settings/kv.rs +++ b/crates/engine-qwen35-cuda/src/settings/kv.rs @@ -1,8 +1,6 @@ //! Settings of the prompt path and the caches around it: prefill streaming, the weight and K/V footprint switches, the //! PLE read-ahead and the cross-session prefix cache. -use super::parse::{ - equals, on_unless_zero, one_of, text_is_one_of, trimmed_number, trimmed_text_is_one_of, -}; +use super::parse::{equals, on_unless_zero, one_of, text_is_one_of, trimmed_number, trimmed_text_is_one_of}; use super::source::EnvSource; /// The spellings that turn `LELEKA_PROMPT_EMBED_ALIAS` on. @@ -45,17 +43,13 @@ impl KvSettings { pub(super) fn from_source(env: &impl EnvSource) -> Self { Self { prefill_stream: on_unless_zero(env, "LELEKA_PREFILL_STREAM"), - prefill_stream_min: trimmed_number::(env, "STRATA_PREFILL_STREAM_MIN") - .unwrap_or(4096), + prefill_stream_min: trimmed_number::(env, "STRATA_PREFILL_STREAM_MIN").unwrap_or(4096), prefill_moe_span_cache: on_unless_zero(env, "LELEKA_PREFILL_MOE_SPAN_CACHE"), prefill_gdn_pool: on_unless_zero(env, "LELEKA_PREFILL_GDN_POOL"), prefill_gdn_mirror: on_unless_zero(env, "LELEKA_PREFILL_GDN_MIRROR"), prefill_staged_input: on_unless_zero(env, "LELEKA_PREFILL_STAGED_INPUT"), dense_slab: !one_of(env, "LELEKA_DENSE_SLAB", &["0", "off"]), - prompt_embed_alias: text_is_one_of( - env.get("LELEKA_PROMPT_EMBED_ALIAS").as_deref(), - &PROMPT_EMBED_ALIAS_ON, - ), + prompt_embed_alias: text_is_one_of(env.get("LELEKA_PROMPT_EMBED_ALIAS").as_deref(), &PROMPT_EMBED_ALIAS_ON), footprint_legacy: trimmed_text_is_one_of( env.get("LELEKA_FOOTPRINT_LEGACY").as_deref(), &FOOTPRINT_LEGACY_ON, diff --git a/crates/engine-qwen35-cuda/src/settings/kv_tests.rs b/crates/engine-qwen35-cuda/src/settings/kv_tests.rs index ee40d676..65eac585 100644 --- a/crates/engine-qwen35-cuda/src/settings/kv_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/kv_tests.rs @@ -26,33 +26,16 @@ fn the_prefill_switches_are_on_unless_exactly_zero() { #[test] fn the_stream_threshold_is_a_trimmed_usize_with_a_default() { assert_eq!(kv(&[]).prefill_stream_min, 4096); - for (value, want) in [ - ("2048", 2048), - (" 8192 ", 8192), - ("0", 0), - ("-1", 4096), - ("x", 4096), - ("", 4096), - ("1.5", 4096), - ] { - assert_eq!( - kv(&[("STRATA_PREFILL_STREAM_MIN", value)]).prefill_stream_min, - want, - "{value:?}" - ); + for (value, want) in + [("2048", 2048), (" 8192 ", 8192), ("0", 0), ("-1", 4096), ("x", 4096), ("", 4096), ("1.5", 4096)] + { + assert_eq!(kv(&[("STRATA_PREFILL_STREAM_MIN", value)]).prefill_stream_min, want, "{value:?}"); } } #[test] fn dense_slab_is_packed_unless_zero_or_off() { - let spellings = [ - ("0", false), - ("off", false), - ("1", true), - ("on", true), - ("OFF", true), - ("", true), - ]; + let spellings = [("0", false), ("off", false), ("1", true), ("on", true), ("OFF", true), ("", true)]; rows("LELEKA_DENSE_SLAB", |k| k.dense_slab, true, &spellings); } @@ -70,12 +53,7 @@ fn the_prompt_embedding_alias_spellings_are_exact() { ("2", false), (" 1", false), ]; - rows( - "LELEKA_PROMPT_EMBED_ALIAS", - |k| k.prompt_embed_alias, - false, - &spellings, - ); + rows("LELEKA_PROMPT_EMBED_ALIAS", |k| k.prompt_embed_alias, false, &spellings); } #[test] @@ -91,12 +69,7 @@ fn the_legacy_footprint_spellings_are_trimmed() { ("off", false), ("ON", false), ]; - rows( - "LELEKA_FOOTPRINT_LEGACY", - |k| k.footprint_legacy, - false, - &spellings, - ); + rows("LELEKA_FOOTPRINT_LEGACY", |k| k.footprint_legacy, false, &spellings); } #[test] @@ -117,29 +90,14 @@ fn the_ple_read_ahead_follows_a_word_or_the_platform() { #[test] fn the_prefix_retention_is_a_trimmed_u64() { assert_eq!(kv(&[]).prefix_retention_s, None); - for (value, want) in [ - ("3600", Some(3600)), - (" 60 ", Some(60)), - ("0", Some(0)), - ("-1", None), - ("1.5", None), - ("x", None), - ("", None), - ] { - assert_eq!( - kv(&[("LELEKA_PREFIX_RETENTION_S", value)]).prefix_retention_s, - want, - "{value:?}" - ); + for (value, want) in + [("3600", Some(3600)), (" 60 ", Some(60)), ("0", Some(0)), ("-1", None), ("1.5", None), ("x", None), ("", None)] + { + assert_eq!(kv(&[("LELEKA_PREFIX_RETENTION_S", value)]).prefix_retention_s, want, "{value:?}"); } } #[test] fn the_checkpoint_reread_switch_is_set_ness() { - rows( - "STRATA_CKPT_REREAD", - |k| k.ckpt_reread, - false, - &[("1", true), ("0", true), ("", true)], - ); + rows("STRATA_CKPT_REREAD", |k| k.ckpt_reread, false, &[("1", true), ("0", true), ("", true)]); } diff --git a/crates/engine-qwen35-cuda/src/settings/memory.rs b/crates/engine-qwen35-cuda/src/settings/memory.rs index da08edb8..dcfa7c1d 100644 --- a/crates/engine-qwen35-cuda/src/settings/memory.rs +++ b/crates/engine-qwen35-cuda/src/settings/memory.rs @@ -60,18 +60,10 @@ pub(crate) struct CpuPoolSettings { impl MemorySettings { pub(super) fn from_source(env: &impl EnvSource) -> Self { - let tuning = |key: &str, default: f32| { - number::(env, key) - .filter(|v| v.is_finite()) - .unwrap_or(default) - }; + let tuning = |key: &str, default: f32| number::(env, key).filter(|v| v.is_finite()).unwrap_or(default); Self { route_tail_skip: trimmed_number::(env, "LELEKA_ROUTE_TAIL_SKIP"), - route_tail_skip_max_cached: trimmed_number::( - env, - "LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED", - ) - .unwrap_or(90.0), + route_tail_skip_max_cached: trimmed_number::(env, "LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED").unwrap_or(90.0), span_cache: on_unless_off(env, "LELEKA_SPAN_CACHE"), refill_defer: one_of(env, "LELEKA_REFILL_DEFER", &["on", "1"]), swap_wait: on_unless_off(env, "LELEKA_SERVE_SWAP_WAIT"), diff --git a/crates/engine-qwen35-cuda/src/settings/memory_tests.rs b/crates/engine-qwen35-cuda/src/settings/memory_tests.rs index ff65eea1..5796a001 100644 --- a/crates/engine-qwen35-cuda/src/settings/memory_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/memory_tests.rs @@ -14,57 +14,23 @@ fn rows(key: &str, field: fn(&MemorySettings) -> bool, unset: bool, values: &[(& #[test] fn span_cache_and_swap_wait_are_on_unless_off_or_zero() { - let spellings = [ - ("off", false), - ("0", false), - ("on", true), - ("1", true), - ("OFF", true), - ("", true), - ]; + let spellings = [("off", false), ("0", false), ("on", true), ("1", true), ("OFF", true), ("", true)]; rows("LELEKA_SPAN_CACHE", |m| m.span_cache, true, &spellings); rows("LELEKA_SERVE_SWAP_WAIT", |m| m.swap_wait, true, &spellings); - rows( - "LELEKA_CPU_ADMIT_EAGER", - |m| m.pool.admit_eager, - true, - &spellings, - ); + rows("LELEKA_CPU_ADMIT_EAGER", |m| m.pool.admit_eager, true, &spellings); } #[test] fn refill_defer_and_locked_only_are_on_or_one() { - let spellings = [ - ("on", true), - ("1", true), - ("off", false), - ("0", false), - ("yes", false), - ("", false), - ]; + let spellings = [("on", true), ("1", true), ("off", false), ("0", false), ("yes", false), ("", false)]; rows("LELEKA_REFILL_DEFER", |m| m.refill_defer, false, &spellings); - rows( - "LELEKA_PCIE_LOCKED_ONLY", - |m| m.pcie_locked_only, - false, - &spellings, - ); + rows("LELEKA_PCIE_LOCKED_ONLY", |m| m.pcie_locked_only, false, &spellings); } #[test] fn the_pcie_auto_modes_are_exact_words() { - rows( - "LELEKA_PCIE_AUTO", - |m| m.pcie_auto_lag, - false, - &[("lag", true), ("on", false), ("LAG", false), ("", false)], - ); - rows( - "LELEKA_PCIE_AUTO", - |m| m.pcie_auto_on, - false, - &[("on", true), ("lag", false), ("1", false), ("", false)], - ); + rows("LELEKA_PCIE_AUTO", |m| m.pcie_auto_lag, false, &[("lag", true), ("on", false), ("LAG", false), ("", false)]); + rows("LELEKA_PCIE_AUTO", |m| m.pcie_auto_on, false, &[("on", true), ("lag", false), ("1", false), ("", false)]); } #[test] @@ -75,78 +41,34 @@ fn the_pool_switches_are_exact_words() { true, &[("job", false), ("group", true), ("JOB", true), ("", true)], ); - rows( - "LELEKA_CPU_POOL_LOOKAHEAD", - |m| m.pool.lookahead, - false, - &[("on", true), ("1", false), ("off", false)], - ); - rows( - "LELEKA_OPEN_CACHE", - |m| m.pool.open_cache, - false, - &[("on", true), ("1", false), ("off", false)], - ); + rows("LELEKA_CPU_POOL_LOOKAHEAD", |m| m.pool.lookahead, false, &[("on", true), ("1", false), ("off", false)]); + rows("LELEKA_OPEN_CACHE", |m| m.pool.open_cache, false, &[("on", true), ("1", false), ("off", false)]); } #[test] fn per_layer_sizing_is_on_unless_exactly_zero() { let key = "LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED"; - rows( - key, - |m| m.per_layer_sized, - true, - &[ - ("0", false), - ("off", true), - ("1", true), - ("", true), - ("00", true), - ], - ); + rows(key, |m| m.per_layer_sized, true, &[("0", false), ("off", true), ("1", true), ("", true), ("00", true)]); } #[test] fn the_adaptive_tuning_numbers_are_finite_f32_or_the_default() { let (count, margin) = ("LELEKA_ADAPT_MIN_COUNT", "LELEKA_ADAPT_MARGIN"); - assert_eq!( - (memory(&[]).adapt_min_count, memory(&[]).adapt_margin), - (2.0, 1.5) - ); - for (value, want) in [ - ("3", 3.0), - ("0.5", 0.5), - ("-1", -1.0), - ("inf", 2.0), - ("NaN", 2.0), - ("x", 2.0), - (" 3", 2.0), - ("", 2.0), - ] { - assert_eq!( - memory(&[(count, value)]).adapt_min_count, - want, - "{count}={value:?}" - ); + assert_eq!((memory(&[]).adapt_min_count, memory(&[]).adapt_margin), (2.0, 1.5)); + for (value, want) in + [("3", 3.0), ("0.5", 0.5), ("-1", -1.0), ("inf", 2.0), ("NaN", 2.0), ("x", 2.0), (" 3", 2.0), ("", 2.0)] + { + assert_eq!(memory(&[(count, value)]).adapt_min_count, want, "{count}={value:?}"); } for (value, want) in [("2", 2.0), ("inf", 1.5), ("x", 1.5), ("3 ", 1.5)] { - assert_eq!( - memory(&[(margin, value)]).adapt_margin, - want, - "{margin}={value:?}" - ); + assert_eq!(memory(&[(margin, value)]).adapt_margin, want, "{margin}={value:?}"); } } #[test] fn the_adaptive_decay_is_kept_as_set_for_its_range_check() { assert_eq!(memory(&[]).adapt_decay, None); - assert_eq!( - memory(&[("LELEKA_ADAPT_DECAY", " 0.5 ")]) - .adapt_decay - .as_deref(), - Some(" 0.5 ") - ); + assert_eq!(memory(&[("LELEKA_ADAPT_DECAY", " 0.5 ")]).adapt_decay.as_deref(), Some(" 0.5 ")); } #[test] @@ -170,14 +92,7 @@ fn the_tail_skip_numbers_are_trimmed() { fn the_cache_fail_count_is_an_untrimmed_i32() { let key = "STRATA_TEST_CACHE_FAIL"; assert_eq!(memory(&[]).test_cache_fail, 0); - for (value, want) in [ - ("2", 2), - ("-1", -1), - ("x", 0), - (" 2", 0), - ("2.5", 0), - ("", 0), - ] { + for (value, want) in [("2", 2), ("-1", -1), ("x", 0), (" 2", 0), ("2.5", 0), ("", 0)] { assert_eq!(memory(&[(key, value)]).test_cache_fail, want, "{value:?}"); } } @@ -186,12 +101,7 @@ fn the_cache_fail_count_is_an_untrimmed_i32() { fn the_pool_words_and_paths_are_kept_as_set() { let none = memory(&[]); assert_eq!( - ( - none.pool.path, - none.pool.prefetch, - none.dump_routing, - none.pool.prefetch_off_file - ), + (none.pool.path, none.pool.prefetch, none.dump_routing, none.pool.prefetch_off_file), (None, None, None, None) ); let set = memory(&[ @@ -203,8 +113,5 @@ fn the_pool_words_and_paths_are_kept_as_set() { assert_eq!(set.pool.path.as_deref(), Some("legacy")); assert_eq!(set.pool.prefetch.as_deref(), Some("auto")); assert_eq!(set.dump_routing, Some(std::ffi::OsString::from("/tmp/r"))); - assert_eq!( - set.pool.prefetch_off_file, - Some(std::ffi::OsString::from("/tmp/off")) - ); + assert_eq!(set.pool.prefetch_off_file, Some(std::ffi::OsString::from("/tmp/off"))); } diff --git a/crates/engine-qwen35-cuda/src/settings/serve.rs b/crates/engine-qwen35-cuda/src/settings/serve.rs index ecae9e1f..13be3d26 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve.rs @@ -40,8 +40,7 @@ impl ServeSettings { capture_dir: env.get_os("LELEKA_CAPTURE_DIR"), mapped_working_set_gib: positive_gib(env, "LELEKA_MAPPED_WORKING_SET_GIB"), resident_budget_gib: positive_gib(env, "LELEKA_ORIGINAL_SERVE_RESIDENT_BUDGET_GIB"), - cpu_workers: number::(env, "LELEKA_ORIGINAL_SERVE_CPU_WORKERS") - .filter(|n| (1..=64).contains(n)), + cpu_workers: number::(env, "LELEKA_ORIGINAL_SERVE_CPU_WORKERS").filter(|n| (1..=64).contains(n)), cpu_pool_plan: equals(env, "LELEKA_CPU_POOL_PLAN", "on"), prefill_loan_tiers: one_of(env, "LELEKA_PREFILL_LOAN_TIERS", &["1", "on"]), } diff --git a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs index 49bf2ba1..23b2bc12 100644 --- a/crates/engine-qwen35-cuda/src/settings/serve_tests.rs +++ b/crates/engine-qwen35-cuda/src/settings/serve_tests.rs @@ -10,15 +10,9 @@ fn serve(pairs: &[(&str, &str)]) -> ServeSettings { fn gguf_ple_is_exactly_one() { let key = "LELEKA_ORIGINAL_SERVE_GGUF_PLE"; assert!(!serve(&[]).gguf_ple); - for (value, want) in [ - ("1", true), - ("0", false), - ("on", false), - ("yes", false), - ("true", false), - (" 1", false), - ("", false), - ] { + for (value, want) in + [("1", true), ("0", false), ("on", false), ("yes", false), ("true", false), (" 1", false), ("", false)] + { assert_eq!(serve(&[(key, value)]).gguf_ple, want, "{value:?}"); } } @@ -27,13 +21,7 @@ fn gguf_ple_is_exactly_one() { fn public_evaluation_is_exactly_yes() { let key = "LELEKA_PUBLIC_EVALUATION"; assert!(!serve(&[]).public_evaluation); - for (value, want) in [ - ("yes", true), - ("YES", false), - ("1", false), - ("true", false), - ("", false), - ] { + for (value, want) in [("yes", true), ("YES", false), ("1", false), ("true", false), ("", false)] { assert_eq!(serve(&[(key, value)]).public_evaluation, want, "{value:?}"); } } @@ -41,15 +29,8 @@ fn public_evaluation_is_exactly_yes() { #[test] fn profile_names_are_kept_as_set() { let none = serve(&[]); - assert_eq!( - (none.profile, none.profile_sha256, none.capture_dir), - (None, None, None) - ); - let set = serve(&[ - ("LELEKA_PROFILE", " p "), - ("LELEKA_PROFILE_SHA256", ""), - ("LELEKA_CAPTURE_DIR", "/tmp/c"), - ]); + assert_eq!((none.profile, none.profile_sha256, none.capture_dir), (None, None, None)); + let set = serve(&[("LELEKA_PROFILE", " p "), ("LELEKA_PROFILE_SHA256", ""), ("LELEKA_CAPTURE_DIR", "/tmp/c")]); assert_eq!(set.profile.as_deref(), Some(" p ")); assert_eq!(set.profile_sha256.as_deref(), Some("")); assert_eq!(set.capture_dir, Some(std::ffi::OsString::from("/tmp/c"))); diff --git a/crates/engine-qwen35-cuda/src/settings/source.rs b/crates/engine-qwen35-cuda/src/settings/source.rs index d6a7ac5b..019c4e1c 100644 --- a/crates/engine-qwen35-cuda/src/settings/source.rs +++ b/crates/engine-qwen35-cuda/src/settings/source.rs @@ -66,9 +66,7 @@ impl MapEnv { /// The `key=value` pairs of a table. #[cfg(test)] pub(crate) fn of(pairs: &[(&str, &str)]) -> Self { - pairs - .iter() - .fold(Self::new(), |env, (key, value)| env.with(key, value)) + pairs.iter().fold(Self::new(), |env, (key, value)| env.with(key, value)) } } @@ -111,11 +109,8 @@ mod tests { #[test] fn prefix_listing_keeps_only_the_operator_namespace() { let env = MapEnv::of(&[("LELEKA_A", "1"), ("STRATA_B", "2"), ("PATH", "/bin")]); - let names: Vec = env - .entries_with_prefix(&["LELEKA_", "STRATA_"]) - .into_iter() - .map(|(name, _)| name) - .collect(); + let names: Vec = + env.entries_with_prefix(&["LELEKA_", "STRATA_"]).into_iter().map(|(name, _)| name).collect(); assert_eq!(names, ["LELEKA_A", "STRATA_B"]); } } diff --git a/crates/engine-qwen35-cuda/tests/bringup_prints_gated.rs b/crates/engine-qwen35-cuda/tests/bringup_prints_gated.rs index 88cb323d..ad84fba6 100644 --- a/crates/engine-qwen35-cuda/tests/bringup_prints_gated.rs +++ b/crates/engine-qwen35-cuda/tests/bringup_prints_gated.rs @@ -27,7 +27,7 @@ const GUARDS: &[&str] = &[ "window_clock", "gpu_profile.is_empty()", ]; -const LOOKBACK: usize = 20; +const LOOKBACK: usize = 30; fn rust_files(dir: &Path, out: &mut Vec) { let Ok(entries) = fs::read_dir(dir) else { return }; @@ -46,26 +46,40 @@ fn test_only(files: &[PathBuf]) -> Vec { let mut gated = Vec::new(); for file in files { let text = fs::read_to_string(file).unwrap_or_default(); - if text.lines().take(40).any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test")) { + if text + .lines() + .take(40) + .any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test")) + { gated.push(file.clone()); } let lines: Vec<&str> = text.lines().collect(); for (index, line) in lines.iter().enumerate() { let trimmed = line.trim_start(); - let declared = trimmed.strip_prefix("pub(crate) mod ").or_else(|| trimmed.strip_prefix("pub(super) mod ")).or_else(|| trimmed.strip_prefix("pub mod ")).or_else(|| trimmed.strip_prefix("mod ")); + let declared = trimmed + .strip_prefix("pub(crate) mod ") + .or_else(|| trimmed.strip_prefix("pub(super) mod ")) + .or_else(|| trimmed.strip_prefix("pub mod ")) + .or_else(|| trimmed.strip_prefix("mod ")); let Some(name) = declared.and_then(|rest| rest.strip_suffix(';')) else { continue }; // the attribute block of the declaration: the lines above it up to the previous item (rustfmt splits a long `cfg(all(...))` over several lines) let mut start = index; while start > 0 && index - start < 12 { let previous = lines[start - 1].trim(); - if previous.is_empty() || previous.ends_with(';') || previous.ends_with('{') || previous.ends_with('}') || previous.starts_with("//") { + if previous.is_empty() + || previous.ends_with(';') + || previous.ends_with('{') + || previous.ends_with('}') + || previous.starts_with("//") + { break; } start -= 1; } let above = lines[start..index].join(" "); let squeezed: String = above.split_whitespace().collect(); - if squeezed.contains("cfg(test)") || squeezed.contains("cfg(all(test") || squeezed.contains("cfg(any(test") { + if squeezed.contains("cfg(test)") || squeezed.contains("cfg(all(test") || squeezed.contains("cfg(any(test") + { let dir = file.parent().unwrap(); gated.push(dir.join(format!("{name}.rs"))); gated.push(dir.join(name).join("mod.rs")); @@ -107,10 +121,16 @@ fn findings(root: &Path) -> Vec { let end = lines .iter() .enumerate() - .position(|(i, l)| l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod "))) + .position(|(i, l)| { + l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod ")) + }) .unwrap_or(lines.len()); for (index, line) in lines.iter().enumerate().take(end) { - let Some(column) = ["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min() else { continue }; + let Some(column) = + ["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min() + else { + continue; + }; let Some(literal) = first_literal(&lines, index, column) else { continue }; if !(literal.starts_with("DBG") || literal.starts_with("PROBE")) { continue; @@ -118,7 +138,12 @@ fn findings(root: &Path) -> Vec { let from = index.saturating_sub(LOOKBACK); let context = lines[from..=index].join("\n"); if !GUARDS.iter().any(|guard| context.contains(guard)) { - bad.push(format!("{}:{}: {}", file.strip_prefix(root).unwrap_or(file).display(), index + 1, line.trim())); + bad.push(format!( + "{}:{}: {}", + file.strip_prefix(root).unwrap_or(file).display(), + index + 1, + line.trim() + )); } } } @@ -142,10 +167,7 @@ fn the_scan_sees_the_prints_it_is_meant_to_guard() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let mut files = Vec::new(); rust_files(&root.join("crates/engine-qwen35-cuda/src"), &mut files); - let total: usize = files - .iter() - .map(|f| fs::read_to_string(f).unwrap_or_default().matches("DBG").count()) - .sum(); + let total: usize = files.iter().map(|f| fs::read_to_string(f).unwrap_or_default().matches("DBG").count()).sum(); assert!(total > 20, "only {total} DBG mentions: is the source path wrong?"); let lines = [" eprintln!(\"DBG x {}\", 1);", " eprintln!(", " \"PROBE y\","]; assert_eq!(first_literal(&lines, 0, 14).as_deref(), Some("DBG x {}\", 1")); diff --git a/crates/engine-qwen35-cuda/tests/stra161_reference.rs b/crates/engine-qwen35-cuda/tests/stra161_reference.rs index 624eeac3..f0adf105 100644 --- a/crates/engine-qwen35-cuda/tests/stra161_reference.rs +++ b/crates/engine-qwen35-cuda/tests/stra161_reference.rs @@ -13,8 +13,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 11, prev: [-1, -1], rows: [ - 13555483, 24877159, 54278900, 63631058, 98394898, 117447587, 136774765, 157274238, - 173487882, 192109366, 213364329, 236577563, 258758149, 262164274, 283572184, 312653920, + 13555483, 24877159, 54278900, 63631058, 98394898, 117447587, 136774765, 157274238, 173487882, 192109366, + 213364329, 236577563, 258758149, 262164274, 283572184, 312653920, ], }, HashCase { @@ -22,8 +22,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 22, prev: [11, -1], rows: [ - 3278367, 29880471, 46922633, 62971672, 94904487, 113013549, 120925297, 159537733, - 161636484, 186269036, 207870452, 237789268, 242975733, 269388091, 285131318, 305889870, + 3278367, 29880471, 46922633, 62971672, 94904487, 113013549, 120925297, 159537733, 161636484, 186269036, + 207870452, 237789268, 242975733, 269388091, 285131318, 305889870, ], }, HashCase { @@ -31,8 +31,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 33, prev: [22, 11], rows: [ - 2485282, 23858032, 54544880, 69506925, 82331991, 106607168, 133019998, 141570514, - 173894108, 180423171, 211374553, 239810912, 253076960, 266343146, 290765399, 312876099, + 2485282, 23858032, 54544880, 69506925, 82331991, 106607168, 133019998, 141570514, 173894108, 180423171, + 211374553, 239810912, 253076960, 266343146, 290765399, 312876099, ], }, HashCase { @@ -40,8 +40,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 44, prev: [33, 22], rows: [ - 12721672, 27113445, 44309803, 60385209, 97021817, 115900810, 134219364, 151977589, - 161183764, 181257609, 201344488, 221596875, 241635416, 261674107, 281687144, 301751935, + 12721672, 27113445, 44309803, 60385209, 97021817, 115900810, 134219364, 151977589, 161183764, 181257609, + 201344488, 221596875, 241635416, 261674107, 281687144, 301751935, ], }, HashCase { @@ -49,8 +49,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 7, prev: [-1, -1], rows: [ - 2927653, 34980843, 54748278, 66612378, 97814964, 109013870, 126560393, 151352333, - 167888935, 182235580, 215170017, 237467519, 247510681, 278779700, 296141806, 304994522, + 2927653, 34980843, 54748278, 66612378, 97814964, 109013870, 126560393, 151352333, 167888935, 182235580, + 215170017, 237467519, 247510681, 278779700, 296141806, 304994522, ], }, HashCase { @@ -58,8 +58,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 8, prev: [7, 248044], rows: [ - 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, - 164805529, 181662903, 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, + 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, 164805529, 181662903, + 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, ], }, HashCase { @@ -67,8 +67,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 9, prev: [248044, 7], rows: [ - 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, - 179716672, 187881262, 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, + 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, 179716672, 187881262, + 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, ], }, HashCase { @@ -76,8 +76,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 100, prev: [-1, -1], rows: [ - 5727835, 21884476, 43702108, 66434789, 84094509, 104112171, 134886528, 157314943, - 162363667, 189466439, 200618315, 232121522, 258547276, 266199001, 289022207, 305180972, + 5727835, 21884476, 43702108, 66434789, 84094509, 104112171, 134886528, 157314943, 162363667, 189466439, + 200618315, 232121522, 258547276, 266199001, 289022207, 305180972, ], }, HashCase { @@ -85,8 +85,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 101, prev: [-1, -1], rows: [ - 14526383, 36975477, 51939184, 65076202, 94510971, 111786935, 138448715, 155393638, - 167579692, 181767276, 211184823, 226303266, 246271192, 267465224, 281469089, 313531602, + 14526383, 36975477, 51939184, 65076202, 94510971, 111786935, 138448715, 155393638, 167579692, 181767276, + 211184823, 226303266, 246271192, 267465224, 281469089, 313531602, ], }, HashCase { @@ -94,8 +94,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 100, prev: [0, 0], rows: [ - 223356, 29869136, 44693816, 65450370, 83243562, 109175069, 138072664, 149936704, - 175869089, 193667153, 214433731, 233779437, 242682975, 271587098, 294555343, 309396483, + 223356, 29869136, 44693816, 65450370, 83243562, 109175069, 138072664, 149936704, 175869089, 193667153, + 214433731, 233779437, 242682975, 271587098, 294555343, 309396483, ], }, HashCase { @@ -103,8 +103,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 101, prev: [100, 0], rows: [ - 9825591, 35767834, 58740777, 62904867, 86476006, 107666813, 129453358, 151836075, - 160726459, 190511348, 208596315, 234569026, 259467109, 264365567, 292665383, 314164387, + 9825591, 35767834, 58740777, 62904867, 86476006, 107666813, 129453358, 151836075, 160726459, 190511348, + 208596315, 234569026, 259467109, 264365567, 292665383, 314164387, ], }, HashCase { @@ -112,8 +112,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248044, prev: [-1, -1], rows: [ - 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, - 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, + 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, + 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, ], }, HashCase { @@ -121,8 +121,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 5, prev: [248044, -1], rows: [ - 15389869, 39778609, 55713969, 62213332, 88817728, 118483999, 133731511, 155458159, - 179763390, 197956758, 205378969, 220499474, 242466248, 265658744, 293662119, 315720898, + 15389869, 39778609, 55713969, 62213332, 88817728, 118483999, 133731511, 155458159, 179763390, 197956758, + 205378969, 220499474, 242466248, 265658744, 293662119, 315720898, ], }, HashCase { @@ -130,8 +130,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248044, prev: [5, 248044], rows: [ - 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, - 170054832, 192967038, 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, + 9663979, 26558231, 56120240, 74755659, 80459717, 109265651, 132697467, 151022725, 170054832, 192967038, + 200687722, 225763581, 259275737, 272983544, 297596484, 300986548, ], }, HashCase { @@ -139,8 +139,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248043, prev: [-1, -1], rows: [ - 5224855, 30284709, 43929396, 72280505, 94883662, 109322550, 131203836, 140794991, - 166459826, 181131035, 209237474, 226844350, 246236135, 265823742, 299063341, 305586418, + 5224855, 30284709, 43929396, 72280505, 94883662, 109322550, 131203836, 140794991, 166459826, 181131035, + 209237474, 226844350, 246236135, 265823742, 299063341, 305586418, ], }, HashCase { @@ -148,8 +148,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 12345, prev: [248043, -1], rows: [ - 11270970, 23825822, 53627731, 75297762, 86108900, 117131242, 124369521, 148669731, - 173053968, 186938961, 219076364, 237563026, 246838602, 277288915, 294366759, 301712965, + 11270970, 23825822, 53627731, 75297762, 86108900, 117131242, 124369521, 148669731, 173053968, 186938961, + 219076364, 237563026, 246838602, 277288915, 294366759, 301712965, ], }, HashCase { @@ -157,8 +157,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248043, prev: [12345, 248043], rows: [ - 9040325, 23423119, 51729309, 72606490, 88803423, 101106903, 139785146, 145105493, - 165075797, 186774126, 216848848, 228384799, 252197080, 276291559, 284385762, 305326936, + 9040325, 23423119, 51729309, 72606490, 88803423, 101106903, 139785146, 145105493, 165075797, 186774126, + 216848848, 228384799, 252197080, 276291559, 284385762, 305326936, ], }, HashCase { @@ -166,8 +166,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 7, prev: [248043, 12345], rows: [ - 4918924, 35785322, 51404601, 69479989, 96595301, 119006811, 132661231, 157603286, - 167367331, 194295259, 207336314, 231383366, 248222822, 265383752, 291175661, 300670030, + 4918924, 35785322, 51404601, 69479989, 96595301, 119006811, 132661231, 157603286, 167367331, 194295259, + 207336314, 231383366, 248222822, 265383752, 291175661, 300670030, ], }, HashCase { @@ -175,8 +175,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 200000, prev: [7, 248043], rows: [ - 19540326, 36155593, 54730668, 61035256, 83860210, 111525643, 123077188, 158579165, - 171421264, 181503411, 210257194, 220050508, 255765827, 271545193, 290152687, 303296503, + 19540326, 36155593, 54730668, 61035256, 83860210, 111525643, 123077188, 158579165, 171421264, 181503411, + 210257194, 220050508, 255765827, 271545193, 290152687, 303296503, ], }, HashCase { @@ -184,8 +184,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 0, prev: [0, 0], rows: [ - 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, 160000374, - 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, 300001275, + 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, 160000374, 180000455, + 200000548, 220000655, 240000802, 260000955, 280001114, 300001275, ], }, HashCase { @@ -193,8 +193,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 8, prev: [-1, 7], rows: [ - 17329723, 28464492, 44031928, 69826401, 80507399, 110734489, 136075079, 156529177, - 176740572, 199715560, 201670584, 220899605, 256162416, 271784618, 290405356, 304107632, + 17329723, 28464492, 44031928, 69826401, 80507399, 110734489, 136075079, 156529177, 176740572, 199715560, + 201670584, 220899605, 256162416, 271784618, 290405356, 304107632, ], }, HashCase { @@ -202,8 +202,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 8, prev: [7, -1], rows: [ - 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, - 164805529, 181662903, 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, + 7508793, 29969020, 54939975, 74089003, 91535754, 104816064, 125484693, 154439441, 164805529, 181662903, + 214193203, 238193346, 259492009, 262016223, 296463606, 310742083, ], }, HashCase { @@ -211,8 +211,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 9, prev: [248044, 7], rows: [ - 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, - 179716672, 187881262, 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, + 5471414, 32902469, 56618078, 65819961, 82278798, 107765152, 125994638, 156967341, 179716672, 187881262, + 219224344, 222418510, 250276020, 278493068, 281311927, 316005603, ], }, HashCase { @@ -220,8 +220,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 9, prev: [7, 248044], rows: [ - 18043673, 37626835, 51159316, 78294604, 94015356, 106720349, 136526052, 144330141, - 176817901, 186368539, 203707490, 230017629, 247662678, 266533413, 293096193, 307951937, + 18043673, 37626835, 51159316, 78294604, 94015356, 106720349, 136526052, 144330141, 176817901, 186368539, + 203707490, 230017629, 247662678, 266533413, 293096193, 307951937, ], }, HashCase { @@ -229,8 +229,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 9, prev: [7, 248046], rows: [ - 15021010, 35157757, 58966972, 76489564, 92542227, 105357841, 125329426, 153354782, - 165228787, 182703128, 210962064, 235778055, 243941989, 273003868, 282890671, 313820845, + 15021010, 35157757, 58966972, 76489564, 92542227, 105357841, 125329426, 153354782, 165228787, 182703128, + 210962064, 235778055, 243941989, 273003868, 282890671, 313820845, ], }, HashCase { @@ -238,8 +238,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248044, prev: [11, 22], rows: [ - 9649829, 25931806, 48482786, 64993297, 80874378, 113775613, 134009371, 142634030, - 170087912, 191029788, 214145939, 237657013, 259240851, 261882900, 282998934, 310342410, + 9649829, 25931806, 48482786, 64993297, 80874378, 113775613, 134009371, 142634030, 170087912, 191029788, + 214145939, 237657013, 259240851, 261882900, 282998934, 310342410, ], }, HashCase { @@ -247,8 +247,8 @@ pub const HASH_CASES: &[HashCase] = &[ token: 248319, prev: [248318, 248319], rows: [ - 3035822, 30922970, 45995374, 64361017, 92705579, 115727959, 130487234, 157254389, - 176190258, 184022063, 210818569, 238984490, 254962129, 271136118, 289904521, 304073142, + 3035822, 30922970, 45995374, 64361017, 92705579, 115727959, 130487234, 157254389, 176190258, 184022063, + 210818569, 238984490, 254962129, 271136118, 289904521, 304073142, ], }, ]; @@ -261,76 +261,61 @@ pub const DECODE_CASES: &[DecodeCase] = &[ DecodeCase { name: "split-nibbles", encoded: [ - 0, 60, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, - 188, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 56, - 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 1, 0, 240, - 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 128, 240, 225, - 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, + 0, 60, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 188, 240, 225, 210, + 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 56, 240, 225, 210, 195, 180, 165, 150, 135, + 120, 105, 90, 75, 60, 45, 30, 15, 1, 0, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, + 30, 15, 0, 128, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, ], expected_words: [ - 3271426048, 3268411392, 3265658880, 3263299584, 3259236352, 3255566336, 3249537024, - 3240099840, 1065353216, 1095761920, 1103626240, 1108869120, 1112801280, 1116340224, - 1118961664, 1122107392, 1122107392, 1118961664, 1116340224, 1112801280, 1108869120, - 1103626240, 1095761920, 1065353216, 3240099840, 3249537024, 3255566336, 3259236352, - 3263299584, 3265658880, 3268411392, 3271426048, 1123942400, 1120927744, 1118175232, - 1115815936, 1111752704, 1108082688, 1102053376, 1092616192, 3212836864, 3243245568, - 3251109888, 3256352768, 3260284928, 3263823872, 3266445312, 3269591040, 3269591040, - 3266445312, 3263823872, 3260284928, 3256352768, 3251109888, 3243245568, 3212836864, - 1092616192, 1102053376, 1108082688, 1111752704, 1115815936, 1118175232, 1120927744, - 1123942400, 3263037440, 3260022784, 3257270272, 3254910976, 3250847744, 3247177728, - 3241148416, 3231711232, 1056964608, 1087373312, 1095237632, 1100480512, 1104412672, - 1107951616, 1110573056, 1113718784, 1113718784, 1110573056, 1107951616, 1104412672, - 1100480512, 1095237632, 1087373312, 1056964608, 3231711232, 3241148416, 3247177728, - 3250847744, 3254910976, 3257270272, 3260022784, 3263037440, 3070099456, 3067084800, - 3064332288, 3061972992, 3057909760, 3054239744, 3048210432, 3038773248, 864026624, - 894435328, 902299648, 907542528, 911474688, 915013632, 917635072, 920780800, 920780800, - 917635072, 915013632, 911474688, 907542528, 902299648, 894435328, 864026624, - 3038773248, 3048210432, 3054239744, 3057909760, 3061972992, 3064332288, 3067084800, - 3070099456, 0, 0, 0, 0, 0, 0, 0, 0, 2147483648, 2147483648, 2147483648, 2147483648, - 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, - 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 0, 0, 0, 0, 0, 0, 0, 0, + 3271426048, 3268411392, 3265658880, 3263299584, 3259236352, 3255566336, 3249537024, 3240099840, 1065353216, + 1095761920, 1103626240, 1108869120, 1112801280, 1116340224, 1118961664, 1122107392, 1122107392, 1118961664, + 1116340224, 1112801280, 1108869120, 1103626240, 1095761920, 1065353216, 3240099840, 3249537024, 3255566336, + 3259236352, 3263299584, 3265658880, 3268411392, 3271426048, 1123942400, 1120927744, 1118175232, 1115815936, + 1111752704, 1108082688, 1102053376, 1092616192, 3212836864, 3243245568, 3251109888, 3256352768, 3260284928, + 3263823872, 3266445312, 3269591040, 3269591040, 3266445312, 3263823872, 3260284928, 3256352768, 3251109888, + 3243245568, 3212836864, 1092616192, 1102053376, 1108082688, 1111752704, 1115815936, 1118175232, 1120927744, + 1123942400, 3263037440, 3260022784, 3257270272, 3254910976, 3250847744, 3247177728, 3241148416, 3231711232, + 1056964608, 1087373312, 1095237632, 1100480512, 1104412672, 1107951616, 1110573056, 1113718784, 1113718784, + 1110573056, 1107951616, 1104412672, 1100480512, 1095237632, 1087373312, 1056964608, 3231711232, 3241148416, + 3247177728, 3250847744, 3254910976, 3257270272, 3260022784, 3263037440, 3070099456, 3067084800, 3064332288, + 3061972992, 3057909760, 3054239744, 3048210432, 3038773248, 864026624, 894435328, 902299648, 907542528, + 911474688, 915013632, 917635072, 920780800, 920780800, 917635072, 915013632, 911474688, 907542528, + 902299648, 894435328, 864026624, 3038773248, 3048210432, 3054239744, 3057909760, 3061972992, 3064332288, + 3067084800, 3070099456, 0, 0, 0, 0, 0, 0, 0, 0, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, + 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, + 2147483648, 2147483648, 0, 0, 0, 0, 0, 0, 0, 0, ], }, DecodeCase { name: "scale-domains", encoded: [ - 0, 0, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 4, - 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 255, 123, - 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 255, 251, - 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 85, 53, 240, - 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, + 0, 0, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 0, 4, 240, 225, 210, 195, + 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, 255, 123, 240, 225, 210, 195, 180, 165, 150, 135, + 120, 105, 90, 75, 60, 45, 30, 15, 255, 251, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, + 45, 30, 15, 85, 53, 240, 225, 210, 195, 180, 165, 150, 135, 120, 105, 90, 75, 60, 45, 30, 15, ], expected_words: [ - 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, - 2147483648, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2147483648, 2147483648, - 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 3153985536, - 3150970880, 3148218368, 3145859072, 3141795840, 3138125824, 3132096512, 3122659328, - 947912704, 978321408, 986185728, 991428608, 995360768, 998899712, 1001521152, - 1004666880, 1004666880, 1001521152, 998899712, 995360768, 991428608, 986185728, - 978321408, 947912704, 3122659328, 3132096512, 3138125824, 3141795840, 3145859072, - 3148218368, 3150970880, 3153985536, 3405635648, 3402622464, 3399871296, 3397513152, - 3393447808, 3389779584, 3383749120, 3374312448, 1199562752, 1229972992, 1237837568, - 1243081984, 1247012224, 1250553536, 1253173696, 1256317888, 1256317888, 1253173696, - 1250553536, 1247012224, 1243081984, 1237837568, 1229972992, 1199562752, 3374312448, - 3383749120, 3389779584, 3393447808, 3397513152, 3399871296, 3402622464, 3405635648, - 1258152000, 1255138816, 1252387648, 1250029504, 1245964160, 1242295936, 1236265472, - 1226828800, 3347046400, 3377456640, 3385321216, 3390565632, 3394495872, 3398037184, - 3400657344, 3403801536, 3403801536, 3400657344, 3398037184, 3394495872, 3390565632, - 3385321216, 3377456640, 3347046400, 1226828800, 1236265472, 1242295936, 1245964160, - 1250029504, 1252387648, 1255138816, 1258152000, 3257486016, 3255476736, 3252504448, - 3249359488, 3246563968, 3241844480, 3236600832, 3226814464, 1051369472, 1082827264, - 1090866432, 1095409152, 1099779200, 1102574720, 1106069120, 1108779328, 1108779328, - 1106069120, 1102574720, 1099779200, 1095409152, 1090866432, 1082827264, 1051369472, - 3226814464, 3236600832, 3241844480, 3246563968, 3249359488, 3252504448, 3255476736, - 3257486016, + 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, 2147483648, + 2147483648, 2147483648, 3153985536, 3150970880, 3148218368, 3145859072, 3141795840, 3138125824, 3132096512, + 3122659328, 947912704, 978321408, 986185728, 991428608, 995360768, 998899712, 1001521152, 1004666880, + 1004666880, 1001521152, 998899712, 995360768, 991428608, 986185728, 978321408, 947912704, 3122659328, + 3132096512, 3138125824, 3141795840, 3145859072, 3148218368, 3150970880, 3153985536, 3405635648, 3402622464, + 3399871296, 3397513152, 3393447808, 3389779584, 3383749120, 3374312448, 1199562752, 1229972992, 1237837568, + 1243081984, 1247012224, 1250553536, 1253173696, 1256317888, 1256317888, 1253173696, 1250553536, 1247012224, + 1243081984, 1237837568, 1229972992, 1199562752, 3374312448, 3383749120, 3389779584, 3393447808, 3397513152, + 3399871296, 3402622464, 3405635648, 1258152000, 1255138816, 1252387648, 1250029504, 1245964160, 1242295936, + 1236265472, 1226828800, 3347046400, 3377456640, 3385321216, 3390565632, 3394495872, 3398037184, 3400657344, + 3403801536, 3403801536, 3400657344, 3398037184, 3394495872, 3390565632, 3385321216, 3377456640, 3347046400, + 1226828800, 1236265472, 1242295936, 1245964160, 1250029504, 1252387648, 1255138816, 1258152000, 3257486016, + 3255476736, 3252504448, 3249359488, 3246563968, 3241844480, 3236600832, 3226814464, 1051369472, 1082827264, + 1090866432, 1095409152, 1099779200, 1102574720, 1106069120, 1108779328, 1108779328, 1106069120, 1102574720, + 1099779200, 1095409152, 1090866432, 1082827264, 1051369472, 3226814464, 3236600832, 3241844480, 3246563968, + 3249359488, 3252504448, 3255476736, 3257486016, ], }, ]; -pub const RAW_WRAP_CONTEXT: [u64; 3] = [ - 18446744073709551615, - 18446744073709551614, - 18446744073709551613, -]; +pub const RAW_WRAP_CONTEXT: [u64; 3] = [18446744073709551615, 18446744073709551614, 18446744073709551613]; pub const RAW_WRAP_MIXED: [u64; 2] = [53991755950561, 18446703520432350442]; // Raw wrap fixture is primitive-only: invalid token IDs must still refuse. // Gate probes: CPU host C libm only; not installed CUDA proof. @@ -342,12 +327,6 @@ pub const GATE_CASES: &[(u32, u32)] = &[ (814313567, 1056968802), (1065353216, 1060841128), ]; -pub const BF16_ROUND_CASES: &[(u32, u16)] = &[ - (0, 0), - (2147483648, 32768), - (1065353216, 16256), - (1065385984, 16256), - (1065451520, 16258), - (3212869632, 49024), -]; +pub const BF16_ROUND_CASES: &[(u32, u16)] = + &[(0, 0), (2147483648, 32768), (1065353216, 16256), (1065385984, 16256), (1065451520, 16258), (3212869632, 49024)]; pub const RESIDUAL_RIVAL: [u32; 5] = [1266679808, 3414163456, 1060841128, 1060841128, 1065353216]; diff --git a/crates/engine-qwen35-cuda/tests/stra166_reference.rs b/crates/engine-qwen35-cuda/tests/stra166_reference.rs index 0bf9eb07..edd9969c 100644 --- a/crates/engine-qwen35-cuda/tests/stra166_reference.rs +++ b/crates/engine-qwen35-cuda/tests/stra166_reference.rs @@ -68,30 +68,15 @@ pub fn reference(logits: &[f32; EXPERTS]) -> Option { let selected_lane_sum = xor_sum(selected_lanes)[0]; let inverse = 1.0 / selected_lane_sum.max(MIN_DENOMINATOR); let weights = selected.map(|probability| probability * inverse); - Some(Reference { - probabilities, - ids, - weights, - selected_lane_sum, - }) + Some(Reference { probabilities, ids, weights, selected_lane_sum }) } #[test] fn all_equal_has_exact_probabilities_and_lower_id_ties() { let output = reference(&[0.0; EXPERTS]).unwrap(); assert_eq!(output.ids, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - assert!( - output - .probabilities - .iter() - .all(|p| p.to_bits() == (1.0_f32 / 512.0).to_bits()) - ); - assert!( - output - .weights - .iter() - .all(|w| w.to_bits() == 0.1_f32.to_bits()) - ); + assert!(output.probabilities.iter().all(|p| p.to_bits() == (1.0_f32 / 512.0).to_bits())); + assert!(output.weights.iter().all(|w| w.to_bits() == 0.1_f32.to_bits())); } #[test] @@ -120,10 +105,7 @@ fn dominant_and_diffuse_cases_have_fixed_independent_id_order() { assert_eq!(dominant.weights[0], 1.0); assert!(dominant.weights[1..].iter().all(|w| *w == 0.0)); let diffuse = std::array::from_fn(|id| (id % 17) as f32 * 0.125); - assert_eq!( - reference(&diffuse).unwrap().ids, - [16, 33, 50, 67, 84, 101, 118, 135, 152, 169] - ); + assert_eq!(reference(&diffuse).unwrap().ids, [16, 33, 50, 67, 84, 101, 118, 135, 152, 169]); } #[test] @@ -142,18 +124,9 @@ fn nonfinite_inputs_are_refused_and_extreme_finite_inputs_underflow() { #[test] fn clamp_boundary_is_a_reduction_helper_case_not_a_fabricated_softmax_case() { - for sum in [ - 0.0_f32, - MIN_DENOMINATOR / 2.0, - MIN_DENOMINATOR, - MIN_DENOMINATOR * 2.0, - ] { + for sum in [0.0_f32, MIN_DENOMINATOR / 2.0, MIN_DENOMINATOR, MIN_DENOMINATOR * 2.0] { let normalized = sum * (1.0 / sum.max(MIN_DENOMINATOR)); - let expected = if sum < MIN_DENOMINATOR { - sum / MIN_DENOMINATOR - } else { - 1.0 - }; + let expected = if sum < MIN_DENOMINATOR { sum / MIN_DENOMINATOR } else { 1.0 }; assert_eq!(normalized.to_bits(), expected.to_bits()); } // In exact arithmetic, the largest 10 of 512 normalized probabilities diff --git a/crates/engine-qwen35-cuda/tests/stra168_full_vocabulary.rs b/crates/engine-qwen35-cuda/tests/stra168_full_vocabulary.rs index 1f3c1e93..c1e47db8 100644 --- a/crates/engine-qwen35-cuda/tests/stra168_full_vocabulary.rs +++ b/crates/engine-qwen35-cuda/tests/stra168_full_vocabulary.rs @@ -17,9 +17,7 @@ const LOGIT_BYTES: usize = 993_280; const PTX_SHA: &str = "8c00d8c7fe1678fc8674d66d63022646600ec03931d06bbb69db7e015909cfa1"; fn evidence_root() -> PathBuf { - let root = PathBuf::from( - std::env::var_os("LELEKA_HEAD_EVIDENCE").expect("explicit private evidence path"), - ); + let root = PathBuf::from(std::env::var_os("LELEKA_HEAD_EVIDENCE").expect("explicit private evidence path")); assert!(root.is_absolute()); root } @@ -35,11 +33,7 @@ fn hash_file(path: &Path) -> String { } digest.update(&chunk[..count]); } - digest - .finalize() - .iter() - .map(|v| format!("{v:02x}")) - .collect() + digest.finalize().iter().map(|v| format!("{v:02x}")).collect() } fn scale(row: usize) -> u8 { @@ -82,9 +76,7 @@ fn expected_q8() -> [u8; Q8_BYTES] { } fn expected_logits() -> Vec { - (0..ROWS) - .flat_map(|row| expected_word(row).to_le_bytes()) - .collect() + (0..ROWS).flat_map(|row| expected_word(row).to_le_bytes()).collect() } #[test] @@ -93,11 +85,7 @@ fn prepare_independent_full_vocabulary_fixture() { let root = evidence_root(); fs::create_dir_all(&root).unwrap(); let input_path = root.join("full-vocabulary.input"); - let file = fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&input_path) - .unwrap(); + let file = fs::OpenOptions::new().write(true).create_new(true).open(&input_path).unwrap(); let mut input = std::io::BufWriter::with_capacity(1 << 20, file); for word in [0x3631_4b51, ROWS as u32, COLUMNS as u32] { input.write_all(&word.to_le_bytes()).unwrap(); @@ -111,24 +99,15 @@ fn prepare_independent_full_vocabulary_fixture() { } // F32 127 input.flush().unwrap(); drop(input); - assert_eq!( - fs::metadata(&input_path).unwrap().len(), - (12 + WEIGHT_BYTES + COLUMNS * 4) as u64 - ); + assert_eq!(fs::metadata(&input_path).unwrap().len(), (12 + WEIGHT_BYTES + COLUMNS * 4) as u64); fs::write(root.join("literal-q8.bin"), expected_q8()).unwrap(); fs::write(root.join("literal-logits.bin"), expected_logits()).unwrap(); - let manifest = [ - "full-vocabulary.input", - "literal-q8.bin", - "literal-logits.bin", - ] - .into_iter() - .map(|name| format!("{} {name}\n", hash_file(&root.join(name)))) - .collect::(); + let manifest = ["full-vocabulary.input", "literal-q8.bin", "literal-logits.bin"] + .into_iter() + .map(|name| format!("{} {name}\n", hash_file(&root.join(name)))) + .collect::(); fs::write(root.join("literal-sha256.txt"), &manifest).unwrap(); - println!( - "FULL_VOCABULARY_CPU_PREP rows={ROWS} columns={COLUMNS} expected_argmax=248319\n{manifest}" - ); + println!("FULL_VOCABULARY_CPU_PREP rows={ROWS} columns={COLUMNS} expected_argmax=248319\n{manifest}"); } #[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] @@ -151,10 +130,7 @@ fn installed_driver_full_vocabulary_matches_original_and_literal_words() { let manifest = fs::read_to_string(root.join("literal-sha256.txt")).unwrap(); for line in manifest.lines() { let (sha, name) = line.split_once(" ").unwrap(); - assert!(matches!( - name, - "full-vocabulary.input" | "literal-q8.bin" | "literal-logits.bin" - )); + assert!(matches!(name, "full-vocabulary.input" | "literal-q8.bin" | "literal-logits.bin")); assert_eq!(hash_file(&root.join(name)), sha); } let input_path = root.join("full-vocabulary.input"); @@ -172,16 +148,9 @@ fn installed_driver_full_vocabulary_matches_original_and_literal_words() { let mut weights = vec![0; WEIGHT_BYTES]; input.read_exact(&mut weights).unwrap(); for (row, actual) in weights.as_chunks::<2100>().0.iter().enumerate() { - assert_eq!( - *actual, - packed_row(scale(row)), - "independent packed row {row}" - ); + assert_eq!(*actual, packed_row(scale(row)), "independent packed row {row}"); } - let activation = vec![0x42fe_0000_u32.to_le_bytes(); COLUMNS] - .into_iter() - .flatten() - .collect::>(); + let activation = vec![0x42fe_0000_u32.to_le_bytes(); COLUMNS].into_iter().flatten().collect::>(); let mut actual_activation = vec![0; COLUMNS * 4]; input.read_exact(&mut actual_activation).unwrap(); assert_eq!(actual_activation, activation); @@ -202,11 +171,7 @@ fn installed_driver_full_vocabulary_matches_original_and_literal_words() { .unwrap(); fs::write(root.join("native.stdout"), &process.stdout).unwrap(); fs::write(root.join("native.stderr"), &process.stderr).unwrap(); - assert!( - process.status.success(), - "{}", - String::from_utf8_lossy(&process.stderr) - ); + assert!(process.status.success(), "{}", String::from_utf8_lossy(&process.stderr)); let native_bytes = fs::read(&native_output).unwrap(); assert_eq!(native_bytes.len(), 16 + 2 * Q8_BYTES + LOGIT_BYTES); assert_eq!( @@ -218,10 +183,7 @@ fn installed_driver_full_vocabulary_matches_original_and_literal_words() { .as_slice() ); assert_eq!(&native_bytes[16..16 + Q8_BYTES], expected_q8()); - assert_eq!( - &native_bytes[16 + Q8_BYTES..16 + 2 * Q8_BYTES], - expected_q8() - ); + assert_eq!(&native_bytes[16 + Q8_BYTES..16 + 2 * Q8_BYTES], expected_q8()); let literal = expected_logits(); assert_eq!(&native_bytes[16 + 2 * Q8_BYTES..], literal); @@ -237,22 +199,8 @@ fn installed_driver_full_vocabulary_matches_original_and_literal_words() { dy.copy_from(&vec![0xa5; LOGIT_BYTES]).unwrap(); let resident = context.allocated_bytes(); assert_eq!(resident, WEIGHT_BYTES + COLUMNS * 4 + LOGIT_BYTES); - context - .q6_k_q8_1( - &dw, - &dx, - &mut dy, - Q6KProjectionShape { - rows: ROWS, - columns: COLUMNS, - }, - ) - .unwrap(); - assert_eq!( - context.allocated_bytes(), - resident, - "quantizer scratch/status released" - ); + context.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows: ROWS, columns: COLUMNS }).unwrap(); + assert_eq!(context.allocated_bytes(), resident, "quantizer scratch/status released"); let mut logits = vec![0; LOGIT_BYTES]; dy.copy_to(&mut logits).unwrap(); assert_eq!(logits, literal, "all 248320 exact independent F32 words"); diff --git a/crates/gateway-text/src/prompt/impl_json.rs b/crates/gateway-text/src/prompt/impl_json.rs index b149659c..c11c7502 100644 --- a/crates/gateway-text/src/prompt/impl_json.rs +++ b/crates/gateway-text/src/prompt/impl_json.rs @@ -28,12 +28,9 @@ impl Json { Plain::Number(n) => Self::Number(n.clone()), Plain::String(s) => Self::String(s.clone()), Plain::Array(items) => Self::Array(items.iter().map(Self::from_value).collect()), - Plain::Object(fields) => Self::Object( - fields - .iter() - .map(|(k, v)| (k.clone(), Self::from_value(v))) - .collect(), - ), + Plain::Object(fields) => { + Self::Object(fields.iter().map(|(k, v)| (k.clone(), Self::from_value(v))).collect()) + } } } @@ -50,11 +47,7 @@ impl Json { if fields.contains_key("type") { keys.sort_by_key(|key| (schema_order(key), key.as_str())); } - Self::Object( - keys.into_iter() - .map(|k| (k.clone(), Self::from_schema_value(&fields[k]))) - .collect(), - ) + Self::Object(keys.into_iter().map(|k| (k.clone(), Self::from_schema_value(&fields[k]))).collect()) } other => Self::from_value(other), } @@ -135,9 +128,7 @@ impl<'de> Deserialize<'de> for Json { } fn visit_f64(self, v: f64) -> Result { - serde_json::Number::from_f64(v) - .map(Json::Number) - .ok_or_else(|| E::custom("non-finite number")) + serde_json::Number::from_f64(v).map(Json::Number).ok_or_else(|| E::custom("non-finite number")) } fn visit_str(self, v: &str) -> Result { @@ -182,11 +173,7 @@ pub(super) fn py_space(c: char) -> bool { /// Jinja's `trim` filter is `str.strip(chars)`. pub(super) fn trim(value: Value, chars: Option) -> String { - let text = if value.is_undefined() { - String::new() - } else { - value.to_string() - }; + let text = if value.is_undefined() { String::new() } else { value.to_string() }; match chars { None => text.trim_matches(py_space).to_owned(), Some(set) => text.trim_matches(|c| set.contains(c)).to_owned(), @@ -196,12 +183,7 @@ pub(super) fn trim(value: Value, chars: Option) -> String { /// Python's `repr(float)` as `json.dumps` writes it: shortest round-trip digits, exponent form outside 1e-4..1e16. pub(super) fn python_float(value: f64) -> String { if value == 0.0 { - return if value.is_sign_negative() { - "-0.0" - } else { - "0.0" - } - .to_owned(); + return if value.is_sign_negative() { "-0.0" } else { "0.0" }.to_owned(); } let scientific = format!("{value:e}"); // shortest digits: "-1.2345e-5" let (mantissa, exponent) = scientific.split_once('e').expect("exponent"); @@ -228,10 +210,6 @@ pub(super) fn python_float(value: f64) -> String { out.push('.'); out.push_str(&digits[1..]); } - format!( - "{out}e{}{:02}", - if exponent < 0 { '-' } else { '+' }, - exponent.abs() - ) + format!("{out}e{}{:02}", if exponent < 0 { '-' } else { '+' }, exponent.abs()) } } diff --git a/crates/gateway-text/src/prompt/impl_renderer.rs b/crates/gateway-text/src/prompt/impl_renderer.rs index 2093fea9..a1f42187 100644 --- a/crates/gateway-text/src/prompt/impl_renderer.rs +++ b/crates/gateway-text/src/prompt/impl_renderer.rs @@ -15,12 +15,9 @@ impl Renderer { env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback); env.add_filter("tojson", tojson); env.add_filter("trim", trim); - env.add_function( - "raise_exception", - |message: String| -> Result { - Err(Error::new(ErrorKind::InvalidOperation, message)) - }, - ); + env.add_function("raise_exception", |message: String| -> Result { + Err(Error::new(ErrorKind::InvalidOperation, message)) + }); env.add_template_owned("chat", source.to_owned()) .map_err(|e| format!("chat template does not compile: {e:#}"))?; Ok(Self { env }) @@ -30,33 +27,22 @@ impl Renderer { let mut context: BTreeMap<&str, Value> = BTreeMap::new(); let messages = without_empty_assistant_turns(input.messages)?; context.insert("messages", Value::from_serialize(&messages)); - context.insert( - "tools", - input.tools.map_or(Value::from(()), Value::from_serialize), - ); - context.insert( - "add_generation_prompt", - Value::from(input.add_generation_prompt), - ); + context.insert("tools", input.tools.map_or(Value::from(()), Value::from_serialize)); + context.insert("add_generation_prompt", Value::from(input.add_generation_prompt)); for (name, value) in &input.kwargs { context.insert(name, Value::from_serialize(value)); } self.env .get_template("chat") .and_then(|template| template.render(&context)) - .map_err(|error| { - error - .detail() - .map_or_else(|| error.to_string(), str::to_owned) - }) + .map_err(|error| error.detail().map_or_else(|| error.to_string(), str::to_owned)) } } /// The compiled pinned template. pub fn pinned() -> &'static Renderer { static PINNED: OnceLock = OnceLock::new(); - PINNED - .get_or_init(|| Renderer::new(PINNED_TEMPLATE).expect("the pinned chat template compiles")) + PINNED.get_or_init(|| Renderer::new(PINNED_TEMPLATE).expect("the pinned chat template compiles")) } impl Role { @@ -87,12 +73,7 @@ impl<'a> Message<'a> { } pub fn text(role: Role, content: &'a str, reasoning: Option<&'a str>) -> Self { - Self { - role, - content, - reasoning, - parts: None, - } + Self { role, content, reasoning, parts: None } } } @@ -116,10 +97,7 @@ pub fn render(messages: &[Message<'_>], effort: Effort) -> Result Result { - let name = tool - .get("name") - .and_then(Plain::as_str) - .ok_or("tool needs a name")?; + let name = tool.get("name").and_then(Plain::as_str).ok_or("tool needs a name")?; let mut function = vec![("name".to_owned(), Json::str(name))]; if let Some(description) = tool.get("description").and_then(Plain::as_str) { function.push(("description".to_owned(), Json::str(description))); @@ -130,17 +108,10 @@ pub fn chat_tool(tool: &Plain) -> Result { if let Some(strict) = tool.get("strict") { function.push(("strict".to_owned(), Json::from_schema_value(strict))); } - Ok(Json::object([ - ("type", Json::str("function")), - ("function", Json::Object(function)), - ])) + Ok(Json::object([("type", Json::str("function")), ("function", Json::Object(function))])) } -pub fn render_with_tools( - messages: &[Message<'_>], - effort: Effort, - tools: &[Plain], -) -> Result { +pub fn render_with_tools(messages: &[Message<'_>], effort: Effort, tools: &[Plain]) -> Result { render_with_images(messages, effort, tools).map(|(prompt, _)| prompt) } @@ -164,15 +135,8 @@ pub(super) fn reference_render() -> bool { /// system messages, the tools and the effort, so the template renders just that part, with the history left out. The /// generation prompt is the template's own closing lines. The result is the template's output byte for byte /// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template. -pub(super) fn render_native( - messages: &[Message<'_>], - effort: Effort, - tools: &[Json], -) -> Result { - let leading = messages - .iter() - .take_while(|message| matches!(message.role, Role::System | Role::Developer)) - .count(); +pub(super) fn render_native(messages: &[Message<'_>], effort: Effort, tools: &[Json]) -> Result { + let leading = messages.iter().take_while(|message| matches!(message.role, Role::System | Role::Developer)).count(); let object = |message: &Message<'_>| { let mut fields = vec![ ("role".to_owned(), Json::str(message.role.name())), @@ -187,10 +151,7 @@ pub(super) fn render_native( // exact output is cut off again. const PLACEHOLDER: &str = "<|im_start|>user\n<|im_end|>\n"; let head: Vec = if leading == 0 { - vec![Json::object([ - ("role", Json::str("user")), - ("content", Json::str("")), - ])] + vec![Json::object([("role", Json::str("user")), ("content", Json::str(""))])] } else { messages[..leading].iter().map(object).collect() }; @@ -207,12 +168,7 @@ pub(super) fn render_native( .to_owned(); } let rest = &messages[leading..]; - prompt.reserve( - rest.iter() - .map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64) - .sum::() - + 64, - ); + prompt.reserve(rest.iter().map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64).sum::() + 64); for message in rest { let content = message.content.trim_matches(py_space); match message.role { @@ -234,10 +190,6 @@ pub(super) fn render_native( } } prompt.push_str("<|im_start|>assistant\n"); - prompt.push_str(if matches!(effort, Effort::None) { - "\n\n\n\n" - } else { - "\n" - }); + prompt.push_str(if matches!(effort, Effort::None) { "\n\n\n\n" } else { "\n" }); Ok(prompt) } diff --git a/crates/gateway-text/src/prompt/json_string.rs b/crates/gateway-text/src/prompt/json_string.rs index 9e085085..f45d6db8 100644 --- a/crates/gateway-text/src/prompt/json_string.rs +++ b/crates/gateway-text/src/prompt/json_string.rs @@ -27,12 +27,7 @@ pub(super) fn json_string(text: &str, ensure_ascii: bool, out: &mut String) { out.push('"'); } -pub(super) fn write_json( - value: &Value, - sort_keys: bool, - ensure_ascii: bool, - out: &mut String, -) -> Result<(), Error> { +pub(super) fn write_json(value: &Value, sort_keys: bool, ensure_ascii: bool, out: &mut String) -> Result<(), Error> { match value.kind() { ValueKind::None => out.push_str("null"), ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }), @@ -76,10 +71,7 @@ pub(super) fn write_json( out.push_str(", "); } let Some(name) = key.as_str() else { - return Err(Error::new( - ErrorKind::InvalidOperation, - "tojson keys must be strings", - )); + return Err(Error::new(ErrorKind::InvalidOperation, "tojson keys must be strings")); }; json_string(name, ensure_ascii, out); out.push_str(": "); diff --git a/crates/gateway-text/src/prompt/tests.rs b/crates/gateway-text/src/prompt/tests.rs index d45834b7..4672b01b 100644 --- a/crates/gateway-text/src/prompt/tests.rs +++ b/crates/gateway-text/src/prompt/tests.rs @@ -19,10 +19,7 @@ struct Case { } fn golden() -> Vec { - serde_json::from_str(include_str!( - "../../../../engine/strata/serve/chat_golden.json" - )) - .unwrap() + serde_json::from_str(include_str!("../../../../engine/strata/serve/chat_golden.json")).unwrap() } /// All ten cases of `serve/chat_golden.json`, straight through the Jinja template: system merging, tool @@ -35,11 +32,7 @@ fn all_ten_golden_cases_render_byte_for_byte() { for case in cases { assert!(case.error.is_none(), "{}", case.name); assert_eq!(case.rendered, case.hf, "{}", case.name); - let kwargs = case - .enable_thinking - .map(|b| ("enable_thinking", Json::Bool(b))) - .into_iter() - .collect(); + let kwargs = case.enable_thinking.map(|b| ("enable_thinking", Json::Bool(b))).into_iter().collect(); let got = pinned() .render(&ChatInput { messages: &case.messages, @@ -91,11 +84,7 @@ fn typed_text_prompts_match_the_golden_bytes() { parts: None, }) .collect::>(); - let effort = if name == "thinking disabled" { - Effort::None - } else { - Effort::XHigh - }; + let effort = if name == "thinking disabled" { Effort::None } else { Effort::XHigh }; assert_eq!(render(&messages, effort).unwrap(), case.rendered, "{name}"); } } @@ -153,37 +142,17 @@ fn native_render_equals_the_template() { json!({"type":"function","name":"bare"}), ]; let mut rng = Rng(0x2545_F491_4F6C_DD1D); - let text = |rng: &mut Rng| { - (0..rng.below(5)) - .map(|_| ATOMS[rng.below(ATOMS.len())]) - .collect::() - }; + let text = |rng: &mut Rng| (0..rng.below(5)).map(|_| ATOMS[rng.below(ATOMS.len())]).collect::(); for case in 0..4000 { let mut storage: Vec<(Role, String, Option)> = Vec::new(); for _ in 0..rng.below(3) { - let role = if rng.below(2) == 0 { - Role::System - } else { - Role::Developer - }; + let role = if rng.below(2) == 0 { Role::System } else { Role::Developer }; storage.push((role, text(&mut rng), None)); } for _ in 0..rng.below(5) { - let role = if rng.below(2) == 0 { - Role::User - } else { - Role::Assistant - }; + let role = if rng.below(2) == 0 { Role::User } else { Role::Assistant }; let reasoning = (rng.below(2) == 0).then(|| text(&mut rng)); - storage.push(( - role, - text(&mut rng), - if role == Role::Assistant { - reasoning - } else { - None - }, - )); + storage.push((role, text(&mut rng), if role == Role::Assistant { reasoning } else { None })); } storage.push((Role::User, text(&mut rng), None)); let messages: Vec> = storage @@ -196,35 +165,17 @@ fn native_render_equals_the_template() { }) .collect(); let tools: Vec = tools_pool.iter().take(rng.below(4)).cloned().collect(); - let effort = [ - Effort::None, - Effort::Low, - Effort::Medium, - Effort::High, - Effort::XHigh, - ][rng.below(5)]; + let effort = [Effort::None, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh][rng.below(5)]; let reference = render_via_template(&messages, effort, &tools).map(|(prompt, _)| prompt); - let chat_tools = tools - .iter() - .map(chat_tool) - .collect::, _>>() - .unwrap(); + let chat_tools = tools.iter().map(chat_tool).collect::, _>>().unwrap(); let native = render_native(&without_empty_turns(&messages), effort, &chat_tools); - assert_eq!( - native, - reference, - "case {case}: {storage:?} {effort:?} tools {}", - tools.len() - ); + assert_eq!(native, reference, "case {case}: {storage:?} {effort:?} tools {}", tools.len()); } } #[test] fn flattened_tool_continuation_matches_the_golden_bytes() { - let case = golden() - .into_iter() - .find(|c| c.name == "tool call and response") - .unwrap(); + let case = golden().into_iter().find(|c| c.name == "tool call and response").unwrap(); let function = case.tools.as_ref().unwrap()[0].get("function").unwrap(); let tools = [json!({ "type":"function", @@ -232,12 +183,7 @@ fn flattened_tool_continuation_matches_the_golden_bytes() { "description": serde_json::to_value(function.get("description")).unwrap(), "parameters": serde_json::to_value(function.get("parameters")).unwrap(), })]; - let user = |content| Message { - role: Role::User, - content, - reasoning: None, - parts: None, - }; + let user = |content| Message { role: Role::User, content, reasoning: None, parts: None }; let messages = [ user("Weather in Oslo?"), Message { @@ -249,10 +195,7 @@ fn flattened_tool_continuation_matches_the_golden_bytes() { user("\n{\"temp\": 3}\n"), user("And in Bergen?"), ]; - assert_eq!( - render_with_tools(&messages, Effort::XHigh, &tools).unwrap(), - case.rendered - ); + assert_eq!(render_with_tools(&messages, Effort::XHigh, &tools).unwrap(), case.rendered); } /// Strata 0.1.50 `ChatTemplate.render` (#843): completed empty assistant turns are not rendered, the final message is kept @@ -284,85 +227,42 @@ fn completed_empty_assistant_turns_are_not_rendered() { assistant(Json::str(""), vec![]), assistant(Json::str(" \n\u{3000}"), vec![]), assistant(Json::Array(vec![]), vec![]), - assistant( - Json::str(""), - vec![("reasoning_content", Json::str("thought"))], - ), + assistant(Json::str(""), vec![("reasoning_content", Json::str("thought"))]), assistant(Json::str(""), vec![("tool_calls", Json::Array(vec![]))]), ] { - let got = render(&[ - user(Json::str("hi")), - dropped.clone(), - user(Json::str("again")), - ]); + let got = render(&[user(Json::str("hi")), dropped.clone(), user(Json::str("again"))]); assert_eq!(got, tail, "{dropped:?}"); } // kept: a tool call, a picture, and the final message - let call = assistant( - Json::str(""), - vec![( - "tool_calls", - Json::Array(vec![Json::object([("name", Json::str("f"))])]), - )], - ); + let call = + assistant(Json::str(""), vec![("tool_calls", Json::Array(vec![Json::object([("name", Json::str("f"))])]))]); let got = render(&[user(Json::str("hi")), call, user(Json::str("again"))]); assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); - let picture = assistant( - Json::Array(vec![Json::object([("type", Json::str("image"))])]), - vec![], - ); + let picture = assistant(Json::Array(vec![Json::object([("type", Json::str("image"))])]), vec![]); let got = render(&[user(Json::str("hi")), picture, user(Json::str("again"))]); assert!(got.contains("<|vision_start|>"), "{got}"); let got = render(&[user(Json::str("hi")), assistant(Json::Null, vec![])]); assert_eq!(got.matches("<|im_start|>assistant").count(), 1, "{got}"); // a content Python cannot iterate fails the render instead of being dropped let error = pinned().render(&ChatInput { - messages: &[ - user(Json::str("hi")), - assistant(Json::Number(42.into()), vec![]), - user(Json::str("again")), - ], + messages: &[user(Json::str("hi")), assistant(Json::Number(42.into()), vec![]), user(Json::str("again"))], tools: None, add_generation_prompt: false, kwargs: vec![], }); assert!(error.is_err()); // the typed path takes the same turns out, native renderer included - let typed = |role, content| Message { - role, - content, - reasoning: Some("thought"), - parts: None, - }; - let messages = [ - typed(Role::User, "hi"), - typed(Role::Assistant, " "), - typed(Role::User, "again"), - ]; + let typed = |role, content| Message { role, content, reasoning: Some("thought"), parts: None }; + let messages = [typed(Role::User, "hi"), typed(Role::Assistant, " "), typed(Role::User, "again")]; let native = render_with_tools(&messages, Effort::XHigh, &[]).unwrap(); assert_eq!(native, format!("{tail}<|im_start|>assistant\n\n")); - assert_eq!( - render_via_template(&messages, Effort::XHigh, &[]) - .unwrap() - .0, - native - ); + assert_eq!(render_via_template(&messages, Effort::XHigh, &[]).unwrap().0, native); } #[test] fn rejects_unrepresentable_message_order() { - let system = Message { - role: Role::System, - content: "rules", - reasoning: None, - parts: None, - }; - let user = Message { - role: Role::User, - content: "question", - reasoning: None, - parts: None, - }; + let system = Message { role: Role::System, content: "rules", reasoning: None, parts: None }; + let user = Message { role: Role::User, content: "question", reasoning: None, parts: None }; assert!(render(&[user, system], Effort::XHigh).is_err()); assert!(render(&[system], Effort::XHigh).is_err()); assert!(render(&[], Effort::XHigh).is_err()); @@ -370,47 +270,27 @@ fn rejects_unrepresentable_message_order() { #[test] fn efforts_select_the_template_instructions() { - let user = [Message { - role: Role::User, - content: "hi", - reasoning: None, - parts: None, - }]; + let user = [Message { role: Role::User, content: "hi", reasoning: None, parts: None }]; let text = |effort| render(&user, effort).unwrap(); assert!(text(Effort::XHigh).contains("Reasoning effort is set to xhigh.")); assert!(text(Effort::High).contains("Reasoning effort is set to xhigh.")); assert!(text(Effort::Low).contains("Reasoning effort is set to low.")); - assert_eq!( - text(Effort::Medium), - "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n" - ); - assert_eq!( - text(Effort::None), - "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" - ); + assert_eq!(text(Effort::Medium), "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n"); + assert_eq!(text(Effort::None), "<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n\n\n\n\n"); } #[test] fn raise_exception_surfaces_the_template_message() { - let messages = [Json::object([ - ("role", Json::str("tool")), - ("content", Json::str("x")), - ])]; + let messages = [Json::object([("role", Json::str("tool")), ("content", Json::str("x"))])]; let bad = pinned().render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("robot")), - ("content", Json::str("x")), - ])], + messages: &[Json::object([("role", Json::str("robot")), ("content", Json::str("x"))])], tools: None, add_generation_prompt: true, kwargs: vec![], }); assert_eq!(bad.unwrap_err(), "Unexpected message role."); let effort = pinned().render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("user")), - ("content", Json::str("x")), - ])], + messages: &[Json::object([("role", Json::str("user")), ("content", Json::str("x"))])], tools: None, add_generation_prompt: true, kwargs: vec![("reasoning_effort", Json::str("extreme"))], @@ -429,12 +309,7 @@ fn tojson_matches_python_json_dumps() { let value: Json = serde_json::from_str(json).unwrap(); let mut context = BTreeMap::new(); context.insert("value", Value::from_serialize(&value)); - renderer - .env - .get_template("chat") - .unwrap() - .render(&context) - .unwrap() + renderer.env.get_template("chat").unwrap().render(&context).unwrap() }; assert_eq!( render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#), @@ -448,10 +323,7 @@ fn tojson_matches_python_json_dumps() { render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"), "[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]" ); - assert_eq!( - render("[18446744073709551615, -9223372036854775808]"), - "[18446744073709551615, -9223372036854775808]" - ); + assert_eq!(render("[18446744073709551615, -9223372036854775808]"), "[18446744073709551615, -9223372036854775808]"); } #[test] @@ -460,12 +332,7 @@ fn trim_is_pythons_strip() { let render = |text: &str| { let mut context = BTreeMap::new(); context.insert("value", Value::from(text)); - renderer - .env - .get_template("chat") - .unwrap() - .render(&context) - .unwrap() + renderer.env.get_template("chat").unwrap().render(&context).unwrap() }; // U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]"); @@ -473,20 +340,21 @@ fn trim_is_pythons_strip() { #[test] fn objects_keep_the_order_they_were_written_in() { - let tools: Vec = serde_json::from_str( - r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#, - ) - .unwrap(); + let tools: Vec = + serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#) + .unwrap(); let out = pinned() .render(&ChatInput { - messages: &[Json::object([ - ("role", Json::str("user")), - ("content", Json::str("x")), - ])], + messages: &[Json::object([("role", Json::str("user")), ("content", Json::str("x"))])], tools: Some(&tools), add_generation_prompt: true, kwargs: vec![("enable_thinking", Json::Bool(false))], }) .unwrap(); - assert!(out.contains(r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"#), "{out}"); + assert!( + out.contains( + r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"# + ), + "{out}" + ); } diff --git a/crates/gateway-text/src/prompt/without_empty_turns.rs b/crates/gateway-text/src/prompt/without_empty_turns.rs index 270b580c..752d9ce3 100644 --- a/crates/gateway-text/src/prompt/without_empty_turns.rs +++ b/crates/gateway-text/src/prompt/without_empty_turns.rs @@ -33,16 +33,11 @@ pub fn render_with_images( .position(|message| !matches!(message.role, Role::System | Role::Developer)) .unwrap_or(messages.len()); if first_non_system == messages.len() - || messages[first_non_system..] - .iter() - .any(|message| matches!(message.role, Role::System | Role::Developer)) + || messages[first_non_system..].iter().any(|message| matches!(message.role, Role::System | Role::Developer)) { return Err("system and developer messages must be at the beginning".into()); } - if messages - .last() - .is_none_or(|message| message.role != Role::User) - { + if messages.last().is_none_or(|message| message.role != Role::User) { return Err("generation needs a final user message".into()); } if !reference_render() && messages.iter().all(|message| message.parts.is_none()) { @@ -67,22 +62,15 @@ pub(super) fn render_via_template( parts .iter() .map(|part| match part { - Part::Text(text) => Json::object([ - ("type", Json::str("text")), - ("text", Json::str(text)), - ]), - Part::Image(source) => Json::object([ - ("type", Json::str("image")), - ("source", Json::str(source)), - ]), + Part::Text(text) => Json::object([("type", Json::str("text")), ("text", Json::str(text))]), + Part::Image(source) => { + Json::object([("type", Json::str("image")), ("source", Json::str(source))]) + } }) .collect(), ), }; - let mut fields = vec![ - ("role".to_owned(), Json::str(message.role.name())), - ("content".to_owned(), content), - ]; + let mut fields = vec![("role".to_owned(), Json::str(message.role.name())), ("content".to_owned(), content)]; if let Some(reasoning) = message.reasoning { fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); } diff --git a/crates/leleka-memory/examples/swap_ab.rs b/crates/leleka-memory/examples/swap_ab.rs index 1d436fa5..b20a0a1d 100644 --- a/crates/leleka-memory/examples/swap_ab.rs +++ b/crates/leleka-memory/examples/swap_ab.rs @@ -52,7 +52,13 @@ fn sealed_memfd(bytes: u64) -> OwnedFd { written += k as u64; } // SAFETY: plain fcntl on an owned descriptor. - let r = unsafe { libc::fcntl(raw, libc::F_ADD_SEALS, libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL) }; + let r = unsafe { + libc::fcntl( + raw, + libc::F_ADD_SEALS, + libc::F_SEAL_WRITE | libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL, + ) + }; assert_eq!(r, 0, "seal: {}", std::io::Error::last_os_error()); fd } @@ -64,7 +70,8 @@ fn main() { let secs = num("--secs", 60); let lock = LockMode::parse(&arg("--lock").unwrap_or_else(|| "off".into())).expect("--lock off|try|require"); let heal = num("--heal", 0) != 0; - let mut cfg = GovernorConfig::from_env(64 << 30, false, &|k| std::env::var(k).ok()).expect("LELEKA_MEMORY_* overrides"); + let mut cfg = + GovernorConfig::from_env(64 << 30, false, &|k| std::env::var(k).ok()).expect("LELEKA_MEMORY_* overrides"); cfg.lock_mode = lock; cfg.heal = heal; cfg.heal_bytes_per_tick = 256 << 20; diff --git a/crates/leleka-memory/rustfmt.toml b/crates/leleka-memory/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/leleka-memory/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/leleka-memory/src/census.rs b/crates/leleka-memory/src/census.rs index bf0924a1..f7c1b162 100644 --- a/crates/leleka-memory/src/census.rs +++ b/crates/leleka-memory/src/census.rs @@ -94,7 +94,13 @@ pub struct FlatReport { impl std::fmt::Display for FlatReport { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - writeln!(f, "flatness over {} samples after {} warm-up: {}", self.samples - self.warmup.min(self.samples), self.warmup, if self.ok { "FLAT" } else { "GROWING" })?; + writeln!( + f, + "flatness over {} samples after {} warm-up: {}", + self.samples - self.warmup.min(self.samples), + self.warmup, + if self.ok { "FLAT" } else { "GROWING" } + )?; for d in &self.drifts { writeln!( f, @@ -130,8 +136,22 @@ pub fn check_flat(series: &[Census], warmup: usize, tol: &Tolerances) -> FlatRep return; } let drift = match quarter_means(&values) { - Some((a, b)) => Drift { series: name, first_quarter_mean: a, last_quarter_mean: b, growth: b - a, tolerance, ok: b - a <= tolerance as f64 }, - None => Drift { series: name, first_quarter_mean: 0.0, last_quarter_mean: 0.0, growth: 0.0, tolerance, ok: false }, + Some((a, b)) => Drift { + series: name, + first_quarter_mean: a, + last_quarter_mean: b, + growth: b - a, + tolerance, + ok: b - a <= tolerance as f64, + }, + None => Drift { + series: name, + first_quarter_mean: 0.0, + last_quarter_mean: 0.0, + growth: 0.0, + tolerance, + ok: false, + }, }; drifts.push(drift); }; @@ -198,7 +218,14 @@ pub fn fit_slope(points: &[(f64, f64)]) -> Option { } slopes.sort_by(f64::total_cmp); let theil_sen = slopes.get(slopes.len() / 2).copied().unwrap_or(0.0); - Some(SlopeFit { n, slope, ci95_low: slope - 1.96 * se, ci95_high: slope + 1.96 * se, theil_sen, r2: if syy > 0.0 { 1.0 - sse / syy } else { 0.0 } }) + Some(SlopeFit { + n, + slope, + ci95_low: slope - 1.96 * se, + ci95_high: slope + 1.96 * se, + theil_sen, + r2: if syy > 0.0 { 1.0 - sse / syy } else { 0.0 }, + }) } #[cfg(test)] @@ -222,7 +249,10 @@ mod tests { #[test] fn warmup_growth_is_ignored_but_later_growth_is_caught() { // fills a cache for 20 requests, then leaks 1 MiB per request - let s = series(120, |i| Census { rss: (60 << 30) + (i.min(20) as u64) * (200 << 20) + (i.saturating_sub(20) as u64) * (4 << 20), ..base() }); + let s = series(120, |i| Census { + rss: (60 << 30) + (i.min(20) as u64) * (200 << 20) + (i.saturating_sub(20) as u64) * (4 << 20), + ..base() + }); let r = check_flat(&s, 20, &Tolerances::default()); assert!(!r.ok); assert!(r.drifts.iter().any(|d| d.series == "rss" && !d.ok), "{r}"); @@ -259,7 +289,8 @@ mod tests { #[test] fn the_slope_fit_finds_a_leak_and_a_plateau() { // 4 KiB per request leaking, with deterministic noise - let leak: Vec<(f64, f64)> = (0..400).map(|i| (i as f64, 1e9 + 4096.0 * i as f64 + ((i * 7919) % 2000) as f64 * 1024.0)).collect(); + let leak: Vec<(f64, f64)> = + (0..400).map(|i| (i as f64, 1e9 + 4096.0 * i as f64 + ((i * 7919) % 2000) as f64 * 1024.0)).collect(); let fit = fit_slope(&leak).unwrap(); assert!((fit.slope - 4096.0).abs() < 4096.0 * 0.2, "{fit:?}"); assert!(!fit.includes_zero() || fit.ci95_low < 4096.0, "{fit:?}"); diff --git a/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs b/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs index 1b557815..27be8418 100644 --- a/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs +++ b/crates/leleka-memory/src/governor/impl_drop_for_samplerguard.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Drop for SamplerGuard { fn drop(&mut self) { self.inner.stop.store(true, Ordering::Release); diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs index 2f18eef6..1f01e942 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2.rs @@ -3,8 +3,6 @@ #[allow(unused_imports)] use super::*; - - impl Governor { pub fn new(cfg: GovernorConfig, src: Arc) -> Self { Self::with_parts(cfg, ProcPressure(src), AnyClock::System) @@ -130,9 +128,15 @@ impl Governor { let inv = self.inventory(); for item in &plan.fixed { inv.set( - crate::inventory::Entry::new("planned", &item.name, item.space, crate::inventory::When::Startup, &item.formula) - .expected(item.bytes) - .swappable(false), + crate::inventory::Entry::new( + "planned", + &item.name, + item.space, + crate::inventory::When::Startup, + &item.formula, + ) + .expected(item.bytes) + .swappable(false), ); } self.log(&format!( @@ -158,7 +162,12 @@ impl Governor { } /// The device check once the device is visible (`cuMemGetInfo`): refuse or note, and keep the numbers for the report. - pub fn check_vram(&self, vram: crate::plan::VramFacts, budget: u64, fixed_estimate: Option) -> Result<(), Refusal> { + pub fn check_vram( + &self, + vram: crate::plan::VramFacts, + budget: u64, + fixed_estimate: Option, + ) -> Result<(), Refusal> { match crate::plan::check_vram(&self.policy(), vram, budget, fixed_estimate) { Ok((plan, note)) => { if let Some(note) = note { @@ -217,7 +226,9 @@ impl Governor { let interval = self.inner.cfg.sample_interval_ms.max(50); let now = self.now_ms(); let last = self.inner.sampled_at_ms.load(Ordering::Acquire); - if now.saturating_sub(last) > interval.saturating_mul(5) && self.inner.counters.samples.load(Ordering::Relaxed) > 0 { + if now.saturating_sub(last) > interval.saturating_mul(5) + && self.inner.counters.samples.load(Ordering::Relaxed) > 0 + { self.sample_at(now); } } diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs index cbf917b7..b1a57c66 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_2_2.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl Governor { - // ---- admission and shedding ------------------------------------------------------------------------------- /// May this request start? Context first (a request that can never fit is a 400, not a retry), then the pressure level, @@ -41,20 +38,21 @@ impl Governor { // the transient of one request (checkpoint / node state / import staging) must not take the host below the hard floor let transient = self.policy().reserve / 4; if let Some(available) = self.available_now() - && available.saturating_sub(transient) < self.policy().hard_floor { - c.rejected_pressure.fetch_add(1, Ordering::Relaxed); - return Admission::Refuse(Refuse { - status: 503, - code: "memory_pressure", - message: format!( - "{} available is within {} of the hard floor {}; retry shortly", - gib(available), - gib(transient), - gib(self.policy().hard_floor) - ), - retry_after_secs: retry, - }); - } + && available.saturating_sub(transient) < self.policy().hard_floor + { + c.rejected_pressure.fetch_add(1, Ordering::Relaxed); + return Admission::Refuse(Refuse { + status: 503, + code: "memory_pressure", + message: format!( + "{} available is within {} of the hard floor {}; retry shortly", + gib(available), + gib(transient), + gib(self.policy().hard_floor) + ), + retry_after_secs: retry, + }); + } c.admitted.fetch_add(1, Ordering::Relaxed); Admission::Admit } @@ -81,7 +79,11 @@ impl Governor { } // A/B inside one engine (bring-up): no trim while the file named by LELEKA_NO_TRIM_FILE exists static NO_TRIM_FILE: OnceLock> = OnceLock::new(); - if NO_TRIM_FILE.get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)).as_ref().is_some_and(|f| f.exists()) { + if NO_TRIM_FILE + .get_or_init(|| std::env::var_os("LELEKA_NO_TRIM_FILE").map(std::path::PathBuf::from)) + .as_ref() + .is_some_and(|f| f.exists()) + { return facts; } let Some(available) = facts.effective_available() else { return facts }; diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs index cbeca80c..64cc6f5c 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_3.rs @@ -3,23 +3,30 @@ #[allow(unused_imports)] use super::*; - - impl Governor { - /// [`Self::guard_archive`] for a sparse memfd: `extents` are the `(offset, len)` ranges that hold data, everything else of the /// `len`-byte descriptor is a hole. Only the extents are locked and healed (locking or populating a hole allocates zero /// pages for it, which would turn the sparse copy back into the full archive), the lock limit is judged against their /// size, and the report says so. `None` is the whole archive. #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - pub fn guard_archive_extents(&self, fd: std::os::fd::BorrowedFd<'_>, len: u64, extents: Option<&[crate::lock::Span]>) -> Result { + pub fn guard_archive_extents( + &self, + fd: std::os::fd::BorrowedFd<'_>, + len: u64, + extents: Option<&[crate::lock::Span]>, + ) -> Result { let started = self.inner.clock.now(); let facts = self.probe(); let mode = self.inner.cfg.lock_mode; if let Some(spans) = extents && let Err(why) = crate::lock::check_spans(spans, len) { - return Err(Refusal { code: "memlock", message: format!("the sparse archive extents are invalid: {why}"), numbers: vec![("archive".to_owned(), len)], advice: vec![] }); + return Err(Refusal { + code: "memlock", + message: format!("the sparse archive extents are invalid: {why}"), + numbers: vec![("archive".to_owned(), len)], + advice: vec![], + }); } // the bytes that are resident and have to be locked let resident = extents.map_or(len, crate::lock::spans_bytes); @@ -54,7 +61,12 @@ impl Governor { }; self.log(&format!("WARNING: cannot map the sealed KAR memfd for the residency guard: {e}")); if mode == LockMode::Require { - return Err(Refusal { code: "memlock", message: format!("mmap of the archive failed: {e}"), numbers: vec![], advice: vec![] }); + return Err(Refusal { + code: "memlock", + message: format!("mmap of the archive failed: {e}"), + numbers: vec![], + advice: vec![], + }); } return Ok(report); } @@ -68,14 +80,19 @@ impl Governor { if *hard == u64::MAX { "unlimited".into() } else { (hard >> 20).to_string() }, need >> 20 ); - self.log(&format!("WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", gib(resident), advice.join(" | "))); + self.log(&format!( + "WARNING: the sealed KAR memfd ({}) stays swappable: {why}. To keep it resident: {}", + gib(resident), + advice.join(" | ") + )); LockOutcome::NotAttempted { why } } LockDecision::Attempt { raise_soft_to } => { if let Some(to) = raise_soft_to - && let Err(e) = crate::lock::raise_memlock_soft(*to) { - self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); - } + && let Err(e) = crate::lock::raise_memlock_soft(*to) + { + self.log(&format!("WARNING: could not raise the soft RLIMIT_MEMLOCK to {} MiB: {e}", to >> 20)); + } let policy = self.policy(); let swapped = self.mapping_swapped(&mapping).unwrap_or(0); let src = self.inner.src.clone(); @@ -90,9 +107,17 @@ impl Governor { None => mapping.lock(GIB, allow), }; match &outcome { - LockOutcome::Locked { bytes } => self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))), - LockOutcome::Partial { locked, why, .. } => self.log(&format!("WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", gib(*locked), gib(len))), - LockOutcome::NotAttempted { why } => self.log(&format!("sealed KAR memfd lock not attempted: {why}")), + LockOutcome::Locked { bytes } => { + self.log(&format!("sealed KAR memfd locked in RAM: {} (mlock, never swapped)", gib(*bytes))) + } + LockOutcome::Partial { locked, why, .. } => self.log(&format!( + "WARNING: sealed KAR memfd lock stopped at {} of {}: {why}", + gib(*locked), + gib(len) + )), + LockOutcome::NotAttempted { why } => { + self.log(&format!("sealed KAR memfd lock not attempted: {why}")) + } } outcome } @@ -110,14 +135,34 @@ impl Governor { if mode == LockMode::Require && !matches!(outcome, LockOutcome::Locked { .. }) { let (numbers, advice) = match &decision { LockDecision::Insufficient { need, soft, hard, advice } => ( - vec![("needed to lock".to_owned(), *need), ("RLIMIT_MEMLOCK soft".to_owned(), *soft), ("RLIMIT_MEMLOCK hard".to_owned(), *hard)], + vec![ + ("needed to lock".to_owned(), *need), + ("RLIMIT_MEMLOCK soft".to_owned(), *soft), + ("RLIMIT_MEMLOCK hard".to_owned(), *hard), + ], advice.clone(), ), _ => (vec![("archive".to_owned(), resident)], vec![]), }; - return Err(Refusal { code: "memlock", message: format!("LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})"), numbers, advice }); + return Err(Refusal { + code: "memlock", + message: format!( + "LELEKA_MEMORY_LOCK=require but the sealed KAR memfd could not be locked ({outcome:?})" + ), + numbers, + advice, + }); } - *lock(&self.inner.guarded) = Some(Guarded { mapping, report: report.clone(), extents: extents.map(<[_]>::to_vec), cursor: 0, last_swapped: 0, warned_swapped: 0, last_check: None, last: None }); + *lock(&self.inner.guarded) = Some(Guarded { + mapping, + report: report.clone(), + extents: extents.map(<[_]>::to_vec), + cursor: 0, + last_swapped: 0, + warned_swapped: 0, + last_check: None, + last: None, + }); Ok(report) } @@ -156,9 +201,10 @@ impl Governor { } if self.inner.cfg.heal && r.swapped_bytes >= 16 * MIB && self.level() == Level::Normal { let budget = self.inner.cfg.heal_bytes_per_tick.min(r.swapped_bytes.max(GIB)); - let ok = self.inner.src.facts() - .effective_available() - .is_some_and(|a| a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve); + let ok = + self.inner.src.facts().effective_available().is_some_and(|a| { + a.saturating_sub(budget.min(r.swapped_bytes)) >= policy.soft_floor + policy.reserve + }); if ok { let mut done = 0; match g.extents.clone() { @@ -170,7 +216,9 @@ impl Governor { g.cursor = 0; } let want = (256 * MIB).min(budget - done); - let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { break }; + let Some((offset, piece)) = crate::lock::compact_piece(&spans, g.cursor, want) else { + break; + }; // whole pages; the last page of the last extent may be partial and is rounded up by the kernel let n = if g.cursor + piece == total || piece < 4096 { piece } else { piece / 4096 * 4096 }; if g.mapping.populate(offset, n).is_err() { diff --git a/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs index d52d6374..aa43f458 100644 --- a/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs +++ b/crates/leleka-memory/src/governor/impl_governor/impl_governor_4.rs @@ -3,10 +3,7 @@ #[allow(unused_imports)] use super::*; - - impl Governor { - // ---- report ----------------------------------------------------------------------------------------------- pub fn report(&self) -> serde_json::Value { @@ -18,7 +15,9 @@ impl Governor { let planned = self.inner.prefix_planned.load(Ordering::Acquire); let target = self.inner.prefix_target.load(Ordering::Acquire); #[cfg(all(target_os = "linux", target_pointer_width = "64"))] - let archive = lock(&self.inner.guarded).as_ref().map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); + let archive = lock(&self.inner.guarded) + .as_ref() + .map(|g| json!({"lock": g.report, "residency": g.last, "heal": {"cursor": g.cursor}})); #[cfg(not(all(target_os = "linux", target_pointer_width = "64")))] let archive: Option = None; json!({ diff --git a/crates/leleka-memory/src/governor/impl_governorconfig.rs b/crates/leleka-memory/src/governor/impl_governorconfig.rs index 2862ab45..724d0c60 100644 --- a/crates/leleka-memory/src/governor/impl_governorconfig.rs +++ b/crates/leleka-memory/src/governor/impl_governorconfig.rs @@ -3,10 +3,17 @@ #[allow(unused_imports)] use super::*; - impl GovernorConfig { pub fn new(policy: Policy) -> Self { - Self { policy, sample_interval_ms: 1000, lock_mode: LockMode::Try, heal: true, heal_bytes_per_tick: GIB, residency_every_ms: 30_000, log: true } + Self { + policy, + sample_interval_ms: 1000, + lock_mode: LockMode::Try, + heal: true, + heal_bytes_per_tick: GIB, + residency_every_ms: 30_000, + log: true, + } } /// Defaults for the host, then the `LELEKA_MEMORY_*` overrides. An unparsable override is an error naming the variable @@ -43,7 +50,13 @@ impl GovernorConfig { let float = |name: &str| -> Result, String> { match env(name) { None => Ok(None), - Some(v) => v.trim().parse::().ok().filter(|f| f.is_finite() && *f >= 0.0).map(Some).ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), + Some(v) => v + .trim() + .parse::() + .ok() + .filter(|f| f.is_finite() && *f >= 0.0) + .map(Some) + .ok_or_else(|| format!("{name}={v:?} is not a non-negative number")), } }; if let Some(v) = number("LELEKA_MEMORY_PSI_GUARD_MIB")? { @@ -68,7 +81,8 @@ impl GovernorConfig { cfg.residency_every_ms = v.saturating_mul(1000).max(1000); } if let Some(v) = env("LELEKA_MEMORY_LOCK") { - cfg.lock_mode = LockMode::parse(v.trim()).ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; + cfg.lock_mode = LockMode::parse(v.trim()) + .ok_or_else(|| format!("LELEKA_MEMORY_LOCK={v:?} must be off, try or require"))?; } if cfg.policy.hard_floor >= cfg.policy.soft_floor { return Err(format!( diff --git a/crates/leleka-memory/src/governor/pressure_tests.rs b/crates/leleka-memory/src/governor/pressure_tests.rs index 281b47b6..e554e84f 100644 --- a/crates/leleka-memory/src/governor/pressure_tests.rs +++ b/crates/leleka-memory/src/governor/pressure_tests.rs @@ -5,22 +5,14 @@ use super::*; use crate::pressure_port::ScriptedPressure; use leleka_obs::time::ManualClock; -const SHAPE: RequestShape = RequestShape { - prompt_tokens: 1000, - max_new_tokens: 100, - max_context: 262_144, -}; +const SHAPE: RequestShape = RequestShape { prompt_tokens: 1000, max_new_tokens: 100, max_context: 262_144 }; /// A governor whose host reads `available_mib` one reading per probe, on a clock that stands still. fn scripted(available_mib: &[u64]) -> (Governor, ManualClock) { let clock = ManualClock::new(); let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); cfg.log = false; - let g = Governor::with_parts( - cfg, - ScriptedPressure::available_mib(available_mib), - AnyClock::from(clock.clone()), - ); + let g = Governor::with_parts(cfg, ScriptedPressure::available_mib(available_mib), AnyClock::from(clock.clone())); g.set_prefix_budget(8 * GIB); (g, clock) } @@ -41,28 +33,18 @@ fn pressure_that_rises_steps_up_at_once_and_one_level_at_a_time_down_after_three let (g, _clock) = scripted(&script); let seen = levels_after(&g, script.len() as u64); use Level::{Normal, Reject, Shed}; - assert_eq!( - seen, - [ - Normal, Shed, Reject, Reject, Reject, Shed, Shed, Shed, Normal - ] - ); + assert_eq!(seen, [Normal, Shed, Reject, Reject, Reject, Shed, Shed, Shed, Normal]); assert_eq!(g.report()["counters"]["level_changes"], 4); } #[test] fn a_host_that_flaps_around_the_soft_floor_never_steps_down() { - let script: Vec = (0..10) - .map(|i| if i % 2 == 0 { 3000 } else { 20_000 }) - .collect(); + let script: Vec = (0..10).map(|i| if i % 2 == 0 { 3000 } else { 20_000 }).collect(); let (g, _clock) = scripted(&script); let seen = levels_after(&g, script.len() as u64); assert!(seen.iter().all(|level| *level == Level::Shed), "{seen:?}"); let report = g.report(); - assert_eq!( - report["counters"]["level_changes"], 1, - "one transition, then held: {report}" - ); + assert_eq!(report["counters"]["level_changes"], 1, "one transition, then held: {report}"); assert_eq!(report["counters"]["samples"], 10); } @@ -79,17 +61,9 @@ fn the_prefix_budget_steps_down_a_quarter_once_per_second_of_the_clock() { let (g, clock) = scripted(&[3000]); g.sample_at(0); assert_eq!(g.directive(8 * GIB).prefix_budget, Some(6 * GIB)); - assert_eq!( - g.directive(6 * GIB).prefix_budget, - Some(6 * GIB), - "no second step in the same instant" - ); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "no second step in the same instant"); clock.advance_ms(999); - assert_eq!( - g.directive(6 * GIB).prefix_budget, - Some(6 * GIB), - "999 ms is not a second" - ); + assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB), "999 ms is not a second"); clock.advance_ms(1); assert_eq!(g.directive(6 * GIB).prefix_budget, Some(6 * GIB / 4 * 3)); assert_eq!(g.report()["counters"]["shed_steps"], 2); @@ -136,9 +110,7 @@ fn admission_follows_the_level_the_scripted_host_drives_it_to() { assert_eq!(g.level(), Level::Shed); assert_eq!(g.admit(&SHAPE), Admission::Admit, "shedding still serves"); g.sample_at(3000); - let Admission::Refuse(refusal) = g.admit(&SHAPE) else { - panic!("rejecting must refuse") - }; + let Admission::Refuse(refusal) = g.admit(&SHAPE) else { panic!("rejecting must refuse") }; assert_eq!((refusal.status, refusal.code), (503, "memory_pressure")); assert!(refusal.retry_after_secs >= 5, "{refusal:?}"); let report = g.report(); @@ -150,29 +122,15 @@ fn admission_follows_the_level_the_scripted_host_drives_it_to() { fn a_request_whose_own_transient_would_cross_the_hard_floor_is_refused_on_the_scripted_host() { // 2.1 GiB available: above the 2 GiB hard floor, but the 256 MiB transient of one request would cross it let (g, _clock) = scripted(&[2150]); - let Admission::Refuse(refusal) = g.admit(&SHAPE) else { - panic!("must refuse") - }; + let Admission::Refuse(refusal) = g.admit(&SHAPE) else { panic!("must refuse") }; assert_eq!(refusal.code, "memory_pressure"); - assert!( - refusal.message.contains("hard floor"), - "{}", - refusal.message - ); + assert!(refusal.message.contains("hard floor"), "{}", refusal.message); } #[test] fn a_context_that_can_never_fit_is_a_400_and_does_not_read_the_host() { let (g, _clock) = scripted(&[20_000]); - let Admission::Refuse(refusal) = g.admit(&RequestShape { - prompt_tokens: 262_144, - ..SHAPE - }) else { - panic!() - }; - assert_eq!( - (refusal.status, refusal.code), - (400, "context_length_exceeded") - ); + let Admission::Refuse(refusal) = g.admit(&RequestShape { prompt_tokens: 262_144, ..SHAPE }) else { panic!() }; + assert_eq!((refusal.status, refusal.code), (400, "context_length_exceeded")); assert_eq!(g.report()["counters"]["rejected_context"], 1); } diff --git a/crates/leleka-memory/src/governor/tests.rs b/crates/leleka-memory/src/governor/tests.rs index 8273485d..76b0e5d8 100644 --- a/crates/leleka-memory/src/governor/tests.rs +++ b/crates/leleka-memory/src/governor/tests.rs @@ -16,12 +16,26 @@ impl ProcSource for Live { } fn live(avail_gib: u64) -> Arc { let mut p = FakeProc::default(); - p.set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_gib * 1024 * 1024)); + p.set( + "/proc/meminfo", + &format!( + "MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", + 121 * 1024 * 1024, + avail_gib * 1024 * 1024 + ), + ); p.set("/proc/self/status", "VmRSS: 1000 kB\nThreads: 3\n"); Arc::new(Live(RwLock::new(p))) } fn set_avail(h: &Live, avail_mib: u64) { - h.0.write().unwrap().set("/proc/meminfo", &format!("MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", 121 * 1024 * 1024, avail_mib * 1024)); + h.0.write().unwrap().set( + "/proc/meminfo", + &format!( + "MemTotal: {} kB\nMemAvailable: {} kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", + 121 * 1024 * 1024, + avail_mib * 1024 + ), + ); } fn governor(host: Arc) -> Governor { let mut cfg = GovernorConfig::new(Policy::for_host(121 * GIB, false)); @@ -40,7 +54,10 @@ fn requests_are_admitted_with_room_and_context_errors_are_400s() { let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: 262_144, ..SHAPE }) else { panic!() }; assert_eq!((r.status, r.code), (400, "context_length_exceeded")); assert!(r.message.contains("262144"), "{}", r.message); - let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: u64::MAX, max_new_tokens: u64::MAX, ..SHAPE }) else { panic!() }; + let Admission::Refuse(r) = g.admit(&RequestShape { prompt_tokens: u64::MAX, max_new_tokens: u64::MAX, ..SHAPE }) + else { + panic!() + }; assert_eq!(r.status, 400, "overflow must not wrap into an admit"); } @@ -48,7 +65,10 @@ fn requests_are_admitted_with_room_and_context_errors_are_400s() { fn shedding_runs_in_order_prefix_cache_first_then_reject_with_retry_after() { let h = live(20); let g = governor(h.clone()); - assert_eq!(g.directive(8 * GIB), ShedDirective { level: Level::Normal, prefix_budget: None, drop_conversation: false }); + assert_eq!( + g.directive(8 * GIB), + ShedDirective { level: Level::Normal, prefix_budget: None, drop_conversation: false } + ); // below the 4 GiB soft floor: shed in steps of a quarter, one step per second set_avail(&h, 3 * 1024); let t = g.sample_at(1000).unwrap(); @@ -120,8 +140,20 @@ fn env_overrides_are_validated_not_ignored() { let owned: Vec<(String, String)> = pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); move |k: &str| owned.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone()) }; - let cfg = GovernorConfig::from_env(121 * GIB, false, &env(&[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), ("LELEKA_MEMORY_LOCK", "require")])).unwrap(); - assert_eq!((cfg.policy.soft_floor, cfg.policy.hard_floor, cfg.lock_mode), (19000 * MIB, 16000 * MIB, LockMode::Require)); + let cfg = GovernorConfig::from_env( + 121 * GIB, + false, + &env(&[ + ("LELEKA_MEMORY_SOFT_FLOOR_MIB", "19000"), + ("LELEKA_MEMORY_HARD_FLOOR_MIB", "16000"), + ("LELEKA_MEMORY_LOCK", "require"), + ]), + ) + .unwrap(); + assert_eq!( + (cfg.policy.soft_floor, cfg.policy.hard_floor, cfg.lock_mode), + (19000 * MIB, 16000 * MIB, LockMode::Require) + ); for bad in [ &[("LELEKA_MEMORY_SOFT_FLOOR_MIB", "lots")][..], &[("LELEKA_MEMORY_LOCK", "maybe")][..], diff --git a/crates/leleka-memory/src/heap.rs b/crates/leleka-memory/src/heap.rs index 5ab93684..658ce64a 100644 --- a/crates/leleka-memory/src/heap.rs +++ b/crates/leleka-memory/src/heap.rs @@ -32,7 +32,13 @@ pub struct HeapStats { pub fn stats() -> Option { // SAFETY: `mallinfo2` takes no arguments and returns a plain struct by value; it reads the allocator's counters under its locks. let m = unsafe { libc::mallinfo2() }; - Some(HeapStats { arena: m.arena as u64, in_use: m.uordblks as u64, free: m.fordblks as u64, mmapped: m.hblkhd as u64, releasable: m.keepcost as u64 }) + Some(HeapStats { + arena: m.arena as u64, + in_use: m.uordblks as u64, + free: m.fordblks as u64, + mmapped: m.hblkhd as u64, + releasable: m.keepcost as u64, + }) } #[cfg(not(all(target_os = "linux", target_env = "gnu", target_pointer_width = "64")))] diff --git a/crates/leleka-memory/src/host.rs b/crates/leleka-memory/src/host.rs index 74ded396..3d419a1e 100644 --- a/crates/leleka-memory/src/host.rs +++ b/crates/leleka-memory/src/host.rs @@ -196,7 +196,9 @@ fn probe_cgroup_v1(src: &dyn ProcSource, proc_cgroup: &str) -> Option Option { let tightest = levels.iter().filter_map(|l| l.limit.map(|v| (v, l.path.clone()))).min_by_key(|(v, _)| *v); let headroom = levels.iter().filter_map(|l| l.headroom).min(); let own = format!("{CGROUP_ROOT}{}", if rel == "/" { String::new() } else { rel.clone() }); - let swap_max = src.read(&format!("{own}/memory.swap.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)).flatten(); + let swap_max = + src.read(&format!("{own}/memory.swap.max")).ok().and_then(|t| procfs::parse_cgroup_limit(&t)).flatten(); let events = src.read(&format!("{own}/memory.events")).ok().and_then(|t| procfs::parse_cgroup_events(&t)); Some(CgroupFacts { path: rel, levels, limit: tightest, headroom, swap_max, events }) } diff --git a/crates/leleka-memory/src/inventory.rs b/crates/leleka-memory/src/inventory.rs index 492b1e2a..892cba08 100644 --- a/crates/leleka-memory/src/inventory.rs +++ b/crates/leleka-memory/src/inventory.rs @@ -215,7 +215,14 @@ impl Inventory { /// The startup table: one row per class, grouped by space, fixed-width. pub fn table(&self) -> String { let mut rows = self.entries(); - rows.sort_by(|a, b| (a.space, a.when, a.component.as_str(), a.class.as_str()).cmp(&(b.space, b.when, b.component.as_str(), b.class.as_str()))); + rows.sort_by(|a, b| { + (a.space, a.when, a.component.as_str(), a.class.as_str()).cmp(&( + b.space, + b.when, + b.component.as_str(), + b.class.as_str(), + )) + }); let mut out = String::new(); out.push_str(&format!( "{:<15} {:<11} {:<34} {:>11} {:>11} {:>11} {:>5} {}\n", @@ -259,7 +266,8 @@ mod tests { use super::*; fn kv() -> Entry { - Entry::new("kv", "host_pinned", Space::HostPinned, When::Startup, "12 layers x cells x 1056 B").bytes(3_321_901_056) + Entry::new("kv", "host_pinned", Space::HostPinned, When::Startup, "12 layers x cells x 1056 B") + .bytes(3_321_901_056) } #[test] @@ -309,7 +317,10 @@ mod tests { inv.set(kv()); inv.set(Entry::new("vram", "kv_resident", Space::Device, When::Startup, "slots x 4244 B").bytes(1 << 30)); let t = inv.table(); - assert!(t.contains("kv.host_pinned") && t.contains("vram.kv_resident") && t.contains("host RAM (accounted)"), "{t}"); + assert!( + t.contains("kv.host_pinned") && t.contains("vram.kv_resident") && t.contains("host RAM (accounted)"), + "{t}" + ); let j = inv.to_json(); assert_eq!(j["device_bytes"], 1u64 << 30); assert_eq!(j["entries"].as_array().unwrap().len(), 2); diff --git a/crates/leleka-memory/src/ledger.rs b/crates/leleka-memory/src/ledger.rs index 42359f4e..8b0d4525 100644 --- a/crates/leleka-memory/src/ledger.rs +++ b/crates/leleka-memory/src/ledger.rs @@ -148,16 +148,25 @@ mod tests { use crate::host::FakeProc; fn proc(rss_kib: u64, pin_kib: u64, avail_kib: u64, shmem_kib: u64) -> FakeProc { - FakeProc::default() - .with("/proc/self/status", &format!("VmRSS: {rss_kib} kB\nVmPin: {pin_kib} kB\n")) - .with("/proc/meminfo", &format!("MemTotal: 100000000 kB\nMemAvailable: {avail_kib} kB\nShmem: {shmem_kib} kB\n")) + FakeProc::default().with("/proc/self/status", &format!("VmRSS: {rss_kib} kB\nVmPin: {pin_kib} kB\n")).with( + "/proc/meminfo", + &format!("MemTotal: 100000000 kB\nMemAvailable: {avail_kib} kB\nShmem: {shmem_kib} kB\n"), + ) } #[test] fn a_stage_records_signed_deltas_of_host_and_device() { let led = Ledger::new(); - let open = led.begin("expert bank", &proc(1000, 0, 90_000_000, 5000), Some(DeviceSample { accounted: 100, free: 1000, total: 2000 })); - let stage = led.end(open, &proc(51_000, 50_000, 40_000_000, 5000), Some(DeviceSample { accounted: 300, free: 700, total: 2000 })); + let open = led.begin( + "expert bank", + &proc(1000, 0, 90_000_000, 5000), + Some(DeviceSample { accounted: 100, free: 1000, total: 2000 }), + ); + let stage = led.end( + open, + &proc(51_000, 50_000, 40_000_000, 5000), + Some(DeviceSample { accounted: 300, free: 700, total: 2000 }), + ); assert_eq!(stage.rss, 50_000 * 1024); assert_eq!(stage.pinned, 50_000 * 1024); assert_eq!(stage.available, -50_000_000 * 1024); diff --git a/crates/leleka-memory/src/lib.rs b/crates/leleka-memory/src/lib.rs index cc0240cd..94d92b1f 100644 --- a/crates/leleka-memory/src/lib.rs +++ b/crates/leleka-memory/src/lib.rs @@ -20,9 +20,14 @@ pub mod smi; pub mod telemetry; pub mod winproc; -pub use governor::{Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, published_report}; +pub use governor::{ + Admission, Governor, GovernorConfig, LockReport, Refuse, RequestShape, SamplerGuard, ShedDirective, + published_report, +}; pub use host::{FakeProc, HostFacts, ProcSource, RealProc}; pub use inventory::{Entry, Inventory, Space, When}; -pub use plan::{CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram}; +pub use plan::{ + CacheWish, FixedItem, GIB, KarForm, MIB, Plan, PlanInput, Policy, Refusal, VramFacts, VramPlan, check_vram, +}; pub use pressure::Level; pub use pressure_port::{MemoryPressure, ProcPressure, ScriptedPressure}; diff --git a/crates/leleka-memory/src/lock.rs b/crates/leleka-memory/src/lock.rs index cfb43270..79f4cafc 100644 --- a/crates/leleka-memory/src/lock.rs +++ b/crates/leleka-memory/src/lock.rs @@ -47,10 +47,18 @@ pub enum LockDecision { #[derive(Clone, Debug, PartialEq, Eq, Serialize)] #[serde(tag = "outcome", rename_all = "snake_case")] pub enum LockOutcome { - Locked { bytes: u64 }, + Locked { + bytes: u64, + }, /// Some chunks locked before the kernel (or the guard) said stop. - Partial { locked: u64, wanted: u64, why: String }, - NotAttempted { why: String }, + Partial { + locked: u64, + wanted: u64, + why: String, + }, + NotAttempted { + why: String, + }, } /// The swap state of the mapping. diff --git a/crates/leleka-memory/src/lock/impl_lockmode.rs b/crates/leleka-memory/src/lock/impl_lockmode.rs index 22c148b0..f49b5f6c 100644 --- a/crates/leleka-memory/src/lock/impl_lockmode.rs +++ b/crates/leleka-memory/src/lock/impl_lockmode.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl LockMode { pub fn parse(text: &str) -> Option { match text { @@ -54,10 +53,12 @@ impl LockOutcome { /// Find the mapping that starts at `start` in `smaps` text and report its swap. pub fn residency_from_smaps(smaps: &str, start: u64, len: u64) -> Option { - procfs::parse_smaps(smaps) - .into_iter() - .find(|e| e.start == start && e.end - e.start >= len) - .map(|e| Residency { mapping_bytes: e.end - e.start, swapped_bytes: e.swap, rss_bytes: e.rss, locked_bytes: e.locked }) + procfs::parse_smaps(smaps).into_iter().find(|e| e.start == start && e.end - e.start >= len).map(|e| Residency { + mapping_bytes: e.end - e.start, + swapped_bytes: e.swap, + rss_bytes: e.rss, + locked_bytes: e.locked, + }) } /// Total bytes of a list of spans. @@ -71,7 +72,9 @@ pub fn check_spans(spans: &[Span], len: u64) -> Result<(), String> { for (i, (offset, n)) in spans.iter().enumerate() { let end = offset.checked_add(*n).ok_or_else(|| format!("span {i} overflows"))?; if !offset.is_multiple_of(PAGE) || *n == 0 || end > len || *offset < previous_end { - return Err(format!("span {i} ({offset}+{n}) is unaligned, empty, out of order or outside the mapping of {len} bytes")); + return Err(format!( + "span {i} ({offset}+{n}) is unaligned, empty, out of order or outside the mapping of {len} bytes" + )); } previous_end = end; } diff --git a/crates/leleka-memory/src/lock/sys.rs b/crates/leleka-memory/src/lock/sys.rs index acfb9ab2..c4274096 100644 --- a/crates/leleka-memory/src/lock/sys.rs +++ b/crates/leleka-memory/src/lock/sys.rs @@ -48,7 +48,8 @@ impl FdMapping { } // SAFETY: a fresh anonymous-address mapping request (null hint, no MAP_FIXED): it cannot replace any existing // mapping; `fd` is a live descriptor for the duration of the call; the result is checked against MAP_FAILED. - let addr = unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) }; + let addr = + unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ, libc::MAP_SHARED, fd.as_raw_fd(), 0) }; if addr == libc::MAP_FAILED { return Err(io::Error::last_os_error()); } @@ -87,7 +88,11 @@ impl FdMapping { while offset < total { let n = chunk.min(total - offset); if !allow(n) { - return LockOutcome::Partial { locked: self.locked, wanted: total, why: "host memory guard refused the next chunk".into() }; + return LockOutcome::Partial { + locked: self.locked, + wanted: total, + why: "host memory guard refused the next chunk".into(), + }; } let (ptr, n_usize) = match self.range(offset, n) { Ok(r) => r, @@ -107,7 +112,12 @@ impl FdMapping { /// each; stop at the first refusal. The holes between the spans are never touched: `mlock` of a hole in a shmem file /// allocates zero pages for it (the sparse copy would silently become the full 55 GB again), so a range outside the /// spans is not representable here. `check_spans` runs first. The counter `locked_bytes` is the sum of the locked spans. - pub fn lock_ranges(&mut self, spans: &[super::Span], chunk: u64, mut allow: impl FnMut(u64) -> bool) -> LockOutcome { + pub fn lock_ranges( + &mut self, + spans: &[super::Span], + chunk: u64, + mut allow: impl FnMut(u64) -> bool, + ) -> LockOutcome { let wanted = super::spans_bytes(spans); if let Err(why) = super::check_spans(spans, self.len as u64) { return LockOutcome::Partial { locked: 0, wanted, why }; @@ -119,7 +129,11 @@ impl FdMapping { while done < span_len { let n = chunk.min(span_len - done); if !allow(n) { - return LockOutcome::Partial { locked, wanted, why: "host memory guard refused the next chunk".into() }; + return LockOutcome::Partial { + locked, + wanted, + why: "host memory guard refused the next chunk".into(), + }; } let (ptr, n_usize) = match self.range(span_offset + done, n) { Ok(r) => r, @@ -199,7 +213,11 @@ mod tests { } fn tempfile_in_target() -> std::fs::File { // an unlinked file under the system temp dir - let path = std::env::temp_dir().join(format!("leleka-memory-lock-{}-{:?}", std::process::id(), std::thread::current().id())); + let path = std::env::temp_dir().join(format!( + "leleka-memory-lock-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(true).open(&path).unwrap(); let _ = std::fs::remove_file(&path); f @@ -341,7 +359,10 @@ mod tests { calls += 1; calls <= 3 }); - assert!(matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), "{outcome:?}"); + assert!( + matches!(outcome, LockOutcome::Partial { locked, wanted, .. } if locked == 12 * PAGE && wanted == 16 * PAGE), + "{outcome:?}" + ); assert_eq!(m.locked_bytes(), 12 * PAGE); m.unlock(); assert_eq!(m.locked_bytes(), 0); diff --git a/crates/leleka-memory/src/lock/tests.rs b/crates/leleka-memory/src/lock/tests.rs index 1e580c93..821fa22a 100644 --- a/crates/leleka-memory/src/lock/tests.rs +++ b/crates/leleka-memory/src/lock/tests.rs @@ -14,14 +14,27 @@ fn the_5090_server_default_limit_cannot_lock_the_55gb_archive_and_says_how_to() let LockDecision::Insufficient { need, soft, hard, advice } = d else { panic!("{d:?}") }; assert!(need > 55 * G && soft == 8 << 20 && hard == 8 << 20); let text = advice.join("\n"); - assert!(text.contains("LimitMEMLOCK=infinity") && text.contains("CAP_IPC_LOCK") && text.contains("MADV_POPULATE_READ"), "{text}"); + assert!( + text.contains("LimitMEMLOCK=infinity") && text.contains("CAP_IPC_LOCK") && text.contains("MADV_POPULATE_READ"), + "{text}" + ); } #[test] fn unlimited_limits_or_the_capability_allow_the_lock() { - assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((u64::MAX, u64::MAX)), &status(Some(0), 0)), LockDecision::Attempt { raise_soft_to: None }); - assert_eq!(plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(CAP_IPC_LOCK_BIT), 0)), LockDecision::Attempt { raise_soft_to: None }); - assert_eq!(plan_lock(LockMode::Try, 55 * G, None, &status(None, 0)), LockDecision::Attempt { raise_soft_to: None }, "unknown limits: try and see"); + assert_eq!( + plan_lock(LockMode::Try, 55 * G, Some((u64::MAX, u64::MAX)), &status(Some(0), 0)), + LockDecision::Attempt { raise_soft_to: None } + ); + assert_eq!( + plan_lock(LockMode::Try, 55 * G, Some((8 << 20, 8 << 20)), &status(Some(CAP_IPC_LOCK_BIT), 0)), + LockDecision::Attempt { raise_soft_to: None } + ); + assert_eq!( + plan_lock(LockMode::Try, 55 * G, None, &status(None, 0)), + LockDecision::Attempt { raise_soft_to: None }, + "unknown limits: try and see" + ); } #[test] diff --git a/crates/leleka-memory/src/plan/auto_prefix_budget.rs b/crates/leleka-memory/src/plan/auto_prefix_budget.rs index 27b92f6b..f3c8fcde 100644 --- a/crates/leleka-memory/src/plan/auto_prefix_budget.rs +++ b/crates/leleka-memory/src/plan/auto_prefix_budget.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The `auto` prefix budget recomputed from the memory available when the stack opens (after the expert bank and the /// other fixed items are really resident): the same rule as [`plan`] with `fixed = 0`. pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pinned: u64) -> u64 { @@ -19,7 +18,13 @@ pub fn auto_prefix_budget(available: Option, policy: &Policy, complement_pi /// Unlike [`auto_prefix_budget`] the result does not depend on how much memory is free beyond the wish: freeing RAM /// elsewhere (a smaller archive copy, a smaller expert bank) cannot make the store bigger than the operator's number. /// Returns the granted bytes and the elastic memory it was clamped against. -pub fn explicit_prefix_budget(wish: u64, available: Option, policy: &Policy, complement_pending: u64) -> (u64, u64) { - let elastic = available.map_or(0, |a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)); +pub fn explicit_prefix_budget( + wish: u64, + available: Option, + policy: &Policy, + complement_pending: u64, +) -> (u64, u64) { + let elastic = available + .map_or(0, |a| a.saturating_sub(policy.soft_floor + policy.reserve).saturating_sub(complement_pending)); (wish.min(elastic) / MIB * MIB, elastic) } diff --git a/crates/leleka-memory/src/plan/impl_policy.rs b/crates/leleka-memory/src/plan/impl_policy.rs index f2fff205..b892cb71 100644 --- a/crates/leleka-memory/src/plan/impl_policy.rs +++ b/crates/leleka-memory/src/plan/impl_policy.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Policy { /// Below this much available memory a cache stops admitting new entries (before anything has to be shed): `soft_floor + reserve`. pub fn admit_floor(&self) -> u64 { @@ -57,24 +56,31 @@ pub fn gib(bytes: u64) -> String { /// The device check, run when the device is first visible: refuses when a measured fixed footprint does not fit in the free /// VRAM, otherwise only notes a free VRAM below the declared budget. The note (if any) is returned. -pub fn check_vram(policy: &Policy, vram: VramFacts, budget: u64, fixed_estimate: Option) -> Result<(VramPlan, Option), Refusal> { +pub fn check_vram( + policy: &Policy, + vram: VramFacts, + budget: u64, + fixed_estimate: Option, +) -> Result<(VramPlan, Option), Refusal> { let plan = VramPlan { free: vram.free, total: vram.total, budget, headroom: policy.vram_headroom }; if let Some(estimate) = fixed_estimate - && plan.free < estimate.saturating_add(plan.headroom) && policy.enforce { - return Err(Refusal { - code: "vram", - message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), - numbers: vec![ - ("vram free".into(), plan.free), - ("vram fixed footprint".into(), estimate), - ("vram headroom".into(), plan.headroom), - ], - advice: vec![ - "stop the other GPU processes (nvidia-smi)".into(), - "lower --gpu-budget / the expert slots / --kv-resident".into(), - ], - }); - } + && plan.free < estimate.saturating_add(plan.headroom) + && policy.enforce + { + return Err(Refusal { + code: "vram", + message: format!("the device footprint does not fit: {} free of {} total", gib(plan.free), gib(plan.total)), + numbers: vec![ + ("vram free".into(), plan.free), + ("vram fixed footprint".into(), estimate), + ("vram headroom".into(), plan.headroom), + ], + advice: vec![ + "stop the other GPU processes (nvidia-smi)".into(), + "lower --gpu-budget / the expert slots / --kv-resident".into(), + ], + }); + } let note = (plan.free < plan.budget).then(|| { format!( "VRAM free {} is below the declared --gpu-budget {}: the stack may run out of device memory while it opens", @@ -103,7 +109,10 @@ pub fn plan(input: &PlanInput) -> Result { None => None, }; let Some(available) = input.host.effective_available() else { - notes.push("host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)".into()); + notes.push( + "host memory telemetry is unavailable (MemAvailable): caches are off and the monitor sheds (fail closed)" + .into(), + ); return Ok(Plan { available_before: None, kar_to_create, @@ -139,10 +148,7 @@ pub fn plan(input: &PlanInput) -> Result { if input.host.cgroup.as_ref().is_some_and(|c| c.limit.is_some()) { advice.push("raise the cgroup limit (memory.max / systemd MemoryMax=) of the service".into()); } - let mut numbers = vec![ - ("available".to_owned(), available), - ("fixed host footprint".to_owned(), fixed_bytes), - ]; + let mut numbers = vec![("available".to_owned(), available), ("fixed host footprint".to_owned(), fixed_bytes)]; if kar_to_create > 0 { numbers.push(("sealed KAR memfd to create".to_owned(), kar_to_create)); } @@ -173,7 +179,11 @@ pub fn plan(input: &PlanInput) -> Result { if let Some(wish) = input.resident_complement { complement = wish.min(elastic); if complement < wish { - notes.push(format!("resident complement clamped from {} to {} (elastic memory)", gib(wish), gib(complement))); + notes.push(format!( + "resident complement clamped from {} to {} (elastic memory)", + gib(wish), + gib(complement) + )); } elastic -= complement; } diff --git a/crates/leleka-memory/src/plan/tests.rs b/crates/leleka-memory/src/plan/tests.rs index 949a02fc..ee81d149 100644 --- a/crates/leleka-memory/src/plan/tests.rs +++ b/crates/leleka-memory/src/plan/tests.rs @@ -197,7 +197,12 @@ fn an_explicit_cap_never_grows_when_ram_is_freed_but_auto_does() { let after = before + 36_600 * MIB; let (granted_before, _) = explicit_prefix_budget(cap, Some(before), &p, 0); let (granted_after, elastic_after) = explicit_prefix_budget(cap, Some(after), &p, 0); - assert_eq!(granted_before, cap - cap % MIB, "inside the cap today: the cap is the budget (auto would give {} MiB)", auto_prefix_budget(Some(before), &p, 0) >> 20); + assert_eq!( + granted_before, + cap - cap % MIB, + "inside the cap today: the cap is the budget (auto would give {} MiB)", + auto_prefix_budget(Some(before), &p, 0) >> 20 + ); assert_eq!(granted_after, cap, "freed RAM does not grow an explicit cap"); assert!(elastic_after > 40 * GIB); // the hazard the cap exists for: auto would hand the freed memory to the cache diff --git a/crates/leleka-memory/src/pressure.rs b/crates/leleka-memory/src/pressure.rs index efe37ca8..ceedcf87 100644 --- a/crates/leleka-memory/src/pressure.rs +++ b/crates/leleka-memory/src/pressure.rs @@ -89,7 +89,14 @@ pub const CALM_SAMPLES: u32 = 3; impl Monitor { pub fn new(policy: Policy) -> Self { - Self { policy, level: Level::Normal, calm: 0, prev_events: None, prev_swap: None, observed: Observed::default() } + Self { + policy, + level: Level::Normal, + calm: 0, + prev_events: None, + prev_swap: None, + observed: Observed::default(), + } } pub fn level(&self) -> Level { self.level @@ -131,9 +138,23 @@ impl Monitor { let at = |floor: u64| a < floor; let at_relaxed = |floor: u64| a < floor.saturating_add(h); if at(hard) { - raise(Level::Reject, Level::Reject, format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Reject, + Level::Reject, + format!("available {} MiB below the hard floor {} MiB", a >> 20, hard >> 20), + &mut level, + &mut why, + &mut relaxed_level, + ); } else if at(soft) { - raise(Level::Shed, Level::Shed, format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Shed, + Level::Shed, + format!("available {} MiB below the soft floor {} MiB", a >> 20, soft >> 20), + &mut level, + &mut why, + &mut relaxed_level, + ); } // what the relaxed (stepping-down) view still holds let r = if at_relaxed(hard) { @@ -154,9 +175,23 @@ impl Monitor { self.observed.psi_some_avg10 = Some(psi.some.avg10); self.observed.psi_full_avg10 = Some(psi.full.avg10); if psi.full.avg10 >= p.psi_full_reject { - raise(Level::Reject, Level::Reject, format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Reject, + Level::Reject, + format!("PSI full avg10 {:.1}% (limit {:.1}%)", psi.full.avg10, p.psi_full_reject), + &mut level, + &mut why, + &mut relaxed_level, + ); } else if psi.some.avg10 >= p.psi_some_shed { - raise(Level::Shed, Level::Shed, format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Shed, + Level::Shed, + format!("PSI some avg10 {:.1}% (limit {:.1}%)", psi.some.avg10, p.psi_some_shed), + &mut level, + &mut why, + &mut relaxed_level, + ); } // PSI avg10 decays smoothly; stepping down needs it clearly below the limit if psi.full.avg10 >= p.psi_full_reject / 2.0 { @@ -175,12 +210,22 @@ impl Monitor { self.observed.cgroup_max_delta = d(now.max, before.max); self.observed.cgroup_oom_delta = d(now.oom, before.oom).max(d(now.oom_kill, before.oom_kill)); if self.observed.cgroup_oom_delta > 0 { - raise(Level::Reject, Level::Reject, format!("cgroup oom events +{}", self.observed.cgroup_oom_delta), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Reject, + Level::Reject, + format!("cgroup oom events +{}", self.observed.cgroup_oom_delta), + &mut level, + &mut why, + &mut relaxed_level, + ); } else if self.observed.cgroup_max_delta > 0 || self.observed.cgroup_high_delta > 0 { raise( Level::Shed, Level::Shed, - format!("cgroup memory.high +{} / memory.max +{} events", self.observed.cgroup_high_delta, self.observed.cgroup_max_delta), + format!( + "cgroup memory.high +{} / memory.max +{} events", + self.observed.cgroup_high_delta, self.observed.cgroup_max_delta + ), &mut level, &mut why, &mut relaxed_level, @@ -197,7 +242,14 @@ impl Monitor { let rate = out.saturating_sub(o0) * 1000 / dt; self.observed.swapout_pages_per_s = Some(rate); if rate >= p.swapout_pages_per_s_shed { - raise(Level::Shed, Level::Shed, format!("swap-out {rate} pages/s (limit {})", p.swapout_pages_per_s_shed), &mut level, &mut why, &mut relaxed_level); + raise( + Level::Shed, + Level::Shed, + format!("swap-out {rate} pages/s (limit {})", p.swapout_pages_per_s_shed), + &mut level, + &mut why, + &mut relaxed_level, + ); } if rate >= p.swapout_pages_per_s_shed / 2 { relaxed_level = relaxed_level.max(Level::Shed); @@ -252,123 +304,4 @@ impl Monitor { } #[cfg(test)] -mod tests { - use super::*; - use crate::plan::GIB; - use crate::procfs::PsiLine; - - fn monitor() -> Monitor { - Monitor::new(Policy::for_host(121 * GIB, false)) - } - fn avail(m: &mut Monitor, at_ms: u64, bytes: u64) -> Option { - m.update(&Sample { at_ms, available: Some(bytes), ..Sample::default() }) - } - - #[test] - fn plenty_of_memory_stays_normal() { - let mut m = monitor(); - for i in 0..10 { - assert!(avail(&mut m, i * 1000, 20 * GIB).is_none()); - } - assert_eq!(m.level(), Level::Normal); - } - - #[test] - fn dropping_below_the_floors_escalates_at_once() { - let mut m = monitor(); - let t = avail(&mut m, 0, 3 * GIB).unwrap(); - assert_eq!((t.from, t.to), (Level::Normal, Level::Shed)); - assert!(t.reason.0.contains("soft floor"), "{:?}", t.reason); - let t = avail(&mut m, 1000, GIB).unwrap(); - assert_eq!((t.from, t.to), (Level::Shed, Level::Reject)); - assert_eq!(m.retry_after_secs(), 15); - } - - #[test] - fn stepping_down_needs_calm_samples_and_the_hysteresis_margin() { - let mut m = monitor(); - avail(&mut m, 0, GIB); - assert_eq!(m.level(), Level::Reject); - // just above the hard floor but inside the hysteresis band: stays - for i in 1..10 { - assert!(avail(&mut m, i * 1000, 2 * GIB + GIB / 2).is_none(), "inside the band at sample {i}"); - } - assert_eq!(m.level(), Level::Reject); - // clearly above hard + margin, below soft: steps down to Shed after 3 calm samples - assert!(avail(&mut m, 20_000, 3 * GIB + GIB / 2).is_none()); - assert!(avail(&mut m, 21_000, 3 * GIB + GIB / 2).is_none()); - let t = avail(&mut m, 22_000, 3 * GIB + GIB / 2).unwrap(); - assert_eq!((t.from, t.to), (Level::Reject, Level::Shed)); - // and to Normal only well above the soft floor + margin - for i in 0..2 { - assert!(avail(&mut m, 30_000 + i * 1000, 6 * GIB).is_none()); - } - let t = avail(&mut m, 33_000, 6 * GIB).unwrap(); - assert_eq!(t.to, Level::Normal); - } - - #[test] - fn one_calm_sample_between_bad_ones_does_not_step_down() { - let mut m = monitor(); - avail(&mut m, 0, 3 * GIB); - for i in 0..6u64 { - let a = if i % 2 == 0 { 20 * GIB } else { 3 * GIB }; - avail(&mut m, 1000 * (i + 1), a); - } - assert_eq!(m.level(), Level::Shed); - } - - #[test] - fn unknown_available_memory_holds_shed() { - let mut m = monitor(); - let t = m.update(&Sample::default()).unwrap(); - assert_eq!(t.to, Level::Shed); - assert!(t.reason.0.contains("unknown")); - for i in 1..10 { - assert!(m.update(&Sample { at_ms: i * 1000, ..Sample::default() }).is_none()); - } - assert_eq!(m.level(), Level::Shed); - } - - #[test] - fn psi_stalls_shed_and_reject_independent_of_available_memory() { - let mut m = monitor(); - let psi = |some: f64, full: f64| Some(Psi { some: PsiLine { avg10: some, ..Default::default() }, full: PsiLine { avg10: full, ..Default::default() } }); - // above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free changes nothing - assert!(m.update(&Sample { at_ms: 0, available: Some(30 * GIB), psi: psi(60.0, 20.0), ..Sample::default() }).is_none()); - assert_eq!(m.level(), Level::Normal); - // below it they count, independently of the floors - let t = m.update(&Sample { at_ms: 1000, available: Some(10 * GIB), psi: psi(30.0, 0.0), ..Sample::default() }).unwrap(); - assert_eq!(t.to, Level::Shed); - assert!(t.reason.0.contains("PSI some")); - let t = m.update(&Sample { at_ms: 2000, available: Some(10 * GIB), psi: psi(40.0, 9.0), ..Sample::default() }).unwrap(); - assert_eq!(t.to, Level::Reject); - // a quiet PSI recovers after the calm samples - for i in 0..3 { - m.update(&Sample { at_ms: 3000 + i * 1000, available: Some(10 * GIB), psi: psi(0.0, 0.0), ..Sample::default() }); - } - assert_eq!(m.level(), Level::Shed); - } - - #[test] - fn cgroup_oom_and_high_events_escalate_by_their_delta() { - let mut m = monitor(); - let ev = |high, max, oom, kill| Some(CgroupEvents { low: 0, high, max, oom, oom_kill: kill }); - assert!(m.update(&Sample { at_ms: 0, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }).is_none(), "the first reading is the baseline"); - assert!(m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }).is_none()); - let t = m.update(&Sample { at_ms: 2000, available: Some(30 * GIB), events: ev(6, 5, 0, 0), ..Sample::default() }).unwrap(); - assert_eq!(t.to, Level::Shed); - let t = m.update(&Sample { at_ms: 3000, available: Some(30 * GIB), events: ev(6, 5, 1, 0), ..Sample::default() }).unwrap(); - assert_eq!(t.to, Level::Reject); - assert_eq!(m.observed.cgroup_oom_delta, 1); - } - - #[test] - fn a_swap_out_storm_sheds() { - let mut m = monitor(); - m.update(&Sample { at_ms: 0, available: Some(30 * GIB), pswpout: Some(1000), ..Sample::default() }); - let t = m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), pswpout: Some(1000 + 100_000), ..Sample::default() }).unwrap(); - assert_eq!(t.to, Level::Shed); - assert_eq!(m.observed.swapout_pages_per_s, Some(100_000)); - } -} +mod tests; diff --git a/crates/leleka-memory/src/pressure/tests.rs b/crates/leleka-memory/src/pressure/tests.rs new file mode 100644 index 00000000..57c6973d --- /dev/null +++ b/crates/leleka-memory/src/pressure/tests.rs @@ -0,0 +1,147 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use crate::plan::GIB; +use crate::procfs::PsiLine; + +fn monitor() -> Monitor { + Monitor::new(Policy::for_host(121 * GIB, false)) +} +fn avail(m: &mut Monitor, at_ms: u64, bytes: u64) -> Option { + m.update(&Sample { at_ms, available: Some(bytes), ..Sample::default() }) +} + +#[test] +fn plenty_of_memory_stays_normal() { + let mut m = monitor(); + for i in 0..10 { + assert!(avail(&mut m, i * 1000, 20 * GIB).is_none()); + } + assert_eq!(m.level(), Level::Normal); +} + +#[test] +fn dropping_below_the_floors_escalates_at_once() { + let mut m = monitor(); + let t = avail(&mut m, 0, 3 * GIB).unwrap(); + assert_eq!((t.from, t.to), (Level::Normal, Level::Shed)); + assert!(t.reason.0.contains("soft floor"), "{:?}", t.reason); + let t = avail(&mut m, 1000, GIB).unwrap(); + assert_eq!((t.from, t.to), (Level::Shed, Level::Reject)); + assert_eq!(m.retry_after_secs(), 15); +} + +#[test] +fn stepping_down_needs_calm_samples_and_the_hysteresis_margin() { + let mut m = monitor(); + avail(&mut m, 0, GIB); + assert_eq!(m.level(), Level::Reject); + // just above the hard floor but inside the hysteresis band: stays + for i in 1..10 { + assert!(avail(&mut m, i * 1000, 2 * GIB + GIB / 2).is_none(), "inside the band at sample {i}"); + } + assert_eq!(m.level(), Level::Reject); + // clearly above hard + margin, below soft: steps down to Shed after 3 calm samples + assert!(avail(&mut m, 20_000, 3 * GIB + GIB / 2).is_none()); + assert!(avail(&mut m, 21_000, 3 * GIB + GIB / 2).is_none()); + let t = avail(&mut m, 22_000, 3 * GIB + GIB / 2).unwrap(); + assert_eq!((t.from, t.to), (Level::Reject, Level::Shed)); + // and to Normal only well above the soft floor + margin + for i in 0..2 { + assert!(avail(&mut m, 30_000 + i * 1000, 6 * GIB).is_none()); + } + let t = avail(&mut m, 33_000, 6 * GIB).unwrap(); + assert_eq!(t.to, Level::Normal); +} + +#[test] +fn one_calm_sample_between_bad_ones_does_not_step_down() { + let mut m = monitor(); + avail(&mut m, 0, 3 * GIB); + for i in 0..6u64 { + let a = if i % 2 == 0 { 20 * GIB } else { 3 * GIB }; + avail(&mut m, 1000 * (i + 1), a); + } + assert_eq!(m.level(), Level::Shed); +} + +#[test] +fn unknown_available_memory_holds_shed() { + let mut m = monitor(); + let t = m.update(&Sample::default()).unwrap(); + assert_eq!(t.to, Level::Shed); + assert!(t.reason.0.contains("unknown")); + for i in 1..10 { + assert!(m.update(&Sample { at_ms: i * 1000, ..Sample::default() }).is_none()); + } + assert_eq!(m.level(), Level::Shed); +} + +#[test] +fn psi_stalls_shed_and_reject_independent_of_available_memory() { + let mut m = monitor(); + let psi = |some: f64, full: f64| { + Some(Psi { + some: PsiLine { avg10: some, ..Default::default() }, + full: PsiLine { avg10: full, ..Default::default() }, + }) + }; + // above the PSI guard (3 x the soft floor) stalls are not about us: a page-cache reader on a host with 30 GiB free changes nothing + assert!( + m.update(&Sample { at_ms: 0, available: Some(30 * GIB), psi: psi(60.0, 20.0), ..Sample::default() }).is_none() + ); + assert_eq!(m.level(), Level::Normal); + // below it they count, independently of the floors + let t = + m.update(&Sample { at_ms: 1000, available: Some(10 * GIB), psi: psi(30.0, 0.0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Shed); + assert!(t.reason.0.contains("PSI some")); + let t = + m.update(&Sample { at_ms: 2000, available: Some(10 * GIB), psi: psi(40.0, 9.0), ..Sample::default() }).unwrap(); + assert_eq!(t.to, Level::Reject); + // a quiet PSI recovers after the calm samples + for i in 0..3 { + m.update(&Sample { + at_ms: 3000 + i * 1000, + available: Some(10 * GIB), + psi: psi(0.0, 0.0), + ..Sample::default() + }); + } + assert_eq!(m.level(), Level::Shed); +} + +#[test] +fn cgroup_oom_and_high_events_escalate_by_their_delta() { + let mut m = monitor(); + let ev = |high, max, oom, kill| Some(CgroupEvents { low: 0, high, max, oom, oom_kill: kill }); + assert!( + m.update(&Sample { at_ms: 0, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }) + .is_none(), + "the first reading is the baseline" + ); + assert!( + m.update(&Sample { at_ms: 1000, available: Some(30 * GIB), events: ev(5, 5, 0, 0), ..Sample::default() }) + .is_none() + ); + let t = m + .update(&Sample { at_ms: 2000, available: Some(30 * GIB), events: ev(6, 5, 0, 0), ..Sample::default() }) + .unwrap(); + assert_eq!(t.to, Level::Shed); + let t = m + .update(&Sample { at_ms: 3000, available: Some(30 * GIB), events: ev(6, 5, 1, 0), ..Sample::default() }) + .unwrap(); + assert_eq!(t.to, Level::Reject); + assert_eq!(m.observed.cgroup_oom_delta, 1); +} + +#[test] +fn a_swap_out_storm_sheds() { + let mut m = monitor(); + m.update(&Sample { at_ms: 0, available: Some(30 * GIB), pswpout: Some(1000), ..Sample::default() }); + let t = m + .update(&Sample { at_ms: 1000, available: Some(30 * GIB), pswpout: Some(1000 + 100_000), ..Sample::default() }) + .unwrap(); + assert_eq!(t.to, Level::Shed); + assert_eq!(m.observed.swapout_pages_per_s, Some(100_000)); +} diff --git a/crates/leleka-memory/src/pressure_port.rs b/crates/leleka-memory/src/pressure_port.rs index 71b0e78b..e85cc40d 100644 --- a/crates/leleka-memory/src/pressure_port.rs +++ b/crates/leleka-memory/src/pressure_port.rs @@ -57,24 +57,13 @@ pub struct ScriptedPressure { impl ScriptedPressure { /// A script of ready readings (at least one). pub fn new(script: Vec) -> Self { - assert!( - !script.is_empty(), - "a scripted host needs at least one reading" - ); - Self { - script, - state: Mutex::new(0), - } + assert!(!script.is_empty(), "a scripted host needs at least one reading"); + Self { script, state: Mutex::new(0) } } /// A script of hosts that differ only in `MemAvailable`, in MiB, with 121 GiB in total and no swap. pub fn available_mib(readings: &[u64]) -> Self { - Self::new( - readings - .iter() - .map(|mib| host_with_available(*mib)) - .collect(), - ) + Self::new(readings.iter().map(|mib| host_with_available(*mib)).collect()) } /// How many times the host was probed. @@ -90,11 +79,7 @@ fn host_with_available(mib: u64) -> HostFacts { mib * 1024 ); let status = "VmRSS: 1000 kB\nThreads: 3\n"; - HostFacts::probe( - &FakeProc::default() - .with("/proc/meminfo", &meminfo) - .with("/proc/self/status", status), - ) + HostFacts::probe(&FakeProc::default().with("/proc/meminfo", &meminfo).with("/proc/self/status", status)) } impl ProcSource for ScriptedPressure { @@ -124,15 +109,7 @@ mod tests { fn the_script_plays_in_order_and_repeats_its_last_reading() { let host = ScriptedPressure::available_mib(&[8000, 2000]); let seen: Vec<_> = (0..4).map(|_| host.facts().effective_available()).collect(); - assert_eq!( - seen, - [ - Some(8000 << 20), - Some(2000 << 20), - Some(2000 << 20), - Some(2000 << 20) - ] - ); + assert_eq!(seen, [Some(8000 << 20), Some(2000 << 20), Some(2000 << 20), Some(2000 << 20)]); assert_eq!(host.probes(), 4); } @@ -145,10 +122,7 @@ mod tests { #[test] fn the_real_adapter_probes_through_its_source() { - let fake = FakeProc::default().with( - "/proc/meminfo", - "MemTotal: 2048 kB\nMemAvailable: 1024 kB\n", - ); + let fake = FakeProc::default().with("/proc/meminfo", "MemTotal: 2048 kB\nMemAvailable: 1024 kB\n"); let pressure = ProcPressure(fake); assert_eq!(pressure.facts().effective_available(), Some(1024 << 10)); assert_eq!(pressure.facts(), HostFacts::probe(&pressure)); diff --git a/crates/leleka-memory/src/procfs.rs b/crates/leleka-memory/src/procfs.rs index 2b216c49..f9b69823 100644 --- a/crates/leleka-memory/src/procfs.rs +++ b/crates/leleka-memory/src/procfs.rs @@ -277,7 +277,8 @@ pub fn parse_smaps(text: &str) -> Vec { let mut entries: Vec = Vec::new(); for line in text.lines() { let first = line.split_ascii_whitespace().next().unwrap_or(""); - let is_header = first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':'); + let is_header = + first.contains('-') && first.chars().all(|c| c.is_ascii_hexdigit() || c == '-') && !first.ends_with(':'); if is_header { let mut fields = line.split_ascii_whitespace(); let range = fields.next().unwrap_or(""); diff --git a/crates/leleka-memory/src/procfs/tests.rs b/crates/leleka-memory/src/procfs/tests.rs index c6f30195..d3eacff7 100644 --- a/crates/leleka-memory/src/procfs/tests.rs +++ b/crates/leleka-memory/src/procfs/tests.rs @@ -83,7 +83,10 @@ fn cgroup_files() { assert_eq!(parse_cgroup_limit("max\n"), Some(None)); assert_eq!(parse_cgroup_limit("1073741824\n"), Some(Some(1 << 30))); assert_eq!(parse_cgroup_limit("lots"), None); - assert_eq!(parse_cgroup_path("0::/user.slice/user-1000.slice/session-578.scope\n").as_deref(), Some("/user.slice/user-1000.slice/session-578.scope")); + assert_eq!( + parse_cgroup_path("0::/user.slice/user-1000.slice/session-578.scope\n").as_deref(), + Some("/user.slice/user-1000.slice/session-578.scope") + ); assert_eq!(parse_cgroup_path("12:memory:/x\n"), None); assert_eq!(parse_cgroup_v1_memory_path("0::/init.scope\n5:memory:/docker/abc\n").as_deref(), Some("/docker/abc")); assert_eq!(parse_cgroup_v1_memory_path("5:cpu,cpuacct:/x\n0::/y\n"), None); diff --git a/crates/leleka-memory/src/smi.rs b/crates/leleka-memory/src/smi.rs index 2c51e16a..801bee55 100644 --- a/crates/leleka-memory/src/smi.rs +++ b/crates/leleka-memory/src/smi.rs @@ -16,14 +16,16 @@ use std::{ }; /// The `--query-gpu` fields, in the order [`parse_csv`] reads them. -pub const QUERY: &str = "index,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw,clocks.sm,temperature.gpu,name"; +pub const QUERY: &str = + "index,utilization.gpu,utilization.memory,memory.used,memory.total,power.draw,clocks.sm,temperature.gpu,name"; /// A new process at most this often; the sample in between is the previous one. pub const MIN_INTERVAL: Duration = Duration::from_secs(2); /// A `nvidia-smi` that has not answered by now is killed (a wedged driver can block it for a long time). pub const RUN_LIMIT: Duration = Duration::from_secs(5); /// Where `nvidia-smi` is looked for besides `PATH`: the WSL2 shim and the usual package locations. -const EXTRA_LOCATIONS: [&str; 3] = ["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"]; +const EXTRA_LOCATIONS: [&str; 3] = + ["/usr/lib/wsl/lib/nvidia-smi", "/usr/bin/nvidia-smi", "/usr/local/nvidia/bin/nvidia-smi"]; /// A field that is a number, or `None` for the placeholders `[N/A]`, `[Not Supported]`, `N/A`, `[Unknown Error]` and anything else. fn number(field: &str) -> Option { @@ -162,7 +164,8 @@ mod tests { assert_eq!((server.util_pct, server.vram_used_mib, server.vram_total_mib), (94, 31606, 32607)); assert_eq!((server.power_w, server.sm_clock_mhz, server.temp_c), (Some(271.4), Some(2887), Some(58))); // and on the RTX 3080 Laptop through the Windows driver (the path WSL2 takes) - let laptop = parse_csv("0, 0, 100, 0, 16384, 32.83, 1545, 59, NVIDIA GeForce RTX 3080 Laptop GPU\n", 0).unwrap(); + let laptop = + parse_csv("0, 0, 100, 0, 16384, 32.83, 1545, 59, NVIDIA GeForce RTX 3080 Laptop GPU\n", 0).unwrap(); assert_eq!((laptop.vram_used_mib, laptop.vram_total_mib, laptop.temp_c), (0, 16384, Some(59))); assert_eq!(laptop.name.as_deref(), Some("NVIDIA GeForce RTX 3080 Laptop GPU")); } @@ -217,7 +220,10 @@ mod tests { // appends to a file on every call so the test can count the processes started std::fs::write( &script, - format!("#!/bin/sh\necho x >> {}\necho '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU'\n", counter.display()), + format!( + "#!/bin/sh\necho x >> {}\necho '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU'\n", + counter.display() + ), ) .unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); @@ -243,10 +249,13 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let counter = dir.join("calls"); let script = dir.join("nvidia-smi"); - let body = format!("#!/bin/sh + let body = format!( + "#!/bin/sh echo x >> {} echo '0, 55, 20, 2048, 8192, 75.5, 1800, 50, Test GPU' -", counter.display()); +", + counter.display() + ); std::fs::write(&script, body).unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); let clock = leleka_obs::time::ManualClock::new(); diff --git a/crates/leleka-memory/src/telemetry/lock.rs b/crates/leleka-memory/src/telemetry/lock.rs index b8a31249..a3303467 100644 --- a/crates/leleka-memory/src/telemetry/lock.rs +++ b/crates/leleka-memory/src/telemetry/lock.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|p| p.into_inner()) } @@ -150,9 +149,13 @@ pub fn request_detail(request_id: &str, rounds: u64, tier: Option) /// The share (percent, one decimal) of expert entries served from VRAM / over PCIe / by the CPU in one request: the counters are /// the stack's lifetime, so it is the difference to the previous request (or all of them after a reload, when they went back). pub fn tier_shares(previous: Option<&TierCounters>, now: &TierCounters) -> (f64, f64, f64) { - let base = previous.filter(|p| now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries); + let base = previous.filter(|p| { + now.vram_entries >= p.vram_entries && now.pcie_entries >= p.pcie_entries && now.cpu_entries >= p.cpu_entries + }); let (v, p, c) = match base { - Some(b) => (now.vram_entries - b.vram_entries, now.pcie_entries - b.pcie_entries, now.cpu_entries - b.cpu_entries), + Some(b) => { + (now.vram_entries - b.vram_entries, now.pcie_entries - b.pcie_entries, now.cpu_entries - b.cpu_entries) + } None => (now.vram_entries, now.pcie_entries, now.cpu_entries), }; let all = (v + p + c).max(1) as f64; @@ -179,7 +182,11 @@ pub fn request_line_fields<'a>(r: &RequestLine<'a>) -> Vec ("dec_tps", rate(r.output_tokens, r.decode_ms).into()), ]; if let Some((vram, pcie, cpu)) = r.shares { - fields.extend([("tier_vram_pct", V::Float(vram)), ("tier_pcie_pct", V::Float(pcie)), ("tier_cpu_pct", V::Float(cpu))]); + fields.extend([ + ("tier_vram_pct", V::Float(vram)), + ("tier_pcie_pct", V::Float(pcie)), + ("tier_cpu_pct", V::Float(cpu)), + ]); } fields } diff --git a/crates/leleka-memory/src/telemetry/render.rs b/crates/leleka-memory/src/telemetry/render.rs index bbb4f8e7..828aa84a 100644 --- a/crates/leleka-memory/src/telemetry/render.rs +++ b/crates/leleka-memory/src/telemetry/render.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn render(state: &State, measured: &Measured) -> String { let mib = |bytes: Option| bytes.map_or(0, |b| b >> 20); let ram = measured.meminfo.mem_total.map(|total| Ram { @@ -11,7 +10,8 @@ pub(super) fn render(state: &State, measured: &Measured) -> String { available_mib: mib(measured.meminfo.mem_available), process_rss_mib: mib(measured.status.vm_rss), process_pinned_mib: mib(measured.status.vm_pin), - swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) >> 20, + swap_used_mib: measured.meminfo.swap_total.unwrap_or(0).saturating_sub(measured.meminfo.swap_free.unwrap_or(0)) + >> 20, }); let live_rate = match (state.phase, state.first_token) { (Phase::Decode, Some(first)) if state.produced_now > 1 => { @@ -61,15 +61,23 @@ pub(super) fn render(state: &State, measured: &Measured) -> String { max_tokens: state.context_max, used_pct: ratio(state.context_live, state.context_max).map(|r| (r * 1e4).round() / 1e2), }, - nan_guard: NanGuard { healed_windows: state.nan_healed, unhealed_windows: state.nan_unhealed, last: state.nan_last.clone() }, + nan_guard: NanGuard { + healed_windows: state.nan_healed, + unhealed_windows: state.nan_unhealed, + last: state.nan_last.clone(), + }, spec: Spec { rounds: state.spec_rounds, tokens: state.spec_tokens, - tokens_per_round: (state.spec_rounds > 0).then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), + tokens_per_round: (state.spec_rounds > 0) + .then(|| (state.spec_tokens as f64 / state.spec_rounds as f64 * 100.0).round() / 100.0), }, expert_tier: state.expert_tier.map(|counters| Tier { counters, - vram_ratio: ratio(counters.vram_entries, counters.vram_entries + counters.pcie_entries + counters.cpu_entries), + vram_ratio: ratio( + counters.vram_entries, + counters.vram_entries + counters.pcie_entries + counters.cpu_entries, + ), }), last_request: state.last_request.clone(), settings: lock(&SETTINGS).clone(), diff --git a/crates/leleka-memory/src/telemetry/tests.rs b/crates/leleka-memory/src/telemetry/tests.rs index 4def72d0..926960ae 100644 --- a/crates/leleka-memory/src/telemetry/tests.rs +++ b/crates/leleka-memory/src/telemetry/tests.rs @@ -9,8 +9,21 @@ fn measured() -> Measured { at: Instant::now(), now_ms: 1, uptime_s: 5, - gpu: Some(GpuSample { index: 0, util_pct: 91, mem_util_pct: 40, vram_used_mib: 30000, vram_total_mib: 32607, power_w: Some(480.0), sm_clock_mhz: Some(2900), temp_c: Some(61), name: Some("NVIDIA GeForce RTX 5090".into()), ..Default::default() }), - meminfo: procfs::parse_meminfo("MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n"), + gpu: Some(GpuSample { + index: 0, + util_pct: 91, + mem_util_pct: 40, + vram_used_mib: 30000, + vram_total_mib: 32607, + power_w: Some(480.0), + sm_clock_mhz: Some(2900), + temp_c: Some(61), + name: Some("NVIDIA GeForce RTX 5090".into()), + ..Default::default() + }), + meminfo: procfs::parse_meminfo( + "MemTotal: 125829120 kB\nMemAvailable: 70000000 kB\nSwapTotal: 0 kB\nSwapFree: 0 kB\n", + ), status: procfs::parse_status("VmRSS:\t55000000 kB\nVmPin:\t3000000 kB\n"), cores: 32, cpu: Some((7.4, 31.0)), @@ -39,13 +52,19 @@ fn the_nan_guard_reports_each_healed_and_unhealed_window() { let _serial = lock(&SERIAL); *lock(&STATE) = None; let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(0), Some(0))); + assert_eq!( + (doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), + (Some(0), Some(0)) + ); assert!(doc["nan_guard"]["last"].is_null()); nan_guard_healed("position 4096, 4 rows, retry 1 of 2: NonFinite"); nan_guard_healed("position 4100, 2 rows, retry 1 of 2: NonFinite"); nan_guard_unhealed("position 8000, 4 rows, retry 2 of 2: NonFinite"); let doc: serde_json::Value = serde_json::from_str(&render_now(&measured())).unwrap(); - assert_eq!((doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), (Some(2), Some(1))); + assert_eq!( + (doc["nan_guard"]["healed_windows"].as_u64(), doc["nan_guard"]["unhealed_windows"].as_u64()), + (Some(2), Some(1)) + ); assert_eq!(doc["nan_guard"]["last"], "unhealed: position 8000, 4 rows, retry 2 of 2: NonFinite"); *lock(&STATE) = None; } @@ -70,13 +89,30 @@ fn the_engine_line_carries_the_figures_of_one_request_and_stays_small() { shares: Some((91.4, 5.1, 3.5)), }; let text = line(&full); - for expected in ["\"comp\":\"engine\"", "\"rid\":\"0b1c2d3e", "\"rounds\":131", "\"tok_per_round\":3.15", "\"dec_tps\":71.5", "\"tier_vram_pct\":91.4"] { + for expected in [ + "\"comp\":\"engine\"", + "\"rid\":\"0b1c2d3e", + "\"rounds\":131", + "\"tok_per_round\":3.15", + "\"dec_tps\":71.5", + "\"tier_vram_pct\":91.4", + ] { assert!(text.contains(expected), "{expected} missing: {text}"); } assert!(text.len() < 512, "{} bytes: {text}", text.len()); eprintln!("ENGINE-LINE-BYTES {} {text}", text.len()); // without the expert tier the three shares are left out; an idle request has no rates - let idle = line(&RequestLine { request_id: "r", input_tokens: 0, reused_tokens: 0, output_tokens: 0, prefill_ms: 0.0, decode_ms: 0.0, produced: 0, rounds: 0, shares: None }); + let idle = line(&RequestLine { + request_id: "r", + input_tokens: 0, + reused_tokens: 0, + output_tokens: 0, + prefill_ms: 0.0, + decode_ms: 0.0, + produced: 0, + rounds: 0, + shares: None, + }); assert!(!idle.contains("tier_") && idle.contains("\"tok_per_round\":null"), "{idle}"); } @@ -103,7 +139,18 @@ fn the_engine_reports_the_speculative_loop_and_the_expert_tier_per_request() { request_started(1000); tokens_delivered(300); request_finished(1000, 400, 300, 600.0, 3000.0); - request_detail("req-1", 100, Some(TierCounters { groups: 40, vram_entries: 900, pcie_entries: 60, cpu_entries: 40, adaptations: 2, swaps: 7 })); + request_detail( + "req-1", + 100, + Some(TierCounters { + groups: 40, + vram_entries: 900, + pcie_entries: 60, + cpu_entries: 40, + adaptations: 2, + swaps: 7, + }), + ); request_started(1000); request_finished(1000, 0, 100, 1200.0, 1000.0); request_detail("req-2", 50, None); diff --git a/crates/leleka-memory/src/winproc.rs b/crates/leleka-memory/src/winproc.rs index 6a8f37b4..3c4de477 100644 --- a/crates/leleka-memory/src/winproc.rs +++ b/crates/leleka-memory/src/winproc.rs @@ -38,7 +38,8 @@ fn kb(bytes: u64) -> u64 { /// `/proc/meminfo`. pub fn meminfo_text(m: &SystemMemory) -> String { let swap_total = m.total_commit.saturating_sub(m.total_phys); - let swap_used = m.total_commit.saturating_sub(m.avail_commit).saturating_sub(m.total_phys.saturating_sub(m.avail_phys)); + let swap_used = + m.total_commit.saturating_sub(m.avail_commit).saturating_sub(m.total_phys.saturating_sub(m.avail_phys)); let swap_free = swap_total.saturating_sub(swap_used); format!( "MemTotal: {} kB\nMemFree: {} kB\nMemAvailable: {} kB\nSwapTotal: {} kB\nSwapFree: {} kB\n", @@ -144,7 +145,12 @@ mod win32 { if unsafe { GlobalMemoryStatusEx(&mut s) } == 0 { return None; } - Some(SystemMemory { total_phys: s.ullTotalPhys, avail_phys: s.ullAvailPhys, total_commit: s.ullTotalPageFile, avail_commit: s.ullAvailPageFile }) + Some(SystemMemory { + total_phys: s.ullTotalPhys, + avail_phys: s.ullAvailPhys, + total_commit: s.ullTotalPageFile, + avail_commit: s.ullAvailPageFile, + }) } pub fn process_memory() -> Option { @@ -155,7 +161,11 @@ mod win32 { if unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) } == 0 { return None; } - Some(ProcessMemory { working_set: c.WorkingSetSize as u64, peak_working_set: c.PeakWorkingSetSize as u64, private_commit: c.PagefileUsage as u64 }) + Some(ProcessMemory { + working_set: c.WorkingSetSize as u64, + peak_working_set: c.PeakWorkingSetSize as u64, + private_commit: c.PagefileUsage as u64, + }) } /// Move every trimmable page of this process (mapped expert-bank pages; page-locked and pinned ones stay) from its working set to the @@ -200,7 +210,12 @@ mod tests { #[test] fn meminfo_round_trips_through_the_linux_parser() { - let text = meminfo_text(&SystemMemory { total_phys: 48 * GIB, avail_phys: 30 * GIB, total_commit: 80 * GIB, avail_commit: 55 * GIB }); + let text = meminfo_text(&SystemMemory { + total_phys: 48 * GIB, + avail_phys: 30 * GIB, + total_commit: 80 * GIB, + avail_commit: 55 * GIB, + }); let info = procfs::parse_meminfo(&text); assert_eq!(info.mem_total, Some(48 * GIB)); assert_eq!(info.mem_available, Some(30 * GIB)); @@ -211,7 +226,11 @@ mod tests { #[test] fn status_and_limits_round_trip() { - let status = procfs::parse_status(&status_text(&ProcessMemory { working_set: 10 * GIB, peak_working_set: 12 * GIB, private_commit: 3 * GIB })); + let status = procfs::parse_status(&status_text(&ProcessMemory { + working_set: 10 * GIB, + peak_working_set: 12 * GIB, + private_commit: 3 * GIB, + })); assert_eq!(status.vm_rss, Some(10 * GIB)); assert_eq!(status.vm_hwm, Some(12 * GIB)); assert_eq!(status.rss_anon, Some(3 * GIB)); @@ -219,7 +238,11 @@ mod tests { assert_eq!(status.vm_lck, None); assert_eq!(procfs::parse_memlock_limit(&limits_text()), Some((u64::MAX, u64::MAX))); // a commit charge above the working set (pages out) never makes the file part negative - let paged = procfs::parse_status(&status_text(&ProcessMemory { working_set: GIB, peak_working_set: GIB, private_commit: 4 * GIB })); + let paged = procfs::parse_status(&status_text(&ProcessMemory { + working_set: GIB, + peak_working_set: GIB, + private_commit: 4 * GIB, + })); assert_eq!((paged.rss_anon, paged.rss_file), (Some(GIB), Some(0))); } diff --git a/crates/leleka-memory/tests/sparse_archive.rs b/crates/leleka-memory/tests/sparse_archive.rs index 3b813012..08bd8dc1 100644 --- a/crates/leleka-memory/tests/sparse_archive.rs +++ b/crates/leleka-memory/tests/sparse_archive.rs @@ -81,7 +81,10 @@ fn extents_that_do_not_fit_the_descriptor_are_refused_before_any_mapping() { let f = sparse_memfd(16, &[(0, 1)]); let g = governor(); for bad in [vec![(1u64, PAGE)], vec![(15 * PAGE, 2 * PAGE)], vec![(0, 2 * PAGE), (PAGE, PAGE)]] { - let e = g.guard_archive_extents(f.as_fd(), 16 * PAGE, Some(&bad)).err().unwrap_or_else(|| panic!("{bad:?} accepted")); + let e = g + .guard_archive_extents(f.as_fd(), 16 * PAGE, Some(&bad)) + .err() + .unwrap_or_else(|| panic!("{bad:?} accepted")); assert!(e.to_string().contains("extents are invalid"), "{e}"); } assert_eq!(allocated(&f), PAGE); diff --git a/crates/leleka-runtime/rustfmt.toml b/crates/leleka-runtime/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/leleka-runtime/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/model-format/examples/bulk_read_bench.rs b/crates/model-format/examples/bulk_read_bench.rs index ce864784..59fe860e 100644 --- a/crates/model-format/examples/bulk_read_bench.rs +++ b/crates/model-format/examples/bulk_read_bench.rs @@ -12,9 +12,7 @@ use std::{fs::File, sync::Mutex}; /// (bytes read, bytes written) by the whole device so far. fn device_bytes() -> Option<(u64, u64)> { let text = std::fs::read_to_string("/sys/block/nvme0n1/stat").ok()?; - let field = |n: usize| -> Option { - Some(text.split_whitespace().nth(n)?.parse::().ok()? * 512) - }; + let field = |n: usize| -> Option { Some(text.split_whitespace().nth(n)?.parse::().ok()? * 512) }; Some((field(2)?, field(6)?)) } @@ -38,12 +36,7 @@ fn main() { _ => Strategy::Plain, }; let chunk = args[6].parse::().expect("CHUNK_MIB") << 20; - let plan = Plan { - strategy, - threads: args[5].parse().expect("THREADS"), - chunk, - ahead: 1 << 30, - }; + let plan = Plan { strategy, threads: args[5].parse().expect("THREADS"), chunk, ahead: 1 << 30 }; let digest = args.iter().any(|a| a == "--digest"); if !args.iter().any(|a| a == "--no-evict-first") { evict(&file, start, len); @@ -84,14 +77,7 @@ fn main() { for (_, d) in &list { outer.update(d); } - print!( - " digest {}", - outer - .finalize() - .iter() - .map(|b| format!("{b:02x}")) - .collect::() - ); + print!(" digest {}", outer.finalize().iter().map(|b| format!("{b:02x}")).collect::()); } println!(); evict(&file, start, len); diff --git a/crates/model-format/examples/kar_cases.rs b/crates/model-format/examples/kar_cases.rs index 1c3752aa..02037ea3 100644 --- a/crates/model-format/examples/kar_cases.rs +++ b/crates/model-format/examples/kar_cases.rs @@ -11,14 +11,22 @@ impl Rng { self.0 ^= self.0 >> 27; self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) } - fn below(&mut self, n: u64) -> u64 { self.next() % n } - fn range(&mut self, lo: u64, hi: u64) -> u64 { lo + self.below(hi - lo + 1) } + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + fn range(&mut self, lo: u64, hi: u64) -> u64 { + lo + self.below(hi - lo + 1) + } +} +fn r16(v: u64) -> u64 { + v.div_ceil(16) * 16 } -fn r16(v: u64) -> u64 { v.div_ceil(16) * 16 } struct Out(Vec, u32); impl Out { - fn w(&mut self, v: u32) { self.0.push(v); } + fn w(&mut self, v: u32) { + self.0.push(v); + } fn bytes(&mut self, b: &[u8]) { for c in b.chunks(4) { let mut x = [0u8; 4]; @@ -37,39 +45,100 @@ fn fixture(rng: &mut Rng, n: u64, group: u32, stored: u8) -> (Vec, KarNested let stride = r16(n_padded / 32 * 4); let end = planes_offset + u64::from(stored) * stride; let mut a: Vec = (0..end).map(|_| rng.next() as u8).collect(); - let fin = |rng: &mut Rng| loop { let b = (rng.next() >> 20) as u16; if b & 0x7c00 != 0x7c00 { return b; } }; - for s in 0..(scales_bytes / 2) as usize { let at = 256 + 2 * s; a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); } - for e in 0..(books_bytes / 2) as usize { let at = books_offset as usize + 2 * e; a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); } + let fin = |rng: &mut Rng| loop { + let b = (rng.next() >> 20) as u16; + if b & 0x7c00 != 0x7c00 { + return b; + } + }; + for s in 0..(scales_bytes / 2) as usize { + let at = 256 + 2 * s; + a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); + } + for e in 0..(books_bytes / 2) as usize { + let at = books_offset as usize + 2 * e; + a[at..at + 2].copy_from_slice(&fin(rng).to_le_bytes()); + } let rec = KarNestedRecord { - name: "t".into(), dimensions: vec![n], n_elements: n, n_padded, group, planes_stored: stored, - planes_min: 2, planes_max: stored, nesting: 0, section_offset: 256, section_bytes: end - 256, - scales_offset: 256, scales_bytes, books_offset, books_bytes, planes_offset, plane_stride_bytes: stride as u32, + name: "t".into(), + dimensions: vec![n], + n_elements: n, + n_padded, + group, + planes_stored: stored, + planes_min: 2, + planes_max: stored, + nesting: 0, + section_offset: 256, + section_bytes: end - 256, + scales_offset: 256, + scales_bytes, + books_offset, + books_bytes, + planes_offset, + plane_stride_bytes: stride as u32, }; rec.validate().unwrap(); (a, rec) } fn scalars(p: &DecodeParams) -> [u32; 12] { - [p.level, p.staged_planes, p.count, p.head32, p.head_group, p.group, p.scales_offset, p.planes_offset, p.plane_stride_words, p.window_words, p.window_groups, p.packet_bytes] + [ + p.level, + p.staged_planes, + p.count, + p.head32, + p.head_group, + p.group, + p.scales_offset, + p.planes_offset, + p.plane_stride_words, + p.window_words, + p.window_groups, + p.packet_bytes, + ] } fn from_scalars(s: [u32; 12]) -> DecodeParams { - DecodeParams { level: s[0], staged_planes: s[1], count: s[2], head32: s[3], head_group: s[4], group: s[5], scales_offset: s[6], planes_offset: s[7], plane_stride_words: s[8], window_words: s[9], window_groups: s[10], packet_bytes: s[11] } + DecodeParams { + level: s[0], + staged_planes: s[1], + count: s[2], + head32: s[3], + head_group: s[4], + group: s[5], + scales_offset: s[6], + planes_offset: s[7], + plane_stride_words: s[8], + window_words: s[9], + window_groups: s[10], + packet_bytes: s[11], + } } fn decode_case(o: &mut Out, p: &DecodeParams, packet: &[u8], grid: u32, out_words: usize) { - let mut out = vec![f32::from_bits(0xdead_beef); out_words]; + let mut out = vec![f32::from_bits(0xdead_beef); out_words]; let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel_decode(p, packet, &mut out))); let status = match res { Ok(s) => s, - Err(_) => { eprintln!("MODEL PANIC for params {p:?} (model guard admits an out-of-bounds access)"); return; } + Err(_) => { + eprintln!("MODEL PANIC for params {p:?} (model guard admits an out-of-bounds access)"); + return; + } }; o.1 += 1; o.w(0); - for v in scalars(p) { o.w(v); } - o.w(grid); o.w(0); o.w(packet.len() as u32); + for v in scalars(p) { + o.w(v); + } + o.w(grid); + o.w(0); + o.w(packet.len() as u32); o.bytes(packet); - o.w(out.len() as u32); o.w(status); - for v in &out { o.w(v.to_bits()); } + o.w(out.len() as u32); + o.w(status); + for v in &out { + o.w(v.to_bits()); + } } fn main() { @@ -79,7 +148,12 @@ fn main() { for level in 2u8..=5 { for round in 0..150 { let group = groups[rng.below(6) as usize]; - let n = match round % 4 { 0 => rng.range(1, 70), 1 => rng.range(1, 3 * u64::from(group) + 5), 2 => rng.range(300, 2600), _ => rng.range(700, 12000) }; + let n = match round % 4 { + 0 => rng.range(1, 70), + 1 => rng.range(1, 3 * u64::from(group) + 5), + 2 => rng.range(300, 2600), + _ => rng.range(700, 12000), + }; let stored = rng.range(u64::from(level), 5) as u8; let (arch, rec) = fixture(&mut rng, n, group, stored); for _ in 0..4 { @@ -110,8 +184,14 @@ fn main() { for field in (0..12).filter(|f| *f != 2) { for delta in [1u32, 2, 4, 32, u32::MAX, 0x8000_0000] { let mut s = base; - s[field] = if delta % 2 == 0 && delta != 0 { s[field].wrapping_add(delta) } else { s[field].wrapping_sub(delta) }; - if delta == 0x8000_0000 { s[field] = base[field] ^ 0x8000_0000; } + s[field] = if delta % 2 == 0 && delta != 0 { + s[field].wrapping_add(delta) + } else { + s[field].wrapping_sub(delta) + }; + if delta == 0x8000_0000 { + s[field] = base[field] ^ 0x8000_0000; + } let q = from_scalars(s); decode_case(&mut o, &q, &packet, plan.grid_blocks(), plan.count as usize); } @@ -127,31 +207,61 @@ fn main() { let rows = rng.range(1, 9) as u32; let tokens = rng.range(1, 3) as u32; let big = rng.below(10) == 0; - let genf = |rng: &mut Rng| { let m = (rng.next() as i32 as f32) / 2147483648.0; if big { m * 3e19 } else { m * 4.0 } }; + let genf = |rng: &mut Rng| { + let m = (rng.next() as i32 as f32) / 2147483648.0; + if big { m * 3e19 } else { m * 4.0 } + }; let w: Vec = (0..cols * rows).map(|_| genf(&mut rng)).collect(); let x: Vec = (0..cols * tokens).map(|_| genf(&mut rng)).collect(); let mut out = vec![0f32; (rows * tokens) as usize]; let status = kernel_multiply(&w, &x, cols, rows, tokens, &mut out); o.1 += 1; - o.w(1); o.w(cols); o.w(rows); o.w(tokens); o.w(0); o.w(0); - for v in &w { o.w(v.to_bits()); } for v in &x { o.w(v.to_bits()); } - o.w(status); o.w(out.len() as u32); for v in &out { o.w(v.to_bits()); } + o.w(1); + o.w(cols); + o.w(rows); + o.w(tokens); + o.w(0); + o.w(0); + for v in &w { + o.w(v.to_bits()); + } + for v in &x { + o.w(v.to_bits()); + } + o.w(status); + o.w(out.len() as u32); + for v in &out { + o.w(v.to_bits()); + } } // swiglu for _ in 0..30 { let values = rng.range(1, 700) as usize; - let g: Vec = (0..values).map(|_| ((rng.next() as i32 as f32) / 2147483648.0) * if rng.below(5) == 0 { 120.0 } else { 8.0 }).collect(); + let g: Vec = (0..values) + .map(|_| ((rng.next() as i32 as f32) / 2147483648.0) * if rng.below(5) == 0 { 120.0 } else { 8.0 }) + .collect(); let u: Vec = (0..values).map(|_| ((rng.next() as i32 as f32) / 2147483648.0) * 3.0).collect(); let mut act = vec![0f32; values]; let status = kernel_swiglu(&g, &u, &mut act); o.1 += 1; - o.w(2); o.w(values as u32); - for v in &g { o.w(v.to_bits()); } for v in &u { o.w(v.to_bits()); } - o.w(status); for v in &act { o.w(v.to_bits()); } + o.w(2); + o.w(values as u32); + for v in &g { + o.w(v.to_bits()); + } + for v in &u { + o.w(v.to_bits()); + } + o.w(status); + for v in &act { + o.w(v.to_bits()); + } } o.0[0] = o.1; let path = std::env::args().nth(1).unwrap(); let mut f = std::fs::File::create(path).unwrap(); - for v in &o.0 { f.write_all(&v.to_le_bytes()).unwrap(); } + for v in &o.0 { + f.write_all(&v.to_le_bytes()).unwrap(); + } eprintln!("{} cases", o.1); } diff --git a/crates/model-format/examples/kar_census.rs b/crates/model-format/examples/kar_census.rs index ebb56d28..58838816 100644 --- a/crates/model-format/examples/kar_census.rs +++ b/crates/model-format/examples/kar_census.rs @@ -12,7 +12,11 @@ //! //! Nothing is written, nothing needs a GPU. use leleka_model_format::kar::{KarInspection, PLE_PART_NAMES, digest_extents}; -use std::{fs::File, process::ExitCode, time::{Duration, Instant}}; +use std::{ + fs::File, + process::ExitCode, + time::{Duration, Instant}, +}; fn main() -> ExitCode { let mut path = None; diff --git a/crates/model-format/rustfmt.toml b/crates/model-format/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/model-format/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/model-format/src/bulk_read/for_each_chunk.rs b/crates/model-format/src/bulk_read/for_each_chunk.rs index ee0d8c9f..f4b4b5d7 100644 --- a/crates/model-format/src/bulk_read/for_each_chunk.rs +++ b/crates/model-format/src/bulk_read/for_each_chunk.rs @@ -3,27 +3,17 @@ #[allow(unused_imports)] use super::*; - /// Read `file[start .. start + len]` in blocks on several threads and hand each block to `sink(absolute_offset, bytes)`. /// Blocks arrive in no particular order, from different threads; each covers a distinct range of at most `plan.chunk` /// bytes. The first error stops the others and is returned. -pub fn for_each_chunk( - file: &File, - start: u64, - len: u64, - plan: Plan, - sink: F, -) -> io::Result +pub fn for_each_chunk(file: &File, start: u64, len: u64, plan: Plan, sink: F) -> io::Result where F: Fn(u64, &[u8]) -> io::Result<()> + Sync, { let began = Instant::now(); let file_len = file.metadata()?.len(); if start.checked_add(len).is_none_or(|end| end > file_len) { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the span is beyond the end of the file", - )); + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the span is beyond the end of the file")); } let chunk = (plan.chunk.max(ALIGN) / ALIGN * ALIGN) as u64; let mut strategy = plan.strategy; @@ -35,11 +25,7 @@ where } } if len == 0 { - return Ok(Report { - strategy, - bytes: 0, - elapsed: began.elapsed(), - }); + return Ok(Report { strategy, bytes: 0, elapsed: began.elapsed() }); } // The block that reaches the file's last bytes may be shorter than its aligned length: `read_full` stops at the end. let threads = plan.threads.clamp(1, len.div_ceil(chunk) as usize); @@ -90,11 +76,7 @@ where if used != Strategy::Direct { evict(file, start, len); } - Ok(Report { - strategy: used, - bytes: len, - elapsed: began.elapsed(), - }) + Ok(Report { strategy: used, bytes: len, elapsed: began.elapsed() }) } /// Fill `dest` with `file[start .. start + dest.len()]`. @@ -111,9 +93,7 @@ pub fn read_into(file: &File, start: u64, dest: &mut [u8], plan: Plan) -> io::Re .lock() .map_err(|_| io::Error::other("destination lock poisoned"))?; if piece.len() != bytes.len() { - return Err(io::Error::other( - "block length differs from the destination piece", - )); + return Err(io::Error::other("block length differs from the destination piece")); } piece.copy_from_slice(bytes); Ok(()) diff --git a/crates/model-format/src/bulk_read/impl_strategy.rs b/crates/model-format/src/bulk_read/impl_strategy.rs index 8e443f66..f0f7a472 100644 --- a/crates/model-format/src/bulk_read/impl_strategy.rs +++ b/crates/model-format/src/bulk_read/impl_strategy.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Strategy { pub fn as_str(self) -> &'static str { match self { @@ -45,12 +44,7 @@ impl Plan { impl Default for Plan { fn default() -> Self { - Plan { - strategy: Strategy::Direct, - threads: 32, - chunk: 8 << 20, - ahead: 1 << 30, - } + Plan { strategy: Strategy::Direct, threads: 32, chunk: 8 << 20, ahead: 1 << 30 } } } @@ -63,8 +57,7 @@ impl Report { impl Aligned { pub(super) fn new(len: usize) -> io::Result { let mut raw = Vec::new(); - raw.try_reserve_exact(len + ALIGN) - .map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, "read buffer"))?; + raw.try_reserve_exact(len + ALIGN).map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, "read buffer"))?; raw.resize(len + ALIGN, 0); let start = (ALIGN - raw.as_ptr() as usize % ALIGN) % ALIGN; Ok(Aligned { raw, start, len }) @@ -168,10 +161,7 @@ impl io::Result<()> + Sync> Shared<'_, F> { let want = (lead + count).next_multiple_of(ALIGN); let got = read_full(direct, &mut buffer.bytes()[..want], aligned)?; if got < lead + count { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file ended before the span did", - )); + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the file ended before the span did")); } (self.sink)(offset, &buffer.bytes()[lead..lead + count]) } @@ -181,10 +171,7 @@ impl io::Result<()> + Sync> Shared<'_, F> { } let got = read_full(self.file, &mut buffer.bytes()[..count], offset)?; if got < count { - return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file ended before the span did", - )); + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the file ended before the span did")); } (self.sink)(offset, &buffer.bytes()[..count])?; evict(self.file, offset, count as u64); @@ -195,17 +182,10 @@ impl io::Result<()> + Sync> Shared<'_, F> { /// Make sure `WILLNEED` covers `ahead` bytes beyond `until` (each byte is advised once). pub(super) fn keep_ahead(&self, until: u64) { - let target = (until + self.ahead) - .min(self.file_len) - .min(self.start + self.len); + let target = (until + self.ahead).min(self.file_len).min(self.start + self.len); let mut done = self.advised_to.load(Ordering::Relaxed).max(self.start); while done < target { - match self.advised_to.compare_exchange( - done, - target, - Ordering::Relaxed, - Ordering::Relaxed, - ) { + match self.advised_to.compare_exchange(done, target, Ordering::Relaxed, Ordering::Relaxed) { Ok(_) => { #[cfg(target_os = "linux")] advise(self.file, done, target - done, rustix::fs::Advice::WillNeed); diff --git a/crates/model-format/src/bulk_read/tests.rs b/crates/model-format/src/bulk_read/tests.rs index 8f5481c3..32f3f240 100644 --- a/crates/model-format/src/bulk_read/tests.rs +++ b/crates/model-format/src/bulk_read/tests.rs @@ -4,9 +4,7 @@ use super::*; use std::io::Write; fn pattern(size: usize) -> Vec { - (0..size) - .map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8) ^ ((n >> 17) as u8)) - .collect() + (0..size).map(|n| ((n / 4096) as u8).wrapping_mul(31) ^ (n as u8) ^ ((n >> 17) as u8)).collect() } fn temp(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) { @@ -23,12 +21,7 @@ fn plans() -> Vec { let mut all = Vec::new(); for strategy in [Strategy::Direct, Strategy::Advise, Strategy::Plain] { for (threads, chunk) in [(1, 4096), (3, 8192), (8, 64 << 10), (4, 1 << 20)] { - all.push(Plan { - strategy, - threads, - chunk, - ahead: 256 << 10, - }); + all.push(Plan { strategy, threads, chunk, ahead: 256 << 10 }); } } all @@ -51,10 +44,7 @@ fn every_strategy_returns_the_same_bytes_for_aligned_and_ragged_spans() { let mut dest = vec![0u8; len]; let report = read_into(&file, start as u64, &mut dest, plan).unwrap(); assert_eq!(report.bytes, len as u64); - assert!( - dest == payload[start..start + len], - "{plan:?} start {start} len {len}" - ); + assert!(dest == payload[start..start + len], "{plan:?} start {start} len {len}"); } } std::fs::remove_file(path).unwrap(); @@ -67,22 +57,16 @@ fn for_each_chunk_covers_the_span_exactly_once() { for plan in plans() { let seen = Mutex::new(vec![0u8; payload.len()]); let count = AtomicU64::new(0); - for_each_chunk( - &file, - 100, - payload.len() as u64 - 100, - plan, - |offset, bytes| { - count.fetch_add(bytes.len() as u64, Ordering::Relaxed); - let mut seen = seen.lock().unwrap(); - for (i, b) in bytes.iter().enumerate() { - assert_eq!(seen[offset as usize + i], 0, "byte visited twice"); - assert_eq!(*b, payload[offset as usize + i]); - seen[offset as usize + i] = 1; - } - Ok(()) - }, - ) + for_each_chunk(&file, 100, payload.len() as u64 - 100, plan, |offset, bytes| { + count.fetch_add(bytes.len() as u64, Ordering::Relaxed); + let mut seen = seen.lock().unwrap(); + for (i, b) in bytes.iter().enumerate() { + assert_eq!(seen[offset as usize + i], 0, "byte visited twice"); + assert_eq!(*b, payload[offset as usize + i]); + seen[offset as usize + i] = 1; + } + Ok(()) + }) .unwrap(); assert_eq!(count.load(Ordering::Relaxed), payload.len() as u64 - 100); assert!(seen.lock().unwrap()[100..].iter().all(|&v| v == 1)); @@ -95,17 +79,9 @@ fn a_span_past_the_end_and_a_sink_error_are_errors() { let payload = pattern(100_000); let (path, file) = temp("err", &payload); let mut dest = vec![0u8; 10]; - assert_eq!( - read_into(&file, 99_995, &mut dest, Plan::default()) - .unwrap_err() - .kind(), - io::ErrorKind::UnexpectedEof - ); + assert_eq!(read_into(&file, 99_995, &mut dest, Plan::default()).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); for plan in plans() { - let error = for_each_chunk(&file, 0, 100_000, plan, |_, _| { - Err(io::Error::other("sink refused")) - }) - .unwrap_err(); + let error = for_each_chunk(&file, 0, 100_000, plan, |_, _| Err(io::Error::other("sink refused"))).unwrap_err(); assert_eq!(error.to_string(), "sink refused"); } let empty = for_each_chunk(&file, 5, 0, Plan::default(), |_, _| Ok(())).unwrap(); @@ -118,12 +94,7 @@ fn a_file_shorter_than_it_was_measured_is_unexpected_eof() { let payload = pattern(50_000); let (path, file) = temp("short", &payload); // Grow the claimed length by truncating after the metadata read: emulate with a span the file cannot serve. - std::fs::OpenOptions::new() - .write(true) - .open(&path) - .unwrap() - .set_len(20_000) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(20_000).unwrap(); let mut dest = vec![0u8; 50_000]; for plan in plans() { assert!(read_into(&file, 0, &mut dest, plan).is_err()); @@ -140,15 +111,7 @@ fn the_environment_overrides_the_defaults() { "LELEKA_LOAD_AHEAD_MIB" => Some("64".into()), _ => None, }); - assert_eq!( - plan, - Plan { - strategy: Strategy::Advise, - threads: 7, - chunk: 16 << 20, - ahead: 64 << 20 - } - ); + assert_eq!(plan, Plan { strategy: Strategy::Advise, threads: 7, chunk: 16 << 20, ahead: 64 << 20 }); let kept = Plan::with_overrides(Plan::default(), |_| Some("nonsense".into())); assert_eq!(kept, Plan::default()); } diff --git a/crates/model-format/src/gguf/impl_cursor.rs b/crates/model-format/src/gguf/impl_cursor.rs index 640afc07..9532c98e 100644 --- a/crates/model-format/src/gguf/impl_cursor.rs +++ b/crates/model-format/src/gguf/impl_cursor.rs @@ -3,25 +3,16 @@ #[allow(unused_imports)] use super::*; - impl Cursor { // Both parser entrypoints have already sought the same descriptor to zero. pub(super) fn new(file: R, size: u64) -> Self { - Self { - file: BufReader::with_capacity(STREAM_BUFFER_BYTES, file), - size, - position: 0, - } + Self { file: BufReader::with_capacity(STREAM_BUFFER_BYTES, file), size, position: 0 } } #[cfg(test)] pub(super) fn with_test_capacity(file: R, size: u64, capacity: usize) -> Self { assert!(capacity > 0 && capacity <= STREAM_BUFFER_BYTES); - Self { - file: BufReader::with_capacity(capacity, file), - size, - position: 0, - } + Self { file: BufReader::with_capacity(capacity, file), size, position: 0 } } pub(super) fn position(&mut self) -> Result { @@ -29,10 +20,7 @@ impl Cursor { } pub(super) fn skip(&mut self, bytes: u64) -> Result<()> { - let end = self - .position()? - .checked_add(bytes) - .ok_or("GGUF offset overflow")?; + let end = self.position()?.checked_add(bytes).ok_or("GGUF offset overflow")?; if end > self.size { return Err("truncated GGUF header".into()); } @@ -46,11 +34,8 @@ impl Cursor { } pub(super) fn take(&mut self, size: usize) -> Result> { - let end = self - .position()? - .checked_add(size as u64) - .filter(|end| *end <= self.size) - .ok_or("truncated GGUF header")?; + let end = + self.position()?.checked_add(size as u64).filter(|end| *end <= self.size).ok_or("truncated GGUF header")?; let mut data = Vec::new(); data.try_reserve_exact(size)?; data.resize(size, 0); @@ -75,9 +60,7 @@ impl Cursor { pub(super) fn u64(&mut self) -> Result { let bytes = self.take(8)?; - Ok(u64::from_le_bytes([ - bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], - ])) + Ok(u64::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]])) } pub(super) fn string(&mut self) -> Result { @@ -100,9 +83,7 @@ impl Cursor { let mut values = Vec::with_capacity(count as usize); for _ in 0..count { let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF tokenizer array size overflow")?; + total = total.checked_add(value.len() as u64).ok_or("GGUF tokenizer array size overflow")?; if total > 512 * 1024 * 1024 { return Err("GGUF tokenizer array exceeds 512 MiB".into()); } @@ -217,9 +198,7 @@ impl Cursor { let mut values = Vec::with_capacity(capacity); for _ in 0..count { let value = self.string()?; - total = total - .checked_add(value.len() as u64) - .ok_or("GGUF metadata array size overflow")?; + total = total.checked_add(value.len() as u64).ok_or("GGUF metadata array size overflow")?; if total > 512 * 1024 * 1024 { return Err("GGUF metadata string array exceeds 512 MiB".into()); } @@ -256,11 +235,7 @@ impl Cursor { Ok(()) } 9 => Err("nested GGUF arrays are unsupported".into()), - _ => self.skip( - count - .checked_mul(value_width(element)?) - .ok_or("GGUF array size overflow")?, - ), + _ => self.skip(count.checked_mul(value_width(element)?).ok_or("GGUF array size overflow")?), } } 10..=12 => self.skip(8), diff --git a/crates/model-format/src/gguf/impl_verifiedgguffile.rs b/crates/model-format/src/gguf/impl_verifiedgguffile.rs index e1809106..b28b85d2 100644 --- a/crates/model-format/src/gguf/impl_verifiedgguffile.rs +++ b/crates/model-format/src/gguf/impl_verifiedgguffile.rs @@ -6,7 +6,6 @@ use super::*; /// `VerifiedGgufFile` as a `WeightSource` (private fields: the impl must live below `gguf`). mod port; - impl VerifiedGgufFile { /// Verify `sha256:<64 hex digits>` and strictly index the same opened file. /// The opened file's contents must remain stable until this handle is dropped. @@ -27,11 +26,7 @@ impl VerifiedGgufFile { let stamps = crate::verify_stamp::global(); // A stamp skips the hash only for this very file in this very state, keyed by the pinned digest. let trusted = matches!((stamps, identity.as_ref()), (Some(s), Some(id)) if s.trusts("gguf", &expected, id)); - let actual: [u8; 32] = if trusted { - expected - } else { - sha256_pipelined(&file, size)? - }; + let actual: [u8; 32] = if trusted { expected } else { sha256_pipelined(&file, size)? }; if actual != expected { return Err("GGUF artifact SHA256 mismatch".into()); } @@ -49,12 +44,7 @@ impl VerifiedGgufFile { if file.metadata()?.len() != size { return Err("GGUF source size changed during indexing".into()); } - Ok(Self { - file, - index, - artifact_sha256: actual, - resident_source_id: None, - }) + Ok(Self { file, index, artifact_sha256: actual, resident_source_id: None }) } pub fn index(&self) -> &TensorIndex { @@ -80,12 +70,8 @@ impl VerifiedGgufFile { #[cfg(test)] pub(crate) fn metadata_snapshot(&mut self) -> Result { self.check_size()?; - let snapshot = read_metadata_snapshot( - &mut self.file, - self.index.summary.file_size, - Some(QWEN4EXP_BINDING_KEYS), - true, - )?; + let snapshot = + read_metadata_snapshot(&mut self.file, self.index.summary.file_size, Some(QWEN4EXP_BINDING_KEYS), true)?; self.check_size()?; Ok(snapshot) } @@ -104,20 +90,15 @@ impl VerifiedGgufFile { /// binder can preserve profile-before-tokenizer error precedence. pub(crate) fn profile_snapshot(&mut self) -> Result { self.check_size()?; - let snapshot = read_metadata_snapshot( - &mut self.file, - self.index.summary.file_size, - Some(QWEN4EXP_BINDING_KEYS), - false, - )?; + let snapshot = + read_metadata_snapshot(&mut self.file, self.index.summary.file_size, Some(QWEN4EXP_BINDING_KEYS), false)?; self.check_size()?; Ok(snapshot) } pub(crate) fn tokenizer_snapshot(&mut self) -> Result> { self.check_size()?; - let snapshot = - read_metadata_snapshot(&mut self.file, self.index.summary.file_size, None, true)?; + let snapshot = read_metadata_snapshot(&mut self.file, self.index.summary.file_size, None, true)?; self.check_size()?; Ok(snapshot.tokenizer) } @@ -132,16 +113,8 @@ impl VerifiedGgufFile { bytes: u64, consume: impl FnMut(&[u8]) -> std::io::Result<()>, ) -> Result<()> { - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 - || offset - .checked_add(bytes) - .is_none_or(|end| end > tensor.bytes) - { + let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 || offset.checked_add(bytes).is_none_or(|end| end > tensor.bytes) { return Err("GGUF tensor byte range is out of bounds".into()); } let absolute = self @@ -151,10 +124,7 @@ impl VerifiedGgufFile { .checked_add(tensor.offset) .and_then(|start| start.checked_add(offset)) .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(bytes) - .is_none_or(|end| end > self.index.summary.file_size) - { + if absolute.checked_add(bytes).is_none_or(|end| end > self.index.summary.file_size) { return Err("GGUF tensor exceeds indexed file".into()); } self.check_size()?; @@ -180,23 +150,10 @@ impl VerifiedGgufFile { } /// `read_tensor_owned` into caller-owned storage (the huge-page bank buffers of `huge_pages`): the same /// FD, indexed bounds and pre/post size observations; every byte of `bytes` is written on success. - pub(crate) fn read_tensor_into( - &mut self, - tensor_number: usize, - offset: u64, - bytes: &mut [u8], - ) -> Result<()> { + pub(crate) fn read_tensor_into(&mut self, tensor_number: usize, offset: u64, bytes: &mut [u8]) -> Result<()> { let length = u64::try_from(bytes.len())?; - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; - if tensor.bytes == 0 - || offset - .checked_add(length) - .is_none_or(|end| end > tensor.bytes) - { + let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; + if tensor.bytes == 0 || offset.checked_add(length).is_none_or(|end| end > tensor.bytes) { return Err("GGUF tensor byte range is out of bounds".into()); } let absolute = self @@ -206,10 +163,7 @@ impl VerifiedGgufFile { .checked_add(tensor.offset) .and_then(|start| start.checked_add(offset)) .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(length) - .is_none_or(|end| end > self.index.summary.file_size) - { + if absolute.checked_add(length).is_none_or(|end| end > self.index.summary.file_size) { return Err("GGUF tensor exceeds indexed file".into()); } self.check_size()?; @@ -223,12 +177,7 @@ impl VerifiedGgufFile { /// Hash the complete indexed tensor without allocating its full payload. pub fn tensor_sha256(&mut self, tensor_number: usize) -> Result<[u8; 32]> { - let bytes = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")? - .bytes; + let bytes = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?.bytes; let mut digest = Sha256::new(); self.stream_tensor(tensor_number, 0, bytes, |chunk| { digest.update(chunk); diff --git a/crates/model-format/src/gguf/impl_verifiedgguffile/port.rs b/crates/model-format/src/gguf/impl_verifiedgguffile/port.rs index cb4076c7..23e141b2 100644 --- a/crates/model-format/src/gguf/impl_verifiedgguffile/port.rs +++ b/crates/model-format/src/gguf/impl_verifiedgguffile/port.rs @@ -1,9 +1,7 @@ //! A verified GGUF shard as a `WeightSource`: positional reads of the very descriptor that was verified, so the //! shard is read from the file it was hashed from, never from a path reopened. use super::super::*; -use crate::weight_source::{ - BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded, -}; +use crate::weight_source::{BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded}; use std::ops::Range; impl WeightSource for VerifiedGgufFile { @@ -19,11 +17,7 @@ impl WeightSource for VerifiedGgufFile { fn region(&self, range: Range) -> std::result::Result, WeightError> { bounded(&range, self.index.summary.file_size)?; - Ok(Region::Positional { - file: &self.file, - offset: range.start, - len: range.end - range.start, - }) + Ok(Region::Positional { file: &self.file, offset: range.start, len: range.end - range.start }) } fn live_len(&self) -> std::result::Result { diff --git a/crates/model-format/src/gguf/parse_artifact_digest.rs b/crates/model-format/src/gguf/parse_artifact_digest.rs index 9105fa42..af062020 100644 --- a/crates/model-format/src/gguf/parse_artifact_digest.rs +++ b/crates/model-format/src/gguf/parse_artifact_digest.rs @@ -3,11 +3,8 @@ #[allow(unused_imports)] use super::*; - pub(super) fn parse_artifact_digest(value: &str) -> Result<[u8; 32]> { - let hex = value - .strip_prefix("sha256:") - .ok_or("invalid GGUF artifact digest")?; + let hex = value.strip_prefix("sha256:").ok_or("invalid GGUF artifact digest")?; if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { return Err("invalid GGUF artifact digest".into()); } @@ -107,12 +104,10 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result let mut values = BTreeMap::new(); for (key, expected) in required { let value = match snapshot.values.get(key) { - Some(MetadataValue::Unsigned(value)) => u32::try_from(*value).map_err(|_| { - format!("runtime_profile: {key} must be a nonnegative 32-bit integer") - })?, - Some(MetadataValue::Signed(value)) => u32::try_from(*value).map_err(|_| { - format!("runtime_profile: {key} must be a nonnegative 32-bit integer") - })?, + Some(MetadataValue::Unsigned(value)) => u32::try_from(*value) + .map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?, + Some(MetadataValue::Signed(value)) => u32::try_from(*value) + .map_err(|_| format!("runtime_profile: {key} must be a nonnegative 32-bit integer"))?, None => return Err(format!("runtime_profile: missing {key}").into()), _ => return Err(format!("runtime_profile: {key} must be an integer").into()), }; @@ -127,9 +122,7 @@ pub(super) fn validate_flash_next_profile(snapshot: &MetadataSnapshot) -> Result } } if values["qwen4exp.expert_used_count"] > values["qwen4exp.expert_count"] { - return Err( - "runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into(), - ); + return Err("runtime_profile: qwen4exp.expert_used_count exceeds qwen4exp.expert_count".into()); } Ok(()) } diff --git a/crates/model-format/src/gguf/read_index_file.rs b/crates/model-format/src/gguf/read_index_file.rs index b5b22b92..99061c66 100644 --- a/crates/model-format/src/gguf/read_index_file.rs +++ b/crates/model-format/src/gguf/read_index_file.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Result { file.seek(SeekFrom::Start(0))?; let mut cursor = Cursor::new(file, size); @@ -79,29 +78,16 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul let kind = cursor.u32()?; let offset = cursor.u64()?; *types.entry(kind).or_insert(0) += 1; - tensor_index.push(TensorInfo { - name, - dimensions: shape, - kind, - offset, - bytes: 0, - }); + tensor_index.push(TensorInfo { name, dimensions: shape, kind, offset, bytes: 0 }); } let header_end = cursor.position()?; - let data_start = header_end - .checked_add(alignment - 1) - .ok_or("GGUF header offset overflow")? - / alignment - * alignment; + let data_start = + header_end.checked_add(alignment - 1).ok_or("GGUF header offset overflow")? / alignment * alignment; if data_start > size { return Err("GGUF data section is truncated".into()); } for tensor in &tensor_index { - if tensor.offset % alignment != 0 - || data_start - .checked_add(tensor.offset) - .is_none_or(|start| start >= size) - { + if tensor.offset % alignment != 0 || data_start.checked_add(tensor.offset).is_none_or(|start| start >= size) { return Err("GGUF tensor offset is out of bounds or unaligned".into()); } } @@ -116,8 +102,8 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul } for (at, &index) in positions.iter().enumerate() { let tensor = &tensor_index[index]; - let (block_elements, block_bytes) = block_geometry(tensor.kind) - .ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; + let (block_elements, block_bytes) = + block_geometry(tensor.kind).ok_or_else(|| format!("unsupported GGUF tensor type {}", tensor.kind))?; let elements = tensor .dimensions .iter() @@ -130,20 +116,10 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul .checked_div(block_elements) .and_then(|blocks| blocks.checked_mul(block_bytes)) .ok_or("GGUF tensor byte count overflow")?; - let end = tensor - .offset - .checked_add(bytes) - .ok_or("GGUF tensor end overflow")?; - let next = positions - .get(at + 1) - .map(|&next| tensor_index[next].offset) - .unwrap_or(size - data_start); + let end = tensor.offset.checked_add(bytes).ok_or("GGUF tensor end overflow")?; + let next = positions.get(at + 1).map(|&next| tensor_index[next].offset).unwrap_or(size - data_start); if end > next || next - end >= alignment { - return Err(format!( - "{}: tensor bytes overlap or have an invalid gap", - tensor.name - ) - .into()); + return Err(format!("{}: tensor bytes overlap or have an invalid gap", tensor.name).into()); } tensor_index[index].bytes = bytes; } @@ -164,10 +140,7 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul file_size: size, types, }; - Ok(TensorIndex { - summary, - tensors: tensor_index, - }) + Ok(TensorIndex { summary, tensors: tensor_index }) } pub fn block_geometry(kind: u32) -> Option<(u64, u64)> { diff --git a/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs index 58b65b9e..a0033cb7 100644 --- a/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs +++ b/crates/model-format/src/gguf/read_metadata_snapshot_with_architecture.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn read_metadata_snapshot_with_architecture( file: &mut File, size: u64, @@ -38,33 +37,20 @@ pub(super) fn read_metadata_snapshot_with_architecture( } let kind = cursor.u32()?; match key.as_str() { - "general.architecture" if parse_architecture && kind == 8 => { - architecture = Some(cursor.string()?) - } + "general.architecture" if parse_architecture && kind == 8 => architecture = Some(cursor.string()?), "split.no" if kind == 2 => split_no = Some(u64::from(cursor.u16()?)), "split.count" if kind == 2 => split_count = Some(u64::from(cursor.u16()?)), - "split.tensors.count" if kind == 5 => { - split_tensors_count = Some(u64::from(cursor.u32()?)) - } + "split.tensors.count" if kind == 5 => split_tensors_count = Some(u64::from(cursor.u32()?)), "split.no" | "split.count" | "split.tensors.count" => { return Err("GGUF split metadata has an invalid integer type".into()); } - "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => { - model = Some(cursor.string()?) - } + "tokenizer.ggml.model" if parse_tokenizer && kind == 8 => model = Some(cursor.string()?), "tokenizer.ggml.pre" if parse_tokenizer && kind == 8 => pre = Some(cursor.string()?), "tokenizer.ggml.tokens" if parse_tokenizer => tokens = Some(cursor.string_array(kind)?), "tokenizer.ggml.merges" if parse_tokenizer => merges = Some(cursor.string_array(kind)?), - "tokenizer.ggml.token_type" if parse_tokenizer => { - token_types = Some(cursor.integer_array(kind)?) - } - "tokenizer.chat_template" if parse_tokenizer && kind == 8 => { - chat_template = Some(cursor.string()?) - } - _ if parse_tokenizer - && key.starts_with("tokenizer.ggml.") - && key.ends_with("_token_id") => - { + "tokenizer.ggml.token_type" if parse_tokenizer => token_types = Some(cursor.integer_array(kind)?), + "tokenizer.chat_template" if parse_tokenizer && kind == 8 => chat_template = Some(cursor.string()?), + _ if parse_tokenizer && key.starts_with("tokenizer.ggml.") && key.ends_with("_token_id") => { special_ids.insert(key, cursor.integer(kind)?); } _ if qwen_keys.is_some_and(|keys| keys.contains(&key.as_str())) => { @@ -85,38 +71,18 @@ pub(super) fn read_metadata_snapshot_with_architecture( }), _ => None, }; - Ok(MetadataSnapshot { - architecture, - split_no, - split_count, - split_tensors_count, - values, - tokenizer, - }) + Ok(MetadataSnapshot { architecture, split_no, split_count, split_tensors_count, values, tokenizer }) } -pub(crate) fn validate_tokenizer_metadata( - tokenizer: TokenizerMetadata, -) -> Result { - let TokenizerMetadata { - model, - pre, - tokens, - merges, - token_types, - special_ids, - chat_template, - } = tokenizer; +pub(crate) fn validate_tokenizer_metadata(tokenizer: TokenizerMetadata) -> Result { + let TokenizerMetadata { model, pre, tokens, merges, token_types, special_ids, chat_template } = tokenizer; if model != "gpt2" || pre != "qwen35" { return Err("only the qwen35 byte-level BPE tokenizer is supported".into()); } if tokens.is_empty() || chat_template.is_empty() { return Err("GGUF tokenizer has an empty vocabulary or chat template".into()); } - if token_types - .as_ref() - .is_some_and(|types| types.len() != tokens.len()) - { + if token_types.as_ref().is_some_and(|types| types.len() != tokens.len()) { return Err("token_type length differs from vocabulary length".into()); } let vocab: HashSet<&str> = tokens.iter().map(String::as_str).collect(); @@ -143,15 +109,7 @@ pub(crate) fn validate_tokenizer_metadata( return Err("special token ID exceeds vocabulary".into()); } } - Ok(TokenizerMetadata { - model, - pre, - tokens, - merges, - token_types, - special_ids, - chat_template, - }) + Ok(TokenizerMetadata { model, pre, tokens, merges, token_types, special_ids, chat_template }) } pub fn inspect(path: &Path) -> Result { @@ -167,22 +125,12 @@ pub fn tensor_index(path: &Path) -> Result { /// Hash one indexed tensor with a fixed-size buffer. The caller must keep the /// verified source file stable between indexing and reading. pub fn tensor_sha256(path: &Path, index: &TensorIndex, tensor_number: usize) -> Result<[u8; 32]> { - let tensor = index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; + let tensor = index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; if tensor.bytes == 0 { return Err("GGUF tensor index lacks verified byte geometry".into()); } - let absolute = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(tensor.bytes) - .is_none_or(|end| end > index.summary.file_size) - { + let absolute = index.summary.data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?; + if absolute.checked_add(tensor.bytes).is_none_or(|end| end > index.summary.file_size) { return Err("GGUF tensor exceeds indexed file".into()); } let mut file = File::open(path)?; diff --git a/crates/model-format/src/gguf/stream_buffer_bytes.rs b/crates/model-format/src/gguf/stream_buffer_bytes.rs index 99bb6530..a9aab2e9 100644 --- a/crates/model-format/src/gguf/stream_buffer_bytes.rs +++ b/crates/model-format/src/gguf/stream_buffer_bytes.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // Production always uses `STREAM_BUFFER_BYTES`. Tests may shrink the span // stream buffer on their own thread to exercise multi-chunk behaviour with // small fixtures (see `with_test_stream_buffer`). diff --git a/crates/model-format/src/gguf/tests.rs b/crates/model-format/src/gguf/tests.rs index 86122915..d335c14e 100644 --- a/crates/model-format/src/gguf/tests.rs +++ b/crates/model-format/src/gguf/tests.rs @@ -29,9 +29,7 @@ impl OwnedFixture { std::fs::create_dir(&directory).unwrap(); let path = directory.join("fixture.gguf"); let small = (0..16).collect::>(); - let large = (0..STREAM_BUFFER_BYTES * 3 + 11) - .map(|at| (at % 251) as u8) - .collect::>(); + let large = (0..STREAM_BUFFER_BYTES * 3 + 11).map(|at| (at % 251) as u8).collect::>(); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(2u64.to_le_bytes()); @@ -53,22 +51,11 @@ impl OwnedFixture { bytes.extend([0u8; 16]); bytes.extend(&large); std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - small, - large, - kind_at, - offset_at, - } + Self { directory, path, bytes, small, large, kind_at, offset_at } } fn digest(&self) -> String { - let hex = Sha256::digest(&self.bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); + let hex = Sha256::digest(&self.bytes).iter().map(|byte| format!("{byte:02x}")).collect::(); format!("sha256:{hex}") } } @@ -79,10 +66,10 @@ impl Drop for OwnedFixture { } } -#[path = "tests/buffered_cursor_preserves_offsets_parsin.rs"] -mod buffered_cursor_preserves_offsets_parsin; #[path = "tests/admits_flash_metadata_and_rejects.rs"] mod admits_flash_metadata_and_rejects; +#[path = "tests/buffered_cursor_preserves_offsets_parsin.rs"] +mod buffered_cursor_preserves_offsets_parsin; #[path = "tests/empty_owned_tensor_validation_preserves.rs"] mod empty_owned_tensor_validation_preserves; #[path = "tests/original_first_source_fence_retains.rs"] diff --git a/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs index 18d121a8..80fbe356 100644 --- a/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs +++ b/crates/model-format/src/gguf/tests/admits_flash_metadata_and_rejects.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn admits_flash_metadata_and_rejects_incompatible_profiles() { let path = std::env::temp_dir().join(format!("strata-gguf-profile-{}", std::process::id())); @@ -31,24 +30,14 @@ fn admits_flash_metadata_and_rejects_incompatible_profiles() { data.resize(data.len().div_ceil(32) * 32, 0); std::fs::write(&path, data).unwrap(); }; - let good = || { - fields - .iter() - .map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())) - .collect::>() - }; + let good = || fields.iter().map(|(k, v)| (*k, 4, v.to_le_bytes().to_vec())).collect::>(); write(good()); check_flash_next_profile(&path).unwrap(); for index in 0..fields.len() { let mut entries = good(); entries.remove(index); write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains(fields[index].0) - ); + assert!(check_flash_next_profile(&path).unwrap_err().to_string().contains(fields[index].0)); let mut entries = good(); entries[index].2 = 0u32.to_le_bytes().to_vec(); write(entries); @@ -58,12 +47,7 @@ fn admits_flash_metadata_and_rejects_incompatible_profiles() { let mut entries = good(); entries[index].2 = (fields[index].1 + 1).to_le_bytes().to_vec(); write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains("expected") - ); + assert!(check_flash_next_profile(&path).unwrap_err().to_string().contains("expected")); } for (kind, bytes) in [ (7, vec![1]), @@ -74,12 +58,7 @@ fn admits_flash_metadata_and_rejects_incompatible_profiles() { let mut entries = good(); entries[0] = (fields[0].0, kind, bytes); write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains(fields[0].0) - ); + assert!(check_flash_next_profile(&path).unwrap_err().to_string().contains(fields[0].0)); } let mut entries = good(); entries[4].2 = 256u32.to_le_bytes().to_vec(); @@ -88,12 +67,7 @@ fn admits_flash_metadata_and_rejects_incompatible_profiles() { let mut entries = good(); entries[5].2 = 513u32.to_le_bytes().to_vec(); write(entries); - assert!( - check_flash_next_profile(&path) - .unwrap_err() - .to_string() - .contains("exceeds") - ); + assert!(check_flash_next_profile(&path).unwrap_err().to_string().contains("exceeds")); for kind in [0, 1, 2, 3, 4, 5, 10, 11] { let mut entries = good(); let bytes = 48u64.to_le_bytes(); @@ -189,17 +163,11 @@ fn indexes_exact_mixed_tensor_spans_and_rejects_bad_layouts() { fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_chunks() { let fixture = OwnedFixture::new(); let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); + assert_eq!(source.artifact_sha256(), <[u8; 32]>::from(Sha256::digest(&fixture.bytes))); assert_eq!(source.index().tensors.len(), 2); assert_eq!(source.index().tensors[1].bytes, fixture.large.len() as u64); for (number, expected) in [(0, &fixture.small), (1, &fixture.large)] { - assert_eq!( - source.tensor_sha256(number).unwrap(), - <[u8; 32]>::from(Sha256::digest(expected)) - ); + assert_eq!(source.tensor_sha256(number).unwrap(), <[u8; 32]>::from(Sha256::digest(expected))); } let mut seen = 0; let mut callbacks = 0; @@ -227,13 +195,9 @@ fn owned_handle_verifies_artifact_and_streams_exact_tensor_bytes_with_bounded_ch #[test] fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { let fixture = OwnedFixture::new(); - for digest in [ - "", - "abc", - "sha256:abc", - &format!("sha256:{}", "g".repeat(64)), - &format!("SHA256:{}", "a".repeat(64)), - ] { + for digest in + ["", "abc", "sha256:abc", &format!("sha256:{}", "g".repeat(64)), &format!("SHA256:{}", "a".repeat(64))] + { assert!( VerifiedGgufFile::open(&fixture.path, digest) .unwrap_err() @@ -242,19 +206,13 @@ fn owned_handle_rejects_bad_digest_nonregular_sources_and_tampering() { ); } assert!( - VerifiedGgufFile::open(&fixture.directory, &fixture.digest()) - .unwrap_err() - .to_string() - .contains("regular file") + VerifiedGgufFile::open(&fixture.directory, &fixture.digest()).unwrap_err().to_string().contains("regular file") ); let mut tampered = fixture.bytes.clone(); *tampered.last_mut().unwrap() ^= 1; std::fs::write(&fixture.path, tampered).unwrap(); assert!( - VerifiedGgufFile::open(&fixture.path, &fixture.digest()) - .unwrap_err() - .to_string() - .contains("SHA256 mismatch") + VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap_err().to_string().contains("SHA256 mismatch") ); } @@ -268,17 +226,12 @@ fn owned_handle_rejects_truncated_unsupported_and_bad_geometry_even_with_matchin 0 => { fixture.bytes.pop(); } - 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4] - .copy_from_slice(&u32::MAX.to_le_bytes()), - 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8] - .copy_from_slice(&0u64.to_le_bytes()), + 1 => fixture.bytes[fixture.kind_at..fixture.kind_at + 4].copy_from_slice(&u32::MAX.to_le_bytes()), + 2 => fixture.bytes[fixture.offset_at..fixture.offset_at + 8].copy_from_slice(&0u64.to_le_bytes()), 3 => fixture.bytes[4..8].copy_from_slice(&2u32.to_le_bytes()), _ => unreachable!(), } std::fs::write(&fixture.path, &fixture.bytes).unwrap(); - assert!( - VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), - "fault {fault}" - ); + assert!(VerifiedGgufFile::open(&fixture.path, &fixture.digest()).is_err(), "fault {fault}"); } } diff --git a/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs index 350421df..65201e42 100644 --- a/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs +++ b/crates/model-format/src/gguf/tests/buffered_cursor_preserves_offsets_parsin.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { struct Counted { @@ -37,12 +36,7 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { bytes.resize(bytes.len() + skipped, 0); bytes.extend(0x5678u16.to_le_bytes()); let length = bytes.len() as u64; - let counted = Counted { - bytes: std::io::Cursor::new(bytes), - reads: 0, - seeks: 0, - requests: Vec::new(), - }; + let counted = Counted { bytes: std::io::Cursor::new(bytes), reads: 0, seeks: 0, requests: Vec::new() }; let mut cursor = Cursor::with_test_capacity(counted, length, SMALL_CAPACITY); for _ in 0..512 { assert_eq!(cursor.u32().unwrap(), 0x10203040); @@ -64,26 +58,12 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { assert_eq!(cursor.position().unwrap(), length); assert_eq!(cursor.file.get_ref().reads, 3); assert!(cursor.file.get_ref().requests.iter().all(|n| *n == 65536)); - assert_eq!( - cursor.skip(1).unwrap_err().to_string(), - "truncated GGUF header" - ); - assert_eq!( - cursor.u8().unwrap_err().to_string(), - "truncated GGUF header" - ); - assert_eq!( - cursor.skip(u64::MAX).unwrap_err().to_string(), - "GGUF offset overflow" - ); + assert_eq!(cursor.skip(1).unwrap_err().to_string(), "truncated GGUF header"); + assert_eq!(cursor.u8().unwrap_err().to_string(), "truncated GGUF header"); + assert_eq!(cursor.skip(u64::MAX).unwrap_err().to_string(), "GGUF offset overflow"); let mut production = Cursor::new( - Counted { - bytes: std::io::Cursor::new(vec![0x78, 0x56, 0x34, 0x12]), - reads: 0, - seeks: 0, - requests: Vec::new(), - }, + Counted { bytes: std::io::Cursor::new(vec![0x78, 0x56, 0x34, 0x12]), reads: 0, seeks: 0, requests: Vec::new() }, 4, ); assert_eq!(production.file.capacity(), 16 * 1024 * 1024); @@ -94,29 +74,15 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { let mut short = Cursor::new(std::io::Cursor::new(vec![0u8; 3]), 4); assert_eq!( - short - .u32() - .unwrap_err() - .downcast_ref::() - .unwrap() - .kind(), + short.u32().unwrap_err().downcast_ref::().unwrap().kind(), std::io::ErrorKind::UnexpectedEof ); let mut oversized = Cursor::new(std::io::Cursor::new(1_048_577u64.to_le_bytes()), 8); - assert_eq!( - oversized.string().unwrap_err().to_string(), - "GGUF header string is too large" - ); + assert_eq!(oversized.string().unwrap_err().to_string(), "GGUF header string is too large"); let mut bad = Cursor::new(std::io::Cursor::new(9u32.to_le_bytes()), 4); - assert_eq!( - bad.skip_value(9).unwrap_err().to_string(), - "truncated GGUF header" - ); + assert_eq!(bad.skip_value(9).unwrap_err().to_string(), "truncated GGUF header"); let mut bad = Cursor::new(std::io::Cursor::new(Vec::new()), 0); - assert_eq!( - bad.skip_value(99).unwrap_err().to_string(), - "unknown GGUF metadata type 99" - ); + assert_eq!(bad.skip_value(99).unwrap_err().to_string(), "unknown GGUF metadata type 99"); // Actual parser entrypoints: literal metadata, a skipped long string, // logical header alignment, and a subsequent read of the original FD. @@ -147,18 +113,12 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { std::fs::write(&fixture.path, &fixture.bytes).unwrap(); let mut verified = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); assert_eq!(verified.index().summary.data_start, data_start as u64); - assert_eq!( - verified.index().summary.architecture.as_deref(), - Some("qwen4exp") - ); + assert_eq!(verified.index().summary.architecture.as_deref(), Some("qwen4exp")); assert_eq!(verified.index().tensors[0].name, "weight"); assert_eq!(verified.index().tensors[0].bytes, 16); let snapshot = verified.profile_snapshot().unwrap(); assert_eq!(snapshot.architecture.as_deref(), Some("qwen4exp")); - assert!(matches!( - snapshot.values.get("qwen4exp.block_count"), - Some(MetadataValue::Unsigned(48)) - )); + assert!(matches!(snapshot.values.get("qwen4exp.block_count"), Some(MetadataValue::Unsigned(48)))); let mut payload = Vec::new(); verified .stream_tensor(0, 0, 16, |chunk| { @@ -167,10 +127,7 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { }) .unwrap(); assert_eq!(payload, [0x11u8, 0x22, 0x33, 0x44].repeat(4)); - assert_eq!( - verified.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); + assert_eq!(verified.artifact_sha256(), <[u8; 32]>::from(Sha256::digest(&fixture.bytes))); let mut duplicate = b"GGUF".to_vec(); duplicate.extend(3u32.to_le_bytes()); @@ -187,17 +144,12 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { read_index_file(&mut file, duplicate.len() as u64, false).map(|_| ()), read_metadata_snapshot(&mut file, duplicate.len() as u64, None, false).map(|_| ()), ] { - assert_eq!( - result.unwrap_err().to_string(), - "duplicate GGUF metadata key: general.architecture" - ); + assert_eq!(result.unwrap_err().to_string(), "duplicate GGUF metadata key: general.architecture"); } // The production span bound is exercised independently of header strings // (whose existing one-MiB limit remains intact). - let span = (0..STREAM_BUFFER_BYTES + 19) - .map(|at| (at % 251) as u8) - .collect::>(); + let span = (0..STREAM_BUFFER_BYTES + 19).map(|at| (at % 251) as u8).collect::>(); std::fs::write(&fixture.path, &span).unwrap(); let mut file = File::open(&fixture.path).unwrap(); let mut seen = 0; @@ -229,11 +181,9 @@ fn buffered_cursor_preserves_offsets_parsing_and_refusals_with_bounded_reads() { std::io::ErrorKind::UnexpectedEof ); assert_eq!( - stream_file_span(&mut file, 0, 17, |_| { - Err(std::io::Error::other("consumer sentinel")) - }) - .unwrap_err() - .to_string(), + stream_file_span(&mut file, 0, 17, |_| { Err(std::io::Error::other("consumer sentinel")) }) + .unwrap_err() + .to_string(), "consumer sentinel" ); } diff --git a/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs index 5f667f42..5b487d91 100644 --- a/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs +++ b/crates/model-format/src/gguf/tests/empty_owned_tensor_validation_preserves.rs @@ -3,23 +3,16 @@ #[allow(unused_imports)] use super::*; - #[test] fn empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks() { let fixture = OwnedFixture::new(); let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); source.file.seek(SeekFrom::Start(3)).unwrap(); - source - .stream_tensor(0, 16, 0, |_| panic!("empty span invoked consumer")) - .unwrap(); + source.stream_tensor(0, 16, 0, |_| panic!("empty span invoked consumer")).unwrap(); assert_eq!(source.file.stream_position().unwrap(), 3); for (number, offset) in [(2, 0), (0, 17), (0, u64::MAX)] { assert!( - source - .stream_tensor(number, offset, 0, |_| { - panic!("invalid empty span invoked consumer") - }) - .is_err() + source.stream_tensor(number, offset, 0, |_| { panic!("invalid empty span invoked consumer") }).is_err() ); assert_eq!(source.file.stream_position().unwrap(), 3); } @@ -31,9 +24,7 @@ fn empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks() { .unwrap(); assert!( source - .stream_tensor(0, 16, 0, |_| { - panic!("changed-size empty span invoked consumer") - }) + .stream_tensor(0, 16, 0, |_| { panic!("changed-size empty span invoked consumer") }) .unwrap_err() .to_string() .contains("size changed") @@ -45,13 +36,7 @@ fn empty_owned_tensor_validation_preserves_cursor_bounds_and_size_checks() { fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() { let fixture = OwnedFixture::new(); let mut source = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - for (number, offset, bytes) in [ - (2, 0, 1), - (0, 0, 17), - (0, 17, 0), - (0, u64::MAX, 1), - (0, 1, u64::MAX), - ] { + for (number, offset, bytes) in [(2, 0, 1), (0, 0, 17), (0, 17, 0), (0, u64::MAX, 1), (0, 1, u64::MAX)] { let mut called = false; assert!( source @@ -63,22 +48,15 @@ fn owned_tensor_bounds_are_checked_before_any_callback_and_stream_can_recover() ); assert!(!called); } - source - .stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")) - .unwrap(); + source.stream_tensor(0, 16, 0, |_| panic!("empty range invoked consumer")).unwrap(); assert!( source - .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other( - "synthetic consumer failure" - ))) + .stream_tensor(1, 0, 10, |_| Err(std::io::Error::other("synthetic consumer failure"))) .unwrap_err() .to_string() .contains("synthetic consumer failure") ); - assert_eq!( - source.tensor_sha256(0).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.small)) - ); + assert_eq!(source.tensor_sha256(0).unwrap(), <[u8; 32]>::from(Sha256::digest(&fixture.small))); } #[cfg(unix)] @@ -89,10 +67,7 @@ fn pathname_replacement_keeps_original_verified_file_and_index() { std::fs::rename(&fixture.path, fixture.directory.join("original.gguf")).unwrap(); std::fs::write(&fixture.path, b"replacement is not a GGUF file").unwrap(); assert!(tensor_index(&fixture.path).is_err()); - assert_eq!( - source.tensor_sha256(1).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.large)) - ); + assert_eq!(source.tensor_sha256(1).unwrap(), <[u8; 32]>::from(Sha256::digest(&fixture.large))); let mut small = Vec::new(); source .stream_tensor(0, 0, 16, |chunk| { @@ -101,10 +76,7 @@ fn pathname_replacement_keeps_original_verified_file_and_index() { }) .unwrap(); assert_eq!(small, fixture.small); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); + assert_eq!(source.artifact_sha256(), <[u8; 32]>::from(Sha256::digest(&fixture.bytes))); } #[test] @@ -115,20 +87,9 @@ fn opened_file_size_changes_are_refused_and_same_size_mutation_is_not_immutabili *mutated.last_mut().unwrap() ^= 1; std::fs::write(&fixture.path, &mutated).unwrap(); // Explicit counterexample: retaining the descriptor does not freeze bytes. - assert_ne!( - source.tensor_sha256(1).unwrap(), - <[u8; 32]>::from(Sha256::digest(&fixture.large)) - ); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&fixture.bytes)) - ); - std::fs::OpenOptions::new() - .write(true) - .open(&fixture.path) - .unwrap() - .set_len(0) - .unwrap(); + assert_ne!(source.tensor_sha256(1).unwrap(), <[u8; 32]>::from(Sha256::digest(&fixture.large))); + assert_eq!(source.artifact_sha256(), <[u8; 32]>::from(Sha256::digest(&fixture.bytes))); + std::fs::OpenOptions::new().write(true).open(&fixture.path).unwrap().set_len(0).unwrap(); let mut called = false; assert!( source diff --git a/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs index 1dff2214..069e4be5 100644 --- a/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs +++ b/crates/model-format/src/gguf/tests/original_first_source_fence_retains.rs @@ -22,10 +22,7 @@ fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_chang let _cleanup = Remove(directory.clone()); let path = directory.join("source.gguf"); // Real bounded verified source, not a synthetic model/Binding/row. - let expected: Vec = [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .flat_map(u32::to_le_bytes) - .collect(); + let expected: Vec = [0x80000000u32, 0, 0x3f800000, 0xbf800000].into_iter().flat_map(u32::to_le_bytes).collect(); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(1u64.to_le_bytes()); @@ -39,18 +36,10 @@ fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_chang bytes.extend(&expected); assert!(bytes.len() <= 128); std::fs::write(&path, &bytes).unwrap(); - let digest = format!( - "sha256:{}", - Sha256::digest(&bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::() - ); + let digest = format!("sha256:{}", Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::()); let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); // ORIGINAL empty descriptor + actual stream FIRST, before new scope. - source - .stream_tensor(0, 0, 0, |_| panic!("emptyspan callback")) - .unwrap(); + source.stream_tensor(0, 0, 0, |_| panic!("emptyspan callback")).unwrap(); let mut original = Vec::new(); source .stream_tensor(0, 0, 16, |chunk| { @@ -129,10 +118,7 @@ fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_chang let mut fence = source.begin_source_fence(0).unwrap(); let error = fence .stream_tensor(0, 0, 16, |_| { - Err(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "public source consumer refusal", - )) + Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "public source consumer refusal")) }) .unwrap_err(); assert!(error.to_string().contains("public source consumer refusal")); @@ -160,9 +146,6 @@ fn original_first_source_fence_retains_opened_fd_cursor_and_refuses_length_chang fence.finish().unwrap(); assert_eq!(actual, original); assert_eq!(actual, expected); - assert_eq!( - source.artifact_sha256(), - <[u8; 32]>::from(Sha256::digest(&bytes)) - ); + assert_eq!(source.artifact_sha256(), <[u8; 32]>::from(Sha256::digest(&bytes))); drop(source); } diff --git a/crates/model-format/src/gguf/value_width.rs b/crates/model-format/src/gguf/value_width.rs index e52c7c17..4bb85b87 100644 --- a/crates/model-format/src/gguf/value_width.rs +++ b/crates/model-format/src/gguf/value_width.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn value_width(kind: u32) -> Result { match kind { 0 | 1 | 7 => Ok(1), @@ -26,8 +25,7 @@ impl GgufSourceFence<'_> { ) -> Result<()> { // Real misses preserve the original full range and before/after source // checks, cursor behavior, read errors and bounded stream buffer. - self.source - .stream_tensor(tensor_number, offset, bytes, consume) + self.source.stream_tensor(tensor_number, offset, bytes, consume) } pub(crate) fn read_tensor_owned( &mut self, @@ -53,29 +51,17 @@ impl VerifiedGgufFile { } pub(super) fn validate_empty_tensor_span(&self, tensor_number: usize) -> Result<()> { - let tensor = self - .index - .tensors - .get(tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; + let tensor = self.index.tensors.get(tensor_number).ok_or("GGUF tensor index is out of bounds")?; if tensor.bytes == 0 { return Err("GGUF tensor byte range is out of bounds".into()); } - let absolute = self - .index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or("GGUF tensor offset overflow")?; + let absolute = self.index.summary.data_start.checked_add(tensor.offset).ok_or("GGUF tensor offset overflow")?; if absolute > self.index.summary.file_size { return Err("GGUF tensor exceeds indexed file".into()); } Ok(()) } - pub(crate) fn begin_source_fence( - &mut self, - tensor_number: usize, - ) -> Result> { + pub(crate) fn begin_source_fence(&mut self, tensor_number: usize) -> Result> { // Exactly the original first empty-span geometry precedes the first // size observation. No seek, read, allocation or cursor mutation. self.validate_empty_tensor_span(tensor_number)?; diff --git a/crates/model-format/src/gguf_digest_capture.rs b/crates/model-format/src/gguf_digest_capture.rs index 91270648..8532ebbc 100644 --- a/crates/model-format/src/gguf_digest_capture.rs +++ b/crates/model-format/src/gguf_digest_capture.rs @@ -7,9 +7,7 @@ pub(crate) fn open_expert_capture( expected_digest: &str, retained_kar: Option<&File>, ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource)> { - open_with_capture(path, expected_digest, |index| { - ProvisionalExpertSource::prepare(index, retained_kar) - }) + open_with_capture(path, expected_digest, |index| ProvisionalExpertSource::prepare(index, retained_kar)) } fn open_with_capture( @@ -52,12 +50,7 @@ fn open_with_capture( if file.metadata()?.len() != size { return Err("GGUF source size changed during indexing".into()); } - let mut verified = VerifiedGgufFile { - file, - index, - artifact_sha256: actual_digest, - resident_source_id: None, - }; + let mut verified = VerifiedGgufFile { file, index, artifact_sha256: actual_digest, resident_source_id: None }; capture.bind_verified(&mut verified); Ok((verified, capture)) } @@ -134,29 +127,16 @@ fn read_provisional_index(file: &mut File, size: u64, strict: bool) -> Result size { return Err("GGUF data section is truncated".into()); } for tensor in &tensor_index { - if tensor.offset % alignment != 0 - || data_start - .checked_add(tensor.offset) - .is_none_or(|start| start >= size) - { + if tensor.offset % alignment != 0 || data_start.checked_add(tensor.offset).is_none_or(|start| start >= size) { return Err("GGUF tensor offset is out of bounds or unaligned".into()); } } @@ -171,8 +151,8 @@ fn read_provisional_index(file: &mut File, size: u64, strict: bool) -> Result Result next || next - end >= alignment { - return Err(format!( - "{}: tensor bytes overlap or have an invalid gap", - tensor.name - ) - .into()); + return Err(format!("{}: tensor bytes overlap or have an invalid gap", tensor.name).into()); } tensor_index[index].bytes = bytes; } @@ -219,10 +189,7 @@ fn read_provisional_index(file: &mut File, size: u64, strict: bool) -> Result, ) -> Result<(VerifiedGgufFile, ProvisionalExpertSource)> { - open_with_capture(path, expected_digest, |index| { - ProvisionalExpertSource::prepare_incremental(index, retained_kar) - }) + open_with_capture(path, expected_digest, |index| ProvisionalExpertSource::prepare_incremental(index, retained_kar)) } diff --git a/crates/model-format/src/gguf_digest_capture_sdet.rs b/crates/model-format/src/gguf_digest_capture_sdet.rs index 797e045b..f17e77f7 100644 --- a/crates/model-format/src/gguf_digest_capture_sdet.rs +++ b/crates/model-format/src/gguf_digest_capture_sdet.rs @@ -13,14 +13,8 @@ struct Fixture { } impl Fixture { fn new() -> Self { - let nonce = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let directory = std::env::temp_dir().join(format!( - "strata-digest-capture-{}-{nonce}", - std::process::id() - )); + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let directory = std::env::temp_dir().join(format!("strata-digest-capture-{}-{nonce}", std::process::id())); std::fs::create_dir(&directory).unwrap(); let path = directory.join("public.gguf"); let mut bytes = b"GGUF".to_vec(); @@ -35,19 +29,11 @@ impl Fixture { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .cycle() - .take(16) - { + for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - } + Self { directory, path, bytes } } fn digest(&self) -> String { format!("sha256:{}", hex(&Sha256::digest(&self.bytes))) @@ -82,22 +68,13 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner Ok(()) }) .unwrap(); - assert_eq!( - format!("sha256:{}", hex(&digest.finalize())), - fixture.digest() - ); + assert_eq!(format!("sha256:{}", hex(&digest.finalize())), fixture.digest()); assert_eq!(candidate.test_bytes().unwrap(), expected); let resident = candidate.test_mint(&mut original).unwrap(); - let out = original - .copy_resident_tensor(&resident, 3, vec![0; 17].into_boxed_slice()) - .unwrap(); + let out = original.copy_resident_tensor(&resident, 3, vec![0; 17].into_boxed_slice()).unwrap(); assert_eq!(&*out, &expected[3..20]); let foreign = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert!( - foreign - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .is_err() - ); + assert!(foreign.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); // Independent chunk sizes exercise exact overlaps, prefix/tail and zero // chunks. These private fixture cells cannot publish a Qwen model bank. for width in 1..=fixture.bytes.len() + 1 { @@ -123,14 +100,9 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner let (new, deferred) = open_expert_capture(&fixture.path, &fixture.digest(), None).unwrap(); assert!(deferred.test_discarded()); assert_eq!(new.artifact_sha256(), original.artifact_sha256()); - assert_eq!( - new.index().summary.file_size, - original.index().summary.file_size - ); + assert_eq!(new.index().summary.file_size, original.index().summary.file_size); let wrong = format!("sha256:{}", "0".repeat(64)); - let old = VerifiedGgufFile::open(&fixture.path, &wrong) - .unwrap_err() - .to_string(); + let old = VerifiedGgufFile::open(&fixture.path, &wrong).unwrap_err().to_string(); let new = match open_expert_capture(&fixture.path, &wrong, None) { Err(error) => error.to_string(), Ok(_) => panic!("wrong digest must fail"), @@ -143,9 +115,7 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner let malformed_path = fixture.directory.join("malformed.gguf"); std::fs::write(&malformed_path, &malformed).unwrap(); let actual_digest = format!("sha256:{}", hex(&Sha256::digest(&malformed))); - let old = VerifiedGgufFile::open(&malformed_path, &actual_digest) - .unwrap_err() - .to_string(); + let old = VerifiedGgufFile::open(&malformed_path, &actual_digest).unwrap_err().to_string(); let new = match open_expert_capture(&malformed_path, &actual_digest, None) { Err(error) => error.to_string(), Ok(_) => panic!("bad index must fail"), @@ -156,23 +126,9 @@ fn original_stream_first_digest_capture_bytes_priority_coverage_and_source_owner let retained = fixture.directory.join("retained.gguf"); std::fs::rename(&fixture.path, &retained).unwrap(); std::fs::write(&fixture.path, b"unrelated path").unwrap(); - assert_eq!( - &*original - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .unwrap(), - expected - ); - std::fs::OpenOptions::new() - .write(true) - .open(&retained) - .unwrap() - .set_len(1) - .unwrap(); - assert!( - original - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .is_err() - ); + assert_eq!(&*original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).unwrap(), expected); + std::fs::OpenOptions::new().write(true).open(&retained).unwrap().set_len(1).unwrap(); + assert!(original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); drop(resident); drop(foreign); drop(original); diff --git a/crates/model-format/src/gguf_native_head.rs b/crates/model-format/src/gguf_native_head.rs index 4381b8cd..15731624 100644 --- a/crates/model-format/src/gguf_native_head.rs +++ b/crates/model-format/src/gguf_native_head.rs @@ -1,8 +1,6 @@ //! Literal Original GgufModel head/embedding admission over genuinely verified FDs. //! Child of gguf; snapshots parse the SAME FD, never an asserted host certificate. -use super::{ - FLASH_NEXT_PROFILE_KEYS, MetadataValue, Result, VerifiedGgufFile, read_metadata_snapshot, -}; +use super::{FLASH_NEXT_PROFILE_KEYS, MetadataValue, Result, VerifiedGgufFile, read_metadata_snapshot}; use std::{collections::BTreeMap, path::Path}; pub struct NativeHeadGgufModel { shards: Vec, @@ -73,10 +71,7 @@ impl NativeHeadGgufModel { } /// Original split/order/duplicate/architecture admission, preserving the real /// source/index pair. Existing verified owners avoid an additional digest pass. - pub fn from_verified( - mut shards: Vec, - embedding_override: bool, - ) -> Result { + pub fn from_verified(mut shards: Vec, embedding_override: bool) -> Result { if shards.is_empty() { return Err("GGUF model has no shards".into()); } @@ -100,9 +95,7 @@ impl NativeHeadGgufModel { { return Err("GGUF split metadata/order mismatch".into()); } - count = count - .checked_add(g.index.tensors.len() as u64) - .ok_or("GGUF tensor count overflow")?; + count = count.checked_add(g.index.tensors.len() as u64).ok_or("GGUF tensor count overflow")?; } if total.is_some_and(|total| total != count) { return Err("GGUF split tensor count mismatch".into()); @@ -118,15 +111,10 @@ impl NativeHeadGgufModel { } let g = &mut shards[0]; g.check_size()?; - let snapshot = read_metadata_snapshot( - &mut g.file, - g.index.summary.file_size, - Some(FLASH_NEXT_PROFILE_KEYS), - false, - )?; + let snapshot = + read_metadata_snapshot(&mut g.file, g.index.summary.file_size, Some(FLASH_NEXT_PROFILE_KEYS), false)?; g.check_size()?; - let override_file = - embedding_override && snapshot.architecture.as_deref() == Some("strata-embd"); + let override_file = embedding_override && snapshot.architecture.as_deref() == Some("strata-embd"); if !override_file { if snapshot.architecture.as_deref() != Some("qwen4exp") { return Err("native head architecture requires qwen4exp".into()); @@ -149,11 +137,7 @@ impl NativeHeadGgufModel { } } } - Ok(Self { - shards, - names, - embedding_override: override_file, - }) + Ok(Self { shards, names, embedding_override: override_file }) } pub fn load_head(&mut self, n: usize, vocab: usize) -> Result { if self.embedding_override { @@ -164,62 +148,33 @@ impl NativeHeadGgufModel { pub fn load_embedding(&mut self, n: usize, vocab: usize) -> Result { self.load("token_embd.weight", n, vocab, true) } - fn load( - &mut self, - name: &str, - n: usize, - vocab: usize, - embedding: bool, - ) -> Result { - if n == 0 - || vocab == 0 - || n > i32::MAX as usize - || vocab > i32::MAX as usize - || !n.is_multiple_of(256) - { + fn load(&mut self, name: &str, n: usize, vocab: usize, embedding: bool) -> Result { + if n == 0 || vocab == 0 || n > i32::MAX as usize || vocab > i32::MAX as usize || !n.is_multiple_of(256) { return Err("native head positive int32/whole256 dimensions".into()); } let &(shard, index) = self.names.get(name).ok_or("native output tensor absent")?; let g = &mut self.shards[shard]; let t = &g.index.tensors[index]; let supported = if embedding { - matches!( - t.kind, - 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42 - ) + matches!(t.kind, 7 | 8 | 11 | 12 | 13 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 30 | 42) } else { - matches!( - t.kind, - 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42 - ) + matches!(t.kind, 2 | 6 | 7 | 8 | 11 | 12 | 13 | 14 | 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42) }; if !supported || t.dimensions != [n as u64, vocab as u64] { return Err("native output unsupported kind/shape".into()); } - let bytes = row_bytes(t.kind, n) - .and_then(|r| r.checked_mul(vocab)) - .ok_or("native output byte extent overflow")?; - let payload = g - .index - .summary - .file_size - .checked_sub(g.index.summary.data_start) - .ok_or("native output payload extent")?; - if t.offset > payload - || bytes as u64 > payload - t.offset - || embedding && t.bytes != bytes as u64 - { + let bytes = + row_bytes(t.kind, n).and_then(|r| r.checked_mul(vocab)).ok_or("native output byte extent overflow")?; + let payload = + g.index.summary.file_size.checked_sub(g.index.summary.data_start).ok_or("native output payload extent")?; + if t.offset > payload || bytes as u64 > payload - t.offset || embedding && t.bytes != bytes as u64 { return Err("native output tensor payload truncated/extent mismatch".into()); } let kind = t.kind; let mut out = Vec::new(); out.try_reserve_exact(bytes)?; g.stream_tensor(index, 0, bytes as u64, |part| { - if out - .len() - .checked_add(part.len()) - .is_none_or(|end| end > bytes) - { + if out.len().checked_add(part.len()).is_none_or(|end| end > bytes) { return Err(std::io::Error::from(std::io::ErrorKind::InvalidData)); } out.extend_from_slice(part); diff --git a/crates/model-format/src/gguf_owned_read_test.rs b/crates/model-format/src/gguf_owned_read_test.rs index 7cff0ba0..846d0913 100644 --- a/crates/model-format/src/gguf_owned_read_test.rs +++ b/crates/model-format/src/gguf_owned_read_test.rs @@ -9,12 +9,8 @@ struct Fixture { } impl Fixture { fn new() -> Self { - let nonce = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let directory = - std::env::temp_dir().join(format!("strata-owned-read-{}-{nonce}", std::process::id())); + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let directory = std::env::temp_dir().join(format!("strata-owned-read-{}-{nonce}", std::process::id())); std::fs::create_dir(&directory).unwrap(); let path = directory.join("tiny.gguf"); let mut bytes = b"GGUF".to_vec(); @@ -29,26 +25,15 @@ impl Fixture { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .cycle() - .take(16) - { + for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } assert!(bytes.len() <= 192); std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - } + Self { directory, path, bytes } } fn open(&self) -> VerifiedGgufFile { - let hex = Sha256::digest(&self.bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); + let hex = Sha256::digest(&self.bytes).iter().map(|b| format!("{b:02x}")).collect::(); VerifiedGgufFile::open(&self.path, &format!("sha256:{hex}")).unwrap() } } @@ -96,13 +81,10 @@ fn original_stream_first_owned_spans_preserve_bytes_cursor_bounds_and_read_error } for (number, offset, n) in [(1, 0, 4), (0, 64, 1), (0, u64::MAX, 4)] { source.file.seek(SeekFrom::Start(11)).unwrap(); - let original_error = source - .stream_tensor(number, offset, n as u64, |_| panic!("invalid callback")) - .unwrap_err(); + let original_error = + source.stream_tensor(number, offset, n as u64, |_| panic!("invalid callback")).unwrap_err(); assert_eq!(source.file.stream_position().unwrap(), 11); - let new_error = source - .read_tensor_owned(number, offset, initialized(n)) - .unwrap_err(); + let new_error = source.read_tensor_owned(number, offset, initialized(n)).unwrap_err(); assert_eq!(new_error.to_string(), original_error.to_string()); assert_eq!(source.file.stream_position().unwrap(), 11); } @@ -111,18 +93,10 @@ fn original_stream_first_owned_spans_preserve_bytes_cursor_bounds_and_read_error std::fs::rename(&fixture.path, fixture.directory.join("retained.gguf")).unwrap(); std::fs::write(&fixture.path, b"different path occupant").unwrap(); let reference = original(&mut source, 0, 64).unwrap(); - assert_eq!( - &*source.read_tensor_owned(0, 0, initialized(64)).unwrap(), - reference - ); + assert_eq!(&*source.read_tensor_owned(0, 0, initialized(64)).unwrap(), reference); // Changed source length refuses before seek; the owner is discarded. let retained = fixture.directory.join("retained.gguf"); - std::fs::OpenOptions::new() - .write(true) - .open(&retained) - .unwrap() - .set_len((fixture.bytes.len() - 1) as u64) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&retained).unwrap().set_len((fixture.bytes.len() - 1) as u64).unwrap(); source.file.seek(SeekFrom::Start(9)).unwrap(); let old = original(&mut source, 0, 64).unwrap_err(); let new = source.read_tensor_owned(0, 0, initialized(64)).unwrap_err(); @@ -143,8 +117,7 @@ fn original_stream_first_owned_spans_preserve_bytes_cursor_bounds_and_read_error ); assert_eq!(new.stream_position().unwrap(), old_cursor); let mut old = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - let old_error = - stream_file_span(&mut old, 0, 3, |_| panic!("write-only consumer")).unwrap_err(); + let old_error = stream_file_span(&mut old, 0, 3, |_| panic!("write-only consumer")).unwrap_err(); let old_cursor = old.stream_position().unwrap(); let mut new = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); let error = read_file_span_owned(&mut new, 0, initialized(3)).unwrap_err(); diff --git a/crates/model-format/src/gguf_resident.rs b/crates/model-format/src/gguf_resident.rs index f9a7e254..e6b60a5c 100644 --- a/crates/model-format/src/gguf_resident.rs +++ b/crates/model-format/src/gguf_resident.rs @@ -49,14 +49,8 @@ mod retained_lease_test { use super::*; #[test] fn original_file_first_retained_box_address_and_foreign_source_refusal() { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = std::env::temp_dir().join(format!( - "strata-bank-lease-{}-{nonce}.gguf", - std::process::id() - )); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("strata-bank-lease-{}-{nonce}.gguf", std::process::id())); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(1u64.to_le_bytes()); @@ -69,18 +63,11 @@ mod retained_lease_test { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .cycle() - .take(16) - { + for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } std::fs::write(&path, &bytes).unwrap(); - let hex = Sha256::digest(&bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); + let hex = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::(); let digest = format!("sha256:{hex}"); let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); let mut original = Vec::new(); @@ -106,12 +93,7 @@ mod retained_lease_test { let foreign_owner = foreign.load_resident_tensor(0, 64).unwrap().into_retained(); assert!(foreign.validate_retained_tensor(&lease).is_err()); assert!(source.validate_retained_tensor(&foreign_owner).is_err()); - std::fs::OpenOptions::new() - .write(true) - .open(&path) - .unwrap() - .set_len((bytes.len() - 1) as u64) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((bytes.len() - 1) as u64).unwrap(); assert!(source.validate_retained_tensor(&lease).is_err()); assert_eq!(source.file.stream_position().unwrap(), 7); drop(retained); @@ -130,14 +112,8 @@ mod retained_lease_test { #[cfg(any(target_os = "linux", windows))] #[test] fn mapped_tensor_is_the_files_bytes_and_a_retained_owner() { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = std::env::temp_dir().join(format!( - "strata-bank-map-{}-{nonce}.gguf", - std::process::id() - )); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("strata-bank-map-{}-{nonce}.gguf", std::process::id())); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(1u64.to_le_bytes()); @@ -150,18 +126,11 @@ mod retained_lease_test { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x80000000u32, 0x3f800000, 0xbf800000, 0x40490fdb] - .into_iter() - .cycle() - .take(16) - { + for word in [0x80000000u32, 0x3f800000, 0xbf800000, 0x40490fdb].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } std::fs::write(&path, &bytes).unwrap(); - let hex = Sha256::digest(&bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); + let hex = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::(); let digest = format!("sha256:{hex}"); let mut source = VerifiedGgufFile::open(&path, &digest).unwrap(); let copy = source.load_resident_tensor(0, 64).unwrap(); @@ -173,9 +142,7 @@ mod retained_lease_test { assert_eq!(mapped.retained_bytes(), copy.into_retained().retained_bytes()); assert_eq!(mapped.retained_bytes().as_ptr() as usize % 16, 0); source.validate_retained_tensor(&mapped).unwrap(); - let out = source - .copy_resident_tensor(&mapped, 16, vec![0u8; 16].into_boxed_slice()) - .unwrap(); + let out = source.copy_resident_tensor(&mapped, 16, vec![0u8; 16].into_boxed_slice()).unwrap(); assert_eq!(&*out, &mapped.retained_bytes()[16..32]); let expected = mapped.retained_bytes().to_vec(); drop(source); @@ -190,14 +157,8 @@ mod retained_lease_test { #[cfg(any(target_os = "linux", windows))] #[test] fn mapped_tensor_refuses_a_file_shortened_after_verification() { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = std::env::temp_dir().join(format!( - "strata-bank-map-short-{}-{nonce}.gguf", - std::process::id() - )); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("strata-bank-map-short-{}-{nonce}.gguf", std::process::id())); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(1u64.to_le_bytes()); @@ -217,12 +178,7 @@ mod retained_lease_test { let hex = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect::(); let mut source = VerifiedGgufFile::open(&path, &format!("sha256:{hex}")).unwrap(); assert!(source.map_resident_tensor(0).is_ok()); - std::fs::OpenOptions::new() - .write(true) - .open(&path) - .unwrap() - .set_len((bytes.len() - 1) as u64) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&path).unwrap().set_len((bytes.len() - 1) as u64).unwrap(); assert!(source.map_resident_tensor(0).is_err()); drop(source); std::fs::remove_file(path).unwrap(); diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs index 9f4e2504..5cbfb4b6 100644 --- a/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl VerifiedGgufFile { /// Constructor is source-owned: arbitrary caller bytes cannot become a bank. pub(crate) fn load_resident_tensor( @@ -11,11 +10,12 @@ impl VerifiedGgufFile { tensor_number: usize, capacity_ceiling: usize, ) -> std::result::Result { - let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { - ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) - })?; - let length = - usize::try_from(tensor.bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or_else(|| ResidentLoadError::Source("GGUF tensor index is out of bounds".into()))?; + let length = usize::try_from(tensor.bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; if length == 0 { return Err(ResidentLoadError::Source("resident tensor is empty".into())); } @@ -23,18 +23,17 @@ impl VerifiedGgufFile { return Err(ResidentLoadError::Budget); } // Existing descriptor/source-size admission precedes allocation. - self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) - .map_err(ResidentLoadError::Source)?; + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())).map_err(ResidentLoadError::Source)?; #[cfg(target_os = "linux")] if crate::huge_pages::mode() != crate::huge_pages::Mode::Off { // The same bytes in a huge-page mapping instead of the heap; refusals map as for the heap copy. - let mut buffer = crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; + let mut buffer = + crate::huge_pages::HugeBuffer::allocate(length).map_err(|_| ResidentLoadError::Allocation)?; let charged_bytes = buffer.charged_len(); if charged_bytes > capacity_ceiling { return Err(ResidentLoadError::Budget); } - self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()) - .map_err(ResidentLoadError::Source)?; + self.read_tensor_into(tensor_number, 0, buffer.as_mut_slice()).map_err(ResidentLoadError::Source)?; let source = match self.resident_source_id { Some(source) => source, None => { @@ -43,25 +42,17 @@ impl VerifiedGgufFile { source } }; - return Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Huge(buffer), - charged_bytes, - }); + return Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Huge(buffer), charged_bytes }); } let mut bytes = Vec::new(); - bytes - .try_reserve_exact(length) - .map_err(|_| ResidentLoadError::Allocation)?; + bytes.try_reserve_exact(length).map_err(|_| ResidentLoadError::Allocation)?; let charged_bytes = bytes.capacity(); if charged_bytes > capacity_ceiling { return Err(ResidentLoadError::Budget); } bytes.resize(length, 0); - let bytes = self - .read_tensor_owned(tensor_number, 0, bytes.into_boxed_slice()) - .map_err(ResidentLoadError::Source)?; + let bytes = + self.read_tensor_owned(tensor_number, 0, bytes.into_boxed_slice()).map_err(ResidentLoadError::Source)?; // The immutable real source owns this identity; no default allocation. let source = match self.resident_source_id { Some(source) => source, @@ -71,12 +62,7 @@ impl VerifiedGgufFile { source } }; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Owned(bytes), - charged_bytes, - }) + Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Owned(bytes), charged_bytes }) } /// The Original's `--mmap-experts` with the GGUF in place (`FileExpertSource::set_gguf`): the tensor's /// bytes are a read-only shared mapping of this verified file instead of a copy, so no RAM is committed @@ -89,28 +75,25 @@ impl VerifiedGgufFile { tensor_number: usize, ) -> std::result::Result { let (tensor_offset, tensor_bytes) = { - let tensor = self.index.tensors.get(tensor_number).ok_or_else(|| { - ResidentLoadError::Source("GGUF tensor index is out of bounds".into()) - })?; + let tensor = self + .index + .tensors + .get(tensor_number) + .ok_or_else(|| ResidentLoadError::Source("GGUF tensor index is out of bounds".into()))?; (tensor.offset, tensor.bytes) }; - let length = - usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; + let length = usize::try_from(tensor_bytes).map_err(|e| ResidentLoadError::Source(e.into()))?; if length == 0 { return Err(ResidentLoadError::Source("resident tensor is empty".into())); } - self.stream_tensor(tensor_number, 0, 0, |_| Ok(())) - .map_err(ResidentLoadError::Source)?; + self.stream_tensor(tensor_number, 0, 0, |_| Ok(())).map_err(ResidentLoadError::Source)?; let absolute = self .index .summary .data_start .checked_add(tensor_offset) .ok_or_else(|| ResidentLoadError::Source("GGUF tensor offset overflow".into()))?; - if absolute - .checked_add(tensor_bytes) - .is_none_or(|end| end > self.index.summary.file_size) - { + if absolute.checked_add(tensor_bytes).is_none_or(|end| end > self.index.summary.file_size) { return Err(ResidentLoadError::Source("GGUF tensor exceeds indexed file".into())); } #[cfg(target_os = "linux")] @@ -118,11 +101,9 @@ impl VerifiedGgufFile { #[cfg(windows)] let page = leleka_libc_shim::allocation_granularity(); let map_offset = absolute & !(page - 1); - let start = usize::try_from(absolute - map_offset) - .map_err(|e| ResidentLoadError::Source(e.into()))?; - let map_len = start - .checked_add(length) - .ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; + let start = usize::try_from(absolute - map_offset).map_err(|e| ResidentLoadError::Source(e.into()))?; + let map_len = + start.checked_add(length).ok_or_else(|| ResidentLoadError::Source("mapping length overflow".into()))?; self.check_size().map_err(ResidentLoadError::Source)?; // SAFETY: a fresh read-only shared mapping of the retained verified descriptor at a page-aligned // offset inside the indexed file; the kernel picks the address. No existing memory is replaced. @@ -144,7 +125,8 @@ impl VerifiedGgufFile { let base = { use std::os::windows::io::AsRawHandle; // SAFETY: a fresh read-only view of the retained verified handle at a granularity-aligned offset inside the indexed file. - let view = unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; + let view = + unsafe { leleka_libc_shim::map_file_readonly(self.file.as_raw_handle().cast(), map_offset, map_len) }; if view.is_null() { return Err(ResidentLoadError::Source(Box::new(std::io::Error::last_os_error()))); } @@ -160,12 +142,7 @@ impl VerifiedGgufFile { source } }; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Mapped(span), - charged_bytes: length, - }) + Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Mapped(span), charged_bytes: length }) } /// Copies a real source-owned bank span, with unchanged indexed bounds and /// same-FD pre/post size checks. A hit intentionally does not seek/read FD. @@ -178,17 +155,11 @@ impl VerifiedGgufFile { if self.resident_source_id != Some(resident.source) { return Err("resident tensor source identity mismatch".into()); } - let tensor = self - .index - .tensors - .get(resident.tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; + let tensor = self.index.tensors.get(resident.tensor_number).ok_or("GGUF tensor index is out of bounds")?; let length = u64::try_from(output.len())?; if tensor.bytes == 0 || resident.bytes.len() as u64 != tensor.bytes - || offset - .checked_add(length) - .is_none_or(|end| end > tensor.bytes) + || offset.checked_add(length).is_none_or(|end| end > tensor.bytes) { return Err("GGUF tensor byte range is out of bounds".into()); } @@ -199,21 +170,12 @@ impl VerifiedGgufFile { .checked_add(tensor.offset) .and_then(|start| start.checked_add(offset)) .ok_or("GGUF tensor offset overflow")?; - if absolute - .checked_add(length) - .is_none_or(|end| end > self.index.summary.file_size) - { + if absolute.checked_add(length).is_none_or(|end| end > self.index.summary.file_size) { return Err("GGUF tensor exceeds indexed file".into()); } let first = usize::try_from(offset)?; - let end = first - .checked_add(output.len()) - .ok_or("resident tensor offset overflow")?; - let selected = resident - .bytes - .as_slice() - .get(first..end) - .ok_or("resident tensor extent")?; + let end = first.checked_add(output.len()).ok_or("resident tensor offset overflow")?; + let selected = resident.bytes.as_slice().get(first..end).ok_or("resident tensor extent")?; self.check_size()?; output.copy_from_slice(selected); self.check_size()?; diff --git a/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs index d221fdb0..ce1f20b7 100644 --- a/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs +++ b/crates/model-format/src/gguf_resident/impl_verifiedgguffile_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl VerifiedGgufFile { pub(crate) fn capture_source_identity(&mut self) -> Result { self.check_size()?; @@ -32,12 +31,7 @@ impl VerifiedGgufFile { return Err("GGUF resident source identity mismatch".into()); } self.stream_tensor(tensor_number, 0, 0, |_| Ok(()))?; - Ok(ResidentTensor { - source, - tensor_number, - bytes: ResidentStorage::Owned(bytes), - charged_bytes, - }) + Ok(ResidentTensor { source, tensor_number, bytes: ResidentStorage::Owned(bytes), charged_bytes }) } } @@ -67,11 +61,7 @@ impl VerifiedGgufFile { if self.resident_source_id != Some(resident.source) { return Err("resident tensor source identity mismatch".into()); } - let tensor = self - .index - .tensors - .get(resident.tensor_number) - .ok_or("GGUF tensor index is out of bounds")?; + let tensor = self.index.tensors.get(resident.tensor_number).ok_or("GGUF tensor index is out of bounds")?; if tensor.bytes == 0 || resident.bytes.len() as u64 != tensor.bytes || resident.charged_bytes < resident.bytes.len() diff --git a/crates/model-format/src/gguf_resident/next_source_id.rs b/crates/model-format/src/gguf_resident/next_source_id.rs index d1d853b1..8c1a59ba 100644 --- a/crates/model-format/src/gguf_resident/next_source_id.rs +++ b/crates/model-format/src/gguf_resident/next_source_id.rs @@ -6,9 +6,7 @@ use super::*; pub(super) fn next_source_id() -> Result { let mut current = NEXT_SOURCE_ID.load(Ordering::Relaxed); loop { - let next = current - .checked_add(1) - .ok_or("resident source identity exhausted")?; + let next = current.checked_add(1).ok_or("resident source identity exhausted")?; match NEXT_SOURCE_ID.compare_exchange(current, next, Ordering::Relaxed, Ordering::Relaxed) { Ok(_) => return Ok(current), Err(actual) => current = actual, diff --git a/crates/model-format/src/gguf_resident_sdet.rs b/crates/model-format/src/gguf_resident_sdet.rs index 47a6595e..423353a6 100644 --- a/crates/model-format/src/gguf_resident_sdet.rs +++ b/crates/model-format/src/gguf_resident_sdet.rs @@ -9,14 +9,8 @@ struct Fixture { } impl Fixture { fn new() -> Self { - let nonce = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let directory = std::env::temp_dir().join(format!( - "strata-resident-bank-{}-{nonce}", - std::process::id() - )); + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let directory = std::env::temp_dir().join(format!("strata-resident-bank-{}-{nonce}", std::process::id())); std::fs::create_dir(&directory).unwrap(); let path = directory.join("tiny.gguf"); let mut bytes = b"GGUF".to_vec(); @@ -31,26 +25,15 @@ impl Fixture { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000] - .into_iter() - .cycle() - .take(16) - { + for word in [0x80000000u32, 0, 0x3f800000, 0xbf800000].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } assert!(bytes.len() <= 192); std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - } + Self { directory, path, bytes } } fn open(&self) -> VerifiedGgufFile { - let hex = Sha256::digest(&self.bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); + let hex = Sha256::digest(&self.bytes).iter().map(|b| format!("{b:02x}")).collect::(); VerifiedGgufFile::open(&self.path, &format!("sha256:{hex}")).unwrap() } } @@ -80,10 +63,7 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( let mut source = fixture.open(); let reference = original(&mut source, 0, 64).unwrap(); let original_end = source.file.stream_position().unwrap(); - assert!(matches!( - source.load_resident_tensor(0, 63), - Err(ResidentLoadError::Budget) - )); + assert!(matches!(source.load_resident_tensor(0, 63), Err(ResidentLoadError::Budget))); assert_eq!(source.resident_source_id, None); assert_eq!(source.file.stream_position().unwrap(), original_end); let bank = source.load_resident_tensor(0, 64).unwrap(); @@ -105,20 +85,12 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( for (offset, n) in [(64, 1), (u64::MAX, 4)] { source.file.seek(SeekFrom::Start(11)).unwrap(); let old = original(&mut source, offset, n).unwrap_err(); - let new = source - .copy_resident_tensor(&bank, offset, initialized(n)) - .unwrap_err(); + let new = source.copy_resident_tensor(&bank, offset, initialized(n)).unwrap_err(); assert_eq!(old.to_string(), new.to_string()); assert_eq!(source.file.stream_position().unwrap(), 11); } - assert!(matches!( - source.load_resident_tensor(1, 64), - Err(ResidentLoadError::Source(_)) - )); - assert!(matches!( - source.load_resident_tensor(0, 63), - Err(ResidentLoadError::Budget) - )); + assert!(matches!(source.load_resident_tensor(1, 64), Err(ResidentLoadError::Source(_)))); + assert!(matches!(source.load_resident_tensor(0, 63), Err(ResidentLoadError::Budget))); assert_eq!(source.resident_source_id, identity); assert_eq!(&*bank.bytes, reference); // Same actual file, independently admitted FD: content equality is not source authority. @@ -127,44 +99,21 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( let foreign_bank = foreign.load_resident_tensor(0, 64).unwrap(); assert_eq!(&*foreign_bank.bytes, foreign_reference); assert_ne!(foreign.resident_source_id, identity); - assert!( - foreign - .copy_resident_tensor(&bank, 0, initialized(64)) - .is_err() - ); - assert!( - source - .copy_resident_tensor(&foreign_bank, 0, initialized(64)) - .is_err() - ); + assert!(foreign.copy_resident_tensor(&bank, 0, initialized(64)).is_err()); + assert!(source.copy_resident_tensor(&foreign_bank, 0, initialized(64)).is_err()); // A replacement path occupant cannot change the already admitted real FD. let retained = fixture.directory.join("retained.gguf"); std::fs::rename(&fixture.path, &retained).unwrap(); std::fs::write(&fixture.path, b"different pathname occupant").unwrap(); let old = original(&mut source, 0, 64).unwrap(); source.file.seek(SeekFrom::Start(9)).unwrap(); - assert_eq!( - &*source - .copy_resident_tensor(&bank, 0, initialized(64)) - .unwrap(), - old - ); + assert_eq!(&*source.copy_resident_tensor(&bank, 0, initialized(64)).unwrap(), old); assert_eq!(source.file.stream_position().unwrap(), 9); - std::fs::OpenOptions::new() - .write(true) - .open(&retained) - .unwrap() - .set_len((fixture.bytes.len() - 1) as u64) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&retained).unwrap().set_len((fixture.bytes.len() - 1) as u64).unwrap(); let old = original(&mut source, 0, 64).unwrap_err(); - let new = source - .copy_resident_tensor(&bank, 0, initialized(64)) - .unwrap_err(); + let new = source.copy_resident_tensor(&bank, 0, initialized(64)).unwrap_err(); assert_eq!(old.to_string(), new.to_string()); - assert!(matches!( - source.load_resident_tensor(0, 64), - Err(ResidentLoadError::Source(_)) - )); + assert!(matches!(source.load_resident_tensor(0, 64), Err(ResidentLoadError::Source(_)))); assert_eq!(source.file.stream_position().unwrap(), 9); assert_eq!(source.resident_source_id, identity); assert_eq!(&*bank.bytes, reference); @@ -179,10 +128,7 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( // neither a source token nor ModelBinding is fabricated. let fixture = Fixture::new(); let mut source = fixture.open(); - source.file = std::fs::OpenOptions::new() - .write(true) - .open(&fixture.path) - .unwrap(); + source.file = std::fs::OpenOptions::new().write(true).open(&fixture.path).unwrap(); let old = original(&mut source, 0, 64).unwrap_err(); match source.load_resident_tensor(0, 64) { Err(ResidentLoadError::Source(new)) => assert_eq!( @@ -208,13 +154,7 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 8388608 kB\n", 1024).is_err()); let cap = usize::try_from(52u64 * 1024 * 1024 * 1024).unwrap(); assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 62914560 kB\n", cap).is_ok()); - assert!( - admit( - "MemTotal: 134217728 kB\nMemAvailable: 134217728 kB\n", - cap + 1 - ) - .is_err() - ); + assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 134217728 kB\n", cap + 1).is_err()); for malformed in [ "", "MemTotal: 1 kB\n", @@ -232,11 +172,5 @@ fn original_stream_first_resident_bank_bytes_source_fences_and_memory_admission( } let overflow = format!("MemTotal: {} kB\nMemAvailable: 1 kB\n", usize::MAX); assert!(admit(&overflow, 0).is_err()); - assert!( - admit( - "MemTotal: 134217728 kB\nMemAvailable: 134217728 kB\n", - usize::MAX - ) - .is_err() - ); + assert!(admit("MemTotal: 134217728 kB\nMemAvailable: 134217728 kB\n", usize::MAX).is_err()); } diff --git a/crates/model-format/src/huge_pages.rs b/crates/model-format/src/huge_pages.rs index 3e1c8e05..19a3cbc5 100644 --- a/crates/model-format/src/huge_pages.rs +++ b/crates/model-format/src/huge_pages.rs @@ -55,7 +55,7 @@ pub fn mode() -> Mode { #[cfg(target_os = "linux")] pub(crate) use linux::HugeBuffer; #[cfg(target_os = "linux")] -pub use linux::{coverage, settle, Coverage}; +pub use linux::{Coverage, coverage, settle}; /// Not Linux: nothing is placed, nothing to report. #[cfg(not(target_os = "linux"))] @@ -119,7 +119,11 @@ mod linux { std::ptr::null_mut(), map_len, libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_HUGETLB | libc::MAP_HUGE_2MB | libc::MAP_POPULATE, + libc::MAP_PRIVATE + | libc::MAP_ANONYMOUS + | libc::MAP_HUGETLB + | libc::MAP_HUGE_2MB + | libc::MAP_POPULATE, -1, 0, ) @@ -133,7 +137,14 @@ mod linux { let reserve = map_len.checked_add(HUGE).ok_or_else(invalid)?; // SAFETY: a fresh private anonymous mapping; the kernel picks the address; nothing is replaced. let p = unsafe { - libc::mmap(std::ptr::null_mut(), reserve, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, -1, 0) + libc::mmap( + std::ptr::null_mut(), + reserve, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) }; if p == libc::MAP_FAILED { return Err(std::io::Error::last_os_error()); @@ -215,7 +226,11 @@ mod linux { return None; } let smaps = std::fs::read_to_string("/proc/self/smaps").ok()?; - let mut out = Coverage { buffers: live.len(), mapped_bytes: live.iter().map(|e| e.1 as u64).sum(), ..Coverage::default() }; + let mut out = Coverage { + buffers: live.len(), + mapped_bytes: live.iter().map(|e| e.1 as u64).sum(), + ..Coverage::default() + }; let mut inside = false; for line in smaps.lines() { let mut words = line.split_whitespace(); @@ -271,8 +286,13 @@ mod linux { .sum(); if before.thp_bytes < aligned { let t = std::time::Instant::now(); - let ranges: Vec<(usize, usize)> = - LIVE.lock().unwrap_or_else(|p| p.into_inner()).iter().filter(|e| !e.2).map(|e| (e.0, e.1 & !(HUGE - 1))).collect(); + let ranges: Vec<(usize, usize)> = LIVE + .lock() + .unwrap_or_else(|p| p.into_inner()) + .iter() + .filter(|e| !e.2) + .map(|e| (e.0, e.1 & !(HUGE - 1))) + .collect(); // linux/mman-common.h MADV_COLLAPSE = 25 (6.1+). Spelled out because libc 0.2.190 does not define it for the musl targets // (the static CLI build failed to compile); glibc's libc::MADV_COLLAPSE has the same value. const MADV_COLLAPSE: libc::c_int = 25; diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 37b8d321..55c52b61 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -220,10 +220,9 @@ pub use nested::{KarNestedRecord, NESTING_TOPDOWN}; #[path = "kar_extents.rs"] mod extents; pub use extents::{ - CensusRecord, EXTENT_ALIGN, Extent, KarCensus, PLE_EXTENTS_SHA256, PLE_PART_NAMES, PLE_PLANES, - PLE_ROW_PLANE_BYTES, PLE_ROW_SCALE_BYTES, PartReads, - RecordClass, ServeReads, digest_extents, digest_extents_with, extents_bytes, extents_cover, - extents_overlap, normalize_extents, + CensusRecord, EXTENT_ALIGN, Extent, KarCensus, PLE_EXTENTS_SHA256, PLE_PART_NAMES, PLE_PLANES, PLE_ROW_PLANE_BYTES, + PLE_ROW_SCALE_BYTES, PartReads, RecordClass, ServeReads, digest_extents, digest_extents_with, extents_bytes, + extents_cover, extents_overlap, normalize_extents, }; #[cfg(test)] @@ -311,7 +310,10 @@ mod row_read_tests { // the refusals are the same as before: a row outside the table, a changed archive length let bad = vec![PLE_ROWS; 16]; assert!(matches!(read_rows_parallel(&files, &parts, total, None, &bad, 8, 2, true), Err(KarError::Range(_)))); - assert!(matches!(read_rows_parallel(&files, &parts, total + 1, None, &[1, 2], 8, 2, true), Err(KarError::Integrity(_)))); + assert!(matches!( + read_rows_parallel(&files, &parts, total + 1, None, &[1, 2], 8, 2, true), + Err(KarError::Integrity(_)) + )); // a row beyond the partitions' last row is a range error on the probe path as well let beyond: Vec = (0..16).map(|i| 1500 + i).collect(); assert!(read_rows_parallel(&files, &parts, total, None, &beyond, 8, 2, true).is_err()); @@ -332,7 +334,9 @@ mod row_read_tests { assert!(same(&ok, &reference), "the check changes no byte that is returned"); // a sealed memfd has no identity to compare: the length check alone assert!(check_archive_state(&file, total, None).is_ok()); - assert!(matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length"))); + assert!( + matches!(check_archive_state(&file, total + 1, Some(&id)), Err(KarError::Integrity(m)) if m.contains("length")) + ); // the file is touched (mtime and ctime move, size and bytes do not): refused, on every entry point std::thread::sleep(std::time::Duration::from_millis(30)); let handle = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); @@ -350,7 +354,12 @@ mod row_read_tests { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap(); assert!(matches!(check_archive_state(&file, total, Some(&id2)), Err(KarError::Integrity(_)))); // the reader a prefill thread owns carries the same state - let reader = KarPleRowReader { files: vec![file.try_clone().unwrap()], parts: parts.clone(), archive_bytes: total, identity: Some(id2) }; + let reader = KarPleRowReader { + files: vec![file.try_clone().unwrap()], + parts: parts.clone(), + archive_bytes: total, + identity: Some(id2), + }; assert!(matches!(reader.read_rows(&rows, 4), Err(KarError::Integrity(_)))); let reader = KarPleRowReader { files, parts, archive_bytes: total, identity: None }; assert!(same(&reader.read_rows(&rows, 4).unwrap(), &reference)); diff --git a/crates/model-format/src/kar/decode_record_range.rs b/crates/model-format/src/kar/decode_record_range.rs index 5caced3e..67f5b5e5 100644 --- a/crates/model-format/src/kar/decode_record_range.rs +++ b/crates/model-format/src/kar/decode_record_range.rs @@ -12,9 +12,7 @@ pub(super) fn decode_record_range( decoder: ScalarDecoder, ) -> Result, String> { let elements = usize::try_from(u64_at(record, 48)).map_err(|_| "KAR tensor is too large")?; - let end = start - .checked_add(count) - .ok_or("KAR decode range overflow")?; + let end = start.checked_add(count).ok_or("KAR decode range overflow")?; if count == 0 || count > 1_000_000 || end > elements { return Err("CPU KAR decoder requires 1..=1,000,000 values within tensor bounds".into()); } @@ -23,23 +21,10 @@ pub(super) fn decode_record_range( return Err("CPU quality oracle only supports RAW F32 tensors".into()); } let offset = u64_at(record, 112) - .checked_add( - (start as u64) - .checked_mul(4) - .ok_or("KAR raw offset overflow")?, - ) + .checked_add((start as u64).checked_mul(4).ok_or("KAR raw offset overflow")?) .ok_or("KAR raw offset overflow")?; - let bytes = read_region( - file, - offset, - count.checked_mul(4).ok_or("KAR raw byte count overflow")?, - )?; - return Ok(bytes - .as_chunks::<4>() - .0 - .iter() - .map(|word| f32::from_le_bytes(*word)) - .collect()); + let bytes = read_region(file, offset, count.checked_mul(4).ok_or("KAR raw byte count overflow")?)?; + return Ok(bytes.as_chunks::<4>().0.iter().map(|word| f32::from_le_bytes(*word)).collect()); } let stored = record[42]; if level == 0 || level > stored { @@ -53,63 +38,33 @@ pub(super) fn decode_record_range( let padded = usize::try_from(u64_at(record, 56)).map_err(|_| "KAR tensor is too large")?; let base_group = start / group_size; let end_group = end.div_ceil(group_size); - let base_element = base_group - .checked_mul(group_size) - .ok_or("KAR decode base overflow")?; - let local_padded = (end_group - base_group) - .checked_mul(group_size) - .ok_or("KAR decode padded size overflow")?; - if base_element - .checked_add(local_padded) - .is_none_or(|end| end > padded) - { + let base_element = base_group.checked_mul(group_size).ok_or("KAR decode base overflow")?; + let local_padded = (end_group - base_group).checked_mul(group_size).ok_or("KAR decode padded size overflow")?; + if base_element.checked_add(local_padded).is_none_or(|end| end > padded) { return Err("KAR decode range exceeds padded tensor".into()); } let scale_bytes = read_region( file, u64_at(record, 64) - .checked_add( - (base_group as u64) - .checked_mul(2) - .ok_or("KAR scale offset overflow")?, - ) + .checked_add((base_group as u64).checked_mul(2).ok_or("KAR scale offset overflow")?) .ok_or("KAR scale offset overflow")?, - (end_group - base_group) - .checked_mul(2) - .ok_or("KAR scale byte count overflow")?, + (end_group - base_group).checked_mul(2).ok_or("KAR scale byte count overflow")?, )?; - let scales = scale_bytes - .as_chunks::<2>() - .0 - .iter() - .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) - .collect::>(); - let book_offset = u64_at(record, 80) - .checked_add((1u64 << (u32::from(level) + 1)) - 4) - .ok_or("KAR book offset overflow")?; + let scales = + scale_bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect::>(); + let book_offset = + u64_at(record, 80).checked_add((1u64 << (u32::from(level) + 1)) - 4).ok_or("KAR book offset overflow")?; let book_bytes = read_region(file, book_offset, (1usize << level) * 2)?; - let book = book_bytes - .as_chunks::<2>() - .0 - .iter() - .map(|pair| u16::from_le_bytes([pair[0], pair[1]])) - .collect::>(); + let book = + book_bytes.as_chunks::<2>().0.iter().map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect::>(); let plane_stride = u64::from(u32_at(record, 104)); let plane_bytes = local_padded / 32 * 4; - let plane_base = u64::try_from( - (base_element / 32) - .checked_mul(4) - .ok_or("KAR plane offset overflow")?, - ) - .map_err(|_| "KAR plane offset overflow")?; + let plane_base = u64::try_from((base_element / 32).checked_mul(4).ok_or("KAR plane offset overflow")?) + .map_err(|_| "KAR plane offset overflow")?; let mut planes = Vec::with_capacity(usize::from(level)); for plane in 0..u64::from(level) { let offset = u64_at(record, 96) - .checked_add( - plane - .checked_mul(plane_stride) - .ok_or("KAR plane offset overflow")?, - ) + .checked_add(plane.checked_mul(plane_stride).ok_or("KAR plane offset overflow")?) .and_then(|offset| offset.checked_add(plane_base)) .ok_or("KAR plane offset overflow")?; let bytes = read_region(file, offset, plane_bytes)?; @@ -124,17 +79,8 @@ pub(super) fn decode_record_range( } let plane_refs = planes.iter().map(Vec::as_slice).collect::>(); let mut output = Vec::new(); - output - .try_reserve_exact(count) - .map_err(|_| "KAR allocation failed")?; + output.try_reserve_exact(count).map_err(|_| "KAR allocation failed")?; output.resize(count, 0.0); - decoder( - &scales, - &book, - &plane_refs, - group, - start - base_element, - &mut output, - )?; + decoder(&scales, &book, &plane_refs, group, start - base_element, &mut output)?; Ok(output) } diff --git a/crates/model-format/src/kar/impl_karpleprofile.rs b/crates/model-format/src/kar/impl_karpleprofile.rs index 6be0d027..ebf96c47 100644 --- a/crates/model-format/src/kar/impl_karpleprofile.rs +++ b/crates/model-format/src/kar/impl_karpleprofile.rs @@ -24,9 +24,7 @@ impl KarPleProfile { } let mut next = 0u64; let mut names = HashSet::new(); - names - .try_reserve(spec.parts.len()) - .map_err(|_| KarError::Allocation)?; + names.try_reserve(spec.parts.len()).map_err(|_| KarError::Allocation)?; for p in &spec.parts { if p.name.is_empty() || p.name.len() > 1024 diff --git a/crates/model-format/src/kar/impl_std_fmt_display.rs b/crates/model-format/src/kar/impl_std_fmt_display.rs index dab51582..11f428f6 100644 --- a/crates/model-format/src/kar/impl_std_fmt_display.rs +++ b/crates/model-format/src/kar/impl_std_fmt_display.rs @@ -6,9 +6,7 @@ use super::*; impl std::fmt::Display for KarError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Self::Format(s) | Self::Range(s) | Self::Integrity(s) | Self::Profile(s) => { - f.write_str(s) - } + Self::Format(s) | Self::Range(s) | Self::Integrity(s) | Self::Profile(s) => f.write_str(s), Self::Allocation => f.write_str("KAR allocation failed"), Self::Io(e) => e.fmt(f), } @@ -16,11 +14,7 @@ impl std::fmt::Display for KarError { } impl std::error::Error for KarError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - if let Self::Io(e) = self { - Some(e) - } else { - None - } + if let Self::Io(e) = self { Some(e) } else { None } } } pub(super) fn typed(error: String) -> KarError { @@ -44,9 +38,7 @@ pub(super) fn typed(error: String) -> KarError { "KAR coded bit count overflow" => KarError::Format("KAR coded bit count overflow"), "KAR decode base overflow" => KarError::Format("KAR decode base overflow"), "KAR decode padded size overflow" => KarError::Format("KAR decode padded size overflow"), - "KAR decode range exceeds padded tensor" => { - KarError::Format("KAR decode range exceeds padded tensor") - } + "KAR decode range exceeds padded tensor" => KarError::Format("KAR decode range exceeds padded tensor"), "KAR decode range overflow" => KarError::Format("KAR decode range overflow"), "KAR directory digest mismatch" => KarError::Format("KAR directory digest mismatch"), "KAR directory length overflow" => KarError::Format("KAR directory length overflow"), @@ -66,9 +58,7 @@ pub(super) fn typed(error: String) -> KarError { "KAR planes offset overflow" => KarError::Format("KAR planes offset overflow"), "KAR raw byte count overflow" => KarError::Format("KAR raw byte count overflow"), "KAR raw offset overflow" => KarError::Format("KAR raw offset overflow"), - "KAR raw tensor section is too small" => { - KarError::Format("KAR raw tensor section is too small") - } + "KAR raw tensor section is too small" => KarError::Format("KAR raw tensor section is too small"), "KAR raw tensor size overflow" => KarError::Format("KAR raw tensor size overflow"), "KAR scale byte count overflow" => KarError::Format("KAR scale byte count overflow"), "KAR scale count overflow" => KarError::Format("KAR scale count overflow"), @@ -78,9 +68,7 @@ pub(super) fn typed(error: String) -> KarError { } "KAR string table overflow" => KarError::Format("KAR string table overflow"), "KAR tensor bit count overflow" => KarError::Format("KAR tensor bit count overflow"), - "KAR tensor element count mismatch" => { - KarError::Format("KAR tensor element count mismatch") - } + "KAR tensor element count mismatch" => KarError::Format("KAR tensor element count mismatch"), "KAR tensor is too large" => KarError::Format("KAR tensor is too large"), "KAR tensor name is not UTF-8" => KarError::Format("KAR tensor name is not UTF-8"), "KAR tensor section overflow" => KarError::Format("KAR tensor section overflow"), @@ -90,30 +78,20 @@ pub(super) fn typed(error: String) -> KarError { "KAR tensor shape overflow" => KarError::Format("KAR tensor shape overflow"), "KARCHIV2" => KarError::Format("KARCHIV2"), "duplicate KAR tensor name" => KarError::Format("duplicate KAR tensor name"), - "invalid KAR byte order or record size" => { - KarError::Format("invalid KAR byte order or record size") - } + "invalid KAR byte order or record size" => KarError::Format("invalid KAR byte order or record size"), "invalid KAR flags, digest algorithm, or element counts" => { KarError::Format("invalid KAR flags, digest algorithm, or element counts") } - "invalid KAR metadata offsets or alignment" => { - KarError::Format("invalid KAR metadata offsets or alignment") - } - "invalid KAR nested tensor parameters" => { - KarError::Format("invalid KAR nested tensor parameters") - } - "invalid KAR nested tensor section layout" => { - KarError::Format("invalid KAR nested tensor section layout") - } + "invalid KAR metadata offsets or alignment" => KarError::Format("invalid KAR metadata offsets or alignment"), + "invalid KAR nested tensor parameters" => KarError::Format("invalid KAR nested tensor parameters"), + "invalid KAR nested tensor section layout" => KarError::Format("invalid KAR nested tensor section layout"), "invalid KAR raw tensor metadata" => KarError::Format("invalid KAR raw tensor metadata"), "invalid KAR tensor name bounds" => KarError::Format("invalid KAR tensor name bounds"), "invalid KAR unused dimension" => KarError::Format("invalid KAR unused dimension"), "source manifest contains an invalid file name" => { KarError::Format("source manifest contains an invalid file name") } - "unsupported KAR archive magic or version" => { - KarError::Format("unsupported KAR archive magic or version") - } + "unsupported KAR archive magic or version" => KarError::Format("unsupported KAR archive magic or version"), "unsupported KAR tensor layout" => KarError::Format("unsupported KAR tensor layout"), _ => KarError::Io(std::io::Error::other(error)), } @@ -131,17 +109,13 @@ impl KarTensorSource { } self.planes_offset .checked_sub(self.section_offset) - .and_then(|prefix| { - prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes)) - }) + .and_then(|prefix| prefix.checked_add(u64::from(level) * u64::from(self.plane_stride_bytes))) .filter(|bytes| *bytes <= self.section_bytes) .ok_or(KarError::Range("invalid KAR GPU prefix size")) } pub fn gpu_decode_bytes(&self) -> Result { - self.n_elements - .checked_mul(4) - .ok_or(KarError::Range("KAR F32 decode size overflow")) + self.n_elements.checked_mul(4).ok_or(KarError::Range("KAR F32 decode size overflow")) } /// One-row output size for a geometrically addressable NESTED table. @@ -163,24 +137,9 @@ impl KarTensorSource { } impl KarInspection { pub fn inspect(file: File) -> Result { - let Parsed { - summary, - file, - sections, - sources, - directory, - payload_offset, - metadata_bytes, - } = inspect_file(file).map_err(typed)?; - Ok(Self { - summary, - file, - sections, - sources, - directory, - payload_offset, - metadata_bytes, - }) + let Parsed { summary, file, sections, sources, directory, payload_offset, metadata_bytes } = + inspect_file(file).map_err(typed)?; + Ok(Self { summary, file, sections, sources, directory, payload_offset, metadata_bytes }) } pub fn summary(&self) -> &KarSummary { &self.summary @@ -190,21 +149,15 @@ impl KarInspection { } pub fn verify_payloads(&mut self) -> Result<(), KarError> { let mut buffer = Vec::new(); - buffer - .try_reserve_exact(8 * 1024 * 1024) - .map_err(|_| KarError::Allocation)?; + buffer.try_reserve_exact(8 * 1024 * 1024).map_err(|_| KarError::Allocation)?; buffer.resize(8 * 1024 * 1024, 0); for section in &self.sections { - self.file - .seek(SeekFrom::Start(section.offset)) - .map_err(KarError::Io)?; + self.file.seek(SeekFrom::Start(section.offset)).map_err(KarError::Io)?; let mut remaining = section.bytes; let mut crc = !0u32; while remaining > 0 { let n = remaining.min(buffer.len() as u64) as usize; - self.file - .read_exact(&mut buffer[..n]) - .map_err(KarError::Io)?; + self.file.read_exact(&mut buffer[..n]).map_err(KarError::Io)?; crc = crc32_step(crc, &buffer[..n]); remaining -= n as u64; } @@ -225,15 +178,9 @@ impl KarInspection { count: usize, decoder: ScalarDecoder, ) -> Result, KarError> { - let index = self - .sources - .iter() - .position(|s| s.name == name) - .ok_or(KarError::Range("KAR tensor not found"))?; - let record: [u8; RECORD_BYTES] = self.directory - [index * RECORD_BYTES..(index + 1) * RECORD_BYTES] - .try_into() - .expect("validated directory"); + let index = self.sources.iter().position(|s| s.name == name).ok_or(KarError::Range("KAR tensor not found"))?; + let record: [u8; RECORD_BYTES] = + self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES].try_into().expect("validated directory"); decode_record_range(&mut self.file, &record, level, start, count, decoder).map_err(typed) } /// Trusted-owner contract, not an OS/stat check: the caller establishes that diff --git a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs index c5292fe6..3f74c4d6 100644 --- a/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs +++ b/crates/model-format/src/kar/impl_verifiedkarpleartifact.rs @@ -12,27 +12,29 @@ impl VerifiedKarPleArtifact { /// ([`digest_extents_with`] over `serve_extents`, measured once from the archive that matched its full pin) stands /// in for them, and the directory digest in the header (checked by `inspect`, inside the extents) covers the rest. /// Fails closed: a wrong digest, a read range outside the extents or a changed length is an error. - pub fn verify_sparse(source: KarImmutableSource, profile: KarPleProfile, extents_sha256: &[u8; 32]) -> Result { + pub fn verify_sparse( + source: KarImmutableSource, + profile: KarPleProfile, + extents_sha256: &[u8; 32], + ) -> Result { Self::verify_with(source, profile, Some(extents_sha256)) } - pub(super) fn verify_with(source: KarImmutableSource, profile: KarPleProfile, sparse_pin: Option<&[u8; 32]>) -> Result { + pub(super) fn verify_with( + source: KarImmutableSource, + profile: KarPleProfile, + sparse_pin: Option<&[u8; 32]>, + ) -> Result { let mut reader = source.inspection; if reader.file.metadata().map_err(KarError::Io)?.len() != profile.spec.archive_bytes || reader.summary.archive_bytes != profile.spec.archive_bytes || reader.summary.source_bytes != profile.spec.virtual_f32_bytes || reader.summary.source_digest != profile.spec.virtual_f32_sha256 { - return Err(KarError::Integrity( - "KAR archive/provenance identity mismatch", - )); + return Err(KarError::Integrity("KAR archive/provenance identity mismatch")); } // A stamp for exactly this file in exactly this state (see verify_stamp.rs) stands in for the full // SHA-256 + CRC pass; a sealed memfd has no stable identity and always takes the full pass. - let identity = reader - .file - .metadata() - .ok() - .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); + let identity = reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)); let stamps = crate::verify_stamp::global(); // An unlinked sealed memfd: only if the parent attested the copy (see `set_attested_archive`). let attested_memfd = identity.is_none() && crate::verify_stamp::attested_archive() && is_unlinked(&reader.file); @@ -51,12 +53,7 @@ impl VerifiedKarPleArtifact { if sparse_pin.is_none() && !trusted { reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; if let (Some(stamps), Some(before)) = (stamps, identity) - && reader - .file - .metadata() - .ok() - .and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) - == Some(before) + && reader.file.metadata().ok().and_then(|m| crate::verify_stamp::FileIdentity::of(&m)) == Some(before) { let _ = stamps.record("kar", &profile.spec.archive_sha256, &before); } @@ -64,12 +61,8 @@ impl VerifiedKarPleArtifact { let mut parts = Vec::new(); let mut books = Vec::new(); let mut book_at_list = Vec::new(); - parts - .try_reserve_exact(profile.spec.parts.len()) - .map_err(|_| KarError::Allocation)?; - books - .try_reserve_exact(profile.spec.parts.len()) - .map_err(|_| KarError::Allocation)?; + parts.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; + books.try_reserve_exact(profile.spec.parts.len()).map_err(|_| KarError::Allocation)?; for p in &profile.spec.parts { let index = reader .sources @@ -88,28 +81,18 @@ impl VerifiedKarPleArtifact { || s.digest != p.derived_f32_sha256 || s.offset != p.derived_f32_offset { - return Err(KarError::Profile( - "KAR PLE partition/source mapping mismatch", - )); + return Err(KarError::Profile("KAR PLE partition/source mapping mismatch")); } let scales = u64_at(record, 64); let planes = s.planes_offset; let stride = u64::from(s.plane_stride_bytes); - let book_at = u64_at(record, 80) - .checked_add(4) - .ok_or(KarError::Range("KAR PLE book overflow"))?; + let book_at = u64_at(record, 80).checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; let bytes = read_region(&mut reader.file, book_at, 8).map_err(typed)?; let book = std::array::from_fn(|i| u16_at(&bytes, i * 2)); if book.iter().any(|b| b & 0x7c00 == 0x7c00) { return Err(KarError::Profile("KAR PLE nonfinite book")); } - parts.push(VerifiedPart { - row_base: p.row_base, - row_count: p.row_count, - scales, - planes, - stride, - }); + parts.push(VerifiedPart { row_base: p.row_base, row_count: p.row_count, scales, planes, stride }); books.push(book); book_at_list.push(book_at); } @@ -207,24 +190,38 @@ impl VerifiedKarPleArtifact { // holds answers each read in about a microsecond, and eight thread starts and joins then cost more than the reads // (about 0.1 ms per token of a decode window); `warm_probe` reads the first row on this thread, times it, and reads the // other fifteen here too when it was served from memory. - let packets = read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 8, 2, true)?; - let mut out = [KarPleRowPacket { - payload: [0; 50], - partition: 0, - }; 16]; + let packets = read_rows_parallel( + self.row_handles(), + &self.parts, + self.archive_bytes(), + self.identity.as_ref(), + rows, + 8, + 2, + true, + )?; + let mut out = [KarPleRowPacket { payload: [0; 50], partition: 0 }; 16]; out.copy_from_slice(&packets); Ok(out) } /// Handles with a file object of their own (so reads through two of them can be in flight at once). pub(super) fn row_handles(&self) -> &[File] { - self.handles - .get_or_init(|| independent_handles(&self.reader.file, ROW_HANDLES)) + self.handles.get_or_init(|| independent_handles(&self.reader.file, ROW_HANDLES)) } /// `read_rows` over any number of rows: the same three region reads per row, the same bounds and non-finite /// scale refusals, but positional (`pread`, no seek) and split over a few threads, because the batched prefill /// reads every row of a chunk the cache does not hold at once (tens of thousands on a cold chunk). pub fn read_rows_batch(&self, rows: &[u64]) -> Result, KarError> { - read_rows_parallel(self.row_handles(), &self.parts, self.archive_bytes(), self.identity.as_ref(), rows, 32, 512, false) + read_rows_parallel( + self.row_handles(), + &self.parts, + self.archive_bytes(), + self.identity.as_ref(), + rows, + 32, + 512, + false, + ) } /// An owned reader of the same rows (handles of its own and a copy of the partition table) that another thread /// can use while this artifact is busy: the prefill reads the rows of the next chunk ahead. diff --git a/crates/model-format/src/kar/independent_handles.rs b/crates/model-format/src/kar/independent_handles.rs index 16d07ff2..83c4eae2 100644 --- a/crates/model-format/src/kar/independent_handles.rs +++ b/crates/model-format/src/kar/independent_handles.rs @@ -31,7 +31,16 @@ pub(super) fn reopen_independent(file: &File) -> std::io::Result { impl KarPleRowReader { /// `max_threads` positional-read threads at most (one per 512 rows). pub fn read_rows(&self, rows: &[u64], max_threads: usize) -> Result, KarError> { - read_rows_parallel(&self.files, &self.parts, self.archive_bytes, self.identity.as_ref(), rows, max_threads, 512, false) + read_rows_parallel( + &self.files, + &self.parts, + self.archive_bytes, + self.identity.as_ref(), + rows, + max_threads, + 512, + false, + ) } } #[allow(clippy::too_many_arguments)] @@ -53,16 +62,8 @@ pub(super) fn read_rows_parallel( } check_archive_state(first, archive_bytes, identity)?; let mut packets = Vec::new(); - packets - .try_reserve_exact(rows.len()) - .map_err(|_| KarError::Allocation)?; - packets.resize( - rows.len(), - KarPleRowPacket { - payload: [0; 50], - partition: 0, - }, - ); + packets.try_reserve_exact(rows.len()).map_err(|_| KarError::Allocation)?; + packets.resize(rows.len(), KarPleRowPacket { payload: [0; 50], partition: 0 }); // positional reads of a file that is not in the page cache are latency-bound: many in flight let workers = (rows.len() / min_rows_per_thread.max(1)).clamp(1, max_threads.max(1)); if warm_probe && workers > 1 { @@ -95,10 +96,7 @@ pub(super) fn read_rows_parallel( .collect(); handles .into_iter() - .map(|h| { - h.join() - .unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked"))) - }) + .map(|h| h.join().unwrap_or(Err(KarError::Format("KAR PLE reader thread panicked")))) .collect() }); for r in results { @@ -157,35 +155,21 @@ pub(super) fn read_rows_chunk( } let scale = p .scales - .checked_add( - local - .checked_mul(10) - .ok_or(KarError::Range("KAR PLE scale overflow"))?, - ) + .checked_add(local.checked_mul(10).ok_or(KarError::Range("KAR PLE scale overflow"))?) .ok_or(KarError::Range("KAR PLE scale overflow"))?; read_at(file, scale, &mut packet.payload[..10])?; for plane in 0..2usize { let at = p .planes - .checked_add( - (plane as u64) - .checked_mul(p.stride) - .ok_or(KarError::Range("KAR PLE plane overflow"))?, - ) + .checked_add((plane as u64).checked_mul(p.stride).ok_or(KarError::Range("KAR PLE plane overflow"))?) .and_then(|at| local.checked_mul(20).and_then(|n| at.checked_add(n))) .ok_or(KarError::Range("KAR PLE plane overflow"))?; read_at(file, at, &mut packet.payload[10 + plane * 20..30 + plane * 20])?; } - if packet.payload[..10] - .as_chunks::<2>() - .0 - .iter() - .any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) - { + if packet.payload[..10].as_chunks::<2>().0.iter().any(|b| u16::from_le_bytes(*b) & 0x7c00 == 0x7c00) { return Err(KarError::Profile("KAR PLE nonfinite scale")); } - packet.partition = - u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; + packet.partition = u16::try_from(index).map_err(|_| KarError::Range("KAR PLE partition index"))?; } Ok(()) } @@ -199,9 +183,7 @@ pub(super) fn read_at(file: &File, offset: u64, buffer: &mut [u8]) -> Result<(), use std::os::windows::fs::FileExt; let mut done = 0; while done < buffer.len() { - let n = file - .seek_read(&mut buffer[done..], offset + done as u64) - .map_err(KarError::Io)?; + let n = file.seek_read(&mut buffer[done..], offset + done as u64).map_err(KarError::Io)?; if n == 0 { return Err(KarError::Io(std::io::ErrorKind::UnexpectedEof.into())); } diff --git a/crates/model-format/src/kar/inspect_file.rs b/crates/model-format/src/kar/inspect_file.rs index 5b67e302..2a1ebde5 100644 --- a/crates/model-format/src/kar/inspect_file.rs +++ b/crates/model-format/src/kar/inspect_file.rs @@ -46,20 +46,13 @@ pub(super) fn inspect_file(mut file: File) -> Result { return Err("invalid KAR flags, digest algorithm, or element counts".into()); } let expected_bpw = archive_bytes as f64 * 8.0 / total_elements as f64; - if !accounted_bpw.is_finite() - || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) - { + if !accounted_bpw.is_finite() || ((accounted_bpw - expected_bpw) / expected_bpw).abs() > 2f64.powi(-40) { return Err("KAR accounted_bpw does not match archive size".into()); } - let directory_bytes = (tensor_count as u64) - .checked_mul(RECORD_BYTES as u64) - .ok_or("KAR directory length overflow")?; - let directory_end = directory_offset - .checked_add(directory_bytes) - .ok_or("KAR directory overflow")?; - let string_end = string_offset - .checked_add(string_bytes) - .ok_or("KAR string table overflow")?; + let directory_bytes = + (tensor_count as u64).checked_mul(RECORD_BYTES as u64).ok_or("KAR directory length overflow")?; + let directory_end = directory_offset.checked_add(directory_bytes).ok_or("KAR directory overflow")?; + let string_end = string_offset.checked_add(string_bytes).ok_or("KAR string table overflow")?; if !directory_offset.is_multiple_of(64) || !string_offset.is_multiple_of(64) || !payload_offset.is_multiple_of(256) @@ -80,35 +73,26 @@ pub(super) fn inspect_file(mut file: File) -> Result { } let mut seen_names = HashSet::new(); - seen_names - .try_reserve(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; + seen_names.try_reserve(tensor_count as usize).map_err(|_| "KAR allocation failed")?; let mut elements_sum = 0u64; let mut bits_sum = 0u64; let mut previous_end = payload_offset; let mut min_planes = u8::MAX; let mut max_planes = 0u8; let mut sections = Vec::new(); - sections - .try_reserve_exact(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; + sections.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?; let mut sources = Vec::new(); - sources - .try_reserve_exact(tensor_count as usize) - .map_err(|_| "KAR allocation failed")?; + sources.try_reserve_exact(tensor_count as usize).map_err(|_| "KAR allocation failed")?; let (records, remainder) = directory.as_chunks::(); debug_assert!(remainder.is_empty()); for record in records { let name_start = u32_at(record, 0) as usize; let name_len = u16_at(record, 4) as usize; - let name_end = name_start - .checked_add(name_len) - .ok_or("KAR name offset overflow")?; + let name_end = name_start.checked_add(name_len).ok_or("KAR name offset overflow")?; if name_end >= names.len() || names[name_end] != 0 { return Err("invalid KAR tensor name bounds".into()); } - let name = std::str::from_utf8(&names[name_start..name_end]) - .map_err(|_| "KAR tensor name is not UTF-8")?; + let name = std::str::from_utf8(&names[name_start..name_end]).map_err(|_| "KAR tensor name is not UTF-8")?; if !seen_names.insert(name) { return Err("duplicate KAR tensor name".into()); } @@ -117,9 +101,7 @@ pub(super) fn inspect_file(mut file: File) -> Result { if !(1..=4).contains(&n_dims) || storage > 1 || record[40] != 0 || record[41] > 2 { return Err("unsupported KAR tensor layout".into()); } - let dims = (0..4) - .map(|index| u64_at(record, 8 + index * 8)) - .collect::>(); + let dims = (0..4).map(|index| u64_at(record, 8 + index * 8)).collect::>(); if dims[n_dims..].iter().any(|dim| *dim != 1) { return Err("invalid KAR unused dimension".into()); } @@ -131,9 +113,7 @@ pub(super) fn inspect_file(mut file: File) -> Result { if product != n_elements || n_elements == 0 { return Err("KAR tensor element count mismatch".into()); } - elements_sum = elements_sum - .checked_add(n_elements) - .ok_or("KAR model element count overflow")?; + elements_sum = elements_sum.checked_add(n_elements).ok_or("KAR model element count overflow")?; let mut source_digest = [0u8; 32]; source_digest.copy_from_slice(&record[128..160]); sources.push(KarTensorSource { @@ -153,21 +133,12 @@ pub(super) fn inspect_file(mut file: File) -> Result { }); let section_offset = u64_at(record, 112); let section_bytes = u64_at(record, 120); - let section_end = section_offset - .checked_add(section_bytes) - .ok_or("KAR tensor section overflow")?; - if section_offset != previous_end - || !section_offset.is_multiple_of(256) - || section_end > archive_bytes - { + let section_end = section_offset.checked_add(section_bytes).ok_or("KAR tensor section overflow")?; + if section_offset != previous_end || !section_offset.is_multiple_of(256) || section_end > archive_bytes { return Err("KAR tensor sections are not contiguous or bounded".into()); } previous_end = section_end; - sections.push(Section { - offset: section_offset, - bytes: section_bytes, - crc32: u32_at(record, 108), - }); + sections.push(Section { offset: section_offset, bytes: section_bytes, crc32: u32_at(record, 108) }); if storage == 0 { let group = u16_at(record, 46) as u64; let planes = record[42]; @@ -183,10 +154,7 @@ pub(super) fn inspect_file(mut file: File) -> Result { { return Err("invalid KAR nested tensor parameters".into()); } - let rounded = n_elements - .div_ceil(group) - .checked_mul(group) - .ok_or("KAR padded count overflow")?; + let rounded = n_elements.div_ceil(group).checked_mul(group).ok_or("KAR padded count overflow")?; if n_padded != rounded { return Err("KAR padded tensor count mismatch".into()); } @@ -196,15 +164,10 @@ pub(super) fn inspect_file(mut file: File) -> Result { let books_bytes = u64_at(record, 88); let planes_offset = u64_at(record, 96); let stride = u32_at(record, 104) as u64; - let expected_scales = (n_padded / group) - .checked_mul(2) - .ok_or("KAR scale count overflow")?; + let expected_scales = (n_padded / group).checked_mul(2).ok_or("KAR scale count overflow")?; let expected_books = (1u64 << (planes as u32 + 2)) - 4; - let plane_words_bytes = (n_padded / 32) - .checked_mul(4) - .ok_or("KAR plane size overflow")?; - let expected_stride = - round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; + let plane_words_bytes = (n_padded / 32).checked_mul(4).ok_or("KAR plane size overflow")?; + let expected_stride = round_up(plane_words_bytes, 16).ok_or("KAR plane stride overflow")?; let books_start = scales_offset .checked_add(scales_bytes) .and_then(|value| round_up(value, 16)) @@ -219,23 +182,15 @@ pub(super) fn inspect_file(mut file: File) -> Result { || books_bytes != expected_books || planes_offset != planes_start || stride != expected_stride - || planes_offset - .checked_add(planes as u64 * stride) - .is_none_or(|end| end > section_end) + || planes_offset.checked_add(planes as u64 * stride).is_none_or(|end| end > section_end) { return Err("invalid KAR nested tensor section layout".into()); } let tensor_bits = (planes as u64) .checked_mul(n_padded) - .and_then(|bits| { - (n_padded / group) - .checked_mul(16) - .and_then(|scale_bits| bits.checked_add(scale_bits)) - }) + .and_then(|bits| (n_padded / group).checked_mul(16).and_then(|scale_bits| bits.checked_add(scale_bits))) .ok_or("KAR tensor bit count overflow")?; - bits_sum = bits_sum - .checked_add(tensor_bits) - .ok_or("KAR coded bit count overflow")?; + bits_sum = bits_sum.checked_add(tensor_bits).ok_or("KAR coded bit count overflow")?; min_planes = min_planes.min(record[43]); max_planes = max_planes.max(record[44]); } else { @@ -247,11 +202,7 @@ pub(super) fn inspect_file(mut file: File) -> Result { return Err("invalid KAR raw tensor metadata".into()); } let width = if record[41] == 0 { 4 } else { 2 }; - if section_bytes - < n_elements - .checked_mul(width) - .ok_or("KAR raw tensor size overflow")? - { + if section_bytes < n_elements.checked_mul(width).ok_or("KAR raw tensor size overflow")? { return Err("KAR raw tensor section is too small".into()); } } diff --git a/crates/model-format/src/kar/read_region.rs b/crates/model-format/src/kar/read_region.rs index 44303bce..25e424a8 100644 --- a/crates/model-format/src/kar/read_region.rs +++ b/crates/model-format/src/kar/read_region.rs @@ -3,17 +3,12 @@ #[allow(unused_imports)] use super::*; - pub(super) fn read_region(file: &mut File, offset: u64, length: usize) -> Result, String> { - file.seek(SeekFrom::Start(offset)) - .map_err(|error| error.to_string())?; + file.seek(SeekFrom::Start(offset)).map_err(|error| error.to_string())?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(length) - .map_err(|_| "KAR allocation failed")?; + bytes.try_reserve_exact(length).map_err(|_| "KAR allocation failed")?; bytes.resize(length, 0); - file.read_exact(&mut bytes) - .map_err(|error| error.to_string())?; + file.read_exact(&mut bytes).map_err(|error| error.to_string())?; Ok(bytes) } @@ -165,9 +160,7 @@ pub(super) fn verify_integrity_stream( if n == 0 { break; } - let end = total - .checked_add(n as u64) - .ok_or(KarError::Range("KAR hash length overflow"))?; + let end = total.checked_add(n as u64).ok_or(KarError::Range("KAR hash length overflow"))?; digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. while let Some(section) = sections.get(index) { if section.offset >= end { @@ -176,10 +169,7 @@ pub(super) fn verify_integrity_stream( let section_end = section.offset + section.bytes; // Checked above. let start = total.max(section.offset); let stop = end.min(section_end); - crc = crc32_step( - crc, - &buffer[(start - total) as usize..(stop - total) as usize], - ); + crc = crc32_step(crc, &buffer[(start - total) as usize..(stop - total) as usize]); if stop != section_end { break; } diff --git a/crates/model-format/src/kar_extents.rs b/crates/model-format/src/kar_extents.rs index 07caa717..872b4fca 100644 --- a/crates/model-format/src/kar_extents.rs +++ b/crates/model-format/src/kar_extents.rs @@ -14,9 +14,7 @@ //! bytes of the extents, in order; //! * [`KarCensus`] is the read-only report `examples/kar_census.rs` prints. -use super::{ - KarError, KarInspection, KarNestedRecord, PLE_ROWS, Sha256, VerifiedPart, read_at, round_up, -}; +use super::{KarError, KarInspection, KarNestedRecord, PLE_ROWS, Sha256, VerifiedPart, read_at, round_up}; use sha2::Digest; use std::fmt::Write as _; @@ -24,10 +22,8 @@ use std::fmt::Write as _; pub const EXTENT_ALIGN: u64 = 4096; /// The two partitions of the pinned `per_layer_token_embd.weight` (order = row order). -pub const PLE_PART_NAMES: [&str; 2] = [ - "per_layer_token_embd.weight#strata-part-001-of-002", - "per_layer_token_embd.weight#strata-part-002-of-002", -]; +pub const PLE_PART_NAMES: [&str; 2] = + ["per_layer_token_embd.weight#strata-part-001-of-002", "per_layer_token_embd.weight#strata-part-002-of-002"]; /// Bytes the serve path reads per PLE row: scales (5 f16 words) and two bit-plane rows (5 words each). pub const PLE_ROW_SCALE_BYTES: u64 = 10; @@ -41,8 +37,8 @@ pub const PLE_PLANES: u64 = 2; /// 7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143. While it is all zero a sparse copy is refused unless the /// operator supplies the digest explicitly. pub const PLE_EXTENTS_SHA256: [u8; 32] = [ - 117, 104, 177, 33, 20, 25, 167, 193, 10, 155, 57, 168, 98, 48, 247, 91, 127, 169, 192, 40, 57, 227, 108, 155, 95, 36, 148, 236, 122, - 247, 33, 67, + 117, 104, 177, 33, 20, 25, 167, 193, 10, 155, 57, 168, 98, 48, 247, 91, 127, 169, 192, 40, 57, 227, 108, 155, 95, + 36, 148, 236, 122, 247, 33, 67, ]; const DOMAIN: &[u8] = b"leleka-kar-extents-v1\0"; diff --git a/crates/model-format/src/kar_extents/impl_extent.rs b/crates/model-format/src/kar_extents/impl_extent.rs index 7750a56f..187085a8 100644 --- a/crates/model-format/src/kar_extents/impl_extent.rs +++ b/crates/model-format/src/kar_extents/impl_extent.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Extent { pub fn new(offset: u64, len: u64) -> Self { Self { offset, len } @@ -22,9 +21,7 @@ pub fn extents_bytes(extents: &[Extent]) -> u64 { /// `archive_bytes`. A range beyond the archive is an error; empty ranges are dropped. pub fn normalize_extents(raw: &[Extent], archive_bytes: u64) -> Result, KarError> { let mut ranges = Vec::new(); - ranges - .try_reserve_exact(raw.len()) - .map_err(|_| KarError::Allocation)?; + ranges.try_reserve_exact(raw.len()).map_err(|_| KarError::Allocation)?; for e in raw.iter().filter(|e| e.len > 0) { let end = e .offset @@ -32,9 +29,7 @@ pub fn normalize_extents(raw: &[Extent], archive_bytes: u64) -> Result bool { /// Bytes of `extents` that fall inside `[offset, offset + len)`. pub fn extents_overlap(extents: &[Extent], offset: u64, len: u64) -> u64 { let end = offset.saturating_add(len); - extents - .iter() - .map(|e| e.end().min(end).saturating_sub(e.offset.max(offset))) - .sum() + extents.iter().map(|e| e.end().min(end).saturating_sub(e.offset.max(offset))).sum() } /// The pinned hash of a sparse copy: SHA-256 over the domain tag, the number of extents, `(offset, len)` of each, and @@ -87,9 +79,7 @@ pub fn digest_extents_with( hash.update(e.len.to_le_bytes()); } let mut buffer = Vec::new(); - buffer - .try_reserve_exact(HASH_CHUNK) - .map_err(|_| KarError::Allocation)?; + buffer.try_reserve_exact(HASH_CHUNK).map_err(|_| KarError::Allocation)?; buffer.resize(HASH_CHUNK, 0); for e in extents { let mut done = 0u64; @@ -117,12 +107,8 @@ impl VerifiedPart { /// The bytes `read_rows_chunk` reads for this partition: the scales, and the first [`PLE_PLANES`] planes. pub(in super::super) fn reads(&self) -> Result<[Extent; 3], KarError> { let rows = self.row_count; - let plane_bytes = rows - .checked_mul(PLE_ROW_PLANE_BYTES) - .ok_or(KarError::Range("KAR PLE plane overflow"))?; - let scale_bytes = rows - .checked_mul(PLE_ROW_SCALE_BYTES) - .ok_or(KarError::Range("KAR PLE scale overflow"))?; + let plane_bytes = rows.checked_mul(PLE_ROW_PLANE_BYTES).ok_or(KarError::Range("KAR PLE plane overflow"))?; + let scale_bytes = rows.checked_mul(PLE_ROW_SCALE_BYTES).ok_or(KarError::Range("KAR PLE scale overflow"))?; let plane = |k: u64| -> Result { let at = k .checked_mul(self.stride) @@ -177,7 +163,10 @@ pub(super) fn merge_exact(mut raw: Vec) -> Vec { /// The `VerifiedPart` a PLE partition record yields (the same fields `VerifiedKarPleArtifact::verify` derives from the /// raw directory bytes), plus the position of its first book. -pub(in super::super) fn part_from_record(record: &KarNestedRecord, row_base: u64) -> Result<(VerifiedPart, u64), KarError> { +pub(in super::super) fn part_from_record( + record: &KarNestedRecord, + row_base: u64, +) -> Result<(VerifiedPart, u64), KarError> { if record.dimensions.len() != 2 || record.dimensions[0] != 160 || record.group != 32 @@ -195,9 +184,6 @@ pub(in super::super) fn part_from_record(record: &KarNestedRecord, row_base: u64 planes: record.planes_offset, stride: u64::from(record.plane_stride_bytes), }; - let book = record - .books_offset - .checked_add(4) - .ok_or(KarError::Range("KAR PLE book overflow"))?; + let book = record.books_offset.checked_add(4).ok_or(KarError::Range("KAR PLE book overflow"))?; Ok((part, book)) } diff --git a/crates/model-format/src/kar_extents/impl_karinspection.rs b/crates/model-format/src/kar_extents/impl_karinspection.rs index a39968bd..734d638e 100644 --- a/crates/model-format/src/kar_extents/impl_karinspection.rs +++ b/crates/model-format/src/kar_extents/impl_karinspection.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl KarInspection { /// Offset of the first tensor section; everything before it is header, directory and names. pub fn payload_offset(&self) -> u64 { @@ -20,9 +19,7 @@ impl KarInspection { for name in part_names { let record = self.nested_record(name)?; let (part, book) = part_from_record(&record, row_base)?; - row_base = row_base - .checked_add(part.row_count) - .ok_or(KarError::Range("KAR PLE row count overflow"))?; + row_base = row_base.checked_add(part.row_count).ok_or(KarError::Range("KAR PLE row count overflow"))?; let [scales, p0, p1] = part.reads()?; parts.push(PartReads { name: record.name.clone(), @@ -38,12 +35,7 @@ impl KarInspection { let raw = exact_reads(self.payload_offset, &verified, &books)?; let exact = merge_exact(raw.clone()); let extents = normalize_extents(&raw, archive_bytes)?; - Ok(ServeReads { - metadata: Extent::new(0, self.payload_offset), - parts, - exact, - extents, - }) + Ok(ServeReads { metadata: Extent::new(0, self.payload_offset), parts, exact, extents }) } /// The read-only report of the directory: every record, the class of each, what the serve path reads of it. @@ -53,10 +45,7 @@ impl KarInspection { let mut records = Vec::with_capacity(self.sources.len()); for source in &self.sources { let ple = serve.parts.iter().find(|p| p.name == source.name); - let stored = nested - .iter() - .find(|n| n.name == source.name) - .map(|n| n.planes_stored); + let stored = nested.iter().find(|n| n.name == source.name).map(|n| n.planes_stored); let class = match (ple.is_some(), source.storage_class) { (true, _) => RecordClass::PleRows, (false, 0) => RecordClass::NestedUnread, @@ -126,7 +115,10 @@ impl KarCensus { self.payload_offset, self.payload_offset, self.metadata_extent_bytes ); if all_records { - let _ = writeln!(out, "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims"); + let _ = writeln!( + out, + "\n# index class section_offset section_bytes elements planes read_exact in_sparse_copy name dims" + ); for (i, r) in self.records.iter().enumerate() { let _ = writeln!( out, @@ -152,7 +144,10 @@ impl KarCensus { } } let _ = writeln!(out, "\n# totals per kind"); - let _ = writeln!(out, "kind records elements section_bytes read_exact_bytes sparse_copy_bytes"); + let _ = writeln!( + out, + "kind records elements section_bytes read_exact_bytes sparse_copy_bytes" + ); for class in [RecordClass::PleRows, RecordClass::NestedUnread, RecordClass::RawUnread] { let t = self.totals(class); let _ = writeln!( @@ -184,10 +179,26 @@ impl KarCensus { } let exact = self.serve.exact_bytes(); let ext = self.serve.extent_bytes(); - let _ = writeln!(out, "serve_read_exact_bytes={exact} ({:.3} GiB, {:.2} % of the archive)", gib(exact), pct(exact, self.archive_bytes)); - let _ = writeln!(out, "sparse_copy_bytes={ext} ({:.3} GiB, {:.2} % of the archive) in {} extents", gib(ext), pct(ext, self.archive_bytes), self.serve.extents.len()); + let _ = writeln!( + out, + "serve_read_exact_bytes={exact} ({:.3} GiB, {:.2} % of the archive)", + gib(exact), + pct(exact, self.archive_bytes) + ); + let _ = writeln!( + out, + "sparse_copy_bytes={ext} ({:.3} GiB, {:.2} % of the archive) in {} extents", + gib(ext), + pct(ext, self.archive_bytes), + self.serve.extents.len() + ); let unread = self.unread_extent_bytes(); - let _ = writeln!(out, "never_read_bytes={unread} ({:.3} GiB, {:.2} % of the archive; archive minus the sparse copy)", gib(unread), pct(unread, self.archive_bytes)); + let _ = writeln!( + out, + "never_read_bytes={unread} ({:.3} GiB, {:.2} % of the archive; archive minus the sparse copy)", + gib(unread), + pct(unread, self.archive_bytes) + ); let nested = self.totals(RecordClass::NestedUnread); let raw = self.totals(RecordClass::RawUnread); let _ = writeln!( diff --git a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs index 904d4ef6..8a18976f 100644 --- a/crates/model-format/src/kar_kernel_model/decode_params_valid.rs +++ b/crates/model-format/src/kar_kernel_model/decode_params_valid.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// The argument guard at the top of `leleka_kar_decode_levels_f32`. It runs in /// 64-bit arithmetic before any packet byte is read, so a corrupt parameter /// block cannot cause an out-of-bounds device read. @@ -35,8 +34,7 @@ pub fn decode_params_valid(p: &DecodeParams) -> bool { words_needed <= u64::from(p.window_words) && groups_needed <= u64::from(p.window_groups) && u64::from(p.scales_offset) + 2 * u64::from(p.window_groups) <= u64::from(p.packet_bytes) - && u64::from(p.planes_offset) + level * u64::from(p.plane_stride_words) * 4 - <= u64::from(p.packet_bytes) + && u64::from(p.planes_offset) + level * u64::from(p.plane_stride_words) * 4 <= u64::from(p.packet_bytes) } /// `gridDim.x` for a decode of `count` elements. @@ -49,10 +47,7 @@ pub fn decode_grid(count: u32) -> u32 { /// word. On `STATUS_BAD_ARGUMENT` no output element is written. pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { let mut status = 0u32; - if !decode_params_valid(p) - || packet.len() < p.packet_bytes as usize - || out.len() < p.count as usize - { + if !decode_params_valid(p) || packet.len() < p.packet_bytes as usize || out.len() < p.count as usize { return STATUS_BAD_ARGUMENT; } let level = p.level; @@ -81,8 +76,8 @@ pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { let group_index = (p.head_group + i) / p.group; let mut code = 0u32; for plane in 0..level { - let at = p.planes_offset as usize - + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; + let at = + p.planes_offset as usize + (plane as usize * p.plane_stride_words as usize + word as usize) * 4; code = (code << 1) | ((le32(packet, at) >> bit) & 1); } let scale_bits = le16(packet, p.scales_offset as usize + 2 * group_index as usize); @@ -102,14 +97,7 @@ pub fn kernel_decode(p: &DecodeParams, packet: &[u8], out: &mut [f32]) -> u32 { /// 256 lanes striding the columns with separately rounded multiply/add, then /// the fixed 128..1 shared-memory tree. Output is `[token][row]`. #[allow(clippy::needless_range_loop)] // lane indices mirror threadIdx.x -pub fn kernel_multiply( - weights: &[f32], - input: &[f32], - columns: u32, - rows: u32, - tokens: u32, - out: &mut [f32], -) -> u32 { +pub fn kernel_multiply(weights: &[f32], input: &[f32], columns: u32, rows: u32, tokens: u32, out: &mut [f32]) -> u32 { let (cols, nrows) = (columns as usize, rows as usize); if columns == 0 || rows == 0 @@ -157,8 +145,7 @@ pub fn kernel_multiply( /// GPU smoke compares this stage with a tolerance, never as a bit claim. pub fn kernel_swiglu(gate: &[f32], up: &[f32], act: &mut [f32]) -> u32 { let values = gate.len(); - if values == 0 || values as u64 > MAX_SWIGLU_VALUES || up.len() != values || act.len() < values - { + if values == 0 || values as u64 > MAX_SWIGLU_VALUES || up.len() != values || act.len() < values { return STATUS_BAD_ARGUMENT; } let mut status = 0; @@ -178,10 +165,9 @@ pub fn kernel_swiglu(gate: &[f32], up: &[f32], act: &mut [f32]) -> u32 { pub fn stage_packet(plan: &WindowPlan, archive: &[u8]) -> Result> { let mut packet = vec![0u8; plan.packet_bytes() as usize]; for range in plan.ranges() { - let (Some(source_end), Some(packet_end)) = ( - range.archive_offset.checked_add(range.len), - range.packet_offset.checked_add(range.len), - ) else { + let (Some(source_end), Some(packet_end)) = + (range.archive_offset.checked_add(range.len), range.packet_offset.checked_add(range.len)) + else { return reject("KAR stage range overflows"); }; if source_end > archive.len() as u64 || packet_end > packet.len() as u64 { diff --git a/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs index a73aa140..bdd330e4 100644 --- a/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs +++ b/crates/model-format/src/kar_kernel_model/impl_fmt_display_for.rs @@ -30,9 +30,7 @@ impl WindowPlan { } /// Every archive range the stager must read, in packet order. pub fn ranges(&self) -> impl Iterator { - [&self.book, &self.scales] - .into_iter() - .chain(self.planes.iter()) + [&self.book, &self.scales].into_iter().chain(self.planes.iter()) } /// Total archive bytes copied into the packet (excludes padding). pub fn staged_source_bytes(&self) -> u64 { @@ -41,12 +39,7 @@ impl WindowPlan { } /// Plan one bounded window of a NESTED record at `level`. -pub fn plan_window( - record: &KarNestedRecord, - level: u8, - start: u64, - count: u64, -) -> Result { +pub fn plan_window(record: &KarNestedRecord, level: u8, start: u64, count: u64) -> Result { if record.validate().is_err() { return reject("KAR nested record layout is invalid"); } @@ -65,9 +58,7 @@ pub fn plan_window( if count == 0 || count > MAX_RANGE_ELEMENTS { return reject("KAR decode count must be 1..=16,777,216"); } - let end = start - .checked_add(count) - .filter(|end| *end <= record.n_elements); + let end = start.checked_add(count).filter(|end| *end <= record.n_elements); let Some(end) = end else { return reject("KAR decode range exceeds the tensor"); }; @@ -117,11 +108,7 @@ pub fn plan_window( count: to_u32(count), first_word, first_group, - book: ByteRange { - archive_offset: record.books_offset + book_skip, - len: book_len, - packet_offset: 0, - }, + book: ByteRange { archive_offset: record.books_offset + book_skip, len: book_len, packet_offset: 0 }, scales: ByteRange { archive_offset: record.scales_offset + first_group * 2, len: scales_len, @@ -148,12 +135,7 @@ pub fn plan_window( /// Plan `rows` complete rows starting at `first_row`. A row is `dims[0]` /// consecutive weights; rows of higher dimensions are flattened in order, so /// expert `e` of a `[cols, rows, experts]` tensor starts at row `e * rows`. -pub fn plan_rows( - record: &KarNestedRecord, - level: u8, - first_row: u64, - rows: u64, -) -> Result { +pub fn plan_rows(record: &KarNestedRecord, level: u8, first_row: u64, rows: u64) -> Result { let Some(&columns) = record.dimensions.first() else { return reject("KAR record has no dimensions"); }; @@ -161,22 +143,14 @@ pub fn plan_rows( return reject("KAR row length or row count is out of range"); } let total_rows = record.n_elements / columns; - if first_row - .checked_add(rows) - .is_none_or(|end| end > total_rows) - { + if first_row.checked_add(rows).is_none_or(|end| end > total_rows) { return reject("KAR row range exceeds the tensor"); } - let (Some(start), Some(count)) = (first_row.checked_mul(columns), rows.checked_mul(columns)) - else { + let (Some(start), Some(count)) = (first_row.checked_mul(columns), rows.checked_mul(columns)) else { return reject("KAR row range overflows"); }; let window = plan_window(record, level, start, count)?; - Ok(RowPlan { - window, - columns: columns as u32, - rows: rows as u32, - }) + Ok(RowPlan { window, columns: columns as u32, rows: rows as u32 }) } /// Row range of one expert in a `[cols, rows, experts]` record. diff --git a/crates/model-format/src/kar_levels.rs b/crates/model-format/src/kar_levels.rs index 46688f00..ce0a338c 100644 --- a/crates/model-format/src/kar_levels.rs +++ b/crates/model-format/src/kar_levels.rs @@ -17,9 +17,7 @@ //! and lower tensor error alone does not pass the model-quality gate. use crate::kar::{KarInspection, KarNestedRecord}; -use crate::kar_kernel_model::{ - self as model, KernelModelError, MAX_LEVEL, MAX_TOKENS, MIN_LEVEL, RowPlan, WindowPlan, -}; +use crate::kar_kernel_model::{self as model, KernelModelError, MAX_LEVEL, MAX_TOKENS, MIN_LEVEL, RowPlan, WindowPlan}; use std::{collections::BTreeMap, fmt}; /// Bytes of the device status word. diff --git a/crates/model-format/src/kar_levels/expert_scratch.rs b/crates/model-format/src/kar_levels/expert_scratch.rs index 0680b121..5037e425 100644 --- a/crates/model-format/src/kar_levels/expert_scratch.rs +++ b/crates/model-format/src/kar_levels/expert_scratch.rs @@ -3,22 +3,14 @@ #[allow(unused_imports)] use super::*; - /// Device scratch of one expert FFN as the closed CUDA program allocates it: /// three packets, one reused F32 weight matrix, input, gate/up/act /// intermediates, output and the status word, each rounded to the granularity. pub fn expert_scratch(rows: &[GpuRows; 3]) -> ScratchBytes { - let weights = rows - .iter() - .map(|r| r.shape.weights_bytes()) - .max() - .unwrap_or(0); + let weights = rows.iter().map(|r| r.shape.weights_bytes()).max().unwrap_or(0); let hidden = u64::from(rows[0].shape.columns) * 4; let ff = u64::from(rows[0].shape.rows) * 4; - let mut buffers: Vec = rows - .iter() - .map(|r| u64::from(r.window.plan.params.packet_bytes)) - .collect(); + let mut buffers: Vec = rows.iter().map(|r| u64::from(r.window.plan.params.packet_bytes)).collect(); buffers.extend([weights, hidden, ff, ff, ff, hidden, STATUS_BYTES]); ScratchBytes::of(&buffers) } @@ -27,11 +19,7 @@ pub fn expert_scratch(rows: &[GpuRows; 3]) -> ScratchBytes { /// from the kernel model (decode, F32 multiply, SwiGLU). It is the reference a /// GPU smoke compares against; the SwiGLU stage differs from the device `expf` /// by libm rounding only, so a device comparison uses a stated tolerance there. -pub fn cpu_reference_mlp( - rows: &[GpuRows; 3], - packets: &[Vec; 3], - input: &[f32], -) -> Result> { +pub fn cpu_reference_mlp(rows: &[GpuRows; 3], packets: &[Vec; 3], input: &[f32]) -> Result> { let apply = |index: usize, x: &[f32]| -> Result> { let r = &rows[index]; let mut weights = vec![0f32; r.window.plan.params.count as usize]; diff --git a/crates/model-format/src/kar_levels/impl_fmt_display_for.rs b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs index d299a759..057d0e1d 100644 --- a/crates/model-format/src/kar_levels/impl_fmt_display_for.rs +++ b/crates/model-format/src/kar_levels/impl_fmt_display_for.rs @@ -13,10 +13,9 @@ impl fmt::Display for KarLevelsError { Self::HostAllocation => f.write_str("KAR host packet allocation failed"), Self::Layout(reason) => f.write_str(reason), Self::NonFinite => f.write_str("KAR expert computation produced a non-finite value"), - Self::Budget { needed, available } => write!( - f, - "KAR scratch needs {needed} bytes but only {available} remain" - ), + Self::Budget { needed, available } => { + write!(f, "KAR scratch needs {needed} bytes but only {available} remain") + } } } } @@ -50,19 +49,13 @@ impl TensorClass { } } pub(super) fn index(self) -> usize { - Self::ALL - .iter() - .position(|c| *c == self) - .expect("class is in ALL") + Self::ALL.iter().position(|c| *c == self).expect("class is in ALL") } } impl ClassLevels { pub fn uniform(level: u8) -> Result { check_level(level)?; - Ok(Self { - default: level, - per_class: [None; 7], - }) + Ok(Self { default: level, per_class: [None; 7] }) } pub fn with(mut self, class: TensorClass, level: u8) -> Result { check_level(level)?; @@ -83,11 +76,7 @@ pub(super) fn check_level(level: u8) -> Result<()> { impl ArchiveView { /// `records` must come from an archive whose payload CRCs and full SHA-256 /// were verified by the caller; this only re-validates record layouts. - pub fn from_records( - sha256: [u8; 32], - archive_bytes: u64, - records: Vec, - ) -> Result { + pub fn from_records(sha256: [u8; 32], archive_bytes: u64, records: Vec) -> Result { let mut map = BTreeMap::new(); for record in records { let section_end = record @@ -95,30 +84,20 @@ impl ArchiveView { .checked_add(record.section_bytes) .ok_or(KarLevelsError::Overlay("KAR section overflows"))?; if record.validate().is_err() || section_end > archive_bytes { - return Err(KarLevelsError::Overlay( - "KAR record layout is invalid or outside its archive", - )); + return Err(KarLevelsError::Overlay("KAR record layout is invalid or outside its archive")); } if map.insert(record.name.clone(), record).is_some() { return Err(KarLevelsError::Overlay("duplicate KAR record name")); } } - Ok(Self { - sha256, - archive_bytes, - records: map, - }) + Ok(Self { sha256, archive_bytes, records: map }) } pub fn from_inspection( inspection: &KarInspection, sha256: [u8; 32], ) -> std::result::Result> { let records = inspection.nested_records()?; - Ok(Self::from_records( - sha256, - inspection.summary().archive_bytes, - records, - )?) + Ok(Self::from_records(sha256, inspection.summary().archive_bytes, records)?) } pub fn records(&self) -> impl Iterator { self.records.values() @@ -134,63 +113,35 @@ impl ArchiveView { impl KarLevelSelector { /// Overlay records must replace same-named base records with identical /// shape; anything else is a mapping the resolver should have rejected. - pub fn new( - base: ArchiveView, - overlay: Option, - policy: LevelPolicy, - ) -> Result { + pub fn new(base: ArchiveView, overlay: Option, policy: LevelPolicy) -> Result { if let Some(overlay) = &overlay { if overlay.sha256 == base.sha256 { - return Err(KarLevelsError::Overlay( - "overlay archive is the base archive", - )); + return Err(KarLevelsError::Overlay("overlay archive is the base archive")); } for (name, replacement) in &overlay.records { let Some(original) = base.records.get(name) else { - return Err(KarLevelsError::Overlay( - "overlay record has no base record to replace", - )); + return Err(KarLevelsError::Overlay("overlay record has no base record to replace")); }; - if original.dimensions != replacement.dimensions - || original.n_elements != replacement.n_elements - { - return Err(KarLevelsError::Overlay( - "overlay record shape differs from its base record", - )); + if original.dimensions != replacement.dimensions || original.n_elements != replacement.n_elements { + return Err(KarLevelsError::Overlay("overlay record shape differs from its base record")); } } } - Ok(Self { - base, - overlay, - policy, - }) + Ok(Self { base, overlay, policy }) } /// Which archive serves `name` and at which level, per class policy. pub fn resolve(&self, name: &str) -> Result> { let class = TensorClass::classify(name); let (slot, record, level) = match self.overlay.as_ref().and_then(|o| o.records.get(name)) { - Some(record) => ( - ArchiveSlot::Overlay, - record, - self.policy.overlay.level_for(class), - ), + Some(record) => (ArchiveSlot::Overlay, record, self.policy.overlay.level_for(class)), None => { - let record = self - .base - .records - .get(name) - .ok_or_else(|| KarLevelsError::UnknownTensor(name.to_owned()))?; + let record = + self.base.records.get(name).ok_or_else(|| KarLevelsError::UnknownTensor(name.to_owned()))?; (ArchiveSlot::Base, record, self.policy.base.level_for(class)) } }; - Ok(Selection { - class, - slot, - level, - record, - }) + Ok(Selection { class, slot, level, record }) } pub fn archive(&self, slot: ArchiveSlot) -> Option<&ArchiveView> { @@ -202,25 +153,15 @@ impl KarLevelSelector { /// Compressed bytes if every named tensor stayed resident at its selected /// level (the libkar `kar_reserve` prefix), checked against a budget. - pub fn resident_bytes<'a>( - &self, - names: impl IntoIterator, - budget: u64, - ) -> Result { + pub fn resident_bytes<'a>(&self, names: impl IntoIterator, budget: u64) -> Result { let mut total = 0u64; for name in names { total = total .checked_add(self.resolve(name)?.resident_prefix_bytes()?) - .ok_or(KarLevelsError::Budget { - needed: u64::MAX, - available: budget, - })?; + .ok_or(KarLevelsError::Budget { needed: u64::MAX, available: budget })?; } if total > budget { - return Err(KarLevelsError::Budget { - needed: total, - available: budget, - }); + return Err(KarLevelsError::Budget { needed: total, available: budget }); } Ok(total) } diff --git a/crates/model-format/src/kar_levels/impl_selection.rs b/crates/model-format/src/kar_levels/impl_selection.rs index 9cadde76..c2af56b8 100644 --- a/crates/model-format/src/kar_levels/impl_selection.rs +++ b/crates/model-format/src/kar_levels/impl_selection.rs @@ -3,13 +3,9 @@ #[allow(unused_imports)] use super::*; - impl Selection<'_> { pub(super) fn window_error(&self, reason: KernelModelError) -> KarLevelsError { - KarLevelsError::Window { - tensor: self.record.name.clone(), - reason, - } + KarLevelsError::Window { tensor: self.record.name.clone(), reason } } /// Bytes the whole level-`level` prefix of this record occupies when kept @@ -17,37 +13,34 @@ impl Selection<'_> { pub fn resident_prefix_bytes(&self) -> Result { let r = self.record; if !(r.planes_min..=r.planes_max).contains(&self.level) { - return Err(self.window_error(KernelModelError::Rejected( - "KAR level is outside the record's certified dial", - ))); + return Err( + self.window_error(KernelModelError::Rejected("KAR level is outside the record's certified dial")) + ); } r.planes_offset .checked_sub(r.section_offset) - .and_then(|prefix| { - prefix.checked_add(u64::from(self.level) * u64::from(r.plane_stride_bytes)) - }) + .and_then(|prefix| prefix.checked_add(u64::from(self.level) * u64::from(r.plane_stride_bytes))) .filter(|bytes| *bytes <= r.section_bytes) .ok_or(KarLevelsError::Overlay("invalid KAR resident prefix size")) } /// Bounded flat element window `[start, start + count)`. pub fn window(&self, start: u64, count: u64) -> Result { - let plan = model::plan_window(self.record, self.level, start, count) - .map_err(|reason| self.window_error(reason))?; + let plan = + model::plan_window(self.record, self.level, start, count).map_err(|reason| self.window_error(reason))?; Ok(GpuWindow::new(self.slot, plan)) } /// `rows` complete rows from `first_row`, ready for the F32 multiply. pub fn rows(&self, first_row: u64, rows: u64, tokens: u32) -> Result { - let plan = model::plan_rows(self.record, self.level, first_row, rows) - .map_err(|reason| self.window_error(reason))?; + let plan = + model::plan_rows(self.record, self.level, first_row, rows).map_err(|reason| self.window_error(reason))?; GpuRows::new(self.slot, plan, tokens) } /// One expert matrix of a `[cols, rows, experts]` record. pub fn expert(&self, expert: u64, tokens: u32) -> Result { - let (first, rows) = - model::expert_rows(self.record, expert).map_err(|reason| self.window_error(reason))?; + let (first, rows) = model::expert_rows(self.record, expert).map_err(|reason| self.window_error(reason))?; self.rows(first, rows, tokens) } } @@ -92,11 +85,7 @@ impl GpuRows { } Ok(Self { window: GpuWindow::new(slot, plan.window), - shape: RowShape { - columns: plan.columns, - rows: plan.rows, - tokens, - }, + shape: RowShape { columns: plan.columns, rows: plan.rows, tokens }, }) } /// packet + decoded F32 weights + input + output + status, each aligned. @@ -112,10 +101,7 @@ impl GpuRows { } impl ScratchBytes { pub fn of(buffers: &[u64]) -> Self { - Self { - raw: buffers.iter().sum(), - aligned: buffers.iter().map(|b| align(*b)).sum(), - } + Self { raw: buffers.iter().sum(), aligned: buffers.iter().map(|b| align(*b)).sum() } } } impl ScratchBudget { @@ -128,10 +114,7 @@ impl ScratchBudget { pub fn reserve(&mut self, scratch: ScratchBytes) -> Result<()> { let available = self.remaining(); if scratch.aligned > available { - return Err(KarLevelsError::Budget { - needed: scratch.aligned, - available, - }); + return Err(KarLevelsError::Budget { needed: scratch.aligned, available }); } self.reserved += scratch.aligned; Ok(()) @@ -154,21 +137,11 @@ impl KarLevelSelector { /// Every layer x gate/up/down bank exists with exactly `[hidden, ff, /// experts]` (down: `[ff, hidden, experts]`) and the first and last expert /// are plannable at the selected level. Called at load, never lazily. - pub fn validate_expert_map( - &self, - layers: u32, - experts: u32, - hidden: u64, - ff: u64, - ) -> Result<()> { + pub fn validate_expert_map(&self, layers: u32, experts: u32, hidden: u64, ff: u64) -> Result<()> { for layer in 0..layers { for role in 0..3 { let selection = self.resolve(&expert_tensor_name(layer, role))?; - let want = if role == 2 { - [ff, hidden, u64::from(experts)] - } else { - [hidden, ff, u64::from(experts)] - }; + let want = if role == 2 { [ff, hidden, u64::from(experts)] } else { [hidden, ff, u64::from(experts)] }; if selection.record.dimensions != want { return Err(KarLevelsError::Layout("KAR expert tensor shape differs")); } @@ -182,10 +155,8 @@ impl KarLevelSelector { /// Plan the three matrices of one routed expert at their policy levels. pub fn plan_expert(&self, layer: u32, expert: u32) -> Result<[GpuRows; 3]> { - let plan = |role| -> Result { - self.resolve(&expert_tensor_name(layer, role))? - .expert(u64::from(expert), 1) - }; + let plan = + |role| -> Result { self.resolve(&expert_tensor_name(layer, role))?.expert(u64::from(expert), 1) }; Ok([plan(0)?, plan(1)?, plan(2)?]) } } @@ -210,18 +181,13 @@ impl RangeSource for [u8] { pub fn stage_window(source: &S, plan: &WindowPlan) -> Result> { let len = plan.packet_bytes() as usize; let mut packet = Vec::new(); - packet - .try_reserve_exact(len) - .map_err(|_| KarLevelsError::HostAllocation)?; + packet.try_reserve_exact(len).map_err(|_| KarLevelsError::HostAllocation)?; packet.resize(len, 0); for range in plan.ranges() { let (at, size) = (range.packet_offset as usize, range.len as usize); - let slot = packet.get_mut(at..at + size).ok_or(KarLevelsError::Layout( - "KAR packet range escapes its packet", - ))?; - source - .read_exact_at(range.archive_offset, slot) - .map_err(|_| KarLevelsError::Read)?; + let slot = + packet.get_mut(at..at + size).ok_or(KarLevelsError::Layout("KAR packet range escapes its packet"))?; + source.read_exact_at(range.archive_offset, slot).map_err(|_| KarLevelsError::Read)?; } Ok(packet) } diff --git a/crates/model-format/src/kar_nested.rs b/crates/model-format/src/kar_nested.rs index 3ea20712..9b655df3 100644 --- a/crates/model-format/src/kar_nested.rs +++ b/crates/model-format/src/kar_nested.rs @@ -7,9 +7,7 @@ //! the identical rules. No payload bytes are read here. use super::{KarError, KarInspection, RECORD_BYTES, round_up, u16_at, u32_at, u64_at}; -use crate::weight_source::{ - BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded, -}; +use crate::weight_source::{BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded}; /// Nesting order stored in directory byte 45. Only top-down is decodable by /// the CPU oracle and the CUDA path; bottom-up is legal in the container. @@ -98,31 +96,21 @@ impl KarNestedRecord { if self.dimensions.is_empty() || self.dimensions.len() > 4 || self.n_elements == 0 - || self - .dimensions - .iter() - .try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) - != Some(self.n_elements) + || self.dimensions.iter().try_fold(1u64, |acc, dim| acc.checked_mul(*dim)) != Some(self.n_elements) { return fail("KAR tensor element count mismatch"); } - let rounded = self - .n_elements - .div_ceil(group) - .checked_mul(group) - .ok_or(KarError::Format("KAR padded count overflow"))?; + let rounded = + self.n_elements.div_ceil(group).checked_mul(group).ok_or(KarError::Format("KAR padded count overflow"))?; if self.n_padded != rounded { return fail("KAR padded tensor count mismatch"); } - let expected_scales = (self.n_padded / group) - .checked_mul(2) - .ok_or(KarError::Format("KAR scale count overflow"))?; + let expected_scales = + (self.n_padded / group).checked_mul(2).ok_or(KarError::Format("KAR scale count overflow"))?; let expected_books = (1u64 << (planes + 2)) - 4; - let plane_words_bytes = (self.n_padded / 32) - .checked_mul(4) - .ok_or(KarError::Format("KAR plane size overflow"))?; - let expected_stride = - round_up(plane_words_bytes, 16).ok_or(KarError::Format("KAR plane stride overflow"))?; + let plane_words_bytes = + (self.n_padded / 32).checked_mul(4).ok_or(KarError::Format("KAR plane size overflow"))?; + let expected_stride = round_up(plane_words_bytes, 16).ok_or(KarError::Format("KAR plane stride overflow"))?; let books_start = self .scales_offset .checked_add(self.scales_bytes) @@ -143,10 +131,7 @@ impl KarNestedRecord { || self.books_bytes != expected_books || self.planes_offset != planes_start || u64::from(self.plane_stride_bytes) != expected_stride - || self - .planes_offset - .checked_add(planes * expected_stride) - .is_none_or(|end| end > section_end) + || self.planes_offset.checked_add(planes * expected_stride).is_none_or(|end| end > section_end) { return fail("invalid KAR nested tensor section layout"); } @@ -158,17 +143,12 @@ impl KarInspection { /// Every NESTED record in directory order. RAW records are skipped. pub fn nested_records(&self) -> Result, KarError> { let mut records = Vec::new(); - records - .try_reserve_exact(self.sources.len()) - .map_err(|_| KarError::Allocation)?; + records.try_reserve_exact(self.sources.len()).map_err(|_| KarError::Allocation)?; for (index, source) in self.sources.iter().enumerate() { - let record: &[u8; RECORD_BYTES] = self.directory - [index * RECORD_BYTES..(index + 1) * RECORD_BYTES] + let record: &[u8; RECORD_BYTES] = self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES] .try_into() .expect("validated directory"); - if let Some(nested) = - KarNestedRecord::from_directory(&source.name, &source.dimensions, record)? - { + if let Some(nested) = KarNestedRecord::from_directory(&source.name, &source.dimensions, record)? { records.push(nested); } } @@ -182,10 +162,8 @@ impl KarInspection { .iter() .position(|source| source.name == name) .ok_or(KarError::Range("KAR tensor not found"))?; - let record: &[u8; RECORD_BYTES] = self.directory - [index * RECORD_BYTES..(index + 1) * RECORD_BYTES] - .try_into() - .expect("validated directory"); + let record: &[u8; RECORD_BYTES] = + self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES].try_into().expect("validated directory"); let source = &self.sources[index]; KarNestedRecord::from_directory(&source.name, &source.dimensions, record)? .ok_or(KarError::Range("KAR tensor is RAW, not NESTED")) @@ -208,9 +186,7 @@ impl KarInspection { #[cfg(unix)] pub fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> Result<(), KarError> { use std::os::unix::fs::FileExt; - let end = offset - .checked_add(out.len() as u64) - .ok_or(KarError::Range("KAR read range overflows"))?; + let end = offset.checked_add(out.len() as u64).ok_or(KarError::Range("KAR read range overflows"))?; if end > self.summary.archive_bytes { return Err(KarError::Range("KAR read range exceeds the archive")); } @@ -224,9 +200,7 @@ impl KarInspection { #[cfg(windows)] pub fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> Result<(), KarError> { use std::os::windows::fs::FileExt; - let end = offset - .checked_add(out.len() as u64) - .ok_or(KarError::Range("KAR read range overflows"))?; + let end = offset.checked_add(out.len() as u64).ok_or(KarError::Range("KAR read range overflows"))?; if end > self.summary.archive_bytes { return Err(KarError::Range("KAR read range exceeds the archive")); } @@ -259,11 +233,7 @@ impl WeightSource for KarInspection { fn region(&self, range: std::ops::Range) -> Result, WeightError> { bounded(&range, self.summary.archive_bytes)?; - Ok(Region::Positional { - file: &self.file, - offset: range.start, - len: range.end - range.start, - }) + Ok(Region::Positional { file: &self.file, offset: range.start, len: range.end - range.start }) } fn live_len(&self) -> Result { diff --git a/crates/model-format/src/lib.rs b/crates/model-format/src/lib.rs index d7ea7deb..d0719a47 100644 --- a/crates/model-format/src/lib.rs +++ b/crates/model-format/src/lib.rs @@ -9,14 +9,14 @@ pub mod bulk_read; pub mod gguf; pub mod huge_pages; +pub mod qwen4exp; pub(crate) mod readahead; pub mod verify_stamp; pub mod weight_source; -pub mod qwen4exp; pub mod kar; pub mod kar_kernel_model; pub mod kar_levels; -pub mod ple_reader; pub mod native_dense_plan; pub mod pinned_arena_plan; +pub mod ple_reader; diff --git a/crates/model-format/src/native_dense_plan.rs b/crates/model-format/src/native_dense_plan.rs index 06f585bc..7479ff84 100644 --- a/crates/model-format/src/native_dense_plan.rs +++ b/crates/model-format/src/native_dense_plan.rs @@ -96,8 +96,16 @@ pub fn eligible(row: &TensorRow, include_ple_key: bool) -> bool { return include_ple_key && matches!(row.kind, 42 | 18 | 23 | 8); } const SUFFIXES: [&str; 10] = [ - ".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight", ".attn_q.weight", ".attn_k.weight", ".attn_v.weight", - ".attn_output.weight", ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight", + ".attn_qkv.weight", + ".attn_gate.weight", + ".ssm_out.weight", + ".attn_q.weight", + ".attn_k.weight", + ".attn_v.weight", + ".attn_output.weight", + ".ffn_gate_shexp.weight", + ".ffn_up_shexp.weight", + ".ffn_down_shexp.weight", ]; SUFFIXES.iter().any(|s| name.ends_with(s)) } @@ -199,7 +207,9 @@ pub fn plan_load( || number.is_some_and(|n| n >= split_count) || tensors != Some(split_tensors) { - return fail("native dense: additional shard must match the architecture-validated first shard's split metadata"); + return fail( + "native dense: additional shard must match the architecture-validated first shard's split metadata", + ); } if let Some(n) = number && !split_numbers.insert(n) @@ -216,7 +226,8 @@ pub fn plan_load( let payload = shard.file_size.saturating_sub(shard.data_start); for tensor in &shard.tensors { let geometry = block_geometry(tensor.kind); - let ok_geometry = geometry.is_some_and(|(elems, _)| !tensor.shape.is_empty() && tensor.shape[0] % elems == 0); + let ok_geometry = + geometry.is_some_and(|(elems, _)| !tensor.shape.is_empty() && tensor.shape[0] % elems == 0); let (block_elements, block_bytes) = match geometry { Some(g) if ok_geometry => g, _ => return fail(format!("native dense: invalid block geometry {}", tensor.name)), @@ -273,7 +284,8 @@ pub fn plan_load( { return fail(format!("native dense: incompatible matrix {}", tensor.name)); } - let bytes = native_mmvq_weight_bytes(tensor.kind, reference.ne0, reference.ne1).map_err(|e| format!("native dense: {e}"))?; + let bytes = native_mmvq_weight_bytes(tensor.kind, reference.ne0, reference.ne1) + .map_err(|e| format!("native dense: {e}"))?; max_in = max_in.max(reference.ne0); total += bytes; items.push(DenseItem { diff --git a/crates/model-format/src/native_dense_plan/tests.rs b/crates/model-format/src/native_dense_plan/tests.rs index 1469daa5..e00e76c1 100644 --- a/crates/model-format/src/native_dense_plan/tests.rs +++ b/crates/model-format/src/native_dense_plan/tests.rs @@ -24,7 +24,9 @@ fn weight_bytes_follow_the_original_tables() { assert!(native_mmvq_weight_bytes(12, 2561, 1).is_err()); assert!(native_mmvq_weight_bytes(12, 256, 0).is_err()); assert!(native_mmvq_weight_bytes(0, 256, 1).is_err()); - assert!(native_mmvq_weight_bytes(14, 256, i64::MAX).is_err() || native_mmvq_weight_bytes(14, 256, i64::MAX).is_ok()); + assert!( + native_mmvq_weight_bytes(14, 256, i64::MAX).is_err() || native_mmvq_weight_bytes(14, 256, i64::MAX).is_ok() + ); assert_eq!(native_q8_1_bytes(2560), Ok(2560 / 32 * 36)); assert!(native_q8_1_bytes(33).is_err()); for t in 0..64 { @@ -34,7 +36,8 @@ fn weight_bytes_follow_the_original_tables() { #[test] fn eligibility_matches_the_name_and_type_rules() { - let yes = ["blk.0.attn_qkv.weight", "blk.3.ssm_out.weight", "blk.47.ffn_down_shexp.weight", "blk.9.attn_output.weight"]; + let yes = + ["blk.0.attn_qkv.weight", "blk.3.ssm_out.weight", "blk.47.ffn_down_shexp.weight", "blk.9.attn_output.weight"]; for n in yes { assert!(eligible(&row(n, 12, &[256, 2], 0), false), "{n}"); } @@ -47,7 +50,12 @@ fn eligibility_matches_the_name_and_type_rules() { } assert!(!eligible(&row("blk.1.ple_key.weight", 12, &[256, 2], 0), true)); // names only - let s = shard(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256], 8000), row("blk.1.ple_key.weight", 23, &[256, 2], 16000), row("blk.2.attn_k.weight", 1, &[4, 2], 20000)]); + let s = shard(vec![ + row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), + row("blk.0.attn_q.weight", 12, &[256], 8000), + row("blk.1.ple_key.weight", 23, &[256, 2], 16000), + row("blk.2.attn_k.weight", 1, &[4, 2], 20000), + ]); assert_eq!(served_names(&[s.clone()], false).into_iter().collect::>(), vec!["blk.0.attn_qkv.weight"]); assert_eq!(served_names(&[s], true).len(), 2); let mut skip = BTreeSet::from(["blk.1.ple_key.weight".to_string(), "x".to_string()]); @@ -59,18 +67,34 @@ fn eligibility_matches_the_name_and_type_rules() { #[test] fn a_valid_two_shard_model_produces_the_upload_plan() { - let mut first = shard(vec![row("blk.0.attn_qkv.weight", 12, &[2560, 1024], 0), row("blk.0.attn_norm.weight", 0, &[2560], 2_000_000)]); + let mut first = shard(vec![ + row("blk.0.attn_qkv.weight", 12, &[2560, 1024], 0), + row("blk.0.attn_norm.weight", 0, &[2560], 2_000_000), + ]); first.split_count = Some(2); first.split_no = Some(0); first.split_tensors = Some(4); - let mut second = ShardInfo { has_architecture: false, data_start: 500, file_size: 900_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(4), ..Default::default() }; + let mut second = ShardInfo { + has_architecture: false, + data_start: 500, + file_size: 900_000, + split_count: Some(2), + split_no: Some(1), + split_tensors: Some(4), + ..Default::default() + }; second.tensors = vec![row("blk.3.ssm_out.weight", 8, &[640, 512], 0)]; first.file_size = 5_000_000; - let plan = plan_load(&[first, second], &|name| match name { - "blk.0.attn_qkv.weight" => Some(canon(2560, 1024)), - "blk.3.ssm_out.weight" => Some(canon(640, 512)), - _ => None, - }, false).unwrap(); + let plan = plan_load( + &[first, second], + &|name| match name { + "blk.0.attn_qkv.weight" => Some(canon(2560, 1024)), + "blk.3.ssm_out.weight" => Some(canon(640, 512)), + _ => None, + }, + false, + ) + .unwrap(); assert_eq!(plan.items.len(), 2); assert_eq!(plan.items[0].bytes, 2560 / 256 * 144 * 1024); assert_eq!(plan.items[0].file_offset, 1000); @@ -99,31 +123,90 @@ fn refusals_carry_the_original_messages() { first.split_no = Some(0); first.split_tensors = Some(2); let extra = ShardInfo { has_architecture: false, data_start: 0, file_size: 100_000, ..Default::default() }; - assert_eq!(plan_load(&[first.clone(), extra], &c, false).unwrap_err(), "native dense: additional shard must match the architecture-validated first shard's split metadata"); + assert_eq!( + plan_load(&[first.clone(), extra], &c, false).unwrap_err(), + "native dense: additional shard must match the architecture-validated first shard's split metadata" + ); let dup = ShardInfo { split_count: Some(2), split_no: Some(0), split_tensors: Some(2), ..Default::default() }; assert!(plan_load(&[first.clone(), dup], &c, false).unwrap_err().contains("additional shard must match")); let mut again = first.clone(); again.tensors = vec![row("blk.9.attn_qkv.weight", 12, &[256, 4], 0)]; - assert_eq!(plan_load(&[first.clone(), again], &c, false).unwrap_err(), "native dense: duplicate split shard number"); + assert_eq!( + plan_load(&[first.clone(), again], &c, false).unwrap_err(), + "native dense: duplicate split shard number" + ); // payload offsets / geometry / truncation / overlap - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256, 4], 0)])], &c, false).unwrap_err(), "native dense: tensor payload offsets overlap"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[250, 4], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[], 0)])], &c, false).unwrap_err(), "native dense: invalid block geometry blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 0], 0)])], &c, false).unwrap_err(), "native dense: invalid tensor extent blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 999_900)])], &c, false).unwrap_err(), "native dense: truncated payload blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_norm.weight", 0, &[8], 100)])], &c, false).unwrap_err(), "native dense: overlapping payload blk.0.attn_qkv.weight"); + assert_eq!( + plan_load( + &[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_q.weight", 12, &[256, 4], 0)])], + &c, + false + ) + .unwrap_err(), + "native dense: tensor payload offsets overlap" + ); + assert_eq!( + plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[250, 4], 0)])], &c, false).unwrap_err(), + "native dense: invalid block geometry blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[], 0)])], &c, false).unwrap_err(), + "native dense: invalid block geometry blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 0], 0)])], &c, false).unwrap_err(), + "native dense: invalid tensor extent blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 999_900)])], &c, false).unwrap_err(), + "native dense: truncated payload blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load( + &[ok(vec![row("blk.0.attn_qkv.weight", 12, &[256, 4], 0), row("blk.0.attn_norm.weight", 0, &[8], 100)])], + &c, + false + ) + .unwrap_err(), + "native dense: overlapping payload blk.0.attn_qkv.weight" + ); // the unsupported/overlapping non-eligible tensor still blocks the model (checked before upload) // canonical-table problems - assert_eq!(plan_load(&[ok(one())], &|_| None, false).unwrap_err(), "native dense: tensor absent from canonical table: blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(one())], &all(Canonical { native_attached: true, ..good }), false).unwrap_err(), "native dense: override already attached"); - assert_eq!(plan_load(&[ok(one())], &all(Canonical { quantized: false, ..good }), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); - assert_eq!(plan_load(&[ok(one())], &all(canon(256, 5)), false).unwrap_err(), "native dense: incompatible matrix blk.0.attn_qkv.weight"); + assert_eq!( + plan_load(&[ok(one())], &|_| None, false).unwrap_err(), + "native dense: tensor absent from canonical table: blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load(&[ok(one())], &all(Canonical { native_attached: true, ..good }), false).unwrap_err(), + "native dense: override already attached" + ); + assert_eq!( + plan_load(&[ok(one())], &all(Canonical { quantized: false, ..good }), false).unwrap_err(), + "native dense: incompatible matrix blk.0.attn_qkv.weight" + ); + assert_eq!( + plan_load(&[ok(one())], &all(canon(256, 5)), false).unwrap_err(), + "native dense: incompatible matrix blk.0.attn_qkv.weight" + ); // unsupported type keeps the canonical path and nothing is left to upload - assert_eq!(plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 1, &[8, 4], 0)])], &c, false).unwrap_err(), "native dense: no supported GDN/QSA matrices in supplied shards"); + assert_eq!( + plan_load(&[ok(vec![row("blk.0.attn_qkv.weight", 1, &[8, 4], 0)])], &c, false).unwrap_err(), + "native dense: no supported GDN/QSA matrices in supplied shards" + ); // a duplicate eligible name across shards (the second declared as shard 1 of 2) let mut a = ok(one()); - a.split_count = Some(2); a.split_no = Some(0); a.split_tensors = Some(2); - let b = ShardInfo { data_start: 0, file_size: 100_000, split_count: Some(2), split_no: Some(1), split_tensors: Some(2), tensors: one(), ..Default::default() }; + a.split_count = Some(2); + a.split_no = Some(0); + a.split_tensors = Some(2); + let b = ShardInfo { + data_start: 0, + file_size: 100_000, + split_count: Some(2), + split_no: Some(1), + split_tensors: Some(2), + tensors: one(), + ..Default::default() + }; assert_eq!(plan_load(&[a, b], &c, false).unwrap_err(), "native dense: duplicate tensor blk.0.attn_qkv.weight"); } @@ -131,7 +214,9 @@ fn refusals_carry_the_original_messages() { fn an_unquantized_ple_key_is_skipped_not_refused() { let ple = row("blk.1.ple_key.weight", 23, &[256, 4], 0); let q = row("blk.0.attn_q.weight", 12, &[256, 4], 50_000); - let canonical = |name: &str| Some(Canonical { quantized: name != "blk.1.ple_key.weight", ne0: 256, ne1: 4, native_attached: false }); + let canonical = |name: &str| { + Some(Canonical { quantized: name != "blk.1.ple_key.weight", ne0: 256, ne1: 4, native_attached: false }) + }; let plan = plan_load(&[shard(vec![ple, q])], &canonical, true).unwrap(); assert_eq!(plan.items.len(), 1); assert_eq!(plan.items[0].name, "blk.0.attn_q.weight"); diff --git a/crates/model-format/src/pinned_arena_plan.rs b/crates/model-format/src/pinned_arena_plan.rs index 9cb2b146..0d914814 100644 --- a/crates/model-format/src/pinned_arena_plan.rs +++ b/crates/model-format/src/pinned_arena_plan.rs @@ -13,9 +13,6 @@ use std::fmt::Write as _; /// Seed constant exactly as written in pinned.cu (`1469598103934665603`, one digit short of the textbook FNV offset). pub const FNV_SEED: u64 = 1_469_598_103_934_665_603; const FNV_PRIME: u64 = 1_099_511_628_211; -pub fn fnv1a64(bytes: &[u8], seed: u64) -> u64 { - bytes.iter().fold(seed, |h, b| (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME)) -} // -------------------------------------------------------------------------------- shared arena file @@ -33,32 +30,6 @@ pub struct SharedArenaHeader { pub pack_hash: u64, } pub const SHARED_ARENA_HEADER_STRUCT_BYTES: usize = 72; -impl SharedArenaHeader { - pub fn new(arena_bytes: u64, pack_hash: u64) -> Self { - Self { magic: SHARED_ARENA_MAGIC, version: 1, header_bytes: SHARED_ARENA_HEADER_BYTES as u32, arena_bytes, pack_hash } - } - pub fn encode(&self) -> [u8; SHARED_ARENA_HEADER_STRUCT_BYTES] { - let mut out = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; - out[0..16].copy_from_slice(&self.magic); - out[16..20].copy_from_slice(&self.version.to_le_bytes()); - out[20..24].copy_from_slice(&self.header_bytes.to_le_bytes()); - out[24..32].copy_from_slice(&self.arena_bytes.to_le_bytes()); - out[32..40].copy_from_slice(&self.pack_hash.to_le_bytes()); - out - } - pub fn decode(bytes: &[u8]) -> Option { - if bytes.len() < SHARED_ARENA_HEADER_STRUCT_BYTES { - return None; - } - Some(Self { - magic: bytes[0..16].try_into().ok()?, - version: u32::from_le_bytes(bytes[16..20].try_into().ok()?), - header_bytes: u32::from_le_bytes(bytes[20..24].try_into().ok()?), - arena_bytes: u64::from_le_bytes(bytes[24..32].try_into().ok()?), - pack_hash: u64::from_le_bytes(bytes[32..40].try_into().ok()?), - }) - } -} /// What `reserve()` does with the shared file for the current open state. #[derive(Clone, Debug, PartialEq, Eq)] @@ -69,114 +40,6 @@ pub enum SharedFileAction { Reuse { file_bytes: u64 }, } pub const SHARED_NOTE_MAPPED: &str = "pack hash checked"; -/// The admission order of `reserve`: nonzero hash, header-size overflow, then fresh/existing-file checks. `existing` is -/// `None` for a file that does not exist yet, else its `(st_size, first header bytes)`. -pub fn plan_shared_file(path: &str, bytes: u64, pack_hash: u64, existing: Option<(u64, &[u8])>) -> Result { - if pack_hash == 0 { - return Err("shared arena requires a nonzero pack hash".into()); - } - let file_bytes = SHARED_ARENA_HEADER_BYTES.checked_add(bytes).ok_or("shared arena size overflows its header")?; - let fresh = existing.is_none_or(|(size, _)| size == 0); - if fresh { - return Ok(SharedFileAction::Create { file_bytes, header: SharedArenaHeader::new(bytes, pack_hash) }); - } - let (size, head) = existing.expect("non-fresh has a state"); - if size != file_bytes { - return Err(format!("shared arena {path} is {size} B, expected {file_bytes} B including its header")); - } - let header = SharedArenaHeader::decode(head); - match header { - Some(h) if h.magic == SHARED_ARENA_MAGIC && h.version == 1 && u64::from(h.header_bytes) == SHARED_ARENA_HEADER_BYTES && h.arena_bytes == bytes => { - if h.pack_hash != pack_hash { - return Err(format!("shared arena {path} was written for pack hash {:016x}, expected {:016x}", h.pack_hash, pack_hash)); - } - Ok(SharedFileAction::Reuse { file_bytes }) - } - _ => Err(format!("shared arena {path} has an incompatible or missing header")), - } -} -/// The arena note of a successful shared mapping: `MAP_SHARED file (pack hash checked)`. -pub fn shared_mapping_note(path: &str) -> String { - format!("MAP_SHARED file {path} ({SHARED_NOTE_MAPPED})") -} - -/// Open or create the shared arena file and run [`plan_shared_file`] over its real state; creating writes the header. -/// Returns the open file (the caller maps `file_bytes` from offset 0, the arena starts `SHARED_ARENA_HEADER_BYTES` in). -#[cfg(unix)] -pub fn open_shared_arena_file(path: &std::path::Path, bytes: u64, pack_hash: u64) -> Result<(std::fs::File, SharedFileAction), String> { - use std::os::unix::fs::{FileExt, OpenOptionsExt}; - let shown = path.display().to_string(); - if pack_hash == 0 { - return Err("shared arena requires a nonzero pack hash".into()); - } - if bytes > u64::MAX - SHARED_ARENA_HEADER_BYTES { - return Err("shared arena size overflows its header".into()); - } - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .open(path) - .map_err(|e| format!("cannot open shared arena {shown}: {e}"))?; - let size = file.metadata().map_err(|e| format!("cannot stat shared arena {shown}: {e}"))?.len(); - let mut head = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; - let have_head = if size == 0 { - false - } else { - file.read_exact_at(&mut head, 0).is_ok() - }; - let plan = plan_shared_file(&shown, bytes, pack_hash, Some((size, if have_head { &head[..] } else { &[] })))?; - if let SharedFileAction::Create { file_bytes, header } = &plan { - file.set_len(*file_bytes).map_err(|e| format!("cannot size shared arena {shown}: {e}"))?; - file.write_all_at(&header.encode(), 0).map_err(|e| format!("cannot write shared arena header {shown}: {e}"))?; - } - Ok((file, plan)) -} - -// -------------------------------------------------------------------------------- registration plan - -/// `STRATA_ARENA_PIN_GIB`: -1 unset/invalid (the engine decides), 0 no cap, N > 0 GiB, -2 "auto". -pub fn arena_pin_cap_gib(value: Option<&str>) -> i32 { - match value { - None | Some("") => -1, - Some("auto") => -2, - Some(v) => { - let n = atoi(v); - if n < 0 { -1 } else { n } - } - } -} -fn atoi(s: &str) -> i32 { - let t = s.trim_start(); - let (neg, t) = match t.as_bytes().first() { - Some(b'-') => (true, &t[1..]), - Some(b'+') => (false, &t[1..]), - _ => (false, t), - }; - let mut n: i64 = 0; - for c in t.bytes().take_while(u8::is_ascii_digit) { - n = (n * 10 + i64::from(c - b'0')).min(i64::from(i32::MAX)); - } - (if neg { -n } else { n }) as i32 -} -/// `uniform_bounds(bytes, slice)`: slice start offsets followed by the end of the last slice; empty for `slice == 0`. -pub fn uniform_bounds(bytes: u64, slice: u64) -> Vec { - let mut b = Vec::new(); - if slice == 0 { - return b; - } - let mut off = 0; - while off + slice <= bytes { - b.push(off); - off += slice; - } - if let Some(&last) = b.last() { - b.push(last + slice); - } - b -} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PinMode { @@ -193,63 +56,12 @@ pub struct PinDecision { pub cap_why: &'static str, pub capped: bool, } -/// The start of the registration branch: `max_pinned_bytes` from the caller wins, else `STRATA_ARENA_PIN_GIB=N`; -/// capped only when `cap > 0 && cap < bytes && bounds.len() >= 2`. -pub fn decide_pin(bytes: u64, bounds_len: usize, max_pinned_bytes: u64, env_gib: i32) -> PinDecision { - let mut cap = max_pinned_bytes; - let mut cap_why = "by the engine (multi-GPU under WDDM, or remote experts)"; - if cap == 0 && env_gib > 0 { - cap = (env_gib as u64) << 30; - cap_why = "by STRATA_ARENA_PIN_GIB"; - } - PinDecision { cap, cap_why, capped: cap > 0 && cap < bytes && bounds_len >= 2 } -} #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct SlicedPin { pub slice_starts: Vec, pub registered_bytes: u64, pub registered_slices: u32, } -/// The slice loop: register `[bounds[i], bounds[i+1])` in order until the limit (`limited`: `off > limit || n > limit - -/// off` stops) or the first refusal. `register(offset, length)` is `cudaHostRegister(base + offset, length)`. -pub fn pin_sliced(bounds: &[u64], limit: Option, mut register: impl FnMut(u64, u64) -> bool) -> SlicedPin { - let mut out = SlicedPin::default(); - for w in bounds.windows(2) { - let (off, n) = (w[0], w[1] - w[0]); - if limit.is_some_and(|limit| off > limit || n > limit - off) { - break; - } - if !register(off, n) { - break; - } - out.slice_starts.push(off); - out.registered_bytes = off + n; - out.registered_slices += 1; - } - out -} -/// The note the constructor builds after a sliced registration (`snprintf("%.1f")` of the limit in GiB included). -pub fn sliced_note(decision: &PinDecision, refusal: &str, limited: bool, limit: u64, limit_why: &str, pinned: &SlicedPin, previous_note: &str) -> String { - let mut note = String::new(); - if decision.capped { - let _ = write!(note, "cudaHostRegister limited to {} GiB {}; ", decision.cap >> 30, decision.cap_why); - } else { - let _ = write!(note, "cudaHostRegister of the whole arena FAILED ({refusal}); "); - if limited { - let _ = write!( - note, - "slices capped at {:.1} GiB ({limit_why}; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); ", - limit as f64 / (1u64 << 30) as f64 - ); - } - } - let _ = write!(note, "{} slices pinned ({} GiB); {previous_note}", pinned.registered_slices, pinned.registered_bytes >> 30); - note -} -/// Whether `STRATA_ARENA_LOCK=0` disables the working-set lock of the unpinned remainder. -pub fn arena_lock_enabled(value: Option<&str>) -> bool { - value != Some("0") -} // -------------------------------------------------------------------------------- parallel expert load @@ -264,135 +76,41 @@ pub struct LoadStats { pub layers: u64, pub layer_checksums: Vec, } -impl LoadStats { - pub fn gib_per_second(&self) -> f64 { - if self.seconds > 0.0 { self.bytes as f64 / (1024.0 * 1024.0 * 1024.0) / self.seconds } else { 0.0 } - } - pub fn read_gib_per_second(&self, threads: usize) -> f64 { - if self.read_seconds <= 0.0 || threads < 1 { - return 0.0; - } - self.bytes as f64 / (1024.0 * 1024.0 * 1024.0) / (self.read_seconds / threads as f64) - } -} - -/// `load_experts`: `layers` uniform ranges of `blobs_per_layer * blob_bytes`. -#[cfg(unix)] -pub fn load_experts(path: &std::path::Path, dst: &mut [u8], blob_bytes: u64, blobs_per_layer: u64, layers: u64, threads: usize, chunk: u64) -> LoadStats { - let n = (blobs_per_layer * blob_bytes) as u64; - let off: Vec = (0..layers).map(|l| l * blobs_per_layer * blob_bytes).collect(); - load_experts_ranges(path, dst, &off, &vec![n; layers as usize], threads, chunk) -} -/// `load_experts_ranges`: reads layer `L` (`layer_bytes[L]` bytes at file offset `layer_off[L]`) into `dst[layer_off[L]..]` -/// with `threads` workers, `chunk` bytes per read, and returns one FNV-1a per layer. A short read is an error, never a -/// zero fill. -#[cfg(unix)] -pub fn load_experts_ranges(path: &std::path::Path, dst: &mut [u8], layer_off: &[u64], layer_bytes: &[u64], threads: usize, chunk: u64) -> LoadStats { - use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; - use std::sync::Mutex; - use std::time::Instant; - let mut st = LoadStats { ok: true, layers: layer_off.len() as u64, bytes: layer_bytes.iter().sum(), ..Default::default() }; - let threads = threads.max(1); - let t0 = Instant::now(); - let fail = |mut st: LoadStats, message: String| { - eprintln!("load_experts: {message}"); - st.seconds = -1.0; - st.ok = false; - st.error = message; - st - }; - if layer_off.len() != layer_bytes.len() || chunk == 0 { - return fail(st, "layer offset and size lists differ, or the chunk is empty".into()); - } - // carve disjoint destination windows (hardening: the Original trusts the ranges) - let mut order: Vec = (0..layer_off.len()).collect(); - order.sort_by_key(|&l| layer_off[l]); - let mut windows: Vec> = (0..layer_off.len()).map(|_| None).collect(); - let mut rest: &mut [u8] = dst; - let mut cursor = 0u64; - for &l in &order { - let (o, n) = (layer_off[l], layer_bytes[l]); - if o < cursor || o.checked_add(n).is_none_or(|e| e > cursor + rest.len() as u64) { - return fail(st, format!("layer {l}: range {o}+{n} overlaps another layer or leaves the destination")); - } - let skip = (o - cursor) as usize; - let (_, tail) = std::mem::take(&mut rest).split_at_mut(skip); - let (win, tail) = tail.split_at_mut(n as usize); - windows[l] = Some((o, win)); - rest = tail; - cursor = o + n; - } - let windows: Vec>> = windows.into_iter().map(Mutex::new).collect(); - let next = AtomicUsize::new(0); - let read_ns = AtomicU64::new(0); - let copy_ns = AtomicU64::new(0); - let error: Mutex> = Mutex::new(None); - let hashes: Vec = (0..layer_off.len()).map(|_| AtomicU64::new(FNV_SEED)).collect(); - std::thread::scope(|scope| { - for _ in 0..threads { - scope.spawn(|| { - let file = match std::fs::File::open(path) { - Ok(f) => f, - Err(_) => { - *error.lock().unwrap() = Some(format!("cannot open {}", path.display())); - return; - } - }; - let mut buf = vec![0u8; chunk as usize]; - let (mut read_local, mut copy_local) = (0u64, 0u64); - loop { - let l = next.fetch_add(1, Ordering::Relaxed); - if l >= windows.len() { - break; - } - let (off, window) = windows[l].lock().unwrap().take().expect("each layer is taken once"); - let mut pos = 0usize; - let mut h = FNV_SEED; - while pos < window.len() { - let n = (window.len() - pos).min(chunk as usize); - let t_read = Instant::now(); - let got = read_up_to(&file, &mut buf[..n], off + pos as u64); - read_local += t_read.elapsed().as_nanos() as u64; - if got != n { - *error.lock().unwrap() = Some(format!("short read in layer {l}: got {got} of {n} B at offset {}", off + pos as u64)); - return; - } - let t_copy = Instant::now(); - window[pos..pos + n].copy_from_slice(&buf[..n]); - h = fnv1a64(&buf[..n], h); - copy_local += t_copy.elapsed().as_nanos() as u64; - pos += n; - } - hashes[l].store(h, Ordering::Relaxed); - } - read_ns.fetch_add(read_local, Ordering::Relaxed); - copy_ns.fetch_add(copy_local, Ordering::Relaxed); - }); - } - }); - if let Some(message) = error.into_inner().unwrap() { - return fail(st, message); - } - st.read_seconds = read_ns.load(Ordering::Relaxed) as f64 / 1e9; - st.copy_seconds = copy_ns.load(Ordering::Relaxed) as f64 / 1e9; - st.layer_checksums = hashes.iter().map(|h| h.load(Ordering::Relaxed)).collect(); - st.seconds = t0.elapsed().as_secs_f64(); - st -} -#[cfg(unix)] -fn read_up_to(file: &std::fs::File, buf: &mut [u8], offset: u64) -> usize { - use std::os::unix::fs::FileExt; - let mut got = 0; - while got < buf.len() { - match file.read_at(&mut buf[got..], offset + got as u64) { - Ok(0) => break, - Ok(n) => got += n, - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(_) => break, - } - } - got -} #[cfg(test)] mod tests; + +mod fnv1a64_fn; +#[allow(unused_imports)] +pub use fnv1a64_fn::arena_lock_enabled; +#[allow(unused_imports)] +pub use fnv1a64_fn::arena_pin_cap_gib; +#[allow(unused_imports)] +use fnv1a64_fn::atoi; +#[allow(unused_imports)] +pub use fnv1a64_fn::decide_pin; +#[allow(unused_imports)] +pub use fnv1a64_fn::fnv1a64; +#[cfg(unix)] +#[allow(unused_imports)] +pub use fnv1a64_fn::open_shared_arena_file; +#[allow(unused_imports)] +pub use fnv1a64_fn::pin_sliced; +#[allow(unused_imports)] +pub use fnv1a64_fn::plan_shared_file; +#[allow(unused_imports)] +pub use fnv1a64_fn::shared_mapping_note; +#[allow(unused_imports)] +pub use fnv1a64_fn::sliced_note; +#[allow(unused_imports)] +pub use fnv1a64_fn::uniform_bounds; +mod load_experts_fn; +#[cfg(unix)] +#[allow(unused_imports)] +pub use load_experts_fn::load_experts; +#[cfg(unix)] +#[allow(unused_imports)] +pub use load_experts_fn::load_experts_ranges; +#[cfg(unix)] +#[allow(unused_imports)] +use load_experts_fn::read_up_to; diff --git a/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs new file mode 100644 index 00000000..aeb88ca5 --- /dev/null +++ b/crates/model-format/src/pinned_arena_plan/fnv1a64_fn.rs @@ -0,0 +1,236 @@ +//! Moved out of the parent module by STRA-338: fn fnv1a64, impl SharedArenaHeader, fn plan_shared_file, fn shared_mapping_note, fn open_shared_arena_file, fn arena_pin_cap_gib .... + +#[allow(unused_imports)] +use super::*; + +pub fn fnv1a64(bytes: &[u8], seed: u64) -> u64 { + bytes.iter().fold(seed, |h, b| (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME)) +} +impl SharedArenaHeader { + pub fn new(arena_bytes: u64, pack_hash: u64) -> Self { + Self { + magic: SHARED_ARENA_MAGIC, + version: 1, + header_bytes: SHARED_ARENA_HEADER_BYTES as u32, + arena_bytes, + pack_hash, + } + } + pub fn encode(&self) -> [u8; SHARED_ARENA_HEADER_STRUCT_BYTES] { + let mut out = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; + out[0..16].copy_from_slice(&self.magic); + out[16..20].copy_from_slice(&self.version.to_le_bytes()); + out[20..24].copy_from_slice(&self.header_bytes.to_le_bytes()); + out[24..32].copy_from_slice(&self.arena_bytes.to_le_bytes()); + out[32..40].copy_from_slice(&self.pack_hash.to_le_bytes()); + out + } + pub fn decode(bytes: &[u8]) -> Option { + if bytes.len() < SHARED_ARENA_HEADER_STRUCT_BYTES { + return None; + } + Some(Self { + magic: bytes[0..16].try_into().ok()?, + version: u32::from_le_bytes(bytes[16..20].try_into().ok()?), + header_bytes: u32::from_le_bytes(bytes[20..24].try_into().ok()?), + arena_bytes: u64::from_le_bytes(bytes[24..32].try_into().ok()?), + pack_hash: u64::from_le_bytes(bytes[32..40].try_into().ok()?), + }) + } +} +/// The admission order of `reserve`: nonzero hash, header-size overflow, then fresh/existing-file checks. `existing` is +/// `None` for a file that does not exist yet, else its `(st_size, first header bytes)`. +pub fn plan_shared_file( + path: &str, + bytes: u64, + pack_hash: u64, + existing: Option<(u64, &[u8])>, +) -> Result { + if pack_hash == 0 { + return Err("shared arena requires a nonzero pack hash".into()); + } + let file_bytes = SHARED_ARENA_HEADER_BYTES.checked_add(bytes).ok_or("shared arena size overflows its header")?; + let fresh = existing.is_none_or(|(size, _)| size == 0); + if fresh { + return Ok(SharedFileAction::Create { file_bytes, header: SharedArenaHeader::new(bytes, pack_hash) }); + } + let (size, head) = existing.expect("non-fresh has a state"); + if size != file_bytes { + return Err(format!("shared arena {path} is {size} B, expected {file_bytes} B including its header")); + } + let header = SharedArenaHeader::decode(head); + match header { + Some(h) + if h.magic == SHARED_ARENA_MAGIC + && h.version == 1 + && u64::from(h.header_bytes) == SHARED_ARENA_HEADER_BYTES + && h.arena_bytes == bytes => + { + if h.pack_hash != pack_hash { + return Err(format!( + "shared arena {path} was written for pack hash {:016x}, expected {:016x}", + h.pack_hash, pack_hash + )); + } + Ok(SharedFileAction::Reuse { file_bytes }) + } + _ => Err(format!("shared arena {path} has an incompatible or missing header")), + } +} +/// The arena note of a successful shared mapping: `MAP_SHARED file (pack hash checked)`. +pub fn shared_mapping_note(path: &str) -> String { + format!("MAP_SHARED file {path} ({SHARED_NOTE_MAPPED})") +} + +/// Open or create the shared arena file and run [`plan_shared_file`] over its real state; creating writes the header. +/// Returns the open file (the caller maps `file_bytes` from offset 0, the arena starts `SHARED_ARENA_HEADER_BYTES` in). +#[cfg(unix)] +pub fn open_shared_arena_file( + path: &std::path::Path, + bytes: u64, + pack_hash: u64, +) -> Result<(std::fs::File, SharedFileAction), String> { + use std::os::unix::fs::{FileExt, OpenOptionsExt}; + let shown = path.display().to_string(); + if pack_hash == 0 { + return Err("shared arena requires a nonzero pack hash".into()); + } + if bytes > u64::MAX - SHARED_ARENA_HEADER_BYTES { + return Err("shared arena size overflows its header".into()); + } + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .open(path) + .map_err(|e| format!("cannot open shared arena {shown}: {e}"))?; + let size = file.metadata().map_err(|e| format!("cannot stat shared arena {shown}: {e}"))?.len(); + let mut head = [0u8; SHARED_ARENA_HEADER_STRUCT_BYTES]; + let have_head = if size == 0 { false } else { file.read_exact_at(&mut head, 0).is_ok() }; + let plan = plan_shared_file(&shown, bytes, pack_hash, Some((size, if have_head { &head[..] } else { &[] })))?; + if let SharedFileAction::Create { file_bytes, header } = &plan { + file.set_len(*file_bytes).map_err(|e| format!("cannot size shared arena {shown}: {e}"))?; + file.write_all_at(&header.encode(), 0).map_err(|e| format!("cannot write shared arena header {shown}: {e}"))?; + } + Ok((file, plan)) +} + +// -------------------------------------------------------------------------------- registration plan + +/// `STRATA_ARENA_PIN_GIB`: -1 unset/invalid (the engine decides), 0 no cap, N > 0 GiB, -2 "auto". +pub fn arena_pin_cap_gib(value: Option<&str>) -> i32 { + match value { + None | Some("") => -1, + Some("auto") => -2, + Some(v) => { + let n = atoi(v); + if n < 0 { -1 } else { n } + } + } +} +pub(super) fn atoi(s: &str) -> i32 { + let t = s.trim_start(); + let (neg, t) = match t.as_bytes().first() { + Some(b'-') => (true, &t[1..]), + Some(b'+') => (false, &t[1..]), + _ => (false, t), + }; + let mut n: i64 = 0; + for c in t.bytes().take_while(u8::is_ascii_digit) { + n = (n * 10 + i64::from(c - b'0')).min(i64::from(i32::MAX)); + } + (if neg { -n } else { n }) as i32 +} +/// `uniform_bounds(bytes, slice)`: slice start offsets followed by the end of the last slice; empty for `slice == 0`. +pub fn uniform_bounds(bytes: u64, slice: u64) -> Vec { + let mut b = Vec::new(); + if slice == 0 { + return b; + } + let mut off = 0; + while off + slice <= bytes { + b.push(off); + off += slice; + } + if let Some(&last) = b.last() { + b.push(last + slice); + } + b +} +/// The start of the registration branch: `max_pinned_bytes` from the caller wins, else `STRATA_ARENA_PIN_GIB=N`; +/// capped only when `cap > 0 && cap < bytes && bounds.len() >= 2`. +pub fn decide_pin(bytes: u64, bounds_len: usize, max_pinned_bytes: u64, env_gib: i32) -> PinDecision { + let mut cap = max_pinned_bytes; + let mut cap_why = "by the engine (multi-GPU under WDDM, or remote experts)"; + if cap == 0 && env_gib > 0 { + cap = (env_gib as u64) << 30; + cap_why = "by STRATA_ARENA_PIN_GIB"; + } + PinDecision { cap, cap_why, capped: cap > 0 && cap < bytes && bounds_len >= 2 } +} +/// The slice loop: register `[bounds[i], bounds[i+1])` in order until the limit (`limited`: `off > limit || n > limit - +/// off` stops) or the first refusal. `register(offset, length)` is `cudaHostRegister(base + offset, length)`. +pub fn pin_sliced(bounds: &[u64], limit: Option, mut register: impl FnMut(u64, u64) -> bool) -> SlicedPin { + let mut out = SlicedPin::default(); + for w in bounds.windows(2) { + let (off, n) = (w[0], w[1] - w[0]); + if limit.is_some_and(|limit| off > limit || n > limit - off) { + break; + } + if !register(off, n) { + break; + } + out.slice_starts.push(off); + out.registered_bytes = off + n; + out.registered_slices += 1; + } + out +} +/// The note the constructor builds after a sliced registration (`snprintf("%.1f")` of the limit in GiB included). +pub fn sliced_note( + decision: &PinDecision, + refusal: &str, + limited: bool, + limit: u64, + limit_why: &str, + pinned: &SlicedPin, + previous_note: &str, +) -> String { + let mut note = String::new(); + if decision.capped { + let _ = write!(note, "cudaHostRegister limited to {} GiB {}; ", decision.cap >> 30, decision.cap_why); + } else { + let _ = write!(note, "cudaHostRegister of the whole arena FAILED ({refusal}); "); + if limited { + let _ = write!( + note, + "slices capped at {:.1} GiB ({limit_why}; STRATA_ARENA_PIN_GIB=auto; N sets a cap; #243); ", + limit as f64 / (1u64 << 30) as f64 + ); + } + } + let _ = write!( + note, + "{} slices pinned ({} GiB); {previous_note}", + pinned.registered_slices, + pinned.registered_bytes >> 30 + ); + note +} +/// Whether `STRATA_ARENA_LOCK=0` disables the working-set lock of the unpinned remainder. +pub fn arena_lock_enabled(value: Option<&str>) -> bool { + value != Some("0") +} +impl LoadStats { + pub fn gib_per_second(&self) -> f64 { + if self.seconds > 0.0 { self.bytes as f64 / (1024.0 * 1024.0 * 1024.0) / self.seconds } else { 0.0 } + } + pub fn read_gib_per_second(&self, threads: usize) -> f64 { + if self.read_seconds <= 0.0 || threads < 1 { + return 0.0; + } + self.bytes as f64 / (1024.0 * 1024.0 * 1024.0) / (self.read_seconds / threads as f64) + } +} diff --git a/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs new file mode 100644 index 00000000..8e4c058a --- /dev/null +++ b/crates/model-format/src/pinned_arena_plan/load_experts_fn.rs @@ -0,0 +1,141 @@ +//! Moved out of the parent module by STRA-338: fn load_experts, fn load_experts_ranges, fn read_up_to. + +#[allow(unused_imports)] +use super::*; + +/// `load_experts`: `layers` uniform ranges of `blobs_per_layer * blob_bytes`. +#[cfg(unix)] +pub fn load_experts( + path: &std::path::Path, + dst: &mut [u8], + blob_bytes: u64, + blobs_per_layer: u64, + layers: u64, + threads: usize, + chunk: u64, +) -> LoadStats { + let n = (blobs_per_layer * blob_bytes) as u64; + let off: Vec = (0..layers).map(|l| l * blobs_per_layer * blob_bytes).collect(); + load_experts_ranges(path, dst, &off, &vec![n; layers as usize], threads, chunk) +} +/// `load_experts_ranges`: reads layer `L` (`layer_bytes[L]` bytes at file offset `layer_off[L]`) into `dst[layer_off[L]..]` +/// with `threads` workers, `chunk` bytes per read, and returns one FNV-1a per layer. A short read is an error, never a +/// zero fill. +#[cfg(unix)] +pub fn load_experts_ranges( + path: &std::path::Path, + dst: &mut [u8], + layer_off: &[u64], + layer_bytes: &[u64], + threads: usize, + chunk: u64, +) -> LoadStats { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + use std::time::Instant; + let mut st = + LoadStats { ok: true, layers: layer_off.len() as u64, bytes: layer_bytes.iter().sum(), ..Default::default() }; + let threads = threads.max(1); + let t0 = Instant::now(); + let fail = |mut st: LoadStats, message: String| { + eprintln!("load_experts: {message}"); + st.seconds = -1.0; + st.ok = false; + st.error = message; + st + }; + if layer_off.len() != layer_bytes.len() || chunk == 0 { + return fail(st, "layer offset and size lists differ, or the chunk is empty".into()); + } + // carve disjoint destination windows (hardening: the Original trusts the ranges) + let mut order: Vec = (0..layer_off.len()).collect(); + order.sort_by_key(|&l| layer_off[l]); + let mut windows: Vec> = (0..layer_off.len()).map(|_| None).collect(); + let mut rest: &mut [u8] = dst; + let mut cursor = 0u64; + for &l in &order { + let (o, n) = (layer_off[l], layer_bytes[l]); + if o < cursor || o.checked_add(n).is_none_or(|e| e > cursor + rest.len() as u64) { + return fail(st, format!("layer {l}: range {o}+{n} overlaps another layer or leaves the destination")); + } + let skip = (o - cursor) as usize; + let (_, tail) = std::mem::take(&mut rest).split_at_mut(skip); + let (win, tail) = tail.split_at_mut(n as usize); + windows[l] = Some((o, win)); + rest = tail; + cursor = o + n; + } + let windows: Vec>> = windows.into_iter().map(Mutex::new).collect(); + let next = AtomicUsize::new(0); + let read_ns = AtomicU64::new(0); + let copy_ns = AtomicU64::new(0); + let error: Mutex> = Mutex::new(None); + let hashes: Vec = (0..layer_off.len()).map(|_| AtomicU64::new(FNV_SEED)).collect(); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + let file = match std::fs::File::open(path) { + Ok(f) => f, + Err(_) => { + *error.lock().unwrap() = Some(format!("cannot open {}", path.display())); + return; + } + }; + let mut buf = vec![0u8; chunk as usize]; + let (mut read_local, mut copy_local) = (0u64, 0u64); + loop { + let l = next.fetch_add(1, Ordering::Relaxed); + if l >= windows.len() { + break; + } + let (off, window) = windows[l].lock().unwrap().take().expect("each layer is taken once"); + let mut pos = 0usize; + let mut h = FNV_SEED; + while pos < window.len() { + let n = (window.len() - pos).min(chunk as usize); + let t_read = Instant::now(); + let got = read_up_to(&file, &mut buf[..n], off + pos as u64); + read_local += t_read.elapsed().as_nanos() as u64; + if got != n { + *error.lock().unwrap() = Some(format!( + "short read in layer {l}: got {got} of {n} B at offset {}", + off + pos as u64 + )); + return; + } + let t_copy = Instant::now(); + window[pos..pos + n].copy_from_slice(&buf[..n]); + h = fnv1a64(&buf[..n], h); + copy_local += t_copy.elapsed().as_nanos() as u64; + pos += n; + } + hashes[l].store(h, Ordering::Relaxed); + } + read_ns.fetch_add(read_local, Ordering::Relaxed); + copy_ns.fetch_add(copy_local, Ordering::Relaxed); + }); + } + }); + if let Some(message) = error.into_inner().unwrap() { + return fail(st, message); + } + st.read_seconds = read_ns.load(Ordering::Relaxed) as f64 / 1e9; + st.copy_seconds = copy_ns.load(Ordering::Relaxed) as f64 / 1e9; + st.layer_checksums = hashes.iter().map(|h| h.load(Ordering::Relaxed)).collect(); + st.seconds = t0.elapsed().as_secs_f64(); + st +} +#[cfg(unix)] +pub(super) fn read_up_to(file: &std::fs::File, buf: &mut [u8], offset: u64) -> usize { + use std::os::unix::fs::FileExt; + let mut got = 0; + while got < buf.len() { + match file.read_at(&mut buf[got..], offset + got as u64) { + Ok(0) => break, + Ok(n) => got += n, + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + } + got +} diff --git a/crates/model-format/src/pinned_arena_plan/tests.rs b/crates/model-format/src/pinned_arena_plan/tests.rs index f98f4696..89cb3ce2 100644 --- a/crates/model-format/src/pinned_arena_plan/tests.rs +++ b/crates/model-format/src/pinned_arena_plan/tests.rs @@ -28,15 +28,38 @@ fn header_layout_and_admission() { let p = "/dev/shm/x"; assert_eq!(plan_shared_file(p, 1 << 20, 0, None).unwrap_err(), "shared arena requires a nonzero pack hash"); assert_eq!(plan_shared_file(p, u64::MAX, 1, None).unwrap_err(), "shared arena size overflows its header"); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, None), Ok(SharedFileAction::Create { file_bytes: size, header: h })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((0, &[]))), Ok(SharedFileAction::Create { file_bytes: size, header: h })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e))), Ok(SharedFileAction::Reuse { file_bytes: size })); - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size + 1, &e))).unwrap_err(), format!("shared arena {p} is {} B, expected {size} B including its header", size + 1)); - assert_eq!(plan_shared_file(p, 1 << 20, 0xbeef, Some((size, &e))).unwrap_err(), format!("shared arena {p} was written for pack hash 000000000000feed, expected 000000000000beef")); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xfeed, None), + Ok(SharedFileAction::Create { file_bytes: size, header: h }) + ); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xfeed, Some((0, &[]))), + Ok(SharedFileAction::Create { file_bytes: size, header: h }) + ); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e))), + Ok(SharedFileAction::Reuse { file_bytes: size }) + ); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xfeed, Some((size + 1, &e))).unwrap_err(), + format!("shared arena {p} is {} B, expected {size} B including its header", size + 1) + ); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xbeef, Some((size, &e))).unwrap_err(), + format!("shared arena {p} was written for pack hash 000000000000feed, expected 000000000000beef") + ); let mut bad = e; bad[3] ^= 1; - assert_eq!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &bad))).unwrap_err(), format!("shared arena {p} has an incompatible or missing header")); - assert!(plan_shared_file(p, 1 << 21, 0xfeed, Some((SHARED_ARENA_HEADER_BYTES + (1 << 21), &e))).unwrap_err().contains("incompatible"), "arena_bytes mismatch"); + assert_eq!( + plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &bad))).unwrap_err(), + format!("shared arena {p} has an incompatible or missing header") + ); + assert!( + plan_shared_file(p, 1 << 21, 0xfeed, Some((SHARED_ARENA_HEADER_BYTES + (1 << 21), &e))) + .unwrap_err() + .contains("incompatible"), + "arena_bytes mismatch" + ); assert!(plan_shared_file(p, 1 << 20, 0xfeed, Some((size, &e[..10]))).unwrap_err().contains("incompatible")); assert_eq!(shared_mapping_note("/dev/shm/a"), "MAP_SHARED file /dev/shm/a (pack hash checked)"); } @@ -116,7 +139,12 @@ fn parallel_load_matches_a_serial_read_and_reports_the_layer_checksums() { let path = temp("experts"); // 5 layers of different sizes at uneven offsets, a gap between layers, random-ish bytes let mut x = 0x1234_5678_9abc_def0u64; - let file: Vec = (0..100_000).map(|_| { x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (x >> 56) as u8 }).collect(); + let file: Vec = (0..100_000) + .map(|_| { + x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (x >> 56) as u8 + }) + .collect(); std::fs::write(&path, &file).unwrap(); let off = [0u64, 7_001, 30_000, 31_000, 90_000]; let len = [7_000u64, 22_999, 1_000, 40_000, 9_999]; @@ -130,7 +158,11 @@ fn parallel_load_matches_a_serial_read_and_reports_the_layer_checksums() { for l in 0..5 { let r = off[l] as usize..(off[l] + len[l]) as usize; assert_eq!(&dst[r.clone()], &file[r.clone()], "layer {l}"); - assert_eq!(stats.layer_checksums[l], fnv1a64(&file[r], FNV_SEED), "layer {l} checksum (chunking must not change it)"); + assert_eq!( + stats.layer_checksums[l], + fnv1a64(&file[r], FNV_SEED), + "layer {l} checksum (chunking must not change it)" + ); } assert!(dst[7_000..7_001].iter().all(|b| *b == 0xee), "bytes between layers stay untouched"); } diff --git a/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs b/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs index 64f70ced..ea24274b 100644 --- a/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs +++ b/crates/model-format/src/ple_reader/impl_fmt_debug_for.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl fmt::Debug for PleReader { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PleReader") diff --git a/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs index 4b1d6cb8..eadfc008 100644 --- a/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs +++ b/crates/model-format/src/ple_reader/impl_pagesource_for_file.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl PageSource for File { fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result { #[cfg(unix)] @@ -17,10 +16,7 @@ impl PageSource for File { #[cfg(not(any(unix, windows)))] { let _ = (buf, offset); - Err(io::Error::new( - io::ErrorKind::Unsupported, - "positional reads unavailable", - )) + Err(io::Error::new(io::ErrorKind::Unsupported, "positional reads unavailable")) } } @@ -102,12 +98,10 @@ impl RowCache { return None; } let s = (Self::mix(row) % self.sets) as usize; - (0..WAYS) - .find(|&w| self.keys[s * WAYS + w] == row) - .map(|w| { - let at = (s * WAYS + w) * self.rb; - &self.data[at..at + self.rb] - }) + (0..WAYS).find(|&w| self.keys[s * WAYS + w] == row).map(|w| { + let at = (s * WAYS + w) * self.rb; + &self.data[at..at + self.rb] + }) } pub fn insert(&mut self, row: u32, bytes: &[u8]) { @@ -156,22 +150,14 @@ pub fn plan_reads( let at = cfg.table_offset + u64::from(row) * rb as u64; let first = at / PAGE as u64 * PAGE as u64; let length = ((at + rb as u64 - 1) / PAGE as u64 * PAGE as u64 - first) as usize + PAGE; - let used = Use { - row, - in_page: (at - first) as usize, - slot: i, - }; + let used = Use { row, in_page: (at - first) as usize, slot: i }; if let Some(&j) = by_page.get(&first) { jobs[j].length = jobs[j].length.max(length); jobs[j].uses.push(used); stats.dedup_rows += 1; } else { by_page.insert(first, jobs.len()); - jobs.push(PlannedRead { - offset: first, - length, - uses: vec![used], - }); + jobs.push(PlannedRead { offset: first, length, uses: vec![used] }); } } // Sorted by offset: prefill chunks then read the SSD in near-sequential order. diff --git a/crates/model-format/src/ple_reader/impl_plereader.rs b/crates/model-format/src/ple_reader/impl_plereader.rs index aa435509..dc04f15d 100644 --- a/crates/model-format/src/ple_reader/impl_plereader.rs +++ b/crates/model-format/src/ple_reader/impl_plereader.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl PleReader { /// `source` is the table's file. The table must fit exactly in it from /// `table_offset` (the caller's GGUF parse checks that; the length is @@ -18,13 +17,9 @@ impl PleReader { if cfg.n_rows > u64::from(EMPTY) { return err("the row count exceeds the 32-bit row index"); } - let table_end = cfg - .n_rows - .checked_mul(cfg.row_bytes as u64) - .and_then(|bytes| bytes.checked_add(cfg.table_offset)); - let len = source - .len() - .map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; + let table_end = + cfg.n_rows.checked_mul(cfg.row_bytes as u64).and_then(|bytes| bytes.checked_add(cfg.table_offset)); + let len = source.len().map_err(|e| PleError(format!("PleReader: cannot size the table file ({e})")))?; if table_end.is_none_or(|end| end > len) { return err("the table extends past the end of the file"); } @@ -36,9 +31,7 @@ impl PleReader { Some(n) => n.min(cfg.max_inflight), }; let seed = 0x9E37_79B9_7F4A_7C15 - ^ std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(1, |d| d.as_micros() as u64); + ^ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(1, |d| d.as_micros() as u64); let state = State { queue: VecDeque::new(), tickets: HashMap::new(), @@ -50,10 +43,7 @@ impl PleReader { error: None, stop: false, inflight: 0, - keep: KeepAlive { - rng: if seed == 0 { 1 } else { seed }, - ..KeepAlive::default() - }, + keep: KeepAlive { rng: if seed == 0 { 1 } else { seed }, ..KeepAlive::default() }, }; let shared = Arc::new(Shared { source, @@ -64,16 +54,10 @@ impl PleReader { done: Condvar::new(), keep_cv: Condvar::new(), }); - let mut reader = Self { - shared: Arc::clone(&shared), - workers: Vec::new(), - keepalive: None, - }; + let mut reader = Self { shared: Arc::clone(&shared), workers: Vec::new(), keepalive: None }; for index in 0..threads { let worker = Arc::clone(&shared); - let spawned = thread::Builder::new() - .name(format!("ple-reader-{index}")) - .spawn(move || worker.worker()); + let spawned = thread::Builder::new().name(format!("ple-reader-{index}")).spawn(move || worker.worker()); match spawned { Ok(handle) => reader.workers.push(handle), Err(e) => return err(format!("cannot create I/O worker: {e}")), @@ -100,10 +84,7 @@ impl PleReader { st.next_ticket = st.next_ticket.wrapping_add(1).max(1); let now = Instant::now(); let rearm = !st.keep.period.is_zero() - && st - .keep - .last_issue - .is_none_or(|last| now.duration_since(last) > st.keep.window); + && st.keep.last_issue.is_none_or(|last| now.duration_since(last) > st.keep.window); st.keep.last_issue = Some(now); let mut out = vec![0u8; rows.len() * rb]; let State { cache, stats, .. } = &mut *st; @@ -113,11 +94,7 @@ impl PleReader { pending = 0; // the reader failed: `collect` reports it, nothing is queued } else { for read in reads { - st.queue.push_back(Job { - read, - ticket: id, - keepalive: false, - }); + st.queue.push_back(Job { read, ticket: id, keepalive: false }); } } st.tickets.insert(id, TicketState { pending, out }); @@ -128,10 +105,7 @@ impl PleReader { if rearm || pending > 0 { shared.keep_cv.notify_all(); } - Ticket { - id, - shared: Arc::clone(shared), - } + Ticket { id, shared: Arc::clone(shared) } } /// Block until every row of the ticket is in the returned buffer. @@ -174,10 +148,7 @@ impl PleReader { _ => { let mut st = lock(&shared.state); st.fail("the table file changed size after verification"); - return Err(st - .error - .clone() - .unwrap_or_else(|| PleError("PleReader: size check failed".into()))); + return Err(st.error.clone().unwrap_or_else(|| PleError("PleReader: size check failed".into()))); } } } @@ -202,9 +173,8 @@ impl PleReader { } if threaded && !period.is_zero() && self.keepalive.is_none() { let worker = Arc::clone(&self.shared); - if let Ok(handle) = thread::Builder::new() - .name("ple-reader-keepalive".into()) - .spawn(move || worker.keepalive_worker()) + if let Ok(handle) = + thread::Builder::new().name("ple-reader-keepalive".into()).spawn(move || worker.keepalive_worker()) { self.keepalive = Some(handle); } diff --git a/crates/model-format/src/ple_reader/impl_state.rs b/crates/model-format/src/ple_reader/impl_state.rs index 7caca794..6394da43 100644 --- a/crates/model-format/src/ple_reader/impl_state.rs +++ b/crates/model-format/src/ple_reader/impl_state.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl State { pub(super) fn record_latency(&mut self, us: f64) { self.stats.read_us_sum += us; @@ -162,21 +161,10 @@ impl Shared { st.keep.rng ^= st.keep.rng >> 7; st.keep.rng ^= st.keep.rng << 17; let first = self.cfg.table_offset / PAGE as u64; - let end = (self.cfg.table_offset - + self.cfg.n_rows * self.cfg.row_bytes as u64) - / PAGE as u64; - let page = first - + if end > first { - st.keep.rng % (end - first) - } else { - 0 - }; + let end = (self.cfg.table_offset + self.cfg.n_rows * self.cfg.row_bytes as u64) / PAGE as u64; + let page = first + if end > first { st.keep.rng % (end - first) } else { 0 }; st.queue.push_back(Job { - read: PlannedRead { - offset: page * PAGE as u64, - length: PAGE, - uses: Vec::new(), - }, + read: PlannedRead { offset: page * PAGE as u64, length: PAGE, uses: Vec::new() }, ticket: 0, keepalive: true, }); @@ -184,19 +172,11 @@ impl Shared { } // Re-evaluate after the period (or when woken). let wait = st.keep.period.max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; + st = self.keep_cv.wait_timeout(st, wait).unwrap_or_else(|p| p.into_inner()).0; } Some(due) => { let wait = (due - now).max(Duration::from_millis(1)); - st = self - .keep_cv - .wait_timeout(st, wait) - .unwrap_or_else(|p| p.into_inner()) - .0; + st = self.keep_cv.wait_timeout(st, wait).unwrap_or_else(|p| p.into_inner()).0; } } } diff --git a/crates/model-format/src/ple_reader/tests.rs b/crates/model-format/src/ple_reader/tests.rs index 9f0d1dea..1d215f76 100644 --- a/crates/model-format/src/ple_reader/tests.rs +++ b/crates/model-format/src/ple_reader/tests.rs @@ -48,11 +48,7 @@ fn table(offset: usize, rows: usize, rb: usize) -> Vec { let mut v = vec![0xEEu8; offset]; for r in 0..rows { for k in 0..rb { - v.push( - (r.wrapping_mul(31) - .wrapping_add(k.wrapping_mul(7)) - .wrapping_add(r >> 8)) as u8, - ); + v.push((r.wrapping_mul(31).wrapping_add(k.wrapping_mul(7)).wrapping_add(r >> 8)) as u8); } } v @@ -132,9 +128,9 @@ fn flaky_reader(threads: Option, panic: bool) -> Arc { Arc::new(PleReader::open(source, c).unwrap()) } -#[path = "tests/rows_match_the_oracle_including.rs"] -mod rows_match_the_oracle_including; #[path = "tests/max_inflight_bounds_concurrent_reads.rs"] mod max_inflight_bounds_concurrent_reads; #[path = "tests/prefetched_keys_are_matched.rs"] mod prefetched_keys_are_matched; +#[path = "tests/rows_match_the_oracle_including.rs"] +mod rows_match_the_oracle_including; diff --git a/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs b/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs index b9ae4c73..8345655f 100644 --- a/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs +++ b/crates/model-format/src/ple_reader/tests/max_inflight_bounds_concurrent_reads.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn max_inflight_bounds_concurrent_reads() { struct Gauge { @@ -26,17 +25,11 @@ fn max_inflight_bounds_concurrent_reads() { } let mut c = cfg(0, 20_000); c.max_inflight = 4; - let gauge = Arc::new(Gauge { - inner: Mem::new(table(0, 20_000, 90)), - now: AtomicU64::new(0), - peak: AtomicU64::new(0), - }); + let gauge = + Arc::new(Gauge { inner: Mem::new(table(0, 20_000, 90)), now: AtomicU64::new(0), peak: AtomicU64::new(0) }); let reader = PleReader::open(gauge.clone(), c.clone()).unwrap(); let rows: Vec = (0..200).map(|i| i * 90).collect(); - assert_eq!( - reader.read_rows(&rows).unwrap(), - oracle(&gauge.inner.bytes, &c, &rows) - ); + assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&gauge.inner.bytes, &c, &rows)); let peak = gauge.peak.load(Ordering::SeqCst); assert!((1..=4).contains(&peak), "peak {peak}"); } @@ -52,26 +45,13 @@ fn keepalive_reads_a_table_page_when_idle_and_stops_after_the_window() { thread::sleep(Duration::from_millis(80)); let s = reader.snapshot(); assert!(s.keepalive_reads >= 3, "{}", s.keepalive_reads); - assert_eq!( - (s.reads, s.bytes, s.read_us.len()), - (base.reads, base.bytes, base.read_us.len()) - ); + assert_eq!((s.reads, s.bytes, s.read_us.len()), (base.reads, base.bytes, base.read_us.len())); let end = (c.table_offset + c.n_rows * 90) / PAGE as u64 * PAGE as u64 + PAGE as u64; - assert!( - src.log - .lock() - .unwrap() - .iter() - .all(|&(o, _)| o >= 8192 / PAGE as u64 * PAGE as u64 && o < end) - ); + assert!(src.log.lock().unwrap().iter().all(|&(o, _)| o >= 8192 / PAGE as u64 * PAGE as u64 && o < end)); thread::sleep(Duration::from_millis(200)); let settled = reader.snapshot().keepalive_reads; thread::sleep(Duration::from_millis(60)); - assert_eq!( - reader.snapshot().keepalive_reads, - settled, - "stopped after the window" - ); + assert_eq!(reader.snapshot().keepalive_reads, settled, "stopped after the window"); reader.read_rows(&[2]).unwrap(); // re-arms thread::sleep(Duration::from_millis(60)); assert!(reader.snapshot().keepalive_reads > settled); @@ -87,10 +67,7 @@ fn a_failing_keepalive_turns_itself_off_not_the_reader() { src.fail.store(true, Ordering::SeqCst); thread::sleep(Duration::from_millis(60)); src.fail.store(false, Ordering::SeqCst); - assert_eq!( - reader.read_rows(&[2000]).unwrap(), - oracle(&src.bytes, &c, &[2000]) - ); + assert_eq!(reader.read_rows(&[2000]).unwrap(), oracle(&src.bytes, &c, &[2000])); } #[test] @@ -114,15 +91,8 @@ fn works_on_a_real_file_with_positional_reads() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("table.bin"); let bytes = table(777, 3000, 90); - std::fs::File::create(&path) - .unwrap() - .write_all(&bytes) - .unwrap(); - let c = PleReaderConfig { - cache_rows: 32, - expected_len: Some(bytes.len() as u64), - ..cfg(777, 3000) - }; + std::fs::File::create(&path).unwrap().write_all(&bytes).unwrap(); + let c = PleReaderConfig { cache_rows: 32, expected_len: Some(bytes.len() as u64), ..cfg(777, 3000) }; let reader = PleReader::open(Arc::new(File::open(&path).unwrap()), c.clone()).unwrap(); let rows: Vec = (0..3100).step_by(37).collect(); assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&bytes, &c, &rows)); @@ -155,11 +125,7 @@ fn property_random_requests_always_equal_the_oracle() { }) .collect(); let ticket = reader.issue(&rows); - assert_eq!( - reader.collect(ticket).unwrap(), - oracle(&bytes, &c, &rows), - "case {case}" - ); + assert_eq!(reader.collect(ticket).unwrap(), oracle(&bytes, &c, &rows), "case {case}"); } } } @@ -179,13 +145,8 @@ fn concurrent_callers_get_their_own_rows() { thread::spawn(move || { let mut rng = 77 + t; for _ in 0..40 { - let rows: Vec = (0..16) - .map(|_| (xorshift(&mut rng) % 5100) as u32) - .collect(); - assert_eq!( - reader.read_rows(&rows).unwrap(), - oracle(&src.bytes, &c, &rows) - ); + let rows: Vec = (0..16).map(|_| (xorshift(&mut rng) % 5100) as u32).collect(); + assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&src.bytes, &c, &rows)); } }) }) diff --git a/crates/model-format/src/ple_reader/tests/prefetched_keys_are_matched.rs b/crates/model-format/src/ple_reader/tests/prefetched_keys_are_matched.rs index b1945014..41127f5f 100644 --- a/crates/model-format/src/ple_reader/tests/prefetched_keys_are_matched.rs +++ b/crates/model-format/src/ple_reader/tests/prefetched_keys_are_matched.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Upstream 41cf05a0 `36381540` (`ngram/ple_reader_test.cpp` `prefetched_keys_are_reused`, issue #2622): `gather_batch` matched /// the prefetched tokens by position, so a prefetch of A..F gathered as D,E,F,A,B,C (or A gathered as A,A,A) read rows that were /// already in flight a second time. Here a ticket owns its rows and the row cache is keyed by row, so there is no position to @@ -31,13 +30,23 @@ fn prefetched_keys_are_matched_by_row_never_by_position() { }, Case { name: "subset", pre: (0..6).map(row).collect(), want: vec![row(4), row(1)], covered: true }, Case { name: "duplicates", pre: vec![row(0)], want: vec![row(0), row(0), row(0)], covered: true }, - Case { name: "duplicate prefetch", pre: vec![row(0), row(0), row(1)], want: vec![row(0), row(1)], covered: true }, + Case { + name: "duplicate prefetch", + pre: vec![row(0), row(0), row(1)], + want: vec![row(0), row(1)], + covered: true, + }, Case { name: "missing key", pre: vec![row(0), row(1)], want: vec![row(0), row(2)], covered: false }, Case { name: "extra prefetch", pre: (0..3).map(row).collect(), want: vec![row(1)], covered: true }, Case { name: "none", pre: vec![row(0)], want: vec![], covered: true }, Case { name: "over the window", pre: vec![row(0), row(1)], want: seventeen.clone(), covered: false }, Case { name: "window overflow", pre: seventeen, want: vec![row(16)], covered: true }, - Case { name: "out of range among them", pre: vec![row(1), 9_999_999], want: vec![9_999_999, row(1)], covered: false }, + Case { + name: "out of range among them", + pre: vec![row(1), 9_999_999], + want: vec![9_999_999, row(1)], + covered: false, + }, ]; for cache_rows in [0u64, 8192] { for io_threads in [Some(0usize), None, Some(3)] { @@ -78,14 +87,22 @@ fn prefetched_keys_are_matched_by_row_never_by_position() { reader.read_rows(&[r]).unwrap(); } let before = reader.snapshot(); - assert_eq!(reader.read_rows(&case.want).unwrap(), oracle(&src.bytes, &c, &case.want), "{tag}: after prefetch"); + assert_eq!( + reader.read_rows(&case.want).unwrap(), + oracle(&src.bytes, &c, &case.want), + "{tag}: after prefetch" + ); let after = reader.snapshot(); if cache_rows > 0 && case.covered { assert_eq!(after.reads, before.reads, "{tag}: a prefetched row is read again"); } // a batch never reads more pages than it has distinct rows let distinct: std::collections::HashSet<_> = case.want.iter().collect(); - assert!(after.reads - before.reads <= distinct.len() as u64, "{tag}: reads {}", after.reads - before.reads); + assert!( + after.reads - before.reads <= distinct.len() as u64, + "{tag}: reads {}", + after.reads - before.reads + ); } } } @@ -97,10 +114,11 @@ fn after_a_failed_read_every_ticket_and_every_later_issue_returns_the_error_and_ let reader = flaky_reader(threads, false); // tickets issued before the failure surfaces: one on the bad page, others behind it in the queue let bad = row_on_page(10); - let tickets: Vec<_> = [vec![row_on_page(1)], vec![bad], vec![row_on_page(2), row_on_page(3)], vec![row_on_page(4)]] - .iter() - .map(|rows| reader.issue(rows)) - .collect(); + let tickets: Vec<_> = + [vec![row_on_page(1)], vec![bad], vec![row_on_page(2), row_on_page(3)], vec![row_on_page(4)]] + .iter() + .map(|rows| reader.issue(rows)) + .collect(); let r = Arc::clone(&reader); let results = within("collect after a failed read", move || { let results: Vec<_> = tickets.into_iter().map(|t| r.collect(t)).collect(); diff --git a/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs b/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs index 8a873fd8..dd8fd2dd 100644 --- a/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs +++ b/crates/model-format/src/ple_reader/tests/rows_match_the_oracle_including.rs @@ -3,17 +3,13 @@ #[allow(unused_imports)] use super::*; - #[test] fn rows_match_the_oracle_including_out_of_range() { let c = cfg(100, 1000); let src = Mem::new(table(100, 1000, 90)); let reader = PleReader::open(src.clone(), c.clone()).unwrap(); let rows = [0u32, 1, 45, 46, 999, 1000, 5_000_000, 3, 3]; - assert_eq!( - reader.read_rows(&rows).unwrap(), - oracle(&src.bytes, &c, &rows) - ); + assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&src.bytes, &c, &rows)); } #[test] @@ -39,10 +35,7 @@ fn a_later_straddler_widens_the_read_of_its_first_page() { let src = Mem::new(table(0, 200, 90)); let reader = PleReader::open(src.clone(), c.clone()).unwrap(); let rows = [3u32, 45, 4]; - assert_eq!( - reader.read_rows(&rows).unwrap(), - oracle(&src.bytes, &c, &rows) - ); + assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&src.bytes, &c, &rows)); let s = reader.snapshot(); assert_eq!((s.reads, s.dedup_rows, s.bytes), (1, 2, 2 * PAGE as u64)); } @@ -56,14 +49,8 @@ fn plan_is_sorted_by_offset_and_covers_every_missing_row_once() { let mut stats = ReaderStats::default(); let plan = plan_reads(&rows, &c, &cache, &mut out, &mut stats); assert!(plan.windows(2).all(|w| w[0].offset < w[1].offset)); - assert!( - plan.iter() - .all(|r| r.offset % PAGE as u64 == 0 && r.length % PAGE == 0) - ); - let mut slots: Vec = plan - .iter() - .flat_map(|r| r.uses.iter().map(|u| u.slot)) - .collect(); + assert!(plan.iter().all(|r| r.offset % PAGE as u64 == 0 && r.length % PAGE == 0)); + let mut slots: Vec = plan.iter().flat_map(|r| r.uses.iter().map(|u| u.slot)).collect(); slots.sort_unstable(); assert_eq!(slots, vec![0, 1, 2, 3, 4, 5]); // slot 6 is out of range assert_eq!(stats.requests, 7); @@ -121,13 +108,7 @@ fn a_failed_read_sticks() { let src = Mem::new(table(0, 1000, 90)); let reader = PleReader::open(src.clone(), c).unwrap(); src.fail.store(true, Ordering::SeqCst); - assert!( - reader - .read_rows(&[5]) - .unwrap_err() - .0 - .contains("read failed") - ); + assert!(reader.read_rows(&[5]).unwrap_err().0.contains("read failed")); src.fail.store(false, Ordering::SeqCst); assert!(reader.read_rows(&[5]).is_err(), "sticky"); } @@ -148,13 +129,7 @@ fn a_short_read_inside_the_table_is_an_error() { log: Mutex::new(Vec::new()), }); let reader = PleReader::open(src, c).unwrap(); - assert!( - reader - .read_rows(&[60]) - .unwrap_err() - .0 - .contains("short read") - ); + assert!(reader.read_rows(&[60]).unwrap_err().0.contains("short read")); } #[test] @@ -172,12 +147,7 @@ fn open_rejects_a_table_past_the_end_and_bad_limits() { assert!(PleReader::open(src.clone(), c.clone()).is_err()); c.row_bytes = 90; c.expected_len = Some(1); - assert!( - PleReader::open(src, c) - .unwrap_err() - .0 - .contains("changed size") - ); + assert!(PleReader::open(src, c).unwrap_err().0.contains("changed size")); } #[test] @@ -194,17 +164,8 @@ fn a_size_change_after_open_fails_collect() { }); let reader = PleReader::open(src.clone(), c).unwrap(); assert!(reader.read_rows(&[1]).is_ok()); - src.reported_len - .as_ref() - .unwrap() - .store(7, Ordering::SeqCst); - assert!( - reader - .read_rows(&[2]) - .unwrap_err() - .0 - .contains("changed size") - ); + src.reported_len.as_ref().unwrap().store(7, Ordering::SeqCst); + assert!(reader.read_rows(&[2]).unwrap_err().0.contains("changed size")); assert!(reader.read_rows(&[3]).is_err(), "sticky"); } @@ -216,10 +177,7 @@ fn inline_mode_has_no_workers_and_matches() { let reader = PleReader::open(src.clone(), c.clone()).unwrap(); assert!(reader.workers.is_empty()); let rows: Vec = (0..60).map(|i| i * 8).collect(); - assert_eq!( - reader.read_rows(&rows).unwrap(), - oracle(&src.bytes, &c, &rows) - ); + assert_eq!(reader.read_rows(&rows).unwrap(), oracle(&src.bytes, &c, &rows)); } #[test] @@ -241,10 +199,7 @@ fn a_dropped_ticket_does_not_wedge_the_reader() { let src = Mem::new(table(0, 2000, 90)); let reader = PleReader::open(src.clone(), c.clone()).unwrap(); drop(reader.issue(&[1, 500, 1000])); - assert_eq!( - reader.read_rows(&[7]).unwrap(), - oracle(&src.bytes, &c, &[7]) - ); + assert_eq!(reader.read_rows(&[7]).unwrap(), oracle(&src.bytes, &c, &[7])); } #[test] diff --git a/crates/model-format/src/qwen4exp.rs b/crates/model-format/src/qwen4exp.rs index eb484dc4..00ed2d3a 100644 --- a/crates/model-format/src/qwen4exp.rs +++ b/crates/model-format/src/qwen4exp.rs @@ -3,9 +3,7 @@ //! This module validates metadata and tensor layout only. It does not decode //! quantized values, allocate device memory, or execute model operations. -use crate::gguf::{ - self, MetadataSnapshot, MetadataValue, TensorIndex, TokenizerMetadata, VerifiedGgufFile, -}; +use crate::gguf::{self, MetadataSnapshot, MetadataValue, TensorIndex, TokenizerMetadata, VerifiedGgufFile}; use std::{ collections::{BTreeMap, BTreeSet}, error::Error, @@ -16,17 +14,15 @@ const PINNED_IDENTITIES: [(u64, [u8; 32]); 2] = [ ( 54_817_524_224, [ - 0x4c, 0x1e, 0xb2, 0xce, 0xb4, 0x91, 0x5e, 0x11, 0x92, 0xf4, 0xf3, 0x86, 0x02, 0x18, - 0x97, 0xbd, 0xe5, 0x6a, 0x97, 0xf4, 0x0a, 0x0b, 0xb7, 0x8b, 0xb8, 0x64, 0x65, 0xe0, - 0xf7, 0xd2, 0xac, 0xa3, + 0x4c, 0x1e, 0xb2, 0xce, 0xb4, 0x91, 0x5e, 0x11, 0x92, 0xf4, 0xf3, 0x86, 0x02, 0x18, 0x97, 0xbd, 0xe5, 0x6a, + 0x97, 0xf4, 0x0a, 0x0b, 0xb7, 0x8b, 0xb8, 0x64, 0x65, 0xe0, 0xf7, 0xd2, 0xac, 0xa3, ], ), ( 28_800_138_432, [ - 0x31, 0x6b, 0x46, 0xf3, 0xa2, 0xdb, 0xd6, 0x8c, 0x90, 0x0f, 0x43, 0x13, 0x6a, 0xb9, - 0x44, 0x9f, 0x9d, 0xcc, 0x37, 0x25, 0xdf, 0xd8, 0xc7, 0x94, 0x84, 0x7c, 0x20, 0x4b, - 0xc1, 0x61, 0xe1, 0x13, + 0x31, 0x6b, 0x46, 0xf3, 0xa2, 0xdb, 0xd6, 0x8c, 0x90, 0x0f, 0x43, 0x13, 0x6a, 0xb9, 0x44, 0x9f, 0x9d, 0xcc, + 0x37, 0x25, 0xdf, 0xd8, 0xc7, 0x94, 0x84, 0x7c, 0x20, 0x4b, 0xc1, 0x61, 0xe1, 0x13, ], ), ]; @@ -232,8 +228,8 @@ pub struct RoutedMoeSourceScope<'source> { #[path = "qwen4exp_expert_source_bank.rs"] mod expert_source_bank; pub use expert_source_bank::{ - ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan, - ResidentExpertSourceError, ResidentExpertSourceReport, + ResidentExpertBankLease, ResidentExpertBankMember, ResidentExpertBankSpan, ResidentExpertSourceError, + ResidentExpertSourceReport, }; #[cfg(test)] diff --git a/crates/model-format/src/qwen4exp/expected_inventory.rs b/crates/model-format/src/qwen4exp/expected_inventory.rs index b3424915..78ece5af 100644 --- a/crates/model-format/src/qwen4exp/expected_inventory.rs +++ b/crates/model-format/src/qwen4exp/expected_inventory.rs @@ -3,57 +3,19 @@ #[allow(unused_imports)] use super::*; - pub(super) fn expected_inventory() -> Vec { let mut expected = Vec::with_capacity(1224); let mut add = |role, name: String, dimensions: &[u64], shard, kind| { - expected.push(ExpectedTensor { - role, - name, - dimensions: dimensions.to_vec(), - shard, - kind, - }); + expected.push(ExpectedTensor { role, name, dimensions: dimensions.to_vec(), shard, kind }); }; for (role, name, dimensions, kind) in [ - ( - GlobalRole::TokenEmbedding, - "token_embd.weight", - &[2560, 248320][..], - None, - ), - ( - GlobalRole::Output, - "output.weight", - &[2560, 248320][..], - None, - ), - ( - GlobalRole::OutputHcDown, - "output_hc_down.weight", - &[10240, 320][..], - None, - ), - ( - GlobalRole::OutputHcNorm, - "output_hc_norm.weight", - &[10240][..], - Some(0), - ), - ( - GlobalRole::OutputHcUp, - "output_hc_up.weight", - &[320, 10240][..], - None, - ), + (GlobalRole::TokenEmbedding, "token_embd.weight", &[2560, 248320][..], None), + (GlobalRole::Output, "output.weight", &[2560, 248320][..], None), + (GlobalRole::OutputHcDown, "output_hc_down.weight", &[10240, 320][..], None), + (GlobalRole::OutputHcNorm, "output_hc_norm.weight", &[10240][..], Some(0)), + (GlobalRole::OutputHcUp, "output_hc_up.weight", &[320, 10240][..], None), ] { - add( - TensorRole::Global(role), - name.to_owned(), - dimensions, - 0, - kind, - ); + add(TensorRole::Global(role), name.to_owned(), dimensions, 0, kind); } add( TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), @@ -66,188 +28,47 @@ pub(super) fn expected_inventory() -> Vec { for layer in 0..48u8 { let prefix = format!("blk.{layer}."); let common = [ - ( - LayerRole::HcAttnDown, - "hc_attn_down.weight", - &[10240, 320][..], - None, - ), - ( - LayerRole::HcAttnUp, - "hc_attn_up.weight", - &[320, 10240][..], - None, - ), - ( - LayerRole::HcAttnInject, - "hc_attn_inject.weight", - &[10240, 4][..], - None, - ), - ( - LayerRole::HcAttnNorm, - "hc_attn_norm.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::HcFfnDown, - "hc_ffn_down.weight", - &[10240, 320][..], - None, - ), - ( - LayerRole::HcFfnUp, - "hc_ffn_up.weight", - &[320, 10240][..], - None, - ), - ( - LayerRole::HcFfnInject, - "hc_ffn_inject.weight", - &[10240, 4][..], - None, - ), - ( - LayerRole::HcFfnNorm, - "hc_ffn_norm.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::FfnGateInp, - "ffn_gate_inp.weight", - &[2560, 512][..], - Some(30), - ), - ( - LayerRole::FfnGateInpShared, - "ffn_gate_inp_shexp.weight", - &[2560][..], - Some(30), - ), - ( - LayerRole::FfnGateShared, - "ffn_gate_shexp.weight", - &[2560, 640][..], - None, - ), - ( - LayerRole::FfnUpShared, - "ffn_up_shexp.weight", - &[2560, 640][..], - None, - ), - ( - LayerRole::FfnDownShared, - "ffn_down_shexp.weight", - &[640, 2560][..], - None, - ), - ( - LayerRole::FfnGateExperts, - "ffn_gate_exps.weight", - &[2560, 640, 512][..], - None, - ), - ( - LayerRole::FfnUpExperts, - "ffn_up_exps.weight", - &[2560, 640, 512][..], - None, - ), - ( - LayerRole::FfnDownExperts, - "ffn_down_exps.weight", - &[640, 2560, 512][..], - None, - ), + (LayerRole::HcAttnDown, "hc_attn_down.weight", &[10240, 320][..], None), + (LayerRole::HcAttnUp, "hc_attn_up.weight", &[320, 10240][..], None), + (LayerRole::HcAttnInject, "hc_attn_inject.weight", &[10240, 4][..], None), + (LayerRole::HcAttnNorm, "hc_attn_norm.weight", &[10240][..], Some(0)), + (LayerRole::HcFfnDown, "hc_ffn_down.weight", &[10240, 320][..], None), + (LayerRole::HcFfnUp, "hc_ffn_up.weight", &[320, 10240][..], None), + (LayerRole::HcFfnInject, "hc_ffn_inject.weight", &[10240, 4][..], None), + (LayerRole::HcFfnNorm, "hc_ffn_norm.weight", &[10240][..], Some(0)), + (LayerRole::FfnGateInp, "ffn_gate_inp.weight", &[2560, 512][..], Some(30)), + (LayerRole::FfnGateInpShared, "ffn_gate_inp_shexp.weight", &[2560][..], Some(30)), + (LayerRole::FfnGateShared, "ffn_gate_shexp.weight", &[2560, 640][..], None), + (LayerRole::FfnUpShared, "ffn_up_shexp.weight", &[2560, 640][..], None), + (LayerRole::FfnDownShared, "ffn_down_shexp.weight", &[640, 2560][..], None), + (LayerRole::FfnGateExperts, "ffn_gate_exps.weight", &[2560, 640, 512][..], None), + (LayerRole::FfnUpExperts, "ffn_up_exps.weight", &[2560, 640, 512][..], None), + (LayerRole::FfnDownExperts, "ffn_down_exps.weight", &[640, 2560, 512][..], None), ]; for (role, name, dimensions, kind) in common { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); + add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); } let family = if layer % 4 == 3 { [ (LayerRole::AttnQ, "attn_q.weight", &[2560, 12288][..], None), (LayerRole::AttnK, "attn_k.weight", &[2560, 512][..], None), (LayerRole::AttnV, "attn_v.weight", &[2560, 512][..], None), - ( - LayerRole::AttnOutput, - "attn_output.weight", - &[6144, 2560][..], - None, - ), - ( - LayerRole::AttnQNorm, - "attn_q_norm.weight", - &[256][..], - Some(0), - ), - ( - LayerRole::AttnKNorm, - "attn_k_norm.weight", - &[256][..], - Some(0), - ), - ( - LayerRole::IndexerQProj, - "indexer.q_proj.weight", - &[2560, 512][..], - None, - ), - ( - LayerRole::IndexerKProj, - "indexer.k_proj.weight", - &[2560, 128][..], - None, - ), - ( - LayerRole::IndexerQNorm, - "indexer.q_norm.weight", - &[128][..], - Some(0), - ), - ( - LayerRole::IndexerKNorm, - "indexer.k_norm.weight", - &[128][..], - Some(0), - ), + (LayerRole::AttnOutput, "attn_output.weight", &[6144, 2560][..], None), + (LayerRole::AttnQNorm, "attn_q_norm.weight", &[256][..], Some(0)), + (LayerRole::AttnKNorm, "attn_k_norm.weight", &[256][..], Some(0)), + (LayerRole::IndexerQProj, "indexer.q_proj.weight", &[2560, 512][..], None), + (LayerRole::IndexerKProj, "indexer.k_proj.weight", &[2560, 128][..], None), + (LayerRole::IndexerQNorm, "indexer.q_norm.weight", &[128][..], Some(0)), + (LayerRole::IndexerKNorm, "indexer.k_norm.weight", &[128][..], Some(0)), ] .to_vec() } else { [ - ( - LayerRole::AttnQkv, - "attn_qkv.weight", - &[2560, 10240][..], - None, - ), - ( - LayerRole::AttnGate, - "attn_gate.weight", - &[2560, 6144][..], - None, - ), + (LayerRole::AttnQkv, "attn_qkv.weight", &[2560, 10240][..], None), + (LayerRole::AttnGate, "attn_gate.weight", &[2560, 6144][..], None), (LayerRole::SsmOut, "ssm_out.weight", &[6144, 2560][..], None), - ( - LayerRole::SsmConv1d, - "ssm_conv1d.weight", - &[4, 10240][..], - None, - ), - ( - LayerRole::SsmAlpha, - "ssm_alpha.weight", - &[2560, 48][..], - None, - ), + (LayerRole::SsmConv1d, "ssm_conv1d.weight", &[4, 10240][..], None), + (LayerRole::SsmAlpha, "ssm_alpha.weight", &[2560, 48][..], None), (LayerRole::SsmBeta, "ssm_beta.weight", &[2560, 48][..], None), (LayerRole::SsmA, "ssm_a", &[48][..], Some(0)), (LayerRole::SsmDtBias, "ssm_dt.bias", &[48][..], Some(0)), @@ -256,60 +77,18 @@ pub(super) fn expected_inventory() -> Vec { .to_vec() }; for (role, name, dimensions, kind) in family { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); + add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); } if layer == 1 { for (role, name, dimensions, kind) in [ - ( - LayerRole::PleConv1d, - "ple_conv1d.weight", - &[4, 10240][..], - Some(1), - ), - ( - LayerRole::PleKey, - "ple_key.weight", - &[2560, 10240][..], - Some(30), - ), - ( - LayerRole::PleNormConv, - "ple_norm_conv.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleNormKey, - "ple_norm_key.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleNormQuery, - "ple_norm_query.weight", - &[10240][..], - Some(0), - ), - ( - LayerRole::PleValue, - "ple_value.weight", - &[2560, 2560][..], - Some(30), - ), + (LayerRole::PleConv1d, "ple_conv1d.weight", &[4, 10240][..], Some(1)), + (LayerRole::PleKey, "ple_key.weight", &[2560, 10240][..], Some(30)), + (LayerRole::PleNormConv, "ple_norm_conv.weight", &[10240][..], Some(0)), + (LayerRole::PleNormKey, "ple_norm_key.weight", &[10240][..], Some(0)), + (LayerRole::PleNormQuery, "ple_norm_query.weight", &[10240][..], Some(0)), + (LayerRole::PleValue, "ple_value.weight", &[2560, 2560][..], Some(30)), ] { - add( - TensorRole::Layer { layer, role }, - format!("{prefix}{name}"), - dimensions, - 0, - kind, - ); + add(TensorRole::Layer { layer, role }, format!("{prefix}{name}"), dimensions, 0, kind); } } } diff --git a/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs index a487fd90..23a1399a 100644 --- a/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs +++ b/crates/model-format/src/qwen4exp/impl_fmt_display_for.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl fmt::Display for BindingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs index 194ce285..ebd26d41 100644 --- a/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Qwen4ExpArtifact { pub fn bind(shard0: VerifiedGgufFile, shard1: VerifiedGgufFile) -> Result { let owners = [shard0, shard1]; @@ -32,25 +31,15 @@ impl Qwen4ExpArtifact { if snapshots[0].architecture.as_deref() != Some("qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } - if snapshots[1] - .architecture - .as_deref() - .is_some_and(|value| value != "qwen4exp") - { + if snapshots[1].architecture.as_deref().is_some_and(|value| value != "qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } topology(&snapshots[0])?; snapshots[0].tokenizer = owners[0].tokenizer_snapshot().map_err(BindingError::Io)?; let [metadata0, metadata1] = snapshots; let views = [ - LogicalShardView { - index: owners[0].index(), - metadata: metadata0, - }, - LogicalShardView { - index: owners[1].index(), - metadata: metadata1, - }, + LogicalShardView { index: owners[0].index(), metadata: metadata0 }, + LogicalShardView { index: owners[1].index(), metadata: metadata1 }, ]; let validated = validate_logical_views(views)?; Ok(Self { @@ -70,17 +59,12 @@ impl Qwen4ExpArtifact { } pub fn tensor(&self, role: TensorRole) -> Result<&ResolvedTensor, BindingError> { - self.roles - .get(&role) - .ok_or(BindingError::Role("not_present")) + self.roles.get(&role).ok_or(BindingError::Role("not_present")) } /// Recheck the retained verified source without rereading immutable weights. pub fn validate_tensor_source(&mut self, role: TensorRole) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; self.shards[tensor.shard as usize] .stream_tensor(tensor.tensor_number, 0, 0, |_| Ok(())) .map_err(BindingError::Io) @@ -90,35 +74,18 @@ impl Qwen4ExpArtifact { /// batched reads that must return exactly the bytes `stream_row` would. /// Row 0 and the last row pass the single-row planner's admission. pub fn row_table_source(&self, role: TensorRole) -> Result { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; if tensor.dimensions.len() != 2 { return Err(BindingError::Role("rank_mismatch")); } let n_rows = tensor.dimensions[1]; let (first, row_bytes) = plan_row(tensor, 0, None)?; - let (last, _) = plan_row( - tensor, - n_rows - .checked_sub(1) - .ok_or(BindingError::Range("row_index"))?, - None, - )?; + let (last, _) = plan_row(tensor, n_rows.checked_sub(1).ok_or(BindingError::Range("row_index"))?, None)?; if first != 0 || last != (n_rows - 1) * row_bytes { return Err(BindingError::Geometry("row_stride")); } - let file = self.shards[tensor.shard as usize] - .duplicate_descriptor() - .map_err(BindingError::Io)?; - Ok(RowTableSource { - file, - table_offset: tensor.absolute_start, - n_rows, - row_bytes, - file_size: tensor.file_size, - }) + let file = self.shards[tensor.shard as usize].duplicate_descriptor().map_err(BindingError::Io)?; + Ok(RowTableSource { file, table_offset: tensor.absolute_start, n_rows, row_bytes, file_size: tensor.file_size }) } pub fn stream_row( @@ -127,28 +94,18 @@ impl Qwen4ExpArtifact { row: u64, mut consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; let range = plan_row(tensor, row, None)?; self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { - consume(chunk) - }) + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| consume(chunk)) .map_err(BindingError::Io) } /// Whole native token table from the same retained verified GGUF owner. /// This closed global source does not widen the expert/row planners. - pub fn stream_token_embedding( - &mut self, - consume: impl FnMut(&[u8]) -> io::Result<()>, - ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&TensorRole::Global(GlobalRole::TokenEmbedding)) - .ok_or(BindingError::Role("not_present"))?; + pub fn stream_token_embedding(&mut self, consume: impl FnMut(&[u8]) -> io::Result<()>) -> Result<(), BindingError> { + let tensor = + self.roles.get(&TensorRole::Global(GlobalRole::TokenEmbedding)).ok_or(BindingError::Role("not_present"))?; if tensor.shard != 0 || tensor.dimensions != [2560, 248320] || tensor.byte_length == 0 { return Err(BindingError::Range("token_embedding_extent")); } @@ -164,15 +121,10 @@ impl Qwen4ExpArtifact { row: u64, mut consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; let range = plan_row(tensor, row, Some(expert))?; self.shards[tensor.shard as usize] - .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| { - consume(chunk) - }) + .stream_tensor(tensor.tensor_number, range.0, range.1, |chunk| consume(chunk)) .map_err(BindingError::Io) } @@ -186,10 +138,7 @@ impl Qwen4ExpArtifact { count: u64, bytes: Box<[u8]>, ) -> Result, BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; if range.1 != bytes.len() as u64 { return Err(BindingError::Range("owned_expert_extent")); @@ -219,10 +168,7 @@ impl Qwen4ExpArtifact { count: u64, consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; let range = plan_stream_rows(tensor, role, first, count, None)?; self.shards[tensor.shard as usize] .stream_tensor(tensor.tensor_number, range.0, range.1, consume) @@ -241,10 +187,7 @@ impl Qwen4ExpArtifact { count: u64, consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { - let tensor = self - .roles - .get(&role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&role).ok_or(BindingError::Role("not_present"))?; let range = plan_stream_rows(tensor, role, first, count, Some(expert))?; self.shards[tensor.shard as usize] .stream_tensor(tensor.tensor_number, range.0, range.1, consume) diff --git a/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs b/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs index f7464ce1..32b62383 100644 --- a/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs +++ b/crates/model-format/src/qwen4exp/impl_qwen4expartifact_2.rs @@ -15,17 +15,12 @@ impl Qwen4ExpArtifact { let layer = u8::try_from(layer).map_err(|_| BindingError::Range("layer"))?; let gate = self .roles - .get(&TensorRole::Layer { - layer, - role: LayerRole::FfnGateExperts, - }) + .get(&TensorRole::Layer { layer, role: LayerRole::FfnGateExperts }) .ok_or(BindingError::Role("not_present"))?; if gate.shard != 0 { return Err(BindingError::Geometry("routed_moe_source_shard")); } - let source = self.shards[0] - .begin_source_fence(gate.tensor_number) - .map_err(BindingError::Io)?; + let source = self.shards[0].begin_source_fence(gate.tensor_number).map_err(BindingError::Io)?; Ok(RoutedMoeSourceScope { source, roles: &self.roles, diff --git a/crates/model-format/src/qwen4exp/plan_stream_rows.rs b/crates/model-format/src/qwen4exp/plan_stream_rows.rs index 7847c2fc..24c31db1 100644 --- a/crates/model-format/src/qwen4exp/plan_stream_rows.rs +++ b/crates/model-format/src/qwen4exp/plan_stream_rows.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - /// Larger spans are restricted to one complete, source-defined matrix. /// Other roles and partial ranges retain the existing 64-row admission. pub(super) fn plan_stream_rows( @@ -18,66 +17,26 @@ pub(super) fn plan_stream_rows( } use LayerRole as L; let (columns, rows, routed) = match role { - TensorRole::Layer { - role: L::FfnGateExperts | L::FfnUpExperts, - .. - } => (2560, 640, true), - TensorRole::Layer { - role: L::FfnDownExperts, - .. - } => (640, 2560, true), - TensorRole::Layer { - role: L::FfnGateShared | L::FfnUpShared, - .. - } => (2560, 640, false), - TensorRole::Layer { - role: L::FfnDownShared, - .. - } => (640, 2560, false), - TensorRole::Layer { - role: L::AttnQkv, .. - } => (2560, 10240, false), - TensorRole::Layer { - role: L::AttnGate, .. - } => (2560, 6144, false), - TensorRole::Layer { - role: L::SsmConv1d, .. - } => (4, 10240, false), - TensorRole::Layer { - layer: 1, - role: L::PleKey, - } if tensor.kind == 30 => (2560, 10240, false), - TensorRole::Layer { - layer: 1, - role: L::PleValue, - } if tensor.kind == 30 => (2560, 2560, false), - TensorRole::Layer { - layer: 1, - role: L::PleConv1d, - } if tensor.kind == 1 => (4, 10240, false), - TensorRole::Layer { - role: L::SsmOut | L::AttnOutput, - .. - } => (6144, 2560, false), + TensorRole::Layer { role: L::FfnGateExperts | L::FfnUpExperts, .. } => (2560, 640, true), + TensorRole::Layer { role: L::FfnDownExperts, .. } => (640, 2560, true), + TensorRole::Layer { role: L::FfnGateShared | L::FfnUpShared, .. } => (2560, 640, false), + TensorRole::Layer { role: L::FfnDownShared, .. } => (640, 2560, false), + TensorRole::Layer { role: L::AttnQkv, .. } => (2560, 10240, false), + TensorRole::Layer { role: L::AttnGate, .. } => (2560, 6144, false), + TensorRole::Layer { role: L::SsmConv1d, .. } => (4, 10240, false), + TensorRole::Layer { layer: 1, role: L::PleKey } if tensor.kind == 30 => (2560, 10240, false), + TensorRole::Layer { layer: 1, role: L::PleValue } if tensor.kind == 30 => (2560, 2560, false), + TensorRole::Layer { layer: 1, role: L::PleConv1d } if tensor.kind == 1 => (4, 10240, false), + TensorRole::Layer { role: L::SsmOut | L::AttnOutput, .. } => (6144, 2560, false), TensorRole::Layer { role: L::AttnQ, .. } => (2560, 12288, false), - TensorRole::Layer { - role: L::AttnK | L::AttnV | L::IndexerQProj | L::FfnGateInp, - .. - } => (2560, 512, false), - TensorRole::Layer { - role: L::IndexerKProj, - .. - } => (2560, 128, false), - TensorRole::Layer { - role: L::HcAttnDown | L::HcFfnDown, - .. + TensorRole::Layer { role: L::AttnK | L::AttnV | L::IndexerQProj | L::FfnGateInp, .. } => (2560, 512, false), + TensorRole::Layer { role: L::IndexerKProj, .. } => (2560, 128, false), + TensorRole::Layer { role: L::HcAttnDown | L::HcFfnDown, .. } | TensorRole::Global(GlobalRole::OutputHcDown) => { + (10240, 320, false) } - | TensorRole::Global(GlobalRole::OutputHcDown) => (10240, 320, false), - TensorRole::Layer { - role: L::HcAttnUp | L::HcFfnUp, - .. + TensorRole::Layer { role: L::HcAttnUp | L::HcFfnUp, .. } | TensorRole::Global(GlobalRole::OutputHcUp) => { + (320, 10240, false) } - | TensorRole::Global(GlobalRole::OutputHcUp) => (320, 10240, false), // The complete vocabulary-major head / embedding table: the native head and embedding owners // (`generate.cpp` NativeHead / embedding upload) read each as ONE whole-tensor stream. TensorRole::Global(GlobalRole::Output | GlobalRole::TokenEmbedding) => (2560, 248320, false), @@ -100,28 +59,15 @@ pub(super) fn plan_row_span( count: u64, expert: Option, ) -> Result<(u64, u64), BindingError> { - let end_row = first - .checked_add(count) - .ok_or(BindingError::Range("row_index"))?; + let end_row = first.checked_add(count).ok_or(BindingError::Range("row_index"))?; let (offset, row_bytes) = plan_row(tensor, first, expert)?; let (last_offset, last_bytes) = plan_row(tensor, end_row - 1, expert)?; - let bytes = row_bytes - .checked_mul(count) - .ok_or(BindingError::Range("byte_count"))?; - let end = offset - .checked_add(bytes) - .ok_or(BindingError::Range("row_offset"))?; - if last_bytes != row_bytes - || last_offset.checked_add(last_bytes) != Some(end) - || end > tensor.byte_length - { + let bytes = row_bytes.checked_mul(count).ok_or(BindingError::Range("byte_count"))?; + let end = offset.checked_add(bytes).ok_or(BindingError::Range("row_offset"))?; + if last_bytes != row_bytes || last_offset.checked_add(last_bytes) != Some(end) || end > tensor.byte_length { return Err(BindingError::Range("tensor_bounds")); } - if tensor - .absolute_start - .checked_add(end) - .is_none_or(|absolute_end| absolute_end > tensor.file_size) - { + if tensor.absolute_start.checked_add(end).is_none_or(|absolute_end| absolute_end > tensor.file_size) { return Err(BindingError::Range("file_bounds")); } Ok((offset, bytes)) @@ -138,24 +84,15 @@ impl RoutedMoeSourceScope<'_> { Ok(()) } pub(super) fn role(&self, role: LayerRole) -> Result { - if !matches!( - role, - LayerRole::FfnGateExperts | LayerRole::FfnUpExperts | LayerRole::FfnDownExperts - ) { + if !matches!(role, LayerRole::FfnGateExperts | LayerRole::FfnUpExperts | LayerRole::FfnDownExperts) { return Err(BindingError::Role("routed_moe_source")); } - Ok(TensorRole::Layer { - layer: self.layer, - role, - }) + Ok(TensorRole::Layer { layer: self.layer, role }) } /// Every request rechecks its exact immutable indexed tensor and empty-span /// extent. Source length observations belong to begin/explicit finish. pub fn tensor(&self, role: LayerRole) -> Result<&ResolvedTensor, BindingError> { - let tensor = self - .roles - .get(&self.role(role)?) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&self.role(role)?).ok_or(BindingError::Role("not_present"))?; if tensor.shard != 0 { return Err(BindingError::Geometry("routed_moe_source_shard")); } @@ -163,9 +100,7 @@ impl RoutedMoeSourceScope<'_> { } pub fn validate_descriptor(&self, role: LayerRole) -> Result<(), BindingError> { let tensor = self.tensor(role)?; - self.source - .validate_tensor(tensor.tensor_number) - .map_err(BindingError::Io) + self.source.validate_tensor(tensor.tensor_number).map_err(BindingError::Io) } /// One complete actual matrix of this source's fixed expert only. pub fn stream_matrix( @@ -174,74 +109,44 @@ impl RoutedMoeSourceScope<'_> { consume: impl FnMut(&[u8]) -> io::Result<()>, ) -> Result<(), BindingError> { let tensor_role = self.role(role)?; - let tensor = self - .roles - .get(&tensor_role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&tensor_role).ok_or(BindingError::Role("not_present"))?; if tensor.shard != 0 { return Err(BindingError::Geometry("routed_moe_source_shard")); } - let rows = if role == LayerRole::FfnDownExperts { - 2560 - } else { - 640 - }; + let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 }; let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; - self.source - .stream_tensor(tensor.tensor_number, range.0, range.1, consume) - .map_err(BindingError::Io) + self.source.stream_tensor(tensor.tensor_number, range.0, range.1, consume).map_err(BindingError::Io) } /// Whole fixed-expert span into its initialized final owner, retaining the /// same real source loan and full original stream bounds/size observations. - pub fn read_matrix_owned( - &mut self, - role: LayerRole, - bytes: Box<[u8]>, - ) -> Result, BindingError> { + pub fn read_matrix_owned(&mut self, role: LayerRole, bytes: Box<[u8]>) -> Result, BindingError> { let tensor_role = self.role(role)?; - let tensor = self - .roles - .get(&tensor_role) - .ok_or(BindingError::Role("not_present"))?; + let tensor = self.roles.get(&tensor_role).ok_or(BindingError::Role("not_present"))?; if tensor.shard != 0 { return Err(BindingError::Geometry("routed_moe_source_shard")); } - let rows = if role == LayerRole::FfnDownExperts { - 2560 - } else { - 640 - }; + let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 }; let range = plan_stream_rows(tensor, tensor_role, 0, rows, Some(u64::from(self.expert)))?; if range.1 != bytes.len() as u64 { return Err(BindingError::Range("owned_expert_extent")); } if let Some(bank) = self.resident_experts { let resident = bank.tensor(tensor_role, tensor)?; - let bytes = self - .source - .copy_resident_tensor(resident, range.0, bytes) - .map_err(BindingError::Io)?; + let bytes = self.source.copy_resident_tensor(resident, range.0, bytes).map_err(BindingError::Io)?; bank.note_copy(bytes.len()); Ok(bytes) } else { - self.source - .read_tensor_owned(tensor.tensor_number, range.0, bytes) - .map_err(BindingError::Io) + self.source.read_tensor_owned(tensor.tensor_number, range.0, bytes).map_err(BindingError::Io) } } /// No-copy, fixed expert span of the actual retained catalog. The source /// fence stays held; completion still requires explicit finish. - pub fn resident_matrix_span( - &self, - role: LayerRole, - ) -> Result { + pub fn resident_matrix_span(&self, role: LayerRole) -> Result { let tensor_role = self.role(role)?; let tensor = self.tensor(role)?; self.validate_descriptor(role)?; - let bank = self - .resident_experts - .ok_or(BindingError::Role("resident_expert_source_absent"))?; + let bank = self.resident_experts.ok_or(BindingError::Role("resident_expert_source_absent"))?; bank.span(tensor_role, tensor, self.expert) } diff --git a/crates/model-format/src/qwen4exp/validate_logical_views.rs b/crates/model-format/src/qwen4exp/validate_logical_views.rs index 43bae635..f455be3b 100644 --- a/crates/model-format/src/qwen4exp/validate_logical_views.rs +++ b/crates/model-format/src/qwen4exp/validate_logical_views.rs @@ -3,25 +3,19 @@ #[allow(unused_imports)] use super::*; - pub(super) fn validate_logical_views( mut shards: [LogicalShardView<'_>; 2], ) -> Result { for (number, shard) in shards.iter().enumerate() { let (expected_no, expected_count) = (number as u64, 2); - if shard.index.summary.split_no != Some(expected_no) - || shard.metadata.split_no != Some(expected_no) - { + if shard.index.summary.split_no != Some(expected_no) || shard.metadata.split_no != Some(expected_no) { return Err(BindingError::Split("split.no")); } - if shard.index.summary.split_count != Some(expected_count) - || shard.metadata.split_count != Some(expected_count) + if shard.index.summary.split_count != Some(expected_count) || shard.metadata.split_count != Some(expected_count) { return Err(BindingError::Split("split.count")); } - if shard.index.summary.split_tensors_count != Some(1224) - || shard.metadata.split_tensors_count != Some(1224) - { + if shard.index.summary.split_tensors_count != Some(1224) || shard.metadata.split_tensors_count != Some(1224) { return Err(BindingError::Split("split.tensors.count")); } } @@ -34,28 +28,15 @@ pub(super) fn validate_logical_views( if shards[0].metadata.architecture.as_deref() != Some("qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } - if shards[1] - .metadata - .architecture - .as_deref() - .is_some_and(|value| value != "qwen4exp") - { + if shards[1].metadata.architecture.as_deref().is_some_and(|value| value != "qwen4exp") { return Err(BindingError::Metadata("general.architecture")); } let topology = topology(&shards[0].metadata)?; let tokenizer = gguf::validate_tokenizer_metadata( - shards[0] - .metadata - .tokenizer - .take() - .ok_or(BindingError::Tokenizer("required_fields"))?, + shards[0].metadata.tokenizer.take().ok_or(BindingError::Tokenizer("required_fields"))?, ) .map_err(|_| BindingError::Tokenizer("invalid_metadata"))?; validate_tokenizer(&tokenizer)?; let roles = validate_role_inventory(&shards)?; - Ok(ValidatedBindingView { - topology, - tokenizer, - roles, - }) + Ok(ValidatedBindingView { topology, tokenizer, roles }) } diff --git a/crates/model-format/src/qwen4exp/validate_owner_index_split.rs b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs index 46ef6d2b..8c2e4197 100644 --- a/crates/model-format/src/qwen4exp/validate_owner_index_split.rs +++ b/crates/model-format/src/qwen4exp/validate_owner_index_split.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn validate_owner_index_split(owners: &[VerifiedGgufFile; 2]) -> Result<(), BindingError> { for (number, owner) in owners.iter().enumerate() { let summary = &owner.index().summary; @@ -49,11 +48,7 @@ pub(super) fn required_uint(metadata: &MetadataSnapshot, key: &'static str) -> R } } -pub(super) fn required_u32( - metadata: &MetadataSnapshot, - key: &'static str, - expected: u32, -) -> Result { +pub(super) fn required_u32(metadata: &MetadataSnapshot, key: &'static str, expected: u32) -> Result { let value = required_uint(metadata, key)?; if value != u64::from(expected) { return Err(BindingError::Metadata(key)); @@ -98,35 +93,25 @@ pub(super) fn topology(metadata: &MetadataSnapshot) -> Result>(), + &(0..48).map(|layer| if layer % 4 == 3 { 4 } else { 0 }).collect::>(), )?; let full_attention_interval = required_u32(metadata, "qwen4exp.full_attention_interval", 4)?; let expert_count = required_u32(metadata, "qwen4exp.expert_count", 512)?; let expert_used_count = required_u32(metadata, "qwen4exp.expert_used_count", 10)?; - let expert_feed_forward_length = - required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; - let expert_shared_feed_forward_length = - required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; + let expert_feed_forward_length = required_u32(metadata, "qwen4exp.expert_feed_forward_length", 640)?; + let expert_shared_feed_forward_length = required_u32(metadata, "qwen4exp.expert_shared_feed_forward_length", 640)?; let attention_head_count = required_u32(metadata, "qwen4exp.attention.head_count", 24)?; let attention_head_count_kv = required_u32(metadata, "qwen4exp.attention.head_count_kv", 2)?; let attention_key_length = required_u32(metadata, "qwen4exp.attention.key_length", 256)?; let attention_value_length = required_u32(metadata, "qwen4exp.attention.value_length", 256)?; let rms_epsilon = required_float(metadata, "qwen4exp.attention.layer_norm_rms_epsilon")?; if (rms_epsilon - 1.0e-6).abs() > 1.0e-12 { - return Err(BindingError::Metadata( - "qwen4exp.attention.layer_norm_rms_epsilon", - )); + return Err(BindingError::Metadata("qwen4exp.attention.layer_norm_rms_epsilon")); } let hc_count = required_u32(metadata, "qwen4exp.hyper_connection.count", 4)?; let hc_low_rank = required_u32(metadata, "qwen4exp.hyper_connection.low_rank", 320)?; let rope_dimension_count = required_u32(metadata, "qwen4exp.rope.dimension_count", 64)?; - let rope_dimension_sections = required_array( - metadata, - "qwen4exp.rope.dimension_sections", - &[11, 11, 10, 0], - )?; + let rope_dimension_sections = required_array(metadata, "qwen4exp.rope.dimension_sections", &[11, 11, 10, 0])?; let rope_frequency_base = required_float(metadata, "qwen4exp.rope.freq_base")?; if rope_frequency_base != 10_000_000.0 { return Err(BindingError::Metadata("qwen4exp.rope.freq_base")); @@ -139,8 +124,7 @@ pub(super) fn topology(metadata: &MetadataSnapshot) -> Result Result; 2], ) -> Result, BindingError> { @@ -11,49 +10,32 @@ pub(super) fn validate_role_inventory( if expected.len() != 1224 { return Err(BindingError::Role("registry_count")); } - let by_name = expected - .iter() - .map(|item| (item.name.as_str(), item)) - .collect::>(); - let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42] - .into_iter() - .collect(); + let by_name = expected.iter().map(|item| (item.name.as_str(), item)).collect::>(); + let allowed_kinds: BTreeSet = [0, 1, 8, 12, 13, 14, 18, 20, 21, 22, 23, 30, 42].into_iter().collect(); let mut actual = BTreeMap::new(); let mut roles = BTreeMap::new(); let mut spans: [Vec<(u64, u64)>; 2] = [Vec::new(), Vec::new()]; for (shard_number, shard) in shards.iter().enumerate() { for (tensor_number, tensor) in shard.index.tensors.iter().enumerate() { - if actual - .insert( - tensor.name.as_str(), - (shard_number as u8, tensor_number, tensor), - ) - .is_some() - { + if actual.insert(tensor.name.as_str(), (shard_number as u8, tensor_number, tensor)).is_some() { return Err(BindingError::Role("duplicate_name")); } } } for spec in &expected { - let (shard_number, tensor_number, tensor) = actual - .get(spec.name.as_str()) - .ok_or(BindingError::Role("missing_name"))?; + let (shard_number, tensor_number, tensor) = + actual.get(spec.name.as_str()).ok_or(BindingError::Role("missing_name"))?; if spec.shard != *shard_number { return Err(BindingError::Role("wrong_shard")); } if tensor.dimensions != spec.dimensions { return Err(BindingError::Geometry("dimensions")); } - if !allowed_kinds.contains(&tensor.kind) - || spec.kind.is_some_and(|kind| kind != tensor.kind) - { + if !allowed_kinds.contains(&tensor.kind) || spec.kind.is_some_and(|kind| kind != tensor.kind) { return Err(BindingError::Geometry("kind")); } - let (block_elements, block_bytes) = - gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; - if tensor.dimensions.first().copied().unwrap_or(0) == 0 - || tensor.dimensions[0] % block_elements != 0 - { + let (block_elements, block_bytes) = gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + if tensor.dimensions.first().copied().unwrap_or(0) == 0 || tensor.dimensions[0] % block_elements != 0 { return Err(BindingError::Geometry("block_alignment")); } let elements = tensor @@ -69,18 +51,12 @@ pub(super) fn validate_role_inventory( return Err(BindingError::Geometry("indexed_byte_count")); } let shard = &shards[*shard_number as usize]; - let absolute_start = shard - .index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or(BindingError::Range("absolute_start"))?; + let absolute_start = + shard.index.summary.data_start.checked_add(tensor.offset).ok_or(BindingError::Range("absolute_start"))?; if absolute_start < shard.index.summary.data_start { return Err(BindingError::Range("data_bounds")); } - let absolute_end = absolute_start - .checked_add(tensor.bytes) - .ok_or(BindingError::Range("absolute_end"))?; + let absolute_end = absolute_start.checked_add(tensor.bytes).ok_or(BindingError::Range("absolute_end"))?; if absolute_end > shard.index.summary.file_size { return Err(BindingError::Range("file_bounds")); } @@ -111,11 +87,7 @@ pub(super) fn validate_role_inventory( Ok(roles) } -pub(super) fn plan_row( - tensor: &ResolvedTensor, - row: u64, - expert: Option, -) -> Result<(u64, u64), BindingError> { +pub(super) fn plan_row(tensor: &ResolvedTensor, row: u64, expert: Option) -> Result<(u64, u64), BindingError> { let dimensions = &tensor.dimensions; match (dimensions.len(), expert) { (1, None) if matches!(tensor.kind, 0 | 1 | 30) => {} @@ -124,8 +96,7 @@ pub(super) fn plan_row( (1 | 2, Some(_)) | (3, None) => return Err(BindingError::Role("rank_mismatch")), _ => return Err(BindingError::Role("rank")), } - let (block_elements, block_bytes) = - gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; + let (block_elements, block_bytes) = gguf::block_geometry(tensor.kind).ok_or(BindingError::Geometry("kind"))?; let dim0 = *dimensions.first().ok_or(BindingError::Geometry("rank"))?; if dim0 == 0 || dim0 % block_elements != 0 { return Err(BindingError::Geometry("block_alignment")); @@ -141,9 +112,7 @@ pub(super) fn plan_row( if tensor.byte_length == 0 || indexed_bytes != tensor.byte_length { return Err(BindingError::Geometry("indexed_byte_count")); } - let row_bytes = (dim0 / block_elements) - .checked_mul(block_bytes) - .ok_or(BindingError::Range("row_bytes"))?; + let row_bytes = (dim0 / block_elements).checked_mul(block_bytes).ok_or(BindingError::Range("row_bytes"))?; let relative = match (dimensions.len(), expert) { (1, None) if row == 0 => Some(0), (2, None) if row < dimensions[1] => row.checked_mul(row_bytes), @@ -155,11 +124,7 @@ pub(super) fn plan_row( _ => unreachable!("rank checked above"), } .ok_or(BindingError::Range("row_offset"))?; - if row_bytes == 0 - || relative - .checked_add(row_bytes) - .is_none_or(|end| end > tensor.byte_length) - { + if row_bytes == 0 || relative.checked_add(row_bytes).is_none_or(|end| end > tensor.byte_length) { return Err(BindingError::Range("tensor_bounds")); } if tensor diff --git a/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs b/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs index ecd70755..603cb4e2 100644 --- a/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs +++ b/crates/model-format/src/qwen4exp/whole_dense_matrix_transport_tests.rs @@ -21,29 +21,16 @@ fn closed_ple_spans_keep_exact_tile_offsets_and_original_formats() { file_size: 4096 + bytes, }; let closed = TensorRole::Layer { layer: 1, role }; - assert_eq!( - plan_stream_rows(&tensor, closed, 0, rows, None).unwrap(), - (0, bytes) - ); + assert_eq!(plan_stream_rows(&tensor, closed, 0, rows, None).unwrap(), (0, bytes)); for first in (0..rows).step_by(64) { - assert_eq!( - plan_rows(&tensor, first, 64, None).unwrap(), - (first * columns * 2, 64 * columns * 2) - ); + assert_eq!(plan_rows(&tensor, first, 64, None).unwrap(), (first * columns * 2, 64 * columns * 2)); } - for (first, count, expert) in [ - (1, rows, None), - (0, rows - 1, None), - (0, rows + 1, None), - (0, rows, Some(0)), - (u64::MAX, rows, None), - ] { + for (first, count, expert) in + [(1, rows, None), (0, rows - 1, None), (0, rows + 1, None), (0, rows, Some(0)), (u64::MAX, rows, None)] + { assert!(plan_stream_rows(&tensor, closed, first, count, expert).is_err()); } - assert!( - plan_stream_rows(&tensor, TensorRole::Layer { layer: 0, role }, 0, rows, None) - .is_err() - ); + assert!(plan_stream_rows(&tensor, TensorRole::Layer { layer: 0, role }, 0, rows, None).is_err()); let mut wrong = tensor.clone(); wrong.kind = if kind == 30 { 1 } else { 30 }; assert!(plan_stream_rows(&wrong, closed, 0, rows, None).is_err()); @@ -65,118 +52,20 @@ fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { // Fixed native topology, BF16 row stride; compare every legacy tile, // including tails, rather than calculating expected via the new planner. let shapes = [ - ( - TensorRole::Layer { - layer: 0, - role: L::AttnQkv, - }, - 2560, - 10240, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::AttnGate, - }, - 2560, - 6144, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::SsmOut, - }, - 6144, - 2560, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnQ, - }, - 2560, - 12288, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnK, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnV, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::IndexerQProj, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::IndexerKProj, - }, - 2560, - 128, - ), - ( - TensorRole::Layer { - layer: 3, - role: L::AttnOutput, - }, - 6144, - 2560, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::FfnGateInp, - }, - 2560, - 512, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcAttnDown, - }, - 10240, - 320, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcFfnDown, - }, - 10240, - 320, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcAttnUp, - }, - 320, - 10240, - ), - ( - TensorRole::Layer { - layer: 0, - role: L::HcFfnUp, - }, - 320, - 10240, - ), + (TensorRole::Layer { layer: 0, role: L::AttnQkv }, 2560, 10240), + (TensorRole::Layer { layer: 0, role: L::AttnGate }, 2560, 6144), + (TensorRole::Layer { layer: 0, role: L::SsmOut }, 6144, 2560), + (TensorRole::Layer { layer: 3, role: L::AttnQ }, 2560, 12288), + (TensorRole::Layer { layer: 3, role: L::AttnK }, 2560, 512), + (TensorRole::Layer { layer: 3, role: L::AttnV }, 2560, 512), + (TensorRole::Layer { layer: 3, role: L::IndexerQProj }, 2560, 512), + (TensorRole::Layer { layer: 3, role: L::IndexerKProj }, 2560, 128), + (TensorRole::Layer { layer: 3, role: L::AttnOutput }, 6144, 2560), + (TensorRole::Layer { layer: 0, role: L::FfnGateInp }, 2560, 512), + (TensorRole::Layer { layer: 0, role: L::HcAttnDown }, 10240, 320), + (TensorRole::Layer { layer: 0, role: L::HcFfnDown }, 10240, 320), + (TensorRole::Layer { layer: 0, role: L::HcAttnUp }, 320, 10240), + (TensorRole::Layer { layer: 0, role: L::HcFfnUp }, 320, 10240), (TensorRole::Global(GlobalRole::OutputHcDown), 10240, 320), (TensorRole::Global(GlobalRole::OutputHcUp), 320, 10240), ]; @@ -192,10 +81,7 @@ fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { byte_length: bytes, file_size: 4096 + bytes, }; - assert_eq!( - plan_stream_rows(&tensor, role, 0, rows, None).unwrap(), - (0, bytes) - ); + assert_eq!(plan_stream_rows(&tensor, role, 0, rows, None).unwrap(), (0, bytes)); let mut concatenated = 0; for first in (0..rows).step_by(64) { let count = (rows - first).min(64); @@ -205,13 +91,9 @@ fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { concatenated += legacy.1; } assert_eq!(concatenated, bytes); - for (first, count, expert) in [ - (1, rows, None), - (0, rows - 1, None), - (0, rows + 1, None), - (0, rows, Some(0)), - (u64::MAX, rows, None), - ] { + for (first, count, expert) in + [(1, rows, None), (0, rows - 1, None), (0, rows + 1, None), (0, rows, Some(0)), (u64::MAX, rows, None)] + { assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); } let mut changed = tensor.clone(); @@ -220,10 +102,7 @@ fn closed_dense_spans_preserve_legacy_offsets_and_refuse_partial_matrices() { changed = tensor.clone(); changed.file_size -= 1; assert!(plan_stream_rows(&changed, role, 0, rows, None).is_err()); - let scalar_role = TensorRole::Layer { - layer: 0, - role: L::HcFfnNorm, - }; + let scalar_role = TensorRole::Layer { layer: 0, role: L::HcFfnNorm }; assert!(plan_stream_rows(&tensor, scalar_role, 0, rows, None).is_err()); } } diff --git a/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs index 71a78e8a..f0c3fe68 100644 --- a/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs +++ b/crates/model-format/src/qwen4exp/whole_moe_matrix_sdet.rs @@ -25,11 +25,7 @@ fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() ]; for (kind, routed, down, stride, tile_bytes, matrix_bytes) in layouts { let (columns, rows) = if down { (640, 2560) } else { (2560, 640) }; - let dimensions = if routed { - vec![columns, rows, 512] - } else { - vec![columns, rows] - }; + let dimensions = if routed { vec![columns, rows, 512] } else { vec![columns, rows] }; let byte_length = matrix_bytes * if routed { 512 } else { 1 }; let tensor = ResolvedTensor { shard: 0, @@ -47,36 +43,20 @@ fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() (false, false) => &[LayerRole::FfnGateShared, LayerRole::FfnUpShared], (false, true) => &[LayerRole::FfnDownShared], }; - let experts: &[Option] = if routed { - &[Some(0), Some(1), Some(511)] - } else { - &[None] - }; + let experts: &[Option] = if routed { &[Some(0), Some(1), Some(511)] } else { &[None] }; for &layer_role in roles { - let role = TensorRole::Layer { - layer: 47, - role: layer_role, - }; + let role = TensorRole::Layer { layer: 47, role: layer_role }; for &expert in experts { let base = expert.unwrap_or(0) * matrix_bytes; - assert_eq!( - plan_stream_rows(&tensor, role, 0, rows, expert).unwrap(), - (base, matrix_bytes) - ); + assert_eq!(plan_stream_rows(&tensor, role, 0, rows, expert).unwrap(), (base, matrix_bytes)); // The literal legacy offsets cover every byte once, in order, // with no expert transition, tail, padding or hidden gap. for tile in 0..rows / 64 { let expected = (base + tile * tile_bytes, tile_bytes); assert_eq!(plan_rows(&tensor, tile * 64, 64, expert).unwrap(), expected); - assert_eq!( - plan_stream_rows(&tensor, role, tile * 64, 64, expert).unwrap(), - expected - ); + assert_eq!(plan_stream_rows(&tensor, role, tile * 64, 64, expert).unwrap(), expected); } - assert_eq!( - plan_row(&tensor, rows - 1, expert).unwrap(), - (base + matrix_bytes - stride, stride) - ); + assert_eq!(plan_row(&tensor, rows - 1, expert).unwrap(), (base + matrix_bytes - stride, stride)); for (first, count) in [ (0, 0), (0, 65), @@ -90,10 +70,7 @@ fn complete_moe_spans_match_literal_legacy_tiles_and_refuse_boundary_crossing() ] { assert!(plan_stream_rows(&tensor, role, first, count, expert).is_err()); } - let other_role = TensorRole::Layer { - layer: 47, - role: LayerRole::HcFfnNorm, - }; + let other_role = TensorRole::Layer { layer: 47, role: LayerRole::HcFfnNorm }; assert!(plan_stream_rows(&tensor, other_role, 0, rows, expert).is_err()); assert!(plan_rows(&tensor, 0, rows, expert).is_err()); diff --git a/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs index fe77d05d..9b3efdc3 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/capture_admit.rs @@ -3,19 +3,10 @@ #[allow(unused_imports)] use super::*; - -pub(super) fn capture_admit( - capacity: usize, - future: usize, - available: usize, -) -> Result<(), ResidentExpertSourceError> { - let headroom = - usize::try_from(FUTURE_HEADROOM).map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; +pub(super) fn capture_admit(capacity: usize, future: usize, available: usize) -> Result<(), ResidentExpertSourceError> { + let headroom = usize::try_from(FUTURE_HEADROOM).map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; if capacity as u64 > SOURCE_CAP - || capacity - .checked_add(future) - .and_then(|n| n.checked_add(headroom)) - .is_none_or(|n| n > available) + || capacity.checked_add(future).and_then(|n| n.checked_add(headroom)).is_none_or(|n| n > available) { return Err(ResidentExpertSourceError::MemoryAdmission); } @@ -26,11 +17,7 @@ pub(super) fn provisional_descriptor( index: &TensorIndex, role: TensorRole, ) -> Result { - let TensorRole::Layer { - layer, - role: layer_role, - } = role - else { + let TensorRole::Layer { layer, role: layer_role } = role else { return Err(ResidentExpertSourceError::Geometry); }; let suffix = match layer_role { @@ -46,11 +33,8 @@ pub(super) fn provisional_descriptor( .enumerate() .find(|(_, tensor)| tensor.name == name) .ok_or(ResidentExpertSourceError::Geometry)?; - let absolute_start = index - .summary - .data_start - .checked_add(tensor.offset) - .ok_or(ResidentExpertSourceError::Geometry)?; + let absolute_start = + index.summary.data_start.checked_add(tensor.offset).ok_or(ResidentExpertSourceError::Geometry)?; let resolved = ResolvedTensor { shard: 0, tensor_number, @@ -62,10 +46,7 @@ pub(super) fn provisional_descriptor( file_size: index.summary.file_size, }; let descriptor = checked_descriptor(role, &resolved)?; - if absolute_start - .checked_add(descriptor.bytes as u64) - .is_none_or(|n| n > descriptor.file_size) - { + if absolute_start.checked_add(descriptor.bytes as u64).is_none_or(|n| n > descriptor.file_size) { return Err(ResidentExpertSourceError::Geometry); } Ok(descriptor) diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs index 79329a85..9c4ba92e 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl ProvisionalExpertSource { pub(super) fn empty() -> Self { Self { @@ -54,12 +53,8 @@ impl ProvisionalExpertSource { if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { return Err(ResidentExpertSourceError::Geometry); } - self.cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; + self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; self.charged = self .cells .capacity() @@ -69,31 +64,18 @@ impl ProvisionalExpertSource { .ok_or(ResidentExpertSourceError::MemoryAdmission)?; // First geometry pass prevents allocation before complete closed layout. for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = self - .source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; + self.source_bytes = + self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; } } - let planned = self - .charged - .checked_add(self.source_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; self.observed = memory_available()?; capture_admit(planned, FUTURE_OWNERS, self.observed)?; let mut remaining = self.source_bytes; for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; for previous in &self.cells { let left = previous.descriptor.absolute_start; @@ -106,14 +88,10 @@ impl ProvisionalExpertSource { } capture_admit(remaining, FUTURE_OWNERS, memory_available()?)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(descriptor.bytes) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; let charged_bytes = bytes.capacity(); - self.charged = self - .charged - .checked_add(charged_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + self.charged = + self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; if self.charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); } @@ -193,15 +171,12 @@ impl ProvisionalExpertSource { let checked = (|| { for cell in &self.cells { if cell.covered != cell.bytes.len() - || provisional_descriptor(source.index(), cell.descriptor.role)? - != cell.descriptor + || provisional_descriptor(source.index(), cell.descriptor.role)? != cell.descriptor { return Err(ResidentExpertSourceError::Geometry); } } - source - .capture_source_identity() - .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error))) + source.capture_source_identity().map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error))) })(); match checked { Ok(identity) => self.source = Some(identity), diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs index be5a0a17..7e5c9193 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_2.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl ProvisionalExpertSource { pub(crate) fn prepare_incremental(index: &TensorIndex, retained_kar: Option<&File>) -> Self { let mut capture = Self::empty(); @@ -28,16 +27,10 @@ impl ProvisionalExpertSource { if index.summary.file_size != PINNED_IDENTITIES[0].0 || index.tensors.len() != 1223 { return Err(ResidentExpertSourceError::Geometry); } - self.cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; - self.banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + self.cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; + self.banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let mut incremental_cells = Vec::new(); - incremental_cells - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + incremental_cells.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; self.incremental = Some(IncrementalCapture { cells: incremental_cells, #[cfg(test)] @@ -49,50 +42,26 @@ impl ProvisionalExpertSource { .checked_mul(size_of::()) .and_then(|n| n.checked_add(self.banks.capacity().checked_mul(size_of::())?)) .and_then(|n| { - n.checked_add( - self.incremental - .as_ref()? - .cells - .capacity() - .checked_mul(size_of::())?, - ) + n.checked_add(self.incremental.as_ref()?.cells.capacity().checked_mul(size_of::())?) }) .and_then(|n| n.checked_add(size_of::() + size_of::())) .ok_or(ResidentExpertSourceError::MemoryAdmission)?; // First geometry pass prevents allocation before complete closed layout. for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - self.source_bytes = self - .source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; + self.source_bytes = + self.source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; } } - let planned = self - .charged - .checked_add(self.source_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let planned = self.charged.checked_add(self.source_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; self.observed = memory_available()?; capture_admit(planned, FUTURE_OWNERS, self.observed)?; let mut remaining = self.source_bytes; for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let descriptor = provisional_descriptor(index, TensorRole::Layer { layer, role })?; - for previous in &self - .incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)? - .cells - { + for previous in &self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.cells { let left = previous.descriptor.absolute_start; let right = left + previous.descriptor.bytes as u64; let start = descriptor.absolute_start; @@ -103,20 +72,14 @@ impl ProvisionalExpertSource { } // Reserved but untouched pages remain a full commitment. Unlike the // original zero-fill, reserve does not make them resident yet. - let committed = self - .charged - .checked_add(remaining) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let committed = + self.charged.checked_add(remaining).ok_or(ResidentExpertSourceError::MemoryAdmission)?; capture_admit(committed, FUTURE_OWNERS, memory_available()?)?; let mut bytes = Vec::new(); - bytes - .try_reserve_exact(descriptor.bytes) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + bytes.try_reserve_exact(descriptor.bytes).map_err(|_| ResidentExpertSourceError::Allocation)?; let charged_bytes = bytes.capacity(); - self.charged = self - .charged - .checked_add(charged_bytes) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + self.charged = + self.charged.checked_add(charged_bytes).ok_or(ResidentExpertSourceError::MemoryAdmission)?; if self.charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); } @@ -131,33 +94,21 @@ impl ProvisionalExpertSource { FUTURE_OWNERS, memory_available()?, )?; - self.incremental - .as_mut() - .ok_or(ResidentExpertSourceError::Geometry)? - .cells - .push(IncrementalTensor { - descriptor, - bytes, - charged_bytes, - covered: 0, - }); + self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.cells.push(IncrementalTensor { + descriptor, + bytes, + charged_bytes, + covered: 0, + }); remaining -= descriptor.bytes; } } capture_admit(self.charged, FUTURE_OWNERS, memory_available()?)?; Ok(()) } - pub(super) fn finish_incremental( - &mut self, - source: &VerifiedGgufFile, - ) -> Result<(), ResidentExpertSourceError> { - let incremental = self - .incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)?; - if !self.cells.is_empty() - || incremental.cells.len() != BANKS - || self.cells.capacity() < incremental.cells.len() + pub(super) fn finish_incremental(&mut self, source: &VerifiedGgufFile) -> Result<(), ResidentExpertSourceError> { + let incremental = self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?; + if !self.cells.is_empty() || incremental.cells.len() != BANKS || self.cells.capacity() < incremental.cells.len() { return Err(ResidentExpertSourceError::Geometry); } @@ -172,10 +123,7 @@ impl ProvisionalExpertSource { } // Original whole SHA/strict index completed before bind calls this. // Move only fully initialized spans into the unchanged opaque gate. - let incremental = self - .incremental - .take() - .ok_or(ResidentExpertSourceError::Geometry)?; + let incremental = self.incremental.take().ok_or(ResidentExpertSourceError::Geometry)?; for cell in incremental.cells { self.cells.push(CapturedTensor { descriptor: cell.descriptor, diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs index 7080a5d8..26f00c78 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_provisionalexpertsource_3.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[cfg(test)] impl ProvisionalExpertSource { pub(super) fn test_incremental_cells(index: &TensorIndex) -> Self { @@ -13,21 +12,13 @@ impl ProvisionalExpertSource { bytes.try_reserve_exact(original.descriptor.bytes).unwrap(); let charged_bytes = bytes.capacity(); capture.incremental = Some(IncrementalCapture { - cells: vec![IncrementalTensor { - descriptor: original.descriptor, - bytes, - charged_bytes, - covered: 0, - }], + cells: vec![IncrementalTensor { descriptor: original.descriptor, bytes, charged_bytes, covered: 0 }], test_available: Some(usize::MAX), }); capture } pub(super) fn test_remaining_commitment(&self) -> Result { - self.incremental - .as_ref() - .ok_or(ResidentExpertSourceError::Geometry)? - .remaining_commitment() + self.incremental.as_ref().ok_or(ResidentExpertSourceError::Geometry)?.remaining_commitment() } pub(super) fn test_observe_inner( &mut self, @@ -35,19 +26,14 @@ impl ProvisionalExpertSource { chunk: &[u8], available: impl FnMut() -> Result, ) -> Result<(), ResidentExpertSourceError> { - self.incremental - .as_mut() - .ok_or(ResidentExpertSourceError::Geometry)? - .observe_inner(position, chunk, available) + self.incremental.as_mut().ok_or(ResidentExpertSourceError::Geometry)?.observe_inner(position, chunk, available) } pub(super) fn test_incremental_bytes(&self) -> Option<&[u8]> { self.incremental .as_ref()? .cells .first() - .filter(|cell| { - cell.covered == cell.descriptor.bytes && cell.bytes.len() == cell.descriptor.bytes - }) + .filter(|cell| cell.covered == cell.descriptor.bytes && cell.bytes.len() == cell.descriptor.bytes) .map(|cell| cell.bytes.as_slice()) } pub(super) fn test_incremental_mint( @@ -58,10 +44,7 @@ impl ProvisionalExpertSource { if self.error.is_some() { return Err("failed capture".into()); } - let mut incremental = self - .incremental - .take() - .ok_or("missing incremental capture")?; + let mut incremental = self.incremental.take().ok_or("missing incremental capture")?; if incremental.cells.len() != 1 { return Err("not one fixture span".into()); } diff --git a/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs index 1fa090f1..61f3c04b 100644 --- a/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp_digest_capture/impl_qwen4expartifact.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Qwen4ExpArtifact { /// Same-FD full digest/index, with non-consumable optional expert capture. /// `retained_kar` is an observational owned FD, never KAR admission. @@ -29,10 +28,7 @@ impl Qwen4ExpArtifact { if let Some(error) = capture.error.take() { return Err(error); } - if capture.cells.len() != BANKS - || !capture.banks.is_empty() - || capture.charged as u64 > SOURCE_CAP - { + if capture.cells.len() != BANKS || !capture.banks.is_empty() || capture.charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::Geometry); } let identity = capture.source.ok_or(ResidentExpertSourceError::Geometry)?; @@ -42,10 +38,7 @@ impl Qwen4ExpArtifact { // Revalidate EVERY bound descriptor before minting even the first final // tensor. Full finite admission still happens at each selected role. for (number, cell) in capture.cells.iter().enumerate() { - let resolved = self - .roles - .get(&cell.descriptor.role) - .ok_or(ResidentExpertSourceError::Geometry)?; + let resolved = self.roles.get(&cell.descriptor.role).ok_or(ResidentExpertSourceError::Geometry)?; if slot(cell.descriptor.role).map_err(ResidentExpertSourceError::Read)? != number || checked_descriptor(cell.descriptor.role, resolved)? != cell.descriptor || cell.covered != cell.bytes.len() @@ -59,10 +52,7 @@ impl Qwen4ExpArtifact { // Existing captured Boxes stay in place. Charge only the new small // shared owners/directory before any wrapping/publication. let retention = retention_metadata_bytes()?; - capture.charged = capture - .charged - .checked_add(retention) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + capture.charged = capture.charged.checked_add(retention).ok_or(ResidentExpertSourceError::MemoryAdmission)?; if capture.charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); } @@ -70,17 +60,9 @@ impl Qwen4ExpArtifact { capture_admit(retention, 0, observed)?; // payload pages already resident for cell in capture.cells { let tensor = self.shards[0] - .admit_captured_tensor( - identity, - cell.descriptor.tensor_number, - cell.bytes, - cell.charged_bytes, - ) + .admit_captured_tensor(identity, cell.descriptor.tensor_number, cell.bytes, cell.charged_bytes) .map_err(|error| ResidentExpertSourceError::Read(BindingError::Io(error)))?; - capture.banks.push(Bank { - descriptor: cell.descriptor, - tensor: tensor.into_retained(), - }); + capture.banks.push(Bank { descriptor: cell.descriptor, tensor: tensor.into_retained() }); } capture_admit(0, 0, memory_available()?)?; let report = ResidentExpertSourceReport { @@ -110,10 +92,7 @@ impl ProvisionalExpertSource { pub(crate) fn test_cells(index: &TensorIndex) -> Self { let tensor = &index.tensors[0]; let descriptor = BankDescriptor { - role: TensorRole::Layer { - layer: 0, - role: LayerRole::FfnGateExperts, - }, + role: TensorRole::Layer { layer: 0, role: LayerRole::FfnGateExperts }, tensor_number: 0, raw_kind: tensor.kind, absolute_start: index.summary.data_start + tensor.offset, @@ -130,10 +109,7 @@ impl ProvisionalExpertSource { capture } pub(crate) fn test_bytes(&self) -> Option<&[u8]> { - self.cells - .first() - .filter(|cell| cell.covered == cell.bytes.len()) - .map(|cell| &*cell.bytes) + self.cells.first().filter(|cell| cell.covered == cell.bytes.len()).map(|cell| &*cell.bytes) } pub(crate) fn test_discarded(&self) -> bool { self.error.is_some() && self.cells.is_empty() @@ -154,12 +130,7 @@ impl ProvisionalExpertSource { return Err("incomplete capture".into()); } let identity = source.capture_source_identity()?; - source.admit_captured_tensor( - identity, - cell.descriptor.tensor_number, - cell.bytes, - cell.charged_bytes, - ) + source.admit_captured_tensor(identity, cell.descriptor.tensor_number, cell.bytes, cell.charged_bytes) } } impl IncrementalCapture { @@ -183,27 +154,20 @@ impl IncrementalCapture { chunk: &[u8], mut available: impl FnMut() -> Result, ) -> Result<(), ResidentExpertSourceError> { - let end = position - .checked_add(chunk.len() as u64) - .ok_or(ResidentExpertSourceError::Geometry)?; + let end = position.checked_add(chunk.len() as u64).ok_or(ResidentExpertSourceError::Geometry)?; let mut remaining = self.remaining_commitment()?; for cell in &mut self.cells { let start = cell.descriptor.absolute_start; - let bank_end = start - .checked_add(cell.descriptor.bytes as u64) - .ok_or(ResidentExpertSourceError::Geometry)?; + let bank_end = + start.checked_add(cell.descriptor.bytes as u64).ok_or(ResidentExpertSourceError::Geometry)?; let left = start.max(position); let right = bank_end.min(end); if left >= right { continue; } - let offset = - usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; - let count = - usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; - let next = offset - .checked_add(count) - .ok_or(ResidentExpertSourceError::Geometry)?; + let offset = usize::try_from(left - start).map_err(|_| ResidentExpertSourceError::Geometry)?; + let count = usize::try_from(right - left).map_err(|_| ResidentExpertSourceError::Geometry)?; + let next = offset.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?; if offset != cell.covered || offset != cell.bytes.len() || next > cell.descriptor.bytes @@ -211,21 +175,13 @@ impl IncrementalCapture { { return Err(ResidentExpertSourceError::Geometry); } - let source = usize::try_from(left - position) - .map_err(|_| ResidentExpertSourceError::Geometry)?; + let source = usize::try_from(left - position).map_err(|_| ResidentExpertSourceError::Geometry)?; let selected = chunk - .get( - source - ..source - .checked_add(count) - .ok_or(ResidentExpertSourceError::Geometry)?, - ) + .get(source..source.checked_add(count).ok_or(ResidentExpertSourceError::Geometry)?) .ok_or(ResidentExpertSourceError::Geometry)?; // Actual snapshot immediately BEFORE touching this span. All other // reserved banks and capacity slack stay committed; no VM credit. - let next_remaining = remaining - .checked_sub(count) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let next_remaining = remaining.checked_sub(count).ok_or(ResidentExpertSourceError::MemoryAdmission)?; capture_admit(remaining, FUTURE_OWNERS, available()?)?; cell.bytes.extend_from_slice(selected); // proven within reservation cell.covered = next; diff --git a/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs b/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs index 830eac67..66959942 100644 --- a/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs +++ b/crates/model-format/src/qwen4exp_digest_capture_incremental_sdet.rs @@ -11,24 +11,17 @@ struct Fixture { } impl Fixture { fn new() -> Self { - let nonce = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let directory = std::env::temp_dir().join(format!( - "strata-incremental-bank-{}-{nonce}", - std::process::id() - )); + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let directory = std::env::temp_dir().join(format!("strata-incremental-bank-{}-{nonce}", std::process::id())); std::fs::create_dir(&directory).unwrap(); let path = directory.join("public.gguf"); let mut bytes = b"GGUF".to_vec(); bytes.extend(3u32.to_le_bytes()); bytes.extend(2u64.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); - for (name, elements, offset) in [ - (b"public.first".as_slice(), 16u64, 0u64), - (b"public.second".as_slice(), 24, 64), - ] { + for (name, elements, offset) in + [(b"public.first".as_slice(), 16u64, 0u64), (b"public.second".as_slice(), 24, 64)] + { bytes.extend((name.len() as u64).to_le_bytes()); bytes.extend(name); bytes.extend(1u32.to_le_bytes()); @@ -37,25 +30,14 @@ impl Fixture { bytes.extend(offset.to_le_bytes()); } bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0u32, 0x80000000, 0x3f800000, 0xbf800000] - .into_iter() - .cycle() - .take(40) - { + for word in [0u32, 0x80000000, 0x3f800000, 0xbf800000].into_iter().cycle().take(40) { bytes.extend(word.to_le_bytes()); } std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - bytes, - } + Self { directory, path, bytes } } fn digest(&self) -> String { - let hex: String = Sha256::digest(&self.bytes) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(); + let hex: String = Sha256::digest(&self.bytes).iter().map(|byte| format!("{byte:02x}")).collect(); format!("sha256:{hex}") } } @@ -69,10 +51,7 @@ fn two_spans(index: &gguf::TensorIndex) -> ProvisionalExpertSource { let mut capture = ProvisionalExpertSource::test_incremental_cells(index); let tensor = &index.tensors[1]; let descriptor = BankDescriptor { - role: TensorRole::Layer { - layer: 1, - role: LayerRole::FfnGateExperts, - }, + role: TensorRole::Layer { layer: 1, role: LayerRole::FfnGateExperts }, tensor_number: 1, raw_kind: tensor.kind, absolute_start: index.summary.data_start + tensor.offset, @@ -82,17 +61,12 @@ fn two_spans(index: &gguf::TensorIndex) -> ProvisionalExpertSource { let mut bytes = Vec::new(); bytes.try_reserve_exact(descriptor.bytes).unwrap(); let charged_bytes = bytes.capacity(); - capture - .incremental - .as_mut() - .unwrap() - .cells - .push(IncrementalTensor { - descriptor, - bytes, - charged_bytes, - covered: 0, - }); + capture.incremental.as_mut().unwrap().cells.push(IncrementalTensor { + descriptor, + bytes, + charged_bytes, + covered: 0, + }); capture } @@ -102,12 +76,7 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() // ORIGINAL strict whole SHA/index + real FD stream FIRST, with the old // zeroed destination and copy ordering, before constructing the candidate. let mut original = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - let extents: Vec<_> = original - .index() - .tensors - .iter() - .map(|tensor| tensor.bytes) - .collect(); + let extents: Vec<_> = original.index().tensors.iter().map(|tensor| tensor.bytes).collect(); let mut expected = Vec::new(); for (number, extent) in extents.into_iter().enumerate() { let mut zeroed = vec![0; extent as usize]; @@ -130,66 +99,30 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() // snapshot is only a numeric fixture input, never a physical/model proof. for width in [1usize, 7, 63, 64, 65, fixture.bytes.len() + 1] { let mut capture = two_spans(index); - let pointers: Vec<_> = capture - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .map(|cell| cell.bytes.as_ptr()) - .collect(); - let capacities: Vec<_> = capture - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .map(|cell| cell.bytes.capacity()) - .collect(); - assert!( - capture - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .all(|cell| cell.bytes.is_empty()) - ); - assert_eq!( - capture.test_remaining_commitment().unwrap(), - capacities.iter().sum::() - ); + let pointers: Vec<_> = + capture.incremental.as_ref().unwrap().cells.iter().map(|cell| cell.bytes.as_ptr()).collect(); + let capacities: Vec<_> = + capture.incremental.as_ref().unwrap().cells.iter().map(|cell| cell.bytes.capacity()).collect(); + assert!(capture.incremental.as_ref().unwrap().cells.iter().all(|cell| cell.bytes.is_empty())); + assert_eq!(capture.test_remaining_commitment().unwrap(), capacities.iter().sum::()); capture.observe(0, &[]); for (number, part) in fixture.bytes.chunks(width).enumerate() { capture.observe((number * width) as u64, part); } - for (number, cell) in capture - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .enumerate() - { + for (number, cell) in capture.incremental.as_ref().unwrap().cells.iter().enumerate() { assert_eq!(cell.bytes, expected[number]); assert_eq!(cell.covered, cell.descriptor.bytes); assert_eq!(cell.bytes.capacity(), capacities[number]); assert_eq!(cell.bytes.as_ptr(), pointers[number]); // no growth/copy } - assert_eq!( - capture.test_remaining_commitment().unwrap(), - capacities.iter().sum::() - 160 - ); + assert_eq!(capture.test_remaining_commitment().unwrap(), capacities.iter().sum::() - 160); } let start = index.summary.data_start; let payload = &fixture.bytes[start as usize..]; let mut partial = ProvisionalExpertSource::test_incremental_cells(index); partial.observe(start, &payload[..31]); - assert_eq!( - partial.incremental.as_ref().unwrap().cells[0].bytes, - expected[0][..31] - ); + assert_eq!(partial.incremental.as_ref().unwrap().cells[0].bytes, expected[0][..31]); assert!(partial.test_incremental_bytes().is_none()); assert!(partial.test_incremental_mint(&mut original).is_err()); // len==covered isn't full @@ -198,64 +131,21 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() let untouched = admitted.test_remaining_commitment().unwrap(); let headroom = usize::try_from(FUTURE_HEADROOM).unwrap(); let exact = untouched + FUTURE_OWNERS + headroom; - let before: Vec<_> = admitted - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .map(|cell| cell.bytes.as_ptr()) - .collect(); + let before: Vec<_> = admitted.incremental.as_ref().unwrap().cells.iter().map(|cell| cell.bytes.as_ptr()).collect(); let error = admitted.test_observe_inner(start, &payload[..31], || Ok(exact - 1)); - assert!(matches!( - error, - Err(ResidentExpertSourceError::MemoryAdmission) - )); - assert!( - admitted - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .all(|cell| cell.bytes.is_empty()) - ); + assert!(matches!(error, Err(ResidentExpertSourceError::MemoryAdmission))); + assert!(admitted.incremental.as_ref().unwrap().cells.iter().all(|cell| cell.bytes.is_empty())); assert_eq!(admitted.test_remaining_commitment().unwrap(), untouched); - admitted - .test_observe_inner(start, &payload[..31], || Ok(exact)) - .unwrap(); - assert_eq!( - admitted.test_remaining_commitment().unwrap(), - untouched - 31 - ); - let saved = admitted.incremental.as_ref().unwrap().cells[0] - .bytes - .clone(); + admitted.test_observe_inner(start, &payload[..31], || Ok(exact)).unwrap(); + assert_eq!(admitted.test_remaining_commitment().unwrap(), untouched - 31); + let saved = admitted.incremental.as_ref().unwrap().cells[0].bytes.clone(); let late = admitted.test_observe_inner(start + 31, &payload[31..64], || Ok(exact - 31 - 1)); - assert!(matches!( - late, - Err(ResidentExpertSourceError::MemoryAdmission) - )); + assert!(matches!(late, Err(ResidentExpertSourceError::MemoryAdmission))); assert_eq!(admitted.incremental.as_ref().unwrap().cells[0].bytes, saved); // refusal before new touch - admitted - .test_observe_inner(start + 31, &payload[31..64], || Ok(exact - 31)) - .unwrap(); - assert_eq!( - admitted.incremental.as_ref().unwrap().cells[0].bytes, - expected[0] - ); - assert_eq!( - admitted.incremental.as_ref().unwrap().cells[0] - .bytes - .as_ptr(), - before[0] - ); - assert_eq!( - admitted.incremental.as_ref().unwrap().cells[1] - .bytes - .as_ptr(), - before[1] - ); + admitted.test_observe_inner(start + 31, &payload[31..64], || Ok(exact - 31)).unwrap(); + assert_eq!(admitted.incremental.as_ref().unwrap().cells[0].bytes, expected[0]); + assert_eq!(admitted.incremental.as_ref().unwrap().cells[0].bytes.as_ptr(), before[0]); + assert_eq!(admitted.incremental.as_ref().unwrap().cells[1].bytes.as_ptr(), before[1]); let mut checks = 0; admitted .test_observe_inner(start + 64, &payload[64..], || { @@ -264,10 +154,7 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() }) .unwrap(); assert_eq!(checks, 1); - assert_eq!( - admitted.incremental.as_ref().unwrap().cells[1].bytes, - expected[1] - ); + assert_eq!(admitted.incremental.as_ref().unwrap().cells[1].bytes, expected[1]); drop(admitted); for (position, selected) in [(start + 1, &payload[1..5]), (u64::MAX, &payload[..2])] { @@ -280,48 +167,22 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() repeated.observe(start, &payload[..4]); assert!(repeated.test_discarded()); let mut failed_snapshot = two_spans(index); - let failure = failed_snapshot.test_observe_inner(start, payload, || { - Err(ResidentExpertSourceError::MemoryAdmission) - }); - assert!(matches!( - failure, - Err(ResidentExpertSourceError::MemoryAdmission) - )); - assert!( - failed_snapshot - .incremental - .as_ref() - .unwrap() - .cells - .iter() - .all(|cell| cell.bytes.is_empty()) - ); + let failure = + failed_snapshot.test_observe_inner(start, payload, || Err(ResidentExpertSourceError::MemoryAdmission)); + assert!(matches!(failure, Err(ResidentExpertSourceError::MemoryAdmission))); + assert!(failed_snapshot.incremental.as_ref().unwrap().cells.iter().all(|cell| cell.bytes.is_empty())); failed_snapshot.fail(ResidentExpertSourceError::MemoryAdmission); assert!(failed_snapshot.test_discarded()); let mut crossing = two_spans(index); let mut snapshots = 0; let later_error = crossing.test_observe_inner(start, payload, || { snapshots += 1; - if snapshots == 1 { - Ok(exact) - } else { - Err(ResidentExpertSourceError::MemoryAdmission) - } + if snapshots == 1 { Ok(exact) } else { Err(ResidentExpertSourceError::MemoryAdmission) } }); - assert!(matches!( - later_error, - Err(ResidentExpertSourceError::MemoryAdmission) - )); + assert!(matches!(later_error, Err(ResidentExpertSourceError::MemoryAdmission))); assert_eq!(snapshots, 2); - assert_eq!( - crossing.incremental.as_ref().unwrap().cells[0].bytes, - expected[0] - ); - assert!( - crossing.incremental.as_ref().unwrap().cells[1] - .bytes - .is_empty() - ); + assert_eq!(crossing.incremental.as_ref().unwrap().cells[0].bytes, expected[0]); + assert!(crossing.incremental.as_ref().unwrap().cells[1].bytes.is_empty()); crossing.fail(ResidentExpertSourceError::MemoryAdmission); assert!(crossing.test_discarded()); // actual wrapper drops partial owners @@ -330,38 +191,18 @@ fn original_zeroed_stream_first_incremental_spans_bytes_commitment_and_refusal() let mut full = ProvisionalExpertSource::test_incremental_cells(index); full.observe(start, &payload[..64]); let resident = full.test_incremental_mint(&mut original).unwrap(); - assert_eq!( - &*original - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .unwrap(), - &expected[0] - ); + assert_eq!(&*original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).unwrap(), &expected[0]); let foreign = VerifiedGgufFile::open(&fixture.path, &fixture.digest()).unwrap(); - assert!( - foreign - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .is_err() - ); + assert!(foreign.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); let wrong = format!("sha256:{}", "0".repeat(64)); - let old_error = VerifiedGgufFile::open(&fixture.path, &wrong) - .unwrap_err() - .to_string(); + let old_error = VerifiedGgufFile::open(&fixture.path, &wrong).unwrap_err().to_string(); let capture_error = match gguf::open_incremental_expert_capture(&fixture.path, &wrong, None) { Err(error) => error.to_string(), Ok(_) => panic!("wrong whole SHA must refuse"), }; assert_eq!(old_error, capture_error); // deferred capture cannot outrank SHA - std::fs::OpenOptions::new() - .write(true) - .open(&fixture.path) - .unwrap() - .set_len(1) - .unwrap(); - assert!( - original - .copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()) - .is_err() - ); + std::fs::OpenOptions::new().write(true).open(&fixture.path).unwrap().set_len(1).unwrap(); + assert!(original.copy_resident_tensor(&resident, 0, vec![0; 64].into_boxed_slice()).is_err()); drop(resident); drop(foreign); drop(index_owner); diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs index cdbe1f6f..12443d0e 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact.rs @@ -6,9 +6,7 @@ use super::*; impl Qwen4ExpArtifact { /// Explicit fresh-owner load; called before publishing a selected binding. /// No tensor finite admission is performed on unused expert banks. - pub fn load_resident_expert_source( - &mut self, - ) -> Result { + pub fn load_resident_expert_source(&mut self) -> Result { if self.resident_experts.is_some() { return Err(ResidentExpertSourceError::AlreadyEnabled); } @@ -16,12 +14,9 @@ impl Qwen4ExpArtifact { return Err(ResidentExpertSourceError::Geometry); } let mut plan = Vec::new(); - plan.try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + plan.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let mut banks = Vec::new(); - banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let metadata = plan .capacity() .checked_mul(size_of::()) @@ -31,26 +26,15 @@ impl Qwen4ExpArtifact { .ok_or(ResidentExpertSourceError::Geometry)?; let mut source_bytes = 0usize; for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let role = TensorRole::Layer { layer, role }; - let tensor = self - .roles - .get(&role) - .ok_or(ResidentExpertSourceError::Geometry)?; + let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; + source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; plan.push(descriptor); } } - let planned = source_bytes - .checked_add(metadata) - .ok_or(ResidentExpertSourceError::Geometry)?; + let planned = source_bytes.checked_add(metadata).ok_or(ResidentExpertSourceError::Geometry)?; let observed = memory_available()?; admit(planned, observed)?; let mut charged = metadata; @@ -59,33 +43,25 @@ impl Qwen4ExpArtifact { // The current snapshot reflects already initialized bank pages too. admit(remaining, memory_available()?)?; let ceiling = usize::try_from( - SOURCE_CAP - .checked_sub(charged as u64) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?, + SOURCE_CAP.checked_sub(charged as u64).ok_or(ResidentExpertSourceError::MemoryAdmission)?, ) .map_err(|_| ResidentExpertSourceError::MemoryAdmission)?; - let tensor = self.shards[0] - .load_resident_tensor(descriptor.tensor_number, ceiling) - .map_err(|error| match error { - gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, - gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, - gguf::ResidentLoadError::Source(error) => { - ResidentExpertSourceError::Read(BindingError::Io(error)) - } - })?; - charged = charged - .checked_add(tensor.charged_bytes()) - .ok_or(ResidentExpertSourceError::MemoryAdmission)?; + let tensor = + self.shards[0].load_resident_tensor(descriptor.tensor_number, ceiling).map_err( + |error| match error { + gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, + gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, + gguf::ResidentLoadError::Source(error) => { + ResidentExpertSourceError::Read(BindingError::Io(error)) + } + }, + )?; + charged = charged.checked_add(tensor.charged_bytes()).ok_or(ResidentExpertSourceError::MemoryAdmission)?; if charged as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); } - remaining = remaining - .checked_sub(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; - banks.push(Bank { - descriptor, - tensor: tensor.into_retained(), - }); + remaining = remaining.checked_sub(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; + banks.push(Bank { descriptor, tensor: tensor.into_retained() }); } // Bank publication itself retains the same current-source refusal. let last = banks.last().ok_or(ResidentExpertSourceError::Geometry)?; @@ -126,9 +102,7 @@ impl Qwen4ExpArtifact { /// experts that are used and can give the memory back. The bytes are the verified file's, so every consumer /// sees exactly what the resident copy would hold. No `MemAvailable` admission: the mapping commits no RAM. #[cfg(any(target_os = "linux", windows))] - pub fn load_mapped_expert_source( - &mut self, - ) -> Result { + pub fn load_mapped_expert_source(&mut self) -> Result { if self.resident_experts.is_some() { return Err(ResidentExpertSourceError::AlreadyEnabled); } @@ -136,31 +110,19 @@ impl Qwen4ExpArtifact { return Err(ResidentExpertSourceError::Geometry); } let mut banks = Vec::new(); - banks - .try_reserve_exact(BANKS) - .map_err(|_| ResidentExpertSourceError::Allocation)?; + banks.try_reserve_exact(BANKS).map_err(|_| ResidentExpertSourceError::Allocation)?; let mut source_bytes = 0usize; for layer in 0..48 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let role = TensorRole::Layer { layer, role }; - let tensor = self - .roles - .get(&role) - .ok_or(ResidentExpertSourceError::Geometry)?; + let tensor = self.roles.get(&role).ok_or(ResidentExpertSourceError::Geometry)?; let descriptor = checked_descriptor(role, tensor)?; - source_bytes = source_bytes - .checked_add(descriptor.bytes) - .ok_or(ResidentExpertSourceError::Geometry)?; + source_bytes = source_bytes.checked_add(descriptor.bytes).ok_or(ResidentExpertSourceError::Geometry)?; if source_bytes as u64 > SOURCE_CAP { return Err(ResidentExpertSourceError::MemoryAdmission); } - let mapped = self.shards[0] - .map_resident_tensor(descriptor.tensor_number) - .map_err(|error| match error { + let mapped = + self.shards[0].map_resident_tensor(descriptor.tensor_number).map_err(|error| match error { gguf::ResidentLoadError::Allocation => ResidentExpertSourceError::Allocation, gguf::ResidentLoadError::Budget => ResidentExpertSourceError::MemoryAdmission, gguf::ResidentLoadError::Source(error) => { @@ -170,10 +132,7 @@ impl Qwen4ExpArtifact { if mapped.len() != descriptor.bytes { return Err(ResidentExpertSourceError::Geometry); } - banks.push(Bank { - descriptor, - tensor: mapped.into_retained(), - }); + banks.push(Bank { descriptor, tensor: mapped.into_retained() }); } } if banks.len() != BANKS { @@ -217,9 +176,7 @@ impl ResidentExpertBankLease { } pub fn retention_metadata_bytes(&self) -> usize { // Complete lease was minted only after this checked closed bound. - BANKS * gguf::ResidentTensor::retention_metadata_bytes() - + size_of::>() - + 2 * size_of::() + BANKS * gguf::ResidentTensor::retention_metadata_bytes() + size_of::>() + 2 * size_of::() } } impl ResidentExpertBankMember { @@ -245,8 +202,6 @@ impl ResidentExpertBankMember { slot(self.descriptor.role) .ok() .and_then(|n| lease.banks.get(n)) - .is_some_and(|bank| { - bank.descriptor == self.descriptor && Rc::ptr_eq(&bank.tensor, &self.tensor) - }) + .is_some_and(|bank| bank.descriptor == self.descriptor && Rc::ptr_eq(&bank.tensor, &self.tensor)) } } diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs index f8d7578a..d0710d43 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/impl_qwen4expartifact_2.rs @@ -6,33 +6,21 @@ use super::*; impl Qwen4ExpArtifact { /// Short actual artifact borrow; result owns all144 existing allocations. pub fn resident_expert_bank_lease(&self) -> Result { - let bank = self - .resident_experts - .as_ref() - .ok_or(BindingError::Role("resident_expert_source_absent"))?; - if bank.banks.len() != BANKS - || bank.report.bank_count != BANKS as u32 - || bank.report.charged_bytes > SOURCE_CAP + let bank = self.resident_experts.as_ref().ok_or(BindingError::Role("resident_expert_source_absent"))?; + if bank.banks.len() != BANKS || bank.report.bank_count != BANKS as u32 || bank.report.charged_bytes > SOURCE_CAP { return Err(BindingError::Geometry("resident_expert_directory")); } for (number, member) in bank.banks.iter().enumerate() { - let tensor = self - .roles - .get(&member.descriptor.role) - .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; + let tensor = + self.roles.get(&member.descriptor.role).ok_or(BindingError::Geometry("resident_expert_descriptor"))?; if slot(member.descriptor.role)? != number { return Err(BindingError::Geometry("resident_expert_directory")); } bank.tensor(member.descriptor.role, tensor)?; - self.shards[0] - .validate_retained_tensor(&member.tensor) - .map_err(BindingError::Io)?; + self.shards[0].validate_retained_tensor(&member.tensor).map_err(BindingError::Io)?; } - Ok(ResidentExpertBankLease { - banks: Rc::clone(&bank.banks), - report: bank.report(), - }) + Ok(ResidentExpertBankLease { banks: Rc::clone(&bank.banks), report: bank.report() }) } /// Rechecks real catalog membership/current sameFD before releasing borrow. pub fn resident_expert_bank_member( @@ -41,28 +29,17 @@ impl Qwen4ExpArtifact { layer: u8, role: LayerRole, ) -> Result { - let bank = self - .resident_experts - .as_ref() - .ok_or(BindingError::Role("resident_expert_source_absent"))?; + let bank = self.resident_experts.as_ref().ok_or(BindingError::Role("resident_expert_source_absent"))?; if !Rc::ptr_eq(&bank.banks, &lease.banks) || lease.banks.len() != BANKS { return Err(BindingError::Geometry("resident_expert_directory")); } let role = TensorRole::Layer { layer, role }; let number = slot(role)?; - let resolved = self - .roles - .get(&role) - .ok_or(BindingError::Geometry("resident_expert_descriptor"))?; + let resolved = self.roles.get(&role).ok_or(BindingError::Geometry("resident_expert_descriptor"))?; bank.tensor(role, resolved)?; let member = &lease.banks[number]; - self.shards[0] - .validate_retained_tensor(&member.tensor) - .map_err(BindingError::Io)?; - Ok(ResidentExpertBankMember { - descriptor: member.descriptor, - tensor: Rc::clone(&member.tensor), - }) + self.shards[0].validate_retained_tensor(&member.tensor).map_err(BindingError::Io)?; + Ok(ResidentExpertBankMember { descriptor: member.descriptor, tensor: Rc::clone(&member.tensor) }) } } impl ResidentExpertBankSpan { @@ -87,8 +64,7 @@ impl ResidentExpertBankSpan { self.member.file_mapped() } pub fn belongs_to(&self, member: &ResidentExpertBankMember) -> bool { - self.member.descriptor == member.descriptor - && Rc::ptr_eq(&self.member.tensor, &member.tensor) + self.member.descriptor == member.descriptor && Rc::ptr_eq(&self.member.tensor, &member.tensor) } } impl ResidentExpertBank { @@ -102,32 +78,16 @@ impl ResidentExpertBank { return Err(BindingError::Range("resident_expert")); } self.tensor(role, tensor)?; - let rows = if matches!( - role, - TensorRole::Layer { - role: LayerRole::FfnDownExperts, - .. - } - ) { - 2560 - } else { - 640 - }; + let rows = if matches!(role, TensorRole::Layer { role: LayerRole::FfnDownExperts, .. }) { 2560 } else { 640 }; let (offset, length) = plan_stream_rows(tensor, role, 0, rows, Some(u64::from(expert)))?; let offset = usize::try_from(offset).map_err(|_| BindingError::Range("resident_expert"))?; let length = usize::try_from(length).map_err(|_| BindingError::Range("resident_expert"))?; let bank = &self.banks[slot(role)?]; - if offset - .checked_add(length) - .is_none_or(|end| end > bank.tensor.retained_bytes().len()) - { + if offset.checked_add(length).is_none_or(|end| end > bank.tensor.retained_bytes().len()) { return Err(BindingError::Range("resident_expert")); } Ok(ResidentExpertBankSpan { - member: ResidentExpertBankMember { - descriptor: bank.descriptor, - tensor: Rc::clone(&bank.tensor), - }, + member: ResidentExpertBankMember { descriptor: bank.descriptor, tensor: Rc::clone(&bank.tensor) }, expert, offset, length, diff --git a/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs index 6ee88a5f..3aa3a194 100644 --- a/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs +++ b/crates/model-format/src/qwen4exp_expert_source_bank/retention_metadata_bytes.rs @@ -23,26 +23,17 @@ pub(super) fn checked_descriptor( ) -> Result { use LayerRole as L; let (columns, rows, kinds): (u64, u64, &[u32]) = match role { - TensorRole::Layer { - layer, - role: L::FfnGateExperts | L::FfnUpExperts, - } if layer < 48 => (2560, 640, &[18, 21, 22, 23]), - TensorRole::Layer { - layer, - role: L::FfnDownExperts, - } if layer < 48 => (640, 2560, &[20, 42]), + TensorRole::Layer { layer, role: L::FfnGateExperts | L::FfnUpExperts } if layer < 48 => { + (2560, 640, &[18, 21, 22, 23]) + } + TensorRole::Layer { layer, role: L::FfnDownExperts } if layer < 48 => (640, 2560, &[20, 42]), _ => return Err(ResidentExpertSourceError::Geometry), }; - if tensor.shard != 0 - || tensor.dimensions != [columns, rows, 512] - || !kinds.contains(&tensor.kind) - { + if tensor.shard != 0 || tensor.dimensions != [columns, rows, 512] || !kinds.contains(&tensor.kind) { return Err(ResidentExpertSourceError::Geometry); } - let first = plan_stream_rows(tensor, role, 0, rows, Some(0)) - .map_err(|_| ResidentExpertSourceError::Geometry)?; - let last = plan_stream_rows(tensor, role, 0, rows, Some(511)) - .map_err(|_| ResidentExpertSourceError::Geometry)?; + let first = plan_stream_rows(tensor, role, 0, rows, Some(0)).map_err(|_| ResidentExpertSourceError::Geometry)?; + let last = plan_stream_rows(tensor, role, 0, rows, Some(511)).map_err(|_| ResidentExpertSourceError::Geometry)?; if first.0 != 0 || first.1 == 0 || first.1.checked_mul(512) != Some(tensor.byte_length) @@ -58,8 +49,7 @@ pub(super) fn checked_descriptor( raw_kind: tensor.kind, absolute_start: tensor.absolute_start, file_size: tensor.file_size, - bytes: usize::try_from(tensor.byte_length) - .map_err(|_| ResidentExpertSourceError::Geometry)?, + bytes: usize::try_from(tensor.byte_length).map_err(|_| ResidentExpertSourceError::Geometry)?, }) } pub(super) fn slot(role: TensorRole) -> Result { @@ -93,10 +83,15 @@ pub(super) fn memory_available() -> Result { } #[cfg(windows)] { - let (total, available) = leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; - parse_memory_available(&format!("MemTotal: {} kB + let (total, available) = + leleka_libc_shim::physical_memory().ok_or(ResidentExpertSourceError::MemoryAdmission)?; + parse_memory_available(&format!( + "MemTotal: {} kB MemAvailable: {} kB -", total / 1024, available / 1024)) +", + total / 1024, + available / 1024 + )) } #[cfg(not(any(target_os = "linux", windows)))] { @@ -126,11 +121,7 @@ pub(super) fn parse_memory_available(text: &str) -> Result Result Result<(), ResidentExpertSourceError> { if capacity as u64 > SOURCE_CAP - || (capacity as u64) - .checked_add(FUTURE_HEADROOM) - .is_none_or(|n| n > available as u64) + || (capacity as u64).checked_add(FUTURE_HEADROOM).is_none_or(|n| n > available as u64) { return Err(ResidentExpertSourceError::MemoryAdmission); } @@ -159,10 +148,8 @@ pub(crate) fn test_resident_source_memory_admission( } impl ResidentExpertBank { pub(in super::super) fn note_copy(&self, bytes: usize) { - self.copied_spans - .set(self.copied_spans.get().saturating_add(1)); - self.copied_bytes - .set(self.copied_bytes.get().saturating_add(bytes as u64)); + self.copied_spans.set(self.copied_spans.get().saturating_add(1)); + self.copied_bytes.set(self.copied_bytes.get().saturating_add(bytes as u64)); } pub(super) fn report(&self) -> ResidentExpertSourceReport { ResidentExpertSourceReport { @@ -176,12 +163,9 @@ impl ResidentExpertBank { role: TensorRole, tensor: &ResolvedTensor, ) -> Result<&gguf::ResidentTensor, BindingError> { - let descriptor = checked_descriptor(role, tensor) - .map_err(|_| BindingError::Geometry("resident_expert_descriptor"))?; - let bank = self - .banks - .get(slot(role)?) - .ok_or(BindingError::Geometry("resident_expert_directory"))?; + let descriptor = + checked_descriptor(role, tensor).map_err(|_| BindingError::Geometry("resident_expert_descriptor"))?; + let bank = self.banks.get(slot(role)?).ok_or(BindingError::Geometry("resident_expert_directory"))?; if bank.descriptor != descriptor || bank.tensor.len() != descriptor.bytes { return Err(BindingError::Geometry("resident_expert_descriptor")); } diff --git a/crates/model-format/src/qwen4exp_file_expert_source.rs b/crates/model-format/src/qwen4exp_file_expert_source.rs index 9f400222..7e471d24 100644 --- a/crates/model-format/src/qwen4exp_file_expert_source.rs +++ b/crates/model-format/src/qwen4exp_file_expert_source.rs @@ -58,61 +58,40 @@ impl FileExpertSourceLease { if layer >= 48 { return Err(BindingError::Range("file_expert_layer")); } - self.members - .get(usize::from(layer) * 3 + r) - .ok_or(BindingError::Geometry("file_expert_directory")) + self.members.get(usize::from(layer) * 3 + r).ok_or(BindingError::Geometry("file_expert_directory")) } } impl Qwen4ExpArtifact { pub fn file_expert_source_lease(&self) -> Result { let mut members = Vec::new(); - members - .try_reserve_exact(144) - .map_err(|_| BindingError::Io("file expert directory allocation".into()))?; + members.try_reserve_exact(144).map_err(|_| BindingError::Io("file expert directory allocation".into()))?; if members.capacity() > 144 { return Err(BindingError::Geometry("file_expert_metadata")); } for layer in 0..48u8 { - for role in [ - LayerRole::FfnGateExperts, - LayerRole::FfnUpExperts, - LayerRole::FfnDownExperts, - ] { + for role in [LayerRole::FfnGateExperts, LayerRole::FfnUpExperts, LayerRole::FfnDownExperts] { let named = TensorRole::Layer { layer, role }; - let tensor = self - .roles - .get(&named) - .ok_or(BindingError::Role("file_expert_role"))?; + let tensor = self.roles.get(&named).ok_or(BindingError::Role("file_expert_role"))?; // Reuse the actual routed bank shape/kind/domain admission; no wider stream geometry. - if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 - { + if tensor.shard != 0 || tensor.dimensions.len() != 3 || tensor.dimensions[2] != 512 { return Err(BindingError::Geometry("file_expert_bank")); } - let rows = if role == LayerRole::FfnDownExperts { - 2560 - } else { - 640 - }; + let rows = if role == LayerRole::FfnDownExperts { 2560 } else { 640 }; let (offset, length) = plan_stream_rows(tensor, named, 0, rows, Some(0))?; if offset != 0 || length.checked_mul(512) != Some(tensor.byte_length) { return Err(BindingError::Geometry("file_expert_bank")); } - self.shards[0] - .validate_empty_tensor_source(tensor.tensor_number) - .map_err(BindingError::Io)?; + self.shards[0].validate_empty_tensor_source(tensor.tensor_number).map_err(BindingError::Io)?; members.push(FileExpertExtent { role: named, absolute: tensor.absolute_start, bytes: tensor.byte_length, - expert_bytes: usize::try_from(length) - .map_err(|_| BindingError::Range("file_expert_bytes"))?, + expert_bytes: usize::try_from(length).map_err(|_| BindingError::Range("file_expert_bytes"))?, kind: tensor.kind, }); } } - let file = self.shards[0] - .expert_file_owner() - .map_err(BindingError::Io)?; + let file = self.shards[0].expert_file_owner().map_err(BindingError::Io)?; let metadata_bytes = members .capacity() .checked_mul(size_of::()) @@ -121,16 +100,9 @@ impl Qwen4ExpArtifact { if metadata_bytes > 16 * 1024 * 1024 { return Err(BindingError::Geometry("file_expert_metadata")); } - Ok(FileExpertSourceLease { - file, - members, - metadata_bytes, - }) + Ok(FileExpertSourceLease { file, members, metadata_bytes }) } - pub fn validate_file_expert_source( - &self, - lease: &FileExpertSourceLease, - ) -> Result<(), BindingError> { + pub fn validate_file_expert_source(&self, lease: &FileExpertSourceLease) -> Result<(), BindingError> { lease.validate_current()?; if self.shards[0].artifact_sha256() != lease.digest() || self.shards[0].index().summary.file_size != lease.indexed_bytes() @@ -138,29 +110,18 @@ impl Qwen4ExpArtifact { return Err(BindingError::Identity(0)); } // Two dup'd file descriptors of the same actual admitted FD, not pathname identity. - let current = self.shards[0] - .expert_file_owner() - .map_err(BindingError::Io)?; + let current = self.shards[0].expert_file_owner().map_err(BindingError::Io)?; #[cfg(unix)] { use std::os::unix::fs::MetadataExt; - let a = current - .file() - .metadata() - .map_err(|e| BindingError::Io(e.into()))?; - let b = lease - .file() - .metadata() - .map_err(|e| BindingError::Io(e.into()))?; + let a = current.file().metadata().map_err(|e| BindingError::Io(e.into()))?; + let b = lease.file().metadata().map_err(|e| BindingError::Io(e.into()))?; if a.dev() != b.dev() || a.ino() != b.ino() { return Err(BindingError::Identity(0)); } } for member in &lease.members { - let tensor = self - .roles - .get(&member.role) - .ok_or(BindingError::Role("file_expert_role"))?; + let tensor = self.roles.get(&member.role).ok_or(BindingError::Role("file_expert_role"))?; if tensor.absolute_start != member.absolute || tensor.byte_length != member.bytes || tensor.kind != member.kind diff --git a/crates/model-format/src/readahead.rs b/crates/model-format/src/readahead.rs index 75a8fc8d..5716480f 100644 --- a/crates/model-format/src/readahead.rs +++ b/crates/model-format/src/readahead.rs @@ -151,11 +151,7 @@ pub(crate) fn with_read_ahead( } #[cfg(not(target_os = "linux"))] let _ = (&mut advised, advise_willneed as fn(&File, u64, u64)); - let mut buffer = pool - .lock() - .ok() - .and_then(|mut p| p.pop()) - .unwrap_or_default(); + let mut buffer = pool.lock().ok().and_then(|mut p| p.pop()).unwrap_or_default(); buffer.resize(count, 0); if let Err(error) = read_exact_at(file, &mut buffer, start + offset) { for tx in &senders { @@ -165,11 +161,7 @@ pub(crate) fn with_read_ahead( } // The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass. evict_span(file, start + offset, count as u64); - let chunk = Arc::new(Chunk { - offset, - data: buffer, - pool: Arc::clone(&pool), - }); + let chunk = Arc::new(Chunk { offset, data: buffer, pool: Arc::clone(&pool) }); let mut any = false; for tx in &senders { any |= tx.send(Ok(Arc::clone(&chunk))).is_ok(); @@ -190,8 +182,7 @@ mod tests { use std::io::Write; fn temp_file(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) { - let path = - std::env::temp_dir().join(format!("leleka-readahead-{}-{name}", std::process::id())); + let path = std::env::temp_dir().join(format!("leleka-readahead-{}-{name}", std::process::id())); let mut file = File::create(&path).unwrap(); file.write_all(bytes).unwrap(); drop(file); @@ -199,37 +190,34 @@ mod tests { } fn pattern(len: usize) -> Vec { - (0..len) - .map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8) - .collect() + (0..len).map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8).collect() } #[test] fn every_consumer_sees_the_whole_span_in_order() { let data = pattern(CHUNK_BYTES * 2 + 12345); let (path, file) = temp_file("span", &data); - let collected: Vec> = - with_read_ahead(&file, 100, data.len() as u64 - 100, 2, |receivers| { - thread::scope(|scope| { - let handles: Vec<_> = receivers - .into_iter() - .map(|rx| { - scope.spawn(move || { - let mut out = Vec::new(); - let mut expected = 0u64; - for item in rx { - let chunk = item.unwrap(); - assert_eq!(chunk.offset, expected); - expected += chunk.len() as u64; - out.extend_from_slice(&chunk); - } - out - }) + let collected: Vec> = with_read_ahead(&file, 100, data.len() as u64 - 100, 2, |receivers| { + thread::scope(|scope| { + let handles: Vec<_> = receivers + .into_iter() + .map(|rx| { + scope.spawn(move || { + let mut out = Vec::new(); + let mut expected = 0u64; + for item in rx { + let chunk = item.unwrap(); + assert_eq!(chunk.offset, expected); + expected += chunk.len() as u64; + out.extend_from_slice(&chunk); + } + out }) - .collect(); - handles.into_iter().map(|h| h.join().unwrap()).collect() - }) - }); + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }) + }); for out in collected { assert_eq!(out, data[100..]); } diff --git a/crates/model-format/src/verify_stamp.rs b/crates/model-format/src/verify_stamp.rs index 1cadca1d..6c510095 100644 --- a/crates/model-format/src/verify_stamp.rs +++ b/crates/model-format/src/verify_stamp.rs @@ -235,7 +235,11 @@ mod tests { assert!(!stamps.trusts("gguf", &digest, &after)); // restoring the old mtime does not restore the old ctime let handle = fs::OpenOptions::new().write(true).open(&file).unwrap(); - handle.set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_nanos(u64::try_from(before.mtime_ns).unwrap())).unwrap(); + handle + .set_modified( + std::time::UNIX_EPOCH + std::time::Duration::from_nanos(u64::try_from(before.mtime_ns).unwrap()), + ) + .unwrap(); let restored = identity(&file); assert_eq!(restored.mtime_ns, before.mtime_ns); assert!(!stamps.trusts("gguf", &digest, &restored), "ctime must still differ"); diff --git a/crates/model-format/src/weight_source.rs b/crates/model-format/src/weight_source.rs index e7c346c1..13812683 100644 --- a/crates/model-format/src/weight_source.rs +++ b/crates/model-format/src/weight_source.rs @@ -107,11 +107,7 @@ impl From for WeightError { #[derive(Clone, Copy, Debug)] pub enum Region<'a> { Resident(&'a [u8]), - Positional { - file: &'a File, - offset: u64, - len: u64, - }, + Positional { file: &'a File, offset: u64, len: u64 }, } impl<'a> Region<'a> { @@ -148,11 +144,7 @@ impl<'a> Region<'a> { } /// Hand the region to `visit` in order: the slice itself when resident, otherwise `scratch`-sized pieces. - pub fn for_each_chunk( - &self, - scratch: &mut [u8], - mut visit: impl FnMut(&[u8]), - ) -> Result<(), WeightError> { + pub fn for_each_chunk(&self, scratch: &mut [u8], mut visit: impl FnMut(&[u8])) -> Result<(), WeightError> { if let Self::Resident(bytes) = self { visit(bytes); return Ok(()); diff --git a/crates/model-format/src/weight_source/digest.rs b/crates/model-format/src/weight_source/digest.rs index b1c34af0..a122f60a 100644 --- a/crates/model-format/src/weight_source/digest.rs +++ b/crates/model-format/src/weight_source/digest.rs @@ -4,13 +4,8 @@ use sha2::{Digest, Sha256}; /// SHA-256 of the whole source. A resident source is hashed in place; a positional one is read through `scratch` /// (the caller's bounded buffer, never larger than the caller chose), so no copy of the model is made. -pub fn sha256_of( - source: &S, - scratch: &mut [u8], -) -> Result<[u8; 32], WeightError> { +pub fn sha256_of(source: &S, scratch: &mut [u8]) -> Result<[u8; 32], WeightError> { let mut digest = Sha256::new(); - source - .region(0..source.len())? - .for_each_chunk(scratch, |piece| digest.update(piece))?; + source.region(0..source.len())?.for_each_chunk(scratch, |piece| digest.update(piece))?; Ok(digest.finalize().into()) } diff --git a/crates/model-format/src/weight_source/file.rs b/crates/model-format/src/weight_source/file.rs index e7a5125d..cb49097e 100644 --- a/crates/model-format/src/weight_source/file.rs +++ b/crates/model-format/src/weight_source/file.rs @@ -1,8 +1,5 @@ //! A file or a sealed memfd read by position: the bytes stay in the file, a caller's buffer receives a range. -use super::{ - BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded, - sha256_of, -}; +use super::{BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded, sha256_of}; use std::{borrow::Borrow, fs::File, io, ops::Range}; #[cfg(unix)] @@ -45,12 +42,7 @@ impl> FileWeightSource { /// The file with its current length and no claim about its content. pub fn unverified(file: F, backing: BackingKind) -> Result { let bytes = file.borrow().metadata()?.len(); - let identity = WeightIdentity { - sha256: [0; 32], - bytes, - verification: Verification::Unverified, - backing, - }; + let identity = WeightIdentity { sha256: [0; 32], bytes, verification: Verification::Unverified, backing }; Ok(Self::new(file, identity)) } @@ -70,11 +62,7 @@ impl> WeightSource for FileWeightSource { fn region(&self, range: Range) -> Result, WeightError> { bounded(&range, self.identity.bytes)?; - Ok(Region::Positional { - file: self.file.borrow(), - offset: range.start, - len: range.end - range.start, - }) + Ok(Region::Positional { file: self.file.borrow(), offset: range.start, len: range.end - range.start }) } fn live_len(&self) -> Result { diff --git a/crates/model-format/src/weight_source/kar_inspection_tests.rs b/crates/model-format/src/weight_source/kar_inspection_tests.rs index 29e317cf..bea42ce0 100644 --- a/crates/model-format/src/weight_source/kar_inspection_tests.rs +++ b/crates/model-format/src/weight_source/kar_inspection_tests.rs @@ -8,14 +8,7 @@ use std::fs::File; /// In range, at the end, past the end, and an offset that overflows. fn cases(end: u64) -> [(u64, usize); 6] { - [ - (0, 64), - (100, 1), - (end - 8, 8), - (end - 4, 8), - (end, 1), - (u64::MAX, 2), - ] + [(0, 64), (100, 1), (end - 8, 8), (end - 4, 8), (end, 1), (u64::MAX, 2)] } #[test] diff --git a/crates/model-format/src/weight_source/kar_levels_tests.rs b/crates/model-format/src/weight_source/kar_levels_tests.rs index 5e49435d..64634898 100644 --- a/crates/model-format/src/weight_source/kar_levels_tests.rs +++ b/crates/model-format/src/weight_source/kar_levels_tests.rs @@ -8,21 +8,12 @@ use crate::weight_source::{MemWeightSource, WeightRange}; fn stager_reads_the_same_packet_through_the_weight_source_port() { let base = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 2, 4)]); let image = finite_image(&base, 5); - let policy = LevelPolicy { - base: uniform(4), - overlay: uniform(4), - }; + let policy = LevelPolicy { base: uniform(4), overlay: uniform(4) }; let selector = KarLevelSelector::new(base, None, policy).unwrap(); let rows = selector.resolve(EXPERT).unwrap().expert(3, 1).unwrap(); let plan = &rows.window.plan; let whole = MemWeightSource::from_vec(image.clone()); - assert_eq!( - stage_window(&WeightRange(&whole), plan), - stage_window(image.as_slice(), plan) - ); + assert_eq!(stage_window(&WeightRange(&whole), plan), stage_window(image.as_slice(), plan)); let short = MemWeightSource::from_vec(image[..2000].to_vec()); - assert_eq!( - stage_window(&WeightRange(&short), plan), - Err(KarLevelsError::Read) - ); + assert_eq!(stage_window(&WeightRange(&short), plan), Err(KarLevelsError::Read)); } diff --git a/crates/model-format/src/weight_source/mem.rs b/crates/model-format/src/weight_source/mem.rs index 0a208865..5d6642d2 100644 --- a/crates/model-format/src/weight_source/mem.rs +++ b/crates/model-format/src/weight_source/mem.rs @@ -1,7 +1,5 @@ //! The test double: a source that owns a small buffer or borrows static bytes. -use super::{ - BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded, -}; +use super::{BackingKind, Region, Verification, WeightError, WeightIdentity, WeightSource, bounded}; use sha2::{Digest, Sha256}; use std::{borrow::Cow, ops::Range}; diff --git a/crates/model-format/src/weight_source/range.rs b/crates/model-format/src/weight_source/range.rs index a7a5b9ab..90b3d2fd 100644 --- a/crates/model-format/src/weight_source/range.rs +++ b/crates/model-format/src/weight_source/range.rs @@ -8,9 +8,7 @@ pub struct WeightRange<'a, S: ?Sized>(pub &'a S); impl RangeSource for WeightRange<'_, S> { fn read_exact_at(&self, offset: u64, out: &mut [u8]) -> Result<(), KarError> { - let end = offset - .checked_add(out.len() as u64) - .ok_or(KarError::Range("weight read range overflows"))?; + let end = offset.checked_add(out.len() as u64).ok_or(KarError::Range("weight read range overflows"))?; let region = self.0.region(offset..end).map_err(refusal)?; if self.0.live_len().map_err(refusal)? != self.0.len() { return Err(KarError::Integrity("weight source length changed")); diff --git a/crates/model-format/src/weight_source/resident.rs b/crates/model-format/src/weight_source/resident.rs index bf219ac8..0629b618 100644 --- a/crates/model-format/src/weight_source/resident.rs +++ b/crates/model-format/src/weight_source/resident.rs @@ -41,17 +41,9 @@ impl VerifiedGgufFile { /// The tensor as a read-only mapping of this verified file: no RAM is committed for it, the OS file cache holds /// the bytes. The same call `map_resident_tensor` makes, with the result seen through the port. #[cfg(any(target_os = "linux", windows))] - pub fn mapped_tensor_source( - &mut self, - tensor_number: usize, - ) -> Result { - let tensor = self - .map_resident_tensor(tensor_number) - .map_err(unavailable)?; - Ok(ResidentWeightSource::from_tensor( - tensor, - self.artifact_sha256(), - )) + pub fn mapped_tensor_source(&mut self, tensor_number: usize) -> Result { + let tensor = self.map_resident_tensor(tensor_number).map_err(unavailable)?; + Ok(ResidentWeightSource::from_tensor(tensor, self.artifact_sha256())) } /// The tensor as an owned copy in RAM (a huge-page buffer when `LELEKA_HUGEPAGES` selects it), at most @@ -61,12 +53,7 @@ impl VerifiedGgufFile { tensor_number: usize, capacity_ceiling: usize, ) -> Result { - let tensor = self - .load_resident_tensor(tensor_number, capacity_ceiling) - .map_err(unavailable)?; - Ok(ResidentWeightSource::from_tensor( - tensor, - self.artifact_sha256(), - )) + let tensor = self.load_resident_tensor(tensor_number, capacity_ceiling).map_err(unavailable)?; + Ok(ResidentWeightSource::from_tensor(tensor, self.artifact_sha256())) } } diff --git a/crates/model-format/src/weight_source/tests.rs b/crates/model-format/src/weight_source/tests.rs index 02529751..f254cf30 100644 --- a/crates/model-format/src/weight_source/tests.rs +++ b/crates/model-format/src/weight_source/tests.rs @@ -18,34 +18,21 @@ fn tiny_gguf() -> Vec { bytes.extend(0u32.to_le_bytes()); bytes.extend(0u64.to_le_bytes()); bytes.resize(bytes.len().div_ceil(32) * 32, 0); - for word in [0x8000_0000u32, 0, 0x3f80_0000, 0xbf80_0000] - .into_iter() - .cycle() - .take(16) - { + for word in [0x8000_0000u32, 0, 0x3f80_0000, 0xbf80_0000].into_iter().cycle().take(16) { bytes.extend(word.to_le_bytes()); } bytes } fn temp_file(tag: &str, bytes: &[u8]) -> PathBuf { - let nonce = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = std::env::temp_dir().join(format!( - "weight-source-{tag}-{}-{nonce}", - std::process::id() - )); + let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("weight-source-{tag}-{}-{nonce}", std::process::id())); fs::write(&path, bytes).unwrap(); path } fn declared(bytes: &[u8]) -> String { - let hex: String = Sha256::digest(bytes) - .iter() - .map(|b| format!("{b:02x}")) - .collect(); + let hex: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect(); format!("sha256:{hex}") } @@ -64,10 +51,7 @@ fn memory_source_returns_the_same_address_for_every_call_and_sub_range() { assert_eq!(inner, &whole[40..80]); let fixed = MemWeightSource::from_static(b"static bytes"); let first = fixed.region(0..6).unwrap().as_slice().unwrap().as_ptr(); - assert_eq!( - first, - fixed.region(0..6).unwrap().as_slice().unwrap().as_ptr() - ); + assert_eq!(first, fixed.region(0..6).unwrap().as_slice().unwrap().as_ptr()); } #[cfg(any(target_os = "linux", windows))] @@ -82,10 +66,7 @@ fn mapped_tensor_source_returns_the_same_address_for_every_call() { let first = source.region(0..64).unwrap().as_slice().unwrap(); let second = source.region(0..64).unwrap().as_slice().unwrap(); assert_eq!(first.as_ptr(), second.as_ptr()); - assert_eq!( - source.region(16..32).unwrap().as_slice().unwrap().as_ptr(), - first[16..].as_ptr() - ); + assert_eq!(source.region(16..32).unwrap().as_slice().unwrap().as_ptr(), first[16..].as_ptr()); let tensor_start = bytes.len() - 64; assert_eq!(first, &bytes[tensor_start..]); drop(source); @@ -100,15 +81,9 @@ fn retained_tensor_source_returns_the_same_address_for_every_call() { let mut shard = VerifiedGgufFile::open(&path, &declared(&bytes)).unwrap(); let source = shard.retained_tensor_source(0, 64).unwrap(); let first = source.region(0..64).unwrap().as_slice().unwrap().as_ptr(); - assert_eq!( - first, - source.region(0..64).unwrap().as_slice().unwrap().as_ptr() - ); + assert_eq!(first, source.region(0..64).unwrap().as_slice().unwrap().as_ptr()); assert_eq!(source.identity().sha256, shard.identity().sha256); - assert!(matches!( - source.identity().backing, - BackingKind::Memory | BackingKind::HugePages - )); + assert!(matches!(source.identity().backing, BackingKind::Memory | BackingKind::HugePages)); drop(source); drop(shard); fs::remove_file(path).unwrap(); @@ -126,10 +101,7 @@ fn positional_sources_expose_no_address_and_fill_only_the_callers_buffer() { region.read_at(0, &mut out).unwrap(); assert_eq!(&out[..], &bytes[8..40]); assert_eq!(region.read_at(1, &mut out), Err(WeightError::Range)); - assert_eq!( - source.region(0..bytes.len() as u64 + 1).err(), - Some(WeightError::Range) - ); + assert_eq!(source.region(0..bytes.len() as u64 + 1).err(), Some(WeightError::Range)); let (start, end) = (9u64, 8u64); assert_eq!(source.region(start..end).err(), Some(WeightError::Range)); drop(file); @@ -186,31 +158,14 @@ fn live_length_follows_the_file_while_the_identity_keeps_the_length_it_was_opene #[test] fn kar_trust_maps_one_to_one() { use crate::kar::KarTrust; - assert_eq!( - Verification::from(KarTrust::FullPass), - Verification::FullPass - ); + assert_eq!(Verification::from(KarTrust::FullPass), Verification::FullPass); assert_eq!(Verification::from(KarTrust::Stamp), Verification::Stamp); - assert_eq!( - Verification::from(KarTrust::AttestedMemfd), - Verification::AttestedMemfd - ); - assert_eq!( - Verification::from(KarTrust::SparseExtents), - Verification::SparseExtents - ); + assert_eq!(Verification::from(KarTrust::AttestedMemfd), Verification::AttestedMemfd); + assert_eq!(Verification::from(KarTrust::SparseExtents), Verification::SparseExtents); } -const OWNERS: [&str; 8] = [ - "to_vec(", - "to_owned(", - "into_boxed_slice", - "Vec", - "Box<[u8]>", - "Arc<[u8]>", - "Rc<[u8]>", - "Cow<", -]; +const OWNERS: [&str; 8] = + ["to_vec(", "to_owned(", "into_boxed_slice", "Vec", "Box<[u8]>", "Arc<[u8]>", "Rc<[u8]>", "Cow<"]; /// The production files of the port never name an owner of model bytes: a copy has to be written next to the port, /// where review sees it, instead of being one method call away. @@ -222,16 +177,10 @@ fn the_production_port_has_no_owning_copy_method() { ("file.rs", include_str!("file.rs")), ("resident.rs", include_str!("resident.rs")), ("range.rs", include_str!("range.rs")), - ( - "gguf/impl_verifiedgguffile/port.rs", - include_str!("../gguf/impl_verifiedgguffile/port.rs"), - ), + ("gguf/impl_verifiedgguffile/port.rs", include_str!("../gguf/impl_verifiedgguffile/port.rs")), ]; for (name, text) in production { - let code: String = text - .lines() - .filter(|l| !l.trim_start().starts_with("//")) - .collect(); + let code: String = text.lines().filter(|l| !l.trim_start().starts_with("//")).collect(); for owner in OWNERS { assert!(!code.contains(owner), "{name} names {owner}"); } diff --git a/crates/model-format/tests/kar_crc_slicing.rs b/crates/model-format/tests/kar_crc_slicing.rs index f25db0ba..0cf56e4f 100644 --- a/crates/model-format/tests/kar_crc_slicing.rs +++ b/crates/model-format/tests/kar_crc_slicing.rs @@ -30,9 +30,7 @@ fn scalar_integrity_stream( if n == 0 { break; } - let end = total - .checked_add(n as u64) - .ok_or(KarError::Range("KAR hash length overflow"))?; + let end = total.checked_add(n as u64).ok_or(KarError::Range("KAR hash length overflow"))?; digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. while let Some(section) = sections.get(index) { if section.offset >= end { @@ -41,10 +39,7 @@ fn scalar_integrity_stream( let section_end = section.offset + section.bytes; // Checked above. let start = total.max(section.offset); let stop = end.min(section_end); - crc = scalar_step( - crc, - &buffer[(start - total) as usize..(stop - total) as usize], - ); + crc = scalar_step(crc, &buffer[(start - total) as usize..(stop - total) as usize]); if stop != section_end { break; } @@ -101,30 +96,13 @@ fn compare_stream( fail_at: Option, expected: &str, ) { - let reader = || Counted { - bytes, - position: 0, - limit: chunk, - fail_at, - calls: 0, - }; + let reader = || Counted { bytes, position: 0, limit: chunk, fail_at, calls: 0 }; let mut old = reader(); - let old_result = outcome(scalar_integrity_stream( - &mut old, - sections, - expected_bytes, - pin, - &mut vec![0; chunk], - )); + let old_result = outcome(scalar_integrity_stream(&mut old, sections, expected_bytes, pin, &mut vec![0; chunk])); assert_eq!(old_result, expected); let mut changed = reader(); - let changed_result = outcome(verify_integrity_stream( - &mut changed, - sections, - expected_bytes, - pin, - &mut vec![0; chunk], - )); + let changed_result = + outcome(verify_integrity_stream(&mut changed, sections, expected_bytes, pin, &mut vec![0; chunk])); assert_eq!(changed_result, old_result); assert_eq!(changed.position, old.position); assert_eq!(changed.calls, old.calls); @@ -228,15 +206,7 @@ fn original_first_crc_slicing_states_tails_splits_and_stream_precedence() { compare_stream(bytes, &overflow, 187, &pin, chunk, Some(0), range_failure); stream_comparisons += 15; } - compare_stream( - bytes, - §ions(), - 187, - &pin, - 0, - None, - "Range(\"KAR integrity buffer is empty\")", - ); + compare_stream(bytes, §ions(), 187, &pin, 0, None, "Range(\"KAR integrity buffer is empty\")"); stream_comparisons += 1; assert_eq!(comparisons, 163792); assert_eq!(stream_comparisons, 196); diff --git a/crates/model-format/tests/kar_extents.rs b/crates/model-format/tests/kar_extents.rs index 90d1ea27..9d08b228 100644 --- a/crates/model-format/tests/kar_extents.rs +++ b/crates/model-format/tests/kar_extents.rs @@ -12,10 +12,18 @@ const PAGE: u64 = 4096; enum Kind { /// A PLE partition: dims `[160, rows]`, `stored` planes. - Ple { rows: u64, stored: u8 }, + Ple { + rows: u64, + stored: u8, + }, /// Another nested record (never read by the serve path). - Nested { elements: u64, stored: u8 }, - Raw { elements: u64 }, + Nested { + elements: u64, + stored: u8, + }, + Raw { + elements: u64, + }, } struct Spec { name: &'static str, @@ -210,7 +218,11 @@ struct Temp(PathBuf); impl Temp { fn new(tag: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - Temp(std::env::temp_dir().join(format!("leleka-extents-{tag}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)))) + Temp(std::env::temp_dir().join(format!( + "leleka-extents-{tag}-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ))) } fn file(tag: &str, bytes: &[u8]) -> Self { let t = Self::new(tag); diff --git a/crates/model-format/tests/kar_extents/builder_makes_archives.rs b/crates/model-format/tests/kar_extents/builder_makes_archives.rs index 2cc16174..b0050273 100644 --- a/crates/model-format/tests/kar_extents/builder_makes_archives.rs +++ b/crates/model-format/tests/kar_extents/builder_makes_archives.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn the_builder_makes_archives_the_inspector_admits() { let bytes = build(&standard()); @@ -25,10 +24,7 @@ fn normalization_aligns_outwards_merges_and_clamps_to_the_archive() { [e(0, 12288)] ); // a hole of at least one page keeps two extents - assert_eq!( - normalize_extents(&[e(0, 10), e(2 * PAGE, 10)], 1 << 20).unwrap(), - [e(0, PAGE), e(2 * PAGE, PAGE)] - ); + assert_eq!(normalize_extents(&[e(0, 10), e(2 * PAGE, 10)], 1 << 20).unwrap(), [e(0, PAGE), e(2 * PAGE, PAGE)]); // the last page is clamped to the archive length assert_eq!(normalize_extents(&[e(8192, 100)], 8192 + 512).unwrap(), [e(8192, 512)]); // beyond the archive is refused @@ -108,7 +104,11 @@ fn every_row_reads_the_same_bytes_through_a_copy_that_holds_only_the_extents() { read_rows_chunk(&full.open(), &parts, &rows, &mut want).unwrap(); read_rows_chunk(&sparse.open(), &parts, &rows, &mut got).unwrap(); assert!(want.iter().zip(&got).all(|(x, y)| x.payload == y.payload && x.partition == y.partition)); - assert_eq!((want[0].partition, want[1000].partition, want[999].partition, want[1776].partition), (0, 1, 0, 1), "the seam"); + assert_eq!( + (want[0].partition, want[1000].partition, want[999].partition, want[1776].partition), + (0, 1, 0, 1), + "the seam" + ); assert!(want.iter().any(|p| p.payload.iter().any(|b| *b != 0))); } @@ -124,10 +124,7 @@ fn the_census_totals_every_record_once_and_matches_the_reads() { assert_eq!((ple.records, nested.records, raw.records), (2, 2, 1)); assert_eq!(ple.elements, 1777 * 160); // sections tile the payload exactly - assert_eq!( - ple.section_bytes + nested.section_bytes + raw.section_bytes + c.payload_offset, - c.archive_bytes - ); + assert_eq!(ple.section_bytes + nested.section_bytes + raw.section_bytes + c.payload_offset, c.archive_bytes); // exact bytes read: metadata + the rows of both partitions + two 8-byte books let rows: u64 = 1777 * (10 + 40); assert_eq!(ple.exact_read_bytes, rows + 16); @@ -138,7 +135,17 @@ fn the_census_totals_every_record_once_and_matches_the_reads() { assert!(c.serve.extent_bytes() < c.archive_bytes); assert_eq!(c.unread_extent_bytes(), c.archive_bytes - c.serve.extent_bytes()); let text = c.render(true); - for needle in ["archive_bytes=", "ple-rows (read)", "nested (never read)", "raw (never read)", "serve_read_exact_bytes=", "sparse_copy_bytes=", "never_read_bytes=", "dense.big", "bytes_before_first_ple_section="] { + for needle in [ + "archive_bytes=", + "ple-rows (read)", + "nested (never read)", + "raw (never read)", + "serve_read_exact_bytes=", + "sparse_copy_bytes=", + "never_read_bytes=", + "dense.big", + "bytes_before_first_ple_section=", + ] { assert!(text.contains(needle), "{needle} missing in\n{text}"); } assert!(!c.render(false).contains("dense.big"), "the summary lists only the PLE records"); @@ -162,14 +169,19 @@ fn a_sparse_copy_has_the_same_pinned_digest_as_the_archive_and_verifies() { digest_extents(&sparse.open(), &reads.extents, |n| seen += n).unwrap(); assert_eq!(seen, reads.extent_bytes()); - let ok = VerifiedKarPleArtifact::verify_sparse(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes), &pin).unwrap(); + let ok = + VerifiedKarPleArtifact::verify_sparse(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes), &pin) + .unwrap(); assert!(ok.is_sparse()); assert_eq!(ok.serve_extents(), &reads.extents[..], "the artifact reads exactly the extents the census lists"); // the full-archive verifier does not accept a sparse copy (its SHA-256 is different) - let refused = VerifiedKarPleArtifact::verify(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes)).err().unwrap(); + let refused = VerifiedKarPleArtifact::verify(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes)) + .err() + .unwrap(); assert!(refused.to_string().contains("full archive SHA"), "{refused}"); // ... and it still accepts the full file - let full_ok = VerifiedKarPleArtifact::verify(inspect(&full).into_owner_controlled(), standard_profile(&bytes)).unwrap(); + let full_ok = + VerifiedKarPleArtifact::verify(inspect(&full).into_owner_controlled(), standard_profile(&bytes)).unwrap(); assert!(!full_ok.is_sparse()); assert_eq!(full_ok.serve_extents(), ok.serve_extents()); } @@ -181,12 +193,17 @@ fn a_sparse_copy_is_refused_for_a_wrong_pin_a_changed_extent_byte_or_a_changed_l let i = inspect(&full); let reads = i.serve_reads(&[PART0, PART1]).unwrap(); let pin = digest_extents(&full.open(), &reads.extents, |_| {}).unwrap(); - let verify = |t: &Temp, pin: &[u8; 32]| VerifiedKarPleArtifact::verify_sparse(inspect(t).into_owner_controlled(), standard_profile(&bytes), pin); + let verify = |t: &Temp, pin: &[u8; 32]| { + VerifiedKarPleArtifact::verify_sparse(inspect(t).into_owner_controlled(), standard_profile(&bytes), pin) + }; // wrong pin let sparse = sparse_copy("rs0", &bytes, &reads.extents); let mut wrong = pin; wrong[0] ^= 1; - assert!(matches!(verify(&sparse, &wrong).err().unwrap(), KarError::Integrity("KAR sparse extents SHA-256 mismatch"))); + assert!(matches!( + verify(&sparse, &wrong).err().unwrap(), + KarError::Integrity("KAR sparse extents SHA-256 mismatch") + )); assert!(verify(&sparse, &[0; 32]).is_err(), "the unpinned (all zero) digest never matches"); // one flipped byte in each kind of extent: a scale, a plane of part 0, a plane of part 1, a book let p0 = i.nested_record(PART0).unwrap(); @@ -240,7 +257,13 @@ fn an_extent_list_that_misses_a_read_range_is_refused_at_verification() { let pin_short = digest_extents(&full.open(), &short, |_| {}).unwrap(); let sparse = sparse_copy("mshort", &bytes, &short); assert!(last.len > 0); - let e = VerifiedKarPleArtifact::verify_sparse(inspect(&sparse).into_owner_controlled(), standard_profile(&bytes), &pin_short).err().unwrap(); + let e = VerifiedKarPleArtifact::verify_sparse( + inspect(&sparse).into_owner_controlled(), + standard_profile(&bytes), + &pin_short, + ) + .err() + .unwrap(); assert!(matches!(e, KarError::Integrity(_)), "{e}"); } diff --git a/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs b/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs index 56ca8c9c..984a7d13 100644 --- a/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs +++ b/crates/model-format/tests/kar_kernel_model/corrupt_launch_parameters_fail_closed.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn corrupt_launch_parameters_fail_closed_before_any_write() { let mut rng = Rng(0xbad); @@ -14,73 +13,19 @@ fn corrupt_launch_parameters_fail_closed_before_any_write() { let mutations: Vec<(&str, DecodeParams)> = vec![ ("level 1", DecodeParams { level: 1, ..good }), ("level 6", DecodeParams { level: 6, ..good }), - ( - "level above staged", - DecodeParams { - staged_planes: 2, - ..good - }, - ), + ("level above staged", DecodeParams { staged_planes: 2, ..good }), ("count 0", DecodeParams { count: 0, ..good }), - ( - "count too big", - DecodeParams { - count: (MAX_RANGE_ELEMENTS + 1) as u32, - ..good - }, - ), + ("count too big", DecodeParams { count: (MAX_RANGE_ELEMENTS + 1) as u32, ..good }), ("group 0", DecodeParams { group: 0, ..good }), ("group 33", DecodeParams { group: 33, ..good }), ("head32 32", DecodeParams { head32: 32, ..good }), - ( - "head_group", - DecodeParams { - head_group: good.group, - ..good - }, - ), - ( - "too few words", - DecodeParams { - window_words: good.window_words - 1, - ..good - }, - ), - ( - "too few groups", - DecodeParams { - window_groups: good.window_groups - 1, - ..good - }, - ), - ( - "stride < words", - DecodeParams { - plane_stride_words: 4, - ..good - }, - ), - ( - "misaligned planes", - DecodeParams { - planes_offset: good.planes_offset + 2, - ..good - }, - ), - ( - "packet too small", - DecodeParams { - packet_bytes: good.packet_bytes - 4, - ..good - }, - ), - ( - "scales outside", - DecodeParams { - scales_offset: good.packet_bytes, - ..good - }, - ), + ("head_group", DecodeParams { head_group: good.group, ..good }), + ("too few words", DecodeParams { window_words: good.window_words - 1, ..good }), + ("too few groups", DecodeParams { window_groups: good.window_groups - 1, ..good }), + ("stride < words", DecodeParams { plane_stride_words: 4, ..good }), + ("misaligned planes", DecodeParams { planes_offset: good.planes_offset + 2, ..good }), + ("packet too small", DecodeParams { packet_bytes: good.packet_bytes - 4, ..good }), + ("scales outside", DecodeParams { scales_offset: good.packet_bytes, ..good }), ]; for (name, bad) in mutations { let mut out = vec![f32::from_bits(0xdead_beef); good.count.max(1) as usize + 8]; @@ -170,16 +115,11 @@ fn multiply_model_is_exact_for_integer_data_and_close_to_f64_otherwise() { let weights: Vec = (0..cols * rows).map(|i| (i % 7) as f32 - 3.0).collect(); let input: Vec = (0..cols * tokens).map(|i| (i % 5) as f32 - 2.0).collect(); let mut out = vec![0f32; (rows * tokens) as usize]; - assert_eq!( - kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), - 0 - ); + assert_eq!(kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), 0); for t in 0..tokens as usize { for r in 0..rows as usize { let exact: i64 = (0..cols as usize) - .map(|c| { - (weights[r * cols as usize + c] as i64) * (input[t * cols as usize + c] as i64) - }) + .map(|c| (weights[r * cols as usize + c] as i64) * (input[t * cols as usize + c] as i64)) .sum(); assert_eq!(out[t * rows as usize + r], exact as f32); } @@ -189,12 +129,8 @@ fn multiply_model_is_exact_for_integer_data_and_close_to_f64_otherwise() { // the L1 mass; this is a sanity bound, not a parity claim). let mut rng = Rng(0x77); let (cols, rows) = (1000u32, 4u32); - let w: Vec = (0..cols * rows) - .map(|_| (rng.below(2001) as f32 - 1000.0) / 640.0) - .collect(); - let x: Vec = (0..cols) - .map(|_| (rng.below(2001) as f32 - 1000.0) / 512.0) - .collect(); + let w: Vec = (0..cols * rows).map(|_| (rng.below(2001) as f32 - 1000.0) / 640.0).collect(); + let x: Vec = (0..cols).map(|_| (rng.below(2001) as f32 - 1000.0) / 512.0).collect(); let mut y = vec![0f32; rows as usize]; assert_eq!(kernel_multiply(&w, &x, cols, rows, 1, &mut y), 0); for r in 0..rows as usize { @@ -214,10 +150,7 @@ fn multiply_model_order_is_lane_strided_then_fixed_tree() { // Lanes 0,1,2 hold 2^24, 2, 1. Tree: (p0 + p2) + p1 = (2^24 + 1 -> 2^24) + 2. // Left-to-right over lanes would give (2^24 + 2) + 1 -> 2^24 + 4. let mut out = [0f32]; - assert_eq!( - kernel_multiply(&[big, 2.0, 1.0], &[1f32; 3], 3, 1, 1, &mut out), - 0 - ); + assert_eq!(kernel_multiply(&[big, 2.0, 1.0], &[1f32; 3], 3, 1, 1, &mut out), 0); assert_eq!(out[0], big + 2.0); // Columns stride by 256 within a lane: lane 0 sums columns 0, 256, 512 in // order, so 2^24 absorbs the two trailing 1.0 terms one at a time. @@ -226,10 +159,7 @@ fn multiply_model_order_is_lane_strided_then_fixed_tree() { weights[256] = 1.0; weights[512] = 1.0; let mut out = [0f32]; - assert_eq!( - kernel_multiply(&weights, &vec![1f32; 513], 513, 1, 1, &mut out), - 0 - ); + assert_eq!(kernel_multiply(&weights, &vec![1f32; 513], 513, 1, 1, &mut out), 0); assert_eq!(out[0], big); } @@ -238,30 +168,19 @@ fn multiply_model_flags_nonfinite_and_bad_shapes() { let mut out = [0f32; 2]; let weights = [f32::NAN, 1.0, 1.0, 1.0]; let input = [1.0, 1.0]; - assert_eq!( - kernel_multiply(&weights, &input, 2, 2, 1, &mut out), - STATUS_NONFINITE_OUTPUT - ); + assert_eq!(kernel_multiply(&weights, &input, 2, 2, 1, &mut out), STATUS_NONFINITE_OUTPUT); for (cols, rows, tokens) in [(0, 2, 1), (2, 0, 1), (2, 2, 0), (2, 2, MAX_TOKENS + 1)] { - assert_eq!( - kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), - STATUS_BAD_ARGUMENT - ); + assert_eq!(kernel_multiply(&weights, &input, cols, rows, tokens, &mut out), STATUS_BAD_ARGUMENT); } // Buffers shorter than the declared geometry are refused, not read. - assert_eq!( - kernel_multiply(&weights[..3], &input, 2, 2, 1, &mut out), - STATUS_BAD_ARGUMENT - ); + assert_eq!(kernel_multiply(&weights[..3], &input, 2, 2, 1, &mut out), STATUS_BAD_ARGUMENT); } #[test] fn decode_then_multiply_matches_oracle_decode_then_multiply() { let mut rng = Rng(0xd0d0); let f = fixture(&mut rng, "ffn", &[48, 10, 3], 32, 4, 2, 4); - let x: Vec = (0..48 * 2) - .map(|_| (rng.below(65) as f32 - 32.0) / 16.0) - .collect(); + let x: Vec = (0..48 * 2).map(|_| (rng.below(65) as f32 - 32.0) / 16.0).collect(); for level in [2u8, 3, 4] { let (first, rows) = expert_rows(&f.record, 2).unwrap(); let plan = plan_rows(&f.record, level, first, rows).unwrap(); diff --git a/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs b/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs index 3665ba29..9423ee3b 100644 --- a/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs +++ b/crates/model-format/tests/kar_kernel_model/f16_widening_matches_exact_reference.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - // ---------------------------------------------------------------- tests #[test] fn f16_widening_matches_exact_reference_for_every_bit_pattern() { @@ -18,11 +17,8 @@ fn f16_widening_matches_exact_reference_for_every_bit_pattern() { assert_eq!(got.is_sign_negative(), sign < 0.0); continue; } - let reference = if exponent == 0 { - mantissa * 2f64.powi(-24) - } else { - (1024.0 + mantissa) * 2f64.powi(exponent - 25) - }; + let reference = + if exponent == 0 { mantissa * 2f64.powi(-24) } else { (1024.0 + mantissa) * 2f64.powi(exponent - 25) }; let want = (sign * reference) as f32; // exact: every f16 is an f32 assert_eq!(got.to_bits(), want.to_bits(), "{bits:#06x}"); } @@ -52,13 +48,8 @@ fn kernel_matches_cpu_oracle_over_random_records_levels_2_to_5() { let count = rng.range(1, n - start); let (plan, got, status) = run_kernel(&f, level, start, count); assert_eq!(status, 0); - let want = - oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); - assert_bits_eq( - &got, - &want, - &format!("L{level} g{group} n{n} start{start} count{count}"), - ); + let want = oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); + assert_bits_eq(&got, &want, &format!("L{level} g{group} n{n} start{start} count{count}")); assert_eq!(plan.params.level, u32::from(level)); cases += 1; } @@ -98,8 +89,7 @@ fn kernel_matches_oracle_on_alignment_edges_and_partial_last_group() { for &(start, count) in &edges { let (_, got, status) = run_kernel(&f, level, start, count); assert_eq!(status, 0); - let want = - oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); + let want = oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); assert_bits_eq(&got, &want, &format!("L{level} start{start} count{count}")); } } @@ -115,8 +105,7 @@ fn multi_block_ranges_cross_block_boundaries_exactly() { let (plan, got, status) = run_kernel(&f, level, start, count); assert_eq!(status, 0); assert_eq!(plan.grid_blocks(), decode_grid(count as u32)); - let want = - oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); + let want = oracle(&f.archive, &f.record, level, start as usize, count as usize).unwrap(); assert_bits_eq(&got, &want, &format!("L{level} {start}+{count}")); } } @@ -131,11 +120,7 @@ fn overlay_selected_levels_decode_from_their_own_archive() { let overlay = fixture(&mut rng, "w", &[777], 32, 4, 3, 4); let (_, base_out, s0) = run_kernel(&base, 2, 100, 400); assert_eq!(s0, 0); - assert_bits_eq( - &base_out, - &oracle(&base.archive, &base.record, 2, 100, 400).unwrap(), - "base L2", - ); + assert_bits_eq(&base_out, &oracle(&base.archive, &base.record, 2, 100, 400).unwrap(), "base L2"); for level in [3u8, 4] { let (_, out, status) = run_kernel(&overlay, level, 100, 400); assert_eq!(status, 0); @@ -200,10 +185,7 @@ fn range_bounds_are_enforced_without_overflow() { (u64::MAX - 3, 8), (0, MAX_RANGE_ELEMENTS + 1), ] { - assert!( - plan_window(&f.record, 2, start, count).is_err(), - "{start}+{count}" - ); + assert!(plan_window(&f.record, 2, start, count).is_err(), "{start}+{count}"); } } @@ -284,10 +266,7 @@ fn plan_ranges_are_in_bounds_aligned_disjoint_and_minimal() { let groups = (start + count).div_ceil(u64::from(group)) - start / u64::from(group); assert_eq!(plan.params.window_words as u64, words); assert_eq!(plan.params.window_groups as u64, groups); - assert_eq!( - plan.staged_source_bytes(), - (1u64 << level) * 2 + groups * 2 + u64::from(level) * words * 4 - ); + assert_eq!(plan.staged_source_bytes(), (1u64 << level) * 2 + groups * 2 + u64::from(level) * words * 4); } } } diff --git a/crates/model-format/tests/kar_kernel_model/mod.rs b/crates/model-format/tests/kar_kernel_model/mod.rs index e2d42d98..15fd51de 100644 --- a/crates/model-format/tests/kar_kernel_model/mod.rs +++ b/crates/model-format/tests/kar_kernel_model/mod.rs @@ -45,15 +45,7 @@ fn round16(value: u64) -> u64 { /// Build a section laid out exactly as the inspector's formulas require, with /// random finite scales/books/planes and random garbage in every padding gap. -fn fixture( - rng: &mut Rng, - name: &str, - dims: &[u64], - group: u32, - stored: u8, - min: u8, - max: u8, -) -> Fixture { +fn fixture(rng: &mut Rng, name: &str, dims: &[u64], group: u32, stored: u8, min: u8, max: u8) -> Fixture { let n_elements: u64 = dims.iter().product(); let n_padded = n_elements.div_ceil(u64::from(group)) * u64::from(group); let scales_bytes = n_padded / u64::from(group) * 2; @@ -92,11 +84,7 @@ fn fixture( plane_stride_bytes: stride as u32, }; record.validate().unwrap(); - Fixture { - archive, - record, - n_padded: n_padded as usize, - } + Fixture { archive, record, n_padded: n_padded as usize } } // --------------------------------------------------------------- oracle @@ -123,9 +111,7 @@ fn oracle_decode_range( if end > padded || planes.iter().any(|plane| plane.len() != padded / 32) { return Err("KAR decoder range or plane length is invalid".into()); } - if scales[start / group..end.div_ceil(group)] - .iter() - .any(|bits| bits & 0x7c00 == 0x7c00) + if scales[start / group..end.div_ceil(group)].iter().any(|bits| bits & 0x7c00 == 0x7c00) || book.iter().any(|bits| bits & 0x7c00 == 0x7c00) { return Err("KAR decoder received non-finite f16 data".into()); @@ -160,15 +146,12 @@ fn oracle( let local_padded = (end_group - base_group) * group_size; assert!(base_element + local_padded <= padded); let region = |offset: u64, len: usize| &archive[offset as usize..offset as usize + len]; - let scales: Vec = region( - r.scales_offset + base_group as u64 * 2, - (end_group - base_group) * 2, - ) - .as_chunks::<2>() - .0 - .iter() - .map(|b| u16::from_le_bytes([b[0], b[1]])) - .collect(); + let scales: Vec = region(r.scales_offset + base_group as u64 * 2, (end_group - base_group) * 2) + .as_chunks::<2>() + .0 + .iter() + .map(|b| u16::from_le_bytes([b[0], b[1]])) + .collect(); let book_offset = r.books_offset + (1u64 << (u32::from(level) + 1)) - 4; let book: Vec = region(book_offset, (1usize << level) * 2) .as_chunks::<2>() @@ -180,27 +163,17 @@ fn oracle( let plane_base = (base_element / 32 * 4) as u64; let planes: Vec> = (0..u64::from(level)) .map(|plane| { - region( - r.planes_offset + plane * u64::from(r.plane_stride_bytes) + plane_base, - plane_bytes, - ) - .as_chunks::<4>() - .0 - .iter() - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect() + region(r.planes_offset + plane * u64::from(r.plane_stride_bytes) + plane_base, plane_bytes) + .as_chunks::<4>() + .0 + .iter() + .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() }) .collect(); let refs: Vec<&[u32]> = planes.iter().map(Vec::as_slice).collect(); let mut out = vec![0f32; count]; - oracle_decode_range( - &scales, - &book, - &refs, - r.group as u16, - start - base_element, - &mut out, - )?; + oracle_decode_range(&scales, &book, &refs, r.group as u16, start - base_element, &mut out)?; Ok(out) } @@ -237,16 +210,8 @@ impl VirtualArchive<'_> { let byte = h as u8; // f16 little endian: odd offsets (relative to the region) hold the // exponent's top bits; clearing bit 2 keeps the exponent below 31. - let relative = if offset >= r.books_offset { - offset - r.books_offset - } else { - offset - r.scales_offset - }; - if in_f16 && relative % 2 == 1 { - byte & 0xbb - } else { - byte - } + let relative = if offset >= r.books_offset { offset - r.books_offset } else { offset - r.scales_offset }; + if in_f16 && relative % 2 == 1 { byte & 0xbb } else { byte } } } impl crate::kar_levels::RangeSource for VirtualArchive<'_> { @@ -268,10 +233,7 @@ fn direct_element(v: &VirtualArchive<'_>, level: u8, element: u64) -> f32 { let r = v.r; let mut code = 0usize; for plane in 0..u64::from(level) { - let at = r.planes_offset - + plane * u64::from(r.plane_stride_bytes) - + (element / 32) * 4 - + (element % 32) / 8; + let at = r.planes_offset + plane * u64::from(r.plane_stride_bytes) + (element / 32) * 4 + (element % 32) / 8; code = (code << 1) | usize::from((v.byte(at) >> (element % 8)) & 1); } let scale_at = r.scales_offset + 2 * (element / u64::from(r.group)); @@ -281,6 +243,6 @@ fn direct_element(v: &VirtualArchive<'_>, level: u8, element: u64) -> f32 { f16_to_f32(book) * f16_to_f32(scale) } -mod f16_widening_matches_exact_reference; mod corrupt_launch_parameters_fail_closed; +mod f16_widening_matches_exact_reference; mod swiglu_model_matches_silu_times; diff --git a/crates/model-format/tests/kar_kernel_model/swiglu_model_matches_silu_times.rs b/crates/model-format/tests/kar_kernel_model/swiglu_model_matches_silu_times.rs index 34a0b3ef..00f37cf3 100644 --- a/crates/model-format/tests/kar_kernel_model/swiglu_model_matches_silu_times.rs +++ b/crates/model-format/tests/kar_kernel_model/swiglu_model_matches_silu_times.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn swiglu_model_matches_silu_times_up_and_flags_nonfinite() { let gate = [0.0f32, 1.0, -1.0, 2.5, -30.0, 8.0]; @@ -13,22 +12,13 @@ fn swiglu_model_matches_silu_times_up_and_flags_nonfinite() { for ((a, g), u) in act.iter().zip(gate).zip(up) { let silu = f64::from(g) / (1.0 + (-f64::from(g)).exp()); let want = silu * f64::from(u); - assert!( - (f64::from(*a) - want).abs() <= want.abs() * 1e-6 + 1e-30, - "{g} {u}" - ); + assert!((f64::from(*a) - want).abs() <= want.abs() * 1e-6 + 1e-30, "{g} {u}"); } assert_eq!(act[0], 0.0); // silu(0) = 0 let mut one = [0f32]; - assert_eq!( - kernel_swiglu(&[f32::NAN], &[1.0], &mut one), - STATUS_NONFINITE_OUTPUT - ); + assert_eq!(kernel_swiglu(&[f32::NAN], &[1.0], &mut one), STATUS_NONFINITE_OUTPUT); assert_eq!(kernel_swiglu(&[], &[], &mut one), STATUS_BAD_ARGUMENT); - assert_eq!( - kernel_swiglu(&[1.0], &[1.0, 2.0], &mut one), - STATUS_BAD_ARGUMENT - ); + assert_eq!(kernel_swiglu(&[1.0], &[1.0, 2.0], &mut one), STATUS_BAD_ARGUMENT); } #[test] @@ -87,9 +77,7 @@ fn windows_beyond_four_gib_elements_use_exact_u64_addressing() { let packet = stage_window(&v, &plan).unwrap(); let mut out = vec![f32::from_bits(0xdead_beef); count as usize]; assert_eq!(kernel_decode(&plan.params, &packet, &mut out), 0, "L{level}"); - let want: Vec = (start..start + count) - .map(|e| direct_element(&v, level, e)) - .collect(); + let want: Vec = (start..start + count).map(|e| direct_element(&v, level, e)).collect(); assert_bits_eq(&out, &want, &format!("L{level} expert {expert} {start}+{count}")); } } diff --git a/crates/model-format/tests/kar_levels/mod.rs b/crates/model-format/tests/kar_levels/mod.rs index 44f50aa3..f241cd87 100644 --- a/crates/model-format/tests/kar_levels/mod.rs +++ b/crates/model-format/tests/kar_levels/mod.rs @@ -8,15 +8,7 @@ fn round16(value: u64) -> u64 { value.div_ceil(16) * 16 } -fn record( - name: &str, - dims: &[u64], - group: u32, - stored: u8, - min: u8, - max: u8, - section_offset: u64, -) -> KarNestedRecord { +fn record(name: &str, dims: &[u64], group: u32, stored: u8, min: u8, max: u8, section_offset: u64) -> KarNestedRecord { let n_elements: u64 = dims.iter().product(); let n_padded = n_elements.div_ceil(u64::from(group)) * u64::from(group); let scales_bytes = n_padded / u64::from(group) * 2; @@ -98,5 +90,5 @@ pub(super) fn finite_image(a: &ArchiveView, seed: u64) -> Vec { image } -mod tensor_classes_follow_gguf_name; mod scratch_budget_reserves_releases; +mod tensor_classes_follow_gguf_name; diff --git a/crates/model-format/tests/kar_levels/scratch_budget_reserves_releases.rs b/crates/model-format/tests/kar_levels/scratch_budget_reserves_releases.rs index 10ce61c7..b359d660 100644 --- a/crates/model-format/tests/kar_levels/scratch_budget_reserves_releases.rs +++ b/crates/model-format/tests/kar_levels/scratch_budget_reserves_releases.rs @@ -3,19 +3,10 @@ #[allow(unused_imports)] use super::*; - #[test] fn scratch_budget_reserves_releases_and_reports_reuse_peak() { let base = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 2, 4)]); - let selector = KarLevelSelector::new( - base, - None, - LevelPolicy { - base: uniform(3), - overlay: uniform(3), - }, - ) - .unwrap(); + let selector = KarLevelSelector::new(base, None, LevelPolicy { base: uniform(3), overlay: uniform(3) }).unwrap(); let selection = selector.resolve(EXPERT).unwrap(); let small = selection.window(0, 64).unwrap().scratch(); let large = selection.expert(0, 8).unwrap().scratch(); @@ -26,13 +17,7 @@ fn scratch_budget_reserves_releases_and_reports_reuse_peak() { budget.reserve(large).unwrap(); budget.reserve(small).unwrap(); assert_eq!(budget.remaining(), 0); - assert_eq!( - budget.reserve(small), - Err(KarLevelsError::Budget { - needed: small.aligned, - available: 0 - }) - ); + assert_eq!(budget.reserve(small), Err(KarLevelsError::Budget { needed: small.aligned, available: 0 })); budget.release(small); budget.reserve(small).unwrap(); // An aligned total can exceed the raw total; accounting uses aligned. @@ -58,10 +43,7 @@ fn random_windows_plan_valid_device_parameters() { let selector = KarLevelSelector::new( archive(1, spec), None, - LevelPolicy { - base: uniform(level), - overlay: uniform(level), - }, + LevelPolicy { base: uniform(level), overlay: uniform(level) }, ) .unwrap(); let selection = selector.resolve("t.weight").unwrap(); @@ -80,26 +62,12 @@ fn random_windows_plan_valid_device_parameters() { fn stager_matches_the_reference_packet_and_refuses_short_or_changed_sources() { let base = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 2, 4)]); let image = finite_image(&base, 5); - let selector = KarLevelSelector::new( - base, - None, - LevelPolicy { - base: uniform(4), - overlay: uniform(4), - }, - ) - .unwrap(); + let selector = KarLevelSelector::new(base, None, LevelPolicy { base: uniform(4), overlay: uniform(4) }).unwrap(); let rows = selector.resolve(EXPERT).unwrap().expert(3, 1).unwrap(); let staged = stage_window(image.as_slice(), &rows.window.plan).unwrap(); - assert_eq!( - staged, - model::stage_packet(&rows.window.plan, &image).unwrap() - ); + assert_eq!(staged, model::stage_packet(&rows.window.plan, &image).unwrap()); // Truncated source: fail closed, never a partial packet. - assert_eq!( - stage_window(&image[..2000], &rows.window.plan), - Err(KarLevelsError::Read) - ); + assert_eq!(stage_window(&image[..2000], &rows.window.plan), Err(KarLevelsError::Read)); } #[test] @@ -107,9 +75,7 @@ fn expert_map_validation_and_cpu_reference_pipeline() { // Two layers, tiny shapes: hidden 64, ff 32, 4 experts. let (hidden, ff) = (64u64, 32u64); let mut specs: Vec = Vec::new(); - let names: Vec = (0..2) - .flat_map(|l| (0..3).map(move |r| expert_tensor_name(l, r))) - .collect(); + let names: Vec = (0..2).flat_map(|l| (0..3).map(move |r| expert_tensor_name(l, r))).collect(); let gate_dims = [hidden, ff, 4]; let down_dims = [ff, hidden, 4]; for (i, name) in names.iter().enumerate() { @@ -121,10 +87,7 @@ fn expert_map_validation_and_cpu_reference_pipeline() { let selector = KarLevelSelector::new( base, None, - LevelPolicy { - base: uniform(3).with(TensorClass::RoutedExpert, 4).unwrap(), - overlay: uniform(3), - }, + LevelPolicy { base: uniform(3).with(TensorClass::RoutedExpert, 4).unwrap(), overlay: uniform(3) }, ) .unwrap(); selector.validate_expert_map(2, 4, hidden, ff).unwrap(); @@ -148,43 +111,22 @@ fn expert_map_validation_and_cpu_reference_pipeline() { let decode = |i: usize| { let r = &rows[i]; let mut w = vec![0f32; r.window.plan.params.count as usize]; - assert_eq!( - model::kernel_decode(&r.window.plan.params, &packets[i], &mut w), - 0 - ); + assert_eq!(model::kernel_decode(&r.window.plan.params, &packets[i], &mut w), 0); w }; let (wg, wu, wd) = (decode(0), decode(1), decode(2)); let matvec = |w: &[f32], x: &[f64], cols: usize| -> Vec { - w.chunks(cols) - .map(|row| row.iter().zip(x).map(|(a, b)| f64::from(*a) * b).sum()) - .collect() + w.chunks(cols).map(|row| row.iter().zip(x).map(|(a, b)| f64::from(*a) * b).sum()).collect() }; let xd: Vec = x.iter().map(|v| f64::from(*v)).collect(); - let (g, u) = ( - matvec(&wg, &xd, hidden as usize), - matvec(&wu, &xd, hidden as usize), - ); - let act: Vec = g - .iter() - .zip(&u) - .map(|(g, u)| g / (1.0 + (-g).exp()) * u) - .collect(); + let (g, u) = (matvec(&wg, &xd, hidden as usize), matvec(&wu, &xd, hidden as usize)); + let act: Vec = g.iter().zip(&u).map(|(g, u)| g / (1.0 + (-g).exp()) * u).collect(); let want = matvec(&wd, &act, ff as usize); for (a, b) in got.iter().zip(&want) { - assert!( - (f64::from(*a) - b).abs() <= b.abs() * 1e-4 + 1e-6, - "{a} {b}" - ); + assert!((f64::from(*a) - b).abs() <= b.abs() * 1e-4 + 1e-6, "{a} {b}"); } // Scratch accounting matches the buffers the closed program allocates. let scratch = expert_scratch(&rows); - let packet_total: u64 = rows - .iter() - .map(|r| u64::from(r.window.plan.params.packet_bytes)) - .sum(); - assert_eq!( - scratch.raw, - packet_total + hidden * ff * 4 + hidden * 4 + 3 * ff * 4 + hidden * 4 + 4 - ); + let packet_total: u64 = rows.iter().map(|r| u64::from(r.window.plan.params.packet_bytes)).sum(); + assert_eq!(scratch.raw, packet_total + hidden * ff * 4 + hidden * 4 + 3 * ff * 4 + hidden * 4 + 4); } diff --git a/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs b/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs index 6d6399ef..17bb2854 100644 --- a/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs +++ b/crates/model-format/tests/kar_levels/tensor_classes_follow_gguf_name.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn tensor_classes_follow_gguf_name_suffixes() { for (name, class) in [ @@ -30,11 +29,7 @@ fn policy_levels_are_bounded_to_2_through_5() { assert!(ClassLevels::uniform(level).is_err(), "{level}"); assert!(uniform(2).with(TensorClass::Attention, level).is_err()); } - let levels = uniform(2) - .with(TensorClass::RoutedExpert, 4) - .unwrap() - .with(TensorClass::Embedding, 5) - .unwrap(); + let levels = uniform(2).with(TensorClass::RoutedExpert, 4).unwrap().with(TensorClass::Embedding, 5).unwrap(); assert_eq!(levels.level_for(TensorClass::RoutedExpert), 4); assert_eq!(levels.level_for(TensorClass::Embedding), 5); assert_eq!(levels.level_for(TensorClass::DenseFfn), 2); @@ -42,55 +37,31 @@ fn policy_levels_are_bounded_to_2_through_5() { #[test] fn base_only_selection_hand_computed_expert_window_and_scratch() { - let base = archive( - 1, - &[ - (EXPERT, &[64, 32, 4], 32, 4, 2, 4), - ("blk.3.attn_q.weight", &[64, 16], 32, 3, 2, 3), - ], - ); + let base = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 2, 4), ("blk.3.attn_q.weight", &[64, 16], 32, 3, 2, 3)]); let selector = KarLevelSelector::new( base, None, - LevelPolicy { - base: uniform(2).with(TensorClass::RoutedExpert, 3).unwrap(), - overlay: uniform(4), - }, + LevelPolicy { base: uniform(2).with(TensorClass::RoutedExpert, 3).unwrap(), overlay: uniform(4) }, ) .unwrap(); let selection = selector.resolve(EXPERT).unwrap(); - assert_eq!( - (selection.class, selection.slot, selection.level), - (TensorClass::RoutedExpert, ArchiveSlot::Base, 3) - ); + assert_eq!((selection.class, selection.slot, selection.level), (TensorClass::RoutedExpert, ArchiveSlot::Base, 3)); let rows = selection.expert(1, 2).unwrap(); // Expert 1 = elements 2048..4096: 64 words, 64 groups (group 32). let g = rows.window.plan.params; assert_eq!((g.level, g.count, g.head32, g.head_group), (3, 2048, 0, 0)); assert_eq!((g.window_words, g.window_groups), (64, 64)); assert_eq!((g.scales_offset, g.planes_offset), (64, 192)); - assert_eq!( - (g.plane_stride_words, g.packet_bytes), - (64, 192 + 3 * 64 * 4) - ); + assert_eq!((g.plane_stride_words, g.packet_bytes), (64, 192 + 3 * 64 * 4)); assert_eq!(rows.window.plan.start, 2048); - assert_eq!( - (rows.shape.columns, rows.shape.rows, rows.shape.tokens), - (64, 32, 2) - ); + assert_eq!((rows.shape.columns, rows.shape.rows, rows.shape.tokens), (64, 32, 2)); // Source ranges: book skip (2^3-2)*2 = 12 bytes into the books section. let r = selection.record; assert_eq!(rows.window.plan.book.archive_offset, r.books_offset + 12); assert_eq!(rows.window.plan.book.len, 16); - assert_eq!( - rows.window.plan.scales.archive_offset, - r.scales_offset + 64 * 2 - ); + assert_eq!(rows.window.plan.scales.archive_offset, r.scales_offset + 64 * 2); for (plane, range) in rows.window.plan.planes.iter().enumerate() { - assert_eq!( - range.archive_offset, - r.planes_offset + plane as u64 * u64::from(r.plane_stride_bytes) + 64 * 4 - ); + assert_eq!(range.archive_offset, r.planes_offset + plane as u64 * u64::from(r.plane_stride_bytes) + 64 * 4); } assert_eq!(rows.window.staged_source_bytes(), 16 + 128 + 3 * 256); // packet 960 + weights 8192 + input 512 + output 256 + status 4. @@ -105,30 +76,15 @@ fn base_only_selection_hand_computed_expert_window_and_scratch() { let attn = selector.resolve("blk.3.attn_q.weight").unwrap(); assert_eq!(attn.level, 2); assert_eq!(attn.window(0, 1024).unwrap().plan.params.level, 2); - assert!(matches!( - selector.resolve("blk.9.nothing.weight"), - Err(KarLevelsError::UnknownTensor(_)) - )); + assert!(matches!(selector.resolve("blk.9.nothing.weight"), Err(KarLevelsError::UnknownTensor(_)))); } #[test] fn overlay_replaces_by_name_with_its_own_level_and_dial() { - let specs: &[Spec] = &[ - (EXPERT, &[64, 32, 4], 32, 2, 2, 2), - ("blk.3.ffn_down.weight", &[64, 32], 32, 2, 2, 2), - ]; + let specs: &[Spec] = &[(EXPERT, &[64, 32, 4], 32, 2, 2, 2), ("blk.3.ffn_down.weight", &[64, 32], 32, 2, 2, 2)]; let base = archive(1, specs); - let overlay = archive( - 2, - &[ - (EXPERT, &[64, 32, 4], 32, 4, 3, 4), - ("blk.3.ffn_down.weight", &[64, 32], 32, 4, 3, 4), - ], - ); - let policy = LevelPolicy { - base: uniform(2), - overlay: uniform(3).with(TensorClass::RoutedExpert, 4).unwrap(), - }; + let overlay = archive(2, &[(EXPERT, &[64, 32, 4], 32, 4, 3, 4), ("blk.3.ffn_down.weight", &[64, 32], 32, 4, 3, 4)]); + let policy = LevelPolicy { base: uniform(2), overlay: uniform(3).with(TensorClass::RoutedExpert, 4).unwrap() }; let selector = KarLevelSelector::new(base, Some(overlay), policy).unwrap(); let expert = selector.resolve(EXPERT).unwrap(); assert_eq!((expert.slot, expert.level), (ArchiveSlot::Overlay, 4)); @@ -138,60 +94,32 @@ fn overlay_replaces_by_name_with_its_own_level_and_dial() { let from_overlay = expert.window(0, 1024).unwrap(); assert_eq!(from_overlay.slot, ArchiveSlot::Overlay); assert_eq!(from_overlay.plan.planes.len(), 4); - assert_eq!( - selector.archive(ArchiveSlot::Overlay).unwrap().sha256(), - &[2; 32] - ); - assert_eq!( - selector.archive(ArchiveSlot::Base).unwrap().sha256(), - &[1; 32] - ); + assert_eq!(selector.archive(ArchiveSlot::Overlay).unwrap().sha256(), &[2; 32]); + assert_eq!(selector.archive(ArchiveSlot::Base).unwrap().sha256(), &[1; 32]); // A policy level outside the serving record's dial is refused at plan time. let strict = KarLevelSelector::new( archive(1, specs), - Some(archive( - 2, - &[ - (EXPERT, &[64, 32, 4], 32, 4, 3, 4), - ("blk.3.ffn_down.weight", &[64, 32], 32, 4, 3, 4), - ], - )), + Some(archive(2, &[(EXPERT, &[64, 32, 4], 32, 4, 3, 4), ("blk.3.ffn_down.weight", &[64, 32], 32, 4, 3, 4)])), LevelPolicy { base: uniform(2), overlay: uniform(2), // below the overlay dial 3..=4 }, ) .unwrap(); - assert!(matches!( - strict.resolve(EXPERT).unwrap().window(0, 64), - Err(KarLevelsError::Window { .. }) - )); + assert!(matches!(strict.resolve(EXPERT).unwrap().window(0, 64), Err(KarLevelsError::Window { .. }))); // Base level above the record's stored planes is likewise refused. - let high = KarLevelSelector::new( - archive(1, specs), - None, - LevelPolicy { - base: uniform(3), - overlay: uniform(3), - }, - ) - .unwrap(); + let high = + KarLevelSelector::new(archive(1, specs), None, LevelPolicy { base: uniform(3), overlay: uniform(3) }).unwrap(); assert!(high.resolve(EXPERT).unwrap().window(0, 64).is_err()); } #[test] fn inconsistent_overlays_are_rejected_before_any_selection() { let base = || archive(1, &[(EXPERT, &[64, 32, 4], 32, 2, 2, 2)]); - let policy = LevelPolicy { - base: uniform(2), - overlay: uniform(3), - }; + let policy = LevelPolicy { base: uniform(2), overlay: uniform(3) }; // Overlay of an unknown tensor. - let orphan = archive( - 2, - &[("blk.9.ffn_up_exps.weight", &[64, 32, 4], 32, 4, 3, 4)], - ); + let orphan = archive(2, &[("blk.9.ffn_up_exps.weight", &[64, 32, 4], 32, 4, 3, 4)]); assert!(KarLevelSelector::new(base(), Some(orphan), policy).is_err()); // Same name, different shape. let reshaped = archive(2, &[(EXPERT, &[64, 32, 5], 32, 4, 3, 4)]); @@ -207,13 +135,7 @@ fn inconsistent_overlays_are_rejected_before_any_selection() { #[test] fn resident_prefix_matches_the_control_plane_formula_and_budget() { - let base = archive( - 1, - &[ - (EXPERT, &[64, 32, 4], 32, 4, 2, 4), - ("blk.3.attn_q.weight", &[96, 7], 64, 3, 2, 3), - ], - ); + let base = archive(1, &[(EXPERT, &[64, 32, 4], 32, 4, 2, 4), ("blk.3.attn_q.weight", &[96, 7], 64, 3, 2, 3)]); let sources: Vec = base .records .values() @@ -233,34 +155,15 @@ fn resident_prefix_matches_the_control_plane_formula_and_budget() { plane_stride_bytes: r.plane_stride_bytes, }) .collect(); - let selector = KarLevelSelector::new( - base, - None, - LevelPolicy { - base: uniform(3), - overlay: uniform(3), - }, - ) - .unwrap(); + let selector = KarLevelSelector::new(base, None, LevelPolicy { base: uniform(3), overlay: uniform(3) }).unwrap(); let mut total = 0; for source in &sources { let selected = selector.resolve(&source.name).unwrap(); let bytes = selected.resident_prefix_bytes().unwrap(); - assert_eq!( - bytes, - source.gpu_resident_bytes(3).unwrap(), - "{}", - source.name - ); + assert_eq!(bytes, source.gpu_resident_bytes(3).unwrap(), "{}", source.name); total += bytes; } let names = sources.iter().map(|s| s.name.as_str()); - assert_eq!( - selector.resident_bytes(names.clone(), total).unwrap(), - total - ); - assert!(matches!( - selector.resident_bytes(names, total - 1), - Err(KarLevelsError::Budget { .. }) - )); + assert_eq!(selector.resident_bytes(names.clone(), total).unwrap(), total); + assert!(matches!(selector.resident_bytes(names, total - 1), Err(KarLevelsError::Budget { .. }))); } diff --git a/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs b/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs index b6be2acf..c4d0a649 100644 --- a/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs +++ b/crates/model-format/tests/kar_ple/fused_integrity_scan_preserves_crc.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { fn bit_step(mut crc: u32, bytes: &[u8]) -> u32 { @@ -45,28 +44,14 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { let mut inspection = fixture.inspect(); let pin: [u8; 32] = Sha256::digest(&bytes).into(); for chunk in [1, 17, 255, 257, 1025, 2048] { - let mut input = Counted { - bytes: &bytes, - read: 0, - eof: 0, - }; - verify_integrity_stream( - &mut input, - &inspection.sections, - bytes.len() as u64, - &pin, - &mut vec![0; chunk], - ) - .unwrap(); + let mut input = Counted { bytes: &bytes, read: 0, eof: 0 }; + verify_integrity_stream(&mut input, &inspection.sections, bytes.len() as u64, &pin, &mut vec![0; chunk]) + .unwrap(); assert_eq!(input.read, bytes.len()); // No separate payload reread. assert_eq!(input.eof, 1); } - inspection - .verify_integrity(bytes.len() as u64, &pin) - .unwrap(); - let row = inspection - .decode_range("fixture.part0", 2, 0, 160, scalar) - .unwrap(); + inspection.verify_integrity(bytes.len() as u64, &pin).unwrap(); + let row = inspection.decode_range("fixture.part0", 2, 0, 160, scalar).unwrap(); for (i, value) in row.iter().enumerate() { assert_eq!(value.to_bits(), EXPECTED[i / 32][i % 4]); } @@ -74,18 +59,10 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { for at in [700, 800, 1100] { let mut changed = bytes.clone(); changed[at] ^= 1; - let error = verify_integrity_stream( - &mut &changed[..], - &inspection.sections, - bytes.len() as u64, - &pin, - &mut [0; 257], - ) - .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR full archive SHA-256 mismatch") - )); + let error = + verify_integrity_stream(&mut &changed[..], &inspection.sections, bytes.len() as u64, &pin, &mut [0; 257]) + .unwrap_err(); + assert!(matches!(error, KarError::Integrity("KAR full archive SHA-256 mismatch"))); } // An admitted header can contain a wrong stored CRC while its whole-file // SHA is correct. Preserve CRC failure, including after the first section. @@ -103,37 +80,18 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { &mut [0; 1025], ) .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR payload CRC-32 mismatch") - )); - let error = verify_integrity_stream( - &mut &bad_crc[..], - &bad_inspection.sections, - bad_crc.len() as u64, - &pin, - &mut [0; 257], - ) - .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR full archive SHA-256 mismatch") - )); + assert!(matches!(error, KarError::Integrity("KAR payload CRC-32 mismatch"))); + let error = + verify_integrity_stream(&mut &bad_crc[..], &bad_inspection.sections, bad_crc.len() as u64, &pin, &mut [0; 257]) + .unwrap_err(); + assert!(matches!(error, KarError::Integrity("KAR full archive SHA-256 mismatch"))); for length in [bytes.len() - 1, bytes.len() + 1] { let mut altered = bytes.clone(); altered.resize(length, 0); - let error = verify_integrity_stream( - &mut &altered[..], - &inspection.sections, - bytes.len() as u64, - &pin, - &mut [0; 257], - ) - .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR full archive SHA-256 mismatch") - )); + let error = + verify_integrity_stream(&mut &altered[..], &inspection.sections, bytes.len() as u64, &pin, &mut [0; 257]) + .unwrap_err(); + assert!(matches!(error, KarError::Integrity("KAR full archive SHA-256 mismatch"))); } // The file-backed (read-ahead) scan agrees with the stream scan on every verdict: a changed payload byte // is a SHA mismatch even though the section CRC fails too, and a longer or shorter file is refused. @@ -142,30 +100,15 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { changed[at] ^= 1; let changed_fixture = Fixture::new(&changed); let mut changed_inspection = changed_fixture.inspect(); - let error = changed_inspection - .verify_integrity(bytes.len() as u64, &pin) - .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR full archive SHA-256 mismatch") - )); + let error = changed_inspection.verify_integrity(bytes.len() as u64, &pin).unwrap_err(); + assert!(matches!(error, KarError::Integrity("KAR full archive SHA-256 mismatch"))); } let mut short_inspection = Fixture::new(&bytes).inspect(); - let error = short_inspection - .verify_integrity(bytes.len() as u64 + 1, &pin) - .unwrap_err(); - assert!( - matches!(error, KarError::Io(_) | KarError::Range(_)), - "{error:?}" - ); + let error = short_inspection.verify_integrity(bytes.len() as u64 + 1, &pin).unwrap_err(); + assert!(matches!(error, KarError::Io(_) | KarError::Range(_)), "{error:?}"); let mut bad_crc_inspection = bad_fixture.inspect(); - let error = bad_crc_inspection - .verify_integrity(bad_crc.len() as u64, &bad_pin) - .unwrap_err(); - assert!(matches!( - error, - KarError::Integrity("KAR payload CRC-32 mismatch") - )); + let error = bad_crc_inspection.verify_integrity(bad_crc.len() as u64, &bad_pin).unwrap_err(); + assert!(matches!(error, KarError::Integrity("KAR payload CRC-32 mismatch"))); // The public verifier still goes through the combined scan before mapping; // no successful serving capability can be minted from this miniature file. let error = VerifiedKarPleArtifact::verify( @@ -174,10 +117,7 @@ fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { ) .err() .unwrap(); - assert!(matches!( - error, - KarError::Integrity("KAR payload CRC-32 mismatch") - )); + assert!(matches!(error, KarError::Integrity("KAR payload CRC-32 mismatch"))); } /// Directory/header fuzz with the digest and CRC recomputed, so the mutation @@ -251,10 +191,8 @@ fn recomputed_integrity_fuzz_admits_only_gpu_consistent_records() { let mut out = vec![0f32; count as usize]; let status = kernel_decode(&plan.params, &packet, &mut out); assert!(status == 0 || status == 2, "byte {at}: status {status}"); - if status == 0 && level == 2 && record.group == 32 && record.planes_stored == 2 - { - let want = inspection - .clone_decode_for_fuzz(&record.name, 2, start as usize, count as usize); + if status == 0 && level == 2 && record.group == 32 && record.planes_stored == 2 { + let want = inspection.clone_decode_for_fuzz(&record.name, 2, start as usize, count as usize); if let Some(want) = want { assert_eq!( out.iter().map(|v| v.to_bits()).collect::>(), diff --git a/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs b/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs index 002c9ad7..d8ec9081 100644 --- a/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs +++ b/crates/model-format/tests/kar_ple/literal_rows_and_partition_books.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn literal_rows_and_partition_books_decode_exactly_in_requested_order() { assert_eq!(oracle_crc(b"123456789"), 0xcbf4_3926); @@ -13,35 +12,19 @@ fn literal_rows_and_partition_books_decode_exactly_in_requested_order() { assert_eq!(inspected.summary().archive_bytes, 1280); assert_eq!(inspected.tensor_sources()[0].dimensions, [160, 2]); for part in [1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1] { - let row = inspected - .decode_range(&format!("fixture.part{part}"), 2, 0, 160, scalar) - .unwrap(); + let row = inspected.decode_range(&format!("fixture.part{part}"), 2, 0, 160, scalar).unwrap(); let expected: Vec = (0..160) .map(|i| { let bits = EXPECTED[i / 32][i % 4]; - if part == 0 { - bits - } else { - (f32::from_bits(bits) * 2.0).to_bits() - } + if part == 0 { bits } else { (f32::from_bits(bits) * 2.0).to_bits() } }) .collect(); - assert_eq!( - row.iter().map(|x| x.to_bits()).collect::>(), - expected - ); + assert_eq!(row.iter().map(|x| x.to_bits()).collect::>(), expected); } } #[test] fn literal_scale_plane_packet_fields_and_cross_group_range_are_preserved() { - fn fields( - s: &[u16], - b: &[u16], - p: &[&[u32]], - g: u16, - start: usize, - o: &mut [f32], - ) -> Result<(), String> { + fn fields(s: &[u16], b: &[u16], p: &[&[u32]], g: u16, start: usize, o: &mut [f32]) -> Result<(), String> { assert_eq!(s, SCALES); assert_eq!(b, BOOKS[0]); assert_eq!(p[0], [0xcccc_cccc; 5]); @@ -50,16 +33,9 @@ fn literal_scale_plane_packet_fields_and_cross_group_range_are_preserved() { } let f = Fixture::new(&tiny_archive()); let mut reader = f.inspect(); - reader - .decode_range("fixture.part0", 2, 0, 160, fields) - .unwrap(); - let got = reader - .decode_range("fixture.part0", 2, 31, 3, scalar) - .unwrap(); - assert_eq!( - got.iter().map(|v| v.to_bits()).collect::>(), - [0x40000000, 0xc0800000, 0xbf800000] - ); + reader.decode_range("fixture.part0", 2, 0, 160, fields).unwrap(); + let got = reader.decode_range("fixture.part0", 2, 31, 3, scalar).unwrap(); + assert_eq!(got.iter().map(|v| v.to_bits()).collect::>(), [0x40000000, 0xc0800000, 0xbf800000]); } #[test] @@ -70,10 +46,7 @@ fn asymmetric_plane_bytes_low_high_bits_and_negative_zero_scale_are_exact() { put16(&mut b, 770, 0x8000); payload_integrity(&mut b); let fixture = Fixture::new(&b); - let got = fixture - .inspect() - .decode_range("fixture.part0", 2, 0, 64, scalar) - .unwrap(); + let got = fixture.inspect().decode_range("fixture.part0", 2, 0, 64, scalar).unwrap(); let mut wanted = [0xc000_0000u32; 64]; wanted[0] = 0x3f00_0000; wanted[15] = 0xbf00_0000; @@ -96,10 +69,7 @@ fn range_overflow_empty_huge_unknown_and_unstored_level_refuse_before_decoder() ("fixture.part0", 0, 0, 1), ("fixture.part0", 3, 0, 1), ] { - assert!( - r.decode_range(name, level, start, count, unexpected_decoder) - .is_err() - ); + assert!(r.decode_range(name, level, start, count, unexpected_decoder).is_err()); } } #[test] @@ -111,10 +81,7 @@ fn retained_descriptor_reads_original_after_path_replacement() { std::fs::write(&f.path, b"different object").unwrap(); r.verify_payloads().unwrap(); let got = r.decode_range("fixture.part0", 2, 0, 4, scalar).unwrap(); - assert_eq!( - got.iter().map(|v| v.to_bits()).collect::>(), - EXPECTED[0] - ); + assert_eq!(got.iter().map(|v| v.to_bits()).collect::>(), EXPECTED[0]); // This proves same-descriptor reads, not protection against same-inode writes. } #[test] @@ -203,28 +170,20 @@ fn verifier_rejects_full_archive_digest_virtual_provenance_and_tiny_mapping() { let f = Fixture::new(&b); let mut p = profile(&b); p.archive_sha256 = [0x66; 32]; - let error = VerifiedKarPleArtifact::verify( - f.inspect().into_owner_controlled(), - KarPleProfile::new(p).unwrap(), - ) - .err() - .unwrap(); + let error = VerifiedKarPleArtifact::verify(f.inspect().into_owner_controlled(), KarPleProfile::new(p).unwrap()) + .err() + .unwrap(); assert!(error.to_string().contains("full archive SHA")); let mut p = profile(&b); p.virtual_f32_sha256 = [0x77; 32]; - let error = VerifiedKarPleArtifact::verify( - f.inspect().into_owner_controlled(), - KarPleProfile::new(p).unwrap(), - ) - .err() - .unwrap(); + let error = VerifiedKarPleArtifact::verify(f.inspect().into_owner_controlled(), KarPleProfile::new(p).unwrap()) + .err() + .unwrap(); assert!(error.to_string().contains("provenance identity")); - let error = VerifiedKarPleArtifact::verify( - f.inspect().into_owner_controlled(), - KarPleProfile::new(profile(&b)).unwrap(), - ) - .err() - .unwrap(); + let error = + VerifiedKarPleArtifact::verify(f.inspect().into_owner_controlled(), KarPleProfile::new(profile(&b)).unwrap()) + .err() + .unwrap(); assert!(error.to_string().contains("partition/source mapping")); // Full serving geometry deliberately remains impossible for this tiny file. } @@ -244,10 +203,8 @@ fn serving_verifier_refuses_nonfinite_partition_book_before_later_mapping() { derived_f32_offset: 1280, derived_f32_sha256: [0x23; 32], }); - let result = VerifiedKarPleArtifact::verify( - fixture.inspect().into_owner_controlled(), - KarPleProfile::new(spec).unwrap(), - ); + let result = + VerifiedKarPleArtifact::verify(fixture.inspect().into_owner_controlled(), KarPleProfile::new(spec).unwrap()); assert!(result.err().unwrap().to_string().contains("nonfinite book")); // There is still no successful tiny serving verification or fake capability. } diff --git a/crates/model-format/tests/kar_ple/mod.rs b/crates/model-format/tests/kar_ple/mod.rs index b7a30ca2..b586d4a7 100644 --- a/crates/model-format/tests/kar_ple/mod.rs +++ b/crates/model-format/tests/kar_ple/mod.rs @@ -8,10 +8,7 @@ use std::{ const NAMES: &[u8] = b"fixture.part0\0fixture.part1\0"; const SCALES: [u16; 5] = [0x3c00, 0x4000, 0x3800, 0xbc00, 0x0001]; -const BOOKS: [[u16; 4]; 2] = [ - [0xc000, 0xb800, 0x3800, 0x4000], - [0xc400, 0xbc00, 0x3c00, 0x4400], -]; +const BOOKS: [[u16; 4]; 2] = [[0xc000, 0xb800, 0x3800, 0x4000], [0xc400, 0xbc00, 0x3c00, 0x4400]]; // Literal expected binary32 products, fixed before candidate implementation. const EXPECTED: [[u32; 4]; 5] = [ [0xc0000000, 0xbf000000, 0x3f000000, 0x40000000], @@ -77,10 +74,9 @@ pub(super) fn tiny_archive() -> Vec { b[104..107].copy_from_slice(&[1, 2, 1]); b[128..160].fill(0x11); b[640..640 + NAMES.len()].copy_from_slice(NAMES); - for (part, record, rows, section, books, planes, stride) in [ - (0, 256, 2u64, 768, 800, 816, 48), - (1, 448, 1, 1024, 1040, 1056, 32), - ] { + for (part, record, rows, section, books, planes, stride) in + [(0, 256, 2u64, 768, 800, 816, 48), (1, 448, 1, 1024, 1040, 1056, 32)] + { put32(&mut b, record, part as u32 * 14); put16(&mut b, record + 4, 13); b[record + 6] = 2; @@ -117,11 +113,7 @@ pub(super) fn tiny_archive() -> Vec { } for group in 0..5 { put32(&mut b, planes as usize + row * 20 + group * 4, 0xcccc_cccc); - put32( - &mut b, - planes as usize + stride + row * 20 + group * 4, - 0xaaaa_aaaa, - ); + put32(&mut b, planes as usize + stride + row * 20 + group * 4, 0xaaaa_aaaa); } } } @@ -137,14 +129,9 @@ impl Fixture { static NEXT: AtomicU64 = AtomicU64::new(0); let base = std::env::var_os("CARGO_TARGET_DIR") .map(PathBuf::from) - .unwrap_or_else(|| { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-kar-sdet") - }); - let directory = base.join(format!( - "kar-ple-fixture-{}-{}", - std::process::id(), - NEXT.fetch_add(1, Ordering::Relaxed) - )); + .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra161-kar-sdet")); + let directory = + base.join(format!("kar-ple-fixture-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); std::fs::create_dir_all(&directory).unwrap(); let path = directory.join("synthetic.kar"); std::fs::write(&path, bytes).unwrap(); @@ -180,11 +167,7 @@ fn scalar( start: usize, out: &mut [f32], ) -> Result<(), String> { - if group != 32 - || planes.len() != 2 - || book.len() != 4 - || scales.iter().chain(book).any(|w| w & 0x7c00 == 0x7c00) - { + if group != 32 || planes.len() != 2 || book.len() != 4 || scales.iter().chain(book).any(|w| w & 0x7c00 == 0x7c00) { return Err("independent finite L2 oracle domain".into()); } for (i, value) in out.iter_mut().enumerate() { @@ -195,14 +178,7 @@ fn scalar( } Ok(()) } -fn unexpected_decoder( - _: &[u16], - _: &[u16], - _: &[&[u32]], - _: u16, - _: usize, - _: &mut [f32], -) -> Result<(), String> { +fn unexpected_decoder(_: &[u16], _: &[u16], _: &[&[u32]], _: u16, _: usize, _: &mut [f32]) -> Result<(), String> { panic!("invalid range reached scalar decoder") } fn profile(bytes: &[u8]) -> KarPleProfileSpec { @@ -232,21 +208,14 @@ fn refused(bytes: &[u8]) -> String { impl KarInspection { /// Fuzz helper: the file-backed CPU oracle with the test's L2 decoder, or /// `None` when that decoder's finite-domain refuses the window. - fn clone_decode_for_fuzz( - &self, - name: &str, - level: u8, - start: usize, - count: usize, - ) -> Option> { + fn clone_decode_for_fuzz(&self, name: &str, level: u8, start: usize, count: usize) -> Option> { let index = self.sources.iter().position(|s| s.name == name)?; - let record: [u8; RECORD_BYTES] = self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES] - .try_into() - .ok()?; + let record: [u8; RECORD_BYTES] = + self.directory[index * RECORD_BYTES..(index + 1) * RECORD_BYTES].try_into().ok()?; let mut file = self.file.try_clone().ok()?; decode_record_range(&mut file, &record, level, start, count, scalar).ok() } } -mod literal_rows_and_partition_books; mod fused_integrity_scan_preserves_crc; +mod literal_rows_and_partition_books; diff --git a/crates/model-format/tests/qwen_artifact_binding/fixtures.rs b/crates/model-format/tests/qwen_artifact_binding/fixtures.rs index a716b50f..d0e4aed8 100644 --- a/crates/model-format/tests/qwen_artifact_binding/fixtures.rs +++ b/crates/model-format/tests/qwen_artifact_binding/fixtures.rs @@ -53,13 +53,13 @@ struct MetadataLocation { mod geometry_fn; #[allow(unused_imports)] -pub use geometry_fn::geometry; -#[allow(unused_imports)] pub use geometry_fn::byte_len; #[allow(unused_imports)] -pub use geometry_fn::logical_indexes; +pub use geometry_fn::geometry; #[allow(unused_imports)] pub use geometry_fn::index; +#[allow(unused_imports)] +pub use geometry_fn::logical_indexes; mod metadata_fn; #[allow(unused_imports)] pub use metadata_fn::metadata; diff --git a/crates/model-format/tests/qwen_artifact_binding/fixtures/geometry_fn.rs b/crates/model-format/tests/qwen_artifact_binding/fixtures/geometry_fn.rs index f2cce1f5..99c8e995 100644 --- a/crates/model-format/tests/qwen_artifact_binding/fixtures/geometry_fn.rs +++ b/crates/model-format/tests/qwen_artifact_binding/fixtures/geometry_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub fn geometry(kind: u32) -> (u64, u64) { let &(_, elements, bytes) = FORMATS.iter().find(|x| x.0 == kind).unwrap(); (elements, bytes) @@ -29,13 +28,7 @@ pub fn logical_indexes() -> [TensorIndex; 2] { 1 } }); - tensors.push(TensorInfo { - name, - dimensions: dims.to_vec(), - kind, - offset: 0, - bytes: byte_len(kind, dims), - }); + tensors.push(TensorInfo { name, dimensions: dims.to_vec(), kind, offset: 0, bytes: byte_len(kind, dims) }); }; for (name, dims) in [ ("token_embd.weight", vec![2560, 248320]), @@ -44,11 +37,7 @@ pub fn logical_indexes() -> [TensorIndex; 2] { ("output_hc_norm.weight", vec![10240]), ("output_hc_up.weight", vec![320, 10240]), ] { - add( - name.to_owned(), - &dims, - if dims.len() == 1 { Some(0) } else { None }, - ); + add(name.to_owned(), &dims, if dims.len() == 1 { Some(0) } else { None }); } for layer in 0..48 { for (name, dims, required) in [ @@ -129,10 +118,7 @@ pub fn logical_indexes() -> [TensorIndex; 2] { offset: 0, bytes: 28_800_138_240, }; - [ - index(0, tensors, 4096, 54_817_524_224), - index(1, vec![table], 192, 28_800_138_432), - ] + [index(0, tensors, 4096, 54_817_524_224), index(1, vec![table], 192, 28_800_138_432)] } pub fn index(shard: u64, tensors: Vec, data_start: u64, file_size: u64) -> TensorIndex { @@ -144,11 +130,7 @@ pub fn index(shard: u64, tensors: Vec, data_start: u64, file_size: u summary: Summary { tensors: tensors.len() as u64, metadata: 0, - architecture: if shard == 0 { - Some("qwen4exp".to_owned()) - } else { - None - }, + architecture: if shard == 0 { Some("qwen4exp".to_owned()) } else { None }, split_no: Some(shard), split_count: Some(2), split_tensors_count: Some(1224), diff --git a/crates/model-format/tests/qwen_artifact_binding/fixtures/impl_tinyowner.rs b/crates/model-format/tests/qwen_artifact_binding/fixtures/impl_tinyowner.rs index d47b54fe..cbf7f9a4 100644 --- a/crates/model-format/tests/qwen_artifact_binding/fixtures/impl_tinyowner.rs +++ b/crates/model-format/tests/qwen_artifact_binding/fixtures/impl_tinyowner.rs @@ -4,14 +4,9 @@ use super::*; impl TinyOwner { - pub fn new( - shard: u64, - rows: &[(String, u32, Vec)], - mut metadata: BTreeMap, - ) -> Self { + pub fn new(shard: u64, rows: &[(String, u32, Vec)], mut metadata: BTreeMap) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - let fixture_root = - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra157-sdet/fixtures"); + let fixture_root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/stra157-sdet/fixtures"); std::fs::create_dir_all(&fixture_root).unwrap(); let directory = fixture_root.join(format!( "leleka-sdet143-{}-{}", @@ -71,14 +66,7 @@ impl TinyOwner { } } let kind = u32::from_le_bytes(bytes[kind_offset..kind_offset + 4].try_into().unwrap()); - metadata_locations.insert( - key, - MetadataLocation { - key: key_offset, - value: kind_offset + 4, - kind, - }, - ); + metadata_locations.insert(key, MetadataLocation { key: key_offset, value: kind_offset + 4, kind }); } let mut tensors = Vec::new(); let mut payloads = Vec::new(); @@ -93,18 +81,9 @@ impl TinyOwner { } bytes.extend(kind.to_le_bytes()); bytes.extend(offset.to_le_bytes()); - tensors.push(TensorInfo { - name: name.clone(), - dimensions: dims.clone(), - kind: *kind, - offset, - bytes: size, - }); - payloads.push( - (0..size) - .map(|i| ((i * 17 + number as u64 * 43 + shard * 97) % 251) as u8) - .collect::>(), - ); + tensors.push(TensorInfo { name: name.clone(), dimensions: dims.clone(), kind: *kind, offset, bytes: size }); + payloads + .push((0..size).map(|i| ((i * 17 + number as u64 * 43 + shard * 97) % 251) as u8).collect::>()); offset += size; } bytes.resize(bytes.len().div_ceil(32) * 32, 0); @@ -114,14 +93,7 @@ impl TinyOwner { bytes.extend(payload); } std::fs::write(&path, &bytes).unwrap(); - Self { - directory, - path, - tensors, - payloads, - bytes, - metadata_locations, - } + Self { directory, path, tensors, payloads, bytes, metadata_locations } } /// Mutate only a metadata key's bytes after VerifiedGgufFile::open. @@ -157,10 +129,7 @@ impl TinyOwner { pub fn open(&self) -> VerifiedGgufFile { let digest = Sha256::digest(&self.bytes); - let hex = digest - .iter() - .map(|b| format!("{b:02x}")) - .collect::(); + let hex = digest.iter().map(|b| format!("{b:02x}")).collect::(); VerifiedGgufFile::open(&self.path, &format!("sha256:{hex}")).unwrap() } pub fn replace_path(&self) { diff --git a/crates/model-format/tests/qwen_artifact_binding/fixtures/metadata_fn.rs b/crates/model-format/tests/qwen_artifact_binding/fixtures/metadata_fn.rs index a79ac1a7..fabe167b 100644 --- a/crates/model-format/tests/qwen_artifact_binding/fixtures/metadata_fn.rs +++ b/crates/model-format/tests/qwen_artifact_binding/fixtures/metadata_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub fn metadata() -> BTreeMap { let mut map = BTreeMap::new(); for (key, value) in [ @@ -39,14 +38,8 @@ pub fn metadata() -> BTreeMap { ] { map.insert(format!("qwen4exp.{key}"), Meta::U64(value)); } - map.insert( - "general.architecture".to_owned(), - Meta::Text("qwen4exp".to_owned()), - ); - map.insert( - "qwen4exp.attention.layer_norm_rms_epsilon".to_owned(), - Meta::F32(0.000001), - ); + map.insert("general.architecture".to_owned(), Meta::Text("qwen4exp".to_owned())); + map.insert("qwen4exp.attention.layer_norm_rms_epsilon".to_owned(), Meta::F32(0.000001)); map.insert("qwen4exp.rope.freq_base".to_owned(), Meta::F32(10_000_000.)); for (key, values) in [ ("attention.compress_ratios", [0, 0, 0, 4].repeat(12)), @@ -55,42 +48,29 @@ pub fn metadata() -> BTreeMap { ( "ple.head_offsets", vec![ - 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, - 160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, - 300001275, + 0, 20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297, 160000374, 180000455, + 200000548, 220000655, 240000802, 260000955, 280001114, 300001275, ], ), ( "ple.head_vocab_sizes", vec![ - 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, - 20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171, + 20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, 20000081, 20000093, + 20000107, 20000147, 20000153, 20000159, 20000161, 20000171, ], ), - ( - "ple.layer_multipliers", - vec![23703573157769, 20109073645365, 8052911324071], - ), + ("ple.layer_multipliers", vec![23703573157769, 20109073645365, 8052911324071]), ] { map.insert(format!("qwen4exp.{key}"), Meta::U64s(values)); } - map.insert( - "tokenizer.ggml.model".to_owned(), - Meta::Text("gpt2".to_owned()), - ); - map.insert( - "tokenizer.ggml.pre".to_owned(), - Meta::Text("qwen35".to_owned()), - ); + map.insert("tokenizer.ggml.model".to_owned(), Meta::Text("gpt2".to_owned())); + map.insert("tokenizer.ggml.pre".to_owned(), Meta::Text("qwen35".to_owned())); map.insert( "tokenizer.ggml.tokens".to_owned(), Meta::Texts((0..248320).map(|i| format!("synthetic_{i}")).collect()), ); map.insert("tokenizer.ggml.merges".to_owned(), Meta::Texts(vec![])); - map.insert( - "tokenizer.chat_template".to_owned(), - Meta::Text("synthetic template".to_owned()), - ); + map.insert("tokenizer.chat_template".to_owned(), Meta::Text("synthetic template".to_owned())); for (key, id) in [("bos", 248044), ("padding", 248044), ("eos", 248046)] { map.insert(format!("tokenizer.ggml.{key}_token_id"), Meta::U64(id)); } diff --git a/crates/model-format/tests/qwen_artifact_binding/large_rows_chunk_by_stream.rs b/crates/model-format/tests/qwen_artifact_binding/large_rows_chunk_by_stream.rs index fbb7de50..c986c7d4 100644 --- a/crates/model-format/tests/qwen_artifact_binding/large_rows_chunk_by_stream.rs +++ b/crates/model-format/tests/qwen_artifact_binding/large_rows_chunk_by_stream.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn large_rows_chunk_by_stream_buffer_abort_immediately_then_recover_exact_cursor() { let (mut artifact, fixtures) = miniature(); @@ -40,19 +39,13 @@ fn large_rows_chunk_by_stream_buffer_abort_immediately_then_recover_exact_cursor .stream_row(role, 0, |chunk| { callbacks += 1; assert_eq!(chunk, &fixtures[0].payloads[14][..65536]); - Err(io::Error::new( - io::ErrorKind::Interrupted, - "synthetic callback abort", - )) + Err(io::Error::new(io::ErrorKind::Interrupted, "synthetic callback abort")) }) .unwrap_err() }); assert_eq!(callbacks, 1); assert!(matches!(error, BindingError::Io(_))); - assert_eq!( - error.source().unwrap().to_string(), - "synthetic callback abort" - ); + assert_eq!(error.source().unwrap().to_string(), "synthetic callback abort"); let mut recovered = Vec::new(); artifact .stream_row(role, 2, |chunk| { @@ -68,10 +61,7 @@ fn sec_uc143_invalid_role_rank_row_expert_and_file_size_fail_before_callback() { // [SEC][UC-143] malicious rank/index/size cannot deliver partial bytes. let (mut artifact, fixtures) = miniature(); let plain = TensorRole::Global(GlobalRole::Output); - let expert = TensorRole::Layer { - layer: 0, - role: LayerRole::FfnUpExperts, - }; + let expert = TensorRole::Layer { layer: 0, role: LayerRole::FfnUpExperts }; let mut calls = 0; assert!( artifact @@ -115,26 +105,14 @@ fn sec_uc143_invalid_role_rank_row_expert_and_file_size_fail_before_callback() { ); assert!( artifact - .stream_row( - TensorRole::Layer { - layer: 48, - role: LayerRole::SsmA - }, - 0, - |_| { - calls += 1; - Ok(()) - } - ) + .stream_row(TensorRole::Layer { layer: 48, role: LayerRole::SsmA }, 0, |_| { + calls += 1; + Ok(()) + }) .is_err() ); assert_eq!(calls, 0); - std::fs::OpenOptions::new() - .write(true) - .open(&fixtures[0].path) - .unwrap() - .set_len(32) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&fixtures[0].path).unwrap().set_len(32).unwrap(); assert!( artifact .stream_row(plain, 0, |_| { @@ -172,10 +150,7 @@ fn sec_uc143_checked_row_planner_refuses_alignment_product_tensor_and_file_overf 9 => tensor.dimensions[1] = u64::MAX, _ => tensor.byte_length += 1, }; - assert!( - plan_row(&tensor, 0, None).is_err(), - "malformed descriptor case{case}" - ); + assert!(plan_row(&tensor, 0, None).is_err(), "malformed descriptor case{case}"); } let mut tensor = base; tensor.dimensions = vec![256, u64::MAX, 2]; @@ -273,12 +248,7 @@ fn sec_uc143_rank1_float_vectors_refuse_retained_file_truncation_before_callback // [SEC][UC-143] retained FD size is checked before delivering vector data. for (kind, expected) in RANK1_VECTOR_BYTES { let (mut artifact, fixtures) = rank1_vector_owner(kind, expected); - std::fs::OpenOptions::new() - .write(true) - .open(&fixtures[0].path) - .unwrap() - .set_len(32) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&fixtures[0].path).unwrap().set_len(32).unwrap(); let mut callbacks = 0; let error = artifact .stream_row(RANK1_ROLE, 0, |_| { diff --git a/crates/model-format/tests/qwen_artifact_binding/mod.rs b/crates/model-format/tests/qwen_artifact_binding/mod.rs index 8e69cb49..427edb8e 100644 --- a/crates/model-format/tests/qwen_artifact_binding/mod.rs +++ b/crates/model-format/tests/qwen_artifact_binding/mod.rs @@ -59,14 +59,8 @@ fn validate( metadata: &[MetadataSnapshot; 2], ) -> Result { validate_logical_views([ - LogicalShardView { - index: &indexes[0], - metadata: metadata[0].clone(), - }, - LogicalShardView { - index: &indexes[1], - metadata: metadata[1].clone(), - }, + LogicalShardView { index: &indexes[0], metadata: metadata[0].clone() }, + LogicalShardView { index: &indexes[1], metadata: metadata[1].clone() }, ]) } fn failure(indexes: &[TensorIndex; 2], metadata: &[MetadataSnapshot; 2]) -> BindingError { @@ -134,10 +128,7 @@ fn role(name: &str) -> TensorRole { "ple_value.weight" => LayerRole::PleValue, _ => panic!("unexpected independent fixture role"), }; - TensorRole::Layer { - layer: layer.parse().unwrap(), - role, - } + TensorRole::Layer { layer: layer.parse().unwrap(), role } } fn miniature() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { @@ -150,45 +141,23 @@ fn miniature() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { rows.push(("fixture.expert".to_owned(), 14, vec![256, 3, 2])); rows.push(("fixture.large".to_owned(), 0, vec![32768, 3])); let first = TinyOwner::new(0, &rows, fixtures::metadata()); - let second = TinyOwner::new( - 1, - &[("fixture.ple".to_owned(), 20, vec![160, 5])], - BTreeMap::new(), - ); + let second = TinyOwner::new(1, &[("fixture.ple".to_owned(), 20, vec![160, 5])], BTreeMap::new()); let owners = [first.open(), second.open()]; for (owner, fixture) in owners.iter().zip([&first, &second]) { for (actual, expected) in owner.index().tensors.iter().zip(&fixture.tensors) { assert_eq!(actual.dimensions, expected.dimensions); - assert_eq!( - (actual.kind, actual.offset, actual.bytes), - (expected.kind, expected.offset, expected.bytes) - ); + assert_eq!((actual.kind, actual.offset, actual.bytes), (expected.kind, expected.offset, expected.bytes)); } } let mut roles = BTreeMap::new(); for (i, &(kind, _, _)) in fixtures::FORMATS.iter().enumerate() { - let role = TensorRole::Layer { - layer: i as u8, - role: LayerRole::FfnUpShared, - }; + let role = TensorRole::Layer { layer: i as u8, role: LayerRole::FfnUpShared }; roles.insert(role, resolved(&owners[0], 0, i)); assert_eq!(owners[0].index().tensors[i].kind, kind); } - roles.insert( - TensorRole::Layer { - layer: 0, - role: LayerRole::FfnUpExperts, - }, - resolved(&owners[0], 0, 13), - ); - roles.insert( - TensorRole::Global(GlobalRole::Output), - resolved(&owners[0], 0, 14), - ); - roles.insert( - TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), - resolved(&owners[1], 1, 0), - ); + roles.insert(TensorRole::Layer { layer: 0, role: LayerRole::FfnUpExperts }, resolved(&owners[0], 0, 13)); + roles.insert(TensorRole::Global(GlobalRole::Output), resolved(&owners[0], 0, 14)); + roles.insert(TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), resolved(&owners[1], 1, 0)); ( Qwen4ExpArtifact { shards: owners, @@ -216,13 +185,8 @@ fn resolved(owner: &VerifiedGgufFile, shard: u8, number: usize) -> ResolvedTenso } fn split_probe_owner(shard: u64, tensor_count: usize, placeholder_key: bool) -> TinyOwner { - let rows = (0..tensor_count) - .map(|number| (format!("fixture.tensor.{number}"), 0, vec![1])) - .collect::>(); - let mut metadata = BTreeMap::from([( - "general.architecture".to_owned(), - Meta::Text("not-qwen4exp".to_owned()), - )]); + let rows = (0..tensor_count).map(|number| (format!("fixture.tensor.{number}"), 0, vec![1])).collect::>(); + let mut metadata = BTreeMap::from([("general.architecture".to_owned(), Meta::Text("not-qwen4exp".to_owned()))]); if placeholder_key { // Same byte length as split.no; changed to that key only after open. metadata.insert("zzzzzzzz".to_owned(), Meta::U16(7)); @@ -247,21 +211,13 @@ const RANK1_VECTOR_BYTES: [(u32, &[u8]); 3] = [ const RANK1_ROLE: TensorRole = TensorRole::Global(GlobalRole::OutputHcNorm); fn rank1_vector_owner(kind: u32, expected: &[u8]) -> (Qwen4ExpArtifact, [TinyOwner; 2]) { - let mut first = TinyOwner::new( - 0, - &[("fixture.vector".to_owned(), kind, vec![4])], - BTreeMap::new(), - ); + let mut first = TinyOwner::new(0, &[("fixture.vector".to_owned(), kind, vec![4])], BTreeMap::new()); assert_eq!(first.payloads[0].len(), expected.len()); let payload_start = first.bytes.len() - expected.len(); first.bytes[payload_start..].copy_from_slice(expected); first.payloads[0].copy_from_slice(expected); std::fs::write(&first.path, &first.bytes).unwrap(); - let second = TinyOwner::new( - 1, - &[("fixture.unused".to_owned(), 0, vec![1])], - BTreeMap::new(), - ); + let second = TinyOwner::new(1, &[("fixture.unused".to_owned(), 0, vec![1])], BTreeMap::new()); let owners = [first.open(), second.open()]; assert_eq!(owners[0].index().tensors[0].dimensions, [4]); let roles = BTreeMap::from([(RANK1_ROLE, resolved(&owners[0], 0, 0))]); @@ -278,6 +234,6 @@ fn rank1_vector_owner(kind: u32, expected: &[u8]) -> (Qwen4ExpArtifact, [TinyOwn ) } +mod large_rows_chunk_by_stream; mod production_identity_bytes_match; mod sec_uc143_inventory_missing_extra; -mod large_rows_chunk_by_stream; diff --git a/crates/model-format/tests/qwen_artifact_binding/production_identity_bytes_match.rs b/crates/model-format/tests/qwen_artifact_binding/production_identity_bytes_match.rs index 7198e95b..0028f1c0 100644 --- a/crates/model-format/tests/qwen_artifact_binding/production_identity_bytes_match.rs +++ b/crates/model-format/tests/qwen_artifact_binding/production_identity_bytes_match.rs @@ -3,24 +3,15 @@ #[allow(unused_imports)] use super::*; - #[test] fn production_identity_bytes_match_the_canonical_verified_shard_digests() { // Literal identities from STRA-143 Speck v4 and independently verified // source shards; this is not a fixture pin or an artifact admission bypass. let expected = [ - ( - 54_817_524_224, - "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3", - ), - ( - 28_800_138_432, - "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113", - ), + (54_817_524_224, "4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"), + (28_800_138_432, "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113"), ]; - for ((actual_size, digest), (expected_size, expected_hex)) in - PINNED_IDENTITIES.iter().zip(expected) - { + for ((actual_size, digest), (expected_size, expected_hex)) in PINNED_IDENTITIES.iter().zip(expected) { let actual_hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect(); assert_eq!(*actual_size, expected_size); assert_eq!(actual_hex, expected_hex); @@ -31,16 +22,10 @@ fn production_identity_bytes_match_the_canonical_verified_shard_digests() { fn legacy_profile_check_ignores_well_formed_unrelated_tokenizer_value_types() { for field in ["tokenizer.ggml.tokens", "tokenizer.ggml.bos_token_id"] { let mut metadata = fixtures::metadata(); - metadata.insert( - field.to_owned(), - Meta::Text("synthetic unrelated field".to_owned()), - ); + metadata.insert(field.to_owned(), Meta::Text("synthetic unrelated field".to_owned())); let fixture = TinyOwner::new(0, &[("fixture.profile".to_owned(), 0, vec![1])], metadata); crate::gguf::check_flash_next_profile(&fixture.path).unwrap(); - assert!( - crate::gguf::tokenizer_metadata(&fixture.path).is_err(), - "tokenizer reader must reject {field}" - ); + assert!(crate::gguf::tokenizer_metadata(&fixture.path).is_err(), "tokenizer reader must reject {field}"); } } @@ -54,46 +39,26 @@ fn complete_1224_logical_manifest_matches_all_roles_locations_and_13_formats() { for (shard, index) in indexes.iter().enumerate() { for (number, expected) in index.tensors.iter().enumerate() { let found = &actual.roles[&role(&expected.name)]; - assert_eq!( - (found.shard(), found.tensor_number()), - (shard as u8, number) - ); + assert_eq!((found.shard(), found.tensor_number()), (shard as u8, number)); assert_eq!(found.name(), expected.name); assert_eq!(found.dimensions(), expected.dimensions); assert_eq!(found.kind(), expected.kind); - assert_eq!( - found.byte_length(), - fixtures::byte_len(expected.kind, &expected.dimensions) - ); - assert_eq!( - found.absolute_start(), - index.summary.data_start + expected.offset - ); + assert_eq!(found.byte_length(), fixtures::byte_len(expected.kind, &expected.dimensions)); + assert_eq!(found.absolute_start(), index.summary.data_start + expected.offset); kinds.insert(found.kind()); } } assert_eq!(kinds, fixtures::FORMATS.iter().map(|x| x.0).collect()); for layer in 0..48 { - let qsa = TensorRole::Layer { - layer, - role: LayerRole::AttnQ, - }; - let gdn = TensorRole::Layer { - layer, - role: LayerRole::AttnQkv, - }; + let qsa = TensorRole::Layer { layer, role: LayerRole::AttnQ }; + let gdn = TensorRole::Layer { layer, role: LayerRole::AttnQkv }; assert_eq!(actual.roles.contains_key(&qsa), layer % 4 == 3); assert_eq!(actual.roles.contains_key(&gdn), layer % 4 != 3); } - assert_eq!( - actual.tokenizer.special_ids["tokenizer.ggml.eos_token_id"], - 248046 - ); + assert_eq!(actual.tokenizer.special_ids["tokenizer.ggml.eos_token_id"], 248046); assert_eq!(actual.topology.ple_eos_token_id, 248044); assert_eq!(actual.tokenizer.tokens.len(), 248320); - println!( - "complete logical manifest:1224 roles,13 formats,36GDN/12QSA; no real pinned-bind claim" - ); + println!("complete logical manifest:1224 roles,13 formats,36GDN/12QSA; no real pinned-bind claim"); } #[test] @@ -143,13 +108,7 @@ fn typed_topology_retains_all_frozen_scalar_and_array_values() { [64, 4, 128, 2048, 4, 128, 16, 48, 6144, 160] ); assert_eq!( - [ - t.ple_ngram_size, - t.ple_heads_per_ngram, - t.ple_conv_kernel, - t.ple_eos_token_id, - t.ple_image_token_id - ], + [t.ple_ngram_size, t.ple_heads_per_ngram, t.ple_conv_kernel, t.ple_eos_token_id, t.ple_image_token_id], [3, 8, 4, 248044, 248056] ); assert_eq!(t.compression_ratios, [0, 0, 0, 4].repeat(12)); @@ -162,12 +121,7 @@ fn typed_topology_retains_all_frozen_scalar_and_array_values() { ("ple.head_vocab_sizes", &t.ple_head_vocab_sizes), ("ple.layer_multipliers", &t.ple_layer_multipliers), ] { - let Meta::U64s(expected) = fixtures::metadata() - .remove(&format!("qwen4exp.{key}")) - .unwrap() - else { - panic!() - }; + let Meta::U64s(expected) = fixtures::metadata().remove(&format!("qwen4exp.{key}")).unwrap() else { panic!() }; assert_eq!(actual, &expected); } } @@ -180,18 +134,9 @@ fn sec_uc143_every_profile_field_missing_or_mismatched_fails_before_publication( let keys = metadata[0].values.keys().cloned().collect::>(); for key in keys { let original = metadata[0].values.remove(&key).unwrap(); - assert!( - matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), - "missing {key}" - ); - metadata[0].values.insert( - key.clone(), - MetadataValue::Text("malicious type confusion".to_owned()), - ); - assert!( - matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), - "type {key}" - ); + assert!(matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), "missing {key}"); + metadata[0].values.insert(key.clone(), MetadataValue::Text("malicious type confusion".to_owned())); + assert!(matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), "type {key}"); let changed = match &original { MetadataValue::Unsigned(v) => MetadataValue::Unsigned(v + 1), MetadataValue::Float(_) => MetadataValue::Float(f64::NAN), @@ -203,10 +148,7 @@ fn sec_uc143_every_profile_field_missing_or_mismatched_fails_before_publication( _ => panic!(), }; metadata[0].values.insert(key.clone(), changed); - assert!( - matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), - "value {key}" - ); + assert!(matches!(failure(&indexes, &metadata), BindingError::Metadata(_)), "value {key}"); metadata[0].values.insert(key, original); } } @@ -219,26 +161,12 @@ fn sec_uc143_split_topology_tokenizer_role_error_precedence_and_safe_messages() indexes[0].summary.split_no = Some(1); metadata[0].values.clear(); indexes[0].tensors[0].name = "../../secret\0payload".to_owned(); - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Split("split.no") - )); + assert!(matches!(failure(&indexes, &metadata), BindingError::Split("split.no"))); indexes[0].summary.split_no = Some(0); - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Metadata(_) - )); + assert!(matches!(failure(&indexes, &metadata), BindingError::Metadata(_))); metadata = snapshots(); - metadata[0] - .tokenizer - .as_mut() - .unwrap() - .special_ids - .insert("tokenizer.ggml.eos_token_id".to_owned(), 248044); - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Tokenizer(_) - )); + metadata[0].tokenizer.as_mut().unwrap().special_ids.insert("tokenizer.ggml.eos_token_id".to_owned(), 248044); + assert!(matches!(failure(&indexes, &metadata), BindingError::Tokenizer(_))); metadata = snapshots(); let error = failure(&indexes, &metadata); assert!(matches!(error, BindingError::Role(_))); @@ -263,10 +191,7 @@ fn sec_uc143_split_identity_and_tokenizer_special_ids_reject_independently() { } _ => metadata[shard].architecture = Some("other".to_owned()), }; - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Split(_) | BindingError::Metadata(_) - )); + assert!(matches!(failure(&indexes, &metadata), BindingError::Split(_) | BindingError::Metadata(_))); } } let indexes = fixtures::logical_indexes(); @@ -275,20 +200,9 @@ fn sec_uc143_split_identity_and_tokenizer_special_ids_reject_independently() { let key = format!("tokenizer.ggml.{key}_token_id"); let token = metadata[0].tokenizer.as_mut().unwrap(); let previous = token.special_ids.insert(key.clone(), 1).unwrap(); - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Tokenizer(_) - )); - metadata[0] - .tokenizer - .as_mut() - .unwrap() - .special_ids - .insert(key, previous); + assert!(matches!(failure(&indexes, &metadata), BindingError::Tokenizer(_))); + metadata[0].tokenizer.as_mut().unwrap().special_ids.insert(key, previous); } metadata[0].tokenizer = None; - assert!(matches!( - failure(&indexes, &metadata), - BindingError::Tokenizer(_) - )); + assert!(matches!(failure(&indexes, &metadata), BindingError::Tokenizer(_))); } diff --git a/crates/model-format/tests/qwen_artifact_binding/sec_uc143_inventory_missing_extra.rs b/crates/model-format/tests/qwen_artifact_binding/sec_uc143_inventory_missing_extra.rs index 5b9957c0..e49a3c36 100644 --- a/crates/model-format/tests/qwen_artifact_binding/sec_uc143_inventory_missing_extra.rs +++ b/crates/model-format/tests/qwen_artifact_binding/sec_uc143_inventory_missing_extra.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn sec_uc143_inventory_missing_extra_duplicate_wrong_family_shard_shape_kind_and_range() { // [SEC][UC-143] adversarial closed inventory with zero published partial object. @@ -14,11 +13,7 @@ fn sec_uc143_inventory_missing_extra_duplicate_wrong_family_shard_shape_kind_and 0 => indexes[0].tensors[0].name = "unregistered.weight".to_owned(), 1 => indexes[1].tensors[0].name = indexes[0].tensors[0].name.clone(), 2 => { - let t = indexes[0] - .tensors - .iter_mut() - .find(|t| t.name == "blk.0.attn_qkv.weight") - .unwrap(); + let t = indexes[0].tensors.iter_mut().find(|t| t.name == "blk.0.attn_qkv.weight").unwrap(); t.name = "blk.0.attn_q.weight".to_owned(); } 3 => { @@ -28,14 +23,7 @@ fn sec_uc143_inventory_missing_extra_duplicate_wrong_family_shard_shape_kind_and } 4 => indexes[0].tensors[0].dimensions[1] += 1, 5 => indexes[0].tensors[0].kind = 24, - 6 => { - indexes[0] - .tensors - .iter_mut() - .find(|t| t.name == "blk.0.ffn_gate_inp.weight") - .unwrap() - .kind = 0 - } + 6 => indexes[0].tensors.iter_mut().find(|t| t.name == "blk.0.ffn_gate_inp.weight").unwrap().kind = 0, 7 => indexes[0].tensors[0].bytes -= 1, 8 => indexes[0].tensors[0].offset = u64::MAX, _ => indexes[0].summary.file_size = 4097, @@ -54,16 +42,8 @@ fn sec_uc143_inventory_missing_extra_duplicate_wrong_family_shard_shape_kind_and #[test] fn actual_public_bind_rejects_minis_at_identity_before_split_or_metadata() { - let a = TinyOwner::new( - 1, - &[("fixture.pin".to_owned(), 0, vec![1])], - BTreeMap::new(), - ); - let b = TinyOwner::new( - 0, - &[("fixture.pin".to_owned(), 0, vec![1])], - BTreeMap::new(), - ); + let a = TinyOwner::new(1, &[("fixture.pin".to_owned(), 0, vec![1])], BTreeMap::new()); + let b = TinyOwner::new(0, &[("fixture.pin".to_owned(), 0, vec![1])], BTreeMap::new()); let error = match Qwen4ExpArtifact::bind(a.open(), b.open()) { Ok(_) => panic!("public pins bypassed"), Err(error) => error, @@ -78,11 +58,9 @@ fn sec_uc143_production_orchestrator_rejects_fresh_split_faults_before_profile() // fixture fault injection so split_snapshot observes data different from // the retained index summary; this is not an immutability guarantee. for shard in 0..2 { - for (field, expected_error) in [ - ("split.no", "split.no"), - ("split.count", "split.count"), - ("split.tensors.count", "split.tensors.count"), - ] { + for (field, expected_error) in + [("split.no", "split.no"), ("split.count", "split.count"), ("split.tensors.count", "split.tensors.count")] + { for missing in [false, true] { let first = split_probe_owner(0, 1223, false); let second = split_probe_owner(1, 1, false); @@ -90,24 +68,16 @@ fn sec_uc143_production_orchestrator_rejects_fresh_split_faults_before_profile() let fixtures = [&first, &second]; let before = std::fs::metadata(&fixtures[shard].path).unwrap().len(); if missing { - fixtures[shard] - .replace_metadata_key_after_open(field, &"x".repeat(field.len())); + fixtures[shard].replace_metadata_key_after_open(field, &"x".repeat(field.len())); } else { match field { - "split.no" => { - fixtures[shard].set_metadata_u16_after_open(field, (1 - shard) as u16) - } + "split.no" => fixtures[shard].set_metadata_u16_after_open(field, (1 - shard) as u16), "split.count" => fixtures[shard].set_metadata_u16_after_open(field, 3), - "split.tensors.count" => { - fixtures[shard].set_metadata_i32_after_open(field, 1225) - } + "split.tensors.count" => fixtures[shard].set_metadata_i32_after_open(field, 1225), _ => unreachable!(), } } - assert_eq!( - std::fs::metadata(&fixtures[shard].path).unwrap().len(), - before - ); + assert_eq!(std::fs::metadata(&fixtures[shard].path).unwrap().len(), before); // The open-time index still reports the original valid split. assert_eq!(owners[shard].index().summary.split_no, Some(shard as u64)); let error = bind_after_identity_error(owners); @@ -139,10 +109,7 @@ fn sec_uc143_production_orchestrator_preserves_index_precedence_and_valid_contin let first = split_probe_owner(0, 1223, false); let second = split_probe_owner(1, 1, false); let error = bind_after_identity_error([first.open(), second.open()]); - assert!(matches!( - error, - BindingError::Metadata("general.architecture") - )); + assert!(matches!(error, BindingError::Metadata("general.architecture"))); } #[test] @@ -157,11 +124,7 @@ fn sec_uc143_production_orchestrator_rejects_duplicate_split_key_after_open() { let error = bind_after_identity_error(owners); assert_eq!(error.to_string(), "GGUF stream I/O failed"); match error { - BindingError::Io(source) => assert!( - source - .to_string() - .contains("duplicate GGUF metadata key: split.no") - ), + BindingError::Io(source) => assert!(source.to_string().contains("duplicate GGUF metadata key: split.no")), _ => panic!("duplicate split key did not fail in the parser stage"), } } @@ -175,10 +138,7 @@ fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_byt } let snapshot = artifact.shards[0].metadata_snapshot().unwrap(); assert_eq!(snapshot.architecture.as_deref(), Some("qwen4exp")); - assert_eq!( - snapshot.tokenizer.unwrap().tokens[248046], - "synthetic_248046" - ); + assert_eq!(snapshot.tokenizer.unwrap().tokens[248046], "synthetic_248046"); let secondary = artifact.shards[1].metadata_snapshot().unwrap(); assert!(secondary.architecture.is_none()); assert!(secondary.tokenizer.is_none()); @@ -187,24 +147,14 @@ fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_byt for row in [0, 2] { let mut actual = Vec::new(); artifact - .stream_row( - TensorRole::Layer { - layer: number as u8, - role: LayerRole::FfnUpShared, - }, - row, - |chunk| { - assert!(chunk.len() <= 65536); - actual.extend_from_slice(chunk); - Ok(()) - }, - ) + .stream_row(TensorRole::Layer { layer: number as u8, role: LayerRole::FfnUpShared }, row, |chunk| { + assert!(chunk.len() <= 65536); + actual.extend_from_slice(chunk); + Ok(()) + }) .unwrap(); let width = fixtures::byte_len(kind, &[256]); - assert_eq!( - actual, - &fixtures[0].payloads[number][(row * width) as usize..((row + 1) * width) as usize] - ); + assert_eq!(actual, &fixtures[0].payloads[number][(row * width) as usize..((row + 1) * width) as usize]); } } for expert in 0..2 { @@ -212,10 +162,7 @@ fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_byt let mut actual = Vec::new(); artifact .stream_expert_row( - TensorRole::Layer { - layer: 0, - role: LayerRole::FfnUpExperts, - }, + TensorRole::Layer { layer: 0, role: LayerRole::FfnUpExperts }, expert, row, |chunk| { @@ -231,18 +178,11 @@ fn sec_uc143_both_replaced_paths_preserve_owned_metadata_and_rank2_rank3_ple_byt for row in [0, 4] { let mut actual = Vec::new(); artifact - .stream_row( - TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), - row, - |chunk| { - actual.extend_from_slice(chunk); - Ok(()) - }, - ) + .stream_row(TensorRole::Global(GlobalRole::PerLayerTokenEmbedding), row, |chunk| { + actual.extend_from_slice(chunk); + Ok(()) + }) .unwrap(); - assert_eq!( - actual, - fixtures[1].payloads[0][row as usize * 90..(row as usize + 1) * 90] - ); + assert_eq!(actual, fixtures[1].payloads[0][row as usize * 90..(row as usize + 1) * 90]); } } diff --git a/crates/model-format/tests/qwen_rows_sdet/file_size_mutation_is_refused.rs b/crates/model-format/tests/qwen_rows_sdet/file_size_mutation_is_refused.rs index b12d2a07..fa7bf826 100644 --- a/crates/model-format/tests/qwen_rows_sdet/file_size_mutation_is_refused.rs +++ b/crates/model-format/tests/qwen_rows_sdet/file_size_mutation_is_refused.rs @@ -3,17 +3,11 @@ #[allow(unused_imports)] use super::*; - #[test] fn file_size_mutation_is_refused_before_and_after_contiguous_read() { let (mut artifact, owners) = tiny_tiles(); let mut calls = 0; - std::fs::OpenOptions::new() - .write(true) - .open(&owners[1].path) - .unwrap() - .set_len(32) - .unwrap(); + std::fs::OpenOptions::new().write(true).open(&owners[1].path).unwrap().set_len(32).unwrap(); assert!( artifact .stream_rows(PLE, 0, 64, |_| { @@ -30,20 +24,14 @@ fn file_size_mutation_is_refused_before_and_after_contiguous_read() { calls += 1; assert_eq!(chunk.len(), 65536); if calls == 1 { - std::fs::OpenOptions::new() - .write(true) - .open(&owners[0].path)? - .set_len(before + 1)?; + std::fs::OpenOptions::new().write(true).open(&owners[0].path)?.set_len(before + 1)?; } Ok(()) }) .unwrap_err() }); assert!(matches!(error, BindingError::Io(_))); - assert_eq!( - calls, 2, - "post-read failure does not undo already delivered callback bytes" - ); + assert_eq!(calls, 2, "post-read failure does not undo already delivered callback bytes"); } #[test] @@ -72,11 +60,7 @@ fn positional_ple_reader_returns_exactly_the_bytes_stream_row_returns() { } else { old = vec![0; 90]; } - assert_eq!( - &batch[slot * 90..(slot + 1) * 90], - &old[..], - "pass {pass} row {row}" - ); + assert_eq!(&batch[slot * 90..(slot + 1) * 90], &old[..], "pass {pass} row {row}"); } } assert!(reader.snapshot().cache_hits > 0); @@ -87,14 +71,6 @@ fn row_table_source_refuses_non_tables_and_a_resized_shard() { let (artifact, owners) = tiny_tiles(); assert!(artifact.row_table_source(VECTOR).is_err(), "rank 1"); assert!(artifact.row_table_source(EXPERT).is_err(), "rank 3"); - std::fs::OpenOptions::new() - .write(true) - .open(&owners[1].path) - .unwrap() - .set_len(32) - .unwrap(); - assert!(matches!( - artifact.row_table_source(PLE), - Err(BindingError::Io(_)) - )); + std::fs::OpenOptions::new().write(true).open(&owners[1].path).unwrap().set_len(32).unwrap(); + assert!(matches!(artifact.row_table_source(PLE), Err(BindingError::Io(_)))); } diff --git a/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs b/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs index 02c23603..14f038e6 100644 --- a/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs +++ b/crates/model-format/tests/qwen_rows_sdet/matrix_and_secondary_spans_equal.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - #[test] fn matrix_and_secondary_spans_equal_literal_and_legacy_rows_for_all_encoded_kinds() { let (mut artifact, _owners) = tiny_tiles(); @@ -19,15 +18,8 @@ fn matrix_and_secondary_spans_equal_literal_and_legacy_rows_for_all_encoded_kind }) .unwrap(); } - assert_eq!( - actual, old, - "kind {}, span {first}+{count}", - FORMATS[number].0 - ); - assert_eq!( - actual, - literal_bytes(first * width, count * width, number as u64, 0) - ); + assert_eq!(actual, old, "kind {}, span {first}+{count}", FORMATS[number].0); + assert_eq!(actual, literal_bytes(first * width, count * width, number as u64, 0)); } } for (first, count) in SPANS { @@ -78,10 +70,7 @@ fn every_expert_first_tail_and_last_span_stays_in_its_own_encoded_plane() { .unwrap(); } assert_eq!(actual, old); - assert_eq!( - actual, - literal_bytes((expert * ROWS + first) * 210, count * 210, 14, 0) - ); + assert_eq!(actual, literal_bytes((expert * ROWS + first) * 210, count * 210, 14, 0)); } } } @@ -118,14 +107,8 @@ fn retained_fd_and_chunked_streams_preserve_large_tiles_after_both_paths_are_rep }); assert_eq!(sizes, [65536, 65536]); assert_eq!(actual, literal_bytes(0, 131072, 13, 0)); - assert_eq!( - rows(&mut artifact, LARGE, 64, 6), - literal_bytes(131072, 12288, 13, 0) - ); - assert_eq!( - rows(&mut artifact, PLE, 63, 7), - literal_bytes(5670, 630, 0, 1) - ); + assert_eq!(rows(&mut artifact, LARGE, 64, 6), literal_bytes(131072, 12288, 13, 0)); + assert_eq!(rows(&mut artifact, PLE, 63, 7), literal_bytes(5670, 630, 0, 1)); } #[test] @@ -142,14 +125,7 @@ fn invalid_count_rank_indices_and_cross_expert_spans_never_invoke_consumer() { (VECTOR, 0, 2), (VECTOR, 1, 1), (EXPERT, 0, 1), - ( - TensorRole::Layer { - layer: 48, - role: LayerRole::SsmA, - }, - 0, - 1, - ), + (TensorRole::Layer { layer: 48, role: LayerRole::SsmA }, 0, 1), ] { assert!( artifact @@ -249,12 +225,6 @@ fn tile_callback_error_stops_immediately_and_next_span_reseeks_exactly() { }); assert!(matches!(error, BindingError::Io(_))); assert_eq!(calls, 1); - assert_eq!( - error.source().unwrap().to_string(), - "owned tile consumer abort" - ); - assert_eq!( - rows(&mut artifact, LARGE, 69, 1), - literal_bytes(141312, 2048, 13, 0) - ); + assert_eq!(error.source().unwrap().to_string(), "owned tile consumer abort"); + assert_eq!(rows(&mut artifact, LARGE, 69, 1), literal_bytes(141312, 2048, 13, 0)); } diff --git a/crates/model-format/tests/qwen_rows_sdet/mod.rs b/crates/model-format/tests/qwen_rows_sdet/mod.rs index 0cf9b29c..027da3bb 100644 --- a/crates/model-format/tests/qwen_rows_sdet/mod.rs +++ b/crates/model-format/tests/qwen_rows_sdet/mod.rs @@ -21,18 +21,12 @@ const FORMATS: [(u32, u64); 13] = [ ]; const SPANS: [(u64, u64); 4] = [(0, 64), (63, 7), (64, 6), (69, 1)]; const LARGE: TensorRole = TensorRole::Global(GlobalRole::Output); -const EXPERT: TensorRole = TensorRole::Layer { - layer: 0, - role: LayerRole::FfnUpExperts, -}; +const EXPERT: TensorRole = TensorRole::Layer { layer: 0, role: LayerRole::FfnUpExperts }; const VECTOR: TensorRole = TensorRole::Global(GlobalRole::OutputHcNorm); const PLE: TensorRole = TensorRole::Global(GlobalRole::PerLayerTokenEmbedding); fn matrix(number: usize) -> TensorRole { - TensorRole::Layer { - layer: number as u8, - role: LayerRole::FfnUpShared, - } + TensorRole::Layer { layer: number as u8, role: LayerRole::FfnUpShared } } fn tiny_tiles() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { @@ -46,11 +40,7 @@ fn tiny_tiles() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { ("fixture.tile.vector".to_owned(), 0, vec![256]), ]); let first = TinyOwner::new(0, &tensors, BTreeMap::new()); - let second = TinyOwner::new( - 1, - &[("fixture.tile.ple".to_owned(), 20, vec![160, ROWS])], - BTreeMap::new(), - ); + let second = TinyOwner::new(1, &[("fixture.tile.ple".to_owned(), 20, vec![160, ROWS])], BTreeMap::new()); let owners = [first.open(), second.open()]; let mut roles = BTreeMap::new(); for number in 0..13 { @@ -75,9 +65,7 @@ fn tiny_tiles() -> (Qwen4ExpArtifact, [TinyOwner; 2]) { // Independent literal fixture emission contract, not either row-read product. fn literal_bytes(start: u64, length: u64, tensor: u64, shard: u64) -> Vec { - (start..start + length) - .map(|i| ((i * 17 + tensor * 43 + shard * 97) % 251) as u8) - .collect() + (start..start + length).map(|i| ((i * 17 + tensor * 43 + shard * 97) % 251) as u8).collect() } fn rows(artifact: &mut Qwen4ExpArtifact, role: TensorRole, first: u64, count: u64) -> Vec { @@ -92,5 +80,5 @@ fn rows(artifact: &mut Qwen4ExpArtifact, role: TensorRole, first: u64, count: u6 bytes } -mod matrix_and_secondary_spans_equal; mod file_size_mutation_is_refused; +mod matrix_and_secondary_spans_equal; diff --git a/crates/native-cpu-expert/build.rs b/crates/native-cpu-expert/build.rs index e0d34139..2667f58f 100644 --- a/crates/native-cpu-expert/build.rs +++ b/crates/native-cpu-expert/build.rs @@ -1,6 +1,6 @@ //! CPU numerical consumers are Rust; no C++/GGML archives are linked. fn main() { - // The remaining extern calls are system libc/libm (affinity, stack admission, - // and Original's float expf), not model kernels or a C++ runtime. - println!("cargo:rerun-if-changed=src/rust_codebooks.rs"); + // The remaining extern calls are system libc/libm (affinity, stack admission, + // and Original's float expf), not model kernels or a C++ runtime. + println!("cargo:rerun-if-changed=src/rust_codebooks.rs"); } diff --git a/crates/native-cpu-expert/examples/kernel_ab.rs b/crates/native-cpu-expert/examples/kernel_ab.rs index 0d98dc71..544826e8 100644 --- a/crates/native-cpu-expert/examples/kernel_ab.rs +++ b/crates/native-cpu-expert/examples/kernel_ab.rs @@ -1,3347 +1,3992 @@ -#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry warnings of their own. -#![deny(warnings, clippy::all)] -//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++ reference outputs and -//! the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run directory `D`; this example only -//! reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the crate only, no module in the production library. -//! -//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived sizes, finite -//! FP16 block headers and activations; any mismatch refuses the WHOLE directory -//! kernel_ab compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] -//! verify D, run our trees in fresh processes (`run-tree`), compare with the C++ -//! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case -//! declares with its basis), write `R/case-.rust-.out` and one -//! COMPONENT_KERNEL record per case and tree to `R/records/` -//! kernel_ab run-tree D --tree T --out R [--pin CPU] [--case ID] -//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or only ID -//! -//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for timing with the -//! explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second half (STRA-318, S0.8b2): -//! -//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] -//! [--llc-bytes B] -//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh process times ONE -//! case in the resident and the streamed regime on the pinned CPU and writes the KAB1-time -//! JSON (writer "rust"); no statistics -//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] -//! [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH] -//! the alternation runner (ARCHITECT 395f0394 sec 1.3): std::process::Command only. Per -//! round it starts FRESH processes for the cells {cpp, rust} x {avx512, avx2} (each twice, -//! a and b, for the A/A pairs) in the order of a seeded schedule file written before the -//! first run, and writes COMPONENT_KERNEL round records. It computes NO statistics: no -//! class, no interval, no A/A verdict (those are S0.10b, STRA-313). -//! -//! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D -//! cargo test -p leleka-native-cpu-expert --example kernel_ab - -use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, cpu_kernel_report, rust_topology}; -use sha2::{Digest, Sha256}; -use std::cell::Cell; -use std::collections::{BTreeMap, BTreeSet}; -use std::ffi::OsString; -use std::fs::{self, File}; -use std::io::{Read, Write}; -use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode}; -use std::sync::OnceLock; -use std::time::{Instant, SystemTime, UNIX_EPOCH}; - -const IN_MAGIC: u32 = 0x4942_414B; -const OUT_MAGIC: u32 = 0x4F42_414B; -const IN_HEADER: usize = 64; -const OUT_HEADER: usize = 20; -const H: usize = 2560; -const FF: usize = 640; -const MAX_ROWS: usize = 8; -/// Largest legitimate file of the format is about 2.7 MB; anything above this is refused before any buffer is taken. -const MAX_FILE_BYTES: u64 = 16 << 20; -const MAX_MANIFEST_BYTES: u64 = 8 << 20; -const MAX_CASES: usize = 1024; -const TOLERANCE_METRIC: &str = "max_abs_error_over_max_abs_reference"; -/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where the schema takes -/// text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a positive count. -const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)"; -const TREES: [&str; 2] = ["avx512", "avx2"]; - -thread_local! { static BUFFERS: Cell = const { Cell::new(0) }; } - -// ------------------------------------------------------------------------------------------------ formats - -/// (ggml id, format, block elements, block bytes, name) as `lib.rs kind()/block()`. -const GATE_UP: [(i32, GateUpFormat, usize, usize, &str); 7] = [ - (18, GateUpFormat::Iq3Xxs, 256, 98, "IQ3_XXS"), - (21, GateUpFormat::Iq3S, 256, 110, "IQ3_S"), - (22, GateUpFormat::Iq2S, 256, 82, "IQ2_S"), - (23, GateUpFormat::Iq4Xs, 256, 136, "IQ4_XS"), - (42, GateUpFormat::Q2_0, 64, 18, "Q2_0"), - (16, GateUpFormat::Iq2Xxs, 256, 66, "IQ2_XXS"), - (17, GateUpFormat::Iq2Xs, 256, 74, "IQ2_XS"), -]; -const DOWN: [(i32, DownFormat, usize, usize, &str); 2] = [(20, DownFormat::Iq4Nl, 32, 18, "IQ4_NL"), (42, DownFormat::Q2_0, 64, 18, "Q2_0")]; - -fn gate_up_row(id: i32) -> Option<&'static (i32, GateUpFormat, usize, usize, &'static str)> { - GATE_UP.iter().find(|r| r.0 == id) -} -fn down_row(id: i32) -> Option<&'static (i32, DownFormat, usize, usize, &'static str)> { - DOWN.iter().find(|r| r.0 == id) -} - -// ------------------------------------------------------------------------------------------------ errors - -/// A refusal of the whole directory: names the file and says why. `incomplete` is the missing-manifest case. -#[derive(Debug)] -struct Refusal { - file: String, - reason: String, - incomplete: bool, -} -impl Refusal { - fn new(file: &str, reason: impl Into) -> Self { - Self { file: file.to_owned(), reason: reason.into(), incomplete: false } - } -} -impl std::fmt::Display for Refusal { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - if self.incomplete { write!(f, "incomplete directory: {}: {}", self.file, self.reason) } else { write!(f, "REFUSED {}: {}", self.file, self.reason) } - } -} - -// ------------------------------------------------------------------------------------------------ helpers - -fn sha_hex(bytes: &[u8]) -> String { - let digest = Sha256::digest(bytes); - digest.iter().map(|b| format!("{b:02x}")).collect() -} - -/// The only place a buffer is taken from a length that came from a file; every caller validates the length first. -fn take_buffer(len: usize) -> Result, String> { - BUFFERS.with(|c| c.set(c.get() + 1)); - let mut v = Vec::new(); - v.try_reserve_exact(len).map_err(|_| format!("a buffer of {len} bytes was refused"))?; - v.resize(len, 0); - Ok(v) -} - -/// Little-endian words of a byte slice (a trailing partial word is ignored; callers pass exact multiples). -fn words_le(bytes: &[u8]) -> Vec { - bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect() -} - -fn le32(b: &[u8], at: usize) -> u32 { - u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) -} - -fn civil_from_days(z: i64) -> (i64, u32, u32) { - let z = z + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = (doy - (153 * mp + 2) / 5 + 1) as u32; - let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; - (if m <= 2 { y + 1 } else { y }, m, d) -} - -fn utc_of(secs: u64) -> String { - let (y, m, d) = civil_from_days((secs / 86_400) as i64); - let s = secs % 86_400; - format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", s / 3600, s % 3600 / 60, s % 60) -} - -fn now_utc() -> String { - utc_of(SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())) -} - -fn is_utc(s: &str) -> bool { - let b = s.as_bytes(); - b.len() == 20 && b.iter().enumerate().all(|(i, c)| match i { - 4 | 7 => *c == b'-', - 10 => *c == b'T', - 13 | 16 => *c == b':', - 19 => *c == b'Z', - _ => c.is_ascii_digit(), - }) -} - -fn is_hex(s: &str, min: usize, max: usize) -> bool { - (min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) -} - -fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 64 && id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') -} - -// ------------------------------------------------------------------------------------------------ JSON (read) - -#[derive(Debug, Clone, PartialEq)] -enum Json { - Null, - Bool(bool), - Num(String), - Str(String), - Arr(Vec), - Obj(Vec<(String, Json)>), -} - -struct Parser<'a> { - b: &'a [u8], - at: usize, -} - -impl Parser<'_> { - fn ws(&mut self) { - while self.at < self.b.len() && matches!(self.b[self.at], b' ' | b'\t' | b'\n' | b'\r') { - self.at += 1; - } - } - fn err(&self, what: &str) -> Result { - Err(format!("JSON error at byte {}: {what}", self.at)) - } - fn lit(&mut self, word: &str, v: Json) -> Result { - if self.b[self.at..].starts_with(word.as_bytes()) { - self.at += word.len(); - Ok(v) - } else { - self.err("unknown literal") - } - } - fn hex4(&mut self) -> Result { - if self.at + 4 > self.b.len() { - return self.err("short \\u escape"); - } - let s = std::str::from_utf8(&self.b[self.at..self.at + 4]).map_err(|_| "bad \\u escape".to_owned())?; - let v = u32::from_str_radix(s, 16).map_err(|_| "bad \\u escape".to_owned())?; - self.at += 4; - Ok(v) - } - fn string(&mut self) -> Result { - self.at += 1; - let mut out: Vec = Vec::new(); - loop { - let Some(&c) = self.b.get(self.at) else { return self.err("unterminated string") }; - self.at += 1; - match c { - b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()), - b'\\' => { - let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") }; - self.at += 1; - let ch = match e { - b'"' => '"', - b'\\' => '\\', - b'/' => '/', - b'b' => '\u{8}', - b'f' => '\u{c}', - b'n' => '\n', - b'r' => '\r', - b't' => '\t', - b'u' => { - let hi = self.hex4()?; - let cp = if (0xD800..0xDC00).contains(&hi) { - if !self.b[self.at..].starts_with(b"\\u") { - return self.err("lone surrogate"); - } - self.at += 2; - let lo = self.hex4()?; - if !(0xDC00..0xE000).contains(&lo) { - return self.err("lone surrogate"); - } - 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00) - } else { - hi - }; - match char::from_u32(cp) { - Some(c) => c, - None => return self.err("lone surrogate"), - } - } - _ => return self.err("unknown escape"), - }; - let mut buf = [0u8; 4]; - out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); - } - 0..=0x1f => return self.err("control character in string"), - _ => out.push(c), - } - } - } - fn number(&mut self) -> Result { - let start = self.at; - while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { - self.at += 1; - } - let text = std::str::from_utf8(&self.b[start..self.at]).map_err(|_| "bad number".to_owned())?; - if text.parse::().is_err() { - return self.err("bad number"); - } - Ok(Json::Num(text.to_owned())) - } - fn value(&mut self, depth: usize) -> Result { - if depth > 32 { - return self.err("nesting deeper than 32"); - } - self.ws(); - match self.b.get(self.at) { - None => self.err("unexpected end"), - Some(b'{') => { - self.at += 1; - let mut items: Vec<(String, Json)> = Vec::new(); - self.ws(); - if self.b.get(self.at) == Some(&b'}') { - self.at += 1; - return Ok(Json::Obj(items)); - } - loop { - self.ws(); - if self.b.get(self.at) != Some(&b'"') { - return self.err("object key expected"); - } - let key = self.string()?; - if items.iter().any(|(k, _)| *k == key) { - return self.err(&format!("duplicate key {key:?}")); - } - self.ws(); - if self.b.get(self.at) != Some(&b':') { - return self.err("':' expected"); - } - self.at += 1; - let v = self.value(depth + 1)?; - items.push((key, v)); - self.ws(); - match self.b.get(self.at) { - Some(b',') => self.at += 1, - Some(b'}') => { - self.at += 1; - return Ok(Json::Obj(items)); - } - _ => return self.err("',' or '}' expected"), - } - } - } - Some(b'[') => { - self.at += 1; - let mut items = Vec::new(); - self.ws(); - if self.b.get(self.at) == Some(&b']') { - self.at += 1; - return Ok(Json::Arr(items)); - } - loop { - items.push(self.value(depth + 1)?); - self.ws(); - match self.b.get(self.at) { - Some(b',') => self.at += 1, - Some(b']') => { - self.at += 1; - return Ok(Json::Arr(items)); - } - _ => return self.err("',' or ']' expected"), - } - } - } - Some(b'"') => Ok(Json::Str(self.string()?)), - Some(b't') => self.lit("true", Json::Bool(true)), - Some(b'f') => self.lit("false", Json::Bool(false)), - Some(b'n') => self.lit("null", Json::Null), - Some(b'-' | b'0'..=b'9') => self.number(), - Some(_) => self.err("unexpected character"), - } - } -} - -fn parse_json(bytes: &[u8]) -> Result { - let mut p = Parser { b: bytes, at: 0 }; - let v = p.value(0)?; - p.ws(); - if p.at != bytes.len() { - return p.err("trailing data"); - } - Ok(v) -} - -impl Json { - fn get(&self, key: &str) -> Option<&Json> { - match self { - Json::Obj(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - fn req(&self, key: &str) -> Result<&Json, String> { - self.get(key).ok_or_else(|| format!("missing key {key:?}")) - } - fn str(&self, key: &str) -> Result<&str, String> { - match self.req(key)? { - Json::Str(s) => Ok(s), - _ => Err(format!("key {key:?} is not a string")), - } - } - fn uint(&self, key: &str) -> Result { - match self.req(key)? { - Json::Num(n) => n.parse::().map_err(|_| format!("key {key:?} is not an unsigned integer")), - _ => Err(format!("key {key:?} is not a number")), - } - } - fn float(&self, key: &str) -> Result { - match self.req(key)? { - Json::Num(n) => n.parse::().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("key {key:?} is not a finite number")), - _ => Err(format!("key {key:?} is not a number")), - } - } - /// A number, or None for a JSON null (the C++ writer prints null for a value it could not measure). - fn float_or_null(&self, key: &str) -> Result, String> { - match self.req(key)? { - Json::Null => Ok(None), - _ => self.float(key).map(Some), - } - } - fn flag(&self, key: &str) -> Result { - match self.req(key)? { - Json::Bool(b) => Ok(*b), - _ => Err(format!("key {key:?} is not a boolean")), - } - } - fn array(&self, key: &str) -> Result<&[Json], String> { - match self.req(key)? { - Json::Arr(a) => Ok(a), - _ => Err(format!("key {key:?} is not an array")), - } - } -} - -// ------------------------------------------------------------------------------------------------ KAB1 headers - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct InHeader { - gu: i32, - down: i32, - rows: usize, - gate: usize, - up: usize, - down_bytes: usize, -} - -impl InHeader { - fn input_at(&self) -> usize { - IN_HEADER + self.gate + self.up + self.down_bytes - } -} - -/// Pure: decides from 64 header bytes and the file length, allocates nothing. -fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result { - if le32(h, 0) != IN_MAGIC { - return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0))); - } - if le32(h, 4) != 1 { - return Err(format!("unsupported version {}, expected 1", le32(h, 4))); - } - let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32); - let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else { return Err(format!("gate/up type {gu} is not in the KAB1 list")) }; - let Some(&(_, _, dq, db, _)) = down_row(down) else { return Err(format!("down type {down} is not in the KAB1 list")) }; - let rows = le32(h, 16) as usize; - if !(1..=MAX_ROWS).contains(&rows) { - return Err(format!("rows {rows} outside 1..={MAX_ROWS}")); - } - if le32(h, 20) as usize != H || le32(h, 24) as usize != FF { - return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24))); - } - let gsize = (H / gq * gb * FF) as u64; - let dsize = (FF / dq * db * H) as u64; - let (g, u, d) = (le32(h, 28) as u64, le32(h, 32) as u64, le32(h, 36) as u64); - if g != gsize || u != gsize || d != dsize { - return Err(format!("byte counts gate/up/down {g}/{u}/{d} differ from the format-derived {gsize}/{gsize}/{dsize}")); - } - if h[40..].iter().any(|b| *b != 0) { - return Err("header padding is not zero".to_owned()); - } - let total = IN_HEADER as u64 + g + u + d + (rows * H * 4) as u64; - if total != file_len { - return Err(format!("file length {file_len} differs from the header-derived {total}")); - } - Ok(InHeader { gu, down, rows, gate: g as usize, up: u as usize, down_bytes: d as usize }) -} - -/// Pure: 20 bytes and the file length. -fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> { - if le32(h, 0) != OUT_MAGIC { - return Err(format!("wrong magic 0x{:08x}, expected 0x{OUT_MAGIC:08x}", le32(h, 0))); - } - if le32(h, 4) != 1 { - return Err(format!("unsupported version {}, expected 1", le32(h, 4))); - } - if le32(h, 8) as usize != rows || le32(h, 12) as usize != H { - return Err(format!("rows {} / n_embd {} differ from the case ({rows} / {H})", le32(h, 8), le32(h, 12))); - } - let tree_id = TREES.iter().position(|t| *t == tree).map_or(u32::MAX, |i| i as u32); - if le32(h, 16) != tree_id { - return Err(format!("tree id {} differs from the file name's tree {tree} ({tree_id})", le32(h, 16))); - } - let total = (OUT_HEADER + rows * H * 4) as u64; - if total != file_len { - return Err(format!("file length {file_len} differs from the header-derived {total}")); - } - Ok(()) -} - -fn fp16_finite(bytes: &[u8], block: usize) -> Option { - (0..bytes.len()).step_by(block).find(|&at| u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00) -} - -// ------------------------------------------------------------------------------------------------ manifest - -#[derive(Debug, Clone, PartialEq)] -struct Tolerance { - value: f64, - basis: String, - basis_written_utc: String, -} - -#[derive(Debug, Clone)] -struct OutRef { - tree: &'static str, - name: String, - sha256: String, - bytes: u64, -} - -#[derive(Debug, Clone)] -struct CaseEntry { - id: String, - gu: i32, - down: i32, - rows: usize, - in_name: String, - in_sha256: String, - in_bytes: u64, - outs: Vec, - tolerance: Option, -} - -#[derive(Debug, Clone)] -struct Provenance { - run_id: String, - engine_strata_pin: String, - compiler_id: String, - compiler_version: String, - target_triple: String, - reference_flags: String, - avx512_ok: Option, -} - -#[derive(Debug)] -struct Verified { - dir: PathBuf, - manifest_sha256: String, - provenance: Provenance, - cases: Vec, - file_count: usize, -} - -type FileTable = Vec<(String, String, u64)>; - -fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, FileTable), String> { - if m.str("format")? != "KAB1" || m.uint("version")? != 1 { - return Err("format is not KAB1 version 1".to_owned()); - } - let p = m.req("provenance")?; - let flags = p.req("flags")?; - let commit = p.str("engine_strata_pin")?; - if !is_hex(commit, 7, 40) { - return Err("provenance.engine_strata_pin is not a commit hash".to_owned()); - } - let built = p.str("built_at_utc")?; - if !is_utc(built) { - return Err("provenance.built_at_utc is not a UTC timestamp".to_owned()); - } - let avx512_ok = match p.get("avx512_ok") { - Some(Json::Bool(b)) => Some(*b), - _ => None, - }; - let provenance = Provenance { - run_id: m.str("run_id")?.to_owned(), - engine_strata_pin: commit.to_owned(), - compiler_id: p.str("compiler_id")?.to_owned(), - compiler_version: p.str("compiler_version")?.to_owned(), - target_triple: p.str("target_triple")?.to_owned(), - reference_flags: format!("strata_cxx_flags: {}; ggml_cpu_arch_flags: {}", flags.str("strata_cxx_flags")?, flags.str("ggml_cpu_arch_flags")?), - avx512_ok, - }; - let Json::Arr(cases_json) = m.req("cases")? else { return Err("cases is not an array".to_owned()) }; - if cases_json.is_empty() || cases_json.len() > MAX_CASES { - return Err(format!("{} cases (1..={MAX_CASES} allowed)", cases_json.len())); - } - let mut cases = Vec::new(); - for c in cases_json { - let id = c.str("id")?.to_owned(); - if !valid_id(&id) { - return Err(format!("case id {id:?} is not a plain identifier")); - } - let rows = c.uint("rows")? as usize; - let in_name = format!("case-{id}.in"); - if c.str("in")? != in_name { - return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?)); - } - let mut outs = Vec::new(); - for tree in TREES { - let key = format!("out_cpp_{tree}"); - let name = format!("case-{id}.cpp-{tree}.out"); - if c.str(&key)? != name { - return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?)); - } - outs.push(OutRef { tree, name, sha256: c.str(&format!("{key}_sha256"))?.to_owned(), bytes: c.uint(&format!("{key}_bytes"))? }); - } - let tolerance = match (c.str("equality")?, c.req("tolerance")?) { - ("bitwise", Json::Null) => None, - ("tolerance", t @ Json::Obj(_)) => { - if t.str("metric")? != TOLERANCE_METRIC { - return Err(format!("case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", t.str("metric")?)); - } - let value = match t.req("value")? { - Json::Num(n) => n.parse::().ok().filter(|v| v.is_finite() && *v > 0.0), - _ => None, - } - .ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))?; - let basis = t.str("basis")?.to_owned(); - let written = t.str("basis_written_utc")?.to_owned(); - if basis.trim().is_empty() || !is_utc(&written) { - return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc")); - } - if written.as_str() > built { - return Err(format!("case {id}: the tolerance basis was written {written}, after the reference run {built}")); - } - Some(Tolerance { value, basis, basis_written_utc: written }) - } - (other, _) => return Err(format!("case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)")), - }; - let in_sha256 = c.str("in_sha256")?.to_owned(); - let gu = c.uint("gu_type")? as i32; - let down = c.uint("down_type")? as i32; - cases.push(CaseEntry { id, gu, down, rows, in_name, in_sha256, in_bytes: c.uint("in_bytes")?, outs, tolerance }); - } - let Json::Obj(files_json) = m.req("files")? else { return Err("files is not an object".to_owned()) }; - let mut files = Vec::new(); - for (name, v) in files_json { - let sha = v.str("sha256")?; - if !is_hex(sha, 64, 64) { - return Err(format!("files.{name}.sha256 is not a sha256")); - } - files.push((name.clone(), sha.to_owned(), v.uint("bytes")?)); - } - let mut seen = BTreeSet::new(); - for c in &cases { - if !seen.insert(c.id.clone()) { - return Err(format!("case id {} appears twice", c.id)); - } - for sha in std::iter::once(&c.in_sha256).chain(c.outs.iter().map(|o| &o.sha256)) { - if !is_hex(sha, 64, 64) { - return Err(format!("case {}: a sha256 is not 64 lowercase hex digits", c.id)); - } - } - } - Ok((provenance, cases, files)) -} - -fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> { - let mut v = vec![(c.in_name.as_str(), c.in_sha256.as_str(), c.in_bytes)]; - v.extend(c.outs.iter().map(|o| (o.name.as_str(), o.sha256.as_str(), o.bytes))); - v -} - -// ------------------------------------------------------------------------------------------------ file readers - -#[derive(Debug)] -struct CaseIn { - header: InHeader, - blob: Vec, -} -impl CaseIn { - fn gate(&self) -> &[u8] { - &self.blob[IN_HEADER..IN_HEADER + self.header.gate] - } - fn up(&self) -> &[u8] { - let s = IN_HEADER + self.header.gate; - &self.blob[s..s + self.header.up] - } - fn down(&self) -> &[u8] { - let s = IN_HEADER + self.header.gate + self.header.up; - &self.blob[s..s + self.header.down_bytes] - } - fn input(&self) -> Vec { - words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect() - } -} - -/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256, FP16 headers and -/// finite activations. Any failure names the file. -fn read_case_in(dir: &Path, c: &CaseEntry) -> Result { - let name = c.in_name.as_str(); - let r = |reason: String| Refusal::new(name, reason); - let mut f = File::open(dir.join(name)).map_err(|e| r(format!("cannot open: {e}")))?; - let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); - if len != c.in_bytes { - return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes))); - } - if len > MAX_FILE_BYTES || len < IN_HEADER as u64 { - return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}"))); - } - let mut hdr = [0u8; IN_HEADER]; - f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?; - let header = validate_in_header(&hdr, len).map_err(r)?; - if header.gu != c.gu || header.down != c.down || header.rows != c.rows { - return Err(r("the header's types / rows differ from the manifest case".to_owned())); - } - let mut blob = take_buffer(len as usize).map_err(r)?; - blob[..IN_HEADER].copy_from_slice(&hdr); - f.read_exact(&mut blob[IN_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?; - if sha_hex(&blob) != c.in_sha256 { - return Err(r("sha256 differs from the manifest".to_owned())); - } - let case = CaseIn { header, blob }; - let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3)); - for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] { - if let Some(at) = fp16_finite(bytes, block) { - return Err(r(format!("non-finite FP16 block header in {role} at byte {at}"))); - } - } - if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) { - return Err(r("non-finite activation".to_owned())); - } - Ok(case) -} - -/// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none. -fn read_out(path: &Path, name: &str, rows: usize, tree: &str, expect: Option<(&str, u64)>) -> Result, Refusal> { - let r = |reason: String| Refusal::new(name, reason); - let mut f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?; - let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); - if let Some((_, bytes)) = expect - && len != bytes - { - return Err(r(format!("length {len} differs from the manifest's {bytes}"))); - } - if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 { - return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}"))); - } - let mut hdr = [0u8; OUT_HEADER]; - f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?; - validate_out_header(&hdr, len, rows, tree).map_err(r)?; - let mut blob = take_buffer(len as usize).map_err(r)?; - blob[..OUT_HEADER].copy_from_slice(&hdr); - f.read_exact(&mut blob[OUT_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?; - if let Some((sha, _)) = expect - && sha_hex(&blob) != sha - { - return Err(r("sha256 differs from the manifest".to_owned())); - } - let bits = words_le(&blob[OUT_HEADER..]); - if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) { - return Err(r("non-finite value".to_owned())); - } - Ok(bits) -} - -/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the cases and the flat -/// files table. A missing manifest is the `incomplete` refusal. -fn read_manifest(dir: &Path) -> Result<(Vec, Provenance, Vec, FileTable), Refusal> { - let mpath = dir.join("manifest.json"); - let mname = "manifest.json"; - if !mpath.is_file() { - let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)"); - r.incomplete = true; - return Err(r); - } - let r = |reason: String| Refusal::new(mname, reason); - let mut f = File::open(&mpath).map_err(|e| r(format!("cannot open: {e}")))?; - let mlen = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); - if mlen > MAX_MANIFEST_BYTES { - return Err(r(format!("length {mlen} above the limit {MAX_MANIFEST_BYTES}"))); - } - let mut mbytes = take_buffer(mlen as usize).map_err(r)?; - f.read_exact(&mut mbytes).map_err(|e| r(format!("cannot read: {e}")))?; - let manifest = parse_json(&mbytes).map_err(r)?; - let (provenance, cases, files) = parse_manifest(&manifest).map_err(r)?; - Ok((mbytes, provenance, cases, files)) -} - -/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory. -fn verify_dir(dir: &Path) -> Result { - let mname = "manifest.json"; - let r = |reason: String| Refusal::new(mname, reason); - let (mbytes, provenance, cases, files) = read_manifest(dir)?; - // the flat files table and the case entries must describe exactly the same files - let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); - expected.sort_unstable(); - let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect(); - table.sort_unstable(); - if expected != table { - return Err(r("the flat files table and the case entries disagree".to_owned())); - } - let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect(); - let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?; - for entry in listing { - let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?; - let n = entry.file_name().to_string_lossy().into_owned(); - if n != mname && !names.contains(n.as_str()) { - return Err(Refusal::new(&n, "file is not in the manifest")); - } - } - let file_count = names.len() + 1; - for c in &cases { - read_case_in(dir, c)?; - for o in &c.outs { - read_out(&dir.join(&o.name), &o.name, c.rows, o.tree, Some((&o.sha256, o.bytes)))?; - } - } - Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count }) -} - -// ------------------------------------------------------------------------------------------------ compare - -#[derive(Debug, PartialEq)] -struct Outcome { - compared: usize, - mismatches: usize, - differing_bits: usize, - max_abs_error: f64, - first_mismatch: Option<(usize, u32, u32)>, -} -impl Outcome { - fn equal(&self) -> bool { - self.mismatches == 0 - } -} - -/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value * max|ref|` per value -/// (the one metric the reader knows, `TOLERANCE_METRIC`). -fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Tolerance>) -> Outcome { - let scale = reference.iter().map(|b| f64::from(f32::from_bits(*b)).abs()).fold(0.0, f64::max); - let mut o = Outcome { compared: reference.len(), mismatches: 0, differing_bits: 0, max_abs_error: 0.0, first_mismatch: None }; - for (i, (a, b)) in ours.iter().zip(reference).enumerate() { - let err = (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs(); - if a != b { - o.differing_bits += 1; - } - if err.is_finite() { - o.max_abs_error = o.max_abs_error.max(err); - } - let bad = match tol { - None => a != b, - Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater), - }; - if bad { - o.mismatches += 1; - o.first_mismatch.get_or_insert((i, *a, *b)); - } - } - if ours.len() != reference.len() { - o.mismatches += ours.len().abs_diff(reference.len()); - } - o -} - -// ------------------------------------------------------------------------------------------------ record (hand-written JSON) - -fn jstr(s: &str) -> String { - let mut o = String::with_capacity(s.len() + 2); - o.push('"'); - for c in s.chars() { - match c { - '"' => o.push_str("\\\""), - '\\' => o.push_str("\\\\"), - '\n' => o.push_str("\\n"), - '\r' => o.push_str("\\r"), - '\t' => o.push_str("\\t"), - c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), - c => o.push(c), - } - } - o.push('"'); - o -} - -struct RecordInput<'a> { - record_id: String, - created_utc: String, - run_started_utc: String, - machine_role: String, - cpu_model: String, - os: String, - ours_compiler: String, - ours_version: String, - ours_triple: String, - ours_flags: String, - tree: &'a str, - verified: &'a Verified, - case: &'a CaseEntry, - pin_cpu: usize, - sibling_idle: bool, - outcome: &'a Outcome, -} - -fn record_json(r: &RecordInput) -> String { - let p = &r.verified.provenance; - let c = r.case; - let mode = if c.tolerance.is_some() { "tolerance" } else { "bitwise" }; - let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { - format!( - ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", - t.value, - jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), - jstr(&t.basis_written_utc) - ) - }); - let tiny = format!("{:e}", f64::from_bits(1)); - let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)); - format!( - "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {{\"compiler\": {oc}, \"version\": {ov}, \"target_triple\": {ot}, \"flags\": {of}}},\n \"reference\": {{\"compiler\": {rc}, \"version\": {rv}, \"target_triple\": {rt}, \"flags\": {rf}}}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree}, \"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {nm}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \"max_drift_fraction\": 0, \"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {rowtype}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}, \"reference\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {{\n \"mode\": \"{mode}\",\n \"verdict\": \"{verdict}\",\n \"compared_values\": {compared},\n \"mismatches\": {mism}{tolerance}\n }}\n}}\n", - rid = jstr(&r.record_id), - created = jstr(&r.created_utc), - started = jstr(&r.run_started_utc), - role = jstr(&r.machine_role), - cpu = jstr(&r.cpu_model), - os = jstr(&r.os), - kernel = jstr(&format!("routed-expert-gate-up-down {gu}+{down} rows={} (equality only; timing {NOT_MEASURED})", c.rows)), - oc = jstr(&r.ours_compiler), - ov = jstr(&r.ours_version), - ot = jstr(&r.ours_triple), - of = jstr(&r.ours_flags), - rc = jstr(&p.compiler_id), - rv = jstr(&p.compiler_version), - rt = jstr(&p.target_triple), - rf = jstr(&p.reference_flags), - cid = jstr(&c.id), - insha = jstr(&c.in_sha256), - msha = jstr(&r.verified.manifest_sha256), - tree = jstr(r.tree), - pin = r.pin_cpu, - sib = r.sibling_idle, - commit = jstr(&p.engine_strata_pin), - nm = jstr(NOT_MEASURED), - rowtype = jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", c.rows)), - verdict = if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, - compared = r.outcome.compared, - mism = r.outcome.mismatches, - ) -} - -// ------------------------------------------------------------------------------------------------ run-tree (one fresh process) - -fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> Result<(), String> { - let tree_id = TREES.iter().position(|t| *t == tree).ok_or("unknown tree")? as u32; - let mut b = Vec::with_capacity(OUT_HEADER + values.len() * 4); - for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree_id] { - b.extend_from_slice(&w.to_le_bytes()); - } - for v in values { - b.extend_from_slice(&v.to_bits().to_le_bytes()); - } - File::create(path).and_then(|mut f| f.write_all(&b)).map_err(|e| format!("{}: {e}", path.display())) -} - -/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then one -/// `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1). -fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result, String> { - let (gu, down) = (gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1); - let input = case.input(); - PreparedJob::new(gu, down, case.gate().into(), case.up().into(), case.down().into(), input.clone().into(), case.header.rows) - .map_err(|e| format!("PreparedJob refused the input: {e:?}"))?; - let pairs: Vec<(usize, usize)> = (0..case.header.rows).map(|t| (t, 0)).collect(); - let expert = BorrowedExpert { gate: case.gate(), up: case.up(), down: case.down(), pairs: &pairs }; - let experts = [expert]; - let group = BorrowedGroup { tokens: &input, experts: &experts, stride: 1 }; - let mut out = vec![0.0f32; case.header.rows * H]; - pool.compute_group(gu, down, &group, &mut out).map_err(|e| format!("compute_group failed: {e:?}"))?; - Ok(out) -} - -fn family_of(report: &[String]) -> Option<&'static str> { - report.iter().find(|l| l.starts_with("cpu: process kernel family ")).map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" }) -} - -fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize, only_case: Option<&str>) -> Result { - let verified = verify_dir(dir).map_err(|e| e.to_string())?; - let previous = rust_topology::pin_current_thread(pin as i32); - if previous < 0 { - eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned"); - } - let report = cpu_kernel_report(); - for line in &report { - println!("REPORT {line}"); - } - let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; - if family != tree { - eprintln!("kernel_ab: this process runs the {family} family, not {tree}"); - return Ok(ExitCode::from(3)); - } - fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; - let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; - let mut done = 0usize; - for c in verified.cases.iter().filter(|c| only_case.is_none_or(|id| c.id == id)) { - let case = read_case_in(&verified.dir, c).map_err(|e| e.to_string())?; - let values = compute_case(&mut pool, &case).map_err(|e| format!("case {}: {e}", c.id))?; - write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?; - done += 1; - } - if done == 0 { - return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?"))); - } - println!("RUN-TREE {tree} cases={done}"); - Ok(ExitCode::SUCCESS) -} - -// ------------------------------------------------------------------------------------------------ compare driver - -/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: false (unknown). -fn sibling_idle(cpu: usize) -> bool { - if !cfg!(target_os = "linux") { - return false; - } - let Ok(list) = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")) else { return false }; - let mut siblings = Vec::new(); - for part in list.trim().split(',') { - let (a, b) = part.split_once('-').unwrap_or((part, part)); - let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) else { return false }; - siblings.extend((a..=b).filter(|s| *s != cpu)); - } - if siblings.is_empty() { - return true; - } - let sample = |cpu: usize| -> Option<(u64, u64)> { - let stat = fs::read_to_string("/proc/stat").ok()?; - let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?; - let f: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); - let idle = f.get(3)? + f.get(4).copied().unwrap_or(0); - Some((f.iter().sum(), idle)) - }; - let before: Vec<_> = siblings.iter().map(|s| sample(*s)).collect(); - std::thread::sleep(std::time::Duration::from_millis(200)); - siblings.iter().zip(before).all(|(s, b)| match (b, sample(*s)) { - (Some(b), Some(a)) => { - let total = a.0.saturating_sub(b.0); - let idle = a.1.saturating_sub(b.1); - total > 0 && (total - idle.min(total)) * 20 < total - } - _ => false, - }) -} - -fn rustc_info() -> (String, String) { - // $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH) - let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default(); - let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" }); - let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim]; - let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" }; - let version = candidates - .iter() - .find_map(|rustc| Command::new(rustc).arg("--version").output().ok().filter(|o| o.status.success()).and_then(|o| String::from_utf8(o.stdout).ok())) - .map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned()); - (version, triple.to_owned()) -} - -fn host_os() -> String { - if cfg!(target_os = "linux") - && let Ok(text) = fs::read_to_string("/etc/os-release") - && let Some(l) = text.lines().find(|l| l.starts_with("PRETTY_NAME=")) - { - return l["PRETTY_NAME=".len()..].trim_matches('"').to_owned(); - } - std::env::consts::OS.to_owned() -} - -fn cpu_model_of(report: &[String]) -> String { - report - .iter() - .find(|l| l.starts_with("cpu: logical ")) - .and_then(|l| l.split_once("): ").map(|x| x.1)) - .and_then(|rest| rest.split(';').next()) - .map_or_else(|| "unknown model".to_owned(), |s| s.trim().to_owned()) -} - -struct Options { - out: Option, - pin: usize, - machine_role: Option, - trees: Vec, - tree: Option, - case: Option, -} - -fn parse_options(args: &[String]) -> Result { - let mut o = Options { out: None, pin: 0, machine_role: None, trees: TREES.iter().map(|t| (*t).to_owned()).collect(), tree: None, case: None }; - let mut it = args.iter(); - while let Some(a) = it.next() { - let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value")); - match a.as_str() { - "--out" => o.out = Some(PathBuf::from(value("--out")?)), - "--pin" => o.pin = value("--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?, - "--machine-role" => o.machine_role = Some(value("--machine-role")?), - "--trees" => o.trees = value("--trees")?.split(',').map(str::to_owned).collect(), - "--tree" => o.tree = Some(value("--tree")?), - "--case" => o.case = Some(value("--case")?), - other => return Err(format!("unknown option {other}")), - } - } - if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) { - return Err(format!("unknown tree {bad} (avx512 | avx2)")); - } - Ok(o) -} - -fn cmd_compare(dir: &Path, opts: &Options) -> Result { - let started = now_utc(); - let verified = match verify_dir(dir) { - Ok(v) => v, - Err(e) => { - println!("{e}"); - return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); - } - }; - println!("KAB1 directory verified: {} files, {} cases, manifest sha256 {}", verified.file_count, verified.cases.len(), verified.manifest_sha256); - let out = opts.out.clone().unwrap_or_else(|| { - let name = dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); - dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.rust")) - }); - if out.starts_with(dir) || dir.starts_with(&out) { - return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); - } - if out.exists() && fs::read_dir(&out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() { - return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display())); - } - let records = out.join("records"); - fs::create_dir_all(&records).map_err(|e| format!("{}: {e}", records.display()))?; - let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; - let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); - let machine_role = opts.machine_role.clone().or_else(|| std::env::var("HOSTNAME").ok()).or_else(|| std::env::var("COMPUTERNAME").ok()).unwrap_or_else(|| "unknown".to_owned()); - let (rustc_version, triple) = rustc_info(); - let flags = format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default()); - let mut all_equal = true; - let mut cells = 0usize; - for tree in &opts.trees { - let sibling = sibling_idle(opts.pin); - let probe = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"), rep: 'a' }; - let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe)); - cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]); - let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?; - let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); - let report: Vec = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect(); - match res.status.code() { - Some(0) => {} - Some(3) if tree == "avx512" && verified.provenance.avx512_ok == Some(false) => { - println!("tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are identical by construction)"); - continue; - } - code => { - eprint!("{}", String::from_utf8_lossy(&res.stderr)); - println!("tree {tree}: the Rust process failed (exit {code:?})"); - return Ok(ExitCode::from(1)); - } - } - println!("tree {tree}: {}", report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str)); - let tree_name: &str = TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"); - for c in &verified.cases { - let ours_name = format!("case-{}.rust-{tree}.out", c.id); - let ours = read_out(&out.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?; - let o = c.outs.iter().find(|o| o.tree == tree_name).ok_or("missing reference out")?; - let reference = read_out(&verified.dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes))).map_err(|e| e.to_string())?; - let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref()); - let label = match (&c.tolerance, outcome.equal()) { - (None, true) => "bitwise EQUAL".to_owned(), - (None, false) => "bitwise NOT EQUAL".to_owned(), - (Some(t), eq) => format!("{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})", if eq { "EQUAL" } else { "NOT EQUAL" }, t.value, t.basis), - }; - let detail = match outcome.first_mismatch { - Some((i, a, b)) => format!("; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}", outcome.mismatches, outcome.compared, outcome.max_abs_error), - None => format!("; {} values", outcome.compared), - }; - println!("case {} [{tree}] {label}{detail}", c.id); - all_equal &= outcome.equal(); - cells += 1; - let record = record_json(&RecordInput { - record_id: format!("kab1-{}-{}-{tree}-{}", verified.provenance.run_id, c.id, started.replace([':', '-'], "")), - created_utc: now_utc(), - run_started_utc: started.clone(), - machine_role: machine_role.clone(), - cpu_model: cpu_model_of(&report), - os: host_os(), - ours_compiler: "rustc".to_owned(), - ours_version: rustc_version.clone(), - ours_triple: triple.clone(), - ours_flags: flags.clone(), - tree: tree_name, - verified: &verified, - case: c, - pin_cpu: opts.pin, - sibling_idle: sibling, - outcome: &outcome, - }); - let path = records.join(format!("case-{}.{tree}.record.json", c.id)); - fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?; - } - } - println!("compared {cells} cells; records in {}; {}", records.display(), if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" }); - Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }) -} - -// ------------------------------------------------------------------------------------------------ flags (time, alternate) - -struct Flags(Vec<(String, String)>); - -impl Flags { - fn parse(args: &[String], known: &[&str]) -> Result { - let mut items: Vec<(String, String)> = Vec::new(); - let mut it = args.iter(); - while let Some(a) = it.next() { - let name = a.strip_prefix("--").ok_or_else(|| format!("unexpected argument {a}"))?; - if !known.contains(&name) { - return Err(format!("unknown option {a}")); - } - if items.iter().any(|(k, _)| k == name) { - return Err(format!("option {a} given twice")); - } - let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; - items.push((name.to_owned(), v.clone())); - } - Ok(Self(items)) - } - fn get(&self, k: &str) -> Option<&str> { - self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) - } - fn req(&self, k: &str) -> Result<&str, String> { - self.get(k).ok_or_else(|| format!("--{k} is required")) - } - fn number(&self, k: &str) -> Result, String> { - self.get(k).map(|v| v.parse::().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose() - } -} - -// ------------------------------------------------------------------------------------------------ clocks and host facts - -/// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses. -const DEFAULT_SLICE_MS: f64 = 60.0; -/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not chosen here. -const CLOCK_MOVED_FRACTION: f64 = 0.05; -/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). -const SIBLING_BUSY_LIMIT: f64 = 0.05; -const ALIGN: usize = 4096; -/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove -/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. -const CHAIN_STEP_CYCLES: f64 = 4.0; -const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice"; - -fn mono_ns() -> u64 { - static ORIGIN: OnceLock = OnceLock::new(); - ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64 -} - -/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain -/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the -/// running value, which no reassociation can remove. -fn core_ghz() -> f64 { - let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); - let mut x = std::hint::black_box(1u64); - let n = 1_000_000u64; - let t0 = mono_ns(); - for _ in 0..n { - x = x.wrapping_mul(k) ^ (x >> 17); - x = x.wrapping_mul(k) ^ (x >> 17); - x = x.wrapping_mul(k) ^ (x >> 17); - x = x.wrapping_mul(k) ^ (x >> 17); - } - let dt = mono_ns().saturating_sub(t0).max(1); - std::hint::black_box(x); - CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64 -} - -fn median_of(v: &[f64]) -> f64 { - if v.is_empty() { - return 0.0; - } - let mut s = v.to_vec(); - s.sort_by(f64::total_cmp); - s[s.len() / 2] -} - -/// Nearest-rank percentile of raw slice values (a description of the slices, not an inference). -fn percentile_of(v: &[f64], p: f64) -> f64 { - if v.is_empty() { - return 0.0; - } - let mut s = v.to_vec(); - s.sort_by(f64::total_cmp); - s[((s.len() - 1) as f64 * p).round() as usize] -} - -fn jnum(v: f64, decimals: usize) -> String { - if v.is_finite() { format!("{v:.decimals$}") } else { "null".to_owned() } -} - -fn read_text(path: &str) -> String { - fs::read_to_string(path).map(|s| s.trim().to_owned()).unwrap_or_default() -} - -fn parse_cpu_list(s: &str) -> Vec { - let mut v = Vec::new(); - for part in s.trim().split(',').filter(|p| !p.is_empty()) { - let (a, b) = part.split_once('-').unwrap_or((part, part)); - if let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) { - v.extend(a..=b); - } - } - v -} - -fn parse_size(s: &str) -> u64 { - let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); - let n = digits.parse::().unwrap_or(0); - match s[digits.len()..].chars().next() { - Some('K' | 'k') => n << 10, - Some('M' | 'm') => n << 20, - Some('G' | 'g') => n << 30, - _ => n, - } -} - -struct Llc { - level: u32, - bytes: u64, - source: String, -} - -/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`). -fn llc_of_cpu(cpu: usize) -> Option { - let mut best: Option = None; - for i in 0..16 { - let d = format!("/sys/devices/system/cpu/cpu{cpu}/cache/index{i}"); - let (level, kind, size) = (read_text(&format!("{d}/level")), read_text(&format!("{d}/type")), read_text(&format!("{d}/size"))); - if level.is_empty() || size.is_empty() || kind == "Instruction" { - continue; - } - let level_n = level.parse::().unwrap_or(0); - if best.as_ref().is_none_or(|b| level_n >= b.level) { - best = Some(Llc { level: level_n, bytes: parse_size(&size), source: format!("{d}/size = {size}") }); - } - } - best.filter(|l| l.bytes > 0) -} - -/// (busy, total) jiffies of one logical CPU from /proc/stat (Linux). -fn proc_stat_cpu(cpu: usize) -> Option<(u64, u64)> { - let stat = fs::read_to_string("/proc/stat").ok()?; - let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?; - let f: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); - let total: u64 = f.iter().take(8).sum(); - Some((total - f.get(3)? - f.get(4).copied().unwrap_or(0), total)) -} - -fn busy_fraction(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> Option { - let (b, a) = (before?, after?); - (a.1 > b.1).then(|| (a.0.saturating_sub(b.0)) as f64 / (a.1 - b.1) as f64) -} - -/// Linux: the logical CPU the calling thread last ran on (field 39 of /proc/thread-self/stat). Elsewhere: None. -fn current_cpu() -> Option { - if !cfg!(target_os = "linux") { - return None; - } - let s = fs::read_to_string("/proc/thread-self/stat").ok()?; - let rest = &s[s.rfind(')')? + 1..]; - rest.split_whitespace().nth(36)?.parse().ok() -} - -/// Linux: every thread of this process with the CPU it last ran on (the pool's worker is one of them). -fn observed_threads() -> Vec<(String, Option)> { - let mut v = Vec::new(); - if let Ok(dir) = fs::read_dir("/proc/self/task") { - for e in dir.flatten() { - let p = e.path(); - let name = read_text(&format!("{}/comm", p.display())); - let cpu = fs::read_to_string(p.join("stat")).ok().and_then(|s| s.get(s.rfind(')')? + 1..)?.split_whitespace().nth(36)?.parse().ok()); - v.push((name, cpu)); - } - } - v.sort(); - v -} - -fn is_managed_name(name: &str) -> bool { - let up = name.to_ascii_uppercase(); - up.starts_with("STRATA_") || up.starts_with("LELEKA_") -} - -/// Every STRATA_* / LELEKA_* variable the process sees. -fn managed_env_now() -> BTreeMap { - std::env::vars_os().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).filter(|(k, _)| is_managed_name(k)).collect() -} - -fn json_env(env: &BTreeMap) -> String { - format!("{{{}}}", env.iter().map(|(k, v)| format!("{}: {}", jstr(k), jstr(v))).collect::>().join(", ")) -} - -// ------------------------------------------------------------------------------------------------ time (one fresh process) - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum RegimeSel { - Both, - Resident, - Streamed, -} - -#[derive(Debug)] -struct TimeArgs { - dir: PathBuf, - case: String, - slices: usize, - pin: usize, - out: PathBuf, - slice_ms: f64, - regime: RegimeSel, - llc_bytes: Option, -} - -const TIME_FLAGS: [&str; 8] = ["run-dir", "case", "slices", "pin", "out", "slice-ms", "regime", "llc-bytes"]; - -/// The command line of `kab time` (STRA-317), checked the same way. -fn parse_time_args(args: &[String]) -> Result { - let f = Flags::parse(args, &TIME_FLAGS)?; - let slices = f.number::("slices")?.ok_or("--slices is required")?; - let pin = f.number::("pin")?.ok_or("--pin is required")?; - let slice_ms = f.number::("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS); - if !(1..=100_000).contains(&slices) { - return Err("--slices must be 1..100000".to_owned()); - } - if !(1.0..=10_000.0).contains(&slice_ms) { - return Err("--slice-ms must be 1..10000".to_owned()); - } - let regime = match f.get("regime").unwrap_or("both") { - "both" => RegimeSel::Both, - "resident" => RegimeSel::Resident, - "streamed" => RegimeSel::Streamed, - _ => return Err("--regime must be both, resident or streamed".to_owned()), - }; - let case = f.req("case")?.to_owned(); - if !valid_id(&case) { - return Err(format!("--case {case:?} is not a plain identifier")); - } - Ok(TimeArgs { - dir: PathBuf::from(f.req("run-dir")?), - case, - slices, - pin, - out: PathBuf::from(f.req("out")?), - slice_ms, - regime, - llc_bytes: f.number::("llc-bytes")?, - }) -} - -/// A buffer whose usable part starts on a 4096-byte boundary. -struct Arena { - buf: Vec, - off: usize, -} -impl Arena { - fn new(len: usize) -> Self { - let size = std::mem::size_of::(); - let buf = vec![T::default(); len + ALIGN / size]; - let misalign = buf.as_ptr() as usize % ALIGN; - let off = if misalign == 0 { 0 } else { (ALIGN - misalign) / size }; - Self { buf, off } - } - fn slice(&self, len: usize) -> &[T] { - &self.buf[self.off..self.off + len] - } - fn slice_mut(&mut self, len: usize) -> &mut [T] { - &mut self.buf[self.off..self.off + len] - } -} - -/// The timed call: one group of one expert through the crate's public pool, exactly as `compute_case` does it. -struct Timed<'a> { - pool: DirectCpuPool, - gu: GateUpFormat, - down: DownFormat, - header: InHeader, - pairs: Vec<(usize, usize)>, - tokens: &'a [f32], - out: Vec, -} - -impl Timed<'_> { - fn call(&mut self, weights: &[u8]) -> Result<(), String> { - let (g, u) = (self.header.gate, self.header.up); - let expert = BorrowedExpert { gate: &weights[..g], up: &weights[g..g + u], down: &weights[g + u..g + u + self.header.down_bytes], pairs: &self.pairs }; - let experts = [expert]; - let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: 1 }; - self.pool.compute_group(self.gu, self.down, &group, &mut self.out).map_err(|e| format!("compute_group failed: {e:?}")) - } -} - -struct Slice { - calls: u64, - wall_ns: u64, - ns_per_call: f64, - ghz_before: f64, - ghz_after: f64, - cycles_per_call: f64, - moved: bool, -} - -/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304). -fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result { - let ghz_before = core_ghz(); - let mut calls = 0u64; - let ns0 = mono_ns(); - let mut ns1; - loop { - t.call(copies[*next % copies.len()])?; - *next += 1; - calls += 1; - ns1 = mono_ns(); - if (ns1 - ns0) as f64 >= ms * 1e6 && calls >= 2 { - break; - } - } - let ghz_after = core_ghz(); - let wall = ns1 - ns0; - let ns_per_call = wall as f64 / calls as f64; - let ghz_mean = 0.5 * (ghz_before + ghz_after); - Ok(Slice { - calls, - wall_ns: wall, - ns_per_call, - ghz_before, - ghz_after, - cycles_per_call: ns_per_call * ghz_mean, - moved: ghz_mean > 0.0 && (ghz_after - ghz_before).abs() > CLOCK_MOVED_FRACTION * ghz_before, - }) -} - -fn slice_json(s: &Slice, idx: usize) -> String { - format!( - "{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}", - s.calls, - s.wall_ns, - jnum(s.ns_per_call, 3), - jnum(s.ghz_before, 6), - jnum(s.ghz_after, 6), - jnum(s.cycles_per_call, 1) - ) -} - -/// Slices with their index within the regime. -type Numbered = Vec<(usize, Slice)>; - -struct RegimeRun { - json: String, - kept: usize, - ok: bool, -} - -struct RegimeSpec<'a> { - label: &'a str, - copies: Vec<&'a [u8]>, - expert_bytes: usize, - stride: usize, - llc: &'a Llc, - slices: usize, - slice_ms: f64, - pin: usize, - selfcheck: bool, -} - -fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { - let mut next = 0usize; - // warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is resident - for _ in 0..3 { - t.call(spec.copies[next % spec.copies.len()])?; - next += 1; - } - if spec.copies.len() > 1 { - for _ in 0..spec.copies.len() { - t.call(spec.copies[next % spec.copies.len()])?; - next += 1; - } - } - let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new()); - let mut migrated: Option = cfg!(target_os = "linux").then_some(0); - for i in 0..spec.slices { - let before = current_cpu(); - let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?; - if let Some(m) = migrated.as_mut() - && (before != Some(spec.pin) || current_cpu() != Some(spec.pin)) - { - *m += 1; - } - if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) } - } - let ns: Vec = kept.iter().map(|k| k.1.ns_per_call).collect(); - let cyc: Vec = kept.iter().map(|k| k.1.cycles_per_call).collect(); - let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) }; - let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n "); - let json = format!( - "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}", - jstr(spec.label), - spec.copies.len(), - spec.expert_bytes, - spec.stride, - spec.expert_bytes * spec.copies.len(), - spec.llc.level, - spec.llc.bytes, - jstr(&spec.llc.source), - spec.copies.len() > 1, - jnum(spec.slice_ms, 1), - spec.slices, - kept.len(), - dropped.len(), - spec.selfcheck, - migrated.map_or("null".to_owned(), |m| m.to_string()), - med(&ns, 3), - med(&cyc, 1), - list(&kept), - list(&dropped) - ); - Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) -} - -fn f32_bits_sha(values: &[f32]) -> String { - let mut b = Vec::with_capacity(values.len() * 4); - for v in values { - b.extend_from_slice(&v.to_bits().to_le_bytes()); - } - sha_hex(&b) -} - -/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + rename. Exit codes as -/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final output differs. -fn cmd_time(args: &[String]) -> Result { - let t = parse_time_args(args)?; - let wall0 = mono_ns(); - // pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin - if rust_topology::pin_current_thread(t.pin as i32) < 0 { - return Err(format!("the pin to CPU {} was refused", t.pin)); - } - if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) { - return Err(format!("the process is not running on CPU {} after the pin", t.pin)); - } - let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin); - let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list")); - let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin); - let sib0 = sibling.and_then(proc_stat_cpu); - let pin0 = proc_stat_cpu(t.pin); - let load0 = read_text("/proc/loadavg"); - - // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes - let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?; - let manifest_sha = sha_hex(&manifest_bytes); - let entry = cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?; - let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?; - let header = case.header; - let weights = &case.blob[IN_HEADER..header.input_at()]; - let expert_bytes = weights.len(); - - // environment and tree - let env = managed_env_now(); - let report = cpu_kernel_report(); - let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; - - // the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp) - let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) { - (Some(bytes), found) => Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() }, - (None, Some(l)) => l, - (None, None) => return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)), - }; - if llc.bytes == 0 { - return Err("--llc-bytes must be positive".to_owned()); - } - let stride = expert_bytes.div_ceil(ALIGN) * ALIGN; - let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1; - if copies_k * stride > (4usize << 30) { - return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned()); - } - - // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity) - let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; - let want = compute_case(&mut pool, &case)?; - let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); - let output_sha = f32_bits_sha(&want); - - let mut tokens = Arena::::new(header.rows * H); - tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); - let mut resident = Arena::::new(stride); - resident.slice_mut(expert_bytes).copy_from_slice(weights); - let mut streamed = Arena::::new(stride * copies_k); - for k in 0..copies_k { - streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); - } - let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)]; - let stm_all = streamed.slice(stride * copies_k); - let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect(); - - let mut timed = Timed { - pool, - gu: gate_up_row(header.gu).ok_or("gate/up type")?.1, - down: down_row(header.down).ok_or("down type")?.1, - header, - pairs: (0..header.rows).map(|r| (r, 0)).collect(), - tokens: tokens.slice(header.rows * H), - out: vec![0.0f32; header.rows * H], - }; - // selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's - let mut selfcheck = true; - for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { - timed.call(w)?; - selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); - } - if !selfcheck { - return Err("selfcheck failed: the timed call differs from the first call".to_owned()); - } - - let ghz0 = core_ghz(); - let mut regimes = Vec::new(); - let mut all_ok = true; - let (mut kept_res, mut kept_stm) = (0, 0); - for (label, copies, sel) in [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] { - if t.regime != RegimeSel::Both && t.regime != sel { - continue; - } - let spec = RegimeSpec { label, copies: copies.clone(), expert_bytes, stride, llc: &llc, slices: t.slices, slice_ms: t.slice_ms, pin: t.pin, selfcheck }; - let r = run_regime(&mut timed, &spec)?; - all_ok &= r.ok; - if sel == RegimeSel::Resident { kept_res = r.kept } else { kept_stm = r.kept } - regimes.push(r.json); - } - let ghz1 = core_ghz(); - timed.call(res_copies[0])?; - let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); - - let threads = observed_threads(); - let sib1 = sibling.and_then(proc_stat_cpu); - let pin1 = proc_stat_cpu(t.pin); - let frac = |f: Option| f.map_or("null".to_owned(), |v| jnum(v, 4)); - let rust_fmt = |l: &str| jstr(l); - let (gu_name, down_name) = (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4)); - let in_name = format!("case-{}.in", t.case); - let command_line = format!( - "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", - t.dir.display(), - t.case, - t.slices, - t.pin, - t.out.display(), - if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() }, - match t.regime { - RegimeSel::Both => String::new(), - RegimeSel::Resident => " --regime resident".to_owned(), - RegimeSel::Streamed => " --regime streamed".to_owned(), - } - ); - let mut j = String::from("{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n"); - j += &format!(" \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", jstr(&command_line), jstr(&t.dir.display().to_string()), jstr(&manifest_sha)); - j += &format!( - " \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n", - jstr(&t.case), - header.gu, - header.down, - jstr(gu_name), - jstr(down_name), - header.rows, - jstr(&in_name), - jstr(&entry.in_sha256), - expert_bytes - ); - j += &format!( - " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n", - jstr(tree), - jstr(tree), - report.iter().map(|l| rust_fmt(l)).collect::>().join(", "), - json_env(&env), - json_env(&env) - ); - j += &format!( - " \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n", - threads.iter().map(|(n, c)| format!("{{\"name\": {}, \"cpu\": {}}}", jstr(n), c.map_or("null".to_owned(), |c| c.to_string()))).collect::>().join(", ") - ); - j += &format!( - " \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n", - t.pin, - jstr(&sib_text), - sibling.map_or("null".to_owned(), |s| s.to_string()), - jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), - frac(busy_fraction(pin0, pin1)), - if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() }, - jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), - jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), - jstr(&load0), - jstr(&read_text("/proc/loadavg")), - current_cpu().map_or("null".to_owned(), |c| c.to_string()) - ); - j += &format!(" \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n"); - j += &format!( - " \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n", - jstr(CLOCK_METHOD), - jnum(CLOCK_MOVED_FRACTION, 2), - jnum(ghz0, 6), - jnum(ghz1, 6) - ); - j += &format!( - " \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n", - jstr(if cfg!(debug_assertions) { "dev" } else { "release" }), - jstr(&std::env::var("RUSTFLAGS").unwrap_or_default()) - ); - j += &format!( - " \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n", - jstr(&output_sha), - mono_ns() - wall0, - regimes.join(",\n ") - ); - let tmp = PathBuf::from(format!("{}.tmp", t.out.display())); - fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; - fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?; - println!("kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} K={copies_k} out={}", t.case, t.pin, t.slices, t.out.display()); - if !all_ok { - eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); - return Ok(ExitCode::from(3)); - } - if !final_same { - eprintln!("kernel_ab time: the final output differs from the first call's"); - return Ok(ExitCode::from(4)); - } - Ok(ExitCode::SUCCESS) -} - -// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -enum Impl { - Cpp, - Rust, -} -impl Impl { - fn name(self) -> &'static str { - match self { - Impl::Cpp => "cpp", - Impl::Rust => "rust", - } - } -} - -/// One process of a round: an implementation, a tree and a replicate (`a` is the A/B process, `b` the A/A twin). -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -struct Proc { - imp: Impl, - tree: &'static str, - rep: char, -} -impl Proc { - fn name(&self) -> String { - format!("{}-{}-{}", self.imp.name(), self.tree, self.rep) - } - fn parse(s: &str) -> Option { - let mut p = s.split('-'); - let imp = match p.next()? { - "cpp" => Impl::Cpp, - "rust" => Impl::Rust, - _ => return None, - }; - let wanted = p.next()?; - let tree = *TREES.iter().find(|t| **t == wanted)?; - let rep = match p.next()? { - "a" => 'a', - "b" => 'b', - _ => return None, - }; - p.next().is_none().then_some(Proc { imp, tree, rep }) - } -} - -/// Every process of a round for the given trees, in canonical order. -fn procs_for(trees: &[&'static str]) -> Vec { - let mut v = Vec::new(); - for imp in [Impl::Cpp, Impl::Rust] { - for tree in trees { - for rep in ['a', 'b'] { - v.push(Proc { imp, tree, rep }); - } - } - } - v -} - -/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The -/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must -/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch -/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time). -fn cell_env(p: &Proc) -> Vec<(String, String)> { - let mut v = Vec::new(); - if p.tree == "avx2" { - v.push(("STRATA_FORCE_AVX2".to_owned(), "1".to_owned())); - } - if p.imp == Impl::Rust { - v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned())); - v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())); - } - v.sort(); - v -} - -/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables. -fn scrubbed_command(program: &Path, parent_env: &[(OsString, OsString)], cell: &[(String, String)]) -> Command { - let mut c = Command::new(program); - c.env_clear(); - for (k, v) in parent_env { - if !is_managed_name(&k.to_string_lossy()) { - c.env(k, v); - } - } - for (k, v) in cell { - c.env(k, v); - } - c -} - -/// Runs a prepared cell command; a failure names the cell. -fn run_cell(cmd: &mut Command, cell: &str) -> Result { - let out = cmd.output().map_err(|e| format!("cell {cell}: cannot start the process: {e}"))?; - if out.status.success() { - return Ok(out); - } - let tail = |b: &[u8]| String::from_utf8_lossy(b).lines().rev().take(3).collect::>().into_iter().rev().collect::>().join(" | "); - Err(format!("cell {cell} failed ({}): stderr: {}; stdout: {}", out.status.code().map_or("killed by a signal".to_owned(), |c| format!("exit {c}")), tail(&out.stderr), tail(&out.stdout))) -} - -fn splitmix(state: &mut u64) -> u64 { - *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = *state; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) -} - -/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds draws a fresh -/// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, rounds, procs). -fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec> { - let n = procs.len(); - let mut out = Vec::new(); - let mut base: Vec = Vec::new(); - for i in 0..rounds as usize { - if i % n == 0 { - let mut st = seed; - for x in [u64::from(batch), (i / n) as u64] { - st = st.wrapping_add(x.wrapping_mul(0x9E37_79B9_7F4A_7C15)); - st = splitmix(&mut st); - } - base = procs.to_vec(); - for j in (1..n).rev() { - let k = (splitmix(&mut st) % (j as u64 + 1)) as usize; - base.swap(j, k); - } - } - let mut order = base.clone(); - order.rotate_left(i % n); - out.push(order); - } - out -} - -const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1"; - -fn schedule_text(seed: u64, batch: u32, rounds: u32, case: &str, pin: usize, first_round: u32, order: &[Vec]) -> String { - let mut t = format!("{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} rounds={rounds} case={case} pin={pin}\n"); - for (i, o) in order.iter().enumerate() { - t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::>().join(",")); - } - t -} - -/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once. -fn parse_schedule(text: &str) -> Result)>, String> { - let mut lines = text.lines(); - if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) { - return Err("not a KAB1-alt schedule".to_owned()); - } - let mut rounds: Vec<(u32, Vec)> = Vec::new(); - for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) { - let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?; - let no = no.parse::().map_err(|_| format!("bad round number in {l:?}"))?; - let order: Vec = list.split(',').map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))).collect::>()?; - if let Some(prev) = rounds.last() - && (no != prev.0 + 1 || BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter()) || order.len() != prev.1.len()) - { - return Err(format!("round {no} does not follow round {} with the same processes", prev.0)); - } - rounds.push((no, order)); - } - if rounds.is_empty() { - return Err("the schedule has no round".to_owned()); - } - Ok(rounds) -} - -/// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git). -fn inside_git_checkout(path: &Path) -> bool { - let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); - abs.ancestors().any(|a| a.join(".git").exists()) -} - -// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON - -#[derive(Debug, Clone)] -struct RegimeStat { - copies_k: usize, - expert_bytes: usize, - llc_bytes: u64, - requested: usize, - dropped: usize, - median_ns: f64, - median_cycles: f64, - ns: Vec, - cycles: Vec, - max_drift: f64, - selfcheck: bool, -} - -#[derive(Debug, Clone)] -struct ProcOut { - proc: Proc, - regimes: BTreeMap, - ghz_start: f64, - ghz_end: f64, - /// None: unknown; Some(true): the sibling was idle (or there is none) under the 5 percent rule. - sibling_idle: Option, - final_unchanged: bool, - output_sha: Option, - tree_text: String, - cpu_model: Option, -} - -/// What a process's JSON must say about the run that produced it. -struct Expect<'a> { - manifest_sha: &'a str, - input_sha: &'a str, - case: &'a str, - pin: usize, -} - -fn parse_regime(r: &Json, imp: Impl) -> Result { - let mut ns = Vec::new(); - let mut cycles = Vec::new(); - let mut max_drift = 0.0f64; - for (key, keep) in [("slices", true), ("dropped", false)] { - for s in r.array(key)? { - let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?); - if g0 > 0.0 { - max_drift = max_drift.max(((g1 - g0).abs() / g0).min(1.0)); - } - if keep { - ns.push(s.float("ns_per_call")?); - cycles.push(s.float("cycles_per_call")?); - } - } - } - let selfcheck_key = if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" }; - let kept = r.uint("slices_kept")? as usize; - if kept != ns.len() || kept == 0 { - return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len())); - } - Ok(RegimeStat { - copies_k: r.uint("copies_k")? as usize, - expert_bytes: r.uint("expert_bytes")? as usize, - llc_bytes: r.uint("llc_bytes")?, - requested: r.uint("slices_requested")? as usize, - dropped: r.uint("dropped_count")? as usize, - median_ns: r.float("median_ns_per_call")?, - median_cycles: r.float("median_cycles_per_call")?, - ns, - cycles, - max_drift, - selfcheck: r.flag(selfcheck_key)?, - }) -} - -fn describe_cpp_tree(d: &Json) -> String { - let b = |k: &str| d.get(k).map_or("?".to_owned(), |v| match v { - Json::Bool(x) => x.to_string(), - Json::Num(n) => n.clone(), - _ => "?".to_owned(), - }); - let env = match d.get("strata_env") { - Some(Json::Obj(items)) if !items.is_empty() => items.iter().map(|(k, v)| format!("{k}={}", if let Json::Str(s) = v { s.as_str() } else { "?" })).collect::>().join(" "), - _ => "no STRATA_* variable set (STRATA_NO_IQ512, STRATA_NO_IQ256 and STRATA_IQ_GATHER unset)".to_owned(), - }; - format!("avx2_ok={} avx512_ok={} iq512_gather_on={} iq256_gather_setting={}; {env}", b("avx2_ok"), b("avx512_ok"), b("iq512_gather_on"), b("iq256_gather_setting")) -} - -/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input hashes, case, -/// pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's. -fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result { - let j = parse_json(bytes)?; - let name = p.name(); - let fail = |what: String| format!("cell {name}: {what}"); - if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 { - return Err(fail("the output is not KAB1-time version 1".to_owned())); - } - if j.str("writer").map_err(fail)? != p.imp.name() { - return Err(fail(format!("the output's writer is {:?}, expected {}", j.str("writer").unwrap_or("?"), p.imp.name()))); - } - if j.str("tree").map_err(fail)? != p.tree { - return Err(fail(format!("the process ran the {} tree, the cell asks for {}", j.str("tree").unwrap_or("?"), p.tree))); - } - if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha { - return Err(fail("manifest_sha256 differs from the run directory's".to_owned())); - } - let c = j.req("case").map_err(fail)?; - if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha { - return Err(fail("the case id or its input hash differs from the manifest's".to_owned())); - } - let pin = j.req("pin").map_err(fail)?; - if pin.uint("cpu").map_err(fail)? as usize != expect.pin { - return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin))); - } - let want_env: BTreeMap = cell_env(p).into_iter().collect(); - let mut seen_env = BTreeMap::new(); - if let Json::Obj(items) = j.req("effective_env").map_err(fail)? { - for (k, v) in items { - seen_env.insert(k.clone(), match v { - Json::Str(s) => s.clone(), - Json::Num(n) => n.clone(), - _ => "?".to_owned(), - }); - } - } - if seen_env != want_env { - return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"))); - } - let mut regimes = BTreeMap::new(); - for r in j.array("regimes").map_err(fail)? { - let label = r.str("regime").map_err(fail)?.to_owned(); - regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?); - } - for want in ["RESIDENT", "STREAMED"] { - if !regimes.contains_key(want) { - return Err(fail(format!("regime {want} is missing"))); - } - } - let clock = j.req("clock_calibration").map_err(fail)?; - let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? { - Json::Null => Some(true), - _ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT), - }; - let detail = j.req("tree_detail").map_err(fail)?; - let (tree_text, cpu_report) = if p.imp == Impl::Rust { - let report: Vec = detail.array("cpu_report").map_err(fail)?.iter().filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None }).collect(); - let line = report.iter().find(|l| l.starts_with("cpu: process kernel family")).cloned().ok_or_else(|| fail("no process kernel family line".to_owned()))?; - (format!("leleka-serve {line}"), report) - } else { - (describe_cpp_tree(detail), Vec::new()) - }; - let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report)); - Ok(ProcOut { - proc: *p, - regimes, - ghz_start: clock.float("ghz_at_start").map_err(fail)?, - ghz_end: clock.float("ghz_at_end").map_err(fail)?, - sibling_idle, - final_unchanged: j.flag("final_output_unchanged").map_err(fail)?, - output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }), - tree_text, - cpu_model, - }) -} - -// ------------------------------------------------------------------------------------------------ alternate: round records - -struct Tool { - compiler: String, - version: String, - triple: String, - flags: String, -} - -struct SideStat { - median: f64, - p05: f64, - p95: f64, -} - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Kind { - Ab, - AaCpp, - AaRust, -} -impl Kind { - fn slug(self) -> &'static str { - match self { - Kind::Ab => "ab", - Kind::AaCpp => "aa-cpp", - Kind::AaRust => "aa-rust", - } - } -} - -/// Everything a round record needs that does not change within a batch. -struct BatchCtx<'a> { - verified: &'a Verified, - case: &'a CaseEntry, - pin: usize, - machine_role: String, - os: String, - cpu_model: String, - started_utc: String, - rust_tool: Tool, - batch: u32, - /// Equality of our tree against the C++ reference per tree, from the equality phase. - equality: &'a BTreeMap<&'static str, Outcome>, -} - -fn side_stat(r: &RegimeStat, cycles: bool) -> SideStat { - let v = if cycles { &r.cycles } else { &r.ns }; - SideStat { median: if cycles { r.median_cycles } else { r.median_ns }, p05: percentile_of(v, 0.05), p95: percentile_of(v, 0.95) } -} - -fn stat_json(s: &SideStat) -> String { - format!("{{\"median\": {}, \"p05\": {}, \"p95\": {}}}", jnum(s.median, 6), jnum(s.p05, 6), jnum(s.p95, 6)) -} - -fn tool_json(t: &Tool) -> String { - format!("{{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}", jstr(&t.compiler), jstr(&t.version), jstr(&t.triple), jstr(&t.flags)) -} - -fn equality_block(c: &CaseEntry, o: &Outcome) -> String { - let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { - format!( - ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", - t.value, - jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), - jstr(&t.basis_written_utc) - ) - }); - format!( - "{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}", - if c.tolerance.is_some() { "tolerance" } else { "bitwise" }, - if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, - o.compared, - o.mismatches - ) -} - -/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and each one's -/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the same function. -fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { - let compared = rows * H; - let selfchecks = a.regimes.values().chain(b.regimes.values()).all(|r| r.selfcheck) && a.final_unchanged && b.final_unchanged; - let same = selfchecks && (a.proc.imp == Impl::Cpp || (a.output_sha.is_some() && a.output_sha == b.output_sha)); - let note = if a.proc.imp == Impl::Cpp { "selfcheck of both processes against compose_expert()" } else { "output sha256 of both processes" }; - let outcome = Outcome { compared, mismatches: usize::from(!same), differing_bits: usize::from(!same), max_abs_error: 0.0, first_mismatch: None }; - (outcome, note.to_owned()) -} - -/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A records. -fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result, String> { - let find = |imp: Impl, tree: &str, rep: char| done.iter().find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep).ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name())); - let p = &ctx.verified.provenance; - let c = ctx.case; - let cpp_tool = Tool { compiler: p.compiler_id.clone(), version: p.compiler_version.clone(), triple: p.target_triple.clone(), flags: p.reference_flags.clone() }; - let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)); - if done.is_empty() { - return Err("empty round".to_owned()); - } - let position = |p: &ProcOut| done.iter().position(|d| d.proc == p.proc).unwrap_or(0); - let mut files = Vec::new(); - let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); - for tree in trees { - let (cpp_a, cpp_b, rust_a, rust_b) = (find(Impl::Cpp, tree, 'a')?, find(Impl::Cpp, tree, 'b')?, find(Impl::Rust, tree, 'a')?, find(Impl::Rust, tree, 'b')?); - for regime in ["RESIDENT", "STREAMED"] { - for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] { - let (ours, reference, ours_tool, ref_tool) = match kind { - Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool), - Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool), - Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool), - }; - let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]); - if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) { - return Err(format!("round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", ours.proc.name(), reference.proc.name(), o.copies_k, r.copies_k, o.llc_bytes, r.llc_bytes)); - } - let (equality, equality_note) = match kind { - Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()), - _ => { - let (outcome, note) = aa_outcome(ours, reference, c.rows); - (aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes")) - } - }; - let kernel = format!( - "routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only", - c.rows, - match kind { - Kind::Ab => "A/B (ours = Rust, reference = C++)", - Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)", - Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)", - }, - ctx.batch, - ours.proc.name(), - reference.proc.name(), - ours.tree_text, - reference.tree_text - ); - let drift = o.max_drift.max(r.max_drift); - // the two processes of this record, earliest first: the clock before the earlier one, after the later one - let (earlier, later) = if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) }; - let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true); - let streamed = if regime == "STREAMED" { format!(",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", o.copies_k, o.expert_bytes, o.llc_bytes) } else { String::new() }; - let rowtype = |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase()); - let json = format!( - "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {equality}\n}}\n", - rid = jstr(&format!("kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}", ctx.verified.provenance.run_id, c.id, ctx.batch, kind.slug(), regime.to_ascii_lowercase())), - created = jstr(&now_utc()), - started = jstr(&ctx.started_utc), - role = jstr(&ctx.machine_role), - cpu = jstr(&ctx.cpu_model), - os = jstr(&ctx.os), - kernel = jstr(&kernel), - ot = tool_json(ours_tool), - rt = tool_json(ref_tool), - cid = jstr(&c.id), - insha = jstr(&c.in_sha256), - msha = jstr(&ctx.verified.manifest_sha256), - tree_q = jstr(tree), - regime_q = jstr(®ime.to_ascii_lowercase()), - pin = ctx.pin, - sib = sibling_idle, - commit = jstr(&p.engine_strata_pin), - method = jstr(&format!("{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", earlier.proc.name(), later.proc.name())), - g0 = jnum(earlier.ghz_start, 6), - g1 = jnum(later.ghz_end, 6), - drift = jnum(drift, 6), - total = o.requested + r.requested, - dropped = o.dropped + r.dropped, - rt_ns = jstr(&rowtype("ns")), - rt_cy = jstr(&rowtype("cycles")), - on = stat_json(&side_stat(o, false)), - rn = stat_json(&side_stat(r, false)), - oc = stat_json(&side_stat(o, true)), - rc = stat_json(&side_stat(r, true)), - ); - files.push((format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()), json)); - } - } - } - Ok(files) -} - -fn aa_equality_block(o: &Outcome) -> String { - format!("{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}", if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, o.compared, o.mismatches) -} - -// ------------------------------------------------------------------------------------------------ alternate: the runner - -const ALT_FLAGS: [&str; 13] = ["run-dir", "case", "rounds", "batch", "pin", "schedule", "seed", "out", "slices", "slice-ms", "llc-bytes", "machine-role", "kab"]; - -#[derive(Debug)] -struct AltArgs { - dir: PathBuf, - case: String, - rounds: u32, - batch: u32, - pin: usize, - schedule: PathBuf, - seed: u64, - out: Option, - slices: usize, - slice_ms: Option, - llc_bytes: Option, - machine_role: Option, - kab: Option, -} - -fn parse_alt_args(args: &[String]) -> Result { - let f = Flags::parse(args, &ALT_FLAGS)?; - let rounds = f.number::("rounds")?.ok_or("--rounds is required")?; - let batch = f.number::("batch")?.ok_or("--batch is required")?; - if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) { - return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned()); - } - let case = f.req("case")?.to_owned(); - if !valid_id(&case) { - return Err(format!("--case {case:?} is not a plain identifier")); - } - let slices = f.number::("slices")?.unwrap_or(20); - if !(1..=100_000).contains(&slices) { - return Err("--slices must be 1..100000".to_owned()); - } - Ok(AltArgs { - dir: PathBuf::from(f.req("run-dir")?), - case, - rounds, - batch, - pin: f.number::("pin")?.ok_or("--pin is required")?, - schedule: PathBuf::from(f.req("schedule")?), - seed: f.number::("seed")?.unwrap_or(1), - out: f.get("out").map(PathBuf::from), - slices, - slice_ms: f.number::("slice-ms")?, - llc_bytes: f.number::("llc-bytes")?, - machine_role: f.get("machine-role").map(str::to_owned), - kab: f.get("kab").map(PathBuf::from), - }) -} - -fn create_new_file(path: &Path, bytes: &[u8]) -> Result<(), String> { - let mut f = fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e} (nothing is overwritten)", path.display()))?; - f.write_all(bytes).map_err(|e| format!("{}: {e}", path.display())) -} - -fn file_sha(path: &Path) -> Result { - fs::read(path).map(|b| sha_hex(&b)).map_err(|e| format!("{}: {e}", path.display())) -} - -fn ours_flags() -> String { - format!("cargo profile {}; RUSTFLAGS={:?}; target-cpu default", if cfg!(debug_assertions) { "dev" } else { "release" }, std::env::var("RUSTFLAGS").unwrap_or_default()) -} - -fn cmd_alternate(args: &[String]) -> Result { - let a = parse_alt_args(args)?; - let started = now_utc(); - let verified = match verify_dir(&a.dir) { - Ok(v) => v, - Err(e) => { - println!("{e}"); - return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); - } - }; - let case = verified.cases.iter().find(|c| c.id == a.case).ok_or_else(|| format!("case {} is not in the manifest", a.case))?.clone(); - let out = a.out.clone().unwrap_or_else(|| { - let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); - a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case)) - }); - let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); - if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) { - return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); - } - if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) { - return Err("--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned()); - } - let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; - let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| { - PathBuf::from(std::env::var("E2E_ROOT").unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default()))).join("build/kernel-ab/kab") - }); - if !kab.is_file() { - return Err(format!("the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", kab.display())); - } - // a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there) - let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect(); - let procs = procs_for(&trees); - - // the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch - let first_round = (a.batch - 1) * a.rounds + 1; - let planned = make_schedule(a.seed, a.batch, a.rounds, &procs); - let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned); - fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; - if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) { - fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; - } - create_new_file(&a.schedule, text.as_bytes())?; - let schedule = parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?; - println!("schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", a.schedule.display(), sha_hex(text.as_bytes()), schedule.len(), procs.len()); - let (records_dir, proc_dir) = (out.join("records"), out.join("processes")); - for d in [&records_dir, &proc_dir] { - fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; - } - let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); - let sibling_at_start = sibling_idle(a.pin); - let machine_role = a.machine_role.clone().or_else(|| std::env::var("HOSTNAME").ok()).or_else(|| std::env::var("COMPUTERNAME").ok()).unwrap_or_else(|| "unknown".to_owned()); - let (rustc_version, triple) = rustc_info(); - - // equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing) - let eq_dir = out.join(format!("equality-b{:04}", a.batch)); - let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new(); - for tree in &trees { - let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; - let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p)); - cmd.arg("run-tree").arg(&a.dir).args(["--tree", tree, "--case", &a.case, "--out"]).arg(&eq_dir).args(["--pin", &a.pin.to_string()]); - run_cell(&mut cmd, &format!("{}/equality", p.name()))?; - let ours_name = format!("case-{}.rust-{tree}.out", a.case); - let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?; - let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?; - let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes))).map_err(|e| e.to_string())?; - let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref()); - println!( - "EQUALITY {} [{tree}] {}{}", - a.case, - if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, - outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!("; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}", outcome.mismatches, outcome.compared, outcome.max_abs_error)) - ); - equality.insert(tree, outcome); - } - - let mut cpu_model = String::new(); - let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result { - let eq = equality - .iter() - .map(|(t, o)| { - format!( - "{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}", - jstr(t), - if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, - if case.tolerance.is_some() { "tolerance" } else { "bitwise" }, - o.compared, - o.mismatches - ) - }) - .collect::>() - .join(", "); - let cells = procs - .iter() - .map(|p| format!("{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}", jstr(&p.name()), jstr(p.imp.name()), jstr(p.tree), json_env(&cell_env(p).into_iter().collect()))) - .collect::>() - .join(", "); - Ok(format!( - "{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n \"input_sha256\": {},\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": {},\n \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n \"equality\": [{eq}],\n \"cells\": [{cells}],\n \"no_statistics\": \"this file computes no class, no interval and no A/A verdict (S0.10b, STRA-313)\"\n}}\n", - a.batch, - a.rounds, - jstr(&started), - jstr(&a.case), - jstr(&a.dir.display().to_string()), - jstr(&verified.manifest_sha256), - jstr(&case.in_sha256), - a.pin, - jstr(&machine_role), - jstr(&cpu_model), - jstr(&host_os()), - a.seed, - jstr(&a.schedule.display().to_string()), - jstr(&sha_hex(text.as_bytes())), - jstr(&kab.display().to_string()), - jstr(&file_sha(&kab)?), - jstr(&own_exe.display().to_string()), - jstr(&file_sha(&own_exe)?), - a.slices, - a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1)) - )) - }; - - let expect = Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin }; - let mut ctx = BatchCtx { - verified: &verified, - case: &case, - pin: a.pin, - machine_role: machine_role.clone(), - os: host_os(), - cpu_model: String::new(), - started_utc: started.clone(), - rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() }, - batch: a.batch, - equality: &equality, - }; - let mut written = Vec::new(); - for (round_no, order) in &schedule { - let mut done: Vec = Vec::new(); - for p in order { - let name = p.name(); - let file = proc_dir.join(format!("r{round_no:05}-{name}.json")); - let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p)); - cmd.arg("time").args(["--run-dir"]).arg(&a.dir).args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"]).arg(&file); - if let Some(ms) = a.slice_ms { - cmd.args(["--slice-ms", &ms.to_string()]); - } - if let Some(b) = a.llc_bytes { - cmd.args(["--llc-bytes", &b.to_string()]); - } - let res = run_cell(&mut cmd, &name)?; - fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat()).map_err(|e| format!("{}: {e}", file.display()))?; - let bytes = fs::read(&file).map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?; - done.push(parse_proc_json(p, &bytes, &expect)?); - } - if cpu_model.is_empty() { - cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned()); - ctx.cpu_model = cpu_model.clone(); - create_new_file(&out.join(format!("batch-{:04}.json", a.batch)), batch_json(cpu_model.clone(), &equality)?.as_bytes())?; - } - for (name, json) in round_records(&ctx, *round_no, &done)? { - create_new_file(&records_dir.join(&name), json.as_bytes())?; - written.push(name); - } - println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); - } - println!("ALTERNATE OK batch={} rounds={} records={} dir={}", a.batch, a.rounds, written.len(), records_dir.display()); - for (t, o) in &equality { - println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }); - } - Ok(ExitCode::SUCCESS) -} - -// ------------------------------------------------------------------------------------------------ main - -fn usage() -> ExitCode { - eprintln!("usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU] [--case ID]"); - eprintln!(" kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]"); - eprintln!(" kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]"); - ExitCode::from(64) -} - -fn main() -> ExitCode { - let args: Vec = std::env::args().skip(1).collect(); - // `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first - if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) { - let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) }; - return result.unwrap_or_else(|e| { - eprintln!("kernel_ab {cmd}: {e}"); - ExitCode::from(1) - }); - } - let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() }; - let dir = Path::new(dir); - let opts = match parse_options(&args[2..]) { - Ok(o) => o, - Err(e) => { - eprintln!("kernel_ab: {e}"); - return usage(); - } - }; - let result = match cmd.as_str() { - "verify" => match verify_dir(dir) { - Ok(v) => { - println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256); - Ok(ExitCode::SUCCESS) - } - Err(e) => { - println!("{e}"); - Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })) - } - }, - "compare" => cmd_compare(dir, &opts), - "run-tree" => match (&opts.tree, &opts.out) { - (Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()), - _ => return usage(), - }, - _ => return usage(), - }; - result.unwrap_or_else(|e| { - eprintln!("kernel_ab: {e}"); - ExitCode::from(1) - }) -} - -// ------------------------------------------------------------------------------------------------ tests - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - static COUNTER: AtomicUsize = AtomicUsize::new(0); - - struct TempDir(PathBuf); - impl TempDir { - fn new() -> Self { - let p = std::env::temp_dir().join(format!("kab1-test-{}-{}", std::process::id(), COUNTER.fetch_add(1, Ordering::SeqCst))); - fs::create_dir_all(&p).unwrap(); - Self(p) - } - } - impl Drop for TempDir { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.0); - } - } - - fn block_filled(len: usize, block: usize, seed: u8) -> Vec { - let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); - for at in (0..len).step_by(block) { - v[at] = 0x00; - v[at + 1] = 0x3c; // FP16 1.0 - } - v - } - - fn in_file(gu: i32, down: i32, rows: usize) -> Vec { - let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); - let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); - let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); - let mut b = Vec::new(); - for w in [IN_MAGIC, 1, gu as u32, down as u32, rows as u32, H as u32, FF as u32, gsize as u32, gsize as u32, dsize as u32] { - b.extend_from_slice(&w.to_le_bytes()); - } - b.resize(IN_HEADER, 0); - b.extend(block_filled(gsize, gb, 1)); - b.extend(block_filled(gsize, gb, 2)); - b.extend(block_filled(dsize, db, 3)); - for i in 0..rows * H { - b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); - } - b - } - - fn out_file(rows: usize, tree: u32) -> Vec { - let mut b = Vec::new(); - for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { - b.extend_from_slice(&w.to_le_bytes()); - } - for i in 0..rows * H { - b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); - } - b - } - - struct Spec { - gu: i32, - down: i32, - rows: usize, - tolerance: Option<&'static str>, - } - - /// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. - fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { - let mut cases = Vec::new(); - let mut files = Vec::new(); - for s in specs { - let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); - let mut inb = in_file(s.gu, s.down, s.rows); - mutate(&mut inb); - fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); - let mut entry = format!( - "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", - s.gu, - s.down, - s.rows, - if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, - s.tolerance.unwrap_or("null"), - sha_hex(&inb), - inb.len() - ); - files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); - for (k, tree) in TREES.iter().enumerate() { - let ob = out_file(s.rows, k as u32); - fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); - entry += &format!(", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \"out_cpp_{tree}_bytes\": {}", sha_hex(&ob), ob.len()); - files.push(format!("\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&ob), ob.len())); - } - cases.push(entry + "}"); - } - let manifest = format!( - "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \"provenance\": {{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {{\"strata_cxx_flags\": \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}}}, \"cases\": [{}], \"files\": {{{}}}}}", - cases.join(", "), - files.join(", ") - ); - fs::write(dir.join("manifest.json"), manifest).unwrap(); - } - - fn two_cases() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] - } - - fn one_case() -> Vec { - vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] - } - - fn id(file: &str) -> String { - format!("case-42-42-r1.{file}") - } - - #[test] - fn a_good_directory_verifies() { - let t = TempDir::new(); - build(&t.0, &two_cases(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases.len(), 2); - assert_eq!(v.file_count, 2 * 3 + 1); - assert_eq!(v.manifest_sha256.len(), 64); - assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); - } - - #[test] - fn a_flipped_byte_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("in")); - let mut b = fs::read(&p).unwrap(); - b[IN_HEADER + 7] ^= 0x40; - fs::write(&p, b).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("sha256"), "{e}"); - } - - #[test] - fn a_truncated_file_refuses_the_directory_and_names_the_file() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let p = t.0.join(id("cpp-avx2.out")); - let b = fs::read(&p).unwrap(); - fs::write(&p, &b[..b.len() - 4]).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); - assert!(e.reason.contains("length"), "{e}"); - } - - #[test] - fn a_wrong_magic_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[0] ^= 0xff); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("magic"), "{e}"); - } - - #[test] - fn a_wrong_version_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[4] = 2); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("version"), "{e}"); - } - - #[test] - fn a_byte_count_that_disagrees_with_the_format_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let wrong = (le32(b, 28) + 18).to_le_bytes(); - b[28..32].copy_from_slice(&wrong); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("format-derived"), "{e}"); - } - - #[test] - fn a_non_finite_fp16_header_is_refused() { - let t = TempDir::new(); - // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it - build(&t.0, &one_case(), |b| { - let at = IN_HEADER + 18 * 3; - b[at] = 0x00; - b[at + 1] = 0x7c; // FP16 +inf - }); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "case-42-42-r1.in"); - assert!(e.reason.contains("non-finite FP16"), "{e}"); - } - - #[test] - fn a_non_finite_activation_is_refused() { - let t = TempDir::new(); - build(&t.0, &one_case(), |b| { - let at = b.len() - 4; - b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); - }); - let e = verify_dir(&t.0).unwrap_err(); - assert!(e.reason.contains("non-finite activation"), "{e}"); - } - - #[test] - fn a_missing_manifest_is_incomplete_and_named() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::remove_file(t.0.join("manifest.json")).unwrap(); - let e = verify_dir(&t.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.incomplete); - assert!(e.to_string().contains("manifest.json")); - } - - #[test] - fn an_extra_or_missing_file_refuses_the_directory() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - fs::write(t.0.join("stray.txt"), b"x").unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); - fs::remove_file(t.0.join("stray.txt")).unwrap(); - fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); - assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); - } - - #[test] - fn an_absurd_length_is_refused_without_taking_a_buffer() { - // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists - let mut h = [0u8; IN_HEADER]; - h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); - h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); - BUFFERS.with(|c| c.set(0)); - assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // and through the file reader: manifest and file agree on a file whose header lies about its size - let t = TempDir::new(); - build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); - BUFFERS.with(|c| c.set(0)); - let (m, _) = (fs::read(t.0.join("manifest.json")).unwrap(), 0); - let (_, cases, _) = parse_manifest(&parse_json(&m).unwrap()).unwrap(); - let e = read_case_in(&t.0, &cases[0]).err().unwrap(); - assert!(e.reason.contains("format-derived"), "{e}"); - assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); - // a manifest that declares an absurd length for a file is refused before a buffer too - let mut lying = cases[0].clone(); - lying.in_bytes = u64::MAX; - assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); - assert_eq!(BUFFERS.with(Cell::get), 0); - // the good path takes exactly one buffer per file - let g = TempDir::new(); - build(&g.0, &one_case(), |_| {}); - BUFFERS.with(|c| c.set(0)); - let (_, cases, _) = parse_manifest(&parse_json(&fs::read(g.0.join("manifest.json")).unwrap()).unwrap()).unwrap(); - read_case_in(&g.0, &cases[0]).unwrap(); - assert_eq!(BUFFERS.with(Cell::get), 1); - } - - #[test] - fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { - let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; - let t = TempDir::new(); - build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); - let v = verify_dir(&t.0).unwrap(); - assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); - for (bad, why) in [ - (ok.replace("0.003", "0"), "positive"), - (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), - (ok.replace("order-only difference", " "), "basis"), - (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), - ] { - let leaked: &'static str = Box::leak(bad.into_boxed_str()); - let d = TempDir::new(); - build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); - let e = verify_dir(&d.0).unwrap_err(); - assert_eq!(e.file, "manifest.json"); - assert!(e.reason.contains(why), "{why}: {e}"); - } - } - - #[test] - fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { - let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); - assert_eq!(j.get("a"), Some(&Json::Arr(vec![Json::Num("1".into()), Json::Num("-2.5e3".into()), Json::Bool(true), Json::Null, Json::Str("x\n\u{e9}\u{1f600}".into())]))); - assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); - for bad in ["{\"a\": 1, \"a\": 2}", "{\"a\": 1,}", "[1 2]", "{\"a\": \"\\ud800\"}", "{} x", "", "{\"a\": 01x}", "\"\u{1}\""] { - assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); - } - assert!(parse_json("[".repeat(40).as_bytes()).is_err()); - } - - #[test] - fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { - let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; - assert!(compare_bits(&a, &a, None).equal()); - let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; - let o = compare_bits(&neg0, &a, None); - assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); - let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; - assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); - let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; - assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); - let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; - assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); - assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); - } - - #[test] - fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); - let mut pool = DirectCpuPool::new(1).unwrap(); - let first = compute_case(&mut pool, &case).unwrap(); - let second = compute_case(&mut pool, &case).unwrap(); - assert_eq!(first.len(), H); - assert!(first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), "the same case twice must be bit-identical"); - let path = t.0.join("ours.rust-avx2.out"); - write_out(&path, 1, "avx2", &first).unwrap(); - let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); - assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); - let outcome = compare_bits(&back, &back, None); - let json = record_json(&RecordInput { - record_id: "kab1-synthetic-r".into(), - created_utc: "2026-10-28T20:00:00Z".into(), - run_started_utc: "2026-10-28T19:59:00Z".into(), - machine_role: "m\"1".into(), - cpu_model: "cpu".into(), - os: "os".into(), - ours_compiler: "rustc".into(), - ours_version: "rustc 1.99.0".into(), - ours_triple: "x86_64-unknown-linux-gnu".into(), - ours_flags: "f".into(), - tree: "avx2", - verified: &v, - case: &v.cases[0], - pin_cpu: 0, - sibling_idle: true, - outcome: &outcome, - }); - let rec = parse_json(json.as_bytes()).unwrap(); - for key in ["schema_version", "level", "record_id", "created_utc", "run_started_utc", "machine", "kernel", "toolchain", "case_id", "input_sha256", "kab1_manifest_sha256", "tree", "regime", "pin", "strata_upstream_commit", "clock_calibration", "rows", "aa_noise_floor", "equality"] { - assert!(rec.get(key).is_some(), "{key}"); - } - assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); - assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); - assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); - } - - // ---------------------------------------------------------------------------------------------------- alternation (STRA-318) - - #[test] - fn the_schedule_is_reproducible_from_the_seed() { - let procs = procs_for(&TREES); - let a = make_schedule(7, 1, 30, &procs); - assert_eq!(a, make_schedule(7, 1, 30, &procs)); - assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule"); - assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule"); - assert_eq!(a.len(), 30); - // the text round-trips through the file format and names the seed - let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a); - assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9")); - let back = parse_schedule(&text).unwrap(); - assert_eq!(back.iter().map(|r| r.1.clone()).collect::>(), a); - assert_eq!(back[0].0, 1); - assert_eq!(back[29].0, 30); - } - - #[test] - fn the_rotation_gives_every_process_every_position_within_a_block() { - let procs = procs_for(&TREES); - assert_eq!(procs.len(), 8); - let s = make_schedule(3, 1, 16, &procs); - for block in s.chunks(8) { - for round in block { - let mut names: Vec<_> = round.iter().map(Proc::name).collect(); - names.sort(); - assert_eq!(names.len(), 8); - names.dedup(); - assert_eq!(names.len(), 8, "every process exactly once per round"); - } - for pos in 0..8 { - let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect(); - assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds"); - } - } - // a host without AVX-512 has only the avx2 cells - assert_eq!(procs_for(&["avx2"]).len(), 4); - } - - #[test] - fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() { - let t = TempDir::new(); - let f = t.0.join("schedule.tsv"); - create_new_file(&f, b"x").unwrap(); - assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten")); - assert_eq!(fs::read(&f).unwrap(), b"x"); - let procs = procs_for(&TREES); - let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs)); - assert!(parse_schedule(&good).is_ok()); - assert!(parse_schedule("nope").is_err()); - assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process")); - assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow")); - // a round that names one process twice (and so lacks another) is refused - let dup = good.lines().map(|l| if l.starts_with("2\t") { l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) } else { l.to_owned() }).collect::>().join("\n"); - assert!(parse_schedule(&dup).is_err()); - } - - /// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run. - #[test] - fn env_probe_child() { - if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) { - return; - } - for (k, v) in std::env::vars() { - if is_managed_name(&k) { - println!("PROBE {k}={v}"); - } - } - } - - /// The child side of the failure test. - #[test] - fn failing_child() { - if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) { - eprintln!("simulated kernel failure"); - std::process::exit(3); - } - } - - fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command { - let mut parent: Vec<(OsString, OsString)> = std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect(); - parent.push(("KAB_TEST_CHILD".into(), mode.into())); - parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into()))); - let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell); - c.args(["--exact", test, "--nocapture", "--test-threads=1"]); - c - } - - #[test] - fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() { - let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' }); - assert_eq!( - cell, - vec![("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())] - ); - assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); - let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], &cell), "rust-avx2-a").unwrap(); - let text = String::from_utf8_lossy(&out.stdout); - // libtest prints "test ... " before the child's own output on the same line - let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); - probes.sort_unstable(); - assert_eq!(probes, vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], "only the cell's variables survive:\n{text}"); - // the cpp avx512 cell sets nothing at all - let out = run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a").unwrap(); - assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); - } - - #[test] - fn a_child_failure_is_reported_with_the_cell_named() { - let e = run_cell(&mut child("tests::failing_child", "fail", &[], &[]), "cpp-avx2-b").unwrap_err(); - assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}"); - assert!(e.contains("simulated kernel failure"), "{e}"); - let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err(); - assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}"); - } - - #[test] - fn the_time_command_line_is_the_one_of_kab_time() { - let v = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::>(); - let t = parse_time_args(&v(&["--run-dir", "D", "--case", "18-20-r1", "--slices", "50", "--pin", "9", "--out", "t.json"])).unwrap(); - assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None)); - let t = parse_time_args(&v(&["--run-dir", "D", "--case", "c", "--slices", "2", "--pin", "0", "--out", "o", "--slice-ms", "5", "--regime", "streamed", "--llc-bytes", "1000"])).unwrap(); - assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); - for bad in [ - v(&["--run-dir", "D", "--case", "c", "--slices", "0", "--pin", "0", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--regime", "both2"]), - v(&["--run-dir", "D", "--case", "../c", "--slices", "1", "--pin", "0", "--out", "o"]), - v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--bogus", "1"]), - v(&["--run-dir", "D", "--run-dir", "E", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o"]), - ] { - assert!(parse_time_args(&bad).is_err(), "{bad:?}"); - } - let a = parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "1", "--pin", "9", "--schedule", "s.tsv"])).unwrap(); - assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20)); - assert!(parse_alt_args(&v(&["--run-dir", "D", "--case", "c", "--rounds", "30", "--batch", "0", "--pin", "9", "--schedule", "s"])).is_err()); - } - - #[test] - fn medians_percentiles_and_parsers_agree_with_the_reference_rules() { - assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference"); - assert_eq!(median_of(&[]), 0.0); - let v: Vec = (1..=21).map(f64::from).collect(); - assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0)); - assert_eq!(parse_cpu_list("2,18"), vec![2, 18]); - assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]); - assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); - assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); - assert_eq!(busy_fraction(None, Some((1, 1))), None); - // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain) - let ghz = core_ghz(); - assert!((0.3..12.0).contains(&ghz), "{ghz}"); - } - - #[test] - fn an_output_inside_a_git_checkout_is_detected() { - let t = TempDir::new(); - let inner = t.0.join("a/b"); - fs::create_dir_all(&inner).unwrap(); - assert!(!inside_git_checkout(&inner)); - fs::create_dir_all(t.0.join(".git")).unwrap(); - assert!(inside_git_checkout(&inner)); - assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv"))); - } - - fn json_regime(label: &str, k: usize, self_key: &str) -> String { - let slice = |g1: f64| format!("{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}"); - format!( - "{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}", - slice(5.0), - slice(5.1), - slice(4.0) - ) - } - - /// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective environment. - fn proc_fixture(p: &Proc, env: &str) -> String { - let (self_key, detail) = if p.imp == Impl::Cpp { - ("selfcheck_bitwise_equal_compose_expert", "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \"iq256_gather_setting\": -1, \"strata_env\": {}}".to_owned()) - } else { - ("selfcheck_bitwise_equal_first_call", format!("{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", p.tree)) - }; - format!( - "{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}", - p.imp.name(), - p.tree, - "cd".repeat(32), - json_regime("RESIDENT", 1, self_key), - json_regime("STREAMED", 3, self_key) - ) - } - - #[test] - fn a_process_json_is_checked_against_the_cell_that_was_started() { - let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 }; - for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] { - let env = json_env(&cell_env(&p).into_iter().collect()); - let ok = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &expect).unwrap(); - assert_eq!(ok.regimes.len(), 2); - let r = &ok.regimes["STREAMED"]; - assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3)); - assert!((r.max_drift - 0.2).abs() < 1e-9, "the dropped slice's 20 percent drift is the maximum: {}", r.max_drift); - assert_eq!(ok.sibling_idle, Some(true)); - // the environment the process saw must be exactly the cell's - let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())])); - let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err(); - assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}"); - // wrong pin, wrong manifest, wrong input, wrong writer: each names the cell - for (bad_expect, what) in [ - (Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"), - (Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"), - (Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"), - ] { - let e = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &bad_expect).unwrap_err(); - assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}"); - } - let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..p }; - assert!(parse_proc_json(&other, proc_fixture(&p, &env).as_bytes(), &expect).unwrap_err().contains("writer")); - } - } - - fn fake_proc(p: Proc, base: f64) -> ProcOut { - let regime = |k: usize| RegimeStat { - copies_k: k, - expert_bytes: 1_000_000, - llc_bytes: 1_000, - requested: 10, - dropped: 1, - median_ns: base, - median_cycles: base * 5.0, - ns: vec![base * 0.9, base, base * 1.1], - cycles: vec![base * 4.5, base * 5.0, base * 5.5], - max_drift: 0.01, - selfcheck: true, - }; - ProcOut { - proc: p, - regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]), - ghz_start: 5.0, - ghz_end: 5.1, - sibling_idle: Some(true), - final_unchanged: true, - output_sha: Some("ab".repeat(32)), - tree_text: format!("tree text of {}", p.name()), - cpu_model: Some("Test CPU".to_owned()), - } - } - - #[test] - fn round_records_have_the_schema_shape_and_keep_not_equal() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let v = verify_dir(&t.0).unwrap(); - let outcome = |bad: usize| Outcome { compared: H, mismatches: bad, differing_bits: bad, max_abs_error: 0.0, first_mismatch: None }; - let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); - let ctx = BatchCtx { - verified: &v, - case: &v.cases[0], - pin: 9, - machine_role: "m".into(), - os: "os".into(), - cpu_model: "cpu".into(), - started_utc: "2026-10-28T20:00:00Z".into(), - rust_tool: Tool { compiler: "rustc".into(), version: "rustc 1.99.0".into(), triple: "x86_64-unknown-linux-gnu".into(), flags: "f".into() }, - batch: 2, - equality: &equality, - }; - let mut done: Vec = procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); - done.reverse(); // the order of execution does not matter to the records - done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = Some(false); - let files = round_records(&ctx, 31, &done).unwrap(); - assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); - let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); - assert_eq!(names.len(), 12); - assert!(names.contains("r00031.ab.avx2.streamed.json") && names.contains("r00031.aa-cpp.avx512.resident.json") && names.contains("r00031.aa-rust.avx2.resident.json")); - for (name, json) in &files { - let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); - for key in ["schema_version", "level", "record_id", "created_utc", "run_started_utc", "machine", "kernel", "toolchain", "case_id", "input_sha256", "kab1_manifest_sha256", "tree", "regime", "pin", "strata_upstream_commit", "clock_calibration", "rows", "aa_noise_floor", "equality"] { - assert!(rec.get(key).is_some(), "{name}: {key}"); - } - assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL"); - assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); - assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256); - let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") }; - let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect(); - assert_eq!(units, ["ns", "cycles"]); - assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type"); - let regime = rec.str("regime").unwrap(); - assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}"); - assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER")); - let eq = rec.req("equality").unwrap(); - let tree = rec.req("tree").unwrap().str("ours").unwrap(); - let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" }; - assert_eq!(eq.str("verdict").unwrap(), want, "{name}"); - if want == "NOT_EQUAL" { - assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden"); - } - } - // the A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation on both - let ab = parse_json(files.iter().find(|f| f.0 == "r00031.ab.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); - assert!(ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a")); - assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc"); - let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); - assert!(aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b")); - assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); - // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b - for (name, json) in &files { - let rec = parse_json(json.as_bytes()).unwrap(); - let busy = name.contains(".aa-cpp.avx2."); - assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); - } - // a streamed set that differs between the two sides of a record is refused - let mut skewed = done.clone(); - skewed.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }).unwrap().regimes.get_mut("STREAMED").unwrap().copies_k = 4; - assert!(round_records(&ctx, 31, &skewed).unwrap_err().contains("streamed set differs")); - // a missing process is named - assert!(round_records(&ctx, 31, &done[1..]).unwrap_err().contains("did not run")); - } - - #[test] - fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() { - let t = TempDir::new(); - build(&t.0, &one_case(), |_| {}); - let out = TempDir::new(); - let file = out.0.join("t.json"); - let args: Vec = ["--run-dir", t.0.to_str().unwrap(), "--case", "42-42-r1", "--slices", "40", "--pin", "0", "--out", file.to_str().unwrap(), "--slice-ms", "1", "--llc-bytes", "8000000"].iter().map(|s| (*s).to_owned()).collect(); - // exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the loaded host's call) - let code = format!("{:?}", cmd_time(&args).unwrap()); - assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}"); - let text = fs::read_to_string(&file).unwrap(); - let j = parse_json(text.as_bytes()).unwrap(); - assert_eq!(j.str("writer").unwrap(), "rust"); - assert_eq!(j.str("format").unwrap(), "KAB1-time"); - assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap()); - assert_eq!(j.str("output_sha256").unwrap().len(), 64); - let tree = j.str("tree").unwrap().to_owned(); - let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' }; - if !code.contains("(0)") { - return; - } - let manifest = fs::read(t.0.join("manifest.json")).unwrap(); - let (_, _, cases, _) = read_manifest(&t.0).unwrap(); - let sha = sha_hex(&manifest); - let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 }; - // the test process runs unscrubbed (its effective environment is empty), so the runner's environment check refuses it ... - assert!(parse_proc_json(&p, text.as_bytes(), &expect).unwrap_err().contains("effective environment")); - // ... and accepts it once the recorded environment is the cell's - let want_env = json_env(&cell_env(&p).into_iter().collect()); - let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1); - let ok = parse_proc_json(&p, as_cell.as_bytes(), &expect).unwrap(); - for r in ["RESIDENT", "STREAMED"] { - let s = &ok.regimes[r]; - assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}"); - assert_eq!(s.requested, 40); - } - assert_eq!(ok.regimes["RESIDENT"].copies_k, 1); - assert!(ok.regimes["STREAMED"].copies_k >= 2); - assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family")); - // a lie about the pin is refused - assert!(parse_proc_json(&p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }).unwrap_err().contains("pinned to CPU")); - } - - #[test] - fn utc_formatting_is_exact() { - assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); - assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); - assert!(is_utc(&now_utc())); - } -} +#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +// This file is its own lint gate: `cargo clippy -- -D warnings` also lints the other workspace crates, which carry warnings of their own. +#![deny(warnings, clippy::all)] +//! Rust half of the CPU kernel A/B, part 1 (STRA-289, S0.8b): the KAB1 reader, the comparison against the C++ reference outputs and +//! the COMPONENT_KERNEL record writer. The C++ driver (`tools/kernel-ab`, STRA-248) writes a run directory `D`; this example only +//! reads it. C++ and Rust meet through files: no FFI, no unsafe, public API of the crate only, no module in the production library. +//! +//! kernel_ab verify D the reader rule: manifest, every sha256 and length, header-derived sizes, finite +//! FP16 block headers and activations; any mismatch refuses the WHOLE directory +//! kernel_ab compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] +//! verify D, run our trees in fresh processes (`run-tree`), compare with the C++ +//! `.out` files (bitwise on the f32 bit patterns, or the tolerance the manifest case +//! declares with its basis), write `R/case-.rust-.out` and one +//! COMPONENT_KERNEL record per case and tree to `R/records/` +//! kernel_ab run-tree D --tree T --out R [--pin CPU] [--case ID] +//! internal: one fresh process, one tree (T = avx512 | avx2), all cases or only ID +//! +//! Timing is not in `verify` / `compare`. The records written by `compare` carry the fields the schema requires for timing with the +//! explicit NOT_MEASURED marker (see `NOT_MEASURED`), never a measurement. Timing is the second half (STRA-318, S0.8b2): +//! +//! kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] +//! [--llc-bytes B] +//! the Rust twin of `kab time` (tools/kernel-ab, STRA-317): ONE fresh process times ONE +//! case in the resident and the streamed regime on the pinned CPU and writes the KAB1-time +//! JSON (writer "rust"); no statistics +//! kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] +//! [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH] +//! the alternation runner (ARCHITECT 395f0394 sec 1.3): std::process::Command only. Per +//! round it starts FRESH processes for the cells {cpp, rust} x {avx512, avx2} (each twice, +//! a and b, for the A/A pairs) in the order of a seeded schedule file written before the +//! first run, and writes COMPONENT_KERNEL round records. It computes NO statistics: no +//! class, no interval, no A/A verdict (those are S0.10b, STRA-313). +//! +//! cargo run --release -p leleka-native-cpu-expert --example kernel_ab -- compare D +//! cargo test -p leleka-native-cpu-expert --example kernel_ab + +use leleka_native_cpu_expert::{ + BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, cpu_kernel_report, + rust_topology, +}; +use sha2::{Digest, Sha256}; +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::OsString; +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode}; +use std::sync::OnceLock; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +const IN_MAGIC: u32 = 0x4942_414B; +const OUT_MAGIC: u32 = 0x4F42_414B; +const IN_HEADER: usize = 64; +const OUT_HEADER: usize = 20; +const H: usize = 2560; +const FF: usize = 640; +const MAX_ROWS: usize = 8; +/// Largest legitimate file of the format is about 2.7 MB; anything above this is refused before any buffer is taken. +const MAX_FILE_BYTES: u64 = 16 << 20; +const MAX_MANIFEST_BYTES: u64 = 8 << 20; +const MAX_CASES: usize = 1024; +const TOLERANCE_METRIC: &str = "max_abs_error_over_max_abs_reference"; +/// Marker of every schema-required timing field this part does not measure (STRA-318 fills them): a text marker where the schema takes +/// text, the smallest positive double (`5e-324`) where it takes a positive number, 1 where it takes a positive count. +const NOT_MEASURED: &str = "NOT_MEASURED (filled by STRA-318, the alternation runner)"; +const TREES: [&str; 2] = ["avx512", "avx2"]; + +thread_local! { static BUFFERS: Cell = const { Cell::new(0) }; } + +// ------------------------------------------------------------------------------------------------ formats + +/// (ggml id, format, block elements, block bytes, name) as `lib.rs kind()/block()`. +const GATE_UP: [(i32, GateUpFormat, usize, usize, &str); 7] = [ + (18, GateUpFormat::Iq3Xxs, 256, 98, "IQ3_XXS"), + (21, GateUpFormat::Iq3S, 256, 110, "IQ3_S"), + (22, GateUpFormat::Iq2S, 256, 82, "IQ2_S"), + (23, GateUpFormat::Iq4Xs, 256, 136, "IQ4_XS"), + (42, GateUpFormat::Q2_0, 64, 18, "Q2_0"), + (16, GateUpFormat::Iq2Xxs, 256, 66, "IQ2_XXS"), + (17, GateUpFormat::Iq2Xs, 256, 74, "IQ2_XS"), +]; +const DOWN: [(i32, DownFormat, usize, usize, &str); 2] = + [(20, DownFormat::Iq4Nl, 32, 18, "IQ4_NL"), (42, DownFormat::Q2_0, 64, 18, "Q2_0")]; + +fn gate_up_row(id: i32) -> Option<&'static (i32, GateUpFormat, usize, usize, &'static str)> { + GATE_UP.iter().find(|r| r.0 == id) +} +fn down_row(id: i32) -> Option<&'static (i32, DownFormat, usize, usize, &'static str)> { + DOWN.iter().find(|r| r.0 == id) +} + +// ------------------------------------------------------------------------------------------------ errors + +/// A refusal of the whole directory: names the file and says why. `incomplete` is the missing-manifest case. +#[derive(Debug)] +struct Refusal { + file: String, + reason: String, + incomplete: bool, +} +impl Refusal { + fn new(file: &str, reason: impl Into) -> Self { + Self { file: file.to_owned(), reason: reason.into(), incomplete: false } + } +} +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.incomplete { + write!(f, "incomplete directory: {}: {}", self.file, self.reason) + } else { + write!(f, "REFUSED {}: {}", self.file, self.reason) + } + } +} + +// ------------------------------------------------------------------------------------------------ helpers + +fn sha_hex(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + digest.iter().map(|b| format!("{b:02x}")).collect() +} + +/// The only place a buffer is taken from a length that came from a file; every caller validates the length first. +fn take_buffer(len: usize) -> Result, String> { + BUFFERS.with(|c| c.set(c.get() + 1)); + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| format!("a buffer of {len} bytes was refused"))?; + v.resize(len, 0); + Ok(v) +} + +/// Little-endian words of a byte slice (a trailing partial word is ignored; callers pass exact multiples). +fn words_le(bytes: &[u8]) -> Vec { + bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect() +} + +fn le32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]) +} + +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +fn utc_of(secs: u64) -> String { + let (y, m, d) = civil_from_days((secs / 86_400) as i64); + let s = secs % 86_400; + format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", s / 3600, s % 3600 / 60, s % 60) +} + +fn now_utc() -> String { + utc_of(SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())) +} + +fn is_utc(s: &str) -> bool { + let b = s.as_bytes(); + b.len() == 20 + && b.iter().enumerate().all(|(i, c)| match i { + 4 | 7 => *c == b'-', + 10 => *c == b'T', + 13 | 16 => *c == b':', + 19 => *c == b'Z', + _ => c.is_ascii_digit(), + }) +} + +fn is_hex(s: &str, min: usize, max: usize) -> bool { + (min..=max).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= 64 && id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') +} + +// ------------------------------------------------------------------------------------------------ JSON (read) + +#[derive(Debug, Clone, PartialEq)] +enum Json { + Null, + Bool(bool), + Num(String), + Str(String), + Arr(Vec), + Obj(Vec<(String, Json)>), +} + +struct Parser<'a> { + b: &'a [u8], + at: usize, +} + +impl Parser<'_> { + fn ws(&mut self) { + while self.at < self.b.len() && matches!(self.b[self.at], b' ' | b'\t' | b'\n' | b'\r') { + self.at += 1; + } + } + fn err(&self, what: &str) -> Result { + Err(format!("JSON error at byte {}: {what}", self.at)) + } + fn lit(&mut self, word: &str, v: Json) -> Result { + if self.b[self.at..].starts_with(word.as_bytes()) { + self.at += word.len(); + Ok(v) + } else { + self.err("unknown literal") + } + } + fn hex4(&mut self) -> Result { + if self.at + 4 > self.b.len() { + return self.err("short \\u escape"); + } + let s = std::str::from_utf8(&self.b[self.at..self.at + 4]).map_err(|_| "bad \\u escape".to_owned())?; + let v = u32::from_str_radix(s, 16).map_err(|_| "bad \\u escape".to_owned())?; + self.at += 4; + Ok(v) + } + fn string(&mut self) -> Result { + self.at += 1; + let mut out: Vec = Vec::new(); + loop { + let Some(&c) = self.b.get(self.at) else { return self.err("unterminated string") }; + self.at += 1; + match c { + b'"' => return String::from_utf8(out).map_err(|_| "string is not UTF-8".to_owned()), + b'\\' => { + let Some(&e) = self.b.get(self.at) else { return self.err("unterminated escape") }; + self.at += 1; + let ch = match e { + b'"' => '"', + b'\\' => '\\', + b'/' => '/', + b'b' => '\u{8}', + b'f' => '\u{c}', + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'u' => { + let hi = self.hex4()?; + let cp = if (0xD800..0xDC00).contains(&hi) { + if !self.b[self.at..].starts_with(b"\\u") { + return self.err("lone surrogate"); + } + self.at += 2; + let lo = self.hex4()?; + if !(0xDC00..0xE000).contains(&lo) { + return self.err("lone surrogate"); + } + 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00) + } else { + hi + }; + match char::from_u32(cp) { + Some(c) => c, + None => return self.err("lone surrogate"), + } + } + _ => return self.err("unknown escape"), + }; + let mut buf = [0u8; 4]; + out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); + } + 0..=0x1f => return self.err("control character in string"), + _ => out.push(c), + } + } + } + fn number(&mut self) -> Result { + let start = self.at; + while self.at < self.b.len() && matches!(self.b[self.at], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') { + self.at += 1; + } + let text = std::str::from_utf8(&self.b[start..self.at]).map_err(|_| "bad number".to_owned())?; + if text.parse::().is_err() { + return self.err("bad number"); + } + Ok(Json::Num(text.to_owned())) + } + fn value(&mut self, depth: usize) -> Result { + if depth > 32 { + return self.err("nesting deeper than 32"); + } + self.ws(); + match self.b.get(self.at) { + None => self.err("unexpected end"), + Some(b'{') => { + self.at += 1; + let mut items: Vec<(String, Json)> = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b'}') { + self.at += 1; + return Ok(Json::Obj(items)); + } + loop { + self.ws(); + if self.b.get(self.at) != Some(&b'"') { + return self.err("object key expected"); + } + let key = self.string()?; + if items.iter().any(|(k, _)| *k == key) { + return self.err(&format!("duplicate key {key:?}")); + } + self.ws(); + if self.b.get(self.at) != Some(&b':') { + return self.err("':' expected"); + } + self.at += 1; + let v = self.value(depth + 1)?; + items.push((key, v)); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b'}') => { + self.at += 1; + return Ok(Json::Obj(items)); + } + _ => return self.err("',' or '}' expected"), + } + } + } + Some(b'[') => { + self.at += 1; + let mut items = Vec::new(); + self.ws(); + if self.b.get(self.at) == Some(&b']') { + self.at += 1; + return Ok(Json::Arr(items)); + } + loop { + items.push(self.value(depth + 1)?); + self.ws(); + match self.b.get(self.at) { + Some(b',') => self.at += 1, + Some(b']') => { + self.at += 1; + return Ok(Json::Arr(items)); + } + _ => return self.err("',' or ']' expected"), + } + } + } + Some(b'"') => Ok(Json::Str(self.string()?)), + Some(b't') => self.lit("true", Json::Bool(true)), + Some(b'f') => self.lit("false", Json::Bool(false)), + Some(b'n') => self.lit("null", Json::Null), + Some(b'-' | b'0'..=b'9') => self.number(), + Some(_) => self.err("unexpected character"), + } + } +} + +fn parse_json(bytes: &[u8]) -> Result { + let mut p = Parser { b: bytes, at: 0 }; + let v = p.value(0)?; + p.ws(); + if p.at != bytes.len() { + return p.err("trailing data"); + } + Ok(v) +} + +impl Json { + fn get(&self, key: &str) -> Option<&Json> { + match self { + Json::Obj(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + fn req(&self, key: &str) -> Result<&Json, String> { + self.get(key).ok_or_else(|| format!("missing key {key:?}")) + } + fn str(&self, key: &str) -> Result<&str, String> { + match self.req(key)? { + Json::Str(s) => Ok(s), + _ => Err(format!("key {key:?} is not a string")), + } + } + fn uint(&self, key: &str) -> Result { + match self.req(key)? { + Json::Num(n) => n.parse::().map_err(|_| format!("key {key:?} is not an unsigned integer")), + _ => Err(format!("key {key:?} is not a number")), + } + } + fn float(&self, key: &str) -> Result { + match self.req(key)? { + Json::Num(n) => n + .parse::() + .ok() + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("key {key:?} is not a finite number")), + _ => Err(format!("key {key:?} is not a number")), + } + } + /// A number, or None for a JSON null (the C++ writer prints null for a value it could not measure). + fn float_or_null(&self, key: &str) -> Result, String> { + match self.req(key)? { + Json::Null => Ok(None), + _ => self.float(key).map(Some), + } + } + fn flag(&self, key: &str) -> Result { + match self.req(key)? { + Json::Bool(b) => Ok(*b), + _ => Err(format!("key {key:?} is not a boolean")), + } + } + fn array(&self, key: &str) -> Result<&[Json], String> { + match self.req(key)? { + Json::Arr(a) => Ok(a), + _ => Err(format!("key {key:?} is not an array")), + } + } +} + +// ------------------------------------------------------------------------------------------------ KAB1 headers + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct InHeader { + gu: i32, + down: i32, + rows: usize, + gate: usize, + up: usize, + down_bytes: usize, +} + +impl InHeader { + fn input_at(&self) -> usize { + IN_HEADER + self.gate + self.up + self.down_bytes + } +} + +/// Pure: decides from 64 header bytes and the file length, allocates nothing. +fn validate_in_header(h: &[u8; IN_HEADER], file_len: u64) -> Result { + if le32(h, 0) != IN_MAGIC { + return Err(format!("wrong magic 0x{:08x}, expected 0x{IN_MAGIC:08x}", le32(h, 0))); + } + if le32(h, 4) != 1 { + return Err(format!("unsupported version {}, expected 1", le32(h, 4))); + } + let (gu, down) = (le32(h, 8) as i32, le32(h, 12) as i32); + let Some(&(_, _, gq, gb, _)) = gate_up_row(gu) else { + return Err(format!("gate/up type {gu} is not in the KAB1 list")); + }; + let Some(&(_, _, dq, db, _)) = down_row(down) else { + return Err(format!("down type {down} is not in the KAB1 list")); + }; + let rows = le32(h, 16) as usize; + if !(1..=MAX_ROWS).contains(&rows) { + return Err(format!("rows {rows} outside 1..={MAX_ROWS}")); + } + if le32(h, 20) as usize != H || le32(h, 24) as usize != FF { + return Err(format!("n_embd {} / n_ff {} differ from {H} / {FF}", le32(h, 20), le32(h, 24))); + } + let gsize = (H / gq * gb * FF) as u64; + let dsize = (FF / dq * db * H) as u64; + let (g, u, d) = (le32(h, 28) as u64, le32(h, 32) as u64, le32(h, 36) as u64); + if g != gsize || u != gsize || d != dsize { + return Err(format!( + "byte counts gate/up/down {g}/{u}/{d} differ from the format-derived {gsize}/{gsize}/{dsize}" + )); + } + if h[40..].iter().any(|b| *b != 0) { + return Err("header padding is not zero".to_owned()); + } + let total = IN_HEADER as u64 + g + u + d + (rows * H * 4) as u64; + if total != file_len { + return Err(format!("file length {file_len} differs from the header-derived {total}")); + } + Ok(InHeader { gu, down, rows, gate: g as usize, up: u as usize, down_bytes: d as usize }) +} + +/// Pure: 20 bytes and the file length. +fn validate_out_header(h: &[u8; OUT_HEADER], file_len: u64, rows: usize, tree: &str) -> Result<(), String> { + if le32(h, 0) != OUT_MAGIC { + return Err(format!("wrong magic 0x{:08x}, expected 0x{OUT_MAGIC:08x}", le32(h, 0))); + } + if le32(h, 4) != 1 { + return Err(format!("unsupported version {}, expected 1", le32(h, 4))); + } + if le32(h, 8) as usize != rows || le32(h, 12) as usize != H { + return Err(format!("rows {} / n_embd {} differ from the case ({rows} / {H})", le32(h, 8), le32(h, 12))); + } + let tree_id = TREES.iter().position(|t| *t == tree).map_or(u32::MAX, |i| i as u32); + if le32(h, 16) != tree_id { + return Err(format!("tree id {} differs from the file name's tree {tree} ({tree_id})", le32(h, 16))); + } + let total = (OUT_HEADER + rows * H * 4) as u64; + if total != file_len { + return Err(format!("file length {file_len} differs from the header-derived {total}")); + } + Ok(()) +} + +fn fp16_finite(bytes: &[u8], block: usize) -> Option { + (0..bytes.len()).step_by(block).find(|&at| u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00) +} + +// ------------------------------------------------------------------------------------------------ manifest + +#[derive(Debug, Clone, PartialEq)] +struct Tolerance { + value: f64, + basis: String, + basis_written_utc: String, +} + +#[derive(Debug, Clone)] +struct OutRef { + tree: &'static str, + name: String, + sha256: String, + bytes: u64, +} + +#[derive(Debug, Clone)] +struct CaseEntry { + id: String, + gu: i32, + down: i32, + rows: usize, + in_name: String, + in_sha256: String, + in_bytes: u64, + outs: Vec, + tolerance: Option, +} + +#[derive(Debug, Clone)] +struct Provenance { + run_id: String, + engine_strata_pin: String, + compiler_id: String, + compiler_version: String, + target_triple: String, + reference_flags: String, + avx512_ok: Option, +} + +#[derive(Debug)] +struct Verified { + dir: PathBuf, + manifest_sha256: String, + provenance: Provenance, + cases: Vec, + file_count: usize, +} + +type FileTable = Vec<(String, String, u64)>; + +fn parse_manifest(m: &Json) -> Result<(Provenance, Vec, FileTable), String> { + if m.str("format")? != "KAB1" || m.uint("version")? != 1 { + return Err("format is not KAB1 version 1".to_owned()); + } + let p = m.req("provenance")?; + let flags = p.req("flags")?; + let commit = p.str("engine_strata_pin")?; + if !is_hex(commit, 7, 40) { + return Err("provenance.engine_strata_pin is not a commit hash".to_owned()); + } + let built = p.str("built_at_utc")?; + if !is_utc(built) { + return Err("provenance.built_at_utc is not a UTC timestamp".to_owned()); + } + let avx512_ok = match p.get("avx512_ok") { + Some(Json::Bool(b)) => Some(*b), + _ => None, + }; + let provenance = Provenance { + run_id: m.str("run_id")?.to_owned(), + engine_strata_pin: commit.to_owned(), + compiler_id: p.str("compiler_id")?.to_owned(), + compiler_version: p.str("compiler_version")?.to_owned(), + target_triple: p.str("target_triple")?.to_owned(), + reference_flags: format!( + "strata_cxx_flags: {}; ggml_cpu_arch_flags: {}", + flags.str("strata_cxx_flags")?, + flags.str("ggml_cpu_arch_flags")? + ), + avx512_ok, + }; + let Json::Arr(cases_json) = m.req("cases")? else { return Err("cases is not an array".to_owned()) }; + if cases_json.is_empty() || cases_json.len() > MAX_CASES { + return Err(format!("{} cases (1..={MAX_CASES} allowed)", cases_json.len())); + } + let mut cases = Vec::new(); + for c in cases_json { + let id = c.str("id")?.to_owned(); + if !valid_id(&id) { + return Err(format!("case id {id:?} is not a plain identifier")); + } + let rows = c.uint("rows")? as usize; + let in_name = format!("case-{id}.in"); + if c.str("in")? != in_name { + return Err(format!("case {id}: file name {:?} is not {in_name}", c.str("in")?)); + } + let mut outs = Vec::new(); + for tree in TREES { + let key = format!("out_cpp_{tree}"); + let name = format!("case-{id}.cpp-{tree}.out"); + if c.str(&key)? != name { + return Err(format!("case {id}: file name {:?} is not {name}", c.str(&key)?)); + } + outs.push(OutRef { + tree, + name, + sha256: c.str(&format!("{key}_sha256"))?.to_owned(), + bytes: c.uint(&format!("{key}_bytes"))?, + }); + } + let tolerance = match (c.str("equality")?, c.req("tolerance")?) { + ("bitwise", Json::Null) => None, + ("tolerance", t @ Json::Obj(_)) => { + if t.str("metric")? != TOLERANCE_METRIC { + return Err(format!( + "case {id}: tolerance metric {:?} is not {TOLERANCE_METRIC}", + t.str("metric")? + )); + } + let value = match t.req("value")? { + Json::Num(n) => n.parse::().ok().filter(|v| v.is_finite() && *v > 0.0), + _ => None, + } + .ok_or_else(|| format!("case {id}: tolerance.value is not a positive number"))?; + let basis = t.str("basis")?.to_owned(); + let written = t.str("basis_written_utc")?.to_owned(); + if basis.trim().is_empty() || !is_utc(&written) { + return Err(format!("case {id}: tolerance needs a non-empty basis and a UTC basis_written_utc")); + } + if written.as_str() > built { + return Err(format!( + "case {id}: the tolerance basis was written {written}, after the reference run {built}" + )); + } + Some(Tolerance { value, basis, basis_written_utc: written }) + } + (other, _) => { + return Err(format!( + "case {id}: equality {other:?} and tolerance disagree (bitwise needs null, tolerance an object)" + )); + } + }; + let in_sha256 = c.str("in_sha256")?.to_owned(); + let gu = c.uint("gu_type")? as i32; + let down = c.uint("down_type")? as i32; + cases.push(CaseEntry { + id, + gu, + down, + rows, + in_name, + in_sha256, + in_bytes: c.uint("in_bytes")?, + outs, + tolerance, + }); + } + let Json::Obj(files_json) = m.req("files")? else { return Err("files is not an object".to_owned()) }; + let mut files = Vec::new(); + for (name, v) in files_json { + let sha = v.str("sha256")?; + if !is_hex(sha, 64, 64) { + return Err(format!("files.{name}.sha256 is not a sha256")); + } + files.push((name.clone(), sha.to_owned(), v.uint("bytes")?)); + } + let mut seen = BTreeSet::new(); + for c in &cases { + if !seen.insert(c.id.clone()) { + return Err(format!("case id {} appears twice", c.id)); + } + for sha in std::iter::once(&c.in_sha256).chain(c.outs.iter().map(|o| &o.sha256)) { + if !is_hex(sha, 64, 64) { + return Err(format!("case {}: a sha256 is not 64 lowercase hex digits", c.id)); + } + } + } + Ok((provenance, cases, files)) +} + +fn case_files(c: &CaseEntry) -> Vec<(&str, &str, u64)> { + let mut v = vec![(c.in_name.as_str(), c.in_sha256.as_str(), c.in_bytes)]; + v.extend(c.outs.iter().map(|o| (o.name.as_str(), o.sha256.as_str(), o.bytes))); + v +} + +// ------------------------------------------------------------------------------------------------ file readers + +#[derive(Debug)] +struct CaseIn { + header: InHeader, + blob: Vec, +} +impl CaseIn { + fn gate(&self) -> &[u8] { + &self.blob[IN_HEADER..IN_HEADER + self.header.gate] + } + fn up(&self) -> &[u8] { + let s = IN_HEADER + self.header.gate; + &self.blob[s..s + self.header.up] + } + fn down(&self) -> &[u8] { + let s = IN_HEADER + self.header.gate + self.header.up; + &self.blob[s..s + self.header.down_bytes] + } + fn input(&self) -> Vec { + words_le(&self.blob[self.header.input_at()..]).into_iter().map(f32::from_bits).collect() + } +} + +/// Reads one case input: length against the manifest and the limit, header decision, THEN the buffer, then sha256, FP16 headers and +/// finite activations. Any failure names the file. +fn read_case_in(dir: &Path, c: &CaseEntry) -> Result { + let name = c.in_name.as_str(); + let r = |reason: String| Refusal::new(name, reason); + let mut f = File::open(dir.join(name)).map_err(|e| r(format!("cannot open: {e}")))?; + let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); + if len != c.in_bytes { + return Err(r(format!("length {len} differs from the manifest's {}", c.in_bytes))); + } + if len > MAX_FILE_BYTES || len < IN_HEADER as u64 { + return Err(r(format!("length {len} outside {IN_HEADER}..={MAX_FILE_BYTES}"))); + } + let mut hdr = [0u8; IN_HEADER]; + f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?; + let header = validate_in_header(&hdr, len).map_err(r)?; + if header.gu != c.gu || header.down != c.down || header.rows != c.rows { + return Err(r("the header's types / rows differ from the manifest case".to_owned())); + } + let mut blob = take_buffer(len as usize).map_err(r)?; + blob[..IN_HEADER].copy_from_slice(&hdr); + f.read_exact(&mut blob[IN_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?; + if sha_hex(&blob) != c.in_sha256 { + return Err(r("sha256 differs from the manifest".to_owned())); + } + let case = CaseIn { header, blob }; + let (gb, db) = (gate_up_row(header.gu).map_or(1, |x| x.3), down_row(header.down).map_or(1, |x| x.3)); + for (role, bytes, block) in [("gate", case.gate(), gb), ("up", case.up(), gb), ("down", case.down(), db)] { + if let Some(at) = fp16_finite(bytes, block) { + return Err(r(format!("non-finite FP16 block header in {role} at byte {at}"))); + } + } + if words_le(&case.blob[header.input_at()..]).into_iter().any(|w| !f32::from_bits(w).is_finite()) { + return Err(r("non-finite activation".to_owned())); + } + Ok(case) +} + +/// Reads an `.out` file as f32 bit patterns. `expect` is the manifest's (sha256, bytes) for a C++ file; ours has none. +fn read_out( + path: &Path, + name: &str, + rows: usize, + tree: &str, + expect: Option<(&str, u64)>, +) -> Result, Refusal> { + let r = |reason: String| Refusal::new(name, reason); + let mut f = File::open(path).map_err(|e| r(format!("cannot open: {e}")))?; + let len = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); + if let Some((_, bytes)) = expect + && len != bytes + { + return Err(r(format!("length {len} differs from the manifest's {bytes}"))); + } + if len > MAX_FILE_BYTES || len < OUT_HEADER as u64 { + return Err(r(format!("length {len} outside {OUT_HEADER}..={MAX_FILE_BYTES}"))); + } + let mut hdr = [0u8; OUT_HEADER]; + f.read_exact(&mut hdr).map_err(|e| r(format!("cannot read the header: {e}")))?; + validate_out_header(&hdr, len, rows, tree).map_err(r)?; + let mut blob = take_buffer(len as usize).map_err(r)?; + blob[..OUT_HEADER].copy_from_slice(&hdr); + f.read_exact(&mut blob[OUT_HEADER..]).map_err(|e| r(format!("cannot read the body: {e}")))?; + if let Some((sha, _)) = expect + && sha_hex(&blob) != sha + { + return Err(r("sha256 differs from the manifest".to_owned())); + } + let bits = words_le(&blob[OUT_HEADER..]); + if bits.iter().any(|b| !f32::from_bits(*b).is_finite()) { + return Err(r("non-finite value".to_owned())); + } + Ok(bits) +} + +/// Reads and parses `manifest.json` (size cap first). Returns its bytes (the caller hashes them), the provenance, the cases and the flat +/// files table. A missing manifest is the `incomplete` refusal. +fn read_manifest(dir: &Path) -> Result<(Vec, Provenance, Vec, FileTable), Refusal> { + let mpath = dir.join("manifest.json"); + let mname = "manifest.json"; + if !mpath.is_file() { + let mut r = Refusal::new(mname, "no manifest.json (the writer publishes it last)"); + r.incomplete = true; + return Err(r); + } + let r = |reason: String| Refusal::new(mname, reason); + let mut f = File::open(&mpath).map_err(|e| r(format!("cannot open: {e}")))?; + let mlen = f.metadata().map_err(|e| r(format!("cannot stat: {e}")))?.len(); + if mlen > MAX_MANIFEST_BYTES { + return Err(r(format!("length {mlen} above the limit {MAX_MANIFEST_BYTES}"))); + } + let mut mbytes = take_buffer(mlen as usize).map_err(r)?; + f.read_exact(&mut mbytes).map_err(|e| r(format!("cannot read: {e}")))?; + let manifest = parse_json(&mbytes).map_err(r)?; + let (provenance, cases, files) = parse_manifest(&manifest).map_err(r)?; + Ok((mbytes, provenance, cases, files)) +} + +/// The reader rule. Everything in the directory is checked before anything is used; any problem refuses the whole directory. +fn verify_dir(dir: &Path) -> Result { + let mname = "manifest.json"; + let r = |reason: String| Refusal::new(mname, reason); + let (mbytes, provenance, cases, files) = read_manifest(dir)?; + // the flat files table and the case entries must describe exactly the same files + let mut expected: Vec<(&str, &str, u64)> = cases.iter().flat_map(case_files).collect(); + expected.sort_unstable(); + let mut table: Vec<(&str, &str, u64)> = files.iter().map(|(n, s, b)| (n.as_str(), s.as_str(), *b)).collect(); + table.sort_unstable(); + if expected != table { + return Err(r("the flat files table and the case entries disagree".to_owned())); + } + let names: BTreeSet<&str> = expected.iter().map(|e| e.0).collect(); + let listing = fs::read_dir(dir).map_err(|e| r(format!("cannot list the directory: {e}")))?; + for entry in listing { + let entry = entry.map_err(|e| r(format!("cannot list the directory: {e}")))?; + let n = entry.file_name().to_string_lossy().into_owned(); + if n != mname && !names.contains(n.as_str()) { + return Err(Refusal::new(&n, "file is not in the manifest")); + } + } + let file_count = names.len() + 1; + for c in &cases { + read_case_in(dir, c)?; + for o in &c.outs { + read_out(&dir.join(&o.name), &o.name, c.rows, o.tree, Some((&o.sha256, o.bytes)))?; + } + } + Ok(Verified { dir: dir.to_owned(), manifest_sha256: sha_hex(&mbytes), provenance, cases, file_count }) +} + +// ------------------------------------------------------------------------------------------------ compare + +#[derive(Debug, PartialEq)] +struct Outcome { + compared: usize, + mismatches: usize, + differing_bits: usize, + max_abs_error: f64, + first_mismatch: Option<(usize, u32, u32)>, +} +impl Outcome { + fn equal(&self) -> bool { + self.mismatches == 0 + } +} + +/// Bitwise on the f32 bit patterns (so -0 and +0 differ) when `tol` is None; otherwise `|ours - ref| <= value * max|ref|` per value +/// (the one metric the reader knows, `TOLERANCE_METRIC`). +fn compare_bits(ours: &[u32], reference: &[u32], tol: Option<&Tolerance>) -> Outcome { + let scale = reference.iter().map(|b| f64::from(f32::from_bits(*b)).abs()).fold(0.0, f64::max); + let mut o = Outcome { + compared: reference.len(), + mismatches: 0, + differing_bits: 0, + max_abs_error: 0.0, + first_mismatch: None, + }; + for (i, (a, b)) in ours.iter().zip(reference).enumerate() { + let err = (f64::from(f32::from_bits(*a)) - f64::from(f32::from_bits(*b))).abs(); + if a != b { + o.differing_bits += 1; + } + if err.is_finite() { + o.max_abs_error = o.max_abs_error.max(err); + } + let bad = match tol { + None => a != b, + Some(t) => err.partial_cmp(&(t.value * scale)).is_none_or(|o| o == std::cmp::Ordering::Greater), + }; + if bad { + o.mismatches += 1; + o.first_mismatch.get_or_insert((i, *a, *b)); + } + } + if ours.len() != reference.len() { + o.mismatches += ours.len().abs_diff(reference.len()); + } + o +} + +// ------------------------------------------------------------------------------------------------ record (hand-written JSON) + +fn jstr(s: &str) -> String { + let mut o = String::with_capacity(s.len() + 2); + o.push('"'); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + '\n' => o.push_str("\\n"), + '\r' => o.push_str("\\r"), + '\t' => o.push_str("\\t"), + c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), + c => o.push(c), + } + } + o.push('"'); + o +} + +struct RecordInput<'a> { + record_id: String, + created_utc: String, + run_started_utc: String, + machine_role: String, + cpu_model: String, + os: String, + ours_compiler: String, + ours_version: String, + ours_triple: String, + ours_flags: String, + tree: &'a str, + verified: &'a Verified, + case: &'a CaseEntry, + pin_cpu: usize, + sibling_idle: bool, + outcome: &'a Outcome, +} + +fn record_json(r: &RecordInput) -> String { + let p = &r.verified.provenance; + let c = r.case; + let mode = if c.tolerance.is_some() { "tolerance" } else { "bitwise" }; + let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { + format!( + ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", + t.value, + jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), + jstr(&t.basis_written_utc) + ) + }); + let tiny = format!("{:e}", f64::from_bits(1)); + let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)); + format!( + "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {{\"compiler\": {oc}, \"version\": {ov}, \"target_triple\": {ot}, \"flags\": {of}}},\n \"reference\": {{\"compiler\": {rc}, \"version\": {rv}, \"target_triple\": {rt}, \"flags\": {rf}}}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree}, \"reference\": {tree}}},\n \"regime\": \"resident\",\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {nm}, \"ghz_before\": {tiny}, \"ghz_after\": {tiny}, \"max_drift_fraction\": 0, \"slices_total\": 1, \"slices_dropped\": 0}},\n \"rows\": [\n {{\"row_type\": {rowtype}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}, \"reference\": {{\"median\": {tiny}, \"p05\": {tiny}, \"p95\": {tiny}}}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {{\n \"mode\": \"{mode}\",\n \"verdict\": \"{verdict}\",\n \"compared_values\": {compared},\n \"mismatches\": {mism}{tolerance}\n }}\n}}\n", + rid = jstr(&r.record_id), + created = jstr(&r.created_utc), + started = jstr(&r.run_started_utc), + role = jstr(&r.machine_role), + cpu = jstr(&r.cpu_model), + os = jstr(&r.os), + kernel = jstr(&format!( + "routed-expert-gate-up-down {gu}+{down} rows={} (equality only; timing {NOT_MEASURED})", + c.rows + )), + oc = jstr(&r.ours_compiler), + ov = jstr(&r.ours_version), + ot = jstr(&r.ours_triple), + of = jstr(&r.ours_flags), + rc = jstr(&p.compiler_id), + rv = jstr(&p.compiler_version), + rt = jstr(&p.target_triple), + rf = jstr(&p.reference_flags), + cid = jstr(&c.id), + insha = jstr(&c.in_sha256), + msha = jstr(&r.verified.manifest_sha256), + tree = jstr(r.tree), + pin = r.pin_cpu, + sib = r.sibling_idle, + commit = jstr(&p.engine_strata_pin), + nm = jstr(NOT_MEASURED), + rowtype = jstr(&format!("{gu}+{down} r{} {NOT_MEASURED}", c.rows)), + verdict = if r.outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, + compared = r.outcome.compared, + mism = r.outcome.mismatches, + ) +} + +// ------------------------------------------------------------------------------------------------ run-tree (one fresh process) + +fn write_out(path: &Path, rows: usize, tree: &str, values: &[f32]) -> Result<(), String> { + let tree_id = TREES.iter().position(|t| *t == tree).ok_or("unknown tree")? as u32; + let mut b = Vec::with_capacity(OUT_HEADER + values.len() * 4); + for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree_id] { + b.extend_from_slice(&w.to_le_bytes()); + } + for v in values { + b.extend_from_slice(&v.to_bits().to_le_bytes()); + } + File::create(path).and_then(|mut f| f.write_all(&b)).map_err(|e| format!("{}: {e}", path.display())) +} + +/// Our kernels on one verified case through the public API: PreparedJob only for the input validation it performs, then one +/// `compute_group` over borrowed bytes (one expert, `rows` tokens, pairs `(t, 0)`, stride 1). +fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result, String> { + let (gu, down) = + (gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1); + let input = case.input(); + PreparedJob::new( + gu, + down, + case.gate().into(), + case.up().into(), + case.down().into(), + input.clone().into(), + case.header.rows, + ) + .map_err(|e| format!("PreparedJob refused the input: {e:?}"))?; + let pairs: Vec<(usize, usize)> = (0..case.header.rows).map(|t| (t, 0)).collect(); + let expert = BorrowedExpert { gate: case.gate(), up: case.up(), down: case.down(), pairs: &pairs }; + let experts = [expert]; + let group = BorrowedGroup { tokens: &input, experts: &experts, stride: 1 }; + let mut out = vec![0.0f32; case.header.rows * H]; + pool.compute_group(gu, down, &group, &mut out).map_err(|e| format!("compute_group failed: {e:?}"))?; + Ok(out) +} + +fn family_of(report: &[String]) -> Option<&'static str> { + report + .iter() + .find(|l| l.starts_with("cpu: process kernel family ")) + .map(|l| if l.starts_with("cpu: process kernel family AVX-512") { "avx512" } else { "avx2" }) +} + +fn cmd_run_tree(dir: &Path, tree: &str, out: &Path, pin: usize, only_case: Option<&str>) -> Result { + let verified = verify_dir(dir).map_err(|e| e.to_string())?; + let previous = rust_topology::pin_current_thread(pin as i32); + if previous < 0 { + eprintln!("kernel_ab: the pin to CPU {pin} was refused; running unpinned"); + } + let report = cpu_kernel_report(); + for line in &report { + println!("REPORT {line}"); + } + let family = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; + if family != tree { + eprintln!("kernel_ab: this process runs the {family} family, not {tree}"); + return Ok(ExitCode::from(3)); + } + fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; + let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; + let mut done = 0usize; + for c in verified.cases.iter().filter(|c| only_case.is_none_or(|id| c.id == id)) { + let case = read_case_in(&verified.dir, c).map_err(|e| e.to_string())?; + let values = compute_case(&mut pool, &case).map_err(|e| format!("case {}: {e}", c.id))?; + write_out(&out.join(format!("case-{}.rust-{tree}.out", c.id)), c.rows, tree, &values)?; + done += 1; + } + if done == 0 { + return Err(format!("case {} is not in the manifest", only_case.unwrap_or("?"))); + } + println!("RUN-TREE {tree} cases={done}"); + Ok(ExitCode::SUCCESS) +} + +// ------------------------------------------------------------------------------------------------ compare driver + +/// Linux: is the SMT sibling of `cpu` idle (below 5 percent busy over 200 ms)? No sibling counts as idle. Elsewhere: false (unknown). +fn sibling_idle(cpu: usize) -> bool { + if !cfg!(target_os = "linux") { + return false; + } + let Ok(list) = fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list")) else { + return false; + }; + let mut siblings = Vec::new(); + for part in list.trim().split(',') { + let (a, b) = part.split_once('-').unwrap_or((part, part)); + let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) else { return false }; + siblings.extend((a..=b).filter(|s| *s != cpu)); + } + if siblings.is_empty() { + return true; + } + let sample = |cpu: usize| -> Option<(u64, u64)> { + let stat = fs::read_to_string("/proc/stat").ok()?; + let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?; + let f: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); + let idle = f.get(3)? + f.get(4).copied().unwrap_or(0); + Some((f.iter().sum(), idle)) + }; + let before: Vec<_> = siblings.iter().map(|s| sample(*s)).collect(); + std::thread::sleep(std::time::Duration::from_millis(200)); + siblings.iter().zip(before).all(|(s, b)| match (b, sample(*s)) { + (Some(b), Some(a)) => { + let total = a.0.saturating_sub(b.0); + let idle = a.1.saturating_sub(b.1); + total > 0 && (total - idle.min(total)) * 20 < total + } + _ => false, + }) +} + +fn rustc_info() -> (String, String) { + // $RUSTC, then `rustc` on the PATH, then the rustup shim of the user (a non-login shell has no cargo bin directory on its PATH) + let home = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")).unwrap_or_default(); + let shim = format!("{home}/.cargo/bin/{}", if cfg!(windows) { "rustc.exe" } else { "rustc" }); + let candidates = [std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned()), "rustc".to_owned(), shim]; + let triple = if cfg!(windows) { "x86_64-pc-windows-msvc" } else { "x86_64-unknown-linux-gnu" }; + let version = candidates + .iter() + .find_map(|rustc| { + Command::new(rustc) + .arg("--version") + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + }) + .map_or_else(|| "unknown (rustc not runnable at record time)".to_owned(), |s| s.trim().to_owned()); + (version, triple.to_owned()) +} + +fn host_os() -> String { + if cfg!(target_os = "linux") + && let Ok(text) = fs::read_to_string("/etc/os-release") + && let Some(l) = text.lines().find(|l| l.starts_with("PRETTY_NAME=")) + { + return l["PRETTY_NAME=".len()..].trim_matches('"').to_owned(); + } + std::env::consts::OS.to_owned() +} + +fn cpu_model_of(report: &[String]) -> String { + report + .iter() + .find(|l| l.starts_with("cpu: logical ")) + .and_then(|l| l.split_once("): ").map(|x| x.1)) + .and_then(|rest| rest.split(';').next()) + .map_or_else(|| "unknown model".to_owned(), |s| s.trim().to_owned()) +} + +struct Options { + out: Option, + pin: usize, + machine_role: Option, + trees: Vec, + tree: Option, + case: Option, +} + +fn parse_options(args: &[String]) -> Result { + let mut o = Options { + out: None, + pin: 0, + machine_role: None, + trees: TREES.iter().map(|t| (*t).to_owned()).collect(), + tree: None, + case: None, + }; + let mut it = args.iter(); + while let Some(a) = it.next() { + let mut value = |what: &str| it.next().cloned().ok_or_else(|| format!("{what} needs a value")); + match a.as_str() { + "--out" => o.out = Some(PathBuf::from(value("--out")?)), + "--pin" => o.pin = value("--pin")?.parse().map_err(|_| "--pin takes a logical CPU number".to_owned())?, + "--machine-role" => o.machine_role = Some(value("--machine-role")?), + "--trees" => o.trees = value("--trees")?.split(',').map(str::to_owned).collect(), + "--tree" => o.tree = Some(value("--tree")?), + "--case" => o.case = Some(value("--case")?), + other => return Err(format!("unknown option {other}")), + } + } + if let Some(bad) = o.trees.iter().find(|t| !TREES.contains(&t.as_str())) { + return Err(format!("unknown tree {bad} (avx512 | avx2)")); + } + Ok(o) +} + +fn cmd_compare(dir: &Path, opts: &Options) -> Result { + let started = now_utc(); + let verified = match verify_dir(dir) { + Ok(v) => v, + Err(e) => { + println!("{e}"); + return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); + } + }; + println!( + "KAB1 directory verified: {} files, {} cases, manifest sha256 {}", + verified.file_count, + verified.cases.len(), + verified.manifest_sha256 + ); + let out = opts.out.clone().unwrap_or_else(|| { + let name = dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); + dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.rust")) + }); + if out.starts_with(dir) || dir.starts_with(&out) { + return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); + } + if out.exists() && fs::read_dir(&out).map_err(|e| format!("{}: {e}", out.display()))?.next().is_some() { + return Err(format!("{} exists and is not empty (nothing is overwritten or deleted)", out.display())); + } + let records = out.join("records"); + fs::create_dir_all(&records).map_err(|e| format!("{}: {e}", records.display()))?; + let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); + let machine_role = opts + .machine_role + .clone() + .or_else(|| std::env::var("HOSTNAME").ok()) + .or_else(|| std::env::var("COMPUTERNAME").ok()) + .unwrap_or_else(|| "unknown".to_owned()); + let (rustc_version, triple) = rustc_info(); + let flags = format!( + "cargo profile {}; RUSTFLAGS={:?}; target-cpu default", + if cfg!(debug_assertions) { "dev" } else { "release" }, + std::env::var("RUSTFLAGS").unwrap_or_default() + ); + let mut all_equal = true; + let mut cells = 0usize; + for tree in &opts.trees { + let sibling = sibling_idle(opts.pin); + let probe = Proc { + imp: Impl::Rust, + tree: TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"), + rep: 'a', + }; + let mut cmd = scrubbed_command(&exe, &parent_env, &cell_env(&probe)); + cmd.arg("run-tree").arg(dir).args(["--tree", tree, "--out"]).arg(&out).args(["--pin", &opts.pin.to_string()]); + let res = cmd.output().map_err(|e| format!("cannot start the {tree} process: {e}"))?; + let stdout = String::from_utf8_lossy(&res.stdout).into_owned(); + let report: Vec = stdout.lines().filter_map(|l| l.strip_prefix("REPORT ")).map(str::to_owned).collect(); + match res.status.code() { + Some(0) => {} + Some(3) if tree == "avx512" && verified.provenance.avx512_ok == Some(false) => { + println!( + "tree avx512: SKIPPED, this host has no AVX-512 (manifest avx512_ok=false; the reference trees are identical by construction)" + ); + continue; + } + code => { + eprint!("{}", String::from_utf8_lossy(&res.stderr)); + println!("tree {tree}: the Rust process failed (exit {code:?})"); + return Ok(ExitCode::from(1)); + } + } + println!( + "tree {tree}: {}", + report.iter().find(|l| l.starts_with("cpu: process kernel family")).map_or("", String::as_str) + ); + let tree_name: &str = TREES.iter().find(|t| **t == tree.as_str()).copied().unwrap_or("avx2"); + for c in &verified.cases { + let ours_name = format!("case-{}.rust-{tree}.out", c.id); + let ours = read_out(&out.join(&ours_name), &ours_name, c.rows, tree, None).map_err(|e| e.to_string())?; + let o = c.outs.iter().find(|o| o.tree == tree_name).ok_or("missing reference out")?; + let reference = read_out(&verified.dir.join(&o.name), &o.name, c.rows, tree, Some((&o.sha256, o.bytes))) + .map_err(|e| e.to_string())?; + let outcome = compare_bits(&ours, &reference, c.tolerance.as_ref()); + let label = match (&c.tolerance, outcome.equal()) { + (None, true) => "bitwise EQUAL".to_owned(), + (None, false) => "bitwise NOT EQUAL".to_owned(), + (Some(t), eq) => format!( + "{} within tolerance {:e} (metric {TOLERANCE_METRIC}; basis: {})", + if eq { "EQUAL" } else { "NOT EQUAL" }, + t.value, + t.basis + ), + }; + let detail = match outcome.first_mismatch { + Some((i, a, b)) => format!( + "; {} of {} values differ, first at {i}: ours {a:#010x} reference {b:#010x}, max abs error {:e}", + outcome.mismatches, outcome.compared, outcome.max_abs_error + ), + None => format!("; {} values", outcome.compared), + }; + println!("case {} [{tree}] {label}{detail}", c.id); + all_equal &= outcome.equal(); + cells += 1; + let record = record_json(&RecordInput { + record_id: format!( + "kab1-{}-{}-{tree}-{}", + verified.provenance.run_id, + c.id, + started.replace([':', '-'], "") + ), + created_utc: now_utc(), + run_started_utc: started.clone(), + machine_role: machine_role.clone(), + cpu_model: cpu_model_of(&report), + os: host_os(), + ours_compiler: "rustc".to_owned(), + ours_version: rustc_version.clone(), + ours_triple: triple.clone(), + ours_flags: flags.clone(), + tree: tree_name, + verified: &verified, + case: c, + pin_cpu: opts.pin, + sibling_idle: sibling, + outcome: &outcome, + }); + let path = records.join(format!("case-{}.{tree}.record.json", c.id)); + fs::write(&path, record).map_err(|e| format!("{}: {e}", path.display()))?; + } + } + println!( + "compared {cells} cells; records in {}; {}", + records.display(), + if all_equal { "ALL EQUAL" } else { "NOT ALL EQUAL" } + ); + Ok(if all_equal && cells > 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }) +} + +// ------------------------------------------------------------------------------------------------ flags (time, alternate) + +struct Flags(Vec<(String, String)>); + +impl Flags { + fn parse(args: &[String], known: &[&str]) -> Result { + let mut items: Vec<(String, String)> = Vec::new(); + let mut it = args.iter(); + while let Some(a) = it.next() { + let name = a.strip_prefix("--").ok_or_else(|| format!("unexpected argument {a}"))?; + if !known.contains(&name) { + return Err(format!("unknown option {a}")); + } + if items.iter().any(|(k, _)| k == name) { + return Err(format!("option {a} given twice")); + } + let v = it.next().ok_or_else(|| format!("{a} needs a value"))?; + items.push((name.to_owned(), v.clone())); + } + Ok(Self(items)) + } + fn get(&self, k: &str) -> Option<&str> { + self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) + } + fn req(&self, k: &str) -> Result<&str, String> { + self.get(k).ok_or_else(|| format!("--{k} is required")) + } + fn number(&self, k: &str) -> Result, String> { + self.get(k).map(|v| v.parse::().map_err(|_| format!("--{k} {v:?} is not a valid number"))).transpose() + } +} + +// ------------------------------------------------------------------------------------------------ clocks and host facts + +/// The 60 ms slice of `tq_cpu_parity.cpp:461` (`slice_ms = quick ? 40 : 60`), the same value `kab time` uses. +const DEFAULT_SLICE_MS: f64 = 60.0; +/// `tq_cpu_parity.cpp:303`: a slice whose calibrated clock moved by more than this fraction is dropped. Copied, not chosen here. +const CLOCK_MOVED_FRACTION: f64 = 0.05; +/// An SMT sibling busier than this fraction is not idle (the 5 percent rule of `sibling_idle`). +const SIBLING_BUSY_LIMIT: f64 = 0.05; +const ALIGN: usize = 4096; +/// Cycles of one step of the calibration chain `x = (x * k) ^ (x >> 17)`: a 64-bit multiply (3 cycles on Intel Skylake to Golden Cove +/// and AMD Zen 1 to 5) then an xor (1 cycle); the shift runs beside the multiply. +const CHAIN_STEP_CYCLES: f64 = 4.0; +const CLOCK_METHOD: &str = "chain of dependent steps x = (x * k) ^ (x >> 17), 4 cycles per step (3 multiply + 1 xor), 1000000 iterations of 4 steps, ghz = 4 * 4e6 / (elapsed ns); before and after every slice"; + +fn mono_ns() -> u64 { + static ORIGIN: OnceLock = OnceLock::new(); + ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() as u64 +} + +/// The core clock in GHz from a chain of dependent steps (safe code: the C++ chain of dependent adds needs inline assembly). A plain +/// chain of multiplies by an opaque constant is folded by LLVM (measured: 175 GHz), so every step also xors in a shifted copy of the +/// running value, which no reassociation can remove. +fn core_ghz() -> f64 { + let k = std::hint::black_box(0x9E37_79B9_7F4A_7C15u64 | 1); + let mut x = std::hint::black_box(1u64); + let n = 1_000_000u64; + let t0 = mono_ns(); + for _ in 0..n { + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + x = x.wrapping_mul(k) ^ (x >> 17); + } + let dt = mono_ns().saturating_sub(t0).max(1); + std::hint::black_box(x); + CHAIN_STEP_CYCLES * 4.0 * n as f64 / dt as f64 +} + +fn median_of(v: &[f64]) -> f64 { + if v.is_empty() { + return 0.0; + } + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + s[s.len() / 2] +} + +/// Nearest-rank percentile of raw slice values (a description of the slices, not an inference). +fn percentile_of(v: &[f64], p: f64) -> f64 { + if v.is_empty() { + return 0.0; + } + let mut s = v.to_vec(); + s.sort_by(f64::total_cmp); + s[((s.len() - 1) as f64 * p).round() as usize] +} + +fn jnum(v: f64, decimals: usize) -> String { + if v.is_finite() { format!("{v:.decimals$}") } else { "null".to_owned() } +} + +fn read_text(path: &str) -> String { + fs::read_to_string(path).map(|s| s.trim().to_owned()).unwrap_or_default() +} + +fn parse_cpu_list(s: &str) -> Vec { + let mut v = Vec::new(); + for part in s.trim().split(',').filter(|p| !p.is_empty()) { + let (a, b) = part.split_once('-').unwrap_or((part, part)); + if let (Ok(a), Ok(b)) = (a.trim().parse::(), b.trim().parse::()) { + v.extend(a..=b); + } + } + v +} + +fn parse_size(s: &str) -> u64 { + let digits: String = s.chars().take_while(char::is_ascii_digit).collect(); + let n = digits.parse::().unwrap_or(0); + match s[digits.len()..].chars().next() { + Some('K' | 'k') => n << 10, + Some('M' | 'm') => n << 20, + Some('G' | 'g') => n << 30, + _ => n, + } +} + +struct Llc { + level: u32, + bytes: u64, + source: String, +} + +/// Linux: the highest-level data or unified cache of `cpu` from sysfs. Elsewhere: None (the caller passes `--llc-bytes`). +fn llc_of_cpu(cpu: usize) -> Option { + let mut best: Option = None; + for i in 0..16 { + let d = format!("/sys/devices/system/cpu/cpu{cpu}/cache/index{i}"); + let (level, kind, size) = + (read_text(&format!("{d}/level")), read_text(&format!("{d}/type")), read_text(&format!("{d}/size"))); + if level.is_empty() || size.is_empty() || kind == "Instruction" { + continue; + } + let level_n = level.parse::().unwrap_or(0); + if best.as_ref().is_none_or(|b| level_n >= b.level) { + best = Some(Llc { level: level_n, bytes: parse_size(&size), source: format!("{d}/size = {size}") }); + } + } + best.filter(|l| l.bytes > 0) +} + +/// (busy, total) jiffies of one logical CPU from /proc/stat (Linux). +fn proc_stat_cpu(cpu: usize) -> Option<(u64, u64)> { + let stat = fs::read_to_string("/proc/stat").ok()?; + let line = stat.lines().find(|l| l.starts_with(&format!("cpu{cpu} ")))?; + let f: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); + let total: u64 = f.iter().take(8).sum(); + Some((total - f.get(3)? - f.get(4).copied().unwrap_or(0), total)) +} + +fn busy_fraction(before: Option<(u64, u64)>, after: Option<(u64, u64)>) -> Option { + let (b, a) = (before?, after?); + (a.1 > b.1).then(|| (a.0.saturating_sub(b.0)) as f64 / (a.1 - b.1) as f64) +} + +/// Linux: the logical CPU the calling thread last ran on (field 39 of /proc/thread-self/stat). Elsewhere: None. +fn current_cpu() -> Option { + if !cfg!(target_os = "linux") { + return None; + } + let s = fs::read_to_string("/proc/thread-self/stat").ok()?; + let rest = &s[s.rfind(')')? + 1..]; + rest.split_whitespace().nth(36)?.parse().ok() +} + +/// Linux: every thread of this process with the CPU it last ran on (the pool's worker is one of them). +fn observed_threads() -> Vec<(String, Option)> { + let mut v = Vec::new(); + if let Ok(dir) = fs::read_dir("/proc/self/task") { + for e in dir.flatten() { + let p = e.path(); + let name = read_text(&format!("{}/comm", p.display())); + let cpu = fs::read_to_string(p.join("stat")) + .ok() + .and_then(|s| s.get(s.rfind(')')? + 1..)?.split_whitespace().nth(36)?.parse().ok()); + v.push((name, cpu)); + } + } + v.sort(); + v +} + +fn is_managed_name(name: &str) -> bool { + let up = name.to_ascii_uppercase(); + up.starts_with("STRATA_") || up.starts_with("LELEKA_") +} + +/// Every STRATA_* / LELEKA_* variable the process sees. +fn managed_env_now() -> BTreeMap { + std::env::vars_os() + .filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))) + .filter(|(k, _)| is_managed_name(k)) + .collect() +} + +fn json_env(env: &BTreeMap) -> String { + format!("{{{}}}", env.iter().map(|(k, v)| format!("{}: {}", jstr(k), jstr(v))).collect::>().join(", ")) +} + +// ------------------------------------------------------------------------------------------------ time (one fresh process) + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum RegimeSel { + Both, + Resident, + Streamed, +} + +#[derive(Debug)] +struct TimeArgs { + dir: PathBuf, + case: String, + slices: usize, + pin: usize, + out: PathBuf, + slice_ms: f64, + regime: RegimeSel, + llc_bytes: Option, +} + +const TIME_FLAGS: [&str; 8] = ["run-dir", "case", "slices", "pin", "out", "slice-ms", "regime", "llc-bytes"]; + +/// The command line of `kab time` (STRA-317), checked the same way. +fn parse_time_args(args: &[String]) -> Result { + let f = Flags::parse(args, &TIME_FLAGS)?; + let slices = f.number::("slices")?.ok_or("--slices is required")?; + let pin = f.number::("pin")?.ok_or("--pin is required")?; + let slice_ms = f.number::("slice-ms")?.unwrap_or(DEFAULT_SLICE_MS); + if !(1..=100_000).contains(&slices) { + return Err("--slices must be 1..100000".to_owned()); + } + if !(1.0..=10_000.0).contains(&slice_ms) { + return Err("--slice-ms must be 1..10000".to_owned()); + } + let regime = match f.get("regime").unwrap_or("both") { + "both" => RegimeSel::Both, + "resident" => RegimeSel::Resident, + "streamed" => RegimeSel::Streamed, + _ => return Err("--regime must be both, resident or streamed".to_owned()), + }; + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); + } + Ok(TimeArgs { + dir: PathBuf::from(f.req("run-dir")?), + case, + slices, + pin, + out: PathBuf::from(f.req("out")?), + slice_ms, + regime, + llc_bytes: f.number::("llc-bytes")?, + }) +} + +/// A buffer whose usable part starts on a 4096-byte boundary. +struct Arena { + buf: Vec, + off: usize, +} +impl Arena { + fn new(len: usize) -> Self { + let size = std::mem::size_of::(); + let buf = vec![T::default(); len + ALIGN / size]; + let misalign = buf.as_ptr() as usize % ALIGN; + let off = if misalign == 0 { 0 } else { (ALIGN - misalign) / size }; + Self { buf, off } + } + fn slice(&self, len: usize) -> &[T] { + &self.buf[self.off..self.off + len] + } + fn slice_mut(&mut self, len: usize) -> &mut [T] { + &mut self.buf[self.off..self.off + len] + } +} + +/// The timed call: one group of one expert through the crate's public pool, exactly as `compute_case` does it. +struct Timed<'a> { + pool: DirectCpuPool, + gu: GateUpFormat, + down: DownFormat, + header: InHeader, + pairs: Vec<(usize, usize)>, + tokens: &'a [f32], + out: Vec, +} + +impl Timed<'_> { + fn call(&mut self, weights: &[u8]) -> Result<(), String> { + let (g, u) = (self.header.gate, self.header.up); + let expert = BorrowedExpert { + gate: &weights[..g], + up: &weights[g..g + u], + down: &weights[g + u..g + u + self.header.down_bytes], + pairs: &self.pairs, + }; + let experts = [expert]; + let group = BorrowedGroup { tokens: self.tokens, experts: &experts, stride: 1 }; + self.pool + .compute_group(self.gu, self.down, &group, &mut self.out) + .map_err(|e| format!("compute_group failed: {e:?}")) + } +} + +struct Slice { + calls: u64, + wall_ns: u64, + ns_per_call: f64, + ghz_before: f64, + ghz_after: f64, + cycles_per_call: f64, + moved: bool, +} + +/// One slice of `ms` milliseconds cycling over the copies; the shape of `time_slice()` in tq_cpu_parity.cpp (lines 290-304). +fn time_slice(t: &mut Timed, copies: &[&[u8]], ms: f64, next: &mut usize) -> Result { + let ghz_before = core_ghz(); + let mut calls = 0u64; + let ns0 = mono_ns(); + let mut ns1; + loop { + t.call(copies[*next % copies.len()])?; + *next += 1; + calls += 1; + ns1 = mono_ns(); + if (ns1 - ns0) as f64 >= ms * 1e6 && calls >= 2 { + break; + } + } + let ghz_after = core_ghz(); + let wall = ns1 - ns0; + let ns_per_call = wall as f64 / calls as f64; + let ghz_mean = 0.5 * (ghz_before + ghz_after); + Ok(Slice { + calls, + wall_ns: wall, + ns_per_call, + ghz_before, + ghz_after, + cycles_per_call: ns_per_call * ghz_mean, + moved: ghz_mean > 0.0 && (ghz_after - ghz_before).abs() > CLOCK_MOVED_FRACTION * ghz_before, + }) +} + +fn slice_json(s: &Slice, idx: usize) -> String { + format!( + "{{\"i\": {idx}, \"calls\": {}, \"wall_ns\": {}, \"ns_per_call\": {}, \"ghz_before\": {}, \"ghz_after\": {}, \"cycles_per_call\": {}}}", + s.calls, + s.wall_ns, + jnum(s.ns_per_call, 3), + jnum(s.ghz_before, 6), + jnum(s.ghz_after, 6), + jnum(s.cycles_per_call, 1) + ) +} + +/// Slices with their index within the regime. +type Numbered = Vec<(usize, Slice)>; + +struct RegimeRun { + json: String, + kept: usize, + ok: bool, +} + +struct RegimeSpec<'a> { + label: &'a str, + copies: Vec<&'a [u8]>, + expert_bytes: usize, + stride: usize, + llc: &'a Llc, + slices: usize, + slice_ms: f64, + pin: usize, + selfcheck: bool, +} + +fn run_regime(t: &mut Timed, spec: &RegimeSpec) -> Result { + let mut next = 0usize; + // warm-up (not recorded): tables and buffers, and for STREAMED one full pass over the copies so every page is resident + for _ in 0..3 { + t.call(spec.copies[next % spec.copies.len()])?; + next += 1; + } + if spec.copies.len() > 1 { + for _ in 0..spec.copies.len() { + t.call(spec.copies[next % spec.copies.len()])?; + next += 1; + } + } + let (mut kept, mut dropped): (Numbered, Numbered) = (Vec::new(), Vec::new()); + let mut migrated: Option = cfg!(target_os = "linux").then_some(0); + for i in 0..spec.slices { + let before = current_cpu(); + let s = time_slice(t, &spec.copies, spec.slice_ms, &mut next)?; + if let Some(m) = migrated.as_mut() + && (before != Some(spec.pin) || current_cpu() != Some(spec.pin)) + { + *m += 1; + } + if s.moved { dropped.push((i, s)) } else { kept.push((i, s)) } + } + let ns: Vec = kept.iter().map(|k| k.1.ns_per_call).collect(); + let cyc: Vec = kept.iter().map(|k| k.1.cycles_per_call).collect(); + let med = |v: &[f64], d: usize| if v.is_empty() { "null".to_owned() } else { jnum(median_of(v), d) }; + let list = |v: &[(usize, Slice)]| v.iter().map(|(i, s)| slice_json(s, *i)).collect::>().join(",\n "); + let json = format!( + "{{\"regime\": {}, \"copies_k\": {}, \"expert_bytes\": {}, \"copy_stride_bytes\": {}, \"working_set_bytes\": {}, \"llc_level\": {}, \"llc_bytes\": {}, \"llc_source\": {}, \"working_set_over_llc\": {}, \"slice_ms\": {}, \"slices_requested\": {}, \"slices_kept\": {}, \"dropped_count\": {}, \"selfcheck_bitwise_equal_first_call\": {}, \"migrated_slices\": {}, \"median_ns_per_call\": {}, \"median_cycles_per_call\": {},\n \"slices\": [\n {}],\n \"dropped\": [\n {}]}}", + jstr(spec.label), + spec.copies.len(), + spec.expert_bytes, + spec.stride, + spec.expert_bytes * spec.copies.len(), + spec.llc.level, + spec.llc.bytes, + jstr(&spec.llc.source), + spec.copies.len() > 1, + jnum(spec.slice_ms, 1), + spec.slices, + kept.len(), + dropped.len(), + spec.selfcheck, + migrated.map_or("null".to_owned(), |m| m.to_string()), + med(&ns, 3), + med(&cyc, 1), + list(&kept), + list(&dropped) + ); + Ok(RegimeRun { json, kept: kept.len(), ok: !kept.is_empty() && migrated.is_none_or(|m| m == 0) }) +} + +fn f32_bits_sha(values: &[f32]) -> String { + let mut b = Vec::with_capacity(values.len() * 4); + for v in values { + b.extend_from_slice(&v.to_bits().to_le_bytes()); + } + sha_hex(&b) +} + +/// `kernel_ab time ...`: one fresh process, one case, the resident and the streamed regime, JSON written by tmp + rename. Exit codes as +/// `kab time`: 0 ok; 1 usage / refused input; 3 a regime kept no slice or a slice migrated off the pin; 4 the final output differs. +fn cmd_time(args: &[String]) -> Result { + let t = parse_time_args(args)?; + let wall0 = mono_ns(); + // pin first (before any buffer or pool exists, so the pool's threads inherit the mask), then the facts about the pin + if rust_topology::pin_current_thread(t.pin as i32) < 0 { + return Err(format!("the pin to CPU {} was refused", t.pin)); + } + if cfg!(target_os = "linux") && current_cpu() != Some(t.pin) { + return Err(format!("the process is not running on CPU {} after the pin", t.pin)); + } + let cpu_dir = format!("/sys/devices/system/cpu/cpu{}", t.pin); + let sib_text = read_text(&format!("{cpu_dir}/topology/thread_siblings_list")); + let sibling = parse_cpu_list(&sib_text).into_iter().rfind(|c| *c != t.pin); + let sib0 = sibling.and_then(proc_stat_cpu); + let pin0 = proc_stat_cpu(t.pin); + let load0 = read_text("/proc/loadavg"); + + // the case: the KAB1 reader rule (validate, then use) and the manifest and case input hashes + let (manifest_bytes, _provenance, cases, _files) = read_manifest(&t.dir).map_err(|e| e.to_string())?; + let manifest_sha = sha_hex(&manifest_bytes); + let entry = + cases.iter().find(|c| c.id == t.case).ok_or_else(|| format!("case {} is not in the manifest", t.case))?; + let case = read_case_in(&t.dir, entry).map_err(|e| e.to_string())?; + let header = case.header; + let weights = &case.blob[IN_HEADER..header.input_at()]; + let expert_bytes = weights.len(); + + // environment and tree + let env = managed_env_now(); + let report = cpu_kernel_report(); + let tree = family_of(&report).ok_or("no process kernel family line in cpu_kernel_report")?; + + // the streamed set: K copies, K x stride at least 2 x the last-level cache of the pinned CPU (the design choice of kab_time.cpp) + let llc = match (t.llc_bytes, llc_of_cpu(t.pin)) { + (Some(bytes), found) => { + Llc { level: found.map_or(0, |l| l.level), bytes, source: "--llc-bytes (override)".to_owned() } + } + (None, Some(l)) => l, + (None, None) => { + return Err(format!("cannot read the last-level cache size of CPU {} from sysfs; pass --llc-bytes", t.pin)); + } + }; + if llc.bytes == 0 { + return Err("--llc-bytes must be positive".to_owned()); + } + let stride = expert_bytes.div_ceil(ALIGN) * ALIGN; + let copies_k = ((2 * llc.bytes) / stride as u64) as usize + 1; + if copies_k * stride > (4usize << 30) { + return Err("the streamed working set would exceed 4 GiB; check --llc-bytes".to_owned()); + } + + // the pool is created AFTER the pin: its worker inherits the one-CPU mask (rust_platform::cores sees a one-CPU affinity) + let mut pool = DirectCpuPool::new(1).map_err(|e| format!("DirectCpuPool::new(1) failed: {e:?}"))?; + let want = compute_case(&mut pool, &case)?; + let want_bits: Vec = want.iter().map(|v| v.to_bits()).collect(); + let output_sha = f32_bits_sha(&want); + + let mut tokens = Arena::::new(header.rows * H); + tokens.slice_mut(header.rows * H).copy_from_slice(&case.input()); + let mut resident = Arena::::new(stride); + resident.slice_mut(expert_bytes).copy_from_slice(weights); + let mut streamed = Arena::::new(stride * copies_k); + for k in 0..copies_k { + streamed.slice_mut(stride * copies_k)[k * stride..k * stride + expert_bytes].copy_from_slice(weights); + } + let res_copies: Vec<&[u8]> = vec![resident.slice(expert_bytes)]; + let stm_all = streamed.slice(stride * copies_k); + let stm_copies: Vec<&[u8]> = (0..copies_k).map(|k| &stm_all[k * stride..k * stride + expert_bytes]).collect(); + + let mut timed = Timed { + pool, + gu: gate_up_row(header.gu).ok_or("gate/up type")?.1, + down: down_row(header.down).ok_or("down type")?.1, + header, + pairs: (0..header.rows).map(|r| (r, 0)).collect(), + tokens: tokens.slice(header.rows * H), + out: vec![0.0f32; header.rows * H], + }; + // selfcheck: the timed call's output on every aligned copy is bit-identical to the first (unaligned) call's + let mut selfcheck = true; + for w in [res_copies[0], stm_copies[0], stm_copies[copies_k - 1]] { + timed.call(w)?; + selfcheck &= timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + } + if !selfcheck { + return Err("selfcheck failed: the timed call differs from the first call".to_owned()); + } + + let ghz0 = core_ghz(); + let mut regimes = Vec::new(); + let mut all_ok = true; + let (mut kept_res, mut kept_stm) = (0, 0); + for (label, copies, sel) in + [("RESIDENT", &res_copies, RegimeSel::Resident), ("STREAMED", &stm_copies, RegimeSel::Streamed)] + { + if t.regime != RegimeSel::Both && t.regime != sel { + continue; + } + let spec = RegimeSpec { + label, + copies: copies.clone(), + expert_bytes, + stride, + llc: &llc, + slices: t.slices, + slice_ms: t.slice_ms, + pin: t.pin, + selfcheck, + }; + let r = run_regime(&mut timed, &spec)?; + all_ok &= r.ok; + if sel == RegimeSel::Resident { + kept_res = r.kept + } else { + kept_stm = r.kept + } + regimes.push(r.json); + } + let ghz1 = core_ghz(); + timed.call(res_copies[0])?; + let final_same = timed.out.iter().map(|v| v.to_bits()).eq(want_bits.iter().copied()); + + let threads = observed_threads(); + let sib1 = sibling.and_then(proc_stat_cpu); + let pin1 = proc_stat_cpu(t.pin); + let frac = |f: Option| f.map_or("null".to_owned(), |v| jnum(v, 4)); + let rust_fmt = |l: &str| jstr(l); + let (gu_name, down_name) = + (gate_up_row(header.gu).map_or("?", |x| x.4), down_row(header.down).map_or("?", |x| x.4)); + let in_name = format!("case-{}.in", t.case); + let command_line = format!( + "time --run-dir {} --case {} --slices {} --pin {} --out {}{}{}", + t.dir.display(), + t.case, + t.slices, + t.pin, + t.out.display(), + if args.iter().any(|a| a == "--slice-ms") { format!(" --slice-ms {}", t.slice_ms) } else { String::new() }, + match t.regime { + RegimeSel::Both => String::new(), + RegimeSel::Resident => " --regime resident".to_owned(), + RegimeSel::Streamed => " --regime streamed".to_owned(), + } + ); + let mut j = String::from( + "{\n \"format\": \"KAB1-time\",\n \"version\": 1,\n \"mode\": \"time\",\n \"writer\": \"rust\",\n", + ); + j += &format!( + " \"command_line\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n", + jstr(&command_line), + jstr(&t.dir.display().to_string()), + jstr(&manifest_sha) + ); + j += &format!( + " \"case\": {{\"id\": {}, \"gu_type\": {}, \"down_type\": {}, \"gu_name\": {}, \"down_name\": {}, \"rows\": {}, \"input_file\": {}, \"input_sha256\": {}, \"input_sha256_matches_manifest\": true, \"expert_bytes\": {}}},\n", + jstr(&t.case), + header.gu, + header.down, + jstr(gu_name), + jstr(down_name), + header.rows, + jstr(&in_name), + jstr(&entry.in_sha256), + expert_bytes + ); + j += &format!( + " \"tree\": {},\n \"tree_detail\": {{\"tree\": {}, \"cpu_report\": [{}], \"strata_env\": {}}},\n \"effective_env\": {},\n", + jstr(tree), + jstr(tree), + report.iter().map(|l| rust_fmt(l)).collect::>().join(", "), + json_env(&env), + json_env(&env) + ); + j += &format!( + " \"pool\": {{\"workers\": 1, \"host_drains\": true, \"threads_observed\": [{}], \"note\": \"DirectCpuPool::new(1): one worker thread plus the calling thread that drains beside it (pool.cpp host_works_); both inherit the one-CPU mask of the pin\"}},\n", + threads + .iter() + .map(|(n, c)| format!( + "{{\"name\": {}, \"cpu\": {}}}", + jstr(n), + c.map_or("null".to_owned(), |c| c.to_string()) + )) + .collect::>() + .join(", ") + ); + j += &format!( + " \"pin\": {{\"cpu\": {}, \"thread_siblings_list\": {}, \"sibling_cpu\": {}, \"physical_core_id\": {}, \"pin_busy_fraction_during_run\": {}, \"sibling_busy_fraction_during_run\": {}, \"sibling_busy_note\": \"/proc/stat jiffies of the sibling logical CPU between the start and the end of this process; it is recorded, no threshold is applied here\", \"scaling_governor\": {}, \"cpufreq_boost\": {}, \"loadavg_start\": {}, \"loadavg_end\": {}, \"final_cpu\": {}}},\n", + t.pin, + jstr(&sib_text), + sibling.map_or("null".to_owned(), |s| s.to_string()), + jstr(&read_text(&format!("{cpu_dir}/topology/core_id"))), + frac(busy_fraction(pin0, pin1)), + if sibling.is_some() { frac(busy_fraction(sib0, sib1)) } else { "null".to_owned() }, + jstr(&read_text(&format!("{cpu_dir}/cpufreq/scaling_governor"))), + jstr(&read_text("/sys/devices/system/cpu/cpufreq/boost")), + jstr(&load0), + jstr(&read_text("/proc/loadavg")), + current_cpu().map_or("null".to_owned(), |c| c.to_string()) + ); + j += &format!( + " \"buffers\": {{\"alignment_bytes\": {ALIGN}, \"expert_copy_stride_bytes\": {stride}, \"activations_aligned\": true, \"scratch_aligned\": false, \"scratch_note\": \"the pool's own scratch is allocated inside the crate\"}},\n" + ); + j += &format!( + " \"clock_calibration\": {{\"method\": {}, \"source\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp --bench: core_ghz() lines 273-284, time_slice() lines 290-304; the dependent-add chain needs inline assembly, so the safe Rust twin chains multiplies\", \"drop_rule\": {{\"source_file\": \"engine/strata/src/kernels/cpu/tq_cpu_parity.cpp\", \"source_line\": 303, \"source_text\": \"std::fabs(g1 - g0) > 0.05 * g0\", \"fraction\": {}, \"meaning\": \"a slice whose calibrated clock moved by more than 5 percent between its before and after calibration is dropped\"}}, \"slice_ms_source\": \"tq_cpu_parity.cpp:461 slice_ms = quick ? 40 : 60\", \"ghz_at_start\": {}, \"ghz_at_end\": {}, \"tsc_invariant\": null, \"clocks\": \"monotonic ns (std::time::Instant); no TSC read: rdtsc and lfence are unsafe intrinsics and the crate keeps unsafe_code = deny\"}},\n", + jstr(CLOCK_METHOD), + jnum(CLOCK_MOVED_FRACTION, 2), + jnum(ghz0, 6), + jnum(ghz1, 6) + ); + j += &format!( + " \"build\": {{\"profile\": {}, \"rustflags\": {}, \"example\": \"crates/native-cpu-expert/examples/kernel_ab.rs\"}},\n", + jstr(if cfg!(debug_assertions) { "dev" } else { "release" }), + jstr(&std::env::var("RUSTFLAGS").unwrap_or_default()) + ); + j += &format!( + " \"selfcheck_bitwise_equal_first_call\": {selfcheck},\n \"final_output_unchanged\": {final_same},\n \"output_sha256\": {},\n \"duration_ns\": {},\n \"timing_caveat\": \"numbers from a shared host are not evidence by themselves; loadavg and the sibling busy fraction are recorded above\",\n \"regimes\": [\n {}\n ]\n}}\n", + jstr(&output_sha), + mono_ns() - wall0, + regimes.join(",\n ") + ); + let tmp = PathBuf::from(format!("{}.tmp", t.out.display())); + fs::write(&tmp, j.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?; + fs::rename(&tmp, &t.out).map_err(|e| format!("rename to {}: {e}", t.out.display()))?; + println!( + "kernel_ab time: case={} tree={tree} pin={} slices={} resident_kept={kept_res} streamed_kept={kept_stm} K={copies_k} out={}", + t.case, + t.pin, + t.slices, + t.out.display() + ); + if !all_ok { + eprintln!("kernel_ab time: a regime has no kept slice or a slice migrated off CPU {}", t.pin); + return Ok(ExitCode::from(3)); + } + if !final_same { + eprintln!("kernel_ab time: the final output differs from the first call's"); + return Ok(ExitCode::from(4)); + } + Ok(ExitCode::SUCCESS) +} + +// ------------------------------------------------------------------------------------------------ alternate: cells, environment, schedule + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +enum Impl { + Cpp, + Rust, +} +impl Impl { + fn name(self) -> &'static str { + match self { + Impl::Cpp => "cpp", + Impl::Rust => "rust", + } + } +} + +/// One process of a round: an implementation, a tree and a replicate (`a` is the A/B process, `b` the A/A twin). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +struct Proc { + imp: Impl, + tree: &'static str, + rep: char, +} +impl Proc { + fn name(&self) -> String { + format!("{}-{}-{}", self.imp.name(), self.tree, self.rep) + } + fn parse(s: &str) -> Option { + let mut p = s.split('-'); + let imp = match p.next()? { + "cpp" => Impl::Cpp, + "rust" => Impl::Rust, + _ => return None, + }; + let wanted = p.next()?; + let tree = *TREES.iter().find(|t| **t == wanted)?; + let rep = match p.next()? { + "a" => 'a', + "b" => 'b', + _ => return None, + }; + p.next().is_none().then_some(Proc { imp, tree, rep }) + } +} + +/// Every process of a round for the given trees, in canonical order. +fn procs_for(trees: &[&'static str]) -> Vec { + let mut v = Vec::new(); + for imp in [Impl::Cpp, Impl::Rust] { + for tree in trees { + for rep in ['a', 'b'] { + v.push(Proc { imp, tree, rep }); + } + } + } + v +} + +/// The environment a cell needs and nothing else. The avx2 trees set `STRATA_FORCE_AVX2=1`, which both implementations honour. The +/// Rust cells run `DirectCpuPool::new(1)`, a worker thread plus the draining caller, both confined to the one pinned CPU: the pool must +/// not re-pin its caller (`LELEKA_CPU_POOL_PIN_HOST=off`, so the pin is the requested one) and its worker must not spin after a batch +/// (`STRATA_POOL_SPIN_US=0`; with the 20 ms default the worker spins on the caller's only CPU and costs it half its time). +fn cell_env(p: &Proc) -> Vec<(String, String)> { + let mut v = Vec::new(); + if p.tree == "avx2" { + v.push(("STRATA_FORCE_AVX2".to_owned(), "1".to_owned())); + } + if p.imp == Impl::Rust { + v.push(("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned())); + v.push(("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned())); + } + v.sort(); + v +} + +/// A command whose environment is exactly: the parent's variables minus every STRATA_* / LELEKA_* one, plus the cell's variables. +fn scrubbed_command(program: &Path, parent_env: &[(OsString, OsString)], cell: &[(String, String)]) -> Command { + let mut c = Command::new(program); + c.env_clear(); + for (k, v) in parent_env { + if !is_managed_name(&k.to_string_lossy()) { + c.env(k, v); + } + } + for (k, v) in cell { + c.env(k, v); + } + c +} + +/// Runs a prepared cell command; a failure names the cell. +fn run_cell(cmd: &mut Command, cell: &str) -> Result { + let out = cmd.output().map_err(|e| format!("cell {cell}: cannot start the process: {e}"))?; + if out.status.success() { + return Ok(out); + } + let tail = |b: &[u8]| { + String::from_utf8_lossy(b) + .lines() + .rev() + .take(3) + .collect::>() + .into_iter() + .rev() + .collect::>() + .join(" | ") + }; + Err(format!( + "cell {cell} failed ({}): stderr: {}; stdout: {}", + out.status.code().map_or("killed by a signal".to_owned(), |c| format!("exit {c}")), + tail(&out.stderr), + tail(&out.stdout) + )) +} + +fn splitmix(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// The schedule of one batch: round `i` (0-based) rotates a seeded permutation by `i mod n`; every block of `n` rounds draws a fresh +/// permutation, so each process takes each position equally often within a block. A pure function of (seed, batch, rounds, procs). +fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc]) -> Vec> { + let n = procs.len(); + let mut out = Vec::new(); + let mut base: Vec = Vec::new(); + for i in 0..rounds as usize { + if i % n == 0 { + let mut st = seed; + for x in [u64::from(batch), (i / n) as u64] { + st = st.wrapping_add(x.wrapping_mul(0x9E37_79B9_7F4A_7C15)); + st = splitmix(&mut st); + } + base = procs.to_vec(); + for j in (1..n).rev() { + let k = (splitmix(&mut st) % (j as u64 + 1)) as usize; + base.swap(j, k); + } + } + let mut order = base.clone(); + order.rotate_left(i % n); + out.push(order); + } + out +} + +const SCHEDULE_MAGIC: &str = "# KAB1-alt schedule v1"; + +fn schedule_text( + seed: u64, + batch: u32, + rounds: u32, + case: &str, + pin: usize, + first_round: u32, + order: &[Vec], +) -> String { + let mut t = format!( + "{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} rounds={rounds} case={case} pin={pin}\n" + ); + for (i, o) in order.iter().enumerate() { + t += &format!("{}\t{}\n", first_round + i as u32, o.iter().map(Proc::name).collect::>().join(",")); + } + t +} + +/// Reads a schedule back: (round number, processes in order) per round. Every round must name each process of the first round once. +fn parse_schedule(text: &str) -> Result)>, String> { + let mut lines = text.lines(); + if !lines.next().is_some_and(|l| l.starts_with(SCHEDULE_MAGIC)) { + return Err("not a KAB1-alt schedule".to_owned()); + } + let mut rounds: Vec<(u32, Vec)> = Vec::new(); + for l in lines.filter(|l| !l.starts_with('#') && !l.is_empty()) { + let (no, list) = l.split_once('\t').ok_or_else(|| format!("bad schedule line {l:?}"))?; + let no = no.parse::().map_err(|_| format!("bad round number in {l:?}"))?; + let order: Vec = list + .split(',') + .map(|n| Proc::parse(n).ok_or_else(|| format!("unknown process {n:?} in the schedule"))) + .collect::>()?; + if let Some(prev) = rounds.last() + && (no != prev.0 + 1 + || BTreeSet::from_iter(order.iter()) != BTreeSet::from_iter(prev.1.iter()) + || order.len() != prev.1.len()) + { + return Err(format!("round {no} does not follow round {} with the same processes", prev.0)); + } + rounds.push((no, order)); + } + if rounds.is_empty() { + return Err("the schedule has no round".to_owned()); + } + Ok(rounds) +} + +/// Refuses a path that is, or lies inside, a Git checkout (generated artifacts stay out of Git). +fn inside_git_checkout(path: &Path) -> bool { + let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()); + abs.ancestors().any(|a| a.join(".git").exists()) +} + +// ------------------------------------------------------------------------------------------------ alternate: reading a process's JSON + +#[derive(Debug, Clone)] +struct RegimeStat { + copies_k: usize, + expert_bytes: usize, + llc_bytes: u64, + requested: usize, + dropped: usize, + median_ns: f64, + median_cycles: f64, + ns: Vec, + cycles: Vec, + max_drift: f64, + selfcheck: bool, +} + +#[derive(Debug, Clone)] +struct ProcOut { + proc: Proc, + regimes: BTreeMap, + ghz_start: f64, + ghz_end: f64, + /// None: unknown; Some(true): the sibling was idle (or there is none) under the 5 percent rule. + sibling_idle: Option, + final_unchanged: bool, + output_sha: Option, + tree_text: String, + cpu_model: Option, +} + +/// What a process's JSON must say about the run that produced it. +struct Expect<'a> { + manifest_sha: &'a str, + input_sha: &'a str, + case: &'a str, + pin: usize, +} + +fn parse_regime(r: &Json, imp: Impl) -> Result { + let mut ns = Vec::new(); + let mut cycles = Vec::new(); + let mut max_drift = 0.0f64; + for (key, keep) in [("slices", true), ("dropped", false)] { + for s in r.array(key)? { + let (g0, g1) = (s.float("ghz_before")?, s.float("ghz_after")?); + if g0 > 0.0 { + max_drift = max_drift.max(((g1 - g0).abs() / g0).min(1.0)); + } + if keep { + ns.push(s.float("ns_per_call")?); + cycles.push(s.float("cycles_per_call")?); + } + } + } + let selfcheck_key = + if imp == Impl::Cpp { "selfcheck_bitwise_equal_compose_expert" } else { "selfcheck_bitwise_equal_first_call" }; + let kept = r.uint("slices_kept")? as usize; + if kept != ns.len() || kept == 0 { + return Err(format!("slices_kept {kept} disagrees with the {} kept slices (or none was kept)", ns.len())); + } + Ok(RegimeStat { + copies_k: r.uint("copies_k")? as usize, + expert_bytes: r.uint("expert_bytes")? as usize, + llc_bytes: r.uint("llc_bytes")?, + requested: r.uint("slices_requested")? as usize, + dropped: r.uint("dropped_count")? as usize, + median_ns: r.float("median_ns_per_call")?, + median_cycles: r.float("median_cycles_per_call")?, + ns, + cycles, + max_drift, + selfcheck: r.flag(selfcheck_key)?, + }) +} + +fn describe_cpp_tree(d: &Json) -> String { + let b = |k: &str| { + d.get(k).map_or("?".to_owned(), |v| match v { + Json::Bool(x) => x.to_string(), + Json::Num(n) => n.clone(), + _ => "?".to_owned(), + }) + }; + let env = match d.get("strata_env") { + Some(Json::Obj(items)) if !items.is_empty() => items + .iter() + .map(|(k, v)| format!("{k}={}", if let Json::Str(s) = v { s.as_str() } else { "?" })) + .collect::>() + .join(" "), + _ => "no STRATA_* variable set (STRATA_NO_IQ512, STRATA_NO_IQ256 and STRATA_IQ_GATHER unset)".to_owned(), + }; + format!( + "avx2_ok={} avx512_ok={} iq512_gather_on={} iq256_gather_setting={}; {env}", + b("avx2_ok"), + b("avx512_ok"), + b("iq512_gather_on"), + b("iq256_gather_setting") + ) +} + +/// Parses a process's KAB1-time JSON and checks it against the cell that was started: writer, tree, manifest and input hashes, case, +/// pin, and that the effective STRATA_* / LELEKA_* environment is exactly the cell's. +fn parse_proc_json(p: &Proc, bytes: &[u8], expect: &Expect) -> Result { + let j = parse_json(bytes)?; + let name = p.name(); + let fail = |what: String| format!("cell {name}: {what}"); + if j.str("format").map_err(fail)? != "KAB1-time" || j.uint("version").map_err(fail)? != 1 { + return Err(fail("the output is not KAB1-time version 1".to_owned())); + } + if j.str("writer").map_err(fail)? != p.imp.name() { + return Err(fail(format!( + "the output's writer is {:?}, expected {}", + j.str("writer").unwrap_or("?"), + p.imp.name() + ))); + } + if j.str("tree").map_err(fail)? != p.tree { + return Err(fail(format!( + "the process ran the {} tree, the cell asks for {}", + j.str("tree").unwrap_or("?"), + p.tree + ))); + } + if j.str("manifest_sha256").map_err(fail)? != expect.manifest_sha { + return Err(fail("manifest_sha256 differs from the run directory's".to_owned())); + } + let c = j.req("case").map_err(fail)?; + if c.str("id").map_err(fail)? != expect.case || c.str("input_sha256").map_err(fail)? != expect.input_sha { + return Err(fail("the case id or its input hash differs from the manifest's".to_owned())); + } + let pin = j.req("pin").map_err(fail)?; + if pin.uint("cpu").map_err(fail)? as usize != expect.pin { + return Err(fail(format!("pinned to CPU {}, expected {}", pin.uint("cpu").unwrap_or(u64::MAX), expect.pin))); + } + let want_env: BTreeMap = cell_env(p).into_iter().collect(); + let mut seen_env = BTreeMap::new(); + if let Json::Obj(items) = j.req("effective_env").map_err(fail)? { + for (k, v) in items { + seen_env.insert( + k.clone(), + match v { + Json::Str(s) => s.clone(), + Json::Num(n) => n.clone(), + _ => "?".to_owned(), + }, + ); + } + } + if seen_env != want_env { + return Err(fail(format!("effective environment {seen_env:?} differs from the cell's {want_env:?}"))); + } + let mut regimes = BTreeMap::new(); + for r in j.array("regimes").map_err(fail)? { + let label = r.str("regime").map_err(fail)?.to_owned(); + regimes.insert(label, parse_regime(r, p.imp).map_err(fail)?); + } + for want in ["RESIDENT", "STREAMED"] { + if !regimes.contains_key(want) { + return Err(fail(format!("regime {want} is missing"))); + } + } + let clock = j.req("clock_calibration").map_err(fail)?; + let sibling_idle = match pin.req("sibling_cpu").map_err(fail)? { + Json::Null => Some(true), + _ => pin.float_or_null("sibling_busy_fraction_during_run").map_err(fail)?.map(|f| f < SIBLING_BUSY_LIMIT), + }; + let detail = j.req("tree_detail").map_err(fail)?; + let (tree_text, cpu_report) = if p.imp == Impl::Rust { + let report: Vec = detail + .array("cpu_report") + .map_err(fail)? + .iter() + .filter_map(|l| if let Json::Str(s) = l { Some(s.clone()) } else { None }) + .collect(); + let line = report + .iter() + .find(|l| l.starts_with("cpu: process kernel family")) + .cloned() + .ok_or_else(|| fail("no process kernel family line".to_owned()))?; + (format!("leleka-serve {line}"), report) + } else { + (describe_cpp_tree(detail), Vec::new()) + }; + let cpu_model = (!cpu_report.is_empty()).then(|| cpu_model_of(&cpu_report)); + Ok(ProcOut { + proc: *p, + regimes, + ghz_start: clock.float("ghz_at_start").map_err(fail)?, + ghz_end: clock.float("ghz_at_end").map_err(fail)?, + sibling_idle, + final_unchanged: j.flag("final_output_unchanged").map_err(fail)?, + output_sha: j.get("output_sha256").and_then(|v| if let Json::Str(s) = v { Some(s.clone()) } else { None }), + tree_text, + cpu_model, + }) +} + +// ------------------------------------------------------------------------------------------------ alternate: round records + +struct Tool { + compiler: String, + version: String, + triple: String, + flags: String, +} + +struct SideStat { + median: f64, + p05: f64, + p95: f64, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind { + Ab, + AaCpp, + AaRust, +} +impl Kind { + fn slug(self) -> &'static str { + match self { + Kind::Ab => "ab", + Kind::AaCpp => "aa-cpp", + Kind::AaRust => "aa-rust", + } + } +} + +/// Everything a round record needs that does not change within a batch. +struct BatchCtx<'a> { + verified: &'a Verified, + case: &'a CaseEntry, + pin: usize, + machine_role: String, + os: String, + cpu_model: String, + started_utc: String, + rust_tool: Tool, + batch: u32, + /// Equality of our tree against the C++ reference per tree, from the equality phase. + equality: &'a BTreeMap<&'static str, Outcome>, +} + +fn side_stat(r: &RegimeStat, cycles: bool) -> SideStat { + let v = if cycles { &r.cycles } else { &r.ns }; + SideStat { + median: if cycles { r.median_cycles } else { r.median_ns }, + p05: percentile_of(v, 0.05), + p95: percentile_of(v, 0.95), + } +} + +fn stat_json(s: &SideStat) -> String { + format!("{{\"median\": {}, \"p05\": {}, \"p95\": {}}}", jnum(s.median, 6), jnum(s.p05, 6), jnum(s.p95, 6)) +} + +fn tool_json(t: &Tool) -> String { + format!( + "{{\"compiler\": {}, \"version\": {}, \"target_triple\": {}, \"flags\": {}}}", + jstr(&t.compiler), + jstr(&t.version), + jstr(&t.triple), + jstr(&t.flags) + ) +} + +fn equality_block(c: &CaseEntry, o: &Outcome) -> String { + let tolerance = c.tolerance.as_ref().map_or(String::new(), |t| { + format!( + ",\n \"tolerance\": {{\"value\": {:e}, \"basis\": {}, \"basis_written_utc\": {}}}", + t.value, + jstr(&format!("{} [metric: {TOLERANCE_METRIC}]", t.basis)), + jstr(&t.basis_written_utc) + ) + }); + format!( + "{{\n \"mode\": \"{}\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}{tolerance}\n }}", + if c.tolerance.is_some() { "tolerance" } else { "bitwise" }, + if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, + o.compared, + o.mismatches + ) +} + +/// The A/A equality: the same implementation in two fresh processes. Rust: the output hashes of the two processes (and each one's +/// selfcheck); C++: each process's timed composition equals `compose_expert()` bit for bit (selfcheck), which is the same function. +fn aa_outcome(a: &ProcOut, b: &ProcOut, rows: usize) -> (Outcome, String) { + let compared = rows * H; + let selfchecks = + a.regimes.values().chain(b.regimes.values()).all(|r| r.selfcheck) && a.final_unchanged && b.final_unchanged; + let same = selfchecks && (a.proc.imp == Impl::Cpp || (a.output_sha.is_some() && a.output_sha == b.output_sha)); + let note = if a.proc.imp == Impl::Cpp { + "selfcheck of both processes against compose_expert()" + } else { + "output sha256 of both processes" + }; + let outcome = Outcome { + compared, + mismatches: usize::from(!same), + differing_bits: usize::from(!same), + max_abs_error: 0.0, + first_mismatch: None, + }; + (outcome, note.to_owned()) +} + +/// The records of one round: per tree and regime the A/B record (ours = Rust `a`, reference = C++ `a`) and the two A/A records. +fn round_records(ctx: &BatchCtx, round_no: u32, done: &[ProcOut]) -> Result, String> { + let find = |imp: Impl, tree: &str, rep: char| { + done.iter() + .find(|p| p.proc.imp == imp && p.proc.tree == tree && p.proc.rep == rep) + .ok_or_else(|| format!("round {round_no}: process {}-{tree}-{rep} did not run", imp.name())) + }; + let p = &ctx.verified.provenance; + let c = ctx.case; + let cpp_tool = Tool { + compiler: p.compiler_id.clone(), + version: p.compiler_version.clone(), + triple: p.target_triple.clone(), + flags: p.reference_flags.clone(), + }; + let (gu, down) = (gate_up_row(c.gu).map_or("?", |x| x.4), down_row(c.down).map_or("?", |x| x.4)); + if done.is_empty() { + return Err("empty round".to_owned()); + } + let position = |p: &ProcOut| done.iter().position(|d| d.proc == p.proc).unwrap_or(0); + let mut files = Vec::new(); + let trees: Vec<&'static str> = TREES.iter().copied().filter(|t| done.iter().any(|d| d.proc.tree == *t)).collect(); + for tree in trees { + let (cpp_a, cpp_b, rust_a, rust_b) = ( + find(Impl::Cpp, tree, 'a')?, + find(Impl::Cpp, tree, 'b')?, + find(Impl::Rust, tree, 'a')?, + find(Impl::Rust, tree, 'b')?, + ); + for regime in ["RESIDENT", "STREAMED"] { + for kind in [Kind::Ab, Kind::AaCpp, Kind::AaRust] { + let (ours, reference, ours_tool, ref_tool) = match kind { + Kind::Ab => (rust_a, cpp_a, &ctx.rust_tool, &cpp_tool), + Kind::AaCpp => (cpp_a, cpp_b, &cpp_tool, &cpp_tool), + Kind::AaRust => (rust_a, rust_b, &ctx.rust_tool, &ctx.rust_tool), + }; + let (o, r) = (&ours.regimes[regime], &reference.regimes[regime]); + if (o.copies_k, o.expert_bytes, o.llc_bytes) != (r.copies_k, r.expert_bytes, r.llc_bytes) { + return Err(format!( + "round {round_no} {tree} {regime}: the streamed set differs between {} and {} (K {} vs {}, LLC {} vs {})", + ours.proc.name(), + reference.proc.name(), + o.copies_k, + r.copies_k, + o.llc_bytes, + r.llc_bytes + )); + } + let (equality, equality_note) = match kind { + Kind::Ab => (equality_block(c, &ctx.equality[tree]), "Rust output against the C++ reference .out file of the run directory, from the equality phase of this batch".to_owned()), + _ => { + let (outcome, note) = aa_outcome(ours, reference, c.rows); + (aa_equality_block(&outcome), format!("{note}, the same implementation in two fresh processes")) + } + }; + let kernel = format!( + "routed-expert-gate-up-down {gu}+{down} rows={} regime {regime} ROUND RECORD {} (batch {}, round {round_no}); ours-slot process {}, reference-slot process {}; tree ours: {}; tree reference: {}; equality: {equality_note}; aa_noise_floor is a PLACEHOLDER (n=1, CI 0): the A/A evaluation is S0.10b, this record carries one round's medians only", + c.rows, + match kind { + Kind::Ab => "A/B (ours = Rust, reference = C++)", + Kind::AaCpp => "A/A (C++ process a in the ours slot, C++ process b in the reference slot)", + Kind::AaRust => "A/A (Rust process a in the ours slot, Rust process b in the reference slot)", + }, + ctx.batch, + ours.proc.name(), + reference.proc.name(), + ours.tree_text, + reference.tree_text + ); + let drift = o.max_drift.max(r.max_drift); + // the two processes of this record, earliest first: the clock before the earlier one, after the later one + let (earlier, later) = + if position(ours) <= position(reference) { (ours, reference) } else { (reference, ours) }; + let sibling_idle = ours.sibling_idle == Some(true) && reference.sibling_idle == Some(true); + let streamed = if regime == "STREAMED" { + format!( + ",\n \"streamed\": {{\"copies\": {}, \"expert_bytes\": {}, \"llc_bytes\": {}}}", + o.copies_k, o.expert_bytes, o.llc_bytes + ) + } else { + String::new() + }; + let rowtype = + |unit: &str| format!("{gu}+{down} rows={} {} [{unit}]", c.rows, regime.to_ascii_lowercase()); + let json = format!( + "{{\n \"schema_version\": \"1\",\n \"level\": \"COMPONENT_KERNEL\",\n \"record_id\": {rid},\n \"created_utc\": {created},\n \"run_started_utc\": {started},\n \"machine\": {{\"machine_role\": {role}, \"cpu_model\": {cpu}, \"gpu_name\": \"none\", \"os\": {os}}},\n \"kernel\": {kernel},\n \"toolchain\": {{\n \"ours\": {ot},\n \"reference\": {rt}\n }},\n \"case_id\": {cid},\n \"input_sha256\": {insha},\n \"kab1_manifest_sha256\": {msha},\n \"tree\": {{\"ours\": {tree_q}, \"reference\": {tree_q}}},\n \"regime\": {regime_q}{streamed},\n \"pin\": {{\"logical_cpu\": {pin}, \"sibling_idle\": {sib}}},\n \"strata_upstream_commit\": {commit},\n \"clock_calibration\": {{\"method\": {method}, \"ghz_before\": {g0}, \"ghz_after\": {g1}, \"max_drift_fraction\": {drift}, \"slices_total\": {total}, \"slices_dropped\": {dropped}}},\n \"rows\": [\n {{\"row_type\": {rt_ns}, \"unit\": \"ns\", \"rounds\": 1, \"ours\": {on}, \"reference\": {rn}}},\n {{\"row_type\": {rt_cy}, \"unit\": \"cycles\", \"rounds\": 1, \"ours\": {oc}, \"reference\": {rc}}}\n ],\n \"aa_noise_floor\": {{\"ours_vs_ours\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"reference_vs_reference\": {{\"n\": 1, \"ci95_low\": 0, \"ci95_high\": 0}}, \"floor_fraction\": 0}},\n \"equality\": {equality}\n}}\n", + rid = jstr(&format!( + "kab1alt-{}-{}-b{}-r{round_no:05}-{}-{tree}-{}", + ctx.verified.provenance.run_id, + c.id, + ctx.batch, + kind.slug(), + regime.to_ascii_lowercase() + )), + created = jstr(&now_utc()), + started = jstr(&ctx.started_utc), + role = jstr(&ctx.machine_role), + cpu = jstr(&ctx.cpu_model), + os = jstr(&ctx.os), + kernel = jstr(&kernel), + ot = tool_json(ours_tool), + rt = tool_json(ref_tool), + cid = jstr(&c.id), + insha = jstr(&c.in_sha256), + msha = jstr(&ctx.verified.manifest_sha256), + tree_q = jstr(tree), + regime_q = jstr(®ime.to_ascii_lowercase()), + pin = ctx.pin, + sib = sibling_idle, + commit = jstr(&p.engine_strata_pin), + method = jstr(&format!( + "{CLOCK_METHOD}; ghz_before is the ghz_at_start of the earlier process of this record ({}), ghz_after the ghz_at_end of the later one ({}); sibling_idle: the SMT sibling stayed under 5 percent busy during both processes; max_drift_fraction is the largest |g1 - g0| / g0 over every slice of the two processes of this record, slices_total and slices_dropped count their requested and dropped slices", + earlier.proc.name(), + later.proc.name() + )), + g0 = jnum(earlier.ghz_start, 6), + g1 = jnum(later.ghz_end, 6), + drift = jnum(drift, 6), + total = o.requested + r.requested, + dropped = o.dropped + r.dropped, + rt_ns = jstr(&rowtype("ns")), + rt_cy = jstr(&rowtype("cycles")), + on = stat_json(&side_stat(o, false)), + rn = stat_json(&side_stat(r, false)), + oc = stat_json(&side_stat(o, true)), + rc = stat_json(&side_stat(r, true)), + ); + files.push(( + format!("r{round_no:05}.{}.{tree}.{}.json", kind.slug(), regime.to_ascii_lowercase()), + json, + )); + } + } + } + Ok(files) +} + +fn aa_equality_block(o: &Outcome) -> String { + format!( + "{{\n \"mode\": \"bitwise\",\n \"verdict\": \"{}\",\n \"compared_values\": {},\n \"mismatches\": {}\n }}", + if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, + o.compared, + o.mismatches + ) +} + +// ------------------------------------------------------------------------------------------------ alternate: the runner + +const ALT_FLAGS: [&str; 13] = [ + "run-dir", + "case", + "rounds", + "batch", + "pin", + "schedule", + "seed", + "out", + "slices", + "slice-ms", + "llc-bytes", + "machine-role", + "kab", +]; + +#[derive(Debug)] +struct AltArgs { + dir: PathBuf, + case: String, + rounds: u32, + batch: u32, + pin: usize, + schedule: PathBuf, + seed: u64, + out: Option, + slices: usize, + slice_ms: Option, + llc_bytes: Option, + machine_role: Option, + kab: Option, +} + +fn parse_alt_args(args: &[String]) -> Result { + let f = Flags::parse(args, &ALT_FLAGS)?; + let rounds = f.number::("rounds")?.ok_or("--rounds is required")?; + let batch = f.number::("batch")?.ok_or("--batch is required")?; + if !(1..=10_000).contains(&rounds) || !(1..=1000).contains(&batch) { + return Err("--rounds must be 1..10000 and --batch 1..1000 (the batch number, counted from 1)".to_owned()); + } + let case = f.req("case")?.to_owned(); + if !valid_id(&case) { + return Err(format!("--case {case:?} is not a plain identifier")); + } + let slices = f.number::("slices")?.unwrap_or(20); + if !(1..=100_000).contains(&slices) { + return Err("--slices must be 1..100000".to_owned()); + } + Ok(AltArgs { + dir: PathBuf::from(f.req("run-dir")?), + case, + rounds, + batch, + pin: f.number::("pin")?.ok_or("--pin is required")?, + schedule: PathBuf::from(f.req("schedule")?), + seed: f.number::("seed")?.unwrap_or(1), + out: f.get("out").map(PathBuf::from), + slices, + slice_ms: f.number::("slice-ms")?, + llc_bytes: f.number::("llc-bytes")?, + machine_role: f.get("machine-role").map(str::to_owned), + kab: f.get("kab").map(PathBuf::from), + }) +} + +fn create_new_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + let mut f = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| format!("{}: {e} (nothing is overwritten)", path.display()))?; + f.write_all(bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +fn file_sha(path: &Path) -> Result { + fs::read(path).map(|b| sha_hex(&b)).map_err(|e| format!("{}: {e}", path.display())) +} + +fn ours_flags() -> String { + format!( + "cargo profile {}; RUSTFLAGS={:?}; target-cpu default", + if cfg!(debug_assertions) { "dev" } else { "release" }, + std::env::var("RUSTFLAGS").unwrap_or_default() + ) +} + +fn cmd_alternate(args: &[String]) -> Result { + let a = parse_alt_args(args)?; + let started = now_utc(); + let verified = match verify_dir(&a.dir) { + Ok(v) => v, + Err(e) => { + println!("{e}"); + return Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })); + } + }; + let case = verified + .cases + .iter() + .find(|c| c.id == a.case) + .ok_or_else(|| format!("case {} is not in the manifest", a.case))? + .clone(); + let out = a.out.clone().unwrap_or_else(|| { + let name = a.dir.file_name().map_or_else(|| "kab1".to_owned(), |n| n.to_string_lossy().into_owned()); + a.dir.parent().unwrap_or(Path::new(".")).join(format!("{name}.alt-{}", a.case)) + }); + let abs = |p: &Path| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()); + if abs(&out).starts_with(abs(&a.dir)) || abs(&a.dir).starts_with(abs(&out)) { + return Err("--out must not contain or lie inside the KAB1 directory".to_owned()); + } + if inside_git_checkout(&out) || inside_git_checkout(&a.schedule) { + return Err( + "--out and --schedule must lie outside every Git checkout (generated artifacts stay out of Git)".to_owned() + ); + } + let own_exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; + let kab = a.kab.clone().or_else(|| std::env::var_os("KAB").map(PathBuf::from)).unwrap_or_else(|| { + PathBuf::from( + std::env::var("E2E_ROOT") + .unwrap_or_else(|_| format!("{}/work/leleka-e2e", std::env::var("HOME").unwrap_or_default())), + ) + .join("build/kernel-ab/kab") + }); + if !kab.is_file() { + return Err(format!( + "the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", + kab.display() + )); + } + // a host without AVX-512 has no avx512 cells (the C++ reference trees are identical by construction there) + let trees: Vec<&'static str> = + TREES.iter().copied().filter(|t| *t != "avx512" || verified.provenance.avx512_ok != Some(false)).collect(); + let procs = procs_for(&trees); + + // the schedule, written BEFORE the first run and read back: the file, not the generator, drives the batch + let first_round = (a.batch - 1) * a.rounds + 1; + let planned = make_schedule(a.seed, a.batch, a.rounds, &procs); + let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned); + fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?; + } + create_new_file(&a.schedule, text.as_bytes())?; + let schedule = + parse_schedule(&fs::read_to_string(&a.schedule).map_err(|e| format!("{}: {e}", a.schedule.display()))?)?; + println!( + "schedule written to {} (sha256 {}) before the first run: {} rounds x {} processes", + a.schedule.display(), + sha_hex(text.as_bytes()), + schedule.len(), + procs.len() + ); + let (records_dir, proc_dir) = (out.join("records"), out.join("processes")); + for d in [&records_dir, &proc_dir] { + fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?; + } + let parent_env: Vec<(OsString, OsString)> = std::env::vars_os().collect(); + let sibling_at_start = sibling_idle(a.pin); + let machine_role = a + .machine_role + .clone() + .or_else(|| std::env::var("HOSTNAME").ok()) + .or_else(|| std::env::var("COMPUTERNAME").ok()) + .unwrap_or_else(|| "unknown".to_owned()); + let (rustc_version, triple) = rustc_info(); + + // equality phase: our tree against the C++ reference .out file, per tree, in fresh processes (the kernels are not touched by timing) + let eq_dir = out.join(format!("equality-b{:04}", a.batch)); + let mut equality: BTreeMap<&'static str, Outcome> = BTreeMap::new(); + for tree in &trees { + let p = Proc { imp: Impl::Rust, tree, rep: 'a' }; + let mut cmd = scrubbed_command(&own_exe, &parent_env, &cell_env(&p)); + cmd.arg("run-tree") + .arg(&a.dir) + .args(["--tree", tree, "--case", &a.case, "--out"]) + .arg(&eq_dir) + .args(["--pin", &a.pin.to_string()]); + run_cell(&mut cmd, &format!("{}/equality", p.name()))?; + let ours_name = format!("case-{}.rust-{tree}.out", a.case); + let ours = read_out(&eq_dir.join(&ours_name), &ours_name, case.rows, tree, None).map_err(|e| e.to_string())?; + let o = case.outs.iter().find(|o| o.tree == *tree).ok_or("missing reference out")?; + let reference = read_out(&a.dir.join(&o.name), &o.name, case.rows, tree, Some((&o.sha256, o.bytes))) + .map_err(|e| e.to_string())?; + let outcome = compare_bits(&ours, &reference, case.tolerance.as_ref()); + println!( + "EQUALITY {} [{tree}] {}{}", + a.case, + if outcome.equal() { "EQUAL" } else { "NOT_EQUAL" }, + outcome.first_mismatch.map_or(format!("; {} values", outcome.compared), |(i, x, y)| format!( + "; {} of {} values differ, first at {i}: ours {x:#010x} reference {y:#010x}, max abs error {:e}", + outcome.mismatches, outcome.compared, outcome.max_abs_error + )) + ); + equality.insert(tree, outcome); + } + + let mut cpu_model = String::new(); + let batch_json = |cpu_model: String, equality: &BTreeMap<&'static str, Outcome>| -> Result { + let eq = equality + .iter() + .map(|(t, o)| { + format!( + "{{\"tree\": {}, \"verdict\": \"{}\", \"mode\": \"{}\", \"compared_values\": {}, \"mismatches\": {}}}", + jstr(t), + if o.equal() { "EQUAL" } else { "NOT_EQUAL" }, + if case.tolerance.is_some() { "tolerance" } else { "bitwise" }, + o.compared, + o.mismatches + ) + }) + .collect::>() + .join(", "); + let cells = procs + .iter() + .map(|p| format!("{{\"process\": {}, \"impl\": {}, \"tree\": {}, \"env_set\": {}, \"env_scrubbed\": \"every STRATA_* and LELEKA_* variable of the parent\"}}", jstr(&p.name()), jstr(p.imp.name()), jstr(p.tree), json_env(&cell_env(p).into_iter().collect()))) + .collect::>() + .join(", "); + Ok(format!( + "{{\n \"format\": \"KAB1-alt\",\n \"version\": 1,\n \"batch\": {},\n \"rounds\": {},\n \"first_round\": {first_round},\n \"run_started_utc\": {},\n \"case\": {},\n \"run_dir\": {},\n \"manifest_sha256\": {},\n \"input_sha256\": {},\n \"pin\": {{\"logical_cpu\": {}, \"sibling_idle_at_start\": {sibling_at_start}}},\n \"pool\": {{\"workers\": 1}},\n \"machine\": {{\"machine_role\": {}, \"cpu_model\": {}, \"os\": {}}},\n \"seed\": {},\n \"schedule\": {{\"file\": {}, \"sha256\": {}}},\n \"kab\": {{\"path\": {}, \"sha256\": {}}},\n \"rust_example\": {{\"path\": {}, \"sha256\": {}}},\n \"slices_per_regime\": {},\n \"slice_ms\": {},\n \"equality\": [{eq}],\n \"cells\": [{cells}],\n \"no_statistics\": \"this file computes no class, no interval and no A/A verdict (S0.10b, STRA-313)\"\n}}\n", + a.batch, + a.rounds, + jstr(&started), + jstr(&a.case), + jstr(&a.dir.display().to_string()), + jstr(&verified.manifest_sha256), + jstr(&case.in_sha256), + a.pin, + jstr(&machine_role), + jstr(&cpu_model), + jstr(&host_os()), + a.seed, + jstr(&a.schedule.display().to_string()), + jstr(&sha_hex(text.as_bytes())), + jstr(&kab.display().to_string()), + jstr(&file_sha(&kab)?), + jstr(&own_exe.display().to_string()), + jstr(&file_sha(&own_exe)?), + a.slices, + a.slice_ms.map_or("null".to_owned(), |m| jnum(m, 1)) + )) + }; + + let expect = + Expect { manifest_sha: &verified.manifest_sha256, input_sha: &case.in_sha256, case: &a.case, pin: a.pin }; + let mut ctx = BatchCtx { + verified: &verified, + case: &case, + pin: a.pin, + machine_role: machine_role.clone(), + os: host_os(), + cpu_model: String::new(), + started_utc: started.clone(), + rust_tool: Tool { compiler: "rustc".to_owned(), version: rustc_version, triple, flags: ours_flags() }, + batch: a.batch, + equality: &equality, + }; + let mut written = Vec::new(); + for (round_no, order) in &schedule { + let mut done: Vec = Vec::new(); + for p in order { + let name = p.name(); + let file = proc_dir.join(format!("r{round_no:05}-{name}.json")); + let mut cmd = scrubbed_command(if p.imp == Impl::Cpp { &kab } else { &own_exe }, &parent_env, &cell_env(p)); + cmd.arg("time") + .args(["--run-dir"]) + .arg(&a.dir) + .args(["--case", &a.case, "--slices", &a.slices.to_string(), "--pin", &a.pin.to_string(), "--out"]) + .arg(&file); + if let Some(ms) = a.slice_ms { + cmd.args(["--slice-ms", &ms.to_string()]); + } + if let Some(b) = a.llc_bytes { + cmd.args(["--llc-bytes", &b.to_string()]); + } + let res = run_cell(&mut cmd, &name)?; + fs::write(file.with_extension("log"), [&res.stdout[..], &res.stderr[..]].concat()) + .map_err(|e| format!("{}: {e}", file.display()))?; + let bytes = fs::read(&file) + .map_err(|e| format!("cell {name}: its output {} was not written: {e}", file.display()))?; + done.push(parse_proc_json(p, &bytes, &expect)?); + } + if cpu_model.is_empty() { + cpu_model = done.iter().find_map(|d| d.cpu_model.clone()).unwrap_or_else(|| "unknown model".to_owned()); + ctx.cpu_model = cpu_model.clone(); + create_new_file( + &out.join(format!("batch-{:04}.json", a.batch)), + batch_json(cpu_model.clone(), &equality)?.as_bytes(), + )?; + } + for (name, json) in round_records(&ctx, *round_no, &done)? { + create_new_file(&records_dir.join(&name), json.as_bytes())?; + written.push(name); + } + println!("round {round_no} done: {}", order.iter().map(Proc::name).collect::>().join(" ")); + } + println!( + "ALTERNATE OK batch={} rounds={} records={} dir={}", + a.batch, + a.rounds, + written.len(), + records_dir.display() + ); + for (t, o) in &equality { + println!("EQUALITY-SUMMARY {} {t} {}", a.case, if o.equal() { "EQUAL" } else { "NOT_EQUAL" }); + } + Ok(ExitCode::SUCCESS) +} + +// ------------------------------------------------------------------------------------------------ main + +fn usage() -> ExitCode { + eprintln!( + "usage: kernel_ab verify D | compare D [--out R] [--pin CPU] [--machine-role NAME] [--trees avx512,avx2] | run-tree D --tree T --out R [--pin CPU] [--case ID]" + ); + eprintln!( + " kernel_ab time --run-dir D --case ID --slices N --pin CPU --out F.json [--slice-ms 60] [--regime both|resident|streamed] [--llc-bytes B]" + ); + eprintln!( + " kernel_ab alternate --run-dir D --case ID --rounds N --batch K --pin CPU --schedule FILE [--seed S] [--out R] [--slices N] [--slice-ms MS] [--llc-bytes B] [--machine-role NAME] [--kab PATH]" + ); + ExitCode::from(64) +} + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + // `time` and `alternate` take flags only (the command line of `kab time`); the older commands take the directory first + if let Some(cmd @ ("time" | "alternate")) = args.first().map(String::as_str) { + let result = if cmd == "time" { cmd_time(&args[1..]) } else { cmd_alternate(&args[1..]) }; + return result.unwrap_or_else(|e| { + eprintln!("kernel_ab {cmd}: {e}"); + ExitCode::from(1) + }); + } + let (Some(cmd), Some(dir)) = (args.first(), args.get(1)) else { return usage() }; + let dir = Path::new(dir); + let opts = match parse_options(&args[2..]) { + Ok(o) => o, + Err(e) => { + eprintln!("kernel_ab: {e}"); + return usage(); + } + }; + let result = match cmd.as_str() { + "verify" => match verify_dir(dir) { + Ok(v) => { + println!("OK {} files (manifest sha256 {})", v.file_count, v.manifest_sha256); + Ok(ExitCode::SUCCESS) + } + Err(e) => { + println!("{e}"); + Ok(ExitCode::from(if e.incomplete { 2 } else { 1 })) + } + }, + "compare" => cmd_compare(dir, &opts), + "run-tree" => match (&opts.tree, &opts.out) { + (Some(t), Some(o)) => cmd_run_tree(dir, t, o, opts.pin, opts.case.as_deref()), + _ => return usage(), + }, + _ => return usage(), + }; + result.unwrap_or_else(|e| { + eprintln!("kernel_ab: {e}"); + ExitCode::from(1) + }) +} + +// ------------------------------------------------------------------------------------------------ tests + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static COUNTER: AtomicUsize = AtomicUsize::new(0); + + struct TempDir(PathBuf); + impl TempDir { + fn new() -> Self { + let p = std::env::temp_dir().join(format!( + "kab1-test-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + fs::create_dir_all(&p).unwrap(); + Self(p) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn block_filled(len: usize, block: usize, seed: u8) -> Vec { + let mut v: Vec = (0..len).map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)).collect(); + for at in (0..len).step_by(block) { + v[at] = 0x00; + v[at + 1] = 0x3c; // FP16 1.0 + } + v + } + + fn in_file(gu: i32, down: i32, rows: usize) -> Vec { + let (gq, gb) = (gate_up_row(gu).unwrap().2, gate_up_row(gu).unwrap().3); + let (dq, db) = (down_row(down).unwrap().2, down_row(down).unwrap().3); + let (gsize, dsize) = (H / gq * gb * FF, FF / dq * db * H); + let mut b = Vec::new(); + for w in [ + IN_MAGIC, + 1, + gu as u32, + down as u32, + rows as u32, + H as u32, + FF as u32, + gsize as u32, + gsize as u32, + dsize as u32, + ] { + b.extend_from_slice(&w.to_le_bytes()); + } + b.resize(IN_HEADER, 0); + b.extend(block_filled(gsize, gb, 1)); + b.extend(block_filled(gsize, gb, 2)); + b.extend(block_filled(dsize, db, 3)); + for i in 0..rows * H { + b.extend_from_slice(&(((i % 97) as f32 - 48.0) / 16.0).to_bits().to_le_bytes()); + } + b + } + + fn out_file(rows: usize, tree: u32) -> Vec { + let mut b = Vec::new(); + for w in [OUT_MAGIC, 1, rows as u32, H as u32, tree] { + b.extend_from_slice(&w.to_le_bytes()); + } + for i in 0..rows * H { + b.extend_from_slice(&((i as f32) * 0.25).to_bits().to_le_bytes()); + } + b + } + + struct Spec { + gu: i32, + down: i32, + rows: usize, + tolerance: Option<&'static str>, + } + + /// Builds a synthetic KAB1 directory; `mutate` edits the `.in` bytes before the manifest records their hash. + fn build(dir: &Path, specs: &[Spec], mutate: impl Fn(&mut Vec)) { + let mut cases = Vec::new(); + let mut files = Vec::new(); + for s in specs { + let id = format!("{}-{}-r{}", s.gu, s.down, s.rows); + let mut inb = in_file(s.gu, s.down, s.rows); + mutate(&mut inb); + fs::write(dir.join(format!("case-{id}.in")), &inb).unwrap(); + let mut entry = format!( + "{{\"id\": \"{id}\", \"gu_type\": {}, \"down_type\": {}, \"rows\": {}, \"seed\": 18446744073709551615, \"equality\": \"{}\", \"tolerance\": {}, \"in\": \"case-{id}.in\", \"in_sha256\": \"{}\", \"in_bytes\": {}", + s.gu, + s.down, + s.rows, + if s.tolerance.is_some() { "tolerance" } else { "bitwise" }, + s.tolerance.unwrap_or("null"), + sha_hex(&inb), + inb.len() + ); + files.push(format!("\"case-{id}.in\": {{\"sha256\": \"{}\", \"bytes\": {}}}", sha_hex(&inb), inb.len())); + for (k, tree) in TREES.iter().enumerate() { + let ob = out_file(s.rows, k as u32); + fs::write(dir.join(format!("case-{id}.cpp-{tree}.out")), &ob).unwrap(); + entry += &format!( + ", \"out_cpp_{tree}\": \"case-{id}.cpp-{tree}.out\", \"out_cpp_{tree}_sha256\": \"{}\", \"out_cpp_{tree}_bytes\": {}", + sha_hex(&ob), + ob.len() + ); + files.push(format!( + "\"case-{id}.cpp-{tree}.out\": {{\"sha256\": \"{}\", \"bytes\": {}}}", + sha_hex(&ob), + ob.len() + )); + } + cases.push(entry + "}"); + } + let manifest = format!( + "{{\"format\": \"KAB1\", \"version\": 1, \"run_id\": \"synthetic\", \"writer\": \"cpp\", \"provenance\": {{\"engine_strata_pin\": \"41cf05a06a25dd29103b7b27a2279a3f60c21876\", \"compiler_id\": \"GNU\", \"compiler_version\": \"15.2.0\", \"target_triple\": \"x86_64-linux-gnu\", \"built_at_utc\": \"2026-10-28T19:05:05Z\", \"avx512_ok\": true, \"flags\": {{\"strata_cxx_flags\": \"-O3 -DNDEBUG\", \"ggml_cpu_arch_flags\": \"-march=native\"}}}}, \"cases\": [{}], \"files\": {{{}}}}}", + cases.join(", "), + files.join(", ") + ); + fs::write(dir.join("manifest.json"), manifest).unwrap(); + } + + fn two_cases() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 2, tolerance: None }, Spec { gu: 18, down: 20, rows: 1, tolerance: None }] + } + + fn one_case() -> Vec { + vec![Spec { gu: 42, down: 42, rows: 1, tolerance: None }] + } + + fn id(file: &str) -> String { + format!("case-42-42-r1.{file}") + } + + #[test] + fn a_good_directory_verifies() { + let t = TempDir::new(); + build(&t.0, &two_cases(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases.len(), 2); + assert_eq!(v.file_count, 2 * 3 + 1); + assert_eq!(v.manifest_sha256.len(), 64); + assert_eq!(v.cases[0].in_sha256, sha_hex(&fs::read(t.0.join("case-42-42-r2.in")).unwrap())); + } + + #[test] + fn a_flipped_byte_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("in")); + let mut b = fs::read(&p).unwrap(); + b[IN_HEADER + 7] ^= 0x40; + fs::write(&p, b).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("sha256"), "{e}"); + } + + #[test] + fn a_truncated_file_refuses_the_directory_and_names_the_file() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let p = t.0.join(id("cpp-avx2.out")); + let b = fs::read(&p).unwrap(); + fs::write(&p, &b[..b.len() - 4]).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.cpp-avx2.out"); + assert!(e.reason.contains("length"), "{e}"); + } + + #[test] + fn a_wrong_magic_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[0] ^= 0xff); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("magic"), "{e}"); + } + + #[test] + fn a_wrong_version_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[4] = 2); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("version"), "{e}"); + } + + #[test] + fn a_byte_count_that_disagrees_with_the_format_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let wrong = (le32(b, 28) + 18).to_le_bytes(); + b[28..32].copy_from_slice(&wrong); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("format-derived"), "{e}"); + } + + #[test] + fn a_non_finite_fp16_header_is_refused() { + let t = TempDir::new(); + // the manifest records the hash of the mutated file, so only the FP16 rule can refuse it + build(&t.0, &one_case(), |b| { + let at = IN_HEADER + 18 * 3; + b[at] = 0x00; + b[at + 1] = 0x7c; // FP16 +inf + }); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "case-42-42-r1.in"); + assert!(e.reason.contains("non-finite FP16"), "{e}"); + } + + #[test] + fn a_non_finite_activation_is_refused() { + let t = TempDir::new(); + build(&t.0, &one_case(), |b| { + let at = b.len() - 4; + b[at..].copy_from_slice(&f32::NAN.to_bits().to_le_bytes()); + }); + let e = verify_dir(&t.0).unwrap_err(); + assert!(e.reason.contains("non-finite activation"), "{e}"); + } + + #[test] + fn a_missing_manifest_is_incomplete_and_named() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::remove_file(t.0.join("manifest.json")).unwrap(); + let e = verify_dir(&t.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.incomplete); + assert!(e.to_string().contains("manifest.json")); + } + + #[test] + fn an_extra_or_missing_file_refuses_the_directory() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + fs::write(t.0.join("stray.txt"), b"x").unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "stray.txt"); + fs::remove_file(t.0.join("stray.txt")).unwrap(); + fs::remove_file(t.0.join(id("cpp-avx512.out"))).unwrap(); + assert_eq!(verify_dir(&t.0).unwrap_err().file, "case-42-42-r1.cpp-avx512.out"); + } + + #[test] + fn an_absurd_length_is_refused_without_taking_a_buffer() { + // header says gate_bytes = 4 GiB - 16; the pure header check refuses it before any buffer exists + let mut h = [0u8; IN_HEADER]; + h.copy_from_slice(&in_file(42, 42, 1)[..IN_HEADER]); + h[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes()); + BUFFERS.with(|c| c.set(0)); + assert!(validate_in_header(&h, 1 << 20).unwrap_err().contains("format-derived")); + assert_eq!(BUFFERS.with(Cell::get), 0); + // and through the file reader: manifest and file agree on a file whose header lies about its size + let t = TempDir::new(); + build(&t.0, &one_case(), |b| b[28..32].copy_from_slice(&(u32::MAX - 15).to_le_bytes())); + BUFFERS.with(|c| c.set(0)); + let (m, _) = (fs::read(t.0.join("manifest.json")).unwrap(), 0); + let (_, cases, _) = parse_manifest(&parse_json(&m).unwrap()).unwrap(); + let e = read_case_in(&t.0, &cases[0]).err().unwrap(); + assert!(e.reason.contains("format-derived"), "{e}"); + assert_eq!(BUFFERS.with(Cell::get), 0, "a buffer was taken before the header was validated"); + // a manifest that declares an absurd length for a file is refused before a buffer too + let mut lying = cases[0].clone(); + lying.in_bytes = u64::MAX; + assert!(read_case_in(&t.0, &lying).unwrap_err().reason.contains("differs from the manifest")); + assert_eq!(BUFFERS.with(Cell::get), 0); + // the good path takes exactly one buffer per file + let g = TempDir::new(); + build(&g.0, &one_case(), |_| {}); + BUFFERS.with(|c| c.set(0)); + let (_, cases, _) = + parse_manifest(&parse_json(&fs::read(g.0.join("manifest.json")).unwrap()).unwrap()).unwrap(); + read_case_in(&g.0, &cases[0]).unwrap(); + assert_eq!(BUFFERS.with(Cell::get), 1); + } + + #[test] + fn a_tolerance_needs_basis_metric_and_a_time_before_the_reference_run() { + let ok = "{\"value\": 0.003, \"metric\": \"max_abs_error_over_max_abs_reference\", \"basis\": \"order-only difference\", \"basis_written_utc\": \"2026-10-28T10:00:00Z\"}"; + let t = TempDir::new(); + build(&t.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(ok) }], |_| {}); + let v = verify_dir(&t.0).unwrap(); + assert_eq!(v.cases[0].tolerance.as_ref().unwrap().value, 0.003); + for (bad, why) in [ + (ok.replace("0.003", "0"), "positive"), + (ok.replace("max_abs_error_over_max_abs_reference", "ulp"), "metric"), + (ok.replace("order-only difference", " "), "basis"), + (ok.replace("2026-10-28T10:00:00Z", "2026-10-28T20:00:00Z"), "after the reference run"), + ] { + let leaked: &'static str = Box::leak(bad.into_boxed_str()); + let d = TempDir::new(); + build(&d.0, &[Spec { gu: 42, down: 42, rows: 1, tolerance: Some(leaked) }], |_| {}); + let e = verify_dir(&d.0).unwrap_err(); + assert_eq!(e.file, "manifest.json"); + assert!(e.reason.contains(why), "{why}: {e}"); + } + } + + #[test] + fn the_json_reader_handles_the_manifest_forms_and_refuses_the_rest() { + let j = parse_json(b"{\"a\": [1, -2.5e3, true, null, \"x\\n\\u00e9\\ud83d\\ude00\"], \"b\": {}}").unwrap(); + assert_eq!( + j.get("a"), + Some(&Json::Arr(vec![ + Json::Num("1".into()), + Json::Num("-2.5e3".into()), + Json::Bool(true), + Json::Null, + Json::Str("x\n\u{e9}\u{1f600}".into()) + ])) + ); + assert_eq!(parse_json(b"{\"s\": 18446744073709551615}").unwrap().uint("s").unwrap(), u64::MAX); + for bad in [ + "{\"a\": 1, \"a\": 2}", + "{\"a\": 1,}", + "[1 2]", + "{\"a\": \"\\ud800\"}", + "{} x", + "", + "{\"a\": 01x}", + "\"\u{1}\"", + ] { + assert!(parse_json(bad.as_bytes()).is_err(), "{bad}"); + } + assert!(parse_json("[".repeat(40).as_bytes()).is_err()); + } + + #[test] + fn bitwise_compare_sees_signed_zero_and_one_ulp_and_tolerance_is_normalised() { + let a = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits()]; + assert!(compare_bits(&a, &a, None).equal()); + let neg0 = [1.0f32.to_bits(), (-0.0f32).to_bits(), 2.0f32.to_bits()]; + let o = compare_bits(&neg0, &a, None); + assert_eq!((o.mismatches, o.first_mismatch), (1, Some((1, (-0.0f32).to_bits(), 0.0f32.to_bits())))); + let ulp = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.0f32.to_bits() + 1]; + assert_eq!(compare_bits(&ulp, &a, None).mismatches, 1); + let tol = Tolerance { value: 1e-6, basis: "test".into(), basis_written_utc: "2026-01-01T00:00:00Z".into() }; + assert!(compare_bits(&ulp, &a, Some(&tol)).equal()); + let far = [1.0f32.to_bits(), 0.0f32.to_bits(), 2.1f32.to_bits()]; + assert_eq!(compare_bits(&far, &a, Some(&tol)).mismatches, 1); + assert_eq!(compare_bits(&a[..2], &a, None).mismatches, 1); + } + + #[test] + fn our_trees_run_on_a_verified_synthetic_case_and_the_record_is_well_formed() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let case = read_case_in(&v.dir, &v.cases[0]).unwrap(); + let mut pool = DirectCpuPool::new(1).unwrap(); + let first = compute_case(&mut pool, &case).unwrap(); + let second = compute_case(&mut pool, &case).unwrap(); + assert_eq!(first.len(), H); + assert!( + first.iter().zip(&second).all(|(a, b)| a.to_bits() == b.to_bits()), + "the same case twice must be bit-identical" + ); + let path = t.0.join("ours.rust-avx2.out"); + write_out(&path, 1, "avx2", &first).unwrap(); + let back = read_out(&path, "ours.rust-avx2.out", 1, "avx2", None).unwrap(); + assert_eq!(back, first.iter().map(|v| v.to_bits()).collect::>()); + let outcome = compare_bits(&back, &back, None); + let json = record_json(&RecordInput { + record_id: "kab1-synthetic-r".into(), + created_utc: "2026-10-28T20:00:00Z".into(), + run_started_utc: "2026-10-28T19:59:00Z".into(), + machine_role: "m\"1".into(), + cpu_model: "cpu".into(), + os: "os".into(), + ours_compiler: "rustc".into(), + ours_version: "rustc 1.99.0".into(), + ours_triple: "x86_64-unknown-linux-gnu".into(), + ours_flags: "f".into(), + tree: "avx2", + verified: &v, + case: &v.cases[0], + pin_cpu: 0, + sibling_idle: true, + outcome: &outcome, + }); + let rec = parse_json(json.as_bytes()).unwrap(); + for key in [ + "schema_version", + "level", + "record_id", + "created_utc", + "run_started_utc", + "machine", + "kernel", + "toolchain", + "case_id", + "input_sha256", + "kab1_manifest_sha256", + "tree", + "regime", + "pin", + "strata_upstream_commit", + "clock_calibration", + "rows", + "aa_noise_floor", + "equality", + ] { + assert!(rec.get(key).is_some(), "{key}"); + } + assert_eq!(rec.req("equality").unwrap().str("verdict").unwrap(), "EQUAL"); + assert_eq!(rec.req("machine").unwrap().str("machine_role").unwrap(), "m\"1"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); + } + + // ---------------------------------------------------------------------------------------------------- alternation (STRA-318) + + #[test] + fn the_schedule_is_reproducible_from_the_seed() { + let procs = procs_for(&TREES); + let a = make_schedule(7, 1, 30, &procs); + assert_eq!(a, make_schedule(7, 1, 30, &procs)); + assert_ne!(a, make_schedule(8, 1, 30, &procs), "another seed gives another schedule"); + assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule"); + assert_eq!(a.len(), 30); + // the text round-trips through the file format and names the seed + let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a); + assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9")); + let back = parse_schedule(&text).unwrap(); + assert_eq!(back.iter().map(|r| r.1.clone()).collect::>(), a); + assert_eq!(back[0].0, 1); + assert_eq!(back[29].0, 30); + } + + #[test] + fn the_rotation_gives_every_process_every_position_within_a_block() { + let procs = procs_for(&TREES); + assert_eq!(procs.len(), 8); + let s = make_schedule(3, 1, 16, &procs); + for block in s.chunks(8) { + for round in block { + let mut names: Vec<_> = round.iter().map(Proc::name).collect(); + names.sort(); + assert_eq!(names.len(), 8); + names.dedup(); + assert_eq!(names.len(), 8, "every process exactly once per round"); + } + for pos in 0..8 { + let at: BTreeSet<_> = block.iter().map(|r| r[pos]).collect(); + assert_eq!(at.len(), 8, "position {pos} is taken by every process once per block of 8 rounds"); + } + } + // a host without AVX-512 has only the avx2 cells + assert_eq!(procs_for(&["avx2"]).len(), 4); + } + + #[test] + fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() { + let t = TempDir::new(); + let f = t.0.join("schedule.tsv"); + create_new_file(&f, b"x").unwrap(); + assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten")); + assert_eq!(fs::read(&f).unwrap(), b"x"); + let procs = procs_for(&TREES); + let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs)); + assert!(parse_schedule(&good).is_ok()); + assert!(parse_schedule("nope").is_err()); + assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process")); + assert!(parse_schedule(&good.replacen("\n2\t", "\n5\t", 1)).unwrap_err().contains("does not follow")); + // a round that names one process twice (and so lacks another) is refused + let dup = good + .lines() + .map(|l| { + if l.starts_with("2\t") { + l.replacen("rust-avx2-b", "rust-avx2-a", 1).replacen("rust-avx2-b", "rust-avx2-a", 1) + } else { + l.to_owned() + } + }) + .collect::>() + .join("\n"); + assert!(parse_schedule(&dup).is_err()); + } + + /// The child side of the environment test: prints the managed variables it sees. Does nothing in a normal run. + #[test] + fn env_probe_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() != Some(std::ffi::OsStr::new("probe")) { + return; + } + for (k, v) in std::env::vars() { + if is_managed_name(&k) { + println!("PROBE {k}={v}"); + } + } + } + + /// The child side of the failure test. + #[test] + fn failing_child() { + if std::env::var_os("KAB_TEST_CHILD").as_deref() == Some(std::ffi::OsStr::new("fail")) { + eprintln!("simulated kernel failure"); + std::process::exit(3); + } + } + + fn child(test: &str, mode: &str, planted: &[(&str, &str)], cell: &[(String, String)]) -> Command { + let mut parent: Vec<(OsString, OsString)> = + std::env::vars_os().filter(|(k, _)| !is_managed_name(&k.to_string_lossy())).collect(); + parent.push(("KAB_TEST_CHILD".into(), mode.into())); + parent.extend(planted.iter().map(|(k, v)| ((*k).into(), (*v).into()))); + let mut c = scrubbed_command(&std::env::current_exe().unwrap(), &parent, cell); + c.args(["--exact", test, "--nocapture", "--test-threads=1"]); + c + } + + #[test] + fn environment_scrubbing_removes_a_planted_strata_variable_and_keeps_only_the_cell() { + let cell = cell_env(&Proc { imp: Impl::Rust, tree: "avx2", rep: 'a' }); + assert_eq!( + cell, + vec![ + ("LELEKA_CPU_POOL_PIN_HOST".to_owned(), "off".to_owned()), + ("STRATA_FORCE_AVX2".to_owned(), "1".to_owned()), + ("STRATA_POOL_SPIN_US".to_owned(), "0".to_owned()) + ] + ); + assert!(cell_env(&Proc { imp: Impl::Cpp, tree: "avx512", rep: 'b' }).is_empty()); + let out = run_cell( + &mut child( + "tests::env_probe_child", + "probe", + &[("STRATA_X", "planted"), ("LELEKA_Y", "planted"), ("strata_lower", "planted")], + &cell, + ), + "rust-avx2-a", + ) + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + // libtest prints "test ... " before the child's own output on the same line + let mut probes: Vec<&str> = text.lines().flat_map(|l| l.split("PROBE ").skip(1)).collect(); + probes.sort_unstable(); + assert_eq!( + probes, + vec!["LELEKA_CPU_POOL_PIN_HOST=off", "STRATA_FORCE_AVX2=1", "STRATA_POOL_SPIN_US=0"], + "only the cell's variables survive:\n{text}" + ); + // the cpp avx512 cell sets nothing at all + let out = + run_cell(&mut child("tests::env_probe_child", "probe", &[("STRATA_X", "planted")], &[]), "cpp-avx512-a") + .unwrap(); + assert!(!String::from_utf8_lossy(&out.stdout).contains("PROBE ")); + } + + #[test] + fn a_child_failure_is_reported_with_the_cell_named() { + let e = run_cell(&mut child("tests::failing_child", "fail", &[], &[]), "cpp-avx2-b").unwrap_err(); + assert!(e.starts_with("cell cpp-avx2-b failed (exit 3)"), "{e}"); + assert!(e.contains("simulated kernel failure"), "{e}"); + let e = run_cell(&mut Command::new("kab-does-not-exist-318"), "rust-avx512-a").unwrap_err(); + assert!(e.starts_with("cell rust-avx512-a: cannot start"), "{e}"); + } + + #[test] + fn the_time_command_line_is_the_one_of_kab_time() { + let v = |a: &[&str]| a.iter().map(|s| (*s).to_owned()).collect::>(); + let t = parse_time_args(&v(&[ + "--run-dir", + "D", + "--case", + "18-20-r1", + "--slices", + "50", + "--pin", + "9", + "--out", + "t.json", + ])) + .unwrap(); + assert_eq!((t.slices, t.pin, t.slice_ms, t.regime, t.llc_bytes), (50, 9, 60.0, RegimeSel::Both, None)); + let t = parse_time_args(&v(&[ + "--run-dir", + "D", + "--case", + "c", + "--slices", + "2", + "--pin", + "0", + "--out", + "o", + "--slice-ms", + "5", + "--regime", + "streamed", + "--llc-bytes", + "1000", + ])) + .unwrap(); + assert_eq!((t.slice_ms, t.regime, t.llc_bytes), (5.0, RegimeSel::Streamed, Some(1000))); + for bad in [ + v(&["--run-dir", "D", "--case", "c", "--slices", "0", "--pin", "0", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--regime", "both2"]), + v(&["--run-dir", "D", "--case", "../c", "--slices", "1", "--pin", "0", "--out", "o"]), + v(&["--run-dir", "D", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o", "--bogus", "1"]), + v(&["--run-dir", "D", "--run-dir", "E", "--case", "c", "--slices", "1", "--pin", "0", "--out", "o"]), + ] { + assert!(parse_time_args(&bad).is_err(), "{bad:?}"); + } + let a = parse_alt_args(&v(&[ + "--run-dir", + "D", + "--case", + "c", + "--rounds", + "30", + "--batch", + "1", + "--pin", + "9", + "--schedule", + "s.tsv", + ])) + .unwrap(); + assert_eq!((a.rounds, a.batch, a.seed, a.slices), (30, 1, 1, 20)); + assert!( + parse_alt_args(&v(&[ + "--run-dir", + "D", + "--case", + "c", + "--rounds", + "30", + "--batch", + "0", + "--pin", + "9", + "--schedule", + "s" + ])) + .is_err() + ); + } + + #[test] + fn medians_percentiles_and_parsers_agree_with_the_reference_rules() { + assert_eq!(median_of(&[3.0, 1.0, 2.0, 10.0]), 3.0, "sorted, element size/2 as the C++ reference"); + assert_eq!(median_of(&[]), 0.0); + let v: Vec = (1..=21).map(f64::from).collect(); + assert_eq!((percentile_of(&v, 0.05), percentile_of(&v, 0.95)), (2.0, 20.0)); + assert_eq!(parse_cpu_list("2,18"), vec![2, 18]); + assert_eq!(parse_cpu_list("0-3,8"), vec![0, 1, 2, 3, 8]); + assert_eq!((parse_size("32768K"), parse_size("32M"), parse_size("512")), (32 << 20, 32 << 20, 512)); + assert_eq!(busy_fraction(Some((10, 100)), Some((30, 200))), Some(0.2)); + assert_eq!(busy_fraction(None, Some((1, 1))), None); + // the calibrated clock of any x86-64 core is in this range (the chain must not be folded away: 175 GHz was the folded multiply chain) + let ghz = core_ghz(); + assert!((0.3..12.0).contains(&ghz), "{ghz}"); + } + + #[test] + fn an_output_inside_a_git_checkout_is_detected() { + let t = TempDir::new(); + let inner = t.0.join("a/b"); + fs::create_dir_all(&inner).unwrap(); + assert!(!inside_git_checkout(&inner)); + fs::create_dir_all(t.0.join(".git")).unwrap(); + assert!(inside_git_checkout(&inner)); + assert!(inside_git_checkout(&t.0.join("not/yet/created/schedule.tsv"))); + } + + fn json_regime(label: &str, k: usize, self_key: &str) -> String { + let slice = |g1: f64| { + format!( + "{{\"i\": 0, \"calls\": 10, \"wall_ns\": 100, \"ns_per_call\": 10.0, \"ghz_before\": 5.0, \"ghz_after\": {g1}, \"cycles_per_call\": 50.0}}" + ) + }; + format!( + "{{\"regime\": \"{label}\", \"copies_k\": {k}, \"expert_bytes\": 1000, \"llc_bytes\": 500, \"slices_requested\": 3, \"slices_kept\": 2, \"dropped_count\": 1, \"{self_key}\": true, \"median_ns_per_call\": 10.0, \"median_cycles_per_call\": 50.0, \"slices\": [{}, {}], \"dropped\": [{}]}}", + slice(5.0), + slice(5.1), + slice(4.0) + ) + } + + /// A process JSON as the C++ writer (`imp` cpp) or this example (rust) writes it, with `env` as its effective environment. + fn proc_fixture(p: &Proc, env: &str) -> String { + let (self_key, detail) = if p.imp == Impl::Cpp { + ("selfcheck_bitwise_equal_compose_expert", "{\"tree\": \"avx512\", \"avx2_ok\": true, \"avx512_ok\": true, \"iq512_gather_on\": false, \"iq256_gather_setting\": -1, \"strata_env\": {}}".to_owned()) + } else { + ( + "selfcheck_bitwise_equal_first_call", + format!( + "{{\"tree\": \"{}\", \"cpu_report\": [\"cpu: logical 16 (8 physical): Test CPU; x\", \"cpu: process kernel family AVX-512 (test)\"], \"strata_env\": {{}}}}", + p.tree + ), + ) + }; + format!( + "{{\"format\": \"KAB1-time\", \"version\": 1, \"writer\": \"{}\", \"manifest_sha256\": \"m\", \"case\": {{\"id\": \"c\", \"input_sha256\": \"i\"}}, \"tree\": \"{}\", \"tree_detail\": {detail}, \"effective_env\": {env}, \"pin\": {{\"cpu\": 9, \"sibling_cpu\": 25, \"sibling_busy_fraction_during_run\": 0.01}}, \"clock_calibration\": {{\"ghz_at_start\": 5.0, \"ghz_at_end\": 5.1}}, \"final_output_unchanged\": true, \"output_sha256\": \"{}\", \"regimes\": [{}, {}]}}", + p.imp.name(), + p.tree, + "cd".repeat(32), + json_regime("RESIDENT", 1, self_key), + json_regime("STREAMED", 3, self_key) + ) + } + + #[test] + fn a_process_json_is_checked_against_the_cell_that_was_started() { + let expect = Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 9 }; + for p in [Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }, Proc { imp: Impl::Rust, tree: "avx512", rep: 'b' }] { + let env = json_env(&cell_env(&p).into_iter().collect()); + let ok = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &expect).unwrap(); + assert_eq!(ok.regimes.len(), 2); + let r = &ok.regimes["STREAMED"]; + assert_eq!((r.copies_k, r.ns.len(), r.dropped, r.requested), (3, 2, 1, 3)); + assert!( + (r.max_drift - 0.2).abs() < 1e-9, + "the dropped slice's 20 percent drift is the maximum: {}", + r.max_drift + ); + assert_eq!(ok.sibling_idle, Some(true)); + // the environment the process saw must be exactly the cell's + let planted = json_env(&BTreeMap::from([("STRATA_X".to_owned(), "1".to_owned())])); + let e = parse_proc_json(&p, proc_fixture(&p, &planted).as_bytes(), &expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}: effective environment", p.name())), "{e}"); + // wrong pin, wrong manifest, wrong input, wrong writer: each names the cell + for (bad_expect, what) in [ + (Expect { manifest_sha: "m", input_sha: "i", case: "c", pin: 8 }, "pinned to CPU"), + (Expect { manifest_sha: "other", input_sha: "i", case: "c", pin: 9 }, "manifest_sha256"), + (Expect { manifest_sha: "m", input_sha: "x", case: "c", pin: 9 }, "input hash"), + ] { + let e = parse_proc_json(&p, proc_fixture(&p, &env).as_bytes(), &bad_expect).unwrap_err(); + assert!(e.starts_with(&format!("cell {}:", p.name())) && e.contains(what), "{e}"); + } + let other = Proc { imp: if p.imp == Impl::Cpp { Impl::Rust } else { Impl::Cpp }, ..p }; + assert!( + parse_proc_json(&other, proc_fixture(&p, &env).as_bytes(), &expect).unwrap_err().contains("writer") + ); + } + } + + fn fake_proc(p: Proc, base: f64) -> ProcOut { + let regime = |k: usize| RegimeStat { + copies_k: k, + expert_bytes: 1_000_000, + llc_bytes: 1_000, + requested: 10, + dropped: 1, + median_ns: base, + median_cycles: base * 5.0, + ns: vec![base * 0.9, base, base * 1.1], + cycles: vec![base * 4.5, base * 5.0, base * 5.5], + max_drift: 0.01, + selfcheck: true, + }; + ProcOut { + proc: p, + regimes: BTreeMap::from([("RESIDENT".to_owned(), regime(1)), ("STREAMED".to_owned(), regime(3))]), + ghz_start: 5.0, + ghz_end: 5.1, + sibling_idle: Some(true), + final_unchanged: true, + output_sha: Some("ab".repeat(32)), + tree_text: format!("tree text of {}", p.name()), + cpu_model: Some("Test CPU".to_owned()), + } + } + + #[test] + fn round_records_have_the_schema_shape_and_keep_not_equal() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let v = verify_dir(&t.0).unwrap(); + let outcome = |bad: usize| Outcome { + compared: H, + mismatches: bad, + differing_bits: bad, + max_abs_error: 0.0, + first_mismatch: None, + }; + let equality = BTreeMap::from([("avx512", outcome(0)), ("avx2", outcome(1835))]); + let ctx = BatchCtx { + verified: &v, + case: &v.cases[0], + pin: 9, + machine_role: "m".into(), + os: "os".into(), + cpu_model: "cpu".into(), + started_utc: "2026-10-28T20:00:00Z".into(), + rust_tool: Tool { + compiler: "rustc".into(), + version: "rustc 1.99.0".into(), + triple: "x86_64-unknown-linux-gnu".into(), + flags: "f".into(), + }, + batch: 2, + equality: &equality, + }; + let mut done: Vec = + procs_for(&TREES).into_iter().enumerate().map(|(i, p)| fake_proc(p, 100.0 + i as f64)).collect(); + done.reverse(); // the order of execution does not matter to the records + done.iter_mut().find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'b' }).unwrap().sibling_idle = + Some(false); + let files = round_records(&ctx, 31, &done).unwrap(); + assert_eq!(files.len(), 12, "2 trees x 2 regimes x (A/B + A/A cpp + A/A rust)"); + let names: BTreeSet<_> = files.iter().map(|f| f.0.as_str()).collect(); + assert_eq!(names.len(), 12); + assert!( + names.contains("r00031.ab.avx2.streamed.json") + && names.contains("r00031.aa-cpp.avx512.resident.json") + && names.contains("r00031.aa-rust.avx2.resident.json") + ); + for (name, json) in &files { + let rec = parse_json(json.as_bytes()).unwrap_or_else(|e| panic!("{name}: {e}")); + for key in [ + "schema_version", + "level", + "record_id", + "created_utc", + "run_started_utc", + "machine", + "kernel", + "toolchain", + "case_id", + "input_sha256", + "kab1_manifest_sha256", + "tree", + "regime", + "pin", + "strata_upstream_commit", + "clock_calibration", + "rows", + "aa_noise_floor", + "equality", + ] { + assert!(rec.get(key).is_some(), "{name}: {key}"); + } + assert_eq!(rec.str("level").unwrap(), "COMPONENT_KERNEL"); + assert_eq!(rec.str("kab1_manifest_sha256").unwrap(), v.manifest_sha256); + assert_eq!(rec.str("input_sha256").unwrap(), v.cases[0].in_sha256); + let Some(Json::Arr(rows)) = rec.get("rows") else { panic!("rows") }; + let units: Vec<_> = rows.iter().map(|r| r.str("unit").unwrap().to_owned()).collect(); + assert_eq!(units, ["ns", "cycles"]); + assert_ne!(rows[0].str("row_type").unwrap(), rows[1].str("row_type").unwrap(), "no repeated row type"); + let regime = rec.str("regime").unwrap(); + assert_eq!(rec.get("streamed").is_some(), regime == "streamed", "{name}"); + assert!(rec.str("kernel").unwrap().contains("PLACEHOLDER")); + let eq = rec.req("equality").unwrap(); + let tree = rec.req("tree").unwrap().str("ours").unwrap(); + let want = if name.contains(".ab.") && tree == "avx2" { "NOT_EQUAL" } else { "EQUAL" }; + assert_eq!(eq.str("verdict").unwrap(), want, "{name}"); + if want == "NOT_EQUAL" { + assert_eq!(eq.uint("mismatches").unwrap(), 1835, "the A/B mismatch count is carried, not hidden"); + } + } + // the A/B record puts Rust in the ours slot and C++ in the reference slot; the A/A records use one implementation on both + let ab = + parse_json(files.iter().find(|f| f.0 == "r00031.ab.avx512.resident.json").unwrap().1.as_bytes()).unwrap(); + assert!( + ab.str("kernel").unwrap().contains("ours-slot process rust-avx512-a, reference-slot process cpp-avx512-a") + ); + assert_eq!(ab.req("toolchain").unwrap().req("ours").unwrap().str("compiler").unwrap(), "rustc"); + let aa = parse_json(files.iter().find(|f| f.0 == "r00031.aa-cpp.avx512.resident.json").unwrap().1.as_bytes()) + .unwrap(); + assert!( + aa.str("kernel").unwrap().contains("ours-slot process cpp-avx512-a, reference-slot process cpp-avx512-b") + ); + assert_eq!(aa.req("equality").unwrap().str("mode").unwrap(), "bitwise"); + // sibling_idle belongs to the two processes of a record: only the A/A cpp avx2 records see the busy sibling of cpp-avx2-b + for (name, json) in &files { + let rec = parse_json(json.as_bytes()).unwrap(); + let busy = name.contains(".aa-cpp.avx2."); + assert_eq!(matches!(rec.req("pin").unwrap().get("sibling_idle"), Some(Json::Bool(false))), busy, "{name}"); + } + // a streamed set that differs between the two sides of a record is refused + let mut skewed = done.clone(); + skewed + .iter_mut() + .find(|p| p.proc == Proc { imp: Impl::Cpp, tree: "avx2", rep: 'a' }) + .unwrap() + .regimes + .get_mut("STREAMED") + .unwrap() + .copies_k = 4; + assert!(round_records(&ctx, 31, &skewed).unwrap_err().contains("streamed set differs")); + // a missing process is named + assert!(round_records(&ctx, 31, &done[1..]).unwrap_err().contains("did not run")); + } + + #[test] + fn the_rust_time_mode_writes_a_process_json_the_runner_accepts() { + let t = TempDir::new(); + build(&t.0, &one_case(), |_| {}); + let out = TempDir::new(); + let file = out.0.join("t.json"); + let args: Vec = [ + "--run-dir", + t.0.to_str().unwrap(), + "--case", + "42-42-r1", + "--slices", + "40", + "--pin", + "0", + "--out", + file.to_str().unwrap(), + "--slice-ms", + "1", + "--llc-bytes", + "8000000", + ] + .iter() + .map(|s| (*s).to_owned()) + .collect(); + // exit 0, or 3 when a 1 ms slice of a ramping clock was dropped in every slice of a regime (kept slices are the loaded host's call) + let code = format!("{:?}", cmd_time(&args).unwrap()); + assert!(code == format!("{:?}", ExitCode::SUCCESS) || code == format!("{:?}", ExitCode::from(3)), "{code}"); + let text = fs::read_to_string(&file).unwrap(); + let j = parse_json(text.as_bytes()).unwrap(); + assert_eq!(j.str("writer").unwrap(), "rust"); + assert_eq!(j.str("format").unwrap(), "KAB1-time"); + assert!(j.flag("selfcheck_bitwise_equal_first_call").unwrap()); + assert_eq!(j.str("output_sha256").unwrap().len(), 64); + let tree = j.str("tree").unwrap().to_owned(); + let p = Proc { imp: Impl::Rust, tree: TREES.iter().find(|t| **t == tree).copied().unwrap(), rep: 'a' }; + if !code.contains("(0)") { + return; + } + let manifest = fs::read(t.0.join("manifest.json")).unwrap(); + let (_, _, cases, _) = read_manifest(&t.0).unwrap(); + let sha = sha_hex(&manifest); + let expect = Expect { manifest_sha: &sha, input_sha: &cases[0].in_sha256, case: "42-42-r1", pin: 0 }; + // the test process runs unscrubbed (its effective environment is empty), so the runner's environment check refuses it ... + assert!(parse_proc_json(&p, text.as_bytes(), &expect).unwrap_err().contains("effective environment")); + // ... and accepts it once the recorded environment is the cell's + let want_env = json_env(&cell_env(&p).into_iter().collect()); + let as_cell = text.replacen("\"effective_env\": {}", &format!("\"effective_env\": {want_env}"), 1); + let ok = parse_proc_json(&p, as_cell.as_bytes(), &expect).unwrap(); + for r in ["RESIDENT", "STREAMED"] { + let s = &ok.regimes[r]; + assert!(s.median_ns > 0.0 && s.median_cycles > 0.0 && !s.ns.is_empty(), "{r}"); + assert_eq!(s.requested, 40); + } + assert_eq!(ok.regimes["RESIDENT"].copies_k, 1); + assert!(ok.regimes["STREAMED"].copies_k >= 2); + assert!(ok.tree_text.starts_with("leleka-serve cpu: process kernel family")); + // a lie about the pin is refused + assert!( + parse_proc_json(&p, as_cell.as_bytes(), &Expect { pin: 3, ..expect }) + .unwrap_err() + .contains("pinned to CPU") + ); + } + + #[test] + fn utc_formatting_is_exact() { + assert_eq!(utc_of(0), "1970-01-01T00:00:00Z"); + assert_eq!(utc_of(1_782_000_000), "2026-06-21T00:00:00Z"); + assert!(is_utc(&now_utc())); + } +} diff --git a/crates/native-cpu-expert/rustfmt.toml b/crates/native-cpu-expert/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/native-cpu-expert/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/native-cpu-expert/src/cpu_report.rs b/crates/native-cpu-expert/src/cpu_report.rs index d33b7a7b..a20a8305 100644 --- a/crates/native-cpu-expert/src/cpu_report.rs +++ b/crates/native-cpu-expert/src/cpu_report.rs @@ -40,7 +40,14 @@ fn probe() -> Core { let l7 = __cpuid_count(7, 0); let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0; let os512 = osxsave && xcr0 & 0xe6 == 0xe6; - let bits = [l7.ebx & (1 << 16) != 0, l7.ebx & (1 << 30) != 0, l7.ebx & (1 << 31) != 0, l7.ebx & (1 << 17) != 0, l7.ecx & (1 << 1) != 0, l7.ecx & (1 << 11) != 0]; + let bits = [ + l7.ebx & (1 << 16) != 0, + l7.ebx & (1 << 30) != 0, + l7.ebx & (1 << 31) != 0, + l7.ebx & (1 << 17) != 0, + l7.ecx & (1 << 1) != 0, + l7.ecx & (1 << 11) != 0, + ]; Core { brand, avx2, avx512: bits.map(|b| b && os512) } } } @@ -104,7 +111,13 @@ pub fn cpu_kernel_report() -> Vec { if core.brand.is_empty() { "unknown model" } else { &core.brand }, if core.avx2 { "yes" } else { "no" }, avx512, - if avx512_complete(core) { "AVX-512" } else if core.avx2 { "AVX2" } else { "none (unsupported)" } + if avx512_complete(core) { + "AVX-512" + } else if core.avx2 { + "AVX2" + } else { + "none (unsupported)" + } )); } let dispatch = crate::rust_simd::dispatch(); @@ -122,7 +135,9 @@ pub fn cpu_kernel_report() -> Vec { if dispatch.iq4nl { "on" } else { "off" }, if switches.is_empty() { String::new() } else { format!("; overridden by {}", switches.join(", ")) } )); - if groups.len() > 1 && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) { + if groups.len() > 1 + && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) + { lines.push("cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; a worker pinned to a core without it would fault or be refused".to_owned()); } lines diff --git a/crates/native-cpu-expert/src/ffi.rs b/crates/native-cpu-expert/src/ffi.rs index 79cff9ce..b1575645 100644 --- a/crates/native-cpu-expert/src/ffi.rs +++ b/crates/native-cpu-expert/src/ffi.rs @@ -1,32 +1,60 @@ //! Closed Rust replacement for the former C++ miss ABI. //! Owned jobs remain alive until every real worker joins on any uncertain error. -use super::{PreparedJob,Result,Error}; -pub(super) struct NativePool {pool:Option} +use super::{Error, PreparedJob, Result}; +pub(super) struct NativePool { + pool: Option, +} impl NativePool { - pub(super) fn new(workers:i32)->Result{Ok(Self{pool:Some(super::rust_pool::NativePool::new(workers)?)})} - pub(super) fn workers(&self)->Result{self.pool.as_ref().ok_or(Error::Closed)?.workers()} - pub(super) fn take_timing(&mut self)->Option<[f64;super::rust_pool::TIMING_STAGES]>{self.pool.as_mut().and_then(super::rust_pool::NativePool::take_timing)} - /// A caught panic drops (stops and joins) the native pool before returning, so no worker can still - /// touch the borrowed group afterwards; the pool is then closed. - pub(super) fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> { - let pool=self.pool.as_mut().ok_or(Error::Closed)?; - match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_borrowed(gu,down,group,out))) { - Ok(result)=>result, - Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} - } - } - pub(super) fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> { - let pool=self.pool.as_mut().ok_or(Error::Closed)?; - match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.prefetch_borrowed(gu,down,experts))) { - Ok(result)=>result, - Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} - } - } - pub(super) fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> { - let pool=self.pool.as_mut().ok_or(Error::Closed)?; - match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||pool.compute_batch(jobs))) { - Ok(result)=>result, - Err(_)=>{drop(self.pool.take());Err(Error::NativeFailure)} - } - } + pub(super) fn new(workers: i32) -> Result { + Ok(Self { pool: Some(super::rust_pool::NativePool::new(workers)?) }) + } + pub(super) fn workers(&self) -> Result { + self.pool.as_ref().ok_or(Error::Closed)?.workers() + } + pub(super) fn take_timing(&mut self) -> Option<[f64; super::rust_pool::TIMING_STAGES]> { + self.pool.as_mut().and_then(super::rust_pool::NativePool::take_timing) + } + /// A caught panic drops (stops and joins) the native pool before returning, so no worker can still + /// touch the borrowed group afterwards; the pool is then closed. + pub(super) fn compute_borrowed( + &mut self, + gu: i32, + down: i32, + group: &super::BorrowedGroup<'_>, + out: &mut [f32], + ) -> Result<()> { + let pool = self.pool.as_mut().ok_or(Error::Closed)?; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| pool.compute_borrowed(gu, down, group, out))) { + Ok(result) => result, + Err(_) => { + drop(self.pool.take()); + Err(Error::NativeFailure) + } + } + } + pub(super) fn prefetch_borrowed( + &mut self, + gu: i32, + down: i32, + experts: &[super::BorrowedExpert<'_>], + ) -> Result<()> { + let pool = self.pool.as_mut().ok_or(Error::Closed)?; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| pool.prefetch_borrowed(gu, down, experts))) { + Ok(result) => result, + Err(_) => { + drop(self.pool.take()); + Err(Error::NativeFailure) + } + } + } + pub(super) fn compute_batch(&mut self, jobs: &mut [PreparedJob]) -> Result<()> { + let pool = self.pool.as_mut().ok_or(Error::Closed)?; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| pool.compute_batch(jobs))) { + Ok(result) => result, + Err(_) => { + drop(self.pool.take()); + Err(Error::NativeFailure) + } + } + } } diff --git a/crates/native-cpu-expert/src/impl_cpupool.rs b/crates/native-cpu-expert/src/impl_cpupool.rs new file mode 100644 index 00000000..69fe1767 --- /dev/null +++ b/crates/native-cpu-expert/src/impl_cpupool.rs @@ -0,0 +1,139 @@ +//! Moved out of the parent module by STRA-338: impl CpuPool, impl PendingBatch, impl Drop_for_PendingBatch, impl Drop_for_CpuPool. + +#[allow(unused_imports)] +use super::*; + +impl CpuPool { + pub fn new(workers: i32) -> Result { + let (command, receive) = mpsc::sync_channel::>(1); + let (send_result, completed) = mpsc::sync_channel(1); + let (startup, initialized) = mpsc::sync_channel(1); + let worker = thread::Builder::new() + .name("leleka-cpu-miss".into()) + .stack_size(2 * 1024 * 1024) + .spawn(move || { + // No pointer/Context/Binding/source scope is captured from the actor. + let mut native = match ffi::NativePool::new(workers) { + Ok(pool) => pool, + Err(error) => { + let _ = startup.send(Err(error)); + return; + } + }; + if startup.send(native.workers()).is_err() { + return; + } + while let Ok(mut jobs) = receive.recv() { + let result = native.compute_batch(&mut jobs); + if matches!(result, Err(Error::NativeFailure | Error::Allocation)) { + // A caught native exception might leave completion uncertain. + // Keep every job owner live until the original pool's stop + // and join completes, then close this coordinator forever. + drop(native); + drop(jobs); + let _ = send_result.send(result.map(|()| Vec::new())); + return; + } + let result = result.map(|()| jobs); + if send_result.send(result).is_err() { + break; + } + } + // NativePool is destroyed here; original destructor joins all workers. + }) + .map_err(|_| Error::Allocation)?; + match initialized.recv().unwrap_or(Err(Error::NativeFailure)) { + Ok(workers) => Ok(Self { + command: Some(command), + completed, + worker: Some(worker), + workers, + failed: false, + in_flight: false, + _actor: PhantomData, + }), + Err(error) => { + drop(command); + let _ = worker.join(); + Err(error) + } + } + } + pub fn workers(&self) -> usize { + self.workers + } + pub fn start(&mut self, jobs: Vec, allowance: usize) -> Result> { + if self.failed || self.in_flight { + return Err(Error::Closed); + } + if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { + return Err(Error::Shape); + } + if allowance > MAX_BATCH_BYTES { + return Err(Error::BudgetExceeded); + } + let mut results = Vec::new(); + results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + let metadata = jobs + .capacity() + .checked_mul(std::mem::size_of::()) + .and_then(|n| { + results.capacity().checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m)) + }) + .ok_or(Error::BudgetExceeded)?; + let charged = jobs + .iter() + .try_fold(metadata, |bytes, job| bytes.checked_add(job.owned_bytes()?).ok_or(Error::BudgetExceeded))?; + if charged > allowance { + return Err(Error::BudgetExceeded); + } + if self.command.as_ref().ok_or(Error::Closed)?.send(jobs).is_err() { + self.failed = true; + return Err(Error::Closed); + } + self.in_flight = true; + Ok(PendingBatch { pool: self, results, consumed: false }) + } +} +impl PendingBatch<'_> { + pub fn join(mut self) -> Result> { + let result = self.pool.completed.recv().unwrap_or(Err(Error::NativeFailure)); + self.pool.in_flight = false; + self.consumed = true; + match result { + Ok(jobs) => { + for job in jobs { + self.results.push(CompletedJob { values: job.output }); + } + Ok(std::mem::take(&mut self.results)) + } + Err(error) => { + if matches!(error, Error::NativeFailure | Error::Allocation | Error::Closed) { + self.pool.failed = true; + } + Err(error) + } + } + } +} +impl Drop for PendingBatch<'_> { + fn drop(&mut self) { + if !self.consumed { + // Cancellation/unwind drains all native consumers, then discards. + // No borrowed source/device owner is on this thread or command. + let result = self.pool.completed.recv(); + self.pool.in_flight = false; + if matches!(result, Err(_) | Ok(Err(Error::NativeFailure | Error::Allocation | Error::Closed))) { + self.pool.failed = true; + } + } + } +} +impl Drop for CpuPool { + fn drop(&mut self) { + drop(self.command.take()); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} diff --git a/crates/native-cpu-expert/src/impl_gateupformat.rs b/crates/native-cpu-expert/src/impl_gateupformat.rs new file mode 100644 index 00000000..a45a1cde --- /dev/null +++ b/crates/native-cpu-expert/src/impl_gateupformat.rs @@ -0,0 +1,179 @@ +//! Moved out of the parent module by STRA-338: impl GateUpFormat, impl DownFormat, impl PreparedJob, impl DirectCpuPool, impl Drop_for_DirectCpuPool, impl CompletedJob. + +#[allow(unused_imports)] +use super::*; + +impl GateUpFormat { + pub(super) fn kind(self) -> i32 { + match self { + Self::Iq3Xxs => 18, + Self::Iq3S => 21, + Self::Iq2S => 22, + Self::Iq4Xs => 23, + Self::Q2_0 => 42, + Self::Iq2Xxs => 16, + Self::Iq2Xs => 17, + } + } + pub(super) fn block(self) -> (usize, usize) { + match self { + Self::Iq3Xxs => (256, 98), + Self::Iq3S => (256, 110), + Self::Iq2S => (256, 82), + Self::Iq4Xs => (256, 136), + Self::Q2_0 => (64, 18), + Self::Iq2Xxs => (256, 66), + Self::Iq2Xs => (256, 74), + } + } +} +impl DownFormat { + pub(super) fn kind(self) -> i32 { + match self { + Self::Iq4Nl => 20, + Self::Q2_0 => 42, + } + } + pub(super) fn block(self) -> (usize, usize) { + match self { + Self::Iq4Nl => (32, 18), + Self::Q2_0 => (64, 18), + } + } +} +impl PreparedJob { + pub fn new( + gu: GateUpFormat, + down: DownFormat, + gate: Box<[u8]>, + up: Box<[u8]>, + down_bytes: Box<[u8]>, + input: Box<[f32]>, + rows: usize, + ) -> Result { + if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H { + return Err(Error::Shape); + } + if input.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFinite); + } + let (gq, gb) = gu.block(); + let (dq, db) = down.block(); + let gsize = H / gq * gb * FF; + let dsize = FF / dq * db * H; + if gate.len() != gsize || up.len() != gsize || down_bytes.len() != dsize { + return Err(Error::Shape); + } + // Every admitted family has one FP16 header at each original block start. + // Integer multipliers are bounded; this is a guard, never a source proof. + for (bytes, block) in [(&gate, gb), (&up, gb), (&down_bytes, db)] { + for at in (0..bytes.len()).step_by(block) { + if u16::from_le_bytes([bytes[at], bytes[at + 1]]) & 0x7c00 == 0x7c00 { + return Err(Error::NonFinite); + } + } + } + let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; + let mut blob = Vec::new(); + blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; + blob.extend_from_slice(&gate); + blob.extend_from_slice(&up); + blob.extend_from_slice(&down_bytes); + // Drop original role owners before output allocation; all numerical + // consumers will use this immutable complete native G|U|D owner. + drop(gate); + drop(up); + drop(down_bytes); + let mut output = Vec::new(); + output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?; + output.resize(rows * H, 0.0); + Ok(Self { + gu, + down, + gate_bytes: gsize, + up_bytes: gsize, + down_bytes: dsize, + rows, + blob: blob.into_boxed_slice(), + input, + output: output.into_boxed_slice(), + }) + } + pub fn owned_bytes(&self) -> Result { + self.input + .len() + .checked_add(self.output.len()) + .and_then(|n| n.checked_mul(4)) + .and_then(|n| n.checked_add(self.blob.len())) + .and_then(|n| n.checked_add(std::mem::size_of::())) + .ok_or(Error::BudgetExceeded) + } +} +impl DirectCpuPool { + pub fn new(workers: i32) -> Result { + let native = ffi::NativePool::new(workers)?; + let workers = native.workers()?; + let pin_host = std::env::var("LELEKA_CPU_POOL_PIN_HOST").as_deref() != Ok("off"); + Ok(Self { native, workers, failed: false, pin_host, host_mask: None, _actor: PhantomData }) + } + pub(super) fn pin_caller(&mut self) { + if self.pin_host && self.host_mask.is_none() { + if let (Some(mask), Some(&core)) = (rust_platform::current_affinity(), rust_platform::cores(false).first()) + { + self.host_mask = Some(mask); + rust_platform::pin(core); + } + } + } + pub fn workers(&self) -> usize { + self.workers + } + /// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`). + pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { + self.native.take_timing() + } + /// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts, + /// all of the same gate/up and down formats). Only the pairs' rows of `out` are written. + pub fn compute_group( + &mut self, + gu: GateUpFormat, + down: DownFormat, + group: &BorrowedGroup<'_>, + out: &mut [f32], + ) -> Result<()> { + if self.failed { + return Err(Error::Closed); + } + self.pin_caller(); + let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out); + if matches!(result, Err(Error::NativeFailure | Error::Closed)) { + self.failed = true; + } + result + } + /// Read every page of the experts' matrices on all workers after `MADV_WILLNEED` on all of them (for a + /// file-mapped source; the pairs are ignored). Nothing is computed or written. + pub fn prefetch(&mut self, gu: GateUpFormat, down: DownFormat, experts: &[BorrowedExpert<'_>]) -> Result<()> { + if self.failed { + return Err(Error::Closed); + } + let result = self.native.prefetch_borrowed(gu.kind(), down.kind(), experts); + if matches!(result, Err(Error::NativeFailure | Error::Closed)) { + self.failed = true; + } + result + } +} + +impl Drop for DirectCpuPool { + fn drop(&mut self) { + if let Some(mask) = self.host_mask.take() { + rust_platform::restore_affinity(&mask); + } + } +} +impl CompletedJob { + pub fn into_values(self) -> Box<[f32]> { + self.values + } +} diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index 2ba9409c..cbfc1520 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -2,55 +2,56 @@ #![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] use std::{marker::PhantomData, rc::Rc, sync::mpsc, thread}; -mod ffi; -mod rust_codebooks; -mod rust_types; -#[allow(unsafe_code)] -mod rust_simd; #[allow(unsafe_code)] mod cpu_report; -pub use cpu_report::cpu_kernel_report; +mod ffi; +mod rust_codebooks; #[allow(unsafe_code)] -mod rust_quant; +mod rust_simd; +mod rust_types; +pub use cpu_report::cpu_kernel_report; #[allow(unsafe_code)] mod rust_iq; #[allow(unsafe_code)] -mod rust_q2; +pub mod rust_legacy; #[allow(unsafe_code)] #[cfg_attr(windows, path = "rust_platform_win.rs")] mod rust_platform; #[allow(unsafe_code)] mod rust_pool; #[allow(unsafe_code)] -pub mod rust_legacy; +mod rust_q2; +#[allow(unsafe_code)] +mod rust_quant; +pub mod pool_plan; +pub mod rust_bench; +pub mod rust_dequant; #[allow(unsafe_code)] -mod rust_kq; -#[allow(unsafe_code)] -mod rust_k_blocks; -#[allow(unsafe_code)] -mod rust_ggml_extra; -mod rust_iq1_grid; -#[allow(unsafe_code)] -pub mod rust_ggml; -#[allow(unsafe_code)] -mod rust_ggml_native; -#[allow(unsafe_code)] -pub mod rust_native_general; -#[allow(unsafe_code)] -pub mod rust_topology; +pub mod rust_expert_layout; #[allow(unsafe_code)] pub mod rust_general_pool; #[allow(unsafe_code)] -pub mod rust_expert_layout; -pub mod rust_dequant; -pub mod pool_plan; -mod rust_weight_quant; +pub mod rust_ggml; +#[allow(unsafe_code)] +mod rust_ggml_extra; +#[allow(unsafe_code)] +mod rust_ggml_native; +mod rust_iq1_grid; +#[allow(unsafe_code)] +mod rust_k_blocks; +#[allow(unsafe_code)] +mod rust_kq; pub mod rust_model_quant; -pub mod rust_bench; +#[allow(unsafe_code)] +pub mod rust_native_general; mod rust_quant_grids; -#[allow(unsafe_code)] mod rust_weight_iq; -pub use rust_kq::{bf16_rows,bf16_rows_multi}; +#[allow(unsafe_code)] +pub mod rust_topology; +#[allow(unsafe_code)] +mod rust_weight_iq; +mod rust_weight_quant; +pub use rust_kq::{bf16_rows, bf16_rows_multi}; pub use rust_platform::advise_will_need; const H: usize = 2560; @@ -60,66 +61,61 @@ pub const MAX_JOBS: usize = 96; pub const MAX_BATCH_BYTES: usize = 96 * 1024 * 1024; #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Error { Shape, Unsupported, Allocation, NonFinite, NativeFailure, BudgetExceeded, Closed } +pub enum Error { + Shape, + Unsupported, + Allocation, + NonFinite, + NativeFailure, + BudgetExceeded, + Closed, +} pub type Result = std::result::Result; #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GateUpFormat { Iq3Xxs, Iq3S, Iq2S, Iq4Xs, Q2_0, Iq2Xxs, Iq2Xs } // Iq2Xxs / Iq2Xs: kernel-A/B coverage (STRA-329); the runtime does not admit them +pub enum GateUpFormat { + Iq3Xxs, + Iq3S, + Iq2S, + Iq4Xs, + Q2_0, + Iq2Xxs, + Iq2Xs, +} // Iq2Xxs / Iq2Xs: kernel-A/B coverage (STRA-329); the runtime does not admit them #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum DownFormat { Iq4Nl, Q2_0 } -impl GateUpFormat { - fn kind(self) -> i32 { match self { Self::Iq3Xxs => 18, Self::Iq3S => 21, Self::Iq2S => 22, Self::Iq4Xs => 23, Self::Q2_0 => 42, Self::Iq2Xxs => 16, Self::Iq2Xs => 17 } } - fn block(self) -> (usize, usize) { match self { Self::Iq3Xxs => (256,98), Self::Iq3S => (256,110), Self::Iq2S => (256,82), Self::Iq4Xs => (256,136), Self::Q2_0 => (64,18), Self::Iq2Xxs => (256,66), Self::Iq2Xs => (256,74) } } -} -impl DownFormat { - fn kind(self) -> i32 { match self { Self::Iq4Nl => 20, Self::Q2_0 => 42 } } - fn block(self) -> (usize, usize) { match self { Self::Iq4Nl => (32,18), Self::Q2_0 => (64,18) } } +pub enum DownFormat { + Iq4Nl, + Q2_0, } /// Owned detached bytes only. Runtime authenticates actual descriptors/source. pub struct PreparedJob { - gu: GateUpFormat, down: DownFormat, gate_bytes: usize, up_bytes: usize, - down_bytes: usize, rows: usize, blob: Box<[u8]>, input: Box<[f32]>, output: Box<[f32]>, -} -impl PreparedJob { - pub fn new(gu: GateUpFormat, down: DownFormat, gate: Box<[u8]>, up: Box<[u8]>, - down_bytes: Box<[u8]>, input: Box<[f32]>, rows: usize) -> Result { - if !(1..=MAX_ROWS).contains(&rows) || input.len() != rows * H { return Err(Error::Shape); } - if input.iter().any(|x| !x.is_finite()) { return Err(Error::NonFinite); } - let (gq,gb) = gu.block(); let (dq,db) = down.block(); - let gsize = H / gq * gb * FF; let dsize = FF / dq * db * H; - if gate.len() != gsize || up.len() != gsize || down_bytes.len() != dsize { return Err(Error::Shape); } - // Every admitted family has one FP16 header at each original block start. - // Integer multipliers are bounded; this is a guard, never a source proof. - for (bytes, block) in [(&gate,gb),(&up,gb),(&down_bytes,db)] { - for at in (0..bytes.len()).step_by(block) { - if u16::from_le_bytes([bytes[at],bytes[at+1]]) & 0x7c00 == 0x7c00 { return Err(Error::NonFinite); } - } - } - let size = gsize.checked_mul(2).and_then(|n| n.checked_add(dsize)).ok_or(Error::Shape)?; - let mut blob = Vec::new(); blob.try_reserve_exact(size).map_err(|_| Error::Allocation)?; - blob.extend_from_slice(&gate); blob.extend_from_slice(&up); blob.extend_from_slice(&down_bytes); - // Drop original role owners before output allocation; all numerical - // consumers will use this immutable complete native G|U|D owner. - drop(gate); drop(up); drop(down_bytes); - let mut output = Vec::new(); output.try_reserve_exact(rows * H).map_err(|_| Error::Allocation)?; - output.resize(rows * H,0.0); - Ok(Self { gu, down, gate_bytes:gsize, up_bytes:gsize, down_bytes:dsize, - rows, blob:blob.into_boxed_slice(), input, output:output.into_boxed_slice() }) - } - pub fn owned_bytes(&self) -> Result { - self.input.len().checked_add(self.output.len()).and_then(|n| n.checked_mul(4)) - .and_then(|n| n.checked_add(self.blob.len())).and_then(|n| n.checked_add(std::mem::size_of::())) - .ok_or(Error::BudgetExceeded) - } + gu: GateUpFormat, + down: DownFormat, + gate_bytes: usize, + up_bytes: usize, + down_bytes: usize, + rows: usize, + blob: Box<[u8]>, + input: Box<[f32]>, + output: Box<[f32]>, } /// One routed expert of a borrowed group: its three encoded matrices in place (no copy) and the /// `(token, slot)` pairs that selected it, in the order its rows are computed. #[derive(Clone, Copy)] -pub struct BorrowedExpert<'a> { pub gate: &'a [u8], pub up: &'a [u8], pub down: &'a [u8], pub pairs: &'a [(usize, usize)] } +pub struct BorrowedExpert<'a> { + pub gate: &'a [u8], + pub up: &'a [u8], + pub down: &'a [u8], + pub pairs: &'a [(usize, usize)], +} /// A whole layer group: `tokens` are its activation rows (`rows * 2560` floats), each pair's result goes /// to output row `token * stride + slot`. #[derive(Clone, Copy)] -pub struct BorrowedGroup<'a> { pub tokens: &'a [f32], pub experts: &'a [BorrowedExpert<'a>], pub stride: usize } +pub struct BorrowedGroup<'a> { + pub tokens: &'a [f32], + pub experts: &'a [BorrowedExpert<'a>], + pub stride: usize, +} /// Output rows a borrowed group may address (8 rows x top-10 is 80). pub const MAX_OUT_ROWS: usize = 128; @@ -129,155 +125,56 @@ pub const MAX_OUT_ROWS: usize = 128; /// crate checks extents, pair bounds, disjoint destinations and finite inputs/outputs, never the source. /// Names of the stages `DirectCpuPool::take_timing` reports, in order. pub const POOL_TIMING_STAGES: usize = rust_pool::TIMING_STAGES; -pub const POOL_TIMING_NAMES: [&str; POOL_TIMING_STAGES] = ["cpu.t.pre", "cpu.t.gu_park0", "cpu.t.gu_publish", "cpu.t.gu_drain", "cpu.t.gu_wait_done", "cpu.t.gu_park1", "cpu.t.requant", "cpu.t.dn_park0", "cpu.t.dn_publish", "cpu.t.dn_drain", "cpu.t.dn_wait_done", "cpu.t.dn_park1", "cpu.t.post"]; +pub const POOL_TIMING_NAMES: [&str; POOL_TIMING_STAGES] = [ + "cpu.t.pre", + "cpu.t.gu_park0", + "cpu.t.gu_publish", + "cpu.t.gu_drain", + "cpu.t.gu_wait_done", + "cpu.t.gu_park1", + "cpu.t.requant", + "cpu.t.dn_park0", + "cpu.t.dn_publish", + "cpu.t.dn_drain", + "cpu.t.dn_wait_done", + "cpu.t.dn_park1", + "cpu.t.post", +]; pub struct DirectCpuPool { - native: ffi::NativePool, workers: usize, failed: bool, + native: ffi::NativePool, + workers: usize, + failed: bool, /// session.cpp `SessionLoopScratch`: the caller (the host loop, which drains beside the workers) is pinned /// once to the first physical core, the one the workers leave free; its previous mask is restored on drop. - pin_host: bool, host_mask: Option<[usize; 16]>, + pin_host: bool, + host_mask: Option<[usize; 16]>, _actor: PhantomData>, } -impl DirectCpuPool { - pub fn new(workers: i32) -> Result { - let native = ffi::NativePool::new(workers)?; - let workers = native.workers()?; - let pin_host = std::env::var("LELEKA_CPU_POOL_PIN_HOST").as_deref() != Ok("off"); - Ok(Self { native, workers, failed: false, pin_host, host_mask: None, _actor: PhantomData }) - } - fn pin_caller(&mut self) { - if self.pin_host && self.host_mask.is_none() { - if let (Some(mask), Some(&core)) = (rust_platform::current_affinity(), rust_platform::cores(false).first()) { - self.host_mask = Some(mask); - rust_platform::pin(core); - } - } - } - pub fn workers(&self) -> usize { self.workers } - /// `LELEKA_POOL_TIMING=1`: the host's stage times of `compute_group` summed since the last call, in ms (see `POOL_TIMING_STAGES`). - pub fn take_timing(&mut self) -> Option<[f64; POOL_TIMING_STAGES]> { self.native.take_timing() } - /// Compute every expert of `group` into `out` in one two-phase dispatch (at most `MAX_JOBS` experts, - /// all of the same gate/up and down formats). Only the pairs' rows of `out` are written. - pub fn compute_group(&mut self, gu: GateUpFormat, down: DownFormat, group: &BorrowedGroup<'_>, out: &mut [f32]) -> Result<()> { - if self.failed { return Err(Error::Closed); } - self.pin_caller(); - let result = self.native.compute_borrowed(gu.kind(), down.kind(), group, out); - if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } - result - } - /// Read every page of the experts' matrices on all workers after `MADV_WILLNEED` on all of them (for a - /// file-mapped source; the pairs are ignored). Nothing is computed or written. - pub fn prefetch(&mut self, gu: GateUpFormat, down: DownFormat, experts: &[BorrowedExpert<'_>]) -> Result<()> { - if self.failed { return Err(Error::Closed); } - let result = self.native.prefetch_borrowed(gu.kind(), down.kind(), experts); - if matches!(result, Err(Error::NativeFailure | Error::Closed)) { self.failed = true; } - result - } -} -impl Drop for DirectCpuPool { - fn drop(&mut self) { - if let Some(mask) = self.host_mask.take() { rust_platform::restore_affinity(&mask); } - } +pub struct CompletedJob { + values: Box<[f32]>, } -pub struct CompletedJob { values: Box<[f32]> } -impl CompletedJob { pub fn into_values(self) -> Box<[f32]> { self.values } } - /// Actor-side exclusive coordinator; its native pool exists only on its worker. /// The command queue has one slot and only one exclusive PendingBatch may exist. pub struct CpuPool { command: Option>>, completed: mpsc::Receiver>>, - worker: Option>, workers: usize, failed: bool, in_flight: bool, + worker: Option>, + workers: usize, + failed: bool, + in_flight: bool, _actor: PhantomData>, } -impl CpuPool { - pub fn new(workers: i32) -> Result { - let (command, receive) = mpsc::sync_channel::>(1); - let (send_result, completed) = mpsc::sync_channel(1); - let (startup, initialized) = mpsc::sync_channel(1); - let worker = thread::Builder::new().name("leleka-cpu-miss".into()).stack_size(2 * 1024 * 1024).spawn(move || { - // No pointer/Context/Binding/source scope is captured from the actor. - let mut native = match ffi::NativePool::new(workers) { - Ok(pool) => pool, - Err(error) => { let _ = startup.send(Err(error)); return; } - }; - if startup.send(native.workers()).is_err() { return; } - while let Ok(mut jobs) = receive.recv() { - let result = native.compute_batch(&mut jobs); - if matches!(result, Err(Error::NativeFailure | Error::Allocation)) { - // A caught native exception might leave completion uncertain. - // Keep every job owner live until the original pool's stop - // and join completes, then close this coordinator forever. - drop(native); - drop(jobs); - let _ = send_result.send(result.map(|()| Vec::new())); - return; - } - let result = result.map(|()| jobs); - if send_result.send(result).is_err() { break; } - } - // NativePool is destroyed here; original destructor joins all workers. - }).map_err(|_| Error::Allocation)?; - match initialized.recv().unwrap_or(Err(Error::NativeFailure)) { - Ok(workers) => Ok(Self { command:Some(command), completed, worker:Some(worker), workers, - failed:false, in_flight:false, _actor:PhantomData }), - Err(error) => { drop(command); let _ = worker.join(); Err(error) } - } - } - pub fn workers(&self) -> usize { self.workers } - pub fn start(&mut self, jobs: Vec, allowance: usize) -> Result> { - if self.failed || self.in_flight { return Err(Error::Closed); } - if !(1..=MAX_JOBS).contains(&jobs.len()) || jobs.capacity() > MAX_JOBS { return Err(Error::Shape); } - if allowance > MAX_BATCH_BYTES { return Err(Error::BudgetExceeded); } - let mut results = Vec::new(); results.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; - let metadata = jobs.capacity().checked_mul(std::mem::size_of::()) - .and_then(|n| results.capacity().checked_mul(std::mem::size_of::()).and_then(|m| n.checked_add(m))) - .ok_or(Error::BudgetExceeded)?; - let charged = jobs.iter().try_fold(metadata, |bytes,job| bytes.checked_add(job.owned_bytes()?) - .ok_or(Error::BudgetExceeded))?; - if charged > allowance { return Err(Error::BudgetExceeded); } - if self.command.as_ref().ok_or(Error::Closed)?.send(jobs).is_err() { - self.failed=true; - return Err(Error::Closed); - } - self.in_flight=true; - Ok(PendingBatch { pool:self, results, consumed:false }) - } -} -pub struct PendingBatch<'pool> { pool:&'pool mut CpuPool, results:Vec, consumed:bool } -impl PendingBatch<'_> { - pub fn join(mut self) -> Result> { - let result = self.pool.completed.recv().unwrap_or(Err(Error::NativeFailure)); - self.pool.in_flight=false; - self.consumed = true; - match result { - Ok(jobs) => { - for job in jobs { self.results.push(CompletedJob { values:job.output }); } - Ok(std::mem::take(&mut self.results)) - } - Err(error) => { if matches!(error,Error::NativeFailure | Error::Allocation | Error::Closed) { self.pool.failed=true; } Err(error) } - } - } -} -impl Drop for PendingBatch<'_> { - fn drop(&mut self) { - if !self.consumed { - // Cancellation/unwind drains all native consumers, then discards. - // No borrowed source/device owner is on this thread or command. - let result = self.pool.completed.recv(); - self.pool.in_flight=false; - if matches!(result,Err(_) | Ok(Err(Error::NativeFailure | Error::Allocation | Error::Closed))) { self.pool.failed=true; } - } - } -} -impl Drop for CpuPool { - fn drop(&mut self) { - drop(self.command.take()); - if let Some(worker) = self.worker.take() { let _ = worker.join(); } - } +pub struct PendingBatch<'pool> { + pool: &'pool mut CpuPool, + results: Vec, + consumed: bool, } #[allow(unsafe_code)] #[cfg(target_os = "linux")] pub mod rust_bench_frontend; + +mod impl_cpupool; +mod impl_gateupformat; diff --git a/crates/native-cpu-expert/src/pool_plan.rs b/crates/native-cpu-expert/src/pool_plan.rs index 2f48ed7e..5f47b25b 100644 --- a/crates/native-cpu-expert/src/pool_plan.rs +++ b/crates/native-cpu-expert/src/pool_plan.rs @@ -155,7 +155,11 @@ mod tests { let two = cpu(256, &[64, 64]); assert_eq!(workers(&two), WORKERS_CAP); assert_eq!((plan_pool_workers(&two).packages, plan_pool_workers(&two).cores), (2, 128)); - assert_eq!(workers(&cpu(80, &[20, 20])), 18, "2x20 cores: the host's socket only, minus the host and the reserve"); + assert_eq!( + workers(&cpu(80, &[20, 20])), + 18, + "2x20 cores: the host's socket only, minus the host and the reserve" + ); assert_eq!(workers(&cpu(48, &[6, 18])), 5, "a smaller host socket decides"); } diff --git a/crates/native-cpu-expert/src/rust_bench.rs b/crates/native-cpu-expert/src/rust_bench.rs index 1887fdf2..f8137367 100644 --- a/crates/native-cpu-expert/src/rust_bench.rs +++ b/crates/native-cpu-expert/src/rust_bench.rs @@ -13,25 +13,33 @@ fn zeros(n: usize) -> Result> { /// Standard MT19937 integer recurrence. The float distribution below is the /// GNU libstdc++ polar/generate_canonical policy used on Linux. -pub struct Mt19937 { words: [u32; 624], cursor: usize } +pub struct Mt19937 { + words: [u32; 624], + cursor: usize, +} impl Mt19937 { pub fn new(seed: u32) -> Self { - let mut words = [0; 624]; words[0] = seed; + let mut words = [0; 624]; + words[0] = seed; for i in 1..624 { - words[i] = 1812433253u32.wrapping_mul(words[i-1] ^ (words[i-1] >> 30)).wrapping_add(i as u32); + words[i] = 1812433253u32.wrapping_mul(words[i - 1] ^ (words[i - 1] >> 30)).wrapping_add(i as u32); } Self { words, cursor: 624 } } pub fn next_u32(&mut self) -> u32 { if self.cursor == 624 { for i in 0..624 { - let v = (self.words[i] & 0x80000000) | (self.words[(i+1)%624] & 0x7fffffff); - self.words[i] = self.words[(i+397)%624] ^ (v >> 1) ^ if v & 1 != 0 { 0x9908b0df } else { 0 }; + let v = (self.words[i] & 0x80000000) | (self.words[(i + 1) % 624] & 0x7fffffff); + self.words[i] = self.words[(i + 397) % 624] ^ (v >> 1) ^ if v & 1 != 0 { 0x9908b0df } else { 0 }; } self.cursor = 0; } - let mut v = self.words[self.cursor]; self.cursor += 1; - v ^= v >> 11; v ^= (v << 7) & 0x9d2c5680; v ^= (v << 15) & 0xefc60000; v ^= v >> 18; + let mut v = self.words[self.cursor]; + self.cursor += 1; + v ^= v >> 11; + v ^= (v << 7) & 0x9d2c5680; + v ^= (v << 15) & 0xefc60000; + v ^= v >> 18; v } fn canonical(&mut self) -> f32 { @@ -43,95 +51,183 @@ impl Mt19937 { pub fn signed_100(&mut self) -> i32 { loop { let p = self.next_u32() as u64 * 201; - if p as u32 >= 201u32.wrapping_neg() % 201 { return (p >> 32) as i32 - 100; } + if p as u32 >= 201u32.wrapping_neg() % 201 { + return (p >> 32) as i32 - 100; + } } } } -pub struct NormalFloat { saved: Option } -impl Default for NormalFloat { fn default() -> Self { Self { saved: None } } } +pub struct NormalFloat { + saved: Option, +} +impl Default for NormalFloat { + fn default() -> Self { + Self { saved: None } + } +} impl NormalFloat { pub fn next(&mut self, rng: &mut Mt19937) -> f32 { - let v = if let Some(v) = self.saved.take() { v } else { + let v = if let Some(v) = self.saved.take() { + v + } else { loop { let x = 2.0 * rng.canonical() - 1.0; let y = 2.0 * rng.canonical() - 1.0; - let r = x*x + y*y; + let r = x * x + y * y; if r <= 1.0 && r != 0.0 { let m = (-2.0 * r.ln() / r).sqrt(); - self.saved = Some(x*m); break y*m; + self.saved = Some(x * m); + break y * m; } } }; - v*1.0 + 0.0 + v * 1.0 + 0.0 } } pub fn relative_l1(actual: &[f32], reference: &[f32]) -> Result { - if actual.len() != reference.len() { return Err(Error::Shape); } + if actual.len() != reference.len() { + return Err(Error::Shape); + } let (mut n, mut d) = (0.0f64, 0.0f64); - for i in 0..actual.len() { n += (actual[i] as f64 - reference[i] as f64).abs(); d += (reference[i] as f64).abs(); } - Ok(n/(d+1e-30)) + for i in 0..actual.len() { + n += (actual[i] as f64 - reference[i] as f64).abs(); + d += (reference[i] as f64).abs(); + } + Ok(n / (d + 1e-30)) } pub fn bit_differences(actual: &[f32], reference: &[f32]) -> Result { - if actual.len() != reference.len() { return Err(Error::Shape); } - Ok(actual.iter().zip(reference).filter(|(a,b)| a.to_bits()!=b.to_bits()).count()) + if actual.len() != reference.len() { + return Err(Error::Shape); + } + Ok(actual.iter().zip(reference).filter(|(a, b)| a.to_bits() != b.to_bits()).count()) +} +pub struct DequantizedExpert { + pub gate: Vec, + pub up: Vec, + pub down: Vec, } -pub struct DequantizedExpert { pub gate: Vec, pub up: Vec, pub down: Vec } pub fn dequantize_expert(f: &NativeFormat, blob: &[u8]) -> Result { - f.validate()?; if blob.len()!=f.bytes { return Err(Error::Shape); } + f.validate()?; + if blob.len() != f.bytes { + return Err(Error::Shape); + } let n = f.n_embd.checked_mul(f.n_ff).ok_or(Error::Shape)?; - let mut gate = zeros(n)?; let mut up = zeros(n)?; let mut down = zeros(n)?; + let mut gate = zeros(n)?; + let mut up = zeros(n)?; + let mut down = zeros(n)?; for r in 0..f.n_ff { - super::rust_dequant::dequantize(f.gu,&blob[r*f.gu_row..(r+1)*f.gu_row],&mut gate[r*f.n_embd..(r+1)*f.n_embd])?; - super::rust_dequant::dequantize(f.gu,&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row],&mut up[r*f.n_embd..(r+1)*f.n_embd])?; + super::rust_dequant::dequantize( + f.gu, + &blob[r * f.gu_row..(r + 1) * f.gu_row], + &mut gate[r * f.n_embd..(r + 1) * f.n_embd], + )?; + super::rust_dequant::dequantize( + f.gu, + &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row], + &mut up[r * f.n_embd..(r + 1) * f.n_embd], + )?; } for r in 0..f.n_embd { - super::rust_dequant::dequantize(f.down,&blob[f.down_offset+r*f.down_row..f.down_offset+(r+1)*f.down_row],&mut down[r*f.n_ff..(r+1)*f.n_ff])?; + super::rust_dequant::dequantize( + f.down, + &blob[f.down_offset + r * f.down_row..f.down_offset + (r + 1) * f.down_row], + &mut down[r * f.n_ff..(r + 1) * f.n_ff], + )?; } Ok(DequantizedExpert { gate, up, down }) } pub fn float_oracle(f: &NativeFormat, blob: &[u8], input: &[f32]) -> Result> { f.validate()?; - if input.is_empty() || input.len()%f.n_embd!=0 { return Err(Error::Shape); } - let w = dequantize_expert(f,blob)?; - let mut out = zeros(input.len())?; let mut hidden = zeros(f.n_ff)?; - for (x,o) in input.chunks_exact(f.n_embd).zip(out.chunks_exact_mut(f.n_embd)) { - for (r,h) in hidden.iter_mut().enumerate() { - let (mut g,mut u) = (0.0f64,0.0f64); - for (i,&x) in x.iter().enumerate() { g += w.gate[r*f.n_embd+i] as f64*x as f64; u += w.up[r*f.n_embd+i] as f64*x as f64; } - *h = (g/(1.0+(-g).exp())*u) as f32; + if input.is_empty() || input.len() % f.n_embd != 0 { + return Err(Error::Shape); + } + let w = dequantize_expert(f, blob)?; + let mut out = zeros(input.len())?; + let mut hidden = zeros(f.n_ff)?; + for (x, o) in input.chunks_exact(f.n_embd).zip(out.chunks_exact_mut(f.n_embd)) { + for (r, h) in hidden.iter_mut().enumerate() { + let (mut g, mut u) = (0.0f64, 0.0f64); + for (i, &x) in x.iter().enumerate() { + g += w.gate[r * f.n_embd + i] as f64 * x as f64; + u += w.up[r * f.n_embd + i] as f64 * x as f64; + } + *h = (g / (1.0 + (-g).exp()) * u) as f32; } - for (r,o) in o.iter_mut().enumerate() { - let mut value=0.0f64; - for (i,&h) in hidden.iter().enumerate() { value += w.down[r*f.n_ff+i] as f64*h as f64; } - *o=value as f32; + for (r, o) in o.iter_mut().enumerate() { + let mut value = 0.0f64; + for (i, &h) in hidden.iter().enumerate() { + value += w.down[r * f.n_ff + i] as f64 * h as f64; + } + *o = value as f32; } } Ok(out) } pub fn synthetic_blob(f: &NativeFormat, seed: u32) -> Result> { f.validate()?; - let mut out = zeros(f.bytes)?; let mut rng=Mt19937::new(seed); let mut nd=NormalFloat::default(); - for (kind,rows,cols,offset) in [(f.gu,f.n_ff,f.n_embd,0),(f.gu,f.n_ff,f.n_embd,f.up_offset),(f.down,f.n_embd,f.n_ff,f.down_offset)] { - let n=rows.checked_mul(cols).ok_or(Error::Shape)?; let mut w=zeros(n)?; - for r in 0..rows { let scale=0.02f32*(0.5f32+(r%7) as f32/7.0f32); for c in 0..cols { w[r*cols+c]=scale*nd.next(&mut rng); } } - let imatrix=if super::rust_model_quant::requires_imatrix(kind) { let mut v=zeros(cols)?; v.fill(1.0); Some(v) } else { None }; - let bytes=kind.row_bytes(cols)?.checked_mul(rows).ok_or(Error::Shape)?; - super::rust_model_quant::quantize_chunk(kind,&w,&mut out[offset..offset+bytes],0,rows,cols,imatrix.as_deref())?; + let mut out = zeros(f.bytes)?; + let mut rng = Mt19937::new(seed); + let mut nd = NormalFloat::default(); + for (kind, rows, cols, offset) in + [(f.gu, f.n_ff, f.n_embd, 0), (f.gu, f.n_ff, f.n_embd, f.up_offset), (f.down, f.n_embd, f.n_ff, f.down_offset)] + { + let n = rows.checked_mul(cols).ok_or(Error::Shape)?; + let mut w = zeros(n)?; + for r in 0..rows { + let scale = 0.02f32 * (0.5f32 + (r % 7) as f32 / 7.0f32); + for c in 0..cols { + w[r * cols + c] = scale * nd.next(&mut rng); + } + } + let imatrix = if super::rust_model_quant::requires_imatrix(kind) { + let mut v = zeros(cols)?; + v.fill(1.0); + Some(v) + } else { + None + }; + let bytes = kind.row_bytes(cols)?.checked_mul(rows).ok_or(Error::Shape)?; + super::rust_model_quant::quantize_chunk( + kind, + &w, + &mut out[offset..offset + bytes], + 0, + rows, + cols, + imatrix.as_deref(), + )?; } Ok(out) } pub fn check_inputs(seed: u32, rows: usize, width: usize) -> Result> { - let mut rng=Mt19937::new(11u32.wrapping_add(seed)); let mut nd=NormalFloat::default(); - let mut x=zeros(rows.checked_mul(width).ok_or(Error::Shape)?)?; - for x in &mut x { *x=nd.next(&mut rng); } Ok(x) + let mut rng = Mt19937::new(11u32.wrapping_add(seed)); + let mut nd = NormalFloat::default(); + let mut x = zeros(rows.checked_mul(width).ok_or(Error::Shape)?)?; + for x in &mut x { + *x = nd.next(&mut rng); + } + Ok(x) +} +pub struct Q5OneMinCase { + pub weights: Vec, + pub input: Vec, + pub width: usize, + pub rows: usize, } -pub struct Q5OneMinCase { pub weights: Vec, pub input: Vec, pub width: usize, pub rows: usize } pub fn q5_one_min_case() -> Result { - let (rows,width)=(64,640); let mut rng=Mt19937::new(5); let mut nd=NormalFloat::default(); - let mut w=zeros(rows*width)?; for w in &mut w { *w=0.3+0.05*nd.next(&mut rng); } - let mut x=zeros(width)?; for x in &mut x { *x=0.01*(rng.signed_100() as f32+0.45); } - let mut weights=zeros(rows*Kind::Q5One.row_bytes(width)?)?; - super::rust_model_quant::quantize_chunk(Kind::Q5One,&w,&mut weights,0,rows,width,None)?; - Ok(Q5OneMinCase { weights, input:x, width, rows }) + let (rows, width) = (64, 640); + let mut rng = Mt19937::new(5); + let mut nd = NormalFloat::default(); + let mut w = zeros(rows * width)?; + for w in &mut w { + *w = 0.3 + 0.05 * nd.next(&mut rng); + } + let mut x = zeros(width)?; + for x in &mut x { + *x = 0.01 * (rng.signed_100() as f32 + 0.45); + } + let mut weights = zeros(rows * Kind::Q5One.row_bytes(width)?)?; + super::rust_model_quant::quantize_chunk(Kind::Q5One, &w, &mut weights, 0, rows, width, None)?; + Ok(Q5OneMinCase { weights, input: x, width, rows }) } diff --git a/crates/native-cpu-expert/src/rust_bench_frontend.rs b/crates/native-cpu-expert/src/rust_bench_frontend.rs index b0a2f2c1..ae2f943a 100644 --- a/crates/native-cpu-expert/src/rust_bench_frontend.rs +++ b/crates/native-cpu-expert/src/rust_bench_frontend.rs @@ -1,263 +1,127 @@ //! Literal Linux host control of native_expert_parity.cpp. Registration is a //! separate unapplied patch. This module never substitutes a CPU result for GPU. -use std::{ffi::{CString,c_char,c_int,c_void}, time::Instant}; -use crate::{Error,Result, rust_bench as bench, rust_ggml::{Kind,NativeFormat}, rust_native_general as cpu}; +use crate::{ + Error, Result, rust_bench as bench, + rust_ggml::{Kind, NativeFormat}, + rust_native_general as cpu, +}; use cpu::NativeActivation; -#[path="rust_bench_gpu.rs"] pub mod gpu; -#[path="rust_bench_model.rs"] mod model; +use std::{ + ffi::{CString, c_char, c_int, c_void}, + time::Instant, +}; +#[path = "rust_bench_gpu.rs"] +pub mod gpu; +#[path = "rust_bench_model.rs"] +mod model; use gpu::ParityGpu; unsafe extern "C" { static mut stdout: *mut c_void; - fn setvbuf(stream:*mut c_void,buffer:*mut c_char,mode:c_int,bytes:usize)->c_int; - fn printf(format:*const c_char,...)->c_int; - fn setenv(name:*const c_char,value:*const c_char,overwrite:c_int)->c_int; + fn setvbuf(stream: *mut c_void, buffer: *mut c_char, mode: c_int, bytes: usize) -> c_int; + fn printf(format: *const c_char, ...) -> c_int; + fn setenv(name: *const c_char, value: *const c_char, overwrite: c_int) -> c_int; } macro_rules! report { ($fmt:literal $(,$arg:expr)* $(,)?) => {{ // Every format is a static NUL-terminated literal and every variadic value // has the exact C default-promoted type named by that format. unsafe { printf(concat!($fmt,"\0").as_ptr().cast() $(,$arg)*); } }}; } -fn numerical(r:Result)->std::result::Result{r.map_err(|e|format!("CPU benchmark: {e:?}"))} -fn zeros(n:usize)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,T::default);Ok(v)} -fn refs(a:&[NativeActivation])->Vec<&NativeActivation>{a.iter().collect()} -fn outputs(v:&mut[f32],width:usize)->Vec<&mut[f32]>{v.chunks_exact_mut(width).collect()} -fn rel(a:&[f32],b:&[f32])->std::result::Result{numerical(bench::relative_l1(a,b))} -fn bits(a:&[f32],b:&[f32])->std::result::Result{numerical(bench::bit_differences(a,b))} -const NT:usize=3;const H:usize=2560;const FF:usize=640; -const NAMES:[&str;43]=["f32","f16","q4_0","q4_1","DEPRECATED","DEPRECATED","q5_0","q5_1","q8_0","q8_1","q2_K","q3_K","q4_K","q5_K","q6_K","q8_K","iq2_xxs","iq2_xs","iq3_xxs","iq1_s","iq4_nl","iq3_s","iq2_s","iq4_xs","i8","i16","i32","i64","f64","iq1_m","bf16","TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking","TYPE_Q4_0_4_8 REMOVED, use Q4_0 with runtime repacking","TYPE_Q4_0_8_8 REMOVED, use Q4_0 with runtime repacking","tq1_0","tq2_0","TYPE_IQ4_NL_4_4 REMOVED, use IQ4_NL with runtime repacking","TYPE_IQ4_NL_4_8 REMOVED, use IQ4_NL with runtime repacking","TYPE_IQ4_NL_8_8 REMOVED, use IQ4_NL with runtime repacking","mxfp4","nvfp4","q1_0","q2_0"]; -fn name(kind:Kind)->CString{CString::new(NAMES[kind.original_id() as usize]).unwrap()} -fn type_of(n:&str)->i32{NAMES.iter().position(|v|v.eq_ignore_ascii_case(n)).map_or(-1,|v|v as i32)} -fn native_fmt(g:i32,d:i32)->std::result::Result{ - let gu=Kind::from_original(g).map_err(|_|format!("native experts: ggml-cpu has no dot product for type {g}"))?; - let down=Kind::from_original(d).map_err(|_|format!("native experts: ggml-cpu has no dot product for type {d}"))?; - if H%gu.block().0!=0||FF%down.block().0!=0||gu.activation_bytes(H).is_err()||down.activation_bytes(FF).is_err(){return Err("native experts: expert geometry is not whole blocks".into());} - if gu.activation_bytes(H).unwrap()>4096||down.activation_bytes(FF).unwrap()>1024{return Err("native experts: activation larger than the pool's buffers".into());} - numerical(NativeFormat::new(gu,down,H,FF)) -} -fn dot(kind:Kind,row:&[u8],a:&NativeActivation,width:usize)->Result{ - a.check(kind,width)?; - if !cpu::cpu_avx2_ok()||row.len()!=kind.row_bytes(width)?||a.encoded_bytes()? > B{return Err(Error::Shape);} - // SAFETY: actual aligned initialized NativeActivation (check() + encoded_bytes() <= B above); no externally cast byte owner. - Ok(unsafe { crate::rust_ggml::dot_raw(kind,row,width,a.raw()) }) -} -fn ggml_rows(kind:Kind,weights:&[u8],width:usize,acts:&[NativeActivation],out:&mut[f32])->Result<()> { - let stride=kind.row_bytes(width)?;if weights.len()%stride!=0||out.len()!=acts.len()*(weights.len()/stride){return Err(Error::Shape);} - let rows=weights.len()/stride;for(t,a)in acts.iter().enumerate(){for r in 0..rows{out[t*rows+r]=dot(kind,&weights[r*stride..(r+1)*stride],a,width)?;}}Ok(()) -} -/// Explicit IQ4_NL row kernel on the SAME 1024-byte HQ owners used by down. -fn iq4nl_hq(weights:&[u8],acts:&[NativeActivation<1024>],out:&mut[f32])->Result<()> { - if !cpu::cpu_avx2_ok()||acts.len()!=NT||weights.len()!=H*Kind::Iq4Nl.row_bytes(FF)?||out.len()!=NT*H{return Err(Error::Shape);} - for a in acts{a.check(Kind::Iq4Nl,FF)?;} - // SAFETY (this view): check(Iq4Nl,FF) pinned n == FF == 640, so 20 Q8Zero = 680 B <= the 1024-byte, 64-aligned owner. - let aa:[&[crate::rust_types::Q8Zero];NT]=std::array::from_fn(|i|unsafe{std::slice::from_raw_parts(acts[i].raw().as_ptr().cast(),FF/32)}); - // SAFETY (iq4nl): cpu_avx2_ok() checked above; each row slice is row_bytes(FF) = 360 B = 20 blocks = aa[t].len(). - for r in 0..H{let mut values=[0.0;NT];unsafe{crate::rust_iq::iq4nl(&weights[r*Kind::Iq4Nl.row_bytes(FF)?..(r+1)*Kind::Iq4Nl.row_bytes(FF)?],&aa,&mut values,false);}for t in 0..NT{out[t*H+r]=values[t];}}Ok(()) -} -fn elapsed(start:Instant,iterations:usize)->f64{start.elapsed().as_secs_f64()*1e6/iterations as f64} +const NT: usize = 3; +const H: usize = 2560; +const FF: usize = 640; +const NAMES: [&str; 43] = [ + "f32", + "f16", + "q4_0", + "q4_1", + "DEPRECATED", + "DEPRECATED", + "q5_0", + "q5_1", + "q8_0", + "q8_1", + "q2_K", + "q3_K", + "q4_K", + "q5_K", + "q6_K", + "q8_K", + "iq2_xxs", + "iq2_xs", + "iq3_xxs", + "iq1_s", + "iq4_nl", + "iq3_s", + "iq2_s", + "iq4_xs", + "i8", + "i16", + "i32", + "i64", + "f64", + "iq1_m", + "bf16", + "TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking", + "TYPE_Q4_0_4_8 REMOVED, use Q4_0 with runtime repacking", + "TYPE_Q4_0_8_8 REMOVED, use Q4_0 with runtime repacking", + "tq1_0", + "tq2_0", + "TYPE_IQ4_NL_4_4 REMOVED, use IQ4_NL with runtime repacking", + "TYPE_IQ4_NL_4_8 REMOVED, use IQ4_NL with runtime repacking", + "TYPE_IQ4_NL_8_8 REMOVED, use IQ4_NL with runtime repacking", + "mxfp4", + "nvfp4", + "q1_0", + "q2_0", +]; -fn cpu_blob(f:&NativeFormat,blob:&[u8],x:&[f32],seed:u32)->std::result::Result<(Vec,usize),String>{ - let mut failures=0usize;let gn=name(f.gu);let dn=name(f.down); - let mut act:[NativeActivation;NT]=std::array::from_fn(|_|NativeActivation::default()); - let mut hq:[NativeActivation<1024>;NT]=std::array::from_fn(|_|NativeActivation::default()); - let mut ff=numerical(zeros::(NT*FF))?; - for k in 0..NT{numerical(act[k].quantize(f.gu,&x[k*H..(k+1)*H]))?;} - numerical(cpu::native_gu_rows(f,blob,&refs(&act),&mut outputs(&mut ff,FF),0,FF))?; - if cpu::iq_supported(f.gu){ - let mut gref=numerical(zeros::(NT*FF))?;numerical(ggml_rows(f.gu,&blob[..f.up_offset],H,&act,&mut gref))?; - let start=Instant::now();for _ in 0..50{for r in 0..FF{ - std::hint::black_box(numerical(dot(f.gu,&blob[r*f.gu_row..(r+1)*f.gu_row],&act[0],H))?); - std::hint::black_box(numerical(dot(f.gu,&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row],&act[0],H))?); - }}let usg=elapsed(start,50); - for is512 in [true,false]{ - if is512&&!cpu::cpu_avx512_ok(){continue;}let tag=if is512{c"avx512"}else{c"avx2"}; - let mut g=numerical(zeros::(NT*FF))?; - numerical(cpu::iq_rows(f.gu,&blob[..f.up_offset],H,&refs(&act),&mut outputs(&mut g,FF),0,FF,is512))?; - let rg=rel(&g,&gref)?;report!(" %s %s gate rows vs ggml vec_dot: rel %.2e\n",gn.as_ptr(),tag.as_ptr(),rg); - if rg>1e-5{report!(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n",gn.as_ptr(),tag.as_ptr(),rg);failures+=1;} - let a1=[&act[0]];let mut f1=[&mut ff[..FF]]; - let start=Instant::now();for _ in 0..50{numerical(cpu::iq_gu_rows(f,blob,&a1,&mut f1,0,FF,is512))?;}let us1=elapsed(start,50); - let aa=[&act[0],&act[1],&act[2]];let mut views=outputs(&mut ff,FF); - let start=Instant::now();for _ in 0..50{numerical(cpu::iq_gu_rows(f,blob,&aa,&mut views,0,FF,is512))?;}let usn=elapsed(start,50); - report!(" gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n",tag.as_ptr(),us1,2.0*f.up_offset as f64/us1/1e3,usg,2.0*f.up_offset as f64/usg/1e3); - report!(" gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n",NT as c_int,tag.as_ptr(),usn,NT as c_int,usg); - } - } - // Original quantizes the ff left by the explicit throughput loops, BEFORE - // re-running GU for width invariance. Do not quantize hq again afterwards. - for k in 0..NT{numerical(hq[k].quantize(f.down,&ff[k*FF..(k+1)*FF]))?;} - let mut got=numerical(zeros::(NT*H))?; - numerical(cpu::native_down_rows(f,blob,&refs(&hq),&mut outputs(&mut got,H),0,H))?; - numerical(cpu::native_gu_rows(f,blob,&refs(&act),&mut outputs(&mut ff,FF),0,FF))?; - let(mut gu_diff,mut dn_diff)=(0usize,0usize);let mut one_ff=numerical(zeros::(FF))?;let mut one_out=numerical(zeros::(H))?; - for k in 0..NT{ - numerical(cpu::native_gu_rows(f,blob,&[&act[k]],&mut [&mut one_ff],0,FF))?; - gu_diff+=bits(&one_ff,&ff[k*FF..(k+1)*FF])?; - numerical(cpu::native_down_rows(f,blob,&[&hq[k]],&mut [&mut one_out],0,H))?; - dn_diff+=bits(&one_out,&got[k*H..(k+1)*H])?; - } - report!(" width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n",NT as c_int,gu_diff,dn_diff); - if gu_diff!=0||dn_diff!=0{failures+=1;} - for role in 0..2{ - let kind=if role==0{f.gu}else{f.down};if !cpu::kq_supported(kind)||(role==0&&kind!=Kind::Q4K){continue;} - let(width,rows,stride,w)=if role==0{(H,FF,f.gu_row,&blob[..f.up_offset])}else{(FF,H,f.down_row,&blob[f.down_offset..])}; - let mut rng=bench::Mt19937::new(77u32.wrapping_add(seed));let mut normal=bench::NormalFloat::default(); - let mut xs=numerical(zeros::(width))?;let mut acts:[NativeActivation;8]=std::array::from_fn(|_|NativeActivation::default()); - for a in &mut acts{for v in &mut xs{*v=normal.next(&mut rng);}numerical(a.quantize(kind,&xs))?;} - let mut reference=numerical(zeros::(8*rows))?;let mut values=numerical(zeros::(8*rows))?; - numerical(ggml_rows(kind,w,width,&acts,&mut reference))?;let mut differ=0usize; - for nt in 1..=8{numerical(cpu::kq_rows(kind,w,width,&refs(&acts[..nt]),&mut outputs(&mut values[..nt*rows],rows),0,rows))?;for t in 0..nt{differ+=usize::from(bits(&values[t*rows..(t+1)*rows],&reference[t*rows..(t+1)*rows])?!=0);}} - let aa=[&acts[0],&acts[1],&acts[2],&acts[3]];let mut views=outputs(&mut values[..4*rows],rows); - let start=Instant::now();for _ in 0..30{numerical(cpu::kq_rows(kind,w,width,&aa,&mut views,0,rows))?;}let usk=elapsed(start,30); - drop(views); - let start=Instant::now();for _ in 0..30{for r in 0..rows{for t in 0..4{values[t*rows+r]=numerical(dot(kind,&w[r*stride..(r+1)*stride],&acts[t],width))?;}}}let usg=elapsed(start,30); - let kn=name(kind);let rn=if role==0{c"gate"}else{c"down"}; - report!(" %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; 4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n",kn.as_ptr(),rn.as_ptr(),differ,usk,usg,usg/usk); - if differ!=0{failures+=1;} - } - if f.down==Kind::Q2Zero{ - let mut a:[crate::rust_legacy::PlanarActivation;NT]=std::array::from_fn(|_|crate::rust_legacy::PlanarActivation::default()); - for k in 0..NT{numerical(a[k].quantize_native(&ff[k*FF..(k+1)*FF]))?;} - let mut alt=numerical(zeros::(NT*H))?;let aa:Vec<_>=a.iter().collect(); - numerical(cpu::q2_rows(&blob[f.down_offset..],FF,&aa,&mut outputs(&mut alt,H),0,H))?; - let tag=if cpu::cpu_avx512_ok(){c"AVX-512"}else{c"AVX-2"}; - report!(" q2_0 %s down vs ggml down: rel %.2e\n",tag.as_ptr(),rel(&alt,&got)?); - } - if f.down==Kind::Iq4Nl{ - let mut alt=numerical(zeros::(NT*H))?;let mut reference=numerical(zeros::(NT*H))?; - numerical(iq4nl_hq(&blob[f.down_offset..],&hq,&mut alt))?; - numerical(ggml_rows(f.down,&blob[f.down_offset..],FF,&hq,&mut reference))?; - let rdn=rel(&alt,&reference)?;report!(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n",rdn); - if rdn>1e-5{report!(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n",rdn);failures+=1;} - let start=Instant::now();for _ in 0..50{numerical(iq4nl_hq(&blob[f.down_offset..],&hq,&mut alt))?;}let usn=elapsed(start,50); - let start=Instant::now();for _ in 0..50{numerical(ggml_rows(f.down,&blob[f.down_offset..],FF,&hq,&mut reference))?;}let usg=elapsed(start,50); - report!(" down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n",NT as c_int,usn,(f.bytes-f.down_offset) as f64/usn/1e3,usg,(f.bytes-f.down_offset) as f64/usg/1e3); - } - // Keep the Original type name owner alive through all variadic calls. - drop(dn);Ok((got,failures)) -} +#[repr(C, align(64))] +struct Q81Owner([u8; 720]); +const USAGE: &str = "usage: native_expert_parity [layer ...]\n native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n native_expert_parity --q5_1-min\n native_expert_parity --bf16-embd\n"; -fn float_reference(weights:&bench::DequantizedExpert,input:&[f32])->Result> { - if input.len()!=NT*H||weights.gate.len()!=FF*H||weights.up.len()!=FF*H||weights.down.len()!=H*FF{return Err(Error::Shape);} - let mut out=zeros::(NT*H)?; - for t in 0..NT{let mut hidden=zeros::(FF)?; - for r in 0..FF{let(mut g,mut u)=(0.0f64,0.0f64);for i in 0..H{g+=weights.gate[r*H+i] as f64*input[t*H+i] as f64;u+=weights.up[r*H+i] as f64*input[t*H+i] as f64;}hidden[r]=(g/(1.0+(-g).exp())*u)as f32;} - for r in 0..H{let mut value=0.0f64;for i in 0..FF{value+=weights.down[r*FF+i]as f64*hidden[i]as f64;}out[t*H+r]=value as f32;} - }Ok(out) -} - -fn check_blob(f:&NativeFormat,blob:&[u8],seed:u32,label:&str,gpu:&mut G)->std::result::Result{ - let weights=numerical(bench::dequantize_expert(f,blob))?; - let x=numerical(bench::check_inputs(seed,NT,H))?; - let reference=numerical(float_reference(&weights,&x))?; - let (cpu,mut failures)=cpu_blob(f,blob,&x,seed)?; - let mut expert=gpu.prepare_expert(f,blob,&x)?; - let candidate=(||{ - gpu.enqueue_expert(&mut expert)?;let got=gpu.download_expert(&mut expert)?; - if got.len()!=NT*H{return Err("GPU expert output extent".into());} - let was=gpu.old_kernels();gpu.set_old_kernels(!was); - let enqueue=gpu.enqueue_expert(&mut expert);gpu.set_old_kernels(was);enqueue?; - let old=gpu.download_expert(&mut expert)?;let same=bits(&old,&got)?==0; - report!(" gpu decode-once vs per-entry kernels: %s\n",if same{c"bitwise equal"}else{c"MISMATCH"}.as_ptr()); - if !same{failures+=1;} - let(mut dqerr,mut differ,mut hdiffer)=(0.0f64,0usize,0usize); - for (role,want) in [&weights.gate,&weights.up,&weights.down].iter().enumerate(){ - let(dq,dh)=gpu.dequantize_expert_role(&expert,role)?; - if dq.len()!=FF*H||dh.len()!=FF*H{return Err("GPU dequant output extent".into());} - // std::max(old, value) preserves old on NaN (not f64::max policy). - let e=rel(&dq,want)?;if dqerr=(0..FF).map(|r|(FF-1-r) as i32).collect();let emb=gpu.embed_expert_gate(&expert,&tk)?; - if emb.len()!=FF*H{return Err("GPU embedding output extent".into());}let mut embdiff=0usize; - for r in 0..FF{embdiff+=usize::from(bits(&emb[r*H..(r+1)*H],&weights.gate[(FF-1-r)*H..(FF-r)*H])?!=0);} - report!(" GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of it: %zu differ; embedding rows: %zu of %lld differ\n",dqerr,differ,(3*FF*H) as i64,hdiffer,embdiff,FF as i64); - if !(dqerr<1e-6)||hdiffer!=0||(f.gu==Kind::Q8Zero&&f.down==Kind::Q8Zero&&(differ!=0||embdiff!=0)){failures+=1;} - Ok(got) - })(); - let close=gpu.release_expert(expert); - let got=match(candidate,close){(Err(e),_)=>return Err(e),(Ok(_),Err(e))=>return Err(e),(Ok(v),Ok(()))=>v}; - let(ec,eg,ecg)=(rel(&cpu,&reference)?,rel(&got,&reference)?,rel(&cpu,&got)?); - let ok=ec<3e-2&&eg<3e-2&&ec.is_finite()&&eg.is_finite();let label=CString::new(label).map_err(|_|"benchmark label contains NUL")?;let gn=name(f.gu);let dn=name(f.down); - report!("%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n",label.as_ptr(),gn.as_ptr(),dn.as_ptr(),f.bytes,ec,eg,ecg,if ok{c"ok"}else{c"FAIL"}.as_ptr()); - Ok(failures+usize::from(!ok)) -} - -#[repr(C,align(64))] struct Q81Owner([u8;720]); -fn check_q5_one(gpu:&mut G)->std::result::Result{ - let case=numerical(bench::q5_one_min_case())?; - let(got,raw)=gpu.q5_one_min(&case.weights,&case.input)?; - if got.len()!=64||raw.len()!=720{return Err("Q5_1 GPU product extent".into());} - if !cpu::cpu_avx2_ok(){return Err("Q5_1 CPU unsupported".into());} - let mut stored=Q81Owner([0;720]);stored.0.copy_from_slice(&raw);let mut summed=Q81Owner(stored.0); - let mut shift=0.0f64; - // SAFETY (the half/to_half calls in this loop): cpu_avx2_ok() (F16C) was checked at the top of this function. - for b in summed.0.chunks_exact_mut(36){ - let d=u16::from_le_bytes([b[0],b[1]]);let s=u16::from_le_bytes([b[2],b[3]]); - let sum=b[4..].iter().map(|v|*v as i8 as i32).sum::(); - let dd=unsafe{crate::rust_simd::half(d)};let ss=unsafe{crate::rust_simd::half(s)}; - let e=(ss-dd*sum as f32).abs() as f64;if shift(64))?;let mut original=numerical(zeros::(64))?; - let stride=numerical(Kind::Q5One.row_bytes(640))?; - // SAFETY (dot_raw): `row` is one Q5_1 row (stride = row_bytes(640)); `summed.0`/`stored.0` are 720-byte, 64-aligned Q81Owner = 20 Q8One blocks. - for r in 0..64{let row=&case.weights[r*stride..(r+1)*stride];unsafe{ - want[r]=crate::rust_ggml::dot_raw(Kind::Q5One,row,640,&summed.0); - original[r]=crate::rust_ggml::dot_raw(Kind::Q5One,row,640,&stored.0); - }} - let(eq,es)=(rel(&got,&want)?,rel(&got,&original)?);let ok=eq<1e-3&&es>10.0*eq&&shift>0.0; - report!("q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n",got[0] as f64,want[0] as f64,original[0] as f64); - report!("q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e (largest per-block sum shift %.3g) %s\n",eq,es,shift,if ok{c"ok"}else{c"FAIL"}.as_ptr()); - Ok(usize::from(!ok)) -} -fn check_bf16(gpu:&mut G)->std::result::Result{ - if !gpu.embed_type_supported(30)||gpu.iq_supported(30)||gpu.row_bytes(30,H)!=H*2{report!("bf16 embedding: type support / row bytes wrong\n");return Ok(1);} - let mut rng=bench::Mt19937::new(290);let mut table=numerical(zeros::(61*H))?; - for v in &mut table{loop{*v=(rng.next_u32()&0xffff)as u16;if !(*v&0x7f80==0x7f80&&*v&0x7f!=0){break;}}} - let ids:Vec=(0..97).map(|_|(rng.next_u32()%61)as i32).collect();let(gathered,dequant)=gpu.bf16_embedding(&table,&ids)?; - if gathered.len()!=97*H||dequant.len()!=table.len(){return Err("BF16 GPU products extent".into());} - let mut rows=0usize;for(r,&id)in ids.iter().enumerate(){for d in 0..H{if gathered[r*H+d].to_bits()!=(table[id as usize*H+d]as u32)<<16{rows+=1;break;}}} - let values=dequant.iter().zip(&table).filter(|(f,b)|f.to_bits()!=(**b as u32)<<16).count(); - report!("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n",97i64,rows,(61*H)as i64,values); - Ok(usize::from(rows!=0||values!=0)) -} -const USAGE:&str="usage: native_expert_parity [layer ...]\n native_expert_parity --synthetic GU/DOWN ... (ggml type names, e.g. q4_K/q5_1)\n native_expert_parity --q5_1-min\n native_expert_parity --bf16-embd\n"; -/// # Safety -/// Call ONLY at process entry before any thread or native CPU dispatch exists: -/// Original's absent-only setenv occurs here, before the actual stream factory. -/// `create_gpu` must create an actual stream and bind the declared owned methods. -pub unsafe fn run(args:&[String],create_gpu:impl FnOnce()->std::result::Result)->i32{ - // SAFETY: `stdout` is glibc's FILE* global, read by value; unbuffering it before any output is the documented single-threaded entry. - unsafe{setvbuf(stdout,std::ptr::null_mut(),2,0);} - if args.len()<2{eprint!("{USAGE}");return 2;} - // SAFETY: NUL-terminated literals; setenv races with other threads' getenv, so this relies on this fn's contract (process entry); - // rust_bench_cuda::main sets the variable first, so the branch is dead there (see its SAFETY note). - if std::env::var_os("STRATA_IQ_MT_MIN").is_none(){if unsafe{setenv(c"STRATA_IQ_MT_MIN".as_ptr(),c"1".as_ptr(),1)}!=0{eprintln!("native_expert_parity: setenv failed");return 1;}} - let mut gpu=match create_gpu(){Ok(g)=>g,Err(e)=>{eprintln!("native_expert_parity: {e}");return 1;}}; - let result=run_modes(args,&mut gpu);let close=gpu.close(); - match(result,close){(Err(e),_)|(Ok(_),Err(e))=>{eprintln!("native_expert_parity: {e}");1},(Ok(failures),Ok(()))=>{report!("native_expert_parity: %d failures\n",failures as c_int);i32::from(failures!=0)}} -} -fn run_modes(args:&[String],gpu:&mut G)->std::result::Result{ - match args[1].as_str(){ - "--q5_1-min"=>check_q5_one(gpu),"--bf16-embd"=>check_bf16(gpu), - "--synthetic"=>{let mut failures=0;for(i,arg)in args.iter().enumerate().skip(2){ - let(gu,dn)=arg.split_once('/').map_or((-1,-1),|(g,d)|(type_of(g),type_of(d))); - let format=if gu<0||dn<0{Err(String::new())}else{native_fmt(gu,dn)}; - let f=match format{Ok(f)if gpu::expert_supported(f.gu,f.down,H,FF)=>f,Ok(_)=>{let arg=CString::new(arg.as_str()).map_err(|_|"argument contains NUL")?;report!("%s: not a pair the GPU expert kernels take\n",arg.as_ptr());failures+=1;continue;},Err(e)=>{let arg=CString::new(arg.as_str()).map_err(|_|"argument contains NUL")?;let err=CString::new(if e.is_empty(){"not a pair the GPU expert kernels take".into()}else{e}).unwrap();report!("%s: %s\n",arg.as_ptr(),err.as_ptr());failures+=1;continue;}}; - let blob=numerical(bench::synthetic_blob(&f,i as u32))?;failures+=check_blob(&f,&blob,i as u32,"synthetic",gpu)?; - }Ok(failures)}, - path=>{let model=model::Model::open(path)?;let layers=if args.len()==2{vec![0,1,2,3,20,47]}else{args[2..].iter().map(|v|crate::rust_simd::atoi(v)).collect()};let mut failures=0; - for layer in layers{let Some((g,d))=model.kinds(layer)else{report!("layer %d: no expert tensors\n",layer as c_int);failures+=1;continue;}; - let f=match native_fmt(g,d){Ok(f)=>f,Err(e)=>{let err=CString::new(e).unwrap();report!("layer %d: %s\n",layer as c_int,err.as_ptr());failures+=1;continue;}}; - let blob=model.expert(layer,&f)?;failures+=check_blob(&f,&blob,layer as u32,&format!("layer {layer}"),gpu)?; - }Ok(failures)} - } -} -/// Explicit executable linkage refusal until Root supplies a genuine driver -/// stream factory. No benchmark check, failure count or GPU value is invented. -pub fn unbound_main()->i32{ - let args:Vec=std::env::args().collect(); - if args.len()<2{eprint!("{USAGE}");2}else{eprintln!("native_expert_parity: source-unresolved genuine CUDA ParityGpu binding; no benchmark executed");1} -} +mod numerical_fn; +#[allow(unused_imports)] +use numerical_fn::bits; +#[allow(unused_imports)] +use numerical_fn::dot; +#[allow(unused_imports)] +use numerical_fn::elapsed; +#[allow(unused_imports)] +use numerical_fn::ggml_rows; +#[allow(unused_imports)] +use numerical_fn::iq4nl_hq; +#[allow(unused_imports)] +use numerical_fn::name; +#[allow(unused_imports)] +use numerical_fn::native_fmt; +#[allow(unused_imports)] +use numerical_fn::numerical; +#[allow(unused_imports)] +use numerical_fn::outputs; +#[allow(unused_imports)] +use numerical_fn::refs; +#[allow(unused_imports)] +use numerical_fn::rel; +#[allow(unused_imports)] +use numerical_fn::type_of; +#[allow(unused_imports)] +use numerical_fn::zeros; +mod cpu_blob_fn; +#[allow(unused_imports)] +use cpu_blob_fn::cpu_blob; +mod float_reference_fn; +#[allow(unused_imports)] +use float_reference_fn::check_bf16; +#[allow(unused_imports)] +use float_reference_fn::check_blob; +#[allow(unused_imports)] +use float_reference_fn::check_q5_one; +#[allow(unused_imports)] +use float_reference_fn::float_reference; +mod run_fn; +#[allow(unused_imports)] +pub use run_fn::run; +#[allow(unused_imports)] +use run_fn::run_modes; +#[allow(unused_imports)] +pub use run_fn::unbound_main; diff --git a/crates/native-cpu-expert/src/rust_bench_frontend/cpu_blob_fn.rs b/crates/native-cpu-expert/src/rust_bench_frontend/cpu_blob_fn.rs new file mode 100644 index 00000000..6a99b364 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_bench_frontend/cpu_blob_fn.rs @@ -0,0 +1,234 @@ +//! Moved out of the parent module by STRA-338: fn cpu_blob. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn cpu_blob( + f: &NativeFormat, + blob: &[u8], + x: &[f32], + seed: u32, +) -> std::result::Result<(Vec, usize), String> { + let mut failures = 0usize; + let gn = name(f.gu); + let dn = name(f.down); + let mut act: [NativeActivation; NT] = std::array::from_fn(|_| NativeActivation::default()); + let mut hq: [NativeActivation<1024>; NT] = std::array::from_fn(|_| NativeActivation::default()); + let mut ff = numerical(zeros::(NT * FF))?; + for k in 0..NT { + numerical(act[k].quantize(f.gu, &x[k * H..(k + 1) * H]))?; + } + numerical(cpu::native_gu_rows(f, blob, &refs(&act), &mut outputs(&mut ff, FF), 0, FF))?; + if cpu::iq_supported(f.gu) { + let mut gref = numerical(zeros::(NT * FF))?; + numerical(ggml_rows(f.gu, &blob[..f.up_offset], H, &act, &mut gref))?; + let start = Instant::now(); + for _ in 0..50 { + for r in 0..FF { + std::hint::black_box(numerical(dot(f.gu, &blob[r * f.gu_row..(r + 1) * f.gu_row], &act[0], H))?); + std::hint::black_box(numerical(dot( + f.gu, + &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row], + &act[0], + H, + ))?); + } + } + let usg = elapsed(start, 50); + for is512 in [true, false] { + if is512 && !cpu::cpu_avx512_ok() { + continue; + } + let tag = if is512 { c"avx512" } else { c"avx2" }; + let mut g = numerical(zeros::(NT * FF))?; + numerical(cpu::iq_rows( + f.gu, + &blob[..f.up_offset], + H, + &refs(&act), + &mut outputs(&mut g, FF), + 0, + FF, + is512, + ))?; + let rg = rel(&g, &gref)?; + report!(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", gn.as_ptr(), tag.as_ptr(), rg); + if rg > 1e-5 { + report!(" %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n", gn.as_ptr(), tag.as_ptr(), rg); + failures += 1; + } + let a1 = [&act[0]]; + let mut f1 = [&mut ff[..FF]]; + let start = Instant::now(); + for _ in 0..50 { + numerical(cpu::iq_gu_rows(f, blob, &a1, &mut f1, 0, FF, is512))?; + } + let us1 = elapsed(start, 50); + let aa = [&act[0], &act[1], &act[2]]; + let mut views = outputs(&mut ff, FF); + let start = Instant::now(); + for _ in 0..50 { + numerical(cpu::iq_gu_rows(f, blob, &aa, &mut views, 0, FF, is512))?; + } + let usn = elapsed(start, 50); + report!( + " gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n", + tag.as_ptr(), + us1, + 2.0 * f.up_offset as f64 / us1 / 1e3, + usg, + 2.0 * f.up_offset as f64 / usg / 1e3 + ); + report!( + " gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", + NT as c_int, + tag.as_ptr(), + usn, + NT as c_int, + usg + ); + } + } + // Original quantizes the ff left by the explicit throughput loops, BEFORE + // re-running GU for width invariance. Do not quantize hq again afterwards. + for k in 0..NT { + numerical(hq[k].quantize(f.down, &ff[k * FF..(k + 1) * FF]))?; + } + let mut got = numerical(zeros::(NT * H))?; + numerical(cpu::native_down_rows(f, blob, &refs(&hq), &mut outputs(&mut got, H), 0, H))?; + numerical(cpu::native_gu_rows(f, blob, &refs(&act), &mut outputs(&mut ff, FF), 0, FF))?; + let (mut gu_diff, mut dn_diff) = (0usize, 0usize); + let mut one_ff = numerical(zeros::(FF))?; + let mut one_out = numerical(zeros::(H))?; + for k in 0..NT { + numerical(cpu::native_gu_rows(f, blob, &[&act[k]], &mut [&mut one_ff], 0, FF))?; + gu_diff += bits(&one_ff, &ff[k * FF..(k + 1) * FF])?; + numerical(cpu::native_down_rows(f, blob, &[&hq[k]], &mut [&mut one_out], 0, H))?; + dn_diff += bits(&one_out, &got[k * H..(k + 1) * H])?; + } + report!( + " width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", + NT as c_int, + gu_diff, + dn_diff + ); + if gu_diff != 0 || dn_diff != 0 { + failures += 1; + } + for role in 0..2 { + let kind = if role == 0 { f.gu } else { f.down }; + if !cpu::kq_supported(kind) || (role == 0 && kind != Kind::Q4K) { + continue; + } + let (width, rows, stride, w) = if role == 0 { + (H, FF, f.gu_row, &blob[..f.up_offset]) + } else { + (FF, H, f.down_row, &blob[f.down_offset..]) + }; + let mut rng = bench::Mt19937::new(77u32.wrapping_add(seed)); + let mut normal = bench::NormalFloat::default(); + let mut xs = numerical(zeros::(width))?; + let mut acts: [NativeActivation; 8] = std::array::from_fn(|_| NativeActivation::default()); + for a in &mut acts { + for v in &mut xs { + *v = normal.next(&mut rng); + } + numerical(a.quantize(kind, &xs))?; + } + let mut reference = numerical(zeros::(8 * rows))?; + let mut values = numerical(zeros::(8 * rows))?; + numerical(ggml_rows(kind, w, width, &acts, &mut reference))?; + let mut differ = 0usize; + for nt in 1..=8 { + numerical(cpu::kq_rows( + kind, + w, + width, + &refs(&acts[..nt]), + &mut outputs(&mut values[..nt * rows], rows), + 0, + rows, + ))?; + for t in 0..nt { + differ += + usize::from(bits(&values[t * rows..(t + 1) * rows], &reference[t * rows..(t + 1) * rows])? != 0); + } + } + let aa = [&acts[0], &acts[1], &acts[2], &acts[3]]; + let mut views = outputs(&mut values[..4 * rows], rows); + let start = Instant::now(); + for _ in 0..30 { + numerical(cpu::kq_rows(kind, w, width, &aa, &mut views, 0, rows))?; + } + let usk = elapsed(start, 30); + drop(views); + let start = Instant::now(); + for _ in 0..30 { + for r in 0..rows { + for t in 0..4 { + values[t * rows + r] = numerical(dot(kind, &w[r * stride..(r + 1) * stride], &acts[t], width))?; + } + } + } + let usg = elapsed(start, 30); + let kn = name(kind); + let rn = if role == 0 { c"gate" } else { c"down" }; + report!( + " %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; 4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n", + kn.as_ptr(), + rn.as_ptr(), + differ, + usk, + usg, + usg / usk + ); + if differ != 0 { + failures += 1; + } + } + if f.down == Kind::Q2Zero { + let mut a: [crate::rust_legacy::PlanarActivation; NT] = + std::array::from_fn(|_| crate::rust_legacy::PlanarActivation::default()); + for k in 0..NT { + numerical(a[k].quantize_native(&ff[k * FF..(k + 1) * FF]))?; + } + let mut alt = numerical(zeros::(NT * H))?; + let aa: Vec<_> = a.iter().collect(); + numerical(cpu::q2_rows(&blob[f.down_offset..], FF, &aa, &mut outputs(&mut alt, H), 0, H))?; + let tag = if cpu::cpu_avx512_ok() { c"AVX-512" } else { c"AVX-2" }; + report!(" q2_0 %s down vs ggml down: rel %.2e\n", tag.as_ptr(), rel(&alt, &got)?); + } + if f.down == Kind::Iq4Nl { + let mut alt = numerical(zeros::(NT * H))?; + let mut reference = numerical(zeros::(NT * H))?; + numerical(iq4nl_hq(&blob[f.down_offset..], &hq, &mut alt))?; + numerical(ggml_rows(f.down, &blob[f.down_offset..], FF, &hq, &mut reference))?; + let rdn = rel(&alt, &reference)?; + report!(" iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn); + if rdn > 1e-5 { + report!(" iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn); + failures += 1; + } + let start = Instant::now(); + for _ in 0..50 { + numerical(iq4nl_hq(&blob[f.down_offset..], &hq, &mut alt))?; + } + let usn = elapsed(start, 50); + let start = Instant::now(); + for _ in 0..50 { + numerical(ggml_rows(f.down, &blob[f.down_offset..], FF, &hq, &mut reference))?; + } + let usg = elapsed(start, 50); + report!( + " down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n", + NT as c_int, + usn, + (f.bytes - f.down_offset) as f64 / usn / 1e3, + usg, + (f.bytes - f.down_offset) as f64 / usg / 1e3 + ); + } + // Keep the Original type name owner alive through all variadic calls. + drop(dn); + Ok((got, failures)) +} diff --git a/crates/native-cpu-expert/src/rust_bench_frontend/float_reference_fn.rs b/crates/native-cpu-expert/src/rust_bench_frontend/float_reference_fn.rs new file mode 100644 index 00000000..90742000 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_bench_frontend/float_reference_fn.rs @@ -0,0 +1,230 @@ +//! Moved out of the parent module by STRA-338: fn float_reference, fn check_blob, fn check_q5_one, fn check_bf16. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn float_reference(weights: &bench::DequantizedExpert, input: &[f32]) -> Result> { + if input.len() != NT * H + || weights.gate.len() != FF * H + || weights.up.len() != FF * H + || weights.down.len() != H * FF + { + return Err(Error::Shape); + } + let mut out = zeros::(NT * H)?; + for t in 0..NT { + let mut hidden = zeros::(FF)?; + for r in 0..FF { + let (mut g, mut u) = (0.0f64, 0.0f64); + for i in 0..H { + g += weights.gate[r * H + i] as f64 * input[t * H + i] as f64; + u += weights.up[r * H + i] as f64 * input[t * H + i] as f64; + } + hidden[r] = (g / (1.0 + (-g).exp()) * u) as f32; + } + for r in 0..H { + let mut value = 0.0f64; + for i in 0..FF { + value += weights.down[r * FF + i] as f64 * hidden[i] as f64; + } + out[t * H + r] = value as f32; + } + } + Ok(out) +} + +pub(super) fn check_blob( + f: &NativeFormat, + blob: &[u8], + seed: u32, + label: &str, + gpu: &mut G, +) -> std::result::Result { + let weights = numerical(bench::dequantize_expert(f, blob))?; + let x = numerical(bench::check_inputs(seed, NT, H))?; + let reference = numerical(float_reference(&weights, &x))?; + let (cpu, mut failures) = cpu_blob(f, blob, &x, seed)?; + let mut expert = gpu.prepare_expert(f, blob, &x)?; + let candidate = (|| { + gpu.enqueue_expert(&mut expert)?; + let got = gpu.download_expert(&mut expert)?; + if got.len() != NT * H { + return Err("GPU expert output extent".into()); + } + let was = gpu.old_kernels(); + gpu.set_old_kernels(!was); + let enqueue = gpu.enqueue_expert(&mut expert); + gpu.set_old_kernels(was); + enqueue?; + let old = gpu.download_expert(&mut expert)?; + let same = bits(&old, &got)? == 0; + report!( + " gpu decode-once vs per-entry kernels: %s\n", + if same { c"bitwise equal" } else { c"MISMATCH" }.as_ptr() + ); + if !same { + failures += 1; + } + let (mut dqerr, mut differ, mut hdiffer) = (0.0f64, 0usize, 0usize); + for (role, want) in [&weights.gate, &weights.up, &weights.down].iter().enumerate() { + let (dq, dh) = gpu.dequantize_expert_role(&expert, role)?; + if dq.len() != FF * H || dh.len() != FF * H { + return Err("GPU dequant output extent".into()); + } + // std::max(old, value) preserves old on NaN (not f64::max policy). + let e = rel(&dq, want)?; + if dqerr < e { + dqerr = e; + } + differ += bits(&dq, want)?; + if !cpu::cpu_avx2_ok() { + return Err("CPU FP16 conversion unsupported".into()); + } + // SAFETY (to_half below): cpu_avx2_ok() (F16C) checked on the previous line. + for (v, h) in dq.iter().zip(dh) { + hdiffer += usize::from(h != unsafe { crate::rust_simd::to_half(*v) }); + } + } + let tk: Vec = (0..FF).map(|r| (FF - 1 - r) as i32).collect(); + let emb = gpu.embed_expert_gate(&expert, &tk)?; + if emb.len() != FF * H { + return Err("GPU embedding output extent".into()); + } + let mut embdiff = 0usize; + for r in 0..FF { + embdiff += usize::from(bits(&emb[r * H..(r + 1) * H], &weights.gate[(FF - 1 - r) * H..(FF - r) * H])? != 0); + } + report!( + " GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of it: %zu differ; embedding rows: %zu of %lld differ\n", + dqerr, + differ, + (3 * FF * H) as i64, + hdiffer, + embdiff, + FF as i64 + ); + if !(dqerr < 1e-6) + || hdiffer != 0 + || (f.gu == Kind::Q8Zero && f.down == Kind::Q8Zero && (differ != 0 || embdiff != 0)) + { + failures += 1; + } + Ok(got) + })(); + let close = gpu.release_expert(expert); + let got = match (candidate, close) { + (Err(e), _) => return Err(e), + (Ok(_), Err(e)) => return Err(e), + (Ok(v), Ok(())) => v, + }; + let (ec, eg, ecg) = (rel(&cpu, &reference)?, rel(&got, &reference)?, rel(&cpu, &got)?); + let ok = ec < 3e-2 && eg < 3e-2 && ec.is_finite() && eg.is_finite(); + let label = CString::new(label).map_err(|_| "benchmark label contains NUL")?; + let gn = name(f.gu); + let dn = name(f.down); + report!( + "%-9s %-8s/%-7s blob %8zu cpu rel %.2e gpu rel %.2e cpu-gpu %.2e %s\n", + label.as_ptr(), + gn.as_ptr(), + dn.as_ptr(), + f.bytes, + ec, + eg, + ecg, + if ok { c"ok" } else { c"FAIL" }.as_ptr() + ); + Ok(failures + usize::from(!ok)) +} +pub(super) fn check_q5_one(gpu: &mut G) -> std::result::Result { + let case = numerical(bench::q5_one_min_case())?; + let (got, raw) = gpu.q5_one_min(&case.weights, &case.input)?; + if got.len() != 64 || raw.len() != 720 { + return Err("Q5_1 GPU product extent".into()); + } + if !cpu::cpu_avx2_ok() { + return Err("Q5_1 CPU unsupported".into()); + } + let mut stored = Q81Owner([0; 720]); + stored.0.copy_from_slice(&raw); + let mut summed = Q81Owner(stored.0); + let mut shift = 0.0f64; + // SAFETY (the half/to_half calls in this loop): cpu_avx2_ok() (F16C) was checked at the top of this function. + for b in summed.0.chunks_exact_mut(36) { + let d = u16::from_le_bytes([b[0], b[1]]); + let s = u16::from_le_bytes([b[2], b[3]]); + let sum = b[4..].iter().map(|v| *v as i8 as i32).sum::(); + let dd = unsafe { crate::rust_simd::half(d) }; + let ss = unsafe { crate::rust_simd::half(s) }; + let e = (ss - dd * sum as f32).abs() as f64; + if shift < e { + shift = e; + } + b[2..4].copy_from_slice(&unsafe { crate::rust_simd::to_half(dd * sum as f32) }.to_le_bytes()); + } + let mut want = numerical(zeros::(64))?; + let mut original = numerical(zeros::(64))?; + let stride = numerical(Kind::Q5One.row_bytes(640))?; + // SAFETY (dot_raw): `row` is one Q5_1 row (stride = row_bytes(640)); `summed.0`/`stored.0` are 720-byte, 64-aligned Q81Owner = 20 Q8One blocks. + for r in 0..64 { + let row = &case.weights[r * stride..(r + 1) * stride]; + unsafe { + want[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &summed.0); + original[r] = crate::rust_ggml::dot_raw(Kind::Q5One, row, 640, &stored.0); + } + } + let (eq, es) = (rel(&got, &want)?, rel(&got, &original)?); + let ok = eq < 1e-3 && es > 10.0 * eq && shift > 0.0; + report!( + "q5_1 min row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n", + got[0] as f64, + want[0] as f64, + original[0] as f64 + ); + report!( + "q5_1 min GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e (largest per-block sum shift %.3g) %s\n", + eq, + es, + shift, + if ok { c"ok" } else { c"FAIL" }.as_ptr() + ); + Ok(usize::from(!ok)) +} +pub(super) fn check_bf16(gpu: &mut G) -> std::result::Result { + if !gpu.embed_type_supported(30) || gpu.iq_supported(30) || gpu.row_bytes(30, H) != H * 2 { + report!("bf16 embedding: type support / row bytes wrong\n"); + return Ok(1); + } + let mut rng = bench::Mt19937::new(290); + let mut table = numerical(zeros::(61 * H))?; + for v in &mut table { + loop { + *v = (rng.next_u32() & 0xffff) as u16; + if !(*v & 0x7f80 == 0x7f80 && *v & 0x7f != 0) { + break; + } + } + } + let ids: Vec = (0..97).map(|_| (rng.next_u32() % 61) as i32).collect(); + let (gathered, dequant) = gpu.bf16_embedding(&table, &ids)?; + if gathered.len() != 97 * H || dequant.len() != table.len() { + return Err("BF16 GPU products extent".into()); + } + let mut rows = 0usize; + for (r, &id) in ids.iter().enumerate() { + for d in 0..H { + if gathered[r * H + d].to_bits() != (table[id as usize * H + d] as u32) << 16 { + rows += 1; + break; + } + } + } + let values = dequant.iter().zip(&table).filter(|(f, b)| f.to_bits() != (**b as u32) << 16).count(); + report!( + "bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n", + 97i64, + rows, + (61 * H) as i64, + values + ); + Ok(usize::from(rows != 0 || values != 0)) +} diff --git a/crates/native-cpu-expert/src/rust_bench_frontend/numerical_fn.rs b/crates/native-cpu-expert/src/rust_bench_frontend/numerical_fn.rs new file mode 100644 index 00000000..73db3abe --- /dev/null +++ b/crates/native-cpu-expert/src/rust_bench_frontend/numerical_fn.rs @@ -0,0 +1,107 @@ +//! Moved out of the parent module by STRA-338: fn numerical, fn zeros, fn refs, fn outputs, fn rel, fn bits .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn numerical(r: Result) -> std::result::Result { + r.map_err(|e| format!("CPU benchmark: {e:?}")) +} +pub(super) fn zeros(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize_with(n, T::default); + Ok(v) +} +pub(super) fn refs(a: &[NativeActivation]) -> Vec<&NativeActivation> { + a.iter().collect() +} +pub(super) fn outputs(v: &mut [f32], width: usize) -> Vec<&mut [f32]> { + v.chunks_exact_mut(width).collect() +} +pub(super) fn rel(a: &[f32], b: &[f32]) -> std::result::Result { + numerical(bench::relative_l1(a, b)) +} +pub(super) fn bits(a: &[f32], b: &[f32]) -> std::result::Result { + numerical(bench::bit_differences(a, b)) +} +pub(super) fn name(kind: Kind) -> CString { + CString::new(NAMES[kind.original_id() as usize]).unwrap() +} +pub(super) fn type_of(n: &str) -> i32 { + NAMES.iter().position(|v| v.eq_ignore_ascii_case(n)).map_or(-1, |v| v as i32) +} +pub(super) fn native_fmt(g: i32, d: i32) -> std::result::Result { + let gu = Kind::from_original(g).map_err(|_| format!("native experts: ggml-cpu has no dot product for type {g}"))?; + let down = + Kind::from_original(d).map_err(|_| format!("native experts: ggml-cpu has no dot product for type {d}"))?; + if H % gu.block().0 != 0 + || FF % down.block().0 != 0 + || gu.activation_bytes(H).is_err() + || down.activation_bytes(FF).is_err() + { + return Err("native experts: expert geometry is not whole blocks".into()); + } + if gu.activation_bytes(H).unwrap() > 4096 || down.activation_bytes(FF).unwrap() > 1024 { + return Err("native experts: activation larger than the pool's buffers".into()); + } + numerical(NativeFormat::new(gu, down, H, FF)) +} +pub(super) fn dot(kind: Kind, row: &[u8], a: &NativeActivation, width: usize) -> Result { + a.check(kind, width)?; + if !cpu::cpu_avx2_ok() || row.len() != kind.row_bytes(width)? || a.encoded_bytes()? > B { + return Err(Error::Shape); + } + // SAFETY: actual aligned initialized NativeActivation (check() + encoded_bytes() <= B above); no externally cast byte owner. + Ok(unsafe { crate::rust_ggml::dot_raw(kind, row, width, a.raw()) }) +} +pub(super) fn ggml_rows( + kind: Kind, + weights: &[u8], + width: usize, + acts: &[NativeActivation], + out: &mut [f32], +) -> Result<()> { + let stride = kind.row_bytes(width)?; + if weights.len() % stride != 0 || out.len() != acts.len() * (weights.len() / stride) { + return Err(Error::Shape); + } + let rows = weights.len() / stride; + for (t, a) in acts.iter().enumerate() { + for r in 0..rows { + out[t * rows + r] = dot(kind, &weights[r * stride..(r + 1) * stride], a, width)?; + } + } + Ok(()) +} +/// Explicit IQ4_NL row kernel on the SAME 1024-byte HQ owners used by down. +pub(super) fn iq4nl_hq(weights: &[u8], acts: &[NativeActivation<1024>], out: &mut [f32]) -> Result<()> { + if !cpu::cpu_avx2_ok() || acts.len() != NT || weights.len() != H * Kind::Iq4Nl.row_bytes(FF)? || out.len() != NT * H + { + return Err(Error::Shape); + } + for a in acts { + a.check(Kind::Iq4Nl, FF)?; + } + // SAFETY (this view): check(Iq4Nl,FF) pinned n == FF == 640, so 20 Q8Zero = 680 B <= the 1024-byte, 64-aligned owner. + let aa: [&[crate::rust_types::Q8Zero]; NT] = + std::array::from_fn(|i| unsafe { std::slice::from_raw_parts(acts[i].raw().as_ptr().cast(), FF / 32) }); + // SAFETY (iq4nl): cpu_avx2_ok() checked above; each row slice is row_bytes(FF) = 360 B = 20 blocks = aa[t].len(). + for r in 0..H { + let mut values = [0.0; NT]; + unsafe { + crate::rust_iq::iq4nl( + &weights[r * Kind::Iq4Nl.row_bytes(FF)?..(r + 1) * Kind::Iq4Nl.row_bytes(FF)?], + &aa, + &mut values, + false, + ); + } + for t in 0..NT { + out[t * H + r] = values[t]; + } + } + Ok(()) +} +pub(super) fn elapsed(start: Instant, iterations: usize) -> f64 { + start.elapsed().as_secs_f64() * 1e6 / iterations as f64 +} diff --git a/crates/native-cpu-expert/src/rust_bench_frontend/run_fn.rs b/crates/native-cpu-expert/src/rust_bench_frontend/run_fn.rs new file mode 100644 index 00000000..c7b09843 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_bench_frontend/run_fn.rs @@ -0,0 +1,123 @@ +//! Moved out of the parent module by STRA-338: fn run, fn run_modes, fn unbound_main. + +#[allow(unused_imports)] +use super::*; + +/// # Safety +/// Call ONLY at process entry before any thread or native CPU dispatch exists: +/// Original's absent-only setenv occurs here, before the actual stream factory. +/// `create_gpu` must create an actual stream and bind the declared owned methods. +pub unsafe fn run(args: &[String], create_gpu: impl FnOnce() -> std::result::Result) -> i32 { + // SAFETY: `stdout` is glibc's FILE* global, read by value; unbuffering it before any output is the documented single-threaded entry. + unsafe { + setvbuf(stdout, std::ptr::null_mut(), 2, 0); + } + if args.len() < 2 { + eprint!("{USAGE}"); + return 2; + } + // SAFETY: NUL-terminated literals; setenv races with other threads' getenv, so this relies on this fn's contract (process entry); + // rust_bench_cuda::main sets the variable first, so the branch is dead there (see its SAFETY note). + if std::env::var_os("STRATA_IQ_MT_MIN").is_none() { + if unsafe { setenv(c"STRATA_IQ_MT_MIN".as_ptr(), c"1".as_ptr(), 1) } != 0 { + eprintln!("native_expert_parity: setenv failed"); + return 1; + } + } + let mut gpu = match create_gpu() { + Ok(g) => g, + Err(e) => { + eprintln!("native_expert_parity: {e}"); + return 1; + } + }; + let result = run_modes(args, &mut gpu); + let close = gpu.close(); + match (result, close) { + (Err(e), _) | (Ok(_), Err(e)) => { + eprintln!("native_expert_parity: {e}"); + 1 + } + (Ok(failures), Ok(())) => { + report!("native_expert_parity: %d failures\n", failures as c_int); + i32::from(failures != 0) + } + } +} +pub(super) fn run_modes(args: &[String], gpu: &mut G) -> std::result::Result { + match args[1].as_str() { + "--q5_1-min" => check_q5_one(gpu), + "--bf16-embd" => check_bf16(gpu), + "--synthetic" => { + let mut failures = 0; + for (i, arg) in args.iter().enumerate().skip(2) { + let (gu, dn) = arg.split_once('/').map_or((-1, -1), |(g, d)| (type_of(g), type_of(d))); + let format = if gu < 0 || dn < 0 { Err(String::new()) } else { native_fmt(gu, dn) }; + let f = match format { + Ok(f) if gpu::expert_supported(f.gu, f.down, H, FF) => f, + Ok(_) => { + let arg = CString::new(arg.as_str()).map_err(|_| "argument contains NUL")?; + report!("%s: not a pair the GPU expert kernels take\n", arg.as_ptr()); + failures += 1; + continue; + } + Err(e) => { + let arg = CString::new(arg.as_str()).map_err(|_| "argument contains NUL")?; + let err = CString::new(if e.is_empty() { + "not a pair the GPU expert kernels take".into() + } else { + e + }) + .unwrap(); + report!("%s: %s\n", arg.as_ptr(), err.as_ptr()); + failures += 1; + continue; + } + }; + let blob = numerical(bench::synthetic_blob(&f, i as u32))?; + failures += check_blob(&f, &blob, i as u32, "synthetic", gpu)?; + } + Ok(failures) + } + path => { + let model = model::Model::open(path)?; + let layers = if args.len() == 2 { + vec![0, 1, 2, 3, 20, 47] + } else { + args[2..].iter().map(|v| crate::rust_simd::atoi(v)).collect() + }; + let mut failures = 0; + for layer in layers { + let Some((g, d)) = model.kinds(layer) else { + report!("layer %d: no expert tensors\n", layer as c_int); + failures += 1; + continue; + }; + let f = match native_fmt(g, d) { + Ok(f) => f, + Err(e) => { + let err = CString::new(e).unwrap(); + report!("layer %d: %s\n", layer as c_int, err.as_ptr()); + failures += 1; + continue; + } + }; + let blob = model.expert(layer, &f)?; + failures += check_blob(&f, &blob, layer as u32, &format!("layer {layer}"), gpu)?; + } + Ok(failures) + } + } +} +/// Explicit executable linkage refusal until Root supplies a genuine driver +/// stream factory. No benchmark check, failure count or GPU value is invented. +pub fn unbound_main() -> i32 { + let args: Vec = std::env::args().collect(); + if args.len() < 2 { + eprint!("{USAGE}"); + 2 + } else { + eprintln!("native_expert_parity: source-unresolved genuine CUDA ParityGpu binding; no benchmark executed"); + 1 + } +} diff --git a/crates/native-cpu-expert/src/rust_bench_gpu.rs b/crates/native-cpu-expert/src/rust_bench_gpu.rs index c25060cc..3863c580 100644 --- a/crates/native-cpu-expert/src/rust_bench_gpu.rs +++ b/crates/native-cpu-expert/src/rust_bench_gpu.rs @@ -35,11 +35,17 @@ pub trait ParityGpu { /// Literal native_expert_supported geometry from iq_kernels.cu; this is kernel /// dispatch metadata, never evidence that a device operation completed. pub fn expert_supported(gu: Kind, down: Kind, h: usize, ff: usize) -> bool { - let g = gu.original_id(); let d = down.original_id(); - let gu_ok = matches!(g,16|17|18|21|22|23|29|42|12|13|8); - let down_ok = matches!(d,20|23|42|7|8); - let is_iq = |t| matches!(t,16|17|18|20|21|22|23|29|42|11|12|13|7|8); - gu_ok && down_ok && is_iq(g) && is_iq(d) && h % gu.block().0 == 0 - && ff % down.block().0 == 0 && h % 256 == 0 + let g = gu.original_id(); + let d = down.original_id(); + let gu_ok = matches!(g, 16 | 17 | 18 | 21 | 22 | 23 | 29 | 42 | 12 | 13 | 8); + let down_ok = matches!(d, 20 | 23 | 42 | 7 | 8); + let is_iq = |t| matches!(t, 16 | 17 | 18 | 20 | 21 | 22 | 23 | 29 | 42 | 11 | 12 | 13 | 7 | 8); + gu_ok + && down_ok + && is_iq(g) + && is_iq(d) + && h % gu.block().0 == 0 + && ff % down.block().0 == 0 + && h % 256 == 0 && ff.checked_mul(h).is_some_and(|n| n % 256 == 0) } diff --git a/crates/native-cpu-expert/src/rust_bench_model.rs b/crates/native-cpu-expert/src/rust_bench_model.rs index 6f22fa71..587ed1cf 100644 --- a/crates/native-cpu-expert/src/rust_bench_model.rs +++ b/crates/native-cpu-expert/src/rust_bench_model.rs @@ -1,121 +1,339 @@ //! Actual read-only mapped GGUF v3 shards for the benchmark's E=7 copy. //! This is an offline loader, not a serving ModelBinding/certificate. -use std::{collections::{HashMap, HashSet}, fs::File}; -#[cfg(unix)] -use std::os::fd::AsRawFd; use crate::rust_ggml::NativeFormat; #[cfg(unix)] +use std::os::fd::AsRawFd; +use std::{ + collections::{HashMap, HashSet}, + fs::File, +}; +#[cfg(unix)] unsafe extern "C" { - fn mmap(address: *mut std::ffi::c_void, bytes: usize, protection: i32, flags: i32, fd: i32, offset: i64) -> *mut std::ffi::c_void; + fn mmap( + address: *mut std::ffi::c_void, + bytes: usize, + protection: i32, + flags: i32, + fd: i32, + offset: i64, + ) -> *mut std::ffi::c_void; fn munmap(address: *mut std::ffi::c_void, bytes: usize) -> i32; } -struct Mapping { file: File, address: *mut std::ffi::c_void, bytes: usize } +struct Mapping { + file: File, + address: *mut std::ffi::c_void, + bytes: usize, +} impl Mapping { - fn open(path: &str) -> Result { - let file=File::open(path).map_err(|e|format!("{path}: {e}"))?; - let bytes=usize::try_from(file.metadata().map_err(|e|e.to_string())?.len()).map_err(|_|"GGUF file too large")?; - if bytes==0 { return Err("empty GGUF file".into()); } + fn open(path: &str) -> Result { + let file = File::open(path).map_err(|e| format!("{path}: {e}"))?; + let bytes = + usize::try_from(file.metadata().map_err(|e| e.to_string())?.len()).map_err(|_| "GGUF file too large")?; + if bytes == 0 { + return Err("empty GGUF file".into()); + } // Actual retained FD, PROT_READ | MAP_PRIVATE. No detached data handle. // SAFETY: a null hint, non-zero length and a live fd; the result is checked against MAP_FAILED before use and unmapped in Drop. #[cfg(unix)] - let address=unsafe { mmap(std::ptr::null_mut(),bytes,1,2,file.as_raw_fd(),0) }; + let address = unsafe { mmap(std::ptr::null_mut(), bytes, 1, 2, file.as_raw_fd(), 0) }; #[cfg(unix)] - if address as isize == -1 { return Err(std::io::Error::last_os_error().to_string()); } + if address as isize == -1 { + return Err(std::io::Error::last_os_error().to_string()); + } // Windows: a read-only view of the whole retained handle (CreateFileMapping + MapViewOfFile). #[cfg(windows)] - let address={ + let address = { use std::os::windows::io::AsRawHandle; // SAFETY: a live file handle; the view is unmapped in Drop. - let view=unsafe { leleka_libc_shim::map_file_readonly(file.as_raw_handle().cast(),0,bytes) }; - if view.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + let view = unsafe { leleka_libc_shim::map_file_readonly(file.as_raw_handle().cast(), 0, bytes) }; + if view.is_null() { + return Err(std::io::Error::last_os_error().to_string()); + } view }; - Ok(Self{file,address,bytes}) + Ok(Self { file, address, bytes }) } // SAFETY: `address`/`bytes` are the live PROT_READ mapping owned by `self` (unmapped only in Drop); the slice borrows &self. // Residual (benchmark-only offline loader): truncating the file underneath raises SIGBUS and a concurrent writer is visible // through the shared pages; stable_length() brackets the copies in Model::expert. - fn bytes(&self)->&[u8] { unsafe { std::slice::from_raw_parts(self.address.cast(),self.bytes) } } - fn stable_length(&self)->Result<(),String> { - if self.file.metadata().map_err(|e|e.to_string())?.len()!=self.bytes as u64 { return Err("GGUF mapped source length changed".into()); } Ok(()) + fn bytes(&self) -> &[u8] { + unsafe { std::slice::from_raw_parts(self.address.cast(), self.bytes) } + } + fn stable_length(&self) -> Result<(), String> { + if self.file.metadata().map_err(|e| e.to_string())?.len() != self.bytes as u64 { + return Err("GGUF mapped source length changed".into()); + } + Ok(()) } } // SAFETY (Drop): `address`/`bytes` are exactly the mmap result; no slice from bytes() outlives `self`. #[cfg(unix)] -impl Drop for Mapping { fn drop(&mut self) { unsafe { munmap(self.address,self.bytes); } } } -#[cfg(windows)] -impl Drop for Mapping { fn drop(&mut self) { unsafe { leleka_libc_shim::unmap_file(self.address); } } } -struct Cursor<'a> { bytes:&'a[u8], at:usize } -impl<'a> Cursor<'a> { - fn take(&mut self,n:usize)->Result<&'a[u8],String>{let end=self.at.checked_add(n).ok_or("GGUF cursor overflow")?;let b=self.bytes.get(self.at..end).ok_or("truncated GGUF")?;self.at=end;Ok(b)} - fn u8(&mut self)->Result{Ok(self.take(1)?[0])} - fn u16(&mut self)->Result{Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))} - fn u32(&mut self)->Result{Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))} - fn u64(&mut self)->Result{Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))} - fn string(&mut self)->Result,String>{let n=usize::try_from(self.u64()?).map_err(|_|"GGUF string too large")?;copy(self.take(n)?)} - fn value(&mut self,kind:u32,depth:u32)->Result{if depth>2{return Err("GGUF nested array too deep".into());}Ok(match kind { - 0=>self.u8()? as u64,1=>(self.u8()? as i8 as i64) as u64, - 2=>self.u16()? as u64,3=>(self.u16()? as i16 as i64) as u64, - 4=>self.u32()? as u64,5=>(self.u32()? as i32 as i64) as u64, - 6=>{self.take(4)?;0},7=>u64::from(self.u8()?!=0),8=>{self.string()?;0}, - 9=>{if depth>2{return Err("GGUF nested array too deep".into());}let ty=self.u32()?;let count=self.u64()?;if count>1<<24{return Err("GGUF array too large".into());}for _ in 0..count{self.value(ty,depth+1)?;}0}, - 10=>self.u64()?,11=>self.u64()?,12=>{self.take(8)?;0},_=>return Err("unknown GGUF metadata type".into())})} -} -fn copy(b:&[u8])->Result,String>{let mut v=Vec::new();v.try_reserve_exact(b.len()).map_err(|_|"GGUF allocation")?;v.extend_from_slice(b);Ok(v)} -struct Tensor { name:Vec, kind:u32, offset:u64 } -struct Shard { map:Mapping, metadata:HashMap,u64>, tensors:Vec, data_start:usize } -impl Shard { - fn open(path:&str)->Result{ - let map=Mapping::open(path)?;let mut c=Cursor{bytes:map.bytes(),at:0}; - if c.u32()?!=0x46554747 || c.u32()?!=3{return Err("GGUF magic/version mismatch".into());} - let nt=usize::try_from(c.u64()?).map_err(|_|"GGUF tensor count")?;let nk=c.u64()?; - let mut metadata=HashMap::new(); - for _ in 0..nk{let key=c.string()?;let ty=c.u32()?;let value=c.value(ty,0)?;metadata.try_reserve(1).map_err(|_|"GGUF allocation")?;metadata.entry(key).or_insert(value);} - let mut tensors=Vec::new();let mut names=HashSet::new(); - // A valid tensor header cannot be shorter than name length+nd+one dim+type+offset. - if nt>(map.bytes.saturating_sub(c.at))/32{return Err("truncated GGUF tensor table".into());} - tensors.try_reserve_exact(nt).map_err(|_|"GGUF allocation")?;names.try_reserve(nt).map_err(|_|"GGUF allocation")?; - for _ in 0..nt{let name=c.string()?;if !names.insert(copy(&name)?){return Err("duplicate GGUF tensor".into());}let nd=c.u32()?;if !(1..=4).contains(&nd){return Err("GGUF tensor dimension".into());}for _ in 0..nd{c.u64()?;}let kind=c.u32()?;let offset=c.u64()?;tensors.push(Tensor{name,kind,offset});} - let alignment=metadata.get(b"general.alignment".as_slice()).copied().filter(|n|*n!=0).unwrap_or(32); - let a=usize::try_from(alignment).map_err(|_|"GGUF alignment overflow")?; - let data_start=c.at.checked_add(a-1).and_then(|n|n.checked_div(a)).and_then(|n|n.checked_mul(a)).ok_or("GGUF alignment overflow")?; - if data_start>map.bytes{return Err("GGUF data start beyond file".into());} - Ok(Self{map,metadata,tensors,data_start}) - } - fn meta(&self,key:&[u8])->Option{self.metadata.get(key).copied()} -} -pub(super) struct Model { shards:Vec, index:HashMap,(usize,usize)> } -impl Model { - pub(super) fn open(any:&str)->Result{ - let paths=split_paths(any)?;let mut shards=Vec::new();shards.try_reserve_exact(paths.len()).map_err(|_|"GGUF allocation")?; - for path in paths{shards.push(Shard::open(&path)?);} - let n=shards.len();let first=&shards[0]; - if n==1&&first.meta(b"split.count").unwrap_or(0)>1{return Err("split GGUF requires all shards".into());} - if n>1 { - if !first.metadata.contains_key(b"general.architecture".as_slice()){return Err("first split shard lacks architecture".into());} - let declared=first.meta(b"split.tensors.count");let mut total=0usize; - for (i,s) in shards.iter().enumerate(){if s.meta(b"split.count")!=Some(n as u64)||s.meta(b"split.no")!=Some(i as u64){return Err("split GGUF count/order mismatch".into());}if let Some(v)=declared{if s.meta(b"split.tensors.count")!=Some(v){return Err("split GGUF tensor count metadata mismatch".into());}}total=total.checked_add(s.tensors.len()).ok_or("tensor count overflow")?;} - if declared.is_some_and(|v|v!=total as u64){return Err("split GGUF tensor count mismatch".into());} +impl Drop for Mapping { + fn drop(&mut self) { + unsafe { + munmap(self.address, self.bytes); } - let mut index=HashMap::new();for (s,shard) in shards.iter().enumerate(){index.try_reserve(shard.tensors.len()).map_err(|_|"GGUF allocation")?;for (t,tensor) in shard.tensors.iter().enumerate(){if index.insert(copy(&tensor.name)?,(s,t)).is_some(){return Err("duplicate tensor across GGUF shards".into());}}} - Ok(Self{shards,index}) - } - pub(super) fn kinds(&self,layer:i32)->Option<(i32,i32)> {let gate=self.find(layer,"gate")?;self.find(layer,"up")?;let down=self.find(layer,"down")?;Some((gate.1.kind as i32,down.1.kind as i32))} - fn find(&self,layer:i32,role:&str)->Option<(&Shard,&Tensor)>{let name=format!("blk.{layer}.ffn_{role}_exps.weight");let(s,t)=*self.index.get(name.as_bytes())?;Some((&self.shards[s],&self.shards[s].tensors[t]))} - pub(super) fn expert(&self,layer:i32,f:&NativeFormat)->Result,String>{ - let mut out=Vec::new();out.try_reserve_exact(f.bytes).map_err(|_|"expert allocation")?; - for (role,n) in [("gate",f.up_offset),("up",f.up_offset),("down",f.bytes-f.down_offset)] { - let (s,t)=self.find(layer,role).ok_or("missing expert tensor")?;s.map.stable_length()?; - let at=usize::try_from(t.offset).ok().and_then(|v|v.checked_add(s.data_start)).and_then(|v|7usize.checked_mul(n).and_then(|e|v.checked_add(e))).ok_or("expert offset overflow")?; - let end=at.checked_add(n).ok_or("expert extent overflow")?;let bytes=s.map.bytes().get(at..end).ok_or("expert E=7 beyond GGUF mapping")?; - out.extend_from_slice(bytes);s.map.stable_length()?; - }Ok(out) } } -fn split_paths(any:&str)->Result,String>{ - let Some(at)=any.rfind("-of-") else{return Ok(vec![any.into()]);};let b=any.as_bytes(); - if at<6||b[at-6]!=b'-'||b.len()!=at+14||&b[at+9..]!=b".gguf"||!b[at-5..at].iter().chain(&b[at+4..at+9]).all(u8::is_ascii_digit){return Ok(vec![any.into()]);} - let no=any[at-5..at].parse::().map_err(|e|e.to_string())?;let n=any[at+4..at+9].parse::().map_err(|e|e.to_string())?; - if n<1||no<1||no>n{return Ok(vec![any.into()]);}let mut out=Vec::new();out.try_reserve_exact(n).map_err(|_|"shard allocation")?; - for i in 1..=n{let mut path=any.to_owned();path.replace_range(at-5..at,&format!("{i:05}"));if File::open(&path).is_err(){return Err(format!("missing model shard {path} (shard {i} of {n}; is the download complete?)"));}out.push(path);}Ok(out) +#[cfg(windows)] +impl Drop for Mapping { + fn drop(&mut self) { + unsafe { + leleka_libc_shim::unmap_file(self.address); + } + } +} +struct Cursor<'a> { + bytes: &'a [u8], + at: usize, +} +impl<'a> Cursor<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + let end = self.at.checked_add(n).ok_or("GGUF cursor overflow")?; + let b = self.bytes.get(self.at..end).ok_or("truncated GGUF")?; + self.at = end; + Ok(b) + } + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap())) + } + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap())) + } + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())) + } + fn string(&mut self) -> Result, String> { + let n = usize::try_from(self.u64()?).map_err(|_| "GGUF string too large")?; + copy(self.take(n)?) + } + fn value(&mut self, kind: u32, depth: u32) -> Result { + if depth > 2 { + return Err("GGUF nested array too deep".into()); + } + Ok(match kind { + 0 => self.u8()? as u64, + 1 => (self.u8()? as i8 as i64) as u64, + 2 => self.u16()? as u64, + 3 => (self.u16()? as i16 as i64) as u64, + 4 => self.u32()? as u64, + 5 => (self.u32()? as i32 as i64) as u64, + 6 => { + self.take(4)?; + 0 + } + 7 => u64::from(self.u8()? != 0), + 8 => { + self.string()?; + 0 + } + 9 => { + if depth > 2 { + return Err("GGUF nested array too deep".into()); + } + let ty = self.u32()?; + let count = self.u64()?; + if count > 1 << 24 { + return Err("GGUF array too large".into()); + } + for _ in 0..count { + self.value(ty, depth + 1)?; + } + 0 + } + 10 => self.u64()?, + 11 => self.u64()?, + 12 => { + self.take(8)?; + 0 + } + _ => return Err("unknown GGUF metadata type".into()), + }) + } +} +fn copy(b: &[u8]) -> Result, String> { + let mut v = Vec::new(); + v.try_reserve_exact(b.len()).map_err(|_| "GGUF allocation")?; + v.extend_from_slice(b); + Ok(v) +} +struct Tensor { + name: Vec, + kind: u32, + offset: u64, +} +struct Shard { + map: Mapping, + metadata: HashMap, u64>, + tensors: Vec, + data_start: usize, +} +impl Shard { + fn open(path: &str) -> Result { + let map = Mapping::open(path)?; + let mut c = Cursor { bytes: map.bytes(), at: 0 }; + if c.u32()? != 0x46554747 || c.u32()? != 3 { + return Err("GGUF magic/version mismatch".into()); + } + let nt = usize::try_from(c.u64()?).map_err(|_| "GGUF tensor count")?; + let nk = c.u64()?; + let mut metadata = HashMap::new(); + for _ in 0..nk { + let key = c.string()?; + let ty = c.u32()?; + let value = c.value(ty, 0)?; + metadata.try_reserve(1).map_err(|_| "GGUF allocation")?; + metadata.entry(key).or_insert(value); + } + let mut tensors = Vec::new(); + let mut names = HashSet::new(); + // A valid tensor header cannot be shorter than name length+nd+one dim+type+offset. + if nt > (map.bytes.saturating_sub(c.at)) / 32 { + return Err("truncated GGUF tensor table".into()); + } + tensors.try_reserve_exact(nt).map_err(|_| "GGUF allocation")?; + names.try_reserve(nt).map_err(|_| "GGUF allocation")?; + for _ in 0..nt { + let name = c.string()?; + if !names.insert(copy(&name)?) { + return Err("duplicate GGUF tensor".into()); + } + let nd = c.u32()?; + if !(1..=4).contains(&nd) { + return Err("GGUF tensor dimension".into()); + } + for _ in 0..nd { + c.u64()?; + } + let kind = c.u32()?; + let offset = c.u64()?; + tensors.push(Tensor { name, kind, offset }); + } + let alignment = metadata.get(b"general.alignment".as_slice()).copied().filter(|n| *n != 0).unwrap_or(32); + let a = usize::try_from(alignment).map_err(|_| "GGUF alignment overflow")?; + let data_start = + c.at.checked_add(a - 1) + .and_then(|n| n.checked_div(a)) + .and_then(|n| n.checked_mul(a)) + .ok_or("GGUF alignment overflow")?; + if data_start > map.bytes { + return Err("GGUF data start beyond file".into()); + } + Ok(Self { map, metadata, tensors, data_start }) + } + fn meta(&self, key: &[u8]) -> Option { + self.metadata.get(key).copied() + } +} +pub(super) struct Model { + shards: Vec, + index: HashMap, (usize, usize)>, +} +impl Model { + pub(super) fn open(any: &str) -> Result { + let paths = split_paths(any)?; + let mut shards = Vec::new(); + shards.try_reserve_exact(paths.len()).map_err(|_| "GGUF allocation")?; + for path in paths { + shards.push(Shard::open(&path)?); + } + let n = shards.len(); + let first = &shards[0]; + if n == 1 && first.meta(b"split.count").unwrap_or(0) > 1 { + return Err("split GGUF requires all shards".into()); + } + if n > 1 { + if !first.metadata.contains_key(b"general.architecture".as_slice()) { + return Err("first split shard lacks architecture".into()); + } + let declared = first.meta(b"split.tensors.count"); + let mut total = 0usize; + for (i, s) in shards.iter().enumerate() { + if s.meta(b"split.count") != Some(n as u64) || s.meta(b"split.no") != Some(i as u64) { + return Err("split GGUF count/order mismatch".into()); + } + if let Some(v) = declared { + if s.meta(b"split.tensors.count") != Some(v) { + return Err("split GGUF tensor count metadata mismatch".into()); + } + } + total = total.checked_add(s.tensors.len()).ok_or("tensor count overflow")?; + } + if declared.is_some_and(|v| v != total as u64) { + return Err("split GGUF tensor count mismatch".into()); + } + } + let mut index = HashMap::new(); + for (s, shard) in shards.iter().enumerate() { + index.try_reserve(shard.tensors.len()).map_err(|_| "GGUF allocation")?; + for (t, tensor) in shard.tensors.iter().enumerate() { + if index.insert(copy(&tensor.name)?, (s, t)).is_some() { + return Err("duplicate tensor across GGUF shards".into()); + } + } + } + Ok(Self { shards, index }) + } + pub(super) fn kinds(&self, layer: i32) -> Option<(i32, i32)> { + let gate = self.find(layer, "gate")?; + self.find(layer, "up")?; + let down = self.find(layer, "down")?; + Some((gate.1.kind as i32, down.1.kind as i32)) + } + fn find(&self, layer: i32, role: &str) -> Option<(&Shard, &Tensor)> { + let name = format!("blk.{layer}.ffn_{role}_exps.weight"); + let (s, t) = *self.index.get(name.as_bytes())?; + Some((&self.shards[s], &self.shards[s].tensors[t])) + } + pub(super) fn expert(&self, layer: i32, f: &NativeFormat) -> Result, String> { + let mut out = Vec::new(); + out.try_reserve_exact(f.bytes).map_err(|_| "expert allocation")?; + for (role, n) in [("gate", f.up_offset), ("up", f.up_offset), ("down", f.bytes - f.down_offset)] { + let (s, t) = self.find(layer, role).ok_or("missing expert tensor")?; + s.map.stable_length()?; + let at = usize::try_from(t.offset) + .ok() + .and_then(|v| v.checked_add(s.data_start)) + .and_then(|v| 7usize.checked_mul(n).and_then(|e| v.checked_add(e))) + .ok_or("expert offset overflow")?; + let end = at.checked_add(n).ok_or("expert extent overflow")?; + let bytes = s.map.bytes().get(at..end).ok_or("expert E=7 beyond GGUF mapping")?; + out.extend_from_slice(bytes); + s.map.stable_length()?; + } + Ok(out) + } +} +fn split_paths(any: &str) -> Result, String> { + let Some(at) = any.rfind("-of-") else { + return Ok(vec![any.into()]); + }; + let b = any.as_bytes(); + if at < 6 + || b[at - 6] != b'-' + || b.len() != at + 14 + || &b[at + 9..] != b".gguf" + || !b[at - 5..at].iter().chain(&b[at + 4..at + 9]).all(u8::is_ascii_digit) + { + return Ok(vec![any.into()]); + } + let no = any[at - 5..at].parse::().map_err(|e| e.to_string())?; + let n = any[at + 4..at + 9].parse::().map_err(|e| e.to_string())?; + if n < 1 || no < 1 || no > n { + return Ok(vec![any.into()]); + } + let mut out = Vec::new(); + out.try_reserve_exact(n).map_err(|_| "shard allocation")?; + for i in 1..=n { + let mut path = any.to_owned(); + path.replace_range(at - 5..at, &format!("{i:05}")); + if File::open(&path).is_err() { + return Err(format!("missing model shard {path} (shard {i} of {n}; is the download complete?)")); + } + out.push(path); + } + Ok(out) } diff --git a/crates/native-cpu-expert/src/rust_codebooks.rs b/crates/native-cpu-expert/src/rust_codebooks.rs index 27f89cc7..def6ae06 100644 --- a/crates/native-cpu-expert/src/rust_codebooks.rs +++ b/crates/native-cpu-expert/src/rust_codebooks.rs @@ -1,360 +1,1905 @@ //! Literal numerical codebooks from pinned ggml-common.h. See LICENSE.ggml. pub(super) const KSIGNS_IQ2XS: [u8; 128] = [ - 0, 129, 130, 3, 132, 5, 6, 135, - 136, 9, 10, 139, 12, 141, 142, 15, - 144, 17, 18, 147, 20, 149, 150, 23, - 24, 153, 154, 27, 156, 29, 30, 159, - 160, 33, 34, 163, 36, 165, 166, 39, - 40, 169, 170, 43, 172, 45, 46, 175, - 48, 177, 178, 51, 180, 53, 54, 183, - 184, 57, 58, 187, 60, 189, 190, 63, - 192, 65, 66, 195, 68, 197, 198, 71, - 72, 201, 202, 75, 204, 77, 78, 207, - 80, 209, 210, 83, 212, 85, 86, 215, - 216, 89, 90, 219, 92, 221, 222, 95, - 96, 225, 226, 99, 228, 101, 102, 231, - 232, 105, 106, 235, 108, 237, 238, 111, - 240, 113, 114, 243, 116, 245, 246, 119, - 120, 249, 250, 123, 252, 125, 126, 255, + 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, + 154, 27, 156, 29, 30, 159, 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, 48, 177, 178, + 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, + 204, 77, 78, 207, 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, 96, 225, 226, 99, 228, + 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, + 252, 125, 126, 255, ]; pub(super) const IQ2XXS_GRID: [u64; 256] = [ - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, - 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, - 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, - 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, - 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, - 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, - 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, - 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, - 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, - 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, - 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, - 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, - 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, - 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, - 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, - 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, - 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, - 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, - 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, - 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, - 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, - 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, - 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, - 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, - 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, - 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, - 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, - 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, - 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, - 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, - 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, + 0x0808080808080808, + 0x080808080808082b, + 0x0808080808081919, + 0x0808080808082b08, + 0x0808080808082b2b, + 0x0808080808190819, + 0x0808080808191908, + 0x08080808082b0808, + 0x08080808082b082b, + 0x08080808082b2b08, + 0x08080808082b2b2b, + 0x0808080819080819, + 0x0808080819081908, + 0x0808080819190808, + 0x0808080819192b08, + 0x08080808192b0819, + 0x08080808192b1908, + 0x080808082b080808, + 0x080808082b08082b, + 0x080808082b082b2b, + 0x080808082b2b082b, + 0x0808081908080819, + 0x0808081908081908, + 0x0808081908190808, + 0x0808081908191919, + 0x0808081919080808, + 0x080808192b081908, + 0x080808192b192b08, + 0x0808082b08080808, + 0x0808082b0808082b, + 0x0808082b082b082b, + 0x0808082b2b08082b, + 0x0808190808080819, + 0x0808190808081908, + 0x0808190808190808, + 0x08081908082b0819, + 0x08081908082b1908, + 0x0808190819080808, + 0x080819081908082b, + 0x0808190819082b08, + 0x08081908192b0808, + 0x080819082b080819, + 0x080819082b081908, + 0x080819082b190808, + 0x080819082b2b1908, + 0x0808191908080808, + 0x080819190808082b, + 0x0808191908082b08, + 0x08081919082b0808, + 0x080819191908192b, + 0x08081919192b2b19, + 0x080819192b080808, + 0x080819192b190819, + 0x0808192b08082b19, + 0x0808192b08190808, + 0x0808192b19080808, + 0x0808192b2b081908, + 0x0808192b2b2b1908, + 0x08082b0808080808, + 0x08082b0808081919, + 0x08082b0808082b08, + 0x08082b0808191908, + 0x08082b08082b2b08, + 0x08082b0819080819, + 0x08082b0819081908, + 0x08082b0819190808, + 0x08082b081919082b, + 0x08082b082b082b08, + 0x08082b1908081908, + 0x08082b1919080808, + 0x08082b2b0808082b, + 0x08082b2b08191908, + 0x0819080808080819, + 0x0819080808081908, + 0x0819080808190808, + 0x08190808082b0819, + 0x0819080819080808, + 0x08190808192b0808, + 0x081908082b081908, + 0x081908082b190808, + 0x081908082b191919, + 0x0819081908080808, + 0x0819081908082b08, + 0x08190819082b0808, + 0x0819081919190808, + 0x0819081919192b2b, + 0x081908192b080808, + 0x0819082b082b1908, + 0x0819082b19081919, + 0x0819190808080808, + 0x0819190808082b08, + 0x08191908082b0808, + 0x08191908082b1919, + 0x0819190819082b19, + 0x081919082b080808, + 0x0819191908192b08, + 0x08191919192b082b, + 0x0819192b08080808, + 0x0819192b0819192b, + 0x08192b0808080819, + 0x08192b0808081908, + 0x08192b0808190808, + 0x08192b0819080808, + 0x08192b082b080819, + 0x08192b1908080808, + 0x08192b1908081919, + 0x08192b192b2b0808, + 0x08192b2b19190819, + 0x082b080808080808, + 0x082b08080808082b, + 0x082b080808082b2b, + 0x082b080819081908, + 0x082b0808192b0819, + 0x082b08082b080808, + 0x082b08082b08082b, + 0x082b0819082b2b19, + 0x082b081919082b08, + 0x082b082b08080808, + 0x082b082b0808082b, + 0x082b190808080819, + 0x082b190808081908, + 0x082b190808190808, + 0x082b190819080808, + 0x082b19081919192b, + 0x082b191908080808, + 0x082b191919080819, + 0x082b1919192b1908, + 0x082b192b2b190808, + 0x082b2b0808082b08, + 0x082b2b08082b0808, + 0x082b2b082b191908, + 0x082b2b2b19081908, + 0x1908080808080819, + 0x1908080808081908, + 0x1908080808190808, + 0x1908080808192b08, + 0x19080808082b0819, + 0x19080808082b1908, + 0x1908080819080808, + 0x1908080819082b08, + 0x190808081919192b, + 0x19080808192b0808, + 0x190808082b080819, + 0x190808082b081908, + 0x190808082b190808, + 0x1908081908080808, + 0x19080819082b0808, + 0x19080819192b0819, + 0x190808192b080808, + 0x190808192b081919, + 0x1908082b08080819, + 0x1908082b08190808, + 0x1908082b19082b08, + 0x1908082b1919192b, + 0x1908082b192b2b08, + 0x1908190808080808, + 0x1908190808082b08, + 0x19081908082b0808, + 0x190819082b080808, + 0x190819082b192b19, + 0x190819190819082b, + 0x19081919082b1908, + 0x1908192b08080808, + 0x19082b0808080819, + 0x19082b0808081908, + 0x19082b0808190808, + 0x19082b0819080808, + 0x19082b0819081919, + 0x19082b1908080808, + 0x19082b1919192b08, + 0x19082b19192b0819, + 0x19082b192b08082b, + 0x19082b2b19081919, + 0x19082b2b2b190808, + 0x1919080808080808, + 0x1919080808082b08, + 0x1919080808190819, + 0x1919080808192b19, + 0x19190808082b0808, + 0x191908082b080808, + 0x191908082b082b08, + 0x1919081908081908, + 0x191908191908082b, + 0x191908192b2b1908, + 0x1919082b2b190819, + 0x191919082b190808, + 0x191919082b19082b, + 0x1919191908082b2b, + 0x1919192b08080819, + 0x1919192b19191908, + 0x19192b0808080808, + 0x19192b0808190819, + 0x19192b0808192b19, + 0x19192b08192b1908, + 0x19192b1919080808, + 0x19192b2b08082b08, + 0x192b080808081908, + 0x192b080808190808, + 0x192b080819080808, + 0x192b0808192b2b08, + 0x192b081908080808, + 0x192b081919191919, + 0x192b082b08192b08, + 0x192b082b192b0808, + 0x192b190808080808, + 0x192b190808081919, + 0x192b191908190808, + 0x192b19190819082b, + 0x192b19192b081908, + 0x192b2b081908082b, + 0x2b08080808080808, + 0x2b0808080808082b, + 0x2b08080808082b2b, + 0x2b08080819080819, + 0x2b0808082b08082b, + 0x2b08081908081908, + 0x2b08081908192b08, + 0x2b08081919080808, + 0x2b08082b08190819, + 0x2b08190808080819, + 0x2b08190808081908, + 0x2b08190808190808, + 0x2b08190808191919, + 0x2b08190819080808, + 0x2b081908192b0808, + 0x2b08191908080808, + 0x2b0819191908192b, + 0x2b0819192b191908, + 0x2b08192b08082b19, + 0x2b08192b19080808, + 0x2b08192b192b0808, + 0x2b082b080808082b, + 0x2b082b1908081908, + 0x2b082b2b08190819, + 0x2b19080808081908, + 0x2b19080808190808, + 0x2b190808082b1908, + 0x2b19080819080808, + 0x2b1908082b2b0819, + 0x2b1908190819192b, + 0x2b1908192b080808, + 0x2b19082b19081919, + 0x2b19190808080808, + 0x2b191908082b082b, + 0x2b19190819081908, + 0x2b19191919190819, + 0x2b192b082b080819, + 0x2b192b19082b0808, + 0x2b2b08080808082b, + 0x2b2b080819190808, + 0x2b2b08082b081919, + 0x2b2b081908082b19, + 0x2b2b082b08080808, + 0x2b2b190808192b08, + 0x2b2b2b0819190808, + 0x2b2b2b1908081908, ]; pub(super) const IQ2XS_GRID: [u64; 512] = [ - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, - 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, - 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, - 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, - 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, - 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, - 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, - 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, - 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, - 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, - 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, - 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, - 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, - 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, - 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, - 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, - 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, - 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, - 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, - 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, - 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, - 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, - 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, - 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, - 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, - 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, - 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, - 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, - 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, - 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, - 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, - 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, - 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, - 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, - 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, - 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, - 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, - 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, - 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, - 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, - 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, - 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, - 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, - 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, - 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, - 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, - 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, - 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, - 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, - 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, - 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, - 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, - 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, - 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, - 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, - 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, - 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, - 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, - 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, - 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, - 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, + 0x0808080808080808, + 0x080808080808082b, + 0x0808080808081919, + 0x0808080808082b08, + 0x0808080808082b2b, + 0x0808080808190819, + 0x0808080808191908, + 0x080808080819192b, + 0x0808080808192b19, + 0x08080808082b0808, + 0x08080808082b082b, + 0x08080808082b1919, + 0x08080808082b2b08, + 0x0808080819080819, + 0x0808080819081908, + 0x080808081908192b, + 0x0808080819082b19, + 0x0808080819190808, + 0x080808081919082b, + 0x0808080819191919, + 0x0808080819192b08, + 0x08080808192b0819, + 0x08080808192b1908, + 0x080808082b080808, + 0x080808082b08082b, + 0x080808082b081919, + 0x080808082b082b08, + 0x080808082b190819, + 0x080808082b191908, + 0x080808082b192b19, + 0x080808082b2b0808, + 0x0808081908080819, + 0x0808081908081908, + 0x080808190808192b, + 0x0808081908082b19, + 0x0808081908190808, + 0x080808190819082b, + 0x0808081908191919, + 0x0808081908192b08, + 0x0808081908192b2b, + 0x08080819082b0819, + 0x08080819082b1908, + 0x0808081919080808, + 0x080808191908082b, + 0x0808081919081919, + 0x0808081919082b08, + 0x0808081919190819, + 0x0808081919191908, + 0x08080819192b0808, + 0x08080819192b2b08, + 0x080808192b080819, + 0x080808192b081908, + 0x080808192b190808, + 0x0808082b08080808, + 0x0808082b0808082b, + 0x0808082b08081919, + 0x0808082b08082b08, + 0x0808082b08190819, + 0x0808082b08191908, + 0x0808082b082b0808, + 0x0808082b19080819, + 0x0808082b19081908, + 0x0808082b19190808, + 0x0808082b19191919, + 0x0808082b2b080808, + 0x0808082b2b082b2b, + 0x0808190808080819, + 0x0808190808081908, + 0x080819080808192b, + 0x0808190808082b19, + 0x0808190808190808, + 0x080819080819082b, + 0x0808190808191919, + 0x0808190808192b08, + 0x08081908082b0819, + 0x08081908082b1908, + 0x0808190819080808, + 0x080819081908082b, + 0x0808190819081919, + 0x0808190819082b08, + 0x0808190819190819, + 0x0808190819191908, + 0x080819081919192b, + 0x08081908192b0808, + 0x080819082b080819, + 0x080819082b081908, + 0x080819082b190808, + 0x0808191908080808, + 0x080819190808082b, + 0x0808191908081919, + 0x0808191908082b08, + 0x0808191908190819, + 0x0808191908191908, + 0x08081919082b0808, + 0x0808191919080819, + 0x0808191919081908, + 0x0808191919190808, + 0x08081919192b0819, + 0x080819192b080808, + 0x0808192b08080819, + 0x0808192b08081908, + 0x0808192b08190808, + 0x0808192b082b192b, + 0x0808192b19080808, + 0x0808192b1908082b, + 0x0808192b2b081908, + 0x08082b0808080808, + 0x08082b080808082b, + 0x08082b0808081919, + 0x08082b0808082b08, + 0x08082b0808082b2b, + 0x08082b0808190819, + 0x08082b0808191908, + 0x08082b08082b0808, + 0x08082b08082b1919, + 0x08082b0819080819, + 0x08082b0819081908, + 0x08082b0819190808, + 0x08082b0819192b08, + 0x08082b082b080808, + 0x08082b082b2b0808, + 0x08082b082b2b2b2b, + 0x08082b1908080819, + 0x08082b1908081908, + 0x08082b1908190808, + 0x08082b1919080808, + 0x08082b192b080819, + 0x08082b192b082b19, + 0x08082b2b08080808, + 0x08082b2b082b0808, + 0x08082b2b082b2b08, + 0x08082b2b2b19192b, + 0x08082b2b2b2b0808, + 0x0819080808080819, + 0x0819080808081908, + 0x081908080808192b, + 0x0819080808082b19, + 0x0819080808190808, + 0x081908080819082b, + 0x0819080808191919, + 0x0819080808192b08, + 0x08190808082b0819, + 0x08190808082b1908, + 0x0819080819080808, + 0x081908081908082b, + 0x0819080819081919, + 0x0819080819082b08, + 0x0819080819190819, + 0x0819080819191908, + 0x08190808192b0808, + 0x08190808192b2b2b, + 0x081908082b080819, + 0x081908082b081908, + 0x081908082b190808, + 0x0819081908080808, + 0x081908190808082b, + 0x0819081908081919, + 0x0819081908082b08, + 0x0819081908190819, + 0x0819081908191908, + 0x08190819082b0808, + 0x0819081919080819, + 0x0819081919081908, + 0x0819081919190808, + 0x081908192b080808, + 0x081908192b191908, + 0x081908192b19192b, + 0x0819082b08080819, + 0x0819082b08081908, + 0x0819082b0808192b, + 0x0819082b08190808, + 0x0819082b19080808, + 0x0819082b192b0808, + 0x0819190808080808, + 0x081919080808082b, + 0x0819190808081919, + 0x0819190808082b08, + 0x0819190808190819, + 0x0819190808191908, + 0x08191908082b0808, + 0x0819190819080819, + 0x0819190819081908, + 0x0819190819082b19, + 0x0819190819190808, + 0x08191908192b1908, + 0x081919082b080808, + 0x0819191908080819, + 0x0819191908081908, + 0x0819191908190808, + 0x0819191919080808, + 0x0819192b08080808, + 0x0819192b08191908, + 0x0819192b19082b19, + 0x08192b0808080819, + 0x08192b0808081908, + 0x08192b0808190808, + 0x08192b080819082b, + 0x08192b0819080808, + 0x08192b0819191908, + 0x08192b082b08192b, + 0x08192b1908080808, + 0x08192b1908081919, + 0x08192b19192b192b, + 0x08192b2b19190819, + 0x08192b2b2b2b2b19, + 0x082b080808080808, + 0x082b08080808082b, + 0x082b080808081919, + 0x082b080808082b08, + 0x082b080808082b2b, + 0x082b080808190819, + 0x082b080808191908, + 0x082b0808082b0808, + 0x082b080819080819, + 0x082b080819081908, + 0x082b080819190808, + 0x082b08082b080808, + 0x082b08082b2b0808, + 0x082b081908080819, + 0x082b081908081908, + 0x082b081908190808, + 0x082b081919080808, + 0x082b081919082b08, + 0x082b0819192b1919, + 0x082b082b08080808, + 0x082b082b082b082b, + 0x082b082b2b080808, + 0x082b082b2b2b2b08, + 0x082b190808080819, + 0x082b190808081908, + 0x082b190808190808, + 0x082b1908082b2b19, + 0x082b190819080808, + 0x082b191908080808, + 0x082b191919080819, + 0x082b19191919082b, + 0x082b19192b192b19, + 0x082b192b08080819, + 0x082b192b08192b2b, + 0x082b192b2b2b192b, + 0x082b2b0808080808, + 0x082b2b0808082b08, + 0x082b2b0808082b2b, + 0x082b2b08082b0808, + 0x082b2b0819191919, + 0x082b2b082b082b08, + 0x082b2b082b2b082b, + 0x082b2b19192b2b08, + 0x082b2b192b190808, + 0x082b2b2b08082b08, + 0x082b2b2b082b0808, + 0x082b2b2b2b08082b, + 0x082b2b2b2b082b08, + 0x082b2b2b2b082b2b, + 0x1908080808080819, + 0x1908080808081908, + 0x190808080808192b, + 0x1908080808082b19, + 0x1908080808190808, + 0x190808080819082b, + 0x1908080808191919, + 0x1908080808192b08, + 0x19080808082b0819, + 0x19080808082b1908, + 0x1908080819080808, + 0x190808081908082b, + 0x1908080819081919, + 0x1908080819082b08, + 0x1908080819082b2b, + 0x1908080819190819, + 0x1908080819191908, + 0x19080808192b0808, + 0x19080808192b1919, + 0x190808082b080819, + 0x190808082b081908, + 0x190808082b190808, + 0x1908081908080808, + 0x190808190808082b, + 0x1908081908081919, + 0x1908081908082b08, + 0x1908081908190819, + 0x1908081908191908, + 0x19080819082b0808, + 0x1908081919080819, + 0x1908081919081908, + 0x1908081919190808, + 0x190808192b080808, + 0x190808192b081919, + 0x190808192b2b082b, + 0x1908082b08080819, + 0x1908082b08081908, + 0x1908082b08190808, + 0x1908082b0819082b, + 0x1908082b082b2b19, + 0x1908082b19080808, + 0x1908190808080808, + 0x190819080808082b, + 0x1908190808081919, + 0x1908190808082b08, + 0x1908190808190819, + 0x1908190808191908, + 0x1908190808192b19, + 0x19081908082b0808, + 0x1908190819080819, + 0x1908190819081908, + 0x1908190819190808, + 0x190819082b080808, + 0x190819082b191908, + 0x1908191908080819, + 0x1908191908081908, + 0x1908191908190808, + 0x19081919082b1908, + 0x1908191919080808, + 0x190819192b192b2b, + 0x1908192b08080808, + 0x1908192b08082b2b, + 0x1908192b19081908, + 0x1908192b19190808, + 0x19082b0808080819, + 0x19082b0808081908, + 0x19082b0808190808, + 0x19082b0819080808, + 0x19082b0819081919, + 0x19082b0819191908, + 0x19082b08192b082b, + 0x19082b1908080808, + 0x19082b1908190819, + 0x19082b1919081908, + 0x19082b1919190808, + 0x19082b19192b2b19, + 0x19082b2b08081908, + 0x1919080808080808, + 0x191908080808082b, + 0x1919080808081919, + 0x1919080808082b08, + 0x1919080808190819, + 0x1919080808191908, + 0x19190808082b0808, + 0x19190808082b2b08, + 0x1919080819080819, + 0x1919080819081908, + 0x1919080819190808, + 0x191908082b080808, + 0x1919081908080819, + 0x1919081908081908, + 0x1919081908190808, + 0x1919081908191919, + 0x1919081919080808, + 0x191908191908082b, + 0x1919082b08080808, + 0x1919082b19081908, + 0x1919082b2b2b2b2b, + 0x1919190808080819, + 0x1919190808081908, + 0x1919190808190808, + 0x19191908082b0819, + 0x1919190819080808, + 0x19191908192b0808, + 0x191919082b080819, + 0x191919082b2b0819, + 0x1919191908080808, + 0x1919191908082b08, + 0x191919192b080808, + 0x191919192b082b08, + 0x1919192b082b0819, + 0x1919192b192b2b08, + 0x1919192b2b2b0819, + 0x19192b0808080808, + 0x19192b0808191908, + 0x19192b0819080819, + 0x19192b0819190808, + 0x19192b082b192b19, + 0x19192b1908192b2b, + 0x19192b1919080808, + 0x19192b191908082b, + 0x19192b2b2b081919, + 0x192b080808080819, + 0x192b080808081908, + 0x192b080808190808, + 0x192b080819080808, + 0x192b080819191908, + 0x192b0808192b082b, + 0x192b08082b08192b, + 0x192b08082b2b2b19, + 0x192b081908080808, + 0x192b082b082b1908, + 0x192b082b19082b2b, + 0x192b082b2b19082b, + 0x192b190808080808, + 0x192b19080819192b, + 0x192b191908190808, + 0x192b191919080808, + 0x192b191919081919, + 0x192b19192b2b1908, + 0x192b2b0808080819, + 0x192b2b08192b2b2b, + 0x192b2b19082b1919, + 0x192b2b2b0808192b, + 0x192b2b2b19191908, + 0x192b2b2b192b082b, + 0x2b08080808080808, + 0x2b0808080808082b, + 0x2b08080808081919, + 0x2b08080808082b08, + 0x2b08080808190819, + 0x2b08080808191908, + 0x2b080808082b0808, + 0x2b080808082b2b2b, + 0x2b08080819080819, + 0x2b08080819081908, + 0x2b08080819190808, + 0x2b0808082b080808, + 0x2b0808082b08082b, + 0x2b0808082b2b2b08, + 0x2b0808082b2b2b2b, + 0x2b08081908080819, + 0x2b08081908081908, + 0x2b0808190808192b, + 0x2b08081908190808, + 0x2b08081919080808, + 0x2b08081919190819, + 0x2b08081919192b19, + 0x2b08082b08080808, + 0x2b08082b082b0808, + 0x2b08082b2b080808, + 0x2b08082b2b08082b, + 0x2b08082b2b2b0808, + 0x2b08082b2b2b2b08, + 0x2b08190808080819, + 0x2b08190808081908, + 0x2b08190808190808, + 0x2b0819080819082b, + 0x2b08190808191919, + 0x2b08190819080808, + 0x2b081908192b0808, + 0x2b0819082b082b19, + 0x2b08191908080808, + 0x2b08191919081908, + 0x2b0819192b2b1919, + 0x2b08192b08192b08, + 0x2b08192b192b2b2b, + 0x2b082b0808080808, + 0x2b082b0808082b08, + 0x2b082b08082b1919, + 0x2b082b0819192b2b, + 0x2b082b082b080808, + 0x2b082b082b08082b, + 0x2b082b082b2b2b08, + 0x2b082b190808192b, + 0x2b082b2b082b082b, + 0x2b082b2b2b080808, + 0x2b082b2b2b082b08, + 0x2b082b2b2b19192b, + 0x2b082b2b2b2b2b08, + 0x2b19080808080819, + 0x2b19080808081908, + 0x2b19080808190808, + 0x2b19080819080808, + 0x2b1908081919192b, + 0x2b1908082b081908, + 0x2b19081908080808, + 0x2b190819082b082b, + 0x2b190819192b1908, + 0x2b19082b1919192b, + 0x2b19082b2b082b19, + 0x2b19190808080808, + 0x2b19190808081919, + 0x2b19190819081908, + 0x2b19190819190808, + 0x2b19190819192b08, + 0x2b191919082b2b19, + 0x2b1919192b190808, + 0x2b1919192b19082b, + 0x2b19192b19080819, + 0x2b192b0819190819, + 0x2b192b082b2b192b, + 0x2b192b1919082b19, + 0x2b192b2b08191919, + 0x2b192b2b192b0808, + 0x2b2b080808080808, + 0x2b2b08080808082b, + 0x2b2b080808082b08, + 0x2b2b080808082b2b, + 0x2b2b0808082b0808, + 0x2b2b0808082b2b2b, + 0x2b2b08082b2b0808, + 0x2b2b081919190819, + 0x2b2b081919192b19, + 0x2b2b08192b2b192b, + 0x2b2b082b08080808, + 0x2b2b082b0808082b, + 0x2b2b082b08082b08, + 0x2b2b082b082b2b2b, + 0x2b2b082b2b080808, + 0x2b2b082b2b2b0808, + 0x2b2b190819080808, + 0x2b2b19082b191919, + 0x2b2b192b192b1919, + 0x2b2b192b2b192b08, + 0x2b2b2b0808082b2b, + 0x2b2b2b08082b0808, + 0x2b2b2b08082b082b, + 0x2b2b2b08082b2b08, + 0x2b2b2b082b2b0808, + 0x2b2b2b082b2b2b08, + 0x2b2b2b1908081908, + 0x2b2b2b192b081908, + 0x2b2b2b192b08192b, + 0x2b2b2b2b082b2b08, + 0x2b2b2b2b082b2b2b, + 0x2b2b2b2b2b190819, + 0x2b2b2b2b2b2b2b2b, ]; pub(super) const IQ2S_GRID: [u64; 1024] = [ - 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, - 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, - 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, - 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, - 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, - 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, - 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, - 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, - 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, - 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, - 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, - 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, - 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, - 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, - 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, - 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, - 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, - 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, - 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, - 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, - 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, - 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, - 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, - 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, - 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, - 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, - 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, - 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, - 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, - 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, - 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, - 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, - 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, - 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, - 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, - 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, - 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, - 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, - 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, - 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, - 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, - 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, - 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, - 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, - 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, - 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, - 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, - 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, - 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, - 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, - 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, - 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, - 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, - 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, - 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, - 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, - 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, - 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, - 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, - 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, - 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, - 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, - 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, - 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, - 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, - 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, - 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, - 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, - 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, - 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, - 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, - 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, - 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, - 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, - 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, - 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, - 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, - 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, - 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, - 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, - 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, - 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, - 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, - 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, - 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, - 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, - 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, - 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, - 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, - 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, - 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, - 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, - 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, - 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, - 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, - 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, - 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, - 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, - 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, - 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, - 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, - 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, - 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, - 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, - 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, - 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, - 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, - 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, - 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, - 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, - 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, - 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, - 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, - 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, - 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, - 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, - 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, - 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, - 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, - 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, - 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, - 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, - 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, - 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, - 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, - 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, - 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, - 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, + 0x0808080808080808, + 0x080808080808082b, + 0x0808080808081919, + 0x0808080808082b08, + 0x0808080808082b2b, + 0x0808080808190819, + 0x0808080808191908, + 0x080808080819192b, + 0x0808080808192b19, + 0x08080808082b0808, + 0x08080808082b082b, + 0x08080808082b1919, + 0x08080808082b2b08, + 0x0808080819080819, + 0x0808080819081908, + 0x080808081908192b, + 0x0808080819082b19, + 0x0808080819190808, + 0x080808081919082b, + 0x0808080819191919, + 0x0808080819192b08, + 0x08080808192b0819, + 0x08080808192b1908, + 0x08080808192b192b, + 0x08080808192b2b19, + 0x080808082b080808, + 0x080808082b08082b, + 0x080808082b081919, + 0x080808082b082b08, + 0x080808082b190819, + 0x080808082b191908, + 0x080808082b2b0808, + 0x080808082b2b1919, + 0x080808082b2b2b2b, + 0x0808081908080819, + 0x0808081908081908, + 0x080808190808192b, + 0x0808081908082b19, + 0x0808081908190808, + 0x080808190819082b, + 0x0808081908191919, + 0x0808081908192b08, + 0x08080819082b0819, + 0x08080819082b1908, + 0x0808081919080808, + 0x080808191908082b, + 0x0808081919081919, + 0x0808081919082b08, + 0x0808081919190819, + 0x0808081919191908, + 0x080808191919192b, + 0x0808081919192b19, + 0x08080819192b0808, + 0x08080819192b1919, + 0x08080819192b2b08, + 0x080808192b080819, + 0x080808192b081908, + 0x080808192b190808, + 0x080808192b19082b, + 0x080808192b191919, + 0x080808192b2b0819, + 0x080808192b2b1908, + 0x0808082b08080808, + 0x0808082b0808082b, + 0x0808082b08081919, + 0x0808082b08082b08, + 0x0808082b08190819, + 0x0808082b08191908, + 0x0808082b082b0808, + 0x0808082b082b2b2b, + 0x0808082b19080819, + 0x0808082b19081908, + 0x0808082b1908192b, + 0x0808082b19082b19, + 0x0808082b19190808, + 0x0808082b19191919, + 0x0808082b2b080808, + 0x0808082b2b081919, + 0x0808082b2b082b2b, + 0x0808082b2b191908, + 0x0808082b2b2b082b, + 0x0808190808080819, + 0x0808190808081908, + 0x080819080808192b, + 0x0808190808082b19, + 0x0808190808190808, + 0x080819080819082b, + 0x0808190808191919, + 0x0808190808192b08, + 0x08081908082b0819, + 0x08081908082b1908, + 0x08081908082b192b, + 0x08081908082b2b19, + 0x0808190819080808, + 0x080819081908082b, + 0x0808190819081919, + 0x0808190819082b08, + 0x0808190819082b2b, + 0x0808190819190819, + 0x0808190819191908, + 0x080819081919192b, + 0x0808190819192b19, + 0x08081908192b0808, + 0x08081908192b082b, + 0x08081908192b1919, + 0x080819082b080819, + 0x080819082b081908, + 0x080819082b08192b, + 0x080819082b082b19, + 0x080819082b190808, + 0x080819082b191919, + 0x080819082b192b08, + 0x080819082b2b0819, + 0x080819082b2b1908, + 0x0808191908080808, + 0x080819190808082b, + 0x0808191908081919, + 0x0808191908082b08, + 0x0808191908082b2b, + 0x0808191908190819, + 0x0808191908191908, + 0x080819190819192b, + 0x0808191908192b19, + 0x08081919082b0808, + 0x08081919082b1919, + 0x08081919082b2b08, + 0x0808191919080819, + 0x0808191919081908, + 0x080819191908192b, + 0x0808191919082b19, + 0x0808191919190808, + 0x080819191919082b, + 0x0808191919191919, + 0x0808191919192b08, + 0x08081919192b0819, + 0x08081919192b1908, + 0x080819192b080808, + 0x080819192b08082b, + 0x080819192b081919, + 0x080819192b082b08, + 0x080819192b190819, + 0x080819192b191908, + 0x080819192b2b0808, + 0x0808192b08080819, + 0x0808192b08081908, + 0x0808192b0808192b, + 0x0808192b08082b19, + 0x0808192b08190808, + 0x0808192b08191919, + 0x0808192b19080808, + 0x0808192b19081919, + 0x0808192b19082b08, + 0x0808192b19190819, + 0x0808192b19191908, + 0x0808192b192b0808, + 0x0808192b2b080819, + 0x0808192b2b081908, + 0x0808192b2b190808, + 0x08082b0808080808, + 0x08082b080808082b, + 0x08082b0808081919, + 0x08082b0808082b08, + 0x08082b0808190819, + 0x08082b0808191908, + 0x08082b080819192b, + 0x08082b0808192b19, + 0x08082b08082b0808, + 0x08082b08082b1919, + 0x08082b08082b2b2b, + 0x08082b0819080819, + 0x08082b0819081908, + 0x08082b081908192b, + 0x08082b0819082b19, + 0x08082b0819190808, + 0x08082b081919082b, + 0x08082b0819191919, + 0x08082b0819192b08, + 0x08082b08192b0819, + 0x08082b08192b1908, + 0x08082b082b080808, + 0x08082b082b081919, + 0x08082b082b191908, + 0x08082b082b2b2b2b, + 0x08082b1908080819, + 0x08082b1908081908, + 0x08082b1908190808, + 0x08082b190819082b, + 0x08082b1908191919, + 0x08082b1908192b08, + 0x08082b19082b0819, + 0x08082b1919080808, + 0x08082b1919081919, + 0x08082b1919082b08, + 0x08082b1919190819, + 0x08082b1919191908, + 0x08082b19192b0808, + 0x08082b192b080819, + 0x08082b192b190808, + 0x08082b2b08080808, + 0x08082b2b08190819, + 0x08082b2b08191908, + 0x08082b2b082b082b, + 0x08082b2b082b2b08, + 0x08082b2b082b2b2b, + 0x08082b2b19190808, + 0x08082b2b2b192b19, + 0x0819080808080819, + 0x0819080808081908, + 0x081908080808192b, + 0x0819080808082b19, + 0x0819080808190808, + 0x081908080819082b, + 0x0819080808191919, + 0x0819080808192b08, + 0x08190808082b0819, + 0x08190808082b1908, + 0x08190808082b192b, + 0x0819080819080808, + 0x081908081908082b, + 0x0819080819081919, + 0x0819080819082b08, + 0x0819080819190819, + 0x0819080819191908, + 0x081908081919192b, + 0x0819080819192b19, + 0x08190808192b0808, + 0x08190808192b082b, + 0x08190808192b1919, + 0x08190808192b2b08, + 0x081908082b080819, + 0x081908082b081908, + 0x081908082b08192b, + 0x081908082b190808, + 0x081908082b191919, + 0x081908082b192b08, + 0x081908082b2b0819, + 0x081908082b2b1908, + 0x0819081908080808, + 0x081908190808082b, + 0x0819081908081919, + 0x0819081908082b08, + 0x0819081908082b2b, + 0x0819081908190819, + 0x0819081908191908, + 0x081908190819192b, + 0x0819081908192b19, + 0x08190819082b0808, + 0x08190819082b082b, + 0x08190819082b1919, + 0x08190819082b2b08, + 0x0819081919080819, + 0x0819081919081908, + 0x081908191908192b, + 0x0819081919082b19, + 0x0819081919190808, + 0x081908191919082b, + 0x0819081919191919, + 0x0819081919192b08, + 0x08190819192b0819, + 0x08190819192b1908, + 0x081908192b080808, + 0x081908192b08082b, + 0x081908192b081919, + 0x081908192b082b08, + 0x081908192b190819, + 0x081908192b191908, + 0x0819082b08080819, + 0x0819082b08081908, + 0x0819082b08082b19, + 0x0819082b08190808, + 0x0819082b08191919, + 0x0819082b082b0819, + 0x0819082b082b1908, + 0x0819082b19080808, + 0x0819082b19081919, + 0x0819082b19190819, + 0x0819082b19191908, + 0x0819082b2b080819, + 0x0819082b2b081908, + 0x0819082b2b190808, + 0x0819190808080808, + 0x081919080808082b, + 0x0819190808081919, + 0x0819190808082b08, + 0x0819190808190819, + 0x0819190808191908, + 0x081919080819192b, + 0x0819190808192b19, + 0x08191908082b0808, + 0x08191908082b1919, + 0x08191908082b2b08, + 0x0819190819080819, + 0x0819190819081908, + 0x081919081908192b, + 0x0819190819082b19, + 0x0819190819190808, + 0x081919081919082b, + 0x0819190819191919, + 0x0819190819192b08, + 0x08191908192b0819, + 0x08191908192b1908, + 0x081919082b080808, + 0x081919082b08082b, + 0x081919082b081919, + 0x081919082b082b08, + 0x081919082b190819, + 0x081919082b191908, + 0x081919082b2b0808, + 0x0819191908080819, + 0x0819191908081908, + 0x081919190808192b, + 0x0819191908082b19, + 0x0819191908190808, + 0x081919190819082b, + 0x0819191908191919, + 0x0819191908192b08, + 0x08191919082b0819, + 0x08191919082b1908, + 0x0819191919080808, + 0x081919191908082b, + 0x0819191919081919, + 0x0819191919082b08, + 0x0819191919190819, + 0x0819191919191908, + 0x08191919192b0808, + 0x081919192b080819, + 0x081919192b081908, + 0x081919192b190808, + 0x0819192b08080808, + 0x0819192b08081919, + 0x0819192b08082b08, + 0x0819192b08190819, + 0x0819192b08191908, + 0x0819192b082b0808, + 0x0819192b19080819, + 0x0819192b19081908, + 0x0819192b19190808, + 0x0819192b2b080808, + 0x0819192b2b2b2b2b, + 0x08192b0808080819, + 0x08192b0808081908, + 0x08192b080808192b, + 0x08192b0808082b19, + 0x08192b0808190808, + 0x08192b0808191919, + 0x08192b0808192b08, + 0x08192b08082b0819, + 0x08192b0819080808, + 0x08192b081908082b, + 0x08192b0819081919, + 0x08192b0819082b08, + 0x08192b0819190819, + 0x08192b0819191908, + 0x08192b08192b0808, + 0x08192b082b080819, + 0x08192b082b081908, + 0x08192b1908080808, + 0x08192b190808082b, + 0x08192b1908081919, + 0x08192b1908082b08, + 0x08192b1908190819, + 0x08192b1908191908, + 0x08192b19082b0808, + 0x08192b1919080819, + 0x08192b1919081908, + 0x08192b1919190808, + 0x08192b19192b2b19, + 0x08192b192b2b082b, + 0x08192b2b08081908, + 0x08192b2b08190808, + 0x08192b2b19080808, + 0x08192b2b1919192b, + 0x082b080808080808, + 0x082b08080808082b, + 0x082b080808081919, + 0x082b080808082b08, + 0x082b080808190819, + 0x082b080808191908, + 0x082b08080819192b, + 0x082b080808192b19, + 0x082b0808082b0808, + 0x082b0808082b1919, + 0x082b0808082b2b2b, + 0x082b080819080819, + 0x082b080819081908, + 0x082b080819190808, + 0x082b08081919082b, + 0x082b080819191919, + 0x082b0808192b1908, + 0x082b08082b080808, + 0x082b08082b082b2b, + 0x082b08082b191908, + 0x082b08082b2b2b2b, + 0x082b081908080819, + 0x082b081908081908, + 0x082b081908190808, + 0x082b08190819082b, + 0x082b081908191919, + 0x082b0819082b0819, + 0x082b081919080808, + 0x082b08191908082b, + 0x082b081919081919, + 0x082b081919190819, + 0x082b081919191908, + 0x082b0819192b0808, + 0x082b08192b080819, + 0x082b08192b081908, + 0x082b08192b190808, + 0x082b082b08080808, + 0x082b082b08082b2b, + 0x082b082b082b082b, + 0x082b082b082b2b08, + 0x082b082b082b2b2b, + 0x082b082b19081908, + 0x082b082b19190808, + 0x082b082b2b082b08, + 0x082b082b2b082b2b, + 0x082b082b2b2b2b08, + 0x082b190808080819, + 0x082b190808081908, + 0x082b19080808192b, + 0x082b190808082b19, + 0x082b190808190808, + 0x082b190808191919, + 0x082b190808192b08, + 0x082b1908082b0819, + 0x082b1908082b1908, + 0x082b190819080808, + 0x082b19081908082b, + 0x082b190819081919, + 0x082b190819082b08, + 0x082b190819190819, + 0x082b190819191908, + 0x082b1908192b0808, + 0x082b19082b080819, + 0x082b19082b081908, + 0x082b19082b190808, + 0x082b191908080808, + 0x082b191908081919, + 0x082b191908082b08, + 0x082b191908190819, + 0x082b191908191908, + 0x082b1919082b0808, + 0x082b191919080819, + 0x082b191919081908, + 0x082b191919190808, + 0x082b1919192b192b, + 0x082b19192b080808, + 0x082b192b08080819, + 0x082b192b08081908, + 0x082b192b08190808, + 0x082b192b19080808, + 0x082b192b19192b19, + 0x082b2b0808080808, + 0x082b2b0808081919, + 0x082b2b0808190819, + 0x082b2b0808191908, + 0x082b2b0819080819, + 0x082b2b0819081908, + 0x082b2b0819190808, + 0x082b2b082b082b2b, + 0x082b2b082b2b2b2b, + 0x082b2b1908080819, + 0x082b2b1908081908, + 0x082b2b1908190808, + 0x082b2b192b191919, + 0x082b2b2b08082b2b, + 0x082b2b2b082b082b, + 0x082b2b2b192b1908, + 0x082b2b2b2b082b08, + 0x082b2b2b2b082b2b, + 0x1908080808080819, + 0x1908080808081908, + 0x190808080808192b, + 0x1908080808082b19, + 0x1908080808190808, + 0x190808080819082b, + 0x1908080808191919, + 0x1908080808192b08, + 0x1908080808192b2b, + 0x19080808082b0819, + 0x19080808082b1908, + 0x19080808082b192b, + 0x1908080819080808, + 0x190808081908082b, + 0x1908080819081919, + 0x1908080819082b08, + 0x1908080819082b2b, + 0x1908080819190819, + 0x1908080819191908, + 0x190808081919192b, + 0x1908080819192b19, + 0x19080808192b0808, + 0x19080808192b082b, + 0x19080808192b1919, + 0x190808082b080819, + 0x190808082b081908, + 0x190808082b190808, + 0x190808082b191919, + 0x190808082b192b08, + 0x190808082b2b0819, + 0x190808082b2b1908, + 0x1908081908080808, + 0x190808190808082b, + 0x1908081908081919, + 0x1908081908082b08, + 0x1908081908190819, + 0x1908081908191908, + 0x190808190819192b, + 0x1908081908192b19, + 0x19080819082b0808, + 0x19080819082b082b, + 0x19080819082b1919, + 0x1908081919080819, + 0x1908081919081908, + 0x190808191908192b, + 0x1908081919082b19, + 0x1908081919190808, + 0x190808191919082b, + 0x1908081919191919, + 0x1908081919192b08, + 0x19080819192b0819, + 0x19080819192b1908, + 0x190808192b080808, + 0x190808192b08082b, + 0x190808192b081919, + 0x190808192b082b08, + 0x190808192b190819, + 0x190808192b191908, + 0x190808192b2b0808, + 0x1908082b08080819, + 0x1908082b08081908, + 0x1908082b08190808, + 0x1908082b0819082b, + 0x1908082b08191919, + 0x1908082b08192b08, + 0x1908082b082b1908, + 0x1908082b19080808, + 0x1908082b19081919, + 0x1908082b19082b08, + 0x1908082b19190819, + 0x1908082b19191908, + 0x1908082b192b0808, + 0x1908082b2b080819, + 0x1908082b2b081908, + 0x1908190808080808, + 0x190819080808082b, + 0x1908190808081919, + 0x1908190808082b08, + 0x1908190808082b2b, + 0x1908190808190819, + 0x1908190808191908, + 0x190819080819192b, + 0x1908190808192b19, + 0x19081908082b0808, + 0x19081908082b082b, + 0x19081908082b1919, + 0x19081908082b2b08, + 0x1908190819080819, + 0x1908190819081908, + 0x190819081908192b, + 0x1908190819082b19, + 0x1908190819190808, + 0x190819081919082b, + 0x1908190819191919, + 0x1908190819192b08, + 0x19081908192b0819, + 0x19081908192b1908, + 0x190819082b080808, + 0x190819082b08082b, + 0x190819082b081919, + 0x190819082b082b08, + 0x190819082b190819, + 0x190819082b191908, + 0x190819082b2b0808, + 0x1908191908080819, + 0x1908191908081908, + 0x190819190808192b, + 0x1908191908082b19, + 0x1908191908190808, + 0x190819190819082b, + 0x1908191908191919, + 0x1908191908192b08, + 0x19081919082b0819, + 0x19081919082b1908, + 0x1908191919080808, + 0x190819191908082b, + 0x1908191919081919, + 0x1908191919082b08, + 0x1908191919190819, + 0x1908191919191908, + 0x19081919192b0808, + 0x19081919192b2b2b, + 0x190819192b080819, + 0x190819192b081908, + 0x190819192b190808, + 0x1908192b08080808, + 0x1908192b0808082b, + 0x1908192b08081919, + 0x1908192b08082b08, + 0x1908192b08190819, + 0x1908192b08191908, + 0x1908192b082b0808, + 0x1908192b19080819, + 0x1908192b19081908, + 0x1908192b19190808, + 0x1908192b2b080808, + 0x1908192b2b2b1919, + 0x19082b0808080819, + 0x19082b0808081908, + 0x19082b0808082b19, + 0x19082b0808190808, + 0x19082b080819082b, + 0x19082b0808191919, + 0x19082b0808192b08, + 0x19082b08082b0819, + 0x19082b08082b1908, + 0x19082b0819080808, + 0x19082b081908082b, + 0x19082b0819081919, + 0x19082b0819082b08, + 0x19082b0819190819, + 0x19082b0819191908, + 0x19082b08192b0808, + 0x19082b082b081908, + 0x19082b082b190808, + 0x19082b1908080808, + 0x19082b190808082b, + 0x19082b1908081919, + 0x19082b1908082b08, + 0x19082b1908190819, + 0x19082b1908191908, + 0x19082b19082b0808, + 0x19082b1919080819, + 0x19082b1919081908, + 0x19082b1919190808, + 0x19082b192b080808, + 0x19082b192b19192b, + 0x19082b2b08080819, + 0x19082b2b08081908, + 0x19082b2b08190808, + 0x19082b2b19080808, + 0x1919080808080808, + 0x191908080808082b, + 0x1919080808081919, + 0x1919080808082b08, + 0x1919080808190819, + 0x1919080808191908, + 0x191908080819192b, + 0x1919080808192b19, + 0x19190808082b0808, + 0x19190808082b082b, + 0x19190808082b1919, + 0x19190808082b2b08, + 0x1919080819080819, + 0x1919080819081908, + 0x191908081908192b, + 0x1919080819082b19, + 0x1919080819190808, + 0x191908081919082b, + 0x1919080819191919, + 0x1919080819192b08, + 0x19190808192b0819, + 0x19190808192b1908, + 0x191908082b080808, + 0x191908082b08082b, + 0x191908082b081919, + 0x191908082b082b08, + 0x191908082b190819, + 0x191908082b191908, + 0x1919081908080819, + 0x1919081908081908, + 0x191908190808192b, + 0x1919081908082b19, + 0x1919081908190808, + 0x191908190819082b, + 0x1919081908191919, + 0x1919081908192b08, + 0x19190819082b0819, + 0x19190819082b1908, + 0x1919081919080808, + 0x191908191908082b, + 0x1919081919081919, + 0x1919081919082b08, + 0x1919081919190819, + 0x1919081919191908, + 0x19190819192b0808, + 0x191908192b080819, + 0x191908192b081908, + 0x191908192b190808, + 0x1919082b08080808, + 0x1919082b08081919, + 0x1919082b08082b08, + 0x1919082b08190819, + 0x1919082b08191908, + 0x1919082b082b0808, + 0x1919082b19080819, + 0x1919082b19081908, + 0x1919082b19190808, + 0x1919082b192b2b19, + 0x1919082b2b080808, + 0x1919190808080819, + 0x1919190808081908, + 0x191919080808192b, + 0x1919190808082b19, + 0x1919190808190808, + 0x191919080819082b, + 0x1919190808191919, + 0x1919190808192b08, + 0x19191908082b0819, + 0x19191908082b1908, + 0x1919190819080808, + 0x191919081908082b, + 0x1919190819081919, + 0x1919190819082b08, + 0x1919190819190819, + 0x1919190819191908, + 0x19191908192b0808, + 0x191919082b080819, + 0x191919082b081908, + 0x191919082b190808, + 0x1919191908080808, + 0x191919190808082b, + 0x1919191908081919, + 0x1919191908082b08, + 0x1919191908190819, + 0x1919191908191908, + 0x19191919082b0808, + 0x1919191919080819, + 0x1919191919081908, + 0x1919191919190808, + 0x191919192b080808, + 0x1919192b08080819, + 0x1919192b08081908, + 0x1919192b08190808, + 0x1919192b082b192b, + 0x1919192b19080808, + 0x19192b0808080808, + 0x19192b080808082b, + 0x19192b0808081919, + 0x19192b0808082b08, + 0x19192b0808190819, + 0x19192b0808191908, + 0x19192b08082b0808, + 0x19192b0819080819, + 0x19192b0819081908, + 0x19192b0819190808, + 0x19192b0819192b2b, + 0x19192b082b080808, + 0x19192b1908080819, + 0x19192b1908081908, + 0x19192b1908190808, + 0x19192b1919080808, + 0x19192b2b08080808, + 0x19192b2b08192b19, + 0x19192b2b2b081919, + 0x19192b2b2b2b2b08, + 0x192b080808080819, + 0x192b080808081908, + 0x192b08080808192b, + 0x192b080808190808, + 0x192b08080819082b, + 0x192b080808191919, + 0x192b080808192b08, + 0x192b0808082b0819, + 0x192b0808082b1908, + 0x192b080819080808, + 0x192b080819081919, + 0x192b080819082b08, + 0x192b080819190819, + 0x192b080819191908, + 0x192b0808192b0808, + 0x192b08082b081908, + 0x192b08082b190808, + 0x192b081908080808, + 0x192b08190808082b, + 0x192b081908081919, + 0x192b081908082b08, + 0x192b081908190819, + 0x192b081908191908, + 0x192b0819082b0808, + 0x192b081919080819, + 0x192b081919081908, + 0x192b081919190808, + 0x192b08192b080808, + 0x192b08192b192b19, + 0x192b082b08081908, + 0x192b082b08190808, + 0x192b082b19080808, + 0x192b082b1919192b, + 0x192b082b2b2b0819, + 0x192b190808080808, + 0x192b190808081919, + 0x192b190808082b08, + 0x192b190808190819, + 0x192b190808191908, + 0x192b1908082b0808, + 0x192b190819080819, + 0x192b190819081908, + 0x192b190819190808, + 0x192b19082b080808, + 0x192b191908080819, + 0x192b191908081908, + 0x192b191908190808, + 0x192b191919080808, + 0x192b191919082b2b, + 0x192b1919192b2b08, + 0x192b19192b19082b, + 0x192b192b08080808, + 0x192b192b2b191908, + 0x192b2b0808080819, + 0x192b2b0808081908, + 0x192b2b0808190808, + 0x192b2b08192b1919, + 0x192b2b082b192b08, + 0x192b2b1908080808, + 0x192b2b19082b2b2b, + 0x192b2b2b1908082b, + 0x192b2b2b2b2b0819, + 0x2b08080808080808, + 0x2b0808080808082b, + 0x2b08080808081919, + 0x2b08080808082b08, + 0x2b08080808190819, + 0x2b08080808191908, + 0x2b08080808192b19, + 0x2b080808082b0808, + 0x2b080808082b1919, + 0x2b08080819080819, + 0x2b08080819081908, + 0x2b08080819190808, + 0x2b0808081919082b, + 0x2b08080819191919, + 0x2b08080819192b08, + 0x2b080808192b0819, + 0x2b0808082b080808, + 0x2b0808082b081919, + 0x2b0808082b190819, + 0x2b0808082b191908, + 0x2b08081908080819, + 0x2b08081908081908, + 0x2b08081908082b19, + 0x2b08081908190808, + 0x2b0808190819082b, + 0x2b08081908191919, + 0x2b08081908192b08, + 0x2b080819082b0819, + 0x2b080819082b1908, + 0x2b08081919080808, + 0x2b0808191908082b, + 0x2b08081919081919, + 0x2b08081919082b08, + 0x2b08081919190819, + 0x2b08081919191908, + 0x2b0808192b080819, + 0x2b0808192b081908, + 0x2b0808192b190808, + 0x2b0808192b2b2b19, + 0x2b08082b08080808, + 0x2b08082b08081919, + 0x2b08082b08082b2b, + 0x2b08082b08190819, + 0x2b08082b08191908, + 0x2b08082b19080819, + 0x2b08082b19081908, + 0x2b08082b19190808, + 0x2b08190808080819, + 0x2b08190808081908, + 0x2b0819080808192b, + 0x2b08190808082b19, + 0x2b08190808190808, + 0x2b0819080819082b, + 0x2b08190808191919, + 0x2b08190808192b08, + 0x2b081908082b0819, + 0x2b08190819080808, + 0x2b0819081908082b, + 0x2b08190819081919, + 0x2b08190819082b08, + 0x2b08190819190819, + 0x2b08190819191908, + 0x2b081908192b0808, + 0x2b0819082b080819, + 0x2b0819082b081908, + 0x2b0819082b190808, + 0x2b08191908080808, + 0x2b0819190808082b, + 0x2b08191908081919, + 0x2b08191908082b08, + 0x2b08191908190819, + 0x2b08191908191908, + 0x2b081919082b0808, + 0x2b08191919080819, + 0x2b08191919081908, + 0x2b08191919190808, + 0x2b0819192b080808, + 0x2b0819192b082b2b, + 0x2b08192b08080819, + 0x2b08192b08081908, + 0x2b08192b08190808, + 0x2b08192b082b2b19, + 0x2b08192b19080808, + 0x2b082b0808080808, + 0x2b082b0808081919, + 0x2b082b0808190819, + 0x2b082b0808191908, + 0x2b082b0819080819, + 0x2b082b0819081908, + 0x2b082b0819190808, + 0x2b082b082b2b082b, + 0x2b082b1908080819, + 0x2b082b1908081908, + 0x2b082b1919080808, + 0x2b082b19192b1919, + 0x2b082b2b082b082b, + 0x2b082b2b19192b08, + 0x2b082b2b19192b2b, + 0x2b082b2b2b08082b, + 0x2b082b2b2b2b082b, + 0x2b19080808080819, + 0x2b19080808081908, + 0x2b19080808082b19, + 0x2b19080808190808, + 0x2b1908080819082b, + 0x2b19080808191919, + 0x2b19080808192b08, + 0x2b190808082b1908, + 0x2b19080819080808, + 0x2b1908081908082b, + 0x2b19080819081919, + 0x2b19080819082b08, + 0x2b19080819190819, + 0x2b19080819191908, + 0x2b190808192b0808, + 0x2b1908082b080819, + 0x2b1908082b081908, + 0x2b1908082b190808, + 0x2b19081908080808, + 0x2b19081908081919, + 0x2b19081908190819, + 0x2b19081908191908, + 0x2b19081919080819, + 0x2b19081919081908, + 0x2b19081919190808, + 0x2b19081919192b2b, + 0x2b19082b08080819, + 0x2b19082b08081908, + 0x2b19082b08190808, + 0x2b19082b19080808, + 0x2b19082b2b2b192b, + 0x2b19190808080808, + 0x2b1919080808082b, + 0x2b19190808081919, + 0x2b19190808082b08, + 0x2b19190808190819, + 0x2b19190808191908, + 0x2b191908082b0808, + 0x2b19190819080819, + 0x2b19190819081908, + 0x2b19190819190808, + 0x2b1919082b080808, + 0x2b1919082b19192b, + 0x2b19191908080819, + 0x2b19191908081908, + 0x2b19191908190808, + 0x2b19191919080808, + 0x2b1919192b192b08, + 0x2b1919192b2b0819, + 0x2b19192b08080808, + 0x2b19192b1908192b, + 0x2b19192b192b1908, + 0x2b192b0808080819, + 0x2b192b0808081908, + 0x2b192b0808190808, + 0x2b192b08082b192b, + 0x2b192b0819080808, + 0x2b192b082b2b2b19, + 0x2b192b1908080808, + 0x2b192b1919082b19, + 0x2b192b191919082b, + 0x2b192b2b2b190808, + 0x2b2b080808080808, + 0x2b2b080808081919, + 0x2b2b080808082b2b, + 0x2b2b080808191908, + 0x2b2b0808082b082b, + 0x2b2b0808082b2b2b, + 0x2b2b080819080819, + 0x2b2b080819081908, + 0x2b2b080819190808, + 0x2b2b08082b2b082b, + 0x2b2b08082b2b2b2b, + 0x2b2b081919080808, + 0x2b2b0819192b1919, + 0x2b2b082b0808082b, + 0x2b2b082b08082b2b, + 0x2b2b082b082b082b, + 0x2b2b082b082b2b08, + 0x2b2b082b082b2b2b, + 0x2b2b082b2b08082b, + 0x2b2b082b2b082b08, + 0x2b2b082b2b082b2b, + 0x2b2b082b2b2b2b08, + 0x2b2b190808080819, + 0x2b2b190808081908, + 0x2b2b190808190808, + 0x2b2b190819080808, + 0x2b2b19082b082b19, + 0x2b2b19082b2b1908, + 0x2b2b191908080808, + 0x2b2b191908192b19, + 0x2b2b192b19190819, + 0x2b2b2b0808082b2b, + 0x2b2b2b08082b2b08, + 0x2b2b2b082b2b082b, + 0x2b2b2b1919191908, + 0x2b2b2b192b08192b, + 0x2b2b2b2b08082b08, + 0x2b2b2b2b08082b2b, + 0x2b2b2b2b082b0808, + 0x2b2b2b2b082b082b, + 0x2b2b2b2b082b2b08, + 0x2b2b2b2b2b082b08, + 0x2b2b2b2b2b2b2b2b, ]; pub(super) const IQ3XXS_GRID: [u32; 256] = [ - 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, - 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, - 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, - 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, - 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, - 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, - 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, - 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, - 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, - 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, - 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, - 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, - 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, - 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, - 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, - 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, - 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, - 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, - 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, - 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, - 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, - 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, - 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, - 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, - 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, - 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, - 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, - 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, - 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, - 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, - 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, - 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, + 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, 0x04041c0c, + 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, 0x040c140c, 0x040c142c, + 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, 0x04140414, 0x04140424, 0x04140c0c, + 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, + 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, + 0x04243e1c, 0x04243e2c, 0x042c040c, 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, + 0x043e0c24, 0x043e0c34, 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, + 0x0c04141c, 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, + 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, 0x0c143e14, + 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, 0x0c24042c, 0x0c242c04, + 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, 0x0c3e2404, 0x14040404, 0x14040414, + 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, + 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, + 0x14140414, 0x14140c0c, 0x14140c3e, 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, + 0x141c0c04, 0x141c0c24, 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, + 0x142c3e24, 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, + 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, 0x1c0c2424, + 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, 0x1c1c0c0c, 0x1c1c1c1c, + 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, + 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, + 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, + 0x24242c0c, 0x24243424, 0x242c142c, 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, + 0x2c040c14, 0x2c04240c, 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, + 0x2c143e14, 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, + 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, 0x340c340c, + 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, 0x34341c1c, 0x343e041c, + 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, 0x3e042c14, 0x3e0c1434, 0x3e0c2404, + 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, + 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, ]; pub(super) const IQ3S_GRID: [u32; 512] = [ - 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, - 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, - 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, - 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, - 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, - 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, - 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, - 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, - 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, - 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, - 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, - 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, - 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, - 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, - 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, - 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, - 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, - 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, - 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, - 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, - 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, - 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, - 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, - 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, - 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, - 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, - 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, - 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, - 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, - 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, - 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, - 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, - 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, - 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, - 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, - 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, - 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, - 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, - 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, - 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, - 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, - 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, - 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, - 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, - 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, - 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, - 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, - 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, - 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, - 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, - 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, - 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, - 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, - 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, - 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, - 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, - 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, - 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, - 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, - 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, - 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, - 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, - 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, + 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, 0x01010309, + 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, 0x0101090b, 0x0101090f, + 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, 0x01010f0f, 0x01030101, 0x01030103, + 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, 0x01030501, 0x01030507, 0x0103050f, 0x01030703, + 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, + 0x01050301, 0x01050307, 0x0105030d, 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, + 0x0105090f, 0x01050b03, 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, + 0x01070505, 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, + 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, 0x01090907, + 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, 0x010b0707, 0x010b0903, + 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, 0x010d0307, 0x010d0703, 0x010d0b05, + 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, + 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, + 0x0301030f, 0x03010501, 0x03010505, 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, + 0x03010f05, 0x03030101, 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, + 0x03030707, 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, + 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, 0x03050f05, + 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, 0x03070701, 0x03070709, + 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, 0x03090309, 0x03090703, 0x03090707, + 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, + 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, + 0x030f0301, 0x030f0305, 0x030f0503, 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, + 0x05010107, 0x0501010b, 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, + 0x0501050f, 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, + 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, 0x05030505, + 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, 0x0505010f, 0x05050503, + 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, 0x05050f03, 0x05050f09, 0x05070101, + 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, 0x05070703, 0x05070707, 0x05070905, 0x05070b01, + 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, + 0x05090f0b, 0x050b0109, 0x050b0303, 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, + 0x050d0105, 0x050d010f, 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, + 0x050f0907, 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, + 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, 0x07030103, + 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, 0x07030f05, 0x07030f0d, + 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, 0x07070103, 0x07070301, 0x07070309, + 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, + 0x07090107, 0x07090303, 0x0709030d, 0x07090505, 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, + 0x070b0301, 0x070b0305, 0x070b050b, 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, + 0x070f0103, 0x070f0107, 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, + 0x09010509, 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, + 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, 0x09050107, + 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, 0x09050f01, 0x09070109, + 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, 0x09090101, 0x09090105, 0x09090509, + 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, + 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, + 0x0b010505, 0x0b010901, 0x0b010909, 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, + 0x0b03010b, 0x0b030305, 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, + 0x0b05070d, 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, + 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, 0x0b0b0b03, + 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, 0x0d01030b, 0x0d010703, + 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, 0x0d050305, 0x0d050709, 0x0d050905, + 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, + 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, + 0x0f010101, 0x0f010109, 0x0f01010f, 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, + 0x0f030105, 0x0f030303, 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, + 0x0f050503, 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, ]; -pub(super) const KVALUES_IQ4NL: [i8; 16] = [ - -127, -104, -83, -65, -49, -35, -22, -10, - 1, 13, 25, 38, 53, 69, 89, 113, -]; +pub(super) const KVALUES_IQ4NL: [i8; 16] = [-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113]; diff --git a/crates/native-cpu-expert/src/rust_dequant.rs b/crates/native-cpu-expert/src/rust_dequant.rs index a4e5f485..2bda8598 100644 --- a/crates/native-cpu-expert/src/rust_dequant.rs +++ b/crates/native-cpu-expert/src/rust_dequant.rs @@ -1,34 +1,339 @@ //! Pinned GGML scalar to_float traits, for the Original CPU/FP32 bench oracle. //! They are deliberately separate from quantized vec_dot accumulation. -use super::{Error,Result}; -use super::rust_ggml::Kind; use super::rust_codebooks::*; -fn u16at(x:&[u8],i:usize)->u16{u16::from_le_bytes([x[i],x[i+1]])} -fn u32at(x:&[u8],i:usize)->u32{u32::from_le_bytes(x[i..i+4].try_into().unwrap())} -pub(super) fn half(h:u16)->f32{let w=(h as u32)<<16;let sign=w&0x80000000;let twice=w.wrapping_add(w);let normal=f32::from_bits((twice>>4).wrapping_add(0xe0<<23))*f32::from_bits(0x07800000);let sub=f32::from_bits((twice>>17)|(126<<23))-0.5;f32::from_bits(sign|if twice<1<<27{sub.to_bits()}else{normal.to_bits()})} -pub(super) fn half_rn(f:f32)->u16{let mut base=(f.abs()*f32::from_bits(0x77800000))*f32::from_bits(0x08800000);let w=f.to_bits();let twice=w.wrapping_add(w);let bias=(twice&0xff000000).max(0x71000000);base=f32::from_bits((bias>>1)+0x07800000)+base;let bits=base.to_bits();((w&0x80000000)>>16)as u16|if twice>0xff000000{0x7e00}else{(((bits>>13)&0x7c00)+(bits&0xfff))as u16}} -fn h(x:&[u8],i:usize)->f32{half(u16at(x,i))} -const FP4:[i8;16]=[0,1,2,3,4,6,8,12,0,-1,-2,-3,-4,-6,-8,-12]; -fn e8_half(e:u8)->f32{f32::from_bits(if e<2{0x00200000u32<f32{if e==0||e==127{return 0.0;}let exp=(e>>3)&15;let m=e&7;let raw=if exp==0{m as f32*f32::from_bits(118<<23)}else{(1.0+m as f32/8.0)*f32::from_bits(((exp as i32-7+127)as u32)<<23)};raw*0.5} -fn six(x:&[u8])->[i32;16]{let a=u32at(x,0);let b=u32at(x,4);let c=u32at(x,8);let u=[(a&0x0f0f0f0f)|((c&0x03030303)<<4),(b&0x0f0f0f0f)|(((c>>2)&0x03030303)<<4),((a>>4)&0x0f0f0f0f)|(((c>>4)&0x03030303)<<4),((b>>4)&0x0f0f0f0f)|(((c>>6)&0x03030303)<<4)];std::array::from_fn(|j|((u[j/4]>>(8*(j%4)))as u8 as i32)-32)} -fn k4(x:&[u8],j:usize)->(i32,i32){if j<4{((x[j]&63)as i32,(x[j+4]&63)as i32)}else{(((x[j+4]&15)|((x[j-4]>>6)<<4))as i32,((x[j+4]>>4)|((x[j]>>6)<<4))as i32)}} -pub fn dequantize(kind:Kind,raw:&[u8],output:&mut[f32])->Result<()>{if kind.row_bytes(output.len())?!=raw.len(){return Err(Error::Shape);}let (q,b)=kind.block();for (x,y) in raw.chunks_exact(b).zip(output.chunks_exact_mut(q)){match kind{ - Kind::F32=>y[0]=f32::from_le_bytes(x.try_into().unwrap()),Kind::F16=>y[0]=h(x,0),Kind::Bf16=>y[0]=f32::from_bits((u16at(x,0)as u32)<<16), - Kind::Q1Zero=>{let d=h(x,0);let negative=-d;for j in 0..128{y[j]=if x[2+j/8]&(1<<(j%8))!=0{d}else{negative};}}, - Kind::Q2Zero=>{let d=h(x,0);for j in 0..64{y[j]=(((x[2+j/4]>>(2*(j%4)))&3)as i32-1)as f32*d;}}, - Kind::Q4Zero|Kind::Q4One|Kind::Q5Zero|Kind::Q5One|Kind::Q8Zero=>{let d=h(x,0);if kind==Kind::Q8Zero{for j in 0..32{y[j]=x[j+2]as i8 as f32*d;}}else{let min=if matches!(kind,Kind::Q4One|Kind::Q5One){h(x,2)}else{0.0};let head=match kind{Kind::Q4Zero=>2,Kind::Q4One=>4,Kind::Q5Zero=>6,_=>8};let high=if matches!(kind,Kind::Q5Zero|Kind::Q5One){u32at(x,head-4)}else{0};for j in 0..16{let low=x[head+j];let a=(low&15)as i32|((((high>>j)&1)as i32)<<4);let c=(low>>4)as i32|((((high>>(j+16))&1)as i32)<<4);if matches!(kind,Kind::Q4One|Kind::Q5One){y[j]=a as f32*d+min;y[j+16]=c as f32*d+min;}else{let center=if kind==Kind::Q4Zero{8}else{16};y[j]=(a-center)as f32*d;y[j+16]=(c-center)as f32*d;}}}}, - Kind::MxFp4=>{let d=e8_half(x[0]);for j in 0..16{y[j]=FP4[(x[1+j]&15)as usize]as f32*d;y[j+16]=FP4[(x[1+j]>>4)as usize]as f32*d;}}, - Kind::NvFp4=>{for k in 0..4{let d=ue4(x[k]);for j in 0..8{let v=x[4+k/2*16+j+k%2*8];y[k*16+j]=FP4[(v&15)as usize]as f32*d;y[k*16+j+8]=FP4[(v>>4)as usize]as f32*d;}}}, - Kind::Q2K=>{let d=h(x,80);let m=h(x,82);for j in 0..256{let sc=x[j/16];let q=(x[16+j/128*32+j%32]>>(2*(j%128/32)))&3;y[j]=(d*(sc&15)as f32)*q as f32-m*(sc>>4)as f32;}}, - Kind::Q3K=>{let d=h(x,108);let sc=six(&x[96..108]);for j in 0..256{let q=((x[32+j/128*32+j%32]>>(2*(j%128/32)))&3)as i32-if x[j%32]&(1<<(j/32))!=0{0}else{4};y[j]=(d*sc[j/16]as f32)*q as f32;}}, - Kind::Q4K|Kind::Q5K=>{let d=h(x,0);let m=h(x,2);let qstart=if kind==Kind::Q4K{16}else{48};for j in 0..256{let k=j/32;let(s,min)=k4(&x[4..16],k);let mut v=((x[qstart+k/2*32+j%32]>>(4*(k%2)))&15)as i32;if kind==Kind::Q5K{v+=(((x[16+j%32]>>k)&1)as i32)<<4;}y[j]=(d*s as f32)*v as f32-m*min as f32;}}, - Kind::Q6K=>{let d=h(x,208);for j in 0..256{let k=j%128/32;let v=((x[j/128*64+if k%2==1{32}else{0}+j%32]>>(if k>=2{4}else{0}))&15)|(((x[128+j/128*32+j%32]>>(k*2))&3)<<4);y[j]=d*x[192+j/16]as i8 as f32*(v as i32-32)as f32;}}, - Kind::Iq2Xxs|Kind::Iq2Xs|Kind::Iq2S=>{let d=h(x,0);for group in 0..8{let packed=if kind==Kind::Iq2Xxs{u32at(x,2+group*8+4)}else{0};for l in 0..4{let (db,grid,sign)=match kind{Kind::Iq2Xxs=>(d*(0.5+(packed>>28)as f32)*0.25,IQ2XXS_GRID[x[2+group*8+l]as usize],KSIGNS_IQ2XS[((packed>>(7*l))&127)as usize]),Kind::Iq2Xs=>{let q=u16at(x,2+(group*4+l)*2);(d*(0.5+((x[66+group]>>(4*(l/2)))&15)as f32)*0.25,IQ2XS_GRID[(q&511)as usize],KSIGNS_IQ2XS[(q>>9)as usize])},_=>{let index=x[2+group*4+l]as usize|(((x[66+group]as usize)<<(8-2*l))&0x300);(d*(0.5+((x[74+group]>>(4*(l/2)))&15)as f32)*0.25,IQ2S_GRID[index],x[34+group*4+l])}};let grid=grid.to_le_bytes();for j in 0..8{y[group*32+l*8+j]=db*grid[j]as f32*if sign&(1<{let d=h(x,0);for group in 0..8{let packed=if kind==Kind::Iq3Xxs{u32at(x,66+group*4)}else{0};let db=if kind==Kind::Iq3Xxs{d*(0.5+(packed>>28)as f32)*0.5}else{d*(1+2*((x[106+group/2]>>(4*(group%2)))&15))as f32};for l in 0..4{let sign=if kind==Kind::Iq3Xxs{KSIGNS_IQ2XS[((packed>>(7*l))&127)as usize]}else{x[74+group*4+l]};let g0=if kind==Kind::Iq3Xxs{IQ3XXS_GRID[x[2+group*8+l*2]as usize]}else{IQ3S_GRID[x[2+group*8+l*2]as usize|(((x[66+group]as usize)<<(8-2*l))&256)]};let g1=if kind==Kind::Iq3Xxs{IQ3XXS_GRID[x[3+group*8+l*2]as usize]}else{IQ3S_GRID[x[3+group*8+l*2]as usize|(((x[66+group]as usize)<<(7-2*l))&256)]};for (half,grid) in [g0,g1].into_iter().enumerate(){let grid=grid.to_le_bytes();for j in 0..4{let at=half*4+j;y[group*32+l*8+at]=db*grid[j]as f32*if sign&(1<{let sc:[u16;4]=if kind==Kind::Iq1M{std::array::from_fn(|j|u16at(x,48+j*2))}else{[0;4]};let d=if kind==Kind::Iq1S{h(x,0)}else{half((sc[0]>>12)|((sc[1]>>8)&0x00f0)|((sc[2]>>4)&0x0f00)|(sc[3]&0xf000))};for group in 0..8{for l in 0..4{let(index,delta,scale)=if kind==Kind::Iq1S{let hi=u16at(x,34+group*2);(x[2+group*4+l]as usize|((((hi>>(3*l))&7)as usize)<<8),if hi&0x8000!=0{-0.125}else{0.125},2*((hi>>12)&7)+1)}else{let hi=x[32+group*2+l/2];(x[group*4+l]as usize|(((hi as usize)<<(if l%2==0{8}else{4}))&0x700),if hi&(if l%2==0{8}else{128})!=0{-0.125}else{0.125},2*((sc[group/2]>>(6*(group%2)+3*(l/2)))&7)+1)};let grid=super::rust_iq1_grid::GRID[index].to_le_bytes();let dl=d*scale as f32;for j in 0..8{y[group*32+l*8+j]=dl*(grid[j]as i8 as f32+delta);}}}}, - Kind::Iq4Nl=>{let d=h(x,0);for j in 0..16{y[j]=d*KVALUES_IQ4NL[(x[2+j]&15)as usize]as f32;y[j+16]=d*KVALUES_IQ4NL[(x[2+j]>>4)as usize]as f32;}}, - Kind::Iq4Xs=>{let d=h(x,0);let hi=u16at(x,2);for k in 0..8{let s=(((x[4+k/2]>>(4*(k%2)))&15)as i32)|((((hi>>(2*k))&3)as i32)<<4);let dl=d*(s-32)as f32;for j in 0..16{y[k*32+j]=dl*KVALUES_IQ4NL[(x[8+k*16+j]&15)as usize]as f32;y[k*32+j+16]=dl*KVALUES_IQ4NL[(x[8+k*16+j]>>4)as usize]as f32;}}}, - Kind::Tq1=>{let d=h(x,52);let powers=[1u8,3,9,27,81];for k in 0..5{for j in 0..32{y[k*32+j]=(((x[j].wrapping_mul(powers[k])as u16*3)>>8)as i16-1)as f32*d;}for j in 0..16{y[160+k*16+j]=(((x[32+j].wrapping_mul(powers[k])as u16*3)>>8)as i16-1)as f32*d;}}for k in 0..4{for j in 0..4{y[240+k*4+j]=(((x[48+j].wrapping_mul(powers[k])as u16*3)>>8)as i16-1)as f32*d;}}}, - Kind::Tq2=>{let d=h(x,64);for j in 0..256{let q=((x[j/128*32+j%32]>>(2*(j%128/32)))&3)as i8;y[j]=(q-1)as f32*d;}} -}}Ok(())} +use super::rust_ggml::Kind; +use super::{Error, Result}; +fn u16at(x: &[u8], i: usize) -> u16 { + u16::from_le_bytes([x[i], x[i + 1]]) +} +fn u32at(x: &[u8], i: usize) -> u32 { + u32::from_le_bytes(x[i..i + 4].try_into().unwrap()) +} +pub(super) fn half(h: u16) -> f32 { + let w = (h as u32) << 16; + let sign = w & 0x80000000; + let twice = w.wrapping_add(w); + let normal = f32::from_bits((twice >> 4).wrapping_add(0xe0 << 23)) * f32::from_bits(0x07800000); + let sub = f32::from_bits((twice >> 17) | (126 << 23)) - 0.5; + f32::from_bits(sign | if twice < 1 << 27 { sub.to_bits() } else { normal.to_bits() }) +} +pub(super) fn half_rn(f: f32) -> u16 { + let mut base = (f.abs() * f32::from_bits(0x77800000)) * f32::from_bits(0x08800000); + let w = f.to_bits(); + let twice = w.wrapping_add(w); + let bias = (twice & 0xff000000).max(0x71000000); + base = f32::from_bits((bias >> 1) + 0x07800000) + base; + let bits = base.to_bits(); + ((w & 0x80000000) >> 16) as u16 + | if twice > 0xff000000 { 0x7e00 } else { (((bits >> 13) & 0x7c00) + (bits & 0xfff)) as u16 } +} +fn h(x: &[u8], i: usize) -> f32 { + half(u16at(x, i)) +} +const FP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12]; +fn e8_half(e: u8) -> f32 { + f32::from_bits(if e < 2 { 0x00200000u32 << e } else { ((e as u32) - 1) << 23 }) +} +fn ue4(e: u8) -> f32 { + if e == 0 || e == 127 { + return 0.0; + } + let exp = (e >> 3) & 15; + let m = e & 7; + let raw = if exp == 0 { + m as f32 * f32::from_bits(118 << 23) + } else { + (1.0 + m as f32 / 8.0) * f32::from_bits(((exp as i32 - 7 + 127) as u32) << 23) + }; + raw * 0.5 +} +fn six(x: &[u8]) -> [i32; 16] { + let a = u32at(x, 0); + let b = u32at(x, 4); + let c = u32at(x, 8); + let u = [ + (a & 0x0f0f0f0f) | ((c & 0x03030303) << 4), + (b & 0x0f0f0f0f) | (((c >> 2) & 0x03030303) << 4), + ((a >> 4) & 0x0f0f0f0f) | (((c >> 4) & 0x03030303) << 4), + ((b >> 4) & 0x0f0f0f0f) | (((c >> 6) & 0x03030303) << 4), + ]; + std::array::from_fn(|j| ((u[j / 4] >> (8 * (j % 4))) as u8 as i32) - 32) +} +fn k4(x: &[u8], j: usize) -> (i32, i32) { + if j < 4 { + ((x[j] & 63) as i32, (x[j + 4] & 63) as i32) + } else { + (((x[j + 4] & 15) | ((x[j - 4] >> 6) << 4)) as i32, ((x[j + 4] >> 4) | ((x[j] >> 6) << 4)) as i32) + } +} +pub fn dequantize(kind: Kind, raw: &[u8], output: &mut [f32]) -> Result<()> { + if kind.row_bytes(output.len())? != raw.len() { + return Err(Error::Shape); + } + let (q, b) = kind.block(); + for (x, y) in raw.chunks_exact(b).zip(output.chunks_exact_mut(q)) { + match kind { + Kind::F32 => y[0] = f32::from_le_bytes(x.try_into().unwrap()), + Kind::F16 => y[0] = h(x, 0), + Kind::Bf16 => y[0] = f32::from_bits((u16at(x, 0) as u32) << 16), + Kind::Q1Zero => { + let d = h(x, 0); + let negative = -d; + for j in 0..128 { + y[j] = if x[2 + j / 8] & (1 << (j % 8)) != 0 { d } else { negative }; + } + } + Kind::Q2Zero => { + let d = h(x, 0); + for j in 0..64 { + y[j] = (((x[2 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 * d; + } + } + Kind::Q4Zero | Kind::Q4One | Kind::Q5Zero | Kind::Q5One | Kind::Q8Zero => { + let d = h(x, 0); + if kind == Kind::Q8Zero { + for j in 0..32 { + y[j] = x[j + 2] as i8 as f32 * d; + } + } else { + let min = if matches!(kind, Kind::Q4One | Kind::Q5One) { h(x, 2) } else { 0.0 }; + let head = match kind { + Kind::Q4Zero => 2, + Kind::Q4One => 4, + Kind::Q5Zero => 6, + _ => 8, + }; + let high = if matches!(kind, Kind::Q5Zero | Kind::Q5One) { u32at(x, head - 4) } else { 0 }; + for j in 0..16 { + let low = x[head + j]; + let a = (low & 15) as i32 | ((((high >> j) & 1) as i32) << 4); + let c = (low >> 4) as i32 | ((((high >> (j + 16)) & 1) as i32) << 4); + if matches!(kind, Kind::Q4One | Kind::Q5One) { + y[j] = a as f32 * d + min; + y[j + 16] = c as f32 * d + min; + } else { + let center = if kind == Kind::Q4Zero { 8 } else { 16 }; + y[j] = (a - center) as f32 * d; + y[j + 16] = (c - center) as f32 * d; + } + } + } + } + Kind::MxFp4 => { + let d = e8_half(x[0]); + for j in 0..16 { + y[j] = FP4[(x[1 + j] & 15) as usize] as f32 * d; + y[j + 16] = FP4[(x[1 + j] >> 4) as usize] as f32 * d; + } + } + Kind::NvFp4 => { + for k in 0..4 { + let d = ue4(x[k]); + for j in 0..8 { + let v = x[4 + k / 2 * 16 + j + k % 2 * 8]; + y[k * 16 + j] = FP4[(v & 15) as usize] as f32 * d; + y[k * 16 + j + 8] = FP4[(v >> 4) as usize] as f32 * d; + } + } + } + Kind::Q2K => { + let d = h(x, 80); + let m = h(x, 82); + for j in 0..256 { + let sc = x[j / 16]; + let q = (x[16 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3; + y[j] = (d * (sc & 15) as f32) * q as f32 - m * (sc >> 4) as f32; + } + } + Kind::Q3K => { + let d = h(x, 108); + let sc = six(&x[96..108]); + for j in 0..256 { + let q = ((x[32 + j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i32 + - if x[j % 32] & (1 << (j / 32)) != 0 { 0 } else { 4 }; + y[j] = (d * sc[j / 16] as f32) * q as f32; + } + } + Kind::Q4K | Kind::Q5K => { + let d = h(x, 0); + let m = h(x, 2); + let qstart = if kind == Kind::Q4K { 16 } else { 48 }; + for j in 0..256 { + let k = j / 32; + let (s, min) = k4(&x[4..16], k); + let mut v = ((x[qstart + k / 2 * 32 + j % 32] >> (4 * (k % 2))) & 15) as i32; + if kind == Kind::Q5K { + v += (((x[16 + j % 32] >> k) & 1) as i32) << 4; + } + y[j] = (d * s as f32) * v as f32 - m * min as f32; + } + } + Kind::Q6K => { + let d = h(x, 208); + for j in 0..256 { + let k = j % 128 / 32; + let v = ((x[j / 128 * 64 + if k % 2 == 1 { 32 } else { 0 } + j % 32] + >> (if k >= 2 { 4 } else { 0 })) + & 15) + | (((x[128 + j / 128 * 32 + j % 32] >> (k * 2)) & 3) << 4); + y[j] = d * x[192 + j / 16] as i8 as f32 * (v as i32 - 32) as f32; + } + } + Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq2S => { + let d = h(x, 0); + for group in 0..8 { + let packed = if kind == Kind::Iq2Xxs { u32at(x, 2 + group * 8 + 4) } else { 0 }; + for l in 0..4 { + let (db, grid, sign) = match kind { + Kind::Iq2Xxs => ( + d * (0.5 + (packed >> 28) as f32) * 0.25, + IQ2XXS_GRID[x[2 + group * 8 + l] as usize], + KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize], + ), + Kind::Iq2Xs => { + let q = u16at(x, 2 + (group * 4 + l) * 2); + ( + d * (0.5 + ((x[66 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25, + IQ2XS_GRID[(q & 511) as usize], + KSIGNS_IQ2XS[(q >> 9) as usize], + ) + } + _ => { + let index = + x[2 + group * 4 + l] as usize | (((x[66 + group] as usize) << (8 - 2 * l)) & 0x300); + ( + d * (0.5 + ((x[74 + group] >> (4 * (l / 2))) & 15) as f32) * 0.25, + IQ2S_GRID[index], + x[34 + group * 4 + l], + ) + } + }; + let grid = grid.to_le_bytes(); + for j in 0..8 { + y[group * 32 + l * 8 + j] = + db * grid[j] as f32 * if sign & (1 << j) != 0 { -1.0 } else { 1.0 }; + } + } + } + } + Kind::Iq3Xxs | Kind::Iq3S => { + let d = h(x, 0); + for group in 0..8 { + let packed = if kind == Kind::Iq3Xxs { u32at(x, 66 + group * 4) } else { 0 }; + let db = if kind == Kind::Iq3Xxs { + d * (0.5 + (packed >> 28) as f32) * 0.5 + } else { + d * (1 + 2 * ((x[106 + group / 2] >> (4 * (group % 2))) & 15)) as f32 + }; + for l in 0..4 { + let sign = if kind == Kind::Iq3Xxs { + KSIGNS_IQ2XS[((packed >> (7 * l)) & 127) as usize] + } else { + x[74 + group * 4 + l] + }; + let g0 = if kind == Kind::Iq3Xxs { + IQ3XXS_GRID[x[2 + group * 8 + l * 2] as usize] + } else { + IQ3S_GRID + [x[2 + group * 8 + l * 2] as usize | (((x[66 + group] as usize) << (8 - 2 * l)) & 256)] + }; + let g1 = if kind == Kind::Iq3Xxs { + IQ3XXS_GRID[x[3 + group * 8 + l * 2] as usize] + } else { + IQ3S_GRID + [x[3 + group * 8 + l * 2] as usize | (((x[66 + group] as usize) << (7 - 2 * l)) & 256)] + }; + for (half, grid) in [g0, g1].into_iter().enumerate() { + let grid = grid.to_le_bytes(); + for j in 0..4 { + let at = half * 4 + j; + y[group * 32 + l * 8 + at] = + db * grid[j] as f32 * if sign & (1 << at) != 0 { -1.0 } else { 1.0 }; + } + } + } + } + } + Kind::Iq1S | Kind::Iq1M => { + let sc: [u16; 4] = + if kind == Kind::Iq1M { std::array::from_fn(|j| u16at(x, 48 + j * 2)) } else { [0; 4] }; + let d = if kind == Kind::Iq1S { + h(x, 0) + } else { + half((sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000)) + }; + for group in 0..8 { + for l in 0..4 { + let (index, delta, scale) = if kind == Kind::Iq1S { + let hi = u16at(x, 34 + group * 2); + ( + x[2 + group * 4 + l] as usize | ((((hi >> (3 * l)) & 7) as usize) << 8), + if hi & 0x8000 != 0 { -0.125 } else { 0.125 }, + 2 * ((hi >> 12) & 7) + 1, + ) + } else { + let hi = x[32 + group * 2 + l / 2]; + ( + x[group * 4 + l] as usize + | (((hi as usize) << (if l % 2 == 0 { 8 } else { 4 })) & 0x700), + if hi & (if l % 2 == 0 { 8 } else { 128 }) != 0 { -0.125 } else { 0.125 }, + 2 * ((sc[group / 2] >> (6 * (group % 2) + 3 * (l / 2))) & 7) + 1, + ) + }; + let grid = super::rust_iq1_grid::GRID[index].to_le_bytes(); + let dl = d * scale as f32; + for j in 0..8 { + y[group * 32 + l * 8 + j] = dl * (grid[j] as i8 as f32 + delta); + } + } + } + } + Kind::Iq4Nl => { + let d = h(x, 0); + for j in 0..16 { + y[j] = d * KVALUES_IQ4NL[(x[2 + j] & 15) as usize] as f32; + y[j + 16] = d * KVALUES_IQ4NL[(x[2 + j] >> 4) as usize] as f32; + } + } + Kind::Iq4Xs => { + let d = h(x, 0); + let hi = u16at(x, 2); + for k in 0..8 { + let s = (((x[4 + k / 2] >> (4 * (k % 2))) & 15) as i32) | ((((hi >> (2 * k)) & 3) as i32) << 4); + let dl = d * (s - 32) as f32; + for j in 0..16 { + y[k * 32 + j] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] & 15) as usize] as f32; + y[k * 32 + j + 16] = dl * KVALUES_IQ4NL[(x[8 + k * 16 + j] >> 4) as usize] as f32; + } + } + } + Kind::Tq1 => { + let d = h(x, 52); + let powers = [1u8, 3, 9, 27, 81]; + for k in 0..5 { + for j in 0..32 { + y[k * 32 + j] = (((x[j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d; + } + for j in 0..16 { + y[160 + k * 16 + j] = + (((x[32 + j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d; + } + } + for k in 0..4 { + for j in 0..4 { + y[240 + k * 4 + j] = + (((x[48 + j].wrapping_mul(powers[k]) as u16 * 3) >> 8) as i16 - 1) as f32 * d; + } + } + } + Kind::Tq2 => { + let d = h(x, 64); + for j in 0..256 { + let q = ((x[j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3) as i8; + y[j] = (q - 1) as f32 * d; + } + } + } + } + Ok(()) +} diff --git a/crates/native-cpu-expert/src/rust_expert_layout.rs b/crates/native-cpu-expert/src/rust_expert_layout.rs index 11f2a271..0151b27d 100644 --- a/crates/native-cpu-expert/src/rust_expert_layout.rs +++ b/crates/native-cpu-expert/src/rust_expert_layout.rs @@ -1,35 +1,272 @@ //! Original native_experts.txt v0..v4 geometry/shard parsing. This metadata //! is numerical layout only; actual ModelBinding/source admission stays outside. -use std::{path::Path,sync::{OnceLock,RwLock}}; -use super::{Error,Result,H,FF}; -use super::rust_ggml::{Kind,NativeFormat}; -#[derive(Clone)]pub struct ExpertLayout{pub native:bool,pub n_layers:usize,pub n_expert:i64,pub format:Vec,pub offset:Vec,pub bytes:Vec,pub gguf_offset:Vec,pub gguf_file:Vec,pub version:i32,pub max_blob:u64,pub total:u64} -impl ExpertLayout{ - pub fn canonical(n_layers:usize,n_expert:i64)->Self{Self{native:false,n_layers,n_expert,format:Vec::new(),offset:Vec::new(),bytes:Vec::new(),gguf_offset:Vec::new(),gguf_file:Vec::new(),version:0,max_blob:super::rust_legacy::BLOB as u64,total:(n_layers as u64).wrapping_mul(n_expert as u64).wrapping_mul(super::rust_legacy::BLOB as u64)}} - pub fn blob_bytes(&self,layer:usize)->Result{if layer>=self.n_layers{return Err(Error::Shape);}Ok(if self.native{self.bytes[layer]}else{super::rust_legacy::BLOB as u64})} - pub fn layer_offset(&self,layer:usize)->Result{if layer>=self.n_layers{return Err(Error::Shape);}Ok(if self.native{self.offset[layer]}else{(layer as u64).wrapping_mul(self.n_expert as u64).wrapping_mul(super::rust_legacy::BLOB as u64)})} - pub fn blob_offset(&self,layer:usize,expert:i64)->Result{Ok(self.layer_offset(layer)?.wrapping_add((expert as u64).wrapping_mul(self.blob_bytes(layer)?)))} - pub fn load(pack:&Path,n_layers:usize,n_expert:i64)->Result{let data=match std::fs::read(pack.join("native_experts.txt")){Ok(v)=>v,Err(_)=>return Ok(Self::canonical(n_layers,n_expert))};let data=std::str::from_utf8(&data).map_err(|_|Error::Shape)?;Self::parse(data,n_layers,n_expert)} - pub fn parse(data:&str,n_layers:usize,n_expert:i64)->Result{let mut l=Self::canonical(n_layers,n_expert);l.native=true;l.max_blob=0;let mut fmt:Vec>=filled(n_layers,None)?;l.offset=filled(n_layers,u64::MAX)?;l.bytes=filled(n_layers,0)?; - for line in data.split('\n'){if line.is_empty()||line.starts_with('#'){if let Some(v)=line.strip_prefix("# strata native experts v"){l.version=super::rust_simd::atoi(v);if l.version>4{return Err(Error::Unsupported);}}if let Some(at)=line.find("(n_expert "){l.n_expert=atoll(&line[at+10..]);}continue;}let mut fields=DecimalStream::new(line);let layer=fields.signed().ok_or(Error::Shape)?;let gu=fields.signed().ok_or(Error::Shape)?;let down=fields.signed().ok_or(Error::Shape)?;let offset=fields.unsigned().ok_or(Error::Shape)?;let bytes=fields.unsigned().ok_or(Error::Shape)?;if layer<0||layer as usize>=n_layers{return Err(Error::Shape);}let f=NativeFormat::new(Kind::from_original(gu as i32)?,Kind::from_original(down as i32)?,H,FF)?;if f.bytes as u64!=bytes{return Err(Error::Shape);}let layer=layer as usize; - let a=fields.unsigned();let b=fields.unsigned();let c=fields.unsigned();if let (Some(a),Some(b),Some(c))=(a,b,c){if l.gguf_offset.is_empty(){l.gguf_offset=filled(n_layers.checked_mul(3).ok_or(Error::Shape)?,0)?;}l.gguf_offset[layer*3..layer*3+3].copy_from_slice(&[a,b,c]);if let Some(file)=fields.word(){let parts:Vec<&str>=file.split(',').collect();if (parts.len()!=1&&parts.len()!=3)||fields.word().is_some(){return Err(Error::Shape);}if l.gguf_file.is_empty(){l.gguf_file=filled(n_layers.checked_mul(3).ok_or(Error::Shape)?,String::new())?;}for r in 0..3{l.gguf_file[layer*3+r]=parts[if parts.len()==1{0}else{r}].to_string();}}} - fmt[layer]=Some(f);l.offset[layer]=offset;l.bytes[layer]=bytes;l.max_blob=l.max_blob.max(bytes); - }let mut at=0u64;for i in 0..n_layers{if l.offset[i]!=at{return Err(Error::Shape);}at=at.wrapping_add(l.bytes[i].wrapping_mul(l.n_expert as u64));}l.total=at;l.format.try_reserve_exact(n_layers).map_err(|_|Error::Allocation)?;for f in fmt{l.format.push(f.ok_or(Error::Shape)?);}Ok(l)} +use super::rust_ggml::{Kind, NativeFormat}; +use super::{Error, FF, H, Result}; +use std::{ + path::Path, + sync::{OnceLock, RwLock}, +}; +#[derive(Clone)] +pub struct ExpertLayout { + pub native: bool, + pub n_layers: usize, + pub n_expert: i64, + pub format: Vec, + pub offset: Vec, + pub bytes: Vec, + pub gguf_offset: Vec, + pub gguf_file: Vec, + pub version: i32, + pub max_blob: u64, + pub total: u64, +} +impl ExpertLayout { + pub fn canonical(n_layers: usize, n_expert: i64) -> Self { + Self { + native: false, + n_layers, + n_expert, + format: Vec::new(), + offset: Vec::new(), + bytes: Vec::new(), + gguf_offset: Vec::new(), + gguf_file: Vec::new(), + version: 0, + max_blob: super::rust_legacy::BLOB as u64, + total: (n_layers as u64).wrapping_mul(n_expert as u64).wrapping_mul(super::rust_legacy::BLOB as u64), + } + } + pub fn blob_bytes(&self, layer: usize) -> Result { + if layer >= self.n_layers { + return Err(Error::Shape); + } + Ok(if self.native { self.bytes[layer] } else { super::rust_legacy::BLOB as u64 }) + } + pub fn layer_offset(&self, layer: usize) -> Result { + if layer >= self.n_layers { + return Err(Error::Shape); + } + Ok(if self.native { + self.offset[layer] + } else { + (layer as u64).wrapping_mul(self.n_expert as u64).wrapping_mul(super::rust_legacy::BLOB as u64) + }) + } + pub fn blob_offset(&self, layer: usize, expert: i64) -> Result { + Ok(self.layer_offset(layer)?.wrapping_add((expert as u64).wrapping_mul(self.blob_bytes(layer)?))) + } + pub fn load(pack: &Path, n_layers: usize, n_expert: i64) -> Result { + let data = match std::fs::read(pack.join("native_experts.txt")) { + Ok(v) => v, + Err(_) => return Ok(Self::canonical(n_layers, n_expert)), + }; + let data = std::str::from_utf8(&data).map_err(|_| Error::Shape)?; + Self::parse(data, n_layers, n_expert) + } + pub fn parse(data: &str, n_layers: usize, n_expert: i64) -> Result { + let mut l = Self::canonical(n_layers, n_expert); + l.native = true; + l.max_blob = 0; + let mut fmt: Vec> = filled(n_layers, None)?; + l.offset = filled(n_layers, u64::MAX)?; + l.bytes = filled(n_layers, 0)?; + for line in data.split('\n') { + if line.is_empty() || line.starts_with('#') { + if let Some(v) = line.strip_prefix("# strata native experts v") { + l.version = super::rust_simd::atoi(v); + if l.version > 4 { + return Err(Error::Unsupported); + } + } + if let Some(at) = line.find("(n_expert ") { + l.n_expert = atoll(&line[at + 10..]); + } + continue; + } + let mut fields = DecimalStream::new(line); + let layer = fields.signed().ok_or(Error::Shape)?; + let gu = fields.signed().ok_or(Error::Shape)?; + let down = fields.signed().ok_or(Error::Shape)?; + let offset = fields.unsigned().ok_or(Error::Shape)?; + let bytes = fields.unsigned().ok_or(Error::Shape)?; + if layer < 0 || layer as usize >= n_layers { + return Err(Error::Shape); + } + let f = NativeFormat::new(Kind::from_original(gu as i32)?, Kind::from_original(down as i32)?, H, FF)?; + if f.bytes as u64 != bytes { + return Err(Error::Shape); + } + let layer = layer as usize; + let a = fields.unsigned(); + let b = fields.unsigned(); + let c = fields.unsigned(); + if let (Some(a), Some(b), Some(c)) = (a, b, c) { + if l.gguf_offset.is_empty() { + l.gguf_offset = filled(n_layers.checked_mul(3).ok_or(Error::Shape)?, 0)?; + } + l.gguf_offset[layer * 3..layer * 3 + 3].copy_from_slice(&[a, b, c]); + if let Some(file) = fields.word() { + let parts: Vec<&str> = file.split(',').collect(); + if (parts.len() != 1 && parts.len() != 3) || fields.word().is_some() { + return Err(Error::Shape); + } + if l.gguf_file.is_empty() { + l.gguf_file = filled(n_layers.checked_mul(3).ok_or(Error::Shape)?, String::new())?; + } + for r in 0..3 { + l.gguf_file[layer * 3 + r] = parts[if parts.len() == 1 { 0 } else { r }].to_string(); + } + } + } + fmt[layer] = Some(f); + l.offset[layer] = offset; + l.bytes[layer] = bytes; + l.max_blob = l.max_blob.max(bytes); + } + let mut at = 0u64; + for i in 0..n_layers { + if l.offset[i] != at { + return Err(Error::Shape); + } + at = at.wrapping_add(l.bytes[i].wrapping_mul(l.n_expert as u64)); + } + l.total = at; + l.format.try_reserve_exact(n_layers).map_err(|_| Error::Allocation)?; + for f in fmt { + l.format.push(f.ok_or(Error::Shape)?); + } + Ok(l) + } +} +fn filled(n: usize, value: T) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize(n, value); + Ok(v) +} +fn atoll(value: &str) -> i64 { + let b = value.as_bytes(); + let mut i = 0; + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + let mut sign = 1i64; + if i < b.len() { + if b[i] == b'-' { + sign = -1; + i += 1; + } else if b[i] == b'+' { + i += 1; + } + } + let mut out = 0i64; + while i < b.len() && b[i].is_ascii_digit() { + out = out.wrapping_mul(10).wrapping_add((b[i] - b'0') as i64); + i += 1; + } + out.wrapping_mul(sign) +} +static LAYOUT: OnceLock> = OnceLock::new(); +pub fn install_layout(layout: ExpertLayout) { + *LAYOUT.get_or_init(|| RwLock::new(ExpertLayout::canonical(0, 512))).write().unwrap_or_else(|p| p.into_inner()) = + layout; +} +pub fn expert_layout() -> ExpertLayout { + LAYOUT + .get_or_init(|| RwLock::new(ExpertLayout::canonical(0, 512))) + .read() + .unwrap_or_else(|p| p.into_inner()) + .clone() +} +pub fn cpu_name() -> String { + /* SAFETY: CPUID is architectural on x86_64; leaves 0x80000002..=4 are queried only after leaf 0x80000000 reported them. */ + unsafe { + use std::arch::x86_64::__cpuid; + if __cpuid(0x80000000).eax < 0x80000004 { + return "unknown".into(); + } + let mut bytes = [0u8; 48]; + for i in 0..3 { + let q = __cpuid(0x80000002 + i); + for (j, v) in [q.eax, q.ebx, q.ecx, q.edx].into_iter().enumerate() { + bytes[(i as usize) * 16 + j * 4..(i as usize) * 16 + j * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + } + let end = bytes.iter().position(|&x| x == 0).unwrap_or(48); + { + let name = String::from_utf8_lossy(&bytes[..end]); + let trimmed = name.trim_matches(' '); + if trimmed.is_empty() { "unknown".to_owned() } else { trimmed.to_owned() } + } + } } -fn filled(n:usize,value:T)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize(n,value);Ok(v)} -fn atoll(value:&str)->i64{let b=value.as_bytes();let mut i=0;while i>=OnceLock::new(); -pub fn install_layout(layout:ExpertLayout){*LAYOUT.get_or_init(||RwLock::new(ExpertLayout::canonical(0,512))).write().unwrap_or_else(|p|p.into_inner())=layout;} -pub fn expert_layout()->ExpertLayout{LAYOUT.get_or_init(||RwLock::new(ExpertLayout::canonical(0,512))).read().unwrap_or_else(|p|p.into_inner()).clone()} -pub fn cpu_name()->String{/* SAFETY: CPUID is architectural on x86_64; leaves 0x80000002..=4 are queried only after leaf 0x80000000 reported them. */unsafe{use std::arch::x86_64::__cpuid;if __cpuid(0x80000000).eax<0x80000004{return "unknown".into();}let mut bytes=[0u8;48];for i in 0..3{let q=__cpuid(0x80000002+i);for (j,v) in [q.eax,q.ebx,q.ecx,q.edx].into_iter().enumerate(){bytes[(i as usize)*16+j*4..(i as usize)*16+j*4+4].copy_from_slice(&v.to_le_bytes());}}let end=bytes.iter().position(|&x|x==0).unwrap_or(48);{let name=String::from_utf8_lossy(&bytes[..end]);let trimmed=name.trim_matches(' ');if trimmed.is_empty(){"unknown".to_owned()}else{trimmed.to_owned()}}}} // Decimal istringstream extraction: consume prefixes, preserve optional failure, // and allow the standard unsigned negation rather than parsing whole tokens. -struct DecimalStream<'a>{text:&'a str,at:usize,failed:bool} -impl<'a> DecimalStream<'a>{ - fn new(text:&'a str)->Self{Self{text,at:0,failed:false}} - fn number(&mut self)->Option<(bool,u64)>{if self.failed{return None;}let b=self.text.as_bytes();while self.atOption{let (neg,n)=self.number()?;let limit=if neg{1u64<<63}else{i64::MAX as u64};if n>limit{self.failed=true;return None;}Some(if neg{(n as i64).wrapping_neg()}else{n as i64})} - fn unsigned(&mut self)->Option{let(neg,n)=self.number()?;Some(if neg{n.wrapping_neg()}else{n})} - fn word(&mut self)->Option<&'a str>{if self.failed{return None;}let b=self.text.as_bytes();while self.at { + text: &'a str, + at: usize, + failed: bool, +} +impl<'a> DecimalStream<'a> { + fn new(text: &'a str) -> Self { + Self { text, at: 0, failed: false } + } + fn number(&mut self) -> Option<(bool, u64)> { + if self.failed { + return None; + } + let b = self.text.as_bytes(); + while self.at < b.len() && b[self.at].is_ascii_whitespace() { + self.at += 1; + } + let mut neg = false; + if self.at < b.len() && matches!(b[self.at], b'+' | b'-') { + neg = b[self.at] == b'-'; + self.at += 1; + } + let start = self.at; + let mut n = Some(0u64); + while self.at < b.len() && b[self.at].is_ascii_digit() { + n = n.and_then(|n| n.checked_mul(10)?.checked_add((b[self.at] - b'0') as u64)); + self.at += 1; + } + if self.at == start || n.is_none() { + self.failed = true; + return None; + } + Some((neg, n.unwrap())) + } + fn signed(&mut self) -> Option { + let (neg, n) = self.number()?; + let limit = if neg { 1u64 << 63 } else { i64::MAX as u64 }; + if n > limit { + self.failed = true; + return None; + } + Some(if neg { (n as i64).wrapping_neg() } else { n as i64 }) + } + fn unsigned(&mut self) -> Option { + let (neg, n) = self.number()?; + Some(if neg { n.wrapping_neg() } else { n }) + } + fn word(&mut self) -> Option<&'a str> { + if self.failed { + return None; + } + let b = self.text.as_bytes(); + while self.at < b.len() && b[self.at].is_ascii_whitespace() { + self.at += 1; + } + let start = self.at; + while self.at < b.len() && !b[self.at].is_ascii_whitespace() { + self.at += 1; + } + if start == self.at { + self.failed = true; + None + } else { + Some(&self.text[start..self.at]) + } + } } diff --git a/crates/native-cpu-expert/src/rust_general_pool.rs b/crates/native-cpu-expert/src/rust_general_pool.rs index 2b73d9dd..342bfbfb 100644 --- a/crates/native-cpu-expert/src/rust_general_pool.rs +++ b/crates/native-cpu-expert/src/rust_general_pool.rs @@ -1,75 +1,124 @@ //! Original seven-mode ExpertPool with lifetime-bounded Rust job adapters. //! Each raw destination write is one disjoint claimed row; no whole mutable //! output slices are shared. Batch operands remain borrowed until done AND park. -use std::{cell::UnsafeCell,sync::{Arc,Mutex,Condvar,OnceLock,atomic::{AtomicBool,AtomicU32,AtomicU64,AtomicI32,AtomicI64,Ordering}},thread,time::{Duration,Instant}}; -use super::{Error,Result,H,FF}; -use super::rust_legacy::{PlanarActivation,SingleScratch}; -use super::rust_native_general::NativeActivation; use super::rust_ggml::NativeFormat; -use super::rust_topology::{CpuTopology,PoolAffinity}; -pub struct PlanarJob<'a>{pub blob:&'a[u8],pub activation:&'a PlanarActivation,pub output:&'a mut[f32]} -pub struct PlanarJobMulti<'a>{pub blob:&'a[u8],pub activation:&'a[&'a PlanarActivation],pub output:&'a mut[&'a mut[f32]]} -pub struct NativeJobMulti<'a>{pub blob:&'a[u8],pub activation:&'a[&'a NativeActivation],pub planar:&'a[&'a PlanarActivation],pub output:&'a mut[&'a mut[f32]]} -#[derive(Clone,Copy)]struct Job{blob:*const u8,len:usize,nt:usize,a:[*const PlanarActivation;8],na:[*const NativeActivation;8],out:[*mut f32;8]} -impl Default for Job{fn default()->Self{Self{blob:std::ptr::null(),len:0,nt:0,a:[std::ptr::null();8],na:[std::ptr::null();8],out:[std::ptr::null_mut();8]}}} -#[repr(align(64))]struct Line(T); -struct Split{ff:[[f32;FF];8],a2:[PlanarActivation;8],hq:[[u8;1024];8]} -impl Default for Split{fn default()->Self{Self{ff:[[0.0;FF];8],a2:std::array::from_fn(|_|PlanarActivation::default()),hq:[[0;1024];8]}}} +use super::rust_legacy::{PlanarActivation, SingleScratch}; +use super::rust_native_general::NativeActivation; +use super::rust_topology::{CpuTopology, PoolAffinity}; +use super::{Error, FF, H, Result}; +use std::{ + cell::UnsafeCell, + sync::{ + Arc, Condvar, Mutex, OnceLock, + atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicU32, AtomicU64, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; +pub struct PlanarJob<'a> { + pub blob: &'a [u8], + pub activation: &'a PlanarActivation, + pub output: &'a mut [f32], +} +pub struct PlanarJobMulti<'a> { + pub blob: &'a [u8], + pub activation: &'a [&'a PlanarActivation], + pub output: &'a mut [&'a mut [f32]], +} +pub struct NativeJobMulti<'a> { + pub blob: &'a [u8], + pub activation: &'a [&'a NativeActivation], + pub planar: &'a [&'a PlanarActivation], + pub output: &'a mut [&'a mut [f32]], +} +#[derive(Clone, Copy)] +struct Job { + blob: *const u8, + len: usize, + nt: usize, + a: [*const PlanarActivation; 8], + na: [*const NativeActivation; 8], + out: [*mut f32; 8], +} +#[repr(align(64))] +struct Line(T); +struct Split { + ff: [[f32; FF]; 8], + a2: [PlanarActivation; 8], + hq: [[u8; 1024]; 8], +} // `hq` rows are reinterpreted as Q8Zero/Q8One (align 2) by rust_ggml::{quantize_raw,dot_raw}; pin the layout. -const _: ()=assert!(std::mem::offset_of!(Split,hq)%4==0); -#[repr(C,align(64))]struct SingleSplit{ff:[f32;FF],a2:PlanarActivation} -impl Default for SingleSplit{fn default()->Self{Self{ff:[0.0;FF],a2:PlanarActivation::default()}}} -struct Batch{jobs:Vec,format:Option,mode:u32,rows:usize,tasks:usize,parts:usize} -struct Shared{head:Line,done:Line,parked:Line,epoch:Line,stop:Line,sleepers:Line,sleep_mu:Mutex<()>,sleep_cv:Condvar,spin:Duration,n:usize,batch:UnsafeCell,split:Vec>,scratch:Vec>,single:Vec>,states:Vec,host:AtomicI32,host_ms:AtomicI64} -// SAFETY: immutable batch publication is release/acquire. Tagged CAS grants one -// disjoint row interval or whole expert. Scratch index belongs to worker/host. -// Host mutation occurs only after both completion and all worker park barriers. -// `batch.jobs` holds raw pointers into CALLER memory; they are cleared (`clear`) or dead before every return, and a -// worker panic is turned into abort (catch_unwind in `new`). The host-thread drain is NOT unwind-guarded here: a host -// panic inside `execute` would leave workers writing caller memory, which is why every extent is validated first. -unsafe impl Sync for Shared{} unsafe impl Send for Shared{} -fn alloc_with(n:usize,make:impl FnMut()->T)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,make);Ok(v)} -fn cells(n:usize)->Result>>{alloc_with(n,||UnsafeCell::new(T::default()))} -static RELEASE_GPU_WAITS:OnceLock=OnceLock::new(); -pub fn install_release_gpu_waits(callback:fn())->Result<()>{RELEASE_GPU_WAITS.set(callback).map_err(|_|Error::Shape)} -fn now_ms()->i64{static START:OnceLock=OnceLock::new();START.get_or_init(Instant::now).elapsed().as_millis().min(i64::MAX as u128)as i64} -impl Shared{ - fn publish(&self){self.epoch.0.fetch_add(1,Ordering::SeqCst);if self.sleepers.0.load(Ordering::SeqCst)!=0{let _lk=self.sleep_mu.lock().unwrap_or_else(|p|p.into_inner());self.sleep_cv.notify_all();}} - fn claim(&self,e:u32)->Option{let mut h=self.head.0.load(Ordering::Acquire);loop{if (h>>32)as u32!=e{return None;}if h&0xffff>=(h>>16)&0xffff{return None;}match self.head.0.compare_exchange_weak(h,h+1,Ordering::AcqRel,Ordering::Acquire){Ok(_)=>return Some((h&0xffff)as usize),Err(next)=>h=next}}} - fn state(&self,id:usize,s:i32){if id(),std::ptr::addr_of!((*z).a2))}else{(std::ptr::addr_of_mut!((*s).ff).cast::(),std::ptr::addr_of!((*s).a2).cast::())};let blob=std::slice::from_raw_parts(j.blob,j.len);let n=j.nt; - if b.mode<=4{let a0=if b.mode==1||b.mode==3{j.a[0]}else{a2_ptr};let mut a=[&*a0;8];for t in 0..n{a[t]=if b.mode==1||b.mode==3{&*j.a[t]}else{&*a2_ptr.add(t)};}if b.mode==1||b.mode==3{super::rust_legacy::gate_each(blob,&a[..n],r0,r1,|t,r,v|ff_ptr.add(t*FF+r).write(v));}else{super::rust_legacy::down_each(blob,&a[..n],r0,r1,|t,r,v|j.out[t].add(r).write(v));}} - else{let f=b.format.as_ref().unwrap();let mut g=[0.0;8];let mut u=g;for r in r0..r1{let (kind,offset,stride,width)=if b.mode==5{(f.gu,0,f.gu_row,H)}else{(f.down,f.down_offset,f.down_row,FF)};let row=&blob[offset+r*stride..offset+(r+1)*stride];if kind.original_id()==42{let a0=if b.mode==5{&(*j.a[0]).0}else{&(*a2_ptr).0};let mut a=[a0;8];for t in 0..n{a[t]=if b.mode==5{&(*j.a[t]).0}else{&(*a2_ptr.add(t)).0};}if super::rust_simd::dispatch().avx512{super::rust_q2::dot512(row,&a[..n],&mut g[..n]);}else{super::rust_q2::dot256(row,&a[..n],&mut g[..n]);}if b.mode==5{let ur=&blob[f.up_offset+r*stride..f.up_offset+(r+1)*stride];if super::rust_simd::dispatch().avx512{super::rust_q2::dot512(ur,&a[..n],&mut u[..n]);}else{super::rust_q2::dot256(ur,&a[..n],&mut u[..n]);}}}else if b.mode==5{let mut a=[&*j.na[0];8];for t in 0..n{a[t]=&*j.na[t];}super::rust_native_general::group_dot(kind,row,&a[..n],&mut g[..n],super::rust_simd::dispatch(),true);let ur=&blob[f.up_offset+r*stride..f.up_offset+(r+1)*stride];super::rust_native_general::group_dot(kind,ur,&a[..n],&mut u[..n],super::rust_simd::dispatch(),true);}else{let base=std::ptr::addr_of!((*s).hq).cast::<[u8;1024]>();let mut a:[&[u8];8]=[&[];8];for t in 0..n{a[t]=&*base.add(t);}super::rust_native_general::group_dot_bytes(kind,row,FF,&a[..n],&mut g[..n],super::rust_simd::dispatch(),false);}debug_assert_eq!(width,if b.mode==5{H}else{FF});for t in 0..n{if b.mode==5{ff_ptr.add(t*FF+r).write(super::rust_simd::silu(g[t],u[t]));}else{j.out[t].add(r).write(g[t]);}}}} - at+=r1-r0;} - }} - fn worker(&self,id:usize,core:i32){super::rust_platform::pin(core);let mut seen=0;self.parked.0.fetch_add(1,Ordering::AcqRel);loop{let at=Instant::now();let mut spins=0u32;while self.epoch.0.load(Ordering::Acquire)==seen{if self.stop.0.load(Ordering::Relaxed){return;}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0||at.elapsed()!{eprintln!("strata: the CPU expert pool stalled {what}");if let Some(f)=RELEASE_GPU_WAITS.get(){f();}std::process::abort()} - fn wait_parked(&self){self.state(self.n,-11);let mut spins=0u32;let mut t=Instant::now();while self.parked.0.load(Ordering::Acquire)!=self.n as u32{std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue;}if spins==1024{t=Instant::now();}else if t.elapsed()>Duration::from_secs(60){self.stall("waiting for workers to park");}}} - fn wait_done(&self,n:usize){self.state(self.n,-12);let mut spins=0u32;let mut seen=0;let mut t=Instant::now();loop{let d=self.done.0.load(Ordering::Acquire);if d>=n as u32{return;}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue;}if spins==1024||d!=seen{t=Instant::now();seen=d;}else if t.elapsed()>Duration::from_secs(60){self.stall("waiting for jobs to finish");}}} +const _: () = assert!(std::mem::offset_of!(Split, hq) % 4 == 0); +#[repr(C, align(64))] +struct SingleSplit { + ff: [f32; FF], + a2: PlanarActivation, } -#[derive(Clone,Debug)]pub struct Diagnostic{pub epoch:u32,pub batch_epoch:u32,pub claimed:u16,pub jobs:u16,pub done:u32,pub parked:u32,pub sleeping:u32,pub mode:u32,pub workers:Vec,pub host:i32,pub host_for_ms:i64} -pub struct ExpertPool{shared:Arc,threads:Vec>,pub topology:CpuTopology,pub affinity:PoolAffinity,pub host_works:bool,pub ms_multi_gu:f64,pub ms_multi_q:f64,pub ms_multi_down:f64,pub multi_bytes:u64,phase:[f64;3]} -impl ExpertPool{ - pub fn new(workers:i32,pin:bool,host_works:bool,affinity:PoolAffinity)->Result{if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);}let topology=super::rust_topology::detect_cpu_topology(true,affinity);let n=if workers>0{workers as usize}else if topology.is_hybrid&&affinity!=PoolAffinity::All{topology.p_cores.saturating_sub(1).max(1)}else{topology.worker_cores.len().max(1)};if n.checked_add(1).and_then(|v|v.checked_mul(3)).is_none_or(|v|v>65535){return Err(Error::Shape);}let spin=std::env::var("STRATA_POOL_SPIN_US").map(|s|Duration::from_micros(super::rust_simd::atoi(&s).max(0)as u64)).unwrap_or(Duration::from_millis(20));let mut jobs=Vec::new();jobs.try_reserve_exact(96).map_err(|_|Error::Allocation)?;let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs,format:None,mode:0,rows:0,tasks:1,parts:1}),split:cells::(96)?,scratch:cells::(n+1)?,single:cells::(16)?,states:alloc_with(n,||AtomicI32::new(-1))?,host:AtomicI32::new(-10),host_ms:AtomicI64::new(now_ms())});let mut pool=Self{shared,threads:Vec::new(),topology,affinity,host_works,ms_multi_gu:0.0,ms_multi_q:0.0,ms_multi_down:0.0,multi_bytes:0,phase:[0.0;3]};pool.threads.try_reserve_exact(n).map_err(|_|Error::Allocation)?;for i in 0..n{let s=Arc::clone(&pool.shared);let core=if pin{pool.topology.worker_cores.get(i).copied().unwrap_or(-1)}else{-1};pool.threads.push(thread::Builder::new().name(format!("strata-general-expert-{i}")).spawn(move||{if std::panic::catch_unwind(std::panic::AssertUnwindSafe(||s.worker(i,core))).is_err(){std::process::abort();}}).map_err(|_|Error::Allocation)?);}Ok(pool)} - pub fn workers(&self)->usize{self.shared.n} - pub fn owned_bytes(&self)->Result{let s=&self.shared;let b=/* SAFETY: &self excludes the &mut self phase methods, so the host is not writing `batch`; workers only read it. */unsafe{&*s.batch.get()};let terms=[(s.split.capacity(),std::mem::size_of::>()),(s.scratch.capacity(),std::mem::size_of::>()),(s.single.capacity(),std::mem::size_of::>()),(s.states.capacity(),std::mem::size_of::()),(b.jobs.capacity(),std::mem::size_of::()),(self.threads.capacity(),std::mem::size_of::>()),(self.topology.worker_cores.capacity(),std::mem::size_of::())];let mut bytes=std::mem::size_of::().checked_add(std::mem::size_of::()).ok_or(Error::Shape)?;for (n,size)in terms{bytes=bytes.checked_add(n.checked_mul(size).ok_or(Error::Shape)?).ok_or(Error::Shape)?;}Ok(bytes)}pub fn pauses(&self)->i64{0}pub fn phase_ms(&self)->[f64;3]{self.phase} - pub fn diagnostic(&self)->Diagnostic{let s=&self.shared;let h=s.head.0.load(Ordering::SeqCst);Diagnostic{epoch:s.epoch.0.load(Ordering::SeqCst),batch_epoch:(h>>32)as u32,claimed:(h&65535)as u16,jobs:((h>>16)&65535)as u16,done:s.done.0.load(Ordering::SeqCst),parked:s.parked.0.load(Ordering::SeqCst),sleeping:s.sleepers.0.load(Ordering::SeqCst),mode:/* SAFETY: as owned_bytes: a plain read of `mode` while the host cannot hold &mut self; workers never write it. */unsafe{(*s.batch.get()).mode},workers:s.states.iter().map(|s|s.load(Ordering::SeqCst)).collect(),host:s.host.load(Ordering::SeqCst),host_for_ms:now_ms()-s.host_ms.load(Ordering::SeqCst)}} - fn phase(&mut self,mode:u32,tasks:usize,rows:usize,parts:usize){self.shared.wait_parked();/* SAFETY: all workers parked => host is the only accessor of `batch` until the Release store of `head`. */unsafe{let b=&mut*self.shared.batch.get();b.mode=mode;b.tasks=tasks;b.rows=rows;b.parts=parts;}self.shared.done.0.store(0,Ordering::Relaxed);let e=self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);self.shared.head.0.store(((e as u64)<<32)|((tasks as u64)<<16),Ordering::Release);self.shared.publish();if self.host_works{self.shared.drain(e,self.shared.n);}self.shared.wait_done(tasks);self.shared.wait_parked();self.shared.state(self.shared.n,-10);} - fn load(&mut self,jobs:&[Job],format:Option)->Result<()>{self.shared.wait_parked();/* SAFETY: all workers parked => exclusive access to `batch`. */unsafe{let b=&mut*self.shared.batch.get();b.jobs.clear();b.jobs.try_reserve(jobs.len()).map_err(|_|Error::Allocation)?;b.jobs.extend_from_slice(jobs);b.format=format;}Ok(())} - fn clear(&mut self){/* SAFETY: only called after the phase barriers (workers parked) or before any publication. */unsafe{let b=&mut*self.shared.batch.get();b.jobs.clear();b.format=None;b.mode=0;}} - fn whole(&mut self,jobs:&[Job])->Result<()>{if jobs.is_empty(){return Ok(());}if jobs.len()>65535{return Err(Error::Shape);}let a=Instant::now();self.load(jobs,None)?;if self.shared.n==1{for i in 0..jobs.len(){/* SAFETY: n==1 and load() saw the lone worker parked; nothing is published here, so it stays parked and scratch[0] is host-only. mode is 0 (clear() after every operation). */unsafe{self.shared.execute(i,0);}}}else{let b=Instant::now();/* SAFETY: load() above waited for all workers to park. */unsafe{let batch=&mut*self.shared.batch.get();batch.mode=0;batch.tasks=jobs.len();}self.shared.done.0.store(0,Ordering::Relaxed);let epoch=self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);self.shared.head.0.store(((epoch as u64)<<32)|((jobs.len()as u64)<<16),Ordering::Release);self.shared.publish();if self.host_works{self.shared.drain(epoch,self.shared.n);}self.shared.wait_done(jobs.len());let c=Instant::now();self.shared.wait_parked();self.shared.state(self.shared.n,-10);let d=Instant::now();self.phase[0]+=(b-a).as_secs_f64()*1000.0;self.phase[1]+=(c-b).as_secs_f64()*1000.0;self.phase[2]+=(d-c).as_secs_f64()*1000.0;}self.clear();Ok(())} - pub fn run(&mut self,jobs:&mut[PlanarJob<'_>])->Result<()>{let mut headers=Vec::new();headers.try_reserve_exact(jobs.len()).map_err(|_|Error::Allocation)?;for j in jobs{if j.blob.len()!=super::rust_legacy::BLOB||j.output.len()!=H||j.activation.0.nchunks!=80||!super::rust_legacy::legacy_supported(){return Err(Error::Shape);}let mut h=Job{blob:j.blob.as_ptr(),len:j.blob.len(),nt:1,..Job::default()};h.a[0]=j.activation;h.out[0]=j.output.as_mut_ptr();headers.push(h);}self.whole(&headers)} - pub fn run_split(&mut self,jobs:&mut[PlanarJob<'_>])->Result<()>{if jobs.is_empty(){return Ok(());}if jobs.len()>16||self.shared.n==1||super::rust_legacy::oracle_q8_zero_enabled(){return self.run(jobs);}let t=Instant::now();let mut headers=[Job::default();16];for (i,j) in jobs.iter_mut().enumerate(){if j.blob.len()!=super::rust_legacy::BLOB||j.output.len()!=H||j.activation.0.nchunks!=80||!super::rust_legacy::legacy_supported(){return Err(Error::Shape);}headers[i].blob=j.blob.as_ptr();headers[i].len=j.blob.len();headers[i].nt=1;headers[i].a[0]=j.activation;headers[i].out[0]=j.output.as_mut_ptr();}let n=jobs.len();self.load(&headers[..n],None)?;let parts=(3*(self.shared.n+usize::from(self.host_works))).div_ceil(n).max(1);if n.checked_mul(parts).is_none_or(|v|v>65535){self.clear();return Err(Error::Shape);}self.phase(1,n*parts,n*FF,parts);/* SAFETY: phase() returned => done AND parked; e < n <= 16 = single.len(). */unsafe{for e in 0..n{let s=&mut*self.shared.single[e].get();if let Err(error)=s.a2.quantize(&s.ff){self.clear();return Err(error);}}}self.phase(2,n*parts,n*H,parts);self.clear();self.phase[1]+=t.elapsed().as_secs_f64()*1000.0;Ok(())} - fn split_headers(&mut self,jobs:&[Job])->Result<()>{if jobs.is_empty(){return Ok(());}if jobs.len()>16||self.shared.n==1||super::rust_legacy::oracle_q8_zero_enabled(){return self.whole(jobs);}let t=Instant::now();self.load(jobs,None)?;let parts=(3*(self.shared.n+usize::from(self.host_works))).div_ceil(jobs.len()).max(1);if jobs.len().checked_mul(parts).is_none_or(|v|v>65535){self.clear();return Err(Error::Shape);}self.phase(1,jobs.len()*parts,jobs.len()*FF,parts);/* SAFETY: phase() returned => done AND parked; jobs.len() <= 16 = single.len(). */unsafe{for e in 0..jobs.len(){let z=&mut*self.shared.single[e].get();if let Err(error)=z.a2.quantize(&z.ff){self.clear();return Err(error);}}}self.phase(2,jobs.len()*parts,jobs.len()*H,parts);self.clear();self.phase[1]+=t.elapsed().as_secs_f64()*1000.0;Ok(())} - pub fn run_split_multi(&mut self,jobs:&mut[PlanarJobMulti<'_>])->Result<()>{if jobs.is_empty(){return Ok(());}let mut all=Vec::new();all.try_reserve_exact(jobs.len()).map_err(|_|Error::Allocation)?;for j in jobs{if j.blob.len()!=super::rust_legacy::BLOB||j.activation.is_empty()||j.activation.len()>8||j.activation.len()!=j.output.len()||j.output.iter().any(|o|o.len()!=H)||j.activation.iter().any(|a|a.0.nchunks!=80)||!super::rust_legacy::legacy_supported(){return Err(Error::Shape);}let mut h=Job{blob:j.blob.as_ptr(),len:j.blob.len(),nt:j.activation.len(),..Job::default()};for t in 0..h.nt{h.a[t]=j.activation[t];h.out[t]=j.output[t].as_mut_ptr();}all.push(h);}if all.len()>96||super::rust_legacy::oracle_q8_zero_enabled(){let mut singles=Vec::new();singles.try_reserve_exact(all.len().checked_mul(8).ok_or(Error::Shape)?).map_err(|_|Error::Allocation)?;for j in all{for t in 0..j.nt{let mut h=j;h.nt=1;h.a[0]=j.a[t];h.out[0]=j.out[t];singles.push(h);}}for c in singles.chunks(16){self.split_headers(c)?;}return Ok(());}self.multi(&all,None)} - pub fn run_split_multi_native(&mut self,f:&NativeFormat,jobs:&mut[NativeJobMulti<'_>])->Result<()>{f.validate()?;if f.n_embd!=H||f.n_ff!=FF{return Err(Error::Shape);}let mut all=Vec::new();all.try_reserve_exact(jobs.len()).map_err(|_|Error::Allocation)?;for j in jobs{let n=j.output.len();if j.blob.len()!=f.bytes||n==0||n>8||j.output.iter().any(|v|v.len()!=H){return Err(Error::Shape);}let q2=f.gu.original_id()==42;if (q2&&j.planar.len()!=n)||(!q2&&j.activation.len()!=n){return Err(Error::Shape);}let mut h=Job{blob:j.blob.as_ptr(),len:j.blob.len(),nt:n,..Job::default()};for t in 0..n{if q2{if j.planar[t].0.nchunks!=80{return Err(Error::Shape);}h.a[t]=j.planar[t];}else{j.activation[t].check(f.gu,H)?;h.na[t]=j.activation[t];}h.out[t]=j.output[t].as_mut_ptr();}all.push(h);}let elapsed=Instant::now();let before=self.phase[1];for c in all.chunks(96){self.multi(c,Some(f.clone()))?;}self.phase[1]=before+elapsed.elapsed().as_secs_f64()*1000.0;Ok(())} - fn multi(&mut self,jobs:&[Job],fmt:Option)->Result<()>{let outer=Instant::now();let n=jobs.len();if n==0{return Ok(());}self.load(jobs,fmt.clone())?;let t0=if fmt.is_some(){Instant::now()}else{outer};let tasks=3*(self.shared.n+usize::from(self.host_works));self.phase(if fmt.is_some(){5}else{3},tasks,n*FF,1);let t1=Instant::now();/* SAFETY: phase() returned => done AND parked; n <= 96 = split.len(); nt <= 8 (validated by the run_split_multi* callers). */unsafe{for e in 0..n{let s=&mut*self.shared.split[e].get();for t in 0..jobs[e].nt{if let Some(f)=&fmt{if f.down.original_id()==42{let a=&mut s.a2[t].0;if super::rust_simd::dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],a);}else{super::rust_quant::q8_one_avx2(&s.ff[t],a);}}else{super::rust_ggml::quantize_raw(f.down,&s.ff[t],&mut s.hq[t]);}}else{if let Err(error)=s.a2[t].quantize(&s.ff[t]){self.clear();return Err(error);}}}}}let t2=Instant::now();self.phase(if fmt.is_some(){6}else{4},tasks,n*H,1);let t3=Instant::now();self.ms_multi_gu+=(t1-t0).as_secs_f64()*1000.0;self.ms_multi_q+=(t2-t1).as_secs_f64()*1000.0;self.ms_multi_down+=(t3-t2).as_secs_f64()*1000.0;let next_bytes=self.multi_bytes.checked_add((n as u64)*(fmt.as_ref().map_or(super::rust_legacy::BLOB,|f|f.bytes)as u64));self.clear();self.multi_bytes=next_bytes.ok_or(Error::Shape)?;self.phase[1]+=(t3-t0).as_secs_f64()*1000.0;Ok(())} +struct Batch { + jobs: Vec, + format: Option, + mode: u32, + rows: usize, + tasks: usize, + parts: usize, } -impl Drop for ExpertPool{fn drop(&mut self){self.shared.stop.0.store(true,Ordering::Release);self.shared.publish();for t in self.threads.drain(..){let _=t.join();}}} +struct Shared { + head: Line, + done: Line, + parked: Line, + epoch: Line, + stop: Line, + sleepers: Line, + sleep_mu: Mutex<()>, + sleep_cv: Condvar, + spin: Duration, + n: usize, + batch: UnsafeCell, + split: Vec>, + scratch: Vec>, + single: Vec>, + states: Vec, + host: AtomicI32, + host_ms: AtomicI64, +} +static RELEASE_GPU_WAITS: OnceLock = OnceLock::new(); +#[derive(Clone, Debug)] +pub struct Diagnostic { + pub epoch: u32, + pub batch_epoch: u32, + pub claimed: u16, + pub jobs: u16, + pub done: u32, + pub parked: u32, + pub sleeping: u32, + pub mode: u32, + pub workers: Vec, + pub host: i32, + pub host_for_ms: i64, +} +pub struct ExpertPool { + shared: Arc, + threads: Vec>, + pub topology: CpuTopology, + pub affinity: PoolAffinity, + pub host_works: bool, + pub ms_multi_gu: f64, + pub ms_multi_q: f64, + pub ms_multi_down: f64, + pub multi_bytes: u64, + phase: [f64; 3], +} + +mod impl_default_for_job; +#[allow(unused_imports)] +use impl_default_for_job::alloc_with; +#[allow(unused_imports)] +use impl_default_for_job::cells; +#[allow(unused_imports)] +pub use impl_default_for_job::install_release_gpu_waits; +#[allow(unused_imports)] +use impl_default_for_job::now_ms; +mod impl_expertpool; +mod impl_expertpool_2; +mod impl_shared; +mod impl_shared_2; diff --git a/crates/native-cpu-expert/src/rust_general_pool/impl_default_for_job.rs b/crates/native-cpu-expert/src/rust_general_pool/impl_default_for_job.rs new file mode 100644 index 00000000..2fa25682 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_general_pool/impl_default_for_job.rs @@ -0,0 +1,51 @@ +//! Moved out of the parent module by STRA-338: impl Default_for_Job, impl Default_for_Split, impl Default_for_SingleSplit, impl Sync_for_Shared, impl Send_for_Shared, fn alloc_with .... + +#[allow(unused_imports)] +use super::*; + +impl Default for Job { + fn default() -> Self { + Self { + blob: std::ptr::null(), + len: 0, + nt: 0, + a: [std::ptr::null(); 8], + na: [std::ptr::null(); 8], + out: [std::ptr::null_mut(); 8], + } + } +} +impl Default for Split { + fn default() -> Self { + Self { ff: [[0.0; FF]; 8], a2: std::array::from_fn(|_| PlanarActivation::default()), hq: [[0; 1024]; 8] } + } +} +impl Default for SingleSplit { + fn default() -> Self { + Self { ff: [0.0; FF], a2: PlanarActivation::default() } + } +} +// SAFETY: immutable batch publication is release/acquire. Tagged CAS grants one +// disjoint row interval or whole expert. Scratch index belongs to worker/host. +// Host mutation occurs only after both completion and all worker park barriers. +// `batch.jobs` holds raw pointers into CALLER memory; they are cleared (`clear`) or dead before every return, and a +// worker panic is turned into abort (catch_unwind in `new`). The host-thread drain is NOT unwind-guarded here: a host +// panic inside `execute` would leave workers writing caller memory, which is why every extent is validated first. +unsafe impl Sync for Shared {} +unsafe impl Send for Shared {} +pub(super) fn alloc_with(n: usize, make: impl FnMut() -> T) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize_with(n, make); + Ok(v) +} +pub(super) fn cells(n: usize) -> Result>> { + alloc_with(n, || UnsafeCell::new(T::default())) +} +pub fn install_release_gpu_waits(callback: fn()) -> Result<()> { + RELEASE_GPU_WAITS.set(callback).map_err(|_| Error::Shape) +} +pub(super) fn now_ms() -> i64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_millis().min(i64::MAX as u128) as i64 +} diff --git a/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool.rs b/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool.rs new file mode 100644 index 00000000..341966c2 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool.rs @@ -0,0 +1,254 @@ +//! Moved out of the parent module by STRA-338: impl ExpertPool. + +#[allow(unused_imports)] +use super::*; + +impl ExpertPool { + pub fn new(workers: i32, pin: bool, host_works: bool, affinity: PoolAffinity) -> Result { + if !super::super::rust_simd::avx2_ok() + || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok() + { + return Err(Error::Unsupported); + } + let topology = super::super::rust_topology::detect_cpu_topology(true, affinity); + let n = if workers > 0 { + workers as usize + } else if topology.is_hybrid && affinity != PoolAffinity::All { + topology.p_cores.saturating_sub(1).max(1) + } else { + topology.worker_cores.len().max(1) + }; + if n.checked_add(1).and_then(|v| v.checked_mul(3)).is_none_or(|v| v > 65535) { + return Err(Error::Shape); + } + let spin = std::env::var("STRATA_POOL_SPIN_US") + .map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64)) + .unwrap_or(Duration::from_millis(20)); + let mut jobs = Vec::new(); + jobs.try_reserve_exact(96).map_err(|_| Error::Allocation)?; + let shared = Arc::new(Shared { + head: Line(AtomicU64::new(0)), + done: Line(AtomicU32::new(0)), + parked: Line(AtomicU32::new(0)), + epoch: Line(AtomicU32::new(0)), + stop: Line(AtomicBool::new(false)), + sleepers: Line(AtomicU32::new(0)), + sleep_mu: Mutex::new(()), + sleep_cv: Condvar::new(), + spin, + n, + batch: UnsafeCell::new(Batch { jobs, format: None, mode: 0, rows: 0, tasks: 1, parts: 1 }), + split: cells::(96)?, + scratch: cells::(n + 1)?, + single: cells::(16)?, + states: alloc_with(n, || AtomicI32::new(-1))?, + host: AtomicI32::new(-10), + host_ms: AtomicI64::new(now_ms()), + }); + let mut pool = Self { + shared, + threads: Vec::new(), + topology, + affinity, + host_works, + ms_multi_gu: 0.0, + ms_multi_q: 0.0, + ms_multi_down: 0.0, + multi_bytes: 0, + phase: [0.0; 3], + }; + pool.threads.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + for i in 0..n { + let s = Arc::clone(&pool.shared); + let core = if pin { pool.topology.worker_cores.get(i).copied().unwrap_or(-1) } else { -1 }; + pool.threads.push( + thread::Builder::new() + .name(format!("strata-general-expert-{i}")) + .spawn(move || { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.worker(i, core))).is_err() { + std::process::abort(); + } + }) + .map_err(|_| Error::Allocation)?, + ); + } + Ok(pool) + } + pub fn workers(&self) -> usize { + self.shared.n + } + pub fn owned_bytes(&self) -> Result { + let s = &self.shared; + let b=/* SAFETY: &self excludes the &mut self phase methods, so the host is not writing `batch`; workers only read it. */unsafe{&*s.batch.get()}; + let terms = [ + (s.split.capacity(), std::mem::size_of::>()), + (s.scratch.capacity(), std::mem::size_of::>()), + (s.single.capacity(), std::mem::size_of::>()), + (s.states.capacity(), std::mem::size_of::()), + (b.jobs.capacity(), std::mem::size_of::()), + (self.threads.capacity(), std::mem::size_of::>()), + (self.topology.worker_cores.capacity(), std::mem::size_of::()), + ]; + let mut bytes = std::mem::size_of::().checked_add(std::mem::size_of::()).ok_or(Error::Shape)?; + for (n, size) in terms { + bytes = bytes.checked_add(n.checked_mul(size).ok_or(Error::Shape)?).ok_or(Error::Shape)?; + } + Ok(bytes) + } + pub fn pauses(&self) -> i64 { + 0 + } + pub fn phase_ms(&self) -> [f64; 3] { + self.phase + } + pub fn diagnostic(&self) -> Diagnostic { + let s = &self.shared; + let h = s.head.0.load(Ordering::SeqCst); + Diagnostic{epoch:s.epoch.0.load(Ordering::SeqCst),batch_epoch:(h>>32)as u32,claimed:(h&65535)as u16,jobs:((h>>16)&65535)as u16,done:s.done.0.load(Ordering::SeqCst),parked:s.parked.0.load(Ordering::SeqCst),sleeping:s.sleepers.0.load(Ordering::SeqCst),mode:/* SAFETY: as owned_bytes: a plain read of `mode` while the host cannot hold &mut self; workers never write it. */unsafe{(*s.batch.get()).mode},workers:s.states.iter().map(|s|s.load(Ordering::SeqCst)).collect(),host:s.host.load(Ordering::SeqCst),host_for_ms:now_ms()-s.host_ms.load(Ordering::SeqCst)} + } + pub(super) fn phase(&mut self, mode: u32, tasks: usize, rows: usize, parts: usize) { + self.shared.wait_parked(); /* SAFETY: all workers parked => host is the only accessor of `batch` until the Release store of `head`. */ + unsafe { + let b = &mut *self.shared.batch.get(); + b.mode = mode; + b.tasks = tasks; + b.rows = rows; + b.parts = parts; + } + self.shared.done.0.store(0, Ordering::Relaxed); + let e = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1); + self.shared.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release); + self.shared.publish(); + if self.host_works { + self.shared.drain(e, self.shared.n); + } + self.shared.wait_done(tasks); + self.shared.wait_parked(); + self.shared.state(self.shared.n, -10); + } + pub(super) fn load(&mut self, jobs: &[Job], format: Option) -> Result<()> { + self.shared.wait_parked(); /* SAFETY: all workers parked => exclusive access to `batch`. */ + unsafe { + let b = &mut *self.shared.batch.get(); + b.jobs.clear(); + b.jobs.try_reserve(jobs.len()).map_err(|_| Error::Allocation)?; + b.jobs.extend_from_slice(jobs); + b.format = format; + } + Ok(()) + } + pub(super) fn clear(&mut self) { + /* SAFETY: only called after the phase barriers (workers parked) or before any publication. */ + unsafe { + let b = &mut *self.shared.batch.get(); + b.jobs.clear(); + b.format = None; + b.mode = 0; + } + } + pub(super) fn whole(&mut self, jobs: &[Job]) -> Result<()> { + if jobs.is_empty() { + return Ok(()); + } + if jobs.len() > 65535 { + return Err(Error::Shape); + } + let a = Instant::now(); + self.load(jobs, None)?; + if self.shared.n == 1 { + for i in 0..jobs.len() { + /* SAFETY: n==1 and load() saw the lone worker parked; nothing is published here, so it stays parked and scratch[0] is host-only. mode is 0 (clear() after every operation). */ + unsafe { + self.shared.execute(i, 0); + } + } + } else { + let b = Instant::now(); /* SAFETY: load() above waited for all workers to park. */ + unsafe { + let batch = &mut *self.shared.batch.get(); + batch.mode = 0; + batch.tasks = jobs.len(); + } + self.shared.done.0.store(0, Ordering::Relaxed); + let epoch = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1); + self.shared.head.0.store(((epoch as u64) << 32) | ((jobs.len() as u64) << 16), Ordering::Release); + self.shared.publish(); + if self.host_works { + self.shared.drain(epoch, self.shared.n); + } + self.shared.wait_done(jobs.len()); + let c = Instant::now(); + self.shared.wait_parked(); + self.shared.state(self.shared.n, -10); + let d = Instant::now(); + self.phase[0] += (b - a).as_secs_f64() * 1000.0; + self.phase[1] += (c - b).as_secs_f64() * 1000.0; + self.phase[2] += (d - c).as_secs_f64() * 1000.0; + } + self.clear(); + Ok(()) + } + pub fn run(&mut self, jobs: &mut [PlanarJob<'_>]) -> Result<()> { + let mut headers = Vec::new(); + headers.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + for j in jobs { + if j.blob.len() != super::super::rust_legacy::BLOB + || j.output.len() != H + || j.activation.0.nchunks != 80 + || !super::super::rust_legacy::legacy_supported() + { + return Err(Error::Shape); + } + let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: 1, ..Job::default() }; + h.a[0] = j.activation; + h.out[0] = j.output.as_mut_ptr(); + headers.push(h); + } + self.whole(&headers) + } + pub fn run_split(&mut self, jobs: &mut [PlanarJob<'_>]) -> Result<()> { + if jobs.is_empty() { + return Ok(()); + } + if jobs.len() > 16 || self.shared.n == 1 || super::super::rust_legacy::oracle_q8_zero_enabled() { + return self.run(jobs); + } + let t = Instant::now(); + let mut headers = [Job::default(); 16]; + for (i, j) in jobs.iter_mut().enumerate() { + if j.blob.len() != super::super::rust_legacy::BLOB + || j.output.len() != H + || j.activation.0.nchunks != 80 + || !super::super::rust_legacy::legacy_supported() + { + return Err(Error::Shape); + } + headers[i].blob = j.blob.as_ptr(); + headers[i].len = j.blob.len(); + headers[i].nt = 1; + headers[i].a[0] = j.activation; + headers[i].out[0] = j.output.as_mut_ptr(); + } + let n = jobs.len(); + self.load(&headers[..n], None)?; + let parts = (3 * (self.shared.n + usize::from(self.host_works))).div_ceil(n).max(1); + if n.checked_mul(parts).is_none_or(|v| v > 65535) { + self.clear(); + return Err(Error::Shape); + } + self.phase(1, n * parts, n * FF, parts); /* SAFETY: phase() returned => done AND parked; e < n <= 16 = single.len(). */ + unsafe { + for e in 0..n { + let s = &mut *self.shared.single[e].get(); + if let Err(error) = s.a2.quantize(&s.ff) { + self.clear(); + return Err(error); + } + } + } + self.phase(2, n * parts, n * H, parts); + self.clear(); + self.phase[1] += t.elapsed().as_secs_f64() * 1000.0; + Ok(()) + } +} diff --git a/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool_2.rs b/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool_2.rs new file mode 100644 index 00000000..bcc3fc0b --- /dev/null +++ b/crates/native-cpu-expert/src/rust_general_pool/impl_expertpool_2.rs @@ -0,0 +1,176 @@ +//! Moved out of the parent module by STRA-338: impl ExpertPool (2), impl Drop_for_ExpertPool. + +#[allow(unused_imports)] +use super::*; + +impl ExpertPool { + pub(super) fn split_headers(&mut self, jobs: &[Job]) -> Result<()> { + if jobs.is_empty() { + return Ok(()); + } + if jobs.len() > 16 || self.shared.n == 1 || super::super::rust_legacy::oracle_q8_zero_enabled() { + return self.whole(jobs); + } + let t = Instant::now(); + self.load(jobs, None)?; + let parts = (3 * (self.shared.n + usize::from(self.host_works))).div_ceil(jobs.len()).max(1); + if jobs.len().checked_mul(parts).is_none_or(|v| v > 65535) { + self.clear(); + return Err(Error::Shape); + } + self.phase(1, jobs.len() * parts, jobs.len() * FF, parts); /* SAFETY: phase() returned => done AND parked; jobs.len() <= 16 = single.len(). */ + unsafe { + for e in 0..jobs.len() { + let z = &mut *self.shared.single[e].get(); + if let Err(error) = z.a2.quantize(&z.ff) { + self.clear(); + return Err(error); + } + } + } + self.phase(2, jobs.len() * parts, jobs.len() * H, parts); + self.clear(); + self.phase[1] += t.elapsed().as_secs_f64() * 1000.0; + Ok(()) + } + pub fn run_split_multi(&mut self, jobs: &mut [PlanarJobMulti<'_>]) -> Result<()> { + if jobs.is_empty() { + return Ok(()); + } + let mut all = Vec::new(); + all.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + for j in jobs { + if j.blob.len() != super::super::rust_legacy::BLOB + || j.activation.is_empty() + || j.activation.len() > 8 + || j.activation.len() != j.output.len() + || j.output.iter().any(|o| o.len() != H) + || j.activation.iter().any(|a| a.0.nchunks != 80) + || !super::super::rust_legacy::legacy_supported() + { + return Err(Error::Shape); + } + let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: j.activation.len(), ..Job::default() }; + for t in 0..h.nt { + h.a[t] = j.activation[t]; + h.out[t] = j.output[t].as_mut_ptr(); + } + all.push(h); + } + if all.len() > 96 || super::super::rust_legacy::oracle_q8_zero_enabled() { + let mut singles = Vec::new(); + singles.try_reserve_exact(all.len().checked_mul(8).ok_or(Error::Shape)?).map_err(|_| Error::Allocation)?; + for j in all { + for t in 0..j.nt { + let mut h = j; + h.nt = 1; + h.a[0] = j.a[t]; + h.out[0] = j.out[t]; + singles.push(h); + } + } + for c in singles.chunks(16) { + self.split_headers(c)?; + } + return Ok(()); + } + self.multi(&all, None) + } + pub fn run_split_multi_native(&mut self, f: &NativeFormat, jobs: &mut [NativeJobMulti<'_>]) -> Result<()> { + f.validate()?; + if f.n_embd != H || f.n_ff != FF { + return Err(Error::Shape); + } + let mut all = Vec::new(); + all.try_reserve_exact(jobs.len()).map_err(|_| Error::Allocation)?; + for j in jobs { + let n = j.output.len(); + if j.blob.len() != f.bytes || n == 0 || n > 8 || j.output.iter().any(|v| v.len() != H) { + return Err(Error::Shape); + } + let q2 = f.gu.original_id() == 42; + if (q2 && j.planar.len() != n) || (!q2 && j.activation.len() != n) { + return Err(Error::Shape); + } + let mut h = Job { blob: j.blob.as_ptr(), len: j.blob.len(), nt: n, ..Job::default() }; + for t in 0..n { + if q2 { + if j.planar[t].0.nchunks != 80 { + return Err(Error::Shape); + } + h.a[t] = j.planar[t]; + } else { + j.activation[t].check(f.gu, H)?; + h.na[t] = j.activation[t]; + } + h.out[t] = j.output[t].as_mut_ptr(); + } + all.push(h); + } + let elapsed = Instant::now(); + let before = self.phase[1]; + for c in all.chunks(96) { + self.multi(c, Some(f.clone()))?; + } + self.phase[1] = before + elapsed.elapsed().as_secs_f64() * 1000.0; + Ok(()) + } + pub(super) fn multi(&mut self, jobs: &[Job], fmt: Option) -> Result<()> { + let outer = Instant::now(); + let n = jobs.len(); + if n == 0 { + return Ok(()); + } + self.load(jobs, fmt.clone())?; + let t0 = if fmt.is_some() { Instant::now() } else { outer }; + let tasks = 3 * (self.shared.n + usize::from(self.host_works)); + self.phase(if fmt.is_some() { 5 } else { 3 }, tasks, n * FF, 1); + let t1 = Instant::now(); /* SAFETY: phase() returned => done AND parked; n <= 96 = split.len(); nt <= 8 (validated by the run_split_multi* callers). */ + unsafe { + for e in 0..n { + let s = &mut *self.shared.split[e].get(); + for t in 0..jobs[e].nt { + if let Some(f) = &fmt { + if f.down.original_id() == 42 { + let a = &mut s.a2[t].0; + if super::super::rust_simd::dispatch().avx512 { + super::super::rust_quant::q8_one_avx512(&s.ff[t], a); + } else { + super::super::rust_quant::q8_one_avx2(&s.ff[t], a); + } + } else { + super::super::rust_ggml::quantize_raw(f.down, &s.ff[t], &mut s.hq[t]); + } + } else { + if let Err(error) = s.a2[t].quantize(&s.ff[t]) { + self.clear(); + return Err(error); + } + } + } + } + } + let t2 = Instant::now(); + self.phase(if fmt.is_some() { 6 } else { 4 }, tasks, n * H, 1); + let t3 = Instant::now(); + self.ms_multi_gu += (t1 - t0).as_secs_f64() * 1000.0; + self.ms_multi_q += (t2 - t1).as_secs_f64() * 1000.0; + self.ms_multi_down += (t3 - t2).as_secs_f64() * 1000.0; + let next_bytes = self + .multi_bytes + .checked_add((n as u64) * (fmt.as_ref().map_or(super::super::rust_legacy::BLOB, |f| f.bytes) as u64)); + self.clear(); + self.multi_bytes = next_bytes.ok_or(Error::Shape)?; + self.phase[1] += (t3 - t0).as_secs_f64() * 1000.0; + Ok(()) + } +} +impl Drop for ExpertPool { + fn drop(&mut self) { + self.shared.stop.0.store(true, Ordering::Release); + self.shared.publish(); + for t in self.threads.drain(..) { + let _ = t.join(); + } + } +} diff --git a/crates/native-cpu-expert/src/rust_general_pool/impl_shared.rs b/crates/native-cpu-expert/src/rust_general_pool/impl_shared.rs new file mode 100644 index 00000000..8e1d07e5 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_general_pool/impl_shared.rs @@ -0,0 +1,242 @@ +//! Moved out of the parent module by STRA-338: impl Shared. + +#[allow(unused_imports)] +use super::*; + +impl Shared { + pub(super) fn publish(&self) { + self.epoch.0.fetch_add(1, Ordering::SeqCst); + if self.sleepers.0.load(Ordering::SeqCst) != 0 { + let _lk = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner()); + self.sleep_cv.notify_all(); + } + } + pub(super) fn claim(&self, e: u32) -> Option { + let mut h = self.head.0.load(Ordering::Acquire); + loop { + if (h >> 32) as u32 != e { + return None; + } + if h & 0xffff >= (h >> 16) & 0xffff { + return None; + } + match self.head.0.compare_exchange_weak(h, h + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return Some((h & 0xffff) as usize), + Err(next) => h = next, + } + } + } + pub(super) fn state(&self, id: usize, s: i32) { + if id < self.n { + self.states[id].store(s, Ordering::Relaxed); + } else { + self.host.store(s, Ordering::Relaxed); + self.host_ms.store(now_ms(), Ordering::Relaxed); + } + } + pub(super) fn drain(&self, e: u32, id: usize) { + while let Some(i) = self.claim(e) { + self.state(id, i as i32); /* SAFETY: claim(e) granted exclusive task `i` of the published epoch; `id` is this thread's own scratch index (worker index, or `n` for the host). */ + unsafe { + self.execute(i, id); + } + self.done.0.fetch_add(1, Ordering::Release); + } + } + /// # Safety + /// The caller holds a successful epoch-tagged claim of task `i` (or is the host running the single-worker path with all + /// workers parked) and `id` is its exclusive scratch index. `batch.jobs[..]` pointers are live until the done+parked + /// barriers. Modes 1/2 are only reached with `nt == 1` jobs; modes 0/3..6 bound `nt <= 8` and rows by FF/H. + pub(super) unsafe fn execute(&self, i: usize, id: usize) { + unsafe { + let b = &*self.batch.get(); + if b.mode == 0 { + let j = b.jobs[i]; + let a = &*j.a[0]; + let out = std::slice::from_raw_parts_mut(j.out[0], H); + super::super::rust_legacy::whole_single( + std::slice::from_raw_parts(j.blob, j.len), + a, + out, + &mut *self.scratch[id].get(), + ); + return; + } + let per = if b.mode == 1 || b.mode == 3 || b.mode == 5 { FF } else { H }; + let (mut at, end) = if b.mode <= 2 { + let e = i / b.parts; + let p = i % b.parts; + (e * per + per * p / b.parts, e * per + per * (p + 1) / b.parts) + } else { + (b.rows * i / b.tasks, b.rows * (i + 1) / b.tasks) + }; + while at < end { + let e = at / per; + let r0 = at % per; + let r1 = per.min(r0 + end - at); + let j = b.jobs[e]; + let s = self.split[e].get(); + let (ff_ptr, a2_ptr) = if b.mode <= 2 { + let z = self.single[e].get(); + (std::ptr::addr_of_mut!((*z).ff).cast::(), std::ptr::addr_of!((*z).a2)) + } else { + ( + std::ptr::addr_of_mut!((*s).ff).cast::(), + std::ptr::addr_of!((*s).a2).cast::(), + ) + }; + let blob = std::slice::from_raw_parts(j.blob, j.len); + let n = j.nt; + if b.mode <= 4 { + let a0 = if b.mode == 1 || b.mode == 3 { j.a[0] } else { a2_ptr }; + let mut a = [&*a0; 8]; + for t in 0..n { + a[t] = if b.mode == 1 || b.mode == 3 { &*j.a[t] } else { &*a2_ptr.add(t) }; + } + if b.mode == 1 || b.mode == 3 { + super::super::rust_legacy::gate_each(blob, &a[..n], r0, r1, |t, r, v| { + ff_ptr.add(t * FF + r).write(v) + }); + } else { + super::super::rust_legacy::down_each(blob, &a[..n], r0, r1, |t, r, v| j.out[t].add(r).write(v)); + } + } else { + let f = b.format.as_ref().unwrap(); + let mut g = [0.0; 8]; + let mut u = g; + for r in r0..r1 { + let (kind, offset, stride, width) = + if b.mode == 5 { (f.gu, 0, f.gu_row, H) } else { (f.down, f.down_offset, f.down_row, FF) }; + let row = &blob[offset + r * stride..offset + (r + 1) * stride]; + if kind.original_id() == 42 { + let a0 = if b.mode == 5 { &(*j.a[0]).0 } else { &(*a2_ptr).0 }; + let mut a = [a0; 8]; + for t in 0..n { + a[t] = if b.mode == 5 { &(*j.a[t]).0 } else { &(*a2_ptr.add(t)).0 }; + } + if super::super::rust_simd::dispatch().avx512 { + super::super::rust_q2::dot512(row, &a[..n], &mut g[..n]); + } else { + super::super::rust_q2::dot256(row, &a[..n], &mut g[..n]); + } + if b.mode == 5 { + let ur = &blob[f.up_offset + r * stride..f.up_offset + (r + 1) * stride]; + if super::super::rust_simd::dispatch().avx512 { + super::super::rust_q2::dot512(ur, &a[..n], &mut u[..n]); + } else { + super::super::rust_q2::dot256(ur, &a[..n], &mut u[..n]); + } + } + } else if b.mode == 5 { + let mut a = [&*j.na[0]; 8]; + for t in 0..n { + a[t] = &*j.na[t]; + } + super::super::rust_native_general::group_dot( + kind, + row, + &a[..n], + &mut g[..n], + super::super::rust_simd::dispatch(), + true, + ); + let ur = &blob[f.up_offset + r * stride..f.up_offset + (r + 1) * stride]; + super::super::rust_native_general::group_dot( + kind, + ur, + &a[..n], + &mut u[..n], + super::super::rust_simd::dispatch(), + true, + ); + } else { + let base = std::ptr::addr_of!((*s).hq).cast::<[u8; 1024]>(); + let mut a: [&[u8]; 8] = [&[]; 8]; + for t in 0..n { + a[t] = &*base.add(t); + } + super::super::rust_native_general::group_dot_bytes( + kind, + row, + FF, + &a[..n], + &mut g[..n], + super::super::rust_simd::dispatch(), + false, + ); + } + debug_assert_eq!(width, if b.mode == 5 { H } else { FF }); + for t in 0..n { + if b.mode == 5 { + ff_ptr.add(t * FF + r).write(super::super::rust_simd::silu(g[t], u[t])); + } else { + j.out[t].add(r).write(g[t]); + } + } + } + } + at += r1 - r0; + } + } + } + pub(super) fn worker(&self, id: usize, core: i32) { + super::super::rust_platform::pin(core); + let mut seen = 0; + self.parked.0.fetch_add(1, Ordering::AcqRel); + loop { + let at = Instant::now(); + let mut spins = 0u32; + while self.epoch.0.load(Ordering::Acquire) == seen { + if self.stop.0.load(Ordering::Relaxed) { + return; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 || at.elapsed() < self.spin { + continue; + } + let mut lk = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner()); + self.state(id, -2); + self.sleepers.0.fetch_add(1, Ordering::SeqCst); + while self.epoch.0.load(Ordering::SeqCst) == seen && !self.stop.0.load(Ordering::Relaxed) { + lk = self.sleep_cv.wait(lk).unwrap_or_else(|p| p.into_inner()); + } + self.sleepers.0.fetch_sub(1, Ordering::Relaxed); + self.state(id, -1); + } + if self.stop.0.load(Ordering::Acquire) { + return; + } + seen = self.epoch.0.load(Ordering::Acquire); + self.parked.0.fetch_sub(1, Ordering::AcqRel); + self.state(id, -3); + self.drain(seen, id); + self.state(id, -1); + self.parked.0.fetch_add(1, Ordering::AcqRel); + } + } + pub(super) fn stall(&self, what: &str) -> ! { + eprintln!("strata: the CPU expert pool stalled {what}"); + if let Some(f) = RELEASE_GPU_WAITS.get() { + f(); + } + std::process::abort() + } + pub(super) fn wait_parked(&self) { + self.state(self.n, -11); + let mut spins = 0u32; + let mut t = Instant::now(); + while self.parked.0.load(Ordering::Acquire) != self.n as u32 { + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + if spins == 1024 { + t = Instant::now(); + } else if t.elapsed() > Duration::from_secs(60) { + self.stall("waiting for workers to park"); + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_general_pool/impl_shared_2.rs b/crates/native-cpu-expert/src/rust_general_pool/impl_shared_2.rs new file mode 100644 index 00000000..1be96e4c --- /dev/null +++ b/crates/native-cpu-expert/src/rust_general_pool/impl_shared_2.rs @@ -0,0 +1,30 @@ +//! Moved out of the parent module by STRA-338: impl Shared (2). + +#[allow(unused_imports)] +use super::*; + +impl Shared { + pub(super) fn wait_done(&self, n: usize) { + self.state(self.n, -12); + let mut spins = 0u32; + let mut seen = 0; + let mut t = Instant::now(); + loop { + let d = self.done.0.load(Ordering::Acquire); + if d >= n as u32 { + return; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + if spins == 1024 || d != seen { + t = Instant::now(); + seen = d; + } else if t.elapsed() > Duration::from_secs(60) { + self.stall("waiting for jobs to finish"); + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml.rs b/crates/native-cpu-expert/src/rust_ggml.rs index 5eaf94de..1f03bd2f 100644 --- a/crates/native-cpu-expert/src/rust_ggml.rs +++ b/crates/native-cpu-expert/src/rust_ggml.rs @@ -1,128 +1,140 @@ //! Pinned GGML CPU type traits used by Original NativeFmt, owned activation //! quantization and row products. Byte/type admission does not mint source proof. -use std::arch::x86_64::*; -use super::{Error,Result}; -use super::rust_types::{Q8K,Q8Zero}; use super::rust_kq::Q8One; -use super::rust_simd::{half,to_half,hsum_original,hsum_ggml}; -#[derive(Clone,Copy,Debug,Eq,PartialEq)] -pub enum Kind{F32,F16,Q4Zero,Q4One,Q5Zero,Q5One,Q8Zero,Q2K,Q3K,Q4K,Q5K,Q6K,Iq2Xxs,Iq2Xs,Iq3Xxs,Iq1S,Iq4Nl,Iq3S,Iq2S,Iq4Xs,Iq1M,Bf16,Tq1,Tq2,MxFp4,NvFp4,Q1Zero,Q2Zero} -impl Kind{ - pub fn from_original(type_id:i32)->Result{Ok(match type_id{0=>Self::F32,1=>Self::F16,2=>Self::Q4Zero,3=>Self::Q4One,6=>Self::Q5Zero,7=>Self::Q5One,8=>Self::Q8Zero,10=>Self::Q2K,11=>Self::Q3K,12=>Self::Q4K,13=>Self::Q5K,14=>Self::Q6K,16=>Self::Iq2Xxs,17=>Self::Iq2Xs,18=>Self::Iq3Xxs,19=>Self::Iq1S,20=>Self::Iq4Nl,21=>Self::Iq3S,22=>Self::Iq2S,23=>Self::Iq4Xs,29=>Self::Iq1M,30=>Self::Bf16,34=>Self::Tq1,35=>Self::Tq2,39=>Self::MxFp4,40=>Self::NvFp4,41=>Self::Q1Zero,42=>Self::Q2Zero,_=>return Err(Error::Unsupported)})} - pub fn original_id(self)->i32{match self{Self::F32=>0,Self::F16=>1,Self::Q4Zero=>2,Self::Q4One=>3,Self::Q5Zero=>6,Self::Q5One=>7,Self::Q8Zero=>8,Self::Q2K=>10,Self::Q3K=>11,Self::Q4K=>12,Self::Q5K=>13,Self::Q6K=>14,Self::Iq2Xxs=>16,Self::Iq2Xs=>17,Self::Iq3Xxs=>18,Self::Iq1S=>19,Self::Iq4Nl=>20,Self::Iq3S=>21,Self::Iq2S=>22,Self::Iq4Xs=>23,Self::Iq1M=>29,Self::Bf16=>30,Self::Tq1=>34,Self::Tq2=>35,Self::MxFp4=>39,Self::NvFp4=>40,Self::Q1Zero=>41,Self::Q2Zero=>42}} - pub fn block(self)->(usize,usize){match self{Self::F32=>(1,4),Self::F16|Self::Bf16=>(1,2),Self::Q4Zero|Self::Iq4Nl=>(32,18),Self::Q4One=>(32,20),Self::Q5Zero=>(32,22),Self::Q5One=>(32,24),Self::Q8Zero=>(32,34),Self::Q2K=>(256,84),Self::Q3K|Self::Iq3S=>(256,110),Self::Q4K=>(256,144),Self::Q5K=>(256,176),Self::Q6K=>(256,210),Self::Iq2Xxs|Self::Tq2=>(256,66),Self::Iq2Xs=>(256,74),Self::Iq3Xxs=>(256,98),Self::Iq1S=>(256,50),Self::Iq2S=>(256,82),Self::Iq4Xs=>(256,136),Self::Iq1M=>(256,56),Self::Tq1=>(256,54),Self::MxFp4=>(32,17),Self::NvFp4=>(64,36),Self::Q1Zero=>(128,18),Self::Q2Zero=>(64,18)}} - pub fn row_bytes(self,n:usize)->Result{let (q,b)=self.block();if n%q!=0{return Err(Error::Shape);}n.checked_div(q).and_then(|v|v.checked_mul(b)).ok_or(Error::Shape)} - pub fn activation_bytes(self,n:usize)->Result{self.act().bytes(n)} - pub fn activation_id(self)->i32{match self.act(){ActKind::F32=>0,ActKind::F16=>1,ActKind::Bf16=>30,ActKind::Zero=>8,ActKind::One=>9,ActKind::K=>15}} - fn act(self)->ActKind{match self{Self::F32=>ActKind::F32,Self::F16=>ActKind::F16,Self::Bf16=>ActKind::Bf16,Self::Q4One|Self::Q5One=>ActKind::One,Self::Q4Zero|Self::Q5Zero|Self::Q8Zero|Self::Iq4Nl|Self::MxFp4|Self::NvFp4|Self::Q1Zero|Self::Q2Zero=>ActKind::Zero,_=>ActKind::K}} +use super::rust_simd::{half, hsum_ggml, hsum_original, to_half}; +use super::rust_types::{Q8K, Q8Zero}; +use super::{Error, Result}; +use std::arch::x86_64::*; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Kind { + F32, + F16, + Q4Zero, + Q4One, + Q5Zero, + Q5One, + Q8Zero, + Q2K, + Q3K, + Q4K, + Q5K, + Q6K, + Iq2Xxs, + Iq2Xs, + Iq3Xxs, + Iq1S, + Iq4Nl, + Iq3S, + Iq2S, + Iq4Xs, + Iq1M, + Bf16, + Tq1, + Tq2, + MxFp4, + NvFp4, + Q1Zero, + Q2Zero, } -#[derive(Clone,Copy,Eq,PartialEq)]enum ActKind{F32,F16,Bf16,Zero,One,K} -impl ActKind{fn bytes(self,n:usize)->Result{let (q,b)=match self{Self::F32=>(1,4),Self::F16|Self::Bf16=>(1,2),Self::Zero=>(32,34),Self::One=>(32,36),Self::K=>(256,292)};if n%q!=0{return Err(Error::Shape);}n.checked_div(q).and_then(|v|v.checked_mul(b)).ok_or(Error::Shape)}} -enum Storage{F32(Vec),Half(Vec),Zero(Vec),One(Vec),K(Vec)} -pub struct Activation{kind:ActKind,n:usize,data:Storage} -fn alloc(n:usize)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,T::default);Ok(v)} -impl Activation{ - pub fn quantize(weight_kind:Kind,input:&[f32])->Result{if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}/* SAFETY (every unsafe block below): avx2_ok() above proved AVX2+FMA+F16C; all vector lengths derive from kind.bytes(n) (n % block == 0) and each callee asserts its own slice lengths. */let kind=weight_kind.act();kind.bytes(input.len())?;let n=input.len();let data=match kind{ - ActKind::F32=>{let mut v=alloc(n)?;v.copy_from_slice(input);Storage::F32(v)}, - ActKind::F16=>{let mut v=alloc(n)?;for (&x,v) in input.iter().zip(&mut v){*v=unsafe{to_half(x)};}Storage::Half(v)}, - ActKind::Bf16=>{let mut v=alloc(n)?;if !unsafe{super::rust_ggml_native::convert_bf16(input,&mut v)}{for (&x,v) in input.iter().zip(&mut v){let b=x.to_bits();*v=if b&0x7fffffff>0x7f800000{((b>>16)|64)as u16}else{(b.wrapping_add(0x7fff+((b>>16)&1))>>16)as u16};}}Storage::Half(v)}, - ActKind::Zero=>{let mut v=alloc(n/32)?;unsafe{super::rust_quant::q8_zero(input,&mut v);}Storage::Zero(v)}, - ActKind::One=>{let mut v=alloc(n/32)?;unsafe{super::rust_kq::quant_one(input,&mut v);}Storage::One(v)}, - ActKind::K=>{let mut v=alloc(n/256)?;super::rust_quant::q8_k(input,&mut v);Storage::K(v)}, - };Ok(Self{kind,n,data})} - pub fn encoded_bytes(&self)->Result{self.kind.bytes(self.n)} +#[derive(Clone, Copy, Eq, PartialEq)] +enum ActKind { + F32, + F16, + Bf16, + Zero, + One, + K, +} +enum Storage { + F32(Vec), + Half(Vec), + Zero(Vec), + One(Vec), + K(Vec), +} +pub struct Activation { + kind: ActKind, + n: usize, + data: Storage, } #[derive(Clone)] -pub struct NativeFormat{pub gu:Kind,pub down:Kind,pub n_embd:usize,pub n_ff:usize,pub gu_row:usize,pub down_row:usize,pub up_offset:usize,pub down_offset:usize,pub bytes:usize,pub activation_bytes:usize,pub hidden_bytes:usize} -impl NativeFormat{ - pub fn new(gu:Kind,down:Kind,n_embd:usize,n_ff:usize)->Result{if n_embd==0||n_ff==0{return Err(Error::Shape);}let gu_row=gu.row_bytes(n_embd)?;let down_row=down.row_bytes(n_ff)?;let activation_bytes=gu.act().bytes(n_embd)?;let hidden_bytes=down.act().bytes(n_ff)?;if activation_bytes>4096||hidden_bytes>1024{return Err(Error::Shape);}let up_offset=gu_row.checked_mul(n_ff).ok_or(Error::Shape)?;let down_offset=up_offset.checked_mul(2).ok_or(Error::Shape)?;let bytes=down_row.checked_mul(n_embd).and_then(|b|b.checked_add(down_offset)).ok_or(Error::Shape)?;Ok(Self{gu,down,n_embd,n_ff,gu_row,down_row,up_offset,down_offset,bytes,activation_bytes,hidden_bytes})} - pub fn validate(&self)->Result<()>{let f=Self::new(self.gu,self.down,self.n_embd,self.n_ff)?;if self.gu_row!=f.gu_row||self.down_row!=f.down_row||self.up_offset!=f.up_offset||self.down_offset!=f.down_offset||self.bytes!=f.bytes||self.activation_bytes!=f.activation_bytes||self.hidden_bytes!=f.hidden_bytes{return Err(Error::Shape);}Ok(())} +pub struct NativeFormat { + pub gu: Kind, + pub down: Kind, + pub n_embd: usize, + pub n_ff: usize, + pub gu_row: usize, + pub down_row: usize, + pub up_offset: usize, + pub down_offset: usize, + pub bytes: usize, + pub activation_bytes: usize, + pub hidden_bytes: usize, } -pub fn dot(kind:Kind,row:&[u8],activation:&Activation)->Result{ - if row.len()!=kind.row_bytes(activation.n)?||activation.kind!=kind.act(){return Err(Error::Shape);}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);} - /* SAFETY: avx2_ok() above; `row.len() == row_bytes(n)` and `activation.kind == kind.act()` were checked, and `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel below gets whole, equal-count blocks. */ - unsafe{match &activation.data{ - Storage::F32(v)=>Ok(float_dot(kind,row,v,&[])),Storage::Half(v)=>Ok(float_dot(kind,row,&[],v)), - Storage::Zero(v)=>match kind{Kind::Iq4Nl=>{let paired=v.len()/2*2;let mut out=[0.0];super::rust_iq::iq4nl(&row[..paired*18],&[&v[..paired]],&mut out,true);if paired>4)as usize]as i32;}out[0]+=(half(y.d)*half(u16::from_le_bytes([b[0],b[1]])))*(a+c)as f32;}Ok(out[0])},Kind::Q2Zero=>Ok(q2_generic(row,v)),Kind::Q1Zero=>Ok(q1_dot(row,v)),Kind::MxFp4=>Ok(super::rust_ggml_extra::mxfp4(row,v)),Kind::NvFp4=>Ok(super::rust_ggml_extra::nvfp4(row,v)),Kind::Q4Zero|Kind::Q5Zero|Kind::Q8Zero=>Ok(super::rust_kq::small_dot(kind.original_id(),row,Some(v),None)),_=>Err(Error::Unsupported)}, - Storage::One(v)=>Ok(super::rust_kq::small_dot(kind.original_id(),row,None,Some(v))), - Storage::K(v)=>match kind{Kind::Iq1S|Kind::Iq1M=>Ok(super::rust_ggml_extra::iq1(kind.original_id(),row,v)),Kind::Tq1|Kind::Tq2=>Ok(super::rust_ggml_extra::ternary(kind.original_id(),row,v)),Kind::Q4K=>{let mut out=[0.0];super::rust_kq::q4_k_dot(row,&[v],&mut out);Ok(out[0])},Kind::Q2K|Kind::Q3K|Kind::Q5K|Kind::Q6K=>Ok(super::rust_k_blocks::dot(kind.original_id(),row,v)),Kind::Iq2Xxs|Kind::Iq2Xs|Kind::Iq3Xxs|Kind::Iq3S|Kind::Iq2S|Kind::Iq4Xs=>Ok(super::rust_iq::dot_single(kind.original_id(),row,v)),_=>Err(Error::Unsupported)}, - }} -} -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn float_dot(kind:Kind,row:&[u8],f:&[f32],h:&[u16])->f32{unsafe{ - let n=if kind==Kind::F32{f.len()}else{h.len()};assert!(row.len()>=n*if kind==Kind::F32{4}else{2}); - if let Some(value)=super::rust_ggml_native::float_dot(kind,row,f,h){return value;} - let np=n&!31;let mut acc=[_mm256_setzero_ps();4]; - for at in (0..np).step_by(32){for j in 0..4{let i=at+j*8;let (x,y)=match kind{ - Kind::F32=>(_mm256_loadu_ps(row.as_ptr().add(i*4).cast()),_mm256_loadu_ps(f.as_ptr().add(i))), - Kind::F16=>(_mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i*2).cast())),_mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast()))), - Kind::Bf16=>(_mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(row.as_ptr().add(i*2).cast())))),_mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(h.as_ptr().add(i).cast()))))),_=>unreachable!()}; - acc[j]=if kind==Kind::Bf16{_mm256_add_ps(_mm256_mul_ps(x,y),acc[j])}else{_mm256_fmadd_ps(x,y,acc[j])}; - }}let sum=_mm256_add_ps(_mm256_add_ps(acc[0],acc[2]),_mm256_add_ps(acc[1],acc[3])); - if kind==Kind::F32{let mut s=hsum_original(sum);for i in np..n{s+=f32::from_le_bytes(row[i*4..i*4+4].try_into().unwrap())*f[i];}s}else{let mut s=if kind==Kind::Bf16{hsum_ggml(sum)}else{hsum_original(sum)}as f64;for i in np..n{let a=u16::from_le_bytes([row[i*2],row[i*2+1]]);let (a,b)=if kind==Kind::Bf16{(f32::from_bits((a as u32)<<16),f32::from_bits((h[i]as u32)<<16))}else{(half(a),half(h[i]))};s+=(a*b)as f64;}s as f32} -}} -// SAFETY (the two `unsafe{half(..)}` below): private; reached only from dot()/dot_raw() after avx2_ok() proved F16C. -fn q2_generic(row:&[u8],y:&[Q8Zero])->f32{let mut total=0.0;for (i,x) in row.chunks_exact(18).enumerate(){let mut sum=0.0;for k in 0..2{let y=y[i*2+k];let mut dot=0i32;for b in 0..8{let q=x[2+k*8+b];for j in 0..4{dot+=(((q>>(j*2))&3)as i32-1)*y.qs[b*4+j]as i32;}}sum+=unsafe{half(y.d)}*dot as f32;}total+=unsafe{half(u16::from_le_bytes([x[0],x[1]]))}*sum;}total} -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn q1_dot(row:&[u8],y:&[Q8Zero])->f32{unsafe{ - let mut acc=_mm256_setzero_ps();for (ib,x) in row.chunks_exact(18).enumerate(){let mut block=_mm256_setzero_ps();for k in 0..4{let mut signs=[0i8;32];for j in 0..32{signs[j]=if x[2+k*4+j/8]&(1<<(j%8))==0{-1}else{0};}let mask=_mm256_loadu_si256(signs.as_ptr().cast());let q=_mm256_loadu_si256(y[ib*4+k].qs.as_ptr().cast());let sy=_mm256_sub_epi8(_mm256_xor_si256(q,mask),mask);let p=_mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1),sy),_mm256_set1_epi16(1));let d=_mm256_set1_ps(half(y[ib*4+k].d));block=if k==0{_mm256_mul_ps(d,_mm256_cvtepi32_ps(p))}else{_mm256_fmadd_ps(d,_mm256_cvtepi32_ps(p),block)};}acc=_mm256_fmadd_ps(_mm256_set1_ps(half(u16::from_le_bytes([x[0],x[1]]))),block,acc);}hsum_ggml(acc) -}} - -// Callers own initialized aligned banks and admit geometry before this private leaf. -/// # Safety -/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())` bytes and be -/// aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers: NativeActivation (bytes at -/// offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const assert in rust_general_pool). -pub(super) unsafe fn quantize_raw(kind:Kind,x:&[f32],dst:&mut[u8]){unsafe{ - let need=kind.activation_bytes(x.len()).expect("admitted activation geometry");let align=match kind.act(){ActKind::F32=>1,ActKind::K=>std::mem::align_of::(),_=>std::mem::align_of::()}; - assert!(dst.len()>=need&&dst.as_ptr().align_offset(align)==0); - match kind.act(){ - ActKind::F32=>std::ptr::copy_nonoverlapping(x.as_ptr().cast::(),dst.as_mut_ptr(),x.len()*4), - ActKind::F16|ActKind::Bf16=>{let v=std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(),x.len());if kind.act()==ActKind::Bf16&&super::rust_ggml_native::convert_bf16(x,v){return;}for (&x,v) in x.iter().zip(v){*v=if kind.act()==ActKind::F16{to_half(x)}else{let b=x.to_bits();if b&0x7fffffff>0x7f800000{((b>>16)|64)as u16}else{(b.wrapping_add(0x7fff+((b>>16)&1))>>16)as u16}};}}, - ActKind::Zero=>super::rust_quant::q8_zero(x,std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(),x.len()/32)), - ActKind::One=>super::rust_kq::quant_one(x,std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(),x.len()/32)), - ActKind::K=>super::rust_quant::q8_k(x,std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(),x.len()/256)), -}}} -/// # Safety -/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>= activation_bytes(n)), -/// aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every caller derives both from a -/// NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a NativeFormat::validate()d row slice; the -/// 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows (1024 B) large enough for Zero/One encodings. -pub(super) unsafe fn dot_raw(kind:Kind,row:&[u8],n:usize,raw:&[u8])->f32{unsafe{ - debug_assert!(kind.activation_bytes(n).is_ok_and(|b|raw.len()>=b)&&kind.row_bytes(n).is_ok_and(|b|row.len()>=b)); - match kind.act(){ - ActKind::F32=>float_dot(kind,row,std::slice::from_raw_parts(raw.as_ptr().cast::(),n),&[]), - ActKind::F16|ActKind::Bf16=>float_dot(kind,row,&[],std::slice::from_raw_parts(raw.as_ptr().cast::(),n)), - ActKind::One=>super::rust_kq::small_dot(kind.original_id(),row,None,Some(std::slice::from_raw_parts(raw.as_ptr().cast::(),n/32))), - ActKind::Zero=>{let y=std::slice::from_raw_parts(raw.as_ptr().cast::(),n/32);match kind{Kind::Q2Zero=>q2_generic(row,y),Kind::Q1Zero=>q1_dot(row,y),Kind::MxFp4=>super::rust_ggml_extra::mxfp4(row,y),Kind::NvFp4=>super::rust_ggml_extra::nvfp4(row,y),Kind::Iq4Nl=>{let paired=y.len()/2*2;let mut out=[0.0];super::rust_iq::iq4nl(&row[..paired*18],&[&y[..paired]],&mut out,true);if paired>4)as usize]as i32;}out[0]+=(half(yy.d)*half(u16::from_le_bytes([b[0],b[1]])))*(a+c)as f32;}out[0]},_=>super::rust_kq::small_dot(kind.original_id(),row,Some(y),None)}}, - ActKind::K=>{let y=std::slice::from_raw_parts(raw.as_ptr().cast::(),n/256);match kind{Kind::Iq1S|Kind::Iq1M=>super::rust_ggml_extra::iq1(kind.original_id(),row,y),Kind::Tq1|Kind::Tq2=>super::rust_ggml_extra::ternary(kind.original_id(),row,y),Kind::Q4K=>{let mut out=[0.0];super::rust_kq::q4_k_dot(row,&[y],&mut out);out[0]},Kind::Q2K|Kind::Q3K|Kind::Q5K|Kind::Q6K=>super::rust_k_blocks::dot(kind.original_id(),row,y),_=>super::rust_iq::dot_single(kind.original_id(),row,y)}}, -}}} #[cfg(test)] mod tests { - use super::*; - use std::panic::{catch_unwind,AssertUnwindSafe}; - #[repr(C,align(8))] struct Aligned([u8;512]); - // quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not written through. - #[test] - fn quantize_raw_refuses_a_short_or_misaligned_destination() { - let x=[0.5f32;64];let k=[0.5f32;256];let mut a=Aligned([0;512]); - // SAFETY (all calls): the destination checks are the asserts under test; no CPU leaf runs unless they pass (last block, avx2_ok()). - assert!(catch_unwind(AssertUnwindSafe(||unsafe{quantize_raw(Kind::Q8Zero,&x,&mut a.0[..67])})).is_err(),"67 < 68 bytes"); - assert!(catch_unwind(AssertUnwindSafe(||unsafe{quantize_raw(Kind::Q8Zero,&x,&mut a.0[1..69])})).is_err(),"odd address"); - assert!(catch_unwind(AssertUnwindSafe(||unsafe{quantize_raw(Kind::Q4K,&k,&mut a.0[2..2+292])})).is_err(),"Q8K needs 4-byte alignment"); - if super::super::rust_simd::avx2_ok(){ - unsafe{quantize_raw(Kind::Q8Zero,&x,&mut a.0[..68]);} - assert_ne!(&a.0[..2],&[0,0],"FP16 block scale written"); - } - } - // The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes per f32 is refused. - #[test] - fn float_dot_refuses_a_row_shorter_than_the_activation() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - let f=[1.0f32;64];let row=vec![0u8;64*4-1]; - // SAFETY: avx2_ok() above; the short row panics at the entry assert before any load. - assert!(catch_unwind(AssertUnwindSafe(||unsafe{float_dot(Kind::F32,&row,&f,&[])})).is_err()); - assert!(catch_unwind(AssertUnwindSafe(||unsafe{float_dot(Kind::F32,&vec![0u8;64*4],&f,&[])})).is_ok()); - } + use super::*; + use std::panic::{AssertUnwindSafe, catch_unwind}; + #[repr(C, align(8))] + struct Aligned([u8; 512]); + // quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not written through. + #[test] + fn quantize_raw_refuses_a_short_or_misaligned_destination() { + let x = [0.5f32; 64]; + let k = [0.5f32; 256]; + let mut a = Aligned([0; 512]); + // SAFETY (all calls): the destination checks are the asserts under test; no CPU leaf runs unless they pass (last block, avx2_ok()). + assert!( + catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[..67]) })).is_err(), + "67 < 68 bytes" + ); + assert!( + catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[1..69]) })).is_err(), + "odd address" + ); + assert!( + catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q4K, &k, &mut a.0[2..2 + 292]) })).is_err(), + "Q8K needs 4-byte alignment" + ); + if super::super::rust_simd::avx2_ok() { + unsafe { + quantize_raw(Kind::Q8Zero, &x, &mut a.0[..68]); + } + assert_ne!(&a.0[..2], &[0, 0], "FP16 block scale written"); + } + } + // The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes per f32 is refused. + #[test] + fn float_dot_refuses_a_row_shorter_than_the_activation() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + let f = [1.0f32; 64]; + let row = vec![0u8; 64 * 4 - 1]; + // SAFETY: avx2_ok() above; the short row panics at the entry assert before any load. + assert!(catch_unwind(AssertUnwindSafe(|| unsafe { float_dot(Kind::F32, &row, &f, &[]) })).is_err()); + assert!( + catch_unwind(AssertUnwindSafe(|| unsafe { float_dot(Kind::F32, &vec![0u8; 64 * 4], &f, &[]) })).is_ok() + ); + } } + +mod impl_kind; +#[allow(unused_imports)] +use impl_kind::alloc; +mod impl_nativeformat; +#[allow(unused_imports)] +pub use impl_nativeformat::dot; +#[allow(unused_imports)] +use impl_nativeformat::float_dot; +#[allow(unused_imports)] +use impl_nativeformat::q1_dot; +#[allow(unused_imports)] +use impl_nativeformat::q2_generic; +mod quantize_raw_fn; +#[allow(unused_imports)] +pub(super) use quantize_raw_fn::dot_raw; +#[allow(unused_imports)] +pub(super) use quantize_raw_fn::quantize_raw; diff --git a/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs b/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs new file mode 100644 index 00000000..f105c37d --- /dev/null +++ b/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs @@ -0,0 +1,219 @@ +//! Moved out of the parent module by STRA-338: impl Kind, impl ActKind, fn alloc, impl Activation. + +#[allow(unused_imports)] +use super::*; + +impl Kind { + pub fn from_original(type_id: i32) -> Result { + Ok(match type_id { + 0 => Self::F32, + 1 => Self::F16, + 2 => Self::Q4Zero, + 3 => Self::Q4One, + 6 => Self::Q5Zero, + 7 => Self::Q5One, + 8 => Self::Q8Zero, + 10 => Self::Q2K, + 11 => Self::Q3K, + 12 => Self::Q4K, + 13 => Self::Q5K, + 14 => Self::Q6K, + 16 => Self::Iq2Xxs, + 17 => Self::Iq2Xs, + 18 => Self::Iq3Xxs, + 19 => Self::Iq1S, + 20 => Self::Iq4Nl, + 21 => Self::Iq3S, + 22 => Self::Iq2S, + 23 => Self::Iq4Xs, + 29 => Self::Iq1M, + 30 => Self::Bf16, + 34 => Self::Tq1, + 35 => Self::Tq2, + 39 => Self::MxFp4, + 40 => Self::NvFp4, + 41 => Self::Q1Zero, + 42 => Self::Q2Zero, + _ => return Err(Error::Unsupported), + }) + } + pub fn original_id(self) -> i32 { + match self { + Self::F32 => 0, + Self::F16 => 1, + Self::Q4Zero => 2, + Self::Q4One => 3, + Self::Q5Zero => 6, + Self::Q5One => 7, + Self::Q8Zero => 8, + Self::Q2K => 10, + Self::Q3K => 11, + Self::Q4K => 12, + Self::Q5K => 13, + Self::Q6K => 14, + Self::Iq2Xxs => 16, + Self::Iq2Xs => 17, + Self::Iq3Xxs => 18, + Self::Iq1S => 19, + Self::Iq4Nl => 20, + Self::Iq3S => 21, + Self::Iq2S => 22, + Self::Iq4Xs => 23, + Self::Iq1M => 29, + Self::Bf16 => 30, + Self::Tq1 => 34, + Self::Tq2 => 35, + Self::MxFp4 => 39, + Self::NvFp4 => 40, + Self::Q1Zero => 41, + Self::Q2Zero => 42, + } + } + pub fn block(self) -> (usize, usize) { + match self { + Self::F32 => (1, 4), + Self::F16 | Self::Bf16 => (1, 2), + Self::Q4Zero | Self::Iq4Nl => (32, 18), + Self::Q4One => (32, 20), + Self::Q5Zero => (32, 22), + Self::Q5One => (32, 24), + Self::Q8Zero => (32, 34), + Self::Q2K => (256, 84), + Self::Q3K | Self::Iq3S => (256, 110), + Self::Q4K => (256, 144), + Self::Q5K => (256, 176), + Self::Q6K => (256, 210), + Self::Iq2Xxs | Self::Tq2 => (256, 66), + Self::Iq2Xs => (256, 74), + Self::Iq3Xxs => (256, 98), + Self::Iq1S => (256, 50), + Self::Iq2S => (256, 82), + Self::Iq4Xs => (256, 136), + Self::Iq1M => (256, 56), + Self::Tq1 => (256, 54), + Self::MxFp4 => (32, 17), + Self::NvFp4 => (64, 36), + Self::Q1Zero => (128, 18), + Self::Q2Zero => (64, 18), + } + } + pub fn row_bytes(self, n: usize) -> Result { + let (q, b) = self.block(); + if n % q != 0 { + return Err(Error::Shape); + } + n.checked_div(q).and_then(|v| v.checked_mul(b)).ok_or(Error::Shape) + } + pub fn activation_bytes(self, n: usize) -> Result { + self.act().bytes(n) + } + pub fn activation_id(self) -> i32 { + match self.act() { + ActKind::F32 => 0, + ActKind::F16 => 1, + ActKind::Bf16 => 30, + ActKind::Zero => 8, + ActKind::One => 9, + ActKind::K => 15, + } + } + pub(super) fn act(self) -> ActKind { + match self { + Self::F32 => ActKind::F32, + Self::F16 => ActKind::F16, + Self::Bf16 => ActKind::Bf16, + Self::Q4One | Self::Q5One => ActKind::One, + Self::Q4Zero + | Self::Q5Zero + | Self::Q8Zero + | Self::Iq4Nl + | Self::MxFp4 + | Self::NvFp4 + | Self::Q1Zero + | Self::Q2Zero => ActKind::Zero, + _ => ActKind::K, + } + } +} +impl ActKind { + pub(super) fn bytes(self, n: usize) -> Result { + let (q, b) = match self { + Self::F32 => (1, 4), + Self::F16 | Self::Bf16 => (1, 2), + Self::Zero => (32, 34), + Self::One => (32, 36), + Self::K => (256, 292), + }; + if n % q != 0 { + return Err(Error::Shape); + } + n.checked_div(q).and_then(|v| v.checked_mul(b)).ok_or(Error::Shape) + } +} +pub(super) fn alloc(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize_with(n, T::default); + Ok(v) +} +impl Activation { + pub fn quantize(weight_kind: Kind, input: &[f32]) -> Result { + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } /* SAFETY (every unsafe block below): avx2_ok() above proved AVX2+FMA+F16C; all vector lengths derive from kind.bytes(n) (n % block == 0) and each callee asserts its own slice lengths. */ + let kind = weight_kind.act(); + kind.bytes(input.len())?; + let n = input.len(); + let data = match kind { + ActKind::F32 => { + let mut v = alloc(n)?; + v.copy_from_slice(input); + Storage::F32(v) + } + ActKind::F16 => { + let mut v = alloc(n)?; + for (&x, v) in input.iter().zip(&mut v) { + *v = unsafe { to_half(x) }; + } + Storage::Half(v) + } + ActKind::Bf16 => { + let mut v = alloc(n)?; + if !unsafe { super::super::rust_ggml_native::convert_bf16(input, &mut v) } { + for (&x, v) in input.iter().zip(&mut v) { + let b = x.to_bits(); + *v = if b & 0x7fffffff > 0x7f800000 { + ((b >> 16) | 64) as u16 + } else { + (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 + }; + } + } + Storage::Half(v) + } + ActKind::Zero => { + let mut v = alloc(n / 32)?; + unsafe { + super::super::rust_quant::q8_zero(input, &mut v); + } + Storage::Zero(v) + } + ActKind::One => { + let mut v = alloc(n / 32)?; + unsafe { + super::super::rust_kq::quant_one(input, &mut v); + } + Storage::One(v) + } + ActKind::K => { + let mut v = alloc(n / 256)?; + super::super::rust_quant::q8_k(input, &mut v); + Storage::K(v) + } + }; + Ok(Self { kind, n, data }) + } + pub fn encoded_bytes(&self) -> Result { + self.kind.bytes(self.n) + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs b/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs new file mode 100644 index 00000000..1bb1be1f --- /dev/null +++ b/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs @@ -0,0 +1,214 @@ +//! Moved out of the parent module by STRA-338: impl NativeFormat, fn dot, fn float_dot, fn q2_generic, fn q1_dot. + +#[allow(unused_imports)] +use super::*; + +impl NativeFormat { + pub fn new(gu: Kind, down: Kind, n_embd: usize, n_ff: usize) -> Result { + if n_embd == 0 || n_ff == 0 { + return Err(Error::Shape); + } + let gu_row = gu.row_bytes(n_embd)?; + let down_row = down.row_bytes(n_ff)?; + let activation_bytes = gu.act().bytes(n_embd)?; + let hidden_bytes = down.act().bytes(n_ff)?; + if activation_bytes > 4096 || hidden_bytes > 1024 { + return Err(Error::Shape); + } + let up_offset = gu_row.checked_mul(n_ff).ok_or(Error::Shape)?; + let down_offset = up_offset.checked_mul(2).ok_or(Error::Shape)?; + let bytes = down_row.checked_mul(n_embd).and_then(|b| b.checked_add(down_offset)).ok_or(Error::Shape)?; + Ok(Self { + gu, + down, + n_embd, + n_ff, + gu_row, + down_row, + up_offset, + down_offset, + bytes, + activation_bytes, + hidden_bytes, + }) + } + pub fn validate(&self) -> Result<()> { + let f = Self::new(self.gu, self.down, self.n_embd, self.n_ff)?; + if self.gu_row != f.gu_row + || self.down_row != f.down_row + || self.up_offset != f.up_offset + || self.down_offset != f.down_offset + || self.bytes != f.bytes + || self.activation_bytes != f.activation_bytes + || self.hidden_bytes != f.hidden_bytes + { + return Err(Error::Shape); + } + Ok(()) + } +} +pub fn dot(kind: Kind, row: &[u8], activation: &Activation) -> Result { + if row.len() != kind.row_bytes(activation.n)? || activation.kind != kind.act() { + return Err(Error::Shape); + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + /* SAFETY: avx2_ok() above; `row.len() == row_bytes(n)` and `activation.kind == kind.act()` were checked, and `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel below gets whole, equal-count blocks. */ + unsafe { + match &activation.data { + Storage::F32(v) => Ok(float_dot(kind, row, v, &[])), + Storage::Half(v) => Ok(float_dot(kind, row, &[], v)), + Storage::Zero(v) => match kind { + Kind::Iq4Nl => { + let paired = v.len() / 2 * 2; + let mut out = [0.0]; + super::super::rust_iq::iq4nl(&row[..paired * 18], &[&v[..paired]], &mut out, true); + if paired < v.len() { + let b = &row[paired * 18..]; + let y = v[paired]; + let values = &super::super::rust_codebooks::KVALUES_IQ4NL; + let mut a = 0i32; + let mut c = 0i32; + for j in 0..16 { + a += y.qs[j] as i32 * values[(b[2 + j] & 15) as usize] as i32; + c += y.qs[j + 16] as i32 * values[(b[2 + j] >> 4) as usize] as i32; + } + out[0] += (half(y.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32; + } + Ok(out[0]) + } + Kind::Q2Zero => Ok(q2_generic(row, v)), + Kind::Q1Zero => Ok(q1_dot(row, v)), + Kind::MxFp4 => Ok(super::super::rust_ggml_extra::mxfp4(row, v)), + Kind::NvFp4 => Ok(super::super::rust_ggml_extra::nvfp4(row, v)), + Kind::Q4Zero | Kind::Q5Zero | Kind::Q8Zero => { + Ok(super::super::rust_kq::small_dot(kind.original_id(), row, Some(v), None)) + } + _ => Err(Error::Unsupported), + }, + Storage::One(v) => Ok(super::super::rust_kq::small_dot(kind.original_id(), row, None, Some(v))), + Storage::K(v) => match kind { + Kind::Iq1S | Kind::Iq1M => Ok(super::super::rust_ggml_extra::iq1(kind.original_id(), row, v)), + Kind::Tq1 | Kind::Tq2 => Ok(super::super::rust_ggml_extra::ternary(kind.original_id(), row, v)), + Kind::Q4K => { + let mut out = [0.0]; + super::super::rust_kq::q4_k_dot(row, &[v], &mut out); + Ok(out[0]) + } + Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => { + Ok(super::super::rust_k_blocks::dot(kind.original_id(), row, v)) + } + Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq3Xxs | Kind::Iq3S | Kind::Iq2S | Kind::Iq4Xs => { + Ok(super::super::rust_iq::dot_single(kind.original_id(), row, v)) + } + _ => Err(Error::Unsupported), + }, + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) -> f32 { + unsafe { + let n = if kind == Kind::F32 { f.len() } else { h.len() }; + assert!(row.len() >= n * if kind == Kind::F32 { 4 } else { 2 }); + if let Some(value) = super::super::rust_ggml_native::float_dot(kind, row, f, h) { + return value; + } + let np = n & !31; + let mut acc = [_mm256_setzero_ps(); 4]; + for at in (0..np).step_by(32) { + for j in 0..4 { + let i = at + j * 8; + let (x, y) = match kind { + Kind::F32 => (_mm256_loadu_ps(row.as_ptr().add(i * 4).cast()), _mm256_loadu_ps(f.as_ptr().add(i))), + Kind::F16 => ( + _mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i * 2).cast())), + _mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast())), + ), + Kind::Bf16 => ( + _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128( + row.as_ptr().add(i * 2).cast(), + )))), + _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128( + h.as_ptr().add(i).cast(), + )))), + ), + _ => unreachable!(), + }; + acc[j] = if kind == Kind::Bf16 { + _mm256_add_ps(_mm256_mul_ps(x, y), acc[j]) + } else { + _mm256_fmadd_ps(x, y, acc[j]) + }; + } + } + let sum = _mm256_add_ps(_mm256_add_ps(acc[0], acc[2]), _mm256_add_ps(acc[1], acc[3])); + if kind == Kind::F32 { + let mut s = hsum_original(sum); + for i in np..n { + s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * f[i]; + } + s + } else { + let mut s = if kind == Kind::Bf16 { hsum_ggml(sum) } else { hsum_original(sum) } as f64; + for i in np..n { + let a = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]); + let (a, b) = if kind == Kind::Bf16 { + (f32::from_bits((a as u32) << 16), f32::from_bits((h[i] as u32) << 16)) + } else { + (half(a), half(h[i])) + }; + s += (a * b) as f64; + } + s as f32 + } + } +} +// SAFETY (the two `unsafe{half(..)}` below): private; reached only from dot()/dot_raw() after avx2_ok() proved F16C. +pub(super) fn q2_generic(row: &[u8], y: &[Q8Zero]) -> f32 { + let mut total = 0.0; + for (i, x) in row.chunks_exact(18).enumerate() { + let mut sum = 0.0; + for k in 0..2 { + let y = y[i * 2 + k]; + let mut dot = 0i32; + for b in 0..8 { + let q = x[2 + k * 8 + b]; + for j in 0..4 { + dot += (((q >> (j * 2)) & 3) as i32 - 1) * y.qs[b * 4 + j] as i32; + } + } + sum += unsafe { half(y.d) } * dot as f32; + } + total += unsafe { half(u16::from_le_bytes([x[0], x[1]])) } * sum; + } + total +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q1_dot(row: &[u8], y: &[Q8Zero]) -> f32 { + unsafe { + let mut acc = _mm256_setzero_ps(); + for (ib, x) in row.chunks_exact(18).enumerate() { + let mut block = _mm256_setzero_ps(); + for k in 0..4 { + let mut signs = [0i8; 32]; + for j in 0..32 { + signs[j] = if x[2 + k * 4 + j / 8] & (1 << (j % 8)) == 0 { -1 } else { 0 }; + } + let mask = _mm256_loadu_si256(signs.as_ptr().cast()); + let q = _mm256_loadu_si256(y[ib * 4 + k].qs.as_ptr().cast()); + let sy = _mm256_sub_epi8(_mm256_xor_si256(q, mask), mask); + let p = _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1), sy), _mm256_set1_epi16(1)); + let d = _mm256_set1_ps(half(y[ib * 4 + k].d)); + block = if k == 0 { + _mm256_mul_ps(d, _mm256_cvtepi32_ps(p)) + } else { + _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(p), block) + }; + } + acc = _mm256_fmadd_ps(_mm256_set1_ps(half(u16::from_le_bytes([x[0], x[1]]))), block, acc); + } + hsum_ggml(acc) + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs b/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs new file mode 100644 index 00000000..2bd6c39b --- /dev/null +++ b/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs @@ -0,0 +1,123 @@ +//! Moved out of the parent module by STRA-338: fn quantize_raw, fn dot_raw. + +#[allow(unused_imports)] +use super::*; + +// Callers own initialized aligned banks and admit geometry before this private leaf. +/// # Safety +/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())` bytes and be +/// aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers: NativeActivation (bytes at +/// offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const assert in rust_general_pool). +pub(in super::super) unsafe fn quantize_raw(kind: Kind, x: &[f32], dst: &mut [u8]) { + unsafe { + let need = kind.activation_bytes(x.len()).expect("admitted activation geometry"); + let align = match kind.act() { + ActKind::F32 => 1, + ActKind::K => std::mem::align_of::(), + _ => std::mem::align_of::(), + }; + assert!(dst.len() >= need && dst.as_ptr().align_offset(align) == 0); + match kind.act() { + ActKind::F32 => std::ptr::copy_nonoverlapping(x.as_ptr().cast::(), dst.as_mut_ptr(), x.len() * 4), + ActKind::F16 | ActKind::Bf16 => { + let v = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len()); + if kind.act() == ActKind::Bf16 && super::super::rust_ggml_native::convert_bf16(x, v) { + return; + } + for (&x, v) in x.iter().zip(v) { + *v = if kind.act() == ActKind::F16 { + to_half(x) + } else { + let b = x.to_bits(); + if b & 0x7fffffff > 0x7f800000 { + ((b >> 16) | 64) as u16 + } else { + (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 + } + }; + } + } + ActKind::Zero => super::super::rust_quant::q8_zero( + x, + std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len() / 32), + ), + ActKind::One => super::super::rust_kq::quant_one( + x, + std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len() / 32), + ), + ActKind::K => super::super::rust_quant::q8_k( + x, + std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len() / 256), + ), + } + } +} +/// # Safety +/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>= activation_bytes(n)), +/// aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every caller derives both from a +/// NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a NativeFormat::validate()d row slice; the +/// 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows (1024 B) large enough for Zero/One encodings. +pub(in super::super) unsafe fn dot_raw(kind: Kind, row: &[u8], n: usize, raw: &[u8]) -> f32 { + unsafe { + debug_assert!( + kind.activation_bytes(n).is_ok_and(|b| raw.len() >= b) && kind.row_bytes(n).is_ok_and(|b| row.len() >= b) + ); + match kind.act() { + ActKind::F32 => float_dot(kind, row, std::slice::from_raw_parts(raw.as_ptr().cast::(), n), &[]), + ActKind::F16 | ActKind::Bf16 => { + float_dot(kind, row, &[], std::slice::from_raw_parts(raw.as_ptr().cast::(), n)) + } + ActKind::One => super::super::rust_kq::small_dot( + kind.original_id(), + row, + None, + Some(std::slice::from_raw_parts(raw.as_ptr().cast::(), n / 32)), + ), + ActKind::Zero => { + let y = std::slice::from_raw_parts(raw.as_ptr().cast::(), n / 32); + match kind { + Kind::Q2Zero => q2_generic(row, y), + Kind::Q1Zero => q1_dot(row, y), + Kind::MxFp4 => super::super::rust_ggml_extra::mxfp4(row, y), + Kind::NvFp4 => super::super::rust_ggml_extra::nvfp4(row, y), + Kind::Iq4Nl => { + let paired = y.len() / 2 * 2; + let mut out = [0.0]; + super::super::rust_iq::iq4nl(&row[..paired * 18], &[&y[..paired]], &mut out, true); + if paired < y.len() { + let b = &row[paired * 18..]; + let yy = y[paired]; + let mut a = 0i32; + let mut c = 0i32; + for j in 0..16 { + a += yy.qs[j] as i32 + * super::super::rust_codebooks::KVALUES_IQ4NL[(b[2 + j] & 15) as usize] as i32; + c += yy.qs[j + 16] as i32 + * super::super::rust_codebooks::KVALUES_IQ4NL[(b[2 + j] >> 4) as usize] as i32; + } + out[0] += (half(yy.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32; + } + out[0] + } + _ => super::super::rust_kq::small_dot(kind.original_id(), row, Some(y), None), + } + } + ActKind::K => { + let y = std::slice::from_raw_parts(raw.as_ptr().cast::(), n / 256); + match kind { + Kind::Iq1S | Kind::Iq1M => super::super::rust_ggml_extra::iq1(kind.original_id(), row, y), + Kind::Tq1 | Kind::Tq2 => super::super::rust_ggml_extra::ternary(kind.original_id(), row, y), + Kind::Q4K => { + let mut out = [0.0]; + super::super::rust_kq::q4_k_dot(row, &[y], &mut out); + out[0] + } + Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => { + super::super::rust_k_blocks::dot(kind.original_id(), row, y) + } + _ => super::super::rust_iq::dot_single(kind.original_id(), row, y), + } + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml_extra.rs b/crates/native-cpu-expert/src/rust_ggml_extra.rs index aa676d1a..bf28c3f1 100644 --- a/crates/native-cpu-expert/src/rust_ggml_extra.rs +++ b/crates/native-cpu-expert/src/rust_ggml_extra.rs @@ -1,29 +1,260 @@ //! Literal pinned GGML AVX2 IQ1, ternary and FP4 row products; see LICENSE.ggml. //! Only integer operand assembly is scalar; floating accumulation is unchanged. -use std::arch::x86_64::*; -use super::rust_types::{Q8K,Q8Zero}; -use super::rust_simd::{half,hsum_ggml}; use super::rust_iq1_grid::GRID; +use super::rust_simd::{half, hsum_ggml}; +use super::rust_types::{Q8K, Q8Zero}; +use std::arch::x86_64::*; // Bounds: row blocks come from chunks_exact(size)/checked slicing (`row[j*17..(j+1)*17]`), activation blocks are safe-indexed; // raw loads are 16 bytes at block offsets <= size-16 (fp4), 32 bytes of Q8Zero.qs / Q8K.qs[..256] / Q8K.bsums, and // GRID[..] indices are (u8 | 11 bits) < 2048 = GRID.len(). Gate: avx2_ok(). -const FP4:[i8;16]=[0,1,2,3,4,6,8,12,0,-1,-2,-3,-4,-6,-8,-12]; -#[target_feature(enable="avx2")] -unsafe fn signed_pairs(a:__m256i,b:__m256i)->__m256i{unsafe{_mm256_maddubs_epi16(_mm256_sign_epi8(a,a),_mm256_sign_epi8(b,a))}} -#[target_feature(enable="avx2")] -unsafe fn fp4(p:*const u8)->__m256i{unsafe{let q=_mm_loadu_si128(p.cast());let v=_mm_loadu_si128(FP4.as_ptr().cast());let lo=_mm_shuffle_epi8(v,_mm_and_si128(q,_mm_set1_epi8(15)));let hi=_mm_shuffle_epi8(v,_mm_and_si128(_mm_srli_epi16::<4>(q),_mm_set1_epi8(15)));_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(lo),hi)}} -fn e8_half(e:u8)->f32{f32::from_bits(if e<2{0x00200000u32<<(e as u32)}else{((e as u32)-1)<<23})} -fn ue4(e:u8)->f32{if e==0||e==127{return 0.0;}let exp=(e>>3)&15;let m=e&7;let raw=if exp==0{(m as f32)*f32::from_bits(118<<23)}else{(1.0+(m as f32)/8.0)*f32::from_bits(((exp as i32-7+127)as u32)<<23)};raw*0.5} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn mxfp4(row:&[u8],y:&[Q8Zero])->f32{unsafe{let mut a=_mm256_setzero_ps();let mut b=a;let mut i=0;while i+1>4)as usize]as i32;}s+=(half(y[i].d)*e8_half(x[0]))*(lo+hi)as f32;}s}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn nvfp4(row:&[u8],y:&[Q8Zero])->f32{unsafe{let mut a=_mm256_setzero_ps();for (i,x) in row.chunks_exact(36).enumerate(){for j in 0..2{let q=fp4(x.as_ptr().add(4+j*16));let lo=_mm256_castsi256_si128(q);let hi=_mm256_extracti128_si256::<1>(q);let q=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_unpacklo_epi64(lo,hi)),_mm_unpackhi_epi64(lo,hi));let p=_mm256_madd_epi16(signed_pairs(q,_mm256_loadu_si256(y[i*2+j].qs.as_ptr().cast())),_mm256_set1_epi16(1));let dy=half(y[i*2+j].d);let scales=_mm256_insertf128_ps::<1>(_mm256_castps128_ps256(_mm_set1_ps(ue4(x[j*2])*dy)),_mm_set1_ps(ue4(x[j*2+1])*dy));a=_mm256_fmadd_ps(scales,_mm256_cvtepi32_ps(p),a);}}hsum_ggml(a)}} +const FP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12]; +#[target_feature(enable = "avx2")] +unsafe fn signed_pairs(a: __m256i, b: __m256i) -> __m256i { + unsafe { _mm256_maddubs_epi16(_mm256_sign_epi8(a, a), _mm256_sign_epi8(b, a)) } +} +#[target_feature(enable = "avx2")] +unsafe fn fp4(p: *const u8) -> __m256i { + unsafe { + let q = _mm_loadu_si128(p.cast()); + let v = _mm_loadu_si128(FP4.as_ptr().cast()); + let lo = _mm_shuffle_epi8(v, _mm_and_si128(q, _mm_set1_epi8(15))); + let hi = _mm_shuffle_epi8(v, _mm_and_si128(_mm_srli_epi16::<4>(q), _mm_set1_epi8(15))); + _mm256_inserti128_si256::<1>(_mm256_castsi128_si256(lo), hi) + } +} +fn e8_half(e: u8) -> f32 { + f32::from_bits(if e < 2 { 0x00200000u32 << (e as u32) } else { ((e as u32) - 1) << 23 }) +} +fn ue4(e: u8) -> f32 { + if e == 0 || e == 127 { + return 0.0; + } + let exp = (e >> 3) & 15; + let m = e & 7; + let raw = if exp == 0 { + (m as f32) * f32::from_bits(118 << 23) + } else { + (1.0 + (m as f32) / 8.0) * f32::from_bits(((exp as i32 - 7 + 127) as u32) << 23) + }; + raw * 0.5 +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn mxfp4(row: &[u8], y: &[Q8Zero]) -> f32 { + unsafe { + let mut a = _mm256_setzero_ps(); + let mut b = a; + let mut i = 0; + while i + 1 < y.len() { + for (j, acc) in [(i, &mut a), (i + 1, &mut b)] { + let x = &row[j * 17..(j + 1) * 17]; + let p = _mm256_madd_epi16( + signed_pairs(fp4(x.as_ptr().add(1)), _mm256_loadu_si256(y[j].qs.as_ptr().cast())), + _mm256_set1_epi16(1), + ); + *acc = _mm256_fmadd_ps(_mm256_set1_ps(half(y[j].d) * e8_half(x[0])), _mm256_cvtepi32_ps(p), *acc); + } + i += 2; + } + let mut s = hsum_ggml(_mm256_add_ps(a, b)); + if i < y.len() { + let x = &row[i * 17..]; + let mut lo = 0i32; + let mut hi = 0i32; + for j in 0..16 { + lo += y[i].qs[j] as i32 * FP4[(x[1 + j] & 15) as usize] as i32; + hi += y[i].qs[j + 16] as i32 * FP4[(x[1 + j] >> 4) as usize] as i32; + } + s += (half(y[i].d) * e8_half(x[0])) * (lo + hi) as f32; + } + s + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn nvfp4(row: &[u8], y: &[Q8Zero]) -> f32 { + unsafe { + let mut a = _mm256_setzero_ps(); + for (i, x) in row.chunks_exact(36).enumerate() { + for j in 0..2 { + let q = fp4(x.as_ptr().add(4 + j * 16)); + let lo = _mm256_castsi256_si128(q); + let hi = _mm256_extracti128_si256::<1>(q); + let q = _mm256_inserti128_si256::<1>( + _mm256_castsi128_si256(_mm_unpacklo_epi64(lo, hi)), + _mm_unpackhi_epi64(lo, hi), + ); + let p = _mm256_madd_epi16( + signed_pairs(q, _mm256_loadu_si256(y[i * 2 + j].qs.as_ptr().cast())), + _mm256_set1_epi16(1), + ); + let dy = half(y[i * 2 + j].d); + let scales = _mm256_insertf128_ps::<1>( + _mm256_castps128_ps256(_mm_set1_ps(ue4(x[j * 2]) * dy)), + _mm_set1_ps(ue4(x[j * 2 + 1]) * dy), + ); + a = _mm256_fmadd_ps(scales, _mm256_cvtepi32_ps(p), a); + } + } + hsum_ggml(a) + } +} // Exactly the byte multiply/subs/avg/shift sequence in pinned tq1_0 AVX2. -fn trit(q:u8)->u8{let a=q.saturating_sub(1)as u16;let avg=(a+1)/2;(((a+avg+1)/2)>>6)as u8&3} -#[target_feature(enable="avx2,f16c")] -pub(super) unsafe fn ternary(kind:i32,row:&[u8],ys:&[Q8K])->f32{unsafe{let mut acc=_mm256_setzero_ps();let size=if kind==34{54}else{66};for (x,y) in row.chunks_exact(size).zip(ys){let mut sums=[_mm256_setzero_si256();3];if kind==35{for j in [0,32]{let mut q=[[0u8;32];4];for k in 0..4{for b in 0..32{q[k][b]=(x[j+b]>>(2*k))&3;}}let mut p=[_mm256_setzero_si256();4];for k in 0..4{p[k]=_mm256_maddubs_epi16(_mm256_loadu_si256(q[k].as_ptr().cast()),_mm256_loadu_si256(y.qs.as_ptr().add(j*4+k*32).cast()));}sums[0]=_mm256_add_epi16(sums[0],_mm256_add_epi16(p[0],p[1]));sums[1]=_mm256_add_epi16(sums[1],_mm256_add_epi16(p[2],p[3]));}sums[0]=_mm256_sub_epi16(_mm256_add_epi16(sums[0],sums[1]),_mm256_loadu_si256(y.bsums.as_ptr().cast()));}else{let powers=[1u8,3,9,27,81];let mut p=[_mm256_setzero_si256();5];for k in 0..5{let mut q=[0u8;32];for b in 0..32{q[b]=trit(x[b].wrapping_mul(powers[k]));}p[k]=_mm256_maddubs_epi16(_mm256_loadu_si256(q.as_ptr().cast()),_mm256_loadu_si256(y.qs.as_ptr().add(k*32).cast()));}sums[0]=_mm256_add_epi16(sums[0],_mm256_add_epi16(p[0],p[1]));sums[1]=_mm256_add_epi16(sums[1],_mm256_add_epi16(p[2],p[3]));sums[2]=_mm256_add_epi16(sums[2],p[4]);for k in 0..3{let mut q=[0u8;32];for b in 0..32{let group=k*2+b/16;let v=if group<5{x[32+b%16].wrapping_mul(powers[group])}else{x[48+b%4].wrapping_mul(powers[(b%16)/4])};q[b]=trit(v);}let p=_mm256_maddubs_epi16(_mm256_loadu_si256(q.as_ptr().cast()),_mm256_loadu_si256(y.qs.as_ptr().add(160+k*32).cast()));sums[k]=_mm256_add_epi16(sums[k],p);}sums[0]=_mm256_sub_epi16(sums[0],_mm256_loadu_si256(y.bsums.as_ptr().cast()));sums[0]=_mm256_add_epi16(sums[0],_mm256_add_epi16(sums[1],sums[2]));}let p=_mm256_madd_epi16(sums[0],_mm256_set1_epi16(1));let d=_mm256_set1_ps(y.d*half(u16::from_le_bytes([x[size-2],x[size-1]])));acc=_mm256_add_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(p),d),acc);}hsum_ggml(acc)}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn iq1(kind:i32,row:&[u8],ys:&[Q8K])->f32{unsafe{let mut accum1=_mm256_setzero_ps();let mut accum2=accum1;let mut scalar=0.0;let size=if kind==19{50}else{56};for (x,y) in row.chunks_exact(size).zip(ys){let mut sums=[_mm256_setzero_si256();2];let mut corr=0i32;let mut scales=_mm256_setzero_si256();let d=if kind==19{y.d*half(u16::from_le_bytes([x[0],x[1]]))}else{let sc:[u16;4]=std::array::from_fn(|j|u16::from_le_bytes([x[48+j*2],x[49+j*2]]));let h=(sc[0]>>12)|((sc[1]>>8)&0x00f0)|((sc[2]>>4)&0x0f00)|(sc[3]&0xf000);let raw=u64::from_le_bytes(x[48..56].try_into().unwrap());scales=_mm256_srlv_epi64(_mm256_set1_epi64x(raw as i64),_mm256_set_epi64x(9,3,6,0));scales=_mm256_add_epi16(_mm256_slli_epi16::<1>(_mm256_and_si256(scales,_mm256_set1_epi16(7))),_mm256_set1_epi16(1));y.d*half(h)}; -let mut idx1=_mm256_set1_epi16(0x0100);let mut idx2=_mm256_add_epi8(idx1,_mm256_set1_epi8(8)); -for ib in (0..8).step_by(2){let mut products=[_mm256_setzero_si256();2];let mut corrections=products;for k in 0..2{let group=ib+k;let mut grid=[0u64;4];let mut signs=[1i8;32];let ls;if kind==19{let h=u16::from_le_bytes([x[34+group*2],x[35+group*2]]);for j in 0..4{let high=match j{0=>(h<<8)&0x700,1=>(h<<5)&0x700,2=>(h<<2)&0x700,_=>(h>>1)&0x700};grid[j]=GRID[x[2+group*4+j]as usize|high as usize];}ls=_mm256_set1_epi16((2*((h>>12)&7)+1)as i16);corr+=(y.bsums[group*2]as i32+y.bsums[group*2+1]as i32)*if h&0x8000!=0{-1}else{1}*(2*((h>>12)&7)+1)as i32;}else{for j in 0..4{let h=x[32+group*2+j/2];let hi=if j%2==0{((h as u16)<<8)&0x700}else{((h as u16)<<4)&0x700};grid[j]=GRID[x[group*4+j]as usize|hi as usize];for v in &mut signs[j*8..j*8+8]{*v=if h&(if j%2==0{8}else{128})!=0{-1}else{1};}}ls=_mm256_shuffle_epi8(scales,if k==0{idx1}else{idx2});}let q=_mm256_loadu_si256(y.qs.as_ptr().add(group*32).cast());let g=_mm256_loadu_si256(grid.as_ptr().cast());products[k]=_mm256_madd_epi16(signed_pairs(g,q),ls);if kind==29{let delta=_mm256_loadu_si256(signs.as_ptr().cast());let c=_mm256_maddubs_epi16(_mm256_set1_epi8(1),_mm256_sign_epi8(q,delta));corrections[k]=_mm256_madd_epi16(c,ls);}} -sums[0]=_mm256_add_epi32(sums[0],_mm256_add_epi32(products[0],products[1]));sums[1]=_mm256_add_epi32(sums[1],_mm256_add_epi32(corrections[0],corrections[1]));idx1=_mm256_add_epi8(idx1,_mm256_set1_epi8(2));idx2=_mm256_add_epi8(idx2,_mm256_set1_epi8(2));}let dv=_mm256_set1_ps(d);accum1=_mm256_fmadd_ps(dv,_mm256_cvtepi32_ps(sums[0]),accum1);if kind==19{scalar+=d*corr as f32;}else{accum2=_mm256_fmadd_ps(dv,_mm256_cvtepi32_ps(sums[1]),accum2);}}if kind==19{hsum_ggml(accum1)+0.125*scalar}else{hsum_ggml(accum1)+0.125*hsum_ggml(accum2)}}} +fn trit(q: u8) -> u8 { + let a = q.saturating_sub(1) as u16; + let avg = (a + 1) / 2; + (((a + avg + 1) / 2) >> 6) as u8 & 3 +} +#[target_feature(enable = "avx2,f16c")] +pub(super) unsafe fn ternary(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 { + unsafe { + let mut acc = _mm256_setzero_ps(); + let size = if kind == 34 { 54 } else { 66 }; + for (x, y) in row.chunks_exact(size).zip(ys) { + let mut sums = [_mm256_setzero_si256(); 3]; + if kind == 35 { + for j in [0, 32] { + let mut q = [[0u8; 32]; 4]; + for k in 0..4 { + for b in 0..32 { + q[k][b] = (x[j + b] >> (2 * k)) & 3; + } + } + let mut p = [_mm256_setzero_si256(); 4]; + for k in 0..4 { + p[k] = _mm256_maddubs_epi16( + _mm256_loadu_si256(q[k].as_ptr().cast()), + _mm256_loadu_si256(y.qs.as_ptr().add(j * 4 + k * 32).cast()), + ); + } + sums[0] = _mm256_add_epi16(sums[0], _mm256_add_epi16(p[0], p[1])); + sums[1] = _mm256_add_epi16(sums[1], _mm256_add_epi16(p[2], p[3])); + } + sums[0] = + _mm256_sub_epi16(_mm256_add_epi16(sums[0], sums[1]), _mm256_loadu_si256(y.bsums.as_ptr().cast())); + } else { + let powers = [1u8, 3, 9, 27, 81]; + let mut p = [_mm256_setzero_si256(); 5]; + for k in 0..5 { + let mut q = [0u8; 32]; + for b in 0..32 { + q[b] = trit(x[b].wrapping_mul(powers[k])); + } + p[k] = _mm256_maddubs_epi16( + _mm256_loadu_si256(q.as_ptr().cast()), + _mm256_loadu_si256(y.qs.as_ptr().add(k * 32).cast()), + ); + } + sums[0] = _mm256_add_epi16(sums[0], _mm256_add_epi16(p[0], p[1])); + sums[1] = _mm256_add_epi16(sums[1], _mm256_add_epi16(p[2], p[3])); + sums[2] = _mm256_add_epi16(sums[2], p[4]); + for k in 0..3 { + let mut q = [0u8; 32]; + for b in 0..32 { + let group = k * 2 + b / 16; + let v = if group < 5 { + x[32 + b % 16].wrapping_mul(powers[group]) + } else { + x[48 + b % 4].wrapping_mul(powers[(b % 16) / 4]) + }; + q[b] = trit(v); + } + let p = _mm256_maddubs_epi16( + _mm256_loadu_si256(q.as_ptr().cast()), + _mm256_loadu_si256(y.qs.as_ptr().add(160 + k * 32).cast()), + ); + sums[k] = _mm256_add_epi16(sums[k], p); + } + sums[0] = _mm256_sub_epi16(sums[0], _mm256_loadu_si256(y.bsums.as_ptr().cast())); + sums[0] = _mm256_add_epi16(sums[0], _mm256_add_epi16(sums[1], sums[2])); + } + let p = _mm256_madd_epi16(sums[0], _mm256_set1_epi16(1)); + let d = _mm256_set1_ps(y.d * half(u16::from_le_bytes([x[size - 2], x[size - 1]]))); + acc = _mm256_add_ps(_mm256_mul_ps(_mm256_cvtepi32_ps(p), d), acc); + } + hsum_ggml(acc) + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn iq1(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 { + unsafe { + let mut accum1 = _mm256_setzero_ps(); + let mut accum2 = accum1; + let mut scalar = 0.0; + let size = if kind == 19 { 50 } else { 56 }; + for (x, y) in row.chunks_exact(size).zip(ys) { + let mut sums = [_mm256_setzero_si256(); 2]; + let mut corr = 0i32; + let mut scales = _mm256_setzero_si256(); + let d = if kind == 19 { + y.d * half(u16::from_le_bytes([x[0], x[1]])) + } else { + let sc: [u16; 4] = std::array::from_fn(|j| u16::from_le_bytes([x[48 + j * 2], x[49 + j * 2]])); + let h = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); + let raw = u64::from_le_bytes(x[48..56].try_into().unwrap()); + scales = _mm256_srlv_epi64(_mm256_set1_epi64x(raw as i64), _mm256_set_epi64x(9, 3, 6, 0)); + scales = _mm256_add_epi16( + _mm256_slli_epi16::<1>(_mm256_and_si256(scales, _mm256_set1_epi16(7))), + _mm256_set1_epi16(1), + ); + y.d * half(h) + }; + let mut idx1 = _mm256_set1_epi16(0x0100); + let mut idx2 = _mm256_add_epi8(idx1, _mm256_set1_epi8(8)); + for ib in (0..8).step_by(2) { + let mut products = [_mm256_setzero_si256(); 2]; + let mut corrections = products; + for k in 0..2 { + let group = ib + k; + let mut grid = [0u64; 4]; + let mut signs = [1i8; 32]; + let ls; + if kind == 19 { + let h = u16::from_le_bytes([x[34 + group * 2], x[35 + group * 2]]); + for j in 0..4 { + let high = match j { + 0 => (h << 8) & 0x700, + 1 => (h << 5) & 0x700, + 2 => (h << 2) & 0x700, + _ => (h >> 1) & 0x700, + }; + grid[j] = GRID[x[2 + group * 4 + j] as usize | high as usize]; + } + ls = _mm256_set1_epi16((2 * ((h >> 12) & 7) + 1) as i16); + corr += (y.bsums[group * 2] as i32 + y.bsums[group * 2 + 1] as i32) + * if h & 0x8000 != 0 { -1 } else { 1 } + * (2 * ((h >> 12) & 7) + 1) as i32; + } else { + for j in 0..4 { + let h = x[32 + group * 2 + j / 2]; + let hi = if j % 2 == 0 { ((h as u16) << 8) & 0x700 } else { ((h as u16) << 4) & 0x700 }; + grid[j] = GRID[x[group * 4 + j] as usize | hi as usize]; + for v in &mut signs[j * 8..j * 8 + 8] { + *v = if h & (if j % 2 == 0 { 8 } else { 128 }) != 0 { -1 } else { 1 }; + } + } + ls = _mm256_shuffle_epi8(scales, if k == 0 { idx1 } else { idx2 }); + } + let q = _mm256_loadu_si256(y.qs.as_ptr().add(group * 32).cast()); + let g = _mm256_loadu_si256(grid.as_ptr().cast()); + products[k] = _mm256_madd_epi16(signed_pairs(g, q), ls); + if kind == 29 { + let delta = _mm256_loadu_si256(signs.as_ptr().cast()); + let c = _mm256_maddubs_epi16(_mm256_set1_epi8(1), _mm256_sign_epi8(q, delta)); + corrections[k] = _mm256_madd_epi16(c, ls); + } + } + sums[0] = _mm256_add_epi32(sums[0], _mm256_add_epi32(products[0], products[1])); + sums[1] = _mm256_add_epi32(sums[1], _mm256_add_epi32(corrections[0], corrections[1])); + idx1 = _mm256_add_epi8(idx1, _mm256_set1_epi8(2)); + idx2 = _mm256_add_epi8(idx2, _mm256_set1_epi8(2)); + } + let dv = _mm256_set1_ps(d); + accum1 = _mm256_fmadd_ps(dv, _mm256_cvtepi32_ps(sums[0]), accum1); + if kind == 19 { + scalar += d * corr as f32; + } else { + accum2 = _mm256_fmadd_ps(dv, _mm256_cvtepi32_ps(sums[1]), accum2); + } + } + if kind == 19 { hsum_ggml(accum1) + 0.125 * scalar } else { hsum_ggml(accum1) + 0.125 * hsum_ggml(accum2) } + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml_native.rs b/crates/native-cpu-expert/src/rust_ggml_native.rs index 2199547d..eb622215 100644 --- a/crates/native-cpu-expert/src/rust_ggml_native.rs +++ b/crates/native-cpu-expert/src/rust_ggml_native.rs @@ -1,8 +1,8 @@ //! Pinned GGML native x86 compiler branches; no caller-selected ISA/math policy. //! The integration patch keeps the original AVX2 bodies as the unselected branch. +use super::rust_ggml::Kind; use std::arch::{asm, x86_64::*}; use std::sync::OnceLock; -use super::rust_ggml::Kind; // These correspond to actual GGML compiler macros, not a runtime highest-ISA // heuristic. Root must seal compiler features together with the Original build. @@ -22,23 +22,45 @@ fn probe() -> bool { // No STRATA_FORCE_AVX2 read here: that flag only controls Original explicit // IQ/Q2 dispatch and does not change compiled GGML type-trait arithmetic. unsafe { - if __cpuid(0).eax < 7 { return false; } + if __cpuid(0).eax < 7 { + return false; + } let c = __cpuid(1).ecx; - if [12, 27, 28, 29].iter().any(|b| c & (1 << b) == 0) { return false; } + if [12, 27, 28, 29].iter().any(|b| c & (1 << b) == 0) { + return false; + } let xcr = _xgetbv(0); - if xcr & 6 != 6 { return false; } + if xcr & 6 != 6 { + return false; + } let p = __cpuid_count(7, 0); - if p.ebx & (1 << 5) == 0 { return false; } + if p.ebx & (1 << 5) == 0 { + return false; + } let wide = F || BF || PH || V512; - if wide && (xcr & 0xe6 != 0xe6 || p.ebx & (1 << 16) == 0) { return false; } - if PH && p.edx & (1 << 23) == 0 { return false; } - if V512 && (p.ebx & (1 << 31) == 0 || p.ecx & (1 << 11) == 0) { return false; } + if wide && (xcr & 0xe6 != 0xe6 || p.ebx & (1 << 16) == 0) { + return false; + } + if PH && p.edx & (1 << 23) == 0 { + return false; + } + if V512 && (p.ebx & (1 << 31) == 0 || p.ecx & (1 << 11) == 0) { + return false; + } if BF || V256 || SIGNED { - if p.eax < 1 { return false; } + if p.eax < 1 { + return false; + } let p1 = __cpuid_count(7, 1); - if BF && p1.eax & (1 << 5) == 0 { return false; } - if V256 && p1.eax & (1 << 4) == 0 { return false; } - if SIGNED && p1.edx & (1 << 4) == 0 { return false; } + if BF && p1.eax & (1 << 5) == 0 { + return false; + } + if V256 && p1.eax & (1 << 4) == 0 { + return false; + } + if SIGNED && p1.edx & (1 << 4) == 0 { + return false; + } } true } @@ -60,73 +82,110 @@ pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) -> } #[target_feature(enable = "avx512f,avx2")] -unsafe fn f32_dot(row: &[u8], y: &[f32]) -> f32 { unsafe { - let n = y.len(); let np = n & !63; - let mut a = [_mm512_setzero_ps(); 4]; - for i in (0..np).step_by(64) { - for (j, a) in a.iter_mut().enumerate() { - let k = i + j * 16; - *a = _mm512_fmadd_ps(_mm512_loadu_ps(row.as_ptr().add(k * 4).cast()), - _mm512_loadu_ps(y.as_ptr().add(k)), *a); +unsafe fn f32_dot(row: &[u8], y: &[f32]) -> f32 { + unsafe { + let n = y.len(); + let np = n & !63; + let mut a = [_mm512_setzero_ps(); 4]; + for i in (0..np).step_by(64) { + for (j, a) in a.iter_mut().enumerate() { + let k = i + j * 16; + *a = _mm512_fmadd_ps( + _mm512_loadu_ps(row.as_ptr().add(k * 4).cast()), + _mm512_loadu_ps(y.as_ptr().add(k)), + *a, + ); + } } + let mut s = _mm512_reduce_add_ps(_mm512_add_ps(_mm512_add_ps(a[0], a[2]), _mm512_add_ps(a[1], a[3]))); + for i in np..n { + s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * y[i]; + } + s } - let mut s = _mm512_reduce_add_ps(_mm512_add_ps(_mm512_add_ps(a[0], a[2]), _mm512_add_ps(a[1], a[3]))); - for i in np..n { s += f32::from_le_bytes(row[i*4..i*4+4].try_into().unwrap()) * y[i]; } - s -}} +} #[target_feature(enable = "avx512f,avx2,f16c")] -unsafe fn f16_dot(row: &[u8], y: &[u16]) -> f32 { unsafe { - let n = y.len(); let np = n & !63; - let mut a = [_mm512_setzero_ps(); 4]; - for i in (0..np).step_by(64) { - for (j, a) in a.iter_mut().enumerate() { - let k = i + j * 16; - *a = _mm512_fmadd_ps(_mm512_cvtph_ps(_mm256_loadu_si256(row.as_ptr().add(k*2).cast())), - _mm512_cvtph_ps(_mm256_loadu_si256(y.as_ptr().add(k).cast())), *a); +unsafe fn f16_dot(row: &[u8], y: &[u16]) -> f32 { + unsafe { + let n = y.len(); + let np = n & !63; + let mut a = [_mm512_setzero_ps(); 4]; + for i in (0..np).step_by(64) { + for (j, a) in a.iter_mut().enumerate() { + let k = i + j * 16; + *a = _mm512_fmadd_ps( + _mm512_cvtph_ps(_mm256_loadu_si256(row.as_ptr().add(k * 2).cast())), + _mm512_cvtph_ps(_mm256_loadu_si256(y.as_ptr().add(k).cast())), + *a, + ); + } } + let mut s = _mm512_reduce_add_ps(_mm512_add_ps(_mm512_add_ps(a[0], a[2]), _mm512_add_ps(a[1], a[3]))) as f64; + for i in np..n { + s += (super::rust_simd::half(u16::from_le_bytes([row[i * 2], row[i * 2 + 1]])) + * super::rust_simd::half(y[i])) as f64; + } + s as f32 } - let mut s = _mm512_reduce_add_ps(_mm512_add_ps(_mm512_add_ps(a[0], a[2]), _mm512_add_ps(a[1], a[3]))) as f64; - for i in np..n { s += (super::rust_simd::half(u16::from_le_bytes([row[i*2],row[i*2+1]])) * super::rust_simd::half(y[i])) as f64; } - s as f32 -}} +} #[target_feature(enable = "avx512f,avx512bf16")] -unsafe fn bf16_dot(row: &[u8], y: &[u16]) -> f32 { unsafe { - let mut i = 0; let mut a = _mm512_setzero_ps(); let mut b = a; - while i + 64 <= y.len() { - a = _mm512_dpbf16_ps(a, std::mem::transmute::<__m512i,__m512bh>(_mm512_loadu_si512(row.as_ptr().add(i*2).cast())), - std::mem::transmute::<__m512i,__m512bh>(_mm512_loadu_si512(y.as_ptr().add(i).cast()))); - b = _mm512_dpbf16_ps(b, std::mem::transmute::<__m512i,__m512bh>(_mm512_loadu_si512(row.as_ptr().add((i+32)*2).cast())), - std::mem::transmute::<__m512i,__m512bh>(_mm512_loadu_si512(y.as_ptr().add(i+32).cast()))); - i += 64; +unsafe fn bf16_dot(row: &[u8], y: &[u16]) -> f32 { + unsafe { + let mut i = 0; + let mut a = _mm512_setzero_ps(); + let mut b = a; + while i + 64 <= y.len() { + a = _mm512_dpbf16_ps( + a, + std::mem::transmute::<__m512i, __m512bh>(_mm512_loadu_si512(row.as_ptr().add(i * 2).cast())), + std::mem::transmute::<__m512i, __m512bh>(_mm512_loadu_si512(y.as_ptr().add(i).cast())), + ); + b = _mm512_dpbf16_ps( + b, + std::mem::transmute::<__m512i, __m512bh>(_mm512_loadu_si512(row.as_ptr().add((i + 32) * 2).cast())), + std::mem::transmute::<__m512i, __m512bh>(_mm512_loadu_si512(y.as_ptr().add(i + 32).cast())), + ); + i += 64; + } + let mut s = 0.0f64; + s += _mm512_reduce_add_ps(a) as f64; + s += _mm512_reduce_add_ps(b) as f64; + bf16_tail(row, y, i, s) } - let mut s = 0.0f64; - s += _mm512_reduce_add_ps(a) as f64; - s += _mm512_reduce_add_ps(b) as f64; - bf16_tail(row, y, i, s) -}} +} #[target_feature(enable = "avx512f,avx2")] -unsafe fn bf16_load(p: *const u8) -> __m512 { unsafe { - _mm512_castsi512_ps(_mm512_slli_epi32::<16>(_mm512_cvtepu16_epi32(_mm256_loadu_si256(p.cast())))) -}} +unsafe fn bf16_load(p: *const u8) -> __m512 { + unsafe { _mm512_castsi512_ps(_mm512_slli_epi32::<16>(_mm512_cvtepu16_epi32(_mm256_loadu_si256(p.cast())))) } +} #[target_feature(enable = "avx512f,avx2")] -unsafe fn bf16_f_dot(row: &[u8], y: &[u16]) -> f32 { unsafe { - let mut i = 0; let mut a = _mm512_setzero_ps(); let mut b = a; - while i + 32 <= y.len() { - a = _mm512_add_ps(_mm512_mul_ps(bf16_load(row.as_ptr().add(i*2)), bf16_load(y.as_ptr().add(i).cast())), a); - b = _mm512_add_ps(_mm512_mul_ps(bf16_load(row.as_ptr().add((i+16)*2)), bf16_load(y.as_ptr().add(i+16).cast())), b); - i += 32; +unsafe fn bf16_f_dot(row: &[u8], y: &[u16]) -> f32 { + unsafe { + let mut i = 0; + let mut a = _mm512_setzero_ps(); + let mut b = a; + while i + 32 <= y.len() { + a = _mm512_add_ps( + _mm512_mul_ps(bf16_load(row.as_ptr().add(i * 2)), bf16_load(y.as_ptr().add(i).cast())), + a, + ); + b = _mm512_add_ps( + _mm512_mul_ps(bf16_load(row.as_ptr().add((i + 16) * 2)), bf16_load(y.as_ptr().add(i + 16).cast())), + b, + ); + i += 32; + } + let mut s = 0.0f64; + s += _mm512_reduce_add_ps(a) as f64; + s += _mm512_reduce_add_ps(b) as f64; + bf16_tail(row, y, i, s) } - let mut s = 0.0f64; - s += _mm512_reduce_add_ps(a) as f64; - s += _mm512_reduce_add_ps(b) as f64; - bf16_tail(row, y, i, s) -}} +} fn bf16_tail(row: &[u8], y: &[u16], i: usize, mut s: f64) -> f32 { for i in i..y.len() { - let x = f32::from_bits((u16::from_le_bytes([row[i*2],row[i*2+1]]) as u32) << 16); + let x = f32::from_bits((u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]) as u32) << 16); s += (x * f32::from_bits((y[i] as u32) << 16)) as f64; } s as f32 @@ -135,99 +194,138 @@ fn bf16_tail(row: &[u8], y: &[u16], i: usize, mut s: f64) -> f32 { // Stable Rust lacks stable __m512h/f16 intrinsics. These instruction-only leaves // keep the actual FP16 hardware accumulator rather than widening it to F32. #[target_feature(enable = "avx512f")] -unsafe fn ph_fma(mut a: __m512i, x: __m512i, y: __m512i) -> __m512i { unsafe { - asm!("vfmadd231ph {a}, {x}, {y}", a = inout(zmm_reg) a, x = in(zmm_reg) x, y = in(zmm_reg) y, +unsafe fn ph_fma(mut a: __m512i, x: __m512i, y: __m512i) -> __m512i { + unsafe { + asm!("vfmadd231ph {a}, {x}, {y}", a = inout(zmm_reg) a, x = in(zmm_reg) x, y = in(zmm_reg) y, options(pure, nomem, nostack)); - a -}} + a + } +} #[target_feature(enable = "avx512f")] -unsafe fn ph_add(a: __m512i, b: __m512i) -> __m512i { unsafe { - let c: __m512i; - asm!("vaddph {c}, {a}, {b}", c = out(zmm_reg) c, a = in(zmm_reg) a, b = in(zmm_reg) b, +unsafe fn ph_add(a: __m512i, b: __m512i) -> __m512i { + unsafe { + let c: __m512i; + asm!("vaddph {c}, {a}, {b}", c = out(zmm_reg) c, a = in(zmm_reg) a, b = in(zmm_reg) b, options(pure, nomem, nostack)); - c -}} + c + } +} #[target_feature(enable = "avx512f")] -unsafe fn ph_add_prefix(a: __m512i, b: __m512i, mask: u16) -> __m512i { unsafe { - let c: __m512i; - // The shrinking reduction only evaluates the retained lanes. kreg uses - // kmovw, zeroing the high mask bits; no AVX512BW/VL instructions are needed. - asm!("vaddph {c} {{{mask}}}{{z}}, {a}, {b}", c = out(zmm_reg) c, +unsafe fn ph_add_prefix(a: __m512i, b: __m512i, mask: u16) -> __m512i { + unsafe { + let c: __m512i; + // The shrinking reduction only evaluates the retained lanes. kreg uses + // kmovw, zeroing the high mask bits; no AVX512BW/VL instructions are needed. + asm!("vaddph {c} {{{mask}}}{{z}}, {a}, {b}", c = out(zmm_reg) c, mask = in(kreg) mask, a = in(zmm_reg) a, b = in(zmm_reg) b, options(pure, nomem, nostack)); - c -}} + c + } +} #[target_feature(enable = "avx512f,f16c")] -unsafe fn ph_reduce(mut a: __m512i) -> f32 { unsafe { - // Same halve-and-add tree as _mm512_reduce_add_ph; each node is actual - // half addition, including its rounding/overflow, not a float emulation. - for offset in [16, 8, 4, 2, 1] { - let words = std::mem::transmute::<__m512i,[u16;32]>(a); - let mut other = [0u16;32]; - other[..offset].copy_from_slice(&words[offset..2*offset]); - a = ph_add_prefix(a, std::mem::transmute::<[u16;32],__m512i>(other), ((1u32 << offset)-1) as u16); - } - super::rust_simd::half(std::mem::transmute::<__m512i,[u16;32]>(a)[0]) -}} -#[target_feature(enable = "avx512f,avx2,f16c")] -unsafe fn f16_ph_dot(row: &[u8], y: &[u16]) -> f32 { unsafe { - let n = y.len(); let np = n & !127; - let mut a = [_mm512_setzero_si512();4]; - for i in (0..np).step_by(128) { - for (j, a) in a.iter_mut().enumerate() { - let k = i + j*32; - *a = ph_fma(*a, _mm512_loadu_si512(row.as_ptr().add(k*2).cast()), _mm512_loadu_si512(y.as_ptr().add(k).cast())); +unsafe fn ph_reduce(mut a: __m512i) -> f32 { + unsafe { + // Same halve-and-add tree as _mm512_reduce_add_ph; each node is actual + // half addition, including its rounding/overflow, not a float emulation. + for offset in [16, 8, 4, 2, 1] { + let words = std::mem::transmute::<__m512i, [u16; 32]>(a); + let mut other = [0u16; 32]; + other[..offset].copy_from_slice(&words[offset..2 * offset]); + a = ph_add_prefix(a, std::mem::transmute::<[u16; 32], __m512i>(other), ((1u32 << offset) - 1) as u16); } + super::rust_simd::half(std::mem::transmute::<__m512i, [u16; 32]>(a)[0]) } - let mut s = ph_reduce(ph_add(ph_add(a[0],a[2]),ph_add(a[1],a[3]))) as f64; - for i in np..n { s += (super::rust_simd::half(u16::from_le_bytes([row[i*2],row[i*2+1]])) * super::rust_simd::half(y[i])) as f64; } - s as f32 -}} +} +#[target_feature(enable = "avx512f,avx2,f16c")] +unsafe fn f16_ph_dot(row: &[u8], y: &[u16]) -> f32 { + unsafe { + let n = y.len(); + let np = n & !127; + let mut a = [_mm512_setzero_si512(); 4]; + for i in (0..np).step_by(128) { + for (j, a) in a.iter_mut().enumerate() { + let k = i + j * 32; + *a = ph_fma( + *a, + _mm512_loadu_si512(row.as_ptr().add(k * 2).cast()), + _mm512_loadu_si512(y.as_ptr().add(k).cast()), + ); + } + } + let mut s = ph_reduce(ph_add(ph_add(a[0], a[2]), ph_add(a[1], a[3]))) as f64; + for i in np..n { + s += (super::rust_simd::half(u16::from_le_bytes([row[i * 2], row[i * 2 + 1]])) + * super::rust_simd::half(y[i])) as f64; + } + s as f32 + } +} pub(super) unsafe fn convert_bf16(x: &[f32], y: &mut [u16]) -> bool { // bf16_convert stores 32 u16 per step through a raw pointer; keep the destination at least as long as the source. assert_eq!(x.len(), y.len()); - if !BF { return false; } + if !BF { + return false; + } // Actual caller owns initialized length-matched destination and admitted CPU. - unsafe { bf16_convert(x, y); } + unsafe { + bf16_convert(x, y); + } true } #[target_feature(enable = "avx512f,avx512bf16")] -unsafe fn bf16_convert(x: &[f32], y: &mut [u16]) { unsafe { - let mut i = 0; - while i + 32 <= x.len() { - let b = _mm512_cvtne2ps_pbh(_mm512_loadu_ps(x.as_ptr().add(i+16)), _mm512_loadu_ps(x.as_ptr().add(i))); - _mm512_storeu_si512(y.as_mut_ptr().add(i).cast(), std::mem::transmute::<__m512bh,__m512i>(b)); - i += 32; +unsafe fn bf16_convert(x: &[f32], y: &mut [u16]) { + unsafe { + let mut i = 0; + while i + 32 <= x.len() { + let b = _mm512_cvtne2ps_pbh(_mm512_loadu_ps(x.as_ptr().add(i + 16)), _mm512_loadu_ps(x.as_ptr().add(i))); + _mm512_storeu_si512(y.as_mut_ptr().add(i).cast(), std::mem::transmute::<__m512bh, __m512i>(b)); + i += 32; + } + // GGML scalar tail: NaNs quieted, round-to-nearest-even. The vector body + // has hardware subnormal flushing and is deliberately not replaced by this. + for i in i..x.len() { + let b = x[i].to_bits(); + y[i] = if b & 0x7fff_ffff > 0x7f80_0000 { + ((b >> 16) | 64) as u16 + } else { + (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 + }; + } } - // GGML scalar tail: NaNs quieted, round-to-nearest-even. The vector body - // has hardware subnormal flushing and is deliberately not replaced by this. - for i in i..x.len() { let b = x[i].to_bits(); y[i] = if b & 0x7fff_ffff > 0x7f80_0000 { - ((b >> 16) | 64) as u16 - } else { (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 }; } -}} +} // Generic GGML small_dot only. Explicit Original KQ multi-row helpers retain // their own AVX2 maddubs/madd sequence, independent of compiler VNNI macros. #[target_feature(enable = "avx2")] -pub(super) unsafe fn unsigned_pairs(x: __m256i, y: __m256i) -> Option<__m256> { unsafe { - if V512 { Some(unsigned_v512(x,y)) } else if V256 { Some(unsigned_v256(x,y)) } else { None } -}} +pub(super) unsafe fn unsigned_pairs(x: __m256i, y: __m256i) -> Option<__m256> { + unsafe { + if V512 { + Some(unsigned_v512(x, y)) + } else if V256 { + Some(unsigned_v256(x, y)) + } else { + None + } + } +} #[target_feature(enable = "avx512vnni,avx512vl,avx2")] -unsafe fn unsigned_v512(x: __m256i,y: __m256i) -> __m256 { - _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(),x,y)) +unsafe fn unsigned_v512(x: __m256i, y: __m256i) -> __m256 { + _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(), x, y)) } #[target_feature(enable = "avxvnni,avx2")] -unsafe fn unsigned_v256(x: __m256i,y: __m256i) -> __m256 { - _mm256_cvtepi32_ps(_mm256_dpbusd_avx_epi32(_mm256_setzero_si256(),x,y)) +unsafe fn unsigned_v256(x: __m256i, y: __m256i) -> __m256 { + _mm256_cvtepi32_ps(_mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), x, y)) } #[target_feature(enable = "avx2")] -pub(super) unsafe fn signed_pairs(x: __m256i,y: __m256i) -> Option<__m256> { unsafe { - if SIGNED { Some(signed_native(x,y)) } else { unsigned_pairs(_mm256_sign_epi8(x,x),_mm256_sign_epi8(y,x)) } -}} +pub(super) unsafe fn signed_pairs(x: __m256i, y: __m256i) -> Option<__m256> { + unsafe { + if SIGNED { Some(signed_native(x, y)) } else { unsigned_pairs(_mm256_sign_epi8(x, x), _mm256_sign_epi8(y, x)) } + } +} #[target_feature(enable = "avxvnniint8,avx2")] -unsafe fn signed_native(x: __m256i,y: __m256i) -> __m256 { - _mm256_cvtepi32_ps(_mm256_dpbssd_epi32(_mm256_setzero_si256(),x,y)) +unsafe fn signed_native(x: __m256i, y: __m256i) -> __m256 { + _mm256_cvtepi32_ps(_mm256_dpbssd_epi32(_mm256_setzero_si256(), x, y)) } #[cfg(test)] diff --git a/crates/native-cpu-expert/src/rust_iq.rs b/crates/native-cpu-expert/src/rust_iq.rs index 6e47902f..3233ef06 100644 --- a/crates/native-cpu-expert/src/rust_iq.rs +++ b/crates/native-cpu-expert/src/rust_iq.rs @@ -1,284 +1,50 @@ //! Literal integer format decode and distinct Original/GGML float reductions. -use std::arch::x86_64::*; use super::rust_codebooks::*; -use super::rust_types::{Q8K,Q8Zero}; -use super::rust_simd::{half,hsum_original,hsum_ggml,signs32,prefetch}; -// Bounds: `row` is walked with chunks_exact/checked slicing and every activation block is safe-indexed (`y[i]`), so a short -// operand panics instead of reading past it. The raw loads are 32/64 bytes at 64*j+32*h (j<4,h<2) of a 256-byte Q8K.qs, 16 -// bytes inside a block (<= block size), and the only data-dependent address is the optional gather: idx <= 255 into -// IQ3XXS_GRID[u32;256] and idx <= 511 into IQ3S_GRID[u32;512]. Gate: avx2_ok() / avx512_ok()+dq_ok(). -fn u16(b:&[u8],o:usize)->u16 {u16::from_le_bytes(b[o..o+2].try_into().unwrap())} -fn u32(b:&[u8],o:usize)->u32 {u32::from_le_bytes(b[o..o+4].try_into().unwrap())} -pub(super) fn format_bytes(t:i32)->usize {match t{16=>66,17=>74,18=>98,21=>110,22=>82,23=>136,_=>unreachable!()}} -fn factor(t:i32)->f32 {match t {16|17|22=>0.125,18=>0.25,21|23=>1.0,_=>unreachable!()}} -// Whole 32-value half: magnitude bytes, literal signs and 16-value integer scales. -#[inline(always)] -fn decode(t:i32,b:&[u8],j:usize,h:usize)->([u8;32],u32,[i16;16]) { - let mut g=[0u8;32];let mut signs=0u32;let (s0,s1); - match t { - 16=>{let a=u32(b,2+16*j+8*h);let w=u32(b,6+16*j+8*h);for l in 0..4 {g[l*8..l*8+8].copy_from_slice(&IQ2XXS_GRID[((a>>(8*l))&255) as usize].to_le_bytes());signs|=(KSIGNS_IQ2XS[((w>>(7*l))&127)as usize]as u32)<<(8*l);}let s=2*(w>>28)as i16+1;s0=s;s1=s;} - 17=>{for l in 0..4 {let v=u16(b,2+16*j+8*h+2*l);g[l*8..l*8+8].copy_from_slice(&IQ2XS_GRID[(v&511)as usize].to_le_bytes());signs|=(KSIGNS_IQ2XS[(v>>9)as usize]as u32)<<(8*l);}let s=b[66+2*j+h];s0=2*(s&15)as i16+1;s1=2*(s>>4)as i16+1;} - 22=>{let q=&b[2+8*j+4*h..];let high=b[66+2*j+h]as usize;for l in 0..4 {let idx=q[l]as usize|((high<<(8-2*l))&0x300);g[l*8..l*8+8].copy_from_slice(&IQ2S_GRID[idx].to_le_bytes());}signs=u32(b,34+8*j+4*h);let s=b[74+2*j+h];s0=2*(s&15)as i16+1;s1=2*(s>>4)as i16+1;} - 18=>{let q=&b[2+16*j+8*h..];for l in 0..8 {g[l*4..l*4+4].copy_from_slice(&IQ3XXS_GRID[q[l]as usize].to_le_bytes());}let w=u32(b,66+8*j+4*h);for l in 0..4 {signs|=(KSIGNS_IQ2XS[((w>>(7*l))&127)as usize]as u32)<<(8*l);}s0=2*(w>>28)as i16+1;s1=s0;} - 21=>{let q=&b[2+16*j+8*h..];let high=b[66+2*j+h]as usize;for l in 0..8 {g[l*4..l*4+4].copy_from_slice(&IQ3S_GRID[q[l]as usize|(((high>>l)&1)<<8)].to_le_bytes());}signs=u32(b,74+8*j+4*h);let s=b[106+j];s0=2*(if h==0{s&15}else{s>>4})as i16+1;s1=s0;} - // IQ4_XS (AVX2 multi-token tree only, STRA-324): iq_avx2.cpp Fmt32<23>::decode. `g` = |kvalues|, the sign bit = (kvalue<0) - // (no kvalue is 0), scale = the signed 6-bit sub-block scale ls-32 of sub-block 2j+h. - 23=>{let hh=2*j+h;let bits=&b[8+16*hh..8+16*hh+16];for l in 0..16 {let lo=KVALUES_IQ4NL[(bits[l]&15)as usize];let hi=KVALUES_IQ4NL[(bits[l]>>4)as usize];g[l]=lo.unsigned_abs();g[16+l]=hi.unsigned_abs();if lo<0{signs|=1<>1)]>>(4*(hh&1)))&15)as i16|((((u16(b,2)>>(2*hh))&3)as i16)<<4);s0=ls-32;s1=s0;} - _=>unreachable!() - } - let mut sc=[s0;16];sc[8..].fill(s1);(g,signs,sc) -} -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn decoded(t:i32,b:&[u8],j:usize,h:usize)->(__m256i,__m256i,__m256i) {unsafe { - let (g,s,sc)=decode(t,b,j,h);(_mm256_loadu_si256(g.as_ptr().cast()),signs32(s),_mm256_loadu_si256(sc.as_ptr().cast())) -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn dot_multi256(t:i32,row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe { - assert!(ys.len()<=8&&ys.len()==out.len());let nb=ys[0].len();assert_eq!(row.len(),nb*format_bytes(t)); - let mut accf=[_mm256_setzero_ps();8]; - for i in 0..nb { - let b=&row[i*format_bytes(t)..][..format_bytes(t)];prefetch(b.as_ptr());let mut ai=[_mm256_setzero_si256();8]; - for j in 0..4 {for h in 0..2 {let (g,sgn,sc)=decoded(t,b,j,h);for (k,y) in ys.iter().enumerate(){let v=_mm256_loadu_si256(y[i].qs.as_ptr().add(64*j+32*h).cast());let sy=_mm256_sign_epi8(v,sgn);ai[k]=_mm256_add_epi32(ai[k],_mm256_madd_epi16(_mm256_maddubs_epi16(g,sy),sc));}}} - let dx=half(u16(b,0))*factor(t);for (k,y) in ys.iter().enumerate(){accf[k]=_mm256_fmadd_ps(_mm256_set1_ps(dx*y[i].d),_mm256_cvtepi32_ps(ai[k]),accf[k]);} - } - for (k,r) in out.iter_mut().enumerate(){*r=hsum_original(accf[k]);} -}} -/// The multi-token IQ kernel, specialised on the format and the token count (iq_avx512.cpp templates its -/// `row_dot` the same way): the same operations in the same order per token, so the same bits. -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] -pub(super) unsafe fn dot_multi512(t:i32,row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe { - macro_rules! by_n {($T:literal)=>{match ys.len(){1=>dot_multi512_tn::<$T,1>(row,ys,out),2=>dot_multi512_tn::<$T,2>(row,ys,out),3=>dot_multi512_tn::<$T,3>(row,ys,out),4=>dot_multi512_tn::<$T,4>(row,ys,out),5=>dot_multi512_tn::<$T,5>(row,ys,out),6=>dot_multi512_tn::<$T,6>(row,ys,out),7=>dot_multi512_tn::<$T,7>(row,ys,out),8=>dot_multi512_tn::<$T,8>(row,ys,out),_=>panic!("dot_multi512: 1..=8 tokens")}}} - match t {16=>by_n!(16),17=>by_n!(17),18=>by_n!(18),21=>by_n!(21),22=>by_n!(22),_=>unreachable!()} -}} -/// `LELEKA_IQ_MULTI=register` (opt-in, measured SLOWER on the 9950X3D: 2 tokens 36.2 against 29.4 us of gate/up drain per expert in -/// `cpu_service_bench`, runs/cpu-service2 bench out-b) builds the multi-token AVX-512 IQ3 halves in registers; the default keeps the stack arrays. -fn iq3_multi_fast()->bool{static ON:std::sync::OnceLock=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var("LELEKA_IQ_MULTI").as_deref()==Ok("register"))} -/// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l, `decode`'s bytes 4l..4l+4), -/// the sign word `decode` returns and its (uniform) 16-bit scale. -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn iq3_half(b:&[u8],j:usize,h:usize)->(__m256i,u32,i16) { - let q=&b[2+16*j+8*h..2+16*j+8*h+8]; - if T==21 { - let high=b[66+2*j+h]as usize;let w=|l:usize|IQ3S_GRID[q[l]as usize|(((high>>l)&1)<<8)]as i32; - let sv=b[106+j]; - (_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),u32(b,74+8*j+4*h),2*(if h==0{sv&15}else{sv>>4})as i16+1) - } else { - let w=|l:usize|IQ3XXS_GRID[q[l]as usize]as i32;let ws=u32(b,66+8*j+4*h);let mut signs=0u32;for l in 0..4 {signs|=(KSIGNS_IQ2XS[((ws>>(7*l))&127)as usize]as u32)<<(8*l);} - (_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),signs,2*(ws>>28)as i16+1) - } -} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] -unsafe fn dot_multi512_tn(row:&[u8],ys:&[&[Q8K]],out:&mut [f32]) {unsafe {dot_multi512_impl::(row,ys,out,iq3_multi_fast())}} -/// `fast`: the register-built IQ3 halves (bitwise the stack-array decode, `iq3_multi_trees_are_bitwise_equal`; slower on Zen 5, opt-in). -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] -unsafe fn dot_multi512_impl(row:&[u8],ys:&[&[Q8K]],out:&mut [f32],fast:bool) {unsafe { - let t=T; - assert!(N<=8&&ys.len()==N&&out.len()==N);let nb=ys[0].len();assert_eq!(row.len(),nb*format_bytes(t));let mut af=[_mm512_setzero_ps();8];let zero=_mm512_setzero_si512(); - for i in 0..nb {let b=&row[i*format_bytes(t)..][..format_bytes(t)];prefetch(b.as_ptr());let mut ai=[_mm512_setzero_si512();8]; - for j in 0..4 { - // IQ3 formats (`iq3_multi_fast`): both halves' grid words straight into the 512-bit register, lane order = `decode`'s byte order - let reg=(T==21||T==18)&&fast&&!super::rust_simd::dispatch().gather; - let (gv,sv,m)=if reg { - let (g0,s0,c0)=iq3_half::(b,j,0);let (g1,s1,c1)=iq3_half::(b,j,1); - (_mm512_inserti64x4::<1>(_mm512_castsi256_si512(g0),g1),_mm512_inserti64x4::<1>(_mm512_castsi256_si512(_mm256_set1_epi16(c0)),_mm256_set1_epi16(c1)),s0 as u64|((s1 as u64)<<32)) - } else { - let (g0,s0,sc0)=decode(t,b,j,0);let (g1,s1,sc1)=decode(t,b,j,1);let mut g=[0u8;64];g[..32].copy_from_slice(&g0);g[32..].copy_from_slice(&g1);let mut sc=[0i16;32];sc[..16].copy_from_slice(&sc0);sc[16..].copy_from_slice(&sc1); - let gv=if super::rust_simd::dispatch().gather&&(t==18||t==21){let q=&b[2+16*j..];let mut idx=_mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast()));if t==21{let m=b[66+2*j]as u16|((b[67+2*j]as u16)<<8);idx=_mm512_mask_add_epi32(idx,m,idx,_mm512_set1_epi32(256));}_mm512_i32gather_epi32::<4>(idx,if t==18{IQ3XXS_GRID.as_ptr().cast()}else{IQ3S_GRID.as_ptr().cast()})}else{_mm512_loadu_si512(g.as_ptr().cast())}; - let sv=_mm512_loadu_si512(sc.as_ptr().cast());let m=s0 as u64|((s1 as u64)<<32); - (gv,sv,m)}; - for k in 0..N {let y=ys[k];let v=_mm512_loadu_si512(y[i].qs.as_ptr().add(64*j).cast());let sy=_mm512_mask_sub_epi8(v,m,zero,v);ai[k]=_mm512_add_epi32(ai[k],_mm512_madd_epi16(_mm512_maddubs_epi16(gv,sy),sv));} - } - let dx=half(u16(b,0))*factor(t);for k in 0..N {let y=ys[k];af[k]=_mm512_fmadd_ps(_mm512_set1_ps(dx*y[i].d),_mm512_cvtepi32_ps(ai[k]),af[k]);} - } - for k in 0..N {out[k]=_mm512_reduce_add_ps(af[k]);} -}} -/// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS (A/B arm); the default is the -/// register-built tree below (`dot_single_iq3`), the same integer lanes and float operations, so the same bits. -fn iq3_single_fast()->bool { - static ON:std::sync::OnceLock=std::sync::OnceLock::new(); - *ON.get_or_init(||std::env::var("LELEKA_IQ_SINGLE").as_deref()!=Ok("legacy")) -} -// GGML AVX2 T1: two alternating exact integer accumulators, factor AFTER final reduction. -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn dot_single(t:i32,row:&[u8],y:&[Q8K])->f32 {unsafe { - if t==23{return iq4xs(row,y);} - if (t==21||t==18)&&iq3_single_fast(){return if t==21{dot_single_iq3::<21>(row,y)}else{dot_single_iq3::<18>(row,y)};} - dot_single_generic(t,row,y) -}} -// The generic tree (decode into stack arrays, then load): the pre-2026-10-31 path of every single-token IQ row. -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn dot_single_generic(t:i32,row:&[u8],y:&[Q8K])->f32 {unsafe { - let mut af=_mm256_setzero_ps();for (i,b) in row.chunks_exact(format_bytes(t)).enumerate(){let mut a=[_mm256_setzero_si256();2];for j in 0..4 {for h in 0..2 {let (g,s,sc)=decoded(t,b,j,h);let q=_mm256_loadu_si256(y[i].qs.as_ptr().add(64*j+32*h).cast());a[h]=_mm256_add_epi32(a[h],_mm256_madd_epi16(_mm256_maddubs_epi16(g,_mm256_sign_epi8(q,s)),sc));}}let d=half(u16(b,0))*y[i].d;af=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(_mm256_add_epi32(a[0],a[1])),af);} - factor(t)*hsum_ggml(af) -}} -/// IQ3_S (21) / IQ3_XXS (18), one token: `dot_single_generic`'s tree with the 32 magnitude bytes of a half built in a -/// register (`_mm256_setr_epi32` of the eight grid words: lane l = grid word l, the bytes `decode` writes at 4l..4l+4), -/// the same sign mask (`signs32`), the same per-half 16-bit scale broadcast, the same two exact i32 accumulators and the -/// same per-block FMA and final reduction. Only where the bytes live between decode and use changes (no stack round trip, -/// no per-half `match`), so every lane, and the result, is bit for bit the generic one's (`iq3_single_trees_are_bitwise_equal`). -/// Bounds: `row` is walked by `chunks_exact(format_bytes(T))`, every offset below is inside a 110/98-byte block, `y[i]` is checked. -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn dot_single_iq3(row:&[u8],y:&[Q8K])->f32 {unsafe { - let mut af=_mm256_setzero_ps(); - for (i,b) in row.chunks_exact(format_bytes(T)).enumerate(){ - let yi=&y[i];let mut a=[_mm256_setzero_si256();2]; - for j in 0..4 {for h in 0..2 { - let q=&b[2+16*j+8*h..2+16*j+8*h+8]; - let (g,s,sc)=if T==21 { - let high=b[66+2*j+h]as usize; - let w=|l:usize|IQ3S_GRID[q[l]as usize|(((high>>l)&1)<<8)]as i32; - let sv=b[106+j];let s0=2*(if h==0{sv&15}else{sv>>4})as i16+1; - (_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),u32(b,74+8*j+4*h),s0) - } else { - let w=|l:usize|IQ3XXS_GRID[q[l]as usize]as i32; - let ws=u32(b,66+8*j+4*h);let mut signs=0u32;for l in 0..4 {signs|=(KSIGNS_IQ2XS[((ws>>(7*l))&127)as usize]as u32)<<(8*l);} - (_mm256_setr_epi32(w(0),w(1),w(2),w(3),w(4),w(5),w(6),w(7)),signs,2*(ws>>28)as i16+1) - }; - let v=_mm256_loadu_si256(yi.qs.as_ptr().add(64*j+32*h).cast()); - a[h]=_mm256_add_epi32(a[h],_mm256_madd_epi16(_mm256_maddubs_epi16(g,_mm256_sign_epi8(v,signs32(s))),_mm256_set1_epi16(sc))); - }} - let d=half(u16(b,0))*yi.d;af=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(_mm256_add_epi32(a[0],a[1])),af); - } - factor(T)*hsum_ggml(af) -}} -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn iq4xs(row:&[u8],y:&[Q8K])->f32 {unsafe { - let values=_mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast());let m4=_mm_set1_epi8(15);let mut af=_mm256_setzero_ps(); - for (i,b) in row.chunks_exact(136).enumerate(){let mut sh=u16(b,2);let mut sums=[_mm256_setzero_si256();2];for ib in (0..8).step_by(2){for h in 0..2 {let bits=_mm_loadu_si128(b.as_ptr().add(8+16*(ib+h)).cast());let q=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_shuffle_epi8(values,_mm_and_si128(bits,m4))),_mm_shuffle_epi8(values,_mm_and_si128(_mm_srli_epi16::<4>(bits),m4)));let v=_mm256_loadu_si256(y[i].qs.as_ptr().add(32*(ib+h)).cast());let p=_mm256_maddubs_epi16(_mm256_sign_epi8(q,q),_mm256_sign_epi8(v,q));let ls=if h==0{((b[4+ib/2]&15)as u16|((sh<<4)&48))as i16-32}else{((b[4+ib/2]>>4)as u16|((sh<<2)&48))as i16-32};sums[h]=_mm256_add_epi32(_mm256_madd_epi16(p,_mm256_set1_epi16(ls)),sums[h]);}sh>>=4;} - af=_mm256_fmadd_ps(_mm256_set1_ps(half(u16(b,0))*y[i].d),_mm256_cvtepi32_ps(_mm256_add_epi32(sums[0],sums[1])),af); - }hsum_ggml(af) -}} -/// IQ4_NL rows specialised on the token count; the same operations in the same order per token. -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn iq4nl(row:&[u8],ys:&[&[Q8Zero]],out:&mut [f32],single:bool) {unsafe { - match ys.len(){1=>iq4nl_n::<1>(row,ys,out,single),2=>iq4nl_n::<2>(row,ys,out,single),3=>iq4nl_n::<3>(row,ys,out,single),4=>iq4nl_n::<4>(row,ys,out,single),5=>iq4nl_n::<5>(row,ys,out,single),6=>iq4nl_n::<6>(row,ys,out,single),7=>iq4nl_n::<7>(row,ys,out,single),8=>iq4nl_n::<8>(row,ys,out,single),_=>panic!("iq4nl: 1..=8 tokens")} -}} -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn iq4nl_n(row:&[u8],ys:&[&[Q8Zero]],out:&mut [f32],single:bool) {unsafe { - assert!(N<=8&&ys.len()==N&&out.len()==N); - let values=_mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast());let m4=_mm_set1_epi8(15);let ones=_mm256_set1_epi16(1);let mut af=[[_mm256_setzero_ps();2];8]; - for (ib,b) in row.chunks_exact(18).enumerate(){prefetch(b.as_ptr());let bits=_mm_loadu_si128(b.as_ptr().add(2).cast());let q=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_shuffle_epi8(values,_mm_and_si128(bits,m4))),_mm_shuffle_epi8(values,_mm_and_si128(_mm_srli_epi16::<4>(bits),m4)));let aq=_mm256_sign_epi8(q,q);let dx=half(u16(b,0)); - for t in 0..N {let y=ys[t];let b=&y[ib];let v=_mm256_loadu_si256(b.qs.as_ptr().cast());let p=_mm256_madd_epi16(_mm256_maddubs_epi16(aq,_mm256_sign_epi8(v,q)),ones);let lane=if single{ib&1}else{0};let d=if single{half(b.d)*dx}else{dx*half(b.d)};af[t][lane]=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(p),af[t][lane]);} - }for t in 0..N {out[t]=if single{hsum_ggml(_mm256_add_ps(af[t][0],af[t][1]))}else{hsum_original(af[t][0])};} -}} +use super::rust_simd::{half, hsum_ggml, hsum_original, prefetch, signs32}; +use super::rust_types::{Q8K, Q8Zero}; +use std::arch::x86_64::*; #[cfg(test)] -mod tests { - use super::*; - use super::super::rust_quant::q8_k; - fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s} - fn h2f(h:u16)->f32 {let e=((h>>10)&31)as u32;assert!(e>0&&e<31,"finite normal FP16 only");f32::from_bits(((h as u32&0x8000)<<16)|((e+112)<<23)|((h as u32&0x3ff)<<13))} - // Scalar model of iq_avx2.cpp row_dot<23,NT> (non-EX): per block one int32 accumulator per lane, sum over the 8 sub-blocks of - // (ls-32) * (4 consecutive signed-codebook x activation products), then ONE fma per block and lane, then the original hsum. - fn model_iq4xs(row:&[u8],y:&[Q8K])->f32 { - let mut acc=[0.0f32;8]; - for (i,b) in row.chunks_exact(136).enumerate() { - let d=h2f(u16(b,0));let sh=u16(b,2);let mut ai=[0i32;8]; - for hh in 0..8 { - let ls=(((b[4+hh/2]>>(4*(hh&1)))&15)as i32)|((((sh>>(2*hh))&3)as i32)<<4);let sc=ls-32; - let w=|e:usize|->i32 {let by=b[8+16*hh+(e&15)];(KVALUES_IQ4NL[if e<16{by&15}else{by>>4}as usize])as i32}; - for l in 0..8 {let mut s=0i32;for k in 0..4 {let e=4*l+k;s+=w(e)*y[i].qs[32*hh+e]as i32;}ai[l]+=sc*s;} - } - for l in 0..8 {acc[l]=(d*y[i].d).mul_add(ai[l]as f32,acc[l]);} - } - let h=[acc[0]+acc[4],acc[1]+acc[5],acc[2]+acc[6],acc[3]+acc[7]];(h[0]+h[1])+(h[2]+h[3]) - } - fn random_rows(t:i32,nb:usize,rows:usize,seed:&mut u64)->Vec { - let bytes=format_bytes(t);let mut row=vec![0u8;rows*nb*bytes];for v in row.iter_mut(){*v=xorshift(seed)as u8;} - for b in row.chunks_exact_mut(bytes){let e=8+(xorshift(seed)%8)as u16;let m=(xorshift(seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} - row - } - fn random_act(nb:usize,scale:f32,seed:&mut u64)->Vec { - let x:Vec=(0..nb*256).map(|_|((xorshift(seed)%20001)as f32-10000.0)*scale).collect();let mut y=vec![Q8K::default();nb];q8_k(&x,&mut y);y - } - // The register-built IQ3 single-token tree against the generic one: every row of random blocks (all grid indices, high - // bits, sign words and scales) and activations of several magnitudes, compared bit for bit. - #[test] - fn iq3_single_trees_are_bitwise_equal() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - let mut seed=0x1d3_5eed_0bad_cafeu64;let nb=10usize; - for t in [21,18] { - for round in 0..8 { - let rows=64;let w=random_rows(t,nb,rows,&mut seed);let y=random_act(nb,0.0001+round as f32*0.37,&mut seed); - for r in w.chunks_exact(nb*format_bytes(t)) { - // SAFETY: avx2_ok() above; every row is nb whole blocks and y has nb blocks. - let (a,b)=unsafe {(dot_single_generic(t,r,&y),if t==21{dot_single_iq3::<21>(r,&y)}else{dot_single_iq3::<18>(r,&y)})}; - assert_eq!(a.to_bits(),b.to_bits(),"type {t} round {round}"); - } - } - } - } - // Throughput of one token's gate+up rows (FF=640 rows x 2 matrices of H=2560) over 48 distinct experts (past the L3), - // generic against register-built, one thread. `cargo test --release -p leleka-native-cpu-expert iq3_single_bench -- --ignored --nocapture` - #[test] - #[ignore = "benchmark"] - fn iq3_single_bench() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP");return;} - let mut seed=42u64;let nb=10usize;let t=21;let experts=48usize;let rows=1280usize; - let w=random_rows(t,nb,rows*experts,&mut seed);let y=random_act(nb,0.01,&mut seed);let rb=nb*format_bytes(t); - for pass in 0..3 { - for (name,fast) in [("generic",false),("iq3",true)] { - let start=std::time::Instant::now();let mut s=0.0f32; - for r in w.chunks_exact(rb){s+=unsafe {if fast{dot_single_iq3::<21>(r,&y)}else{dot_single_generic(t,r,&y)}};} - let el=start.elapsed().as_secs_f64(); - eprintln!("pass {pass} {name}: {:.1} us per expert gate+up, {:.2} GB/s (sum {s})",el*1e6/experts as f64,w.len()as f64/el/1e9); - } - if super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok() { - let y2=random_act(nb,0.01,&mut seed);let ys=[y.as_slice(),y2.as_slice()];let start=std::time::Instant::now();let mut s=0.0f32; - for r in w.chunks_exact(rb){let mut o=[0.0f32;2];unsafe {dot_multi512_impl::<21,2>(r,&ys,&mut o,false);}s+=o[0];} - let el=start.elapsed().as_secs_f64(); - eprintln!("pass {pass} multi512 x2 stack: {:.1} us per expert gate+up (sum {s})",el*1e6/experts as f64); - let start=std::time::Instant::now();let mut s=0.0f32; - for r in w.chunks_exact(rb){let mut o=[0.0f32;2];unsafe {dot_multi512_impl::<21,2>(r,&ys,&mut o,true);}s+=o[0];} - let el=start.elapsed().as_secs_f64(); - eprintln!("pass {pass} multi512 x2 register: {:.1} us per expert gate+up (sum {s})",el*1e6/experts as f64); - } - // the down rows of the same experts: H=2560 rows of IQ4_NL over FF=640 (20 blocks of 18 bytes), one token - let dn=random_iq4nl(2560*experts,20,&mut seed);let hq=random_q8zero(20,&mut seed);let start=std::time::Instant::now();let mut s=0.0f32; - for r in dn.chunks_exact(20*18){let mut o=[0.0f32];unsafe {iq4nl(r,&[hq.as_slice()],&mut o,true);}s+=o[0];} - let el=start.elapsed().as_secs_f64(); - eprintln!("pass {pass} iq4nl down x1: {:.1} us per expert down, {:.2} GB/s (sum {s})",el*1e6/experts as f64,dn.len()as f64/el/1e9); - } - } - fn random_iq4nl(rows:usize,nb:usize,seed:&mut u64)->Vec { - let mut v=vec![0u8;rows*nb*18];for x in v.iter_mut(){*x=xorshift(seed)as u8;} - for b in v.chunks_exact_mut(18){let e=8+(xorshift(seed)%8)as u16;let m=(xorshift(seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());}v - } - fn random_q8zero(nb:usize,seed:&mut u64)->Vec { - let mut v=vec![Q8Zero::default();nb];for b in v.iter_mut(){b.d=0x3c00;for q in b.qs.iter_mut(){*q=xorshift(seed)as i8;}}v - } - #[test] - fn iq3_multi_trees_are_bitwise_equal() { - if !(super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok()){eprintln!("SKIP: AVX-512");return;} - let mut seed=0x3e3e_5eed_7777_0001u64;let nb=10usize; - macro_rules! cmp {($T:literal,$N:literal,$w:expr,$ys:expr)=>{{let mut a=[0.0f32;$N];let mut b=[0.0f32;$N]; - for r in $w.chunks_exact(nb*format_bytes($T)) {unsafe {dot_multi512_impl::<$T,$N>(r,&$ys[..$N],&mut a,false);dot_multi512_impl::<$T,$N>(r,&$ys[..$N],&mut b,true);} - for k in 0..$N {assert_eq!(a[k].to_bits(),b[k].to_bits(),"type {} tokens {} token {k}",$T,$N);}}}}} - for round in 0..6 { - let acts:Vec>=(0..4).map(|k|random_act(nb,0.0003+(round*4+k) as f32*0.21,&mut seed)).collect();let ys:Vec<&[Q8K]>=acts.iter().map(|y|y.as_slice()).collect(); - let w21=random_rows(21,nb,32,&mut seed);let w18=random_rows(18,nb,32,&mut seed); - cmp!(21,1,w21,ys);cmp!(21,2,w21,ys);cmp!(21,3,w21,ys);cmp!(21,4,w21,ys);cmp!(18,1,w18,ys);cmp!(18,2,w18,ys);cmp!(18,3,w18,ys);cmp!(18,4,w18,ys); - } - } - // IQ4_XS gate/up rows at two or more tokens on the AVX2 tree take the multi-token kernel (iq_avx2.cpp iq256_gu_rows, native_expert.cpp - // `!cpu512 && iq256_supported(23)`), not ggml's single-token dot: its last bits differ, and a Q2_0 down projection (not requantized - // to int8 as IQ4_NL's is) exposed it in KAB1 (STRA-324: cases 23-42-r2/r3/r8). - #[test] - fn iq4xs_multi_token_avx2_kernel_matches_the_scalar_model_bitwise() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - let mut seed=0x5eed_1234_abcd_ef01u64;let nb=10usize; - for round in 0..6 { - let mut row=vec![0u8;nb*136];for v in row.iter_mut(){*v=xorshift(&mut seed)as u8;} - for b in row.chunks_exact_mut(136){let e=8+(xorshift(&mut seed)%8)as u16;let m=(xorshift(&mut seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} - let mut ys:Vec>=Vec::new(); - for _ in 0..8 {let x:Vec=(0..nb*256).map(|_|((xorshift(&mut seed)%20001)as f32-10000.0)*(0.001+(round as f32))).collect();let mut y=vec![Q8K::default();nb];q8_k(&x,&mut y);ys.push(y);} - for nt in [1usize,2,3,5,8] { - let refs:Vec<&[Q8K]>=ys[..nt].iter().map(|y|y.as_slice()).collect();let mut out=vec![0.0f32;nt]; - // SAFETY: avx2_ok() above; row is exactly nb blocks of 136 bytes and every Q8K row has nb blocks. - unsafe {dot_multi256(23,&row,&refs,&mut out);} - for t in 0..nt {assert_eq!(out[t].to_bits(),model_iq4xs(&row,&ys[t]).to_bits(),"round {round} nt {nt} token {t}");} - } - } - } -} +mod tests; + +mod u16_fn; +#[allow(unused_imports)] +use u16_fn::decode; +#[allow(unused_imports)] +use u16_fn::decoded; +#[allow(unused_imports)] +pub(super) use u16_fn::dot_multi256; +#[allow(unused_imports)] +pub(super) use u16_fn::dot_multi512; +#[allow(unused_imports)] +use u16_fn::dot_multi512_tn; +#[allow(unused_imports)] +use u16_fn::factor; +#[allow(unused_imports)] +pub(super) use u16_fn::format_bytes; +#[allow(unused_imports)] +use u16_fn::iq3_half; +#[allow(unused_imports)] +use u16_fn::iq3_multi_fast; +#[allow(unused_imports)] +use u16_fn::u16; +#[allow(unused_imports)] +use u16_fn::u32; +mod dot_multi512_impl_fn; +#[allow(unused_imports)] +use dot_multi512_impl_fn::dot_multi512_impl; +#[allow(unused_imports)] +pub(super) use dot_multi512_impl_fn::dot_single; +#[allow(unused_imports)] +use dot_multi512_impl_fn::dot_single_generic; +#[allow(unused_imports)] +use dot_multi512_impl_fn::dot_single_iq3; +#[allow(unused_imports)] +use dot_multi512_impl_fn::iq3_single_fast; +#[allow(unused_imports)] +pub(super) use dot_multi512_impl_fn::iq4nl; +#[allow(unused_imports)] +use dot_multi512_impl_fn::iq4xs; +mod iq4nl_n_fn; +#[allow(unused_imports)] +use iq4nl_n_fn::iq4nl_n; diff --git a/crates/native-cpu-expert/src/rust_iq/dot_multi512_impl_fn.rs b/crates/native-cpu-expert/src/rust_iq/dot_multi512_impl_fn.rs new file mode 100644 index 00000000..a823bc9a --- /dev/null +++ b/crates/native-cpu-expert/src/rust_iq/dot_multi512_impl_fn.rs @@ -0,0 +1,228 @@ +//! Moved out of the parent module by STRA-338: fn dot_multi512_impl, fn iq3_single_fast, fn dot_single, fn dot_single_generic, fn dot_single_iq3, fn iq4xs .... + +#[allow(unused_imports)] +use super::*; + +/// `fast`: the register-built IQ3 halves (bitwise the stack-array decode, `iq3_multi_trees_are_bitwise_equal`; slower on Zen 5, opt-in). +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] +pub(super) unsafe fn dot_multi512_impl( + row: &[u8], + ys: &[&[Q8K]], + out: &mut [f32], + fast: bool, +) { + unsafe { + let t = T; + assert!(N <= 8 && ys.len() == N && out.len() == N); + let nb = ys[0].len(); + assert_eq!(row.len(), nb * format_bytes(t)); + let mut af = [_mm512_setzero_ps(); 8]; + let zero = _mm512_setzero_si512(); + for i in 0..nb { + let b = &row[i * format_bytes(t)..][..format_bytes(t)]; + prefetch(b.as_ptr()); + let mut ai = [_mm512_setzero_si512(); 8]; + for j in 0..4 { + // IQ3 formats (`iq3_multi_fast`): both halves' grid words straight into the 512-bit register, lane order = `decode`'s byte order + let reg = (T == 21 || T == 18) && fast && !super::super::rust_simd::dispatch().gather; + let (gv, sv, m) = if reg { + let (g0, s0, c0) = iq3_half::(b, j, 0); + let (g1, s1, c1) = iq3_half::(b, j, 1); + ( + _mm512_inserti64x4::<1>(_mm512_castsi256_si512(g0), g1), + _mm512_inserti64x4::<1>(_mm512_castsi256_si512(_mm256_set1_epi16(c0)), _mm256_set1_epi16(c1)), + s0 as u64 | ((s1 as u64) << 32), + ) + } else { + let (g0, s0, sc0) = decode(t, b, j, 0); + let (g1, s1, sc1) = decode(t, b, j, 1); + let mut g = [0u8; 64]; + g[..32].copy_from_slice(&g0); + g[32..].copy_from_slice(&g1); + let mut sc = [0i16; 32]; + sc[..16].copy_from_slice(&sc0); + sc[16..].copy_from_slice(&sc1); + let gv = if super::super::rust_simd::dispatch().gather && (t == 18 || t == 21) { + let q = &b[2 + 16 * j..]; + let mut idx = _mm512_cvtepu8_epi32(_mm_loadu_si128(q.as_ptr().cast())); + if t == 21 { + let m = b[66 + 2 * j] as u16 | ((b[67 + 2 * j] as u16) << 8); + idx = _mm512_mask_add_epi32(idx, m, idx, _mm512_set1_epi32(256)); + } + _mm512_i32gather_epi32::<4>( + idx, + if t == 18 { IQ3XXS_GRID.as_ptr().cast() } else { IQ3S_GRID.as_ptr().cast() }, + ) + } else { + _mm512_loadu_si512(g.as_ptr().cast()) + }; + let sv = _mm512_loadu_si512(sc.as_ptr().cast()); + let m = s0 as u64 | ((s1 as u64) << 32); + (gv, sv, m) + }; + for k in 0..N { + let y = ys[k]; + let v = _mm512_loadu_si512(y[i].qs.as_ptr().add(64 * j).cast()); + let sy = _mm512_mask_sub_epi8(v, m, zero, v); + ai[k] = _mm512_add_epi32(ai[k], _mm512_madd_epi16(_mm512_maddubs_epi16(gv, sy), sv)); + } + } + let dx = half(u16(b, 0)) * factor(t); + for k in 0..N { + let y = ys[k]; + af[k] = _mm512_fmadd_ps(_mm512_set1_ps(dx * y[i].d), _mm512_cvtepi32_ps(ai[k]), af[k]); + } + } + for k in 0..N { + out[k] = _mm512_reduce_add_ps(af[k]); + } + } +} +/// `LELEKA_IQ_SINGLE=legacy` keeps the generic single-token tree for IQ3_S / IQ3_XXS (A/B arm); the default is the +/// register-built tree below (`dot_single_iq3`), the same integer lanes and float operations, so the same bits. +pub(super) fn iq3_single_fast() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_IQ_SINGLE").as_deref() != Ok("legacy")) +} +// GGML AVX2 T1: two alternating exact integer accumulators, factor AFTER final reduction. +#[target_feature(enable = "avx2,fma,f16c")] +pub(in super::super) unsafe fn dot_single(t: i32, row: &[u8], y: &[Q8K]) -> f32 { + unsafe { + if t == 23 { + return iq4xs(row, y); + } + if (t == 21 || t == 18) && iq3_single_fast() { + return if t == 21 { dot_single_iq3::<21>(row, y) } else { dot_single_iq3::<18>(row, y) }; + } + dot_single_generic(t, row, y) + } +} +// The generic tree (decode into stack arrays, then load): the pre-2026-10-31 path of every single-token IQ row. +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn dot_single_generic(t: i32, row: &[u8], y: &[Q8K]) -> f32 { + unsafe { + let mut af = _mm256_setzero_ps(); + for (i, b) in row.chunks_exact(format_bytes(t)).enumerate() { + let mut a = [_mm256_setzero_si256(); 2]; + for j in 0..4 { + for h in 0..2 { + let (g, s, sc) = decoded(t, b, j, h); + let q = _mm256_loadu_si256(y[i].qs.as_ptr().add(64 * j + 32 * h).cast()); + a[h] = + _mm256_add_epi32(a[h], _mm256_madd_epi16(_mm256_maddubs_epi16(g, _mm256_sign_epi8(q, s)), sc)); + } + } + let d = half(u16(b, 0)) * y[i].d; + af = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(a[0], a[1])), af); + } + factor(t) * hsum_ggml(af) + } +} +/// IQ3_S (21) / IQ3_XXS (18), one token: `dot_single_generic`'s tree with the 32 magnitude bytes of a half built in a +/// register (`_mm256_setr_epi32` of the eight grid words: lane l = grid word l, the bytes `decode` writes at 4l..4l+4), +/// the same sign mask (`signs32`), the same per-half 16-bit scale broadcast, the same two exact i32 accumulators and the +/// same per-block FMA and final reduction. Only where the bytes live between decode and use changes (no stack round trip, +/// no per-half `match`), so every lane, and the result, is bit for bit the generic one's (`iq3_single_trees_are_bitwise_equal`). +/// Bounds: `row` is walked by `chunks_exact(format_bytes(T))`, every offset below is inside a 110/98-byte block, `y[i]` is checked. +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn dot_single_iq3(row: &[u8], y: &[Q8K]) -> f32 { + unsafe { + let mut af = _mm256_setzero_ps(); + for (i, b) in row.chunks_exact(format_bytes(T)).enumerate() { + let yi = &y[i]; + let mut a = [_mm256_setzero_si256(); 2]; + for j in 0..4 { + for h in 0..2 { + let q = &b[2 + 16 * j + 8 * h..2 + 16 * j + 8 * h + 8]; + let (g, s, sc) = if T == 21 { + let high = b[66 + 2 * j + h] as usize; + let w = |l: usize| IQ3S_GRID[q[l] as usize | (((high >> l) & 1) << 8)] as i32; + let sv = b[106 + j]; + let s0 = 2 * (if h == 0 { sv & 15 } else { sv >> 4 }) as i16 + 1; + ( + _mm256_setr_epi32(w(0), w(1), w(2), w(3), w(4), w(5), w(6), w(7)), + u32(b, 74 + 8 * j + 4 * h), + s0, + ) + } else { + let w = |l: usize| IQ3XXS_GRID[q[l] as usize] as i32; + let ws = u32(b, 66 + 8 * j + 4 * h); + let mut signs = 0u32; + for l in 0..4 { + signs |= (KSIGNS_IQ2XS[((ws >> (7 * l)) & 127) as usize] as u32) << (8 * l); + } + ( + _mm256_setr_epi32(w(0), w(1), w(2), w(3), w(4), w(5), w(6), w(7)), + signs, + 2 * (ws >> 28) as i16 + 1, + ) + }; + let v = _mm256_loadu_si256(yi.qs.as_ptr().add(64 * j + 32 * h).cast()); + a[h] = _mm256_add_epi32( + a[h], + _mm256_madd_epi16( + _mm256_maddubs_epi16(g, _mm256_sign_epi8(v, signs32(s))), + _mm256_set1_epi16(sc), + ), + ); + } + } + let d = half(u16(b, 0)) * yi.d; + af = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(a[0], a[1])), af); + } + factor(T) * hsum_ggml(af) + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn iq4xs(row: &[u8], y: &[Q8K]) -> f32 { + unsafe { + let values = _mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast()); + let m4 = _mm_set1_epi8(15); + let mut af = _mm256_setzero_ps(); + for (i, b) in row.chunks_exact(136).enumerate() { + let mut sh = u16(b, 2); + let mut sums = [_mm256_setzero_si256(); 2]; + for ib in (0..8).step_by(2) { + for h in 0..2 { + let bits = _mm_loadu_si128(b.as_ptr().add(8 + 16 * (ib + h)).cast()); + let q = _mm256_inserti128_si256::<1>( + _mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))), + _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16::<4>(bits), m4)), + ); + let v = _mm256_loadu_si256(y[i].qs.as_ptr().add(32 * (ib + h)).cast()); + let p = _mm256_maddubs_epi16(_mm256_sign_epi8(q, q), _mm256_sign_epi8(v, q)); + let ls = if h == 0 { + ((b[4 + ib / 2] & 15) as u16 | ((sh << 4) & 48)) as i16 - 32 + } else { + ((b[4 + ib / 2] >> 4) as u16 | ((sh << 2) & 48)) as i16 - 32 + }; + sums[h] = _mm256_add_epi32(_mm256_madd_epi16(p, _mm256_set1_epi16(ls)), sums[h]); + } + sh >>= 4; + } + af = _mm256_fmadd_ps( + _mm256_set1_ps(half(u16(b, 0)) * y[i].d), + _mm256_cvtepi32_ps(_mm256_add_epi32(sums[0], sums[1])), + af, + ); + } + hsum_ggml(af) + } +} +/// IQ4_NL rows specialised on the token count; the same operations in the same order per token. +#[target_feature(enable = "avx2,fma,f16c")] +pub(in super::super) unsafe fn iq4nl(row: &[u8], ys: &[&[Q8Zero]], out: &mut [f32], single: bool) { + unsafe { + match ys.len() { + 1 => iq4nl_n::<1>(row, ys, out, single), + 2 => iq4nl_n::<2>(row, ys, out, single), + 3 => iq4nl_n::<3>(row, ys, out, single), + 4 => iq4nl_n::<4>(row, ys, out, single), + 5 => iq4nl_n::<5>(row, ys, out, single), + 6 => iq4nl_n::<6>(row, ys, out, single), + 7 => iq4nl_n::<7>(row, ys, out, single), + 8 => iq4nl_n::<8>(row, ys, out, single), + _ => panic!("iq4nl: 1..=8 tokens"), + } + } +} diff --git a/crates/native-cpu-expert/src/rust_iq/iq4nl_n_fn.rs b/crates/native-cpu-expert/src/rust_iq/iq4nl_n_fn.rs new file mode 100644 index 00000000..29f08831 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_iq/iq4nl_n_fn.rs @@ -0,0 +1,37 @@ +//! Moved out of the parent module by STRA-338: fn iq4nl_n. + +#[allow(unused_imports)] +use super::*; + +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn iq4nl_n(row: &[u8], ys: &[&[Q8Zero]], out: &mut [f32], single: bool) { + unsafe { + assert!(N <= 8 && ys.len() == N && out.len() == N); + let values = _mm_loadu_si128(KVALUES_IQ4NL.as_ptr().cast()); + let m4 = _mm_set1_epi8(15); + let ones = _mm256_set1_epi16(1); + let mut af = [[_mm256_setzero_ps(); 2]; 8]; + for (ib, b) in row.chunks_exact(18).enumerate() { + prefetch(b.as_ptr()); + let bits = _mm_loadu_si128(b.as_ptr().add(2).cast()); + let q = _mm256_inserti128_si256::<1>( + _mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))), + _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16::<4>(bits), m4)), + ); + let aq = _mm256_sign_epi8(q, q); + let dx = half(u16(b, 0)); + for t in 0..N { + let y = ys[t]; + let b = &y[ib]; + let v = _mm256_loadu_si256(b.qs.as_ptr().cast()); + let p = _mm256_madd_epi16(_mm256_maddubs_epi16(aq, _mm256_sign_epi8(v, q)), ones); + let lane = if single { ib & 1 } else { 0 }; + let d = if single { half(b.d) * dx } else { dx * half(b.d) }; + af[t][lane] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(p), af[t][lane]); + } + } + for t in 0..N { + out[t] = if single { hsum_ggml(_mm256_add_ps(af[t][0], af[t][1])) } else { hsum_original(af[t][0]) }; + } + } +} diff --git a/crates/native-cpu-expert/src/rust_iq/tests.rs b/crates/native-cpu-expert/src/rust_iq/tests.rs new file mode 100644 index 00000000..07c6ae8d --- /dev/null +++ b/crates/native-cpu-expert/src/rust_iq/tests.rs @@ -0,0 +1,280 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::super::rust_quant::q8_k; +use super::*; +fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s +} +fn h2f(h: u16) -> f32 { + let e = ((h >> 10) & 31) as u32; + assert!(e > 0 && e < 31, "finite normal FP16 only"); + f32::from_bits(((h as u32 & 0x8000) << 16) | ((e + 112) << 23) | ((h as u32 & 0x3ff) << 13)) +} +// Scalar model of iq_avx2.cpp row_dot<23,NT> (non-EX): per block one int32 accumulator per lane, sum over the 8 sub-blocks of +// (ls-32) * (4 consecutive signed-codebook x activation products), then ONE fma per block and lane, then the original hsum. +fn model_iq4xs(row: &[u8], y: &[Q8K]) -> f32 { + let mut acc = [0.0f32; 8]; + for (i, b) in row.chunks_exact(136).enumerate() { + let d = h2f(u16(b, 0)); + let sh = u16(b, 2); + let mut ai = [0i32; 8]; + for hh in 0..8 { + let ls = (((b[4 + hh / 2] >> (4 * (hh & 1))) & 15) as i32) | ((((sh >> (2 * hh)) & 3) as i32) << 4); + let sc = ls - 32; + let w = |e: usize| -> i32 { + let by = b[8 + 16 * hh + (e & 15)]; + (KVALUES_IQ4NL[if e < 16 { by & 15 } else { by >> 4 } as usize]) as i32 + }; + for l in 0..8 { + let mut s = 0i32; + for k in 0..4 { + let e = 4 * l + k; + s += w(e) * y[i].qs[32 * hh + e] as i32; + } + ai[l] += sc * s; + } + } + for l in 0..8 { + acc[l] = (d * y[i].d).mul_add(ai[l] as f32, acc[l]); + } + } + let h = [acc[0] + acc[4], acc[1] + acc[5], acc[2] + acc[6], acc[3] + acc[7]]; + (h[0] + h[1]) + (h[2] + h[3]) +} +fn random_rows(t: i32, nb: usize, rows: usize, seed: &mut u64) -> Vec { + let bytes = format_bytes(t); + let mut row = vec![0u8; rows * nb * bytes]; + for v in row.iter_mut() { + *v = xorshift(seed) as u8; + } + for b in row.chunks_exact_mut(bytes) { + let e = 8 + (xorshift(seed) % 8) as u16; + let m = (xorshift(seed) & 0x3ff) as u16; + b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + } + row +} +fn random_act(nb: usize, scale: f32, seed: &mut u64) -> Vec { + let x: Vec = (0..nb * 256).map(|_| ((xorshift(seed) % 20001) as f32 - 10000.0) * scale).collect(); + let mut y = vec![Q8K::default(); nb]; + q8_k(&x, &mut y); + y +} +// The register-built IQ3 single-token tree against the generic one: every row of random blocks (all grid indices, high +// bits, sign words and scales) and activations of several magnitudes, compared bit for bit. +#[test] +fn iq3_single_trees_are_bitwise_equal() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + let mut seed = 0x1d3_5eed_0bad_cafeu64; + let nb = 10usize; + for t in [21, 18] { + for round in 0..8 { + let rows = 64; + let w = random_rows(t, nb, rows, &mut seed); + let y = random_act(nb, 0.0001 + round as f32 * 0.37, &mut seed); + for r in w.chunks_exact(nb * format_bytes(t)) { + // SAFETY: avx2_ok() above; every row is nb whole blocks and y has nb blocks. + let (a, b) = unsafe { + ( + dot_single_generic(t, r, &y), + if t == 21 { dot_single_iq3::<21>(r, &y) } else { dot_single_iq3::<18>(r, &y) }, + ) + }; + assert_eq!(a.to_bits(), b.to_bits(), "type {t} round {round}"); + } + } + } +} +// Throughput of one token's gate+up rows (FF=640 rows x 2 matrices of H=2560) over 48 distinct experts (past the L3), +// generic against register-built, one thread. `cargo test --release -p leleka-native-cpu-expert iq3_single_bench -- --ignored --nocapture` +#[test] +#[ignore = "benchmark"] +fn iq3_single_bench() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP"); + return; + } + let mut seed = 42u64; + let nb = 10usize; + let t = 21; + let experts = 48usize; + let rows = 1280usize; + let w = random_rows(t, nb, rows * experts, &mut seed); + let y = random_act(nb, 0.01, &mut seed); + let rb = nb * format_bytes(t); + for pass in 0..3 { + for (name, fast) in [("generic", false), ("iq3", true)] { + let start = std::time::Instant::now(); + let mut s = 0.0f32; + for r in w.chunks_exact(rb) { + s += unsafe { if fast { dot_single_iq3::<21>(r, &y) } else { dot_single_generic(t, r, &y) } }; + } + let el = start.elapsed().as_secs_f64(); + eprintln!( + "pass {pass} {name}: {:.1} us per expert gate+up, {:.2} GB/s (sum {s})", + el * 1e6 / experts as f64, + w.len() as f64 / el / 1e9 + ); + } + if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() { + let y2 = random_act(nb, 0.01, &mut seed); + let ys = [y.as_slice(), y2.as_slice()]; + let start = std::time::Instant::now(); + let mut s = 0.0f32; + for r in w.chunks_exact(rb) { + let mut o = [0.0f32; 2]; + unsafe { + dot_multi512_impl::<21, 2>(r, &ys, &mut o, false); + } + s += o[0]; + } + let el = start.elapsed().as_secs_f64(); + eprintln!( + "pass {pass} multi512 x2 stack: {:.1} us per expert gate+up (sum {s})", + el * 1e6 / experts as f64 + ); + let start = std::time::Instant::now(); + let mut s = 0.0f32; + for r in w.chunks_exact(rb) { + let mut o = [0.0f32; 2]; + unsafe { + dot_multi512_impl::<21, 2>(r, &ys, &mut o, true); + } + s += o[0]; + } + let el = start.elapsed().as_secs_f64(); + eprintln!( + "pass {pass} multi512 x2 register: {:.1} us per expert gate+up (sum {s})", + el * 1e6 / experts as f64 + ); + } + // the down rows of the same experts: H=2560 rows of IQ4_NL over FF=640 (20 blocks of 18 bytes), one token + let dn = random_iq4nl(2560 * experts, 20, &mut seed); + let hq = random_q8zero(20, &mut seed); + let start = std::time::Instant::now(); + let mut s = 0.0f32; + for r in dn.chunks_exact(20 * 18) { + let mut o = [0.0f32]; + unsafe { + iq4nl(r, &[hq.as_slice()], &mut o, true); + } + s += o[0]; + } + let el = start.elapsed().as_secs_f64(); + eprintln!( + "pass {pass} iq4nl down x1: {:.1} us per expert down, {:.2} GB/s (sum {s})", + el * 1e6 / experts as f64, + dn.len() as f64 / el / 1e9 + ); + } +} +fn random_iq4nl(rows: usize, nb: usize, seed: &mut u64) -> Vec { + let mut v = vec![0u8; rows * nb * 18]; + for x in v.iter_mut() { + *x = xorshift(seed) as u8; + } + for b in v.chunks_exact_mut(18) { + let e = 8 + (xorshift(seed) % 8) as u16; + let m = (xorshift(seed) & 0x3ff) as u16; + b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + } + v +} +fn random_q8zero(nb: usize, seed: &mut u64) -> Vec { + let mut v = vec![Q8Zero::default(); nb]; + for b in v.iter_mut() { + b.d = 0x3c00; + for q in b.qs.iter_mut() { + *q = xorshift(seed) as i8; + } + } + v +} +#[test] +fn iq3_multi_trees_are_bitwise_equal() { + if !(super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok()) { + eprintln!("SKIP: AVX-512"); + return; + } + let mut seed = 0x3e3e_5eed_7777_0001u64; + let nb = 10usize; + macro_rules! cmp { + ($T:literal,$N:literal,$w:expr,$ys:expr) => {{ + let mut a = [0.0f32; $N]; + let mut b = [0.0f32; $N]; + for r in $w.chunks_exact(nb * format_bytes($T)) { + unsafe { + dot_multi512_impl::<$T, $N>(r, &$ys[..$N], &mut a, false); + dot_multi512_impl::<$T, $N>(r, &$ys[..$N], &mut b, true); + } + for k in 0..$N { + assert_eq!(a[k].to_bits(), b[k].to_bits(), "type {} tokens {} token {k}", $T, $N); + } + } + }}; + } + for round in 0..6 { + let acts: Vec> = + (0..4).map(|k| random_act(nb, 0.0003 + (round * 4 + k) as f32 * 0.21, &mut seed)).collect(); + let ys: Vec<&[Q8K]> = acts.iter().map(|y| y.as_slice()).collect(); + let w21 = random_rows(21, nb, 32, &mut seed); + let w18 = random_rows(18, nb, 32, &mut seed); + cmp!(21, 1, w21, ys); + cmp!(21, 2, w21, ys); + cmp!(21, 3, w21, ys); + cmp!(21, 4, w21, ys); + cmp!(18, 1, w18, ys); + cmp!(18, 2, w18, ys); + cmp!(18, 3, w18, ys); + cmp!(18, 4, w18, ys); + } +} +// IQ4_XS gate/up rows at two or more tokens on the AVX2 tree take the multi-token kernel (iq_avx2.cpp iq256_gu_rows, native_expert.cpp +// `!cpu512 && iq256_supported(23)`), not ggml's single-token dot: its last bits differ, and a Q2_0 down projection (not requantized +// to int8 as IQ4_NL's is) exposed it in KAB1 (STRA-324: cases 23-42-r2/r3/r8). +#[test] +fn iq4xs_multi_token_avx2_kernel_matches_the_scalar_model_bitwise() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + let mut seed = 0x5eed_1234_abcd_ef01u64; + let nb = 10usize; + for round in 0..6 { + let mut row = vec![0u8; nb * 136]; + for v in row.iter_mut() { + *v = xorshift(&mut seed) as u8; + } + for b in row.chunks_exact_mut(136) { + let e = 8 + (xorshift(&mut seed) % 8) as u16; + let m = (xorshift(&mut seed) & 0x3ff) as u16; + b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + } + let mut ys: Vec> = Vec::new(); + for _ in 0..8 { + let x: Vec = (0..nb * 256) + .map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * (0.001 + (round as f32))) + .collect(); + let mut y = vec![Q8K::default(); nb]; + q8_k(&x, &mut y); + ys.push(y); + } + for nt in [1usize, 2, 3, 5, 8] { + let refs: Vec<&[Q8K]> = ys[..nt].iter().map(|y| y.as_slice()).collect(); + let mut out = vec![0.0f32; nt]; + // SAFETY: avx2_ok() above; row is exactly nb blocks of 136 bytes and every Q8K row has nb blocks. + unsafe { + dot_multi256(23, &row, &refs, &mut out); + } + for t in 0..nt { + assert_eq!(out[t].to_bits(), model_iq4xs(&row, &ys[t]).to_bits(), "round {round} nt {nt} token {t}"); + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_iq/u16_fn.rs b/crates/native-cpu-expert/src/rust_iq/u16_fn.rs new file mode 100644 index 00000000..30cd3455 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_iq/u16_fn.rs @@ -0,0 +1,226 @@ +//! Moved out of the parent module by STRA-338: fn u16, fn u32, fn format_bytes, fn factor, fn decode, fn decoded .... + +#[allow(unused_imports)] +use super::*; + +// Bounds: `row` is walked with chunks_exact/checked slicing and every activation block is safe-indexed (`y[i]`), so a short +// operand panics instead of reading past it. The raw loads are 32/64 bytes at 64*j+32*h (j<4,h<2) of a 256-byte Q8K.qs, 16 +// bytes inside a block (<= block size), and the only data-dependent address is the optional gather: idx <= 255 into +// IQ3XXS_GRID[u32;256] and idx <= 511 into IQ3S_GRID[u32;512]. Gate: avx2_ok() / avx512_ok()+dq_ok(). +pub(super) fn u16(b: &[u8], o: usize) -> u16 { + u16::from_le_bytes(b[o..o + 2].try_into().unwrap()) +} +pub(super) fn u32(b: &[u8], o: usize) -> u32 { + u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) +} +pub(in super::super) fn format_bytes(t: i32) -> usize { + match t { + 16 => 66, + 17 => 74, + 18 => 98, + 21 => 110, + 22 => 82, + 23 => 136, + _ => unreachable!(), + } +} +pub(super) fn factor(t: i32) -> f32 { + match t { + 16 | 17 | 22 => 0.125, + 18 => 0.25, + 21 | 23 => 1.0, + _ => unreachable!(), + } +} +// Whole 32-value half: magnitude bytes, literal signs and 16-value integer scales. +#[inline(always)] +pub(super) fn decode(t: i32, b: &[u8], j: usize, h: usize) -> ([u8; 32], u32, [i16; 16]) { + let mut g = [0u8; 32]; + let mut signs = 0u32; + let (s0, s1); + match t { + 16 => { + let a = u32(b, 2 + 16 * j + 8 * h); + let w = u32(b, 6 + 16 * j + 8 * h); + for l in 0..4 { + g[l * 8..l * 8 + 8].copy_from_slice(&IQ2XXS_GRID[((a >> (8 * l)) & 255) as usize].to_le_bytes()); + signs |= (KSIGNS_IQ2XS[((w >> (7 * l)) & 127) as usize] as u32) << (8 * l); + } + let s = 2 * (w >> 28) as i16 + 1; + s0 = s; + s1 = s; + } + 17 => { + for l in 0..4 { + let v = u16(b, 2 + 16 * j + 8 * h + 2 * l); + g[l * 8..l * 8 + 8].copy_from_slice(&IQ2XS_GRID[(v & 511) as usize].to_le_bytes()); + signs |= (KSIGNS_IQ2XS[(v >> 9) as usize] as u32) << (8 * l); + } + let s = b[66 + 2 * j + h]; + s0 = 2 * (s & 15) as i16 + 1; + s1 = 2 * (s >> 4) as i16 + 1; + } + 22 => { + let q = &b[2 + 8 * j + 4 * h..]; + let high = b[66 + 2 * j + h] as usize; + for l in 0..4 { + let idx = q[l] as usize | ((high << (8 - 2 * l)) & 0x300); + g[l * 8..l * 8 + 8].copy_from_slice(&IQ2S_GRID[idx].to_le_bytes()); + } + signs = u32(b, 34 + 8 * j + 4 * h); + let s = b[74 + 2 * j + h]; + s0 = 2 * (s & 15) as i16 + 1; + s1 = 2 * (s >> 4) as i16 + 1; + } + 18 => { + let q = &b[2 + 16 * j + 8 * h..]; + for l in 0..8 { + g[l * 4..l * 4 + 4].copy_from_slice(&IQ3XXS_GRID[q[l] as usize].to_le_bytes()); + } + let w = u32(b, 66 + 8 * j + 4 * h); + for l in 0..4 { + signs |= (KSIGNS_IQ2XS[((w >> (7 * l)) & 127) as usize] as u32) << (8 * l); + } + s0 = 2 * (w >> 28) as i16 + 1; + s1 = s0; + } + 21 => { + let q = &b[2 + 16 * j + 8 * h..]; + let high = b[66 + 2 * j + h] as usize; + for l in 0..8 { + g[l * 4..l * 4 + 4].copy_from_slice(&IQ3S_GRID[q[l] as usize | (((high >> l) & 1) << 8)].to_le_bytes()); + } + signs = u32(b, 74 + 8 * j + 4 * h); + let s = b[106 + j]; + s0 = 2 * (if h == 0 { s & 15 } else { s >> 4 }) as i16 + 1; + s1 = s0; + } + // IQ4_XS (AVX2 multi-token tree only, STRA-324): iq_avx2.cpp Fmt32<23>::decode. `g` = |kvalues|, the sign bit = (kvalue<0) + // (no kvalue is 0), scale = the signed 6-bit sub-block scale ls-32 of sub-block 2j+h. + 23 => { + let hh = 2 * j + h; + let bits = &b[8 + 16 * hh..8 + 16 * hh + 16]; + for l in 0..16 { + let lo = KVALUES_IQ4NL[(bits[l] & 15) as usize]; + let hi = KVALUES_IQ4NL[(bits[l] >> 4) as usize]; + g[l] = lo.unsigned_abs(); + g[16 + l] = hi.unsigned_abs(); + if lo < 0 { + signs |= 1 << l; + } + if hi < 0 { + signs |= 1 << (16 + l); + } + } + let ls = ((b[4 + (hh >> 1)] >> (4 * (hh & 1))) & 15) as i16 | ((((u16(b, 2) >> (2 * hh)) & 3) as i16) << 4); + s0 = ls - 32; + s1 = s0; + } + _ => unreachable!(), + } + let mut sc = [s0; 16]; + sc[8..].fill(s1); + (g, signs, sc) +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn decoded(t: i32, b: &[u8], j: usize, h: usize) -> (__m256i, __m256i, __m256i) { + unsafe { + let (g, s, sc) = decode(t, b, j, h); + (_mm256_loadu_si256(g.as_ptr().cast()), signs32(s), _mm256_loadu_si256(sc.as_ptr().cast())) + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(in super::super) unsafe fn dot_multi256(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) { + unsafe { + assert!(ys.len() <= 8 && ys.len() == out.len()); + let nb = ys[0].len(); + assert_eq!(row.len(), nb * format_bytes(t)); + let mut accf = [_mm256_setzero_ps(); 8]; + for i in 0..nb { + let b = &row[i * format_bytes(t)..][..format_bytes(t)]; + prefetch(b.as_ptr()); + let mut ai = [_mm256_setzero_si256(); 8]; + for j in 0..4 { + for h in 0..2 { + let (g, sgn, sc) = decoded(t, b, j, h); + for (k, y) in ys.iter().enumerate() { + let v = _mm256_loadu_si256(y[i].qs.as_ptr().add(64 * j + 32 * h).cast()); + let sy = _mm256_sign_epi8(v, sgn); + ai[k] = _mm256_add_epi32(ai[k], _mm256_madd_epi16(_mm256_maddubs_epi16(g, sy), sc)); + } + } + } + let dx = half(u16(b, 0)) * factor(t); + for (k, y) in ys.iter().enumerate() { + accf[k] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[i].d), _mm256_cvtepi32_ps(ai[k]), accf[k]); + } + } + for (k, r) in out.iter_mut().enumerate() { + *r = hsum_original(accf[k]); + } + } +} +/// The multi-token IQ kernel, specialised on the format and the token count (iq_avx512.cpp templates its +/// `row_dot` the same way): the same operations in the same order per token, so the same bits. +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] +pub(in super::super) unsafe fn dot_multi512(t: i32, row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) { + unsafe { + macro_rules! by_n { + ($T:literal) => { + match ys.len() { + 1 => dot_multi512_tn::<$T, 1>(row, ys, out), + 2 => dot_multi512_tn::<$T, 2>(row, ys, out), + 3 => dot_multi512_tn::<$T, 3>(row, ys, out), + 4 => dot_multi512_tn::<$T, 4>(row, ys, out), + 5 => dot_multi512_tn::<$T, 5>(row, ys, out), + 6 => dot_multi512_tn::<$T, 6>(row, ys, out), + 7 => dot_multi512_tn::<$T, 7>(row, ys, out), + 8 => dot_multi512_tn::<$T, 8>(row, ys, out), + _ => panic!("dot_multi512: 1..=8 tokens"), + } + }; + } + match t { + 16 => by_n!(16), + 17 => by_n!(17), + 18 => by_n!(18), + 21 => by_n!(21), + 22 => by_n!(22), + _ => unreachable!(), + } + } +} +/// `LELEKA_IQ_MULTI=register` (opt-in, measured SLOWER on the 9950X3D: 2 tokens 36.2 against 29.4 us of gate/up drain per expert in +/// `cpu_service_bench`, runs/cpu-service2 bench out-b) builds the multi-token AVX-512 IQ3 halves in registers; the default keeps the stack arrays. +pub(super) fn iq3_multi_fast() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_IQ_MULTI").as_deref() == Ok("register")) +} +/// One 32-weight half of an IQ3_S (21) / IQ3_XXS (18) block in a register: the eight grid words (lane l = word l, `decode`'s bytes 4l..4l+4), +/// the sign word `decode` returns and its (uniform) 16-bit scale. +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn iq3_half(b: &[u8], j: usize, h: usize) -> (__m256i, u32, i16) { + let q = &b[2 + 16 * j + 8 * h..2 + 16 * j + 8 * h + 8]; + if T == 21 { + let high = b[66 + 2 * j + h] as usize; + let w = |l: usize| IQ3S_GRID[q[l] as usize | (((high >> l) & 1) << 8)] as i32; + let sv = b[106 + j]; + ( + _mm256_setr_epi32(w(0), w(1), w(2), w(3), w(4), w(5), w(6), w(7)), + u32(b, 74 + 8 * j + 4 * h), + 2 * (if h == 0 { sv & 15 } else { sv >> 4 }) as i16 + 1, + ) + } else { + let w = |l: usize| IQ3XXS_GRID[q[l] as usize] as i32; + let ws = u32(b, 66 + 8 * j + 4 * h); + let mut signs = 0u32; + for l in 0..4 { + signs |= (KSIGNS_IQ2XS[((ws >> (7 * l)) & 127) as usize] as u32) << (8 * l); + } + (_mm256_setr_epi32(w(0), w(1), w(2), w(3), w(4), w(5), w(6), w(7)), signs, 2 * (ws >> 28) as i16 + 1) + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] +pub(super) unsafe fn dot_multi512_tn(row: &[u8], ys: &[&[Q8K]], out: &mut [f32]) { + unsafe { dot_multi512_impl::(row, ys, out, iq3_multi_fast()) } +} diff --git a/crates/native-cpu-expert/src/rust_iq1_grid.rs b/crates/native-cpu-expert/src/rust_iq1_grid.rs index c0c6ea8c..c850266b 100644 --- a/crates/native-cpu-expert/src/rust_iq1_grid.rs +++ b/crates/native-cpu-expert/src/rust_iq1_grid.rs @@ -1,259 +1,2051 @@ //! Literal pinned GGML IQ1 grid; see LICENSE.ggml. -pub(super) const GRID:[u64;2048]=[ -0xffffffffffffffff,0xffffffffffffff01,0xffffffffffff0000,0xffffffffffff01ff,0xffffffffffff0101,0xffffffffff00ff00,0xffffffffff000000,0xffffffffff01ffff, -0xffffffffff01ff01,0xffffffffff0101ff,0xffffffffff010101,0xffffffff00ff0000,0xffffffff0000ff00,0xffffffff000000ff,0xffffffff00000001,0xffffffff00010000, -0xffffffff01ffffff,0xffffffff01ffff01,0xffffffff01ff01ff,0xffffffff01ff0101,0xffffffff01000000,0xffffffff0101ffff,0xffffffff0101ff01,0xffffffff010101ff, -0xffffffff01010101,0xffffff00ffff00ff,0xffffff00ffff0000,0xffffff00ff00ff00,0xffffff00ff0000ff,0xffffff00ff000001,0xffffff00ff000100,0xffffff00ff000101, -0xffffff00ff010000,0xffffff0000ffff00,0xffffff0000ff0001,0xffffff0000ff0100,0xffffff000000ff01,0xffffff0000000000,0xffffff0000000101,0xffffff000001ff00, -0xffffff00000100ff,0xffffff0000010001,0xffffff00000101ff,0xffffff0001ff0000,0xffffff000100ff00,0xffffff00010000ff,0xffffff0001000001,0xffffff0001010000, -0xffffff01ffffffff,0xffffff01ffffff01,0xffffff01ffff01ff,0xffffff01ffff0101,0xffffff01ff000000,0xffffff01ff01ffff,0xffffff01ff01ff01,0xffffff01ff0101ff, -0xffffff01ff010101,0xffffff0100ff0000,0xffffff010000ff00,0xffffff0100000100,0xffffff01000100ff,0xffffff0100010100,0xffffff0101ffffff,0xffffff0101ffff01, -0xffffff0101ff01ff,0xffffff0101ff0101,0xffffff010100ff00,0xffffff0101000000,0xffffff0101000100,0xffffff010101ffff,0xffffff010101ff01,0xffffff01010101ff, -0xffffff0101010101,0xffff00ffff00ff00,0xffff00ffff0000ff,0xffff00ffff000001,0xffff00ffff010000,0xffff00ff00ffff00,0xffff00ff00ff0100,0xffff00ff00000000, -0xffff00ff00000101,0xffff00ff000100ff,0xffff00ff00010000,0xffff00ff0100ff00,0xffff00ff01000100,0xffff00ff01010000,0xffff0000ffffff00,0xffff0000ffff00ff, -0xffff0000ffff0000,0xffff0000ffff0001,0xffff0000ff000000,0xffff0000ff0001ff,0xffff0000ff000101,0xffff0000ff010100,0xffff000000ffffff,0xffff000000ff0000, -0xffff000000ff0101,0xffff00000000ffff,0xffff00000000ff00,0xffff0000000000ff,0xffff000000000000,0xffff000000000001,0xffff000000000100,0xffff00000001ffff, -0xffff00000001ff01,0xffff000000010000,0xffff0000000101ff,0xffff000000010101,0xffff000001ffff00,0xffff00000100ff00,0xffff000001000000,0xffff0000010001ff, -0xffff000001000101,0xffff00000101ff00,0xffff0000010100ff,0xffff000001010000,0xffff000001010001,0xffff000001010100,0xffff0001ff0000ff,0xffff0001ff000100, -0xffff000100ffff00,0xffff000100ff00ff,0xffff00010000ffff,0xffff00010000ff01,0xffff000100000000,0xffff0001000001ff,0xffff00010001ffff,0xffff00010001ff00, -0xffff000100010001,0xffff000100010100,0xffff000101ff0000,0xffff00010100ff00,0xffff0001010000ff,0xffff000101000100,0xffff01ffffffffff,0xffff01ffffffff01, -0xffff01ffffff01ff,0xffff01ffffff0101,0xffff01ffff000000,0xffff01ffff01ffff,0xffff01ffff01ff01,0xffff01ffff0101ff,0xffff01ffff010101,0xffff01ff00ff0000, -0xffff01ff0000ff00,0xffff01ff00000001,0xffff01ff00010000,0xffff01ff01ffffff,0xffff01ff01ffff01,0xffff01ff01ff01ff,0xffff01ff01ff0101,0xffff01ff01000000, -0xffff01ff0101ffff,0xffff01ff0101ff01,0xffff01ff010101ff,0xffff01ff01010101,0xffff0100ffff0000,0xffff0100ff00ff00,0xffff0100ff0000ff,0xffff0100ff000100, -0xffff0100ff0100ff,0xffff0100ff010000,0xffff010000ffff00,0xffff01000000ffff,0xffff01000000ff00,0xffff010000000000,0xffff01000001ff00,0xffff0100000100ff, -0xffff010000010100,0xffff01000100ff00,0xffff0100010000ff,0xffff010001000001,0xffff010001000100,0xffff010001010000,0xffff0101ffffffff,0xffff0101ffffff01, -0xffff0101ffff01ff,0xffff0101ffff0101,0xffff0101ff000000,0xffff0101ff01ffff,0xffff0101ff01ff01,0xffff0101ff0101ff,0xffff0101ff010101,0xffff010100ff0000, -0xffff01010000ff00,0xffff010100000100,0xffff01010001ff00,0xffff010100010000,0xffff010101ffffff,0xffff010101ffff01,0xffff010101ff0000,0xffff010101ff01ff, -0xffff010101ff0101,0xffff010101000000,0xffff01010101ffff,0xffff01010101ff01,0xffff0101010101ff,0xffff010101010101,0xff00ffffff00ffff,0xff00ffffff00ff00, -0xff00ffffff0000ff,0xff00ffffff000100,0xff00ffffff0100ff,0xff00ffffff010000,0xff00ffff00ffff00,0xff00ffff00ff00ff,0xff00ffff0000ffff,0xff00ffff00000000, -0xff00ffff000001ff,0xff00ffff0001ff00,0xff00ffff000100ff,0xff00ffff00010000,0xff00ffff00010100,0xff00ffff0100ff00,0xff00ffff010000ff,0xff00ffff01000001, -0xff00ffff0101ff00,0xff00ffff01010000,0xff00ff00ffffff00,0xff00ff00ffff00ff,0xff00ff00ffff0001,0xff00ff00ffff0100,0xff00ff00ff00ffff,0xff00ff00ff00ff01, -0xff00ff00ff000000,0xff00ff00ff0001ff,0xff00ff00ff01ff00,0xff00ff00ff0100ff,0xff00ff00ff010100,0xff00ff0000ff0000,0xff00ff0000ff0101,0xff00ff000000ffff, -0xff00ff000000ff00,0xff00ff000000ff01,0xff00ff00000000ff,0xff00ff0000000000,0xff00ff0000000001,0xff00ff0000000100,0xff00ff000001ffff,0xff00ff0000010000, -0xff00ff0001ff00ff,0xff00ff000100ff01,0xff00ff0001000000,0xff00ff000101ff00,0xff00ff00010100ff,0xff00ff01ff00ff00,0xff00ff01ff0000ff,0xff00ff01ff000001, -0xff00ff01ff010000,0xff00ff0100ffffff,0xff00ff0100ff0001,0xff00ff0100ff0100,0xff00ff010000ff01,0xff00ff0100000000,0xff00ff01000001ff,0xff00ff0100000101, -0xff00ff01000100ff,0xff00ff0100010001,0xff00ff0101ff0000,0xff00ff010100ff00,0xff00ff01010000ff,0xff00ff0101000001,0xff00ff0101010000,0xff0000ffffffff00, -0xff0000ffffff0001,0xff0000ffffff0100,0xff0000ffff0000ff,0xff0000ffff000000,0xff0000ffff0001ff,0xff0000ffff000100,0xff0000ffff01ff00,0xff0000ffff010001, -0xff0000ff00ffff00,0xff0000ff00ff0000,0xff0000ff00ff0001,0xff0000ff00ff01ff,0xff0000ff00ff0101,0xff0000ff0000ff00,0xff0000ff000000ff,0xff0000ff00000000, -0xff0000ff00000001,0xff0000ff00000100,0xff0000ff0001ff01,0xff0000ff00010000,0xff0000ff000101ff,0xff0000ff01ff00ff,0xff0000ff01ff0100,0xff0000ff0100ffff, -0xff0000ff010000ff,0xff0000ff01000000,0xff0000ff010001ff,0xff0000ff01000100,0xff0000ff01000101,0xff0000ff0101ff00,0xff0000ff010100ff,0xff0000ff01010000, -0xff0000ff01010100,0xff000000ffffff01,0xff000000ffff0000,0xff000000ffff0101,0xff000000ff00ff00,0xff000000ff0000ff,0xff000000ff000000,0xff000000ff000001, -0xff000000ff000100,0xff000000ff01ffff,0xff000000ff01ff01,0xff000000ff010000,0xff000000ff0101ff,0xff000000ff010101,0xff00000000ffff00,0xff00000000ff00ff, -0xff00000000ff0000,0xff00000000ff0001,0xff0000000000ff00,0xff0000000000ff01,0xff000000000000ff,0xff00000000000000,0xff00000000000001,0xff00000000000100, -0xff00000000000101,0xff0000000001ff00,0xff000000000100ff,0xff00000000010000,0xff00000000010001,0xff00000000010100,0xff00000001ffffff,0xff00000001ffff01, -0xff00000001ff00ff,0xff00000001ff0000,0xff00000001ff01ff,0xff00000001ff0101,0xff0000000100ffff,0xff0000000100ff00,0xff000000010000ff,0xff00000001000000, -0xff00000001000001,0xff00000001000100,0xff00000001000101,0xff0000000101ffff,0xff0000000101ff01,0xff00000001010000,0xff000001ffffff00,0xff000001ffff00ff, -0xff000001ffff0000,0xff000001ffff0001,0xff000001ff000000,0xff000001ff000001,0xff000001ff0001ff,0xff000001ff000101,0xff000001ff01ff00,0xff000001ff010001, -0xff00000100ffffff,0xff00000100ffff01,0xff00000100ff00ff,0xff00000100ff0000,0xff00000100ff01ff,0xff00000100ff0101,0xff0000010000ff00,0xff00000100000000, -0xff00000100000001,0xff000001000001ff,0xff00000100000100,0xff0000010001ff00,0xff000001000100ff,0xff00000100010000,0xff000001000101ff,0xff00000100010100, -0xff00000100010101,0xff00000101ff0001,0xff00000101ff0101,0xff0000010100ff01,0xff00000101000000,0xff000001010100ff,0xff00000101010100,0xff0001ffff00ff00, -0xff0001ffff000001,0xff0001ffff010000,0xff0001ff00ffff00,0xff0001ff00ff00ff,0xff0001ff00ff0001,0xff0001ff00ff0100,0xff0001ff0000ffff,0xff0001ff00000000, -0xff0001ff000001ff,0xff0001ff00000101,0xff0001ff0001ffff,0xff0001ff0001ff00,0xff0001ff000100ff,0xff0001ff00010001,0xff0001ff00010100,0xff0001ff01ff0000, -0xff0001ff0100ff00,0xff0001ff010000ff,0xff0001ff01010000,0xff000100ff00ffff,0xff000100ff00ff01,0xff000100ff000000,0xff000100ff000101,0xff000100ff01ff00, -0xff000100ff010000,0xff00010000ffff01,0xff00010000ff00ff,0xff00010000ff0000,0xff00010000ff01ff,0xff0001000000ff00,0xff000100000000ff,0xff00010000000000, -0xff00010000000001,0xff00010000000100,0xff00010000000101,0xff0001000001ffff,0xff00010000010000,0xff00010000010101,0xff00010001ff0100,0xff0001000100ff00, -0xff0001000100ff01,0xff00010001000000,0xff000100010001ff,0xff0001000101ff00,0xff00010001010001,0xff00010001010100,0xff000101ffff0100,0xff000101ff000001, -0xff000101ff0100ff,0xff000101ff010001,0xff00010100ff00ff,0xff00010100ff0001,0xff00010100ff0100,0xff0001010000ffff,0xff0001010000ff01,0xff00010100000000, -0xff000101000001ff,0xff0001010001ff00,0xff00010100010001,0xff00010100010100,0xff00010101ff0000,0xff0001010100ff00,0xff00010101000001,0xff00010101000101, -0xff01ffffffffffff,0xff01ffffffffff01,0xff01ffffffff01ff,0xff01ffffffff0101,0xff01ffffff000000,0xff01ffffff01ffff,0xff01ffffff01ff01,0xff01ffffff010000, -0xff01ffffff0101ff,0xff01ffffff010101,0xff01ffff00ff0000,0xff01ffff0000ff00,0xff01ffff00000100,0xff01ffff0001ff00,0xff01ffff00010000,0xff01ffff01ffffff, -0xff01ffff01ffff01,0xff01ffff01ff01ff,0xff01ffff01ff0101,0xff01ffff01000000,0xff01ffff0101ffff,0xff01ffff0101ff01,0xff01ffff01010000,0xff01ffff010101ff, -0xff01ffff01010101,0xff01ff00ffff0000,0xff01ff00ff00ff00,0xff01ff00ff0000ff,0xff01ff00ff000100,0xff01ff00ff010000,0xff01ff0000ffff01,0xff01ff0000ff00ff, -0xff01ff0000ff0100,0xff01ff0000000000,0xff01ff00000001ff,0xff01ff0000000101,0xff01ff000001ff00,0xff01ff00000100ff,0xff01ff0000010000,0xff01ff0000010001, -0xff01ff0001ff0000,0xff01ff000100ffff,0xff01ff0001000001,0xff01ff0001000100,0xff01ff0001010000,0xff01ff01ffffff00,0xff01ff01ffff01ff,0xff01ff01ffff0101, -0xff01ff01ff00ff00,0xff01ff01ff000000,0xff01ff01ff01ffff,0xff01ff01ff01ff01,0xff01ff01ff0101ff,0xff01ff01ff010101,0xff01ff0100ff0000,0xff01ff010000ff00, -0xff01ff0100000001,0xff01ff0100000100,0xff01ff0100010000,0xff01ff0101ffff00,0xff01ff0101ff01ff,0xff01ff0101ff0101,0xff01ff010100ff00,0xff01ff0101000000, -0xff01ff010101ffff,0xff01ff010101ff01,0xff01ff01010101ff,0xff01ff0101010101,0xff0100ffffff0000,0xff0100ffff0000ff,0xff0100ffff000001,0xff0100ffff000100, -0xff0100ffff010000,0xff0100ff00ff00ff,0xff0100ff00ff0000,0xff0100ff00ff0001,0xff0100ff00ff0100,0xff0100ff0000ff01,0xff0100ff00000000,0xff0100ff000001ff, -0xff0100ff00000101,0xff0100ff00010001,0xff0100ff01ff0000,0xff0100ff0100ff00,0xff0100ff010000ff,0xff0100ff01000100,0xff0100ff0101ff00,0xff0100ff01010000, -0xff010000ffff0100,0xff010000ff000000,0xff010000ff01ff00,0xff010000ff010100,0xff01000000ffffff,0xff01000000ff0000,0xff01000000ff01ff,0xff0100000000ff00, -0xff010000000000ff,0xff01000000000000,0xff01000000000100,0xff0100000001ff01,0xff01000000010000,0xff010000000101ff,0xff01000001ff0100,0xff0100000100ffff, -0xff010000010000ff,0xff01000001000000,0xff010000010001ff,0xff01000001000101,0xff0100000101ff00,0xff010000010100ff,0xff01000001010001,0xff01000001010100, -0xff010001ffff0000,0xff010001ff00ffff,0xff010001ff00ff01,0xff010001ff000100,0xff010001ff010000,0xff01000100ffff00,0xff01000100ff0100,0xff01000100000000, -0xff0100010001ffff,0xff0100010001ff00,0xff01000100010100,0xff01000101ff00ff,0xff01000101ff0001,0xff0100010100ffff,0xff01000101000101,0xff0101ffffffffff, -0xff0101ffffffff01,0xff0101ffffff01ff,0xff0101ffffff0101,0xff0101ffff000000,0xff0101ffff01ffff,0xff0101ffff01ff01,0xff0101ffff0101ff,0xff0101ffff010101, -0xff0101ff00ff0000,0xff0101ff0000ff00,0xff0101ff000000ff,0xff0101ff00010000,0xff0101ff01ffffff,0xff0101ff01ffff01,0xff0101ff01ff01ff,0xff0101ff01ff0101, -0xff0101ff0101ffff,0xff0101ff0101ff01,0xff0101ff010101ff,0xff0101ff01010101,0xff010100ffff0100,0xff010100ff00ff00,0xff010100ff0000ff,0xff010100ff000100, -0xff010100ff010000,0xff01010000ff0001,0xff01010000ff0100,0xff0101000000ff01,0xff01010000000000,0xff0101000001ff00,0xff010100000100ff,0xff01010000010001, -0xff01010000010100,0xff01010001ff0000,0xff0101000100ffff,0xff01010001000001,0xff01010001000100,0xff010100010100ff,0xff01010001010000,0xff010101ffffffff, -0xff010101ffffff01,0xff010101ffff01ff,0xff010101ffff0101,0xff010101ff01ffff,0xff010101ff01ff01,0xff010101ff0101ff,0xff010101ff010101,0xff01010100ff0000, -0xff0101010000ff00,0xff01010100000001,0xff01010100000100,0xff01010100010000,0xff01010101ffffff,0xff01010101ffff01,0xff01010101ff01ff,0xff01010101ff0101, -0xff01010101000000,0xff0101010101ffff,0xff0101010101ff01,0xff010101010101ff,0xff01010101010101,0x00ffffffffff0000,0x00ffffffff00ff00,0x00ffffffff000001, -0x00ffffffff010000,0x00ffffff00ff0100,0x00ffffff0000ff01,0x00ffffff00000000,0x00ffffff000001ff,0x00ffffff00000101,0x00ffffff0001ff00,0x00ffffff000100ff, -0x00ffffff00010001,0x00ffffff010000ff,0x00ffffff01000100,0x00ffffff0101ff00,0x00ffffff01010001,0x00ffff00ffffffff,0x00ffff00ffffff00,0x00ffff00ffff00ff, -0x00ffff00ffff0001,0x00ffff00ffff0100,0x00ffff00ff00ff01,0x00ffff00ff000000,0x00ffff00ff000001,0x00ffff00ff0001ff,0x00ffff00ff000101,0x00ffff00ff01ff00, -0x00ffff00ff010001,0x00ffff00ff010100,0x00ffff0000ff0000,0x00ffff0000ff01ff,0x00ffff0000ff0101,0x00ffff000000ff00,0x00ffff00000000ff,0x00ffff0000000000, -0x00ffff0000000001,0x00ffff0000000100,0x00ffff0000000101,0x00ffff0000010000,0x00ffff00000101ff,0x00ffff0000010101,0x00ffff0001ffff00,0x00ffff0001ff00ff, -0x00ffff0001ff0001,0x00ffff000100ffff,0x00ffff000100ff01,0x00ffff0001000000,0x00ffff000101ffff,0x00ffff000101ff00,0x00ffff000101ff01,0x00ffff01ffff0000, -0x00ffff01ff00ff00,0x00ffff01ff0000ff,0x00ffff01ff000001,0x00ffff01ff010000,0x00ffff0100ffff00,0x00ffff010000ff01,0x00ffff0100000000,0x00ffff0100000101, -0x00ffff01000100ff,0x00ffff0100010100,0x00ffff0101ff0100,0x00ffff01010000ff,0x00ffff0101010000,0x00ff00ffffffff00,0x00ff00ffff000000,0x00ff00ffff000100, -0x00ff00ffff010100,0x00ff00ff00ff0000,0x00ff00ff00ff01ff,0x00ff00ff00ff0101,0x00ff00ff0000ff00,0x00ff00ff000000ff,0x00ff00ff00000000,0x00ff00ff00000001, -0x00ff00ff0001ff00,0x00ff00ff0001ff01,0x00ff00ff00010000,0x00ff00ff000101ff,0x00ff00ff00010101,0x00ff00ff01ffff00,0x00ff00ff01ff0001,0x00ff00ff01ff0100, -0x00ff00ff0100ffff,0x00ff00ff0100ff01,0x00ff00ff01000000,0x00ff00ff0101ffff,0x00ff00ff0101ff00,0x00ff00ff01010100,0x00ff0000ffffff00,0x00ff0000ffffff01, -0x00ff0000ffff0000,0x00ff0000ffff0101,0x00ff0000ff00ff00,0x00ff0000ff0000ff,0x00ff0000ff000000,0x00ff0000ff000001,0x00ff0000ff000100,0x00ff0000ff01ffff, -0x00ff0000ff010000,0x00ff0000ff010101,0x00ff000000ffff00,0x00ff000000ff00ff,0x00ff000000ff0000,0x00ff000000ff0001,0x00ff000000ff0100,0x00ff00000000ffff, -0x00ff00000000ff00,0x00ff0000000000ff,0x00ff000000000000,0x00ff000000000001,0x00ff0000000001ff,0x00ff000000000100,0x00ff00000001ff00,0x00ff0000000100ff, -0x00ff000000010000,0x00ff000000010001,0x00ff000000010100,0x00ff000001ffff01,0x00ff000001ff00ff,0x00ff000001ff0000,0x00ff000001ff01ff,0x00ff00000100ff00, -0x00ff0000010000ff,0x00ff000001000000,0x00ff000001000001,0x00ff000001000100,0x00ff000001000101,0x00ff000001010000,0x00ff0000010101ff,0x00ff000001010101, -0x00ff0001ffffff00,0x00ff0001ffff0000,0x00ff0001ffff0100,0x00ff0001ff0000ff,0x00ff0001ff000000,0x00ff0001ff0001ff,0x00ff0001ff000101,0x00ff0001ff01ff00, -0x00ff0001ff0100ff,0x00ff0001ff010100,0x00ff000100ffffff,0x00ff000100ffff01,0x00ff000100ff0000,0x00ff000100ff01ff,0x00ff00010000ffff,0x00ff00010000ff00, -0x00ff00010000ff01,0x00ff000100000000,0x00ff000100000001,0x00ff000100000100,0x00ff00010001ff01,0x00ff000100010000,0x00ff0001000101ff,0x00ff000101ffff00, -0x00ff000101ff0000,0x00ff000101ff0101,0x00ff0001010000ff,0x00ff000101000000,0x00ff00010101ff00,0x00ff0001010100ff,0x00ff000101010001,0x00ff01ffffff0000, -0x00ff01ffff00ff00,0x00ff01ffff000000,0x00ff01ffff000101,0x00ff01ffff010000,0x00ff01ff00ffff01,0x00ff01ff00ff0100,0x00ff01ff0000ffff,0x00ff01ff00000000, -0x00ff01ff000001ff,0x00ff01ff0001ff00,0x00ff01ff000100ff,0x00ff01ff00010001,0x00ff01ff00010100,0x00ff01ff01ff0000,0x00ff01ff0100ff00,0x00ff01ff010000ff, -0x00ff01ff01000001,0x00ff01ff01000100,0x00ff01ff01010000,0x00ff0100ffffff00,0x00ff0100ffff0000,0x00ff0100ffff0001,0x00ff0100ffff0101,0x00ff0100ff00ffff, -0x00ff0100ff0000ff,0x00ff0100ff000000,0x00ff0100ff0001ff,0x00ff0100ff01ff00,0x00ff0100ff0100ff,0x00ff0100ff010001,0x00ff010000ffffff,0x00ff010000ff0000, -0x00ff010000ff0101,0x00ff01000000ff00,0x00ff01000000ff01,0x00ff0100000000ff,0x00ff010000000000,0x00ff010000000001,0x00ff010000000100,0x00ff01000001ffff, -0x00ff01000001ff01,0x00ff010000010000,0x00ff010000010001,0x00ff010000010101,0x00ff010001ff0001,0x00ff010001ff0100,0x00ff01000100ff01,0x00ff010001000000, -0x00ff010001000001,0x00ff0100010001ff,0x00ff01000101ff00,0x00ff0100010100ff,0x00ff010001010001,0x00ff010001010100,0x00ff0101ff000001,0x00ff010100ff00ff, -0x00ff010100ff0001,0x00ff010100ff0100,0x00ff010100000000,0x00ff0101000001ff,0x00ff010100000101,0x00ff0101000100ff,0x00ff010100010100,0x00ff0101010000ff, -0x00ff010101010000,0x0000ffffffffff00,0x0000ffffffff00ff,0x0000ffffffff0000,0x0000ffffffff0001,0x0000ffffffff0100,0x0000ffffff00ff01,0x0000ffffff000000, -0x0000ffffff000101,0x0000ffffff01ff00,0x0000ffffff0100ff,0x0000ffffff010100,0x0000ffff00ffffff,0x0000ffff00ff0000,0x0000ffff00ff01ff,0x0000ffff0000ff00, -0x0000ffff000000ff,0x0000ffff00000000,0x0000ffff00000001,0x0000ffff00000100,0x0000ffff00010000,0x0000ffff000101ff,0x0000ffff01ff0001,0x0000ffff01ff0100, -0x0000ffff01000000,0x0000ffff010001ff,0x0000ffff0101ffff,0x0000ffff0101ff00,0x0000ffff01010001,0x0000ffff01010100,0x0000ff00ffff0000,0x0000ff00ffff01ff, -0x0000ff00ffff0100,0x0000ff00ffff0101,0x0000ff00ff00ff00,0x0000ff00ff0000ff,0x0000ff00ff000000,0x0000ff00ff000001,0x0000ff00ff0001ff,0x0000ff00ff000100, -0x0000ff00ff01ffff,0x0000ff00ff010000,0x0000ff00ff010001,0x0000ff00ff0101ff,0x0000ff00ff010101,0x0000ff0000ffff00,0x0000ff0000ff00ff,0x0000ff0000ff0000, -0x0000ff0000ff0001,0x0000ff0000ff0100,0x0000ff000000ffff,0x0000ff000000ff00,0x0000ff000000ff01,0x0000ff00000000ff,0x0000ff0000000000,0x0000ff0000000001, -0x0000ff00000001ff,0x0000ff0000000100,0x0000ff0000000101,0x0000ff000001ff00,0x0000ff00000100ff,0x0000ff0000010000,0x0000ff0000010001,0x0000ff0000010100, -0x0000ff0001ffff01,0x0000ff0001ff0000,0x0000ff000100ff00,0x0000ff00010000ff,0x0000ff0001000000,0x0000ff0001000001,0x0000ff0001000100,0x0000ff000101ffff, -0x0000ff0001010000,0x0000ff0001010101,0x0000ff01ffffff00,0x0000ff01ffff0001,0x0000ff01ff00ff01,0x0000ff01ff000000,0x0000ff01ff000101,0x0000ff01ff01ff00, -0x0000ff01ff0100ff,0x0000ff0100ffff01,0x0000ff0100ff0000,0x0000ff0100ff0101,0x0000ff010000ff00,0x0000ff01000000ff,0x0000ff0100000000,0x0000ff0100000001, -0x0000ff0100000100,0x0000ff010001ff01,0x0000ff0100010000,0x0000ff0101ff0000,0x0000ff010100ffff,0x0000ff010100ff01,0x0000ff0101000000,0x0000ff0101000100, -0x0000ff0101000101,0x0000ff01010100ff,0x000000ffffff00ff,0x000000ffffff0000,0x000000ffff00ff00,0x000000ffff0000ff,0x000000ffff000000,0x000000ffff000001, -0x000000ffff0001ff,0x000000ffff000100,0x000000ffff01ff00,0x000000ffff010000,0x000000ffff0101ff,0x000000ffff010101,0x000000ff00ffff00,0x000000ff00ff00ff, -0x000000ff00ff0000,0x000000ff00ff0001,0x000000ff00ff0100,0x000000ff00ff0101,0x000000ff0000ffff,0x000000ff0000ff00,0x000000ff000000ff,0x000000ff00000000, -0x000000ff00000001,0x000000ff000001ff,0x000000ff00000100,0x000000ff00000101,0x000000ff0001ff00,0x000000ff0001ff01,0x000000ff000100ff,0x000000ff00010000, -0x000000ff00010001,0x000000ff00010100,0x000000ff01ffffff,0x000000ff01ff01ff,0x000000ff01ff0101,0x000000ff0100ff00,0x000000ff010000ff,0x000000ff01000000, -0x000000ff01000001,0x000000ff01000100,0x000000ff0101ff00,0x000000ff010100ff,0x000000ff01010000,0x000000ff01010101,0x00000000ffffff00,0x00000000ffffff01, -0x00000000ffff00ff,0x00000000ffff0000,0x00000000ffff0001,0x00000000ffff0100,0x00000000ff00ffff,0x00000000ff00ff00,0x00000000ff00ff01,0x00000000ff0000ff, -0x00000000ff000000,0x00000000ff000001,0x00000000ff000100,0x00000000ff000101,0x00000000ff01ff00,0x00000000ff0100ff,0x00000000ff010000,0x00000000ff010001, -0x00000000ff010100,0x0000000000ffffff,0x0000000000ffff00,0x0000000000ffff01,0x0000000000ff00ff,0x0000000000ff0000,0x0000000000ff0001,0x0000000000ff01ff, -0x0000000000ff0100,0x000000000000ffff,0x000000000000ff00,0x000000000000ff01,0x00000000000000ff,0x0000000000000000,0x0000000000000001,0x00000000000001ff, -0x0000000000000100,0x0000000000000101,0x000000000001ffff,0x000000000001ff00,0x00000000000100ff,0x0000000000010000,0x0000000000010001,0x00000000000101ff, -0x0000000000010100,0x0000000000010101,0x0000000001ffff00,0x0000000001ff00ff,0x0000000001ff0000,0x0000000001ff0100,0x0000000001ff0101,0x000000000100ffff, -0x000000000100ff00,0x00000000010000ff,0x0000000001000000,0x0000000001000001,0x00000000010001ff,0x0000000001000100,0x000000000101ff00,0x00000000010100ff, -0x0000000001010000,0x0000000001010001,0x0000000001010100,0x00000001ffffffff,0x00000001ffffff00,0x00000001ffffff01,0x00000001ffff00ff,0x00000001ffff0001, -0x00000001ffff01ff,0x00000001ffff0100,0x00000001ff00ff00,0x00000001ff0000ff,0x00000001ff000000,0x00000001ff0001ff,0x00000001ff000100,0x00000001ff01ffff, -0x00000001ff01ff00,0x00000001ff01ff01,0x00000001ff0100ff,0x00000001ff010000,0x00000001ff010001,0x00000001ff0101ff,0x00000001ff010100,0x0000000100ffff00, -0x0000000100ff0000,0x0000000100ff0001,0x0000000100ff01ff,0x0000000100ff0100,0x0000000100ff0101,0x000000010000ffff,0x000000010000ff00,0x000000010000ff01, -0x00000001000000ff,0x0000000100000000,0x0000000100000001,0x00000001000001ff,0x0000000100000100,0x0000000100000101,0x000000010001ff00,0x00000001000100ff, -0x0000000100010000,0x0000000100010100,0x0000000101ffff01,0x0000000101ff0000,0x0000000101ff0001,0x0000000101ff01ff,0x0000000101ff0100,0x0000000101ff0101, -0x000000010100ff00,0x0000000101000000,0x0000000101000101,0x000000010101ff01,0x0000000101010000,0x0000000101010001,0x00000001010101ff,0x0000000101010100, -0x000001ffffff00ff,0x000001ffffff0000,0x000001ffffff0001,0x000001ffffff0100,0x000001ffff00ffff,0x000001ffff000000,0x000001ffff0001ff,0x000001ffff01ff00, -0x000001ffff010101,0x000001ff00ff0000,0x000001ff00ff01ff,0x000001ff00ff0101,0x000001ff0000ff00,0x000001ff000000ff,0x000001ff00000000,0x000001ff00000001, -0x000001ff000001ff,0x000001ff00000100,0x000001ff0001ffff,0x000001ff0001ff01,0x000001ff000100ff,0x000001ff00010000,0x000001ff01ffff01,0x000001ff01ff0100, -0x000001ff0100ffff,0x000001ff0100ff01,0x000001ff01000000,0x000001ff010001ff,0x000001ff0101ff00,0x000001ff01010100,0x00000100ffffff00,0x00000100ffffff01, -0x00000100ffff0000,0x00000100ffff0101,0x00000100ff00ff00,0x00000100ff0000ff,0x00000100ff000000,0x00000100ff000001,0x00000100ff000100,0x00000100ff010000, -0x0000010000ffff00,0x0000010000ff00ff,0x0000010000ff0000,0x0000010000ff0001,0x0000010000ff0100,0x000001000000ffff,0x000001000000ff00,0x000001000000ff01, -0x00000100000000ff,0x0000010000000000,0x0000010000000001,0x00000100000001ff,0x0000010000000100,0x0000010000000101,0x000001000001ff00,0x00000100000100ff, -0x0000010000010000,0x0000010000010001,0x0000010000010100,0x0000010001ffff00,0x0000010001ff0000,0x0000010001ff0100,0x000001000100ff00,0x00000100010000ff, -0x0000010001000000,0x0000010001000001,0x00000100010001ff,0x0000010001000100,0x0000010001010000,0x00000101ffff00ff,0x00000101ffff01ff,0x00000101ff000000, -0x00000101ff000101,0x00000101ff01ffff,0x00000101ff010000,0x00000101ff010001,0x00000101ff010100,0x0000010100ff0000,0x0000010100ff01ff,0x0000010100ff0100, -0x000001010000ff00,0x0000010100000000,0x0000010100000001,0x00000101000001ff,0x0000010100000100,0x000001010001ff01,0x0000010100010000,0x00000101000101ff, -0x0000010100010101,0x0000010101ffff00,0x0000010101ff0101,0x000001010100ff01,0x0000010101000000,0x0000010101000001,0x00000101010001ff,0x0000010101000101, -0x000001010101ff00,0x0001ffffffff0000,0x0001ffffff0000ff,0x0001ffffff000001,0x0001ffffff000100,0x0001ffffff010000,0x0001ffff00ff00ff,0x0001ffff0000ffff, -0x0001ffff00000000,0x0001ffff00000001,0x0001ffff000001ff,0x0001ffff00000101,0x0001ffff0001ff00,0x0001ffff000100ff,0x0001ffff00010001,0x0001ffff00010100, -0x0001ffff01ffff00,0x0001ffff01000001,0x0001ffff01010000,0x0001ff00ffffff00,0x0001ff00ffff00ff,0x0001ff00ffff0001,0x0001ff00ffff0100,0x0001ff00ff00ff01, -0x0001ff00ff000000,0x0001ff00ff01ff00,0x0001ff00ff01ff01,0x0001ff00ff010001,0x0001ff00ff010100,0x0001ff0000ff0000,0x0001ff0000ff0100,0x0001ff000000ff00, -0x0001ff0000000000,0x0001ff0000000001,0x0001ff0000000100,0x0001ff0000010000,0x0001ff0000010001,0x0001ff0000010101,0x0001ff0001ff00ff,0x0001ff0001ff0101, -0x0001ff000100ff01,0x0001ff0001000000,0x0001ff000101ff00,0x0001ff0001010001,0x0001ff0001010100,0x0001ff01ff00ff00,0x0001ff01ff000001,0x0001ff01ff000100, -0x0001ff0100ffffff,0x0001ff0100ffff00,0x0001ff0100ff0001,0x0001ff0100000000,0x0001ff0100000001,0x0001ff01000001ff,0x0001ff010001ffff,0x0001ff0101ff0000, -0x0001ff010100ff00,0x0001ff0101000001,0x0001ff0101010000,0x000100ffff00ff00,0x000100ffff00ff01,0x000100ffff000000,0x000100ffff000001,0x000100ffff000101, -0x000100ffff01ff00,0x000100ffff010001,0x000100ffff010100,0x000100ff00ffffff,0x000100ff00ffff01,0x000100ff00ff0000,0x000100ff00ff01ff,0x000100ff00ff0101, -0x000100ff0000ff00,0x000100ff000000ff,0x000100ff00000000,0x000100ff00000001,0x000100ff00000100,0x000100ff00000101,0x000100ff0001ffff,0x000100ff0001ff01, -0x000100ff00010000,0x000100ff01ff00ff,0x000100ff01ff0000,0x000100ff01ff0100,0x000100ff0100ffff,0x000100ff0100ff01,0x000100ff010000ff,0x000100ff01000000, -0x000100ff01000001,0x000100ff010001ff,0x000100ff01000101,0x000100ff0101ff00,0x000100ff010100ff,0x000100ff01010100,0x00010000ffff0000,0x00010000ffff01ff, -0x00010000ffff0101,0x00010000ff00ff00,0x00010000ff000000,0x00010000ff000001,0x00010000ff000100,0x0001000000ff00ff,0x0001000000ff0000,0x0001000000ff0001, -0x0001000000ff0100,0x000100000000ffff,0x000100000000ff00,0x00010000000000ff,0x0001000000000000,0x0001000000000001,0x0001000000000100,0x000100000001ff00, -0x00010000000100ff,0x0001000000010000,0x0001000000010001,0x0001000000010100,0x0001000001ff0001,0x0001000001ff0100,0x0001000001ff0101,0x000100000100ff00, -0x0001000001000000,0x0001000001000001,0x0001000001000100,0x0001000001000101,0x000100000101ff01,0x0001000001010000,0x0001000001010001,0x00010000010101ff, -0x00010001ffffff01,0x00010001ffff0100,0x00010001ff000000,0x00010001ff01ffff,0x00010001ff010001,0x00010001ff0101ff,0x00010001ff010100,0x0001000100ffffff, -0x0001000100ff0000,0x0001000100ff01ff,0x0001000100ff0101,0x000100010000ff00,0x00010001000000ff,0x0001000100000000,0x0001000100000001,0x00010001000001ff, -0x0001000100000101,0x000100010001ffff,0x0001000100010000,0x00010001000101ff,0x0001000101ffffff,0x0001000101ffff01,0x0001000101ff0000,0x0001000101ff0101, -0x00010001010000ff,0x0001000101000001,0x00010001010001ff,0x0001000101000100,0x000100010101ffff,0x00010001010100ff,0x0001000101010001,0x0001000101010101, -0x000101ffff000001,0x000101ffff000100,0x000101ffff010000,0x000101ff00ffff00,0x000101ff0000ff01,0x000101ff00000000,0x000101ff00000101,0x000101ff0001ff00, -0x000101ff00010100,0x000101ff01ff0000,0x000101ff0100ff00,0x000101ff010001ff,0x000101ff01010001,0x00010100ffffff00,0x00010100ffff00ff,0x00010100ff00ffff, -0x00010100ff000000,0x00010100ff01ff00,0x00010100ff0100ff,0x00010100ff010001,0x00010100ff010100,0x0001010000ffffff,0x0001010000ffff00,0x0001010000ff0000, -0x0001010000ff0001,0x0001010000ff01ff,0x000101000000ff00,0x00010100000000ff,0x0001010000000000,0x0001010000000001,0x0001010000000100,0x000101000001ffff, -0x0001010000010000,0x0001010000010101,0x0001010001ffff01,0x0001010001ff00ff,0x0001010001ff0101,0x0001010001000000,0x000101000101ff00,0x00010100010100ff, -0x0001010001010000,0x0001010001010100,0x00010101ff00ff00,0x00010101ff000001,0x00010101ff0001ff,0x0001010100ffff00,0x0001010100ff00ff,0x0001010100ff0100, -0x000101010000ffff,0x0001010100000000,0x00010101000001ff,0x0001010100000101,0x00010101000100ff,0x0001010100010000,0x0001010100010100,0x0001010101ff0001, -0x00010101010000ff,0x00010101010001ff,0x0001010101000101,0x0001010101010001,0x01ffffffffffffff,0x01ffffffffffff01,0x01ffffffffff01ff,0x01ffffffffff0101, -0x01ffffffff01ffff,0x01ffffffff01ff01,0x01ffffffff0101ff,0x01ffffffff010101,0x01ffffff00ff0000,0x01ffffff0000ffff,0x01ffffff0000ff00,0x01ffffff000000ff, -0x01ffffff00000001,0x01ffffff00000100,0x01ffffff00010000,0x01ffffff01ffffff,0x01ffffff01ffff01,0x01ffffff01ff01ff,0x01ffffff01ff0101,0x01ffffff01000000, -0x01ffffff0101ffff,0x01ffffff0101ff01,0x01ffffff010101ff,0x01ffffff01010101,0x01ffff00ffff0000,0x01ffff00ff00ff00,0x01ffff00ff0000ff,0x01ffff00ff000001, -0x01ffff00ff000100,0x01ffff00ff010000,0x01ffff0000ffff00,0x01ffff0000ff00ff,0x01ffff0000ff0100,0x01ffff000000ffff,0x01ffff000000ff01,0x01ffff0000000000, -0x01ffff0000000001,0x01ffff00000001ff,0x01ffff0000000100,0x01ffff00000100ff,0x01ffff0000010001,0x01ffff0000010100,0x01ffff0001ff0000,0x01ffff0001ff0100, -0x01ffff00010000ff,0x01ffff0001000001,0x01ffff0001000100,0x01ffff0001010000,0x01ffff01ffffffff,0x01ffff01ffffff01,0x01ffff01ffff01ff,0x01ffff01ffff0101, -0x01ffff01ff000000,0x01ffff01ff01ffff,0x01ffff01ff01ff01,0x01ffff01ff0101ff,0x01ffff01ff010101,0x01ffff010000ff00,0x01ffff01000000ff,0x01ffff0100000100, -0x01ffff0100010000,0x01ffff0101ffffff,0x01ffff0101ffff01,0x01ffff0101ff01ff,0x01ffff0101ff0101,0x01ffff0101000000,0x01ffff010101ffff,0x01ffff010101ff01, -0x01ffff01010101ff,0x01ffff0101010101,0x01ff00ffff0000ff,0x01ff00ffff000100,0x01ff00ff00ffff00,0x01ff00ff00ff00ff,0x01ff00ff0000ff00,0x01ff00ff00000000, -0x01ff00ff00000101,0x01ff00ff0001ff00,0x01ff00ff000100ff,0x01ff00ff00010100,0x01ff00ff010000ff,0x01ff00ff01000100,0x01ff0000ffffff00,0x01ff0000ffff0100, -0x01ff0000ff00ff01,0x01ff0000ff000000,0x01ff0000ff000101,0x01ff0000ff010001,0x01ff0000ff010100,0x01ff000000ffffff,0x01ff000000ffff00,0x01ff000000ff0000, -0x01ff000000ff01ff,0x01ff00000000ff00,0x01ff0000000000ff,0x01ff000000000000,0x01ff000000000001,0x01ff000000000100,0x01ff000000000101,0x01ff000000010000, -0x01ff000000010001,0x01ff0000000101ff,0x01ff000000010101,0x01ff000001ffff00,0x01ff000001ff00ff,0x01ff000001ff0001,0x01ff000001ff0100,0x01ff00000100ffff, -0x01ff00000100ff01,0x01ff000001000000,0x01ff0000010001ff,0x01ff000001010001,0x01ff0001ff00ff00,0x01ff0001ff000001,0x01ff0001ff000100,0x01ff0001ff010000, -0x01ff000100ffff00,0x01ff000100ff00ff,0x01ff000100ff0100,0x01ff000100ff0101,0x01ff00010000ffff,0x01ff000100000000,0x01ff000100000100,0x01ff000100000101, -0x01ff00010001ff00,0x01ff000100010001,0x01ff000100010101,0x01ff000101ff0000,0x01ff00010100ff00,0x01ff000101000101,0x01ff0001010100ff,0x01ff01ffffffffff, -0x01ff01ffffffff01,0x01ff01ffffff01ff,0x01ff01ffffff0101,0x01ff01ffff000000,0x01ff01ffff01ffff,0x01ff01ffff01ff01,0x01ff01ffff0101ff,0x01ff01ffff010101, -0x01ff01ff00ffff00,0x01ff01ff00ff0000,0x01ff01ff0000ff00,0x01ff01ff000000ff,0x01ff01ff00000100,0x01ff01ff00010000,0x01ff01ff00010100,0x01ff01ff01ffffff, -0x01ff01ff01ffff01,0x01ff01ff01ff01ff,0x01ff01ff01ff0101,0x01ff01ff01000000,0x01ff01ff0101ffff,0x01ff01ff0101ff01,0x01ff01ff010101ff,0x01ff01ff01010101, -0x01ff0100ffff0000,0x01ff0100ffff0001,0x01ff0100ff00ff00,0x01ff0100ff0000ff,0x01ff0100ff000001,0x01ff0100ff010000,0x01ff010000ffff00,0x01ff010000ff00ff, -0x01ff010000ff0001,0x01ff010000ff0100,0x01ff01000000ffff,0x01ff01000000ff01,0x01ff010000000000,0x01ff010000000101,0x01ff01000001ff00,0x01ff0100000100ff, -0x01ff010001ff0000,0x01ff010001000001,0x01ff010001000100,0x01ff010001010000,0x01ff0101ffffffff,0x01ff0101ffffff01,0x01ff0101ffff01ff,0x01ff0101ffff0101, -0x01ff0101ff000000,0x01ff0101ff01ffff,0x01ff0101ff01ff01,0x01ff0101ff0101ff,0x01ff0101ff010101,0x01ff010100ff0000,0x01ff01010000ff00,0x01ff0101000000ff, -0x01ff010100000001,0x01ff010101ffffff,0x01ff010101ffff01,0x01ff010101ff01ff,0x01ff010101ff0101,0x01ff010101000000,0x01ff01010101ffff,0x01ff01010101ff01, -0x01ff0101010101ff,0x01ff010101010101,0x0100ffffffff0000,0x0100ffffff00ff00,0x0100ffffff000001,0x0100ffffff0001ff,0x0100ffffff000100,0x0100ffffff010000, -0x0100ffff00ffff00,0x0100ffff00ff0001,0x0100ffff00ff0100,0x0100ffff00000000,0x0100ffff000001ff,0x0100ffff00000101,0x0100ffff00010100,0x0100ffff00010101, -0x0100ffff01ff0000,0x0100ffff0100ff00,0x0100ffff010000ff,0x0100ffff01000001,0x0100ffff01000100,0x0100ffff01010000,0x0100ff00ffffff00,0x0100ff00ffff00ff, -0x0100ff00ffff0001,0x0100ff00ffff0100,0x0100ff00ff00ffff,0x0100ff00ff000000,0x0100ff00ff0001ff,0x0100ff00ff000101,0x0100ff00ff01ff00,0x0100ff00ff0100ff, -0x0100ff00ff010001,0x0100ff00ff010100,0x0100ff0000ffffff,0x0100ff0000ff0000,0x0100ff000000ffff,0x0100ff000000ff00,0x0100ff00000000ff,0x0100ff0000000000, -0x0100ff0000000001,0x0100ff0000000100,0x0100ff000001ff01,0x0100ff0000010000,0x0100ff0001ff00ff,0x0100ff0001ff0001,0x0100ff000100ff01,0x0100ff0001000000, -0x0100ff00010001ff,0x0100ff000101ff00,0x0100ff00010100ff,0x0100ff0001010001,0x0100ff0001010100,0x0100ff01ffff0000,0x0100ff01ff00ff00,0x0100ff01ff0000ff, -0x0100ff01ff000100,0x0100ff01ff010000,0x0100ff0100ff00ff,0x0100ff0100ff0001,0x0100ff0100ff0100,0x0100ff010000ffff,0x0100ff010000ff01,0x0100ff0100000000, -0x0100ff01000001ff,0x0100ff0100010001,0x0100ff0100010100,0x0100ff0101ff0000,0x0100ff01010000ff,0x0100ff0101000001,0x0100ff0101010100,0x010000ffffffff00, -0x010000ffffff00ff,0x010000ffffff0001,0x010000ffff00ffff,0x010000ffff000000,0x010000ffff0001ff,0x010000ffff010001,0x010000ff00ffffff,0x010000ff00ff0101, -0x010000ff0000ff00,0x010000ff000000ff,0x010000ff00000000,0x010000ff00000001,0x010000ff000001ff,0x010000ff00000100,0x010000ff0001ffff,0x010000ff0001ff00, -0x010000ff0001ff01,0x010000ff00010000,0x010000ff01ff00ff,0x010000ff01ff0001,0x010000ff0100ff01,0x010000ff010000ff,0x010000ff01000000,0x010000ff010001ff, -0x010000ff0101ff00,0x010000ff01010100,0x01000000ffffffff,0x01000000ffff0000,0x01000000ffff01ff,0x01000000ffff0101,0x01000000ff00ffff,0x01000000ff00ff00, -0x01000000ff0000ff,0x01000000ff000000,0x01000000ff000001,0x01000000ff000100,0x01000000ff01ff00,0x01000000ff010000,0x01000000ff010100,0x01000000ff010101, -0x0100000000ffff00,0x0100000000ff00ff,0x0100000000ff0000,0x0100000000ff0001,0x0100000000ff0100,0x010000000000ffff,0x010000000000ff00,0x010000000000ff01, -0x01000000000000ff,0x0100000000000000,0x0100000000000001,0x01000000000001ff,0x0100000000000100,0x0100000000000101,0x010000000001ff00,0x01000000000100ff, -0x0100000000010000,0x0100000000010001,0x0100000000010100,0x0100000001ffff00,0x0100000001ff0000,0x0100000001ff01ff,0x010000000100ff00,0x010000000100ff01, -0x01000000010000ff,0x0100000001000000,0x0100000001000001,0x0100000001000100,0x0100000001000101,0x010000000101ffff,0x010000000101ff01,0x0100000001010000, -0x01000000010101ff,0x0100000001010101,0x01000001ffffff00,0x01000001ffff00ff,0x01000001ff00ffff,0x01000001ff000000,0x01000001ff000100,0x01000001ff01ffff, -0x01000001ff010001,0x01000001ff010100,0x0100000100ff0000,0x0100000100ff01ff,0x0100000100ff0100,0x010000010000ff00,0x010000010000ff01,0x0100000100000000, -0x0100000100000001,0x0100000100000100,0x0100000100010000,0x01000001000101ff,0x0100000101ffff01,0x0100000101ff00ff,0x0100000101ff0100,0x0100000101ff0101, -0x010000010100ff01,0x01000001010000ff,0x0100000101000000,0x01000001010100ff,0x0100000101010001,0x0100000101010100,0x010001ffffff0000,0x010001ffff000001, -0x010001ffff000100,0x010001ffff010000,0x010001ff00ffff00,0x010001ff00ff0001,0x010001ff0000ffff,0x010001ff0000ff01,0x010001ff00000000,0x010001ff00000001, -0x010001ff00000101,0x010001ff000100ff,0x010001ff00010000,0x010001ff01ff0000,0x010001ff0100ff00,0x010001ff01000001,0x010001ff01000100,0x010001ff01010000, -0x01000100ffff00ff,0x01000100ffff0001,0x01000100ffff0100,0x01000100ff00ffff,0x01000100ff00ff01,0x01000100ff000000,0x01000100ff0001ff,0x01000100ff000101, -0x01000100ff01ffff,0x01000100ff01ff00,0x01000100ff0100ff,0x01000100ff010001,0x0100010000ffffff,0x0100010000ffff01,0x0100010000ff0000,0x0100010000ff01ff, -0x0100010000ff0101,0x010001000000ff00,0x01000100000000ff,0x0100010000000000,0x0100010000000001,0x0100010000000100,0x010001000001ff01,0x0100010000010000, -0x0100010000010001,0x0100010000010101,0x0100010001ffff00,0x0100010001ff00ff,0x010001000100ffff,0x010001000100ff01,0x0100010001000000,0x0100010001000101, -0x010001000101ff00,0x0100010001010001,0x01000101ffff0000,0x01000101ff000000,0x01000101ff010000,0x0100010100ff00ff,0x0100010100ff0001,0x0100010100ff0100, -0x010001010000ffff,0x0100010100000000,0x01000101000001ff,0x010001010001ff00,0x0100010101ff0000,0x010001010100ff00,0x01000101010000ff,0x0100010101000000, -0x0100010101000001,0x0101ffffffffffff,0x0101ffffffffff01,0x0101ffffffff01ff,0x0101ffffffff0101,0x0101ffffff000000,0x0101ffffff01ffff,0x0101ffffff01ff01, -0x0101ffffff0101ff,0x0101ffffff010101,0x0101ffff00ff0000,0x0101ffff0000ff00,0x0101ffff000000ff,0x0101ffff00000001,0x0101ffff00000100,0x0101ffff01ffffff, -0x0101ffff01ffff01,0x0101ffff01ff01ff,0x0101ffff01ff0101,0x0101ffff01000000,0x0101ffff0101ffff,0x0101ffff0101ff01,0x0101ffff010101ff,0x0101ffff01010101, -0x0101ff00ffff0000,0x0101ff00ffff0100,0x0101ff00ff00ff00,0x0101ff00ff0000ff,0x0101ff00ff000001,0x0101ff00ff000100,0x0101ff00ff000101,0x0101ff0000ff0001, -0x0101ff0000ff0100,0x0101ff000000ff00,0x0101ff0000000000,0x0101ff00000001ff,0x0101ff0000000101,0x0101ff000001ff00,0x0101ff00000100ff,0x0101ff0001ff0000, -0x0101ff000100ffff,0x0101ff000100ff01,0x0101ff0001000001,0x0101ff0001000100,0x0101ff01ffffff01,0x0101ff01ffff01ff,0x0101ff01ffff0101,0x0101ff01ff00ffff, -0x0101ff01ff000100,0x0101ff01ff01ff01,0x0101ff01ff0101ff,0x0101ff01ff010101,0x0101ff0100ff0000,0x0101ff010000ff00,0x0101ff0100000001,0x0101ff0100000100, -0x0101ff0100010000,0x0101ff0101ffffff,0x0101ff0101ffff01,0x0101ff0101ff01ff,0x0101ff0101ff0101,0x0101ff0101000000,0x0101ff010101ffff,0x0101ff010101ff01, -0x0101ff01010101ff,0x0101ff0101010101,0x010100ffff000100,0x010100ffff010000,0x010100ff00ffff00,0x010100ff00ff00ff,0x010100ff0000ffff,0x010100ff000000ff, -0x010100ff00000000,0x010100ff000001ff,0x010100ff00000101,0x010100ff0001ff00,0x010100ff00010000,0x010100ff00010001,0x010100ff000101ff,0x010100ff00010100, -0x010100ff01ff0000,0x01010000ffff0001,0x01010000ffff0100,0x01010000ff00ffff,0x01010000ff00ff01,0x01010000ff000000,0x01010000ff0001ff,0x01010000ff010001, -0x01010000ff010100,0x0101000000ffff01,0x0101000000ff0000,0x010100000000ff00,0x01010000000000ff,0x0101000000000000,0x0101000000000001,0x0101000000000100, -0x0101000000010000,0x0101000000010101,0x0101000001ffff00,0x0101000001ff00ff,0x0101000001ff0000,0x0101000001ff0001,0x0101000001ff0100,0x010100000100ff01, -0x0101000001000000,0x01010000010001ff,0x01010001ffff0000,0x01010001ff00ff00,0x01010001ff000001,0x01010001ff000101,0x01010001ff01ff00,0x01010001ff010000, -0x0101000100ff00ff,0x0101000100ff0001,0x0101000100ff0101,0x010100010000ff01,0x0101000100000000,0x0101000100000001,0x01010001000001ff,0x010100010001ffff, -0x010100010001ff01,0x0101000101ff0001,0x010100010100ffff,0x0101000101000000,0x0101000101000001,0x0101000101000100,0x010100010101ff00,0x01010001010100ff, -0x0101000101010001,0x010101ffffffffff,0x010101ffffffff01,0x010101ffffff01ff,0x010101ffffff0101,0x010101ffff01ffff,0x010101ffff01ff01,0x010101ffff0101ff, -0x010101ffff010101,0x010101ff0000ff00,0x010101ff000000ff,0x010101ff00000001,0x010101ff00000100,0x010101ff01ffffff,0x010101ff01ffff01,0x010101ff01ff01ff, -0x010101ff01ff0101,0x010101ff01000000,0x010101ff0101ffff,0x010101ff0101ff01,0x010101ff010101ff,0x010101ff01010101,0x01010100ffff0000,0x01010100ff0000ff, -0x01010100ff000100,0x01010100ff01ff00,0x01010100ff010000,0x0101010000ffff00,0x010101000000ffff,0x0101010000000000,0x0101010000000101,0x010101000001ff00, -0x0101010000010001,0x0101010000010100,0x010101000100ffff,0x0101010001000001,0x01010101ffffffff,0x01010101ffffff01,0x01010101ffff01ff,0x01010101ffff0101, -0x01010101ff01ffff,0x01010101ff01ff01,0x01010101ff0101ff,0x01010101ff010101,0x010101010000ff00,0x01010101000000ff,0x0101010100000001,0x0101010101ffffff, -0x0101010101ffff01,0x0101010101ff01ff,0x0101010101ff0101,0x0101010101000000,0x010101010101ffff,0x010101010101ff01,0x01010101010101ff,0x0101010101010101, +pub(super) const GRID: [u64; 2048] = [ + 0xffffffffffffffff, + 0xffffffffffffff01, + 0xffffffffffff0000, + 0xffffffffffff01ff, + 0xffffffffffff0101, + 0xffffffffff00ff00, + 0xffffffffff000000, + 0xffffffffff01ffff, + 0xffffffffff01ff01, + 0xffffffffff0101ff, + 0xffffffffff010101, + 0xffffffff00ff0000, + 0xffffffff0000ff00, + 0xffffffff000000ff, + 0xffffffff00000001, + 0xffffffff00010000, + 0xffffffff01ffffff, + 0xffffffff01ffff01, + 0xffffffff01ff01ff, + 0xffffffff01ff0101, + 0xffffffff01000000, + 0xffffffff0101ffff, + 0xffffffff0101ff01, + 0xffffffff010101ff, + 0xffffffff01010101, + 0xffffff00ffff00ff, + 0xffffff00ffff0000, + 0xffffff00ff00ff00, + 0xffffff00ff0000ff, + 0xffffff00ff000001, + 0xffffff00ff000100, + 0xffffff00ff000101, + 0xffffff00ff010000, + 0xffffff0000ffff00, + 0xffffff0000ff0001, + 0xffffff0000ff0100, + 0xffffff000000ff01, + 0xffffff0000000000, + 0xffffff0000000101, + 0xffffff000001ff00, + 0xffffff00000100ff, + 0xffffff0000010001, + 0xffffff00000101ff, + 0xffffff0001ff0000, + 0xffffff000100ff00, + 0xffffff00010000ff, + 0xffffff0001000001, + 0xffffff0001010000, + 0xffffff01ffffffff, + 0xffffff01ffffff01, + 0xffffff01ffff01ff, + 0xffffff01ffff0101, + 0xffffff01ff000000, + 0xffffff01ff01ffff, + 0xffffff01ff01ff01, + 0xffffff01ff0101ff, + 0xffffff01ff010101, + 0xffffff0100ff0000, + 0xffffff010000ff00, + 0xffffff0100000100, + 0xffffff01000100ff, + 0xffffff0100010100, + 0xffffff0101ffffff, + 0xffffff0101ffff01, + 0xffffff0101ff01ff, + 0xffffff0101ff0101, + 0xffffff010100ff00, + 0xffffff0101000000, + 0xffffff0101000100, + 0xffffff010101ffff, + 0xffffff010101ff01, + 0xffffff01010101ff, + 0xffffff0101010101, + 0xffff00ffff00ff00, + 0xffff00ffff0000ff, + 0xffff00ffff000001, + 0xffff00ffff010000, + 0xffff00ff00ffff00, + 0xffff00ff00ff0100, + 0xffff00ff00000000, + 0xffff00ff00000101, + 0xffff00ff000100ff, + 0xffff00ff00010000, + 0xffff00ff0100ff00, + 0xffff00ff01000100, + 0xffff00ff01010000, + 0xffff0000ffffff00, + 0xffff0000ffff00ff, + 0xffff0000ffff0000, + 0xffff0000ffff0001, + 0xffff0000ff000000, + 0xffff0000ff0001ff, + 0xffff0000ff000101, + 0xffff0000ff010100, + 0xffff000000ffffff, + 0xffff000000ff0000, + 0xffff000000ff0101, + 0xffff00000000ffff, + 0xffff00000000ff00, + 0xffff0000000000ff, + 0xffff000000000000, + 0xffff000000000001, + 0xffff000000000100, + 0xffff00000001ffff, + 0xffff00000001ff01, + 0xffff000000010000, + 0xffff0000000101ff, + 0xffff000000010101, + 0xffff000001ffff00, + 0xffff00000100ff00, + 0xffff000001000000, + 0xffff0000010001ff, + 0xffff000001000101, + 0xffff00000101ff00, + 0xffff0000010100ff, + 0xffff000001010000, + 0xffff000001010001, + 0xffff000001010100, + 0xffff0001ff0000ff, + 0xffff0001ff000100, + 0xffff000100ffff00, + 0xffff000100ff00ff, + 0xffff00010000ffff, + 0xffff00010000ff01, + 0xffff000100000000, + 0xffff0001000001ff, + 0xffff00010001ffff, + 0xffff00010001ff00, + 0xffff000100010001, + 0xffff000100010100, + 0xffff000101ff0000, + 0xffff00010100ff00, + 0xffff0001010000ff, + 0xffff000101000100, + 0xffff01ffffffffff, + 0xffff01ffffffff01, + 0xffff01ffffff01ff, + 0xffff01ffffff0101, + 0xffff01ffff000000, + 0xffff01ffff01ffff, + 0xffff01ffff01ff01, + 0xffff01ffff0101ff, + 0xffff01ffff010101, + 0xffff01ff00ff0000, + 0xffff01ff0000ff00, + 0xffff01ff00000001, + 0xffff01ff00010000, + 0xffff01ff01ffffff, + 0xffff01ff01ffff01, + 0xffff01ff01ff01ff, + 0xffff01ff01ff0101, + 0xffff01ff01000000, + 0xffff01ff0101ffff, + 0xffff01ff0101ff01, + 0xffff01ff010101ff, + 0xffff01ff01010101, + 0xffff0100ffff0000, + 0xffff0100ff00ff00, + 0xffff0100ff0000ff, + 0xffff0100ff000100, + 0xffff0100ff0100ff, + 0xffff0100ff010000, + 0xffff010000ffff00, + 0xffff01000000ffff, + 0xffff01000000ff00, + 0xffff010000000000, + 0xffff01000001ff00, + 0xffff0100000100ff, + 0xffff010000010100, + 0xffff01000100ff00, + 0xffff0100010000ff, + 0xffff010001000001, + 0xffff010001000100, + 0xffff010001010000, + 0xffff0101ffffffff, + 0xffff0101ffffff01, + 0xffff0101ffff01ff, + 0xffff0101ffff0101, + 0xffff0101ff000000, + 0xffff0101ff01ffff, + 0xffff0101ff01ff01, + 0xffff0101ff0101ff, + 0xffff0101ff010101, + 0xffff010100ff0000, + 0xffff01010000ff00, + 0xffff010100000100, + 0xffff01010001ff00, + 0xffff010100010000, + 0xffff010101ffffff, + 0xffff010101ffff01, + 0xffff010101ff0000, + 0xffff010101ff01ff, + 0xffff010101ff0101, + 0xffff010101000000, + 0xffff01010101ffff, + 0xffff01010101ff01, + 0xffff0101010101ff, + 0xffff010101010101, + 0xff00ffffff00ffff, + 0xff00ffffff00ff00, + 0xff00ffffff0000ff, + 0xff00ffffff000100, + 0xff00ffffff0100ff, + 0xff00ffffff010000, + 0xff00ffff00ffff00, + 0xff00ffff00ff00ff, + 0xff00ffff0000ffff, + 0xff00ffff00000000, + 0xff00ffff000001ff, + 0xff00ffff0001ff00, + 0xff00ffff000100ff, + 0xff00ffff00010000, + 0xff00ffff00010100, + 0xff00ffff0100ff00, + 0xff00ffff010000ff, + 0xff00ffff01000001, + 0xff00ffff0101ff00, + 0xff00ffff01010000, + 0xff00ff00ffffff00, + 0xff00ff00ffff00ff, + 0xff00ff00ffff0001, + 0xff00ff00ffff0100, + 0xff00ff00ff00ffff, + 0xff00ff00ff00ff01, + 0xff00ff00ff000000, + 0xff00ff00ff0001ff, + 0xff00ff00ff01ff00, + 0xff00ff00ff0100ff, + 0xff00ff00ff010100, + 0xff00ff0000ff0000, + 0xff00ff0000ff0101, + 0xff00ff000000ffff, + 0xff00ff000000ff00, + 0xff00ff000000ff01, + 0xff00ff00000000ff, + 0xff00ff0000000000, + 0xff00ff0000000001, + 0xff00ff0000000100, + 0xff00ff000001ffff, + 0xff00ff0000010000, + 0xff00ff0001ff00ff, + 0xff00ff000100ff01, + 0xff00ff0001000000, + 0xff00ff000101ff00, + 0xff00ff00010100ff, + 0xff00ff01ff00ff00, + 0xff00ff01ff0000ff, + 0xff00ff01ff000001, + 0xff00ff01ff010000, + 0xff00ff0100ffffff, + 0xff00ff0100ff0001, + 0xff00ff0100ff0100, + 0xff00ff010000ff01, + 0xff00ff0100000000, + 0xff00ff01000001ff, + 0xff00ff0100000101, + 0xff00ff01000100ff, + 0xff00ff0100010001, + 0xff00ff0101ff0000, + 0xff00ff010100ff00, + 0xff00ff01010000ff, + 0xff00ff0101000001, + 0xff00ff0101010000, + 0xff0000ffffffff00, + 0xff0000ffffff0001, + 0xff0000ffffff0100, + 0xff0000ffff0000ff, + 0xff0000ffff000000, + 0xff0000ffff0001ff, + 0xff0000ffff000100, + 0xff0000ffff01ff00, + 0xff0000ffff010001, + 0xff0000ff00ffff00, + 0xff0000ff00ff0000, + 0xff0000ff00ff0001, + 0xff0000ff00ff01ff, + 0xff0000ff00ff0101, + 0xff0000ff0000ff00, + 0xff0000ff000000ff, + 0xff0000ff00000000, + 0xff0000ff00000001, + 0xff0000ff00000100, + 0xff0000ff0001ff01, + 0xff0000ff00010000, + 0xff0000ff000101ff, + 0xff0000ff01ff00ff, + 0xff0000ff01ff0100, + 0xff0000ff0100ffff, + 0xff0000ff010000ff, + 0xff0000ff01000000, + 0xff0000ff010001ff, + 0xff0000ff01000100, + 0xff0000ff01000101, + 0xff0000ff0101ff00, + 0xff0000ff010100ff, + 0xff0000ff01010000, + 0xff0000ff01010100, + 0xff000000ffffff01, + 0xff000000ffff0000, + 0xff000000ffff0101, + 0xff000000ff00ff00, + 0xff000000ff0000ff, + 0xff000000ff000000, + 0xff000000ff000001, + 0xff000000ff000100, + 0xff000000ff01ffff, + 0xff000000ff01ff01, + 0xff000000ff010000, + 0xff000000ff0101ff, + 0xff000000ff010101, + 0xff00000000ffff00, + 0xff00000000ff00ff, + 0xff00000000ff0000, + 0xff00000000ff0001, + 0xff0000000000ff00, + 0xff0000000000ff01, + 0xff000000000000ff, + 0xff00000000000000, + 0xff00000000000001, + 0xff00000000000100, + 0xff00000000000101, + 0xff0000000001ff00, + 0xff000000000100ff, + 0xff00000000010000, + 0xff00000000010001, + 0xff00000000010100, + 0xff00000001ffffff, + 0xff00000001ffff01, + 0xff00000001ff00ff, + 0xff00000001ff0000, + 0xff00000001ff01ff, + 0xff00000001ff0101, + 0xff0000000100ffff, + 0xff0000000100ff00, + 0xff000000010000ff, + 0xff00000001000000, + 0xff00000001000001, + 0xff00000001000100, + 0xff00000001000101, + 0xff0000000101ffff, + 0xff0000000101ff01, + 0xff00000001010000, + 0xff000001ffffff00, + 0xff000001ffff00ff, + 0xff000001ffff0000, + 0xff000001ffff0001, + 0xff000001ff000000, + 0xff000001ff000001, + 0xff000001ff0001ff, + 0xff000001ff000101, + 0xff000001ff01ff00, + 0xff000001ff010001, + 0xff00000100ffffff, + 0xff00000100ffff01, + 0xff00000100ff00ff, + 0xff00000100ff0000, + 0xff00000100ff01ff, + 0xff00000100ff0101, + 0xff0000010000ff00, + 0xff00000100000000, + 0xff00000100000001, + 0xff000001000001ff, + 0xff00000100000100, + 0xff0000010001ff00, + 0xff000001000100ff, + 0xff00000100010000, + 0xff000001000101ff, + 0xff00000100010100, + 0xff00000100010101, + 0xff00000101ff0001, + 0xff00000101ff0101, + 0xff0000010100ff01, + 0xff00000101000000, + 0xff000001010100ff, + 0xff00000101010100, + 0xff0001ffff00ff00, + 0xff0001ffff000001, + 0xff0001ffff010000, + 0xff0001ff00ffff00, + 0xff0001ff00ff00ff, + 0xff0001ff00ff0001, + 0xff0001ff00ff0100, + 0xff0001ff0000ffff, + 0xff0001ff00000000, + 0xff0001ff000001ff, + 0xff0001ff00000101, + 0xff0001ff0001ffff, + 0xff0001ff0001ff00, + 0xff0001ff000100ff, + 0xff0001ff00010001, + 0xff0001ff00010100, + 0xff0001ff01ff0000, + 0xff0001ff0100ff00, + 0xff0001ff010000ff, + 0xff0001ff01010000, + 0xff000100ff00ffff, + 0xff000100ff00ff01, + 0xff000100ff000000, + 0xff000100ff000101, + 0xff000100ff01ff00, + 0xff000100ff010000, + 0xff00010000ffff01, + 0xff00010000ff00ff, + 0xff00010000ff0000, + 0xff00010000ff01ff, + 0xff0001000000ff00, + 0xff000100000000ff, + 0xff00010000000000, + 0xff00010000000001, + 0xff00010000000100, + 0xff00010000000101, + 0xff0001000001ffff, + 0xff00010000010000, + 0xff00010000010101, + 0xff00010001ff0100, + 0xff0001000100ff00, + 0xff0001000100ff01, + 0xff00010001000000, + 0xff000100010001ff, + 0xff0001000101ff00, + 0xff00010001010001, + 0xff00010001010100, + 0xff000101ffff0100, + 0xff000101ff000001, + 0xff000101ff0100ff, + 0xff000101ff010001, + 0xff00010100ff00ff, + 0xff00010100ff0001, + 0xff00010100ff0100, + 0xff0001010000ffff, + 0xff0001010000ff01, + 0xff00010100000000, + 0xff000101000001ff, + 0xff0001010001ff00, + 0xff00010100010001, + 0xff00010100010100, + 0xff00010101ff0000, + 0xff0001010100ff00, + 0xff00010101000001, + 0xff00010101000101, + 0xff01ffffffffffff, + 0xff01ffffffffff01, + 0xff01ffffffff01ff, + 0xff01ffffffff0101, + 0xff01ffffff000000, + 0xff01ffffff01ffff, + 0xff01ffffff01ff01, + 0xff01ffffff010000, + 0xff01ffffff0101ff, + 0xff01ffffff010101, + 0xff01ffff00ff0000, + 0xff01ffff0000ff00, + 0xff01ffff00000100, + 0xff01ffff0001ff00, + 0xff01ffff00010000, + 0xff01ffff01ffffff, + 0xff01ffff01ffff01, + 0xff01ffff01ff01ff, + 0xff01ffff01ff0101, + 0xff01ffff01000000, + 0xff01ffff0101ffff, + 0xff01ffff0101ff01, + 0xff01ffff01010000, + 0xff01ffff010101ff, + 0xff01ffff01010101, + 0xff01ff00ffff0000, + 0xff01ff00ff00ff00, + 0xff01ff00ff0000ff, + 0xff01ff00ff000100, + 0xff01ff00ff010000, + 0xff01ff0000ffff01, + 0xff01ff0000ff00ff, + 0xff01ff0000ff0100, + 0xff01ff0000000000, + 0xff01ff00000001ff, + 0xff01ff0000000101, + 0xff01ff000001ff00, + 0xff01ff00000100ff, + 0xff01ff0000010000, + 0xff01ff0000010001, + 0xff01ff0001ff0000, + 0xff01ff000100ffff, + 0xff01ff0001000001, + 0xff01ff0001000100, + 0xff01ff0001010000, + 0xff01ff01ffffff00, + 0xff01ff01ffff01ff, + 0xff01ff01ffff0101, + 0xff01ff01ff00ff00, + 0xff01ff01ff000000, + 0xff01ff01ff01ffff, + 0xff01ff01ff01ff01, + 0xff01ff01ff0101ff, + 0xff01ff01ff010101, + 0xff01ff0100ff0000, + 0xff01ff010000ff00, + 0xff01ff0100000001, + 0xff01ff0100000100, + 0xff01ff0100010000, + 0xff01ff0101ffff00, + 0xff01ff0101ff01ff, + 0xff01ff0101ff0101, + 0xff01ff010100ff00, + 0xff01ff0101000000, + 0xff01ff010101ffff, + 0xff01ff010101ff01, + 0xff01ff01010101ff, + 0xff01ff0101010101, + 0xff0100ffffff0000, + 0xff0100ffff0000ff, + 0xff0100ffff000001, + 0xff0100ffff000100, + 0xff0100ffff010000, + 0xff0100ff00ff00ff, + 0xff0100ff00ff0000, + 0xff0100ff00ff0001, + 0xff0100ff00ff0100, + 0xff0100ff0000ff01, + 0xff0100ff00000000, + 0xff0100ff000001ff, + 0xff0100ff00000101, + 0xff0100ff00010001, + 0xff0100ff01ff0000, + 0xff0100ff0100ff00, + 0xff0100ff010000ff, + 0xff0100ff01000100, + 0xff0100ff0101ff00, + 0xff0100ff01010000, + 0xff010000ffff0100, + 0xff010000ff000000, + 0xff010000ff01ff00, + 0xff010000ff010100, + 0xff01000000ffffff, + 0xff01000000ff0000, + 0xff01000000ff01ff, + 0xff0100000000ff00, + 0xff010000000000ff, + 0xff01000000000000, + 0xff01000000000100, + 0xff0100000001ff01, + 0xff01000000010000, + 0xff010000000101ff, + 0xff01000001ff0100, + 0xff0100000100ffff, + 0xff010000010000ff, + 0xff01000001000000, + 0xff010000010001ff, + 0xff01000001000101, + 0xff0100000101ff00, + 0xff010000010100ff, + 0xff01000001010001, + 0xff01000001010100, + 0xff010001ffff0000, + 0xff010001ff00ffff, + 0xff010001ff00ff01, + 0xff010001ff000100, + 0xff010001ff010000, + 0xff01000100ffff00, + 0xff01000100ff0100, + 0xff01000100000000, + 0xff0100010001ffff, + 0xff0100010001ff00, + 0xff01000100010100, + 0xff01000101ff00ff, + 0xff01000101ff0001, + 0xff0100010100ffff, + 0xff01000101000101, + 0xff0101ffffffffff, + 0xff0101ffffffff01, + 0xff0101ffffff01ff, + 0xff0101ffffff0101, + 0xff0101ffff000000, + 0xff0101ffff01ffff, + 0xff0101ffff01ff01, + 0xff0101ffff0101ff, + 0xff0101ffff010101, + 0xff0101ff00ff0000, + 0xff0101ff0000ff00, + 0xff0101ff000000ff, + 0xff0101ff00010000, + 0xff0101ff01ffffff, + 0xff0101ff01ffff01, + 0xff0101ff01ff01ff, + 0xff0101ff01ff0101, + 0xff0101ff0101ffff, + 0xff0101ff0101ff01, + 0xff0101ff010101ff, + 0xff0101ff01010101, + 0xff010100ffff0100, + 0xff010100ff00ff00, + 0xff010100ff0000ff, + 0xff010100ff000100, + 0xff010100ff010000, + 0xff01010000ff0001, + 0xff01010000ff0100, + 0xff0101000000ff01, + 0xff01010000000000, + 0xff0101000001ff00, + 0xff010100000100ff, + 0xff01010000010001, + 0xff01010000010100, + 0xff01010001ff0000, + 0xff0101000100ffff, + 0xff01010001000001, + 0xff01010001000100, + 0xff010100010100ff, + 0xff01010001010000, + 0xff010101ffffffff, + 0xff010101ffffff01, + 0xff010101ffff01ff, + 0xff010101ffff0101, + 0xff010101ff01ffff, + 0xff010101ff01ff01, + 0xff010101ff0101ff, + 0xff010101ff010101, + 0xff01010100ff0000, + 0xff0101010000ff00, + 0xff01010100000001, + 0xff01010100000100, + 0xff01010100010000, + 0xff01010101ffffff, + 0xff01010101ffff01, + 0xff01010101ff01ff, + 0xff01010101ff0101, + 0xff01010101000000, + 0xff0101010101ffff, + 0xff0101010101ff01, + 0xff010101010101ff, + 0xff01010101010101, + 0x00ffffffffff0000, + 0x00ffffffff00ff00, + 0x00ffffffff000001, + 0x00ffffffff010000, + 0x00ffffff00ff0100, + 0x00ffffff0000ff01, + 0x00ffffff00000000, + 0x00ffffff000001ff, + 0x00ffffff00000101, + 0x00ffffff0001ff00, + 0x00ffffff000100ff, + 0x00ffffff00010001, + 0x00ffffff010000ff, + 0x00ffffff01000100, + 0x00ffffff0101ff00, + 0x00ffffff01010001, + 0x00ffff00ffffffff, + 0x00ffff00ffffff00, + 0x00ffff00ffff00ff, + 0x00ffff00ffff0001, + 0x00ffff00ffff0100, + 0x00ffff00ff00ff01, + 0x00ffff00ff000000, + 0x00ffff00ff000001, + 0x00ffff00ff0001ff, + 0x00ffff00ff000101, + 0x00ffff00ff01ff00, + 0x00ffff00ff010001, + 0x00ffff00ff010100, + 0x00ffff0000ff0000, + 0x00ffff0000ff01ff, + 0x00ffff0000ff0101, + 0x00ffff000000ff00, + 0x00ffff00000000ff, + 0x00ffff0000000000, + 0x00ffff0000000001, + 0x00ffff0000000100, + 0x00ffff0000000101, + 0x00ffff0000010000, + 0x00ffff00000101ff, + 0x00ffff0000010101, + 0x00ffff0001ffff00, + 0x00ffff0001ff00ff, + 0x00ffff0001ff0001, + 0x00ffff000100ffff, + 0x00ffff000100ff01, + 0x00ffff0001000000, + 0x00ffff000101ffff, + 0x00ffff000101ff00, + 0x00ffff000101ff01, + 0x00ffff01ffff0000, + 0x00ffff01ff00ff00, + 0x00ffff01ff0000ff, + 0x00ffff01ff000001, + 0x00ffff01ff010000, + 0x00ffff0100ffff00, + 0x00ffff010000ff01, + 0x00ffff0100000000, + 0x00ffff0100000101, + 0x00ffff01000100ff, + 0x00ffff0100010100, + 0x00ffff0101ff0100, + 0x00ffff01010000ff, + 0x00ffff0101010000, + 0x00ff00ffffffff00, + 0x00ff00ffff000000, + 0x00ff00ffff000100, + 0x00ff00ffff010100, + 0x00ff00ff00ff0000, + 0x00ff00ff00ff01ff, + 0x00ff00ff00ff0101, + 0x00ff00ff0000ff00, + 0x00ff00ff000000ff, + 0x00ff00ff00000000, + 0x00ff00ff00000001, + 0x00ff00ff0001ff00, + 0x00ff00ff0001ff01, + 0x00ff00ff00010000, + 0x00ff00ff000101ff, + 0x00ff00ff00010101, + 0x00ff00ff01ffff00, + 0x00ff00ff01ff0001, + 0x00ff00ff01ff0100, + 0x00ff00ff0100ffff, + 0x00ff00ff0100ff01, + 0x00ff00ff01000000, + 0x00ff00ff0101ffff, + 0x00ff00ff0101ff00, + 0x00ff00ff01010100, + 0x00ff0000ffffff00, + 0x00ff0000ffffff01, + 0x00ff0000ffff0000, + 0x00ff0000ffff0101, + 0x00ff0000ff00ff00, + 0x00ff0000ff0000ff, + 0x00ff0000ff000000, + 0x00ff0000ff000001, + 0x00ff0000ff000100, + 0x00ff0000ff01ffff, + 0x00ff0000ff010000, + 0x00ff0000ff010101, + 0x00ff000000ffff00, + 0x00ff000000ff00ff, + 0x00ff000000ff0000, + 0x00ff000000ff0001, + 0x00ff000000ff0100, + 0x00ff00000000ffff, + 0x00ff00000000ff00, + 0x00ff0000000000ff, + 0x00ff000000000000, + 0x00ff000000000001, + 0x00ff0000000001ff, + 0x00ff000000000100, + 0x00ff00000001ff00, + 0x00ff0000000100ff, + 0x00ff000000010000, + 0x00ff000000010001, + 0x00ff000000010100, + 0x00ff000001ffff01, + 0x00ff000001ff00ff, + 0x00ff000001ff0000, + 0x00ff000001ff01ff, + 0x00ff00000100ff00, + 0x00ff0000010000ff, + 0x00ff000001000000, + 0x00ff000001000001, + 0x00ff000001000100, + 0x00ff000001000101, + 0x00ff000001010000, + 0x00ff0000010101ff, + 0x00ff000001010101, + 0x00ff0001ffffff00, + 0x00ff0001ffff0000, + 0x00ff0001ffff0100, + 0x00ff0001ff0000ff, + 0x00ff0001ff000000, + 0x00ff0001ff0001ff, + 0x00ff0001ff000101, + 0x00ff0001ff01ff00, + 0x00ff0001ff0100ff, + 0x00ff0001ff010100, + 0x00ff000100ffffff, + 0x00ff000100ffff01, + 0x00ff000100ff0000, + 0x00ff000100ff01ff, + 0x00ff00010000ffff, + 0x00ff00010000ff00, + 0x00ff00010000ff01, + 0x00ff000100000000, + 0x00ff000100000001, + 0x00ff000100000100, + 0x00ff00010001ff01, + 0x00ff000100010000, + 0x00ff0001000101ff, + 0x00ff000101ffff00, + 0x00ff000101ff0000, + 0x00ff000101ff0101, + 0x00ff0001010000ff, + 0x00ff000101000000, + 0x00ff00010101ff00, + 0x00ff0001010100ff, + 0x00ff000101010001, + 0x00ff01ffffff0000, + 0x00ff01ffff00ff00, + 0x00ff01ffff000000, + 0x00ff01ffff000101, + 0x00ff01ffff010000, + 0x00ff01ff00ffff01, + 0x00ff01ff00ff0100, + 0x00ff01ff0000ffff, + 0x00ff01ff00000000, + 0x00ff01ff000001ff, + 0x00ff01ff0001ff00, + 0x00ff01ff000100ff, + 0x00ff01ff00010001, + 0x00ff01ff00010100, + 0x00ff01ff01ff0000, + 0x00ff01ff0100ff00, + 0x00ff01ff010000ff, + 0x00ff01ff01000001, + 0x00ff01ff01000100, + 0x00ff01ff01010000, + 0x00ff0100ffffff00, + 0x00ff0100ffff0000, + 0x00ff0100ffff0001, + 0x00ff0100ffff0101, + 0x00ff0100ff00ffff, + 0x00ff0100ff0000ff, + 0x00ff0100ff000000, + 0x00ff0100ff0001ff, + 0x00ff0100ff01ff00, + 0x00ff0100ff0100ff, + 0x00ff0100ff010001, + 0x00ff010000ffffff, + 0x00ff010000ff0000, + 0x00ff010000ff0101, + 0x00ff01000000ff00, + 0x00ff01000000ff01, + 0x00ff0100000000ff, + 0x00ff010000000000, + 0x00ff010000000001, + 0x00ff010000000100, + 0x00ff01000001ffff, + 0x00ff01000001ff01, + 0x00ff010000010000, + 0x00ff010000010001, + 0x00ff010000010101, + 0x00ff010001ff0001, + 0x00ff010001ff0100, + 0x00ff01000100ff01, + 0x00ff010001000000, + 0x00ff010001000001, + 0x00ff0100010001ff, + 0x00ff01000101ff00, + 0x00ff0100010100ff, + 0x00ff010001010001, + 0x00ff010001010100, + 0x00ff0101ff000001, + 0x00ff010100ff00ff, + 0x00ff010100ff0001, + 0x00ff010100ff0100, + 0x00ff010100000000, + 0x00ff0101000001ff, + 0x00ff010100000101, + 0x00ff0101000100ff, + 0x00ff010100010100, + 0x00ff0101010000ff, + 0x00ff010101010000, + 0x0000ffffffffff00, + 0x0000ffffffff00ff, + 0x0000ffffffff0000, + 0x0000ffffffff0001, + 0x0000ffffffff0100, + 0x0000ffffff00ff01, + 0x0000ffffff000000, + 0x0000ffffff000101, + 0x0000ffffff01ff00, + 0x0000ffffff0100ff, + 0x0000ffffff010100, + 0x0000ffff00ffffff, + 0x0000ffff00ff0000, + 0x0000ffff00ff01ff, + 0x0000ffff0000ff00, + 0x0000ffff000000ff, + 0x0000ffff00000000, + 0x0000ffff00000001, + 0x0000ffff00000100, + 0x0000ffff00010000, + 0x0000ffff000101ff, + 0x0000ffff01ff0001, + 0x0000ffff01ff0100, + 0x0000ffff01000000, + 0x0000ffff010001ff, + 0x0000ffff0101ffff, + 0x0000ffff0101ff00, + 0x0000ffff01010001, + 0x0000ffff01010100, + 0x0000ff00ffff0000, + 0x0000ff00ffff01ff, + 0x0000ff00ffff0100, + 0x0000ff00ffff0101, + 0x0000ff00ff00ff00, + 0x0000ff00ff0000ff, + 0x0000ff00ff000000, + 0x0000ff00ff000001, + 0x0000ff00ff0001ff, + 0x0000ff00ff000100, + 0x0000ff00ff01ffff, + 0x0000ff00ff010000, + 0x0000ff00ff010001, + 0x0000ff00ff0101ff, + 0x0000ff00ff010101, + 0x0000ff0000ffff00, + 0x0000ff0000ff00ff, + 0x0000ff0000ff0000, + 0x0000ff0000ff0001, + 0x0000ff0000ff0100, + 0x0000ff000000ffff, + 0x0000ff000000ff00, + 0x0000ff000000ff01, + 0x0000ff00000000ff, + 0x0000ff0000000000, + 0x0000ff0000000001, + 0x0000ff00000001ff, + 0x0000ff0000000100, + 0x0000ff0000000101, + 0x0000ff000001ff00, + 0x0000ff00000100ff, + 0x0000ff0000010000, + 0x0000ff0000010001, + 0x0000ff0000010100, + 0x0000ff0001ffff01, + 0x0000ff0001ff0000, + 0x0000ff000100ff00, + 0x0000ff00010000ff, + 0x0000ff0001000000, + 0x0000ff0001000001, + 0x0000ff0001000100, + 0x0000ff000101ffff, + 0x0000ff0001010000, + 0x0000ff0001010101, + 0x0000ff01ffffff00, + 0x0000ff01ffff0001, + 0x0000ff01ff00ff01, + 0x0000ff01ff000000, + 0x0000ff01ff000101, + 0x0000ff01ff01ff00, + 0x0000ff01ff0100ff, + 0x0000ff0100ffff01, + 0x0000ff0100ff0000, + 0x0000ff0100ff0101, + 0x0000ff010000ff00, + 0x0000ff01000000ff, + 0x0000ff0100000000, + 0x0000ff0100000001, + 0x0000ff0100000100, + 0x0000ff010001ff01, + 0x0000ff0100010000, + 0x0000ff0101ff0000, + 0x0000ff010100ffff, + 0x0000ff010100ff01, + 0x0000ff0101000000, + 0x0000ff0101000100, + 0x0000ff0101000101, + 0x0000ff01010100ff, + 0x000000ffffff00ff, + 0x000000ffffff0000, + 0x000000ffff00ff00, + 0x000000ffff0000ff, + 0x000000ffff000000, + 0x000000ffff000001, + 0x000000ffff0001ff, + 0x000000ffff000100, + 0x000000ffff01ff00, + 0x000000ffff010000, + 0x000000ffff0101ff, + 0x000000ffff010101, + 0x000000ff00ffff00, + 0x000000ff00ff00ff, + 0x000000ff00ff0000, + 0x000000ff00ff0001, + 0x000000ff00ff0100, + 0x000000ff00ff0101, + 0x000000ff0000ffff, + 0x000000ff0000ff00, + 0x000000ff000000ff, + 0x000000ff00000000, + 0x000000ff00000001, + 0x000000ff000001ff, + 0x000000ff00000100, + 0x000000ff00000101, + 0x000000ff0001ff00, + 0x000000ff0001ff01, + 0x000000ff000100ff, + 0x000000ff00010000, + 0x000000ff00010001, + 0x000000ff00010100, + 0x000000ff01ffffff, + 0x000000ff01ff01ff, + 0x000000ff01ff0101, + 0x000000ff0100ff00, + 0x000000ff010000ff, + 0x000000ff01000000, + 0x000000ff01000001, + 0x000000ff01000100, + 0x000000ff0101ff00, + 0x000000ff010100ff, + 0x000000ff01010000, + 0x000000ff01010101, + 0x00000000ffffff00, + 0x00000000ffffff01, + 0x00000000ffff00ff, + 0x00000000ffff0000, + 0x00000000ffff0001, + 0x00000000ffff0100, + 0x00000000ff00ffff, + 0x00000000ff00ff00, + 0x00000000ff00ff01, + 0x00000000ff0000ff, + 0x00000000ff000000, + 0x00000000ff000001, + 0x00000000ff000100, + 0x00000000ff000101, + 0x00000000ff01ff00, + 0x00000000ff0100ff, + 0x00000000ff010000, + 0x00000000ff010001, + 0x00000000ff010100, + 0x0000000000ffffff, + 0x0000000000ffff00, + 0x0000000000ffff01, + 0x0000000000ff00ff, + 0x0000000000ff0000, + 0x0000000000ff0001, + 0x0000000000ff01ff, + 0x0000000000ff0100, + 0x000000000000ffff, + 0x000000000000ff00, + 0x000000000000ff01, + 0x00000000000000ff, + 0x0000000000000000, + 0x0000000000000001, + 0x00000000000001ff, + 0x0000000000000100, + 0x0000000000000101, + 0x000000000001ffff, + 0x000000000001ff00, + 0x00000000000100ff, + 0x0000000000010000, + 0x0000000000010001, + 0x00000000000101ff, + 0x0000000000010100, + 0x0000000000010101, + 0x0000000001ffff00, + 0x0000000001ff00ff, + 0x0000000001ff0000, + 0x0000000001ff0100, + 0x0000000001ff0101, + 0x000000000100ffff, + 0x000000000100ff00, + 0x00000000010000ff, + 0x0000000001000000, + 0x0000000001000001, + 0x00000000010001ff, + 0x0000000001000100, + 0x000000000101ff00, + 0x00000000010100ff, + 0x0000000001010000, + 0x0000000001010001, + 0x0000000001010100, + 0x00000001ffffffff, + 0x00000001ffffff00, + 0x00000001ffffff01, + 0x00000001ffff00ff, + 0x00000001ffff0001, + 0x00000001ffff01ff, + 0x00000001ffff0100, + 0x00000001ff00ff00, + 0x00000001ff0000ff, + 0x00000001ff000000, + 0x00000001ff0001ff, + 0x00000001ff000100, + 0x00000001ff01ffff, + 0x00000001ff01ff00, + 0x00000001ff01ff01, + 0x00000001ff0100ff, + 0x00000001ff010000, + 0x00000001ff010001, + 0x00000001ff0101ff, + 0x00000001ff010100, + 0x0000000100ffff00, + 0x0000000100ff0000, + 0x0000000100ff0001, + 0x0000000100ff01ff, + 0x0000000100ff0100, + 0x0000000100ff0101, + 0x000000010000ffff, + 0x000000010000ff00, + 0x000000010000ff01, + 0x00000001000000ff, + 0x0000000100000000, + 0x0000000100000001, + 0x00000001000001ff, + 0x0000000100000100, + 0x0000000100000101, + 0x000000010001ff00, + 0x00000001000100ff, + 0x0000000100010000, + 0x0000000100010100, + 0x0000000101ffff01, + 0x0000000101ff0000, + 0x0000000101ff0001, + 0x0000000101ff01ff, + 0x0000000101ff0100, + 0x0000000101ff0101, + 0x000000010100ff00, + 0x0000000101000000, + 0x0000000101000101, + 0x000000010101ff01, + 0x0000000101010000, + 0x0000000101010001, + 0x00000001010101ff, + 0x0000000101010100, + 0x000001ffffff00ff, + 0x000001ffffff0000, + 0x000001ffffff0001, + 0x000001ffffff0100, + 0x000001ffff00ffff, + 0x000001ffff000000, + 0x000001ffff0001ff, + 0x000001ffff01ff00, + 0x000001ffff010101, + 0x000001ff00ff0000, + 0x000001ff00ff01ff, + 0x000001ff00ff0101, + 0x000001ff0000ff00, + 0x000001ff000000ff, + 0x000001ff00000000, + 0x000001ff00000001, + 0x000001ff000001ff, + 0x000001ff00000100, + 0x000001ff0001ffff, + 0x000001ff0001ff01, + 0x000001ff000100ff, + 0x000001ff00010000, + 0x000001ff01ffff01, + 0x000001ff01ff0100, + 0x000001ff0100ffff, + 0x000001ff0100ff01, + 0x000001ff01000000, + 0x000001ff010001ff, + 0x000001ff0101ff00, + 0x000001ff01010100, + 0x00000100ffffff00, + 0x00000100ffffff01, + 0x00000100ffff0000, + 0x00000100ffff0101, + 0x00000100ff00ff00, + 0x00000100ff0000ff, + 0x00000100ff000000, + 0x00000100ff000001, + 0x00000100ff000100, + 0x00000100ff010000, + 0x0000010000ffff00, + 0x0000010000ff00ff, + 0x0000010000ff0000, + 0x0000010000ff0001, + 0x0000010000ff0100, + 0x000001000000ffff, + 0x000001000000ff00, + 0x000001000000ff01, + 0x00000100000000ff, + 0x0000010000000000, + 0x0000010000000001, + 0x00000100000001ff, + 0x0000010000000100, + 0x0000010000000101, + 0x000001000001ff00, + 0x00000100000100ff, + 0x0000010000010000, + 0x0000010000010001, + 0x0000010000010100, + 0x0000010001ffff00, + 0x0000010001ff0000, + 0x0000010001ff0100, + 0x000001000100ff00, + 0x00000100010000ff, + 0x0000010001000000, + 0x0000010001000001, + 0x00000100010001ff, + 0x0000010001000100, + 0x0000010001010000, + 0x00000101ffff00ff, + 0x00000101ffff01ff, + 0x00000101ff000000, + 0x00000101ff000101, + 0x00000101ff01ffff, + 0x00000101ff010000, + 0x00000101ff010001, + 0x00000101ff010100, + 0x0000010100ff0000, + 0x0000010100ff01ff, + 0x0000010100ff0100, + 0x000001010000ff00, + 0x0000010100000000, + 0x0000010100000001, + 0x00000101000001ff, + 0x0000010100000100, + 0x000001010001ff01, + 0x0000010100010000, + 0x00000101000101ff, + 0x0000010100010101, + 0x0000010101ffff00, + 0x0000010101ff0101, + 0x000001010100ff01, + 0x0000010101000000, + 0x0000010101000001, + 0x00000101010001ff, + 0x0000010101000101, + 0x000001010101ff00, + 0x0001ffffffff0000, + 0x0001ffffff0000ff, + 0x0001ffffff000001, + 0x0001ffffff000100, + 0x0001ffffff010000, + 0x0001ffff00ff00ff, + 0x0001ffff0000ffff, + 0x0001ffff00000000, + 0x0001ffff00000001, + 0x0001ffff000001ff, + 0x0001ffff00000101, + 0x0001ffff0001ff00, + 0x0001ffff000100ff, + 0x0001ffff00010001, + 0x0001ffff00010100, + 0x0001ffff01ffff00, + 0x0001ffff01000001, + 0x0001ffff01010000, + 0x0001ff00ffffff00, + 0x0001ff00ffff00ff, + 0x0001ff00ffff0001, + 0x0001ff00ffff0100, + 0x0001ff00ff00ff01, + 0x0001ff00ff000000, + 0x0001ff00ff01ff00, + 0x0001ff00ff01ff01, + 0x0001ff00ff010001, + 0x0001ff00ff010100, + 0x0001ff0000ff0000, + 0x0001ff0000ff0100, + 0x0001ff000000ff00, + 0x0001ff0000000000, + 0x0001ff0000000001, + 0x0001ff0000000100, + 0x0001ff0000010000, + 0x0001ff0000010001, + 0x0001ff0000010101, + 0x0001ff0001ff00ff, + 0x0001ff0001ff0101, + 0x0001ff000100ff01, + 0x0001ff0001000000, + 0x0001ff000101ff00, + 0x0001ff0001010001, + 0x0001ff0001010100, + 0x0001ff01ff00ff00, + 0x0001ff01ff000001, + 0x0001ff01ff000100, + 0x0001ff0100ffffff, + 0x0001ff0100ffff00, + 0x0001ff0100ff0001, + 0x0001ff0100000000, + 0x0001ff0100000001, + 0x0001ff01000001ff, + 0x0001ff010001ffff, + 0x0001ff0101ff0000, + 0x0001ff010100ff00, + 0x0001ff0101000001, + 0x0001ff0101010000, + 0x000100ffff00ff00, + 0x000100ffff00ff01, + 0x000100ffff000000, + 0x000100ffff000001, + 0x000100ffff000101, + 0x000100ffff01ff00, + 0x000100ffff010001, + 0x000100ffff010100, + 0x000100ff00ffffff, + 0x000100ff00ffff01, + 0x000100ff00ff0000, + 0x000100ff00ff01ff, + 0x000100ff00ff0101, + 0x000100ff0000ff00, + 0x000100ff000000ff, + 0x000100ff00000000, + 0x000100ff00000001, + 0x000100ff00000100, + 0x000100ff00000101, + 0x000100ff0001ffff, + 0x000100ff0001ff01, + 0x000100ff00010000, + 0x000100ff01ff00ff, + 0x000100ff01ff0000, + 0x000100ff01ff0100, + 0x000100ff0100ffff, + 0x000100ff0100ff01, + 0x000100ff010000ff, + 0x000100ff01000000, + 0x000100ff01000001, + 0x000100ff010001ff, + 0x000100ff01000101, + 0x000100ff0101ff00, + 0x000100ff010100ff, + 0x000100ff01010100, + 0x00010000ffff0000, + 0x00010000ffff01ff, + 0x00010000ffff0101, + 0x00010000ff00ff00, + 0x00010000ff000000, + 0x00010000ff000001, + 0x00010000ff000100, + 0x0001000000ff00ff, + 0x0001000000ff0000, + 0x0001000000ff0001, + 0x0001000000ff0100, + 0x000100000000ffff, + 0x000100000000ff00, + 0x00010000000000ff, + 0x0001000000000000, + 0x0001000000000001, + 0x0001000000000100, + 0x000100000001ff00, + 0x00010000000100ff, + 0x0001000000010000, + 0x0001000000010001, + 0x0001000000010100, + 0x0001000001ff0001, + 0x0001000001ff0100, + 0x0001000001ff0101, + 0x000100000100ff00, + 0x0001000001000000, + 0x0001000001000001, + 0x0001000001000100, + 0x0001000001000101, + 0x000100000101ff01, + 0x0001000001010000, + 0x0001000001010001, + 0x00010000010101ff, + 0x00010001ffffff01, + 0x00010001ffff0100, + 0x00010001ff000000, + 0x00010001ff01ffff, + 0x00010001ff010001, + 0x00010001ff0101ff, + 0x00010001ff010100, + 0x0001000100ffffff, + 0x0001000100ff0000, + 0x0001000100ff01ff, + 0x0001000100ff0101, + 0x000100010000ff00, + 0x00010001000000ff, + 0x0001000100000000, + 0x0001000100000001, + 0x00010001000001ff, + 0x0001000100000101, + 0x000100010001ffff, + 0x0001000100010000, + 0x00010001000101ff, + 0x0001000101ffffff, + 0x0001000101ffff01, + 0x0001000101ff0000, + 0x0001000101ff0101, + 0x00010001010000ff, + 0x0001000101000001, + 0x00010001010001ff, + 0x0001000101000100, + 0x000100010101ffff, + 0x00010001010100ff, + 0x0001000101010001, + 0x0001000101010101, + 0x000101ffff000001, + 0x000101ffff000100, + 0x000101ffff010000, + 0x000101ff00ffff00, + 0x000101ff0000ff01, + 0x000101ff00000000, + 0x000101ff00000101, + 0x000101ff0001ff00, + 0x000101ff00010100, + 0x000101ff01ff0000, + 0x000101ff0100ff00, + 0x000101ff010001ff, + 0x000101ff01010001, + 0x00010100ffffff00, + 0x00010100ffff00ff, + 0x00010100ff00ffff, + 0x00010100ff000000, + 0x00010100ff01ff00, + 0x00010100ff0100ff, + 0x00010100ff010001, + 0x00010100ff010100, + 0x0001010000ffffff, + 0x0001010000ffff00, + 0x0001010000ff0000, + 0x0001010000ff0001, + 0x0001010000ff01ff, + 0x000101000000ff00, + 0x00010100000000ff, + 0x0001010000000000, + 0x0001010000000001, + 0x0001010000000100, + 0x000101000001ffff, + 0x0001010000010000, + 0x0001010000010101, + 0x0001010001ffff01, + 0x0001010001ff00ff, + 0x0001010001ff0101, + 0x0001010001000000, + 0x000101000101ff00, + 0x00010100010100ff, + 0x0001010001010000, + 0x0001010001010100, + 0x00010101ff00ff00, + 0x00010101ff000001, + 0x00010101ff0001ff, + 0x0001010100ffff00, + 0x0001010100ff00ff, + 0x0001010100ff0100, + 0x000101010000ffff, + 0x0001010100000000, + 0x00010101000001ff, + 0x0001010100000101, + 0x00010101000100ff, + 0x0001010100010000, + 0x0001010100010100, + 0x0001010101ff0001, + 0x00010101010000ff, + 0x00010101010001ff, + 0x0001010101000101, + 0x0001010101010001, + 0x01ffffffffffffff, + 0x01ffffffffffff01, + 0x01ffffffffff01ff, + 0x01ffffffffff0101, + 0x01ffffffff01ffff, + 0x01ffffffff01ff01, + 0x01ffffffff0101ff, + 0x01ffffffff010101, + 0x01ffffff00ff0000, + 0x01ffffff0000ffff, + 0x01ffffff0000ff00, + 0x01ffffff000000ff, + 0x01ffffff00000001, + 0x01ffffff00000100, + 0x01ffffff00010000, + 0x01ffffff01ffffff, + 0x01ffffff01ffff01, + 0x01ffffff01ff01ff, + 0x01ffffff01ff0101, + 0x01ffffff01000000, + 0x01ffffff0101ffff, + 0x01ffffff0101ff01, + 0x01ffffff010101ff, + 0x01ffffff01010101, + 0x01ffff00ffff0000, + 0x01ffff00ff00ff00, + 0x01ffff00ff0000ff, + 0x01ffff00ff000001, + 0x01ffff00ff000100, + 0x01ffff00ff010000, + 0x01ffff0000ffff00, + 0x01ffff0000ff00ff, + 0x01ffff0000ff0100, + 0x01ffff000000ffff, + 0x01ffff000000ff01, + 0x01ffff0000000000, + 0x01ffff0000000001, + 0x01ffff00000001ff, + 0x01ffff0000000100, + 0x01ffff00000100ff, + 0x01ffff0000010001, + 0x01ffff0000010100, + 0x01ffff0001ff0000, + 0x01ffff0001ff0100, + 0x01ffff00010000ff, + 0x01ffff0001000001, + 0x01ffff0001000100, + 0x01ffff0001010000, + 0x01ffff01ffffffff, + 0x01ffff01ffffff01, + 0x01ffff01ffff01ff, + 0x01ffff01ffff0101, + 0x01ffff01ff000000, + 0x01ffff01ff01ffff, + 0x01ffff01ff01ff01, + 0x01ffff01ff0101ff, + 0x01ffff01ff010101, + 0x01ffff010000ff00, + 0x01ffff01000000ff, + 0x01ffff0100000100, + 0x01ffff0100010000, + 0x01ffff0101ffffff, + 0x01ffff0101ffff01, + 0x01ffff0101ff01ff, + 0x01ffff0101ff0101, + 0x01ffff0101000000, + 0x01ffff010101ffff, + 0x01ffff010101ff01, + 0x01ffff01010101ff, + 0x01ffff0101010101, + 0x01ff00ffff0000ff, + 0x01ff00ffff000100, + 0x01ff00ff00ffff00, + 0x01ff00ff00ff00ff, + 0x01ff00ff0000ff00, + 0x01ff00ff00000000, + 0x01ff00ff00000101, + 0x01ff00ff0001ff00, + 0x01ff00ff000100ff, + 0x01ff00ff00010100, + 0x01ff00ff010000ff, + 0x01ff00ff01000100, + 0x01ff0000ffffff00, + 0x01ff0000ffff0100, + 0x01ff0000ff00ff01, + 0x01ff0000ff000000, + 0x01ff0000ff000101, + 0x01ff0000ff010001, + 0x01ff0000ff010100, + 0x01ff000000ffffff, + 0x01ff000000ffff00, + 0x01ff000000ff0000, + 0x01ff000000ff01ff, + 0x01ff00000000ff00, + 0x01ff0000000000ff, + 0x01ff000000000000, + 0x01ff000000000001, + 0x01ff000000000100, + 0x01ff000000000101, + 0x01ff000000010000, + 0x01ff000000010001, + 0x01ff0000000101ff, + 0x01ff000000010101, + 0x01ff000001ffff00, + 0x01ff000001ff00ff, + 0x01ff000001ff0001, + 0x01ff000001ff0100, + 0x01ff00000100ffff, + 0x01ff00000100ff01, + 0x01ff000001000000, + 0x01ff0000010001ff, + 0x01ff000001010001, + 0x01ff0001ff00ff00, + 0x01ff0001ff000001, + 0x01ff0001ff000100, + 0x01ff0001ff010000, + 0x01ff000100ffff00, + 0x01ff000100ff00ff, + 0x01ff000100ff0100, + 0x01ff000100ff0101, + 0x01ff00010000ffff, + 0x01ff000100000000, + 0x01ff000100000100, + 0x01ff000100000101, + 0x01ff00010001ff00, + 0x01ff000100010001, + 0x01ff000100010101, + 0x01ff000101ff0000, + 0x01ff00010100ff00, + 0x01ff000101000101, + 0x01ff0001010100ff, + 0x01ff01ffffffffff, + 0x01ff01ffffffff01, + 0x01ff01ffffff01ff, + 0x01ff01ffffff0101, + 0x01ff01ffff000000, + 0x01ff01ffff01ffff, + 0x01ff01ffff01ff01, + 0x01ff01ffff0101ff, + 0x01ff01ffff010101, + 0x01ff01ff00ffff00, + 0x01ff01ff00ff0000, + 0x01ff01ff0000ff00, + 0x01ff01ff000000ff, + 0x01ff01ff00000100, + 0x01ff01ff00010000, + 0x01ff01ff00010100, + 0x01ff01ff01ffffff, + 0x01ff01ff01ffff01, + 0x01ff01ff01ff01ff, + 0x01ff01ff01ff0101, + 0x01ff01ff01000000, + 0x01ff01ff0101ffff, + 0x01ff01ff0101ff01, + 0x01ff01ff010101ff, + 0x01ff01ff01010101, + 0x01ff0100ffff0000, + 0x01ff0100ffff0001, + 0x01ff0100ff00ff00, + 0x01ff0100ff0000ff, + 0x01ff0100ff000001, + 0x01ff0100ff010000, + 0x01ff010000ffff00, + 0x01ff010000ff00ff, + 0x01ff010000ff0001, + 0x01ff010000ff0100, + 0x01ff01000000ffff, + 0x01ff01000000ff01, + 0x01ff010000000000, + 0x01ff010000000101, + 0x01ff01000001ff00, + 0x01ff0100000100ff, + 0x01ff010001ff0000, + 0x01ff010001000001, + 0x01ff010001000100, + 0x01ff010001010000, + 0x01ff0101ffffffff, + 0x01ff0101ffffff01, + 0x01ff0101ffff01ff, + 0x01ff0101ffff0101, + 0x01ff0101ff000000, + 0x01ff0101ff01ffff, + 0x01ff0101ff01ff01, + 0x01ff0101ff0101ff, + 0x01ff0101ff010101, + 0x01ff010100ff0000, + 0x01ff01010000ff00, + 0x01ff0101000000ff, + 0x01ff010100000001, + 0x01ff010101ffffff, + 0x01ff010101ffff01, + 0x01ff010101ff01ff, + 0x01ff010101ff0101, + 0x01ff010101000000, + 0x01ff01010101ffff, + 0x01ff01010101ff01, + 0x01ff0101010101ff, + 0x01ff010101010101, + 0x0100ffffffff0000, + 0x0100ffffff00ff00, + 0x0100ffffff000001, + 0x0100ffffff0001ff, + 0x0100ffffff000100, + 0x0100ffffff010000, + 0x0100ffff00ffff00, + 0x0100ffff00ff0001, + 0x0100ffff00ff0100, + 0x0100ffff00000000, + 0x0100ffff000001ff, + 0x0100ffff00000101, + 0x0100ffff00010100, + 0x0100ffff00010101, + 0x0100ffff01ff0000, + 0x0100ffff0100ff00, + 0x0100ffff010000ff, + 0x0100ffff01000001, + 0x0100ffff01000100, + 0x0100ffff01010000, + 0x0100ff00ffffff00, + 0x0100ff00ffff00ff, + 0x0100ff00ffff0001, + 0x0100ff00ffff0100, + 0x0100ff00ff00ffff, + 0x0100ff00ff000000, + 0x0100ff00ff0001ff, + 0x0100ff00ff000101, + 0x0100ff00ff01ff00, + 0x0100ff00ff0100ff, + 0x0100ff00ff010001, + 0x0100ff00ff010100, + 0x0100ff0000ffffff, + 0x0100ff0000ff0000, + 0x0100ff000000ffff, + 0x0100ff000000ff00, + 0x0100ff00000000ff, + 0x0100ff0000000000, + 0x0100ff0000000001, + 0x0100ff0000000100, + 0x0100ff000001ff01, + 0x0100ff0000010000, + 0x0100ff0001ff00ff, + 0x0100ff0001ff0001, + 0x0100ff000100ff01, + 0x0100ff0001000000, + 0x0100ff00010001ff, + 0x0100ff000101ff00, + 0x0100ff00010100ff, + 0x0100ff0001010001, + 0x0100ff0001010100, + 0x0100ff01ffff0000, + 0x0100ff01ff00ff00, + 0x0100ff01ff0000ff, + 0x0100ff01ff000100, + 0x0100ff01ff010000, + 0x0100ff0100ff00ff, + 0x0100ff0100ff0001, + 0x0100ff0100ff0100, + 0x0100ff010000ffff, + 0x0100ff010000ff01, + 0x0100ff0100000000, + 0x0100ff01000001ff, + 0x0100ff0100010001, + 0x0100ff0100010100, + 0x0100ff0101ff0000, + 0x0100ff01010000ff, + 0x0100ff0101000001, + 0x0100ff0101010100, + 0x010000ffffffff00, + 0x010000ffffff00ff, + 0x010000ffffff0001, + 0x010000ffff00ffff, + 0x010000ffff000000, + 0x010000ffff0001ff, + 0x010000ffff010001, + 0x010000ff00ffffff, + 0x010000ff00ff0101, + 0x010000ff0000ff00, + 0x010000ff000000ff, + 0x010000ff00000000, + 0x010000ff00000001, + 0x010000ff000001ff, + 0x010000ff00000100, + 0x010000ff0001ffff, + 0x010000ff0001ff00, + 0x010000ff0001ff01, + 0x010000ff00010000, + 0x010000ff01ff00ff, + 0x010000ff01ff0001, + 0x010000ff0100ff01, + 0x010000ff010000ff, + 0x010000ff01000000, + 0x010000ff010001ff, + 0x010000ff0101ff00, + 0x010000ff01010100, + 0x01000000ffffffff, + 0x01000000ffff0000, + 0x01000000ffff01ff, + 0x01000000ffff0101, + 0x01000000ff00ffff, + 0x01000000ff00ff00, + 0x01000000ff0000ff, + 0x01000000ff000000, + 0x01000000ff000001, + 0x01000000ff000100, + 0x01000000ff01ff00, + 0x01000000ff010000, + 0x01000000ff010100, + 0x01000000ff010101, + 0x0100000000ffff00, + 0x0100000000ff00ff, + 0x0100000000ff0000, + 0x0100000000ff0001, + 0x0100000000ff0100, + 0x010000000000ffff, + 0x010000000000ff00, + 0x010000000000ff01, + 0x01000000000000ff, + 0x0100000000000000, + 0x0100000000000001, + 0x01000000000001ff, + 0x0100000000000100, + 0x0100000000000101, + 0x010000000001ff00, + 0x01000000000100ff, + 0x0100000000010000, + 0x0100000000010001, + 0x0100000000010100, + 0x0100000001ffff00, + 0x0100000001ff0000, + 0x0100000001ff01ff, + 0x010000000100ff00, + 0x010000000100ff01, + 0x01000000010000ff, + 0x0100000001000000, + 0x0100000001000001, + 0x0100000001000100, + 0x0100000001000101, + 0x010000000101ffff, + 0x010000000101ff01, + 0x0100000001010000, + 0x01000000010101ff, + 0x0100000001010101, + 0x01000001ffffff00, + 0x01000001ffff00ff, + 0x01000001ff00ffff, + 0x01000001ff000000, + 0x01000001ff000100, + 0x01000001ff01ffff, + 0x01000001ff010001, + 0x01000001ff010100, + 0x0100000100ff0000, + 0x0100000100ff01ff, + 0x0100000100ff0100, + 0x010000010000ff00, + 0x010000010000ff01, + 0x0100000100000000, + 0x0100000100000001, + 0x0100000100000100, + 0x0100000100010000, + 0x01000001000101ff, + 0x0100000101ffff01, + 0x0100000101ff00ff, + 0x0100000101ff0100, + 0x0100000101ff0101, + 0x010000010100ff01, + 0x01000001010000ff, + 0x0100000101000000, + 0x01000001010100ff, + 0x0100000101010001, + 0x0100000101010100, + 0x010001ffffff0000, + 0x010001ffff000001, + 0x010001ffff000100, + 0x010001ffff010000, + 0x010001ff00ffff00, + 0x010001ff00ff0001, + 0x010001ff0000ffff, + 0x010001ff0000ff01, + 0x010001ff00000000, + 0x010001ff00000001, + 0x010001ff00000101, + 0x010001ff000100ff, + 0x010001ff00010000, + 0x010001ff01ff0000, + 0x010001ff0100ff00, + 0x010001ff01000001, + 0x010001ff01000100, + 0x010001ff01010000, + 0x01000100ffff00ff, + 0x01000100ffff0001, + 0x01000100ffff0100, + 0x01000100ff00ffff, + 0x01000100ff00ff01, + 0x01000100ff000000, + 0x01000100ff0001ff, + 0x01000100ff000101, + 0x01000100ff01ffff, + 0x01000100ff01ff00, + 0x01000100ff0100ff, + 0x01000100ff010001, + 0x0100010000ffffff, + 0x0100010000ffff01, + 0x0100010000ff0000, + 0x0100010000ff01ff, + 0x0100010000ff0101, + 0x010001000000ff00, + 0x01000100000000ff, + 0x0100010000000000, + 0x0100010000000001, + 0x0100010000000100, + 0x010001000001ff01, + 0x0100010000010000, + 0x0100010000010001, + 0x0100010000010101, + 0x0100010001ffff00, + 0x0100010001ff00ff, + 0x010001000100ffff, + 0x010001000100ff01, + 0x0100010001000000, + 0x0100010001000101, + 0x010001000101ff00, + 0x0100010001010001, + 0x01000101ffff0000, + 0x01000101ff000000, + 0x01000101ff010000, + 0x0100010100ff00ff, + 0x0100010100ff0001, + 0x0100010100ff0100, + 0x010001010000ffff, + 0x0100010100000000, + 0x01000101000001ff, + 0x010001010001ff00, + 0x0100010101ff0000, + 0x010001010100ff00, + 0x01000101010000ff, + 0x0100010101000000, + 0x0100010101000001, + 0x0101ffffffffffff, + 0x0101ffffffffff01, + 0x0101ffffffff01ff, + 0x0101ffffffff0101, + 0x0101ffffff000000, + 0x0101ffffff01ffff, + 0x0101ffffff01ff01, + 0x0101ffffff0101ff, + 0x0101ffffff010101, + 0x0101ffff00ff0000, + 0x0101ffff0000ff00, + 0x0101ffff000000ff, + 0x0101ffff00000001, + 0x0101ffff00000100, + 0x0101ffff01ffffff, + 0x0101ffff01ffff01, + 0x0101ffff01ff01ff, + 0x0101ffff01ff0101, + 0x0101ffff01000000, + 0x0101ffff0101ffff, + 0x0101ffff0101ff01, + 0x0101ffff010101ff, + 0x0101ffff01010101, + 0x0101ff00ffff0000, + 0x0101ff00ffff0100, + 0x0101ff00ff00ff00, + 0x0101ff00ff0000ff, + 0x0101ff00ff000001, + 0x0101ff00ff000100, + 0x0101ff00ff000101, + 0x0101ff0000ff0001, + 0x0101ff0000ff0100, + 0x0101ff000000ff00, + 0x0101ff0000000000, + 0x0101ff00000001ff, + 0x0101ff0000000101, + 0x0101ff000001ff00, + 0x0101ff00000100ff, + 0x0101ff0001ff0000, + 0x0101ff000100ffff, + 0x0101ff000100ff01, + 0x0101ff0001000001, + 0x0101ff0001000100, + 0x0101ff01ffffff01, + 0x0101ff01ffff01ff, + 0x0101ff01ffff0101, + 0x0101ff01ff00ffff, + 0x0101ff01ff000100, + 0x0101ff01ff01ff01, + 0x0101ff01ff0101ff, + 0x0101ff01ff010101, + 0x0101ff0100ff0000, + 0x0101ff010000ff00, + 0x0101ff0100000001, + 0x0101ff0100000100, + 0x0101ff0100010000, + 0x0101ff0101ffffff, + 0x0101ff0101ffff01, + 0x0101ff0101ff01ff, + 0x0101ff0101ff0101, + 0x0101ff0101000000, + 0x0101ff010101ffff, + 0x0101ff010101ff01, + 0x0101ff01010101ff, + 0x0101ff0101010101, + 0x010100ffff000100, + 0x010100ffff010000, + 0x010100ff00ffff00, + 0x010100ff00ff00ff, + 0x010100ff0000ffff, + 0x010100ff000000ff, + 0x010100ff00000000, + 0x010100ff000001ff, + 0x010100ff00000101, + 0x010100ff0001ff00, + 0x010100ff00010000, + 0x010100ff00010001, + 0x010100ff000101ff, + 0x010100ff00010100, + 0x010100ff01ff0000, + 0x01010000ffff0001, + 0x01010000ffff0100, + 0x01010000ff00ffff, + 0x01010000ff00ff01, + 0x01010000ff000000, + 0x01010000ff0001ff, + 0x01010000ff010001, + 0x01010000ff010100, + 0x0101000000ffff01, + 0x0101000000ff0000, + 0x010100000000ff00, + 0x01010000000000ff, + 0x0101000000000000, + 0x0101000000000001, + 0x0101000000000100, + 0x0101000000010000, + 0x0101000000010101, + 0x0101000001ffff00, + 0x0101000001ff00ff, + 0x0101000001ff0000, + 0x0101000001ff0001, + 0x0101000001ff0100, + 0x010100000100ff01, + 0x0101000001000000, + 0x01010000010001ff, + 0x01010001ffff0000, + 0x01010001ff00ff00, + 0x01010001ff000001, + 0x01010001ff000101, + 0x01010001ff01ff00, + 0x01010001ff010000, + 0x0101000100ff00ff, + 0x0101000100ff0001, + 0x0101000100ff0101, + 0x010100010000ff01, + 0x0101000100000000, + 0x0101000100000001, + 0x01010001000001ff, + 0x010100010001ffff, + 0x010100010001ff01, + 0x0101000101ff0001, + 0x010100010100ffff, + 0x0101000101000000, + 0x0101000101000001, + 0x0101000101000100, + 0x010100010101ff00, + 0x01010001010100ff, + 0x0101000101010001, + 0x010101ffffffffff, + 0x010101ffffffff01, + 0x010101ffffff01ff, + 0x010101ffffff0101, + 0x010101ffff01ffff, + 0x010101ffff01ff01, + 0x010101ffff0101ff, + 0x010101ffff010101, + 0x010101ff0000ff00, + 0x010101ff000000ff, + 0x010101ff00000001, + 0x010101ff00000100, + 0x010101ff01ffffff, + 0x010101ff01ffff01, + 0x010101ff01ff01ff, + 0x010101ff01ff0101, + 0x010101ff01000000, + 0x010101ff0101ffff, + 0x010101ff0101ff01, + 0x010101ff010101ff, + 0x010101ff01010101, + 0x01010100ffff0000, + 0x01010100ff0000ff, + 0x01010100ff000100, + 0x01010100ff01ff00, + 0x01010100ff010000, + 0x0101010000ffff00, + 0x010101000000ffff, + 0x0101010000000000, + 0x0101010000000101, + 0x010101000001ff00, + 0x0101010000010001, + 0x0101010000010100, + 0x010101000100ffff, + 0x0101010001000001, + 0x01010101ffffffff, + 0x01010101ffffff01, + 0x01010101ffff01ff, + 0x01010101ffff0101, + 0x01010101ff01ffff, + 0x01010101ff01ff01, + 0x01010101ff0101ff, + 0x01010101ff010101, + 0x010101010000ff00, + 0x01010101000000ff, + 0x0101010100000001, + 0x0101010101ffffff, + 0x0101010101ffff01, + 0x0101010101ff01ff, + 0x0101010101ff0101, + 0x0101010101000000, + 0x010101010101ffff, + 0x010101010101ff01, + 0x01010101010101ff, + 0x0101010101010101, ]; diff --git a/crates/native-cpu-expert/src/rust_k_blocks.rs b/crates/native-cpu-expert/src/rust_k_blocks.rs index b2546777..9ff64509 100644 --- a/crates/native-cpu-expert/src/rust_k_blocks.rs +++ b/crates/native-cpu-expert/src/rust_k_blocks.rs @@ -1,40 +1,156 @@ //! Pinned ggml x86 AVX2 Q2_K/Q3_K/Q5_K/Q6_K row dot sequences. //! Only integer operand unpack is scalarized; vector lane grouping and every //! float FMA/correction/reduction follow the pinned AVX2 branch. -use std::arch::x86_64::*; +use super::rust_simd::{half, hsum_ggml}; use super::rust_types::Q8K; -use super::rust_simd::{half,hsum_ggml}; +use std::arch::x86_64::*; // Bounds: `dot` asserts row.len()==ys.len()*block; all row bytes are read through safe indexing, and the only raw loads are // 32-byte reads of local [i16;16]/[u8;256]/[i8;256] arrays at offsets <= 224 and of y.bsums ([i16;16]). Gate: avx2_ok(). -fn h(x:&[u8],p:usize)->f32{/* SAFETY: private; reached only from `dot`, whose entry gate proved F16C. */unsafe{half(u16::from_le_bytes([x[p],x[p+1]]))}} -fn six_scales(x:&[u8])->[i16;16]{ - let a=u32::from_le_bytes(x[..4].try_into().unwrap());let b=u32::from_le_bytes(x[4..8].try_into().unwrap());let c=u32::from_le_bytes(x[8..12].try_into().unwrap()); - let u=[(a&0x0f0f0f0f)|((c&0x03030303)<<4),(b&0x0f0f0f0f)|(((c>>2)&0x03030303)<<4),((a>>4)&0x0f0f0f0f)|(((c>>4)&0x03030303)<<4),((b>>4)&0x0f0f0f0f)|(((c>>6)&0x03030303)<<4)]; - std::array::from_fn(|i|((u[i/4]>>(i%4*8))as u8 as i16)-32) +fn h(x: &[u8], p: usize) -> f32 { + /* SAFETY: private; reached only from `dot`, whose entry gate proved F16C. */ + unsafe { half(u16::from_le_bytes([x[p], x[p + 1]])) } } -fn k4(x:&[u8])->([i16;8],[i16;8]){ - let s=std::array::from_fn(|j|if j<4{(x[j]&63)as i16}else{((x[j+4]&15)|((x[j-4]>>6)<<4))as i16}); - let m=std::array::from_fn(|j|if j<4{(x[j+4]&63)as i16}else{((x[j+4]>>4)|((x[j]>>6)<<4))as i16});(s,m) +fn six_scales(x: &[u8]) -> [i16; 16] { + let a = u32::from_le_bytes(x[..4].try_into().unwrap()); + let b = u32::from_le_bytes(x[4..8].try_into().unwrap()); + let c = u32::from_le_bytes(x[8..12].try_into().unwrap()); + let u = [ + (a & 0x0f0f0f0f) | ((c & 0x03030303) << 4), + (b & 0x0f0f0f0f) | (((c >> 2) & 0x03030303) << 4), + ((a >> 4) & 0x0f0f0f0f) | (((c >> 4) & 0x03030303) << 4), + ((b >> 4) & 0x0f0f0f0f) | (((c >> 6) & 0x03030303) << 4), + ]; + std::array::from_fn(|i| ((u[i / 4] >> (i % 4 * 8)) as u8 as i16) - 32) +} +fn k4(x: &[u8]) -> ([i16; 8], [i16; 8]) { + let s = + std::array::from_fn( + |j| if j < 4 { (x[j] & 63) as i16 } else { ((x[j + 4] & 15) | ((x[j - 4] >> 6) << 4)) as i16 }, + ); + let m = + std::array::from_fn( + |j| if j < 4 { (x[j + 4] & 63) as i16 } else { ((x[j + 4] >> 4) | ((x[j] >> 6) << 4)) as i16 }, + ); + (s, m) +} +#[target_feature(enable = "avx2")] +unsafe fn pair_scale(a: i16, b: i16) -> __m256i { + _mm256_setr_epi16(a, a, a, a, a, a, a, a, b, b, b, b, b, b, b, b) +} +#[target_feature(enable = "avx2")] +unsafe fn product(q: &[u8], high: Option<&[u8]>, y: &[i8], scales: __m256i) -> __m256i { + unsafe { + let p = _mm256_maddubs_epi16(_mm256_loadu_si256(q.as_ptr().cast()), _mm256_loadu_si256(y.as_ptr().cast())); + let p = if let Some(hi) = high { + _mm256_sub_epi16( + p, + _mm256_maddubs_epi16(_mm256_loadu_si256(hi.as_ptr().cast()), _mm256_loadu_si256(y.as_ptr().cast())), + ) + } else { + p + }; + _mm256_madd_epi16(scales, p) + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn dot(kind: i32, row: &[u8], ys: &[Q8K]) -> f32 { + unsafe { + let size = match kind { + 10 => 84, + 11 => 110, + 13 => 176, + 14 => 210, + _ => unreachable!(), + }; + assert_eq!(row.len(), ys.len() * size); + let mut acc = _mm256_setzero_ps(); + let mut mins_sum = 0.0f32; + for (x, y) in row.chunks_exact(size).zip(ys) { + let mut q = [0u8; 256]; + let mut hi = [0u8; 256]; + let (sc, d) = match kind { + 10 => { + for j in 0..256 { + q[j] = (x[16 + (j / 128) * 32 + j % 32] >> ((j % 128 / 32) * 2)) & 3; + } + let sc = std::array::from_fn(|j| (x[j] & 15) as i16); + let min: [i16; 16] = std::array::from_fn(|j| (x[j] >> 4) as i16); + let prod = _mm256_madd_epi16( + _mm256_loadu_si256(min.as_ptr().cast()), + _mm256_loadu_si256(y.bsums.as_ptr().cast()), + ); + let dm = -y.d * h(x, 82); + acc = _mm256_fmadd_ps(_mm256_set1_ps(dm), _mm256_cvtepi32_ps(prod), acc); + (sc, y.d * h(x, 80)) + } + 11 => { + for j in 0..256 { + q[j] = (x[32 + (j / 128) * 32 + j % 32] >> ((j % 128 / 32) * 2)) & 3; + hi[j] = if x[j % 32] & (1 << (j / 32)) == 0 { 4 } else { 0 }; + } + (six_scales(&x[96..108]), y.d * h(x, 108)) + } + 13 => { + let (s, m) = k4(&x[4..16]); + for j in 0..256 { + let chunk = j / 32; + q[j] = (x[48 + (chunk / 2) * 32 + j % 32] >> ((chunk % 2) * 4)) & 15; + q[j] += ((x[16 + j % 32] >> chunk) & 1) << 4; + } + let mins = _mm_setr_epi16(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7]); + let b = _mm256_loadu_si256(y.bsums.as_ptr().cast()); + let b = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(b), _mm256_extracti128_si256::<1>(b)); + let prod = _mm_madd_epi16(mins, b); + let hs = _mm_hadd_epi32(_mm_hadd_epi32(prod, _mm_setzero_si128()), _mm_setzero_si128()); + mins_sum += (-y.d * h(x, 2)) * _mm_extract_epi32::<0>(hs) as f32; + (std::array::from_fn(|j| s[j / 2]), y.d * h(x, 0)) + } + 14 => { + for j in 0..256 { + let chunk = j % 128 / 32; + q[j] = ((x[j / 128 * 64 + if chunk == 1 || chunk == 3 { 32 } else { 0 } + j % 32] + >> (if chunk >= 2 { 4 } else { 0 })) + & 15) + | (((x[128 + j / 128 * 32 + j % 32] >> (chunk * 2)) & 3) << 4); + } + let sc = std::array::from_fn(|j| x[192 + j] as i8 as i16); + (sc, y.d * h(x, 208)) + } + _ => unreachable!(), + }; + let mut sum = _mm256_setzero_si256(); + for group in 0..2 { + let at = group * 128; + let mut p = [_mm256_setzero_si256(); 4]; + for j in 0..4 { + let offset = at + j * 32; + p[j] = product( + &q[offset..], + if kind == 11 { Some(&hi[offset..]) } else { None }, + &y.qs[offset..], + pair_scale(sc[offset / 16], sc[offset / 16 + 1]), + ); + } + if kind == 14 { + sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[0], p[1])); + sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[2], p[3])); + } else { + sum = _mm256_add_epi32( + sum, + _mm256_add_epi32(_mm256_add_epi32(p[0], p[1]), _mm256_add_epi32(p[2], p[3])), + ); + } + } + if kind == 14 { + let sub = _mm256_slli_epi32::<5>(_mm256_madd_epi16( + _mm256_loadu_si256(y.bsums.as_ptr().cast()), + _mm256_loadu_si256(sc.as_ptr().cast()), + )); + sum = _mm256_sub_epi32(sum, sub); + } + acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sum), acc); + } + let total = hsum_ggml(acc); + if kind == 13 { total + mins_sum } else { total } + } } -#[target_feature(enable="avx2")] -unsafe fn pair_scale(a:i16,b:i16)->__m256i{_mm256_setr_epi16(a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b)} -#[target_feature(enable="avx2")] -unsafe fn product(q:&[u8],high:Option<&[u8]>,y:&[i8],scales:__m256i)->__m256i{unsafe{ - let p=_mm256_maddubs_epi16(_mm256_loadu_si256(q.as_ptr().cast()),_mm256_loadu_si256(y.as_ptr().cast())); - let p=if let Some(hi)=high{_mm256_sub_epi16(p,_mm256_maddubs_epi16(_mm256_loadu_si256(hi.as_ptr().cast()),_mm256_loadu_si256(y.as_ptr().cast())))}else{p};_mm256_madd_epi16(scales,p) -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn dot(kind:i32,row:&[u8],ys:&[Q8K])->f32{unsafe{ - let size=match kind{10=>84,11=>110,13=>176,14=>210,_=>unreachable!()};assert_eq!(row.len(),ys.len()*size);let mut acc=_mm256_setzero_ps();let mut mins_sum=0.0f32; - for (x,y) in row.chunks_exact(size).zip(ys){let mut q=[0u8;256];let mut hi=[0u8;256];let (sc,d)=match kind{ - 10=>{for j in 0..256{q[j]=(x[16+(j/128)*32+j%32]>>((j%128/32)*2))&3;}let sc=std::array::from_fn(|j|(x[j]&15)as i16);let min: [i16;16]=std::array::from_fn(|j|(x[j]>>4)as i16);let prod=_mm256_madd_epi16(_mm256_loadu_si256(min.as_ptr().cast()),_mm256_loadu_si256(y.bsums.as_ptr().cast()));let dm=-y.d*h(x,82);acc=_mm256_fmadd_ps(_mm256_set1_ps(dm),_mm256_cvtepi32_ps(prod),acc);(sc,y.d*h(x,80))}, - 11=>{for j in 0..256{q[j]=(x[32+(j/128)*32+j%32]>>((j%128/32)*2))&3;hi[j]=if x[j%32]&(1<<(j/32))==0{4}else{0};}(six_scales(&x[96..108]),y.d*h(x,108))}, - 13=>{let (s,m)=k4(&x[4..16]);for j in 0..256{let chunk=j/32;q[j]=(x[48+(chunk/2)*32+j%32]>>((chunk%2)*4))&15;q[j]+=((x[16+j%32]>>chunk)&1)<<4;}let mins=_mm_setr_epi16(m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7]);let b=_mm256_loadu_si256(y.bsums.as_ptr().cast());let b=_mm_hadd_epi16(_mm256_extracti128_si256::<0>(b),_mm256_extracti128_si256::<1>(b));let prod=_mm_madd_epi16(mins,b);let hs=_mm_hadd_epi32(_mm_hadd_epi32(prod,_mm_setzero_si128()),_mm_setzero_si128());mins_sum+=(-y.d*h(x,2))*_mm_extract_epi32::<0>(hs)as f32;(std::array::from_fn(|j|s[j/2]),y.d*h(x,0))}, - 14=>{for j in 0..256{let chunk=j%128/32;q[j]=((x[j/128*64+if chunk==1||chunk==3{32}else{0}+j%32]>>(if chunk>=2{4}else{0}))&15)|(((x[128+j/128*32+j%32]>>(chunk*2))&3)<<4);}let sc=std::array::from_fn(|j|x[192+j]as i8 as i16);(sc,y.d*h(x,208))},_=>unreachable!()}; - let mut sum=_mm256_setzero_si256();for group in 0..2{let at=group*128;let mut p=[_mm256_setzero_si256();4];for j in 0..4{let offset=at+j*32;p[j]=product(&q[offset..],if kind==11{Some(&hi[offset..])}else{None},&y.qs[offset..],pair_scale(sc[offset/16],sc[offset/16+1]));} - if kind==14{sum=_mm256_add_epi32(sum,_mm256_add_epi32(p[0],p[1]));sum=_mm256_add_epi32(sum,_mm256_add_epi32(p[2],p[3]));}else{sum=_mm256_add_epi32(sum,_mm256_add_epi32(_mm256_add_epi32(p[0],p[1]),_mm256_add_epi32(p[2],p[3])));} - } - if kind==14{let sub=_mm256_slli_epi32::<5>(_mm256_madd_epi16(_mm256_loadu_si256(y.bsums.as_ptr().cast()),_mm256_loadu_si256(sc.as_ptr().cast())));sum=_mm256_sub_epi32(sum,sub);} - acc=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(sum),acc); - }let total=hsum_ggml(acc);if kind==13{total+mins_sum}else{total} -}} diff --git a/crates/native-cpu-expert/src/rust_kq.rs b/crates/native-cpu-expert/src/rust_kq.rs index a0eadd9a..be73bd1b 100644 --- a/crates/native-cpu-expert/src/rust_kq.rs +++ b/crates/native-cpu-expert/src/rust_kq.rs @@ -1,82 +1,308 @@ //! Original kq_avx2.cpp KQ grouped kernels and BF16 router kernels. //! The SIMD integer/FMA/reduction tree is unchanged; no scalar dot fallback. +use super::rust_simd::{half, hsum_ggml}; +use super::rust_types::{Q8K, Q8Zero}; +use super::{Error, Result}; use std::arch::x86_64::*; -use super::rust_types::{Q8K,Q8Zero}; -use super::rust_simd::{half,hsum_ggml}; -use super::{Error,Result}; // Bounds: every row walk is chunks_exact(block)/safe slicing with a `y[ib]` safe index; raw loads read 16 bytes of a block // at offset (2|4|6|8) <= block-16, 32 bytes of Q8One/Q8Zero.qs ([i8;32]) or Q8K.qs/bsums ([i8;256]/[i16;16] = 32 bytes). // bf16_* are `pub` safe wrappers: shape-checked with checked_mul, then avx2_ok() (AVX2+FMA) before the unsafe leaf. #[repr(C)] -#[derive(Clone,Copy,Default)] -pub(super) struct Q8One{pub d:u16,pub s:u16,pub qs:[i8;32]} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn quant_one(x:&[f32],out:&mut[Q8One]){unsafe{ - assert_eq!(x.len(),out.len()*32); - for (x,y) in x.chunks_exact(32).zip(out){let mut q=Q8Zero::default();super::rust_quant::q8_zero(x,std::slice::from_mut(&mut q));let mut m=_mm256_andnot_ps(_mm256_set1_ps(-0.0),_mm256_loadu_ps(x.as_ptr()));for j in 1..4{m=_mm256_max_ps(m,_mm256_andnot_ps(_mm256_set1_ps(-0.0),_mm256_loadu_ps(x.as_ptr().add(8*j))));}let h=_mm_max_ps(_mm256_extractf128_ps::<1>(m),_mm256_castps256_ps128(m));let h=_mm_max_ps(h,_mm_movehl_ps(h,h));let d=_mm_cvtss_f32(_mm_max_ss(h,_mm_movehdup_ps(h)))/127.0;let sum=q.qs.iter().map(|&q|q as i32).sum::();y.d=q.d;y.s=super::rust_simd::to_half(d*sum as f32);y.qs=q.qs;} -}} -#[target_feature(enable="avx2")] -unsafe fn nibbles(p:*const u8)->__m256i{unsafe{let v=_mm_loadu_si128(p.cast());_mm256_and_si256(_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(v),_mm_srli_epi16::<4>(v)),_mm256_set1_epi8(15))}} -#[target_feature(enable="avx2")] -unsafe fn bits(p:*const u8)->__m256i{unsafe{ - let x=std::ptr::read_unaligned(p.cast::());let sh=_mm256_set_epi64x(0x0303030303030303,0x0202020202020202,0x0101010101010101,0); - let v=_mm256_shuffle_epi8(_mm256_set1_epi32(x as i32),sh);_mm256_cmpeq_epi8(_mm256_or_si256(v,_mm256_set1_epi64x(0x7fbfdfeff7fbfdfeu64 as i64)),_mm256_set1_epi8(-1)) -}} -#[target_feature(enable="avx2")] -unsafe fn unsigned_dot(x:__m256i,y:__m256i)->__m256{unsafe{_mm256_cvtepi32_ps(_mm256_madd_epi16(_mm256_set1_epi16(1),_mm256_maddubs_epi16(x,y)))}} -#[target_feature(enable="avx2")] -unsafe fn signed_dot(x:__m256i,y:__m256i)->__m256{unsafe{unsigned_dot(_mm256_sign_epi8(x,x),_mm256_sign_epi8(y,x))}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q8_zero_dot(row:&[u8],ys:&[&[Q8Zero]],res:&mut[f32]){unsafe{ - let mut acc=[_mm256_setzero_ps();8];assert_eq!(row.len(),ys[0].len()*34); - for (ib,x) in row.chunks_exact(34).enumerate(){let xd=half(u16::from_le_bytes([x[0],x[1]]));let qx=_mm256_loadu_si256(x.as_ptr().add(2).cast());let ax=_mm256_sign_epi8(qx,qx); - for t in 0..ys.len(){let y=ys[t][ib];let sy=_mm256_sign_epi8(_mm256_loadu_si256(y.qs.as_ptr().cast()),qx);let q=unsigned_dot(ax,sy);let d=_mm256_set1_ps(xd*half(y.d));acc[t]=_mm256_fmadd_ps(d,q,acc[t]);} - }for t in 0..ys.len(){res[t]=hsum_ggml(acc[t]);} -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q5_one_dot(row:&[u8],ys:&[&[Q8One]],res:&mut[f32]){unsafe{ - let mut acc=[_mm256_setzero_ps();8];let mut sums=[0.0f32;8];assert_eq!(row.len(),ys[0].len()*24); - for (ib,x) in row.chunks_exact(24).enumerate(){let dx=_mm256_set1_ps(half(u16::from_le_bytes([x[0],x[1]])));let xm=half(u16::from_le_bytes([x[2],x[3]]));let qx=_mm256_or_si256(nibbles(x.as_ptr().add(8)),_mm256_and_si256(bits(x.as_ptr().add(4)),_mm256_set1_epi8(16))); - for t in 0..ys.len(){let y=ys[t][ib];sums[t]+=xm*half(y.s);let dy=_mm256_set1_ps(half(y.d));let q=unsigned_dot(qx,_mm256_loadu_si256(y.qs.as_ptr().cast()));acc[t]=_mm256_fmadd_ps(q,_mm256_mul_ps(dx,dy),acc[t]);} - }for t in 0..ys.len(){res[t]=hsum_ggml(acc[t])+sums[t];} -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q4_k_dot(row:&[u8],ys:&[&[Q8K]],res:&mut[f32]){unsafe{ - let mut acc=[_mm256_setzero_ps();8];let mut acc_m=[_mm_setzero_ps();8];assert_eq!(row.len(),ys[0].len()*144); - for (ib,x) in row.chunks_exact(144).enumerate(){let xd=half(u16::from_le_bytes([x[0],x[1]]));let xdmin=half(u16::from_le_bytes([x[2],x[3]]));let mut u=[0u32;4];for j in 0..3{u[j]=u32::from_le_bytes(x[4+j*4..8+j*4].try_into().unwrap());} - u[3]=((u[2]>>4)&0x0f0f0f0f)|(((u[1]>>6)&0x03030303)<<4);let aux=u[1]&0x3f3f3f3f;u[1]=(u[2]&0x0f0f0f0f)|(((u[0]>>6)&0x03030303)<<4);u[2]=aux;u[0]&=0x3f3f3f3f; - let ms=_mm256_cvtepu8_epi16(_mm_set_epi32(u[3]as i32,u[2]as i32,u[1]as i32,u[0]as i32));let mins=_mm256_extracti128_si256::<1>(ms);let s128=_mm256_castsi256_si128(ms);let scales=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(s128),s128); - let mut ql=[_mm256_setzero_si256();4];let mut qh=ql;let mut sl=ql;let mut sh=ql; - for j in 0..4{let mut l=[0i8;32];let mut h=[0i8;32];for k in 0..32{l[k]=(4*j+k%2)as i8;h[k]=(4*j+2+k%2)as i8;}sl[j]=_mm256_shuffle_epi8(scales,_mm256_loadu_si256(l.as_ptr().cast()));sh[j]=_mm256_shuffle_epi8(scales,_mm256_loadu_si256(h.as_ptr().cast()));let q=_mm256_loadu_si256(x.as_ptr().add(16+j*32).cast());ql[j]=_mm256_and_si256(q,_mm256_set1_epi8(15));qh[j]=_mm256_and_si256(_mm256_srli_epi16::<4>(q),_mm256_set1_epi8(15));} - for t in 0..ys.len(){let y=&ys[t][ib];let d=y.d*xd;let dm=-y.d*xdmin;let sums=_mm256_loadu_si256(y.bsums.as_ptr().cast());let sums=_mm_hadd_epi16(_mm256_extracti128_si256::<0>(sums),_mm256_extracti128_si256::<1>(sums));let prod=_mm_madd_epi16(mins,sums);acc_m[t]=_mm_fmadd_ps(_mm_set1_ps(dm),_mm_cvtepi32_ps(prod),acc_m[t]);let mut sumi=_mm256_setzero_si256(); - for j in 0..4{let lo=_mm256_madd_epi16(sl[j],_mm256_maddubs_epi16(ql[j],_mm256_loadu_si256(y.qs.as_ptr().add(j*64).cast())));let hi=_mm256_madd_epi16(sh[j],_mm256_maddubs_epi16(qh[j],_mm256_loadu_si256(y.qs.as_ptr().add(j*64+32).cast())));sumi=_mm256_add_epi32(sumi,_mm256_add_epi32(lo,hi));} - acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d),_mm256_cvtepi32_ps(sumi),acc[t]); - } - }for t in 0..ys.len(){let m=_mm_add_ps(acc_m[t],_mm_movehl_ps(acc_m[t],acc_m[t]));let m=_mm_add_ss(m,_mm_movehdup_ps(m));res[t]=hsum_ggml(acc[t])+_mm_cvtss_f32(m);} -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn small_dot(kind:i32,row:&[u8],zero:Option<&[Q8Zero]>,one:Option<&[Q8One]>)->f32{unsafe{ - let block=match kind{2=>18,3=>20,6=>22,7=>24,8=>34,_=>unreachable!()};let mut acc=_mm256_setzero_ps();let mut sums=0.0; - for (ib,x) in row.chunks_exact(block).enumerate(){let xd=half(u16::from_le_bytes([x[0],x[1]]));let (yd,qy)=if let Some(y)=zero{(half(y[ib].d),_mm256_loadu_si256(y[ib].qs.as_ptr().cast()))}else{let y=one.unwrap();sums+=half(u16::from_le_bytes([x[2],x[3]]))*half(y[ib].s);(half(y[ib].d),_mm256_loadu_si256(y[ib].qs.as_ptr().cast()))};let qx=match kind{ - 2=>_mm256_sub_epi8(nibbles(x.as_ptr().add(2)),_mm256_set1_epi8(8)), - 3=>nibbles(x.as_ptr().add(4)), - 6=>_mm256_or_si256(nibbles(x.as_ptr().add(6)),_mm256_andnot_si256(bits(x.as_ptr().add(2)),_mm256_set1_epi8(-16))), - 7=>_mm256_or_si256(nibbles(x.as_ptr().add(8)),_mm256_and_si256(bits(x.as_ptr().add(4)),_mm256_set1_epi8(16))), - 8=>_mm256_loadu_si256(x.as_ptr().add(2).cast()),_=>unreachable!()}; - let q=if matches!(kind,3|7){super::rust_ggml_native::unsigned_pairs(qx,qy).unwrap_or_else(||unsigned_dot(qx,qy))}else{super::rust_ggml_native::signed_pairs(qx,qy).unwrap_or_else(||signed_dot(qx,qy))};acc=if kind==7{_mm256_fmadd_ps(q,_mm256_set1_ps(xd*yd),acc)}else{_mm256_fmadd_ps(_mm256_set1_ps(xd*yd),q,acc)}; - }if matches!(kind,3|7){hsum_ggml(acc)+sums}else{hsum_ggml(acc)} -}} -pub fn bf16_rows(weights:&[u16],rows:usize,cols:usize,input:&[f32],out:&mut[f32])->Result<()>{ - if rows.checked_mul(cols)!=Some(weights.len())||input.len()!=cols||out.len()!=rows{return Err(Error::Shape);}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}/* SAFETY: avx2_ok() proved AVX2+FMA; shapes checked above: weights.len()==rows*cols, input.len()==cols, out.len()==rows, so every c+8<=cols load is in range. */unsafe{bf16_single(weights,rows,cols,input,out);}Ok(()) +#[derive(Clone, Copy, Default)] +pub(super) struct Q8One { + pub d: u16, + pub s: u16, + pub qs: [i8; 32], } -#[target_feature(enable="avx2,fma")] -unsafe fn bf16_single(w:&[u16],rows:usize,cols:usize,x:&[f32],out:&mut[f32]){unsafe{ - for r in 0..rows{let wr=&w[r*cols..(r+1)*cols];let mut acc=_mm256_setzero_ps();let mut c=0;while c+8<=cols{let h=_mm256_cvtepu16_epi32(_mm_loadu_si128(wr.as_ptr().add(c).cast()));let f=_mm256_castsi256_ps(_mm256_slli_epi32::<16>(h));acc=_mm256_fmadd_ps(f,_mm256_loadu_ps(x.as_ptr().add(c)),acc);c+=8;}let mut s=hsum_ggml(acc);while cResult<()>{ - if nt==0||nt>8||cols%8!=0||rows.checked_mul(cols)!=Some(weights.len())||cols.checked_mul(nt)!=Some(input.len())||rows.checked_mul(nt)!=Some(out.len()){return Err(Error::Shape);}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}/* SAFETY: avx2_ok() proved AVX2+FMA; cols%8==0, nt<=8 and the checked products pin w=rows*cols, x=nt*cols, out=nt*rows. */unsafe{bf16_multi(weights,rows,cols,input,nt,out);}Ok(()) +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn quant_one(x: &[f32], out: &mut [Q8One]) { + unsafe { + assert_eq!(x.len(), out.len() * 32); + for (x, y) in x.chunks_exact(32).zip(out) { + let mut q = Q8Zero::default(); + super::rust_quant::q8_zero(x, std::slice::from_mut(&mut q)); + let mut m = _mm256_andnot_ps(_mm256_set1_ps(-0.0), _mm256_loadu_ps(x.as_ptr())); + for j in 1..4 { + m = _mm256_max_ps(m, _mm256_andnot_ps(_mm256_set1_ps(-0.0), _mm256_loadu_ps(x.as_ptr().add(8 * j)))); + } + let h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m)); + let h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + let d = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h))) / 127.0; + let sum = q.qs.iter().map(|&q| q as i32).sum::(); + y.d = q.d; + y.s = super::rust_simd::to_half(d * sum as f32); + y.qs = q.qs; + } + } +} +#[target_feature(enable = "avx2")] +unsafe fn nibbles(p: *const u8) -> __m256i { + unsafe { + let v = _mm_loadu_si128(p.cast()); + _mm256_and_si256( + _mm256_inserti128_si256::<1>(_mm256_castsi128_si256(v), _mm_srli_epi16::<4>(v)), + _mm256_set1_epi8(15), + ) + } +} +#[target_feature(enable = "avx2")] +unsafe fn bits(p: *const u8) -> __m256i { + unsafe { + let x = std::ptr::read_unaligned(p.cast::()); + let sh = _mm256_set_epi64x(0x0303030303030303, 0x0202020202020202, 0x0101010101010101, 0); + let v = _mm256_shuffle_epi8(_mm256_set1_epi32(x as i32), sh); + _mm256_cmpeq_epi8(_mm256_or_si256(v, _mm256_set1_epi64x(0x7fbfdfeff7fbfdfeu64 as i64)), _mm256_set1_epi8(-1)) + } +} +#[target_feature(enable = "avx2")] +unsafe fn unsigned_dot(x: __m256i, y: __m256i) -> __m256 { + unsafe { _mm256_cvtepi32_ps(_mm256_madd_epi16(_mm256_set1_epi16(1), _mm256_maddubs_epi16(x, y))) } +} +#[target_feature(enable = "avx2")] +unsafe fn signed_dot(x: __m256i, y: __m256i) -> __m256 { + unsafe { unsigned_dot(_mm256_sign_epi8(x, x), _mm256_sign_epi8(y, x)) } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q8_zero_dot(row: &[u8], ys: &[&[Q8Zero]], res: &mut [f32]) { + unsafe { + let mut acc = [_mm256_setzero_ps(); 8]; + assert_eq!(row.len(), ys[0].len() * 34); + for (ib, x) in row.chunks_exact(34).enumerate() { + let xd = half(u16::from_le_bytes([x[0], x[1]])); + let qx = _mm256_loadu_si256(x.as_ptr().add(2).cast()); + let ax = _mm256_sign_epi8(qx, qx); + for t in 0..ys.len() { + let y = ys[t][ib]; + let sy = _mm256_sign_epi8(_mm256_loadu_si256(y.qs.as_ptr().cast()), qx); + let q = unsigned_dot(ax, sy); + let d = _mm256_set1_ps(xd * half(y.d)); + acc[t] = _mm256_fmadd_ps(d, q, acc[t]); + } + } + for t in 0..ys.len() { + res[t] = hsum_ggml(acc[t]); + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q5_one_dot(row: &[u8], ys: &[&[Q8One]], res: &mut [f32]) { + unsafe { + let mut acc = [_mm256_setzero_ps(); 8]; + let mut sums = [0.0f32; 8]; + assert_eq!(row.len(), ys[0].len() * 24); + for (ib, x) in row.chunks_exact(24).enumerate() { + let dx = _mm256_set1_ps(half(u16::from_le_bytes([x[0], x[1]]))); + let xm = half(u16::from_le_bytes([x[2], x[3]])); + let qx = _mm256_or_si256( + nibbles(x.as_ptr().add(8)), + _mm256_and_si256(bits(x.as_ptr().add(4)), _mm256_set1_epi8(16)), + ); + for t in 0..ys.len() { + let y = ys[t][ib]; + sums[t] += xm * half(y.s); + let dy = _mm256_set1_ps(half(y.d)); + let q = unsigned_dot(qx, _mm256_loadu_si256(y.qs.as_ptr().cast())); + acc[t] = _mm256_fmadd_ps(q, _mm256_mul_ps(dx, dy), acc[t]); + } + } + for t in 0..ys.len() { + res[t] = hsum_ggml(acc[t]) + sums[t]; + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q4_k_dot(row: &[u8], ys: &[&[Q8K]], res: &mut [f32]) { + unsafe { + let mut acc = [_mm256_setzero_ps(); 8]; + let mut acc_m = [_mm_setzero_ps(); 8]; + assert_eq!(row.len(), ys[0].len() * 144); + for (ib, x) in row.chunks_exact(144).enumerate() { + let xd = half(u16::from_le_bytes([x[0], x[1]])); + let xdmin = half(u16::from_le_bytes([x[2], x[3]])); + let mut u = [0u32; 4]; + for j in 0..3 { + u[j] = u32::from_le_bytes(x[4 + j * 4..8 + j * 4].try_into().unwrap()); + } + u[3] = ((u[2] >> 4) & 0x0f0f0f0f) | (((u[1] >> 6) & 0x03030303) << 4); + let aux = u[1] & 0x3f3f3f3f; + u[1] = (u[2] & 0x0f0f0f0f) | (((u[0] >> 6) & 0x03030303) << 4); + u[2] = aux; + u[0] &= 0x3f3f3f3f; + let ms = _mm256_cvtepu8_epi16(_mm_set_epi32(u[3] as i32, u[2] as i32, u[1] as i32, u[0] as i32)); + let mins = _mm256_extracti128_si256::<1>(ms); + let s128 = _mm256_castsi256_si128(ms); + let scales = _mm256_inserti128_si256::<1>(_mm256_castsi128_si256(s128), s128); + let mut ql = [_mm256_setzero_si256(); 4]; + let mut qh = ql; + let mut sl = ql; + let mut sh = ql; + for j in 0..4 { + let mut l = [0i8; 32]; + let mut h = [0i8; 32]; + for k in 0..32 { + l[k] = (4 * j + k % 2) as i8; + h[k] = (4 * j + 2 + k % 2) as i8; + } + sl[j] = _mm256_shuffle_epi8(scales, _mm256_loadu_si256(l.as_ptr().cast())); + sh[j] = _mm256_shuffle_epi8(scales, _mm256_loadu_si256(h.as_ptr().cast())); + let q = _mm256_loadu_si256(x.as_ptr().add(16 + j * 32).cast()); + ql[j] = _mm256_and_si256(q, _mm256_set1_epi8(15)); + qh[j] = _mm256_and_si256(_mm256_srli_epi16::<4>(q), _mm256_set1_epi8(15)); + } + for t in 0..ys.len() { + let y = &ys[t][ib]; + let d = y.d * xd; + let dm = -y.d * xdmin; + let sums = _mm256_loadu_si256(y.bsums.as_ptr().cast()); + let sums = _mm_hadd_epi16(_mm256_extracti128_si256::<0>(sums), _mm256_extracti128_si256::<1>(sums)); + let prod = _mm_madd_epi16(mins, sums); + acc_m[t] = _mm_fmadd_ps(_mm_set1_ps(dm), _mm_cvtepi32_ps(prod), acc_m[t]); + let mut sumi = _mm256_setzero_si256(); + for j in 0..4 { + let lo = _mm256_madd_epi16( + sl[j], + _mm256_maddubs_epi16(ql[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64).cast())), + ); + let hi = _mm256_madd_epi16( + sh[j], + _mm256_maddubs_epi16(qh[j], _mm256_loadu_si256(y.qs.as_ptr().add(j * 64 + 32).cast())), + ); + sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(lo, hi)); + } + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[t]); + } + } + for t in 0..ys.len() { + let m = _mm_add_ps(acc_m[t], _mm_movehl_ps(acc_m[t], acc_m[t])); + let m = _mm_add_ss(m, _mm_movehdup_ps(m)); + res[t] = hsum_ggml(acc[t]) + _mm_cvtss_f32(m); + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn small_dot(kind: i32, row: &[u8], zero: Option<&[Q8Zero]>, one: Option<&[Q8One]>) -> f32 { + unsafe { + let block = match kind { + 2 => 18, + 3 => 20, + 6 => 22, + 7 => 24, + 8 => 34, + _ => unreachable!(), + }; + let mut acc = _mm256_setzero_ps(); + let mut sums = 0.0; + for (ib, x) in row.chunks_exact(block).enumerate() { + let xd = half(u16::from_le_bytes([x[0], x[1]])); + let (yd, qy) = if let Some(y) = zero { + (half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast())) + } else { + let y = one.unwrap(); + sums += half(u16::from_le_bytes([x[2], x[3]])) * half(y[ib].s); + (half(y[ib].d), _mm256_loadu_si256(y[ib].qs.as_ptr().cast())) + }; + let qx = match kind { + 2 => _mm256_sub_epi8(nibbles(x.as_ptr().add(2)), _mm256_set1_epi8(8)), + 3 => nibbles(x.as_ptr().add(4)), + 6 => _mm256_or_si256( + nibbles(x.as_ptr().add(6)), + _mm256_andnot_si256(bits(x.as_ptr().add(2)), _mm256_set1_epi8(-16)), + ), + 7 => _mm256_or_si256( + nibbles(x.as_ptr().add(8)), + _mm256_and_si256(bits(x.as_ptr().add(4)), _mm256_set1_epi8(16)), + ), + 8 => _mm256_loadu_si256(x.as_ptr().add(2).cast()), + _ => unreachable!(), + }; + let q = if matches!(kind, 3 | 7) { + super::rust_ggml_native::unsigned_pairs(qx, qy).unwrap_or_else(|| unsigned_dot(qx, qy)) + } else { + super::rust_ggml_native::signed_pairs(qx, qy).unwrap_or_else(|| signed_dot(qx, qy)) + }; + acc = if kind == 7 { + _mm256_fmadd_ps(q, _mm256_set1_ps(xd * yd), acc) + } else { + _mm256_fmadd_ps(_mm256_set1_ps(xd * yd), q, acc) + }; + } + if matches!(kind, 3 | 7) { hsum_ggml(acc) + sums } else { hsum_ggml(acc) } + } +} +pub fn bf16_rows(weights: &[u16], rows: usize, cols: usize, input: &[f32], out: &mut [f32]) -> Result<()> { + if rows.checked_mul(cols) != Some(weights.len()) || input.len() != cols || out.len() != rows { + return Err(Error::Shape); + } + if !super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } /* SAFETY: avx2_ok() proved AVX2+FMA; shapes checked above: weights.len()==rows*cols, input.len()==cols, out.len()==rows, so every c+8<=cols load is in range. */ + unsafe { + bf16_single(weights, rows, cols, input, out); + } + Ok(()) +} +#[target_feature(enable = "avx2,fma")] +unsafe fn bf16_single(w: &[u16], rows: usize, cols: usize, x: &[f32], out: &mut [f32]) { + unsafe { + for r in 0..rows { + let wr = &w[r * cols..(r + 1) * cols]; + let mut acc = _mm256_setzero_ps(); + let mut c = 0; + while c + 8 <= cols { + let h = _mm256_cvtepu16_epi32(_mm_loadu_si128(wr.as_ptr().add(c).cast())); + let f = _mm256_castsi256_ps(_mm256_slli_epi32::<16>(h)); + acc = _mm256_fmadd_ps(f, _mm256_loadu_ps(x.as_ptr().add(c)), acc); + c += 8; + } + let mut s = hsum_ggml(acc); + while c < cols { + s += f32::from_bits((wr[c] as u32) << 16) * x[c]; + c += 1; + } + out[r] = s; + } + } +} +pub fn bf16_rows_multi( + weights: &[u16], + rows: usize, + cols: usize, + input: &[f32], + nt: usize, + out: &mut [f32], +) -> Result<()> { + if nt == 0 + || nt > 8 + || cols % 8 != 0 + || rows.checked_mul(cols) != Some(weights.len()) + || cols.checked_mul(nt) != Some(input.len()) + || rows.checked_mul(nt) != Some(out.len()) + { + return Err(Error::Shape); + } + if !super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } /* SAFETY: avx2_ok() proved AVX2+FMA; cols%8==0, nt<=8 and the checked products pin w=rows*cols, x=nt*cols, out=nt*rows. */ + unsafe { + bf16_multi(weights, rows, cols, input, nt, out); + } + Ok(()) +} +#[target_feature(enable = "avx2,fma")] +unsafe fn bf16_multi(w: &[u16], rows: usize, cols: usize, x: &[f32], nt: usize, out: &mut [f32]) { + unsafe { + for r in 0..rows { + let mut acc = [_mm256_setzero_ps(); 8]; + for c in (0..cols).step_by(8) { + let h = _mm256_cvtepu16_epi32(_mm_loadu_si128(w.as_ptr().add(r * cols + c).cast())); + let f = _mm256_castsi256_ps(_mm256_slli_epi32::<16>(h)); + for t in 0..nt { + acc[t] = _mm256_fmadd_ps(f, _mm256_loadu_ps(x.as_ptr().add(t * cols + c)), acc[t]); + } + } + for t in 0..nt { + out[t * rows + r] = hsum_ggml(acc[t]); + } + } + } } -#[target_feature(enable="avx2,fma")] -unsafe fn bf16_multi(w:&[u16],rows:usize,cols:usize,x:&[f32],nt:usize,out:&mut[f32]){unsafe{ - for r in 0..rows{let mut acc=[_mm256_setzero_ps();8];for c in (0..cols).step_by(8){let h=_mm256_cvtepu16_epi32(_mm_loadu_si128(w.as_ptr().add(r*cols+c).cast()));let f=_mm256_castsi256_ps(_mm256_slli_epi32::<16>(h));for t in 0..nt{acc[t]=_mm256_fmadd_ps(f,_mm256_loadu_ps(x.as_ptr().add(t*cols+c)),acc[t]);}}for t in 0..nt{out[t*rows+r]=hsum_ggml(acc[t]);}} -}} diff --git a/crates/native-cpu-expert/src/rust_legacy.rs b/crates/native-cpu-expert/src/rust_legacy.rs index d634dc4f..fa517991 100644 --- a/crates/native-cpu-expert/src/rust_legacy.rs +++ b/crates/native-cpu-expert/src/rust_legacy.rs @@ -1,175 +1,76 @@ //! Original expert.cpp planar Q2, oracle, row-range and scalar benchmark entrypoints. //! These are numerical owners only; they carry no model/source authority. -use std::{arch::x86_64::*, sync::{OnceLock, atomic::{AtomicBool,Ordering}}}; -use super::{Error,Result,H,FF,MAX_ROWS}; +use super::rust_simd::{hsum_original, silu}; use super::rust_types::ActQ; -use super::rust_simd::{silu,hsum_original}; -pub const BLOB:usize=1_382_400; -const D_CODES:usize=2*FF*640; -const GU_SCALES:usize=D_CODES+H*160; -const D_SCALES:usize=GU_SCALES+2*FF*40*2; -static ORACLE:AtomicBool=AtomicBool::new(false); -pub fn set_oracle_q8_zero(enabled:bool){ORACLE.store(enabled,Ordering::Relaxed);} -pub fn oracle_q8_zero_enabled()->bool{ORACLE.load(Ordering::Relaxed)} -// Original h2f integer conversion, including half subnormals and signed zero. -pub(super) fn half(bytes:&[u8])->f32{ - let h=u16::from_le_bytes([bytes[0],bytes[1]]);let sign=(h as u32>>15)<<31; - let mut e=(h as u32>>10)&31;let mut m=h as u32&1023; - let bits=if e==0{if m==0{sign}else{e=113;while m&1024==0{m<<=1;e-=1;}sign|(e<<23)|((m&1023)<<13)}}else if e==31{sign|0x7f800000|(m<<13)}else{sign|((e+112)<<23)|(m<<13)}; - f32::from_bits(bits) -} -pub(super) fn legacy_supported()->bool{/* SAFETY: CPUID is architectural on x86_64; XGETBV is only executed after the OSXSAVE bit (ecx bit 27) was verified. */unsafe{ - if __cpuid(0).eax<7||__cpuid(1).ecx&(1<<27)==0{return false;} - let c=__cpuid_count(7,0);_xgetbv(0)&0xe6==0xe6&&[16,17,30,31].iter().all(|b|c.ebx&(1<Self{Self(ActQ::default())}} -impl PlanarActivation{ - pub fn quantize(&mut self,x:&[f32])->Result<()>{ - if x.is_empty()||x.len()>H||x.len()%32!=0{return Err(Error::Shape);} - if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);} - if oracle_q8_zero_enabled(){ - let mut q=[super::rust_types::Q8Zero::default();80];/* SAFETY: avx2_ok() above (AVX2+FMA+F16C); x.len() <= H and % 32 == 0 so x.len()/32 <= 80 = q.len(). */unsafe{super::rust_quant::q8_zero(x,&mut q[..x.len()/32]);} - self.0.nchunks=(x.len()/32)as i32; - for (k,q) in q[..x.len()/32].iter().enumerate(){self.0.q[k*32..k*32+32].copy_from_slice(&q.qs);let d=half(&q.d.to_le_bytes());let s=q.qs.iter().map(|&v|v as i32).sum::();self.0.scale[k]=d;self.0.sum[k]=s;self.0.hx[k]=d*s as f32;} - }else{ - if !legacy_supported(){return Err(Error::Unsupported);} - /* SAFETY: legacy_supported() above proved AVX-512 F/DQ/BW/VL (+VNNI/VBMI, XCR0); x.len() <= H, % 32 == 0 (asserted by the leaf). */unsafe{super::rust_quant::q8_one_avx512(x,&mut self.0);} - }Ok(()) - } - pub fn quantize_native(&mut self,x:&[f32])->Result<()>{if x.is_empty()||x.len()>H||x.len()%32!=0{return Err(Error::Shape);}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}/* SAFETY: avx2_ok() above; the avx512 arm additionally checks dq_ok() before its leaf. */unsafe{if super::rust_simd::dispatch().avx512{if !super::rust_simd::dq_ok(){return Err(Error::Unsupported);}super::rust_quant::q8_one_avx512(x,&mut self.0);}else{super::rust_quant::q8_one_avx2(x,&mut self.0);}}Ok(())} - -} -#[repr(C,align(64))] -pub struct PlanarScratch{a2:[PlanarActivation;MAX_ROWS],ff:[[f32;FF];MAX_ROWS],single:SingleScratch} -impl Default for PlanarScratch{fn default()->Self{Self{a2:std::array::from_fn(|_|PlanarActivation::default()),ff:[[0.0;FF];MAX_ROWS],single:SingleScratch::default()}}} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] -unsafe fn unpack32(p:*const u8)->__m256i{unsafe{ - let q=_mm256_cvtepu16_epi64(_mm_loadl_epi64(p.cast())); - _mm256_and_si256(_mm256_multishift_epi64_epi8(_mm256_set1_epi64x(0x0e0c0a0806040200),q),_mm256_set1_epi8(3)) -}} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] -unsafe fn dot32(p:*const u8,q:*const i8)->__m256i{unsafe{ - _mm256_dpbusd_epi32(_mm256_setzero_si256(),unpack32(p),_mm256_loadu_si256(q.cast())) -}} -// The correction `corr += d*(hx0+hx1)` is ONE fused multiply-add, as in the pinned C++ (expert.cpp row_dot line 242 and row_dot_multi line 294, -// GCC contracts it under -mfma); a separate mul+add rounds twice (STRA-329; the same rule as rust_q2.rs, STRA-324). -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] -unsafe fn row256(codes:&[u8],scales:&[u8],a:&[&ActQ],out:&mut[f32]){unsafe{ - let mut acc=[_mm256_setzero_ps();MAX_ROWS];let mut corr=[0.0f32;MAX_ROWS]; - assert!(scales.len()/2<=40&&codes.len()>=scales.len()/2*16&&a.len()<=MAX_ROWS); - for b in 0..scales.len()/2{let d=half(&scales[b*2..]);let lo=unpack32(codes.as_ptr().add(b*16));let hi=unpack32(codes.as_ptr().add(b*16+8)); - for t in 0..a.len(){let x=a[t];let sl=_mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(),lo,_mm256_loadu_si256(x.q.as_ptr().add(b*64).cast())));let sh=_mm256_cvtepi32_ps(_mm256_dpbusd_epi32(_mm256_setzero_si256(),hi,_mm256_loadu_si256(x.q.as_ptr().add(b*64+32).cast()))); - acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2]),sl,acc[t]);acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*x.scale[b*2+1]),sh,acc[t]);corr[t]=d.mul_add(x.hx[b*2]+x.hx[b*2+1],corr[t]); - } - }for t in 0..a.len(){out[t]=hsum_original(acc[t])-corr[t];} -}} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] -unsafe fn row512(codes:&[u8],scales:&[u8],a:&[&ActQ],out:&mut[f32]){unsafe{ - let mut acc=[_mm512_setzero_ps();MAX_ROWS];let mut corr=[_mm512_setzero_ps();MAX_ROWS];let nb=scales.len()/2;assert!(nb<=40&&codes.len()>=nb*16&&a.len()<=MAX_ROWS); - let dup=_mm512_setr_epi32(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7);let base=_mm512_setr_epi32(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1); - for b0 in (0..nb).step_by(8){let n=(nb-b0).min(8);let m8=if n==8{255}else{(1u16<f32{unsafe{ - assert!(scales.len()/2<=40&&codes.len()>=scales.len()/2*16);let mut result=0.0;for b in 0..scales.len()/2{let mut block=0.0;for h in 0..2{let chunk=b*2+h;let x=dot32(codes.as_ptr().add(b*16+h*8),a.q.as_ptr().add(chunk*32));let v=_mm_add_epi32(_mm256_castsi256_si128(x),_mm256_extracti128_si256::<1>(x));let v=_mm_hadd_epi32(v,v);let dot=_mm_cvtsi128_si32(_mm_hadd_epi32(v,v))-a.sum[chunk];block+=a.scale[chunk]*dot as f32;}result+=half(&scales[b*2..])*block;}result -}} -fn row(codes:&[u8],scales:&[u8],a:&[&ActQ],out:&mut[f32],oracle:bool){/* SAFETY: private; every caller (gate_up_rows, down_rows, expert_quantized, whole_single, gate_each, down_each) first passed legacy_supported() -- directly or via ExpertPool::run, run_split and run_split_multi -- and hands 640 B/80 B (gate/up) or 160 B/20 B (down) code/scale slices, i.e. nb <= 40 (asserted in the leaves). */unsafe{ - if oracle{for t in 0..a.len(){out[t]=row_oracle(codes,scales,a[t]);}} - else{static ZMM:OnceLock=OnceLock::new();if *ZMM.get_or_init(||std::env::var_os("STRATA_CPU_YMM").is_none()){row512(codes,scales,a,out);}else{row256(codes,scales,a,out);}} -}} -fn admit(blob:&[u8],a:&[&PlanarActivation],out:&[&mut[f32]],width:usize,chunks:i32,r0:usize,r1:usize)->Result<()>{ - if blob.len()!=BLOB||a.is_empty()||a.len()>MAX_ROWS||a.len()!=out.len()||r0>r1||r1>width||out.iter().any(|v|v.len()!=width)||a.iter().any(|x|x.0.nchunks!=chunks){return Err(Error::Shape);} - if !legacy_supported(){return Err(Error::Unsupported);}Ok(()) -} -pub fn gate_up_rows(blob:&[u8],a:&[&PlanarActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()>{ - admit(blob,a,out,FF,80,r0,r1)?;let empty=ActQ::default();let mut aa=[∅MAX_ROWS];for t in 0..a.len(){aa[t]=&a[t].0;} - let mut g=[0.0;MAX_ROWS];let mut u=[0.0;MAX_ROWS]; - // Original row-range APIs always use row_dot, even in oracle activation mode. - for r in r0..r1{row(&blob[(2*r)*640..(2*r+1)*640],&blob[GU_SCALES+2*r*80..GU_SCALES+(2*r+1)*80],&aa[..a.len()],&mut g[..a.len()],false);row(&blob[(2*r+1)*640..(2*r+2)*640],&blob[GU_SCALES+(2*r+1)*80..GU_SCALES+(2*r+2)*80],&aa[..a.len()],&mut u[..a.len()],false);for t in 0..a.len(){out[t][r]=silu(g[t],u[t]);}}Ok(()) -} -pub fn down_rows(blob:&[u8],a:&[&PlanarActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()>{ - admit(blob,a,out,H,20,r0,r1)?;let empty=ActQ::default();let mut aa=[∅MAX_ROWS];for t in 0..a.len(){aa[t]=&a[t].0;}let mut v=[0.0;MAX_ROWS];for r in r0..r1{row(&blob[D_CODES+r*160..D_CODES+(r+1)*160],&blob[D_SCALES+r*20..D_SCALES+(r+1)*20],&aa[..a.len()],&mut v[..a.len()],false);for t in 0..a.len(){out[t][r]=v[t];}}Ok(()) -} -pub fn expert_quantized(blob:&[u8],a:&[&PlanarActivation],out:&mut[&mut[f32]],scratch:&mut PlanarScratch)->Result<()>{ - // The Original multi entry falls back to complete per-token experts for - // oracle mode or a call wider than its eight-row multi scratch. - if blob.len()!=BLOB||a.is_empty()||a.len()>i32::MAX as usize||a.len()!=out.len()||out.iter().any(|v|v.len()!=H)||a.iter().any(|x|x.0.nchunks!=80){return Err(Error::Shape);} - if !legacy_supported(){return Err(Error::Unsupported);} - let oracle=oracle_q8_zero_enabled(); - if oracle||a.len()>MAX_ROWS{for t in 0..a.len(){whole_single(blob,a[t],out[t],&mut scratch.single);}return Ok(());} - let empty=ActQ::default();let mut aa=[∅MAX_ROWS];for t in 0..a.len(){aa[t]=&a[t].0;}let mut g=[0.0;MAX_ROWS];let mut u=[0.0;MAX_ROWS]; - for r in 0..FF{row(&blob[(2*r)*640..(2*r+1)*640],&blob[GU_SCALES+2*r*80..GU_SCALES+(2*r+1)*80],&aa[..a.len()],&mut g[..a.len()],oracle);row(&blob[(2*r+1)*640..(2*r+2)*640],&blob[GU_SCALES+(2*r+1)*80..GU_SCALES+(2*r+2)*80],&aa[..a.len()],&mut u[..a.len()],oracle);for t in 0..a.len(){scratch.ff[t][r]=silu(g[t],u[t]);}} - for t in 0..a.len(){scratch.a2[t].quantize(&scratch.ff[t])?;} - for t in 0..a.len(){aa[t]=&scratch.a2[t].0;} - for r in 0..H{row(&blob[D_CODES+r*160..D_CODES+(r+1)*160],&blob[D_SCALES+r*20..D_SCALES+(r+1)*20],&aa[..a.len()],&mut g[..a.len()],oracle);for t in 0..a.len(){out[t][r]=g[t];}}Ok(()) -} -pub fn expert(blob:&[u8],x:&[f32],out:&mut[f32],scratch:&mut PlanarScratch)->Result<()>{if x.len()!=H{return Err(Error::Shape);}let mut a=PlanarActivation::default();a.quantize(x)?;expert_quantized(blob,&[&a],&mut[out],scratch)} -/// Original scalar benchmark, deliberately distinct from VNNI evaluation order. -pub fn expert_scalar(blob:&[u8],x:&[f32],out:&mut[f32],quantized:bool)->Result<()>{ - if blob.len()!=BLOB||x.len()!=H||out.len()!=H{return Err(Error::Shape);} - let mut xq=[0.0;H];let mut a=PlanarActivation::default();let input=if quantized{a.quantize(x)?;for (i,v) in xq.iter_mut().enumerate(){*v=a.0.scale[i/32]*a.0.q[i]as f32;}&xq[..]}else{x};let mut ff=[0.0;FF]; - for r in 0..FF{let mut sg=0.0;let mut su=0.0;for b in 0..40{let dg=half(&blob[GU_SCALES+2*r*80+2*b..]);let du=half(&blob[GU_SCALES+(2*r+1)*80+2*b..]);for j in 0..64{let o=b*64+j;sg+=(((blob[2*r*640+b*16+j/4]>>(2*(j%4)))&3)as i32-1)as f32*dg*input[o];su+=(((blob[(2*r+1)*640+b*16+j/4]>>(2*(j%4)))&3)as i32-1)as f32*du*input[o];}}ff[r]=silu(sg,su);} - if quantized{a.quantize(&ff)?;for (i,v) in ff.iter_mut().enumerate(){*v=a.0.scale[i/32]*a.0.q[i]as f32;}} - for (r,value) in out.iter_mut().enumerate(){let mut sum=0.0;for b in 0..10{let d=half(&blob[D_SCALES+r*20+2*b..]);for j in 0..64{sum+=(((blob[D_CODES+r*160+b*16+j/4]>>(2*(j%4)))&3)as i32-1)as f32*d*ff[b*64+j];}}*value=sum;}Ok(()) +#[repr(C, align(64))] +pub struct PlanarScratch { + a2: [PlanarActivation; MAX_ROWS], + ff: [[f32; FF]; MAX_ROWS], + single: SingleScratch, } -// Disjoint row cells are written by the pool callback; it never creates an -// overlapping mutable whole-row slice while another worker owns another range. -pub(super) fn gate_each(blob:&[u8],a:&[&PlanarActivation],r0:usize,r1:usize,mut write:impl FnMut(usize,usize,f32)){ - let empty=ActQ::default();let mut aa=[∅MAX_ROWS];for t in 0..a.len(){aa[t]=&a[t].0;}let mut g=[0.0;MAX_ROWS];let mut u=g; - for r in r0..r1{row(&blob[(2*r)*640..(2*r+1)*640],&blob[GU_SCALES+2*r*80..GU_SCALES+(2*r+1)*80],&aa[..a.len()],&mut g[..a.len()],false);row(&blob[(2*r+1)*640..(2*r+2)*640],&blob[GU_SCALES+(2*r+1)*80..GU_SCALES+(2*r+2)*80],&aa[..a.len()],&mut u[..a.len()],false);for t in 0..a.len(){write(t,r,silu(g[t],u[t]));}} +#[repr(C, align(64))] +pub(super) struct SingleScratch { + _a1: ActQ, + a2: PlanarActivation, + ff: [f32; FF], } -pub(super) fn down_each(blob:&[u8],a:&[&PlanarActivation],r0:usize,r1:usize,mut write:impl FnMut(usize,usize,f32)){ - let empty=ActQ::default();let mut aa=[∅MAX_ROWS];for t in 0..a.len(){aa[t]=&a[t].0;}let mut v=[0.0;MAX_ROWS];for r in r0..r1{row(&blob[D_CODES+r*160..D_CODES+(r+1)*160],&blob[D_SCALES+r*20..D_SCALES+(r+1)*20],&aa[..a.len()],&mut v[..a.len()],false);for t in 0..a.len(){write(t,r,v[t]);}} -} - -#[repr(C,align(64))] -pub(super) struct SingleScratch{_a1:ActQ,a2:PlanarActivation,ff:[f32;FF]} -impl Default for SingleScratch{fn default()->Self{Self{_a1:ActQ::default(),a2:PlanarActivation::default(),ff:[0.0;FF]}}} -pub(super) fn whole_single(blob:&[u8],a:&PlanarActivation,out:&mut[f32],s:&mut SingleScratch){let oracle=oracle_q8_zero_enabled();let mut g=[0.0];let mut u=[0.0];for r in 0..FF{row(&blob[(2*r)*640..(2*r+1)*640],&blob[GU_SCALES+2*r*80..GU_SCALES+(2*r+1)*80],&[&a.0],&mut g,oracle);row(&blob[(2*r+1)*640..(2*r+2)*640],&blob[GU_SCALES+(2*r+1)*80..GU_SCALES+(2*r+2)*80],&[&a.0],&mut u,oracle);s.ff[r]=silu(g[0],u[0]);}s.a2.quantize(&s.ff).expect("admitted legacy whole geometry");for (r,o) in out.iter_mut().enumerate(){row(&blob[D_CODES+r*160..D_CODES+(r+1)*160],&blob[D_SCALES+r*20..D_SCALES+(r+1)*20],&[&s.a2.0],&mut g,oracle);*o=g[0];}} #[cfg(test)] -mod tests { - use super::*; - use std::panic::{catch_unwind,AssertUnwindSafe}; - // The AVX-512 row leaves load a.q / a.scale / a.hx for every 8-byte-code block pair of the row: more than 40 blocks would read - // past the ActQ, so the leaves refuse it before the first load (the exact-fit 640 B / 80 B row still runs). - #[test] - fn leaf_rows_longer_than_the_activation_are_refused() { - if !legacy_supported(){eprintln!("SKIP: Original AVX-512 capability required");return;} - let a=ActQ::default();let mut out=[0.0f32]; - let (codes,scales)=(vec![0u8;41*16],vec![0u8;41*2]); - for oracle in [false,true]{ - assert!(catch_unwind(AssertUnwindSafe(||row(&codes,&scales,&[&a],&mut out,oracle))).is_err(),"41 blocks, oracle={oracle}"); - assert!(catch_unwind(AssertUnwindSafe(||row(&codes[..40*16],&scales[..40*2],&[&a],&mut out,oracle))).is_ok(),"40 blocks, oracle={oracle}"); - } - } +mod tests; - // STRA-329: row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) fuses the weight-scale times activation-sum correction like expert.cpp:242/:294. - // With an all-zero activation the integer dots vanish, so the result is exactly -corr and the scalar model below is the whole kernel. - #[test] - fn row256_correction_is_one_fused_multiply_add() { - if !legacy_supported(){eprintln!("SKIP: Original AVX-512 capability required");return;} - let mut seed=0x0329_5eed_1234_abcdu64;let mut next=||{seed^=seed<<13;seed^=seed>>7;seed^=seed<<17;seed}; - let mut differed=0; - for round in 0..8 { - let nb=40usize;let mut scales=vec![0u8;nb*2];let mut a=ActQ::default();let mut codes=vec![0u8;nb*16]; - for v in codes.iter_mut(){*v=next()as u8;} - for b in 0..nb {let e=10+(next()%6)as u16;let m=(next()&0x3ff)as u16;scales[b*2..b*2+2].copy_from_slice(&((e<<10)|m).to_le_bytes()); - for h in 0..2 {a.hx[b*2+h]=((next()%2_000_001)as f32-1_000_000.0)*(0.001+0.37*round as f32);}} - let (mut fused,mut unfused)=(0.0f32,0.0f32); - for b in 0..nb {let d=half(&scales[b*2..]);let s=a.hx[b*2]+a.hx[b*2+1];fused=d.mul_add(s,fused);unfused+=d*s;} - let mut out=[0.0f32];/* SAFETY: legacy_supported() above; 40 blocks of 16 code bytes / 2 scale bytes, the ActQ holds 80 chunks. */unsafe{row256(&codes,&scales,&[&a],&mut out);} - assert_eq!(out[0].to_bits(),(-fused).to_bits(),"round {round}: -corr must be the fused chain"); - if fused.to_bits()!=unfused.to_bits(){differed+=1;} - } - assert!(differed>0,"the fixture must separate the fused and the unfused chain, or the test proves nothing"); - } -} +mod set_oracle_q8_zero_fn; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::dot32; +#[allow(unused_imports)] +pub(super) use set_oracle_q8_zero_fn::half; +#[allow(unused_imports)] +pub(super) use set_oracle_q8_zero_fn::legacy_supported; +#[allow(unused_imports)] +pub use set_oracle_q8_zero_fn::oracle_q8_zero_enabled; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::row; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::row_oracle; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::row256; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::row512; +#[allow(unused_imports)] +pub use set_oracle_q8_zero_fn::set_oracle_q8_zero; +#[allow(unused_imports)] +use set_oracle_q8_zero_fn::unpack32; +mod admit_fn; +#[allow(unused_imports)] +use admit_fn::admit; +#[allow(unused_imports)] +pub use admit_fn::down_rows; +#[allow(unused_imports)] +pub use admit_fn::expert; +#[allow(unused_imports)] +pub use admit_fn::expert_quantized; +#[allow(unused_imports)] +pub use admit_fn::expert_scalar; +#[allow(unused_imports)] +pub use admit_fn::gate_up_rows; +mod gate_each_fn; +#[allow(unused_imports)] +pub(super) use gate_each_fn::down_each; +#[allow(unused_imports)] +pub(super) use gate_each_fn::gate_each; +#[allow(unused_imports)] +pub(super) use gate_each_fn::whole_single; diff --git a/crates/native-cpu-expert/src/rust_legacy/admit_fn.rs b/crates/native-cpu-expert/src/rust_legacy/admit_fn.rs new file mode 100644 index 00000000..3a06efb2 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_legacy/admit_fn.rs @@ -0,0 +1,217 @@ +//! Moved out of the parent module by STRA-338: fn admit, fn gate_up_rows, fn down_rows, fn expert_quantized, fn expert, fn expert_scalar. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn admit( + blob: &[u8], + a: &[&PlanarActivation], + out: &[&mut [f32]], + width: usize, + chunks: i32, + r0: usize, + r1: usize, +) -> Result<()> { + if blob.len() != BLOB + || a.is_empty() + || a.len() > MAX_ROWS + || a.len() != out.len() + || r0 > r1 + || r1 > width + || out.iter().any(|v| v.len() != width) + || a.iter().any(|x| x.0.nchunks != chunks) + { + return Err(Error::Shape); + } + if !legacy_supported() { + return Err(Error::Unsupported); + } + Ok(()) +} +pub fn gate_up_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> { + admit(blob, a, out, FF, 80, r0, r1)?; + let empty = ActQ::default(); + let mut aa = [∅ MAX_ROWS]; + for t in 0..a.len() { + aa[t] = &a[t].0; + } + let mut g = [0.0; MAX_ROWS]; + let mut u = [0.0; MAX_ROWS]; + // Original row-range APIs always use row_dot, even in oracle activation mode. + for r in r0..r1 { + row( + &blob[(2 * r) * 640..(2 * r + 1) * 640], + &blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80], + &aa[..a.len()], + &mut g[..a.len()], + false, + ); + row( + &blob[(2 * r + 1) * 640..(2 * r + 2) * 640], + &blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80], + &aa[..a.len()], + &mut u[..a.len()], + false, + ); + for t in 0..a.len() { + out[t][r] = silu(g[t], u[t]); + } + } + Ok(()) +} +pub fn down_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> { + admit(blob, a, out, H, 20, r0, r1)?; + let empty = ActQ::default(); + let mut aa = [∅ MAX_ROWS]; + for t in 0..a.len() { + aa[t] = &a[t].0; + } + let mut v = [0.0; MAX_ROWS]; + for r in r0..r1 { + row( + &blob[D_CODES + r * 160..D_CODES + (r + 1) * 160], + &blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20], + &aa[..a.len()], + &mut v[..a.len()], + false, + ); + for t in 0..a.len() { + out[t][r] = v[t]; + } + } + Ok(()) +} +pub fn expert_quantized( + blob: &[u8], + a: &[&PlanarActivation], + out: &mut [&mut [f32]], + scratch: &mut PlanarScratch, +) -> Result<()> { + // The Original multi entry falls back to complete per-token experts for + // oracle mode or a call wider than its eight-row multi scratch. + if blob.len() != BLOB + || a.is_empty() + || a.len() > i32::MAX as usize + || a.len() != out.len() + || out.iter().any(|v| v.len() != H) + || a.iter().any(|x| x.0.nchunks != 80) + { + return Err(Error::Shape); + } + if !legacy_supported() { + return Err(Error::Unsupported); + } + let oracle = oracle_q8_zero_enabled(); + if oracle || a.len() > MAX_ROWS { + for t in 0..a.len() { + whole_single(blob, a[t], out[t], &mut scratch.single); + } + return Ok(()); + } + let empty = ActQ::default(); + let mut aa = [∅ MAX_ROWS]; + for t in 0..a.len() { + aa[t] = &a[t].0; + } + let mut g = [0.0; MAX_ROWS]; + let mut u = [0.0; MAX_ROWS]; + for r in 0..FF { + row( + &blob[(2 * r) * 640..(2 * r + 1) * 640], + &blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80], + &aa[..a.len()], + &mut g[..a.len()], + oracle, + ); + row( + &blob[(2 * r + 1) * 640..(2 * r + 2) * 640], + &blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80], + &aa[..a.len()], + &mut u[..a.len()], + oracle, + ); + for t in 0..a.len() { + scratch.ff[t][r] = silu(g[t], u[t]); + } + } + for t in 0..a.len() { + scratch.a2[t].quantize(&scratch.ff[t])?; + } + for t in 0..a.len() { + aa[t] = &scratch.a2[t].0; + } + for r in 0..H { + row( + &blob[D_CODES + r * 160..D_CODES + (r + 1) * 160], + &blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20], + &aa[..a.len()], + &mut g[..a.len()], + oracle, + ); + for t in 0..a.len() { + out[t][r] = g[t]; + } + } + Ok(()) +} +pub fn expert(blob: &[u8], x: &[f32], out: &mut [f32], scratch: &mut PlanarScratch) -> Result<()> { + if x.len() != H { + return Err(Error::Shape); + } + let mut a = PlanarActivation::default(); + a.quantize(x)?; + expert_quantized(blob, &[&a], &mut [out], scratch) +} +/// Original scalar benchmark, deliberately distinct from VNNI evaluation order. +pub fn expert_scalar(blob: &[u8], x: &[f32], out: &mut [f32], quantized: bool) -> Result<()> { + if blob.len() != BLOB || x.len() != H || out.len() != H { + return Err(Error::Shape); + } + let mut xq = [0.0; H]; + let mut a = PlanarActivation::default(); + let input = if quantized { + a.quantize(x)?; + for (i, v) in xq.iter_mut().enumerate() { + *v = a.0.scale[i / 32] * a.0.q[i] as f32; + } + &xq[..] + } else { + x + }; + let mut ff = [0.0; FF]; + for r in 0..FF { + let mut sg = 0.0; + let mut su = 0.0; + for b in 0..40 { + let dg = half(&blob[GU_SCALES + 2 * r * 80 + 2 * b..]); + let du = half(&blob[GU_SCALES + (2 * r + 1) * 80 + 2 * b..]); + for j in 0..64 { + let o = b * 64 + j; + sg += (((blob[2 * r * 640 + b * 16 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 * dg * input[o]; + su += (((blob[(2 * r + 1) * 640 + b * 16 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 + * du + * input[o]; + } + } + ff[r] = silu(sg, su); + } + if quantized { + a.quantize(&ff)?; + for (i, v) in ff.iter_mut().enumerate() { + *v = a.0.scale[i / 32] * a.0.q[i] as f32; + } + } + for (r, value) in out.iter_mut().enumerate() { + let mut sum = 0.0; + for b in 0..10 { + let d = half(&blob[D_SCALES + r * 20 + 2 * b..]); + for j in 0..64 { + sum += (((blob[D_CODES + r * 160 + b * 16 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 + * d + * ff[b * 64 + j]; + } + } + *value = sum; + } + Ok(()) +} diff --git a/crates/native-cpu-expert/src/rust_legacy/gate_each_fn.rs b/crates/native-cpu-expert/src/rust_legacy/gate_each_fn.rs new file mode 100644 index 00000000..7dfcba62 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_legacy/gate_each_fn.rs @@ -0,0 +1,105 @@ +//! Moved out of the parent module by STRA-338: fn gate_each, fn down_each, impl Default_for_SingleScratch, fn whole_single. + +#[allow(unused_imports)] +use super::*; + +// Disjoint row cells are written by the pool callback; it never creates an +// overlapping mutable whole-row slice while another worker owns another range. +pub(in super::super) fn gate_each( + blob: &[u8], + a: &[&PlanarActivation], + r0: usize, + r1: usize, + mut write: impl FnMut(usize, usize, f32), +) { + let empty = ActQ::default(); + let mut aa = [∅ MAX_ROWS]; + for t in 0..a.len() { + aa[t] = &a[t].0; + } + let mut g = [0.0; MAX_ROWS]; + let mut u = g; + for r in r0..r1 { + row( + &blob[(2 * r) * 640..(2 * r + 1) * 640], + &blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80], + &aa[..a.len()], + &mut g[..a.len()], + false, + ); + row( + &blob[(2 * r + 1) * 640..(2 * r + 2) * 640], + &blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80], + &aa[..a.len()], + &mut u[..a.len()], + false, + ); + for t in 0..a.len() { + write(t, r, silu(g[t], u[t])); + } + } +} +pub(in super::super) fn down_each( + blob: &[u8], + a: &[&PlanarActivation], + r0: usize, + r1: usize, + mut write: impl FnMut(usize, usize, f32), +) { + let empty = ActQ::default(); + let mut aa = [∅ MAX_ROWS]; + for t in 0..a.len() { + aa[t] = &a[t].0; + } + let mut v = [0.0; MAX_ROWS]; + for r in r0..r1 { + row( + &blob[D_CODES + r * 160..D_CODES + (r + 1) * 160], + &blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20], + &aa[..a.len()], + &mut v[..a.len()], + false, + ); + for t in 0..a.len() { + write(t, r, v[t]); + } + } +} +impl Default for SingleScratch { + fn default() -> Self { + Self { _a1: ActQ::default(), a2: PlanarActivation::default(), ff: [0.0; FF] } + } +} +pub(in super::super) fn whole_single(blob: &[u8], a: &PlanarActivation, out: &mut [f32], s: &mut SingleScratch) { + let oracle = oracle_q8_zero_enabled(); + let mut g = [0.0]; + let mut u = [0.0]; + for r in 0..FF { + row( + &blob[(2 * r) * 640..(2 * r + 1) * 640], + &blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80], + &[&a.0], + &mut g, + oracle, + ); + row( + &blob[(2 * r + 1) * 640..(2 * r + 2) * 640], + &blob[GU_SCALES + (2 * r + 1) * 80..GU_SCALES + (2 * r + 2) * 80], + &[&a.0], + &mut u, + oracle, + ); + s.ff[r] = silu(g[0], u[0]); + } + s.a2.quantize(&s.ff).expect("admitted legacy whole geometry"); + for (r, o) in out.iter_mut().enumerate() { + row( + &blob[D_CODES + r * 160..D_CODES + (r + 1) * 160], + &blob[D_SCALES + r * 20..D_SCALES + (r + 1) * 20], + &[&s.a2.0], + &mut g, + oracle, + ); + *o = g[0]; + } +} diff --git a/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero_fn.rs b/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero_fn.rs new file mode 100644 index 00000000..0883a54a --- /dev/null +++ b/crates/native-cpu-expert/src/rust_legacy/set_oracle_q8_zero_fn.rs @@ -0,0 +1,241 @@ +//! Moved out of the parent module by STRA-338: fn set_oracle_q8_zero, fn oracle_q8_zero_enabled, fn half, fn legacy_supported, impl Default_for_PlanarActivation, impl PlanarActivation .... + +#[allow(unused_imports)] +use super::*; + +pub fn set_oracle_q8_zero(enabled: bool) { + ORACLE.store(enabled, Ordering::Relaxed); +} +pub fn oracle_q8_zero_enabled() -> bool { + ORACLE.load(Ordering::Relaxed) +} +// Original h2f integer conversion, including half subnormals and signed zero. +pub(in super::super) fn half(bytes: &[u8]) -> f32 { + let h = u16::from_le_bytes([bytes[0], bytes[1]]); + let sign = (h as u32 >> 15) << 31; + let mut e = (h as u32 >> 10) & 31; + let mut m = h as u32 & 1023; + let bits = if e == 0 { + if m == 0 { + sign + } else { + e = 113; + while m & 1024 == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 1023) << 13) + } + } else if e == 31 { + sign | 0x7f800000 | (m << 13) + } else { + sign | ((e + 112) << 23) | (m << 13) + }; + f32::from_bits(bits) +} +pub(in super::super) fn legacy_supported() -> bool { + /* SAFETY: CPUID is architectural on x86_64; XGETBV is only executed after the OSXSAVE bit (ecx bit 27) was verified. */ + unsafe { + if __cpuid(0).eax < 7 || __cpuid(1).ecx & (1 << 27) == 0 { + return false; + } + let c = __cpuid_count(7, 0); + _xgetbv(0) & 0xe6 == 0xe6 + && [16, 17, 30, 31].iter().all(|b| c.ebx & (1 << b) != 0) + && c.ecx & (1 << 11) != 0 + && c.ecx & (1 << 1) != 0 + } +} +impl Default for PlanarActivation { + fn default() -> Self { + Self(ActQ::default()) + } +} +impl PlanarActivation { + pub fn quantize(&mut self, x: &[f32]) -> Result<()> { + if x.is_empty() || x.len() > H || x.len() % 32 != 0 { + return Err(Error::Shape); + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + if oracle_q8_zero_enabled() { + let mut q = [super::super::rust_types::Q8Zero::default(); 80]; /* SAFETY: avx2_ok() above (AVX2+FMA+F16C); x.len() <= H and % 32 == 0 so x.len()/32 <= 80 = q.len(). */ + unsafe { + super::super::rust_quant::q8_zero(x, &mut q[..x.len() / 32]); + } + self.0.nchunks = (x.len() / 32) as i32; + for (k, q) in q[..x.len() / 32].iter().enumerate() { + self.0.q[k * 32..k * 32 + 32].copy_from_slice(&q.qs); + let d = half(&q.d.to_le_bytes()); + let s = q.qs.iter().map(|&v| v as i32).sum::(); + self.0.scale[k] = d; + self.0.sum[k] = s; + self.0.hx[k] = d * s as f32; + } + } else { + if !legacy_supported() { + return Err(Error::Unsupported); + } + /* SAFETY: legacy_supported() above proved AVX-512 F/DQ/BW/VL (+VNNI/VBMI, XCR0); x.len() <= H, % 32 == 0 (asserted by the leaf). */ + unsafe { + super::super::rust_quant::q8_one_avx512(x, &mut self.0); + } + } + Ok(()) + } + pub fn quantize_native(&mut self, x: &[f32]) -> Result<()> { + if x.is_empty() || x.len() > H || x.len() % 32 != 0 { + return Err(Error::Shape); + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } /* SAFETY: avx2_ok() above; the avx512 arm additionally checks dq_ok() before its leaf. */ + unsafe { + if super::super::rust_simd::dispatch().avx512 { + if !super::super::rust_simd::dq_ok() { + return Err(Error::Unsupported); + } + super::super::rust_quant::q8_one_avx512(x, &mut self.0); + } else { + super::super::rust_quant::q8_one_avx2(x, &mut self.0); + } + } + Ok(()) + } +} +impl Default for PlanarScratch { + fn default() -> Self { + Self { + a2: std::array::from_fn(|_| PlanarActivation::default()), + ff: [[0.0; FF]; MAX_ROWS], + single: SingleScratch::default(), + } + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] +pub(super) unsafe fn unpack32(p: *const u8) -> __m256i { + unsafe { + let q = _mm256_cvtepu16_epi64(_mm_loadl_epi64(p.cast())); + _mm256_and_si256(_mm256_multishift_epi64_epi8(_mm256_set1_epi64x(0x0e0c0a0806040200), q), _mm256_set1_epi8(3)) + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] +pub(super) unsafe fn dot32(p: *const u8, q: *const i8) -> __m256i { + unsafe { _mm256_dpbusd_epi32(_mm256_setzero_si256(), unpack32(p), _mm256_loadu_si256(q.cast())) } +} +// The correction `corr += d*(hx0+hx1)` is ONE fused multiply-add, as in the pinned C++ (expert.cpp row_dot line 242 and row_dot_multi line 294, +// GCC contracts it under -mfma); a separate mul+add rounds twice (STRA-329; the same rule as rust_q2.rs, STRA-324). +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] +pub(super) unsafe fn row256(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32]) { + unsafe { + let mut acc = [_mm256_setzero_ps(); MAX_ROWS]; + let mut corr = [0.0f32; MAX_ROWS]; + assert!(scales.len() / 2 <= 40 && codes.len() >= scales.len() / 2 * 16 && a.len() <= MAX_ROWS); + for b in 0..scales.len() / 2 { + let d = half(&scales[b * 2..]); + let lo = unpack32(codes.as_ptr().add(b * 16)); + let hi = unpack32(codes.as_ptr().add(b * 16 + 8)); + for t in 0..a.len() { + let x = a[t]; + let sl = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32( + _mm256_setzero_si256(), + lo, + _mm256_loadu_si256(x.q.as_ptr().add(b * 64).cast()), + )); + let sh = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32( + _mm256_setzero_si256(), + hi, + _mm256_loadu_si256(x.q.as_ptr().add(b * 64 + 32).cast()), + )); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2]), sl, acc[t]); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * x.scale[b * 2 + 1]), sh, acc[t]); + corr[t] = d.mul_add(x.hx[b * 2] + x.hx[b * 2 + 1], corr[t]); + } + } + for t in 0..a.len() { + out[t] = hsum_original(acc[t]) - corr[t]; + } + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] +pub(super) unsafe fn row512(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32]) { + unsafe { + let mut acc = [_mm512_setzero_ps(); MAX_ROWS]; + let mut corr = [_mm512_setzero_ps(); MAX_ROWS]; + let nb = scales.len() / 2; + assert!(nb <= 40 && codes.len() >= nb * 16 && a.len() <= MAX_ROWS); + let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); + let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); + for b0 in (0..nb).step_by(8) { + let n = (nb - b0).min(8); + let m8 = if n == 8 { 255 } else { (1u16 << n) - 1 } as u8; + let m16 = if n == 8 { 65535 } else { (1u32 << (2 * n)) - 1 } as u16; + let hs = _mm_maskz_loadu_epi16(m8, scales.as_ptr().add(b0 * 2).cast()); + let ds = _mm512_castps256_ps512(_mm256_cvtph_ps(hs)); + let dd = _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, ds)); + let mut p = [_mm512_setzero_ps(); MAX_ROWS]; + for t in 0..a.len() { + p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].scale.as_ptr().add(b0 * 2))); + corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].hx.as_ptr().add(b0 * 2)), corr[t]); + } + for i in 0..n { + let b = b0 + i; + let q = _mm512_cvtepu16_epi64(_mm_loadu_si128(codes.as_ptr().add(b * 16).cast())); + let q = _mm512_and_si512( + _mm512_multishift_epi64_epi8(_mm512_set1_epi64(0x0e0c0a0806040200), q), + _mm512_set1_epi8(3), + ); + for t in 0..a.len() { + let dot = _mm512_dpbusd_epi32( + _mm512_setzero_si512(), + q, + _mm512_loadu_si512(a[t].q.as_ptr().add(b * 64).cast()), + ); + let s = _mm512_permutexvar_ps(_mm512_add_epi32(base, _mm512_set1_epi32((2 * i) as i32)), p[t]); + acc[t] = _mm512_fmadd_ps(s, _mm512_cvtepi32_ps(dot), acc[t]); + } + } + } + for t in 0..a.len() { + out[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); + } + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vnni,avx512vbmi,avx2,fma,f16c")] +pub(super) unsafe fn row_oracle(codes: &[u8], scales: &[u8], a: &ActQ) -> f32 { + unsafe { + assert!(scales.len() / 2 <= 40 && codes.len() >= scales.len() / 2 * 16); + let mut result = 0.0; + for b in 0..scales.len() / 2 { + let mut block = 0.0; + for h in 0..2 { + let chunk = b * 2 + h; + let x = dot32(codes.as_ptr().add(b * 16 + h * 8), a.q.as_ptr().add(chunk * 32)); + let v = _mm_add_epi32(_mm256_castsi256_si128(x), _mm256_extracti128_si256::<1>(x)); + let v = _mm_hadd_epi32(v, v); + let dot = _mm_cvtsi128_si32(_mm_hadd_epi32(v, v)) - a.sum[chunk]; + block += a.scale[chunk] * dot as f32; + } + result += half(&scales[b * 2..]) * block; + } + result + } +} +pub(super) fn row(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut [f32], oracle: bool) { + /* SAFETY: private; every caller (gate_up_rows, down_rows, expert_quantized, whole_single, gate_each, down_each) first passed legacy_supported() -- directly or via ExpertPool::run, run_split and run_split_multi -- and hands 640 B/80 B (gate/up) or 160 B/20 B (down) code/scale slices, i.e. nb <= 40 (asserted in the leaves). */ + unsafe { + if oracle { + for t in 0..a.len() { + out[t] = row_oracle(codes, scales, a[t]); + } + } else { + static ZMM: OnceLock = OnceLock::new(); + if *ZMM.get_or_init(|| std::env::var_os("STRATA_CPU_YMM").is_none()) { + row512(codes, scales, a, out); + } else { + row256(codes, scales, a, out); + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_legacy/tests.rs b/crates/native-cpu-expert/src/rust_legacy/tests.rs new file mode 100644 index 00000000..e6e6d595 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_legacy/tests.rs @@ -0,0 +1,78 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; +use std::panic::{AssertUnwindSafe, catch_unwind}; +// The AVX-512 row leaves load a.q / a.scale / a.hx for every 8-byte-code block pair of the row: more than 40 blocks would read +// past the ActQ, so the leaves refuse it before the first load (the exact-fit 640 B / 80 B row still runs). +#[test] +fn leaf_rows_longer_than_the_activation_are_refused() { + if !legacy_supported() { + eprintln!("SKIP: Original AVX-512 capability required"); + return; + } + let a = ActQ::default(); + let mut out = [0.0f32]; + let (codes, scales) = (vec![0u8; 41 * 16], vec![0u8; 41 * 2]); + for oracle in [false, true] { + assert!( + catch_unwind(AssertUnwindSafe(|| row(&codes, &scales, &[&a], &mut out, oracle))).is_err(), + "41 blocks, oracle={oracle}" + ); + assert!( + catch_unwind(AssertUnwindSafe(|| row(&codes[..40 * 16], &scales[..40 * 2], &[&a], &mut out, oracle))) + .is_ok(), + "40 blocks, oracle={oracle}" + ); + } +} + +// STRA-329: row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) fuses the weight-scale times activation-sum correction like expert.cpp:242/:294. +// With an all-zero activation the integer dots vanish, so the result is exactly -corr and the scalar model below is the whole kernel. +#[test] +fn row256_correction_is_one_fused_multiply_add() { + if !legacy_supported() { + eprintln!("SKIP: Original AVX-512 capability required"); + return; + } + let mut seed = 0x0329_5eed_1234_abcdu64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut differed = 0; + for round in 0..8 { + let nb = 40usize; + let mut scales = vec![0u8; nb * 2]; + let mut a = ActQ::default(); + let mut codes = vec![0u8; nb * 16]; + for v in codes.iter_mut() { + *v = next() as u8; + } + for b in 0..nb { + let e = 10 + (next() % 6) as u16; + let m = (next() & 0x3ff) as u16; + scales[b * 2..b * 2 + 2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + for h in 0..2 { + a.hx[b * 2 + h] = ((next() % 2_000_001) as f32 - 1_000_000.0) * (0.001 + 0.37 * round as f32); + } + } + let (mut fused, mut unfused) = (0.0f32, 0.0f32); + for b in 0..nb { + let d = half(&scales[b * 2..]); + let s = a.hx[b * 2] + a.hx[b * 2 + 1]; + fused = d.mul_add(s, fused); + unfused += d * s; + } + let mut out = [0.0f32]; /* SAFETY: legacy_supported() above; 40 blocks of 16 code bytes / 2 scale bytes, the ActQ holds 80 chunks. */ + unsafe { + row256(&codes, &scales, &[&a], &mut out); + } + assert_eq!(out[0].to_bits(), (-fused).to_bits(), "round {round}: -corr must be the fused chain"); + if fused.to_bits() != unfused.to_bits() { + differed += 1; + } + } + assert!(differed > 0, "the fixture must separate the fused and the unfused chain, or the test proves nothing"); +} diff --git a/crates/native-cpu-expert/src/rust_model_quant.rs b/crates/native-cpu-expert/src/rust_model_quant.rs index e1dee91e..8311dc2a 100644 --- a/crates/native-cpu-expert/src/rust_model_quant.rs +++ b/crates/native-cpu-expert/src/rust_model_quant.rs @@ -1,15 +1,78 @@ //! Original ggml_quantize_chunk/type-trait adapter for numerical bench/conversion. //! No weight/source/binding certificate is created by encoding a float slice. -use super::{Error,Result}; use super::rust_ggml::Kind; -pub fn requires_imatrix(kind:Kind)->bool{matches!(kind,Kind::Iq2Xxs|Kind::Iq2Xs|Kind::Iq1S)} -pub fn quantize_init(kind:Kind)->Result<()>{super::rust_weight_iq::init(kind)} -pub fn quantize_free()->Result<()>{for k in [Kind::Iq2Xxs,Kind::Iq2Xs,Kind::Iq2S,Kind::Iq1S,Kind::Iq1M,Kind::Iq3Xxs,Kind::Iq3S]{super::rust_weight_iq::free(k)?;}Ok(())} -fn validate(kind:Kind,x:&[f32],y:&[u8],imatrix:Option<&[f32]>)->Result<()>{if x.is_empty()||y.len()!=kind.row_bytes(x.len())?||imatrix.is_some_and(|w|w.len()!=x.len())||requires_imatrix(kind)&&imatrix.is_none(){return Err(Error::Shape);}if x.iter().any(|x|!x.is_finite())||imatrix.is_some_and(|w|w.iter().any(|x|!x.is_finite()||*x<0.0)){return Err(Error::NonFinite);}Ok(())} +use super::{Error, Result}; +pub fn requires_imatrix(kind: Kind) -> bool { + matches!(kind, Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq1S) +} +pub fn quantize_init(kind: Kind) -> Result<()> { + super::rust_weight_iq::init(kind) +} +pub fn quantize_free() -> Result<()> { + for k in [Kind::Iq2Xxs, Kind::Iq2Xs, Kind::Iq2S, Kind::Iq1S, Kind::Iq1M, Kind::Iq3Xxs, Kind::Iq3S] { + super::rust_weight_iq::free(k)?; + } + Ok(()) +} +fn validate(kind: Kind, x: &[f32], y: &[u8], imatrix: Option<&[f32]>) -> Result<()> { + if x.is_empty() + || y.len() != kind.row_bytes(x.len())? + || imatrix.is_some_and(|w| w.len() != x.len()) + || requires_imatrix(kind) && imatrix.is_none() + { + return Err(Error::Shape); + } + if x.iter().any(|x| !x.is_finite()) || imatrix.is_some_and(|w| w.iter().any(|x| !x.is_finite() || *x < 0.0)) { + return Err(Error::NonFinite); + } + Ok(()) +} /// Reference model traits. IQ2_XXS/XS/IQ1_S have no unweighted reference; /// callers use quantize_chunk with their actual required imatrix instead. -pub fn quantize_row_ref(kind:Kind,x:&[f32],y:&mut[u8])->Result<()>{validate(kind,x,y,None)?;quantize_init(kind)?;if !super::rust_weight_quant::row_without_iq(kind,x,y,None,true)?{super::rust_weight_iq::row(kind,x,y,None)?;}Ok(())} -pub fn quantize_chunk(kind:Kind,src:&[f32],dst:&mut[u8],start:usize,nrows:usize,n_per_row:usize,imatrix:Option<&[f32]>)->Result{ - if n_per_row==0||start%kind.block().0!=0||start%n_per_row!=0||imatrix.is_some_and(|w|w.len()!=n_per_row)||requires_imatrix(kind)&&imatrix.is_none(){return Err(Error::Shape);}let rowbytes=kind.row_bytes(n_per_row)?;let n=nrows.checked_mul(n_per_row).ok_or(Error::Shape)?;let end=start.checked_add(n).ok_or(Error::Shape)?;let at=(start/n_per_row).checked_mul(rowbytes).ok_or(Error::Shape)?;let bytes=nrows.checked_mul(rowbytes).ok_or(Error::Shape)?;let outend=at.checked_add(bytes).ok_or(Error::Shape)?;if end>src.len()||outend>dst.len(){return Err(Error::Shape);}if src[start..end].iter().any(|x|!x.is_finite())||imatrix.is_some_and(|w|w.iter().any(|x|!x.is_finite()||*x<0.0)){return Err(Error::NonFinite);}quantize_init(kind)?; - for (x,y)in src[start..end].chunks_exact(n_per_row).zip(dst[at..outend].chunks_exact_mut(rowbytes)){if !super::rust_weight_quant::row_without_iq(kind,x,y,imatrix,false)?{super::rust_weight_iq::row(kind,x,y,imatrix)?;}}Ok(bytes) +pub fn quantize_row_ref(kind: Kind, x: &[f32], y: &mut [u8]) -> Result<()> { + validate(kind, x, y, None)?; + quantize_init(kind)?; + if !super::rust_weight_quant::row_without_iq(kind, x, y, None, true)? { + super::rust_weight_iq::row(kind, x, y, None)?; + } + Ok(()) +} +pub fn quantize_chunk( + kind: Kind, + src: &[f32], + dst: &mut [u8], + start: usize, + nrows: usize, + n_per_row: usize, + imatrix: Option<&[f32]>, +) -> Result { + if n_per_row == 0 + || start % kind.block().0 != 0 + || start % n_per_row != 0 + || imatrix.is_some_and(|w| w.len() != n_per_row) + || requires_imatrix(kind) && imatrix.is_none() + { + return Err(Error::Shape); + } + let rowbytes = kind.row_bytes(n_per_row)?; + let n = nrows.checked_mul(n_per_row).ok_or(Error::Shape)?; + let end = start.checked_add(n).ok_or(Error::Shape)?; + let at = (start / n_per_row).checked_mul(rowbytes).ok_or(Error::Shape)?; + let bytes = nrows.checked_mul(rowbytes).ok_or(Error::Shape)?; + let outend = at.checked_add(bytes).ok_or(Error::Shape)?; + if end > src.len() || outend > dst.len() { + return Err(Error::Shape); + } + if src[start..end].iter().any(|x| !x.is_finite()) + || imatrix.is_some_and(|w| w.iter().any(|x| !x.is_finite() || *x < 0.0)) + { + return Err(Error::NonFinite); + } + quantize_init(kind)?; + for (x, y) in src[start..end].chunks_exact(n_per_row).zip(dst[at..outend].chunks_exact_mut(rowbytes)) { + if !super::rust_weight_quant::row_without_iq(kind, x, y, imatrix, false)? { + super::rust_weight_iq::row(kind, x, y, imatrix)?; + } + } + Ok(bytes) } diff --git a/crates/native-cpu-expert/src/rust_native_general.rs b/crates/native-cpu-expert/src/rust_native_general.rs index 2fcaa9cd..6eca6324 100644 --- a/crates/native-cpu-expert/src/rust_native_general.rs +++ b/crates/native-cpu-expert/src/rust_native_general.rs @@ -1,143 +1,59 @@ //! Original native_fmt, quantization and env-selected grouped dispatch. //! Fixed initialized owned activation bytes mirror the Original pool banks. -use super::{Error,Result}; -use super::rust_ggml::{Kind,NativeFormat}; -use super::rust_types::{Q8K,Q8Zero}; +use super::rust_ggml::{Kind, NativeFormat}; use super::rust_kq::Q8One; +use super::rust_types::{Q8K, Q8Zero}; +use super::{Error, Result}; // Bounds: NativeActivation is `repr(C, align(64))` with `bytes` at offset 0, so the Q8K/Q8Zero/Q8One/u16/f32 views of `raw()` // are aligned; quantize() guarantees activation_bytes(n) <= BYTES and check(kind, n) pins `self.n == n` and the encoding // class, so every `from_raw_parts(.., n/block)` stays inside the array. Weight extents come from NativeFormat::validate() // (recomputed geometry) plus `blob.len() == f.bytes`, `r1 <= rows`, and `out[t].len() == rows`. Gate: avx2_ok(). -#[repr(C,align(64))] -pub struct NativeActivation{bytes:[u8;BYTES],pub(super) n:usize,kind:Kind} -impl Default for NativeActivation{fn default()->Self{Self{bytes:[0;BYTES],n:0,kind:Kind::F32}}} -impl NativeActivation{ - pub fn quantize(&mut self,kind:Kind,input:&[f32])->Result<()> {if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}let bytes=kind.activation_bytes(input.len())?;if input.is_empty()||bytes>BYTES{return Err(Error::Shape);}/* SAFETY: avx2_ok() above; `bytes == activation_bytes(len) <= BYTES`, and `self.bytes` is at offset 0 of a 64-aligned repr(C) struct. */unsafe{super::rust_ggml::quantize_raw(kind,input,&mut self.bytes[..bytes]);}self.kind=kind;self.n=input.len();Ok(())} - pub fn encoded_bytes(&self)->Result{self.kind.activation_bytes(self.n)} - pub(super) fn check(&self,kind:Kind,n:usize)->Result<()>{if self.n!=n||self.kind.activation_id()!=kind.activation_id(){return Err(Error::Shape);}Ok(())} - pub(super) fn raw(&self)->&[u8]{&self.bytes} -} -pub fn native_gu_rows(f:&NativeFormat,blob:&[u8],act:&[&NativeActivation],ff:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()> { - f.validate()?;if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}if blob.len()!=f.bytes||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=ff.len()||r0>r1||r1>f.n_ff||ff.iter().any(|v|v.len()!=f.n_ff){return Err(Error::Shape);}for a in act{a.check(f.gu,f.n_embd)?;}let d=super::rust_simd::dispatch();if d.iq512&&(act.len()as i32)>=d.mt_min&&matches!(f.gu.original_id(),16|17|18|21|22)&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);} - for r in r0..r1{let gr=&blob[r*f.gu_row..(r+1)*f.gu_row];let ur=&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row];for at in (0..act.len()).step_by(8){let end=(at+8).min(act.len());let chunk=&act[at..end];let mut g=[0.0;8];let mut u=[0.0;8];/* SAFETY: module header; avx2_ok() and (iq512 && dq_ok) checked above, gr/ur are whole rows of a validated blob. */unsafe{group_dot_policy(f.gu,gr,chunk,&mut g[..chunk.len()],d,true,act.len());group_dot_policy(f.gu,ur,chunk,&mut u[..chunk.len()],d,true,act.len());}for t in 0..chunk.len(){ff[at+t][r]=super::rust_simd::silu(g[t],u[t]);}}}Ok(()) -} -pub fn native_down_rows(f:&NativeFormat,blob:&[u8],hq:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()> { - f.validate()?;if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}if blob.len()!=f.bytes||hq.is_empty()||hq.len()>i32::MAX as usize||hq.len()!=out.len()||r0>r1||r1>f.n_embd||out.iter().any(|v|v.len()!=f.n_embd){return Err(Error::Shape);}for a in hq{a.check(f.down,f.n_ff)?;}let d=super::rust_simd::dispatch();for r in r0..r1{let row=&blob[f.down_offset+r*f.down_row..f.down_offset+(r+1)*f.down_row];for at in (0..hq.len()).step_by(8){let end=(at+8).min(hq.len());let chunk=&hq[at..end];let mut v=[0.0;8];/* SAFETY: module header; avx2_ok() checked above, `row` is a whole down row of a validated blob. */unsafe{group_dot_policy(f.down,row,chunk,&mut v[..chunk.len()],d,false,hq.len());}for t in 0..chunk.len(){out[at+t][r]=v[t];}}}Ok(()) -} -/// Multi-token gate/up kernel choice of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`): -/// Some(true) = the 512-bit kernel, Some(false) = the 256-bit one, None = ggml's per-token dot. IQ4_XS (23) has only the 256-bit kernel and -/// takes it on an AVX2-only tree (STRA-329: this site omitted it, rust_pool.rs `f.gu==23&&!d.avx512` has it since STRA-324). -pub(super) fn gu_multi_route(k:i32,policy_nt:i32,d:&super::rust_simd::Dispatch)->Option { - if policy_nt(kind:Kind,row:&[u8],act:&[&NativeActivation],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool){unsafe{let mut raw:[&[u8];8]=[&[];8];for t in 0..act.len(){raw[t]=act[t].raw();}group_dot_bytes(kind,row,act[0].n,&raw[..act.len()],out,d,gu)}} -pub(super) unsafe fn group_dot_bytes(kind:Kind,row:&[u8],n:usize,act:&[&[u8]],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool){unsafe{ - group_dot_bytes_policy(kind,row,n,act,out,d,gu,act.len()); -}} -unsafe fn group_dot_policy(kind:Kind,row:&[u8],act:&[&NativeActivation],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool,policy_nt:usize){unsafe{let mut raw:[&[u8];8]=[&[];8];for t in 0..act.len(){raw[t]=act[t].raw();}group_dot_bytes_policy(kind,row,act[0].n,&raw[..act.len()],out,d,gu,policy_nt)}} -unsafe fn group_dot_bytes_policy(kind:Kind,row:&[u8],n:usize,act:&[&[u8]],out:&mut[f32],d:&super::rust_simd::Dispatch,gu:bool,policy_nt:usize){unsafe{ - let nt=act.len();let k=kind.original_id();static KQ:std::sync::OnceLock=std::sync::OnceLock::new();let kq=*KQ.get_or_init(||std::env::var("STRATA_KQ256").ok().is_some_and(|s|super::rust_simd::atoi(&s)!=0));if kq&&policy_nt>=2&&((gu&&k==12)||(!gu&&matches!(k,7|8))){if k==12{let mut a=[&[][..];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast::(),n/256);}super::rust_kq::q4_k_dot(row,&a[..nt],out);}else if k==7{let mut a:[&[Q8One];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_kq::q5_one_dot(row,&a[..nt],out);}else{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_kq::q8_zero_dot(row,&a[..nt],out);}return;} - if gu&&let Some(wide)=gu_multi_route(k,policy_nt as i32,d){let mut a:[&[Q8K];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/256);}if wide{super::rust_iq::dot_multi512(k,row,&a[..nt],out);}else{super::rust_iq::dot_multi256(k,row,&a[..nt],out);}return;} - if !gu&&(policy_nt as i32)>=d.mt_min&&k==20&&d.iq4nl{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..nt{a[t]=std::slice::from_raw_parts(act[t].as_ptr().cast(),n/32);}super::rust_iq::iq4nl(row,&a[..nt],out,false);return;} - for t in 0..nt{out[t]=super::rust_ggml::dot_raw(kind,row,n,act[t]);} -}} -/// The explicit Original kq256 benchmark API is independent of its env policy. -pub fn kq_rows(kind:Kind,weights:&[u8],width:usize,act:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()>{ - if !matches!(kind,Kind::Q4K|Kind::Q5One|Kind::Q8Zero)||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=out.len()||r0>r1{return Err(Error::Shape);}let stride=kind.row_bytes(width)?;if stride==0||weights.len()%stride!=0||r1>weights.len()/stride||out.iter().any(|o|o.len()!=weights.len()/stride){return Err(Error::Shape);}for a in act{a.check(kind,width)?;}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);}/* SAFETY: module header; avx2_ok() checked above, check(kind,width) pinned every activation, row extents are r*stride slices. */unsafe{for base in (0..act.len()).step_by(8){let act=&act[base..(base+8).min(act.len())];for r in r0..r1{let row=&weights[r*stride..(r+1)*stride];let mut v=[0.0;8];match kind{Kind::Q4K=>{let mut a:[&[Q8K];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),width/256);}super::rust_kq::q4_k_dot(row,&a[..act.len()],&mut v[..act.len()]);},Kind::Q5One=>{let mut a:[&[Q8One];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),width/32);}super::rust_kq::q5_one_dot(row,&a[..act.len()],&mut v[..act.len()]);},Kind::Q8Zero=>{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),width/32);}super::rust_kq::q8_zero_dot(row,&a[..act.len()],&mut v[..act.len()]);},_=>unreachable!()}for t in 0..act.len(){out[base+t][r]=v[t];}}}}Ok(()) -} - -/// Explicit Original IQ256/IQ512 benchmark entry, independent of MT/env policy. -pub fn iq_rows(kind:Kind,weights:&[u8],width:usize,act:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize,avx512:bool)->Result<()> { - if !matches!(kind.original_id(),16|17|18|21|22)||width==0||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=out.len()||r0>r1{return Err(Error::Shape);} - let stride=kind.row_bytes(width)?;if weights.len()%stride!=0||r1>weights.len()/stride||out.iter().any(|v|v.len()!=weights.len()/stride){return Err(Error::Shape);}for a in act{a.check(kind,width)?;} - if !super::rust_simd::avx2_ok()||avx512&&(!super::rust_simd::avx512_ok()||!super::rust_simd::dq_ok()){return Err(Error::Unsupported);} - /* SAFETY: module header; avx2_ok() (and avx512_ok()+dq_ok() when `avx512`) checked above; width % 256 == 0 via row_bytes(). */unsafe{for base in (0..act.len()).step_by(8){let act=&act[base..(base+8).min(act.len())];let mut a:[&[Q8K];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),width/256);}for r in r0..r1{let row=&weights[r*stride..(r+1)*stride];let mut v=[0.0;8];if avx512{super::rust_iq::dot_multi512(kind.original_id(),row,&a[..act.len()],&mut v[..act.len()]);}else{super::rust_iq::dot_multi256(kind.original_id(),row,&a[..act.len()],&mut v[..act.len()]);}for t in 0..act.len(){out[base+t][r]=v[t];}}}}Ok(()) -} -pub fn iq_gu_rows(f:&NativeFormat,blob:&[u8],act:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize,avx512:bool)->Result<()> { - f.validate()?;if !matches!(f.gu.original_id(),16|17|18|21|22)||blob.len()!=f.bytes||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=out.len()||r0>r1||r1>f.n_ff||out.iter().any(|v|v.len()!=f.n_ff){return Err(Error::Shape);}for a in act{a.check(f.gu,f.n_embd)?;} - if !super::rust_simd::avx2_ok()||avx512&&(!super::rust_simd::avx512_ok()||!super::rust_simd::dq_ok()){return Err(Error::Unsupported);} - /* SAFETY: module header; gates checked above; f.validate() pinned n_embd % 256 == 0 for these kinds. */unsafe{for base in (0..act.len()).step_by(8){let act=&act[base..(base+8).min(act.len())];let mut a:[&[Q8K];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),f.n_embd/256);}for r in r0..r1{let g=&blob[r*f.gu_row..(r+1)*f.gu_row];let u=&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row];let mut gv=[0.0;8];let mut uv=gv;if avx512{super::rust_iq::dot_multi512(f.gu.original_id(),g,&a[..act.len()],&mut gv[..act.len()]);super::rust_iq::dot_multi512(f.gu.original_id(),u,&a[..act.len()],&mut uv[..act.len()]);}else{super::rust_iq::dot_multi256(f.gu.original_id(),g,&a[..act.len()],&mut gv[..act.len()]);super::rust_iq::dot_multi256(f.gu.original_id(),u,&a[..act.len()],&mut uv[..act.len()]);}for t in 0..act.len(){out[base+t][r]=super::rust_simd::silu(gv[t],uv[t]);}}}}Ok(()) -} -pub fn iq4nl_rows(weights:&[u8],width:usize,act:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()> { - if width==0||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=out.len()||r0>r1{return Err(Error::Shape);}let stride=Kind::Iq4Nl.row_bytes(width)?;if weights.len()%stride!=0||r1>weights.len()/stride||out.iter().any(|v|v.len()!=weights.len()/stride){return Err(Error::Shape);}for a in act{a.check(Kind::Iq4Nl,width)?;}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);} - /* SAFETY: module header; avx2_ok() checked above; width % 32 == 0 via row_bytes(). */unsafe{for base in (0..act.len()).step_by(8){let act=&act[base..(base+8).min(act.len())];let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),width/32);}for r in r0..r1{let mut v=[0.0;8];super::rust_iq::iq4nl(&weights[r*stride..(r+1)*stride],&a[..act.len()],&mut v[..act.len()],false);for t in 0..act.len(){out[base+t][r]=v[t];}}}}Ok(()) -} - -/// Original header capability predicates. Numerical owners still admit actual -/// CPU capability before entering their instruction leaves. -pub fn native_experts_available()->bool{true} -pub fn kq_supported(kind:Kind)->bool{matches!(kind,Kind::Q4K|Kind::Q5One|Kind::Q8Zero)} -pub fn iq_supported(kind:Kind)->bool{matches!(kind.original_id(),16|17|18|21|22)} -pub fn cpu_avx2_ok()->bool{super::rust_simd::avx2_ok()} -pub fn cpu_avx512_ok()->bool{super::rust_simd::avx512_ok()} - -/// Original explicit KQ gate/up entry, independent of STRATA_KQ256. -pub fn kq_gu_rows(f:&NativeFormat,blob:&[u8],act:&[&NativeActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()>{ - f.validate()?;if !kq_supported(f.gu)||blob.len()!=f.bytes||act.is_empty()||act.len()>i32::MAX as usize||act.len()!=out.len()||r0>r1||r1>f.n_ff||out.iter().any(|o|o.len()!=f.n_ff){return Err(Error::Shape);}for a in act{a.check(f.gu,f.n_embd)?;}if !super::rust_simd::avx2_ok(){return Err(Error::Unsupported);} - /* SAFETY: module header; avx2_ok() checked above; f.validate() pinned the geometry and blob.len()==f.bytes. */unsafe{for base in (0..act.len()).step_by(8){let act=&act[base..(base+8).min(act.len())];for r in r0..r1{let mut g=[0.0;8];let mut u=g;for(role,values)in [(0,&mut g),(f.up_offset,&mut u)]{let row=&blob[role+r*f.gu_row..role+(r+1)*f.gu_row];match f.gu{Kind::Q4K=>{let mut a:[&[Q8K];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),f.n_embd/256);}super::rust_kq::q4_k_dot(row,&a[..act.len()],&mut values[..act.len()]);},Kind::Q5One=>{let mut a:[&[Q8One];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),f.n_embd/32);}super::rust_kq::q5_one_dot(row,&a[..act.len()],&mut values[..act.len()]);},Kind::Q8Zero=>{let mut a:[&[Q8Zero];8]=[&[];8];for t in 0..act.len(){a[t]=std::slice::from_raw_parts(act[t].raw().as_ptr().cast(),f.n_embd/32);}super::rust_kq::q8_zero_dot(row,&a[..act.len()],&mut values[..act.len()]);},_=>unreachable!()}}for t in 0..act.len(){out[base+t][r]=super::rust_simd::silu(g[t],u[t]);}}}}Ok(()) -} - -/// Original q2_rows_any dispatch on a genuine initialized Planar activation. -pub fn q2_rows(weights:&[u8],width:usize,act:&[&super::rust_legacy::PlanarActivation],out:&mut[&mut[f32]],r0:usize,r1:usize)->Result<()>{ - if width==0||width>super::H||act.is_empty()||act.len()>8||act.len()!=out.len()||r0>r1{return Err(Error::Shape);}let stride=Kind::Q2Zero.row_bytes(width)?;if weights.len()%stride!=0||r1>weights.len()/stride||out.iter().any(|o|o.len()!=weights.len()/stride)||act.iter().any(|a|a.0.nchunks!= (width/32)as i32){return Err(Error::Shape);}if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);} - let empty=super::rust_types::ActQ::default();let mut a=[∅8];for t in 0..act.len(){a[t]=&act[t].0;}let mut values=[0.0;8];/* SAFETY: avx2_ok() (+dq_ok() if avx512_ok()) checked above; rows are `stride = width/64*18 <= 720` bytes (width <= H) and act.len() <= 8 (see rust_q2 bounds). */unsafe{for r in r0..r1{let row=&weights[r*stride..(r+1)*stride];if super::rust_simd::avx512_ok(){super::rust_q2::dot512(row,&a[..act.len()],&mut values[..act.len()]);}else{super::rust_q2::dot256(row,&a[..act.len()],&mut values[..act.len()]);}for t in 0..act.len(){out[t][r]=values[t];}}}Ok(()) +#[repr(C, align(64))] +pub struct NativeActivation { + bytes: [u8; BYTES], + pub(super) n: usize, + kind: Kind, } #[cfg(test)] -mod tests { - use super::*; - use super::super::rust_simd::{avx2_ok,avx512_ok,Dispatch}; - fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s} - fn dispatch_of(iq512:bool,iq256:bool,avx512:bool)->Dispatch {Dispatch{iq512,iq256,iq4nl:true,mt_min:2,gather:false,prefetch:0,avx512}} - // native_expert.cpp native_gu_rows: `nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`, then AVX-512 kernel first, else AVX2. - #[test] - fn gu_multi_route_follows_native_gu_rows() { - let avx2_tree=dispatch_of(false,true,false);let avx512_tree=dispatch_of(true,true,true);let no_iq512=dispatch_of(false,true,true);let no_iq256=dispatch_of(true,false,true);let no_iq256_avx2=dispatch_of(false,false,false); - for k in [16,17,18,21,22] { - assert_eq!(gu_multi_route(k,2,&avx2_tree),Some(false),"k {k} avx2 tree");assert_eq!(gu_multi_route(k,1,&avx2_tree),None,"k {k} one token is ggml's dot"); - assert_eq!(gu_multi_route(k,3,&avx512_tree),Some(true),"k {k} avx512 tree");assert_eq!(gu_multi_route(k,3,&no_iq512),Some(false),"k {k} STRATA_NO_IQ512"); - assert_eq!(gu_multi_route(k,3,&no_iq256),Some(true),"k {k} STRATA_NO_IQ256 keeps the 512-bit kernel");assert_eq!(gu_multi_route(k,3,&no_iq256_avx2),None); - } - // IQ4_XS: the 256-bit kernel only, and only where there is no AVX-512 CPU (an AVX-512 CPU keeps ggml's dot for it). - assert_eq!(gu_multi_route(23,2,&avx2_tree),Some(false));assert_eq!(gu_multi_route(23,8,&avx2_tree),Some(false));assert_eq!(gu_multi_route(23,1,&avx2_tree),None); - assert_eq!(gu_multi_route(23,3,&avx512_tree),None);assert_eq!(gu_multi_route(23,3,&no_iq512),None);assert_eq!(gu_multi_route(23,3,&no_iq256_avx2),None); - for k in [2,12,20,42] {assert_eq!(gu_multi_route(k,4,&avx2_tree),None,"k {k} has no multi-token IQ kernel");} - } - // Differential: native_gu_rows with an IQ4_XS gate/up at 2..8 tokens on the AVX2 tree == the multi-token kernel row by row. - // The tree is chosen once per process (OnceLock), so on an AVX-512 CPU the test re-runs itself in a child with STRATA_FORCE_AVX2=1. - #[test] - fn iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel() { - if !avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - if avx512_ok() { - assert!(std::env::var_os("LELEKA_TEST_AVX2_CHILD").is_none(),"STRATA_FORCE_AVX2=1 did not select the AVX2 tree"); - let path=module_path!();let path=&path[path.find("::").unwrap()+2..]; - let status=std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact",&format!("{path}::iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel"),"--nocapture"]) - .env("STRATA_FORCE_AVX2","1").env("LELEKA_TEST_AVX2_CHILD","1").status().unwrap(); - assert!(status.success(),"child run on the AVX2 tree failed");return; - } - let (n_embd,n_ff)=(512usize,32usize);let f=NativeFormat::new(Kind::Iq4Xs,Kind::Iq4Nl,n_embd,n_ff).unwrap(); - let mut seed=0x5eed_0329_abcd_ef01u64; - for round in 0..3 { - let mut blob=vec![0u8;f.bytes];for v in blob.iter_mut(){*v=xorshift(&mut seed)as u8;} - for b in blob[..f.down_offset].chunks_exact_mut(136){let e=8+(xorshift(&mut seed)%8)as u16;let m=(xorshift(&mut seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} - for nt in [2usize,3,5,8] { - let mut acts:Vec=(0..nt).map(|_|NativeActivation::default()).collect(); - for a in acts.iter_mut(){let x:Vec=(0..n_embd).map(|_|((xorshift(&mut seed)%20001)as f32-10000.0)*(0.001+round as f32)).collect();a.quantize(Kind::Iq4Xs,&x).unwrap();} - let refs:Vec<&NativeActivation>=acts.iter().collect();let mut ff=vec![vec![0.0f32;n_ff];nt]; - {let mut outs:Vec<&mut [f32]>=ff.iter_mut().map(|v|v.as_mut_slice()).collect();native_gu_rows(&f,&blob,&refs,&mut outs,0,n_ff).unwrap();} - let ys:Vec<&[Q8K]>=acts.iter().map(|a|/* SAFETY: quantize(Iq4Xs, n_embd) wrote n_embd/256 Q8K blocks at offset 0 of the 64-aligned activation. */unsafe{std::slice::from_raw_parts(a.raw().as_ptr().cast::(),n_embd/256)}).collect(); - for r in 0..n_ff { - let (mut g,mut u)=([0.0f32;8],[0.0f32;8]); - // SAFETY: avx2_ok() above; rows are whole IQ4_XS rows of the validated blob and every activation has n_embd/256 blocks. - unsafe{super::super::rust_iq::dot_multi256(23,&blob[r*f.gu_row..(r+1)*f.gu_row],&ys,&mut g[..nt]);super::super::rust_iq::dot_multi256(23,&blob[f.up_offset+r*f.gu_row..f.up_offset+(r+1)*f.gu_row],&ys,&mut u[..nt]);} - for t in 0..nt {assert_eq!(ff[t][r].to_bits(),super::super::rust_simd::silu(g[t],u[t]).to_bits(),"round {round} nt {nt} row {r} token {t}");} - } - } - } - } -} +mod tests; + +mod impl_default_for_nativeactivation; +#[allow(unused_imports)] +pub(super) use impl_default_for_nativeactivation::group_dot; +#[allow(unused_imports)] +pub(super) use impl_default_for_nativeactivation::group_dot_bytes; +#[allow(unused_imports)] +use impl_default_for_nativeactivation::group_dot_policy; +#[allow(unused_imports)] +pub(super) use impl_default_for_nativeactivation::gu_multi_route; +#[allow(unused_imports)] +pub use impl_default_for_nativeactivation::native_down_rows; +#[allow(unused_imports)] +pub use impl_default_for_nativeactivation::native_gu_rows; +mod group_dot_bytes_policy_fn; +#[allow(unused_imports)] +use group_dot_bytes_policy_fn::group_dot_bytes_policy; +#[allow(unused_imports)] +pub use group_dot_bytes_policy_fn::iq_gu_rows; +#[allow(unused_imports)] +pub use group_dot_bytes_policy_fn::iq_rows; +#[allow(unused_imports)] +pub use group_dot_bytes_policy_fn::kq_rows; +mod iq4nl_rows_fn; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::cpu_avx2_ok; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::cpu_avx512_ok; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::iq_supported; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::iq4nl_rows; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::kq_gu_rows; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::kq_supported; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::native_experts_available; +#[allow(unused_imports)] +pub use iq4nl_rows_fn::q2_rows; diff --git a/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy_fn.rs b/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy_fn.rs new file mode 100644 index 00000000..a3c219cc --- /dev/null +++ b/crates/native-cpu-expert/src/rust_native_general/group_dot_bytes_policy_fn.rs @@ -0,0 +1,255 @@ +//! Moved out of the parent module by STRA-338: fn group_dot_bytes_policy, fn kq_rows, fn iq_rows, fn iq_gu_rows. + +#[allow(unused_imports)] +use super::*; + +pub(super) unsafe fn group_dot_bytes_policy( + kind: Kind, + row: &[u8], + n: usize, + act: &[&[u8]], + out: &mut [f32], + d: &super::super::rust_simd::Dispatch, + gu: bool, + policy_nt: usize, +) { + unsafe { + let nt = act.len(); + let k = kind.original_id(); + static KQ: std::sync::OnceLock = std::sync::OnceLock::new(); + let kq = *KQ + .get_or_init(|| std::env::var("STRATA_KQ256").ok().is_some_and(|s| super::super::rust_simd::atoi(&s) != 0)); + if kq && policy_nt >= 2 && ((gu && k == 12) || (!gu && matches!(k, 7 | 8))) { + if k == 12 { + let mut a = [&[][..]; 8]; + for t in 0..nt { + a[t] = std::slice::from_raw_parts(act[t].as_ptr().cast::(), n / 256); + } + super::super::rust_kq::q4_k_dot(row, &a[..nt], out); + } else if k == 7 { + let mut a: [&[Q8One]; 8] = [&[]; 8]; + for t in 0..nt { + a[t] = std::slice::from_raw_parts(act[t].as_ptr().cast(), n / 32); + } + super::super::rust_kq::q5_one_dot(row, &a[..nt], out); + } else { + let mut a: [&[Q8Zero]; 8] = [&[]; 8]; + for t in 0..nt { + a[t] = std::slice::from_raw_parts(act[t].as_ptr().cast(), n / 32); + } + super::super::rust_kq::q8_zero_dot(row, &a[..nt], out); + } + return; + } + if gu && let Some(wide) = gu_multi_route(k, policy_nt as i32, d) { + let mut a: [&[Q8K]; 8] = [&[]; 8]; + for t in 0..nt { + a[t] = std::slice::from_raw_parts(act[t].as_ptr().cast(), n / 256); + } + if wide { + super::super::rust_iq::dot_multi512(k, row, &a[..nt], out); + } else { + super::super::rust_iq::dot_multi256(k, row, &a[..nt], out); + } + return; + } + if !gu && (policy_nt as i32) >= d.mt_min && k == 20 && d.iq4nl { + let mut a: [&[Q8Zero]; 8] = [&[]; 8]; + for t in 0..nt { + a[t] = std::slice::from_raw_parts(act[t].as_ptr().cast(), n / 32); + } + super::super::rust_iq::iq4nl(row, &a[..nt], out, false); + return; + } + for t in 0..nt { + out[t] = super::super::rust_ggml::dot_raw(kind, row, n, act[t]); + } + } +} +/// The explicit Original kq256 benchmark API is independent of its env policy. +pub fn kq_rows( + kind: Kind, + weights: &[u8], + width: usize, + act: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + if !matches!(kind, Kind::Q4K | Kind::Q5One | Kind::Q8Zero) + || act.is_empty() + || act.len() > i32::MAX as usize + || act.len() != out.len() + || r0 > r1 + { + return Err(Error::Shape); + } + let stride = kind.row_bytes(width)?; + if stride == 0 + || weights.len() % stride != 0 + || r1 > weights.len() / stride + || out.iter().any(|o| o.len() != weights.len() / stride) + { + return Err(Error::Shape); + } + for a in act { + a.check(kind, width)?; + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } /* SAFETY: module header; avx2_ok() checked above, check(kind,width) pinned every activation, row extents are r*stride slices. */ + unsafe { + for base in (0..act.len()).step_by(8) { + let act = &act[base..(base + 8).min(act.len())]; + for r in r0..r1 { + let row = &weights[r * stride..(r + 1) * stride]; + let mut v = [0.0; 8]; + match kind { + Kind::Q4K => { + let mut a: [&[Q8K]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), width / 256); + } + super::super::rust_kq::q4_k_dot(row, &a[..act.len()], &mut v[..act.len()]); + } + Kind::Q5One => { + let mut a: [&[Q8One]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), width / 32); + } + super::super::rust_kq::q5_one_dot(row, &a[..act.len()], &mut v[..act.len()]); + } + Kind::Q8Zero => { + let mut a: [&[Q8Zero]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), width / 32); + } + super::super::rust_kq::q8_zero_dot(row, &a[..act.len()], &mut v[..act.len()]); + } + _ => unreachable!(), + } + for t in 0..act.len() { + out[base + t][r] = v[t]; + } + } + } + } + Ok(()) +} + +/// Explicit Original IQ256/IQ512 benchmark entry, independent of MT/env policy. +pub fn iq_rows( + kind: Kind, + weights: &[u8], + width: usize, + act: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, + avx512: bool, +) -> Result<()> { + if !matches!(kind.original_id(), 16 | 17 | 18 | 21 | 22) + || width == 0 + || act.is_empty() + || act.len() > i32::MAX as usize + || act.len() != out.len() + || r0 > r1 + { + return Err(Error::Shape); + } + let stride = kind.row_bytes(width)?; + if weights.len() % stride != 0 + || r1 > weights.len() / stride + || out.iter().any(|v| v.len() != weights.len() / stride) + { + return Err(Error::Shape); + } + for a in act { + a.check(kind, width)?; + } + if !super::super::rust_simd::avx2_ok() + || avx512 && (!super::super::rust_simd::avx512_ok() || !super::super::rust_simd::dq_ok()) + { + return Err(Error::Unsupported); + } + /* SAFETY: module header; avx2_ok() (and avx512_ok()+dq_ok() when `avx512`) checked above; width % 256 == 0 via row_bytes(). */ + unsafe { + for base in (0..act.len()).step_by(8) { + let act = &act[base..(base + 8).min(act.len())]; + let mut a: [&[Q8K]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), width / 256); + } + for r in r0..r1 { + let row = &weights[r * stride..(r + 1) * stride]; + let mut v = [0.0; 8]; + if avx512 { + super::super::rust_iq::dot_multi512(kind.original_id(), row, &a[..act.len()], &mut v[..act.len()]); + } else { + super::super::rust_iq::dot_multi256(kind.original_id(), row, &a[..act.len()], &mut v[..act.len()]); + } + for t in 0..act.len() { + out[base + t][r] = v[t]; + } + } + } + } + Ok(()) +} +pub fn iq_gu_rows( + f: &NativeFormat, + blob: &[u8], + act: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, + avx512: bool, +) -> Result<()> { + f.validate()?; + if !matches!(f.gu.original_id(), 16 | 17 | 18 | 21 | 22) + || blob.len() != f.bytes + || act.is_empty() + || act.len() > i32::MAX as usize + || act.len() != out.len() + || r0 > r1 + || r1 > f.n_ff + || out.iter().any(|v| v.len() != f.n_ff) + { + return Err(Error::Shape); + } + for a in act { + a.check(f.gu, f.n_embd)?; + } + if !super::super::rust_simd::avx2_ok() + || avx512 && (!super::super::rust_simd::avx512_ok() || !super::super::rust_simd::dq_ok()) + { + return Err(Error::Unsupported); + } + /* SAFETY: module header; gates checked above; f.validate() pinned n_embd % 256 == 0 for these kinds. */ + unsafe { + for base in (0..act.len()).step_by(8) { + let act = &act[base..(base + 8).min(act.len())]; + let mut a: [&[Q8K]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), f.n_embd / 256); + } + for r in r0..r1 { + let g = &blob[r * f.gu_row..(r + 1) * f.gu_row]; + let u = &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row]; + let mut gv = [0.0; 8]; + let mut uv = gv; + if avx512 { + super::super::rust_iq::dot_multi512(f.gu.original_id(), g, &a[..act.len()], &mut gv[..act.len()]); + super::super::rust_iq::dot_multi512(f.gu.original_id(), u, &a[..act.len()], &mut uv[..act.len()]); + } else { + super::super::rust_iq::dot_multi256(f.gu.original_id(), g, &a[..act.len()], &mut gv[..act.len()]); + super::super::rust_iq::dot_multi256(f.gu.original_id(), u, &a[..act.len()], &mut uv[..act.len()]); + } + for t in 0..act.len() { + out[base + t][r] = super::super::rust_simd::silu(gv[t], uv[t]); + } + } + } + } + Ok(()) +} diff --git a/crates/native-cpu-expert/src/rust_native_general/impl_default_for_nativeactivation.rs b/crates/native-cpu-expert/src/rust_native_general/impl_default_for_nativeactivation.rs new file mode 100644 index 00000000..e8808ae0 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_native_general/impl_default_for_nativeactivation.rs @@ -0,0 +1,196 @@ +//! Moved out of the parent module by STRA-338: impl Default_for_NativeActivation, impl NativeActivation, fn native_gu_rows, fn native_down_rows, fn gu_multi_route, fn group_dot .... + +#[allow(unused_imports)] +use super::*; + +impl Default for NativeActivation { + fn default() -> Self { + Self { bytes: [0; BYTES], n: 0, kind: Kind::F32 } + } +} +impl NativeActivation { + pub fn quantize(&mut self, kind: Kind, input: &[f32]) -> Result<()> { + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + let bytes = kind.activation_bytes(input.len())?; + if input.is_empty() || bytes > BYTES { + return Err(Error::Shape); + } /* SAFETY: avx2_ok() above; `bytes == activation_bytes(len) <= BYTES`, and `self.bytes` is at offset 0 of a 64-aligned repr(C) struct. */ + unsafe { + super::super::rust_ggml::quantize_raw(kind, input, &mut self.bytes[..bytes]); + } + self.kind = kind; + self.n = input.len(); + Ok(()) + } + pub fn encoded_bytes(&self) -> Result { + self.kind.activation_bytes(self.n) + } + pub(in super::super) fn check(&self, kind: Kind, n: usize) -> Result<()> { + if self.n != n || self.kind.activation_id() != kind.activation_id() { + return Err(Error::Shape); + } + Ok(()) + } + pub(in super::super) fn raw(&self) -> &[u8] { + &self.bytes + } +} +pub fn native_gu_rows( + f: &NativeFormat, + blob: &[u8], + act: &[&NativeActivation], + ff: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + f.validate()?; + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + if blob.len() != f.bytes + || act.is_empty() + || act.len() > i32::MAX as usize + || act.len() != ff.len() + || r0 > r1 + || r1 > f.n_ff + || ff.iter().any(|v| v.len() != f.n_ff) + { + return Err(Error::Shape); + } + for a in act { + a.check(f.gu, f.n_embd)?; + } + let d = super::super::rust_simd::dispatch(); + if d.iq512 + && (act.len() as i32) >= d.mt_min + && matches!(f.gu.original_id(), 16 | 17 | 18 | 21 | 22) + && !super::super::rust_simd::dq_ok() + { + return Err(Error::Unsupported); + } + for r in r0..r1 { + let gr = &blob[r * f.gu_row..(r + 1) * f.gu_row]; + let ur = &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row]; + for at in (0..act.len()).step_by(8) { + let end = (at + 8).min(act.len()); + let chunk = &act[at..end]; + let mut g = [0.0; 8]; + let mut u = [0.0; 8]; /* SAFETY: module header; avx2_ok() and (iq512 && dq_ok) checked above, gr/ur are whole rows of a validated blob. */ + unsafe { + group_dot_policy(f.gu, gr, chunk, &mut g[..chunk.len()], d, true, act.len()); + group_dot_policy(f.gu, ur, chunk, &mut u[..chunk.len()], d, true, act.len()); + } + for t in 0..chunk.len() { + ff[at + t][r] = super::super::rust_simd::silu(g[t], u[t]); + } + } + } + Ok(()) +} +pub fn native_down_rows( + f: &NativeFormat, + blob: &[u8], + hq: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + f.validate()?; + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + if blob.len() != f.bytes + || hq.is_empty() + || hq.len() > i32::MAX as usize + || hq.len() != out.len() + || r0 > r1 + || r1 > f.n_embd + || out.iter().any(|v| v.len() != f.n_embd) + { + return Err(Error::Shape); + } + for a in hq { + a.check(f.down, f.n_ff)?; + } + let d = super::super::rust_simd::dispatch(); + for r in r0..r1 { + let row = &blob[f.down_offset + r * f.down_row..f.down_offset + (r + 1) * f.down_row]; + for at in (0..hq.len()).step_by(8) { + let end = (at + 8).min(hq.len()); + let chunk = &hq[at..end]; + let mut v = [0.0; 8]; /* SAFETY: module header; avx2_ok() checked above, `row` is a whole down row of a validated blob. */ + unsafe { + group_dot_policy(f.down, row, chunk, &mut v[..chunk.len()], d, false, hq.len()); + } + for t in 0..chunk.len() { + out[at + t][r] = v[t]; + } + } + } + Ok(()) +} +/// Multi-token gate/up kernel choice of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`): +/// Some(true) = the 512-bit kernel, Some(false) = the 256-bit one, None = ggml's per-token dot. IQ4_XS (23) has only the 256-bit kernel and +/// takes it on an AVX2-only tree (STRA-329: this site omitted it, rust_pool.rs `f.gu==23&&!d.avx512` has it since STRA-324). +pub(in super::super) fn gu_multi_route(k: i32, policy_nt: i32, d: &super::super::rust_simd::Dispatch) -> Option { + if policy_nt < d.mt_min { + return None; + } + let wide = matches!(k, 16 | 17 | 18 | 21 | 22); + if wide && d.iq512 { + return Some(true); + } + if (wide || k == 23 && !d.avx512) && d.iq256 { + return Some(false); + } + None +} +// Inputs are genuine initialized banks admitted above, never external cast handles. +pub(in super::super) unsafe fn group_dot( + kind: Kind, + row: &[u8], + act: &[&NativeActivation], + out: &mut [f32], + d: &super::super::rust_simd::Dispatch, + gu: bool, +) { + unsafe { + let mut raw: [&[u8]; 8] = [&[]; 8]; + for t in 0..act.len() { + raw[t] = act[t].raw(); + } + group_dot_bytes(kind, row, act[0].n, &raw[..act.len()], out, d, gu) + } +} +pub(in super::super) unsafe fn group_dot_bytes( + kind: Kind, + row: &[u8], + n: usize, + act: &[&[u8]], + out: &mut [f32], + d: &super::super::rust_simd::Dispatch, + gu: bool, +) { + unsafe { + group_dot_bytes_policy(kind, row, n, act, out, d, gu, act.len()); + } +} +pub(super) unsafe fn group_dot_policy( + kind: Kind, + row: &[u8], + act: &[&NativeActivation], + out: &mut [f32], + d: &super::super::rust_simd::Dispatch, + gu: bool, + policy_nt: usize, +) { + unsafe { + let mut raw: [&[u8]; 8] = [&[]; 8]; + for t in 0..act.len() { + raw[t] = act[t].raw(); + } + group_dot_bytes_policy(kind, row, act[0].n, &raw[..act.len()], out, d, gu, policy_nt) + } +} diff --git a/crates/native-cpu-expert/src/rust_native_general/iq4nl_rows_fn.rs b/crates/native-cpu-expert/src/rust_native_general/iq4nl_rows_fn.rs new file mode 100644 index 00000000..22ec5f98 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_native_general/iq4nl_rows_fn.rs @@ -0,0 +1,187 @@ +//! Moved out of the parent module by STRA-338: fn iq4nl_rows, fn native_experts_available, fn kq_supported, fn iq_supported, fn cpu_avx2_ok, fn cpu_avx512_ok .... + +#[allow(unused_imports)] +use super::*; + +pub fn iq4nl_rows( + weights: &[u8], + width: usize, + act: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + if width == 0 || act.is_empty() || act.len() > i32::MAX as usize || act.len() != out.len() || r0 > r1 { + return Err(Error::Shape); + } + let stride = Kind::Iq4Nl.row_bytes(width)?; + if weights.len() % stride != 0 + || r1 > weights.len() / stride + || out.iter().any(|v| v.len() != weights.len() / stride) + { + return Err(Error::Shape); + } + for a in act { + a.check(Kind::Iq4Nl, width)?; + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + /* SAFETY: module header; avx2_ok() checked above; width % 32 == 0 via row_bytes(). */ + unsafe { + for base in (0..act.len()).step_by(8) { + let act = &act[base..(base + 8).min(act.len())]; + let mut a: [&[Q8Zero]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), width / 32); + } + for r in r0..r1 { + let mut v = [0.0; 8]; + super::super::rust_iq::iq4nl( + &weights[r * stride..(r + 1) * stride], + &a[..act.len()], + &mut v[..act.len()], + false, + ); + for t in 0..act.len() { + out[base + t][r] = v[t]; + } + } + } + } + Ok(()) +} + +/// Original header capability predicates. Numerical owners still admit actual +/// CPU capability before entering their instruction leaves. +pub fn native_experts_available() -> bool { + true +} +pub fn kq_supported(kind: Kind) -> bool { + matches!(kind, Kind::Q4K | Kind::Q5One | Kind::Q8Zero) +} +pub fn iq_supported(kind: Kind) -> bool { + matches!(kind.original_id(), 16 | 17 | 18 | 21 | 22) +} +pub fn cpu_avx2_ok() -> bool { + super::super::rust_simd::avx2_ok() +} +pub fn cpu_avx512_ok() -> bool { + super::super::rust_simd::avx512_ok() +} + +/// Original explicit KQ gate/up entry, independent of STRATA_KQ256. +pub fn kq_gu_rows( + f: &NativeFormat, + blob: &[u8], + act: &[&NativeActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + f.validate()?; + if !kq_supported(f.gu) + || blob.len() != f.bytes + || act.is_empty() + || act.len() > i32::MAX as usize + || act.len() != out.len() + || r0 > r1 + || r1 > f.n_ff + || out.iter().any(|o| o.len() != f.n_ff) + { + return Err(Error::Shape); + } + for a in act { + a.check(f.gu, f.n_embd)?; + } + if !super::super::rust_simd::avx2_ok() { + return Err(Error::Unsupported); + } + /* SAFETY: module header; avx2_ok() checked above; f.validate() pinned the geometry and blob.len()==f.bytes. */ + unsafe { + for base in (0..act.len()).step_by(8) { + let act = &act[base..(base + 8).min(act.len())]; + for r in r0..r1 { + let mut g = [0.0; 8]; + let mut u = g; + for (role, values) in [(0, &mut g), (f.up_offset, &mut u)] { + let row = &blob[role + r * f.gu_row..role + (r + 1) * f.gu_row]; + match f.gu { + Kind::Q4K => { + let mut a: [&[Q8K]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), f.n_embd / 256); + } + super::super::rust_kq::q4_k_dot(row, &a[..act.len()], &mut values[..act.len()]); + } + Kind::Q5One => { + let mut a: [&[Q8One]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), f.n_embd / 32); + } + super::super::rust_kq::q5_one_dot(row, &a[..act.len()], &mut values[..act.len()]); + } + Kind::Q8Zero => { + let mut a: [&[Q8Zero]; 8] = [&[]; 8]; + for t in 0..act.len() { + a[t] = std::slice::from_raw_parts(act[t].raw().as_ptr().cast(), f.n_embd / 32); + } + super::super::rust_kq::q8_zero_dot(row, &a[..act.len()], &mut values[..act.len()]); + } + _ => unreachable!(), + } + } + for t in 0..act.len() { + out[base + t][r] = super::super::rust_simd::silu(g[t], u[t]); + } + } + } + } + Ok(()) +} + +/// Original q2_rows_any dispatch on a genuine initialized Planar activation. +pub fn q2_rows( + weights: &[u8], + width: usize, + act: &[&super::super::rust_legacy::PlanarActivation], + out: &mut [&mut [f32]], + r0: usize, + r1: usize, +) -> Result<()> { + if width == 0 || width > super::super::H || act.is_empty() || act.len() > 8 || act.len() != out.len() || r0 > r1 { + return Err(Error::Shape); + } + let stride = Kind::Q2Zero.row_bytes(width)?; + if weights.len() % stride != 0 + || r1 > weights.len() / stride + || out.iter().any(|o| o.len() != weights.len() / stride) + || act.iter().any(|a| a.0.nchunks != (width / 32) as i32) + { + return Err(Error::Shape); + } + if !super::super::rust_simd::avx2_ok() || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok() + { + return Err(Error::Unsupported); + } + let empty = super::super::rust_types::ActQ::default(); + let mut a = [∅ 8]; + for t in 0..act.len() { + a[t] = &act[t].0; + } + let mut values = [0.0; 8]; /* SAFETY: avx2_ok() (+dq_ok() if avx512_ok()) checked above; rows are `stride = width/64*18 <= 720` bytes (width <= H) and act.len() <= 8 (see rust_q2 bounds). */ + unsafe { + for r in r0..r1 { + let row = &weights[r * stride..(r + 1) * stride]; + if super::super::rust_simd::avx512_ok() { + super::super::rust_q2::dot512(row, &a[..act.len()], &mut values[..act.len()]); + } else { + super::super::rust_q2::dot256(row, &a[..act.len()], &mut values[..act.len()]); + } + for t in 0..act.len() { + out[t][r] = values[t]; + } + } + } + Ok(()) +} diff --git a/crates/native-cpu-expert/src/rust_native_general/tests.rs b/crates/native-cpu-expert/src/rust_native_general/tests.rs new file mode 100644 index 00000000..e0a70abd --- /dev/null +++ b/crates/native-cpu-expert/src/rust_native_general/tests.rs @@ -0,0 +1,119 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::super::rust_simd::{Dispatch, avx2_ok, avx512_ok}; +use super::*; +fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s +} +fn dispatch_of(iq512: bool, iq256: bool, avx512: bool) -> Dispatch { + Dispatch { iq512, iq256, iq4nl: true, mt_min: 2, gather: false, prefetch: 0, avx512 } +} +// native_expert.cpp native_gu_rows: `nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`, then AVX-512 kernel first, else AVX2. +#[test] +fn gu_multi_route_follows_native_gu_rows() { + let avx2_tree = dispatch_of(false, true, false); + let avx512_tree = dispatch_of(true, true, true); + let no_iq512 = dispatch_of(false, true, true); + let no_iq256 = dispatch_of(true, false, true); + let no_iq256_avx2 = dispatch_of(false, false, false); + for k in [16, 17, 18, 21, 22] { + assert_eq!(gu_multi_route(k, 2, &avx2_tree), Some(false), "k {k} avx2 tree"); + assert_eq!(gu_multi_route(k, 1, &avx2_tree), None, "k {k} one token is ggml's dot"); + assert_eq!(gu_multi_route(k, 3, &avx512_tree), Some(true), "k {k} avx512 tree"); + assert_eq!(gu_multi_route(k, 3, &no_iq512), Some(false), "k {k} STRATA_NO_IQ512"); + assert_eq!(gu_multi_route(k, 3, &no_iq256), Some(true), "k {k} STRATA_NO_IQ256 keeps the 512-bit kernel"); + assert_eq!(gu_multi_route(k, 3, &no_iq256_avx2), None); + } + // IQ4_XS: the 256-bit kernel only, and only where there is no AVX-512 CPU (an AVX-512 CPU keeps ggml's dot for it). + assert_eq!(gu_multi_route(23, 2, &avx2_tree), Some(false)); + assert_eq!(gu_multi_route(23, 8, &avx2_tree), Some(false)); + assert_eq!(gu_multi_route(23, 1, &avx2_tree), None); + assert_eq!(gu_multi_route(23, 3, &avx512_tree), None); + assert_eq!(gu_multi_route(23, 3, &no_iq512), None); + assert_eq!(gu_multi_route(23, 3, &no_iq256_avx2), None); + for k in [2, 12, 20, 42] { + assert_eq!(gu_multi_route(k, 4, &avx2_tree), None, "k {k} has no multi-token IQ kernel"); + } +} +// Differential: native_gu_rows with an IQ4_XS gate/up at 2..8 tokens on the AVX2 tree == the multi-token kernel row by row. +// The tree is chosen once per process (OnceLock), so on an AVX-512 CPU the test re-runs itself in a child with STRATA_FORCE_AVX2=1. +#[test] +fn iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel() { + if !avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + if avx512_ok() { + assert!( + std::env::var_os("LELEKA_TEST_AVX2_CHILD").is_none(), + "STRATA_FORCE_AVX2=1 did not select the AVX2 tree" + ); + let path = module_path!(); + let path = &path[path.find("::").unwrap() + 2..]; + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + &format!("{path}::iq4xs_gate_up_at_two_or_more_tokens_takes_the_avx2_multi_token_kernel"), + "--nocapture", + ]) + .env("STRATA_FORCE_AVX2", "1") + .env("LELEKA_TEST_AVX2_CHILD", "1") + .status() + .unwrap(); + assert!(status.success(), "child run on the AVX2 tree failed"); + return; + } + let (n_embd, n_ff) = (512usize, 32usize); + let f = NativeFormat::new(Kind::Iq4Xs, Kind::Iq4Nl, n_embd, n_ff).unwrap(); + let mut seed = 0x5eed_0329_abcd_ef01u64; + for round in 0..3 { + let mut blob = vec![0u8; f.bytes]; + for v in blob.iter_mut() { + *v = xorshift(&mut seed) as u8; + } + for b in blob[..f.down_offset].chunks_exact_mut(136) { + let e = 8 + (xorshift(&mut seed) % 8) as u16; + let m = (xorshift(&mut seed) & 0x3ff) as u16; + b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + } + for nt in [2usize, 3, 5, 8] { + let mut acts: Vec = (0..nt).map(|_| NativeActivation::default()).collect(); + for a in acts.iter_mut() { + let x: Vec = (0..n_embd) + .map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * (0.001 + round as f32)) + .collect(); + a.quantize(Kind::Iq4Xs, &x).unwrap(); + } + let refs: Vec<&NativeActivation> = acts.iter().collect(); + let mut ff = vec![vec![0.0f32; n_ff]; nt]; + { + let mut outs: Vec<&mut [f32]> = ff.iter_mut().map(|v| v.as_mut_slice()).collect(); + native_gu_rows(&f, &blob, &refs, &mut outs, 0, n_ff).unwrap(); + } + let ys:Vec<&[Q8K]>=acts.iter().map(|a|/* SAFETY: quantize(Iq4Xs, n_embd) wrote n_embd/256 Q8K blocks at offset 0 of the 64-aligned activation. */unsafe{std::slice::from_raw_parts(a.raw().as_ptr().cast::(),n_embd/256)}).collect(); + for r in 0..n_ff { + let (mut g, mut u) = ([0.0f32; 8], [0.0f32; 8]); + // SAFETY: avx2_ok() above; rows are whole IQ4_XS rows of the validated blob and every activation has n_embd/256 blocks. + unsafe { + super::super::rust_iq::dot_multi256(23, &blob[r * f.gu_row..(r + 1) * f.gu_row], &ys, &mut g[..nt]); + super::super::rust_iq::dot_multi256( + 23, + &blob[f.up_offset + r * f.gu_row..f.up_offset + (r + 1) * f.gu_row], + &ys, + &mut u[..nt], + ); + } + for t in 0..nt { + assert_eq!( + ff[t][r].to_bits(), + super::super::rust_simd::silu(g[t], u[t]).to_bits(), + "round {round} nt {nt} row {r} token {t}" + ); + } + } + } + } +} diff --git a/crates/native-cpu-expert/src/rust_platform.rs b/crates/native-cpu-expert/src/rust_platform.rs index 22e9e4d4..01b1926d 100644 --- a/crates/native-cpu-expert/src/rust_platform.rs +++ b/crates/native-cpu-expert/src/rust_platform.rs @@ -1,69 +1,150 @@ //! Linux x86_64 Original topology, affinity and actual stack admission. -use super::{Error,Result}; -#[repr(C)]struct Limit{current:u64,max:u64} -#[repr(C,align(8))]struct Attr{words:[usize;7]} +use super::{Error, Result}; +#[repr(C)] +struct Limit { + current: u64, + max: u64, +} +#[repr(C, align(8))] +struct Attr { + words: [usize; 7], +} unsafe extern "C" { - fn getrlimit(resource:i32,limit:*mut Limit)->i32; - fn pthread_getattr_default_np(attr:*mut Attr)->i32; - fn pthread_attr_getstacksize(attr:*const Attr,size:*mut usize)->i32; - fn pthread_attr_destroy(attr:*mut Attr)->i32; - fn sched_getaffinity(pid:i32,bytes:usize,set:*mut usize)->i32; - fn pthread_self()->usize; - fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32; - fn pthread_getaffinity_np(thread:usize,bytes:usize,set:*mut usize)->i32; - fn sysconf(name:i32)->i64; - fn madvise(addr:*mut u8,len:usize,advice:i32)->i32; + fn getrlimit(resource: i32, limit: *mut Limit) -> i32; + fn pthread_getattr_default_np(attr: *mut Attr) -> i32; + fn pthread_attr_getstacksize(attr: *const Attr, size: *mut usize) -> i32; + fn pthread_attr_destroy(attr: *mut Attr) -> i32; + fn sched_getaffinity(pid: i32, bytes: usize, set: *mut usize) -> i32; + fn pthread_self() -> usize; + fn pthread_setaffinity_np(thread: usize, bytes: usize, set: *const usize) -> i32; + fn pthread_getaffinity_np(thread: usize, bytes: usize, set: *mut usize) -> i32; + fn sysconf(name: i32) -> i64; + fn madvise(addr: *mut u8, len: usize, advice: i32) -> i32; } -pub(super) fn stack_size()->Result { - #[cfg(not(target_env="gnu"))] {return Err(Error::Unsupported);} - // SAFETY: `limit`/`attr`/`size` are live, writable locals of the exact glibc layouts (struct rlimit = 2*u64, - // pthread_attr_t = 56 bytes, align 8); the attr is destroyed exactly once, only after a successful getattr. - #[cfg(target_env="gnu")] unsafe { - let mut limit=Limit{current:0,max:0};if getrlimit(3,&mut limit)!=0||limit.current==0||limit.current==u64::MAX||limit.current>8*1024*1024{return Err(Error::Unsupported);} - let mut attr=Attr{words:[0;7]};if pthread_getattr_default_np(&mut attr)!=0{return Err(Error::Unsupported);} - let mut size=0;let query=pthread_attr_getstacksize(&attr,&mut size);let release=pthread_attr_destroy(&mut attr); - if query!=0||release!=0||size==0||size>8*1024*1024{Err(Error::Unsupported)}else{Ok(size)} - } +pub(super) fn stack_size() -> Result { + #[cfg(not(target_env = "gnu"))] + { + return Err(Error::Unsupported); + } + // SAFETY: `limit`/`attr`/`size` are live, writable locals of the exact glibc layouts (struct rlimit = 2*u64, + // pthread_attr_t = 56 bytes, align 8); the attr is destroyed exactly once, only after a successful getattr. + #[cfg(target_env = "gnu")] + unsafe { + let mut limit = Limit { current: 0, max: 0 }; + if getrlimit(3, &mut limit) != 0 + || limit.current == 0 + || limit.current == u64::MAX + || limit.current > 8 * 1024 * 1024 + { + return Err(Error::Unsupported); + } + let mut attr = Attr { words: [0; 7] }; + if pthread_getattr_default_np(&mut attr) != 0 { + return Err(Error::Unsupported); + } + let mut size = 0; + let query = pthread_attr_getstacksize(&attr, &mut size); + let release = pthread_attr_destroy(&mut attr); + if query != 0 || release != 0 || size == 0 || size > 8 * 1024 * 1024 { + Err(Error::Unsupported) + } else { + Ok(size) + } + } } -fn read_cpu(cpu:i32,key:&str)->i64 {std::fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/{key}")).ok().and_then(|s|s.split_whitespace().next()?.parse().ok()).unwrap_or(-1)} -pub(super) fn cores(skip_first:bool)->Vec { - let mut set=[0usize;16];let mut allowed=Vec::new(); - // SAFETY: initialized Linux cpu_set_t-sized mask, no pointer retention. - if unsafe {sched_getaffinity(0,std::mem::size_of_val(&set),set.as_mut_ptr())}==0 {for i in 0..1024 {if set[i/64]&(1usize<<(i%64))!=0{allowed.push(i as i32);}}} - else {let n=unsafe {sysconf(84)};for i in 0..n.max(0){allowed.push(i as i32);}} - let mut seen=Vec::new();let mut physical=Vec::new();for cpu in allowed {let key=(read_cpu(cpu,"physical_package_id"),read_cpu(cpu,"core_id"));if key.0>=0&&key.1>=0 {if seen.contains(&key){continue;}seen.push(key);}physical.push(cpu);} - if skip_first&&!physical.is_empty(){physical.remove(0);}physical +fn read_cpu(cpu: i32, key: &str) -> i64 { + std::fs::read_to_string(format!("/sys/devices/system/cpu/cpu{cpu}/topology/{key}")) + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .unwrap_or(-1) +} +pub(super) fn cores(skip_first: bool) -> Vec { + let mut set = [0usize; 16]; + let mut allowed = Vec::new(); + // SAFETY: initialized Linux cpu_set_t-sized mask, no pointer retention. + if unsafe { sched_getaffinity(0, std::mem::size_of_val(&set), set.as_mut_ptr()) } == 0 { + for i in 0..1024 { + if set[i / 64] & (1usize << (i % 64)) != 0 { + allowed.push(i as i32); + } + } + } else { + let n = unsafe { sysconf(84) }; + for i in 0..n.max(0) { + allowed.push(i as i32); + } + } + let mut seen = Vec::new(); + let mut physical = Vec::new(); + for cpu in allowed { + let key = (read_cpu(cpu, "physical_package_id"), read_cpu(cpu, "core_id")); + if key.0 >= 0 && key.1 >= 0 { + if seen.contains(&key) { + continue; + } + seen.push(key); + } + physical.push(cpu); + } + if skip_first && !physical.is_empty() { + physical.remove(0); + } + physical } /// `madvise(MADV_WILLNEED)` over the pages of `bytes`: the kernel starts reading a file-mapped range in the /// background (expert_source.cpp `warm`). Advice only; a failure changes nothing. /// `madvise(MADV_WILLNEED)` over `[addr, addr+len)` rounded out to pages: advice only, it never reads or /// writes the range, so any address is memory-safe (an unmapped range just fails). -pub fn advise_will_need(addr:usize,len:usize) { - if len==0{return;} - let page=4096usize;let start=addr&!(page-1);let Some(end)=addr.checked_add(len) else {return}; - // SAFETY: MADV_WILLNEED (3) only schedules readahead; it accesses no memory of this process. - unsafe {let _=madvise(start as *mut u8,end-start,3);} +pub fn advise_will_need(addr: usize, len: usize) { + if len == 0 { + return; + } + let page = 4096usize; + let start = addr & !(page - 1); + let Some(end) = addr.checked_add(len) else { return }; + // SAFETY: MADV_WILLNEED (3) only schedules readahead; it accesses no memory of this process. + unsafe { + let _ = madvise(start as *mut u8, end - start, 3); + } } -pub(super) fn will_need(bytes:&[u8]) { - if bytes.is_empty(){return;} - let page=4096usize;let start=bytes.as_ptr() as usize&!(page-1);let end=bytes.as_ptr() as usize+bytes.len(); - // SAFETY: advice over pages that contain the caller's live borrowed range; MADV_WILLNEED (3) never - // changes the contents or the mapping. - unsafe {let _=madvise(start as *mut u8,end-start,3);} +pub(super) fn will_need(bytes: &[u8]) { + if bytes.is_empty() { + return; + } + let page = 4096usize; + let start = bytes.as_ptr() as usize & !(page - 1); + let end = bytes.as_ptr() as usize + bytes.len(); + // SAFETY: advice over pages that contain the caller's live borrowed range; MADV_WILLNEED (3) never + // changes the contents or the mapping. + unsafe { + let _ = madvise(start as *mut u8, end - start, 3); + } } /// The calling thread's affinity mask (to restore after `pin`). -pub(super) fn current_affinity()->Option<[usize;16]> { - let mut set=[0usize;16]; - // SAFETY: initialized cpu_set_t-sized mask of the calling thread, no pointer retention. - (unsafe {pthread_getaffinity_np(pthread_self(),std::mem::size_of_val(&set),set.as_mut_ptr())}==0).then_some(set) +pub(super) fn current_affinity() -> Option<[usize; 16]> { + let mut set = [0usize; 16]; + // SAFETY: initialized cpu_set_t-sized mask of the calling thread, no pointer retention. + (unsafe { pthread_getaffinity_np(pthread_self(), std::mem::size_of_val(&set), set.as_mut_ptr()) } == 0) + .then_some(set) } -pub(super) fn restore_affinity(set:&[usize;16]) { - // SAFETY: as `pin`; a refusal leaves the thread where it is. - unsafe {let _=pthread_setaffinity_np(pthread_self(),std::mem::size_of_val(set),set.as_ptr());} +pub(super) fn restore_affinity(set: &[usize; 16]) { + // SAFETY: as `pin`; a refusal leaves the thread where it is. + unsafe { + let _ = pthread_setaffinity_np(pthread_self(), std::mem::size_of_val(set), set.as_ptr()); + } } -pub(super) fn pin(core:i32) { - if core<0{return;}let mut set=[0usize;16];if core as usize>=1024{return;}set[core as usize/64]|=1usize<<(core as usize%64); - // Original intentionally ignores OS affinity refusal; it does not change math. - // SAFETY: `set` is a live 128-byte cpu_set_t-sized mask for the calling thread; no pointer is retained. - unsafe {let _=pthread_setaffinity_np(pthread_self(),std::mem::size_of_val(&set),set.as_ptr());} +pub(super) fn pin(core: i32) { + if core < 0 { + return; + } + let mut set = [0usize; 16]; + if core as usize >= 1024 { + return; + } + set[core as usize / 64] |= 1usize << (core as usize % 64); + // Original intentionally ignores OS affinity refusal; it does not change math. + // SAFETY: `set` is a live 128-byte cpu_set_t-sized mask for the calling thread; no pointer is retained. + unsafe { + let _ = pthread_setaffinity_np(pthread_self(), std::mem::size_of_val(&set), set.as_ptr()); + } } diff --git a/crates/native-cpu-expert/src/rust_platform_win.rs b/crates/native-cpu-expert/src/rust_platform_win.rs index cd428529..200f79f6 100644 --- a/crates/native-cpu-expert/src/rust_platform_win.rs +++ b/crates/native-cpu-expert/src/rust_platform_win.rs @@ -26,7 +26,8 @@ pub(super) fn stack_size() -> Result { fn process_mask() -> Option { let (mut process, mut system) = (0usize, 0usize); // SAFETY: the current-process pseudo handle and two writable words. - (unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut process, &mut system) } != 0 && process != 0).then_some(process) + (unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut process, &mut system) } != 0 && process != 0) + .then_some(process) } /// Pure: the first set bit of every group of sibling bits (`cores` are the per-physical-core masks), restricted to `allowed`. @@ -53,7 +54,8 @@ pub(super) fn physical_core_masks() -> Vec { return Vec::new(); } // SAFETY: an all-zero SYSTEM_LOGICAL_PROCESSOR_INFORMATION is a valid value (integers and a union of integers). - let mut buffer: Vec = (0..bytes as usize / entry).map(|_| unsafe { std::mem::zeroed() }).collect(); + let mut buffer: Vec = + (0..bytes as usize / entry).map(|_| unsafe { std::mem::zeroed() }).collect(); // SAFETY: `buffer` has exactly `bytes` writable bytes. if unsafe { GetLogicalProcessorInformation(buffer.as_mut_ptr(), &mut bytes) } == 0 { return Vec::new(); @@ -84,7 +86,8 @@ pub fn advise_will_need(addr: usize, len: usize) { let page = 4096usize; let start = addr & !(page - 1); let Some(end) = addr.checked_add(len) else { return }; - let mut range = WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: start as *mut core::ffi::c_void, NumberOfBytes: end - start }; + let mut range = + WIN32_MEMORY_RANGE_ENTRY { VirtualAddress: start as *mut core::ffi::c_void, NumberOfBytes: end - start }; // SAFETY: one live range entry; PrefetchVirtualMemory only schedules paging I/O for the current process. unsafe { let _ = PrefetchVirtualMemory(GetCurrentProcess(), 1, &mut range, 0); diff --git a/crates/native-cpu-expert/src/rust_pool.rs b/crates/native-cpu-expert/src/rust_pool.rs index 21467e84..ff263b2a 100644 --- a/crates/native-cpu-expert/src/rust_pool.rs +++ b/crates/native-cpu-expert/src/rust_pool.rs @@ -1,188 +1,97 @@ //! Persistent Original epoch/claim/park protocol over closed Rust-owned jobs. //! Unsafe sharing is restricted to admitted disjoint row cells. No raw owner escapes. -use std::{cell::UnsafeCell,sync::{Arc,Mutex,Condvar,atomic::{AtomicBool,AtomicU32,AtomicU64,Ordering}},thread,time::{Duration,Instant}}; -use super::{PreparedJob,Error,Result,H,FF,MAX_ROWS,MAX_JOBS}; -use super::rust_types::{ActQ,Q8K,SplitBuf,NativeFmt}; -use super::rust_simd::{dispatch,silu}; -#[repr(align(64))]struct Line(T); -#[repr(C,align(64))]struct NativeAct{q:[Q8K;10],padding:[u8;1176]} -impl Default for NativeAct{fn default()->Self{Self{q:[Q8K::default();10],padding:[0;1176]}}} -#[repr(C,align(64))]struct Scratch{a1:ActQ,a2:ActQ,ff:[f32;FF]} -impl Default for Scratch{fn default()->Self{Self{a1:ActQ::default(),a2:ActQ::default(),ff:[0.0;FF]}}} -#[repr(C)] -#[derive(Clone,Copy)]struct Job{gate:*const u8,up:*const u8,down:*const u8,rows:i32,act:[*const ActQ;MAX_ROWS],output:[*mut f32;MAX_ROWS],nact:[*const u8;MAX_ROWS]} -impl Default for Job{fn default()->Self{Self{gate:std::ptr::null(),up:std::ptr::null(),down:std::ptr::null(),rows:0,act:[std::ptr::null();MAX_ROWS],output:[std::ptr::null_mut();MAX_ROWS],nact:[std::ptr::null();MAX_ROWS]}}} -#[repr(C,align(64))]struct SingleSplit{ff:[f32;FF],a2:ActQ} -impl Default for SingleSplit{fn default()->Self{Self{ff:[0.0;FF],a2:ActQ::default()}}} -const _: ()=assert!(std::mem::size_of::()==224); -const _: ()=assert!(std::mem::size_of::()==9728); -const _: ()=assert!(std::mem::size_of::()==6144); -struct Batch{jobs:[Job;MAX_JOBS],format:NativeFmt,count:usize,mode:u32,rows:usize,tasks:usize} -struct Shared { - head:Line,done:Line,parked:Line,epoch:Line,stop:Line,sleepers:Line, - sleep_mu:Mutex<()>,sleep_cv:Condvar,spin:Duration,n:usize, - batch:UnsafeCell,act:Vec>,nact:Vec>,split:Vec>, - // Borrowed groups quantize every token once (expert_source.cpp act_multi/nact_multi), not once per job row. - tok_act:Vec>,tok_nact:Vec>, - // Keep the original per-worker scratch reservation even though native phases - // require only split storage; it remains owned until all worker joins complete. - _scratch:Vec,_single_split:Vec, +use super::rust_simd::{dispatch, silu}; +use super::rust_types::{ActQ, NativeFmt, Q8K, SplitBuf}; +use super::{Error, FF, H, MAX_JOBS, MAX_ROWS, PreparedJob, Result}; +use std::{ + cell::UnsafeCell, + sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}, + }, + thread, + time::{Duration, Instant}, +}; +#[repr(align(64))] +struct Line(T); +#[repr(C, align(64))] +struct NativeAct { + q: [Q8K; 10], + padding: [u8; 1176], } -// SAFETY: epoch release publishes immutable batch/operands. Every successful -// epoch-tagged CAS claims a disjoint global row interval. No row is accessed by -// another claim. Host mutates batch/activation storage only after done AND parked. -// Both waits are required: a delayed sleeper carries its OLD epoch into claim. -// `batch.jobs` holds raw pointers into CALLER memory that dangle between calls; they are dereferenced only after a -// successful claim of the epoch that published them, and `done == tasks` then `parked == n` precede every return. -// A panicking host is caught by ffi::NativePool, which drops (stops + joins) this pool before the borrows end; a -// panicking worker never reaches `done`, so the host aborts after 60 s instead of returning to the caller. -unsafe impl Sync for Shared {} -unsafe impl Send for Shared {} -/// `!any(|v| !v.is_finite())` as a branch-free exponent fold that vectorizes (`LELEKA_Q8K=legacy` keeps the element-wise scan). -fn all_finite(v:&[f32])->bool{if !super::rust_quant::q8k_fast(){return !v.iter().any(|x|!x.is_finite());}let mut bad=0u32;for c in v.chunks(256){let mut m=0u32;for x in c{m|=u32::from(x.to_bits()&0x7f80_0000==0x7f80_0000);}bad|=m;}bad==0} -fn allocated(n:usize)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,T::default);Ok(v)} -impl Shared { - fn publish(&self){self.epoch.0.fetch_add(1,Ordering::SeqCst);if self.sleepers.0.load(Ordering::SeqCst)!=0{let _lock=self.sleep_mu.lock().unwrap_or_else(|p|p.into_inner());self.sleep_cv.notify_all();}} - fn claim(&self,epoch:u32)->Option{let mut h=self.head.0.load(Ordering::Acquire);loop{if (h>>32)as u32!=epoch{return None;}let n=((h>>16)&0xffff)as usize;let i=(h&0xffff)as usize;if i>=n{return None;}match self.head.0.compare_exchange_weak(h,h+1,Ordering::AcqRel,Ordering::Acquire){Ok(_)=>return Some(i),Err(next)=>h=next}}} - fn drain(&self,epoch:u32){while let Some(i)=self.claim(epoch){ - // SAFETY: admission covers whole immutable blobs and output rows. The claim - // uniquely owns [g0,g1); batch remains alive through done+parked barriers. - unsafe {self.execute(i);}self.done.0.fetch_add(1,Ordering::Release); - }} - /// # Safety - /// The caller holds a successful epoch-tagged claim of task `i` (so `batch` is published and immutable, and every - /// gate/up/down/activation/output pointer in `batch.jobs[..count]` is live until the done+parked barriers). Task `i` owns - /// the row interval `[rows*i/tasks, rows*(i+1)/tasks)`; `rows == count*per` so `at/per < count` for every row. - unsafe fn execute(&self,i:usize){unsafe { - let b=&*self.batch.get();let per=match b.mode{5=>FF,6=>H,_=>2*FF+H};let mut at=b.rows*i/b.tasks;let end=b.rows*(i+1)/b.tasks; - while at()).q.as_slice();MAX_ROWS];for t in 0..nr{yy[t]=(&*j.nact[t].cast::()).q.as_slice();}let d=dispatch();if (nr as i32)>=d.mt_min&&matches!(f.gu,16|17|18|21|22)&&d.iq512{super::rust_iq::dot_multi512(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi512(f.gu,ur,&yy[..nr],&mut u[..nr]);}else if (nr as i32)>=d.mt_min&&(matches!(f.gu,16|17|18|21|22)||f.gu==23&&!d.avx512)&&d.iq256{super::rust_iq::dot_multi256(f.gu,gr,&yy[..nr],&mut g[..nr]);super::rust_iq::dot_multi256(f.gu,ur,&yy[..nr],&mut u[..nr]);}else{for t in 0..nr{g[t]=super::rust_iq::dot_single(f.gu,gr,yy[t]);u[t]=super::rust_iq::dot_single(f.gu,ur,yy[t]);}}} - let dst=std::ptr::addr_of_mut!((*slot).ff).cast::();for t in 0..nr{dst.add(t*FF+r).write(silu(g[t],u[t]));} - } - } else { - for r in r0..r1{let row=&down[r*f.down_row..(r+1)*f.down_row]; - if f.down==42{let base=std::ptr::addr_of!((*slot).a2).cast::();let mut aa=[&*base;MAX_ROWS];for t in 0..nr{aa[t]=&*base.add(t);}if dispatch().avx512{super::rust_q2::dot512(row,&aa[..nr],&mut g[..nr]);}else{super::rust_q2::dot256(row,&aa[..nr],&mut g[..nr]);}} - else{let base=std::ptr::addr_of!((*slot).hq).cast::();let empty:&[super::rust_types::Q8Zero]=&[];let mut yy=[empty;MAX_ROWS];for t in 0..nr{yy[t]=&(*base.add(t)).q;}let d=dispatch();let single=(nr as i32)Duration::from_secs(60){eprintln!("strata: the CPU expert pool stalled waiting for workers to park");std::process::abort();}}} - fn wait_done(&self,n:usize){let mut spins=0u32;let mut seen=0u32;let mut t=Instant::now();loop{let d=self.done.0.load(Ordering::Acquire);if d>=n as u32{return;}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue;}if spins==1024||d!=seen{t=Instant::now();seen=d;}else if t.elapsed()>Duration::from_secs(60){eprintln!("strata: the CPU expert pool stalled waiting for jobs");std::process::abort();}}} +#[repr(C, align(64))] +struct Scratch { + a1: ActQ, + a2: ActQ, + ff: [f32; FF], +} +#[repr(C)] +#[derive(Clone, Copy)] +struct Job { + gate: *const u8, + up: *const u8, + down: *const u8, + rows: i32, + act: [*const ActQ; MAX_ROWS], + output: [*mut f32; MAX_ROWS], + nact: [*const u8; MAX_ROWS], +} +#[repr(C, align(64))] +struct SingleSplit { + ff: [f32; FF], + a2: ActQ, +} +const _: () = assert!(std::mem::size_of::() == 224); +const _: () = assert!(std::mem::size_of::() == 9728); +const _: () = assert!(std::mem::size_of::() == 6144); +struct Batch { + jobs: [Job; MAX_JOBS], + format: NativeFmt, + count: usize, + mode: u32, + rows: usize, + tasks: usize, +} +struct Shared { + head: Line, + done: Line, + parked: Line, + epoch: Line, + stop: Line, + sleepers: Line, + sleep_mu: Mutex<()>, + sleep_cv: Condvar, + spin: Duration, + n: usize, + batch: UnsafeCell, + act: Vec>, + nact: Vec>, + split: Vec>, + // Borrowed groups quantize every token once (expert_source.cpp act_multi/nact_multi), not once per job row. + tok_act: Vec>, + tok_nact: Vec>, + // Keep the original per-worker scratch reservation even though native phases + // require only split storage; it remains owned until all worker joins complete. + _scratch: Vec, + _single_split: Vec, } /// `LELEKA_POOL_TIMING=1`: wall time of the host's stages of `compute_borrowed`, summed over calls until taken (ms): /// 0 pre (validation, token quantization, job table), 1-5 gate/up phase (park wait before, publish, host drain, wait done, park wait after), /// 6 host requantization, 7-11 down phase (same five), 12 post (output check). Off: no clock is read. -pub const TIMING_STAGES:usize=13; -/// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is an A/B knob: every row is -/// computed by the same code whatever task holds it, so the output does not depend on it. -fn tasks_per_thread()->usize{static V:std::sync::OnceLock=std::sync::OnceLock::new();*V.get_or_init(||std::env::var("LELEKA_POOL_TASKS_PER_THREAD").ok().and_then(|v|v.parse().ok()).filter(|v|(1..=16).contains(v)).unwrap_or(3))} -pub(super) struct NativePool{shared:Arc,workers:Vec>,timing:Option<[f64;TIMING_STAGES]>} -impl NativePool { - pub fn new(workers:i32)->Result{if !(0..=15).contains(&workers){return Err(Error::Shape);}let stack=super::rust_platform::stack_size()?;if !super::rust_simd::avx2_ok()||super::rust_simd::avx512_ok()&&!super::rust_simd::dq_ok(){return Err(Error::Unsupported);}let cores=super::rust_platform::cores(true);if workers==0&&cores.len()>15{return Err(Error::Unsupported);}let n=if workers>0{workers as usize}else{cores.len().max(1)}; - let spin=std::env::var("STRATA_POOL_SPIN_US").map(|s|Duration::from_micros(super::rust_simd::atoi(&s).max(0)as u64)).unwrap_or(Duration::from_millis(20)); - let shared=Arc::new(Shared{head:Line(AtomicU64::new(0)),done:Line(AtomicU32::new(0)),parked:Line(AtomicU32::new(0)),epoch:Line(AtomicU32::new(0)),stop:Line(AtomicBool::new(false)),sleepers:Line(AtomicU32::new(0)),sleep_mu:Mutex::new(()),sleep_cv:Condvar::new(),spin,n,batch:UnsafeCell::new(Batch{jobs:[Job::default();MAX_JOBS],format:NativeFmt::new(18,42)?,count:0,mode:0,rows:0,tasks:1}),act:allocated(MAX_JOBS)?,nact:allocated(MAX_JOBS)?,split:allocated(MAX_JOBS)?,tok_act:allocated(1)?,tok_nact:allocated(1)?,_scratch:allocated(n+1)?,_single_split:allocated(16)?}); - let timing=std::env::var("LELEKA_POOL_TIMING").is_ok_and(|v|v=="1").then_some([0.0;TIMING_STAGES]);let mut out=Self{shared,workers:Vec::new(),timing};out.workers.try_reserve_exact(n).map_err(|_|Error::Allocation)?;for i in 0..n{let shared=Arc::clone(&out.shared);let core=cores.get(i).copied().unwrap_or(-1);out.workers.push(thread::Builder::new().name(format!("strata-expert-{i}")).stack_size(stack).spawn(move||shared.worker(core)).map_err(|_|Error::Allocation)?);}Ok(out) - } - pub fn workers(&self)->Result{Ok(self.workers.len())} - fn phase(&mut self,mode:u32,rows:usize){self.phase_timed(mode,rows,0)} - /// `at`: first of the five timing stages of this phase (ignored when timing is off). - fn phase_timed(&mut self,mode:u32,rows:usize,at:usize){ - let on=self.timing.is_some();let mut t=[None;6];let mut lap=|i:usize|{if on{t[i]=Some(Instant::now());}}; - lap(0);self.shared.wait_parked();lap(1);let tasks=tasks_per_thread()*(self.shared.n+1);/* SAFETY: wait_parked() above proves every worker finished its previous drain and holds no claim, so the host is the only accessor of `batch` until the Release store of `head` below publishes it. */unsafe {let b=&mut*self.shared.batch.get();b.mode=mode;b.rows=rows;b.tasks=tasks;}self.shared.done.0.store(0,Ordering::Relaxed);let e=self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1);self.shared.head.0.store(((e as u64)<<32)|((tasks as u64)<<16),Ordering::Release);self.shared.publish();lap(2);self.shared.drain(e);lap(3);self.shared.wait_done(tasks);lap(4);self.shared.wait_parked();lap(5); - if let Some(acc)=self.timing.as_mut(){for i in 0..5{if let (Some(a),Some(b))=(t[i],t[i+1]){acc[at+i]+=b.duration_since(a).as_secs_f64()*1e3;}}} - } - /// The summed stage times since the last call (see `TIMING_STAGES`), zeroed; `None` when timing is off. - pub fn take_timing(&mut self)->Option<[f64;TIMING_STAGES]>{self.timing.as_mut().map(|t|std::mem::replace(t,[0.0;TIMING_STAGES]))} - pub fn compute_batch(&mut self,jobs:&mut [PreparedJob])->Result<()> { - if !(1..=MAX_JOBS).contains(&jobs.len()){return Err(Error::Shape);}let gu=jobs[0].gu;let down=jobs[0].down;if jobs.iter().any(|j|j.gu!=gu||j.down!=down){return Err(Error::Shape);}let f=NativeFmt::new(gu.kind(),down.kind())?; - // Validate the ENTIRE batch before touching quantized operands or publication. - for j in jobs.iter(){if !(1..=MAX_ROWS).contains(&j.rows)||j.input.len()!=j.rows*H||j.output.len()!=j.rows*H||j.gate_bytes!=f.up_off||j.up_bytes!=f.up_off||j.down_bytes!=f.bytes-f.down_off{return Err(Error::Shape);}if j.input.iter().any(|x|!x.is_finite()){return Err(Error::NonFinite);}} - self.shared.wait_parked(); - // SAFETY: all workers parked; jobs remain exclusively borrowed until both - // phases finish and workers park again. NativePool::Drop joins before owners. - unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=jobs.len();for (e,j) in jobs.iter_mut().enumerate(){let p=j.blob.as_ptr();b.jobs[e]=Job{gate:p,up:p.add(f.up_off),down:p.add(f.down_off),rows:j.rows as i32,..Job::default()};for t in 0..j.rows{let x=&j.input[t*H..(t+1)*H];b.jobs[e].output[t]=j.output.as_mut_ptr().add(t*H);b.jobs[e].act[t]=(*self.shared.act[e].get()).as_ptr().add(t);b.jobs[e].nact[t]=(*self.shared.nact[e].get()).as_ptr().add(t).cast();let ptr=(*self.shared.act[e].get()).as_mut_ptr().add(t);if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut*ptr);}else{super::rust_quant::q8_one_avx2(x,&mut*ptr);}}else{let ptr=(*self.shared.nact[e].get()).as_mut_ptr().add(t);super::rust_quant::q8_k(x,&mut(*ptr).q);}}}} - self.run_published(f,jobs.len()); - if jobs.iter().any(|j|j.output.iter().any(|v|!v.is_finite())){Err(Error::NonFinite)}else{Ok(())} - } - /// Gate/up phase, the host requantization of every job's hidden rows, then the down phase, over the - /// `count` jobs already described in the batch (workers parked). - fn run_published(&mut self,f:NativeFmt,count:usize){ - self.phase_timed(5,count*FF,1);let t=self.timing.is_some().then(Instant::now); - // SAFETY: all workers parked after phase 5; job rows were admitted before publication. - unsafe {let b=&*self.shared.batch.get();for e in 0..count{let rows=b.jobs[e].rows as usize;let s=&mut*self.shared.split[e].get();for t in 0..rows{if f.down==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(&s.ff[t],&mut s.a2[t]);}else{super::rust_quant::q8_one_avx2(&s.ff[t],&mut s.a2[t]);}}else{super::rust_quant::q8_zero(&s.ff[t],&mut s.hq[t].q);}}}} - if let (Some(t),Some(acc))=(t,self.timing.as_mut()){acc[6]+=t.elapsed().as_secs_f64()*1e3;} - self.phase_timed(6,count*H,7); - } - /// Fault the borrowed matrices in on every worker (and the caller) after `MADV_WILLNEED` on all of - /// them: a file-mapped source's misses become many outstanding reads instead of one serial stream - /// (expert_source.cpp `prefetch` on its fetch threads). Reads only; nothing is computed or written. - pub fn prefetch_borrowed(&mut self,gu:i32,down:i32,experts:&[super::BorrowedExpert<'_>])->Result<()> { - let f=NativeFmt::new(gu,down)?; - if !(1..=MAX_JOBS).contains(&experts.len()){return Err(Error::Shape);} - for x in experts{if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off{return Err(Error::Shape);}} - for x in experts{for m in [x.gate,x.up,x.down]{super::rust_platform::will_need(m);}} - self.shared.wait_parked(); - // SAFETY: all workers parked; the borrowed matrices outlive this call, which returns only after the - // phase finished and the workers parked again. The phase only reads them. - unsafe {let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();for (e,x) in experts.iter().enumerate(){b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),..Job::default()};}} - self.phase(7,experts.len()*(2*FF+H)); - Ok(()) - } - /// One whole group straight from borrowed encoded matrices into the caller's output rows: a single - /// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns; - /// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of - /// each pair receives that expert's row; the pairs of all experts must name distinct rows. - pub fn compute_borrowed(&mut self,gu:i32,down:i32,group:&super::BorrowedGroup<'_>,out:&mut [f32])->Result<()> { - let t_pre=self.timing.is_some().then(Instant::now);let f=NativeFmt::new(gu,down)?;let experts=group.experts;let tokens=group.tokens;let stride=group.stride; - if !(1..=MAX_JOBS).contains(&experts.len())||tokens.len()%H!=0||!(1..=MAX_ROWS).contains(&(tokens.len()/H))||stride==0||out.len()%H!=0{return Err(Error::Shape);} - let ntok=tokens.len()/H;let out_rows=out.len()/H;if out_rows>super::MAX_OUT_ROWS{return Err(Error::Shape);} - // Validate the ENTIRE group (extents, pair bounds, disjoint destinations, finite inputs) first. - let mut written=[0u64;super::MAX_OUT_ROWS/64];let mut used=[false;MAX_ROWS]; - for x in experts{ - if x.gate.len()!=f.up_off||x.up.len()!=f.up_off||x.down.len()!=f.bytes-f.down_off||!(1..=MAX_ROWS).contains(&x.pairs.len()){return Err(Error::Shape);} - for &(token,slot) in x.pairs{ - if token>=ntok||slot>=stride{return Err(Error::Shape);} - let row=token.checked_mul(stride).and_then(|r|r.checked_add(slot)).ok_or(Error::Shape)?; - if row>=out_rows||written[row/64]>>(row%64)&1!=0{return Err(Error::Shape);} - written[row/64]|=1<<(row%64);used[token]=true; - } - } - if !all_finite(tokens){return Err(Error::NonFinite);} - self.shared.wait_parked(); - // SAFETY: all workers parked; the borrowed matrices, tokens and `out` outlive this call, which returns - // only after both phases finished and the workers parked again. Destinations are pairwise disjoint rows. - unsafe { - let ta=&mut*self.shared.tok_act[0].get();let tn=&mut*self.shared.tok_nact[0].get(); - for t in (0..ntok).filter(|&t|used[t]){let x=&tokens[t*H..(t+1)*H];if f.gu==42{if dispatch().avx512{super::rust_quant::q8_one_avx512(x,&mut ta[t]);}else{super::rust_quant::q8_one_avx2(x,&mut ta[t]);}}else if super::rust_quant::q8k_fast(){super::rust_quant::q8_k_avx2(x,&mut tn[t].q);}else{super::rust_quant::q8_k(x,&mut tn[t].q);}} - let b=&mut*self.shared.batch.get();b.format=f;b.count=experts.len();let base=out.as_mut_ptr(); - for (e,x) in experts.iter().enumerate(){ - b.jobs[e]=Job{gate:x.gate.as_ptr(),up:x.up.as_ptr(),down:x.down.as_ptr(),rows:x.pairs.len() as i32,..Job::default()}; - for (t,&(token,slot)) in x.pairs.iter().enumerate(){b.jobs[e].act[t]=ta.as_ptr().add(token);b.jobs[e].nact[t]=tn.as_ptr().add(token).cast();b.jobs[e].output[t]=base.add((token*stride+slot)*H);} - } - } - if let (Some(t),Some(acc))=(t_pre,self.timing.as_mut()){acc[0]+=t.elapsed().as_secs_f64()*1e3;} - self.run_published(f,experts.len()); - let t_post=self.timing.is_some().then(Instant::now); - for x in experts{for &(token,slot) in x.pairs{let at=(token*stride+slot)*H;if !all_finite(&out[at..at+H]){return Err(Error::NonFinite);}}} - if let (Some(t),Some(acc))=(t_post,self.timing.as_mut()){acc[12]+=t.elapsed().as_secs_f64()*1e3;} - Ok(()) - } +pub const TIMING_STAGES: usize = 13; +pub(super) struct NativePool { + shared: Arc, + workers: Vec>, + timing: Option<[f64; TIMING_STAGES]>, } -impl Drop for NativePool{fn drop(&mut self){self.shared.stop.0.store(true,Ordering::Release);self.shared.publish();for t in self.workers.drain(..){let _=t.join();}}} + +mod impl_default_for_nativeact; +#[allow(unused_imports)] +use impl_default_for_nativeact::all_finite; +#[allow(unused_imports)] +use impl_default_for_nativeact::allocated; +mod impl_shared; +#[allow(unused_imports)] +use impl_shared::tasks_per_thread; +mod impl_nativepool; +mod impl_nativepool_2; diff --git a/crates/native-cpu-expert/src/rust_pool/impl_default_for_nativeact.rs b/crates/native-cpu-expert/src/rust_pool/impl_default_for_nativeact.rs new file mode 100644 index 00000000..c2ef0142 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_pool/impl_default_for_nativeact.rs @@ -0,0 +1,64 @@ +//! Moved out of the parent module by STRA-338: impl Default_for_NativeAct, impl Default_for_Scratch, impl Default_for_Job, impl Default_for_SingleSplit, impl Sync_for_Shared, impl Send_for_Shared .... + +#[allow(unused_imports)] +use super::*; + +impl Default for NativeAct { + fn default() -> Self { + Self { q: [Q8K::default(); 10], padding: [0; 1176] } + } +} +impl Default for Scratch { + fn default() -> Self { + Self { a1: ActQ::default(), a2: ActQ::default(), ff: [0.0; FF] } + } +} +impl Default for Job { + fn default() -> Self { + Self { + gate: std::ptr::null(), + up: std::ptr::null(), + down: std::ptr::null(), + rows: 0, + act: [std::ptr::null(); MAX_ROWS], + output: [std::ptr::null_mut(); MAX_ROWS], + nact: [std::ptr::null(); MAX_ROWS], + } + } +} +impl Default for SingleSplit { + fn default() -> Self { + Self { ff: [0.0; FF], a2: ActQ::default() } + } +} +// SAFETY: epoch release publishes immutable batch/operands. Every successful +// epoch-tagged CAS claims a disjoint global row interval. No row is accessed by +// another claim. Host mutates batch/activation storage only after done AND parked. +// Both waits are required: a delayed sleeper carries its OLD epoch into claim. +// `batch.jobs` holds raw pointers into CALLER memory that dangle between calls; they are dereferenced only after a +// successful claim of the epoch that published them, and `done == tasks` then `parked == n` precede every return. +// A panicking host is caught by ffi::NativePool, which drops (stops + joins) this pool before the borrows end; a +// panicking worker never reaches `done`, so the host aborts after 60 s instead of returning to the caller. +unsafe impl Sync for Shared {} +unsafe impl Send for Shared {} +/// `!any(|v| !v.is_finite())` as a branch-free exponent fold that vectorizes (`LELEKA_Q8K=legacy` keeps the element-wise scan). +pub(super) fn all_finite(v: &[f32]) -> bool { + if !super::super::rust_quant::q8k_fast() { + return !v.iter().any(|x| !x.is_finite()); + } + let mut bad = 0u32; + for c in v.chunks(256) { + let mut m = 0u32; + for x in c { + m |= u32::from(x.to_bits() & 0x7f80_0000 == 0x7f80_0000); + } + bad |= m; + } + bad == 0 +} +pub(super) fn allocated(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize_with(n, T::default); + Ok(v) +} diff --git a/crates/native-cpu-expert/src/rust_pool/impl_nativepool.rs b/crates/native-cpu-expert/src/rust_pool/impl_nativepool.rs new file mode 100644 index 00000000..cdcfe275 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_pool/impl_nativepool.rs @@ -0,0 +1,245 @@ +//! Moved out of the parent module by STRA-338: impl NativePool. + +#[allow(unused_imports)] +use super::*; + +impl NativePool { + pub fn new(workers: i32) -> Result { + if !(0..=15).contains(&workers) { + return Err(Error::Shape); + } + let stack = super::super::rust_platform::stack_size()?; + if !super::super::rust_simd::avx2_ok() + || super::super::rust_simd::avx512_ok() && !super::super::rust_simd::dq_ok() + { + return Err(Error::Unsupported); + } + let cores = super::super::rust_platform::cores(true); + if workers == 0 && cores.len() > 15 { + return Err(Error::Unsupported); + } + let n = if workers > 0 { workers as usize } else { cores.len().max(1) }; + let spin = std::env::var("STRATA_POOL_SPIN_US") + .map(|s| Duration::from_micros(super::super::rust_simd::atoi(&s).max(0) as u64)) + .unwrap_or(Duration::from_millis(20)); + let shared = Arc::new(Shared { + head: Line(AtomicU64::new(0)), + done: Line(AtomicU32::new(0)), + parked: Line(AtomicU32::new(0)), + epoch: Line(AtomicU32::new(0)), + stop: Line(AtomicBool::new(false)), + sleepers: Line(AtomicU32::new(0)), + sleep_mu: Mutex::new(()), + sleep_cv: Condvar::new(), + spin, + n, + batch: UnsafeCell::new(Batch { + jobs: [Job::default(); MAX_JOBS], + format: NativeFmt::new(18, 42)?, + count: 0, + mode: 0, + rows: 0, + tasks: 1, + }), + act: allocated(MAX_JOBS)?, + nact: allocated(MAX_JOBS)?, + split: allocated(MAX_JOBS)?, + tok_act: allocated(1)?, + tok_nact: allocated(1)?, + _scratch: allocated(n + 1)?, + _single_split: allocated(16)?, + }); + let timing = std::env::var("LELEKA_POOL_TIMING").is_ok_and(|v| v == "1").then_some([0.0; TIMING_STAGES]); + let mut out = Self { shared, workers: Vec::new(), timing }; + out.workers.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + for i in 0..n { + let shared = Arc::clone(&out.shared); + let core = cores.get(i).copied().unwrap_or(-1); + out.workers.push( + thread::Builder::new() + .name(format!("strata-expert-{i}")) + .stack_size(stack) + .spawn(move || shared.worker(core)) + .map_err(|_| Error::Allocation)?, + ); + } + Ok(out) + } + pub fn workers(&self) -> Result { + Ok(self.workers.len()) + } + pub(super) fn phase(&mut self, mode: u32, rows: usize) { + self.phase_timed(mode, rows, 0) + } + /// `at`: first of the five timing stages of this phase (ignored when timing is off). + pub(super) fn phase_timed(&mut self, mode: u32, rows: usize, at: usize) { + let on = self.timing.is_some(); + let mut t = [None; 6]; + let mut lap = |i: usize| { + if on { + t[i] = Some(Instant::now()); + } + }; + lap(0); + self.shared.wait_parked(); + lap(1); + let tasks = tasks_per_thread() * (self.shared.n + 1); /* SAFETY: wait_parked() above proves every worker finished its previous drain and holds no claim, so the host is the only accessor of `batch` until the Release store of `head` below publishes it. */ + unsafe { + let b = &mut *self.shared.batch.get(); + b.mode = mode; + b.rows = rows; + b.tasks = tasks; + } + self.shared.done.0.store(0, Ordering::Relaxed); + let e = self.shared.epoch.0.load(Ordering::Relaxed).wrapping_add(1); + self.shared.head.0.store(((e as u64) << 32) | ((tasks as u64) << 16), Ordering::Release); + self.shared.publish(); + lap(2); + self.shared.drain(e); + lap(3); + self.shared.wait_done(tasks); + lap(4); + self.shared.wait_parked(); + lap(5); + if let Some(acc) = self.timing.as_mut() { + for i in 0..5 { + if let (Some(a), Some(b)) = (t[i], t[i + 1]) { + acc[at + i] += b.duration_since(a).as_secs_f64() * 1e3; + } + } + } + } + /// The summed stage times since the last call (see `TIMING_STAGES`), zeroed; `None` when timing is off. + pub fn take_timing(&mut self) -> Option<[f64; TIMING_STAGES]> { + self.timing.as_mut().map(|t| std::mem::replace(t, [0.0; TIMING_STAGES])) + } + pub fn compute_batch(&mut self, jobs: &mut [PreparedJob]) -> Result<()> { + if !(1..=MAX_JOBS).contains(&jobs.len()) { + return Err(Error::Shape); + } + let gu = jobs[0].gu; + let down = jobs[0].down; + if jobs.iter().any(|j| j.gu != gu || j.down != down) { + return Err(Error::Shape); + } + let f = NativeFmt::new(gu.kind(), down.kind())?; + // Validate the ENTIRE batch before touching quantized operands or publication. + for j in jobs.iter() { + if !(1..=MAX_ROWS).contains(&j.rows) + || j.input.len() != j.rows * H + || j.output.len() != j.rows * H + || j.gate_bytes != f.up_off + || j.up_bytes != f.up_off + || j.down_bytes != f.bytes - f.down_off + { + return Err(Error::Shape); + } + if j.input.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFinite); + } + } + self.shared.wait_parked(); + // SAFETY: all workers parked; jobs remain exclusively borrowed until both + // phases finish and workers park again. NativePool::Drop joins before owners. + unsafe { + let b = &mut *self.shared.batch.get(); + b.format = f; + b.count = jobs.len(); + for (e, j) in jobs.iter_mut().enumerate() { + let p = j.blob.as_ptr(); + b.jobs[e] = Job { + gate: p, + up: p.add(f.up_off), + down: p.add(f.down_off), + rows: j.rows as i32, + ..Job::default() + }; + for t in 0..j.rows { + let x = &j.input[t * H..(t + 1) * H]; + b.jobs[e].output[t] = j.output.as_mut_ptr().add(t * H); + b.jobs[e].act[t] = (*self.shared.act[e].get()).as_ptr().add(t); + b.jobs[e].nact[t] = (*self.shared.nact[e].get()).as_ptr().add(t).cast(); + let ptr = (*self.shared.act[e].get()).as_mut_ptr().add(t); + if f.gu == 42 { + if dispatch().avx512 { + super::super::rust_quant::q8_one_avx512(x, &mut *ptr); + } else { + super::super::rust_quant::q8_one_avx2(x, &mut *ptr); + } + } else { + let ptr = (*self.shared.nact[e].get()).as_mut_ptr().add(t); + super::super::rust_quant::q8_k(x, &mut (*ptr).q); + } + } + } + } + self.run_published(f, jobs.len()); + if jobs.iter().any(|j| j.output.iter().any(|v| !v.is_finite())) { Err(Error::NonFinite) } else { Ok(()) } + } + /// Gate/up phase, the host requantization of every job's hidden rows, then the down phase, over the + /// `count` jobs already described in the batch (workers parked). + pub(super) fn run_published(&mut self, f: NativeFmt, count: usize) { + self.phase_timed(5, count * FF, 1); + let t = self.timing.is_some().then(Instant::now); + // SAFETY: all workers parked after phase 5; job rows were admitted before publication. + unsafe { + let b = &*self.shared.batch.get(); + for e in 0..count { + let rows = b.jobs[e].rows as usize; + let s = &mut *self.shared.split[e].get(); + for t in 0..rows { + if f.down == 42 { + if dispatch().avx512 { + super::super::rust_quant::q8_one_avx512(&s.ff[t], &mut s.a2[t]); + } else { + super::super::rust_quant::q8_one_avx2(&s.ff[t], &mut s.a2[t]); + } + } else { + super::super::rust_quant::q8_zero(&s.ff[t], &mut s.hq[t].q); + } + } + } + } + if let (Some(t), Some(acc)) = (t, self.timing.as_mut()) { + acc[6] += t.elapsed().as_secs_f64() * 1e3; + } + self.phase_timed(6, count * H, 7); + } + /// Fault the borrowed matrices in on every worker (and the caller) after `MADV_WILLNEED` on all of + /// them: a file-mapped source's misses become many outstanding reads instead of one serial stream + /// (expert_source.cpp `prefetch` on its fetch threads). Reads only; nothing is computed or written. + pub fn prefetch_borrowed( + &mut self, + gu: i32, + down: i32, + experts: &[super::super::BorrowedExpert<'_>], + ) -> Result<()> { + let f = NativeFmt::new(gu, down)?; + if !(1..=MAX_JOBS).contains(&experts.len()) { + return Err(Error::Shape); + } + for x in experts { + if x.gate.len() != f.up_off || x.up.len() != f.up_off || x.down.len() != f.bytes - f.down_off { + return Err(Error::Shape); + } + } + for x in experts { + for m in [x.gate, x.up, x.down] { + super::super::rust_platform::will_need(m); + } + } + self.shared.wait_parked(); + // SAFETY: all workers parked; the borrowed matrices outlive this call, which returns only after the + // phase finished and the workers parked again. The phase only reads them. + unsafe { + let b = &mut *self.shared.batch.get(); + b.format = f; + b.count = experts.len(); + for (e, x) in experts.iter().enumerate() { + b.jobs[e] = Job { gate: x.gate.as_ptr(), up: x.up.as_ptr(), down: x.down.as_ptr(), ..Job::default() }; + } + } + self.phase(7, experts.len() * (2 * FF + H)); + Ok(()) + } +} diff --git a/crates/native-cpu-expert/src/rust_pool/impl_nativepool_2.rs b/crates/native-cpu-expert/src/rust_pool/impl_nativepool_2.rs new file mode 100644 index 00000000..0a7f3411 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_pool/impl_nativepool_2.rs @@ -0,0 +1,128 @@ +//! Moved out of the parent module by STRA-338: impl NativePool (2), impl Drop_for_NativePool. + +#[allow(unused_imports)] +use super::*; + +impl NativePool { + /// One whole group straight from borrowed encoded matrices into the caller's output rows: a single + /// two-phase dispatch, no copy of expert bytes or activations. Every borrow ends before this returns; + /// the caller holds `group` and `out` exclusively for the call. `out` row `token * stride + slot` of + /// each pair receives that expert's row; the pairs of all experts must name distinct rows. + pub fn compute_borrowed( + &mut self, + gu: i32, + down: i32, + group: &super::super::BorrowedGroup<'_>, + out: &mut [f32], + ) -> Result<()> { + let t_pre = self.timing.is_some().then(Instant::now); + let f = NativeFmt::new(gu, down)?; + let experts = group.experts; + let tokens = group.tokens; + let stride = group.stride; + if !(1..=MAX_JOBS).contains(&experts.len()) + || tokens.len() % H != 0 + || !(1..=MAX_ROWS).contains(&(tokens.len() / H)) + || stride == 0 + || out.len() % H != 0 + { + return Err(Error::Shape); + } + let ntok = tokens.len() / H; + let out_rows = out.len() / H; + if out_rows > super::super::MAX_OUT_ROWS { + return Err(Error::Shape); + } + // Validate the ENTIRE group (extents, pair bounds, disjoint destinations, finite inputs) first. + let mut written = [0u64; super::super::MAX_OUT_ROWS / 64]; + let mut used = [false; MAX_ROWS]; + for x in experts { + if x.gate.len() != f.up_off + || x.up.len() != f.up_off + || x.down.len() != f.bytes - f.down_off + || !(1..=MAX_ROWS).contains(&x.pairs.len()) + { + return Err(Error::Shape); + } + for &(token, slot) in x.pairs { + if token >= ntok || slot >= stride { + return Err(Error::Shape); + } + let row = token.checked_mul(stride).and_then(|r| r.checked_add(slot)).ok_or(Error::Shape)?; + if row >= out_rows || written[row / 64] >> (row % 64) & 1 != 0 { + return Err(Error::Shape); + } + written[row / 64] |= 1 << (row % 64); + used[token] = true; + } + } + if !all_finite(tokens) { + return Err(Error::NonFinite); + } + self.shared.wait_parked(); + // SAFETY: all workers parked; the borrowed matrices, tokens and `out` outlive this call, which returns + // only after both phases finished and the workers parked again. Destinations are pairwise disjoint rows. + unsafe { + let ta = &mut *self.shared.tok_act[0].get(); + let tn = &mut *self.shared.tok_nact[0].get(); + for t in (0..ntok).filter(|&t| used[t]) { + let x = &tokens[t * H..(t + 1) * H]; + if f.gu == 42 { + if dispatch().avx512 { + super::super::rust_quant::q8_one_avx512(x, &mut ta[t]); + } else { + super::super::rust_quant::q8_one_avx2(x, &mut ta[t]); + } + } else if super::super::rust_quant::q8k_fast() { + super::super::rust_quant::q8_k_avx2(x, &mut tn[t].q); + } else { + super::super::rust_quant::q8_k(x, &mut tn[t].q); + } + } + let b = &mut *self.shared.batch.get(); + b.format = f; + b.count = experts.len(); + let base = out.as_mut_ptr(); + for (e, x) in experts.iter().enumerate() { + b.jobs[e] = Job { + gate: x.gate.as_ptr(), + up: x.up.as_ptr(), + down: x.down.as_ptr(), + rows: x.pairs.len() as i32, + ..Job::default() + }; + for (t, &(token, slot)) in x.pairs.iter().enumerate() { + b.jobs[e].act[t] = ta.as_ptr().add(token); + b.jobs[e].nact[t] = tn.as_ptr().add(token).cast(); + b.jobs[e].output[t] = base.add((token * stride + slot) * H); + } + } + } + if let (Some(t), Some(acc)) = (t_pre, self.timing.as_mut()) { + acc[0] += t.elapsed().as_secs_f64() * 1e3; + } + self.run_published(f, experts.len()); + let t_post = self.timing.is_some().then(Instant::now); + for x in experts { + for &(token, slot) in x.pairs { + let at = (token * stride + slot) * H; + if !all_finite(&out[at..at + H]) { + return Err(Error::NonFinite); + } + } + } + if let (Some(t), Some(acc)) = (t_post, self.timing.as_mut()) { + acc[12] += t.elapsed().as_secs_f64() * 1e3; + } + Ok(()) + } +} +impl Drop for NativePool { + fn drop(&mut self) { + self.shared.stop.0.store(true, Ordering::Release); + self.shared.publish(); + for t in self.workers.drain(..) { + let _ = t.join(); + } + } +} diff --git a/crates/native-cpu-expert/src/rust_pool/impl_shared.rs b/crates/native-cpu-expert/src/rust_pool/impl_shared.rs new file mode 100644 index 00000000..60edc822 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_pool/impl_shared.rs @@ -0,0 +1,243 @@ +//! Moved out of the parent module by STRA-338: impl Shared, fn tasks_per_thread. + +#[allow(unused_imports)] +use super::*; + +impl Shared { + pub(super) fn publish(&self) { + self.epoch.0.fetch_add(1, Ordering::SeqCst); + if self.sleepers.0.load(Ordering::SeqCst) != 0 { + let _lock = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner()); + self.sleep_cv.notify_all(); + } + } + pub(super) fn claim(&self, epoch: u32) -> Option { + let mut h = self.head.0.load(Ordering::Acquire); + loop { + if (h >> 32) as u32 != epoch { + return None; + } + let n = ((h >> 16) & 0xffff) as usize; + let i = (h & 0xffff) as usize; + if i >= n { + return None; + } + match self.head.0.compare_exchange_weak(h, h + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return Some(i), + Err(next) => h = next, + } + } + } + pub(super) fn drain(&self, epoch: u32) { + while let Some(i) = self.claim(epoch) { + // SAFETY: admission covers whole immutable blobs and output rows. The claim + // uniquely owns [g0,g1); batch remains alive through done+parked barriers. + unsafe { + self.execute(i); + } + self.done.0.fetch_add(1, Ordering::Release); + } + } + /// # Safety + /// The caller holds a successful epoch-tagged claim of task `i` (so `batch` is published and immutable, and every + /// gate/up/down/activation/output pointer in `batch.jobs[..count]` is live until the done+parked barriers). Task `i` owns + /// the row interval `[rows*i/tasks, rows*(i+1)/tasks)`; `rows == count*per` so `at/per < count` for every row. + pub(super) unsafe fn execute(&self, i: usize) { + unsafe { + let b = &*self.batch.get(); + let per = match b.mode { + 5 => FF, + 6 => H, + _ => 2 * FF + H, + }; + let mut at = b.rows * i / b.tasks; + let end = b.rows * (i + 1) / b.tasks; + while at < end { + let e = at / per; + debug_assert!(e < b.count); + let r0 = at % per; + let r1 = per.min(r0 + end - at); + let j = b.jobs[e]; + let nr = j.rows as usize; + let f = b.format; + let gate = std::slice::from_raw_parts(j.gate, f.up_off); + let up = std::slice::from_raw_parts(j.up, f.up_off); + let down = std::slice::from_raw_parts(j.down, f.bytes - f.down_off); + let slot = self.split[e].get(); + let mut g = [0.0f32; MAX_ROWS]; + let mut u = [0.0f32; MAX_ROWS]; + if b.mode == 7 { + // Prefault: read the first and the last byte of every encoded row (rows are contiguous, so every page). + for r in r0..r1 { + let row = if r < FF { + &gate[r * f.gu_row..(r + 1) * f.gu_row] + } else if r < 2 * FF { + &up[(r - FF) * f.gu_row..(r - FF + 1) * f.gu_row] + } else { + &down[(r - 2 * FF) * f.down_row..(r - 2 * FF + 1) * f.down_row] + }; + std::ptr::read_volatile(row.as_ptr()); + std::ptr::read_volatile(row.as_ptr().add(row.len() - 1)); + } + } else if b.mode == 5 { + for r in r0..r1 { + let gr = &gate[r * f.gu_row..(r + 1) * f.gu_row]; + let ur = &up[r * f.gu_row..(r + 1) * f.gu_row]; + if f.gu == 42 { + let mut aa = [&*j.act[0]; MAX_ROWS]; + for t in 0..nr { + aa[t] = &*j.act[t]; + } + if dispatch().avx512 { + super::super::rust_q2::dot512(gr, &aa[..nr], &mut g[..nr]); + super::super::rust_q2::dot512(ur, &aa[..nr], &mut u[..nr]); + } else { + super::super::rust_q2::dot256(gr, &aa[..nr], &mut g[..nr]); + super::super::rust_q2::dot256(ur, &aa[..nr], &mut u[..nr]); + } + } else { + let mut yy = [(&*j.nact[0].cast::()).q.as_slice(); MAX_ROWS]; + for t in 0..nr { + yy[t] = (&*j.nact[t].cast::()).q.as_slice(); + } + let d = dispatch(); + if (nr as i32) >= d.mt_min && matches!(f.gu, 16 | 17 | 18 | 21 | 22) && d.iq512 { + super::super::rust_iq::dot_multi512(f.gu, gr, &yy[..nr], &mut g[..nr]); + super::super::rust_iq::dot_multi512(f.gu, ur, &yy[..nr], &mut u[..nr]); + } else if (nr as i32) >= d.mt_min + && (matches!(f.gu, 16 | 17 | 18 | 21 | 22) || f.gu == 23 && !d.avx512) + && d.iq256 + { + super::super::rust_iq::dot_multi256(f.gu, gr, &yy[..nr], &mut g[..nr]); + super::super::rust_iq::dot_multi256(f.gu, ur, &yy[..nr], &mut u[..nr]); + } else { + for t in 0..nr { + g[t] = super::super::rust_iq::dot_single(f.gu, gr, yy[t]); + u[t] = super::super::rust_iq::dot_single(f.gu, ur, yy[t]); + } + } + } + let dst = std::ptr::addr_of_mut!((*slot).ff).cast::(); + for t in 0..nr { + dst.add(t * FF + r).write(silu(g[t], u[t])); + } + } + } else { + for r in r0..r1 { + let row = &down[r * f.down_row..(r + 1) * f.down_row]; + if f.down == 42 { + let base = std::ptr::addr_of!((*slot).a2).cast::(); + let mut aa = [&*base; MAX_ROWS]; + for t in 0..nr { + aa[t] = &*base.add(t); + } + if dispatch().avx512 { + super::super::rust_q2::dot512(row, &aa[..nr], &mut g[..nr]); + } else { + super::super::rust_q2::dot256(row, &aa[..nr], &mut g[..nr]); + } + } else { + let base = std::ptr::addr_of!((*slot).hq).cast::(); + let empty: &[super::super::rust_types::Q8Zero] = &[]; + let mut yy = [empty; MAX_ROWS]; + for t in 0..nr { + yy[t] = &(*base.add(t)).q; + } + let d = dispatch(); + let single = (nr as i32) < d.mt_min || !d.iq4nl; + super::super::rust_iq::iq4nl(row, &yy[..nr], &mut g[..nr], single); + } + for t in 0..nr { + j.output[t].add(r).write(g[t]); + } + } + } + at += r1 - r0; + } + } + } + pub(super) fn worker(&self, core: i32) { + super::super::rust_platform::pin(core); + let mut seen = 0u32; + self.parked.0.fetch_add(1, Ordering::AcqRel); + loop { + let parked_at = Instant::now(); + let mut spins = 0u32; + while self.epoch.0.load(Ordering::Acquire) == seen { + if self.stop.0.load(Ordering::Relaxed) { + return; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 || parked_at.elapsed() < self.spin { + continue; + } + let mut lock = self.sleep_mu.lock().unwrap_or_else(|p| p.into_inner()); + self.sleepers.0.fetch_add(1, Ordering::SeqCst); + while self.epoch.0.load(Ordering::SeqCst) == seen && !self.stop.0.load(Ordering::Relaxed) { + lock = self.sleep_cv.wait(lock).unwrap_or_else(|p| p.into_inner()); + } + self.sleepers.0.fetch_sub(1, Ordering::Relaxed); + } + if self.stop.0.load(Ordering::Acquire) { + return; + } + seen = self.epoch.0.load(Ordering::Acquire); + self.parked.0.fetch_sub(1, Ordering::AcqRel); + self.drain(seen); + self.parked.0.fetch_add(1, Ordering::AcqRel); + } + } + pub(super) fn wait_parked(&self) { + let mut spins = 0u32; + let mut t = Instant::now(); + while self.parked.0.load(Ordering::Acquire) != self.n as u32 { + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + if spins == 1024 { + t = Instant::now(); + } else if t.elapsed() > Duration::from_secs(60) { + eprintln!("strata: the CPU expert pool stalled waiting for workers to park"); + std::process::abort(); + } + } + } + pub(super) fn wait_done(&self, n: usize) { + let mut spins = 0u32; + let mut seen = 0u32; + let mut t = Instant::now(); + loop { + let d = self.done.0.load(Ordering::Acquire); + if d >= n as u32 { + return; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + if spins == 1024 || d != seen { + t = Instant::now(); + seen = d; + } else if t.elapsed() > Duration::from_secs(60) { + eprintln!("strata: the CPU expert pool stalled waiting for jobs"); + std::process::abort(); + } + } + } +} +/// Tasks per participating thread in a phase (pool.cpp `phase_tasks`: 3). `LELEKA_POOL_TASKS_PER_THREAD` (1..=16) is an A/B knob: every row is +/// computed by the same code whatever task holds it, so the output does not depend on it. +pub(super) fn tasks_per_thread() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + std::env::var("LELEKA_POOL_TASKS_PER_THREAD") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|v| (1..=16).contains(v)) + .unwrap_or(3) + }) +} diff --git a/crates/native-cpu-expert/src/rust_q2.rs b/crates/native-cpu-expert/src/rust_q2.rs index ac01801b..04e4a090 100644 --- a/crates/native-cpu-expert/src/rust_q2.rs +++ b/crates/native-cpu-expert/src/rust_q2.rs @@ -1,105 +1,246 @@ //! Original Q2_0 GGUF block path, preserving distinct AVX2 and ZMM trees. -use std::arch::x86_64::*; -use super::rust_types::ActQ; use super::rust_simd::half; +use super::rust_types::ActQ; +use std::arch::x86_64::*; // Bounds: for each 18-byte block b of `row`, dot256/dot512 read a.q[b*64..b*64+64], a.scale/hx[2b..2b+2] and row[b*18..(b+1)*18]. // ActQ has 2560 q and 80 scale/hx entries, so `row.len() <= 40*18 = 720` and `a.len() <= 8` are required and asserted // below (callers pass 720-byte gate/up rows, 180-byte down rows, or q2_rows(width <= H)). Gate: avx2_ok() / avx512_ok()+dq_ok(). -#[target_feature(enable="avx2,fma,f16c")] -unsafe fn unpack(c:&[u8])->(__m256i,__m256i) {unsafe { - let b=_mm_loadu_si128(c.as_ptr().cast());let m=_mm_set1_epi8(3);let c0=_mm_and_si128(b,m);let c1=_mm_and_si128(_mm_srli_epi16::<2>(b),m);let c2=_mm_and_si128(_mm_srli_epi16::<4>(b),m);let c3=_mm_and_si128(_mm_srli_epi16::<6>(b),m); - let a0=_mm_unpacklo_epi8(c0,c1);let a1=_mm_unpacklo_epi8(c2,c3);let b0=_mm_unpackhi_epi8(c0,c1);let b1=_mm_unpackhi_epi8(c2,c3); - (_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_unpacklo_epi16(a0,a1)),_mm_unpackhi_epi16(a0,a1)),_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(_mm_unpacklo_epi16(b0,b1)),_mm_unpackhi_epi16(b0,b1))) -}} +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn unpack(c: &[u8]) -> (__m256i, __m256i) { + unsafe { + let b = _mm_loadu_si128(c.as_ptr().cast()); + let m = _mm_set1_epi8(3); + let c0 = _mm_and_si128(b, m); + let c1 = _mm_and_si128(_mm_srli_epi16::<2>(b), m); + let c2 = _mm_and_si128(_mm_srli_epi16::<4>(b), m); + let c3 = _mm_and_si128(_mm_srli_epi16::<6>(b), m); + let a0 = _mm_unpacklo_epi8(c0, c1); + let a1 = _mm_unpacklo_epi8(c2, c3); + let b0 = _mm_unpackhi_epi8(c0, c1); + let b1 = _mm_unpackhi_epi8(c2, c3); + ( + _mm256_inserti128_si256::<1>( + _mm256_castsi128_si256(_mm_unpacklo_epi16(a0, a1)), + _mm_unpackhi_epi16(a0, a1), + ), + _mm256_inserti128_si256::<1>( + _mm256_castsi128_si256(_mm_unpacklo_epi16(b0, b1)), + _mm_unpackhi_epi16(b0, b1), + ), + ) + } +} // The weight-scale times activation-sum correction `corr += d*(hx0+hx1)` is ONE fused multiply-add (vfmadd231ss), as in the pinned C++ // q2_avx2.cpp row_multi built by GCC with -mfma (default -ffp-contract=fast contracts it; objdump of q2_avx2.o shows the scalar vfmadd) and as in the // AVX-512 tree's explicit `_mm512_fmadd_ps(dd,hx,corr)`. A separate mul+add rounds twice and differs in the last bits (STRA-324). Not contractible // by rustc, hence the explicit `mul_add`; this function enables `fma`, so it lowers to the instruction, never to a libm call. -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn dot256(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe { - assert!(row.len()<=40*18&&a.len()<=8); - let mut acc=[_mm256_setzero_ps();8];let mut corr=[0.0f32;8];let ones=_mm256_set1_epi16(1); - for (b,blk) in row.chunks_exact(18).enumerate(){let d=half(u16::from_le_bytes([blk[0],blk[1]]));let (lo,hi)=unpack(&blk[2..]);for (t,a) in a.iter().enumerate(){let q=a.q.as_ptr().add(b*64);let s0=_mm256_madd_epi16(_mm256_maddubs_epi16(lo,_mm256_loadu_si256(q.cast())),ones);let s1=_mm256_madd_epi16(_mm256_maddubs_epi16(hi,_mm256_loadu_si256(q.add(32).cast())),ones); - acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*a.scale[2*b]),_mm256_cvtepi32_ps(s0),acc[t]);acc[t]=_mm256_fmadd_ps(_mm256_set1_ps(d*a.scale[2*b+1]),_mm256_cvtepi32_ps(s1),acc[t]);corr[t]=d.mul_add(a.hx[2*b]+a.hx[2*b+1],corr[t]);}} - for (t,r) in r.iter_mut().enumerate(){let h=_mm_add_ps(_mm256_castps256_ps128(acc[t]),_mm256_extractf128_ps::<1>(acc[t]));let s=_mm_add_ps(h,_mm_movehl_ps(h,h));*r=_mm_cvtss_f32(_mm_add_ss(s,_mm_movehdup_ps(s)))-corr[t];} -}} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn dot256(row: &[u8], a: &[&ActQ], r: &mut [f32]) { + unsafe { + assert!(row.len() <= 40 * 18 && a.len() <= 8); + let mut acc = [_mm256_setzero_ps(); 8]; + let mut corr = [0.0f32; 8]; + let ones = _mm256_set1_epi16(1); + for (b, blk) in row.chunks_exact(18).enumerate() { + let d = half(u16::from_le_bytes([blk[0], blk[1]])); + let (lo, hi) = unpack(&blk[2..]); + for (t, a) in a.iter().enumerate() { + let q = a.q.as_ptr().add(b * 64); + let s0 = _mm256_madd_epi16(_mm256_maddubs_epi16(lo, _mm256_loadu_si256(q.cast())), ones); + let s1 = _mm256_madd_epi16(_mm256_maddubs_epi16(hi, _mm256_loadu_si256(q.add(32).cast())), ones); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b]), _mm256_cvtepi32_ps(s0), acc[t]); + acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b + 1]), _mm256_cvtepi32_ps(s1), acc[t]); + corr[t] = d.mul_add(a.hx[2 * b] + a.hx[2 * b + 1], corr[t]); + } + } + for (t, r) in r.iter_mut().enumerate() { + let h = _mm_add_ps(_mm256_castps256_ps128(acc[t]), _mm256_extractf128_ps::<1>(acc[t])); + let s = _mm_add_ps(h, _mm_movehl_ps(h, h)); + *r = _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) - corr[t]; + } + } +} /// The Q2_0 rows specialised on the token count; the same operations in the same order per token. -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] -pub(super) unsafe fn dot512(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe { - match a.len(){1=>dot512_n::<1>(row,a,r),2=>dot512_n::<2>(row,a,r),3=>dot512_n::<3>(row,a,r),4=>dot512_n::<4>(row,a,r),5=>dot512_n::<5>(row,a,r),6=>dot512_n::<6>(row,a,r),7=>dot512_n::<7>(row,a,r),8=>dot512_n::<8>(row,a,r),_=>panic!("dot512: 1..=8 tokens")} -}} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] -unsafe fn dot512_n(row:&[u8],a:&[&ActQ],r:&mut [f32]) {unsafe { - assert!(N<=8&&a.len()==N&&r.len()==N&&row.len()<=40*18); - let mut acc=[_mm512_setzero_ps();8];let mut corr=[_mm512_setzero_ps();8];let base=_mm512_setr_epi32(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1);let dup=_mm512_setr_epi32(0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7);let nb=row.len()/18; - for b0 in (0..nb).step_by(8){let n=(nb-b0).min(8);let mask=if n==8{0xffff}else{((1u32<<(2*n))-1)as u16};let mut sc=[0u16;8];for i in 0..n{sc[i]=u16::from_le_bytes([row[(b0+i)*18],row[(b0+i)*18+1]]);} - let d8=_mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(sc.as_ptr().cast())));let dd=_mm512_maskz_mov_ps(mask,_mm512_permutexvar_ps(dup,d8));let mut p=[_mm512_setzero_ps();8]; - for t in 0..N {let a=a[t];p[t]=_mm512_mul_ps(dd,_mm512_maskz_loadu_ps(mask,a.scale.as_ptr().add(2*b0)));corr[t]=_mm512_fmadd_ps(dd,_mm512_maskz_loadu_ps(mask,a.hx.as_ptr().add(2*b0)),corr[t]);} - for i in 0..n{let b=b0+i;let packed=_mm_loadu_si128(row.as_ptr().add(b*18+2).cast());let lanes=_mm512_cvtepu16_epi64(packed);let ctrl=_mm512_set1_epi64(0x0e0c0a0806040200);let w=_mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl,lanes),_mm512_set1_epi8(3));let idx=_mm512_add_epi32(base,_mm512_set1_epi32(2*i as i32));for t in 0..N {let a=a[t];let dot=_mm512_dpbusd_epi32(_mm512_setzero_si512(),w,_mm512_loadu_si512(a.q.as_ptr().add(b*64).cast()));acc[t]=_mm512_fmadd_ps(_mm512_permutexvar_ps(idx,p[t]),_mm512_cvtepi32_ps(dot),acc[t]);}} - } - for t in 0..N {r[t]=_mm512_reduce_add_ps(acc[t])-_mm512_reduce_add_ps(corr[t]);} -}} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] +pub(super) unsafe fn dot512(row: &[u8], a: &[&ActQ], r: &mut [f32]) { + unsafe { + match a.len() { + 1 => dot512_n::<1>(row, a, r), + 2 => dot512_n::<2>(row, a, r), + 3 => dot512_n::<3>(row, a, r), + 4 => dot512_n::<4>(row, a, r), + 5 => dot512_n::<5>(row, a, r), + 6 => dot512_n::<6>(row, a, r), + 7 => dot512_n::<7>(row, a, r), + 8 => dot512_n::<8>(row, a, r), + _ => panic!("dot512: 1..=8 tokens"), + } + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,avx512vbmi,avx512vnni,avx2,fma,f16c")] +unsafe fn dot512_n(row: &[u8], a: &[&ActQ], r: &mut [f32]) { + unsafe { + assert!(N <= 8 && a.len() == N && r.len() == N && row.len() <= 40 * 18); + let mut acc = [_mm512_setzero_ps(); 8]; + let mut corr = [_mm512_setzero_ps(); 8]; + let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1); + let dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7); + let nb = row.len() / 18; + for b0 in (0..nb).step_by(8) { + let n = (nb - b0).min(8); + let mask = if n == 8 { 0xffff } else { ((1u32 << (2 * n)) - 1) as u16 }; + let mut sc = [0u16; 8]; + for i in 0..n { + sc[i] = u16::from_le_bytes([row[(b0 + i) * 18], row[(b0 + i) * 18 + 1]]); + } + let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(sc.as_ptr().cast()))); + let dd = _mm512_maskz_mov_ps(mask, _mm512_permutexvar_ps(dup, d8)); + let mut p = [_mm512_setzero_ps(); 8]; + for t in 0..N { + let a = a[t]; + p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(mask, a.scale.as_ptr().add(2 * b0))); + corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(mask, a.hx.as_ptr().add(2 * b0)), corr[t]); + } + for i in 0..n { + let b = b0 + i; + let packed = _mm_loadu_si128(row.as_ptr().add(b * 18 + 2).cast()); + let lanes = _mm512_cvtepu16_epi64(packed); + let ctrl = _mm512_set1_epi64(0x0e0c0a0806040200); + let w = _mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3)); + let idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i as i32)); + for t in 0..N { + let a = a[t]; + let dot = _mm512_dpbusd_epi32( + _mm512_setzero_si512(), + w, + _mm512_loadu_si512(a.q.as_ptr().add(b * 64).cast()), + ); + acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]); + } + } + } + for t in 0..N { + r[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]); + } + } +} #[cfg(test)] mod tests { - use super::*; - use std::panic::{catch_unwind,AssertUnwindSafe}; - // A row longer than the 40 blocks an ActQ holds would make the kernels load past `a.q` / `a.scale`: it is refused before any load, - // while the exact-fit row still runs. - fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s} - fn h2f(h:u16)->f32 {let e=((h>>10)&31)as u32;assert!(e>0&&e<31,"finite normal FP16 only");f32::from_bits(((h as u32&0x8000)<<16)|((e+112)<<23)|((h as u32&0x3ff)<<13))} - // Scalar model of q2_avx2.cpp row_multi (the AVX2 tree): per 32-value chunk and lane (4 consecutive code x activation products, exact in int32), - // `acc = fma(d*scale, float(sum), acc)` twice per block, the correction chain `corr` fused (`fused`) or as a separate mul+add, the reduction - // ((l0+l4)+(l2+l6)) + ((l1+l5)+(l3+l7)), result minus corr. - fn model(row:&[u8],a:&ActQ,fused:bool)->f32 { - let mut acc=[0.0f32;8];let mut corr=0.0f32; - for (b,blk) in row.chunks_exact(18).enumerate() { - let d=h2f(u16::from_le_bytes([blk[0],blk[1]]));let code=|i:usize|->i32 {((blk[2+i/4]>>(2*(i%4)))&3)as i32}; - for c in 0..2 {for l in 0..8 {let mut s=0i32;for k in 0..4 {let e=32*c+4*l+k;s+=code(e)*a.q[b*64+e]as i32;}acc[l]=(d*a.scale[2*b+c]).mul_add(s as f32,acc[l]);}} - let t=a.hx[2*b]+a.hx[2*b+1];corr=if fused{d.mul_add(t,corr)}else{corr+d*t}; - } - let h=[acc[0]+acc[4],acc[1]+acc[5],acc[2]+acc[6],acc[3]+acc[7]];let s=[h[0]+h[2],h[1]+h[3]];(s[0]+s[1])-corr - } - // The Q2_0 AVX2 tree (gate/up: 40 blocks, down: 10 blocks of the hidden), 1..8 tokens, against the scalar model of the pinned C++ AVX2 row kernel. The - // correction `corr += d*(hx0+hx1)` is fused there (GCC contracts it under -mfma) and in the AVX-512 tree; a separate mul+add (the first Rust port) differed in the - // last bits of 20 of 40 KAB1 cases (every Q2_0 down, STRA-324). The check that the unfused model differs keeps this test sensitive to that change. - #[test] - fn avx2_tree_matches_the_pinned_cpp_row_kernel_model_for_gate_up_and_down_rows() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - let mut seed=0x0123_4567_89ab_cdefu64;let mut unfused_differs=0usize; - for (nb,n) in [(10usize,640usize),(40,2560)] { - let mut acts:Vec=Vec::new(); - for tok in 0..8 {let x:Vec=(0..n).map(|_|((xorshift(&mut seed)%20001)as f32-10000.0)*0.01*(1.0+(tok as f32))).collect();let mut a=ActQ::default(); - // SAFETY: avx2_ok() above; n <= 2560 and n % 32 == 0. - unsafe {super::super::rust_quant::q8_one_avx2(&x,&mut a);}acts.push(a);} - for _ in 0..8 { - let mut row=vec![0u8;nb*18];for v in row.iter_mut(){*v=xorshift(&mut seed)as u8;} - for b in row.chunks_exact_mut(18){let e=8+(xorshift(&mut seed)%8)as u16;let m=(xorshift(&mut seed)&0x3ff)as u16;b[..2].copy_from_slice(&((e<<10)|m).to_le_bytes());} - for nt in 1..=8usize { - let refs:Vec<&ActQ>=acts[..nt].iter().collect();let mut out=vec![0.0f32;nt]; - // SAFETY: avx2_ok() above; rows have at most 40 blocks and at most 8 tokens. - unsafe {dot256(&row,&refs,&mut out);} - for t in 0..nt { - assert_eq!(out[t].to_bits(),model(&row,&acts[t],true).to_bits(),"blocks {nb} nt {nt} token {t}"); - if model(&row,&acts[t],false).to_bits()!=out[t].to_bits(){unfused_differs+=1;} - } + use super::*; + use std::panic::{AssertUnwindSafe, catch_unwind}; + // A row longer than the 40 blocks an ActQ holds would make the kernels load past `a.q` / `a.scale`: it is refused before any load, + // while the exact-fit row still runs. + fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s + } + fn h2f(h: u16) -> f32 { + let e = ((h >> 10) & 31) as u32; + assert!(e > 0 && e < 31, "finite normal FP16 only"); + f32::from_bits(((h as u32 & 0x8000) << 16) | ((e + 112) << 23) | ((h as u32 & 0x3ff) << 13)) + } + // Scalar model of q2_avx2.cpp row_multi (the AVX2 tree): per 32-value chunk and lane (4 consecutive code x activation products, exact in int32), + // `acc = fma(d*scale, float(sum), acc)` twice per block, the correction chain `corr` fused (`fused`) or as a separate mul+add, the reduction + // ((l0+l4)+(l2+l6)) + ((l1+l5)+(l3+l7)), result minus corr. + fn model(row: &[u8], a: &ActQ, fused: bool) -> f32 { + let mut acc = [0.0f32; 8]; + let mut corr = 0.0f32; + for (b, blk) in row.chunks_exact(18).enumerate() { + let d = h2f(u16::from_le_bytes([blk[0], blk[1]])); + let code = |i: usize| -> i32 { ((blk[2 + i / 4] >> (2 * (i % 4))) & 3) as i32 }; + for c in 0..2 { + for l in 0..8 { + let mut s = 0i32; + for k in 0..4 { + let e = 32 * c + 4 * l + k; + s += code(e) * a.q[b * 64 + e] as i32; + } + acc[l] = (d * a.scale[2 * b + c]).mul_add(s as f32, acc[l]); + } + } + let t = a.hx[2 * b] + a.hx[2 * b + 1]; + corr = if fused { d.mul_add(t, corr) } else { corr + d * t }; + } + let h = [acc[0] + acc[4], acc[1] + acc[5], acc[2] + acc[6], acc[3] + acc[7]]; + let s = [h[0] + h[2], h[1] + h[3]]; + (s[0] + s[1]) - corr + } + // The Q2_0 AVX2 tree (gate/up: 40 blocks, down: 10 blocks of the hidden), 1..8 tokens, against the scalar model of the pinned C++ AVX2 row kernel. The + // correction `corr += d*(hx0+hx1)` is fused there (GCC contracts it under -mfma) and in the AVX-512 tree; a separate mul+add (the first Rust port) differed in the + // last bits of 20 of 40 KAB1 cases (every Q2_0 down, STRA-324). The check that the unfused model differs keeps this test sensitive to that change. + #[test] + fn avx2_tree_matches_the_pinned_cpp_row_kernel_model_for_gate_up_and_down_rows() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + let mut seed = 0x0123_4567_89ab_cdefu64; + let mut unfused_differs = 0usize; + for (nb, n) in [(10usize, 640usize), (40, 2560)] { + let mut acts: Vec = Vec::new(); + for tok in 0..8 { + let x: Vec = (0..n) + .map(|_| ((xorshift(&mut seed) % 20001) as f32 - 10000.0) * 0.01 * (1.0 + (tok as f32))) + .collect(); + let mut a = ActQ::default(); + // SAFETY: avx2_ok() above; n <= 2560 and n % 32 == 0. + unsafe { + super::super::rust_quant::q8_one_avx2(&x, &mut a); + } + acts.push(a); + } + for _ in 0..8 { + let mut row = vec![0u8; nb * 18]; + for v in row.iter_mut() { + *v = xorshift(&mut seed) as u8; + } + for b in row.chunks_exact_mut(18) { + let e = 8 + (xorshift(&mut seed) % 8) as u16; + let m = (xorshift(&mut seed) & 0x3ff) as u16; + b[..2].copy_from_slice(&((e << 10) | m).to_le_bytes()); + } + for nt in 1..=8usize { + let refs: Vec<&ActQ> = acts[..nt].iter().collect(); + let mut out = vec![0.0f32; nt]; + // SAFETY: avx2_ok() above; rows have at most 40 blocks and at most 8 tokens. + unsafe { + dot256(&row, &refs, &mut out); + } + for t in 0..nt { + assert_eq!( + out[t].to_bits(), + model(&row, &acts[t], true).to_bits(), + "blocks {nb} nt {nt} token {t}" + ); + if model(&row, &acts[t], false).to_bits() != out[t].to_bits() { + unfused_differs += 1; + } + } + } + } + } + assert!(unfused_differs > 0, "the unfused correction must be distinguishable from the fused one on this data"); + } + #[test] + fn rows_longer_than_the_activation_are_refused_before_any_load() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + let a = ActQ::default(); + let row = vec![0u8; 41 * 18]; + let mut out = [0.0f32]; + // SAFETY: avx2_ok() above; the over-long row panics at the entry assert before any vector load. + assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row, &[&a], &mut out) })).is_err()); + // SAFETY: avx2_ok() above; 720 bytes = 40 blocks, the largest row an ActQ covers. + assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot256(&row[..40 * 18], &[&a], &mut out) })).is_ok()); + if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() { + // SAFETY: avx512_ok()+dq_ok() above; same bounds as the AVX2 leaf. + assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row, &[&a], &mut out) })).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| unsafe { dot512(&row[..40 * 18], &[&a], &mut out) })).is_ok()); + } } - } - } - assert!(unfused_differs>0,"the unfused correction must be distinguishable from the fused one on this data"); - } - #[test] - fn rows_longer_than_the_activation_are_refused_before_any_load() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - let a=ActQ::default();let row=vec![0u8;41*18];let mut out=[0.0f32]; - // SAFETY: avx2_ok() above; the over-long row panics at the entry assert before any vector load. - assert!(catch_unwind(AssertUnwindSafe(||unsafe{dot256(&row,&[&a],&mut out)})).is_err()); - // SAFETY: avx2_ok() above; 720 bytes = 40 blocks, the largest row an ActQ covers. - assert!(catch_unwind(AssertUnwindSafe(||unsafe{dot256(&row[..40*18],&[&a],&mut out)})).is_ok()); - if super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok(){ - // SAFETY: avx512_ok()+dq_ok() above; same bounds as the AVX2 leaf. - assert!(catch_unwind(AssertUnwindSafe(||unsafe{dot512(&row,&[&a],&mut out)})).is_err()); - assert!(catch_unwind(AssertUnwindSafe(||unsafe{dot512(&row[..40*18],&[&a],&mut out)})).is_ok()); - } - } } diff --git a/crates/native-cpu-expert/src/rust_quant.rs b/crates/native-cpu-expert/src/rust_quant.rs index 446ffd68..76d4bf0d 100644 --- a/crates/native-cpu-expert/src/rust_quant.rs +++ b/crates/native-cpu-expert/src/rust_quant.rs @@ -1,151 +1,354 @@ //! Literal Original and pinned GGML activation quantizers. -use std::arch::x86_64::*; -use super::rust_types::{ActQ,Q8K,Q8Zero}; use super::rust_simd::to_half; +use super::rust_types::{ActQ, Q8K, Q8Zero}; +use std::arch::x86_64::*; // Bounds: q8_zero asserts x.len()==32*y.len() and stores 32 i8 per Q8Zero; q8_one_* assert x.len()<=2560 && %32==0, so // every store lands in a.q[..x.len()] (H = 2560 i8) and a.scale/sum/hx[..x.len()/32] (80 entries); all vector accesses // are unaligned (loadu/storeu). Gate: see rust_simd.rs SAFETY CONTRACT. // ggml nearest_int: signed bit-bias rounding; inputs bounded by signed maximum. -fn nearest_int(x:f32)->i32 {debug_assert!(x.abs()<=4_194_303.0);let y=x+12_582_912.0; (y.to_bits()&0x007f_ffff) as i32-0x0040_0000} -pub(super) fn q8_k(x:&[f32],y:&mut [Q8K]) { - assert_eq!(x.len(),256*y.len()); - for (xb,y) in x.chunks_exact(256).zip(y) { - let mut max=0.0f32;let mut amax=0.0f32; - for &x in xb {let ax=x.abs();if ax>amax{amax=ax;max=x;}} - if amax==0.0 {y.d=0.0;y.qs.fill(0);continue;} - let iscale=-127.0/max; - for (q,&x) in y.qs.iter_mut().zip(xb) {*q=nearest_int(iscale*x).min(127) as i8;} - for (sum,q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)){*sum=q.iter().map(|&v|v as i32).sum::() as i16;} - y.d=1.0/iscale; - } +fn nearest_int(x: f32) -> i32 { + debug_assert!(x.abs() <= 4_194_303.0); + let y = x + 12_582_912.0; + (y.to_bits() & 0x007f_ffff) as i32 - 0x0040_0000 +} +pub(super) fn q8_k(x: &[f32], y: &mut [Q8K]) { + assert_eq!(x.len(), 256 * y.len()); + for (xb, y) in x.chunks_exact(256).zip(y) { + let mut max = 0.0f32; + let mut amax = 0.0f32; + for &x in xb { + let ax = x.abs(); + if ax > amax { + amax = ax; + max = x; + } + } + if amax == 0.0 { + y.d = 0.0; + y.qs.fill(0); + continue; + } + let iscale = -127.0 / max; + for (q, &x) in y.qs.iter_mut().zip(xb) { + *q = nearest_int(iscale * x).min(127) as i8; + } + for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) { + *sum = q.iter().map(|&v| v as i32).sum::() as i16; + } + y.d = 1.0 / iscale; + } } /// `LELEKA_Q8K=legacy` keeps the scalar `q8_k` on the borrowed-group path (A/B arm); the default there is `q8_k_avx2`. -pub(super) fn q8k_fast()->bool{static ON:std::sync::OnceLock=std::sync::OnceLock::new();*ON.get_or_init(||std::env::var("LELEKA_Q8K").as_deref()!=Ok("legacy"))} +pub(super) fn q8k_fast() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LELEKA_Q8K").as_deref() != Ok("legacy")) +} /// `q8_k` with the 256 products, roundings and the clamp in 256-bit lanes: the same IEEE multiply `iscale*x`, the same magic-number /// `nearest_int` (add 12582912, mantissa bits), `min(127)`; the signed maximum is the FIRST element of largest magnitude (the scalar loop's /// strict `>`), `d = 1/iscale`, `bsums` summed as before, and an all-zero block leaves `bsums` as the scalar one does. Inputs must be finite /// (the caller's check), so no NaN reaches the maximum. Bitwise `q8_k` (`q8_k_avx2_is_bitwise_q8_k`). -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q8_k_avx2(x:&[f32],y:&mut [Q8K]) {unsafe { - assert_eq!(x.len(),256*y.len()); - for (xb,y) in x.chunks_exact(256).zip(y) { - let sign=_mm256_set1_ps(-0.0);let mut m=_mm256_setzero_ps(); - for c in 0..32 {m=_mm256_max_ps(m,_mm256_andnot_ps(sign,_mm256_loadu_ps(xb.as_ptr().add(8*c))));} - let mut h=_mm_max_ps(_mm256_extractf128_ps::<1>(m),_mm256_castps256_ps128(m));h=_mm_max_ps(h,_mm_movehl_ps(h,h));h=_mm_max_ss(h,_mm_movehdup_ps(h)); - let amax=_mm_cvtss_f32(h); - if amax==0.0 {y.d=0.0;y.qs.fill(0);continue;} - let max=*xb.iter().find(|v|v.abs()==amax).unwrap_or(&amax); - let iscale=-127.0/max;let vs=_mm256_set1_ps(iscale);let magic=_mm256_set1_ps(12_582_912.0);let mant=_mm256_set1_epi32(0x007f_ffff);let bias=_mm256_set1_epi32(0x0040_0000);let top=_mm256_set1_epi32(127); - let q=|c:usize|{let v=_mm256_add_ps(_mm256_mul_ps(vs,_mm256_loadu_ps(xb.as_ptr().add(8*c))),magic);_mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(v),mant),bias),top)}; - for g in 0..8 { - let a=_mm256_packs_epi32(q(4*g),q(4*g+1));let b=_mm256_packs_epi32(q(4*g+2),q(4*g+3)); - let p=_mm256_permutevar8x32_epi32(_mm256_packs_epi16(a,b),_mm256_setr_epi32(0,4,1,5,2,6,3,7)); - _mm256_storeu_si256(y.qs.as_mut_ptr().add(32*g).cast(),p); - } - for (sum,q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)){*sum=q.iter().map(|&v|v as i32).sum::() as i16;} - y.d=1.0/iscale; - } -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q8_zero(x:&[f32],y:&mut [Q8Zero]) {unsafe { - assert_eq!(x.len(),32*y.len()); - for (xb,y) in x.chunks_exact(32).zip(y) { - let mut v0=_mm256_loadu_ps(xb.as_ptr());let mut v1=_mm256_loadu_ps(xb.as_ptr().add(8));let mut v2=_mm256_loadu_ps(xb.as_ptr().add(16));let mut v3=_mm256_loadu_ps(xb.as_ptr().add(24)); - let sign=_mm256_set1_ps(-0.0);let mut m=_mm256_andnot_ps(sign,v0); - m=_mm256_max_ps(m,_mm256_andnot_ps(sign,v1));m=_mm256_max_ps(m,_mm256_andnot_ps(sign,v2));m=_mm256_max_ps(m,_mm256_andnot_ps(sign,v3)); - let mut h=_mm_max_ps(_mm256_extractf128_ps::<1>(m),_mm256_castps256_ps128(m));h=_mm_max_ps(h,_mm_movehl_ps(h,h));h=_mm_max_ss(h,_mm_movehdup_ps(h)); - let amax=_mm_cvtss_f32(h);let d=amax/127.0;y.d=to_half(d); - let inv=_mm256_set1_ps(if amax!=0.0 {127.0/amax}else{0.0}); - v0=_mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v0,inv));v1=_mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v1,inv));v2=_mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v2,inv));v3=_mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v3,inv)); - let i0=_mm256_packs_epi32(_mm256_cvtps_epi32(v0),_mm256_cvtps_epi32(v1));let i2=_mm256_packs_epi32(_mm256_cvtps_epi32(v2),_mm256_cvtps_epi32(v3)); - let i0=_mm256_packs_epi16(i0,i2);let i0=_mm256_permutevar8x32_epi32(i0,_mm256_setr_epi32(0,4,1,5,2,6,3,7)); - _mm256_storeu_si256(y.qs.as_mut_ptr().cast(),i0); - } -}} -#[target_feature(enable="avx2,fma,f16c")] -pub(super) unsafe fn q8_one_avx2(x:&[f32],a:&mut ActQ) {unsafe { - assert!(x.len()<=2560&&x.len()%32==0);a.nchunks=(x.len()/32)as i32; - let absmask=_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));let half=_mm256_set1_ps(0.5);let mhalf=_mm256_set1_ps(-0.5);let zero=_mm256_setzero_ps();let lo=_mm256_set1_epi32(-127);let hi=_mm256_set1_epi32(127); - for (k,xb) in x.chunks_exact(32).enumerate() { - let mut v=[_mm256_setzero_ps();4];let mut m=_mm256_setzero_ps(); - for i in 0..4 {v[i]=_mm256_loadu_ps(xb.as_ptr().add(8*i));m=_mm256_max_ps(m,_mm256_and_ps(v[i],absmask));} - let mut h=_mm_max_ps(_mm256_castps256_ps128(m),_mm256_extractf128_ps::<1>(m));h=_mm_max_ps(h,_mm_movehl_ps(h,h));let amax=_mm_cvtss_f32(_mm_max_ss(h,_mm_movehdup_ps(h))); - let s=if amax>0.0{amax/127.0}else{0.0};let inv=if s>0.0{1.0/s}else{0.0};let vinv=_mm256_set1_ps(inv);let mut sum=_mm256_setzero_si256();let mut qi=[0i32;32]; - for i in 0..4 {let t=_mm256_mul_ps(v[i],vinv);let r=_mm256_add_ps(t,_mm256_blendv_ps(mhalf,half,_mm256_cmp_ps::<_CMP_GE_OQ>(t,zero)));let q=_mm256_min_epi32(_mm256_max_epi32(_mm256_cvttps_epi32(r),lo),hi);sum=_mm256_add_epi32(sum,q);_mm256_storeu_si256(qi.as_mut_ptr().add(8*i).cast(),q);} - for (j,&q) in qi.iter().enumerate(){a.q[k*32+j]=q as i8;} - let mut s4=_mm_add_epi32(_mm256_castsi256_si128(sum),_mm256_extracti128_si256::<1>(sum));s4=_mm_add_epi32(s4,_mm_shuffle_epi32::<0x4e>(s4));s4=_mm_add_epi32(s4,_mm_shuffle_epi32::<0xb1>(s4));let total=_mm_cvtsi128_si32(s4); - a.scale[k]=s;a.sum[k]=total;a.hx[k]=s*total as f32; - } -}} -#[target_feature(enable="avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")] -pub(super) unsafe fn q8_one_avx512(x:&[f32],a:&mut ActQ) {unsafe { - assert!(x.len()<=2560&&x.len()%32==0);a.nchunks=(x.len()/32)as i32; - let half=_mm512_set1_ps(0.5);let mhalf=_mm512_set1_ps(-0.5);let zero=_mm512_setzero_ps();let lo=_mm512_set1_epi32(-127);let hi=_mm512_set1_epi32(127);let absmask=_mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff)); - for (k,xb) in x.chunks_exact(32).enumerate() { - let x0=_mm512_loadu_ps(xb.as_ptr());let x1=_mm512_loadu_ps(xb.as_ptr().add(16));let amax=_mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0,absmask),_mm512_and_ps(x1,absmask))); - let s=if amax>0.0{amax/127.0}else{0.0};let inv=if s>0.0{1.0/s}else{0.0};let vinv=_mm512_set1_ps(inv);let t0=_mm512_mul_ps(x0,vinv);let t1=_mm512_mul_ps(x1,vinv); - let r0=_mm512_add_ps(t0,_mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t0,zero),mhalf,half));let r1=_mm512_add_ps(t1,_mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t1,zero),mhalf,half)); - let v0=_mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r0),lo),hi);let v1=_mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r1),lo),hi); - _mm_storeu_si128(a.q.as_mut_ptr().add(k*32).cast(),_mm512_cvtepi32_epi8(v0));_mm_storeu_si128(a.q.as_mut_ptr().add(k*32+16).cast(),_mm512_cvtepi32_epi8(v1)); - let sum=_mm512_reduce_add_epi32(_mm512_add_epi32(v0,v1));a.scale[k]=s;a.sum[k]=sum;a.hx[k]=s*sum as f32; - } -}} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q8_k_avx2(x: &[f32], y: &mut [Q8K]) { + unsafe { + assert_eq!(x.len(), 256 * y.len()); + for (xb, y) in x.chunks_exact(256).zip(y) { + let sign = _mm256_set1_ps(-0.0); + let mut m = _mm256_setzero_ps(); + for c in 0..32 { + m = _mm256_max_ps(m, _mm256_andnot_ps(sign, _mm256_loadu_ps(xb.as_ptr().add(8 * c)))); + } + let mut h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + h = _mm_max_ss(h, _mm_movehdup_ps(h)); + let amax = _mm_cvtss_f32(h); + if amax == 0.0 { + y.d = 0.0; + y.qs.fill(0); + continue; + } + let max = *xb.iter().find(|v| v.abs() == amax).unwrap_or(&amax); + let iscale = -127.0 / max; + let vs = _mm256_set1_ps(iscale); + let magic = _mm256_set1_ps(12_582_912.0); + let mant = _mm256_set1_epi32(0x007f_ffff); + let bias = _mm256_set1_epi32(0x0040_0000); + let top = _mm256_set1_epi32(127); + let q = |c: usize| { + let v = _mm256_add_ps(_mm256_mul_ps(vs, _mm256_loadu_ps(xb.as_ptr().add(8 * c))), magic); + _mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(v), mant), bias), top) + }; + for g in 0..8 { + let a = _mm256_packs_epi32(q(4 * g), q(4 * g + 1)); + let b = _mm256_packs_epi32(q(4 * g + 2), q(4 * g + 3)); + let p = + _mm256_permutevar8x32_epi32(_mm256_packs_epi16(a, b), _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); + _mm256_storeu_si256(y.qs.as_mut_ptr().add(32 * g).cast(), p); + } + for (sum, q) in y.bsums.iter_mut().zip(y.qs.chunks_exact(16)) { + *sum = q.iter().map(|&v| v as i32).sum::() as i16; + } + y.d = 1.0 / iscale; + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q8_zero(x: &[f32], y: &mut [Q8Zero]) { + unsafe { + assert_eq!(x.len(), 32 * y.len()); + for (xb, y) in x.chunks_exact(32).zip(y) { + let mut v0 = _mm256_loadu_ps(xb.as_ptr()); + let mut v1 = _mm256_loadu_ps(xb.as_ptr().add(8)); + let mut v2 = _mm256_loadu_ps(xb.as_ptr().add(16)); + let mut v3 = _mm256_loadu_ps(xb.as_ptr().add(24)); + let sign = _mm256_set1_ps(-0.0); + let mut m = _mm256_andnot_ps(sign, v0); + m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v1)); + m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v2)); + m = _mm256_max_ps(m, _mm256_andnot_ps(sign, v3)); + let mut h = _mm_max_ps(_mm256_extractf128_ps::<1>(m), _mm256_castps256_ps128(m)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + h = _mm_max_ss(h, _mm_movehdup_ps(h)); + let amax = _mm_cvtss_f32(h); + let d = amax / 127.0; + y.d = to_half(d); + let inv = _mm256_set1_ps(if amax != 0.0 { 127.0 / amax } else { 0.0 }); + v0 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v0, inv)); + v1 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v1, inv)); + v2 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v2, inv)); + v3 = _mm256_round_ps::<_MM_FROUND_TO_NEAREST_INT>(_mm256_mul_ps(v3, inv)); + let i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1)); + let i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3)); + let i0 = _mm256_packs_epi16(i0, i2); + let i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); + _mm256_storeu_si256(y.qs.as_mut_ptr().cast(), i0); + } + } +} +#[target_feature(enable = "avx2,fma,f16c")] +pub(super) unsafe fn q8_one_avx2(x: &[f32], a: &mut ActQ) { + unsafe { + assert!(x.len() <= 2560 && x.len() % 32 == 0); + a.nchunks = (x.len() / 32) as i32; + let absmask = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)); + let half = _mm256_set1_ps(0.5); + let mhalf = _mm256_set1_ps(-0.5); + let zero = _mm256_setzero_ps(); + let lo = _mm256_set1_epi32(-127); + let hi = _mm256_set1_epi32(127); + for (k, xb) in x.chunks_exact(32).enumerate() { + let mut v = [_mm256_setzero_ps(); 4]; + let mut m = _mm256_setzero_ps(); + for i in 0..4 { + v[i] = _mm256_loadu_ps(xb.as_ptr().add(8 * i)); + m = _mm256_max_ps(m, _mm256_and_ps(v[i], absmask)); + } + let mut h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps::<1>(m)); + h = _mm_max_ps(h, _mm_movehl_ps(h, h)); + let amax = _mm_cvtss_f32(_mm_max_ss(h, _mm_movehdup_ps(h))); + let s = if amax > 0.0 { amax / 127.0 } else { 0.0 }; + let inv = if s > 0.0 { 1.0 / s } else { 0.0 }; + let vinv = _mm256_set1_ps(inv); + let mut sum = _mm256_setzero_si256(); + let mut qi = [0i32; 32]; + for i in 0..4 { + let t = _mm256_mul_ps(v[i], vinv); + let r = _mm256_add_ps(t, _mm256_blendv_ps(mhalf, half, _mm256_cmp_ps::<_CMP_GE_OQ>(t, zero))); + let q = _mm256_min_epi32(_mm256_max_epi32(_mm256_cvttps_epi32(r), lo), hi); + sum = _mm256_add_epi32(sum, q); + _mm256_storeu_si256(qi.as_mut_ptr().add(8 * i).cast(), q); + } + for (j, &q) in qi.iter().enumerate() { + a.q[k * 32 + j] = q as i8; + } + let mut s4 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256::<1>(sum)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0x4e>(s4)); + s4 = _mm_add_epi32(s4, _mm_shuffle_epi32::<0xb1>(s4)); + let total = _mm_cvtsi128_si32(s4); + a.scale[k] = s; + a.sum[k] = total; + a.hx[k] = s * total as f32; + } + } +} +#[target_feature(enable = "avx512f,avx512bw,avx512vl,avx512dq,f16c,fma")] +pub(super) unsafe fn q8_one_avx512(x: &[f32], a: &mut ActQ) { + unsafe { + assert!(x.len() <= 2560 && x.len() % 32 == 0); + a.nchunks = (x.len() / 32) as i32; + let half = _mm512_set1_ps(0.5); + let mhalf = _mm512_set1_ps(-0.5); + let zero = _mm512_setzero_ps(); + let lo = _mm512_set1_epi32(-127); + let hi = _mm512_set1_epi32(127); + let absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff)); + for (k, xb) in x.chunks_exact(32).enumerate() { + let x0 = _mm512_loadu_ps(xb.as_ptr()); + let x1 = _mm512_loadu_ps(xb.as_ptr().add(16)); + let amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask))); + let s = if amax > 0.0 { amax / 127.0 } else { 0.0 }; + let inv = if s > 0.0 { 1.0 / s } else { 0.0 }; + let vinv = _mm512_set1_ps(inv); + let t0 = _mm512_mul_ps(x0, vinv); + let t1 = _mm512_mul_ps(x1, vinv); + let r0 = _mm512_add_ps(t0, _mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t0, zero), mhalf, half)); + let r1 = _mm512_add_ps(t1, _mm512_mask_blend_ps(_mm512_cmp_ps_mask::<_CMP_GE_OQ>(t1, zero), mhalf, half)); + let v0 = _mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r0), lo), hi); + let v1 = _mm512_min_epi32(_mm512_max_epi32(_mm512_cvttps_epi32(r1), lo), hi); + _mm_storeu_si128(a.q.as_mut_ptr().add(k * 32).cast(), _mm512_cvtepi32_epi8(v0)); + _mm_storeu_si128(a.q.as_mut_ptr().add(k * 32 + 16).cast(), _mm512_cvtepi32_epi8(v1)); + let sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1)); + a.scale[k] = s; + a.sum[k] = sum; + a.hx[k] = s * sum as f32; + } + } +} #[cfg(test)] mod tests { - use super::*; - // Original expert.cpp scalar rule, evaluated FIRST without SIMD quantization. - // This bounded transport-free oracle covers tie rounding and the whole public - // activation extent. It does not qualify IQ dots or model output. - fn original_scalar(x:&[f32])->ActQ { - let mut a=ActQ::default();a.nchunks=(x.len()/32)as i32; - for (k,xb) in x.chunks_exact(32).enumerate() { - let mut maximum=0.0f32;for &value in xb{maximum=maximum.max(value.abs());} - let scale=if maximum>0.0{maximum/127.0}else{0.0}; - let inv=if scale>0.0{1.0/scale}else{0.0};let mut sum=0i32; - for (j,&value) in xb.iter().enumerate(){let t=value*inv;let rounded=t+if t>=0.0{0.5}else{-0.5};let q=(rounded as i32).clamp(-127,127);a.q[k*32+j]=q as i8;sum+=q;} - a.scale[k]=scale;a.sum[k]=sum;a.hx[k]=scale*sum as f32; - }a - } - fn exact(actual:&ActQ,expected:&ActQ,n:usize){ - assert_eq!(actual.nchunks,expected.nchunks);assert_eq!(&actual.q[..n],&expected.q[..n]); - assert_eq!(&actual.sum[..n/32],&expected.sum[..n/32]); - for k in 0..n/32{assert_eq!(actual.scale[k].to_bits(),expected.scale[k].to_bits());assert_eq!(actual.hx[k].to_bits(),expected.hx[k].to_bits());} - } - #[test] - fn original_scalar_first_q8_one_ties_zero_and_full_rows() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP: Original AVX2/F16C/FMA capability required");return;} - for n in [640usize,2560]{for changed in [false,true]{ - let mut x=vec![0.0f32;n]; - for (i,value) in x.iter_mut().enumerate(){*value=match i%32{0=>127.0,1=>-127.0,2=>0.5,3=>-0.5,4=>1.5,5=>-1.5,6=>0.0,7=>-0.0,_=>if changed{(i%61)as f32-30.0}else{(i%47)as f32-23.0}};} - let expected=original_scalar(&x);let mut actual=ActQ::default(); - // SAFETY: actual CPUID/XCR0 admission above; whole sanitized arrays. - unsafe {q8_one_avx2(&x,&mut actual);}exact(&actual,&expected,n); - if super::super::rust_simd::avx512_ok()&&super::super::rust_simd::dq_ok(){unsafe {q8_one_avx512(&x,&mut actual);}exact(&actual,&expected,n);} - x.fill(-0.0);let expected=original_scalar(&x);unsafe {q8_one_avx2(&x,&mut actual);}exact(&actual,&expected,n); - }} - } + use super::*; + // Original expert.cpp scalar rule, evaluated FIRST without SIMD quantization. + // This bounded transport-free oracle covers tie rounding and the whole public + // activation extent. It does not qualify IQ dots or model output. + fn original_scalar(x: &[f32]) -> ActQ { + let mut a = ActQ::default(); + a.nchunks = (x.len() / 32) as i32; + for (k, xb) in x.chunks_exact(32).enumerate() { + let mut maximum = 0.0f32; + for &value in xb { + maximum = maximum.max(value.abs()); + } + let scale = if maximum > 0.0 { maximum / 127.0 } else { 0.0 }; + let inv = if scale > 0.0 { 1.0 / scale } else { 0.0 }; + let mut sum = 0i32; + for (j, &value) in xb.iter().enumerate() { + let t = value * inv; + let rounded = t + if t >= 0.0 { 0.5 } else { -0.5 }; + let q = (rounded as i32).clamp(-127, 127); + a.q[k * 32 + j] = q as i8; + sum += q; + } + a.scale[k] = scale; + a.sum[k] = sum; + a.hx[k] = scale * sum as f32; + } + a + } + fn exact(actual: &ActQ, expected: &ActQ, n: usize) { + assert_eq!(actual.nchunks, expected.nchunks); + assert_eq!(&actual.q[..n], &expected.q[..n]); + assert_eq!(&actual.sum[..n / 32], &expected.sum[..n / 32]); + for k in 0..n / 32 { + assert_eq!(actual.scale[k].to_bits(), expected.scale[k].to_bits()); + assert_eq!(actual.hx[k].to_bits(), expected.hx[k].to_bits()); + } + } + #[test] + fn original_scalar_first_q8_one_ties_zero_and_full_rows() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP: Original AVX2/F16C/FMA capability required"); + return; + } + for n in [640usize, 2560] { + for changed in [false, true] { + let mut x = vec![0.0f32; n]; + for (i, value) in x.iter_mut().enumerate() { + *value = match i % 32 { + 0 => 127.0, + 1 => -127.0, + 2 => 0.5, + 3 => -0.5, + 4 => 1.5, + 5 => -1.5, + 6 => 0.0, + 7 => -0.0, + _ => { + if changed { + (i % 61) as f32 - 30.0 + } else { + (i % 47) as f32 - 23.0 + } + } + }; + } + let expected = original_scalar(&x); + let mut actual = ActQ::default(); + // SAFETY: actual CPUID/XCR0 admission above; whole sanitized arrays. + unsafe { + q8_one_avx2(&x, &mut actual); + } + exact(&actual, &expected, n); + if super::super::rust_simd::avx512_ok() && super::super::rust_simd::dq_ok() { + unsafe { + q8_one_avx512(&x, &mut actual); + } + exact(&actual, &expected, n); + } + x.fill(-0.0); + let expected = original_scalar(&x); + unsafe { + q8_one_avx2(&x, &mut actual); + } + exact(&actual, &expected, n); + } + } + } } #[cfg(test)] mod q8k_tests { - use super::*; - fn xorshift(s:&mut u64)->u64 {*s^=*s<<13;*s^=*s>>7;*s^=*s<<17;*s} - #[test] - fn q8_k_avx2_is_bitwise_q8_k() { - if !super::super::rust_simd::avx2_ok(){eprintln!("SKIP");return;} - let mut seed=0x7a11_5eed_0102_0304u64; - for round in 0..400 { - let nb=10;let scale=[1e-6f32,1e-3,0.5,3.0,1e3,3e4][round%6]; - let mut x:Vec=(0..nb*256).map(|_|((xorshift(&mut seed)%200001)as f32-100000.0)*scale/1e5).collect(); - // ties of magnitude with both signs, zero blocks, rounding-half cases - if round%5==1 {x[3]=7.0*scale;x[200]=-7.0*scale;for v in x[256..512].iter_mut(){*v=0.0;}} - if round%5==2 {let m=x[..256].iter().fold(0.0f32,|a,v|a.max(v.abs()));x[10]=-m;x[11]=m;} - if round%5==3 {for (i,v) in x.iter_mut().enumerate().take(256){*v=(i as f32-128.0)*0.5;}} - let mut a=vec![Q8K::default();nb];let mut b=vec![Q8K::default();nb]; - for (i,(p,q)) in a.iter_mut().zip(b.iter_mut()).enumerate(){p.bsums=[i as i16;16];q.bsums=[i as i16;16];} - q8_k(&x,&mut a);unsafe {q8_k_avx2(&x,&mut b);} - for (i,(p,q)) in a.iter().zip(&b).enumerate(){assert_eq!(p.d.to_bits(),q.d.to_bits(),"d round {round} block {i}");assert_eq!(p.qs,q.qs,"qs round {round} block {i}");assert_eq!(p.bsums,q.bsums,"bsums round {round} block {i}");} - } - } + use super::*; + fn xorshift(s: &mut u64) -> u64 { + *s ^= *s << 13; + *s ^= *s >> 7; + *s ^= *s << 17; + *s + } + #[test] + fn q8_k_avx2_is_bitwise_q8_k() { + if !super::super::rust_simd::avx2_ok() { + eprintln!("SKIP"); + return; + } + let mut seed = 0x7a11_5eed_0102_0304u64; + for round in 0..400 { + let nb = 10; + let scale = [1e-6f32, 1e-3, 0.5, 3.0, 1e3, 3e4][round % 6]; + let mut x: Vec = + (0..nb * 256).map(|_| ((xorshift(&mut seed) % 200001) as f32 - 100000.0) * scale / 1e5).collect(); + // ties of magnitude with both signs, zero blocks, rounding-half cases + if round % 5 == 1 { + x[3] = 7.0 * scale; + x[200] = -7.0 * scale; + for v in x[256..512].iter_mut() { + *v = 0.0; + } + } + if round % 5 == 2 { + let m = x[..256].iter().fold(0.0f32, |a, v| a.max(v.abs())); + x[10] = -m; + x[11] = m; + } + if round % 5 == 3 { + for (i, v) in x.iter_mut().enumerate().take(256) { + *v = (i as f32 - 128.0) * 0.5; + } + } + let mut a = vec![Q8K::default(); nb]; + let mut b = vec![Q8K::default(); nb]; + for (i, (p, q)) in a.iter_mut().zip(b.iter_mut()).enumerate() { + p.bsums = [i as i16; 16]; + q.bsums = [i as i16; 16]; + } + q8_k(&x, &mut a); + unsafe { + q8_k_avx2(&x, &mut b); + } + for (i, (p, q)) in a.iter().zip(&b).enumerate() { + assert_eq!(p.d.to_bits(), q.d.to_bits(), "d round {round} block {i}"); + assert_eq!(p.qs, q.qs, "qs round {round} block {i}"); + assert_eq!(p.bsums, q.bsums, "bsums round {round} block {i}"); + } + } + } } diff --git a/crates/native-cpu-expert/src/rust_quant_grids.rs b/crates/native-cpu-expert/src/rust_quant_grids.rs index 22c6eb3e..409a3f6b 100644 --- a/crates/native-cpu-expert/src/rust_quant_grids.rs +++ b/crates/native-cpu-expert/src/rust_quant_grids.rs @@ -1,301 +1,276 @@ //! Literal pinned GGML model-quantizer grid indices, not regenerated grids. -pub(super) const KGRID_2BIT_256: [u16;256] = [ -0,2,5,8,10,17,20,32,34,40,42,65,68,80,88,97, -100,128,130,138,162,257,260,272,277,320,388,408,512,514,546,642, -1025,1028,1040,1057,1060,1088,1090,1096,1120,1153,1156,1168,1188,1280,1282,1288, -1312,1350,1385,1408,1425,1545,1552,1600,1668,1700,2048,2053,2056,2068,2088,2113, -2116,2128,2130,2184,2308,2368,2562,2580,4097,4100,4112,4129,4160,4192,4228,4240, -4245,4352,4360,4384,4432,4442,4480,4644,4677,5120,5128,5152,5157,5193,5248,5400, -5474,5632,5654,6145,6148,6160,6208,6273,6400,6405,6560,6737,8192,8194,8202,8260, -8289,8320,8322,8489,8520,8704,8706,9217,9220,9232,9280,9302,9472,9537,9572,9872, -10248,10272,10388,10820,16385,16388,16400,16408,16417,16420,16448,16456,16470,16480,16513,16516, -16528,16640,16672,16737,16768,16773,16897,16912,16968,16982,17000,17408,17416,17440,17536,17561, -17682,17700,17920,18433,18436,18448,18496,18501,18688,18776,18785,18818,19013,19088,20480,20488, -20497,20505,20512,20608,20616,20740,20802,20900,21137,21648,21650,21770,22017,22100,22528,22545, -22553,22628,22848,23048,24580,24592,24640,24680,24832,24917,25112,25184,25600,25605,25872,25874, -25988,26690,32768,32770,32778,32833,32898,33028,33048,33088,33297,33793,33796,33808,33813,33856, -33888,34048,34118,34196,34313,34368,34400,34818,35076,35345,36868,36880,36900,36928,37025,37142, -37248,37445,37888,37922,37956,38225,39041,39200,40962,41040,41093,41225,41472,42008,43088,43268, +pub(super) const KGRID_2BIT_256: [u16; 256] = [ + 0, 2, 5, 8, 10, 17, 20, 32, 34, 40, 42, 65, 68, 80, 88, 97, 100, 128, 130, 138, 162, 257, 260, 272, 277, 320, 388, + 408, 512, 514, 546, 642, 1025, 1028, 1040, 1057, 1060, 1088, 1090, 1096, 1120, 1153, 1156, 1168, 1188, 1280, 1282, + 1288, 1312, 1350, 1385, 1408, 1425, 1545, 1552, 1600, 1668, 1700, 2048, 2053, 2056, 2068, 2088, 2113, 2116, 2128, + 2130, 2184, 2308, 2368, 2562, 2580, 4097, 4100, 4112, 4129, 4160, 4192, 4228, 4240, 4245, 4352, 4360, 4384, 4432, + 4442, 4480, 4644, 4677, 5120, 5128, 5152, 5157, 5193, 5248, 5400, 5474, 5632, 5654, 6145, 6148, 6160, 6208, 6273, + 6400, 6405, 6560, 6737, 8192, 8194, 8202, 8260, 8289, 8320, 8322, 8489, 8520, 8704, 8706, 9217, 9220, 9232, 9280, + 9302, 9472, 9537, 9572, 9872, 10248, 10272, 10388, 10820, 16385, 16388, 16400, 16408, 16417, 16420, 16448, 16456, + 16470, 16480, 16513, 16516, 16528, 16640, 16672, 16737, 16768, 16773, 16897, 16912, 16968, 16982, 17000, 17408, + 17416, 17440, 17536, 17561, 17682, 17700, 17920, 18433, 18436, 18448, 18496, 18501, 18688, 18776, 18785, 18818, + 19013, 19088, 20480, 20488, 20497, 20505, 20512, 20608, 20616, 20740, 20802, 20900, 21137, 21648, 21650, 21770, + 22017, 22100, 22528, 22545, 22553, 22628, 22848, 23048, 24580, 24592, 24640, 24680, 24832, 24917, 25112, 25184, + 25600, 25605, 25872, 25874, 25988, 26690, 32768, 32770, 32778, 32833, 32898, 33028, 33048, 33088, 33297, 33793, + 33796, 33808, 33813, 33856, 33888, 34048, 34118, 34196, 34313, 34368, 34400, 34818, 35076, 35345, 36868, 36880, + 36900, 36928, 37025, 37142, 37248, 37445, 37888, 37922, 37956, 38225, 39041, 39200, 40962, 41040, 41093, 41225, + 41472, 42008, 43088, 43268, ]; -pub(super) const KGRID_2BIT_512: [u16;512] = [ -0,2,5,8,10,17,20,22,25,32,34,37,40,65,68,70, -73,80,82,85,88,97,100,128,130,133,136,145,148,153,160,257, -260,262,265,272,274,277,280,282,289,292,320,322,325,328,337,340, -352,360,385,388,400,512,514,517,520,529,532,544,577,580,592,597, -640,650,1025,1028,1030,1033,1040,1042,1045,1048,1057,1060,1088,1090,1093,1096, -1105,1108,1110,1120,1153,1156,1168,1280,1282,1285,1288,1297,1300,1312,1345,1348, -1360,1377,1408,1537,1540,1552,1574,1600,1602,1668,2048,2050,2053,2056,2058,2065, -2068,2080,2085,2113,2116,2128,2136,2176,2208,2218,2305,2308,2320,2368,2433,2441, -2560,2592,2600,2710,2720,4097,4100,4102,4105,4112,4114,4117,4120,4129,4132,4160, -4162,4165,4168,4177,4180,4192,4202,4225,4228,4240,4352,4354,4357,4360,4369,4372, -4384,4417,4420,4432,4480,4500,4502,4609,4612,4614,4624,4672,4704,5120,5122,5125, -5128,5137,5140,5152,5185,5188,5193,5200,5220,5248,5377,5380,5392,5440,5632,5652, -5705,6145,6148,6160,6162,6208,6228,6278,6400,6405,6502,6737,6825,8192,8194,8197, -8200,8202,8209,8212,8224,8257,8260,8272,8320,8352,8449,8452,8464,8512,8520,8549, -8704,8738,8832,8872,9217,9220,9232,9257,9280,9472,9537,9554,9625,9729,9754,9894, -10240,10248,10250,10272,10325,10376,10402,10600,10640,10760,10784,10882,10888,10890,16385,16388, -16390,16393,16400,16402,16405,16408,16417,16420,16448,16450,16453,16456,16458,16465,16468,16480, -16485,16513,16516,16528,16640,16642,16645,16648,16657,16660,16672,16705,16708,16720,16768,16773, -16802,16897,16900,16912,16914,16937,16960,17408,17410,17413,17416,17425,17428,17433,17440,17473, -17476,17488,17536,17556,17665,17668,17680,17700,17728,17818,17920,17930,17988,18000,18433,18436, -18448,18496,18501,18516,18530,18688,18705,18756,18768,18793,18948,20480,20482,20485,20488,20497, -20500,20512,20520,20545,20548,20560,20608,20737,20740,20752,20757,20800,20802,20992,21060,21162, -21505,21508,21520,21537,21568,21600,21633,21665,21760,21768,21888,21896,22049,22120,22177,22528, -22548,22593,22608,22681,22810,22848,22850,23173,24577,24580,24592,24640,24660,24674,24710,24745, -24832,25124,25162,25234,25600,25622,25872,25920,25925,26020,26625,26730,26917,27142,27220,27234, -32768,32770,32773,32776,32785,32788,32800,32810,32833,32836,32848,32896,32898,32936,32938,33025, -33028,33030,33040,33088,33105,33113,33280,33312,33408,33410,33440,33448,33793,33796,33808,33810, -33813,33856,33888,33929,34048,34116,34213,34328,34410,34816,34824,34853,34906,34944,34946,34984, -35078,35362,35456,35464,35478,35496,36865,36868,36880,36928,36950,36996,37120,37154,37220,37462, -37513,37888,37893,37956,37968,37976,38185,38288,38290,38465,38993,39078,39241,39445,39520,40960, -40962,40968,40970,40992,41002,41120,41297,41305,41382,41472,41474,41480,41514,41600,41632,42048, -42133,42597,42648,43018,43040,43042,43048,43168,43176,43268,43396,43398,43560,43562,43665,43690, +pub(super) const KGRID_2BIT_512: [u16; 512] = [ + 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70, 73, 80, 82, 85, 88, 97, 100, 128, 130, 133, 136, 145, + 148, 153, 160, 257, 260, 262, 265, 272, 274, 277, 280, 282, 289, 292, 320, 322, 325, 328, 337, 340, 352, 360, 385, + 388, 400, 512, 514, 517, 520, 529, 532, 544, 577, 580, 592, 597, 640, 650, 1025, 1028, 1030, 1033, 1040, 1042, + 1045, 1048, 1057, 1060, 1088, 1090, 1093, 1096, 1105, 1108, 1110, 1120, 1153, 1156, 1168, 1280, 1282, 1285, 1288, + 1297, 1300, 1312, 1345, 1348, 1360, 1377, 1408, 1537, 1540, 1552, 1574, 1600, 1602, 1668, 2048, 2050, 2053, 2056, + 2058, 2065, 2068, 2080, 2085, 2113, 2116, 2128, 2136, 2176, 2208, 2218, 2305, 2308, 2320, 2368, 2433, 2441, 2560, + 2592, 2600, 2710, 2720, 4097, 4100, 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4160, 4162, 4165, 4168, 4177, + 4180, 4192, 4202, 4225, 4228, 4240, 4352, 4354, 4357, 4360, 4369, 4372, 4384, 4417, 4420, 4432, 4480, 4500, 4502, + 4609, 4612, 4614, 4624, 4672, 4704, 5120, 5122, 5125, 5128, 5137, 5140, 5152, 5185, 5188, 5193, 5200, 5220, 5248, + 5377, 5380, 5392, 5440, 5632, 5652, 5705, 6145, 6148, 6160, 6162, 6208, 6228, 6278, 6400, 6405, 6502, 6737, 6825, + 8192, 8194, 8197, 8200, 8202, 8209, 8212, 8224, 8257, 8260, 8272, 8320, 8352, 8449, 8452, 8464, 8512, 8520, 8549, + 8704, 8738, 8832, 8872, 9217, 9220, 9232, 9257, 9280, 9472, 9537, 9554, 9625, 9729, 9754, 9894, 10240, 10248, + 10250, 10272, 10325, 10376, 10402, 10600, 10640, 10760, 10784, 10882, 10888, 10890, 16385, 16388, 16390, 16393, + 16400, 16402, 16405, 16408, 16417, 16420, 16448, 16450, 16453, 16456, 16458, 16465, 16468, 16480, 16485, 16513, + 16516, 16528, 16640, 16642, 16645, 16648, 16657, 16660, 16672, 16705, 16708, 16720, 16768, 16773, 16802, 16897, + 16900, 16912, 16914, 16937, 16960, 17408, 17410, 17413, 17416, 17425, 17428, 17433, 17440, 17473, 17476, 17488, + 17536, 17556, 17665, 17668, 17680, 17700, 17728, 17818, 17920, 17930, 17988, 18000, 18433, 18436, 18448, 18496, + 18501, 18516, 18530, 18688, 18705, 18756, 18768, 18793, 18948, 20480, 20482, 20485, 20488, 20497, 20500, 20512, + 20520, 20545, 20548, 20560, 20608, 20737, 20740, 20752, 20757, 20800, 20802, 20992, 21060, 21162, 21505, 21508, + 21520, 21537, 21568, 21600, 21633, 21665, 21760, 21768, 21888, 21896, 22049, 22120, 22177, 22528, 22548, 22593, + 22608, 22681, 22810, 22848, 22850, 23173, 24577, 24580, 24592, 24640, 24660, 24674, 24710, 24745, 24832, 25124, + 25162, 25234, 25600, 25622, 25872, 25920, 25925, 26020, 26625, 26730, 26917, 27142, 27220, 27234, 32768, 32770, + 32773, 32776, 32785, 32788, 32800, 32810, 32833, 32836, 32848, 32896, 32898, 32936, 32938, 33025, 33028, 33030, + 33040, 33088, 33105, 33113, 33280, 33312, 33408, 33410, 33440, 33448, 33793, 33796, 33808, 33810, 33813, 33856, + 33888, 33929, 34048, 34116, 34213, 34328, 34410, 34816, 34824, 34853, 34906, 34944, 34946, 34984, 35078, 35362, + 35456, 35464, 35478, 35496, 36865, 36868, 36880, 36928, 36950, 36996, 37120, 37154, 37220, 37462, 37513, 37888, + 37893, 37956, 37968, 37976, 38185, 38288, 38290, 38465, 38993, 39078, 39241, 39445, 39520, 40960, 40962, 40968, + 40970, 40992, 41002, 41120, 41297, 41305, 41382, 41472, 41474, 41480, 41514, 41600, 41632, 42048, 42133, 42597, + 42648, 43018, 43040, 43042, 43048, 43168, 43176, 43268, 43396, 43398, 43560, 43562, 43665, 43690, ]; -pub(super) const KGRID_1BIT_2048: [u16;2048] = [ -0,2,5,8,10,17,21,32,34,40,42,69,81,84,86,101, -128,130,136,138,149,160,162,168,170,260,261,273,276,278,281,282, -293,321,326,329,338,341,346,353,356,358,360,389,401,404,406,421, -512,514,520,522,533,544,546,552,554,581,593,601,612,617,640,642, -648,650,657,661,665,672,674,680,682,1041,1044,1046,1061,1089,1097,1109, -1114,1124,1125,1169,1177,1189,1281,1284,1285,1286,1301,1304,1306,1321,1344,1349, -1354,1360,1361,1364,1365,1366,1369,1376,1378,1381,1384,1386,1409,1425,1429,1432, -1434,1441,1444,1445,1446,1449,1556,1561,1601,1604,1616,1618,1621,1624,1632,1633, -1638,1641,1669,1681,1684,1689,2048,2050,2056,2058,2069,2080,2082,2088,2090,2117, -2129,2134,2149,2176,2178,2184,2186,2197,2208,2210,2216,2218,2309,2321,2324,2329, -2340,2341,2369,2384,2385,2389,2401,2404,2409,2449,2452,2454,2457,2469,2560,2562, -2568,2570,2581,2592,2594,2600,2602,2629,2641,2649,2657,2661,2688,2690,2693,2696, -2698,2709,2720,2722,2728,2730,4112,4113,4116,4121,4132,4133,4161,4164,4176,4181, -4184,4193,4196,4197,4201,4241,4244,4246,4257,4261,4353,4356,4358,4361,4368,4370, -4373,4376,4385,4388,4393,4421,4426,4432,4433,4434,4436,4437,4438,4441,4448,4453, -4484,4498,4501,4513,4516,4625,4628,4630,4645,4672,4678,4681,4690,4693,4696,4698, -4708,4710,4741,4753,4756,4758,4773,5121,5126,5129,5140,5141,5144,5145,5153,5158, -5185,5189,5190,5192,5194,5201,5204,5205,5206,5209,5218,5221,5224,5252,5257,5264, -5268,5269,5272,5273,5274,5281,5284,5285,5289,5378,5381,5386,5393,5396,5397,5398, -5401,5408,5410,5413,5416,5418,5441,5444,5445,5446,5457,5458,5460,5461,5462,5465, -5466,5473,5476,5477,5478,5481,5504,5506,5508,5509,5512,5514,5520,5521,5524,5525, -5526,5529,5530,5536,5538,5541,5633,5636,5637,5638,5653,5654,5656,5658,5665,5670, -5696,5698,5700,5701,5704,5706,5713,5717,5718,5720,5721,5729,5732,5733,5736,5737, -5738,5766,5770,5778,5781,5796,5801,6161,6166,6181,6209,6212,6214,6217,6224,6229, -6232,6234,6240,6241,6244,6246,6249,6277,6289,6292,6309,6416,6418,6421,6426,6433, -6437,6466,6468,6469,6472,6481,6484,6485,6486,6489,6490,6496,6501,6506,6537,6545, -6546,6549,6552,6561,6566,6569,6665,6678,6692,6694,6724,6726,6729,6736,6738,6741, -6744,6753,6758,6761,6789,6801,6806,6810,8192,8194,8200,8202,8213,8224,8226,8229, -8232,8234,8261,8273,8281,8289,8293,8320,8322,8328,8330,8341,8352,8354,8357,8360, -8362,8453,8465,8468,8473,8485,8514,8516,8521,8533,8536,8538,8545,8548,8549,8550, -8581,8592,8598,8601,8613,8705,8712,8714,8721,8725,8736,8738,8744,8746,8773,8785, -8790,8793,8805,8833,8840,8842,8849,8853,8864,8866,8872,8874,9221,9236,9238,9241, -9253,9284,9285,9286,9289,9298,9301,9304,9306,9318,9349,9361,9364,9369,9377,9381, -9481,9493,9505,9513,9536,9541,9544,9553,9556,9557,9561,9570,9573,9576,9609,9616, -9620,9621,9624,9626,9633,9636,9638,9641,9733,9744,9746,9753,9765,9793,9801,9813, -9824,9825,9833,9860,9862,9872,9882,10240,10242,10248,10250,10261,10272,10274,10280,10282, -10309,10321,10324,10341,10368,10370,10376,10378,10400,10402,10408,10410,10505,10513,10516,10521, -10533,10566,10569,10578,10581,10593,10596,10598,10601,10629,10640,10646,10649,10660,10661,10752, -10754,10760,10762,10784,10786,10792,10794,10821,10833,10838,10841,10853,10880,10882,10888,10890, -10901,10912,10914,10920,10922,16389,16401,16406,16421,16457,16466,16469,16472,16474,16481,16484, -16486,16532,16537,16545,16550,16640,16641,16644,16646,16649,16658,16661,16662,16664,16666,16673, -16678,16681,16709,16712,16714,16721,16724,16725,16726,16729,16730,16741,16744,16746,16769,16772, -16774,16784,16786,16789,16800,16801,16802,16901,16913,16916,16918,16933,16961,16978,16981,16986, -16996,17001,17033,17044,17061,17409,17429,17433,17449,17477,17480,17482,17489,17492,17493,17494, -17505,17506,17509,17512,17514,17537,17542,17545,17552,17554,17557,17568,17569,17577,17665,17666, -17669,17674,17681,17684,17685,17686,17689,17696,17701,17706,17729,17732,17733,17734,17737,17744, -17745,17748,17749,17750,17752,17753,17761,17764,17765,17766,17769,17794,17796,17797,17800,17809, -17812,17813,17814,17817,17818,17829,17832,17834,17921,17925,17929,17940,17941,17944,17946,17953, -17956,17961,17984,17986,17989,17992,18000,18001,18002,18005,18006,18009,18018,18021,18024,18049, -18053,18058,18068,18069,18081,18084,18086,18437,18449,18453,18458,18469,18498,18505,18512,18517, -18520,18529,18532,18534,18537,18565,18577,18580,18582,18585,18597,18689,18693,18694,18698,18704, -18708,18709,18712,18721,18724,18726,18752,18757,18762,18769,18770,18772,18773,18774,18777,18784, -18786,18789,18790,18794,18822,18825,18834,18837,18838,18840,18849,18852,18854,18857,18966,19012, -19014,19017,19029,19032,19034,19044,19049,19092,19109,20481,20484,20485,20486,20489,20498,20501, -20506,20513,20516,20521,20544,20549,20552,20561,20564,20565,20566,20569,20581,20584,20614,20617, -20629,20632,20640,20641,20646,20649,20741,20744,20745,20746,20753,20756,20757,20758,20760,20761, -20768,20773,20774,20776,20778,20801,20804,20805,20806,20809,20816,20817,20818,20820,20821,20822, -20824,20825,20826,20833,20836,20837,20838,20841,20866,20869,20881,20884,20885,20886,20889,20896, -20901,20906,20993,20998,21010,21013,21018,21025,21028,21058,21061,21066,21073,21076,21077,21078, -21081,21090,21093,21125,21136,21138,21141,21145,21146,21156,21508,21509,21521,21524,21525,21526, -21528,21529,21537,21541,21544,21546,21569,21572,21573,21574,21577,21578,21584,21585,21588,21589, -21590,21592,21593,21594,21601,21602,21604,21605,21606,21609,21632,21640,21642,21649,21652,21653, -21654,21657,21665,21668,21669,21674,21761,21762,21764,21765,21766,21769,21776,21777,21778,21780, -21781,21782,21785,21786,21793,21796,21797,21798,21801,21824,21825,21826,21828,21829,21830,21832, -21833,21840,21841,21842,21844,21845,21846,21848,21849,21850,21856,21857,21860,21861,21862,21864, -21865,21866,21889,21892,21893,21897,21898,21904,21905,21908,21909,21910,21912,21913,21921,21924, -21925,21926,21929,22016,22017,22018,22020,22022,22024,22025,22033,22036,22037,22040,22041,22048, -22049,22050,22052,22053,22054,22056,22057,22081,22085,22086,22088,22089,22090,22096,22097,22098, -22100,22101,22102,22104,22105,22106,22113,22116,22117,22121,22146,22149,22150,22152,22153,22154, -22161,22165,22170,22178,22181,22182,22184,22185,22532,22533,22534,22537,22544,22549,22552,22561, -22570,22597,22600,22602,22609,22612,22613,22614,22616,22617,22624,22626,22628,22629,22658,22665, -22672,22674,22677,22680,22689,22697,22785,22786,22789,22794,22801,22804,22805,22806,22809,22821, -22849,22852,22853,22854,22857,22864,22865,22866,22868,22869,22870,22872,22873,22874,22881,22884, -22885,22886,22889,22913,22917,22921,22929,22932,22933,22934,22936,22937,22949,23044,23048,23061, -23066,23072,23077,23078,23081,23109,23112,23113,23121,23125,23126,23128,23129,23138,23141,23144, -23146,23169,23178,23186,23189,23190,23192,23194,23201,24581,24596,24598,24601,24613,24644,24656, -24661,24662,24664,24666,24673,24676,24678,24681,24705,24726,24741,24833,24836,24838,24841,24850, -24853,24865,24866,24870,24873,24901,24905,24913,24917,24918,24921,24933,24934,24938,24964,24970, -24978,24981,24993,24998,25001,25105,25110,25113,25152,25153,25158,25173,25174,25176,25184,25221, -25233,25238,25253,25617,25618,25621,25622,25626,25633,25638,25641,25664,25666,25669,25672,25674, -25681,25684,25685,25686,25689,25690,25696,25698,25701,25732,25733,25737,25744,25746,25748,25749, -25750,25752,25754,25761,25764,25769,25861,25864,25866,25873,25877,25878,25881,25924,25925,25926, -25929,25936,25937,25940,25941,25942,25945,25953,25956,25957,25958,25961,25990,25993,25994,26001, -26005,26006,26009,26010,26018,26021,26022,26024,26114,26121,26133,26144,26150,26152,26153,26176, -26181,26184,26186,26193,26196,26197,26198,26200,26202,26208,26213,26216,26240,26242,26245,26250, -26260,26262,26264,26265,26272,26276,26278,26282,26646,26649,26661,26689,26706,26709,26714,26721, -26729,26757,26769,26776,26790,26881,26884,26896,26901,26913,26916,26918,26921,26944,26945,26949, -26950,26952,26961,26964,26965,26966,26969,26976,26981,26986,27010,27012,27018,27029,27041,27044, -27045,27049,27153,27158,27160,27201,27204,27209,27216,27221,27224,27226,27236,27237,27241,27270, -27284,27288,27290,27302,32768,32770,32776,32778,32800,32802,32808,32810,32837,32848,32849,32852, -32854,32857,32869,32896,32898,32904,32906,32917,32928,32930,32936,32938,33029,33041,33044,33046, -33049,33061,33089,33092,33097,33104,33106,33109,33110,33112,33113,33124,33126,33129,33157,33161, -33172,33174,33177,33189,33280,33282,33288,33290,33301,33312,33314,33320,33322,33361,33364,33369, -33381,33408,33410,33416,33418,33429,33440,33442,33448,33450,33812,33817,33857,33860,33873,33877, -33882,33889,33892,33897,33940,33945,34049,34057,34066,34069,34074,34086,34089,34112,34113,34117, -34120,34129,34132,34133,34134,34137,34138,34149,34150,34152,34154,34177,34180,34182,34185,34192, -34194,34197,34200,34214,34321,34326,34329,34341,34369,34372,34377,34378,34384,34389,34393,34394, -34401,34406,34410,34437,34449,34458,34468,34816,34818,34824,34826,34837,34848,34850,34856,34858, -34881,34885,34897,34900,34905,34917,34921,34944,34946,34952,34954,34965,34976,34978,34984,34986, -35077,35078,35089,35092,35094,35109,35137,35140,35142,35145,35152,35154,35157,35162,35169,35172, -35205,35222,35225,35237,35328,35330,35336,35338,35349,35360,35362,35368,35370,35397,35409,35412, -35414,35456,35458,35464,35466,35477,35488,35490,35496,35498,36869,36881,36886,36888,36889,36901, -36929,36934,36937,36949,36952,36954,36969,36970,36997,37009,37012,37014,37017,37029,37121,37124, -37126,37129,37136,37141,37144,37146,37153,37156,37158,37161,37184,37189,37200,37201,37204,37205, -37206,37209,37218,37221,37252,37254,37266,37269,37272,37281,37284,37286,37289,37381,37393,37396, -37401,37413,37444,37446,37449,37456,37458,37461,37464,37478,37481,37509,37524,37526,37545,37889, -37892,37894,37904,37909,37912,37926,37952,37962,37969,37972,37973,37974,37976,37977,37984,37985, -37986,37989,38020,38022,38034,38036,38037,38040,38049,38057,38144,38149,38152,38154,38160,38161, -38164,38165,38166,38169,38177,38181,38185,38186,38209,38212,38213,38214,38217,38224,38225,38226, -38228,38229,38230,38232,38233,38234,38241,38244,38245,38246,38249,38273,38277,38280,38289,38290, -38292,38293,38294,38297,38298,38304,38306,38309,38312,38314,38401,38404,38416,38421,38425,38432, -38438,38441,38469,38472,38473,38481,38482,38485,38486,38489,38501,38504,38530,38532,38537,38538, -38546,38548,38549,38564,38566,38569,38917,38934,38937,38949,38977,38982,38992,38994,38997,38998, -39002,39012,39013,39045,39057,39062,39065,39077,39172,39174,39177,39184,39186,39189,39192,39194, -39200,39201,39204,39206,39232,39234,39237,39240,39242,39249,39252,39253,39254,39257,39266,39269, -39270,39274,39297,39300,39312,39314,39317,39322,39329,39334,39429,39445,39461,39492,39494,39497, -39504,39509,39512,39521,39557,39569,39572,39573,39574,40960,40962,40968,40970,40981,40992,40994, -41000,41002,41029,41041,41044,41046,41049,41088,41090,41096,41098,41109,41120,41122,41128,41130, -41221,41225,41233,41236,41238,41241,41242,41286,41289,41297,41301,41304,41306,41313,41316,41349, -41360,41362,41366,41369,41474,41480,41482,41488,41497,41506,41512,41514,41541,41553,41558,41561, -41573,41600,41602,41608,41610,41621,41632,41634,41640,41642,42009,42021,42049,42052,42064,42068, -42069,42072,42074,42081,42085,42086,42088,42089,42117,42246,42249,42256,42258,42261,42264,42278, -42281,42306,42309,42321,42324,42325,42326,42329,42341,42346,42369,42372,42373,42374,42377,42386, -42389,42392,42501,42513,42518,42522,42529,42533,42564,42566,42570,42578,42581,42582,42584,42592, -42594,42630,42640,42645,42646,42649,42657,42660,42662,43008,43010,43016,43018,43040,43042,43048, -43050,43089,43092,43094,43097,43136,43138,43144,43146,43157,43168,43170,43176,43178,43269,43284, -43289,43297,43301,43329,43344,43349,43354,43361,43366,43369,43408,43414,43520,43522,43528,43530, -43552,43554,43560,43562,43601,43604,43606,43648,43650,43656,43658,43669,43680,43682,43688,43690, +pub(super) const KGRID_1BIT_2048: [u16; 2048] = [ + 0, 2, 5, 8, 10, 17, 21, 32, 34, 40, 42, 69, 81, 84, 86, 101, 128, 130, 136, 138, 149, 160, 162, 168, 170, 260, 261, + 273, 276, 278, 281, 282, 293, 321, 326, 329, 338, 341, 346, 353, 356, 358, 360, 389, 401, 404, 406, 421, 512, 514, + 520, 522, 533, 544, 546, 552, 554, 581, 593, 601, 612, 617, 640, 642, 648, 650, 657, 661, 665, 672, 674, 680, 682, + 1041, 1044, 1046, 1061, 1089, 1097, 1109, 1114, 1124, 1125, 1169, 1177, 1189, 1281, 1284, 1285, 1286, 1301, 1304, + 1306, 1321, 1344, 1349, 1354, 1360, 1361, 1364, 1365, 1366, 1369, 1376, 1378, 1381, 1384, 1386, 1409, 1425, 1429, + 1432, 1434, 1441, 1444, 1445, 1446, 1449, 1556, 1561, 1601, 1604, 1616, 1618, 1621, 1624, 1632, 1633, 1638, 1641, + 1669, 1681, 1684, 1689, 2048, 2050, 2056, 2058, 2069, 2080, 2082, 2088, 2090, 2117, 2129, 2134, 2149, 2176, 2178, + 2184, 2186, 2197, 2208, 2210, 2216, 2218, 2309, 2321, 2324, 2329, 2340, 2341, 2369, 2384, 2385, 2389, 2401, 2404, + 2409, 2449, 2452, 2454, 2457, 2469, 2560, 2562, 2568, 2570, 2581, 2592, 2594, 2600, 2602, 2629, 2641, 2649, 2657, + 2661, 2688, 2690, 2693, 2696, 2698, 2709, 2720, 2722, 2728, 2730, 4112, 4113, 4116, 4121, 4132, 4133, 4161, 4164, + 4176, 4181, 4184, 4193, 4196, 4197, 4201, 4241, 4244, 4246, 4257, 4261, 4353, 4356, 4358, 4361, 4368, 4370, 4373, + 4376, 4385, 4388, 4393, 4421, 4426, 4432, 4433, 4434, 4436, 4437, 4438, 4441, 4448, 4453, 4484, 4498, 4501, 4513, + 4516, 4625, 4628, 4630, 4645, 4672, 4678, 4681, 4690, 4693, 4696, 4698, 4708, 4710, 4741, 4753, 4756, 4758, 4773, + 5121, 5126, 5129, 5140, 5141, 5144, 5145, 5153, 5158, 5185, 5189, 5190, 5192, 5194, 5201, 5204, 5205, 5206, 5209, + 5218, 5221, 5224, 5252, 5257, 5264, 5268, 5269, 5272, 5273, 5274, 5281, 5284, 5285, 5289, 5378, 5381, 5386, 5393, + 5396, 5397, 5398, 5401, 5408, 5410, 5413, 5416, 5418, 5441, 5444, 5445, 5446, 5457, 5458, 5460, 5461, 5462, 5465, + 5466, 5473, 5476, 5477, 5478, 5481, 5504, 5506, 5508, 5509, 5512, 5514, 5520, 5521, 5524, 5525, 5526, 5529, 5530, + 5536, 5538, 5541, 5633, 5636, 5637, 5638, 5653, 5654, 5656, 5658, 5665, 5670, 5696, 5698, 5700, 5701, 5704, 5706, + 5713, 5717, 5718, 5720, 5721, 5729, 5732, 5733, 5736, 5737, 5738, 5766, 5770, 5778, 5781, 5796, 5801, 6161, 6166, + 6181, 6209, 6212, 6214, 6217, 6224, 6229, 6232, 6234, 6240, 6241, 6244, 6246, 6249, 6277, 6289, 6292, 6309, 6416, + 6418, 6421, 6426, 6433, 6437, 6466, 6468, 6469, 6472, 6481, 6484, 6485, 6486, 6489, 6490, 6496, 6501, 6506, 6537, + 6545, 6546, 6549, 6552, 6561, 6566, 6569, 6665, 6678, 6692, 6694, 6724, 6726, 6729, 6736, 6738, 6741, 6744, 6753, + 6758, 6761, 6789, 6801, 6806, 6810, 8192, 8194, 8200, 8202, 8213, 8224, 8226, 8229, 8232, 8234, 8261, 8273, 8281, + 8289, 8293, 8320, 8322, 8328, 8330, 8341, 8352, 8354, 8357, 8360, 8362, 8453, 8465, 8468, 8473, 8485, 8514, 8516, + 8521, 8533, 8536, 8538, 8545, 8548, 8549, 8550, 8581, 8592, 8598, 8601, 8613, 8705, 8712, 8714, 8721, 8725, 8736, + 8738, 8744, 8746, 8773, 8785, 8790, 8793, 8805, 8833, 8840, 8842, 8849, 8853, 8864, 8866, 8872, 8874, 9221, 9236, + 9238, 9241, 9253, 9284, 9285, 9286, 9289, 9298, 9301, 9304, 9306, 9318, 9349, 9361, 9364, 9369, 9377, 9381, 9481, + 9493, 9505, 9513, 9536, 9541, 9544, 9553, 9556, 9557, 9561, 9570, 9573, 9576, 9609, 9616, 9620, 9621, 9624, 9626, + 9633, 9636, 9638, 9641, 9733, 9744, 9746, 9753, 9765, 9793, 9801, 9813, 9824, 9825, 9833, 9860, 9862, 9872, 9882, + 10240, 10242, 10248, 10250, 10261, 10272, 10274, 10280, 10282, 10309, 10321, 10324, 10341, 10368, 10370, 10376, + 10378, 10400, 10402, 10408, 10410, 10505, 10513, 10516, 10521, 10533, 10566, 10569, 10578, 10581, 10593, 10596, + 10598, 10601, 10629, 10640, 10646, 10649, 10660, 10661, 10752, 10754, 10760, 10762, 10784, 10786, 10792, 10794, + 10821, 10833, 10838, 10841, 10853, 10880, 10882, 10888, 10890, 10901, 10912, 10914, 10920, 10922, 16389, 16401, + 16406, 16421, 16457, 16466, 16469, 16472, 16474, 16481, 16484, 16486, 16532, 16537, 16545, 16550, 16640, 16641, + 16644, 16646, 16649, 16658, 16661, 16662, 16664, 16666, 16673, 16678, 16681, 16709, 16712, 16714, 16721, 16724, + 16725, 16726, 16729, 16730, 16741, 16744, 16746, 16769, 16772, 16774, 16784, 16786, 16789, 16800, 16801, 16802, + 16901, 16913, 16916, 16918, 16933, 16961, 16978, 16981, 16986, 16996, 17001, 17033, 17044, 17061, 17409, 17429, + 17433, 17449, 17477, 17480, 17482, 17489, 17492, 17493, 17494, 17505, 17506, 17509, 17512, 17514, 17537, 17542, + 17545, 17552, 17554, 17557, 17568, 17569, 17577, 17665, 17666, 17669, 17674, 17681, 17684, 17685, 17686, 17689, + 17696, 17701, 17706, 17729, 17732, 17733, 17734, 17737, 17744, 17745, 17748, 17749, 17750, 17752, 17753, 17761, + 17764, 17765, 17766, 17769, 17794, 17796, 17797, 17800, 17809, 17812, 17813, 17814, 17817, 17818, 17829, 17832, + 17834, 17921, 17925, 17929, 17940, 17941, 17944, 17946, 17953, 17956, 17961, 17984, 17986, 17989, 17992, 18000, + 18001, 18002, 18005, 18006, 18009, 18018, 18021, 18024, 18049, 18053, 18058, 18068, 18069, 18081, 18084, 18086, + 18437, 18449, 18453, 18458, 18469, 18498, 18505, 18512, 18517, 18520, 18529, 18532, 18534, 18537, 18565, 18577, + 18580, 18582, 18585, 18597, 18689, 18693, 18694, 18698, 18704, 18708, 18709, 18712, 18721, 18724, 18726, 18752, + 18757, 18762, 18769, 18770, 18772, 18773, 18774, 18777, 18784, 18786, 18789, 18790, 18794, 18822, 18825, 18834, + 18837, 18838, 18840, 18849, 18852, 18854, 18857, 18966, 19012, 19014, 19017, 19029, 19032, 19034, 19044, 19049, + 19092, 19109, 20481, 20484, 20485, 20486, 20489, 20498, 20501, 20506, 20513, 20516, 20521, 20544, 20549, 20552, + 20561, 20564, 20565, 20566, 20569, 20581, 20584, 20614, 20617, 20629, 20632, 20640, 20641, 20646, 20649, 20741, + 20744, 20745, 20746, 20753, 20756, 20757, 20758, 20760, 20761, 20768, 20773, 20774, 20776, 20778, 20801, 20804, + 20805, 20806, 20809, 20816, 20817, 20818, 20820, 20821, 20822, 20824, 20825, 20826, 20833, 20836, 20837, 20838, + 20841, 20866, 20869, 20881, 20884, 20885, 20886, 20889, 20896, 20901, 20906, 20993, 20998, 21010, 21013, 21018, + 21025, 21028, 21058, 21061, 21066, 21073, 21076, 21077, 21078, 21081, 21090, 21093, 21125, 21136, 21138, 21141, + 21145, 21146, 21156, 21508, 21509, 21521, 21524, 21525, 21526, 21528, 21529, 21537, 21541, 21544, 21546, 21569, + 21572, 21573, 21574, 21577, 21578, 21584, 21585, 21588, 21589, 21590, 21592, 21593, 21594, 21601, 21602, 21604, + 21605, 21606, 21609, 21632, 21640, 21642, 21649, 21652, 21653, 21654, 21657, 21665, 21668, 21669, 21674, 21761, + 21762, 21764, 21765, 21766, 21769, 21776, 21777, 21778, 21780, 21781, 21782, 21785, 21786, 21793, 21796, 21797, + 21798, 21801, 21824, 21825, 21826, 21828, 21829, 21830, 21832, 21833, 21840, 21841, 21842, 21844, 21845, 21846, + 21848, 21849, 21850, 21856, 21857, 21860, 21861, 21862, 21864, 21865, 21866, 21889, 21892, 21893, 21897, 21898, + 21904, 21905, 21908, 21909, 21910, 21912, 21913, 21921, 21924, 21925, 21926, 21929, 22016, 22017, 22018, 22020, + 22022, 22024, 22025, 22033, 22036, 22037, 22040, 22041, 22048, 22049, 22050, 22052, 22053, 22054, 22056, 22057, + 22081, 22085, 22086, 22088, 22089, 22090, 22096, 22097, 22098, 22100, 22101, 22102, 22104, 22105, 22106, 22113, + 22116, 22117, 22121, 22146, 22149, 22150, 22152, 22153, 22154, 22161, 22165, 22170, 22178, 22181, 22182, 22184, + 22185, 22532, 22533, 22534, 22537, 22544, 22549, 22552, 22561, 22570, 22597, 22600, 22602, 22609, 22612, 22613, + 22614, 22616, 22617, 22624, 22626, 22628, 22629, 22658, 22665, 22672, 22674, 22677, 22680, 22689, 22697, 22785, + 22786, 22789, 22794, 22801, 22804, 22805, 22806, 22809, 22821, 22849, 22852, 22853, 22854, 22857, 22864, 22865, + 22866, 22868, 22869, 22870, 22872, 22873, 22874, 22881, 22884, 22885, 22886, 22889, 22913, 22917, 22921, 22929, + 22932, 22933, 22934, 22936, 22937, 22949, 23044, 23048, 23061, 23066, 23072, 23077, 23078, 23081, 23109, 23112, + 23113, 23121, 23125, 23126, 23128, 23129, 23138, 23141, 23144, 23146, 23169, 23178, 23186, 23189, 23190, 23192, + 23194, 23201, 24581, 24596, 24598, 24601, 24613, 24644, 24656, 24661, 24662, 24664, 24666, 24673, 24676, 24678, + 24681, 24705, 24726, 24741, 24833, 24836, 24838, 24841, 24850, 24853, 24865, 24866, 24870, 24873, 24901, 24905, + 24913, 24917, 24918, 24921, 24933, 24934, 24938, 24964, 24970, 24978, 24981, 24993, 24998, 25001, 25105, 25110, + 25113, 25152, 25153, 25158, 25173, 25174, 25176, 25184, 25221, 25233, 25238, 25253, 25617, 25618, 25621, 25622, + 25626, 25633, 25638, 25641, 25664, 25666, 25669, 25672, 25674, 25681, 25684, 25685, 25686, 25689, 25690, 25696, + 25698, 25701, 25732, 25733, 25737, 25744, 25746, 25748, 25749, 25750, 25752, 25754, 25761, 25764, 25769, 25861, + 25864, 25866, 25873, 25877, 25878, 25881, 25924, 25925, 25926, 25929, 25936, 25937, 25940, 25941, 25942, 25945, + 25953, 25956, 25957, 25958, 25961, 25990, 25993, 25994, 26001, 26005, 26006, 26009, 26010, 26018, 26021, 26022, + 26024, 26114, 26121, 26133, 26144, 26150, 26152, 26153, 26176, 26181, 26184, 26186, 26193, 26196, 26197, 26198, + 26200, 26202, 26208, 26213, 26216, 26240, 26242, 26245, 26250, 26260, 26262, 26264, 26265, 26272, 26276, 26278, + 26282, 26646, 26649, 26661, 26689, 26706, 26709, 26714, 26721, 26729, 26757, 26769, 26776, 26790, 26881, 26884, + 26896, 26901, 26913, 26916, 26918, 26921, 26944, 26945, 26949, 26950, 26952, 26961, 26964, 26965, 26966, 26969, + 26976, 26981, 26986, 27010, 27012, 27018, 27029, 27041, 27044, 27045, 27049, 27153, 27158, 27160, 27201, 27204, + 27209, 27216, 27221, 27224, 27226, 27236, 27237, 27241, 27270, 27284, 27288, 27290, 27302, 32768, 32770, 32776, + 32778, 32800, 32802, 32808, 32810, 32837, 32848, 32849, 32852, 32854, 32857, 32869, 32896, 32898, 32904, 32906, + 32917, 32928, 32930, 32936, 32938, 33029, 33041, 33044, 33046, 33049, 33061, 33089, 33092, 33097, 33104, 33106, + 33109, 33110, 33112, 33113, 33124, 33126, 33129, 33157, 33161, 33172, 33174, 33177, 33189, 33280, 33282, 33288, + 33290, 33301, 33312, 33314, 33320, 33322, 33361, 33364, 33369, 33381, 33408, 33410, 33416, 33418, 33429, 33440, + 33442, 33448, 33450, 33812, 33817, 33857, 33860, 33873, 33877, 33882, 33889, 33892, 33897, 33940, 33945, 34049, + 34057, 34066, 34069, 34074, 34086, 34089, 34112, 34113, 34117, 34120, 34129, 34132, 34133, 34134, 34137, 34138, + 34149, 34150, 34152, 34154, 34177, 34180, 34182, 34185, 34192, 34194, 34197, 34200, 34214, 34321, 34326, 34329, + 34341, 34369, 34372, 34377, 34378, 34384, 34389, 34393, 34394, 34401, 34406, 34410, 34437, 34449, 34458, 34468, + 34816, 34818, 34824, 34826, 34837, 34848, 34850, 34856, 34858, 34881, 34885, 34897, 34900, 34905, 34917, 34921, + 34944, 34946, 34952, 34954, 34965, 34976, 34978, 34984, 34986, 35077, 35078, 35089, 35092, 35094, 35109, 35137, + 35140, 35142, 35145, 35152, 35154, 35157, 35162, 35169, 35172, 35205, 35222, 35225, 35237, 35328, 35330, 35336, + 35338, 35349, 35360, 35362, 35368, 35370, 35397, 35409, 35412, 35414, 35456, 35458, 35464, 35466, 35477, 35488, + 35490, 35496, 35498, 36869, 36881, 36886, 36888, 36889, 36901, 36929, 36934, 36937, 36949, 36952, 36954, 36969, + 36970, 36997, 37009, 37012, 37014, 37017, 37029, 37121, 37124, 37126, 37129, 37136, 37141, 37144, 37146, 37153, + 37156, 37158, 37161, 37184, 37189, 37200, 37201, 37204, 37205, 37206, 37209, 37218, 37221, 37252, 37254, 37266, + 37269, 37272, 37281, 37284, 37286, 37289, 37381, 37393, 37396, 37401, 37413, 37444, 37446, 37449, 37456, 37458, + 37461, 37464, 37478, 37481, 37509, 37524, 37526, 37545, 37889, 37892, 37894, 37904, 37909, 37912, 37926, 37952, + 37962, 37969, 37972, 37973, 37974, 37976, 37977, 37984, 37985, 37986, 37989, 38020, 38022, 38034, 38036, 38037, + 38040, 38049, 38057, 38144, 38149, 38152, 38154, 38160, 38161, 38164, 38165, 38166, 38169, 38177, 38181, 38185, + 38186, 38209, 38212, 38213, 38214, 38217, 38224, 38225, 38226, 38228, 38229, 38230, 38232, 38233, 38234, 38241, + 38244, 38245, 38246, 38249, 38273, 38277, 38280, 38289, 38290, 38292, 38293, 38294, 38297, 38298, 38304, 38306, + 38309, 38312, 38314, 38401, 38404, 38416, 38421, 38425, 38432, 38438, 38441, 38469, 38472, 38473, 38481, 38482, + 38485, 38486, 38489, 38501, 38504, 38530, 38532, 38537, 38538, 38546, 38548, 38549, 38564, 38566, 38569, 38917, + 38934, 38937, 38949, 38977, 38982, 38992, 38994, 38997, 38998, 39002, 39012, 39013, 39045, 39057, 39062, 39065, + 39077, 39172, 39174, 39177, 39184, 39186, 39189, 39192, 39194, 39200, 39201, 39204, 39206, 39232, 39234, 39237, + 39240, 39242, 39249, 39252, 39253, 39254, 39257, 39266, 39269, 39270, 39274, 39297, 39300, 39312, 39314, 39317, + 39322, 39329, 39334, 39429, 39445, 39461, 39492, 39494, 39497, 39504, 39509, 39512, 39521, 39557, 39569, 39572, + 39573, 39574, 40960, 40962, 40968, 40970, 40981, 40992, 40994, 41000, 41002, 41029, 41041, 41044, 41046, 41049, + 41088, 41090, 41096, 41098, 41109, 41120, 41122, 41128, 41130, 41221, 41225, 41233, 41236, 41238, 41241, 41242, + 41286, 41289, 41297, 41301, 41304, 41306, 41313, 41316, 41349, 41360, 41362, 41366, 41369, 41474, 41480, 41482, + 41488, 41497, 41506, 41512, 41514, 41541, 41553, 41558, 41561, 41573, 41600, 41602, 41608, 41610, 41621, 41632, + 41634, 41640, 41642, 42009, 42021, 42049, 42052, 42064, 42068, 42069, 42072, 42074, 42081, 42085, 42086, 42088, + 42089, 42117, 42246, 42249, 42256, 42258, 42261, 42264, 42278, 42281, 42306, 42309, 42321, 42324, 42325, 42326, + 42329, 42341, 42346, 42369, 42372, 42373, 42374, 42377, 42386, 42389, 42392, 42501, 42513, 42518, 42522, 42529, + 42533, 42564, 42566, 42570, 42578, 42581, 42582, 42584, 42592, 42594, 42630, 42640, 42645, 42646, 42649, 42657, + 42660, 42662, 43008, 43010, 43016, 43018, 43040, 43042, 43048, 43050, 43089, 43092, 43094, 43097, 43136, 43138, + 43144, 43146, 43157, 43168, 43170, 43176, 43178, 43269, 43284, 43289, 43297, 43301, 43329, 43344, 43349, 43354, + 43361, 43366, 43369, 43408, 43414, 43520, 43522, 43528, 43530, 43552, 43554, 43560, 43562, 43601, 43604, 43606, + 43648, 43650, 43656, 43658, 43669, 43680, 43682, 43688, 43690, ]; -pub(super) const KGRID_2BIT_1024: [u16;1024] = [ -0,2,5,8,10,17,20,22,25,32,34,37,40,65,68,70, -73,80,82,85,88,97,100,102,105,128,130,133,136,145,148,160, -165,170,257,260,262,265,272,274,277,280,289,292,320,322,325,328, -337,340,342,345,352,357,360,385,388,400,402,405,417,420,512,514, -517,520,529,532,544,554,577,580,582,585,592,597,640,645,650,660, -674,1025,1028,1030,1033,1040,1042,1045,1048,1057,1060,1062,1065,1088,1090,1093, -1096,1098,1105,1108,1110,1113,1120,1122,1125,1153,1156,1158,1161,1168,1173,1176, -1185,1188,1280,1282,1285,1288,1290,1297,1300,1302,1305,1312,1317,1320,1345,1348, -1350,1353,1360,1362,1365,1368,1377,1380,1408,1410,1413,1416,1425,1428,1440,1537, -1540,1542,1545,1552,1557,1600,1605,1608,1617,1620,1632,1665,1668,1680,2048,2050, -2053,2056,2065,2068,2070,2073,2080,2085,2090,2113,2116,2118,2121,2128,2130,2133, -2136,2145,2148,2176,2181,2196,2218,2305,2308,2320,2322,2325,2328,2337,2368,2373, -2376,2385,2388,2400,2433,2448,2560,2577,2580,2594,2600,2602,2640,2713,4097,4100, -4102,4105,4112,4114,4117,4120,4129,4132,4134,4160,4162,4165,4168,4177,4180,4182, -4185,4192,4194,4197,4200,4225,4228,4230,4240,4245,4248,4257,4260,4352,4354,4357, -4360,4362,4369,4372,4374,4377,4384,4386,4389,4392,4417,4420,4422,4425,4432,4434, -4437,4440,4449,4452,4480,4482,4485,4488,4497,4500,4609,4612,4617,4624,4629,4641, -4644,4672,4677,4689,4692,4737,4740,4752,5120,5122,5125,5128,5137,5140,5142,5145, -5152,5157,5160,5185,5188,5190,5193,5200,5202,5205,5208,5217,5220,5248,5250,5253, -5256,5265,5268,5280,5377,5380,5382,5385,5392,5394,5397,5400,5409,5412,5440,5442, -5445,5448,5457,5460,5472,5505,5508,5520,5632,5637,5640,5649,5652,5664,5697,5700, -5712,5760,5802,6145,6148,6150,6153,6160,6165,6168,6177,6208,6210,6213,6216,6225, -6228,6240,6273,6276,6400,6402,6405,6408,6417,6420,6432,6465,6468,6480,6505,6562, -6660,6672,6720,6742,8192,8194,8197,8200,8209,8212,8214,8217,8224,8229,8234,8257, -8260,8272,8274,8277,8292,8320,8330,8340,8362,8449,8452,8464,8466,8469,8481,8512, -8514,8517,8529,8532,8544,8577,8580,8592,8704,8714,8738,8744,8746,8772,8784,8840, -8842,8872,9217,9220,9222,9225,9232,9237,9240,9249,9252,9280,9282,9285,9288,9297, -9300,9312,9345,9348,9360,9472,9477,9480,9489,9492,9504,9537,9540,9552,9574,9600, -9729,9732,9744,9792,9817,10240,10245,10257,10260,10305,10308,10320,10378,10410,10497,10500, -10512,10645,10762,10786,10852,10888,10890,16385,16388,16390,16393,16400,16402,16405,16408,16410, -16417,16420,16422,16448,16450,16453,16456,16458,16465,16468,16470,16473,16480,16482,16485,16513, -16516,16528,16533,16536,16545,16548,16640,16642,16645,16648,16657,16660,16662,16665,16672,16674, -16677,16705,16708,16710,16713,16720,16722,16725,16728,16737,16740,16768,16770,16773,16776,16785, -16788,16800,16897,16900,16912,16914,16917,16920,16932,16960,16965,16968,16977,16980,16992,17025, -17028,17408,17410,17413,17416,17418,17425,17428,17430,17433,17440,17442,17445,17448,17473,17476, -17478,17481,17488,17490,17493,17496,17505,17508,17536,17538,17541,17544,17553,17556,17568,17665, -17668,17670,17673,17680,17682,17685,17688,17697,17700,17728,17730,17733,17736,17745,17748,17760, -17770,17793,17796,17808,17920,17922,17925,17928,17937,17940,17952,17985,17988,18000,18048,18085, -18433,18436,18441,18448,18450,18453,18456,18465,18468,18496,18498,18501,18504,18513,18516,18528, -18564,18576,18688,18690,18693,18696,18705,18708,18720,18753,18756,18768,18816,18838,18945,18948, -18960,19008,20480,20482,20485,20488,20497,20500,20502,20505,20512,20514,20517,20520,20545,20548, -20550,20553,20560,20562,20565,20568,20577,20580,20608,20610,20613,20616,20625,20628,20737,20740, -20742,20745,20752,20754,20757,20760,20769,20772,20800,20802,20805,20808,20817,20820,20832,20865, -20868,20880,20992,20997,21000,21009,21012,21024,21057,21060,21072,21097,21120,21505,21508,21510, -21513,21520,21522,21525,21528,21537,21540,21568,21570,21573,21576,21585,21588,21600,21633,21636, -21648,21760,21762,21765,21768,21777,21780,21792,21825,21828,21840,21888,22017,22020,22032,22054, -22080,22528,22530,22533,22536,22545,22548,22560,22593,22596,22608,22618,22656,22785,22788,22800, -22848,23040,23065,23173,23208,24577,24580,24582,24592,24594,24597,24600,24609,24612,24640,24645, -24648,24657,24660,24672,24708,24720,24832,24834,24837,24840,24849,24852,24864,24897,24900,24912, -24960,24985,25092,25104,25152,25174,25249,25600,25605,25608,25617,25620,25632,25665,25668,25680, -25728,25857,25860,25872,25920,25930,25960,26002,26112,26260,26625,26628,26640,26725,26776,26880, -26922,27202,27297,32768,32770,32773,32776,32785,32788,32793,32800,32805,32833,32836,32848,32850, -32853,32856,32865,32896,32901,32913,32916,33025,33028,33033,33040,33042,33045,33048,33057,33060, -33088,33090,33093,33096,33105,33108,33153,33156,33168,33193,33280,33285,33290,33297,33300,33345, -33348,33360,33793,33796,33798,33801,33808,33810,33813,33816,33825,33856,33858,33861,33864,33873, -33876,33888,33921,33924,33936,34048,34050,34053,34056,34065,34068,34080,34113,34116,34128,34176, -34186,34305,34308,34320,34345,34368,34816,34821,34833,34836,34881,34884,34896,34978,35073,35076, -35136,35173,35362,35416,35418,35458,35490,36865,36868,36873,36880,36882,36885,36888,36900,36928, -36930,36933,36936,36945,36948,36960,36993,36996,37008,37120,37125,37137,37140,37185,37188,37200, -37210,37377,37380,37392,37440,37542,37888,37890,37893,37896,37905,37908,37920,37953,37956,37968, -38016,38038,38145,38148,38160,38208,38296,38305,38400,38470,38500,38913,38916,38928,38950,38976, -39081,39168,39241,39250,39568,40960,40965,40970,40980,40994,41002,41025,41028,41040,41122,41130, -41280,41317,41474,41482,41506,41512,41514,41602,41608,41610,41640,41985,41988,42000,42048,42121, -42148,42240,42265,42577,43018,43048,43170,43348,43398,43528,43530,43552,43554,43560,43656,43690, +pub(super) const KGRID_2BIT_1024: [u16; 1024] = [ + 0, 2, 5, 8, 10, 17, 20, 22, 25, 32, 34, 37, 40, 65, 68, 70, 73, 80, 82, 85, 88, 97, 100, 102, 105, 128, 130, 133, + 136, 145, 148, 160, 165, 170, 257, 260, 262, 265, 272, 274, 277, 280, 289, 292, 320, 322, 325, 328, 337, 340, 342, + 345, 352, 357, 360, 385, 388, 400, 402, 405, 417, 420, 512, 514, 517, 520, 529, 532, 544, 554, 577, 580, 582, 585, + 592, 597, 640, 645, 650, 660, 674, 1025, 1028, 1030, 1033, 1040, 1042, 1045, 1048, 1057, 1060, 1062, 1065, 1088, + 1090, 1093, 1096, 1098, 1105, 1108, 1110, 1113, 1120, 1122, 1125, 1153, 1156, 1158, 1161, 1168, 1173, 1176, 1185, + 1188, 1280, 1282, 1285, 1288, 1290, 1297, 1300, 1302, 1305, 1312, 1317, 1320, 1345, 1348, 1350, 1353, 1360, 1362, + 1365, 1368, 1377, 1380, 1408, 1410, 1413, 1416, 1425, 1428, 1440, 1537, 1540, 1542, 1545, 1552, 1557, 1600, 1605, + 1608, 1617, 1620, 1632, 1665, 1668, 1680, 2048, 2050, 2053, 2056, 2065, 2068, 2070, 2073, 2080, 2085, 2090, 2113, + 2116, 2118, 2121, 2128, 2130, 2133, 2136, 2145, 2148, 2176, 2181, 2196, 2218, 2305, 2308, 2320, 2322, 2325, 2328, + 2337, 2368, 2373, 2376, 2385, 2388, 2400, 2433, 2448, 2560, 2577, 2580, 2594, 2600, 2602, 2640, 2713, 4097, 4100, + 4102, 4105, 4112, 4114, 4117, 4120, 4129, 4132, 4134, 4160, 4162, 4165, 4168, 4177, 4180, 4182, 4185, 4192, 4194, + 4197, 4200, 4225, 4228, 4230, 4240, 4245, 4248, 4257, 4260, 4352, 4354, 4357, 4360, 4362, 4369, 4372, 4374, 4377, + 4384, 4386, 4389, 4392, 4417, 4420, 4422, 4425, 4432, 4434, 4437, 4440, 4449, 4452, 4480, 4482, 4485, 4488, 4497, + 4500, 4609, 4612, 4617, 4624, 4629, 4641, 4644, 4672, 4677, 4689, 4692, 4737, 4740, 4752, 5120, 5122, 5125, 5128, + 5137, 5140, 5142, 5145, 5152, 5157, 5160, 5185, 5188, 5190, 5193, 5200, 5202, 5205, 5208, 5217, 5220, 5248, 5250, + 5253, 5256, 5265, 5268, 5280, 5377, 5380, 5382, 5385, 5392, 5394, 5397, 5400, 5409, 5412, 5440, 5442, 5445, 5448, + 5457, 5460, 5472, 5505, 5508, 5520, 5632, 5637, 5640, 5649, 5652, 5664, 5697, 5700, 5712, 5760, 5802, 6145, 6148, + 6150, 6153, 6160, 6165, 6168, 6177, 6208, 6210, 6213, 6216, 6225, 6228, 6240, 6273, 6276, 6400, 6402, 6405, 6408, + 6417, 6420, 6432, 6465, 6468, 6480, 6505, 6562, 6660, 6672, 6720, 6742, 8192, 8194, 8197, 8200, 8209, 8212, 8214, + 8217, 8224, 8229, 8234, 8257, 8260, 8272, 8274, 8277, 8292, 8320, 8330, 8340, 8362, 8449, 8452, 8464, 8466, 8469, + 8481, 8512, 8514, 8517, 8529, 8532, 8544, 8577, 8580, 8592, 8704, 8714, 8738, 8744, 8746, 8772, 8784, 8840, 8842, + 8872, 9217, 9220, 9222, 9225, 9232, 9237, 9240, 9249, 9252, 9280, 9282, 9285, 9288, 9297, 9300, 9312, 9345, 9348, + 9360, 9472, 9477, 9480, 9489, 9492, 9504, 9537, 9540, 9552, 9574, 9600, 9729, 9732, 9744, 9792, 9817, 10240, 10245, + 10257, 10260, 10305, 10308, 10320, 10378, 10410, 10497, 10500, 10512, 10645, 10762, 10786, 10852, 10888, 10890, + 16385, 16388, 16390, 16393, 16400, 16402, 16405, 16408, 16410, 16417, 16420, 16422, 16448, 16450, 16453, 16456, + 16458, 16465, 16468, 16470, 16473, 16480, 16482, 16485, 16513, 16516, 16528, 16533, 16536, 16545, 16548, 16640, + 16642, 16645, 16648, 16657, 16660, 16662, 16665, 16672, 16674, 16677, 16705, 16708, 16710, 16713, 16720, 16722, + 16725, 16728, 16737, 16740, 16768, 16770, 16773, 16776, 16785, 16788, 16800, 16897, 16900, 16912, 16914, 16917, + 16920, 16932, 16960, 16965, 16968, 16977, 16980, 16992, 17025, 17028, 17408, 17410, 17413, 17416, 17418, 17425, + 17428, 17430, 17433, 17440, 17442, 17445, 17448, 17473, 17476, 17478, 17481, 17488, 17490, 17493, 17496, 17505, + 17508, 17536, 17538, 17541, 17544, 17553, 17556, 17568, 17665, 17668, 17670, 17673, 17680, 17682, 17685, 17688, + 17697, 17700, 17728, 17730, 17733, 17736, 17745, 17748, 17760, 17770, 17793, 17796, 17808, 17920, 17922, 17925, + 17928, 17937, 17940, 17952, 17985, 17988, 18000, 18048, 18085, 18433, 18436, 18441, 18448, 18450, 18453, 18456, + 18465, 18468, 18496, 18498, 18501, 18504, 18513, 18516, 18528, 18564, 18576, 18688, 18690, 18693, 18696, 18705, + 18708, 18720, 18753, 18756, 18768, 18816, 18838, 18945, 18948, 18960, 19008, 20480, 20482, 20485, 20488, 20497, + 20500, 20502, 20505, 20512, 20514, 20517, 20520, 20545, 20548, 20550, 20553, 20560, 20562, 20565, 20568, 20577, + 20580, 20608, 20610, 20613, 20616, 20625, 20628, 20737, 20740, 20742, 20745, 20752, 20754, 20757, 20760, 20769, + 20772, 20800, 20802, 20805, 20808, 20817, 20820, 20832, 20865, 20868, 20880, 20992, 20997, 21000, 21009, 21012, + 21024, 21057, 21060, 21072, 21097, 21120, 21505, 21508, 21510, 21513, 21520, 21522, 21525, 21528, 21537, 21540, + 21568, 21570, 21573, 21576, 21585, 21588, 21600, 21633, 21636, 21648, 21760, 21762, 21765, 21768, 21777, 21780, + 21792, 21825, 21828, 21840, 21888, 22017, 22020, 22032, 22054, 22080, 22528, 22530, 22533, 22536, 22545, 22548, + 22560, 22593, 22596, 22608, 22618, 22656, 22785, 22788, 22800, 22848, 23040, 23065, 23173, 23208, 24577, 24580, + 24582, 24592, 24594, 24597, 24600, 24609, 24612, 24640, 24645, 24648, 24657, 24660, 24672, 24708, 24720, 24832, + 24834, 24837, 24840, 24849, 24852, 24864, 24897, 24900, 24912, 24960, 24985, 25092, 25104, 25152, 25174, 25249, + 25600, 25605, 25608, 25617, 25620, 25632, 25665, 25668, 25680, 25728, 25857, 25860, 25872, 25920, 25930, 25960, + 26002, 26112, 26260, 26625, 26628, 26640, 26725, 26776, 26880, 26922, 27202, 27297, 32768, 32770, 32773, 32776, + 32785, 32788, 32793, 32800, 32805, 32833, 32836, 32848, 32850, 32853, 32856, 32865, 32896, 32901, 32913, 32916, + 33025, 33028, 33033, 33040, 33042, 33045, 33048, 33057, 33060, 33088, 33090, 33093, 33096, 33105, 33108, 33153, + 33156, 33168, 33193, 33280, 33285, 33290, 33297, 33300, 33345, 33348, 33360, 33793, 33796, 33798, 33801, 33808, + 33810, 33813, 33816, 33825, 33856, 33858, 33861, 33864, 33873, 33876, 33888, 33921, 33924, 33936, 34048, 34050, + 34053, 34056, 34065, 34068, 34080, 34113, 34116, 34128, 34176, 34186, 34305, 34308, 34320, 34345, 34368, 34816, + 34821, 34833, 34836, 34881, 34884, 34896, 34978, 35073, 35076, 35136, 35173, 35362, 35416, 35418, 35458, 35490, + 36865, 36868, 36873, 36880, 36882, 36885, 36888, 36900, 36928, 36930, 36933, 36936, 36945, 36948, 36960, 36993, + 36996, 37008, 37120, 37125, 37137, 37140, 37185, 37188, 37200, 37210, 37377, 37380, 37392, 37440, 37542, 37888, + 37890, 37893, 37896, 37905, 37908, 37920, 37953, 37956, 37968, 38016, 38038, 38145, 38148, 38160, 38208, 38296, + 38305, 38400, 38470, 38500, 38913, 38916, 38928, 38950, 38976, 39081, 39168, 39241, 39250, 39568, 40960, 40965, + 40970, 40980, 40994, 41002, 41025, 41028, 41040, 41122, 41130, 41280, 41317, 41474, 41482, 41506, 41512, 41514, + 41602, 41608, 41610, 41640, 41985, 41988, 42000, 42048, 42121, 42148, 42240, 42265, 42577, 43018, 43048, 43170, + 43348, 43398, 43528, 43530, 43552, 43554, 43560, 43656, 43690, ]; -pub(super) const KGRID_256: [u16;256] = [ -0,2,4,9,11,15,16,18,25,34,59,61,65,67,72,74, -81,85,88,90,97,108,120,128,130,132,137,144,146,153,155,159, -169,175,189,193,199,200,202,213,248,267,287,292,303,315,317,321, -327,346,362,413,436,456,460,462,483,497,513,515,520,522,529,531, -536,538,540,551,552,576,578,585,592,594,641,643,648,650,657,664, -698,704,706,720,729,742,758,769,773,808,848,852,870,889,901,978, -992,1024,1026,1033,1035,1040,1042,1046,1049,1058,1089,1091,1093,1096,1098,1105, -1112,1139,1143,1144,1152,1154,1161,1167,1168,1170,1183,1184,1197,1217,1224,1228, -1272,1276,1309,1323,1347,1367,1377,1404,1473,1475,1486,1509,1537,1544,1546,1553, -1555,1576,1589,1594,1600,1602,1616,1625,1636,1638,1665,1667,1672,1685,1706,1722, -1737,1755,1816,1831,1850,1856,1862,1874,1901,1932,1950,1971,2011,2032,2052,2063, -2077,2079,2091,2095,2172,2192,2207,2208,2224,2230,2247,2277,2308,2345,2356,2389, -2403,2424,2501,2504,2506,2520,2570,2593,2616,2624,2630,2646,2669,2700,2714,2746, -2754,2795,2824,2835,2839,2874,2882,2905,2984,3028,3042,3092,3108,3110,3124,3153, -3185,3215,3252,3288,3294,3364,3397,3434,3483,3523,3537,3587,3589,3591,3592,3610, -3626,3670,3680,3722,3749,3754,3776,3789,3803,3824,3857,3873,3904,3906,3924,3992, +pub(super) const KGRID_256: [u16; 256] = [ + 0, 2, 4, 9, 11, 15, 16, 18, 25, 34, 59, 61, 65, 67, 72, 74, 81, 85, 88, 90, 97, 108, 120, 128, 130, 132, 137, 144, + 146, 153, 155, 159, 169, 175, 189, 193, 199, 200, 202, 213, 248, 267, 287, 292, 303, 315, 317, 321, 327, 346, 362, + 413, 436, 456, 460, 462, 483, 497, 513, 515, 520, 522, 529, 531, 536, 538, 540, 551, 552, 576, 578, 585, 592, 594, + 641, 643, 648, 650, 657, 664, 698, 704, 706, 720, 729, 742, 758, 769, 773, 808, 848, 852, 870, 889, 901, 978, 992, + 1024, 1026, 1033, 1035, 1040, 1042, 1046, 1049, 1058, 1089, 1091, 1093, 1096, 1098, 1105, 1112, 1139, 1143, 1144, + 1152, 1154, 1161, 1167, 1168, 1170, 1183, 1184, 1197, 1217, 1224, 1228, 1272, 1276, 1309, 1323, 1347, 1367, 1377, + 1404, 1473, 1475, 1486, 1509, 1537, 1544, 1546, 1553, 1555, 1576, 1589, 1594, 1600, 1602, 1616, 1625, 1636, 1638, + 1665, 1667, 1672, 1685, 1706, 1722, 1737, 1755, 1816, 1831, 1850, 1856, 1862, 1874, 1901, 1932, 1950, 1971, 2011, + 2032, 2052, 2063, 2077, 2079, 2091, 2095, 2172, 2192, 2207, 2208, 2224, 2230, 2247, 2277, 2308, 2345, 2356, 2389, + 2403, 2424, 2501, 2504, 2506, 2520, 2570, 2593, 2616, 2624, 2630, 2646, 2669, 2700, 2714, 2746, 2754, 2795, 2824, + 2835, 2839, 2874, 2882, 2905, 2984, 3028, 3042, 3092, 3108, 3110, 3124, 3153, 3185, 3215, 3252, 3288, 3294, 3364, + 3397, 3434, 3483, 3523, 3537, 3587, 3589, 3591, 3592, 3610, 3626, 3670, 3680, 3722, 3749, 3754, 3776, 3789, 3803, + 3824, 3857, 3873, 3904, 3906, 3924, 3992, ]; -pub(super) const KGRID_512: [u16;512] = [ -0,1,2,5,7,8,9,10,12,14,16,17,21,27,32,34, -37,39,41,43,48,50,57,60,63,64,65,66,68,72,73,77, -80,83,87,89,93,100,113,117,122,128,129,133,135,136,139,142, -145,149,152,156,162,165,167,169,171,184,187,195,201,205,208,210, -217,219,222,228,232,234,247,249,253,256,267,271,273,276,282,288, -291,297,312,322,324,336,338,342,347,353,357,359,374,379,390,393, -395,409,426,441,448,450,452,464,466,470,475,488,492,512,513,514, -516,520,521,523,525,527,528,530,537,540,542,556,558,561,570,576, -577,579,582,584,588,593,600,603,609,616,618,632,638,640,650,653, -655,656,660,666,672,675,685,688,698,705,708,711,712,715,721,727, -728,732,737,754,760,771,773,778,780,793,795,802,806,808,812,833, -840,843,849,856,858,873,912,916,919,932,934,961,963,968,970,977, -989,993,1010,1016,1024,1025,1027,1029,1031,1032,1034,1036,1038,1041,1043,1047, -1048,1050,1057,1059,1061,1064,1066,1079,1080,1083,1085,1088,1090,1096,1099,1103, -1106,1109,1113,1116,1122,1129,1153,1156,1159,1169,1171,1176,1183,1185,1195,1199, -1209,1212,1216,1218,1221,1225,1234,1236,1241,1243,1250,1256,1270,1281,1287,1296, -1299,1306,1309,1313,1338,1341,1348,1353,1362,1375,1376,1387,1400,1408,1410,1415, -1425,1453,1457,1477,1481,1494,1496,1507,1512,1538,1545,1547,1549,1551,1554,1561, -1563,1565,1570,1572,1575,1577,1587,1593,1601,1603,1605,1612,1617,1619,1632,1648, -1658,1662,1664,1674,1680,1690,1692,1704,1729,1736,1740,1745,1747,1751,1752,1761, -1763,1767,1773,1787,1795,1801,1806,1810,1817,1834,1840,1844,1857,1864,1866,1877, -1882,1892,1902,1915,1934,1953,1985,1987,2000,2002,2013,2048,2052,2058,2064,2068, -2071,2074,2081,2088,2104,2114,2119,2121,2123,2130,2136,2141,2147,2153,2157,2177, -2179,2184,2189,2193,2203,2208,2223,2226,2232,2244,2249,2251,2256,2258,2265,2269, -2304,2306,2324,2335,2336,2361,2373,2375,2385,2418,2443,2460,2480,2504,2509,2520, -2531,2537,2562,2568,2572,2578,2592,2596,2599,2602,2614,2620,2625,2627,2629,2634, -2641,2650,2682,2688,2697,2707,2712,2718,2731,2754,2759,2760,2775,2788,2793,2805, -2811,2817,2820,2832,2842,2854,2890,2902,2921,2923,2978,3010,3012,3026,3081,3083, -3085,3097,3099,3120,3136,3152,3159,3188,3210,3228,3234,3245,3250,3256,3264,3276, -3281,3296,3349,3363,3378,3392,3395,3420,3440,3461,3488,3529,3531,3584,3588,3591, -3600,3602,3614,3616,3628,3634,3650,3657,3668,3683,3685,3713,3716,3720,3726,3729, -3736,3753,3778,3802,3805,3819,3841,3845,3851,3856,3880,3922,3938,3970,3993,4032, +pub(super) const KGRID_512: [u16; 512] = [ + 0, 1, 2, 5, 7, 8, 9, 10, 12, 14, 16, 17, 21, 27, 32, 34, 37, 39, 41, 43, 48, 50, 57, 60, 63, 64, 65, 66, 68, 72, + 73, 77, 80, 83, 87, 89, 93, 100, 113, 117, 122, 128, 129, 133, 135, 136, 139, 142, 145, 149, 152, 156, 162, 165, + 167, 169, 171, 184, 187, 195, 201, 205, 208, 210, 217, 219, 222, 228, 232, 234, 247, 249, 253, 256, 267, 271, 273, + 276, 282, 288, 291, 297, 312, 322, 324, 336, 338, 342, 347, 353, 357, 359, 374, 379, 390, 393, 395, 409, 426, 441, + 448, 450, 452, 464, 466, 470, 475, 488, 492, 512, 513, 514, 516, 520, 521, 523, 525, 527, 528, 530, 537, 540, 542, + 556, 558, 561, 570, 576, 577, 579, 582, 584, 588, 593, 600, 603, 609, 616, 618, 632, 638, 640, 650, 653, 655, 656, + 660, 666, 672, 675, 685, 688, 698, 705, 708, 711, 712, 715, 721, 727, 728, 732, 737, 754, 760, 771, 773, 778, 780, + 793, 795, 802, 806, 808, 812, 833, 840, 843, 849, 856, 858, 873, 912, 916, 919, 932, 934, 961, 963, 968, 970, 977, + 989, 993, 1010, 1016, 1024, 1025, 1027, 1029, 1031, 1032, 1034, 1036, 1038, 1041, 1043, 1047, 1048, 1050, 1057, + 1059, 1061, 1064, 1066, 1079, 1080, 1083, 1085, 1088, 1090, 1096, 1099, 1103, 1106, 1109, 1113, 1116, 1122, 1129, + 1153, 1156, 1159, 1169, 1171, 1176, 1183, 1185, 1195, 1199, 1209, 1212, 1216, 1218, 1221, 1225, 1234, 1236, 1241, + 1243, 1250, 1256, 1270, 1281, 1287, 1296, 1299, 1306, 1309, 1313, 1338, 1341, 1348, 1353, 1362, 1375, 1376, 1387, + 1400, 1408, 1410, 1415, 1425, 1453, 1457, 1477, 1481, 1494, 1496, 1507, 1512, 1538, 1545, 1547, 1549, 1551, 1554, + 1561, 1563, 1565, 1570, 1572, 1575, 1577, 1587, 1593, 1601, 1603, 1605, 1612, 1617, 1619, 1632, 1648, 1658, 1662, + 1664, 1674, 1680, 1690, 1692, 1704, 1729, 1736, 1740, 1745, 1747, 1751, 1752, 1761, 1763, 1767, 1773, 1787, 1795, + 1801, 1806, 1810, 1817, 1834, 1840, 1844, 1857, 1864, 1866, 1877, 1882, 1892, 1902, 1915, 1934, 1953, 1985, 1987, + 2000, 2002, 2013, 2048, 2052, 2058, 2064, 2068, 2071, 2074, 2081, 2088, 2104, 2114, 2119, 2121, 2123, 2130, 2136, + 2141, 2147, 2153, 2157, 2177, 2179, 2184, 2189, 2193, 2203, 2208, 2223, 2226, 2232, 2244, 2249, 2251, 2256, 2258, + 2265, 2269, 2304, 2306, 2324, 2335, 2336, 2361, 2373, 2375, 2385, 2418, 2443, 2460, 2480, 2504, 2509, 2520, 2531, + 2537, 2562, 2568, 2572, 2578, 2592, 2596, 2599, 2602, 2614, 2620, 2625, 2627, 2629, 2634, 2641, 2650, 2682, 2688, + 2697, 2707, 2712, 2718, 2731, 2754, 2759, 2760, 2775, 2788, 2793, 2805, 2811, 2817, 2820, 2832, 2842, 2854, 2890, + 2902, 2921, 2923, 2978, 3010, 3012, 3026, 3081, 3083, 3085, 3097, 3099, 3120, 3136, 3152, 3159, 3188, 3210, 3228, + 3234, 3245, 3250, 3256, 3264, 3276, 3281, 3296, 3349, 3363, 3378, 3392, 3395, 3420, 3440, 3461, 3488, 3529, 3531, + 3584, 3588, 3591, 3600, 3602, 3614, 3616, 3628, 3634, 3650, 3657, 3668, 3683, 3685, 3713, 3716, 3720, 3726, 3729, + 3736, 3753, 3778, 3802, 3805, 3819, 3841, 3845, 3851, 3856, 3880, 3922, 3938, 3970, 3993, 4032, ]; diff --git a/crates/native-cpu-expert/src/rust_simd.rs b/crates/native-cpu-expert/src/rust_simd.rs index ac048059..4a306388 100644 --- a/crates/native-cpu-expert/src/rust_simd.rs +++ b/crates/native-cpu-expert/src/rust_simd.rs @@ -7,62 +7,148 @@ use std::sync::OnceLock; // `avx512*` leaves. Every entry point checks its gate before reaching a leaf (NativePool::new, ExpertPool::new, // PlanarActivation::*, rust_native_general::*_rows, Activation::{quantize,dot}). Slice extents are either asserted in // the leaf or established by the safe caller; each leaf's header states the bound it relies on. -#[cfg_attr(not(windows), link(name="m"))] -unsafe extern "C" { fn expf(x:f32)->f32; } -pub(super) fn silu(g:f32,u:f32)->f32 { - // SAFETY: libc expf is the exact float overload used by Original std::exp. - (g/(1.0+unsafe {expf(-g)}))*u +#[cfg_attr(not(windows), link(name = "m"))] +unsafe extern "C" { + fn expf(x: f32) -> f32; } -pub(super) fn atoi(value:&str)->i32 { - let b=value.as_bytes();let mut i=0;while i f32 { + // SAFETY: libc expf is the exact float overload used by Original std::exp. + (g / (1.0 + unsafe { expf(-g) })) * u +} +pub(super) fn atoi(value: &str) -> i32 { + let b = value.as_bytes(); + let mut i = 0; + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + let mut sign = 1i32; + if i < b.len() { + if b[i] == b'-' { + sign = -1; + i += 1; + } else if b[i] == b'+' { + i += 1; + } + } + let mut v = 0i32; + while i < b.len() && b[i].is_ascii_digit() { + v = v.wrapping_mul(10).wrapping_add((b[i] - b'0') as i32); + i += 1; + } + v.wrapping_mul(sign) } #[derive(Clone, Copy)] -pub(super) struct Dispatch {pub iq512:bool,pub iq256:bool,pub iq4nl:bool,pub mt_min:i32,pub gather:bool,pub prefetch:i32,pub avx512:bool} -pub(super) fn dispatch()->&'static Dispatch { - static D:OnceLock=OnceLock::new();D.get_or_init(||{ - let avx512=avx512_ok();Dispatch {iq512:avx512&&std::env::var_os("STRATA_NO_IQ512").is_none(),iq256:std::env::var_os("STRATA_NO_IQ256").is_none(),iq4nl:std::env::var_os("STRATA_NO_IQ4NL").is_none(),mt_min:std::env::var("STRATA_IQ_MT_MIN").map(|s|atoi(&s)).unwrap_or(2),gather:std::env::var_os("STRATA_IQ_GATHER").is_some(),prefetch:std::env::var("STRATA_IQ_PREFETCH").map(|s|atoi(&s)).unwrap_or(2048),avx512} - }) +pub(super) struct Dispatch { + pub iq512: bool, + pub iq256: bool, + pub iq4nl: bool, + pub mt_min: i32, + pub gather: bool, + pub prefetch: i32, + pub avx512: bool, } -pub(super) fn avx2_ok()->bool { - static VALUE:OnceLock=OnceLock::new();*VALUE.get_or_init(probe_avx2) && super::rust_ggml_native::compiled_admitted() +pub(super) fn dispatch() -> &'static Dispatch { + static D: OnceLock = OnceLock::new(); + D.get_or_init(|| { + let avx512 = avx512_ok(); + Dispatch { + iq512: avx512 && std::env::var_os("STRATA_NO_IQ512").is_none(), + iq256: std::env::var_os("STRATA_NO_IQ256").is_none(), + iq4nl: std::env::var_os("STRATA_NO_IQ4NL").is_none(), + mt_min: std::env::var("STRATA_IQ_MT_MIN").map(|s| atoi(&s)).unwrap_or(2), + gather: std::env::var_os("STRATA_IQ_GATHER").is_some(), + prefetch: std::env::var("STRATA_IQ_PREFETCH").map(|s| atoi(&s)).unwrap_or(2048), + avx512, + } + }) } -fn probe_avx2()->bool { - // SAFETY: CPUID always available on x86_64; XGETBV only after OSXSAVE. - unsafe {if __cpuid(0).eax<7{return false;}let c=__cpuid(1).ecx; - if [12,27,28,29].iter().any(|b|c&(1< bool { + static VALUE: OnceLock = OnceLock::new(); + *VALUE.get_or_init(probe_avx2) && super::rust_ggml_native::compiled_admitted() } -pub(super) fn avx512_ok()->bool { - static VALUE:OnceLock=OnceLock::new();*VALUE.get_or_init(probe_avx512) +fn probe_avx2() -> bool { + // SAFETY: CPUID always available on x86_64; XGETBV only after OSXSAVE. + unsafe { + if __cpuid(0).eax < 7 { + return false; + } + let c = __cpuid(1).ecx; + if [12, 27, 28, 29].iter().any(|b| c & (1 << b) == 0) { + return false; + } + _xgetbv(0) & 6 == 6 && __cpuid_count(7, 0).ebx & (1 << 5) != 0 + } } -fn probe_avx512()->bool { - if std::env::var("STRATA_FORCE_AVX2").is_ok_and(|v|v.as_bytes().first()==Some(&b'1')){return false;} - // SAFETY: same Original CPUID/OSXSAVE/XCR0 gate, plus wrapper's DQ refusal. - unsafe {if __cpuid(0).eax<7||__cpuid(1).ecx&(1<<27)==0{return false;} - if _xgetbv(0)&0xe6!=0xe6{return false;}let c=__cpuid_count(7,0); - [16,30,31].iter().all(|b|c.ebx&(1< bool { + static VALUE: OnceLock = OnceLock::new(); + *VALUE.get_or_init(probe_avx512) } -pub(super) fn dq_ok()->bool {/* SAFETY: CPUID exists on x86_64; callers query it only after avx2_ok()/avx512_ok() confirmed max leaf >= 7. */unsafe {__cpuid_count(7,0).ebx&(1<<17)!=0}} -#[target_feature(enable="avx2,f16c")] -pub(super) unsafe fn half(h:u16)->f32 { unsafe {_mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(h as i32)))} } -#[target_feature(enable="avx2,f16c")] -pub(super) unsafe fn to_half(x:f32)->u16 { unsafe {_mm_cvtsi128_si32(_mm_cvtps_ph::<0>(_mm_set_ss(x))) as u16} } -#[target_feature(enable="avx2")] -pub(super) unsafe fn hsum_original(v:__m256)->f32 {unsafe {let s=_mm_add_ps(_mm256_castps256_ps128(v),_mm256_extractf128_ps::<1>(v));_mm_cvtss_f32(_mm_hadd_ps(_mm_hadd_ps(s,s),s))}} -#[target_feature(enable="avx2")] -pub(super) unsafe fn hsum_ggml(v:__m256)->f32 {unsafe {let s=_mm_add_ps(_mm256_extractf128_ps::<1>(v),_mm256_castps256_ps128(v));let s=_mm_add_ps(s,_mm_movehl_ps(s,s));_mm_cvtss_f32(_mm_add_ss(s,_mm_movehdup_ps(s)))}} -#[target_feature(enable="avx2")] -pub(super) unsafe fn signs32(m:u32)->__m256i {unsafe { - let bm=_mm_set1_epi32(m as i32); - let lo=_mm_shuffle_epi8(bm,_mm_setr_epi8(0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1)); - let hi=_mm_shuffle_epi8(bm,_mm_setr_epi8(2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3)); - let bits=_mm256_inserti128_si256::<1>(_mm256_castsi128_si256(lo),hi); - let sel=_mm256_setr_epi8(1,2,4,8,16,32,64,-128,1,2,4,8,16,32,64,-128,1,2,4,8,16,32,64,-128,1,2,4,8,16,32,64,-128); - _mm256_or_si256(_mm256_cmpeq_epi8(_mm256_and_si256(bits,sel),sel),_mm256_set1_epi8(1)) -}} -#[target_feature(enable="avx2")] +fn probe_avx512() -> bool { + if std::env::var("STRATA_FORCE_AVX2").is_ok_and(|v| v.as_bytes().first() == Some(&b'1')) { + return false; + } + // SAFETY: same Original CPUID/OSXSAVE/XCR0 gate, plus wrapper's DQ refusal. + unsafe { + if __cpuid(0).eax < 7 || __cpuid(1).ecx & (1 << 27) == 0 { + return false; + } + if _xgetbv(0) & 0xe6 != 0xe6 { + return false; + } + let c = __cpuid_count(7, 0); + [16, 30, 31].iter().all(|b| c.ebx & (1 << b) != 0) && c.ecx & (1 << 11) != 0 && c.ecx & (1 << 1) != 0 + } +} +pub(super) fn dq_ok() -> bool { + /* SAFETY: CPUID exists on x86_64; callers query it only after avx2_ok()/avx512_ok() confirmed max leaf >= 7. */ + unsafe { __cpuid_count(7, 0).ebx & (1 << 17) != 0 } +} +#[target_feature(enable = "avx2,f16c")] +pub(super) unsafe fn half(h: u16) -> f32 { + unsafe { _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(h as i32))) } +} +#[target_feature(enable = "avx2,f16c")] +pub(super) unsafe fn to_half(x: f32) -> u16 { + unsafe { _mm_cvtsi128_si32(_mm_cvtps_ph::<0>(_mm_set_ss(x))) as u16 } +} +#[target_feature(enable = "avx2")] +pub(super) unsafe fn hsum_original(v: __m256) -> f32 { + unsafe { + let s = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps::<1>(v)); + _mm_cvtss_f32(_mm_hadd_ps(_mm_hadd_ps(s, s), s)) + } +} +#[target_feature(enable = "avx2")] +pub(super) unsafe fn hsum_ggml(v: __m256) -> f32 { + unsafe { + let s = _mm_add_ps(_mm256_extractf128_ps::<1>(v), _mm256_castps256_ps128(v)); + let s = _mm_add_ps(s, _mm_movehl_ps(s, s)); + _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) + } +} +#[target_feature(enable = "avx2")] +pub(super) unsafe fn signs32(m: u32) -> __m256i { + unsafe { + let bm = _mm_set1_epi32(m as i32); + let lo = _mm_shuffle_epi8(bm, _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1)); + let hi = _mm_shuffle_epi8(bm, _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3)); + let bits = _mm256_inserti128_si256::<1>(_mm256_castsi128_si256(lo), hi); + let sel = _mm256_setr_epi8( + 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, + 32, 64, -128, + ); + _mm256_or_si256(_mm256_cmpeq_epi8(_mm256_and_si256(bits, sel), sel), _mm256_set1_epi8(1)) + } +} +#[target_feature(enable = "avx2")] /// # Safety /// Only the target feature: PREFETCH never faults and reads nothing, so `p` may be any address (wrapping_add, no deref). -pub(super) unsafe fn prefetch(p:*const u8) {let n=dispatch().prefetch;if n>0 {unsafe {_mm_prefetch::<_MM_HINT_T0>(p.wrapping_add(n as usize).cast());_mm_prefetch::<_MM_HINT_T0>(p.wrapping_add(n as usize+64).cast());}}} +pub(super) unsafe fn prefetch(p: *const u8) { + let n = dispatch().prefetch; + if n > 0 { + unsafe { + _mm_prefetch::<_MM_HINT_T0>(p.wrapping_add(n as usize).cast()); + _mm_prefetch::<_MM_HINT_T0>(p.wrapping_add(n as usize + 64).cast()); + } + } +} diff --git a/crates/native-cpu-expert/src/rust_topology.rs b/crates/native-cpu-expert/src/rust_topology.rs index 1aeb2a1b..cbc5794f 100644 --- a/crates/native-cpu-expert/src/rust_topology.rs +++ b/crates/native-cpu-expert/src/rust_topology.rs @@ -1,49 +1,179 @@ //! Literal Original Linux hybrid topology and reversible host affinity. use super::rust_platform::pin; -#[derive(Clone,Copy,Debug,Default,Eq,PartialEq)]pub enum PoolAffinity{Auto,PCores,#[default]All} -#[derive(Clone,Debug,Default)]pub struct CpuTopology{pub is_hybrid:bool,pub p_cores:usize,pub p_threads:usize,pub e_cores:usize,pub worker_cores:Vec,pub host_core:i32} -#[cfg(unix)] -unsafe extern "C"{fn sched_getaffinity(pid:i32,bytes:usize,set:*mut usize)->i32;fn pthread_getaffinity_np(thread:usize,bytes:usize,set:*mut usize)->i32;fn pthread_setaffinity_np(thread:usize,bytes:usize,set:*const usize)->i32;fn pthread_self()->usize;} -#[cfg(unix)] -fn number(path:String)->i64{std::fs::read_to_string(path).ok().and_then(|s|s.split_whitespace().next()?.parse().ok()).unwrap_or(-1)} -#[cfg(unix)] -pub fn detect_cpu_topology(skip_first:bool,affinity:PoolAffinity)->CpuTopology{ - let mut t=CpuTopology{host_core:-1,..CpuTopology::default()};let mut mask=[0usize;16];let mut allowed=Vec::new();if /* SAFETY: `mask` is a live, writable 128-byte cpu_set_t-sized buffer; no pointer is retained. */unsafe{sched_getaffinity(0,std::mem::size_of_val(&mask),mask.as_mut_ptr())}==0{for i in 0..1024{if mask[i/64]&(1usize<<(i%64))!=0{allowed.push(i as i32);}}}else{allowed.extend(0..std::thread::available_parallelism().map(|n|n.get()).unwrap_or(0)as i32);} - let mut seen=Vec::new();let mut all=Vec::new();let mut max=0;let mut min=1_000_000;for cpu in allowed{let package=number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id"));let core=number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id"));let cap=number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity"));if cap>0{max=max.max(cap);min=min.min(cap);}let sibling=if package>=0&&core>=0{let key=(package,core);if seen.contains(&key){true}else{seen.push(key);false}}else{false};all.push((cpu,cap,sibling));}t.is_hybrid=max>0&&max>min; - if t.is_hybrid{for &(_,cap,sibling) in &all{if cap==max{if !sibling{t.p_cores+=1;}t.p_threads+=1;}else if !sibling{t.e_cores+=1;}}}else{t.p_cores=seen.len();t.p_threads=all.len();} - if affinity==PoolAffinity::All||!t.is_hybrid{t.worker_cores=all.iter().filter_map(|&(cpu,_,sib)|(!sib).then_some(cpu)).collect();if skip_first&&!t.worker_cores.is_empty(){t.host_core=t.worker_cores.remove(0);}return t;} - let mut primary=Vec::new();let mut siblings=Vec::new();let mut efficient=Vec::new();for (cpu,cap,sib) in all{if cap==max{if sib{siblings.push(cpu);}else{primary.push(cpu);}}else{efficient.push(cpu);}} - if skip_first&&!primary.is_empty(){t.host_core=primary.remove(0);}t.worker_cores=primary;t.worker_cores.extend(siblings);if affinity!=PoolAffinity::PCores{t.worker_cores.extend(efficient);}t +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum PoolAffinity { + Auto, + PCores, + #[default] + All, +} +#[derive(Clone, Debug, Default)] +pub struct CpuTopology { + pub is_hybrid: bool, + pub p_cores: usize, + pub p_threads: usize, + pub e_cores: usize, + pub worker_cores: Vec, + pub host_core: i32, } #[cfg(unix)] -pub fn pin_current_thread(core:i32)->i64{if core<0{return -1;}let mut old=[0usize;16];if /* SAFETY: `old` is a live 128-byte cpu_set_t-sized buffer for the calling thread. */unsafe{pthread_getaffinity_np(pthread_self(),std::mem::size_of_val(&old),old.as_mut_ptr())}!=0{return -1;}let previous=old[0]as i64;pin(core);previous} +unsafe extern "C" { + fn sched_getaffinity(pid: i32, bytes: usize, set: *mut usize) -> i32; + fn pthread_getaffinity_np(thread: usize, bytes: usize, set: *mut usize) -> i32; + fn pthread_setaffinity_np(thread: usize, bytes: usize, set: *const usize) -> i32; + fn pthread_self() -> usize; +} #[cfg(unix)] -pub fn restore_thread_affinity(previous:i64){if previous<=0{return;}let mut mask=[0usize;16];mask[0]=previous as usize;/* SAFETY: `mask` is a live 128-byte mask; a refusal leaves the thread where it is. */unsafe{let _=pthread_setaffinity_np(pthread_self(),std::mem::size_of_val(&mask),mask.as_ptr());}} +fn number(path: String) -> i64 { + std::fs::read_to_string(path).ok().and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or(-1) +} +#[cfg(unix)] +pub fn detect_cpu_topology(skip_first: bool, affinity: PoolAffinity) -> CpuTopology { + let mut t = CpuTopology { host_core: -1, ..CpuTopology::default() }; + let mut mask = [0usize; 16]; + let mut allowed = Vec::new(); + if + /* SAFETY: `mask` is a live, writable 128-byte cpu_set_t-sized buffer; no pointer is retained. */ + unsafe { sched_getaffinity(0, std::mem::size_of_val(&mask), mask.as_mut_ptr()) } == 0 { + for i in 0..1024 { + if mask[i / 64] & (1usize << (i % 64)) != 0 { + allowed.push(i as i32); + } + } + } else { + allowed.extend(0..std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0) as i32); + } + let mut seen = Vec::new(); + let mut all = Vec::new(); + let mut max = 0; + let mut min = 1_000_000; + for cpu in allowed { + let package = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/physical_package_id")); + let core = number(format!("/sys/devices/system/cpu/cpu{cpu}/topology/core_id")); + let cap = number(format!("/sys/devices/system/cpu/cpu{cpu}/cpu_capacity")); + if cap > 0 { + max = max.max(cap); + min = min.min(cap); + } + let sibling = if package >= 0 && core >= 0 { + let key = (package, core); + if seen.contains(&key) { + true + } else { + seen.push(key); + false + } + } else { + false + }; + all.push((cpu, cap, sibling)); + } + t.is_hybrid = max > 0 && max > min; + if t.is_hybrid { + for &(_, cap, sibling) in &all { + if cap == max { + if !sibling { + t.p_cores += 1; + } + t.p_threads += 1; + } else if !sibling { + t.e_cores += 1; + } + } + } else { + t.p_cores = seen.len(); + t.p_threads = all.len(); + } + if affinity == PoolAffinity::All || !t.is_hybrid { + t.worker_cores = all.iter().filter_map(|&(cpu, _, sib)| (!sib).then_some(cpu)).collect(); + if skip_first && !t.worker_cores.is_empty() { + t.host_core = t.worker_cores.remove(0); + } + return t; + } + let mut primary = Vec::new(); + let mut siblings = Vec::new(); + let mut efficient = Vec::new(); + for (cpu, cap, sib) in all { + if cap == max { + if sib { + siblings.push(cpu); + } else { + primary.push(cpu); + } + } else { + efficient.push(cpu); + } + } + if skip_first && !primary.is_empty() { + t.host_core = primary.remove(0); + } + t.worker_cores = primary; + t.worker_cores.extend(siblings); + if affinity != PoolAffinity::PCores { + t.worker_cores.extend(efficient); + } + t +} +#[cfg(unix)] +pub fn pin_current_thread(core: i32) -> i64 { + if core < 0 { + return -1; + } + let mut old = [0usize; 16]; + if + /* SAFETY: `old` is a live 128-byte cpu_set_t-sized buffer for the calling thread. */ + unsafe { pthread_getaffinity_np(pthread_self(), std::mem::size_of_val(&old), old.as_mut_ptr()) } != 0 { + return -1; + } + let previous = old[0] as i64; + pin(core); + previous +} +#[cfg(unix)] +pub fn restore_thread_affinity(previous: i64) { + if previous <= 0 { + return; + } + let mut mask = [0usize; 16]; + mask[0] = previous as usize; /* SAFETY: `mask` is a live 128-byte mask; a refusal leaves the thread where it is. */ + unsafe { + let _ = pthread_setaffinity_np(pthread_self(), std::mem::size_of_val(&mask), mask.as_ptr()); + } +} /// Windows: the machine is treated as non-hybrid (every physical core is a worker core, SMT siblings are skipped), the /// non-hybrid branch of the Linux detection. Efficiency classes of hybrid CPUs are not read. #[cfg(windows)] -pub fn detect_cpu_topology(skip_first:bool,affinity:PoolAffinity)->CpuTopology{ - let _=affinity; - let mut t=CpuTopology{host_core:-1,..CpuTopology::default()}; - let masks=super::rust_platform::physical_core_masks(); - let all_threads:usize=masks.iter().map(|m|m.count_ones() as usize).sum(); - t.p_cores=masks.len();t.p_threads=all_threads; - t.worker_cores=super::rust_platform::cores(false); - if skip_first&&!t.worker_cores.is_empty(){t.host_core=t.worker_cores.remove(0);} - t +pub fn detect_cpu_topology(skip_first: bool, affinity: PoolAffinity) -> CpuTopology { + let _ = affinity; + let mut t = CpuTopology { host_core: -1, ..CpuTopology::default() }; + let masks = super::rust_platform::physical_core_masks(); + let all_threads: usize = masks.iter().map(|m| m.count_ones() as usize).sum(); + t.p_cores = masks.len(); + t.p_threads = all_threads; + t.worker_cores = super::rust_platform::cores(false); + if skip_first && !t.worker_cores.is_empty() { + t.host_core = t.worker_cores.remove(0); + } + t } /// Pins the calling thread to `core` and returns the previous mask (word 0), or -1. #[cfg(windows)] -pub fn pin_current_thread(core:i32)->i64{ - if core<0{return -1;} - let Some(old)=super::rust_platform::current_affinity() else{return -1}; - pin(core); - old[0] as i64 +pub fn pin_current_thread(core: i32) -> i64 { + if core < 0 { + return -1; + } + let Some(old) = super::rust_platform::current_affinity() else { return -1 }; + pin(core); + old[0] as i64 } #[cfg(windows)] -pub fn restore_thread_affinity(previous:i64){ - if previous<=0{return;} - let mut mask=[0usize;16];mask[0]=previous as usize; - super::rust_platform::restore_affinity(&mask); +pub fn restore_thread_affinity(previous: i64) { + if previous <= 0 { + return; + } + let mut mask = [0usize; 16]; + mask[0] = previous as usize; + super::rust_platform::restore_affinity(&mask); } diff --git a/crates/native-cpu-expert/src/rust_types.rs b/crates/native-cpu-expert/src/rust_types.rs index 5aa115c4..9bc2f0a4 100644 --- a/crates/native-cpu-expert/src/rust_types.rs +++ b/crates/native-cpu-expert/src/rust_types.rs @@ -1,37 +1,105 @@ //! Original native CPU storage layouts. All dimensions are admitted before kernels. -use super::{Error, Result, H, FF, MAX_ROWS}; +use super::{Error, FF, H, MAX_ROWS, Result}; #[repr(C, align(64))] #[derive(Clone)] -pub(super) struct ActQ { pub q:[i8;H], pub scale:[f32;80], pub sum:[i32;80], pub hx:[f32;80], pub nchunks:i32 } -impl Default for ActQ { fn default()->Self { Self {q:[0;H],scale:[0.0;80],sum:[0;80],hx:[0.0;80],nchunks:0} } } -#[repr(C)] -#[derive(Clone, Copy)] -pub(super) struct Q8K { pub d:f32,pub qs:[i8;256],pub bsums:[i16;16] } -impl Default for Q8K { fn default()->Self {Self {d:0.0,qs:[0;256],bsums:[0;16]}} } -#[repr(C)] -#[derive(Clone, Copy)] -pub(super) struct Q8Zero {pub d:u16,pub qs:[i8;32]} -impl Default for Q8Zero {fn default()->Self {Self {d:0,qs:[0;32]}}} -#[repr(C,align(64))] -#[derive(Clone,Copy)] -pub(super) struct NativeHidden {pub q:[Q8Zero;FF/32],pub padding:[u8;344]} -impl Default for NativeHidden{fn default()->Self{Self{q:[Q8Zero::default();FF/32],padding:[0;344]}}} -#[repr(C, align(64))] -pub(super) struct SplitBuf {pub ff:[[f32;FF];MAX_ROWS],pub a2:[ActQ;MAX_ROWS],pub hq:[NativeHidden;MAX_ROWS]} -impl Default for SplitBuf {fn default()->Self {Self {ff:[[0.0;FF];MAX_ROWS],a2:std::array::from_fn(|_|ActQ::default()),hq:[NativeHidden::default();MAX_ROWS]}}} -#[derive(Clone,Copy)] -pub(super) struct NativeFmt {pub gu:i32,pub down:i32,pub gu_row:usize,pub down_row:usize,pub up_off:usize,pub down_off:usize,pub bytes:usize} -impl NativeFmt { - pub fn new(gu:i32,down:i32)->Result { - let (q,b)=match gu {16=>(256,66),17=>(256,74),18=>(256,98),21=>(256,110),22=>(256,82),23=>(256,136),42=>(64,18),_=>return Err(Error::Unsupported)}; - let (dq,db)=match down {20=>(32,18),42=>(64,18),_=>return Err(Error::Unsupported)}; - let gu_row=H/q*b;let down_row=FF/dq*db;let up_off=gu_row*FF;let down_off=2*up_off; - Ok(Self {gu,down,gu_row,down_row,up_off,down_off,bytes:down_off+down_row*H}) - } +pub(super) struct ActQ { + pub q: [i8; H], + pub scale: [f32; 80], + pub sum: [i32; 80], + pub hx: [f32; 80], + pub nchunks: i32, } -const _: ()=assert!(std::mem::size_of::()==3584); -const _: ()=assert!(std::mem::size_of::()==292); -const _: ()=assert!(std::mem::size_of::()==34); +impl Default for ActQ { + fn default() -> Self { + Self { q: [0; H], scale: [0.0; 80], sum: [0; 80], hx: [0.0; 80], nchunks: 0 } + } +} +#[repr(C)] +#[derive(Clone, Copy)] +pub(super) struct Q8K { + pub d: f32, + pub qs: [i8; 256], + pub bsums: [i16; 16], +} +impl Default for Q8K { + fn default() -> Self { + Self { d: 0.0, qs: [0; 256], bsums: [0; 16] } + } +} +#[repr(C)] +#[derive(Clone, Copy)] +pub(super) struct Q8Zero { + pub d: u16, + pub qs: [i8; 32], +} +impl Default for Q8Zero { + fn default() -> Self { + Self { d: 0, qs: [0; 32] } + } +} +#[repr(C, align(64))] +#[derive(Clone, Copy)] +pub(super) struct NativeHidden { + pub q: [Q8Zero; FF / 32], + pub padding: [u8; 344], +} +impl Default for NativeHidden { + fn default() -> Self { + Self { q: [Q8Zero::default(); FF / 32], padding: [0; 344] } + } +} +#[repr(C, align(64))] +pub(super) struct SplitBuf { + pub ff: [[f32; FF]; MAX_ROWS], + pub a2: [ActQ; MAX_ROWS], + pub hq: [NativeHidden; MAX_ROWS], +} +impl Default for SplitBuf { + fn default() -> Self { + Self { + ff: [[0.0; FF]; MAX_ROWS], + a2: std::array::from_fn(|_| ActQ::default()), + hq: [NativeHidden::default(); MAX_ROWS], + } + } +} +#[derive(Clone, Copy)] +pub(super) struct NativeFmt { + pub gu: i32, + pub down: i32, + pub gu_row: usize, + pub down_row: usize, + pub up_off: usize, + pub down_off: usize, + pub bytes: usize, +} +impl NativeFmt { + pub fn new(gu: i32, down: i32) -> Result { + let (q, b) = match gu { + 16 => (256, 66), + 17 => (256, 74), + 18 => (256, 98), + 21 => (256, 110), + 22 => (256, 82), + 23 => (256, 136), + 42 => (64, 18), + _ => return Err(Error::Unsupported), + }; + let (dq, db) = match down { + 20 => (32, 18), + 42 => (64, 18), + _ => return Err(Error::Unsupported), + }; + let gu_row = H / q * b; + let down_row = FF / dq * db; + let up_off = gu_row * FF; + let down_off = 2 * up_off; + Ok(Self { gu, down, gu_row, down_row, up_off, down_off, bytes: down_off + down_row * H }) + } +} +const _: () = assert!(std::mem::size_of::() == 3584); +const _: () = assert!(std::mem::size_of::() == 292); +const _: () = assert!(std::mem::size_of::() == 34); -const _: ()=assert!(std::mem::size_of::()==1024); -const _: ()=assert!(std::mem::size_of::()==57344); +const _: () = assert!(std::mem::size_of::() == 1024); +const _: () = assert!(std::mem::size_of::() == 57344); diff --git a/crates/native-cpu-expert/src/rust_weight_iq.rs b/crates/native-cpu-expert/src/rust_weight_iq.rs index 20e941ef..f1c62d80 100644 --- a/crates/native-cpu-expert/src/rust_weight_iq.rs +++ b/crates/native-cpu-expert/src/rust_weight_iq.rs @@ -1,63 +1,73 @@ //! Pinned GGML IQ model quantizers and exact distance/index ordered neighbors. -use super::{Error,Result}; -use super::rust_ggml::Kind; -use super::rust_weight_quant::{nearest,qp}; use super::rust_dequant::half_rn; +use super::rust_ggml::Kind; use super::rust_quant_grids::*; -use std::sync::{Arc,Mutex}; -struct Grid{points:Vec<[i8;8]>,map:Vec,neighbors:Vec,dim:usize,bits:usize} -fn alloc(n:usize)->Result>{let mut v=Vec::new();v.try_reserve_exact(n).map_err(|_|Error::Allocation)?;v.resize_with(n,T::default);Ok(v)} -impl Grid{ - fn new(codes:&[u16],dim:usize,bits:usize,want:usize)->Result{let size=if dim==8{43692}else{4096};let mut points=alloc::<[i8;8]>(codes.len())?;let mut map=alloc::(size)?;map.fill(-1);for (i,&code) in codes.iter().enumerate(){for j in 0..dim{points[i][j]=(2*((code as usize>>(bits*j))&((1<(codes.len())?;let mut counts=alloc::(size)?;let mut total=0usize; - for i in 0..size{if map[i]>=0{continue;}Self::distances(i,dim,bits,&points,&mut dist);dist.sort_unstable();let n=Self::count(&dist,want);counts[i]=n;total=total.checked_add(n+1).ok_or(Error::Allocation)?;} - 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;}Ok(Self{points,map,neighbors,dim,bits}) - } - 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;for k in 0..dim{let pos=(2*((i>>(bits*k))&((1<usize{let(mut n,mut distance,mut have)=(0,d[0].0,1);for &(x,_) in d{if x>distance{if have==want{break;}distance=x;have+=1;}n+=1;}n} - fn key(&self,l:&[i8])->usize{let mut u=0;for i in 0..self.dim{u|=(l[i]as usize)<<(self.bits*i);}u} - fn index(&self,l:&[i8])->Result{let i=self.map[self.key(l)];if i<0{Err(Error::NativeFailure)}else{Ok(i as usize)}} - 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=0} +use super::rust_weight_quant::{nearest, qp}; +use super::{Error, Result}; +use std::sync::{Arc, Mutex}; +struct Grid { + points: Vec<[i8; 8]>, + map: Vec, + neighbors: Vec, + dim: usize, + bits: usize, } -static CACHE:Mutex<[Option>;6]>=Mutex::new([None,None,None,None,None,None]); -fn grid_kind(k:Kind)->Option{match k{Kind::Iq2Xxs=>Some(0),Kind::Iq2Xs=>Some(1),Kind::Iq1S|Kind::Iq1M=>Some(2),Kind::Iq2S=>Some(3),Kind::Iq3Xxs=>Some(4),Kind::Iq3S=>Some(5),_=>None}} -fn grid(k:Kind)->Result>{let i=grid_kind(k).ok_or(Error::Unsupported)?;let mut cache=CACHE.lock().map_err(|_|Error::NativeFailure)?;if let Some(g)=&cache[i]{return Ok(Arc::clone(g));}let (codes,dim,bits,want):(&[u16],usize,usize,usize)=match i{0=>(&KGRID_2BIT_256,8,2,2),1=>(&KGRID_2BIT_512,8,2,2),2=>(&KGRID_1BIT_2048,8,2,3),3=>(&KGRID_2BIT_1024,8,2,1),4=>(&KGRID_256,4,3,2),_=>(&KGRID_512,4,3,3)};let g=Arc::new(Grid::new(codes,dim,bits,want)?);cache[i]=Some(Arc::clone(&g));Ok(g)} -pub(super) fn init(k:Kind)->Result<()>{if grid_kind(k).is_some(){grid(k)?;}Ok(())} -pub(super) fn free(k:Kind)->Result<()>{if let Some(i)=grid_kind(k){CACHE.lock().map_err(|_|Error::NativeFailure)?[i]=None;}Ok(())} -fn put_h(y:&mut[u8],d:f32){y[..2].copy_from_slice(&half_rn(d).to_le_bytes());} -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<(f32,f32){let(mut sx,mut s2)=(0.0,0.0);for i in 0..x.len(){let q=(2*l[i]+1)as f32;sx+=w[i]*x[i]*q;s2+=w[i]*q*q;}(sx,s2)} -fn quant_candidates(g:&Grid,inv:f32,x:&[f32],w:&[f32],scale:f32,l:&mut[i8],max:i32,on:&mut[bool]){for k in 0..x.len()/g.dim{let at=k*g.dim;for j in 0..g.dim{l[at+j]=nearest(0.5*(inv*x[at+j]-1.0)).clamp(0,max-1)as i8;}on[k]=g.resolve(&mut l[at..at+g.dim],&x[at..at+g.dim],&w[at..at+g.dim],scale);}} -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 mut sum=0.0;for &v in x{sum+=v*v;}let sigma=sum/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]=std::array::from_fn(|i|qw[at+i]*(sigma+xb[i]*xb[i]).sqrt());let wa:[f32;32]=std::array::from_fn(|i|w[i].sqrt());let(xv,mut sign)=signs::<32>(xb,&w,true);let mut max=xv[0];for &v in &xv[1..]{if v>max{max=v;}}if max<1e-15{continue;}let mut l=[0i8;32];let mut lp=[0u8;32];let mut scale=qp(&xv,4,&mut lp,&w);for i in 0..32{l[i]=lp[i]as i8;}let effective=scale*3.0;if effective<=0.0{continue;}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,&xv,&wa,1.0/inv,&mut aux,3,&mut[false;4]);let(sx,s2)=totals(&xv,&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,&xv,&wa,scale,&mut l,3,&mut[false;4]);let(sx,s2)=totals(&xv,&w,&l);if s2>0.0{scale=sx/s2;}}if scale<0.0{scale=-scale;for s in &mut sign{*s=!*s&127;}}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;}} - if maxs==0.0{return Ok(());}let d=maxs/31.0;put_h(y,d);let inv=1.0/d;for ib in 0..8{q2[2*ib+1]|=(nearest(0.5*(inv*scales[ib]-1.0)).clamp(0,15)as u32)<<28;}for (i,v) in q2.into_iter().enumerate(){y[2+i*4..6+i*4].copy_from_slice(&v.to_le_bytes());}Ok(())} -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 mut sum=0.0;for &v in x{sum+=v*v;}let sigma=sum/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]=std::array::from_fn(|i|qw[at+i]*(sigma+xb[i]*xb[i]).sqrt());let wa:[f32;16]=std::array::from_fn(|i|w[i].sqrt());let(xv,mut sign)=signs::<16>(xb,&w,true);let mut max=xv[0];for &v in &xv[1..]{if v>max{max=v;}}if max<1e-15{continue;}let mut l=[0i8;16];let mut on=[true;2];let mut scale=max/5.0;let mut best=0.0;for is in -9..=9{let inv=(5.0+is as f32*0.1)/max;let mut aux=[0i8;16];let mut ao=[true;2];quant_candidates(g,inv,&xv,&wa,1.0/inv,&mut aux,3,&mut ao);let(sx,s2)=totals(&xv,&w,&aux);if s2>0.0&&sx*sx>best*s2{scale=sx/s2;best=scale*sx;l=aux;on=ao;}} - if on.iter().any(|v|!*v)&&scale>0.0{let inv=1.0/scale;for k in 0..2{if on[k]{continue;}let at=k*8;for j in 0..8{l[at+j]=nearest(0.5*(inv*xv[at+j]-1.0)).clamp(0,2)as i8;}g.resolve(&mut l[at..at+8],&xv[at..at+8],&wa[at..at+8],scale);}let(sx,s2)=totals(&xv,&w,&l);if s2>0.0{scale=sx/s2;}}if scale<0.0{scale=-scale;for s in &mut sign[..2]{*s=!*s&127;}}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;}} - if maxs==0.0{return Ok(());}let d=maxs/31.0;put_h(y,d);let inv=1.0/d;for ib in 0..16{let s=nearest(0.5*(inv*scales[ib]-1.0)).clamp(0,15)as u8;y[66+ib/2]|=s<<(4*(ib%2));}for(i,v)in q2.into_iter().enumerate(){y[2+i*2..4+i*2].copy_from_slice(&v.to_le_bytes());}Ok(())} -fn iq3(g:&Grid,kind:Kind,x:&[f32],y:&mut[u8],qw:Option<&[f32]>)->Result<()>{let full=kind==Kind::Iq3S;let mut scales=[0.0;8];let mut flags=[0u32;8];let mut q3=[0u8;104];y.fill(0);let mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/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]=std::array::from_fn(|i|qw.map_or(xb[i]*xb[i],|q|q[at+i]*(sigma+xb[i]*xb[i]).sqrt()));let wa:[f32;32]=std::array::from_fn(|i|w[i].sqrt());let(xv,mut sign)=signs::<32>(xb,&w,!full);let mut max=xv[0];for &v in &xv[1..]{if v>max{max=v;}}if (full&&max==0.0)||(!full&&max<1e-8){continue;}let mut l=[0i8;32];let mut on=[!full;8];let mut scale=max/15.0;let mut best=0.0;let tries=if full{9}else{15};for is in -tries..=tries{let inv=(15.0+is as f32*0.2)/max;let mut aux=[0i8;32];let mut ao=[true;8];quant_candidates(g,inv,&xv,&wa,1.0/inv,&mut aux,8,&mut ao);let(sx,s2)=totals(&xv,&w,&aux);if s2>0.0&&sx*sx>best*s2{scale=sx/s2;best=scale*sx;l=aux;on=ao;}} - if on.iter().any(|v|!*v)&&scale>0.0{let inv=1.0/scale;for k in 0..8{if !full&&on[k]{continue;}let at=k*4;for j in 0..4{l[at+j]=nearest(0.5*(inv*xv[at+j]-1.0)).clamp(0,7)as i8;}g.resolve(&mut l[at..at+4],&xv[at..at+4],&wa[at..at+4],scale);}let(sx,s2)=totals(&xv,&w,&l);if s2>0.0{scale=sx/s2;}}if scale<0.0{scale=-scale;for s in &mut sign{*s=if full{!*s}else{!*s&127};}}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)<maxs{maxs=scale;}} - if maxs==0.0{return Ok(());}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.into_iter().enumerate(){y[66+i*4..70+i*4].copy_from_slice(&v.to_le_bytes());}}Ok(())} -fn iq2_s(g:&Grid,x:&[f32],y:&mut[u8],qw:Option<&[f32]>)->Result<()>{let mut scales=[0.0;16];y.fill(0);let mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/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]=std::array::from_fn(|i|qw.map_or(0.25*sigma+xb[i]*xb[i],|q|q[at+i]*(sigma+xb[i]*xb[i]).sqrt()));let wa:[f32;16]=std::array::from_fn(|i|w[i].sqrt());let(xv,mut sign)=signs::<16>(xb,&w,false);let mut max=xv[0];for &v in &xv[1..]{if v>max{max=v;}}if max<1e-8{continue;}let mut l=[0i8;16];let mut on=[true;2];let mut scale=max/5.0;let mut best=0.0;for is in -9..=9{let inv=(5.0+is as f32*0.1)/max;let mut aux=[0i8;16];let mut ao=[true;2];quant_candidates(g,inv,&xv,&wa,1.0/inv,&mut aux,3,&mut ao);let(sx,s2)=totals(&xv,&w,&aux);if s2>0.0&&sx*sx>best*s2{scale=sx/s2;best=scale*sx;l=aux;on=ao;}} - if on.iter().any(|v|!*v)&&scale>0.0{let inv=1.0/scale;for k in 0..2{if on[k]{continue;}let at=k*8;for j in 0..8{l[at+j]=nearest(0.5*(inv*xv[at+j]-1.0)).clamp(0,2)as i8;}g.resolve(&mut l[at..at+8],&xv[at..at+8],&wa[at..at+8],scale);}let(sx,s2)=totals(&xv,&w,&l);if s2>0.0{scale=sx/s2;}}if scale<0.0{scale=-scale;for s in &mut sign[..2]{*s=!*s;}}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{return Ok(());}let d=maxs/31.0;put_h(y,d*0.9875);let inv=1.0/d;for ib in 0..16{let s=nearest(0.5*(inv*scales[ib]-1.0)).clamp(0,15)as u8;y[74+ib/2]|=s<<(4*(ib%2));}Ok(())} -const XP:[f32;3]=[-0.875,0.125,1.125];const XM:[f32;3]=[-1.125,-0.125,0.875]; -#[repr(C)]#[derive(Clone,Copy,Default)]struct Pair{value:f32,index:i32} -unsafe extern "C"{fn qsort(base:*mut std::ffi::c_void,n:usize,size:usize,compare:unsafe extern "C" fn(*const std::ffi::c_void,*const std::ffi::c_void)->i32);} -unsafe extern "C" fn compare_pair(a:*const std::ffi::c_void,b:*const std::ffi::c_void)->i32{unsafe{let a=(*a.cast::()).value;let b=(*b.cast::()).value;if ab{1}else{0}}} -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. */unsafe{qsort(p.as_mut_ptr().cast(),N,std::mem::size_of::(),compare_pair);}p} -impl Grid{ - fn resolve_one(&self,l:&mut[i8],x:&[f32],w:&[f32],scale:f32,values:&[f32;3])->Result<(usize,bool)>{let mapped=self.map[self.key(l)];if mapped>=0{return Ok((mapped as usize,true));}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..8{let q=values[((p[i]-1)/2)as usize];let d=scale*q-x[i];err+=w[i]*d*d;}if err>; 6]> = Mutex::new([None, None, None, None, None, None]); +const XP: [f32; 3] = [-0.875, 0.125, 1.125]; +const XM: [f32; 3] = [-1.125, -0.125, 0.875]; +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct Pair { + value: f32, + index: i32, } -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 mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/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]=std::array::from_fn(|i|qw[at+i]*(sigma+xb[i]*xb[i]).sqrt());let mut max=xb[0].abs();for &v in &xb[1..]{if v.abs()>max{max=v.abs();}}if max<1e-12{continue;}let p=pairs::<32>(xb);let mut sx=[0.0;33];let mut sw=sx;for j in 0..32{let i=p[j].index as usize;sx[j+1]=sx[j]+w[i]*xb[i];sw[j+1]=sw[j]+w[i];}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=(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];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{continue;}let mut l=[0i8;32];for j in 0..32{l[p[j].index as usize]=if j<(b1 as usize){0}else if j<(b2 as usize){1}else{2};}if scale<0.0{for q in &mut l{*q=2-*q;}scale=-scale;shift=-shift;}let values=if shift==1{&XP}else{&XM};let mut indices=[0usize;4];let mut all=true;for k in 0..4{let at=k*8;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;}if !all{let(mut qx,mut q2)=(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;}}if qx>0.0&&q2>0.0{scale=qx/q2;}}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);}heads[ib]=high;scales[ib]=scale;shifts[ib]=shift;if scale>maxs{maxs=scale;}} - if maxs==0.0{return Ok(());}let d=maxs/15.0;put_h(y,d*1.125);let inv=1.0/d;for ib in 0..8{let mut l=nearest(0.5*(inv*scales[ib]-1.0)).clamp(0,7)as u16;if shifts[ib]==-1{l|=8;}heads[ib]|=l<<12;y[34+ib*2..36+ib*2].copy_from_slice(&heads[ib].to_le_bytes());}Ok(())} -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 mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/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]=std::array::from_fn(|i|qw.map_or(xb[i]*xb[i],|q|q[at+i]*(sigma+xb[i]*xb[i]).sqrt()));let mut max=xb[0].abs();for &v in &xb[1..]{if v.abs()>max{max=v.abs();}}if max<1e-7{continue;}let p=pairs::<16>(xb);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 mut qx=[0.0;4];let mut q2=qx;for j in 0..16{let i=p[j].index as usize;let value=if j=8&&k%2==0){&XP}else{&XM};qx[k]+=w[i]*vals[value]*xb[i];q2[k]+=w[i]*vals[value]*vals[value];}}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{continue;}let mut l=[0i8;16];for j in 0..16{l[p[j].index as usize]=if j<(b1 as usize){0}else if j<(b2 as usize){1}else{2};}if scale<0.0{for q in &mut l{*q=2-*q;}scale=-scale;which=3-which;}let mut indices=[0usize;2];let mut all=true;for k in 0..2{let values=if (k==0&&which<2)||(k==1&&which%2==0){&XP}else{&XM};let at=k*8;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;}if !all{let(mut qx,mut q2)=(0.0,0.0);for k in 0..2{let values=if(k==0&&which<2)||(k==1&&which%2==0){&XP}else{&XM};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;}}if qx>0.0&&q2>0.0{scale=qx/q2;}}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);scales[ib]=scale;shifts[ib]=which as usize;if scale>maxs{maxs=scale;}} - if maxs==0.0{return Ok(());}let mut d=maxs/15.0;let inv=1.0/d;let mut sc=[0u16;4];let(mut qx,mut q2)=(0.0,0.0);let masks=[0u8,128,8,136];for ib in 0..16{let l=nearest(0.5*(inv*scales[ib]-1.0)).clamp(0,7);sc[ib/4]|=(l as u16)<<(3*(ib%4));y[32+ib]|=masks[shifts[ib]];let at=ib*16;let xb=&x[at..at+16];let w:[f32;16]=std::array::from_fn(|i|qw.map_or(xb[i]*xb[i],|q|q[at+i]*(sigma+xb[i]*xb[i]).sqrt()));for k in 0..2{let values=if(k==0&&shifts[ib]<2)||(k==1&&shifts[ib]%2==0){&XP}else{&XM};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;qx+=w[k*8+j]*q*xb[k*8+j];q2+=w[k*8+j]*q*q;}}}if q2>0.0{d=qx/q2;}let packed=half_rn(d*1.1125);sc[0]|=(packed&15)<<12;sc[1]|=(packed&0xf0)<<8;sc[2]|=(packed&0xf00)<<4;sc[3]|=packed&0xf000;for(i,v)in sc.into_iter().enumerate(){y[48+i*2..50+i*2].copy_from_slice(&v.to_le_bytes());}Ok(())} -pub(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]);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)?,_=>return Err(Error::Unsupported)}}Ok(())} +unsafe extern "C" { + fn qsort( + base: *mut std::ffi::c_void, + n: usize, + size: usize, + compare: unsafe extern "C" fn(*const std::ffi::c_void, *const std::ffi::c_void) -> i32, + ); +} + +mod alloc_fn; +#[allow(unused_imports)] +use alloc_fn::alloc; +#[allow(unused_imports)] +pub(super) use alloc_fn::free; +#[allow(unused_imports)] +use alloc_fn::grid; +#[allow(unused_imports)] +use alloc_fn::grid_kind; +#[allow(unused_imports)] +pub(super) use alloc_fn::init; +#[allow(unused_imports)] +use alloc_fn::put_h; +#[allow(unused_imports)] +use alloc_fn::quant_candidates; +#[allow(unused_imports)] +use alloc_fn::signs; +#[allow(unused_imports)] +use alloc_fn::totals; +mod iq2_xxs_fn; +#[allow(unused_imports)] +use iq2_xxs_fn::iq2_xs; +#[allow(unused_imports)] +use iq2_xxs_fn::iq2_xxs; +mod iq3_fn; +#[allow(unused_imports)] +use iq3_fn::compare_pair; +#[allow(unused_imports)] +use iq3_fn::iq2_s; +#[allow(unused_imports)] +use iq3_fn::iq3; +#[allow(unused_imports)] +use iq3_fn::pairs; +mod impl_grid; +#[allow(unused_imports)] +use impl_grid::iq1_s; +mod iq1_m_fn; +#[allow(unused_imports)] +use iq1_m_fn::iq1_m; +#[allow(unused_imports)] +pub(super) use iq1_m_fn::row; 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 new file mode 100644 index 00000000..4741b5d3 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_iq/alloc_fn.rs @@ -0,0 +1,224 @@ +//! Moved out of the parent module by STRA-338: fn alloc, impl Grid, fn grid_kind, fn grid, fn init, fn free .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn alloc(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::Allocation)?; + v.resize_with(n, T::default); + Ok(v) +} +impl Grid { + pub(super) fn new(codes: &[u16], dim: usize, bits: usize, want: usize) -> Result { + let size = if dim == 8 { 43692 } else { 4096 }; + let mut points = alloc::<[i8; 8]>(codes.len())?; + let mut map = alloc::(size)?; + map.fill(-1); + for (i, &code) in codes.iter().enumerate() { + for j in 0..dim { + points[i][j] = (2 * ((code as usize >> (bits * j)) & ((1 << bits) - 1)) + 1) as i8; + } + map[code as usize] = i as i32; + } + let mut dist = alloc::<(i32, u16)>(codes.len())?; + let mut counts = alloc::(size)?; + let mut total = 0usize; + for i in 0..size { + if map[i] >= 0 { + continue; + } + Self::distances(i, dim, bits, &points, &mut dist); + dist.sort_unstable(); + let n = Self::count(&dist, want); + counts[i] = n; + total = total.checked_add(n + 1).ok_or(Error::Allocation)?; + } + 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; + } + Ok(Self { points, map, neighbors, dim, bits }) + } + 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; + for k in 0..dim { + let pos = (2 * ((i >> (bits * k)) & ((1 << bits) - 1)) + 1) as i32; + let dx = pg[k] as i32 - pos; + d += dx * dx; + } + dist[j] = (d, j as u16); + } + } + pub(super) fn count(d: &[(i32, u16)], want: usize) -> usize { + let (mut n, mut distance, mut have) = (0, d[0].0, 1); + for &(x, _) in d { + if x > distance { + if have == want { + break; + } + distance = x; + have += 1; + } + n += 1; + } + n + } + pub(super) fn key(&self, l: &[i8]) -> usize { + let mut u = 0; + for i in 0..self.dim { + u |= (l[i] as usize) << (self.bits * i); + } + u + } + pub(super) fn index(&self, l: &[i8]) -> Result { + let i = self.map[self.key(l)]; + if i < 0 { Err(Error::NativeFailure) } else { Ok(i as usize) } + } + 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; + } + } + assert_ne!(index, usize::MAX); + index + }; + for i in 0..self.dim { + l[i] = (self.points[index][i] - 1) / 2; + } + mapped >= 0 + } +} +pub(super) fn grid_kind(k: Kind) -> Option { + match k { + Kind::Iq2Xxs => Some(0), + Kind::Iq2Xs => Some(1), + Kind::Iq1S | Kind::Iq1M => Some(2), + Kind::Iq2S => Some(3), + Kind::Iq3Xxs => Some(4), + Kind::Iq3S => Some(5), + _ => None, + } +} +pub(super) fn grid(k: Kind) -> Result> { + let i = grid_kind(k).ok_or(Error::Unsupported)?; + let mut cache = CACHE.lock().map_err(|_| Error::NativeFailure)?; + if let Some(g) = &cache[i] { + return Ok(Arc::clone(g)); + } + let (codes, dim, bits, want): (&[u16], usize, usize, usize) = match i { + 0 => (&KGRID_2BIT_256, 8, 2, 2), + 1 => (&KGRID_2BIT_512, 8, 2, 2), + 2 => (&KGRID_1BIT_2048, 8, 2, 3), + 3 => (&KGRID_2BIT_1024, 8, 2, 1), + 4 => (&KGRID_256, 4, 3, 2), + _ => (&KGRID_512, 4, 3, 3), + }; + let g = Arc::new(Grid::new(codes, dim, bits, want)?); + cache[i] = Some(Arc::clone(&g)); + Ok(g) +} +pub(in super::super) fn init(k: Kind) -> Result<()> { + if grid_kind(k).is_some() { + grid(k)?; + } + Ok(()) +} +pub(in super::super) fn free(k: Kind) -> Result<()> { + if let Some(i) = grid_kind(k) { + CACHE.lock().map_err(|_| Error::NativeFailure)?[i] = None; + } + Ok(()) +} +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; + } + } + if parity && flips % 2 == 1 { + let mut least = 0; + let mut error = w[k * 8] * xb[k * 8] * xb[k * 8]; + for j in 1..8 { + let at = k * 8 + j; + let e = w[at] * xb[at] * xb[at]; + if e < error { + least = j; + error = e; + } + } + 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() { + let q = (2 * l[i] + 1) as f32; + sx += w[i] * x[i] * q; + s2 += w[i] * q * q; + } + (sx, s2) +} +pub(super) fn quant_candidates( + g: &Grid, + inv: f32, + x: &[f32], + w: &[f32], + scale: f32, + l: &mut [i8], + max: i32, + on: &mut [bool], +) { + for k in 0..x.len() / g.dim { + let at = k * g.dim; + for j in 0..g.dim { + l[at + j] = nearest(0.5 * (inv * x[at + j] - 1.0)).clamp(0, max - 1) as i8; + } + on[k] = g.resolve(&mut l[at..at + g.dim], &x[at..at + g.dim], &w[at..at + g.dim], scale); + } +} 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 new file mode 100644 index 00000000..e9cbfcb6 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_iq/impl_grid.rs @@ -0,0 +1,170 @@ +//! Moved out of the parent module by STRA-338: impl Grid, fn iq1_s. + +#[allow(unused_imports)] +use super::*; + +impl Grid { + pub(super) fn resolve_one( + &self, + l: &mut [i8], + x: &[f32], + w: &[f32], + scale: f32, + values: &[f32; 3], + ) -> Result<(usize, bool)> { + let mapped = self.map[self.key(l)]; + if mapped >= 0 { + return Ok((mapped as usize, true)); + } + 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..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; + } + } + // 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. + if index == usize::MAX { + return Err(Error::NonFinite); + } + for i in 0..8 { + l[i] = (self.points[index][i] - 1) / 2; + } + Ok((index, false)) + } +} +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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 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] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt()); + let mut max = xb[0].abs(); + for &v in &xb[1..] { + if v.abs() > max { + max = v.abs(); + } + } + if max < 1e-12 { + continue; + } + let p = pairs::<32>(xb); + let mut sx = [0.0; 33]; + let mut sw = sx; + for j in 0..32 { + let i = p[j].index as usize; + sx[j + 1] = sx[j] + w[i] * xb[i]; + sw[j + 1] = sw[j] + w[i]; + } + 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 = + (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]; + 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 { + continue; + } + let mut l = [0i8; 32]; + for j in 0..32 { + l[p[j].index as usize] = if j < (b1 as usize) { + 0 + } else if j < (b2 as usize) { + 1 + } else { + 2 + }; + } + if scale < 0.0 { + for q in &mut l { + *q = 2 - *q; + } + scale = -scale; + shift = -shift; + } + let values = if shift == 1 { &XP } else { &XM }; + let mut indices = [0usize; 4]; + let mut all = true; + for k in 0..4 { + let at = k * 8; + 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; + } + if !all { + let (mut qx, mut q2) = (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; + } + } + if qx > 0.0 && q2 > 0.0 { + scale = qx / q2; + } + } + 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); + } + heads[ib] = high; + scales[ib] = scale; + shifts[ib] = shift; + if scale > maxs { + maxs = scale; + } + } + if maxs == 0.0 { + return Ok(()); + } + let d = maxs / 15.0; + put_h(y, d * 1.125); + let inv = 1.0 / d; + for ib in 0..8 { + let mut l = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 7) as u16; + if shifts[ib] == -1 { + l |= 8; + } + heads[ib] |= l << 12; + y[34 + ib * 2..36 + ib * 2].copy_from_slice(&heads[ib].to_le_bytes()); + } + 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 new file mode 100644 index 00000000..eb779db0 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq1_m_fn.rs @@ -0,0 +1,172 @@ +//! Moved out of the parent module by STRA-338: fn iq1_m, fn row. + +#[allow(unused_imports)] +use super::*; + +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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 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] = + std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt())); + let mut max = xb[0].abs(); + for &v in &xb[1..] { + if v.abs() > max { + max = v.abs(); + } + } + if max < 1e-7 { + continue; + } + let p = pairs::<16>(xb); + 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 mut qx = [0.0; 4]; + let mut q2 = qx; + for j in 0..16 { + let i = p[j].index as usize; + let value = if j < i1 { + 0 + } else if j < i2 { + 1 + } else { + 2 + }; + for k in 0..4 { + let vals = if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM }; + qx[k] += w[i] * vals[value] * xb[i]; + q2[k] += w[i] * vals[value] * vals[value]; + } + } + 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 { + continue; + } + let mut l = [0i8; 16]; + for j in 0..16 { + l[p[j].index as usize] = if j < (b1 as usize) { + 0 + } else if j < (b2 as usize) { + 1 + } else { + 2 + }; + } + if scale < 0.0 { + for q in &mut l { + *q = 2 - *q; + } + scale = -scale; + which = 3 - which; + } + let mut indices = [0usize; 2]; + let mut all = true; + for k in 0..2 { + let values = if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM }; + let at = k * 8; + 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; + } + if !all { + let (mut qx, mut q2) = (0.0, 0.0); + for k in 0..2 { + let values = if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM }; + 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; + } + } + if qx > 0.0 && q2 > 0.0 { + scale = qx / q2; + } + } + 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); + scales[ib] = scale; + shifts[ib] = which as usize; + if scale > maxs { + maxs = scale; + } + } + if maxs == 0.0 { + return Ok(()); + } + let mut d = maxs / 15.0; + let inv = 1.0 / d; + let mut sc = [0u16; 4]; + let (mut qx, mut q2) = (0.0, 0.0); + let masks = [0u8, 128, 8, 136]; + for ib in 0..16 { + let l = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 7); + sc[ib / 4] |= (l as u16) << (3 * (ib % 4)); + y[32 + ib] |= masks[shifts[ib]]; + let at = ib * 16; + let xb = &x[at..at + 16]; + let w: [f32; 16] = + std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt())); + for k in 0..2 { + let values = if (k == 0 && shifts[ib] < 2) || (k == 1 && shifts[ib] % 2 == 0) { &XP } else { &XM }; + 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; + qx += w[k * 8 + j] * q * xb[k * 8 + j]; + q2 += w[k * 8 + j] * q * q; + } + } + } + if q2 > 0.0 { + d = qx / q2; + } + let packed = half_rn(d * 1.1125); + sc[0] |= (packed & 15) << 12; + sc[1] |= (packed & 0xf0) << 8; + sc[2] |= (packed & 0xf00) << 4; + sc[3] |= packed & 0xf000; + for (i, v) in sc.into_iter().enumerate() { + y[48 + i * 2..50 + i * 2].copy_from_slice(&v.to_le_bytes()); + } + Ok(()) +} +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]); + 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)?, + _ => return Err(Error::Unsupported), + } + } + Ok(()) +} 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 new file mode 100644 index 00000000..b02590a7 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq2_xxs_fn.rs @@ -0,0 +1,178 @@ +//! Moved out of the parent module by STRA-338: fn iq2_xxs, fn iq2_xs. + +#[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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = sum / 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] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt()); + let wa: [f32; 32] = std::array::from_fn(|i| w[i].sqrt()); + let (xv, mut sign) = signs::<32>(xb, &w, true); + let mut max = xv[0]; + for &v in &xv[1..] { + if v > max { + max = v; + } + } + if max < 1e-15 { + continue; + } + let mut l = [0i8; 32]; + let mut lp = [0u8; 32]; + let mut scale = qp(&xv, 4, &mut lp, &w); + for i in 0..32 { + l[i] = lp[i] as i8; + } + let effective = scale * 3.0; + if effective <= 0.0 { + continue; + } + 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, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]); + let (sx, s2) = totals(&xv, &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, &xv, &wa, scale, &mut l, 3, &mut [false; 4]); + let (sx, s2) = totals(&xv, &w, &l); + if s2 > 0.0 { + scale = sx / s2; + } + } + if scale < 0.0 { + scale = -scale; + for s in &mut sign { + *s = !*s & 127; + } + } + 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; + } + } + if maxs == 0.0 { + return Ok(()); + } + let d = maxs / 31.0; + put_h(y, d); + let inv = 1.0 / d; + for ib in 0..8 { + q2[2 * ib + 1] |= (nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u32) << 28; + } + for (i, v) in q2.into_iter().enumerate() { + y[2 + i * 4..6 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + Ok(()) +} +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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = sum / 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] = std::array::from_fn(|i| qw[at + i] * (sigma + xb[i] * xb[i]).sqrt()); + let wa: [f32; 16] = std::array::from_fn(|i| w[i].sqrt()); + let (xv, mut sign) = signs::<16>(xb, &w, true); + let mut max = xv[0]; + for &v in &xv[1..] { + if v > max { + max = v; + } + } + if max < 1e-15 { + continue; + } + let mut l = [0i8; 16]; + let mut on = [true; 2]; + let mut scale = max / 5.0; + let mut best = 0.0; + for is in -9..=9 { + let inv = (5.0 + is as f32 * 0.1) / max; + let mut aux = [0i8; 16]; + let mut ao = [true; 2]; + quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut ao); + let (sx, s2) = totals(&xv, &w, &aux); + if s2 > 0.0 && sx * sx > best * s2 { + scale = sx / s2; + best = scale * sx; + l = aux; + on = ao; + } + } + if on.iter().any(|v| !*v) && scale > 0.0 { + let inv = 1.0 / scale; + for k in 0..2 { + if on[k] { + continue; + } + let at = k * 8; + for j in 0..8 { + l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 2) as i8; + } + g.resolve(&mut l[at..at + 8], &xv[at..at + 8], &wa[at..at + 8], scale); + } + let (sx, s2) = totals(&xv, &w, &l); + if s2 > 0.0 { + scale = sx / s2; + } + } + if scale < 0.0 { + scale = -scale; + for s in &mut sign[..2] { + *s = !*s & 127; + } + } + 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; + } + } + if maxs == 0.0 { + return Ok(()); + } + let d = maxs / 31.0; + put_h(y, d); + let inv = 1.0 / d; + for ib in 0..16 { + let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8; + y[66 + ib / 2] |= s << (4 * (ib % 2)); + } + for (i, v) in q2.into_iter().enumerate() { + y[2 + i * 2..4 + i * 2].copy_from_slice(&v.to_le_bytes()); + } + 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 new file mode 100644 index 00000000..cd7f49c4 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_iq/iq3_fn.rs @@ -0,0 +1,223 @@ +//! Moved out of the parent module by STRA-338: fn iq3, fn iq2_s, fn compare_pair, fn pairs. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> { + let full = kind == Kind::Iq3S; + let mut scales = [0.0; 8]; + let mut flags = [0u32; 8]; + let mut q3 = [0u8; 104]; + y.fill(0); + let mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 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] = + std::array::from_fn(|i| qw.map_or(xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt())); + let wa: [f32; 32] = std::array::from_fn(|i| w[i].sqrt()); + let (xv, mut sign) = signs::<32>(xb, &w, !full); + let mut max = xv[0]; + for &v in &xv[1..] { + if v > max { + max = v; + } + } + if (full && max == 0.0) || (!full && max < 1e-8) { + continue; + } + let mut l = [0i8; 32]; + let mut on = [!full; 8]; + let mut scale = max / 15.0; + let mut best = 0.0; + let tries = if full { 9 } else { 15 }; + for is in -tries..=tries { + let inv = (15.0 + is as f32 * 0.2) / max; + let mut aux = [0i8; 32]; + let mut ao = [true; 8]; + quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 8, &mut ao); + let (sx, s2) = totals(&xv, &w, &aux); + if s2 > 0.0 && sx * sx > best * s2 { + scale = sx / s2; + best = scale * sx; + l = aux; + on = ao; + } + } + if on.iter().any(|v| !*v) && scale > 0.0 { + let inv = 1.0 / scale; + for k in 0..8 { + if !full && on[k] { + continue; + } + let at = k * 4; + for j in 0..4 { + l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 7) as i8; + } + g.resolve(&mut l[at..at + 4], &xv[at..at + 4], &wa[at..at + 4], scale); + } + let (sx, s2) = totals(&xv, &w, &l); + if s2 > 0.0 { + scale = sx / s2; + } + } + if scale < 0.0 { + scale = -scale; + for s in &mut sign { + *s = if full { !*s } else { !*s & 127 }; + } + } + 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; + } + } + 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); + } + scales[ib] = scale; + if scale > maxs { + maxs = scale; + } + } + if maxs == 0.0 { + return Ok(()); + } + 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.into_iter().enumerate() { + y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes()); + } + } + Ok(()) +} +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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 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] = std::array::from_fn(|i| { + qw.map_or(0.25 * sigma + xb[i] * xb[i], |q| q[at + i] * (sigma + xb[i] * xb[i]).sqrt()) + }); + let wa: [f32; 16] = std::array::from_fn(|i| w[i].sqrt()); + let (xv, mut sign) = signs::<16>(xb, &w, false); + let mut max = xv[0]; + for &v in &xv[1..] { + if v > max { + max = v; + } + } + if max < 1e-8 { + continue; + } + let mut l = [0i8; 16]; + let mut on = [true; 2]; + let mut scale = max / 5.0; + let mut best = 0.0; + for is in -9..=9 { + let inv = (5.0 + is as f32 * 0.1) / max; + let mut aux = [0i8; 16]; + let mut ao = [true; 2]; + quant_candidates(g, inv, &xv, &wa, 1.0 / inv, &mut aux, 3, &mut ao); + let (sx, s2) = totals(&xv, &w, &aux); + if s2 > 0.0 && sx * sx > best * s2 { + scale = sx / s2; + best = scale * sx; + l = aux; + on = ao; + } + } + if on.iter().any(|v| !*v) && scale > 0.0 { + let inv = 1.0 / scale; + for k in 0..2 { + if on[k] { + continue; + } + let at = k * 8; + for j in 0..8 { + l[at + j] = nearest(0.5 * (inv * xv[at + j] - 1.0)).clamp(0, 2) as i8; + } + g.resolve(&mut l[at..at + 8], &xv[at..at + 8], &wa[at..at + 8], scale); + } + let (sx, s2) = totals(&xv, &w, &l); + if s2 > 0.0 { + scale = sx / s2; + } + } + if scale < 0.0 { + scale = -scale; + for s in &mut sign[..2] { + *s = !*s; + } + } + 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 { + return Ok(()); + } + let d = maxs / 31.0; + put_h(y, d * 0.9875); + let inv = 1.0 / d; + for ib in 0..16 { + let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8; + y[74 + ib / 2] |= s << (4 * (ib % 2)); + } + Ok(()) +} +pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *const std::ffi::c_void) -> i32 { + unsafe { + let a = (*a.cast::()).value; + let b = (*b.cast::()).value; + if a < b { + -1 + } else if a > b { + 1 + } else { + 0 + } + } +} +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. */ + unsafe { + qsort(p.as_mut_ptr().cast(), N, std::mem::size_of::(), compare_pair); + } + p +} diff --git a/crates/native-cpu-expert/src/rust_weight_quant.rs b/crates/native-cpu-expert/src/rust_weight_quant.rs index 9e891820..3948e242 100644 --- a/crates/native-cpu-expert/src/rust_weight_quant.rs +++ b/crates/native-cpu-expert/src/rust_weight_quant.rs @@ -1,69 +1,71 @@ //! Scalar model quantization from pinned GGML 3cf03257, ggml-quants.c. //! This is the model-file/benchmark reference path, not activation SIMD packing. -use super::{Error,Result}; +use super::rust_dequant::{half, half_rn}; use super::rust_ggml::Kind; -use super::rust_dequant::{half,half_rn}; -const EPS:f32=1e-15; -pub(super) fn nearest(x:f32)->i32{debug_assert!(x.abs()<=4194303.0);let bits=(x+12582912.0).to_bits();(bits&0x7fffff)as i32-0x400000} -fn put_h(y:&mut[u8],at:usize,x:f32){y[at..at+2].copy_from_slice(&half_rn(x).to_le_bytes());} -fn h(y:&[u8],at:usize)->f32{half(u16::from_le_bytes([y[at],y[at+1]]))} -fn max_signed(x:&[f32])->(f32,f32){let(mut a,mut v)=(0.0,0.0);for &f in x{if f.abs()>a{a=f.abs();v=f;}}(a,v)} -fn weight(x:f32,rmse:i32,qw:Option)->f32{qw.unwrap_or_else(||match rmse{1=>x*x,2=>1.0,3=>x.abs(),_=>x.abs().sqrt()})} -pub(super) fn qx(x:&[f32],nmax:i32,l:&mut[i8],mut rmse:i32,qw:Option<&[f32]>)->f32{ - let(amax,max)=max_signed(x);if amax0.0{0.5*(scale+1.0/inv)}else{1.0/inv};}let mut best=scale*sx; - for is in -9..=9{if is==0{continue;}inv=-(nmax as f32+0.1*is as f32)/max;sx=0.0;s2=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;}if s2>0.0&&sx*sx>best*s2{for i in 0..x.len(){l[i]=(nmax+nearest(inv*x[i]).clamp(-nmax,nmax-1))as i8;}scale=sx/s2;best=scale*sx;}} - scale -} -fn q3(x:&[f32],l:&mut[i8])->f32{let(a,max)=max_signed(x);if a0.0{let mut t2=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*s2>sx*sx*t2{l[i]=q as i8;sx=tx;s2=t2;changed+=1;}}}}if changed==0{break;}}for l in l{*l+=4;}if s2>0.0{sx/s2}else{0.0}} -/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights. -fn qkx(x:&[f32],nmax:i32,w:&[f32],l:&mut[u8],rmin:f32,rdelta:f32,nstep:i32,mad:bool,third:bool)->(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]max{max=x[i];}sw+=w[i];sx+=w[i]*x[i];}if min>0.0{min=0.0;}if (third&&max<=min)||(!third&&max==min){l.fill(0);return(0.0,-min);} - let mut inv=nmax as f32/(max-min);let mut scale=1.0/inv;let mut best=0.0;for i in 0..x.len(){l[i]=nearest(inv*(x[i]-min)).clamp(0,nmax)as u8;let diff=scale*l[i]as f32+min-x[i];best+=w[i]*if mad{diff.abs()}else{diff*diff};} - let mut aux=[0u8;32];for is in 0..=nstep{inv=(rmin+rdelta*is as f32+nmax as f32)/(max-min);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];}let det=sw*sl2-sl*sl;if det>0.0{let mut ds=(sw*sxl-sx*sl)/det;let mut dm=(sl2*sx-sl*sxl)/det;if dm>0.0{dm=0.0;ds=sxl/sl2;}let mut error=0.0;for i in 0..x.len(){let diff=ds*aux[i]as f32+dm-x[i];error+=w[i]*if mad{diff.abs()}else{diff*diff};}if errorf32{let mut max=0.0;for &x in x{if x>max{max=x;}}if max0.0&&t2>0.0{let q=nearest(x[i]*t2/tx).min(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*s2>sx*sx*t2{l[i]=q as u8;sx=tx;s2=t2;changed+=1;}}}}if changed==0{break;}}if s2>0.0{sx/s2}else{0.0}} -fn pack4(l:&[u8],y:&mut[u8]){for j in 0..16{y[j]=l[j]|(l[j+16]<<4);}} -fn small(kind:Kind,x:&[f32],y:&mut[u8],qw:Option<&[f32]>,sigma:f32){ - if matches!(kind,Kind::F32|Kind::F16|Kind::Bf16){match kind{Kind::F32=>y.copy_from_slice(&x[0].to_le_bytes()),Kind::F16=>put_h(y,0,x[0]),_=>{let b=x[0].to_bits();let h=if b&0x7fffffff>0x7f800000{(b>>16)|64}else{b.wrapping_add(0x7fff+((b>>16)&1))>>16};y.copy_from_slice(&(h as u16).to_le_bytes());}}return;} - if kind==Kind::Q1Zero{let mut sum=0.0;for &v in x{sum+=v.abs();}put_h(y,0,sum/128.0);y[2..].fill(0);for j in 0..128{if x[j]>=0.0{y[2+j/8]|=1<<(j%8);}}return;} - if kind==Kind::Q2Zero{let(a,_)=max_signed(x);put_h(y,0,a);let inv=if a>0.0{1.0/a}else{0.0};y[2..].fill(0);for j in 0..64{let q=((x[j]*inv).round()as i32+1).clamp(0,3);y[2+j/4]|=(q as u8)<<(2*(j%4));}return;} - if kind==Kind::Q8Zero{let(a,_)=max_signed(x);let d=a/127.0;let inv=if d!=0.0{1.0/d}else{0.0};put_h(y,0,d);for j in 0..32{y[j+2]=(x[j]*inv).round()as i8 as u8;}return;} - let is_min=matches!(kind,Kind::Q4One|Kind::Q5One);let five=matches!(kind,Kind::Q5Zero|Kind::Q5One);let nmax=if five{31}else{15};let mut l=[0u8;32];let(d,m)=if let Some(qw)=qw{let w=std::array::from_fn::<_,32,_>(|j|qw[j]*(sigma+x[j]*x[j]).sqrt());if is_min{let(s,m)=qkx(x,nmax,&w,&mut l,-0.9,0.05,36,false,true);(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;}(d,0.0)}}else if is_min{let(mut min,mut max)=(f32::MAX,-f32::MAX);for &v in x{if vmax{max=v;}}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 five{q as u8}else{q.min(15)as u8};}(d,min)}else{let(_,max)=max_signed(x);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(nmax)as u8;}(d,0.0)}; - put_h(y,0,d);let head=if is_min{put_h(y,2,m);4}else{2};if five{let mut hi=0u32;for j in 0..16{y[head+4+j]=(l[j]&15)|((l[j+16]&15)<<4);hi|=((l[j]as u32&16)>>4)<>4)<<(j+16);}y[head..head+4].copy_from_slice(&hi.to_le_bytes());}else{pack4(&l,&mut y[head..]);} -} -const FP4:[i8;16]=[0,1,2,3,4,6,8,12,0,-1,-2,-3,-4,-6,-8,-12]; -fn e8_half(e:u8)->f32{f32::from_bits(if e<2{0x00200000u32<f32{if e==0||e==127{return 0.0;}let exp=(e>>3)&15;let m=e&7;let raw=if exp==0{m as f32*f32::from_bits(118<<23)}else{(1.0+m as f32/8.0)*f32::from_bits(((exp as i32-7+127)as u32)<<23)};raw*0.5} -fn pack_ue4(mut x:f32)->u8{if !(x>0.0){return 0;}if x>448.0{x=448.0;}let bits=x.to_bits();let exp=((bits>>23)&255)as i32-127;let mut e=exp+7;if e<=0{let m=(x*512.0+0.5)as i32;return if m<1{0}else{m.min(7)as u8};}if e>=15{return 126;}let mut m=((bits>>20)&7)+((bits>>19)&1);if m>7{m=0;e+=1;if e>=15{return 126;}}((e as u32)<<3|m)as u8} -fn best_fp4(x:f32,d:f32)->u8{let mut best=0;let mut error=(FP4[0]as f32*d-x).abs();for i in 1..16{let e=(FP4[i]as f32*d-x).abs();if e0.0{(a.log2().floor()-2.0+127.0)as i32 as u8}else{0};y[0]=e;let d=e8_half(e);for j in 0..16{y[j+1]=best_fp4(x[j],d)|(best_fp4(x[j+16],d)<<4);}}else{for s in 0..4{let xb=&x[s*16..s*16+16];let(a,_)=max_signed(xb);let e=pack_ue4(a/6.0);y[s]=e;let d=ue4(e);for j in 0..8{y[4+s*8+j]=best_fp4(xb[j],d)|(best_fp4(xb[j+8],d)<<4);}}}} -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);for p in 0..2{for j in 0..32{let mut q=0;for k in 0..4{q|=((((x[p*128+k*32+j]*inv).round()as i32+1)&3)as u8)<<(2*k);}y[p*32+j]=q;}}}else{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;}}}} -fn pack_k2(l:&[u8],y:&mut[u8]){for p in 0..2{for j in 0..32{y[p*32+j]=l[p*128+j]|(l[p*128+j+32]<<2)|(l[p*128+j+64]<<4)|(l[p*128+j+96]<<6);}}} -fn q2k(x:&[f32],y:&mut[u8],qw:Option<&[f32]>){let mut l=[0u8;256];let mut scales=[0.0;16];let mut mins=scales;let mut sw=scales;let mut maxs=0.0;let mut maxm=0.0;let mut sum=0.0;for &v in x{sum+=v*v;}let sigma=sum/256.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()});for &v in &w{sw[k]+=v;}let(d,m)=if qw.is_some(){qkx(xb,3,&w,&mut l[k*16..k*16+16],-0.9,0.05,36,false,true)}else{qkx(xb,3,&w,&mut l[k*16..k*16+16],-0.5,0.1,15,true,false)};scales[k]=d;mins[k]=m;if d>maxs{maxs=d;}if m>maxm{maxm=m;}} - let mut ls=[0u8;16];let mut lm=ls;let(d,m)=if qw.is_some(){(qp(&scales,15,&mut ls,&sw),qp(&mins,15,&mut lm,&sw))}else{let si=if maxs>0.0{15.0/maxs}else{0.0};let mi=if maxm>0.0{15.0/maxm}else{0.0};for k in 0..16{ls[k]=nearest(si*scales[k])as u8;lm[k]=nearest(mi*mins[k])as u8;}(maxs/15.0,maxm/15.0)};put_h(y,80,d);put_h(y,82,m);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;}let dm=m*(y[k]>>4)as f32;for j in 0..16{l[k*16+j]=nearest((x[k*16+j]+dm)/ds).clamp(0,3)as u8;}}pack_k2(&l,&mut y[16..80]);} -fn pack_scale3(l:&[i8;16],y:&mut[u8]){y.fill(0);for j in 0..16{let q=l[j]as u8;if j<8{y[j]=q&15;}else{y[j-8]|=(q&15)<<4;}y[j%4+8]|=(q>>4)<<(2*(j/4));}} -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} -fn q3k(x:&[f32],y:&mut[u8],qw:Option<&[f32]>){let mut l=[0i8;256];let mut scales=[0.0;16];let mut sw=scales;let mut maxs=0.0;let mut amax=0.0;let mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/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];}} - let mut ls=[0i8;16];let d=if qw.is_some(){qx(&scales,32,&mut ls,1,Some(&sw))}else if maxs!=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}else{0.0};pack_scale3(&ls,&mut y[96..108]);put_h(y,108,d);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{for j in 0..16{l[k*16+j]=(nearest(x[k*16+j]/ds).clamp(-4,3)+4)as i8;}}}y[..32].fill(0);let mut low=[0u8;256];for j in 0..256{if l[j]>3{y[j%32]|=1<<(j/32);l[j]-=4;}low[j]=l[j]as u8;}pack_k2(&low,&mut y[32..96]);} -fn pack_scale4(ls:&[u8;8],lm:&[u8;8],y:&mut[u8]){for j in 0..8{let s=ls[j];let m=lm[j];if j<4{y[j]=s;y[j+4]=m;}else{y[j+4]=(s&15)|((m&15)<<4);y[j-4]|=(s>>4)<<6;y[j]|=(m>>4)<<6;}}} -fn unpack_scale4(y:&[u8],j:usize)->(u8,u8){if j<4{(y[j]&63,y[j+4]&63)}else{((y[j+4]&15)|((y[j-4]>>6)<<4),(y[j+4]>>4)|((y[j]>>6)<<4))}} -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 mut scales=[0.0;8];let mut mins=scales;let mut sw=scales;let(mut maxs,mut maxm)=(0.0,0.0);let mut sum=0.0;for &v in x{sum+=v*v;}let sigma=2.0*sum/256.0;let av=sigma.sqrt();for k in 0..8{let xb=&x[k*32..k*32+32];let w:[f32;32]=if let Some(q)=qw{std::array::from_fn(|j|q[k*32+j]*(sigma+xb[j]*xb[j]).sqrt())}else{let mut s=0.0;for &v in xb{s+=v*v;}let avg=(s/32.0).sqrt();std::array::from_fn(|j|avg+xb[j].abs())};for &v in &w{sw[k]+=v;}let(d,m)=if qw.is_some(){qkx(xb,nmax,&w,&mut l[k*32..k*32+32],-0.9,0.05,36,false,true)}else{qkx(xb,nmax,&w,&mut l[k*32..k*32+32],if five{-0.5}else{-1.0},0.1,if five{15}else{20},false,false)};scales[k]=d;mins[k]=m;if d>maxs{maxs=d;}if m>maxm{maxm=m;}} - // av belongs to the weighted implementation's no-imatrix branch; public - // quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML. - let _=av; - let mut ls=[0u8;8];let mut lm=ls;let(d,m)=if qw.is_some(){(qp(&scales,63,&mut ls,&sw),qp(&mins,63,&mut lm,&sw))}else{let si=if maxs>0.0{63.0/maxs}else{0.0};let mi=if maxm>0.0{63.0/maxm}else{0.0};for k in 0..8{ls[k]=(nearest(si*scales[k])as u8).min(63);lm[k]=(nearest(mi*mins[k])as u8).min(63);}(maxs/63.0,maxm/63.0)};pack_scale4(&ls,&lm,&mut y[4..16]);put_h(y,0,d);put_h(y,2,m);let d=h(y,0);let m=h(y,2);for k in 0..8{let(s,min)=unpack_scale4(&y[4..16],k);let ds=d*s as f32;if ds==0.0{continue;}let dm=m*min as f32;for j in 0..32{l[k*32+j]=nearest((x[k*32+j]+dm)/ds).clamp(0,nmax)as u8;}}let head=if five{y[16..48].fill(0);48}else{16};for k in 0..4{for j in 0..32{let a=l[k*64+j];let b=l[k*64+j+32];y[head+k*32+j]=(a&15)|((b&15)<<4);if five{if a>15{y[16+j]|=1<<(2*k);}if b>15{y[16+j]|=2<<(2*k);}}}} -} -fn q6k(x:&[f32],y:&mut[u8],qw:Option<&[f32]>){let mut l=[0i8;256];let mut scales=[0.0;16];let(mut maxs,mut amax)=(0.0,0.0);for k in 0..16{let d=qx(&x[k*16..k*16+16],32,&mut l[k*16..k*16+16],1,qw.map(|q|&q[k*16..k*16+16]));scales[k]=d;if d.abs()>amax{amax=d.abs();maxs=d;}}if amax>4)|((b>>4)<<2)|((c>>4)<<4)|((d>>4)<<6);}}} -fn best_iq4(x:f32)->u8{let v=&super::rust_codebooks::KVALUES_IQ4NL;if x<=v[0]as f32{return 0;}if x>=v[15]as f32{return 15;}let(mut lo,mut hi)=(0,15);while hi-lo>1{let m=(lo+hi)/2;if x,ntry:i32){let n=x.len();let nb=n/32;let mut sigma=0.0;for &v in x{sigma+=v*v;}sigma*=2.0/n as f32;let mut l=[0u8;256];let mut scales=[0.0;8];let(mut maxs,mut amax)=(0.0,0.0);y.fill(0);put_h(y,0,0.0);let values=&super::rust_codebooks::KVALUES_IQ4NL;for k in 0..nb{let xb=&x[k*32..k*32+32];let w:[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]});let(a,max)=max_signed(xb);if a0{-max/values[0]as f32}else{max/values[0]as f32};let mut inv=1.0/d;let(mut sx,mut s2)=(0.0,0.0);for j in 0..32{let q=best_iq4(inv*xb[j]);l[k*32+j]=q;let q=values[q as usize]as f32;sx+=w[j]*q*xb[j];s2+=w[j]*q*q;}d=if s2>0.0{sx/s2}else{0.0};let mut best=d*sx;for itry in -ntry..=ntry{inv=(itry as f32+values[0]as f32)/max;sx=0.0;s2=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;}if s2>0.0&&sx*sx>best*s2{d=sx/s2;best=d*sx;}}scales[k]=d;if d.abs()>amax{amax=d.abs();maxs=d;}} - let head=if kind==Kind::Iq4Xs{let d=-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 in 0..nb{let s=nearest(inv*scales[k]).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);}y[2..4].copy_from_slice(&high.to_le_bytes());8}else{put_h(y,0,scales[0]);if ntry>0{let inv=if scales[0]!=0.0{1.0/scales[0]}else{0.0};for j in 0..n{l[j]=best_iq4(inv*x[j]);}}2};for k in 0..nb{pack4(&l[k*32..k*32+32],&mut y[head+k*16..head+(k+1)*16]);} -} -/// 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(super) fn row_without_iq(kind:Kind,x:&[f32],y:&mut[u8],qw:Option<&[f32]>,reference_iq4:bool)->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 mut sum=0.0;for &v in x{sum+=v*v;}let sigma=sum/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]);match kind{ - Kind::F32|Kind::F16|Kind::Bf16|Kind::Q1Zero|Kind::Q2Zero|Kind::Q4Zero|Kind::Q4One|Kind::Q5Zero|Kind::Q5One|Kind::Q8Zero=>small(kind,x,y,w,sigma),Kind::MxFp4|Kind::NvFp4=>fp4(kind,x,y),Kind::Tq1|Kind::Tq2=>ternary(kind,x,y),Kind::Q2K=>q2k(x,y,w),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,if reference_iq4&&kind==Kind::Iq4Nl{-1}else{7}),_=>return Ok(false)}}Ok(true)} +use super::{Error, Result}; +const EPS: f32 = 1e-15; +const FP4: [i8; 16] = [0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12]; + +mod nearest_fn; +#[allow(unused_imports)] +use nearest_fn::h; +#[allow(unused_imports)] +use nearest_fn::max_signed; +#[allow(unused_imports)] +pub(super) use nearest_fn::nearest; +#[allow(unused_imports)] +use nearest_fn::put_h; +#[allow(unused_imports)] +use nearest_fn::q3; +#[allow(unused_imports)] +use nearest_fn::qkx; +#[allow(unused_imports)] +pub(super) use nearest_fn::qx; +#[allow(unused_imports)] +use nearest_fn::weight; +mod qp_fn; +#[allow(unused_imports)] +use qp_fn::e8_half; +#[allow(unused_imports)] +use qp_fn::pack_ue4; +#[allow(unused_imports)] +use qp_fn::pack4; +#[allow(unused_imports)] +pub(super) use qp_fn::qp; +#[allow(unused_imports)] +use qp_fn::small; +#[allow(unused_imports)] +use qp_fn::ue4; +mod best_fp4_fn; +#[allow(unused_imports)] +use best_fp4_fn::best_fp4; +#[allow(unused_imports)] +use best_fp4_fn::fp4; +#[allow(unused_imports)] +use best_fp4_fn::pack_k2; +#[allow(unused_imports)] +use best_fp4_fn::pack_scale3; +#[allow(unused_imports)] +use best_fp4_fn::pack_scale4; +#[allow(unused_imports)] +use best_fp4_fn::q2k; +#[allow(unused_imports)] +use best_fp4_fn::q3k; +#[allow(unused_imports)] +use best_fp4_fn::ternary; +#[allow(unused_imports)] +use best_fp4_fn::unpack_scale3; +#[allow(unused_imports)] +use best_fp4_fn::unpack_scale4; +mod q45k_fn; +#[allow(unused_imports)] +use q45k_fn::best_iq4; +#[allow(unused_imports)] +use q45k_fn::q6k; +#[allow(unused_imports)] +use q45k_fn::q45k; +mod iq4_fn; +#[allow(unused_imports)] +use iq4_fn::iq4; +#[allow(unused_imports)] +pub(super) use iq4_fn::row_without_iq; 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 new file mode 100644 index 00000000..5ee0c31b --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_quant/best_fp4_fn.rs @@ -0,0 +1,239 @@ +//! Moved out of the parent module by STRA-338: fn best_fp4, fn fp4, fn ternary, fn pack_k2, fn q2k, fn pack_scale3 .... + +#[allow(unused_imports)] +use super::*; + +pub(super) fn best_fp4(x: f32, d: f32) -> u8 { + let mut best = 0; + let mut error = (FP4[0] as f32 * d - x).abs(); + for i in 1..16 { + let e = (FP4[i] as f32 * d - x).abs(); + if e < error { + best = i; + error = e; + } + } + best as u8 +} +pub(super) fn fp4(kind: Kind, x: &[f32], y: &mut [u8]) { + if kind == Kind::MxFp4 { + let (a, _) = max_signed(x); + let e = if a > 0.0 { (a.log2().floor() - 2.0 + 127.0) as i32 as u8 } else { 0 }; + y[0] = e; + let d = e8_half(e); + for j in 0..16 { + y[j + 1] = best_fp4(x[j], d) | (best_fp4(x[j + 16], d) << 4); + } + } else { + for s in 0..4 { + let xb = &x[s * 16..s * 16 + 16]; + let (a, _) = max_signed(xb); + let e = pack_ue4(a / 6.0); + y[s] = e; + let d = ue4(e); + for j in 0..8 { + y[4 + s * 8 + j] = best_fp4(xb[j], d) | (best_fp4(xb[j + 8], d) << 4); + } + } + } +} +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); + for p in 0..2 { + for j in 0..32 { + let mut q = 0; + for k in 0..4 { + q |= ((((x[p * 128 + k * 32 + j] * inv).round() as i32 + 1) & 3) as u8) << (2 * k); + } + y[p * 32 + j] = q; + } + } + } else { + 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; + } + } + } +} +pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) { + for p in 0..2 { + for j in 0..32 { + y[p * 32 + j] = + l[p * 128 + j] | (l[p * 128 + j + 32] << 2) | (l[p * 128 + j + 64] << 4) | (l[p * 128 + j + 96] << 6); + } + } +} +pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) { + let mut l = [0u8; 256]; + let mut scales = [0.0; 16]; + let mut mins = scales; + let mut sw = scales; + let mut maxs = 0.0; + let mut maxm = 0.0; + let mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = sum / 256.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() } + }); + for &v in &w { + sw[k] += v; + } + let (d, m) = if qw.is_some() { + qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], -0.9, 0.05, 36, false, true) + } else { + qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], -0.5, 0.1, 15, true, false) + }; + scales[k] = d; + mins[k] = m; + if d > maxs { + maxs = d; + } + if m > maxm { + maxm = m; + } + } + let mut ls = [0u8; 16]; + let mut lm = ls; + let (d, m) = if qw.is_some() { + (qp(&scales, 15, &mut ls, &sw), qp(&mins, 15, &mut lm, &sw)) + } else { + let si = if maxs > 0.0 { 15.0 / maxs } else { 0.0 }; + let mi = if maxm > 0.0 { 15.0 / maxm } else { 0.0 }; + for k in 0..16 { + ls[k] = nearest(si * scales[k]) as u8; + lm[k] = nearest(mi * mins[k]) as u8; + } + (maxs / 15.0, maxm / 15.0) + }; + put_h(y, 80, d); + put_h(y, 82, m); + 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; + } + let dm = m * (y[k] >> 4) as f32; + for j in 0..16 { + l[k * 16 + j] = nearest((x[k * 16 + j] + dm) / ds).clamp(0, 3) as u8; + } + } + pack_k2(&l, &mut y[16..80]); +} +pub(super) fn pack_scale3(l: &[i8; 16], y: &mut [u8]) { + y.fill(0); + for j in 0..16 { + let q = l[j] as u8; + if j < 8 { + y[j] = q & 15; + } else { + y[j - 8] |= (q & 15) << 4; + } + y[j % 4 + 8] |= (q >> 4) << (2 * (j / 4)); + } +} +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 mut scales = [0.0; 16]; + let mut sw = scales; + let mut maxs = 0.0; + let mut amax = 0.0; + let mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 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]; + } + } + let mut ls = [0i8; 16]; + let d = if qw.is_some() { + qx(&scales, 32, &mut ls, 1, Some(&sw)) + } else if maxs != 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 + } else { + 0.0 + }; + pack_scale3(&ls, &mut y[96..108]); + put_h(y, 108, d); + 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 { + for j in 0..16 { + l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8; + } + } + } + y[..32].fill(0); + let mut low = [0u8; 256]; + for j in 0..256 { + if l[j] > 3 { + y[j % 32] |= 1 << (j / 32); + l[j] -= 4; + } + low[j] = l[j] as u8; + } + pack_k2(&low, &mut y[32..96]); +} +pub(super) fn pack_scale4(ls: &[u8; 8], lm: &[u8; 8], y: &mut [u8]) { + for j in 0..8 { + let s = ls[j]; + let m = lm[j]; + if j < 4 { + y[j] = s; + y[j + 4] = m; + } else { + y[j + 4] = (s & 15) | ((m & 15) << 4); + y[j - 4] |= (s >> 4) << 6; + y[j] |= (m >> 4) << 6; + } + } +} +pub(super) fn unpack_scale4(y: &[u8], j: usize) -> (u8, u8) { + if j < 4 { + (y[j] & 63, y[j + 4] & 63) + } else { + ((y[j + 4] & 15) | ((y[j - 4] >> 6) << 4), (y[j + 4] >> 4) | ((y[j] >> 6) << 4)) + } +} 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 new file mode 100644 index 00000000..ffaa88b6 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_quant/iq4_fn.rs @@ -0,0 +1,140 @@ +//! Moved out of the parent module by STRA-338: fn iq4, fn row_without_iq. + +#[allow(unused_imports)] +use super::*; + +pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) { + let n = x.len(); + let nb = n / 32; + let mut sigma = 0.0; + for &v in x { + sigma += v * v; + } + sigma *= 2.0 / n as f32; + let mut l = [0u8; 256]; + let mut scales = [0.0; 8]; + let (mut maxs, mut amax) = (0.0, 0.0); + y.fill(0); + put_h(y, 0, 0.0); + let values = &super::super::rust_codebooks::KVALUES_IQ4NL; + for k in 0..nb { + let xb = &x[k * 32..k * 32 + 32]; + let w: [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] } + }); + let (a, max) = max_signed(xb); + if a < EPS { + scales[k] = 0.0; + continue; + } + let mut d = if ntry > 0 { -max / values[0] as f32 } else { max / values[0] as f32 }; + let mut inv = 1.0 / d; + let (mut sx, mut s2) = (0.0, 0.0); + for j in 0..32 { + let q = best_iq4(inv * xb[j]); + l[k * 32 + j] = q; + let q = values[q as usize] as f32; + sx += w[j] * q * xb[j]; + s2 += w[j] * q * q; + } + d = if s2 > 0.0 { sx / s2 } else { 0.0 }; + let mut best = d * sx; + for itry in -ntry..=ntry { + inv = (itry as f32 + values[0] as f32) / max; + sx = 0.0; + s2 = 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; + } + if s2 > 0.0 && sx * sx > best * s2 { + d = sx / s2; + best = d * sx; + } + } + scales[k] = d; + if d.abs() > amax { + amax = d.abs(); + maxs = d; + } + } + let head = if kind == Kind::Iq4Xs { + let d = -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 in 0..nb { + let s = nearest(inv * scales[k]).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); + } + y[2..4].copy_from_slice(&high.to_le_bytes()); + 8 + } else { + put_h(y, 0, scales[0]); + if ntry > 0 { + let inv = if scales[0] != 0.0 { 1.0 / scales[0] } else { 0.0 }; + for j in 0..n { + l[j] = best_iq4(inv * x[j]); + } + } + 2 + }; + for k in 0..nb { + pack4(&l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]); + } +} +/// 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 { + 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 mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = sum / 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]); + match kind { + Kind::F32 + | Kind::F16 + | Kind::Bf16 + | Kind::Q1Zero + | Kind::Q2Zero + | Kind::Q4Zero + | Kind::Q4One + | Kind::Q5Zero + | Kind::Q5One + | Kind::Q8Zero => small(kind, x, y, w, sigma), + Kind::MxFp4 | Kind::NvFp4 => fp4(kind, x, y), + Kind::Tq1 | Kind::Tq2 => ternary(kind, x, y), + Kind::Q2K => q2k(x, y, w), + 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, if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 }), + _ => 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 new file mode 100644 index 00000000..ed7f90c9 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_quant/nearest_fn.rs @@ -0,0 +1,204 @@ +//! Moved out of the parent module by STRA-338: fn nearest, fn put_h, fn h, fn max_signed, fn weight, fn qx .... + +#[allow(unused_imports)] +use super::*; + +pub(in super::super) fn nearest(x: f32) -> i32 { + debug_assert!(x.abs() <= 4194303.0); + let bits = (x + 12582912.0).to_bits(); + (bits & 0x7fffff) as i32 - 0x400000 +} +pub(super) fn put_h(y: &mut [u8], at: usize, x: f32) { + y[at..at + 2].copy_from_slice(&half_rn(x).to_le_bytes()); +} +pub(super) fn h(y: &[u8], at: usize) -> f32 { + half(u16::from_le_bytes([y[at], y[at + 1]])) +} +pub(super) fn max_signed(x: &[f32]) -> (f32, f32) { + let (mut a, mut v) = (0.0, 0.0); + for &f in x { + if f.abs() > a { + a = f.abs(); + v = f; + } + } + (a, v) +} +pub(super) fn weight(x: f32, rmse: i32, qw: Option) -> f32 { + qw.unwrap_or_else(|| match rmse { + 1 => x * x, + 2 => 1.0, + 3 => x.abs(), + _ => x.abs().sqrt(), + }) +} +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 { + l.fill(0); + return 0.0; + } + let mut inv = -(nmax as f32) / max; + if rmse == 0 { + for (&x, l) in x.iter().zip(l) { + *l = (nmax + nearest(inv * x).clamp(-nmax, nmax - 1)) as i8; + } + return 1.0 / inv; + } + let early = rmse < 0; + if early { + rmse = -rmse; + } + 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); + l[i] = (q + nmax) as i8; + 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; + } + let mut scale = if s2 != 0.0 { sx / s2 } else { 0.0 }; + if early { + return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv }; + } + let mut best = scale * sx; + for is in -9..=9 { + if is == 0 { + continue; + } + inv = -(nmax as f32 + 0.1 * is as f32) / max; + sx = 0.0; + s2 = 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; + } + if s2 > 0.0 && sx * sx > best * s2 { + for i in 0..x.len() { + l[i] = (nmax + nearest(inv * x[i]).clamp(-nmax, nmax - 1)) as i8; + } + 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; + let (mut sx, mut s2) = (0.0, 0.0); + for i in 0..x.len() { + let q = nearest(inv * x[i]).clamp(-4, 3); + l[i] = q as i8; + let w = x[i] * x[i]; + sx += w * x[i] * q as f32; + s2 += w * q as f32 * q as f32; + } + for _ in 0..5 { + let mut changed = 0; + for i in 0..x.len() { + let w = x[i] * x[i]; + let mut tx = sx - w * x[i] * l[i] as f32; + if tx > 0.0 { + let mut t2 = 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 * s2 > sx * sx * t2 { + l[i] = q as i8; + sx = tx; + s2 = t2; + changed += 1; + } + } + } + } + if changed == 0 { + break; + } + } + for l in l { + *l += 4; + } + if s2 > 0.0 { sx / s2 } else { 0.0 } +} +/// 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) { + 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; + } + if (third && max <= min) || (!third && max == min) { + l.fill(0); + return (0.0, -min); + } + let mut inv = nmax as f32 / (max - min); + let mut scale = 1.0 / inv; + let mut best = 0.0; + for i in 0..x.len() { + l[i] = nearest(inv * (x[i] - min)).clamp(0, nmax) as u8; + let diff = scale * l[i] as f32 + min - x[i]; + best += w[i] * if mad { diff.abs() } else { diff * diff }; + } + let mut aux = [0u8; 32]; + for is in 0..=nstep { + inv = (rmin + rdelta * is as f32 + nmax as f32) / (max - min); + 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]; + } + let det = sw * sl2 - sl * sl; + if det > 0.0 { + let mut ds = (sw * sxl - sx * sl) / det; + let mut dm = (sl2 * sx - sl * sxl) / det; + if dm > 0.0 { + dm = 0.0; + ds = sxl / sl2; + } + let mut error = 0.0; + for i in 0..x.len() { + let diff = ds * aux[i] as f32 + dm - x[i]; + error += w[i] * if mad { diff.abs() } else { diff * diff }; + } + if error < best { + l.copy_from_slice(&aux[..x.len()]); + best = error; + scale = ds; + min = dm; + } + } + } + (scale, -min) +} 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 new file mode 100644 index 00000000..6ff026a5 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_quant/q45k_fn.rs @@ -0,0 +1,174 @@ +//! Moved out of the parent module by STRA-338: fn q45k, fn q6k, fn best_iq4. + +#[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 mut scales = [0.0; 8]; + let mut mins = scales; + let mut sw = scales; + let (mut maxs, mut maxm) = (0.0, 0.0); + let mut sum = 0.0; + for &v in x { + sum += v * v; + } + let sigma = 2.0 * sum / 256.0; + let av = sigma.sqrt(); + for k in 0..8 { + let xb = &x[k * 32..k * 32 + 32]; + let w: [f32; 32] = if let Some(q) = qw { + std::array::from_fn(|j| q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt()) + } else { + let mut s = 0.0; + for &v in xb { + s += v * v; + } + let avg = (s / 32.0).sqrt(); + std::array::from_fn(|j| avg + xb[j].abs()) + }; + for &v in &w { + sw[k] += v; + } + let (d, m) = if qw.is_some() { + qkx(xb, nmax, &w, &mut l[k * 32..k * 32 + 32], -0.9, 0.05, 36, false, true) + } else { + qkx( + xb, + nmax, + &w, + &mut l[k * 32..k * 32 + 32], + if five { -0.5 } else { -1.0 }, + 0.1, + if five { 15 } else { 20 }, + false, + false, + ) + }; + scales[k] = d; + mins[k] = m; + if d > maxs { + maxs = d; + } + if m > maxm { + maxm = m; + } + } + // av belongs to the weighted implementation's no-imatrix branch; public + // quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML. + let _ = av; + let mut ls = [0u8; 8]; + let mut lm = ls; + let (d, m) = if qw.is_some() { + (qp(&scales, 63, &mut ls, &sw), qp(&mins, 63, &mut lm, &sw)) + } else { + let si = if maxs > 0.0 { 63.0 / maxs } else { 0.0 }; + let mi = if maxm > 0.0 { 63.0 / maxm } else { 0.0 }; + for k in 0..8 { + ls[k] = (nearest(si * scales[k]) as u8).min(63); + lm[k] = (nearest(mi * mins[k]) as u8).min(63); + } + (maxs / 63.0, maxm / 63.0) + }; + pack_scale4(&ls, &lm, &mut y[4..16]); + put_h(y, 0, d); + put_h(y, 2, m); + let d = h(y, 0); + let m = h(y, 2); + for k in 0..8 { + let (s, min) = unpack_scale4(&y[4..16], k); + let ds = d * s as f32; + if ds == 0.0 { + continue; + } + let dm = m * min as f32; + for j in 0..32 { + l[k * 32 + j] = nearest((x[k * 32 + j] + dm) / ds).clamp(0, nmax) as u8; + } + } + let head = if five { + y[16..48].fill(0); + 48 + } else { + 16 + }; + for k in 0..4 { + for j in 0..32 { + let a = l[k * 64 + j]; + let b = l[k * 64 + j + 32]; + y[head + k * 32 + j] = (a & 15) | ((b & 15) << 4); + if five { + 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 mut scales = [0.0; 16]; + let (mut maxs, mut amax) = (0.0, 0.0); + for k in 0..16 { + let d = qx(&x[k * 16..k * 16 + 16], 32, &mut l[k * 16..k * 16 + 16], 1, qw.map(|q| &q[k * 16..k * 16 + 16])); + scales[k] = d; + if d.abs() > amax { + amax = d.abs(); + maxs = d; + } + } + 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; + } + let d = h(y, 208); + for k in 0..16 { + let ds = d * y[192 + k] as i8 as f32; + if ds == 0.0 { + continue; + } + for j in 0..16 { + l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-32, 31) + 32) as i8; + } + } + for k in 0..2 { + for j in 0..32 { + let a = l[k * 128 + j] as u8; + let b = l[k * 128 + j + 32] as u8; + let c = l[k * 128 + j + 64] as u8; + let d = l[k * 128 + j + 96] as u8; + y[k * 64 + j] = (a & 15) | ((c & 15) << 4); + y[k * 64 + j + 32] = (b & 15) | ((d & 15) << 4); + y[128 + k * 32 + j] = (a >> 4) | ((b >> 4) << 2) | ((c >> 4) << 4) | ((d >> 4) << 6); + } + } +} +pub(super) fn best_iq4(x: f32) -> u8 { + let v = &super::super::rust_codebooks::KVALUES_IQ4NL; + if x <= v[0] as f32 { + return 0; + } + if x >= v[15] as f32 { + return 15; + } + let (mut lo, mut hi) = (0, 15); + while hi - lo > 1 { + let m = (lo + hi) / 2; + if x < v[m] as f32 { + hi = m; + } else { + lo = m; + } + } + if x - (v[hi - 1] as f32) < (v[hi] as f32) - x { (hi - 1) as u8 } else { hi as u8 } +} 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 new file mode 100644 index 00000000..20d38c43 --- /dev/null +++ b/crates/native-cpu-expert/src/rust_weight_quant/qp_fn.rs @@ -0,0 +1,238 @@ +//! Moved out of the parent module by STRA-338: fn qp, fn pack4, fn small, fn e8_half, fn ue4, fn pack_ue4. + +#[allow(unused_imports)] +use super::*; + +pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32 { + let mut max = 0.0; + for &x in x { + if x > max { + max = x; + } + } + if max < EPS { + l.fill(0); + return 0.0; + } + 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 { + if is == 0 { + continue; + } + let ti = (0.1 * is as f32 + nmax as f32) / max; + 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; + } + if err < best { + best = err; + inv = ti; + } + } + 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() { + let mut tx = sx - w[i] * x[i] * l[i] as f32; + let mut t2 = 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(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 * s2 > sx * sx * t2 { + l[i] = q as u8; + sx = tx; + s2 = t2; + changed += 1; + } + } + } + } + if changed == 0 { + break; + } + } + if s2 > 0.0 { sx / 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) { + if matches!(kind, Kind::F32 | Kind::F16 | Kind::Bf16) { + match kind { + Kind::F32 => y.copy_from_slice(&x[0].to_le_bytes()), + Kind::F16 => put_h(y, 0, x[0]), + _ => { + let b = x[0].to_bits(); + let h = if b & 0x7fffffff > 0x7f800000 { + (b >> 16) | 64 + } else { + b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16 + }; + y.copy_from_slice(&(h as u16).to_le_bytes()); + } + } + return; + } + if kind == Kind::Q1Zero { + let mut sum = 0.0; + for &v in x { + sum += v.abs(); + } + put_h(y, 0, sum / 128.0); + y[2..].fill(0); + for j in 0..128 { + if x[j] >= 0.0 { + y[2 + j / 8] |= 1 << (j % 8); + } + } + return; + } + if kind == Kind::Q2Zero { + let (a, _) = max_signed(x); + put_h(y, 0, a); + let inv = if a > 0.0 { 1.0 / a } else { 0.0 }; + y[2..].fill(0); + for j in 0..64 { + let q = ((x[j] * inv).round() as i32 + 1).clamp(0, 3); + y[2 + j / 4] |= (q as u8) << (2 * (j % 4)); + } + return; + } + if kind == Kind::Q8Zero { + let (a, _) = max_signed(x); + let d = a / 127.0; + let inv = if d != 0.0 { 1.0 / d } else { 0.0 }; + put_h(y, 0, d); + for j in 0..32 { + y[j + 2] = (x[j] * inv).round() as i8 as u8; + } + return; + } + let is_min = matches!(kind, Kind::Q4One | Kind::Q5One); + let five = matches!(kind, Kind::Q5Zero | Kind::Q5One); + let nmax = if five { 31 } else { 15 }; + let mut l = [0u8; 32]; + let (d, m) = if let Some(qw) = qw { + let w = std::array::from_fn::<_, 32, _>(|j| qw[j] * (sigma + x[j] * x[j]).sqrt()); + if is_min { + let (s, m) = qkx(x, nmax, &w, &mut l, -0.9, 0.05, 36, false, true); + (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; + } + (d, 0.0) + } + } else if is_min { + let (mut min, mut max) = (f32::MAX, -f32::MAX); + for &v in x { + if v < min { + min = v; + } + if v > max { + max = v; + } + } + 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 five { q as u8 } else { q.min(15) as u8 }; + } + (d, min) + } else { + let (_, max) = max_signed(x); + 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(nmax) as u8; + } + (d, 0.0) + }; + put_h(y, 0, d); + let head = if is_min { + put_h(y, 2, m); + 4 + } else { + 2 + }; + if five { + let mut hi = 0u32; + for j in 0..16 { + y[head + 4 + j] = (l[j] & 15) | ((l[j + 16] & 15) << 4); + hi |= ((l[j] as u32 & 16) >> 4) << j; + hi |= ((l[j + 16] as u32 & 16) >> 4) << (j + 16); + } + y[head..head + 4].copy_from_slice(&hi.to_le_bytes()); + } else { + pack4(&l, &mut y[head..]); + } +} +pub(super) fn e8_half(e: u8) -> f32 { + f32::from_bits(if e < 2 { 0x00200000u32 << e } else { ((e as u32) - 1) << 23 }) +} +pub(super) fn ue4(e: u8) -> f32 { + if e == 0 || e == 127 { + return 0.0; + } + let exp = (e >> 3) & 15; + let m = e & 7; + let raw = if exp == 0 { + m as f32 * f32::from_bits(118 << 23) + } else { + (1.0 + m as f32 / 8.0) * f32::from_bits(((exp as i32 - 7 + 127) as u32) << 23) + }; + raw * 0.5 +} +pub(super) fn pack_ue4(mut x: f32) -> u8 { + if !(x > 0.0) { + return 0; + } + if x > 448.0 { + x = 448.0; + } + let bits = x.to_bits(); + let exp = ((bits >> 23) & 255) as i32 - 127; + let mut e = exp + 7; + if e <= 0 { + let m = (x * 512.0 + 0.5) as i32; + return if m < 1 { 0 } else { m.min(7) as u8 }; + } + if e >= 15 { + return 126; + } + let mut m = ((bits >> 20) & 7) + ((bits >> 19) & 1); + if m > 7 { + m = 0; + e += 1; + if e >= 15 { + return 126; + } + } + ((e as u32) << 3 | m) as u8 +} diff --git a/crates/native-cpu-expert/tests/borrowed_group_parity.rs b/crates/native-cpu-expert/tests/borrowed_group_parity.rs index 51026d65..8b8c4a48 100644 --- a/crates/native-cpu-expert/tests/borrowed_group_parity.rs +++ b/crates/native-cpu-expert/tests/borrowed_group_parity.rs @@ -5,7 +5,9 @@ //! //! cargo test --release -p leleka-native-cpu-expert --test borrowed_group_parity //! (the ignored `group_path_cost` prints the model-free cost of both paths) -use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob}; +use leleka_native_cpu_expert::{ + BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, +}; use std::time::Instant; const H: usize = 2560; @@ -110,7 +112,15 @@ fn plan(ids: &[usize], include: &[bool]) -> Vec<(usize, Vec<(usize, usize)>)> { /// The previous serve path: copy every role into owned boxes, build owned inputs, run batches of 12 with /// a join between them, scatter every expert's rows into the output. -fn owned_path(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { +fn owned_path( + pool: &mut CpuPool, + gu: GateUpFormat, + down: DownFormat, + bank: &[Expert], + tokens: &[f32], + jobs: &[(usize, Vec<(usize, usize)>)], + out: &mut [f32], +) { for batch in jobs.chunks(OLD_BATCH) { let mut prepared = Vec::with_capacity(batch.len()); for (e, pairs) in batch { @@ -120,8 +130,16 @@ fn owned_path(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Ex input.extend_from_slice(&tokens[row * H..(row + 1) * H]); } prepared.push( - PreparedJob::new(gu, down, x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice(), input.into_boxed_slice(), pairs.len()) - .expect("owned job"), + PreparedJob::new( + gu, + down, + x.gate.clone().into_boxed_slice(), + x.up.clone().into_boxed_slice(), + x.down.clone().into_boxed_slice(), + input.into_boxed_slice(), + pairs.len(), + ) + .expect("owned job"), ); } let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); @@ -135,10 +153,21 @@ fn owned_path(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Ex } } -fn borrowed_path(pool: &mut DirectCpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { - let experts: Vec> = - jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect(); - pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out).expect("borrowed group"); +fn borrowed_path( + pool: &mut DirectCpuPool, + gu: GateUpFormat, + down: DownFormat, + bank: &[Expert], + tokens: &[f32], + jobs: &[(usize, Vec<(usize, usize)>)], + out: &mut [f32], +) { + let experts: Vec> = jobs + .iter() + .map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }) + .collect(); + pool.compute_group(gu, down, &BorrowedGroup { tokens, experts: &experts, stride: TOP_K }, out) + .expect("borrowed group"); } const PAIRS: [(GateUpFormat, DownFormat); 10] = [ @@ -178,18 +207,30 @@ fn borrowed_group_is_bit_identical_to_the_owned_batches() { owned_path(&mut owned, gu, down, &bank, &tokens, &jobs, &mut a); if share != 100 { // the file-mapped source's prefetch phase reads only: the group computes the same bits - let refs: Vec> = - jobs.iter().map(|(e, pairs)| BorrowedExpert { gate: &bank[*e].gate, up: &bank[*e].up, down: &bank[*e].down, pairs }).collect(); + let refs: Vec> = jobs + .iter() + .map(|(e, pairs)| BorrowedExpert { + gate: &bank[*e].gate, + up: &bank[*e].up, + down: &bank[*e].down, + pairs, + }) + .collect(); direct.prefetch(gu, down, &refs).expect("prefetch"); } borrowed_path(&mut direct, gu, down, &bank, &tokens, &jobs, &mut b); let differing = a.iter().zip(&b).filter(|(x, y)| x.to_bits() != y.to_bits()).count(); assert_eq!(differing, 0, "{gu:?} x {down:?} rows={rows} share={share}: {differing} floats differ"); // A digest of every output bit: compared across builds to prove a kernel change bit-exact. - let digest = b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); + let digest = b + .iter() + .fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ u64::from(v.to_bits())).wrapping_mul(0x100_0000_01b3)); eprintln!("DIGEST {gu:?} {down:?} rows={rows} share={share} {digest:016x}"); let computed: usize = jobs.iter().map(|(_, p)| p.len()).sum(); - assert!(b.iter().filter(|v| v.is_finite()).count() == computed * H, "{gu:?} x {down:?}: only planned rows written, all finite"); + assert!( + b.iter().filter(|v| v.is_finite()).count() == computed * H, + "{gu:?} x {down:?}: only planned rows written, all finite" + ); groups += 1; } } @@ -216,36 +257,67 @@ fn borrowed_group_refuses_bad_shapes_without_touching_out() { assert!(direct.compute_group(gu, down, &group, &mut out).is_err()); } let short = BorrowedExpert { gate: &bank[0].gate[1..], up: &bank[0].up, down: &bank[0].down, pairs: &pairs_a }; - assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out).is_err()); + assert!( + direct + .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &[short], stride: TOP_K }, &mut out) + .is_err() + ); let wrong_format = [x(&pairs_a)]; - assert!(direct.compute_group(GateUpFormat::Iq3Xxs, down, &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, &mut out).is_err()); + assert!( + direct + .compute_group( + GateUpFormat::Iq3Xxs, + down, + &BorrowedGroup { tokens: &tokens, experts: &wrong_format, stride: TOP_K }, + &mut out + ) + .is_err() + ); let mut nan = tokens.clone(); nan[5] = f32::NAN; - assert!(direct.compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out).is_err()); + assert!( + direct + .compute_group(gu, down, &BorrowedGroup { tokens: &nan, experts: &wrong_format, stride: TOP_K }, &mut out) + .is_err() + ); assert!(out.iter().all(|&v| v == -3.0), "a refused group writes nothing"); // and the pool still serves a good group afterwards let good = [x(&pairs_a)]; - direct.compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out).expect("good group"); + direct + .compute_group(gu, down, &BorrowedGroup { tokens: &tokens, experts: &good, stride: TOP_K }, &mut out) + .expect("good group"); assert!(out[H..2 * H].iter().all(|v| v.is_finite())); } /// The previous runtime prepare step per expert also copied each role out of the source (`block`) and /// scanned every block header (`encoded_finite`) before `PreparedJob::new` copied them again. -fn owned_path_with_source_copy(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, bank: &[Expert], tokens: &[f32], jobs: &[(usize, Vec<(usize, usize)>)], out: &mut [f32]) { +fn owned_path_with_source_copy( + pool: &mut CpuPool, + gu: GateUpFormat, + down: DownFormat, + bank: &[Expert], + tokens: &[f32], + jobs: &[(usize, Vec<(usize, usize)>)], + out: &mut [f32], +) { let (_, gb) = gate_up_block(gu); let (_, db) = down_block(down); - let scan = |bytes: &[u8], block: usize| bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00); + let scan = |bytes: &[u8], block: usize| { + bytes.chunks_exact(block).all(|b| u16::from_le_bytes([b[0], b[1]]) & 0x7c00 != 0x7c00) + }; for batch in jobs.chunks(OLD_BATCH) { let mut prepared = Vec::with_capacity(batch.len()); for (e, pairs) in batch { let x = &bank[*e]; - let (g, u, d) = (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); + let (g, u, d) = + (x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice()); assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db)); let mut input = Vec::with_capacity(pairs.len() * H); for &(row, _) in pairs { input.extend_from_slice(&tokens[row * H..(row + 1) * H]); } - prepared.push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")); + prepared + .push(PreparedJob::new(gu, down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")); } let done = pool.start(prepared, 48 << 20).expect("start").join().expect("join"); for (job, (_, pairs)) in done.into_iter().zip(batch) { diff --git a/crates/native-cpu-expert/tests/cpu_pool_probe.rs b/crates/native-cpu-expert/tests/cpu_pool_probe.rs index f1f40f4d..2d34aecb 100644 --- a/crates/native-cpu-expert/tests/cpu_pool_probe.rs +++ b/crates/native-cpu-expert/tests/cpu_pool_probe.rs @@ -72,7 +72,10 @@ fn cpu_pool_runs_every_expert_format_pair() { match result { Ok(done) => { let finite = done.into_iter().all(|j| j.into_values().iter().all(|v| v.is_finite())); - eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", started.elapsed()); + eprintln!( + "PREFLIGHT cpu expert {gu:?} x {down:?} rows={rows} ok finite={finite} in {:?}", + started.elapsed() + ); } Err(e) => eprintln!("PREFLIGHT cpu expert {gu:?} x {down:?} ERR: {e:?}"), } diff --git a/crates/native-cpu-expert/tests/cpu_service_bench.rs b/crates/native-cpu-expert/tests/cpu_service_bench.rs index 314be836..d531be3e 100644 --- a/crates/native-cpu-expert/tests/cpu_service_bench.rs +++ b/crates/native-cpu-expert/tests/cpu_service_bench.rs @@ -5,7 +5,9 @@ //! //! BENCH_WORKERS (default 15) BENCH_EXPERTS (default 256) BENCH_CALLS (default 2000) //! LELEKA_POOL_TIMING=1 cargo test --release -p leleka-native-cpu-expert --test cpu_service_bench -- --ignored --nocapture -use leleka_native_cpu_expert::{BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, POOL_TIMING_NAMES}; +use leleka_native_cpu_expert::{ + BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, POOL_TIMING_NAMES, +}; const H: usize = 2560; const FF: usize = 640; @@ -53,7 +55,11 @@ fn cpu_service_bench() { let calls = env_usize("BENCH_CALLS", 2000); let mut rng = Rng(0x5eed_cafe_f00d_1234); let experts: Vec = (0..n_experts) - .map(|_| Expert { gate: blocks(&mut rng, FF * H / 256, 110), up: blocks(&mut rng, FF * H / 256, 110), down: blocks(&mut rng, H * FF / 32, 18) }) + .map(|_| Expert { + gate: blocks(&mut rng, FF * H / 256, 110), + up: blocks(&mut rng, FF * H / 256, 110), + down: blocks(&mut rng, H * FF / 32, 18), + }) .collect(); let mut pool = match DirectCpuPool::new(workers) { Ok(p) => p, @@ -79,7 +85,8 @@ fn cpu_service_bench() { let _ = pool.take_timing(); let start = std::time::Instant::now(); for _ in 0..calls { - let pairs: Vec> = members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); + let pairs: Vec> = + members.iter().enumerate().map(|(slot, toks)| toks.iter().map(|&t| (t, slot)).collect()).collect(); let group_experts: Vec> = pairs .iter() .map(|p| { @@ -89,11 +96,16 @@ fn cpu_service_bench() { }) .collect(); let group = BorrowedGroup { tokens: &tokens[..rows * H], experts: &group_experts, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..rows * TOP_K * H]).expect("compute_group"); + pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..rows * TOP_K * H]) + .expect("compute_group"); } let us = start.elapsed().as_secs_f64() * 1e6 / calls as f64; let n = members.len() as f64; - let mut line = format!("pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", us / n, n * 2.33e6 / us / 1e3); + let mut line = format!( + "pass {pass} {label}: {us:.1} us per call, {:.1} us per expert, {:.1} GB/s", + us / n, + n * 2.33e6 / us / 1e3 + ); if let Some(t) = pool.take_timing() { line.push_str(" |"); for (name, ms) in POOL_TIMING_NAMES.iter().zip(t) { @@ -134,11 +146,15 @@ fn cpu_service_bench() { t_scan += t1.elapsed().as_secs_f64(); let e = [BorrowedExpert { gate: &x.gate, up: &x.up, down: &x.down, pairs: &pairs }]; let group = BorrowedGroup { tokens: &tokens[..H], experts: &e, stride: TOP_K }; - pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..TOP_K * H]).expect("compute_group"); + pool.compute_group(GateUpFormat::Iq3S, DownFormat::Iq4Nl, &group, &mut out[..TOP_K * H]) + .expect("compute_group"); } let _ = pool.take_timing(); - eprintln!("pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", - start.elapsed().as_secs_f64() * 1e6 / calls as f64, t_scan * 1e6 / calls as f64); + eprintln!( + "pass {pass} first use, branch_free={branch_free}: {:.1} us per expert (scan {:.1}, compute the rest)", + start.elapsed().as_secs_f64() * 1e6 / calls as f64, + t_scan * 1e6 / calls as f64 + ); } } } diff --git a/crates/native-cpu-expert/tests/pool_lifecycle.rs b/crates/native-cpu-expert/tests/pool_lifecycle.rs index bfcbe501..aeda8c4d 100644 --- a/crates/native-cpu-expert/tests/pool_lifecycle.rs +++ b/crates/native-cpu-expert/tests/pool_lifecycle.rs @@ -92,7 +92,12 @@ fn pool(workers: i32) -> Option { fn pairs_of(expert: usize, tokens: usize) -> Vec<(usize, usize)> { vec![(expert % tokens, expert), ((expert + 1) % tokens, expert)] } -fn run(pool: &mut DirectCpuPool, bank: &[Expert], tokens: &[f32], out: &mut [f32]) -> Result<(), leleka_native_cpu_expert::Error> { +fn run( + pool: &mut DirectCpuPool, + bank: &[Expert], + tokens: &[f32], + out: &mut [f32], +) -> Result<(), leleka_native_cpu_expert::Error> { let rows = tokens.len() / H; let pairs: Vec> = (0..bank.len()).map(|e| pairs_of(e, rows)).collect(); let experts: Vec> = bank @@ -137,7 +142,10 @@ fn repeated_groups_across_idle_gaps_are_bit_identical() { let mut reference = vec![-3.0f32; 4 * STRIDE * H]; run(&mut pool, &bank, &tokens, &mut reference).expect("reference group"); let written: usize = (0..bank.len()).map(|e| pairs_of(e, 4).len()).sum(); - assert_eq!(reference.as_chunks::().0.iter().filter(|row| row.iter().all(|v| v.is_finite() && *v != -3.0)).count(), written); + assert_eq!( + reference.as_chunks::().0.iter().filter(|row| row.iter().all(|v| v.is_finite() && *v != -3.0)).count(), + written + ); let gaps = [0u64, 0, 0, 200, 0, 3_000, 0, 0, 25_000]; for round in 0..180 { thread::sleep(Duration::from_micros(gaps[round % gaps.len()])); diff --git a/crates/native-cpu-expert/tests/token_count_invariance.rs b/crates/native-cpu-expert/tests/token_count_invariance.rs index 895b2c77..b7ed0664 100644 --- a/crates/native-cpu-expert/tests/token_count_invariance.rs +++ b/crates/native-cpu-expert/tests/token_count_invariance.rs @@ -48,7 +48,14 @@ fn matrix(rng: &mut Rng, bytes: usize, block: usize) -> Vec { out } -fn run(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, blobs: &[Vec; 3], tokens: &[f32], n: usize) -> Vec { +fn run( + pool: &mut CpuPool, + gu: GateUpFormat, + down: DownFormat, + blobs: &[Vec; 3], + tokens: &[f32], + n: usize, +) -> Vec { let job = PreparedJob::new( gu, down, @@ -59,7 +66,11 @@ fn run(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, blobs: &[Vec; n, ) .expect("job"); - let done = pool.start(vec![job], 48 << 20).expect("start").join().unwrap_or_else(|e| panic!("join {gu:?} + {down:?} n={n}: {e:?}")); + let done = pool + .start(vec![job], 48 << 20) + .expect("start") + .join() + .unwrap_or_else(|e| panic!("join {gu:?} + {down:?} n={n}: {e:?}")); done.into_iter().next().expect("one job").into_values().to_vec() } @@ -67,18 +78,35 @@ fn run(pool: &mut CpuPool, gu: GateUpFormat, down: DownFormat, blobs: &[Vec; fn the_first_two_tokens_do_not_depend_on_the_group_size() { let mut pool = CpuPool::new(1).expect("pool"); let mut rng = Rng(0x0329_5eed_9e37_79b9); - let gates = [GateUpFormat::Iq2Xxs, GateUpFormat::Iq2Xs, GateUpFormat::Iq3Xxs, GateUpFormat::Iq3S, GateUpFormat::Iq2S, GateUpFormat::Iq4Xs, GateUpFormat::Q2_0]; + let gates = [ + GateUpFormat::Iq2Xxs, + GateUpFormat::Iq2Xs, + GateUpFormat::Iq3Xxs, + GateUpFormat::Iq3S, + GateUpFormat::Iq2S, + GateUpFormat::Iq4Xs, + GateUpFormat::Q2_0, + ]; for gu in gates { for down in [DownFormat::Iq4Nl, DownFormat::Q2_0] { let (gq, gb) = gate_up_block(gu); let (dq, db) = down_block(down); - let blobs = [matrix(&mut rng, H / gq * gb * FF, gb), matrix(&mut rng, H / gq * gb * FF, gb), matrix(&mut rng, FF / dq * db * H, db)]; - let tokens: Vec = (0..8 * H).map(|_| ((rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0)).collect(); + let blobs = [ + matrix(&mut rng, H / gq * gb * FF, gb), + matrix(&mut rng, H / gq * gb * FF, gb), + matrix(&mut rng, FF / dq * db * H, db), + ]; + let tokens: Vec = + (0..8 * H).map(|_| ((rng.next() >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0)).collect(); let base = run(&mut pool, gu, down, &blobs, &tokens, 2); for n in 3..=8 { let wide = run(&mut pool, gu, down, &blobs, &tokens, n); for i in 0..2 * H { - assert_eq!(wide[i].to_bits(), base[i].to_bits(), "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}"); + assert_eq!( + wide[i].to_bits(), + base[i].to_bits(), + "{gu:?} + {down:?}: {n} tokens differ from 2 tokens at output {i}" + ); } } } diff --git a/crates/obs/rustfmt.toml b/crates/obs/rustfmt.toml new file mode 100644 index 00000000..fd33e4dd --- /dev/null +++ b/crates/obs/rustfmt.toml @@ -0,0 +1,3 @@ +# Line width of the lawbook (301): 120 columns. Max heuristics keep short calls and struct literals on one line. +max_width = 120 +use_small_heuristics = "Max" diff --git a/crates/obs/src/hist.rs b/crates/obs/src/hist.rs index 3b0281ae..f731efaa 100644 --- a/crates/obs/src/hist.rs +++ b/crates/obs/src/hist.rs @@ -12,7 +12,11 @@ pub struct Histogram { impl Histogram { pub fn new(bounds: &'static [f64]) -> Self { - Self { bounds, counts: (0..=bounds.len()).map(|_| AtomicU64::new(0)).collect(), sum_bits: AtomicU64::new(0f64.to_bits()) } + Self { + bounds, + counts: (0..=bounds.len()).map(|_| AtomicU64::new(0)).collect(), + sum_bits: AtomicU64::new(0f64.to_bits()), + } } pub fn observe(&self, value: f64) { diff --git a/crates/obs/src/impl_level.rs b/crates/obs/src/impl_level.rs index 50ce81dc..ab3a962f 100644 --- a/crates/obs/src/impl_level.rs +++ b/crates/obs/src/impl_level.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - impl Level { pub fn as_str(self) -> &'static str { match self { @@ -79,7 +78,11 @@ impl<'a, T: Into>> From> for V<'a> { impl Settings { pub fn from_env(get: impl Fn(&str) -> Option, stderr_is_terminal: bool) -> Settings { let debug = get("LELEKA_LOG_DEBUG").is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes" | "on")); - let min_level = if debug { Level::Debug } else { get("LELEKA_LOG_LEVEL").and_then(|v| Level::parse(&v)).unwrap_or(Level::Info) }; + let min_level = if debug { + Level::Debug + } else { + get("LELEKA_LOG_LEVEL").and_then(|v| Level::parse(&v)).unwrap_or(Level::Info) + }; // `leleka run` sets LELEKA_LOG_FORMAT=json for its children. A process started by hand keeps the plain lines the lab // scripts parse (legacy) when its standard error is a file, and writes key=value text on a terminal. let (format, legacy) = match get("LELEKA_LOG_FORMAT").as_deref().map(str::trim) { @@ -88,7 +91,8 @@ impl Settings { Some("legacy") => (Format::Text, true), _ => (Format::Text, !stderr_is_terminal), }; - let legacy = legacy || get("LELEKA_LOG_LEGACY").is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes" | "on")); + let legacy = + legacy || get("LELEKA_LOG_LEGACY").is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes" | "on")); Settings { min_level, format, debug, legacy } } } @@ -158,7 +162,15 @@ pub(super) fn render_fields(settings: &Settings, fields: &[Field<'_>]) -> Vec<(S } /// The line for one event (no trailing newline). Pure: the clock and the settings are arguments. -pub fn format_line(settings: &Settings, ts_ms: u64, level: Level, comp: &str, ev: &str, fields: &[Field<'_>], suppressed: u64) -> String { +pub fn format_line( + settings: &Settings, + ts_ms: u64, + level: Level, + comp: &str, + ev: &str, + fields: &[Field<'_>], + suppressed: u64, +) -> String { let mut rendered = render_fields(settings, fields); if suppressed > 0 { rendered.push(("suppressed".to_owned(), Rendered::Raw(suppressed.to_string()))); diff --git a/crates/obs/src/lib.rs b/crates/obs/src/lib.rs index e3ba9816..b80ce86c 100644 --- a/crates/obs/src/lib.rs +++ b/crates/obs/src/lib.rs @@ -107,17 +107,34 @@ mod tests { Level::Warn, "supervisor", "engine_exit", - &[("code", 137u32.into()), ("reason", "signal 9".into()), ("restart", true.into()), ("ratio", 0.5f64.into()), ("gone", V::Null)], + &[ + ("code", 137u32.into()), + ("reason", "signal 9".into()), + ("restart", true.into()), + ("ratio", 0.5f64.into()), + ("gone", V::Null), + ], 0, ); assert!(line.starts_with("{\"ts\":\"20") && line.ends_with('}') && !line.contains('\n'), "{line}"); assert!(line.contains("\"lvl\":\"warn\",\"comp\":\"supervisor\",\"ev\":\"engine_exit\""), "{line}"); - assert!(line.contains("\"code\":137,\"reason\":\"signal 9\",\"restart\":true,\"ratio\":0.5,\"gone\":null"), "{line}"); + assert!( + line.contains("\"code\":137,\"reason\":\"signal 9\",\"restart\":true,\"ratio\":0.5,\"gone\":null"), + "{line}" + ); } #[test] fn strings_are_escaped_and_non_finite_numbers_become_null() { - let line = format_line(&JSON, 0, Level::Info, "api", "x", &[("msg", "a\"b\\c\nd\u{1}".into()), ("nan", f64::NAN.into())], 0); + let line = format_line( + &JSON, + 0, + Level::Info, + "api", + "x", + &[("msg", "a\"b\\c\nd\u{1}".into()), ("nan", f64::NAN.into())], + 0, + ); assert!(line.contains(r#""msg":"a\"b\\c\nd\u0001""#), "{line}"); assert!(line.contains("\"nan\":null"), "{line}"); assert!(!line.contains('\n')); @@ -125,7 +142,15 @@ mod tests { #[test] fn the_text_format_is_key_value() { - let line = format_line(&TEXT, 0, Level::Info, "api", "request", &[("rid", "req-1".into()), ("msg", "two words".into()), ("n", 5u64.into())], 3); + let line = format_line( + &TEXT, + 0, + Level::Info, + "api", + "request", + &[("rid", "req-1".into()), ("msg", "two words".into()), ("n", 5u64.into())], + 3, + ); assert_eq!(line, "1970-01-01T00:00:00.000Z INFO api request rid=req-1 msg=\"two words\" n=5 suppressed=3"); } @@ -158,7 +183,12 @@ mod tests { #[test] fn the_debug_opt_in_adds_lengths_only() { let line = format_line(&DEBUG, 0, Level::Debug, "api", "x", &[("prompt", "0123456789".into())], 0); - assert!(line.contains("\"prompt_len\":10") && line.contains("\"prompt\":\"[redacted]\"") && !line.contains("0123456789"), "{line}"); + assert!( + line.contains("\"prompt_len\":10") + && line.contains("\"prompt\":\"[redacted]\"") + && !line.contains("0123456789"), + "{line}" + ); } #[test] @@ -187,7 +217,8 @@ mod tests { #[test] fn values_and_lines_are_bounded() { let long = "x ".repeat(2000); - let line = format_line(&JSON, 0, Level::Info, "api", "x", &[("msg", long.as_str().into()), ("a", 1u64.into())], 0); + let line = + format_line(&JSON, 0, Level::Info, "api", "x", &[("msg", long.as_str().into()), ("a", 1u64.into())], 0); assert!(line.len() < MAX_LINE, "{}", line.len()); assert!(line.contains('~')); let many: Vec<(String, u64)> = (0..400).map(|i| (format!("f{i}"), u64::MAX)).collect(); @@ -242,47 +273,47 @@ mod tests { mod impl_level; #[allow(unused_imports)] -pub use impl_level::settings; -#[allow(unused_imports)] -use impl_level::json_string; -#[allow(unused_imports)] use impl_level::clean_key; #[allow(unused_imports)] -use impl_level::render_fields; -#[allow(unused_imports)] -pub use impl_level::format_line; -#[allow(unused_imports)] use impl_level::clean_key_dash; #[allow(unused_imports)] +pub use impl_level::format_line; +#[allow(unused_imports)] use impl_level::json_line; #[allow(unused_imports)] +use impl_level::json_string; +#[allow(unused_imports)] +use impl_level::render_fields; +#[allow(unused_imports)] +pub use impl_level::settings; +#[allow(unused_imports)] use impl_level::text_line; mod write_stderr_fn; #[allow(unused_imports)] -use write_stderr_fn::write_stderr; -#[allow(unused_imports)] -use write_stderr_fn::request_sink; +pub use write_stderr_fn::debug; #[allow(unused_imports)] pub use write_stderr_fn::emit; #[allow(unused_imports)] -pub use write_stderr_fn::emit_keyed; -#[allow(unused_imports)] pub use write_stderr_fn::emit_always; #[allow(unused_imports)] +pub use write_stderr_fn::emit_keyed; +#[allow(unused_imports)] pub use write_stderr_fn::emit_msg; #[allow(unused_imports)] -pub use write_stderr_fn::trace_msg; -#[allow(unused_imports)] -pub use write_stderr_fn::legacy_line; -#[allow(unused_imports)] -pub use write_stderr_fn::record; -#[allow(unused_imports)] -pub use write_stderr_fn::debug; +pub use write_stderr_fn::error; #[allow(unused_imports)] pub use write_stderr_fn::info; #[allow(unused_imports)] -pub use write_stderr_fn::warn; -#[allow(unused_imports)] -pub use write_stderr_fn::error; +pub use write_stderr_fn::legacy_line; #[allow(unused_imports)] pub use write_stderr_fn::new_request_id; +#[allow(unused_imports)] +pub use write_stderr_fn::record; +#[allow(unused_imports)] +use write_stderr_fn::request_sink; +#[allow(unused_imports)] +pub use write_stderr_fn::trace_msg; +#[allow(unused_imports)] +pub use write_stderr_fn::warn; +#[allow(unused_imports)] +use write_stderr_fn::write_stderr; diff --git a/crates/obs/src/rate.rs b/crates/obs/src/rate.rs index edb18af9..e7c21143 100644 --- a/crates/obs/src/rate.rs +++ b/crates/obs/src/rate.rs @@ -24,7 +24,9 @@ impl Policy { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Verdict { /// Log it; `suppressed` lines of this key were dropped since the last logged one. - Allow { suppressed: u64 }, + Allow { + suppressed: u64, + }, Drop, } @@ -47,7 +49,11 @@ impl Limiter { pub fn check(&self, key: &str, policy: Policy, now_ms: u64) -> Verdict { let Ok(mut buckets) = self.buckets.lock() else { return Verdict::Allow { suppressed: 0 } }; let key = if buckets.contains_key(key) || buckets.len() < MAX_KEYS { key } else { "(other)" }; - let bucket = buckets.entry(key.to_owned()).or_insert(Bucket { tokens: f64::from(policy.burst), last_ms: now_ms, suppressed: 0 }); + let bucket = buckets.entry(key.to_owned()).or_insert(Bucket { + tokens: f64::from(policy.burst), + last_ms: now_ms, + suppressed: 0, + }); let earned = now_ms.saturating_sub(bucket.last_ms) as f64 / policy.refill_ms.max(1) as f64; bucket.tokens = (bucket.tokens + earned).min(f64::from(policy.burst)); bucket.last_ms = now_ms; diff --git a/crates/obs/src/redact.rs b/crates/obs/src/redact.rs index a5554e89..aa5c0775 100644 --- a/crates/obs/src/redact.rs +++ b/crates/obs/src/redact.rs @@ -12,12 +12,38 @@ pub const MARK: &str = "[redacted]"; /// Key segments (split at `_`, `-`, `.`) whose string value is user text. const TEXT_SEGMENTS: &[&str] = &[ - "prompt", "completion", "completions", "content", "text", "body", "messages", "instructions", "reasoning", "arguments", "input", "output", - "response", "query", "transcript", "stdout", "diff", "code", + "prompt", + "completion", + "completions", + "content", + "text", + "body", + "messages", + "instructions", + "reasoning", + "arguments", + "input", + "output", + "response", + "query", + "transcript", + "stdout", + "diff", + "code", ]; /// Key segments whose string value is a credential. const SECRET_SEGMENTS: &[&str] = &[ - "password", "passwd", "secret", "authorization", "bearer", "cookie", "apikey", "credential", "credentials", "passphrase", "auth", + "password", + "passwd", + "secret", + "authorization", + "bearer", + "cookie", + "apikey", + "credential", + "credentials", + "passphrase", + "auth", ]; fn segments(key: &str) -> impl Iterator + '_ { @@ -36,7 +62,11 @@ pub enum KeyClass { pub fn classify_key(key: &str) -> KeyClass { let lower = key.to_ascii_lowercase(); - if lower == "key" || lower == "token" || lower.ends_with("_token") || lower.ends_with("_key") && !lower.ends_with("cache_key") { + if lower == "key" + || lower == "token" + || lower.ends_with("_token") + || lower.ends_with("_key") && !lower.ends_with("cache_key") + { return KeyClass::Secret; } let mut class = KeyClass::Plain; @@ -92,7 +122,18 @@ const TOKEN_PREFIXES: &[(&str, usize)] = &[ fn scrub_named_values(text: &str, out: &mut String) -> bool { // `name=value` / `name":"value` for credential-looking names; the value runs to the next separator. - const NAMES: &[&str] = &["token", "secret", "password", "passwd", "api_key", "apikey", "api-key", "access_key", "authorization", "key"]; + const NAMES: &[&str] = &[ + "token", + "secret", + "password", + "passwd", + "api_key", + "apikey", + "api-key", + "access_key", + "authorization", + "key", + ]; let lower = text.to_ascii_lowercase(); let bytes = text.as_bytes(); let mut changed = false; @@ -228,10 +269,15 @@ fn scrub_runs(text: &str) -> Cow<'_, str> { } let long_run = &text[start..end]; let alnum = &text[start..i]; - let token_by_prefix = TOKEN_PREFIXES.iter().any(|(prefix, min)| long_run.starts_with(prefix) && long_run.len() >= prefix.len() + min) + let token_by_prefix = TOKEN_PREFIXES + .iter() + .any(|(prefix, min)| long_run.starts_with(prefix) && long_run.len() >= prefix.len() + min) && (start == 0 || !word_char(bytes[start - 1])); let digest_shape = is_hex(alnum) && matches!(alnum.len(), 40 | 64); - let random_run = alnum.len() >= 32 && !digest_shape && alnum.bytes().any(|b| b.is_ascii_digit()) && alnum.bytes().any(|b| b.is_ascii_alphabetic()); + let random_run = alnum.len() >= 32 + && !digest_shape + && alnum.bytes().any(|b| b.is_ascii_digit()) + && alnum.bytes().any(|b| b.is_ascii_alphabetic()); if token_by_prefix { out.push_str(&text[last..start]); out.push_str(MARK); @@ -287,81 +333,4 @@ pub fn clip(text: &str, max: usize) -> &str { } #[cfg(test)] -mod tests { - use super::*; - - #[test] - fn keys_are_classified() { - for key in ["prompt", "output_text", "content", "messages", "request_body", "completion", "instructions", "tool_arguments"] { - assert_eq!(classify_key(key), KeyClass::Text, "{key}"); - } - for key in ["api_key", "authorization", "password", "token", "hf_token", "client_secret", "cookie", "key"] { - assert_eq!(classify_key(key), KeyClass::Secret, "{key}"); - } - for key in ["prompt_tok", "ptok", "otok", "rid", "model", "ttft_ms", "cached_tok", "ep", "msg"] { - assert_eq!(classify_key(key), if key == "prompt_tok" { KeyClass::Text } else { KeyClass::Plain }, "{key}"); - } - } - - #[test] - fn registered_secrets_never_survive() { - register_secret("correct-horse-battery-staple-0123456789"); - let out = scrub("failed to open correct-horse-battery-staple-0123456789 for reading"); - assert!(!out.contains("correct-horse"), "{out}"); - assert!(out.contains(MARK)); - } - - #[test] - fn bearer_and_authorization_text_is_scrubbed() { - let out = scrub("sent Authorization: Bearer abcdef0123456789abcdef0123456789 to host"); - assert!(!out.contains("abcdef0123"), "{out}"); - let out = scrub("header bearer SECRETVALUE and more"); - assert!(!out.contains("SECRETVALUE"), "{out}"); - assert!(out.ends_with("and more"), "{out}"); - } - - #[test] - fn token_shapes_and_query_parameters_are_scrubbed() { - for sample in [ - "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345", - "sk-proj-AbCdEfGhIjKlMnOpQrStUv0123", - "ghp_AbCdEfGhIjKlMnOpQrStUvWxYz012345", - "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.sig", - "AKIAABCDEFGHIJKLMNOP", - "Zk3Qw9Lp0Xa7Vb2Nc8Md4Hs6Jt1Rf5Ye9Uo", - ] { - let text = format!("value {sample} end"); - let out = scrub(&text); - assert!(!out.contains(&sample[4..]), "{sample} -> {out}"); - } - let out = scrub("GET /v1/x?api_key=ABC123def&mode=fast HTTP/1.1"); - assert!(!out.contains("ABC123def") && out.contains("mode=fast"), "{out}"); - let out = scrub(r#"{"token":"abc12345xyz","n":5}"#); - assert!(!out.contains("abc12345xyz") && out.contains("\"n\":5"), "{out}"); - let out = scrub("connect https://user:hunter2@example.com/path"); - assert!(!out.contains("hunter2") && out.contains("@example.com/path"), "{out}"); - } - - #[test] - fn ordinary_text_digests_and_paths_pass() { - let digest = "80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; - let commit = "478f0c481b2a39e7e4b6e5a4c4d9b6e1a2f3d4c5"; - for text in [ - "engine exited (signal 9); restart 1/3", - "model Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf loaded", - "/home/para/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar", - "listening on 127.0.0.1:8081", - digest, - commit, - ] { - assert_eq!(scrub(text), text, "{text}"); - } - } - - #[test] - fn clip_respects_character_boundaries() { - assert_eq!(clip("héllo", 2), "h"); - assert_eq!(clip("héllo", 3), "hé"); - assert_eq!(clip("abc", 10), "abc"); - } -} +mod tests; diff --git a/crates/obs/src/redact/tests.rs b/crates/obs/src/redact/tests.rs new file mode 100644 index 00000000..fb313573 --- /dev/null +++ b/crates/obs/src/redact/tests.rs @@ -0,0 +1,80 @@ +//! Moved out of the parent file by STRA-338 (same module path as before). + +use super::*; + +#[test] +fn keys_are_classified() { + for key in + ["prompt", "output_text", "content", "messages", "request_body", "completion", "instructions", "tool_arguments"] + { + assert_eq!(classify_key(key), KeyClass::Text, "{key}"); + } + for key in ["api_key", "authorization", "password", "token", "hf_token", "client_secret", "cookie", "key"] { + assert_eq!(classify_key(key), KeyClass::Secret, "{key}"); + } + for key in ["prompt_tok", "ptok", "otok", "rid", "model", "ttft_ms", "cached_tok", "ep", "msg"] { + assert_eq!(classify_key(key), if key == "prompt_tok" { KeyClass::Text } else { KeyClass::Plain }, "{key}"); + } +} + +#[test] +fn registered_secrets_never_survive() { + register_secret("correct-horse-battery-staple-0123456789"); + let out = scrub("failed to open correct-horse-battery-staple-0123456789 for reading"); + assert!(!out.contains("correct-horse"), "{out}"); + assert!(out.contains(MARK)); +} + +#[test] +fn bearer_and_authorization_text_is_scrubbed() { + let out = scrub("sent Authorization: Bearer abcdef0123456789abcdef0123456789 to host"); + assert!(!out.contains("abcdef0123"), "{out}"); + let out = scrub("header bearer SECRETVALUE and more"); + assert!(!out.contains("SECRETVALUE"), "{out}"); + assert!(out.ends_with("and more"), "{out}"); +} + +#[test] +fn token_shapes_and_query_parameters_are_scrubbed() { + for sample in [ + "hf_AbCdEfGhIjKlMnOpQrStUvWxYz012345", + "sk-proj-AbCdEfGhIjKlMnOpQrStUv0123", + "ghp_AbCdEfGhIjKlMnOpQrStUvWxYz012345", + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.payload.sig", + "AKIAABCDEFGHIJKLMNOP", + "Zk3Qw9Lp0Xa7Vb2Nc8Md4Hs6Jt1Rf5Ye9Uo", + ] { + let text = format!("value {sample} end"); + let out = scrub(&text); + assert!(!out.contains(&sample[4..]), "{sample} -> {out}"); + } + let out = scrub("GET /v1/x?api_key=ABC123def&mode=fast HTTP/1.1"); + assert!(!out.contains("ABC123def") && out.contains("mode=fast"), "{out}"); + let out = scrub(r#"{"token":"abc12345xyz","n":5}"#); + assert!(!out.contains("abc12345xyz") && out.contains("\"n\":5"), "{out}"); + let out = scrub("connect https://user:hunter2@example.com/path"); + assert!(!out.contains("hunter2") && out.contains("@example.com/path"), "{out}"); +} + +#[test] +fn ordinary_text_digests_and_paths_pass() { + let digest = "80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"; + let commit = "478f0c481b2a39e7e4b6e5a4c4d9b6e1a2f3d4c5"; + for text in [ + "engine exited (signal 9); restart 1/3", + "model Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf loaded", + "/home/para/work/leleka/models/leleka-gates/assets/qwen-iq3-s-l2-v4.kar", + "listening on 127.0.0.1:8081", + digest, + commit, + ] { + assert_eq!(scrub(text), text, "{text}"); + } +} + +#[test] +fn clip_respects_character_boundaries() { + assert_eq!(clip("héllo", 2), "h"); + assert_eq!(clip("héllo", 3), "hé"); + assert_eq!(clip("abc", 10), "abc"); +} diff --git a/crates/obs/src/time.rs b/crates/obs/src/time.rs index 5a16349b..e5d8d3e6 100644 --- a/crates/obs/src/time.rs +++ b/crates/obs/src/time.rs @@ -6,9 +6,7 @@ pub use clock::{AnyClock, Clock, ManualClock, Stopwatch, SystemClock}; /// Milliseconds since the Unix epoch. pub fn now_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)) + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)) } fn civil_from_days(days: i64) -> (i64, u32, u32) { diff --git a/crates/obs/src/time/clock.rs b/crates/obs/src/time/clock.rs index a2dd4364..423c9347 100644 --- a/crates/obs/src/time/clock.rs +++ b/crates/obs/src/time/clock.rs @@ -53,19 +53,12 @@ pub struct ManualClock { impl ManualClock { /// A clock standing at an arbitrary starting point. pub fn new() -> Self { - Self { - base: Instant::now(), - advanced_ns: Arc::new(AtomicU64::new(0)), - tick_ns: 0, - } + Self { base: Instant::now(), advanced_ns: Arc::new(AtomicU64::new(0)), tick_ns: 0 } } /// A clock that moves forward by `step` after each reading. pub fn ticking(step: Duration) -> Self { - Self { - tick_ns: u64::try_from(step.as_nanos()).unwrap_or(u64::MAX), - ..Self::new() - } + Self { tick_ns: u64::try_from(step.as_nanos()).unwrap_or(u64::MAX), ..Self::new() } } /// Move every clone of this clock forward. @@ -125,10 +118,7 @@ pub struct Stopwatch { impl Stopwatch { /// Start counting now. pub fn start(clock: C) -> Self { - Self { - epoch: clock.now(), - clock, - } + Self { epoch: clock.now(), clock } } /// Time since [`Self::start`]. @@ -170,10 +160,7 @@ mod tests { other.advance(Duration::from_secs(3)); assert_eq!(clock.since(start), Duration::from_secs(3)); assert_eq!(start.checked_duration_since(clock.now()), None); - assert_eq!( - clock.since(clock.now() + Duration::from_secs(1)), - Duration::ZERO - ); + assert_eq!(clock.since(clock.now() + Duration::from_secs(1)), Duration::ZERO); } #[test] @@ -212,17 +199,10 @@ mod tests { let watch = Stopwatch::start(AnyClock::from(clock.clone())); assert_eq!(watch.elapsed_ms(), 0); clock.advance_ms(1999); - assert_eq!( - (watch.elapsed_ms(), watch.elapsed()), - (1999, Duration::from_millis(1999)) - ); + assert_eq!((watch.elapsed_ms(), watch.elapsed()), (1999, Duration::from_millis(1999))); let mark = watch.now(); clock.advance_ms(1); - assert_eq!( - watch.since(mark), - Duration::from_millis(1), - "it is a clock too" - ); + assert_eq!(watch.since(mark), Duration::from_millis(1), "it is a clock too"); } #[test] diff --git a/crates/obs/src/write_stderr_fn.rs b/crates/obs/src/write_stderr_fn.rs index f1736906..9a7423c6 100644 --- a/crates/obs/src/write_stderr_fn.rs +++ b/crates/obs/src/write_stderr_fn.rs @@ -3,7 +3,6 @@ #[allow(unused_imports)] use super::*; - pub(super) fn write_stderr(line: &str) { let mut stderr = std::io::stderr().lock(); let mut buffer = String::with_capacity(line.len() + 1); diff --git a/limits-baseline.json b/limits-baseline.json index f05b3a66..16df46d2 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -16,7 +16,7 @@ "leleka-context": { "fn_lines": 6, "complexity": 6, - "width": 10 + "width": 9 }, "leleka-cpu-kernels": { "fn_lines": 1 @@ -33,8 +33,8 @@ "width": 6 }, "leleka-cuda-driver": { - "fn_lines": 657, - "width": 2561, + "fn_lines": 680, + "width": 824, "complexity": 668, "nesting": 32 }, @@ -44,6 +44,20 @@ "complexity": 53, "nesting": 7 }, + "leleka-engine-core": { + "fn_lines": 44, + "complexity": 38, + "width": 56 + }, + "leleka-engine-fake": { + "width": 1 + }, + "leleka-engine-qwen35-cuda": { + "fn_lines": 606, + "width": 759, + "complexity": 591, + "nesting": 30 + }, "leleka-experimental-ref": { "fn_lines": 15, "width": 19, @@ -59,7 +73,7 @@ "leleka-gateway-text": { "width": 64, "complexity": 16, - "fn_lines": 15, + "fn_lines": 14, "nesting": 1 }, "leleka-gguf": { @@ -115,21 +129,21 @@ "complexity": 2 }, "leleka-memory": { - "width": 164, - "fn_lines": 21, + "fn_lines": 24, + "width": 97, "complexity": 11, "nesting": 1 }, "leleka-model-format": { - "fn_lines": 84, - "complexity": 62, - "width": 100, + "fn_lines": 69, + "complexity": 63, + "width": 69, "nesting": 4 }, "leleka-native-cpu-expert": { + "fn_lines": 97, "complexity": 84, - "fn_lines": 6, - "width": 1106, + "width": 121, "nesting": 24 }, "leleka-native-parity-bench": { @@ -146,9 +160,9 @@ "width": 2 }, "leleka-obs": { - "width": 16, - "fn_lines": 4, + "fn_lines": 5, "complexity": 4, + "width": 7, "nesting": 1 }, "leleka-offline-tools": { @@ -165,10 +179,7 @@ "nesting": 2 }, "leleka-runtime": { - "fn_lines": 633, - "width": 1995, - "complexity": 616, - "nesting": 30 + "width": 2 }, "leleka-runtime-client": { "fn_lines": 9, @@ -218,9 +229,9 @@ "fn_lines": 5 }, "leleka-context": { - "fn_lines": 12, + "fn_lines": 5, "complexity": 1, - "width": 1 + "width": 2 }, "leleka-cpu-kernels": { "fn_lines": 8, @@ -239,15 +250,27 @@ "complexity": 1 }, "leleka-cuda-driver": { - "fn_lines": 134, + "fn_lines": 107, "complexity": 32, - "width": 188, + "width": 66, "nesting": 6 }, "leleka-deploy": { "fn_lines": 89, "width": 67 }, + "leleka-engine-core": { + "fn_lines": 11, + "width": 15, + "complexity": 3, + "nesting": 1 + }, + "leleka-engine-qwen35-cuda": { + "fn_lines": 75, + "width": 76, + "complexity": 12, + "nesting": 6 + }, "leleka-experimental-ref": { "fn_lines": 14, "width": 58, @@ -259,9 +282,9 @@ "fn_lines": 3 }, "leleka-gateway-text": { - "fn_lines": 13, + "fn_lines": 12, "nesting": 2, - "width": 21 + "width": 20 }, "leleka-gguf": { "fn_lines": 5, @@ -297,22 +320,22 @@ "width": 2 }, "leleka-memory": { - "fn_lines": 2, + "fn_lines": 5, "complexity": 1, "nesting": 1, - "width": 67 + "width": 21 }, "leleka-model-format": { - "fn_lines": 83, - "width": 70, - "complexity": 14, + "fn_lines": 71, + "width": 36, + "complexity": 13, "nesting": 4 }, "leleka-native-cpu-expert": { - "fn_lines": 26, + "fn_lines": 44, "complexity": 22, "nesting": 6, - "width": 325 + "width": 137 }, "leleka-npu-service": { "fn_lines": 3, @@ -322,9 +345,6 @@ "leleka-npu-worker": { "fn_lines": 2 }, - "leleka-obs": { - "width": 7 - }, "leleka-offline-tools": { "fn_lines": 3 }, @@ -332,12 +352,6 @@ "fn_lines": 11, "complexity": 1 }, - "leleka-runtime": { - "fn_lines": 131, - "complexity": 27, - "nesting": 6, - "width": 250 - }, "leleka-runtime-client": { "fn_lines": 9 },